context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// ==++== // // // Copyright (c) 2006 Microsoft Corporation. All rights reserved. // // The use and distribution terms for this software are contained in the file // named license.txt, which can be found in the root of this distribution. // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // You must not remove this notice, or any other, from this software. // // // ==--== namespace Microsoft.JScript { using Microsoft.JScript.Vsa; using System; using System.Collections; using System.Reflection; using System.Runtime.InteropServices.Expando; [System.Runtime.InteropServices.ComVisible(true)] public class GlobalScope : ActivationObject, IExpando { private ArrayList componentScopes; //List of script blocks that collectively form a global or module scope. Script blocks have no component scopes. internal GlobalObject globalObject; //null for script blocks and module scopes. private bool recursive; //Set this while busy with a lookup, in case the object to which the lookup has been delegated returns the favor. internal bool evilScript; //Indicates that script contains an eval, or that it may be followed by separately compiled script blocks internal Object thisObject; //Late bound uses of the this literal use this value. Only happens in calls to eval from global code. internal bool isComponentScope; private TypeReflector globalObjectTR; private TypeReflector typeReflector; public GlobalScope(GlobalScope parent, VsaEngine engine) : this(parent, engine, parent != null) { } internal GlobalScope(GlobalScope parent, VsaEngine engine, bool isComponentScope) : base(parent) { this.componentScopes = null; this.recursive = false; this.isComponentScope = isComponentScope; if (parent == null) { this.globalObject = engine.Globals.globalObject; this.globalObjectTR = TypeReflector.GetTypeReflectorFor(Globals.TypeRefs.ToReferenceContext(this.globalObject.GetType())); this.fast = !(this.globalObject is LenientGlobalObject); } else { this.globalObject = null; this.globalObjectTR = null; this.fast = parent.fast; if (isComponentScope) ((GlobalScope)this.parent).AddComponentScope(this); } this.engine = engine; this.isKnownAtCompileTime = this.fast; this.evilScript = true; //True by default. Set it false when a single script block is being compiled. this.thisObject = this; this.typeReflector = TypeReflector.GetTypeReflectorFor(Globals.TypeRefs.ToReferenceContext(this.GetType())); if (isComponentScope) engine.Scopes.Add(this); } internal void AddComponentScope(GlobalScope component) { if (this.componentScopes == null) this.componentScopes = new ArrayList(); this.componentScopes.Add(component); component.thisObject = this.thisObject; //Component scopes pretend they are one and the same as their parent scope. } public FieldInfo AddField(String name) { if (this.fast) return null; if (this.isComponentScope) return ((GlobalScope)this.parent).AddField(name); FieldInfo field = (FieldInfo)this.name_table[name]; if (field == null) { field = new JSExpandoField(name); this.name_table[name] = field; this.field_table.Add(field); } return field; } MethodInfo IExpando.AddMethod(String name, Delegate method) { return null; } internal override JSVariableField AddNewField(String name, Object value, FieldAttributes attributeFlags) { if (!this.isComponentScope) return base.AddNewField(name, value, attributeFlags); //Could get here from eval return ((GlobalScope)this.parent).AddNewField(name, value, attributeFlags); } PropertyInfo IExpando.AddProperty(String name) { return null; } internal override bool DeleteMember(String name) { if (this.isComponentScope) return this.parent.DeleteMember(name); FieldInfo field = (FieldInfo)this.name_table[name]; if (field != null) { if (field is JSExpandoField) { field.SetValue(this, Missing.Value); this.name_table.Remove(name); this.field_table.Remove(field); return true; } else return false; } else return false; } public override Object GetDefaultThisObject() { return this; } internal override Object GetDefaultValue(PreferredType preferred_type) { if (preferred_type == PreferredType.String || preferred_type == PreferredType.LocaleString) return ""; else return Double.NaN; } public override FieldInfo GetField(String name, int lexLevel) { return this.GetField(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly); } internal JSField[] GetFields() { int n = this.field_table.Count; JSField[] result = new JSField[n]; for (int i = 0; i < n; i++) result[i] = (JSField)this.field_table[i]; return result; } public override FieldInfo[] GetFields(BindingFlags bindingAttr) { return base.GetFields(bindingAttr | BindingFlags.DeclaredOnly); } public override GlobalScope GetGlobalScope() { return this; } public override FieldInfo GetLocalField(String name) { return this.GetField(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly); } public override MemberInfo[] GetMember(String name, BindingFlags bindingAttr) { return this.GetMember(name, bindingAttr, false); } private MemberInfo[] GetMember(String name, BindingFlags bindingAttr, bool calledFromParent) { if (this.recursive) return new MemberInfo[0]; MemberInfo[] result = null; if (!this.isComponentScope) { //Look for an expando MemberInfo[] members = base.GetMember(name, bindingAttr | BindingFlags.DeclaredOnly); if (members.Length > 0) return members; if (this.componentScopes != null) for (int i = 0, n = this.componentScopes.Count; i < n; i++) { GlobalScope sc = (GlobalScope)this.componentScopes[i]; result = sc.GetMember(name, bindingAttr | BindingFlags.DeclaredOnly, true); if (result.Length > 0) return result; } if (this.globalObject != null) result = this.globalObjectTR.GetMember(name, bindingAttr & ~BindingFlags.NonPublic | BindingFlags.Static); if (result != null && result.Length > 0) return ScriptObject.WrapMembers(result, this.globalObject); } else { //Look for global variables represented as static fields on subclass of GlobalScope. I.e. the script block case. result = this.typeReflector.GetMember(name, bindingAttr & ~BindingFlags.NonPublic | BindingFlags.Static); int n = result.Length; if (n > 0) { int toBeHidden = 0; MemberInfo[] newResult = new MemberInfo[n]; for (int i = 0; i < n; i++) { MemberInfo mem = newResult[i] = result[i]; if (mem.DeclaringType.IsAssignableFrom(Typeob.GlobalScope)) { newResult[i] = null; toBeHidden++; } else if (mem is FieldInfo) { FieldInfo field = (FieldInfo)mem; if (field.IsStatic && field.FieldType == Typeob.Type) { Type t = (Type)field.GetValue(null); if (t != null) newResult[i] = t; } } } if (toBeHidden == 0) return result; if (toBeHidden == n) return new MemberInfo[0]; MemberInfo[] remainingMembers = new MemberInfo[n - toBeHidden]; int j = 0; foreach (MemberInfo mem in newResult) if (mem != null) remainingMembers[j++] = mem; return remainingMembers; } } if (this.parent != null && !calledFromParent && ((bindingAttr & BindingFlags.DeclaredOnly) == 0 || this.isComponentScope)) { this.recursive = true; try { result = ((ScriptObject)this.parent).GetMember(name, bindingAttr); } finally { this.recursive = false; } if (result != null && result.Length > 0) return result; } return new MemberInfo[0]; } public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { if (this.recursive) return new MemberInfo[0]; MemberInfoList result = new MemberInfoList(); if (this.isComponentScope) { MemberInfo[] mems = Globals.TypeRefs.ToReferenceContext(this.GetType()).GetMembers(bindingAttr | BindingFlags.DeclaredOnly); if (mems != null) foreach (MemberInfo mem in mems) result.Add(mem); } else { if (this.componentScopes != null) { for (int i = 0, n = this.componentScopes.Count; i < n; i++) { GlobalScope sc = (GlobalScope)this.componentScopes[i]; this.recursive = true; MemberInfo[] mems = null; try { mems = sc.GetMembers(bindingAttr); } finally { this.recursive = false; } if (mems != null) foreach (MemberInfo mem in mems) result.Add(mem); } } IEnumerator enu = this.field_table.GetEnumerator(); while (enu.MoveNext()) { FieldInfo field = (FieldInfo)enu.Current; result.Add(field); } } if (this.parent != null && (this.isComponentScope || ((bindingAttr & BindingFlags.DeclaredOnly) == 0))) { this.recursive = true; MemberInfo[] mems = null; try { mems = ((ScriptObject)this.parent).GetMembers(bindingAttr); } finally { this.recursive = false; } if (mems != null) foreach (MemberInfo mem in mems) result.Add(mem); } return result.ToArray(); } public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { return base.GetMethods(bindingAttr | BindingFlags.DeclaredOnly); } public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { return base.GetProperties(bindingAttr | BindingFlags.DeclaredOnly); } internal override void GetPropertyEnumerator(ArrayList enums, ArrayList objects) { FieldInfo[] fields = this.GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); if (fields.Length > 0) { enums.Add(fields.GetEnumerator()); objects.Add(this); } ScriptObject parent = this.GetParent(); if (parent != null) parent.GetPropertyEnumerator(enums, objects); } internal void SetFast() { this.fast = true; this.isKnownAtCompileTime = true; if (this.globalObject != null) { this.globalObject = GlobalObject.commonInstance; this.globalObjectTR = TypeReflector.GetTypeReflectorFor(Globals.TypeRefs.ToReferenceContext(this.globalObject.GetType())); } } void IExpando.RemoveMember(MemberInfo m) { this.DeleteMember(m.Name); } internal override void SetMemberValue(String name, Object value) { MemberInfo[] members = this.GetMember(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); if (members.Length == 0) { // We do not want to create expando fields on the global object when assigning to an undefined // variable in the debugger. if (VsaEngine.executeForJSEE) throw new JScriptException(JSError.UndefinedIdentifier, new Context(new DocumentContext("", null), name)); FieldInfo field = this.AddField(name); if (field != null) field.SetValue(this, value); return; } MemberInfo m = LateBinding.SelectMember(members); if (m == null) throw new JScriptException(JSError.AssignmentToReadOnly); LateBinding.SetMemberValue(this, name, value, m, members); } } }
/* * Naiad ver. 0.5 * Copyright (c) Microsoft Corporation * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT * LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR * A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.Concurrent; using System.IO; using Microsoft.Research.Naiad.Serialization; using Microsoft.Research.Naiad.DataStructures; using Microsoft.Research.Naiad.Dataflow.Channels; using Microsoft.Research.Naiad.Scheduling; using Microsoft.Research.Naiad.Frameworks.DifferentialDataflow.CollectionTrace; using System.Linq.Expressions; using System.Diagnostics; using Microsoft.Research.Naiad.Runtime.Progress; using Microsoft.Research.Naiad; using Microsoft.Research.Naiad.Dataflow; using Microsoft.Research.Naiad.Dataflow.StandardVertices; using Microsoft.Research.Naiad.Diagnostics; namespace Microsoft.Research.Naiad.Frameworks.DifferentialDataflow.OperatorImplementations { internal class BinaryStatefulOperator<K, V1, V2, S1, S2, T, R> : BinaryBufferingVertex<Weighted<S1>, Weighted<S2>, Weighted<R>, T> where K : IEquatable<K> where V1 : IEquatable<V1> where V2 : IEquatable<V2> where S1 : IEquatable<S1> where S2 : IEquatable<S2> where T : Time<T> where R : IEquatable<R> { public override void OnReceive1(Message<Weighted<S1>, T> message) { if (this.inputImmutable1) { this.NotifyAt(message.time); for (int i = 0; i < message.length; i++) this.OnInput1(message.payload[i], message.time); } else base.OnReceive1(message); } public override void OnReceive2(Message<Weighted<S2>, T> message) { if (this.inputImmutable2) { this.NotifyAt(message.time); for (int i = 0; i < message.length; i++) this.OnInput2(message.payload[i], message.time); } else base.OnReceive2(message); } protected override void OnShutdown() { base.OnShutdown(); if (inputTrace1 != null) inputTrace1.Release(); inputTrace1 = null; if (inputTrace2 != null) inputTrace2.Release(); inputTrace2 = null; if (outputTrace != null) outputTrace.Release(); outputTrace = null; keyIndices = null; keysToProcess = null; internTable = null; } protected override void UpdateReachability(List<Pointstamp> versions) { base.UpdateReachability(versions); if (versions != null && internTable != null) internTable.UpdateReachability(versions); } //public readonly Naiad.Frameworks.RecvFiberBank<Weighted<S1>, T> LeftInput; //public readonly Naiad.Frameworks.RecvFiberBank<Weighted<S2>, T> RightInput; //public override FiberRecvEndpoint<Weighted<S1>, T> LeftInput { get { return new LeftRecvEndpoint(this); } } //public override FiberRecvEndpoint<Weighted<S2>, T> RightInput { get { return new RightRecvEndpoint(this); } } public Func<S1, K> key1; // extracts the key from the input record public Func<S1, V1> value1; // reduces input record to relevant value public Func<S2, K> key2; // extracts the key from the input record public Func<S2, V2> value2; // reduces input record to relevant value public Expression<Func<S1, K>> keyExpression1; // extracts the key from the input record public Expression<Func<S1, V1>> valueExpression1; // reduces input record to relevant value public Expression<Func<S2, K>> keyExpression2; // extracts the key from the input record public Expression<Func<S2, V2>> valueExpression2; // reduces input record to relevant value readonly bool MaintainOutputTrace; protected CollectionTraceWithHeap<R> createOutputTrace() { return new CollectionTraceWithHeap<R>((x, y) => internTable.LessThan(x, y), x => internTable.UpdateTime(x), this.Stage.Placement.Count); } protected CollectionTraceCheckpointable<V2> createInputTrace2() { if (Microsoft.Research.Naiad.Utilities.ExpressionComparer.Instance.Equals(keyExpression2, valueExpression2)) { if (this.inputImmutable2) { Logging.Progress("Allocating immutable no heap in {0}", this); return new CollectionTraceImmutableNoHeap<V2>(); } else return new CollectionTraceWithoutHeap<V2>((x, y) => internTable.LessThan(x, y), x => internTable.UpdateTime(x)); } else { if (this.inputImmutable2) { Logging.Progress("Allocating immutable heap in {0}", this); return new CollectionTraceImmutable<V2>(); } else return new CollectionTraceWithHeap<V2>((x, y) => internTable.LessThan(x, y), x => internTable.UpdateTime(x), this.Stage.Placement.Count); } } protected CollectionTraceCheckpointable<V1> createInputTrace1() { if (Microsoft.Research.Naiad.Utilities.ExpressionComparer.Instance.Equals(keyExpression1, valueExpression1)) { if (this.inputImmutable1) return new CollectionTraceImmutableNoHeap<V1>(); else return new CollectionTraceWithoutHeap<V1>((x, y) => internTable.LessThan(x, y), x => internTable.UpdateTime(x)); } else { if (this.inputImmutable1) { Logging.Progress("Allocating immutable heap in {0}", this); return new CollectionTraceImmutable<V1>(); } else return new CollectionTraceWithHeap<V1>((x, y) => internTable.LessThan(x, y), x => internTable.UpdateTime(x), this.Stage.Placement.Count); } } public override void OnNotify(T workTime) { if (!this.inputImmutable1) { foreach (var record in this.Input1.GetRecordsAt(workTime)) OnInput1(record, workTime); } if (!this.inputImmutable2) { foreach (var record in this.Input2.GetRecordsAt(workTime)) OnInput2(record, workTime); } Compute(); Flush(); //if (this.inputImmutable1 && this.inputImmutable2) // this.ShutDown(); //else { if (inputTrace1 != null) inputTrace1.Compact(); if (inputTrace2 != null) inputTrace2.Compact(); } } protected Dictionary<K, BinaryKeyIndices> keyIndices; protected CollectionTraceCheckpointable<V1> inputTrace1; // collects all differences that have processed. protected CollectionTraceCheckpointable<V2> inputTrace2; // collects all differences that have processed. protected CollectionTraceCheckpointable<R> outputTrace; // collects outputs protected int outputWorkspace = 0; protected LatticeInternTable<T> internTable = new LatticeInternTable<T>(); protected NaiadList<K> keysToProcess = new NaiadList<K>(1); public virtual void OnInput1(Weighted<S1> entry, T time) { var k = key1(entry.record); BinaryKeyIndices state; if (!keyIndices.TryGetValue(k, out state)) state = new BinaryKeyIndices(); if (state.unprocessed1 == 0 && state.unprocessed2 == 0) keysToProcess.Add(k); inputTrace1.Introduce(ref state.unprocessed1, value1(entry.record), entry.weight, internTable.Intern(time)); keyIndices[k] = state; } public virtual void OnInput2(Weighted<S2> entry, T time) { var k = key2(entry.record); BinaryKeyIndices state; if (!keyIndices.TryGetValue(k, out state)) state = new BinaryKeyIndices(); if (state.unprocessed1 == 0 && state.unprocessed2 == 0) keysToProcess.Add(k); inputTrace2.Introduce(ref state.unprocessed2, value2(entry.record), entry.weight, internTable.Intern(time)); keyIndices[k] = state; } public virtual void Compute() { for (int i = 0; i < keysToProcess.Count; i++) Update(keysToProcess.Array[i]); keysToProcess.Clear(); } protected NaiadList<Weighted<V1>> collection1 = new NaiadList<Weighted<V1>>(1); protected NaiadList<Weighted<V1>> difference1 = new NaiadList<Weighted<V1>>(1); protected NaiadList<Weighted<V2>> collection2 = new NaiadList<Weighted<V2>>(1); protected NaiadList<Weighted<V2>> difference2 = new NaiadList<Weighted<V2>>(1); // Moves from unprocessed[key] to processed[key], updating output[key] and Send()ing. protected virtual void Update(K key) { var traceIndices = keyIndices[key]; if (traceIndices.unprocessed1 != 0 || traceIndices.unprocessed2 != 0) { inputTrace1.EnsureStateIsCurrentWRTAdvancedTimes(ref traceIndices.processed1); inputTrace2.EnsureStateIsCurrentWRTAdvancedTimes(ref traceIndices.processed2); // iterate through the times that may require updates. var interestingTimes = InterestingTimes(traceIndices); // incorporate the updates, so we can compare old and new outputs. inputTrace1.IntroduceFrom(ref traceIndices.processed1, ref traceIndices.unprocessed1, false); inputTrace2.IntroduceFrom(ref traceIndices.processed2, ref traceIndices.unprocessed2, false); for (int i = 0; i < interestingTimes.Count; i++) UpdateTime(key, traceIndices, interestingTimes.Array[i]); // clean out the state we just processed inputTrace1.ZeroState(ref traceIndices.unprocessed1); inputTrace2.ZeroState(ref traceIndices.unprocessed2); // move the differences we produced from local to persistent storage. if (MaintainOutputTrace) { outputTrace.IntroduceFrom(ref traceIndices.output, ref outputWorkspace); outputTrace.EnsureStateIsCurrentWRTAdvancedTimes(ref traceIndices.output); } else outputTrace.ZeroState(ref outputWorkspace); keyIndices[key] = traceIndices; } } protected NaiadList<int> timeList = new NaiadList<int>(1); protected NaiadList<int> truthList = new NaiadList<int>(1); protected NaiadList<int> deltaList = new NaiadList<int>(1); protected virtual NaiadList<int> InterestingTimes(BinaryKeyIndices keyIndex) { deltaList.Clear(); inputTrace1.EnumerateTimes(keyIndex.unprocessed1, deltaList); inputTrace2.EnumerateTimes(keyIndex.unprocessed2, deltaList); truthList.Clear(); inputTrace1.EnumerateTimes(keyIndex.processed1, truthList); inputTrace2.EnumerateTimes(keyIndex.processed2, truthList); timeList.Clear(); this.internTable.InterestingTimes(timeList, truthList, deltaList); return timeList; } protected NaiadList<Weighted<R>> outputCollection = new NaiadList<Weighted<R>>(1); protected virtual void UpdateTime(K key, BinaryKeyIndices keyIndex, int timeIndex) { // subtract out prior records before adding new ones outputTrace.SubtractStrictlyPriorDifferences(ref outputWorkspace, timeIndex); NewOutputMinusOldOutput(key, keyIndex, timeIndex); var outputTime = this.internTable.times[timeIndex]; outputCollection.Clear(); outputTrace.EnumerateDifferenceAt(outputWorkspace, timeIndex, outputCollection); var output = this.Output.GetBufferForTime(outputTime); for (int i = 0; i < outputCollection.Count; i++) output.Send(outputCollection.Array[i]); } protected virtual void NewOutputMinusOldOutput(K key, BinaryKeyIndices keyIndex, int timeIndex) { Reduce(key, keyIndex, timeIndex); // this suggests we want to init updateToOutput with -output outputCollection.Clear(); outputTrace.EnumerateCollectionAt(keyIndex.output, timeIndex, outputCollection); for (int i = 0; i < outputCollection.Count; i++) outputTrace.Introduce(ref outputWorkspace, outputCollection.Array[i].record, -outputCollection.Array[i].weight, timeIndex); } // expected to populate resultList to match reduction(collection.source) protected virtual void Reduce(K key, BinaryKeyIndices keyIndex, int time) { } /* Checkpoint format: * bool terminated * if !terminated: * LatticeInternTable<T> internTable * CollectionTrace<> inputTrace1 * CollectionTrace<> inputTrace2 * CollectionTrace<> outputTrace * Dictionary<K,KeyIndices> keysToProcess * int recordsToProcessCount1 * (T,NaiadList<Weighted<S>>)*recordsToProcessCount recordsToProcess1 * int recordsToProcessCount2 * (T,NaiadList<Weighted<S>>)*recordsToProcessCount recordsToProcess2 */ protected override void Checkpoint(NaiadWriter writer) { base.Checkpoint(writer); writer.Write(this.IsShutDown); if (!this.IsShutDown) { this.internTable.Checkpoint(writer); this.inputTrace1.Checkpoint(writer); this.inputTrace2.Checkpoint(writer); this.outputTrace.Checkpoint(writer); this.keyIndices.Checkpoint(writer); this.Input1.Checkpoint(writer); this.Input2.Checkpoint(writer); /* writer.Write(this.recordsToProcess1.Count, PrimitiveSerializers.Int32); foreach (KeyValuePair<T, NaiadList<Weighted<S1>>> kvp in this.recordsToProcess1) { writer.Write(kvp.Key, timeSerializer); kvp.Value.Checkpoint(writer, weightedS1Serializer); } writer.Write(this.recordsToProcess2.Count, PrimitiveSerializers.Int32); foreach (KeyValuePair<T, NaiadList<Weighted<S2>>> kvp in this.recordsToProcess2) { writer.Write(kvp.Key, timeSerializer); kvp.Value.Checkpoint(writer, weightedS2Serializer); } */ } } protected override void Restore(NaiadReader reader) { base.Restore(reader); this.isShutdown = reader.Read<bool>(); if (!this.isShutdown) { this.internTable.Restore(reader); this.inputTrace1.Restore(reader); this.inputTrace2.Restore(reader); this.outputTrace.Restore(reader); this.keyIndices.Restore(reader); this.Input1.Restore(reader); this.Input2.Restore(reader); /* int recordsToProcessCount1 = reader.Read<int>(PrimitiveSerializers.Int32); foreach (NaiadList<Weighted<S1>> recordList in this.recordsToProcess1.Values) recordList.Free(); this.recordsToProcess1.Clear(); for (int i = 0; i < recordsToProcessCount1; ++i) { T key = reader.Read<T>(timeSerializer); NaiadList<Weighted<S1>> value = new NaiadList<Weighted<S1>>(); value.Restore(reader, weightedS1Serializer); this.recordsToProcess1[key] = value; } int recordsToProcessCount2 = reader.Read<int>(PrimitiveSerializers.Int32); foreach (NaiadList<Weighted<S2>> recordList in this.recordsToProcess2.Values) recordList.Free(); this.recordsToProcess2.Clear(); for (int i = 0; i < recordsToProcessCount2; ++i) { T key = reader.Read<T>(timeSerializer); NaiadList<Weighted<S2>> value = new NaiadList<Weighted<S2>>(); value.Restore(reader, weightedS2Serializer); this.recordsToProcess2[key] = value; } */ } } protected readonly bool inputImmutable1 = false; protected readonly bool inputImmutable2 = false; public BinaryStatefulOperator(int index, Stage<T> stage, bool input1Immutable, bool input2Immutable, Expression<Func<S1, K>> k1, Expression<Func<S2, K>> k2, Expression<Func<S1, V1>> v1, Expression<Func<S2, V2>> v2, bool maintainOC = true) : base(index, stage, null) { key1 = k1.Compile(); value1 = v1.Compile(); key2 = k2.Compile(); value2 = v2.Compile(); keyExpression1 = k1; keyExpression2 = k2; valueExpression1 = v1; valueExpression2 = v2; MaintainOutputTrace = maintainOC; inputImmutable1 = input1Immutable; inputImmutable2 = input2Immutable; keyIndices = new Dictionary<K, BinaryKeyIndices>(); inputTrace1 = createInputTrace1(); inputTrace2 = createInputTrace2(); outputTrace = createOutputTrace(); outputWorkspace = 0; } } internal class ConservativeBinaryStatefulOperator<K, V1, V2, S1, S2, T, R> : BinaryBufferingVertex<Weighted<S1>, Weighted<S2>, Weighted<R>, T> where K : IEquatable<K> where V1 : IEquatable<V1> where V2 : IEquatable<V2> where S1 : IEquatable<S1> where S2 : IEquatable<S2> where T : Time<T> where R : IEquatable<R> { public override void OnReceive1(Message<Weighted<S1>, T> message) { if (this.inputImmutable1) { this.NotifyAt(message.time); for (int i = 0; i < message.length; i++) this.OnInput1(message.payload[i], message.time); } else base.OnReceive1(message); } public override void OnReceive2(Message<Weighted<S2>, T> message) { if (this.inputImmutable2) { this.NotifyAt(message.time); for (int i = 0; i < message.length; i++) { this.OnInput2(message.payload[i], message.time); } } else base.OnReceive2(message); } protected override void OnShutdown() { base.OnShutdown(); if (inputTrace1 != null) inputTrace1.Release(); inputTrace1 = null; if (inputTrace2 != null) inputTrace2.Release(); inputTrace2 = null; if (outputTrace != null) outputTrace.Release(); outputTrace = null; keyIndices = null; KeysToProcessAtTimes = null; internTable = null; } protected override void UpdateReachability(List<Pointstamp> versions) { base.UpdateReachability(versions); if (versions != null && internTable != null) internTable.UpdateReachability(versions); } public Func<S1, K> key1; // extracts the key from the input record public Func<S1, V1> value1; // reduces input record to relevant value public Func<S2, K> key2; // extracts the key from the input record public Func<S2, V2> value2; // reduces input record to relevant value public Expression<Func<S1, K>> keyExpression1; // extracts the key from the input record public Expression<Func<S1, V1>> valueExpression1; // reduces input record to relevant value public Expression<Func<S2, K>> keyExpression2; // extracts the key from the input record public Expression<Func<S2, V2>> valueExpression2; // reduces input record to relevant value protected CollectionTraceWithHeap<R> createOutputTrace() { return new CollectionTraceWithHeap<R>((x, y) => internTable.LessThan(x, y), x => internTable.UpdateTime(x), this.Stage.Placement.Count); } protected CollectionTraceCheckpointable<V2> createInputTrace2() { if (Microsoft.Research.Naiad.Utilities.ExpressionComparer.Instance.Equals(keyExpression2, valueExpression2)) { if (this.inputImmutable2) { Logging.Progress("Allocating immutable no heap in {0}", this); return new CollectionTraceImmutableNoHeap<V2>(); } else return new CollectionTraceWithoutHeap<V2>((x, y) => internTable.LessThan(x, y), x => internTable.UpdateTime(x)); } else { if (this.inputImmutable2) { Logging.Progress("Allocating immutable heap in {0}", this); return new CollectionTraceImmutable<V2>(); } else return new CollectionTraceWithHeap<V2>((x, y) => internTable.LessThan(x, y), x => internTable.UpdateTime(x), this.Stage.Placement.Count); } } protected CollectionTraceCheckpointable<V1> createInputTrace1() { if (Microsoft.Research.Naiad.Utilities.ExpressionComparer.Instance.Equals(keyExpression1, valueExpression1)) { if (this.inputImmutable1) return new CollectionTraceImmutableNoHeap<V1>(); else return new CollectionTraceWithoutHeap<V1>((x, y) => internTable.LessThan(x, y), x => internTable.UpdateTime(x)); } else { if (this.inputImmutable1) { Logging.Progress("Allocating immutable heap in {0}", this); return new CollectionTraceImmutable<V1>(); } else return new CollectionTraceWithHeap<V1>((x, y) => internTable.LessThan(x, y), x => internTable.UpdateTime(x), this.Stage.Placement.Count); } } public override void OnNotify(T time) { if (!this.inputImmutable1) foreach (var record in this.Input1.GetRecordsAt(time)) OnInput1(record, time); if (!this.inputImmutable2) foreach (var record in this.Input2.GetRecordsAt(time)) OnInput2(record, time); Compute(time); Flush(); if (inputTrace1 != null) inputTrace1.Compact(); if (inputTrace2 != null) inputTrace2.Compact(); } protected Dictionary<K, BinaryKeyIndices> keyIndices; protected CollectionTraceCheckpointable<V1> inputTrace1; // collects all differences that have processed. protected CollectionTraceCheckpointable<V2> inputTrace2; // collects all differences that have processed. protected CollectionTraceCheckpointable<R> outputTrace; // collects outputs protected int outputWorkspace = 0; protected LatticeInternTable<T> internTable = new LatticeInternTable<T>(); //protected NaiadList<K> keysToProcess = new NaiadList<K>(1); protected Dictionary<T, HashSet<K>> KeysToProcessAtTimes = new Dictionary<T, HashSet<K>>(); public virtual void OnInput1(Weighted<S1> entry, T time) { var k = key1(entry.record); BinaryKeyIndices state; if (!keyIndices.TryGetValue(k, out state)) state = new BinaryKeyIndices(); if (state.unprocessed1 == 0 && state.unprocessed2 == 0) { if (!this.KeysToProcessAtTimes.ContainsKey(time)) this.KeysToProcessAtTimes.Add(time, new HashSet<K>()); this.KeysToProcessAtTimes[time].Add(k); } inputTrace1.Introduce(ref state.unprocessed1, value1(entry.record), entry.weight, internTable.Intern(time)); keyIndices[k] = state; } public virtual void OnInput2(Weighted<S2> entry, T time) { var k = key2(entry.record); BinaryKeyIndices state; if (!keyIndices.TryGetValue(k, out state)) state = new BinaryKeyIndices(); if (state.unprocessed1 == 0 && state.unprocessed2 == 0) { if (!this.KeysToProcessAtTimes.ContainsKey(time)) this.KeysToProcessAtTimes.Add(time, new HashSet<K>()); this.KeysToProcessAtTimes[time].Add(k); } inputTrace2.Introduce(ref state.unprocessed2, value2(entry.record), entry.weight, internTable.Intern(time)); keyIndices[k] = state; } public virtual void Compute(T time) { if (this.KeysToProcessAtTimes.ContainsKey(time)) { foreach (var key in this.KeysToProcessAtTimes[time]) Update(key, time); inputTrace1.Compact(); inputTrace2.Compact(); outputTrace.Compact(); } } protected NaiadList<Weighted<V1>> collection1 = new NaiadList<Weighted<V1>>(1); protected NaiadList<Weighted<V1>> difference1 = new NaiadList<Weighted<V1>>(1); protected NaiadList<Weighted<V2>> collection2 = new NaiadList<Weighted<V2>>(1); protected NaiadList<Weighted<V2>> difference2 = new NaiadList<Weighted<V2>>(1); // Moves from unprocessed[key] to processed[key], updating output[key] and Send()ing. protected virtual void Update(K key, T time) { var traceIndices = keyIndices[key]; if (traceIndices.unprocessed1 != 0 || traceIndices.unprocessed2 != 0) { // iterate through the times that may require updates. var interestingTimes = InterestingTimes(traceIndices); for (int i = 0; i < interestingTimes.Count; i++) { var newTime = this.internTable.times[interestingTimes.Array[i]]; if (!newTime.Equals(time)) { if (!this.KeysToProcessAtTimes.ContainsKey(newTime)) { this.KeysToProcessAtTimes.Add(newTime, new HashSet<K>()); this.NotifyAt(newTime); } this.KeysToProcessAtTimes[newTime].Add(key); } } // move the differences we produced from local to persistent storage. outputTrace.IntroduceFrom(ref traceIndices.output, ref outputWorkspace); // incorporate the updates, so we can compare old and new outputs. inputTrace1.IntroduceFrom(ref traceIndices.processed1, ref traceIndices.unprocessed1, true); inputTrace2.IntroduceFrom(ref traceIndices.processed2, ref traceIndices.unprocessed2, true); } inputTrace1.EnsureStateIsCurrentWRTAdvancedTimes(ref traceIndices.processed1); inputTrace2.EnsureStateIsCurrentWRTAdvancedTimes(ref traceIndices.processed2); outputTrace.EnsureStateIsCurrentWRTAdvancedTimes(ref traceIndices.output); UpdateTime(key, traceIndices, this.internTable.Intern(time)); outputTrace.IntroduceFrom(ref traceIndices.output, ref this.outputWorkspace, true); keyIndices[key] = traceIndices; } protected NaiadList<int> timeList = new NaiadList<int>(1); protected NaiadList<int> truthList = new NaiadList<int>(1); protected NaiadList<int> deltaList = new NaiadList<int>(1); protected virtual NaiadList<int> InterestingTimes(BinaryKeyIndices keyIndex) { deltaList.Clear(); inputTrace1.EnumerateTimes(keyIndex.unprocessed1, deltaList); inputTrace2.EnumerateTimes(keyIndex.unprocessed2, deltaList); truthList.Clear(); inputTrace1.EnumerateTimes(keyIndex.processed1, truthList); inputTrace2.EnumerateTimes(keyIndex.processed2, truthList); timeList.Clear(); this.internTable.InterestingTimes(timeList, truthList, deltaList); return timeList; } protected NaiadList<Weighted<R>> outputCollection = new NaiadList<Weighted<R>>(1); protected virtual void UpdateTime(K key, BinaryKeyIndices keyIndex, int timeIndex) { // subtract out prior records before adding new ones // outputTrace.SubtractStrictlyPriorDifferences(ref outputWorkspace, timeIndex); NewOutputMinusOldOutput(key, keyIndex, timeIndex); var outputTime = this.internTable.times[timeIndex]; outputCollection.Clear(); outputTrace.EnumerateDifferenceAt(outputWorkspace, timeIndex, outputCollection); var output = this.Output.GetBufferForTime(outputTime); for (int i = 0; i < outputCollection.Count; i++) output.Send(outputCollection.Array[i]); } protected virtual void NewOutputMinusOldOutput(K key, BinaryKeyIndices keyIndex, int timeIndex) { if (keyIndex.processed1 != 0 || keyIndex.processed2 != 0) Reduce(key, keyIndex, timeIndex); // this suggests we want to init updateToOutput with -output outputCollection.Clear(); outputTrace.EnumerateCollectionAt(keyIndex.output, timeIndex, outputCollection); for (int i = 0; i < outputCollection.Count; i++) outputTrace.Introduce(ref outputWorkspace, outputCollection.Array[i].record, -outputCollection.Array[i].weight, timeIndex); } // expected to populate resultList to match reduction(collection.source) protected virtual void Reduce(K key, BinaryKeyIndices keyIndex, int time) { } /* Checkpoint format: * bool terminated * if !terminated: * LatticeInternTable<T> internTable * CollectionTrace<> inputTrace1 * CollectionTrace<> inputTrace2 * CollectionTrace<> outputTrace * Dictionary<K,KeyIndices> keysToProcess * int recordsToProcessCount1 * (T,NaiadList<Weighted<S>>)*recordsToProcessCount recordsToProcess1 * int recordsToProcessCount2 * (T,NaiadList<Weighted<S>>)*recordsToProcessCount recordsToProcess2 */ protected override void Checkpoint(NaiadWriter writer) { base.Checkpoint(writer); writer.Write(this.isShutdown); if (!this.isShutdown) { this.internTable.Checkpoint(writer); this.inputTrace1.Checkpoint(writer); this.inputTrace2.Checkpoint(writer); this.outputTrace.Checkpoint(writer); this.keyIndices.Checkpoint(writer); this.Input1.Checkpoint(writer); this.Input2.Checkpoint(writer); /* writer.Write(this.recordsToProcess1.Count, PrimitiveSerializers.Int32); foreach (KeyValuePair<T, NaiadList<Weighted<S1>>> kvp in this.recordsToProcess1) { writer.Write(kvp.Key, timeSerializer); kvp.Value.Checkpoint(writer, weightedS1Serializer); } writer.Write(this.recordsToProcess2.Count, PrimitiveSerializers.Int32); foreach (KeyValuePair<T, NaiadList<Weighted<S2>>> kvp in this.recordsToProcess2) { writer.Write(kvp.Key, timeSerializer); kvp.Value.Checkpoint(writer, weightedS2Serializer); } */ } } protected override void Restore(NaiadReader reader) { base.Restore(reader); this.isShutdown = reader.Read<bool>(); if (!this.isShutdown) { this.internTable.Restore(reader); this.inputTrace1.Restore(reader); this.inputTrace2.Restore(reader); this.outputTrace.Restore(reader); this.keyIndices.Restore(reader); this.Input1.Restore(reader); this.Input2.Restore(reader); /* int recordsToProcessCount1 = reader.Read<int>(PrimitiveSerializers.Int32); foreach (NaiadList<Weighted<S1>> recordList in this.recordsToProcess1.Values) recordList.Free(); this.recordsToProcess1.Clear(); for (int i = 0; i < recordsToProcessCount1; ++i) { T key = reader.Read<T>(timeSerializer); NaiadList<Weighted<S1>> value = new NaiadList<Weighted<S1>>(); value.Restore(reader, weightedS1Serializer); this.recordsToProcess1[key] = value; } int recordsToProcessCount2 = reader.Read<int>(PrimitiveSerializers.Int32); foreach (NaiadList<Weighted<S2>> recordList in this.recordsToProcess2.Values) recordList.Free(); this.recordsToProcess2.Clear(); for (int i = 0; i < recordsToProcessCount2; ++i) { T key = reader.Read<T>(timeSerializer); NaiadList<Weighted<S2>> value = new NaiadList<Weighted<S2>>(); value.Restore(reader, weightedS2Serializer); this.recordsToProcess2[key] = value; } */ } } protected readonly bool inputImmutable1 = false; protected readonly bool inputImmutable2 = false; public ConservativeBinaryStatefulOperator(int index, Stage<T> stage, bool input1Immutable, bool input2Immutable, Expression<Func<S1, K>> k1, Expression<Func<S2, K>> k2, Expression<Func<S1, V1>> v1, Expression<Func<S2, V2>> v2, bool maintainOC = true) : base(index, stage, null) { key1 = k1.Compile(); value1 = v1.Compile(); key2 = k2.Compile(); value2 = v2.Compile(); keyExpression1 = k1; keyExpression2 = k2; valueExpression1 = v1; valueExpression2 = v2; inputImmutable1 = input1Immutable; inputImmutable2 = input2Immutable; keyIndices = new Dictionary<K, BinaryKeyIndices>(); inputTrace1 = createInputTrace1(); inputTrace2 = createInputTrace2(); outputTrace = createOutputTrace(); outputWorkspace = 0; } } internal abstract class BinaryStatefulOperator<S, T> : OperatorImplementations.BinaryStatefulOperator<S, S, S, S, S, T, S> where S : IEquatable<S> where T : Time<T> { protected abstract Int64 WeightFunction(Int64 weight1, Int64 weight2); protected override void NewOutputMinusOldOutput(S key, BinaryKeyIndices keyIndices, int timeIndex) { collection1.Clear(); inputTrace1.EnumerateCollectionAt(keyIndices.processed1, timeIndex, collection1); collection2.Clear(); inputTrace2.EnumerateCollectionAt(keyIndices.processed2, timeIndex, collection2); var newSum1 = 0L; for (int i = 0; i < collection1.Count; i++) newSum1 += collection1.Array[i].weight; var newSum2 = 0L; for (int i = 0; i < collection2.Count; i++) newSum2 += collection2.Array[i].weight; difference1.Clear(); inputTrace1.EnumerateCollectionAt(keyIndices.unprocessed1, timeIndex, difference1); difference2.Clear(); inputTrace2.EnumerateCollectionAt(keyIndices.unprocessed2, timeIndex, difference2); var oldSum1 = newSum1; for (int i = 0; i < difference1.Count; i++) oldSum1 -= difference1.Array[i].weight; var oldSum2 = newSum2; for (int i = 0; i < difference2.Count; i++) oldSum2 -= difference2.Array[i].weight; var oldOut = WeightFunction(oldSum1, oldSum2); var newOut = WeightFunction(newSum1, newSum2); if (oldOut != newOut) outputTrace.Introduce(ref outputWorkspace, key, newOut - oldOut, timeIndex); } public BinaryStatefulOperator(int index, Stage<T> stage, bool input1Immutable, bool input2Immutable) : base(index, stage, input1Immutable, input2Immutable, x => x, x => x, x => x, x => x, 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 System.Collections.Generic; using System.Data.Common; using System.Data.SqlTypes; using System.Diagnostics; using System.Globalization; using System.Xml; using System.IO; using MSS = Microsoft.SqlServer.Server; namespace System.Data.SqlClient { internal sealed class MetaType { internal readonly Type ClassType; // com+ type internal readonly Type SqlType; internal readonly int FixedLength; // fixed length size in bytes (-1 for variable) internal readonly bool IsFixed; // true if fixed length, note that sqlchar and sqlbinary are not considered fixed length internal readonly bool IsLong; // true if long internal readonly bool IsPlp; // Column is Partially Length Prefixed (MAX) internal readonly byte Precision; // maximum precision for numeric types internal readonly byte Scale; internal readonly byte TDSType; internal readonly byte NullableType; internal readonly string TypeName; // string name of this type internal readonly SqlDbType SqlDbType; internal readonly DbType DbType; // holds count of property bytes expected for a SQLVariant structure internal readonly byte PropBytes; // pre-computed fields internal readonly bool IsAnsiType; internal readonly bool IsBinType; internal readonly bool IsCharType; internal readonly bool IsNCharType; internal readonly bool IsSizeInCharacters; internal readonly bool IsNewKatmaiType; internal readonly bool IsVarTime; internal readonly bool Is70Supported; internal readonly bool Is80Supported; internal readonly bool Is90Supported; internal readonly bool Is100Supported; public MetaType(byte precision, byte scale, int fixedLength, bool isFixed, bool isLong, bool isPlp, byte tdsType, byte nullableTdsType, string typeName, Type classType, Type sqlType, SqlDbType sqldbType, DbType dbType, byte propBytes) { this.Precision = precision; this.Scale = scale; this.FixedLength = fixedLength; this.IsFixed = isFixed; this.IsLong = isLong; this.IsPlp = isPlp; this.TDSType = tdsType; this.NullableType = nullableTdsType; this.TypeName = typeName; this.SqlDbType = sqldbType; this.DbType = dbType; this.ClassType = classType; this.SqlType = sqlType; this.PropBytes = propBytes; IsAnsiType = _IsAnsiType(sqldbType); IsBinType = _IsBinType(sqldbType); IsCharType = _IsCharType(sqldbType); IsNCharType = _IsNCharType(sqldbType); IsSizeInCharacters = _IsSizeInCharacters(sqldbType); IsNewKatmaiType = _IsNewKatmaiType(sqldbType); IsVarTime = _IsVarTime(sqldbType); Is70Supported = _Is70Supported(SqlDbType); Is80Supported = _Is80Supported(SqlDbType); Is90Supported = _Is90Supported(SqlDbType); Is100Supported = _Is100Supported(SqlDbType); } // properties should be inlined so there should be no perf penalty for using these accessor functions public int TypeId { // partial length prefixed (xml, nvarchar(max),...) get { return 0; } } private static bool _IsAnsiType(SqlDbType type) { return (type == SqlDbType.Char || type == SqlDbType.VarChar || type == SqlDbType.Text); } // is this type size expressed as count of characters or bytes? private static bool _IsSizeInCharacters(SqlDbType type) { return (type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.Xml || type == SqlDbType.NText); } private static bool _IsCharType(SqlDbType type) { return (type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.NText || type == SqlDbType.Char || type == SqlDbType.VarChar || type == SqlDbType.Text || type == SqlDbType.Xml); } private static bool _IsNCharType(SqlDbType type) { return (type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.NText || type == SqlDbType.Xml); } private static bool _IsBinType(SqlDbType type) { return (type == SqlDbType.Image || type == SqlDbType.Binary || type == SqlDbType.VarBinary || type == SqlDbType.Timestamp || type == SqlDbType.Udt || (int)type == 24 /*SqlSmallVarBinary*/); } private static bool _Is70Supported(SqlDbType type) { return ((type != SqlDbType.BigInt) && ((int)type > 0) && ((int)type <= (int)SqlDbType.VarChar)); } private static bool _Is80Supported(SqlDbType type) { return ((int)type >= 0 && ((int)type <= (int)SqlDbType.Variant)); } private static bool _Is90Supported(SqlDbType type) { return _Is80Supported(type) || SqlDbType.Xml == type || SqlDbType.Udt == type; } private static bool _Is100Supported(SqlDbType type) { return _Is90Supported(type) || SqlDbType.Date == type || SqlDbType.Time == type || SqlDbType.DateTime2 == type || SqlDbType.DateTimeOffset == type; } private static bool _IsNewKatmaiType(SqlDbType type) { return SqlDbType.Structured == type; } internal static bool _IsVarTime(SqlDbType type) { return (type == SqlDbType.Time || type == SqlDbType.DateTime2 || type == SqlDbType.DateTimeOffset); } // // map SqlDbType to MetaType class // internal static MetaType GetMetaTypeFromSqlDbType(SqlDbType target, bool isMultiValued) { // WebData 113289 switch (target) { case SqlDbType.BigInt: return s_metaBigInt; case SqlDbType.Binary: return s_metaBinary; case SqlDbType.Bit: return s_metaBit; case SqlDbType.Char: return s_metaChar; case SqlDbType.DateTime: return s_metaDateTime; case SqlDbType.Decimal: return MetaDecimal; case SqlDbType.Float: return s_metaFloat; case SqlDbType.Image: return MetaImage; case SqlDbType.Int: return s_metaInt; case SqlDbType.Money: return s_metaMoney; case SqlDbType.NChar: return s_metaNChar; case SqlDbType.NText: return MetaNText; case SqlDbType.NVarChar: return MetaNVarChar; case SqlDbType.Real: return s_metaReal; case SqlDbType.UniqueIdentifier: return s_metaUniqueId; case SqlDbType.SmallDateTime: return s_metaSmallDateTime; case SqlDbType.SmallInt: return s_metaSmallInt; case SqlDbType.SmallMoney: return s_metaSmallMoney; case SqlDbType.Text: return MetaText; case SqlDbType.Timestamp: return s_metaTimestamp; case SqlDbType.TinyInt: return s_metaTinyInt; case SqlDbType.VarBinary: return MetaVarBinary; case SqlDbType.VarChar: return s_metaVarChar; case SqlDbType.Variant: return s_metaVariant; case (SqlDbType)TdsEnums.SmallVarBinary: return s_metaSmallVarBinary; case SqlDbType.Xml: return MetaXml; case SqlDbType.Udt: return MetaUdt; case SqlDbType.Structured: if (isMultiValued) { return s_metaTable; } else { return s_metaSUDT; } case SqlDbType.Date: return s_metaDate; case SqlDbType.Time: return MetaTime; case SqlDbType.DateTime2: return s_metaDateTime2; case SqlDbType.DateTimeOffset: return MetaDateTimeOffset; default: throw SQL.InvalidSqlDbType(target); } } // // map DbType to MetaType class // internal static MetaType GetMetaTypeFromDbType(DbType target) { // if we can't map it, we need to throw switch (target) { case DbType.AnsiString: return s_metaVarChar; case DbType.AnsiStringFixedLength: return s_metaChar; case DbType.Binary: return MetaVarBinary; case DbType.Byte: return s_metaTinyInt; case DbType.Boolean: return s_metaBit; case DbType.Currency: return s_metaMoney; case DbType.Date: case DbType.DateTime: return s_metaDateTime; case DbType.Decimal: return MetaDecimal; case DbType.Double: return s_metaFloat; case DbType.Guid: return s_metaUniqueId; case DbType.Int16: return s_metaSmallInt; case DbType.Int32: return s_metaInt; case DbType.Int64: return s_metaBigInt; case DbType.Object: return s_metaVariant; case DbType.Single: return s_metaReal; case DbType.String: return MetaNVarChar; case DbType.StringFixedLength: return s_metaNChar; case DbType.Time: return s_metaDateTime; case DbType.Xml: return MetaXml; case DbType.DateTime2: return s_metaDateTime2; case DbType.DateTimeOffset: return MetaDateTimeOffset; case DbType.SByte: // unsupported case DbType.UInt16: case DbType.UInt32: case DbType.UInt64: case DbType.VarNumeric: default: throw ADP.DbTypeNotSupported(target, typeof(SqlDbType)); // no direct mapping, error out } } internal static MetaType GetMaxMetaTypeFromMetaType(MetaType mt) { // if we can't map it, we need to throw switch (mt.SqlDbType) { case SqlDbType.VarBinary: case SqlDbType.Binary: return MetaMaxVarBinary; case SqlDbType.VarChar: case SqlDbType.Char: return MetaMaxVarChar; case SqlDbType.NVarChar: case SqlDbType.NChar: return MetaMaxNVarChar; case SqlDbType.Udt: return s_metaMaxUdt; default: return mt; } } // // map COM+ Type to MetaType class // internal static MetaType GetMetaTypeFromType(Type dataType) { return GetMetaTypeFromValue(dataType, null, false, true); } internal static MetaType GetMetaTypeFromValue(object value, bool streamAllowed = true) { return GetMetaTypeFromValue(value.GetType(), value, true, streamAllowed); } private static MetaType GetMetaTypeFromValue(Type dataType, object value, bool inferLen, bool streamAllowed) { switch (Type.GetTypeCode(dataType)) { case TypeCode.Empty: throw ADP.InvalidDataType(TypeCode.Empty); case TypeCode.Object: if (dataType == typeof(byte[])) { // Must not default to image if inferLen is false if (!inferLen || ((byte[])value).Length <= TdsEnums.TYPE_SIZE_LIMIT) { return MetaVarBinary; } else { return MetaImage; } } else if (dataType == typeof(System.Guid)) { return s_metaUniqueId; } else if (dataType == typeof(object)) { return s_metaVariant; } // check sql types now else if (dataType == typeof(SqlBinary)) return MetaVarBinary; else if (dataType == typeof(SqlBoolean)) return s_metaBit; else if (dataType == typeof(SqlByte)) return s_metaTinyInt; else if (dataType == typeof(SqlBytes)) return MetaVarBinary; else if (dataType == typeof(SqlChars)) return MetaNVarChar; else if (dataType == typeof(SqlDateTime)) return s_metaDateTime; else if (dataType == typeof(SqlDouble)) return s_metaFloat; else if (dataType == typeof(SqlGuid)) return s_metaUniqueId; else if (dataType == typeof(SqlInt16)) return s_metaSmallInt; else if (dataType == typeof(SqlInt32)) return s_metaInt; else if (dataType == typeof(SqlInt64)) return s_metaBigInt; else if (dataType == typeof(SqlMoney)) return s_metaMoney; else if (dataType == typeof(SqlDecimal)) return MetaDecimal; else if (dataType == typeof(SqlSingle)) return s_metaReal; else if (dataType == typeof(SqlXml)) return MetaXml; else if (dataType == typeof(SqlString)) { return ((inferLen && !((SqlString)value).IsNull) ? PromoteStringType(((SqlString)value).Value) : MetaNVarChar); } else if (dataType == typeof(IEnumerable<DbDataRecord>) || dataType == typeof(DataTable)) { return s_metaTable; } else if (dataType == typeof(TimeSpan)) { return MetaTime; } else if (dataType == typeof(DateTimeOffset)) { return MetaDateTimeOffset; } else { // UDT ? SqlUdtInfo attribs = SqlUdtInfo.TryGetFromType(dataType); if (attribs != null) { return MetaUdt; } if (streamAllowed) { // Derived from Stream ? if (typeof(Stream).IsAssignableFrom(dataType)) { return MetaVarBinary; } // Derived from TextReader ? else if (typeof(TextReader).IsAssignableFrom(dataType)) { return MetaNVarChar; } // Derived from XmlReader ? else if (typeof(System.Xml.XmlReader).IsAssignableFrom(dataType)) { return MetaXml; } } } throw ADP.UnknownDataType(dataType); case TypeCode.DBNull: throw ADP.InvalidDataType(TypeCode.DBNull); case TypeCode.Boolean: return s_metaBit; case TypeCode.Char: throw ADP.InvalidDataType(TypeCode.Char); case TypeCode.SByte: throw ADP.InvalidDataType(TypeCode.SByte); case TypeCode.Byte: return s_metaTinyInt; case TypeCode.Int16: return s_metaSmallInt; case TypeCode.UInt16: throw ADP.InvalidDataType(TypeCode.UInt16); case TypeCode.Int32: return s_metaInt; case TypeCode.UInt32: throw ADP.InvalidDataType(TypeCode.UInt32); case TypeCode.Int64: return s_metaBigInt; case TypeCode.UInt64: throw ADP.InvalidDataType(TypeCode.UInt64); case TypeCode.Single: return s_metaReal; case TypeCode.Double: return s_metaFloat; case TypeCode.Decimal: return MetaDecimal; case TypeCode.DateTime: return s_metaDateTime; case TypeCode.String: return (inferLen ? PromoteStringType((string)value) : MetaNVarChar); default: throw ADP.UnknownDataTypeCode(dataType, Type.GetTypeCode(dataType)); } } internal static object GetNullSqlValue(Type sqlType) { if (sqlType == typeof(SqlSingle)) return SqlSingle.Null; else if (sqlType == typeof(SqlString)) return SqlString.Null; else if (sqlType == typeof(SqlDouble)) return SqlDouble.Null; else if (sqlType == typeof(SqlBinary)) return SqlBinary.Null; else if (sqlType == typeof(SqlGuid)) return SqlGuid.Null; else if (sqlType == typeof(SqlBoolean)) return SqlBoolean.Null; else if (sqlType == typeof(SqlByte)) return SqlByte.Null; else if (sqlType == typeof(SqlInt16)) return SqlInt16.Null; else if (sqlType == typeof(SqlInt32)) return SqlInt32.Null; else if (sqlType == typeof(SqlInt64)) return SqlInt64.Null; else if (sqlType == typeof(SqlDecimal)) return SqlDecimal.Null; else if (sqlType == typeof(SqlDateTime)) return SqlDateTime.Null; else if (sqlType == typeof(SqlMoney)) return SqlMoney.Null; else if (sqlType == typeof(SqlXml)) return SqlXml.Null; else if (sqlType == typeof(object)) return DBNull.Value; else if (sqlType == typeof(IEnumerable<DbDataRecord>)) return DBNull.Value; else if (sqlType == typeof(DataTable)) return DBNull.Value; else if (sqlType == typeof(DateTime)) return DBNull.Value; else if (sqlType == typeof(TimeSpan)) return DBNull.Value; else if (sqlType == typeof(DateTimeOffset)) return DBNull.Value; else { Debug.Fail("Unknown SqlType!"); return DBNull.Value; } } internal static MetaType PromoteStringType(string s) { int len = s.Length; if ((len << 1) > TdsEnums.TYPE_SIZE_LIMIT) { return s_metaVarChar; // try as var char since we can send a 8K characters } return MetaNVarChar; // send 4k chars, but send as unicode } internal static object GetComValueFromSqlVariant(object sqlVal) { object comVal = null; if (ADP.IsNull(sqlVal)) return comVal; if (sqlVal is SqlSingle) comVal = ((SqlSingle)sqlVal).Value; else if (sqlVal is SqlString) comVal = ((SqlString)sqlVal).Value; else if (sqlVal is SqlDouble) comVal = ((SqlDouble)sqlVal).Value; else if (sqlVal is SqlBinary) comVal = ((SqlBinary)sqlVal).Value; else if (sqlVal is SqlGuid) comVal = ((SqlGuid)sqlVal).Value; else if (sqlVal is SqlBoolean) comVal = ((SqlBoolean)sqlVal).Value; else if (sqlVal is SqlByte) comVal = ((SqlByte)sqlVal).Value; else if (sqlVal is SqlInt16) comVal = ((SqlInt16)sqlVal).Value; else if (sqlVal is SqlInt32) comVal = ((SqlInt32)sqlVal).Value; else if (sqlVal is SqlInt64) comVal = ((SqlInt64)sqlVal).Value; else if (sqlVal is SqlDecimal) comVal = ((SqlDecimal)sqlVal).Value; else if (sqlVal is SqlDateTime) comVal = ((SqlDateTime)sqlVal).Value; else if (sqlVal is SqlMoney) comVal = ((SqlMoney)sqlVal).Value; else if (sqlVal is SqlXml) comVal = ((SqlXml)sqlVal).Value; else { AssertIsUserDefinedTypeInstance(sqlVal, "unknown SqlType class stored in sqlVal"); } return comVal; } /// <summary> /// Assert that the supplied object is an instance of a SQL User-Defined Type (UDT). /// </summary> /// <param name="sqlValue">Object instance to be tested.</param> /// <remarks> /// This method is only compiled with debug builds, and it a helper method for the GetComValueFromSqlVariant method defined in this class. /// /// The presence of the SqlUserDefinedTypeAttribute on the object's type /// is used to determine if the object is a UDT instance (if present it is a UDT, else it is not). /// </remarks> /// <exception cref="NullReferenceException"> /// If sqlValue is null. Callers must ensure the object is non-null. /// </exception> [Conditional("DEBUG")] private static void AssertIsUserDefinedTypeInstance(object sqlValue, string failedAssertMessage) { Type type = sqlValue.GetType(); Microsoft.SqlServer.Server.SqlUserDefinedTypeAttribute[] attributes = (Microsoft.SqlServer.Server.SqlUserDefinedTypeAttribute[])type.GetCustomAttributes(typeof(Microsoft.SqlServer.Server.SqlUserDefinedTypeAttribute), true); Debug.Assert(attributes.Length > 0, failedAssertMessage); } // devnote: This method should not be used with SqlDbType.Date and SqlDbType.DateTime2. // With these types the values should be used directly as CLR types instead of being converted to a SqlValue internal static object GetSqlValueFromComVariant(object comVal) { object sqlVal = null; if ((null != comVal) && (DBNull.Value != comVal)) { if (comVal is float) sqlVal = new SqlSingle((float)comVal); else if (comVal is string) sqlVal = new SqlString((string)comVal); else if (comVal is double) sqlVal = new SqlDouble((double)comVal); else if (comVal is byte[]) sqlVal = new SqlBinary((byte[])comVal); else if (comVal is char) sqlVal = new SqlString(((char)comVal).ToString()); else if (comVal is char[]) sqlVal = new SqlChars((char[])comVal); else if (comVal is System.Guid) sqlVal = new SqlGuid((Guid)comVal); else if (comVal is bool) sqlVal = new SqlBoolean((bool)comVal); else if (comVal is byte) sqlVal = new SqlByte((byte)comVal); else if (comVal is short) sqlVal = new SqlInt16((short)comVal); else if (comVal is int) sqlVal = new SqlInt32((int)comVal); else if (comVal is long) sqlVal = new SqlInt64((long)comVal); else if (comVal is decimal) sqlVal = new SqlDecimal((decimal)comVal); else if (comVal is DateTime) { // devnote: Do not use with SqlDbType.Date and SqlDbType.DateTime2. See comment at top of method. sqlVal = new SqlDateTime((DateTime)comVal); } else if (comVal is XmlReader) sqlVal = new SqlXml((XmlReader)comVal); else if (comVal is TimeSpan || comVal is DateTimeOffset) sqlVal = comVal; #if DEBUG else Debug.Fail("unknown SqlType class stored in sqlVal"); #endif } return sqlVal; } internal static SqlDbType GetSqlDbTypeFromOleDbType(short dbType, string typeName) { // OleDbTypes not supported return SqlDbType.Variant; } internal static MetaType GetSqlDataType(int tdsType, uint userType, int length) { switch (tdsType) { case TdsEnums.SQLMONEYN: return ((4 == length) ? s_metaSmallMoney : s_metaMoney); case TdsEnums.SQLDATETIMN: return ((4 == length) ? s_metaSmallDateTime : s_metaDateTime); case TdsEnums.SQLINTN: return ((4 <= length) ? ((4 == length) ? s_metaInt : s_metaBigInt) : ((2 == length) ? s_metaSmallInt : s_metaTinyInt)); case TdsEnums.SQLFLTN: return ((4 == length) ? s_metaReal : s_metaFloat); case TdsEnums.SQLTEXT: return MetaText; case TdsEnums.SQLVARBINARY: return s_metaSmallVarBinary; case TdsEnums.SQLBIGVARBINARY: return MetaVarBinary; case TdsEnums.SQLVARCHAR: case TdsEnums.SQLBIGVARCHAR: return s_metaVarChar; case TdsEnums.SQLBINARY: case TdsEnums.SQLBIGBINARY: return ((TdsEnums.SQLTIMESTAMP == userType) ? s_metaTimestamp : s_metaBinary); case TdsEnums.SQLIMAGE: return MetaImage; case TdsEnums.SQLCHAR: case TdsEnums.SQLBIGCHAR: return s_metaChar; case TdsEnums.SQLINT1: return s_metaTinyInt; case TdsEnums.SQLBIT: case TdsEnums.SQLBITN: return s_metaBit; case TdsEnums.SQLINT2: return s_metaSmallInt; case TdsEnums.SQLINT4: return s_metaInt; case TdsEnums.SQLINT8: return s_metaBigInt; case TdsEnums.SQLMONEY: return s_metaMoney; case TdsEnums.SQLDATETIME: return s_metaDateTime; case TdsEnums.SQLFLT8: return s_metaFloat; case TdsEnums.SQLFLT4: return s_metaReal; case TdsEnums.SQLMONEY4: return s_metaSmallMoney; case TdsEnums.SQLDATETIM4: return s_metaSmallDateTime; case TdsEnums.SQLDECIMALN: case TdsEnums.SQLNUMERICN: return MetaDecimal; case TdsEnums.SQLUNIQUEID: return s_metaUniqueId; case TdsEnums.SQLNCHAR: return s_metaNChar; case TdsEnums.SQLNVARCHAR: return MetaNVarChar; case TdsEnums.SQLNTEXT: return MetaNText; case TdsEnums.SQLVARIANT: return s_metaVariant; case TdsEnums.SQLUDT: return MetaUdt; case TdsEnums.SQLXMLTYPE: return MetaXml; case TdsEnums.SQLTABLE: return s_metaTable; case TdsEnums.SQLDATE: return s_metaDate; case TdsEnums.SQLTIME: return MetaTime; case TdsEnums.SQLDATETIME2: return s_metaDateTime2; case TdsEnums.SQLDATETIMEOFFSET: return MetaDateTimeOffset; case TdsEnums.SQLVOID: default: Debug.Fail("Unknown type " + tdsType.ToString(CultureInfo.InvariantCulture)); throw SQL.InvalidSqlDbType((SqlDbType)tdsType); } } internal static MetaType GetDefaultMetaType() { return MetaNVarChar; } // Converts an XmlReader into String internal static string GetStringFromXml(XmlReader xmlreader) { SqlXml sxml = new SqlXml(xmlreader); return sxml.Value; } private static readonly MetaType s_metaBigInt = new MetaType (19, 255, 8, true, false, false, TdsEnums.SQLINT8, TdsEnums.SQLINTN, MetaTypeName.BIGINT, typeof(long), typeof(SqlInt64), SqlDbType.BigInt, DbType.Int64, 0); private static readonly MetaType s_metaFloat = new MetaType (15, 255, 8, true, false, false, TdsEnums.SQLFLT8, TdsEnums.SQLFLTN, MetaTypeName.FLOAT, typeof(double), typeof(SqlDouble), SqlDbType.Float, DbType.Double, 0); private static readonly MetaType s_metaReal = new MetaType (7, 255, 4, true, false, false, TdsEnums.SQLFLT4, TdsEnums.SQLFLTN, MetaTypeName.REAL, typeof(float), typeof(SqlSingle), SqlDbType.Real, DbType.Single, 0); // MetaBinary has two bytes of properties for binary and varbinary // 2 byte maxlen private static readonly MetaType s_metaBinary = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGBINARY, TdsEnums.SQLBIGBINARY, MetaTypeName.BINARY, typeof(byte[]), typeof(SqlBinary), SqlDbType.Binary, DbType.Binary, 2); // Syntactic sugar for the user...timestamps are 8-byte fixed length binary columns private static readonly MetaType s_metaTimestamp = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGBINARY, TdsEnums.SQLBIGBINARY, MetaTypeName.TIMESTAMP, typeof(byte[]), typeof(SqlBinary), SqlDbType.Timestamp, DbType.Binary, 2); internal static readonly MetaType MetaVarBinary = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGVARBINARY, TdsEnums.SQLBIGVARBINARY, MetaTypeName.VARBINARY, typeof(byte[]), typeof(SqlBinary), SqlDbType.VarBinary, DbType.Binary, 2); internal static readonly MetaType MetaMaxVarBinary = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLBIGVARBINARY, TdsEnums.SQLBIGVARBINARY, MetaTypeName.VARBINARY, typeof(byte[]), typeof(SqlBinary), SqlDbType.VarBinary, DbType.Binary, 2); // We have an internal type for smallvarbinarys stored on TdsEnums. We // store on TdsEnums instead of SqlDbType because we do not want to expose // this type to the user. private static readonly MetaType s_metaSmallVarBinary = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLVARBINARY, TdsEnums.SQLBIGBINARY, string.Empty, typeof(byte[]), typeof(SqlBinary), TdsEnums.SmallVarBinary, DbType.Binary, 2); internal static readonly MetaType MetaImage = new MetaType (255, 255, -1, false, true, false, TdsEnums.SQLIMAGE, TdsEnums.SQLIMAGE, MetaTypeName.IMAGE, typeof(byte[]), typeof(SqlBinary), SqlDbType.Image, DbType.Binary, 0); private static readonly MetaType s_metaBit = new MetaType (255, 255, 1, true, false, false, TdsEnums.SQLBIT, TdsEnums.SQLBITN, MetaTypeName.BIT, typeof(bool), typeof(SqlBoolean), SqlDbType.Bit, DbType.Boolean, 0); private static readonly MetaType s_metaTinyInt = new MetaType (3, 255, 1, true, false, false, TdsEnums.SQLINT1, TdsEnums.SQLINTN, MetaTypeName.TINYINT, typeof(byte), typeof(SqlByte), SqlDbType.TinyInt, DbType.Byte, 0); private static readonly MetaType s_metaSmallInt = new MetaType (5, 255, 2, true, false, false, TdsEnums.SQLINT2, TdsEnums.SQLINTN, MetaTypeName.SMALLINT, typeof(short), typeof(SqlInt16), SqlDbType.SmallInt, DbType.Int16, 0); private static readonly MetaType s_metaInt = new MetaType (10, 255, 4, true, false, false, TdsEnums.SQLINT4, TdsEnums.SQLINTN, MetaTypeName.INT, typeof(int), typeof(SqlInt32), SqlDbType.Int, DbType.Int32, 0); // MetaVariant has seven bytes of properties for MetaChar and MetaVarChar // 5 byte tds collation // 2 byte maxlen private static readonly MetaType s_metaChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGCHAR, TdsEnums.SQLBIGCHAR, MetaTypeName.CHAR, typeof(string), typeof(SqlString), SqlDbType.Char, DbType.AnsiStringFixedLength, 7); private static readonly MetaType s_metaVarChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGVARCHAR, TdsEnums.SQLBIGVARCHAR, MetaTypeName.VARCHAR, typeof(string), typeof(SqlString), SqlDbType.VarChar, DbType.AnsiString, 7); internal static readonly MetaType MetaMaxVarChar = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLBIGVARCHAR, TdsEnums.SQLBIGVARCHAR, MetaTypeName.VARCHAR, typeof(string), typeof(SqlString), SqlDbType.VarChar, DbType.AnsiString, 7); internal static readonly MetaType MetaText = new MetaType (255, 255, -1, false, true, false, TdsEnums.SQLTEXT, TdsEnums.SQLTEXT, MetaTypeName.TEXT, typeof(string), typeof(SqlString), SqlDbType.Text, DbType.AnsiString, 0); // MetaVariant has seven bytes of properties for MetaNChar and MetaNVarChar // 5 byte tds collation // 2 byte maxlen private static readonly MetaType s_metaNChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLNCHAR, TdsEnums.SQLNCHAR, MetaTypeName.NCHAR, typeof(string), typeof(SqlString), SqlDbType.NChar, DbType.StringFixedLength, 7); internal static readonly MetaType MetaNVarChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLNVARCHAR, TdsEnums.SQLNVARCHAR, MetaTypeName.NVARCHAR, typeof(string), typeof(SqlString), SqlDbType.NVarChar, DbType.String, 7); internal static readonly MetaType MetaMaxNVarChar = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLNVARCHAR, TdsEnums.SQLNVARCHAR, MetaTypeName.NVARCHAR, typeof(string), typeof(SqlString), SqlDbType.NVarChar, DbType.String, 7); internal static readonly MetaType MetaNText = new MetaType (255, 255, -1, false, true, false, TdsEnums.SQLNTEXT, TdsEnums.SQLNTEXT, MetaTypeName.NTEXT, typeof(string), typeof(SqlString), SqlDbType.NText, DbType.String, 7); // MetaVariant has two bytes of properties for numeric/decimal types // 1 byte precision // 1 byte scale internal static readonly MetaType MetaDecimal = new MetaType (38, 4, 17, true, false, false, TdsEnums.SQLNUMERICN, TdsEnums.SQLNUMERICN, MetaTypeName.DECIMAL, typeof(decimal), typeof(SqlDecimal), SqlDbType.Decimal, DbType.Decimal, 2); internal static readonly MetaType MetaXml = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLXMLTYPE, TdsEnums.SQLXMLTYPE, MetaTypeName.XML, typeof(string), typeof(SqlXml), SqlDbType.Xml, DbType.Xml, 0); private static readonly MetaType s_metaDateTime = new MetaType (23, 3, 8, true, false, false, TdsEnums.SQLDATETIME, TdsEnums.SQLDATETIMN, MetaTypeName.DATETIME, typeof(System.DateTime), typeof(SqlDateTime), SqlDbType.DateTime, DbType.DateTime, 0); private static readonly MetaType s_metaSmallDateTime = new MetaType (16, 0, 4, true, false, false, TdsEnums.SQLDATETIM4, TdsEnums.SQLDATETIMN, MetaTypeName.SMALLDATETIME, typeof(System.DateTime), typeof(SqlDateTime), SqlDbType.SmallDateTime, DbType.DateTime, 0); private static readonly MetaType s_metaMoney = new MetaType (19, 255, 8, true, false, false, TdsEnums.SQLMONEY, TdsEnums.SQLMONEYN, MetaTypeName.MONEY, typeof(decimal), typeof(SqlMoney), SqlDbType.Money, DbType.Currency, 0); private static readonly MetaType s_metaSmallMoney = new MetaType (10, 255, 4, true, false, false, TdsEnums.SQLMONEY4, TdsEnums.SQLMONEYN, MetaTypeName.SMALLMONEY, typeof(decimal), typeof(SqlMoney), SqlDbType.SmallMoney, DbType.Currency, 0); private static readonly MetaType s_metaUniqueId = new MetaType (255, 255, 16, true, false, false, TdsEnums.SQLUNIQUEID, TdsEnums.SQLUNIQUEID, MetaTypeName.ROWGUID, typeof(System.Guid), typeof(SqlGuid), SqlDbType.UniqueIdentifier, DbType.Guid, 0); private static readonly MetaType s_metaVariant = new MetaType (255, 255, -1, true, false, false, TdsEnums.SQLVARIANT, TdsEnums.SQLVARIANT, MetaTypeName.VARIANT, typeof(object), typeof(object), SqlDbType.Variant, DbType.Object, 0); internal static readonly MetaType MetaUdt = new MetaType (255, 255, -1, false, false, true, TdsEnums.SQLUDT, TdsEnums.SQLUDT, MetaTypeName.UDT, typeof(object), typeof(object), SqlDbType.Udt, DbType.Object, 0); private static readonly MetaType s_metaMaxUdt = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLUDT, TdsEnums.SQLUDT, MetaTypeName.UDT, typeof(object), typeof(object), SqlDbType.Udt, DbType.Object, 0); private static readonly MetaType s_metaTable = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLTABLE, TdsEnums.SQLTABLE, MetaTypeName.TABLE, typeof(IEnumerable<DbDataRecord>), typeof(IEnumerable<DbDataRecord>), SqlDbType.Structured, DbType.Object, 0); private static readonly MetaType s_metaSUDT = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLVOID, TdsEnums.SQLVOID, "", typeof(MSS.SqlDataRecord), typeof(MSS.SqlDataRecord), SqlDbType.Structured, DbType.Object, 0); private static readonly MetaType s_metaDate = new MetaType (255, 255, 3, true, false, false, TdsEnums.SQLDATE, TdsEnums.SQLDATE, MetaTypeName.DATE, typeof(System.DateTime), typeof(System.DateTime), SqlDbType.Date, DbType.Date, 0); internal static readonly MetaType MetaTime = new MetaType (255, 7, -1, false, false, false, TdsEnums.SQLTIME, TdsEnums.SQLTIME, MetaTypeName.TIME, typeof(System.TimeSpan), typeof(System.TimeSpan), SqlDbType.Time, DbType.Time, 1); private static readonly MetaType s_metaDateTime2 = new MetaType (255, 7, -1, false, false, false, TdsEnums.SQLDATETIME2, TdsEnums.SQLDATETIME2, MetaTypeName.DATETIME2, typeof(System.DateTime), typeof(System.DateTime), SqlDbType.DateTime2, DbType.DateTime2, 1); internal static readonly MetaType MetaDateTimeOffset = new MetaType (255, 7, -1, false, false, false, TdsEnums.SQLDATETIMEOFFSET, TdsEnums.SQLDATETIMEOFFSET, MetaTypeName.DATETIMEOFFSET, typeof(System.DateTimeOffset), typeof(System.DateTimeOffset), SqlDbType.DateTimeOffset, DbType.DateTimeOffset, 1); public static TdsDateTime FromDateTime(DateTime dateTime, byte cb) { SqlDateTime sqlDateTime; TdsDateTime tdsDateTime = new TdsDateTime(); Debug.Assert(cb == 8 || cb == 4, "Invalid date time size!"); if (cb == 8) { sqlDateTime = new SqlDateTime(dateTime); tdsDateTime.time = sqlDateTime.TimeTicks; } else { // note that smalldatetime is days & minutes. // Adding 30 seconds ensures proper roundup if the seconds are >= 30 // The AddSeconds function handles eventual carryover sqlDateTime = new SqlDateTime(dateTime.AddSeconds(30)); tdsDateTime.time = sqlDateTime.TimeTicks / SqlDateTime.SQLTicksPerMinute; } tdsDateTime.days = sqlDateTime.DayTicks; return tdsDateTime; } public static DateTime ToDateTime(int sqlDays, int sqlTime, int length) { if (length == 4) { return new SqlDateTime(sqlDays, sqlTime * SqlDateTime.SQLTicksPerMinute).Value; } else { Debug.Assert(length == 8, "invalid length for DateTime"); return new SqlDateTime(sqlDays, sqlTime).Value; } } internal static int GetTimeSizeFromScale(byte scale) { if (scale <= 2) return 3; if (scale <= 4) return 4; return 5; } // // please leave string sorted alphabetically // note that these names should only be used in the context of parameters. We always send over BIG* and nullable types for SQL Server // private static class MetaTypeName { public const string BIGINT = "bigint"; public const string BINARY = "binary"; public const string BIT = "bit"; public const string CHAR = "char"; public const string DATETIME = "datetime"; public const string DECIMAL = "decimal"; public const string FLOAT = "float"; public const string IMAGE = "image"; public const string INT = "int"; public const string MONEY = "money"; public const string NCHAR = "nchar"; public const string NTEXT = "ntext"; public const string NVARCHAR = "nvarchar"; public const string REAL = "real"; public const string ROWGUID = "uniqueidentifier"; public const string SMALLDATETIME = "smalldatetime"; public const string SMALLINT = "smallint"; public const string SMALLMONEY = "smallmoney"; public const string TEXT = "text"; public const string TIMESTAMP = "timestamp"; public const string TINYINT = "tinyint"; public const string UDT = "udt"; public const string VARBINARY = "varbinary"; public const string VARCHAR = "varchar"; public const string VARIANT = "sql_variant"; public const string XML = "xml"; public const string TABLE = "table"; public const string DATE = "date"; public const string TIME = "time"; public const string DATETIME2 = "datetime2"; public const string DATETIMEOFFSET = "datetimeoffset"; } } // // note: it is the client's responsibility to know what size date time he is working with // internal struct TdsDateTime { public int days; // offset in days from 1/1/1900 // private UInt32 time; // if smalldatetime, this is # of minutes since midnight // otherwise: # of 1/300th of a second since midnight public int time; } }
// 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.Text; using System.IO; using System.Diagnostics; [assembly: System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] namespace System.Xml.XmlDiff { internal enum DiffType { None, Success, Element, Whitespace, Comment, PI, Text, CData, Attribute, NS, Prefix, SourceExtra, TargetExtra, NodeType } public class XmlDiff { private XmlDiffDocument _SourceDoc; private XmlDiffDocument _TargetDoc; private XmlWriter _Writer; // Writer to write out the result private StringBuilder _Output; // Option Flags private XmlDiffOption _XmlDiffOption = XmlDiffOption.None; private bool _IgnoreEmptyElement = true; private bool _IgnoreWhitespace = true; private bool _IgnoreComments = false; private bool _IgnoreAttributeOrder = true; private bool _IgnoreNS = true; private bool _IgnorePrefix = true; private bool _IgnoreDTD = true; private bool _IgnoreChildOrder = true; public XmlDiff() { } public XmlDiffOption Option { get { return _XmlDiffOption; } set { _XmlDiffOption = value; IgnoreEmptyElement = (((int)_XmlDiffOption) & ((int)XmlDiffOption.IgnoreEmptyElement)) > 0; IgnoreWhitespace = (((int)_XmlDiffOption) & ((int)XmlDiffOption.IgnoreWhitespace)) > 0; IgnoreComments = (((int)_XmlDiffOption) & ((int)XmlDiffOption.IgnoreComments)) > 0; IgnoreAttributeOrder = (((int)_XmlDiffOption) & ((int)XmlDiffOption.IgnoreAttributeOrder)) > 0; IgnoreNS = (((int)_XmlDiffOption) & ((int)XmlDiffOption.IgnoreNS)) > 0; IgnorePrefix = (((int)_XmlDiffOption) & ((int)XmlDiffOption.IgnorePrefix)) > 0; IgnoreDTD = (((int)_XmlDiffOption) & ((int)XmlDiffOption.IgnoreDTD)) > 0; IgnoreChildOrder = (((int)_XmlDiffOption) & ((int)XmlDiffOption.IgnoreChildOrder)) > 0; } } internal bool IgnoreEmptyElement { get { return _IgnoreEmptyElement; } set { _IgnoreEmptyElement = value; } } internal bool IgnoreComments { get { return _IgnoreComments; } set { _IgnoreComments = value; } } internal bool IgnoreAttributeOrder { get { return _IgnoreAttributeOrder; } set { _IgnoreAttributeOrder = value; } } internal bool IgnoreWhitespace { get { return _IgnoreWhitespace; } set { _IgnoreWhitespace = value; } } internal bool IgnoreNS { get { return _IgnoreNS; } set { _IgnoreNS = value; } } internal bool IgnorePrefix { get { return _IgnorePrefix; } set { _IgnorePrefix = value; } } internal bool IgnoreDTD { get { return _IgnoreDTD; } set { _IgnoreDTD = value; } } internal bool IgnoreChildOrder { get { return _IgnoreChildOrder; } set { _IgnoreChildOrder = value; } } private void InitFiles() { this._SourceDoc = new XmlDiffDocument(); this._SourceDoc.Option = this._XmlDiffOption; this._TargetDoc = new XmlDiffDocument(); this._TargetDoc.Option = this.Option; _Output = new StringBuilder(String.Empty); } public bool Compare(Stream source, Stream target) { InitFiles(); this._SourceDoc.Load(XmlReader.Create(source)); this._TargetDoc.Load(XmlReader.Create(target)); return Diff(); } public bool Compare(XmlReader source, XmlReader target) { InitFiles(); this._SourceDoc.Load(source); this._TargetDoc.Load(target); return Diff(); } public bool Compare(XmlReader source, XmlReader target, XmlDiffAdvancedOptions advOptions) { InitFiles(); this._SourceDoc.Load(source); this._TargetDoc.Load(target); XmlDiffNavigator nav = this._SourceDoc.CreateNavigator(); if (advOptions.IgnoreChildOrderExpr != null && advOptions.IgnoreChildOrderExpr != "") { this._SourceDoc.SortChildren(); this._TargetDoc.SortChildren(); } return Diff(); } private bool Diff() { bool flag = false; XmlWriterSettings xws = new XmlWriterSettings(); xws.ConformanceLevel = ConformanceLevel.Auto; xws.CheckCharacters = false; _Writer = XmlWriter.Create(new StringWriter(_Output), xws); _Writer.WriteStartElement(String.Empty, "Root", String.Empty); flag = CompareChildren(this._SourceDoc, this._TargetDoc); _Writer.WriteEndElement(); _Writer.Dispose(); return flag; } // This function is being called recursively to compare the children of a certain node. // When calling this function the navigator should be pointing at the parent node whose children // we wants to compare and return the navigator back to the same node before exiting from it. private bool CompareChildren(XmlDiffNode sourceNode, XmlDiffNode targetNode) { XmlDiffNode sourceChild = sourceNode.FirstChild; XmlDiffNode targetChild = targetNode.FirstChild; bool flag = true; bool tempFlag = true; DiffType result; // Loop to compare all the child elements of the parent node while (sourceChild != null || targetChild != null) { //Console.WriteLine( (sourceChild!=null)?(sourceChild.NodeType.ToString()):"null" ); //Console.WriteLine( (targetChild!=null)?(targetChild.NodeType.ToString()):"null" ); if (sourceChild != null) { if (targetChild != null) { // Both Source and Target Read successful if ((result = CompareNodes(sourceChild, targetChild)) == DiffType.Success) { // Child nodes compared successfully, write out the result WriteResult(sourceChild, targetChild, DiffType.Success); // Check whether this Node has Children, if it does call CompareChildren recursively if (sourceChild.FirstChild != null) tempFlag = CompareChildren(sourceChild, targetChild); else if (targetChild.FirstChild != null) { WriteResult(null, targetChild, DiffType.TargetExtra); tempFlag = false; } // set the compare flag flag = (flag && tempFlag); // Writing out End Element to the result if (sourceChild.NodeType == XmlDiffNodeType.Element && !(sourceChild is XmlDiffEmptyElement)) { XmlDiffElement sourceElem = sourceChild as XmlDiffElement; XmlDiffElement targetElem = targetChild as XmlDiffElement; Debug.Assert(sourceElem != null); Debug.Assert(targetElem != null); _Writer.WriteStartElement(String.Empty, "Node", String.Empty); _Writer.WriteAttributeString(String.Empty, "SourceLineNum", String.Empty, sourceElem.EndLineNumber.ToString()); _Writer.WriteAttributeString(String.Empty, "SourceLinePos", String.Empty, sourceElem.EndLinePosition.ToString()); _Writer.WriteAttributeString(String.Empty, "TargetLineNum", String.Empty, targetElem.EndLineNumber.ToString()); _Writer.WriteAttributeString(String.Empty, "TargetLinePos", String.Empty, targetElem.EndLinePosition.ToString()); _Writer.WriteStartElement(String.Empty, "Diff", String.Empty); _Writer.WriteEndElement(); _Writer.WriteStartElement(String.Empty, "Lexical-equal", String.Empty); _Writer.WriteCData("</" + sourceElem.Name + ">"); _Writer.WriteEndElement(); _Writer.WriteEndElement(); } // Move to Next child sourceChild = sourceChild.NextSibling; targetChild = targetChild.NextSibling; } else { // Child nodes not matched, start the recovery process bool recoveryFlag = false; // Try to match the source node with the target nodes at the same level XmlDiffNode backupTargetChild = targetChild.NextSibling; while (!recoveryFlag && backupTargetChild != null) { if (CompareNodes(sourceChild, backupTargetChild) == DiffType.Success) { recoveryFlag = true; do { WriteResult(null, targetChild, DiffType.TargetExtra); targetChild = targetChild.NextSibling; } while (targetChild != backupTargetChild); break; } backupTargetChild = backupTargetChild.NextSibling; } // If not recovered, try to match the target node with the source nodes at the same level if (!recoveryFlag) { XmlDiffNode backupSourceChild = sourceChild.NextSibling; while (!recoveryFlag && backupSourceChild != null) { if (CompareNodes(backupSourceChild, targetChild) == DiffType.Success) { recoveryFlag = true; do { WriteResult(sourceChild, null, DiffType.SourceExtra); sourceChild = sourceChild.NextSibling; } while (sourceChild != backupSourceChild); break; } backupSourceChild = backupSourceChild.NextSibling; } } // If still not recovered, write both of them as different nodes and move on if (!recoveryFlag) { WriteResult(sourceChild, targetChild, result); // Check whether this Node has Children, if it does call CompareChildren recursively if (sourceChild.FirstChild != null) { tempFlag = CompareChildren(sourceChild, targetChild); } else if (targetChild.FirstChild != null) { WriteResult(null, targetChild, DiffType.TargetExtra); tempFlag = false; } // Writing out End Element to the result bool bSourceNonEmpElemEnd = (sourceChild.NodeType == XmlDiffNodeType.Element && !(sourceChild is XmlDiffEmptyElement)); bool bTargetNonEmpElemEnd = (targetChild.NodeType == XmlDiffNodeType.Element && !(targetChild is XmlDiffEmptyElement)); if (bSourceNonEmpElemEnd || bTargetNonEmpElemEnd) { XmlDiffElement sourceElem = sourceChild as XmlDiffElement; XmlDiffElement targetElem = targetChild as XmlDiffElement; _Writer.WriteStartElement(String.Empty, "Node", String.Empty); _Writer.WriteAttributeString(String.Empty, "SourceLineNum", String.Empty, (sourceElem != null) ? sourceElem.EndLineNumber.ToString() : "-1"); _Writer.WriteAttributeString(String.Empty, "SourceLinePos", String.Empty, (sourceElem != null) ? sourceElem.EndLinePosition.ToString() : "-1"); _Writer.WriteAttributeString(String.Empty, "TargetLineNum", String.Empty, (targetElem != null) ? targetElem.EndLineNumber.ToString() : "-1"); _Writer.WriteAttributeString(String.Empty, "TargetLinePos", String.Empty, (targetElem != null) ? targetElem.EndLineNumber.ToString() : "-1"); _Writer.WriteStartElement(String.Empty, "Diff", String.Empty); _Writer.WriteAttributeString(String.Empty, "DiffType", String.Empty, GetDiffType(result)); if (bSourceNonEmpElemEnd) { _Writer.WriteStartElement(String.Empty, "File1", String.Empty); _Writer.WriteCData("</" + sourceElem.Name + ">"); _Writer.WriteEndElement(); } if (bTargetNonEmpElemEnd) { _Writer.WriteStartElement(String.Empty, "File2", String.Empty); _Writer.WriteCData("</" + targetElem.Name + ">"); _Writer.WriteEndElement(); } _Writer.WriteEndElement(); _Writer.WriteStartElement(String.Empty, "Lexical-equal", String.Empty); _Writer.WriteEndElement(); _Writer.WriteEndElement(); } sourceChild = sourceChild.NextSibling; targetChild = targetChild.NextSibling; } flag = false; } } else { // SourceRead NOT NULL targetRead is NULL WriteResult(sourceChild, null, DiffType.SourceExtra); flag = false; sourceChild = sourceChild.NextSibling; } } else if (targetChild != null) { // SourceRead is NULL and targetRead is NOT NULL WriteResult(null, targetChild, DiffType.TargetExtra); flag = false; targetChild = targetChild.NextSibling; } else { //Both SourceRead and TargetRead is NULL Debug.Assert(false, "Impossible Situation for comparison"); } } return flag; } // This function compares the two nodes passed to it, depending upon the options set by the user. private DiffType CompareNodes(XmlDiffNode sourceNode, XmlDiffNode targetNode) { if (sourceNode.NodeType != targetNode.NodeType) { return DiffType.NodeType; } switch (sourceNode.NodeType) { case XmlDiffNodeType.Element: XmlDiffElement sourceElem = sourceNode as XmlDiffElement; XmlDiffElement targetElem = targetNode as XmlDiffElement; Debug.Assert(sourceElem != null); Debug.Assert(targetElem != null); if (!IgnoreNS) { if (sourceElem.NamespaceURI != targetElem.NamespaceURI) return DiffType.NS; } if (!IgnorePrefix) { if (sourceElem.Prefix != targetElem.Prefix) return DiffType.Prefix; } if (sourceElem.LocalName != targetElem.LocalName) return DiffType.Element; if (!IgnoreEmptyElement) { if ((sourceElem is XmlDiffEmptyElement) != (targetElem is XmlDiffEmptyElement)) return DiffType.Element; } if (!CompareAttributes(sourceElem, targetElem)) { return DiffType.Attribute; } break; case XmlDiffNodeType.Text: case XmlDiffNodeType.Comment: case XmlDiffNodeType.WS: XmlDiffCharacterData sourceText = sourceNode as XmlDiffCharacterData; XmlDiffCharacterData targetText = targetNode as XmlDiffCharacterData; Debug.Assert(sourceText != null); Debug.Assert(targetText != null); if (IgnoreWhitespace) { if (sourceText.Value.Trim() == targetText.Value.Trim()) return DiffType.Success; } else { if (sourceText.Value == targetText.Value) return DiffType.Success; } if (sourceText.NodeType == XmlDiffNodeType.Text || sourceText.NodeType == XmlDiffNodeType.WS)//should ws nodes also as text nodes??? return DiffType.Text; else if (sourceText.NodeType == XmlDiffNodeType.Comment) return DiffType.Comment; else if (sourceText.NodeType == XmlDiffNodeType.CData) return DiffType.CData; else return DiffType.None; case XmlDiffNodeType.PI: XmlDiffProcessingInstruction sourcePI = sourceNode as XmlDiffProcessingInstruction; XmlDiffProcessingInstruction targetPI = targetNode as XmlDiffProcessingInstruction; Debug.Assert(sourcePI != null); Debug.Assert(targetPI != null); if (sourcePI.Name != targetPI.Name || sourcePI.Value != targetPI.Value) return DiffType.PI; break; default: break; } return DiffType.Success; } // This function writes the result in XML format so that it can be used by other applications to display the diff private void WriteResult(XmlDiffNode sourceNode, XmlDiffNode targetNode, DiffType result) { _Writer.WriteStartElement(String.Empty, "Node", String.Empty); _Writer.WriteAttributeString(String.Empty, "SourceLineNum", String.Empty, (sourceNode != null) ? sourceNode.LineNumber.ToString() : "-1"); _Writer.WriteAttributeString(String.Empty, "SourceLinePos", String.Empty, (sourceNode != null) ? sourceNode.LinePosition.ToString() : "-1"); _Writer.WriteAttributeString(String.Empty, "TargetLineNum", String.Empty, (targetNode != null) ? targetNode.LineNumber.ToString() : "-1"); _Writer.WriteAttributeString(String.Empty, "TargetLinePos", String.Empty, (targetNode != null) ? targetNode.LinePosition.ToString() : "-1"); if (result == DiffType.Success) { _Writer.WriteStartElement(String.Empty, "Diff", String.Empty); _Writer.WriteEndElement(); _Writer.WriteStartElement(String.Empty, "Lexical-equal", String.Empty); if (sourceNode.NodeType == XmlDiffNodeType.CData) { _Writer.WriteString("<![CDATA["); _Writer.WriteCData(GetNodeText(sourceNode, result)); _Writer.WriteString("]]>"); } else { _Writer.WriteCData(GetNodeText(sourceNode, result)); } _Writer.WriteEndElement(); } else { _Writer.WriteStartElement(String.Empty, "Diff", String.Empty); _Writer.WriteAttributeString(String.Empty, "DiffType", String.Empty, GetDiffType(result)); if (sourceNode != null) { _Writer.WriteStartElement(String.Empty, "File1", String.Empty); if (sourceNode.NodeType == XmlDiffNodeType.CData) { _Writer.WriteString("<![CDATA["); _Writer.WriteCData(GetNodeText(sourceNode, result)); _Writer.WriteString("]]>"); } else { _Writer.WriteString(GetNodeText(sourceNode, result)); } _Writer.WriteEndElement(); } if (targetNode != null) { _Writer.WriteStartElement(String.Empty, "File2", String.Empty); if (targetNode.NodeType == XmlDiffNodeType.CData) { _Writer.WriteString("<![CDATA["); _Writer.WriteCData(GetNodeText(targetNode, result)); _Writer.WriteString("]]>"); } else { _Writer.WriteString(GetNodeText(targetNode, result)); } _Writer.WriteEndElement(); } _Writer.WriteEndElement(); _Writer.WriteStartElement(String.Empty, "Lexical-equal", String.Empty); _Writer.WriteEndElement(); } _Writer.WriteEndElement(); } // This is a helper function for WriteResult. It gets the Xml representation of the different node we wants // to write out and all it's children. private String GetNodeText(XmlDiffNode diffNode, DiffType result) { string text = string.Empty; switch (diffNode.NodeType) { case XmlDiffNodeType.Element: if (result == DiffType.SourceExtra || result == DiffType.TargetExtra) return diffNode.OuterXml; StringWriter str = new StringWriter(); XmlWriter writer = XmlWriter.Create(str); XmlDiffElement diffElem = diffNode as XmlDiffElement; Debug.Assert(diffNode != null); writer.WriteStartElement(diffElem.Prefix, diffElem.LocalName, diffElem.NamespaceURI); XmlDiffAttribute diffAttr = diffElem.FirstAttribute; while (diffAttr != null) { writer.WriteAttributeString(diffAttr.Prefix, diffAttr.LocalName, diffAttr.NamespaceURI, diffAttr.Value); diffAttr = (XmlDiffAttribute)diffAttr.NextSibling; } if (diffElem is XmlDiffEmptyElement) { writer.WriteEndElement(); text = str.ToString(); } else { text = str.ToString(); text += ">"; } writer.Dispose(); break; case XmlDiffNodeType.CData: text = ((XmlDiffCharacterData)diffNode).Value; break; default: text = diffNode.OuterXml; break; } return text; } // This function is used to compare the attributes of an element node according to the options set by the user. private bool CompareAttributes(XmlDiffElement sourceElem, XmlDiffElement targetElem) { Debug.Assert(sourceElem != null); Debug.Assert(targetElem != null); if (sourceElem.AttributeCount != targetElem.AttributeCount) return false; if (sourceElem.AttributeCount == 0) return true; XmlDiffAttribute sourceAttr = sourceElem.FirstAttribute; XmlDiffAttribute targetAttr = targetElem.FirstAttribute; while (sourceAttr != null && targetAttr != null) { if (!IgnoreNS) { if (sourceAttr.NamespaceURI != targetAttr.NamespaceURI) return false; } if (!IgnorePrefix) { if (sourceAttr.Prefix != targetAttr.Prefix) return false; } if (sourceAttr.LocalName != targetAttr.LocalName || sourceAttr.Value != targetAttr.Value) return false; sourceAttr = (XmlDiffAttribute)(sourceAttr.NextSibling); targetAttr = (XmlDiffAttribute)(targetAttr.NextSibling); } return true; } public string ToXml() { if (_Output != null) return _Output.ToString(); return string.Empty; } public void ToXml(Stream stream) { StreamWriter writer = new StreamWriter(stream); writer.Write("<?xml-stylesheet type='text/xsl' href='diff.xsl'?>"); writer.Write(ToXml()); writer.Dispose(); } private String GetDiffType(DiffType type) { switch (type) { case DiffType.None: return String.Empty; case DiffType.Element: return "1"; case DiffType.Whitespace: return "2"; case DiffType.Comment: return "3"; case DiffType.PI: return "4"; case DiffType.Text: return "5"; case DiffType.Attribute: return "6"; case DiffType.NS: return "7"; case DiffType.Prefix: return "8"; case DiffType.SourceExtra: return "9"; case DiffType.TargetExtra: return "10"; case DiffType.NodeType: return "11"; case DiffType.CData: return "12"; default: return String.Empty; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsHttp { using Models; /// <summary> /// HttpRedirects operations. /// </summary> public partial interface IHttpRedirects { /// <summary> /// Return 300 status code and redirect to /http/success/200 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationHeaderResponse<HttpRedirectsHead300Headers>> Head300WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 300 status code and redirect to /http/success/200 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<string>,HttpRedirectsGet300Headers>> Get300WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 301 status code and redirect to /http/success/200 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationHeaderResponse<HttpRedirectsHead301Headers>> Head301WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 301 status code and redirect to /http/success/200 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationHeaderResponse<HttpRedirectsGet301Headers>> Get301WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Put true Boolean value in request returns 301. This request /// should not be automatically redirected, but should return the /// received 301 to the caller for evaluation /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationHeaderResponse<HttpRedirectsPut301Headers>> Put301WithHttpMessagesAsync(bool? booleanValue = default(bool?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 302 status code and redirect to /http/success/200 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationHeaderResponse<HttpRedirectsHead302Headers>> Head302WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 302 status code and redirect to /http/success/200 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationHeaderResponse<HttpRedirectsGet302Headers>> Get302WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Patch true Boolean value in request returns 302. This request /// should not be automatically redirected, but should return the /// received 302 to the caller for evaluation /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationHeaderResponse<HttpRedirectsPatch302Headers>> Patch302WithHttpMessagesAsync(bool? booleanValue = default(bool?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Post true Boolean value in request returns 303. This request /// should be automatically redirected usign a get, ultimately /// returning a 200 status code /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationHeaderResponse<HttpRedirectsPost303Headers>> Post303WithHttpMessagesAsync(bool? booleanValue = default(bool?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Redirect with 307, resulting in a 200 success /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationHeaderResponse<HttpRedirectsHead307Headers>> Head307WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Redirect get with 307, resulting in a 200 success /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationHeaderResponse<HttpRedirectsGet307Headers>> Get307WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Put redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationHeaderResponse<HttpRedirectsPut307Headers>> Put307WithHttpMessagesAsync(bool? booleanValue = default(bool?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Patch redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationHeaderResponse<HttpRedirectsPatch307Headers>> Patch307WithHttpMessagesAsync(bool? booleanValue = default(bool?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Post redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationHeaderResponse<HttpRedirectsPost307Headers>> Post307WithHttpMessagesAsync(bool? booleanValue = default(bool?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Delete redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationHeaderResponse<HttpRedirectsDelete307Headers>> Delete307WithHttpMessagesAsync(bool? booleanValue = default(bool?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } }
using System; using System.Text; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace HETSAPI.Models { /// <summary> /// History Database Model /// </summary> [MetaData (Description = "A log entry created by the system based on a triggering event and related to an entity in the application - e.g. piece of Equipment, an Owner, a Project and so on.")] public sealed class History : AuditableEntity, IEquatable<History> { /// <summary> /// Default constructor, required by entity framework /// </summary> public History() { Id = 0; } /// <summary> /// Initializes a new instance of the <see cref="History" /> class. /// </summary> /// <param name="id">A system-generated unique identifier for a History (required).</param> /// <param name="historyText">The text of the history entry tracked against the related entity. (required).</param> /// <param name="createdDate">Date the record is created..</param> public History(int id, string historyText, DateTime? createdDate = null) { Id = id; HistoryText = historyText; CreatedDate = createdDate; } /// <summary> /// A system-generated unique identifier for a History /// </summary> /// <value>A system-generated unique identifier for a History</value> [MetaData (Description = "A system-generated unique identifier for a History")] public int Id { get; set; } /// <summary> /// The text of the history entry tracked against the related entity. /// </summary> /// <value>The text of the history entry tracked against the related entity.</value> [MetaData (Description = "The text of the history entry tracked against the related entity.")] [MaxLength(2048)] public string HistoryText { get; set; } /// <summary> /// Date the record is created. /// </summary> /// <value>Date the record is created.</value> [MetaData (Description = "Date the record is created.")] public DateTime? CreatedDate { get; set; } /// <summary> /// Link to the Owner /// </summary> /// <value>Link to the Owner</value> [MetaData(Description = "Link to the Owner.")] public Owner Owner { get; set; } /// <summary> /// Foreign key for Owner /// </summary> [ForeignKey("Owner")] [JsonIgnore] [MetaData(Description = "Link to the Owner.")] public int? OwnerId { get; set; } /// <summary> /// Link to the Project /// </summary> /// <value>Link to the Project</value> [MetaData(Description = "Link to the Project.")] public Project Project { get; set; } /// <summary> /// Foreign key for Project /// </summary> [ForeignKey("Project")] [JsonIgnore] [MetaData(Description = "Link to the Project.")] public int? ProjectId { get; set; } /// <summary> /// Link to the Equipment /// </summary> /// <value>Link to the Equipment</value> [MetaData(Description = "Link to the Equipment.")] public Equipment Equipment { get; set; } /// <summary> /// Foreign key for Equipment /// </summary> [ForeignKey("Equipment")] [JsonIgnore] [MetaData(Description = "Link to the Equipment.")] public int? EquipmentId { get; set; } /// <summary> /// Link to the RentalRequest /// </summary> /// <value>Link to the Equipment</value> [MetaData(Description = "Link to the RentalRequest.")] public RentalRequest RentalRequest { get; set; } /// <summary> /// Foreign key for RentalRequest /// </summary> [ForeignKey("RentalRequest")] [JsonIgnore] [MetaData(Description = "Link to the RentalRequest.")] public int? RentalRequestId { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class History {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" HistoryText: ").Append(HistoryText).Append("\n"); sb.Append(" CreatedDate: ").Append(CreatedDate).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (obj is null) { return false; } if (ReferenceEquals(this, obj)) { return true; } return obj.GetType() == GetType() && Equals((History)obj); } /// <summary> /// Returns true if History instances are equal /// </summary> /// <param name="other">Instance of History to be compared</param> /// <returns>Boolean</returns> public bool Equals(History other) { if (other is null) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( Id == other.Id || Id.Equals(other.Id) ) && ( HistoryText == other.HistoryText || HistoryText != null && HistoryText.Equals(other.HistoryText) ) && ( CreatedDate == other.CreatedDate || CreatedDate != null && CreatedDate.Equals(other.CreatedDate) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks hash = hash * 59 + Id.GetHashCode(); if (HistoryText != null) { hash = hash * 59 + HistoryText.GetHashCode(); } if (CreatedDate != null) { hash = hash * 59 + CreatedDate.GetHashCode(); } return hash; } } #region Operators /// <summary> /// Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator ==(History left, History right) { return Equals(left, right); } /// <summary> /// Not Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator !=(History left, History right) { return !Equals(left, right); } #endregion Operators } }
// Copyright 2020 The Tilt Brush 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. using UnityEngine; namespace TiltBrush { public class BaseTool : MonoBehaviour { public enum ToolType { SketchSurface, Selection, ColorPicker, BrushPicker, BrushAndColorPicker, SketchOrigin, AutoGif, CanvasTool, TransformTool, StampTool, FreePaintTool, EraserTool, ScreenshotTool, DropperTool, SaveIconTool, ThreeDofViewingTool, MultiCamTool, TeleportTool, RepaintTool, RecolorTool, RebrushTool, SelectionTool, PinTool, EmptyTool, CameraPathTool, } public ToolType m_Type; public bool m_ShowTransformGizmo = false; [SerializeField] protected bool m_ExitOnAbortCommand = true; [SerializeField] protected bool m_ScalingSupported = false; public virtual float ButtonHoldDuration { get { return 1.0f; } } protected Transform m_Parent; protected SketchSurfacePanel m_SketchSurface; protected Vector3 m_ParentBaseScale; private Vector3 m_ParentScale; protected bool m_RequestExit; protected bool m_EatInput; protected bool m_AllowDrawing; protected bool m_ToolHidden; public bool IsEatingInput { get { return m_EatInput; } } public bool ExitRequested() { return m_RequestExit; } public bool ToolHidden() { return m_ToolHidden; } public void EatInput() { m_EatInput = true; } public void AllowDrawing(bool bAllow) { m_AllowDrawing = bAllow; } public virtual bool ShouldShowPointer() { return false; } virtual public void Init() { m_Parent = transform.parent; if (m_Parent != null) { m_ParentBaseScale = m_Parent.localScale; m_SketchSurface = m_Parent.GetComponent<SketchSurfacePanel>(); } } virtual protected void Awake() { // Some tools attach things to controllers (like the camera to the brush in SaveIconTool) // and these need to be swapped when the controllers are swapped. InputManager.OnSwapControllers += OnSwap; } virtual protected void OnDestroy() { InputManager.OnSwapControllers -= OnSwap; } virtual protected void OnSwap() { } virtual public void HideTool(bool bHide) { m_ToolHidden = bHide; } virtual public bool ShouldShowTouch() { return true; } virtual public bool CanShowPromosWhileInUse() { return true; } virtual public void EnableTool(bool bEnable) { m_RequestExit = false; gameObject.SetActive(bEnable); if (bEnable) { if (m_Parent != null) { m_ParentScale = m_Parent.localScale; m_Parent.localScale = m_ParentBaseScale; } PointerManager.m_Instance.RequestPointerRendering(ShouldShowPointer()); } else { if (m_Parent != null) { m_Parent.localScale = m_ParentScale; } m_EatInput = false; m_AllowDrawing = false; } } // Called only on frames that UpdateTool() has been called. // Guaranteed to be called after new poses have been received from OpenVR. virtual public void LateUpdateTool() {} virtual public void UpdateTool() { if (m_EatInput) { if (!InputManager.m_Instance.GetCommand(InputManager.SketchCommands.Activate)) { m_EatInput = false; } } if (m_ExitOnAbortCommand && InputManager.m_Instance.GetCommandDown(InputManager.SketchCommands.Abort)) { m_RequestExit = true; } } // Called to notify the tool that it should assign controller materials. public virtual void AssignControllerMaterials(InputManager.ControllerName controller) { } public bool ScalingSupported() { return m_ScalingSupported; } // Modifies the size by some amount determined by the implementation. // _usually_ this will have the effect that GetSize() changes by fAdjustAmount, // but not necessarily (see FreePaintTool). virtual public void UpdateSize(float fAdjustAmount) { } virtual public void Monitor() { } virtual public float GetSizeRatio( InputManager.ControllerName controller, VrInput input) { if (controller == InputManager.ControllerName.Brush) { return GetSize01(); } return 0.0f; } virtual public float GetSize() { return 0.0f; } // Returns a number in [0,1] virtual public float GetSize01() { return 0.0f; } virtual public void SetColor(Color rColor) { } virtual public void SetExtraText(string sExtra) { } virtual public void SetToolProgress(float fProgress) { } virtual public void BacksideActive(bool bActive) { } virtual public bool LockPointerToSketchSurface() { return true; } virtual public bool AllowsWidgetManipulation() { return true; } // Overridden by classes to set when tool sizing interaction should be disabled. virtual public bool CanAdjustSize() { return true; } // Overridden by classes to set when gaze and widget interaction should be disabled. virtual public bool InputBlocked() { return false; } virtual public bool AllowWorldTransformation() { return true; } // True if this tool can be used while a sketch is loading. virtual public bool AvailableDuringLoading() { return false; } // If this is true, the tool will tell the panels to hide. virtual public bool HidePanels() { return false; } // If this is true, the tool will disallow the pin cushion from spawning. virtual public bool BlockPinCushion() { return false; } // If this is true, the user can use the default tool toggle. virtual public bool AllowDefaultToolToggle() { return !PointerManager.m_Instance.IsMainPointerCreatingStroke(); } virtual public void EnableRenderer(bool enable) { gameObject.SetActive(enable); } protected bool PointInTriangle(ref Vector3 rPoint, ref Vector3 rA, ref Vector3 rB, ref Vector3 rC) { if (SameSide(ref rPoint, ref rA, ref rB, ref rC) && SameSide(ref rPoint, ref rB, ref rA, ref rC) && SameSide(ref rPoint, ref rC, ref rA, ref rB)) { return true; } return false; } protected bool SameSide(ref Vector3 rPoint1, ref Vector3 rPoint2, ref Vector3 rA, ref Vector3 rB) { Vector3 vCross1 = Vector3.Cross(rB - rA, rPoint1 - rA); Vector3 vCross2 = Vector3.Cross(rB - rA, rPoint2 - rA); return (Vector3.Dot(vCross1, vCross2) >= 0); } protected bool SegmentSphereIntersection(Vector3 vSegA, Vector3 vSegB, Vector3 vSphereCenter, float fSphereRadSq) { //check segment start to sphere Vector3 vStartToSphere = vSphereCenter - vSegA; if (vStartToSphere.sqrMagnitude < fSphereRadSq) { return true; } //check to see if our ray is pointing in the right direction Vector3 vSegment = vSegB - vSegA; Ray segmentRay = new Ray(vSegA, vSegment.normalized); float fDistToCenterProj = Vector3.Dot(vStartToSphere, segmentRay.direction); if (fDistToCenterProj < 0.0f) { return false; } //if the distance to our projection is within the segment bounds, we're on the right track if (fDistToCenterProj * fDistToCenterProj > vSegment.sqrMagnitude) { return false; } //see if this projected point is within the sphere Vector3 vProjectedPoint = segmentRay.GetPoint(fDistToCenterProj); Vector3 vToProjectedPoint = vProjectedPoint - vSphereCenter; return vToProjectedPoint.sqrMagnitude <= fSphereRadSq; } } } // namespace TiltBrush
// 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 Microsoft.Xunit.Performance; using System; using System.Linq; using System.Runtime.CompilerServices; using System.Reflection; using System.Collections.Generic; using Xunit; [assembly: OptimizeForBenchmarks] [assembly: MeasureInstructionsRetired] public static class ConstantArgsFloat { #if DEBUG public const int Iterations = 1; #else public const int Iterations = 100000; #endif // Floats feeding math operations. // // Inlining in Bench0xp should enable constant folding // Inlining in Bench0xn will not enable constant folding static float Five = 5; static float Ten = 10; static float Id(float x) { return x; } static float F00(float x) { return x * x; } static bool Bench00p() { float t = 10; float f = F00(t); return (f == 100); } static bool Bench00n() { float t = Ten; float f = F00(t); return (f == 100); } static bool Bench00p1() { float t = Id(10); float f = F00(t); return (f == 100); } static bool Bench00n1() { float t = Id(Ten); float f = F00(t); return (f == 100); } static bool Bench00p2() { float t = Id(10); float f = F00(Id(t)); return (f == 100); } static bool Bench00n2() { float t = Id(Ten); float f = F00(Id(t)); return (f == 100); } static bool Bench00p3() { float t = 10; float f = F00(Id(Id(t))); return (f == 100); } static bool Bench00n3() { float t = Ten; float f = F00(Id(Id(t))); return (f == 100); } static bool Bench00p4() { float t = 5; float f = F00(2 * t); return (f == 100); } static bool Bench00n4() { float t = Five; float f = F00(2 * t); return (f == 100); } static float F01(float x) { return 1000 / x; } static bool Bench01p() { float t = 10; float f = F01(t); return (f == 100); } static bool Bench01n() { float t = Ten; float f = F01(t); return (f == 100); } static float F02(float x) { return 20 * (x / 2); } static bool Bench02p() { float t = 10; float f = F02(t); return (f == 100); } static bool Bench02n() { float t = Ten; float f = F02(t); return (f == 100); } static float F03(float x) { return 91 + 1009 % x; } static bool Bench03p() { float t = 10; float f = F03(t); return (f == 100); } static bool Bench03n() { float t = Ten; float f = F03(t); return (f == 100); } static float F04(float x) { return 50 * (x % 4); } static bool Bench04p() { float t = 10; float f = F04(t); return (f == 100); } static bool Bench04n() { float t = Ten; float f = F04(t); return (f == 100); } static float F06(float x) { return -x + 110; } static bool Bench06p() { float t = 10; float f = F06(t); return (f == 100); } static bool Bench06n() { float t = Ten; float f = F06(t); return (f == 100); } // Floats feeding comparisons. // // Inlining in Bench1xp should enable branch optimization // Inlining in Bench1xn will not enable branch optimization static float F10(float x) { return x == 10 ? 100 : 0; } static bool Bench10p() { float t = 10; float f = F10(t); return (f == 100); } static bool Bench10n() { float t = Ten; float f = F10(t); return (f == 100); } static float F101(float x) { return x != 10 ? 0 : 100; } static bool Bench10p1() { float t = 10; float f = F101(t); return (f == 100); } static bool Bench10n1() { float t = Ten; float f = F101(t); return (f == 100); } static float F102(float x) { return x >= 10 ? 100 : 0; } static bool Bench10p2() { float t = 10; float f = F102(t); return (f == 100); } static bool Bench10n2() { float t = Ten; float f = F102(t); return (f == 100); } static float F103(float x) { return x <= 10 ? 100 : 0; } static bool Bench10p3() { float t = 10; float f = F103(t); return (f == 100); } static bool Bench10n3() { float t = Ten; float f = F102(t); return (f == 100); } static float F11(float x) { if (x == 10) { return 100; } else { return 0; } } static bool Bench11p() { float t = 10; float f = F11(t); return (f == 100); } static bool Bench11n() { float t = Ten; float f = F11(t); return (f == 100); } static float F111(float x) { if (x != 10) { return 0; } else { return 100; } } static bool Bench11p1() { float t = 10; float f = F111(t); return (f == 100); } static bool Bench11n1() { float t = Ten; float f = F111(t); return (f == 100); } static float F112(float x) { if (x > 10) { return 0; } else { return 100; } } static bool Bench11p2() { float t = 10; float f = F112(t); return (f == 100); } static bool Bench11n2() { float t = Ten; float f = F112(t); return (f == 100); } static float F113(float x) { if (x < 10) { return 0; } else { return 100; } } static bool Bench11p3() { float t = 10; float f = F113(t); return (f == 100); } static bool Bench11n3() { float t = Ten; float f = F113(t); return (f == 100); } // Ununsed (or effectively unused) parameters // // Simple callee analysis may overstate inline benefit static float F20(float x) { return 100; } static bool Bench20p() { float t = 10; float f = F20(t); return (f == 100); } static bool Bench20p1() { float t = Ten; float f = F20(t); return (f == 100); } static float F21(float x) { return -x + 100 + x; } static bool Bench21p() { float t = 10; float f = F21(t); return (f == 100); } static bool Bench21n() { float t = Ten; float f = F21(t); return (f == 100); } static float F211(float x) { return x - x + 100; } static bool Bench21p1() { float t = 10; float f = F211(t); return (f == 100); } static bool Bench21n1() { float t = Ten; float f = F211(t); return (f == 100); } static float F22(float x) { if (x > 0) { return 100; } return 100; } static bool Bench22p() { float t = 10; float f = F22(t); return (f == 100); } static bool Bench22p1() { float t = Ten; float f = F22(t); return (f == 100); } static float F23(float x) { if (x > 0) { return 90 + x; } return 100; } static bool Bench23p() { float t = 10; float f = F23(t); return (f == 100); } static bool Bench23n() { float t = Ten; float f = F23(t); return (f == 100); } // Multiple parameters static float F30(float x, float y) { return y * y; } static bool Bench30p() { float t = 10; float f = F30(t, t); return (f == 100); } static bool Bench30n() { float t = Ten; float f = F30(t, t); return (f == 100); } static bool Bench30p1() { float s = Ten; float t = 10; float f = F30(s, t); return (f == 100); } static bool Bench30n1() { float s = 10; float t = Ten; float f = F30(s, t); return (f == 100); } static bool Bench30p2() { float s = 10; float t = 10; float f = F30(s, t); return (f == 100); } static bool Bench30n2() { float s = Ten; float t = Ten; float f = F30(s, t); return (f == 100); } static bool Bench30p3() { float s = 10; float t = s; float f = F30(s, t); return (f == 100); } static bool Bench30n3() { float s = Ten; float t = s; float f = F30(s, t); return (f == 100); } static float F31(float x, float y, float z) { return z * z; } static bool Bench31p() { float t = 10; float f = F31(t, t, t); return (f == 100); } static bool Bench31n() { float t = Ten; float f = F31(t, t, t); return (f == 100); } static bool Bench31p1() { float r = Ten; float s = Ten; float t = 10; float f = F31(r, s, t); return (f == 100); } static bool Bench31n1() { float r = 10; float s = 10; float t = Ten; float f = F31(r, s, t); return (f == 100); } static bool Bench31p2() { float r = 10; float s = 10; float t = 10; float f = F31(r, s, t); return (f == 100); } static bool Bench31n2() { float r = Ten; float s = Ten; float t = Ten; float f = F31(r, s, t); return (f == 100); } static bool Bench31p3() { float r = 10; float s = r; float t = s; float f = F31(r, s, t); return (f == 100); } static bool Bench31n3() { float r = Ten; float s = r; float t = s; float f = F31(r, s, t); return (f == 100); } // Two args, both used static float F40(float x, float y) { return x * x + y * y - 100; } static bool Bench40p() { float t = 10; float f = F40(t, t); return (f == 100); } static bool Bench40n() { float t = Ten; float f = F40(t, t); return (f == 100); } static bool Bench40p1() { float s = Ten; float t = 10; float f = F40(s, t); return (f == 100); } static bool Bench40p2() { float s = 10; float t = Ten; float f = F40(s, t); return (f == 100); } static float F41(float x, float y) { return x * y; } static bool Bench41p() { float t = 10; float f = F41(t, t); return (f == 100); } static bool Bench41n() { float t = Ten; float f = F41(t, t); return (f == 100); } static bool Bench41p1() { float s = 10; float t = Ten; float f = F41(s, t); return (f == 100); } static bool Bench41p2() { float s = Ten; float t = 10; float f = F41(s, t); return (f == 100); } private static IEnumerable<object[]> MakeArgs(params string[] args) { return args.Select(arg => new object[] { arg }); } public static IEnumerable<object[]> TestFuncs = MakeArgs( "Bench00p", "Bench00n", "Bench00p1", "Bench00n1", "Bench00p2", "Bench00n2", "Bench00p3", "Bench00n3", "Bench00p4", "Bench00n4", "Bench01p", "Bench01n", "Bench02p", "Bench02n", "Bench03p", "Bench03n", "Bench04p", "Bench04n", "Bench06p", "Bench06n", "Bench10p", "Bench10n", "Bench10p1", "Bench10n1", "Bench10p2", "Bench10n2", "Bench10p3", "Bench10n3", "Bench11p", "Bench11n", "Bench11p1", "Bench11n1", "Bench11p2", "Bench11n2", "Bench11p3", "Bench11n3", "Bench20p", "Bench20p1", "Bench21p", "Bench21n", "Bench21p1", "Bench21n1", "Bench22p", "Bench22p1", "Bench23p", "Bench23n", "Bench30p", "Bench30n", "Bench30p1", "Bench30n1", "Bench30p2", "Bench30n2", "Bench30p3", "Bench30n3", "Bench31p", "Bench31n", "Bench31p1", "Bench31n1", "Bench31p2", "Bench31n2", "Bench31p3", "Bench31n3", "Bench40p", "Bench40n", "Bench40p1", "Bench40p2", "Bench41p", "Bench41n", "Bench41p1", "Bench41p2" ); static Func<bool> LookupFunc(object o) { TypeInfo t = typeof(ConstantArgsFloat).GetTypeInfo(); MethodInfo m = t.GetDeclaredMethod((string) o); return m.CreateDelegate(typeof(Func<bool>)) as Func<bool>; } [Benchmark] [MemberData(nameof(TestFuncs))] public static void Test(object funcName) { Func<bool> f = LookupFunc(funcName); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Iterations; i++) { f(); } } } } static bool TestBase(Func<bool> f) { bool result = true; for (int i = 0; i < Iterations; i++) { result &= f(); } return result; } public static int Main() { bool result = true; foreach(object[] o in TestFuncs) { string funcName = (string) o[0]; Func<bool> func = LookupFunc(funcName); bool thisResult = TestBase(func); if (!thisResult) { Console.WriteLine("{0} failed", funcName); } result &= thisResult; } return (result ? 100 : -1); } }
using System; using System.Collections.Generic; using System.Text; using gView.Framework.Carto; using gView.Framework.Geometry; using gView.Framework.Symbology; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.IO; namespace gView.Plugins.Editor { class EditSketch : IGraphicElement2, IGraphicsElementDesigning { private IGeometry _geometry = null; private ISymbol _symbol = null; private int _actPartNr = 0; public EditSketch(IGeometry geometry) { _geometry = geometry; //geometry.Clone() as IGeometry; if (geometry is IPoint || geometry is IMultiPoint) { _symbol = new SimplePointSymbol(); ((SimplePointSymbol)_symbol).Size = 14; ((SimplePointSymbol)_symbol).Marker = SimplePointSymbol.MarkerType.Star; ((SimplePointSymbol)_symbol).Color = Color.Yellow; } else if (geometry is IPolyline) { _symbol = new SimpleLineSymbol(); ((SimpleLineSymbol)_symbol).Color = Color.Yellow; ((SimpleLineSymbol)_symbol).Width = 2.0f; ((SimpleLineSymbol)_symbol).PenDashStyle = DashStyle.Solid; } else if (geometry is IPolygon) { SimpleLineSymbol outlineSymbol = new SimpleLineSymbol(); outlineSymbol.Color = Color.Orange; outlineSymbol.Width = 2.0f; outlineSymbol.PenDashStyle = DashStyle.Solid; _symbol = new SimpleFillSymbol(); ((SimpleFillSymbol)_symbol).Color = Color.FromArgb(125, Color.Yellow); ((SimpleFillSymbol)_symbol).OutlineSymbol = outlineSymbol; } } public void AddPoint(IPoint point) { if (point == null) return; if (_geometry is IPoint && _actPartNr==0) { ((IPoint)_geometry).X = point.X; ((IPoint)_geometry).Y = point.Y; ((IPoint)_geometry).Z = point.Z; } else if (_geometry is IMultiPoint) { IMultiPoint mPoint = (IMultiPoint)_geometry; mPoint.AddPoint(point); } else if (_geometry is IPolyline) { IPolyline pLine = (IPolyline)_geometry; if (_actPartNr >= pLine.PathCount) { gView.Framework.Geometry.Path path = new gView.Framework.Geometry.Path(); path.AddPoint(point); pLine.AddPath(path); _actPartNr = pLine.PathCount - 1; } else { pLine[_actPartNr].AddPoint(point); } } else if (_geometry is IPolygon) { IPolygon poly = (IPolygon)_geometry; if (_actPartNr >= poly.RingCount) { Ring ring = new Ring(); ring.AddPoint(point); poly.AddRing(ring); _actPartNr = poly.RingCount - 1; } else { poly[_actPartNr].AddPoint(point); } } } public geometryType GeometryType { get { if (_geometry is IPoint) return geometryType.Point; else if (_geometry is IMultiPoint) return geometryType.Multipoint; else if (_geometry is IPolyline) return geometryType.Polyline; else if (_geometry is IPolygon) return geometryType.Polygon; return geometryType.Unknown; } } public IPointCollection Part { get { if (_geometry is Polyline) { IPolyline pLine = (IPolyline)_geometry; if (pLine.PathCount > _actPartNr) { return pLine[_actPartNr]; } } else if (_geometry is IPolygon) { IPolygon poly = (IPolygon)_geometry; if (poly.RingCount > _actPartNr) { return poly[_actPartNr]; } } return null; } } public void ClosePart() { if (Part != null && Part.PointCount > 2) Part.AddPoint(Part[0]); } public int PartCount { get { if (_geometry is Polyline) { IPolyline pLine = (IPolyline)_geometry; return pLine.PathCount; } else if (_geometry is IPolygon) { IPolygon poly = (IPolygon)_geometry; return poly.RingCount; } return 1; } } public int ActivePartNumber { get { return _actPartNr; } set { if (value < 0) return; if (_geometry is Polyline) { IPolyline pLine = (IPolyline)_geometry; if (pLine.PathCount >= value) { _actPartNr = value; } } else if (_geometry is IPolygon) { IPolygon poly = (IPolygon)_geometry; if (poly.RingCount >= value) { _actPartNr = value; } } } } #region IGraphicElement2 Member public string Name { get { return "Editor.Sketch"; } } public System.Drawing.Image Icon { get { return null; } } public gView.Framework.Symbology.ISymbol Symbol { get { return _symbol; } set { _symbol = value; } } public void DrawGrabbers(IDisplay display) { if (_geometry == null || display == null) return; IPointCollection pColl=gView.Framework.SpatialAlgorithms.Algorithm.GeometryPoints(_geometry, false); if (pColl == null || pColl.PointCount == 0) return; SimplePointSymbol pointSymbol = new SimplePointSymbol(); pointSymbol.Color = System.Drawing.Color.White; pointSymbol.OutlineColor = System.Drawing.Color.Black; pointSymbol.OutlineWidth = 1; pointSymbol.Marker = SimplePointSymbol.MarkerType.Square; pointSymbol.Size = 5; for (int i = 0; i < pColl.PointCount; i++) { IPoint point = pColl[i]; if (point == null) continue; display.Draw(pointSymbol, point); } } public gView.Framework.Geometry.IGeometry Geometry { get { return _geometry; } } #endregion #region IGraphicElement Member public void Draw(IDisplay display) { if (display != null && _symbol != null && _geometry != null) display.Draw(_symbol, _geometry); } #endregion #region IGraphicsElementScaling Member public void Scale(double scaleX, double scaleY) { } public void ScaleX(double scale) { } public void ScaleY(double scale) { } #endregion #region IGraphicsElementRotation Member public double Rotation { get { return 0.0; } set { } } #endregion #region IIGraphicsElementTranslation Member public void Translation(double x, double y) { } #endregion #region IGraphicsElementDesigning Member public IGraphicElement2 Ghost { get { return null; } } public HitPositions HitTest(IDisplay display, gView.Framework.Geometry.IPoint point) { if (_geometry == null) return null; IPointCollection pColl = gView.Framework.SpatialAlgorithms.Algorithm.GeometryPoints(_geometry, true); if (pColl == null || pColl.PointCount == 0) return null; double tol = 5.0 * display.mapScale / (display.dpi / 0.0254); // [m] if (display.SpatialReference != null && display.SpatialReference.SpatialParameters.IsGeographic) { tol = 180.0 * tol / Math.PI / 6370000.0; } for (int i = 0; i < pColl.PointCount; i++) { IPoint p = pColl[i]; if (p == null) continue; if (gView.Framework.SpatialAlgorithms.Algorithm.PointDistance(p, point) < tol) { return new HitPosition(HitPosition.VertexCursor, i); } } List<IPath> paths = gView.Framework.SpatialAlgorithms.Algorithm.GeometryPaths(_geometry); if (paths == null || paths.Count == 0) return null; Polyline pLine = new Polyline(paths); if (gView.Framework.SpatialAlgorithms.Algorithm.IntersectBox(pLine, new Envelope( point.X - tol / 2, point.Y - tol / 2, point.X + tol / 2, point.Y + tol / 2))) { return new HitPosition(System.Windows.Forms.Cursors.Default, -1); } return null; } public void Design(IDisplay display, HitPositions hit, double dx, double dy) { if (_geometry == null) return; IPointCollection pColl = gView.Framework.SpatialAlgorithms.Algorithm.GeometryPoints(_geometry, false); if (pColl == null || pColl.PointCount == 0) return; if (hit.HitID>=0 && hit.HitID < pColl.PointCount) { pColl[hit.HitID].X = dx; pColl[hit.HitID].Y = dy; } } public bool TrySelect(IDisplay display, gView.Framework.Geometry.IEnvelope envelope) { return false; } public bool TrySelect(IDisplay display, gView.Framework.Geometry.IPoint point) { return false; } public bool RemoveVertex(IDisplay display, int index) { Vertices(_geometry, index); // "leere" Parts entfernen! if (_geometry is Polyline) { IPolyline pLine = (IPolyline)_geometry; for (int i = 0; i < pLine.PathCount; i++) { if (pLine[i] == null) continue; if (pLine[i].PointCount == 0) { pLine.RemovePath(i); i = -1; } } } else if (_geometry is IPolygon) { IPolygon poly = (IPolygon)_geometry; for (int i = 0; i < poly.RingCount; i++) { if (poly[i] == null) continue; if (poly[i].PointCount == 0) { poly.RemoveRing(i); i = -1; } } } return true; } public bool AddVertex(IDisplay display, gView.Framework.Geometry.IPoint point) { double distance; IPoint snapped = gView.Framework.SpatialAlgorithms.Algorithm.NearestPointToPath( _geometry, point, out distance, true); return snapped != null; } #endregion #region Helper Classes internal class HitPosition : HitPositions { private System.Windows.Forms.Cursor _cursor; private int _id; public HitPosition(System.Windows.Forms.Cursor cursor, int id) { _cursor = cursor; _id = id; } #region HitPositions Member public object Cursor { get { return _cursor; } } public int HitID { get { return _id; } } #endregion static private Cursor _vertexCursor = null; static internal Cursor VertexCursor { get { if (_vertexCursor == null) { MemoryStream ms = new MemoryStream(); ms.Write(global::gView.Plugins.Editor.Properties.Resources.Vertex, 0, global::gView.Plugins.Editor.Properties.Resources.Vertex.Length); ms.Position = 0; _vertexCursor = new Cursor(ms); } return _vertexCursor; } } } #endregion #region Helper private IPointCollection Vertices(IGeometry geometry, int removeAt) { IPointCollection pColl = new PointCollection(); Vertices(geometry as IGeometry, pColl, removeAt); return pColl; } private void Vertices(IGeometry geometry, IPointCollection pColl, int removeAt) { if (geometry == null || pColl == null) return; if (geometry is IPoint) { Vertices(geometry as IPoint, pColl, removeAt); } else if (geometry is IMultiPoint) { Vertices(geometry as IPointCollection, pColl, removeAt); } else if (geometry is IPolyline) { for (int i = 0; i < ((IPolyline)geometry).PathCount; i++) { Vertices(((IPolyline)geometry)[i] as IPointCollection, pColl, removeAt); } } else if (geometry is IPolygon) { for (int i = 0; i < ((IPolygon)geometry).RingCount; i++) { Vertices(((IPolygon)geometry)[i] as IPointCollection, pColl, removeAt); } } else if (geometry is IAggregateGeometry) { for (int i = 0; i < ((IAggregateGeometry)geometry).GeometryCount; i++) { Vertices(((IAggregateGeometry)geometry)[i] as IGeometry, pColl, removeAt); } } } private void Vertices(IPoint p, IPointCollection vertices, int removeAt) { if (p == null || vertices == null) return; vertices.AddPoint(p); } private void Vertices(IPointCollection pColl, IPointCollection vertices, int removeAt) { if (pColl == null || vertices == null) return; for (int i = 0; i < pColl.PointCount; i++) { if (vertices.PointCount == removeAt) pColl.RemovePoint(i); vertices.AddPoint(pColl[i]); } } #endregion public override bool Equals(object obj) { if (!(obj is EditSketch)) return false; if (this == obj) return true; EditSketch sketch = (EditSketch)obj; if (_geometry!=null && !_geometry.Equals(sketch._geometry)) return false; if (_geometry == null && sketch._geometry != null) return false; if (_symbol != null && sketch._symbol != null && !_symbol.GetType().Equals(sketch._symbol.GetType())) return false; return true; } } }
using Lucene.Net.Support; using System; using System.Collections.Generic; using System.Text; /* * dk.brics.automaton * * Copyright (c) 2001-2009 Anders Moeller * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * this SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ namespace Lucene.Net.Util.Automaton { /// <summary> /// Construction of basic automata. /// <para/> /// @lucene.experimental /// </summary> public sealed class BasicAutomata { private BasicAutomata() { } /// <summary> /// Returns a new (deterministic) automaton with the empty language. /// </summary> public static Automaton MakeEmpty() { Automaton a = new Automaton(); State s = new State(); a.initial = s; a.deterministic = true; return a; } /// <summary> /// Returns a new (deterministic) automaton that accepts only the empty string. /// </summary> public static Automaton MakeEmptyString() { Automaton a = new Automaton(); a.singleton = ""; a.deterministic = true; return a; } /// <summary> /// Returns a new (deterministic) automaton that accepts all strings. /// </summary> public static Automaton MakeAnyString() { Automaton a = new Automaton(); State s = new State(); a.initial = s; s.accept = true; s.AddTransition(new Transition(Character.MIN_CODE_POINT, Character.MAX_CODE_POINT, s)); a.deterministic = true; return a; } /// <summary> /// Returns a new (deterministic) automaton that accepts any single codepoint. /// </summary> public static Automaton MakeAnyChar() { return MakeCharRange(Character.MIN_CODE_POINT, Character.MAX_CODE_POINT); } /// <summary> /// Returns a new (deterministic) automaton that accepts a single codepoint of /// the given value. /// </summary> public static Automaton MakeChar(int c) { Automaton a = new Automaton(); a.singleton = new string(Character.ToChars(c)); a.deterministic = true; return a; } /// <summary> /// Returns a new (deterministic) automaton that accepts a single codepoint whose /// value is in the given interval (including both end points). /// </summary> public static Automaton MakeCharRange(int min, int max) { if (min == max) { return MakeChar(min); } Automaton a = new Automaton(); State s1 = new State(); State s2 = new State(); a.initial = s1; s2.accept = true; if (min <= max) { s1.AddTransition(new Transition(min, max, s2)); } a.deterministic = true; return a; } /// <summary> /// Constructs sub-automaton corresponding to decimal numbers of length /// <c>x.Substring(n).Length</c>. /// </summary> private static State AnyOfRightLength(string x, int n) { State s = new State(); if (x.Length == n) { s.Accept = true; } else { s.AddTransition(new Transition('0', '9', AnyOfRightLength(x, n + 1))); } return s; } /// <summary> /// Constructs sub-automaton corresponding to decimal numbers of value at least /// <c>x.Substring(n)</c> and length <c>x.Substring(n).Length</c>. /// </summary> private static State AtLeast(string x, int n, ICollection<State> initials, bool zeros) { State s = new State(); if (x.Length == n) { s.Accept = true; } else { if (zeros) { initials.Add(s); } char c = x[n]; s.AddTransition(new Transition(c, AtLeast(x, n + 1, initials, zeros && c == '0'))); if (c < '9') { s.AddTransition(new Transition((char)(c + 1), '9', AnyOfRightLength(x, n + 1))); } } return s; } /// <summary> /// Constructs sub-automaton corresponding to decimal numbers of value at most /// <c>x.Substring(n)</c> and length <c>x.Substring(n).Length</c>. /// </summary> private static State AtMost(string x, int n) { State s = new State(); if (x.Length == n) { s.Accept = true; } else { char c = x[n]; s.AddTransition(new Transition(c, AtMost(x, (char)n + 1))); if (c > '0') { s.AddTransition(new Transition('0', (char)(c - 1), AnyOfRightLength(x, n + 1))); } } return s; } /// <summary> /// Constructs sub-automaton corresponding to decimal numbers of value between /// <c>x.Substring(n)</c> and <c>y.Substring(n)</c> and of length <c>x.Substring(n).Length</c> /// (which must be equal to <c>y.Substring(n).Length</c>). /// </summary> private static State Between(string x, string y, int n, ICollection<State> initials, bool zeros) { State s = new State(); if (x.Length == n) { s.Accept = true; } else { if (zeros) { initials.Add(s); } char cx = x[n]; char cy = y[n]; if (cx == cy) { s.AddTransition(new Transition(cx, Between(x, y, n + 1, initials, zeros && cx == '0'))); } else // cx<cy { s.AddTransition(new Transition(cx, AtLeast(x, n + 1, initials, zeros && cx == '0'))); s.AddTransition(new Transition(cy, AtMost(y, n + 1))); if (cx + 1 < cy) { s.AddTransition(new Transition((char)(cx + 1), (char)(cy - 1), AnyOfRightLength(x, n + 1))); } } } return s; } /// <summary> /// Returns a new automaton that accepts strings representing decimal /// non-negative integers in the given interval. /// </summary> /// <param name="min"> Minimal value of interval. </param> /// <param name="max"> Maximal value of interval (both end points are included in the /// interval). </param> /// <param name="digits"> If &gt; 0, use fixed number of digits (strings must be prefixed /// by 0's to obtain the right length) - otherwise, the number of /// digits is not fixed. </param> /// <exception cref="ArgumentException"> If min &gt; max or if numbers in the /// interval cannot be expressed with the given fixed number of /// digits. </exception> public static Automaton MakeInterval(int min, int max, int digits) { Automaton a = new Automaton(); string x = Convert.ToString(min); string y = Convert.ToString(max); if (min > max || (digits > 0 && y.Length > digits)) { throw new System.ArgumentException(); } int d; if (digits > 0) { d = digits; } else { d = y.Length; } StringBuilder bx = new StringBuilder(); for (int i = x.Length; i < d; i++) { bx.Append('0'); } bx.Append(x); x = bx.ToString(); StringBuilder by = new StringBuilder(); for (int i = y.Length; i < d; i++) { by.Append('0'); } by.Append(y); y = by.ToString(); ICollection<State> initials = new List<State>(); a.initial = Between(x, y, 0, initials, digits <= 0); if (digits <= 0) { List<StatePair> pairs = new List<StatePair>(); foreach (State p in initials) { if (a.initial != p) { pairs.Add(new StatePair(a.initial, p)); } } BasicOperations.AddEpsilons(a, pairs); a.initial.AddTransition(new Transition('0', a.initial)); a.deterministic = false; } else { a.deterministic = true; } a.CheckMinimizeAlways(); return a; } /// <summary> /// Returns a new (deterministic) automaton that accepts the single given /// string. /// </summary> public static Automaton MakeString(string s) { Automaton a = new Automaton(); a.singleton = s; a.deterministic = true; return a; } public static Automaton MakeString(int[] word, int offset, int length) { Automaton a = new Automaton(); a.IsDeterministic = true; State s = new State(); a.initial = s; for (int i = offset; i < offset + length; i++) { State s2 = new State(); s.AddTransition(new Transition(word[i], s2)); s = s2; } s.accept = true; return a; } /// <summary> /// Returns a new (deterministic and minimal) automaton that accepts the union /// of the given collection of <see cref="BytesRef"/>s representing UTF-8 encoded /// strings. /// </summary> /// <param name="utf8Strings"> /// The input strings, UTF-8 encoded. The collection must be in sorted /// order. /// </param> /// <returns> An <see cref="Automaton"/> accepting all input strings. The resulting /// automaton is codepoint based (full unicode codepoints on /// transitions). </returns> public static Automaton MakeStringUnion(ICollection<BytesRef> utf8Strings) { if (utf8Strings.Count == 0) { return MakeEmpty(); } else { return DaciukMihovAutomatonBuilder.Build(utf8Strings); } } } }
#region License /* ********************************************************************************** * Copyright (c) Roman Ivantsov * This source code is subject to terms and conditions of the MIT License * for Irony. A copy of the license can be found in the License.txt file * at the root of this distribution. * By using this source code in any fashion, you are agreeing to be bound by the terms of the * MIT License. * You must not remove this notice from this software. * **********************************************************************************/ #endregion using System; using System.Collections.Generic; using System.Text; using System.Globalization; namespace Irony.Parsing { #region notes //Identifier terminal. Matches alpha-numeric sequences that usually represent identifiers and keywords. // c#: @ prefix signals to not interpret as a keyword; allows \u escapes // #endregion [Flags] public enum IdOptions : short { None = 0, AllowsEscapes = 0x01, CanStartWithEscape = 0x03, //bit 2 with bit 1 together IsNotKeyword = 0x10, NameIncludesPrefix = 0x20, } public enum CaseRestriction { None, FirstUpper, FirstLower, AllUpper, AllLower } public class UnicodeCategoryList : List<UnicodeCategory> { } public class IdentifierTerminal : CompoundTerminalBase { //Id flags for internal use internal enum IdFlagsInternal : short { HasEscapes = 0x100, } //Note that extraChars, extraFirstChars are used to form AllFirstChars and AllChars fields, which in turn // are used in QuickParse. Only if QuickParse fails, the process switches to full version with checking every // char's category #region constructors and initialization public IdentifierTerminal(string name) : this(name, IdOptions.None) { } public IdentifierTerminal(string name, IdOptions flags) : this(name, "_", "_") { Options = flags; } public IdentifierTerminal(string name, string extraChars, string extraFirstChars): base(name) { AllFirstChars = Strings.AllLatinLetters + extraFirstChars; AllChars = Strings.AllLatinLetters + Strings.DecimalDigits + extraChars; } public void AddPrefix(string prefix, IdOptions flags) { base.AddPrefixFlag(prefix, (short)flags); } #endregion #region properties: AllChars, AllFirstChars //Used in QuickParse only! public string AllChars; public string AllFirstChars; public TokenEditorInfo KeywordEditorInfo = new TokenEditorInfo(TokenType.Keyword, TokenColor.Keyword, TokenTriggers.None); public IdOptions Options; //flags for the case when there are no prefixes public CaseRestriction CaseRestriction; public readonly UnicodeCategoryList StartCharCategories = new UnicodeCategoryList(); //categories of first char public readonly UnicodeCategoryList CharCategories = new UnicodeCategoryList(); //categories of all other chars public readonly UnicodeCategoryList CharsToRemoveCategories = new UnicodeCategoryList(); //categories of chars to remove from final id, usually formatting category #endregion #region overrides public override void Init(GrammarData grammarData) { base.Init(grammarData); AllChars = AllChars?? String.Empty; AllFirstChars = AllFirstChars ?? string.Empty; //Adjust case restriction. We adjust only first chars; if first char is ok, we will scan the rest without restriction // and then check casing for entire identifier switch(CaseRestriction) { case CaseRestriction.AllLower: case CaseRestriction.FirstLower: AllFirstChars = AllFirstChars.ToLower(); break; case CaseRestriction.AllUpper: case CaseRestriction.FirstUpper: AllFirstChars = AllFirstChars.ToUpper(); break; } //if there are "first" chars defined by categories, add the terminal to FallbackTerminals if (this.StartCharCategories.Count > 0) Grammar.FallbackTerminals.Add(this); if (this.EditorInfo == null) this.EditorInfo = new TokenEditorInfo(TokenType.Identifier, TokenColor.Identifier, TokenTriggers.None); if (this.AstNodeType == null && this.AstNodeCreator == null && grammarData.Grammar.FlagIsSet(LanguageFlags.CreateAst)) this.AstNodeType = typeof(Irony.Ast.IdentifierNode); } //TODO: put into account non-Ascii aplhabets specified by means of Unicode categories! public override IList<string> GetFirsts() { StringList list = new StringList(); list.AddRange(Prefixes); if (string.IsNullOrEmpty(AllFirstChars)) return list; char[] chars = AllFirstChars.ToCharArray(); foreach (char ch in chars) list.Add(ch.ToString()); if ((Options & IdOptions.CanStartWithEscape) != 0) list.Add(this.EscapeChar.ToString()); return list; } private void AdjustCasing() { switch(CaseRestriction) { case CaseRestriction.None: break; case CaseRestriction.FirstLower: AllFirstChars = AllFirstChars.ToLower(); break; case CaseRestriction.FirstUpper: AllFirstChars = AllFirstChars.ToUpper(); break; case CaseRestriction.AllLower: AllFirstChars = AllFirstChars.ToLower(); AllChars = AllChars.ToLower(); break; case CaseRestriction.AllUpper: AllFirstChars = AllFirstChars.ToUpper(); AllChars = AllChars.ToUpper(); break; }//switch }//method protected override void InitDetails(ParsingContext context, CompoundTokenDetails details) { base.InitDetails(context, details); details.Flags = (short)Options; } //Override to assign IsKeyword flag to keyword tokens protected override Token CreateToken(ParsingContext context, ISourceStream source, CompoundTokenDetails details) { Token token = base.CreateToken(context, source, details); token.Symbol = SymbolTable.Symbols.TextToSymbol(token.ValueString); if (details.IsSet((short)IdOptions.IsNotKeyword)) return token; //check if it is keyword CheckReservedWord(token); return token; } private void CheckReservedWord(Token token) { KeyTerm keyTerm; if (Grammar.KeyTerms.TryGetValue(token.Text, out keyTerm)) { token.KeyTerm = keyTerm; //if it is reserved word, then overwrite terminal if (keyTerm.FlagIsSet(TermFlags.IsReservedWord)) token.SetTerminal(keyTerm); } } protected override Token QuickParse(ParsingContext context, ISourceStream source) { if (AllFirstChars.IndexOf(source.PreviewChar) < 0) return null; source.PreviewPosition++; while (AllChars.IndexOf(source.PreviewChar) >= 0 && !source.EOF()) source.PreviewPosition++; //if it is not a terminator then cancel; we need to go through full algorithm if (GrammarData.WhitespaceAndDelimiters.IndexOf(source.PreviewChar) < 0) return null; var token = source.CreateToken(this.OutputTerminal); if(CaseRestriction != CaseRestriction.None && !CheckCaseRestriction(token.ValueString)) return null; //!!! Do not convert to common case (all-lower) for case-insensitive grammar. Let identifiers remain as is, // it is responsibility of interpreter to provide case-insensitive read/write operations for identifiers // if (!this.GrammarData.Grammar.CaseSensitive) // token.Value = token.Text.ToLower(CultureInfo.InvariantCulture); CheckReservedWord(token); token.Symbol = SymbolTable.Symbols.TextToSymbol(token.ValueString); return token; } protected override bool ReadBody(ISourceStream source, CompoundTokenDetails details) { int start = source.PreviewPosition; bool allowEscapes = details.IsSet((short)IdOptions.AllowsEscapes); CharList outputChars = new CharList(); while (!source.EOF()) { char current = source.PreviewChar; if (GrammarData.WhitespaceAndDelimiters.IndexOf(current) >= 0) break; if (allowEscapes && current == this.EscapeChar) { current = ReadUnicodeEscape(source, details); //We need to back off the position. ReadUnicodeEscape sets the position to symbol right after escape digits. //This is the char that we should process in next iteration, so we must backup one char, to pretend the escaped // char is at position of last digit of escape sequence. source.PreviewPosition--; if (details.Error != null) return false; } //Check if current character is OK if (!CharOk(current, source.PreviewPosition == start)) break; //Check if we need to skip this char UnicodeCategory currCat = char.GetUnicodeCategory(current); //I know, it suxx, we do it twice, fix it later if (!this.CharsToRemoveCategories.Contains(currCat)) outputChars.Add(current); //add it to output (identifier) source.PreviewPosition++; }//while if (outputChars.Count == 0) return false; //Convert collected chars to string details.Body = new string(outputChars.ToArray()); if (!CheckCaseRestriction(details.Body)) return false; return !string.IsNullOrEmpty(details.Body); } private bool CharOk(char ch, bool first) { //first check char lists, then categories string all = first? AllFirstChars : AllChars; if(all.IndexOf(ch) >= 0) return true; //check categories UnicodeCategory chCat = char.GetUnicodeCategory(ch); UnicodeCategoryList catList = first ? StartCharCategories : CharCategories; if (catList.Contains(chCat)) return true; return false; } private bool CheckCaseRestriction(string body) { switch(CaseRestriction) { case CaseRestriction.FirstLower: return Char.IsLower(body, 0); case CaseRestriction.FirstUpper: return Char.IsUpper(body, 0); case CaseRestriction.AllLower: return body.ToLower() == body; case CaseRestriction.AllUpper: return body.ToUpper() == body; default : return true; } }//method private char ReadUnicodeEscape(ISourceStream source, CompoundTokenDetails details) { //Position is currently at "\" symbol source.PreviewPosition++; //move to U/u char int len; switch (source.PreviewChar) { case 'u': len = 4; break; case 'U': len = 8; break; default: details.Error = Resources.ErrInvEscSymbol; // "Invalid escape symbol, expected 'u' or 'U' only." return '\0'; } if (source.PreviewPosition + len > source.Text.Length) { details.Error = Resources.ErrInvEscSeq; // "Invalid escape sequence"; return '\0'; } source.PreviewPosition++; //move to the first digit string digits = source.Text.Substring(source.PreviewPosition, len); char result = (char)Convert.ToUInt32(digits, 16); source.PreviewPosition += len; details.Flags |= (int) IdFlagsInternal.HasEscapes; return result; } protected override bool ConvertValue(CompoundTokenDetails details) { if (details.IsSet((short)IdOptions.NameIncludesPrefix)) details.Value = details.Prefix + details.Body; else details.Value = details.Body; return true; } #endregion }//class } //namespace
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Reflection; using System.Reflection.Metadata; using System.Threading; using Internal.TypeSystem; namespace Internal.TypeSystem.Ecma { public sealed class EcmaMethod : MethodDesc, EcmaModule.IEntityHandleObject { private static class MethodFlags { public const int BasicMetadataCache = 0x0001; public const int Virtual = 0x0002; public const int NewSlot = 0x0004; public const int Abstract = 0x0008; public const int Final = 0x0010; public const int NoInlining = 0x0020; public const int AggressiveInlining = 0x0040; public const int AttributeMetadataCache = 0x0100; public const int Intrinsic = 0x0200; }; private EcmaType _type; private MethodDefinitionHandle _handle; // Cached values private ThreadSafeFlags _methodFlags; private MethodSignature _signature; private string _name; private TypeDesc[] _genericParameters; // TODO: Optional field? internal EcmaMethod(EcmaType type, MethodDefinitionHandle handle) { _type = type; _handle = handle; #if DEBUG // Initialize name eagerly in debug builds for convenience this.ToString(); #endif } EntityHandle EcmaModule.IEntityHandleObject.Handle { get { return _handle; } } public override TypeSystemContext Context { get { return _type.Module.Context; } } public override TypeDesc OwningType { get { return _type; } } private MethodSignature InitializeSignature() { var metadataReader = MetadataReader; BlobReader signatureReader = metadataReader.GetBlobReader(metadataReader.GetMethodDefinition(_handle).Signature); EcmaSignatureParser parser = new EcmaSignatureParser(Module, signatureReader); var signature = parser.ParseMethodSignature(); return (_signature = signature); } public override MethodSignature Signature { get { if (_signature == null) return InitializeSignature(); return _signature; } } public EcmaModule Module { get { return _type.EcmaModule; } } public MetadataReader MetadataReader { get { return _type.MetadataReader; } } public MethodDefinitionHandle Handle { get { return _handle; } } [MethodImpl(MethodImplOptions.NoInlining)] private int InitializeMethodFlags(int mask) { int flags = 0; if ((mask & MethodFlags.BasicMetadataCache) != 0) { var methodAttributes = Attributes; var methodImplAttributes = ImplAttributes; if ((methodAttributes & MethodAttributes.Virtual) != 0) flags |= MethodFlags.Virtual; if ((methodAttributes & MethodAttributes.NewSlot) != 0) flags |= MethodFlags.NewSlot; if ((methodAttributes & MethodAttributes.Abstract) != 0) flags |= MethodFlags.Abstract; if ((methodAttributes & MethodAttributes.Final) != 0) flags |= MethodFlags.Final; if ((methodImplAttributes & MethodImplAttributes.NoInlining) != 0) flags |= MethodFlags.NoInlining; if ((methodImplAttributes & MethodImplAttributes.AggressiveInlining) != 0) flags |= MethodFlags.AggressiveInlining; flags |= MethodFlags.BasicMetadataCache; } // Fetching custom attribute based properties is more expensive, so keep that under // a separate cache that might not be accessed very frequently. if ((mask & MethodFlags.AttributeMetadataCache) != 0) { var metadataReader = this.MetadataReader; var methodDefinition = metadataReader.GetMethodDefinition(_handle); foreach (var attributeHandle in methodDefinition.GetCustomAttributes()) { StringHandle namespaceHandle, nameHandle; if (!metadataReader.GetAttributeNamespaceAndName(attributeHandle, out namespaceHandle, out nameHandle)) continue; if (metadataReader.StringComparer.Equals(namespaceHandle, "System.Runtime.CompilerServices")) { if (metadataReader.StringComparer.Equals(nameHandle, "IntrinsicAttribute")) { flags |= MethodFlags.Intrinsic; } } } flags |= MethodFlags.AttributeMetadataCache; } Debug.Assert((flags & mask) != 0); _methodFlags.AddFlags(flags); return flags & mask; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private int GetMethodFlags(int mask) { int flags = _methodFlags.Value & mask; if (flags != 0) return flags; return InitializeMethodFlags(mask); } public override bool IsVirtual { get { return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.Virtual) & MethodFlags.Virtual) != 0; } } public override bool IsNewSlot { get { return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.NewSlot) & MethodFlags.NewSlot) != 0; } } public override bool IsAbstract { get { return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.Abstract) & MethodFlags.Abstract) != 0; } } public override bool IsFinal { get { return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.Final) & MethodFlags.Final) != 0; } } public override bool IsNoInlining { get { return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.NoInlining) & MethodFlags.NoInlining) != 0; } } public override bool IsAggressiveInlining { get { return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.AggressiveInlining) & MethodFlags.AggressiveInlining) != 0; } } public override bool IsIntrinsic { get { return (GetMethodFlags(MethodFlags.AttributeMetadataCache | MethodFlags.Intrinsic) & MethodFlags.Intrinsic) != 0; } } public MethodAttributes Attributes { get { return MetadataReader.GetMethodDefinition(_handle).Attributes; } } public MethodImplAttributes ImplAttributes { get { return MetadataReader.GetMethodDefinition(_handle).ImplAttributes; } } private string InitializeName() { var metadataReader = MetadataReader; var name = metadataReader.GetString(metadataReader.GetMethodDefinition(_handle).Name); return (_name = name); } public override string Name { get { if (_name == null) return InitializeName(); return _name; } } private void ComputeGenericParameters() { var genericParameterHandles = MetadataReader.GetMethodDefinition(_handle).GetGenericParameters(); int count = genericParameterHandles.Count; if (count > 0) { TypeDesc[] genericParameters = new TypeDesc[count]; int i = 0; foreach (var genericParameterHandle in genericParameterHandles) { genericParameters[i++] = new EcmaGenericParameter(Module, genericParameterHandle); } Interlocked.CompareExchange(ref _genericParameters, genericParameters, null); } else { _genericParameters = TypeDesc.EmptyTypes; } } public override Instantiation Instantiation { get { if (_genericParameters == null) ComputeGenericParameters(); return new Instantiation(_genericParameters); } } public override bool HasCustomAttribute(string attributeNamespace, string attributeName) { return MetadataReader.HasCustomAttribute(MetadataReader.GetMethodDefinition(_handle).GetCustomAttributes(), attributeNamespace, attributeName); } public override string ToString() { return _type.ToString() + "." + Name; } public override bool IsPInvoke { get { return (((int)Attributes & (int)MethodAttributes.PinvokeImpl) != 0); } } public override PInvokeMetadata GetPInvokeMethodMetadata() { if (!IsPInvoke) return default(PInvokeMetadata); MetadataReader metadataReader = MetadataReader; MethodImport import = metadataReader.GetMethodDefinition(_handle).GetImport(); string name = metadataReader.GetString(import.Name); // Spot check the enums match Debug.Assert((int)MethodImportAttributes.CallingConventionStdCall == (int)PInvokeAttributes.CallingConventionStdCall); Debug.Assert((int)MethodImportAttributes.CharSetAuto == (int)PInvokeAttributes.CharSetAuto); Debug.Assert((int)MethodImportAttributes.CharSetUnicode == (int)PInvokeAttributes.CharSetUnicode); return new PInvokeMetadata(name, (PInvokeAttributes)import.Attributes); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.CSharp.RuntimeBinder.Errors; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { [Flags] internal enum MemLookFlags : uint { None = 0, Ctor = EXPRFLAG.EXF_CTOR, NewObj = EXPRFLAG.EXF_NEWOBJCALL, Operator = EXPRFLAG.EXF_OPERATOR, Indexer = EXPRFLAG.EXF_INDEXER, UserCallable = EXPRFLAG.EXF_USERCALLABLE, BaseCall = EXPRFLAG.EXF_BASECALL, // All EXF flags are < 0x01000000 MustBeInvocable = 0x20000000, TypeVarsAllowed = 0x40000000, ExtensionCall = 0x80000000, All = Ctor | NewObj | Operator | Indexer | UserCallable | BaseCall | MustBeInvocable | TypeVarsAllowed | ExtensionCall } ///////////////////////////////////////////////////////////////////////////////// // MemberLookup class handles looking for a member within a type and its // base types. This only handles AGGTYPESYMs and TYVARSYMs. // // Lookup must be called before any other methods. internal sealed class MemberLookup { // The inputs to Lookup. private CSemanticChecker _pSemanticChecker; private SymbolLoader _pSymbolLoader; private CType _typeSrc; private Expr _obj; private CType _typeQual; private ParentSymbol _symWhere; private Name _name; private int _arity; private MemLookFlags _flags; private CMemberLookupResults _results; // For maintaining the type array. We throw the first 8 or so here. private readonly List<AggregateType> _rgtypeStart; // Results of the lookup. private List<AggregateType> _prgtype; private int _csym; // Number of syms found. private readonly SymWithType _swtFirst; // The first symbol found. private readonly List<MethPropWithType> _methPropWithTypeList; // When we look up methods, we want to keep the list of all candidate methods given a particular name. // These are for error reporting. private readonly SymWithType _swtAmbig; // An ambiguous symbol. private readonly SymWithType _swtInaccess; // An inaccessible symbol. private readonly SymWithType _swtBad; // If we're looking for a constructor or indexer, this matched on name, but isn't the right thing. private readonly SymWithType _swtBogus; // A bogus member - such as an indexed property. private readonly SymWithType _swtBadArity; // An symbol with the wrong arity. private SymWithType _swtAmbigWarn; // An ambiguous symbol, but only warn. // We have an override symbol, which we've errored on in SymbolPrepare. If we have nothing better, use this. // This is because if we have: // // class C : D // { // public override int M() { } // static void Main() // { // C c = new C(); // c.M(); <-- // // We try to look up M, and find the M on C, but throw it out since its an override, and // we want the virtual that it overrides. However, in this case, we'll never find that // virtual, since it doesn't exist. We therefore want to use the override anyway, and // continue on to give results with that. private readonly SymWithType _swtOverride; private bool _fMulti; // Whether symFirst is of a kind for which we collect multiples (methods and indexers). /*************************************************************************************************** Another match was found. Increment the count of syms and add the type to our list if it's not already there. ***************************************************************************************************/ private void RecordType(AggregateType type, Symbol sym) { Debug.Assert(type != null && sym != null); if (!_prgtype.Contains(type)) { _prgtype.Add(type); } // Now record the sym.... _csym++; // If it is first, record it. if (_swtFirst == null) { _swtFirst.Set(sym, type); Debug.Assert(_csym == 1); Debug.Assert(_prgtype[0] == type); _fMulti = sym is MethodSymbol || sym is IndexerSymbol; } } /****************************************************************************** Search just the given type (not any bases). Returns true iff it finds something (which will have been recorded by RecordType). pfHideByName is set to true iff something was found that hides all members of base types (eg, a hidebyname method). ******************************************************************************/ private bool SearchSingleType(AggregateType typeCur, out bool pfHideByName) { bool fFoundSome = false; pfHideByName = false; // Make sure this type is accessible. It may not be due to private inheritance // or friend assemblies. bool fInaccess = !GetSemanticChecker().CheckTypeAccess(typeCur, _symWhere); if (fInaccess && (_csym != 0 || _swtInaccess != null)) return false; // Loop through symbols. Symbol symCur = null; for (symCur = GetSymbolLoader().LookupAggMember(_name, typeCur.getAggregate(), symbmask_t.MASK_ALL); symCur != null; symCur = GetSymbolLoader().LookupNextSym(symCur, typeCur.getAggregate(), symbmask_t.MASK_ALL)) { // Check for arity. switch (symCur.getKind()) { case SYMKIND.SK_MethodSymbol: // For non-zero arity, only methods of the correct arity are considered. // For zero arity, don't filter out any methods since we do type argument // inferencing. if (_arity > 0 && ((MethodSymbol)symCur).typeVars.Count != _arity) { if (!_swtBadArity) _swtBadArity.Set(symCur, typeCur); continue; } break; case SYMKIND.SK_AggregateSymbol: // For types, always filter on arity. if (((AggregateSymbol)symCur).GetTypeVars().Count != _arity) { if (!_swtBadArity) _swtBadArity.Set(symCur, typeCur); continue; } break; case SYMKIND.SK_TypeParameterSymbol: if ((_flags & MemLookFlags.TypeVarsAllowed) == 0) continue; if (_arity > 0) { if (!_swtBadArity) _swtBadArity.Set(symCur, typeCur); continue; } break; default: // All others are only considered when arity is zero. if (_arity > 0) { if (!_swtBadArity) _swtBadArity.Set(symCur, typeCur); continue; } break; } // Check for user callability. if (symCur.IsOverride() && !symCur.IsHideByName()) { if (!_swtOverride) { _swtOverride.Set(symCur, typeCur); } continue; } MethodOrPropertySymbol methProp = symCur as MethodOrPropertySymbol; MethodSymbol meth = symCur as MethodSymbol; if (methProp != null && (_flags & MemLookFlags.UserCallable) != 0 && !methProp.isUserCallable()) { // If its an indexed property method symbol, let it through. if (meth != null && meth.isPropertyAccessor() && ((symCur.name.Text.StartsWith("set_", StringComparison.Ordinal) && meth.Params.Count > 1) || (symCur.name.Text.StartsWith("get_", StringComparison.Ordinal) && meth.Params.Count > 0))) { if (!_swtInaccess) { _swtInaccess.Set(symCur, typeCur); } continue; } } if (fInaccess || !GetSemanticChecker().CheckAccess(symCur, typeCur, _symWhere, _typeQual)) { // Not accessible so get the next sym. if (!_swtInaccess) { _swtInaccess.Set(symCur, typeCur); } if (fInaccess) { return false; } continue; } PropertySymbol prop = symCur as PropertySymbol; // Make sure that whether we're seeing a ctor, operator, or indexer is consistent with the flags. if (((_flags & MemLookFlags.Ctor) == 0) != (meth == null || !meth.IsConstructor()) || ((_flags & MemLookFlags.Operator) == 0) != (meth == null || !meth.isOperator) || ((_flags & MemLookFlags.Indexer) == 0) != !(prop is IndexerSymbol)) { if (!_swtBad) { _swtBad.Set(symCur, typeCur); } continue; } // We can't call CheckBogus on methods or indexers because if the method has the wrong // number of parameters people don't think they should have to /r the assemblies containing // the parameter types and they complain about the resulting CS0012 errors. if (!(symCur is MethodSymbol) && (_flags & MemLookFlags.Indexer) == 0 && CSemanticChecker.CheckBogus(symCur)) { // A bogus member - we can't use these, so only record them for error reporting. if (!_swtBogus) { _swtBogus.Set(symCur, typeCur); } continue; } // if we are in a calling context then we should only find a property if it is delegate valued if ((_flags & MemLookFlags.MustBeInvocable) != 0) { if ((symCur is FieldSymbol field && !IsDelegateType(field.GetType(), typeCur) && !IsDynamicMember(symCur)) || (prop != null && !IsDelegateType(prop.RetType, typeCur) && !IsDynamicMember(symCur))) { if (!_swtBad) { _swtBad.Set(symCur, typeCur); } continue; } } if (methProp != null) { MethPropWithType mwpInsert = new MethPropWithType(methProp, typeCur); _methPropWithTypeList.Add(mwpInsert); } // We have a visible symbol. fFoundSome = true; if (_swtFirst) { if (!typeCur.isInterfaceType()) { // Non-interface case. Debug.Assert(_fMulti || typeCur == _prgtype[0]); if (!_fMulti) { if (_swtFirst.Sym is FieldSymbol && symCur is EventSymbol // The isEvent bit is only set on symbols which come from source... // This is not a problem for the compiler because the field is only // accessible in the scope in which it is declared, // but in the EE we ignore accessibility... && _swtFirst.Field().isEvent ) { // m_swtFirst is just the field behind the event symCur so ignore symCur. continue; } else if (_swtFirst.Sym is FieldSymbol && symCur is EventSymbol) { // symCur is the matching event. continue; } goto LAmbig; } if (_swtFirst.Sym.getKind() != symCur.getKind()) { if (typeCur == _prgtype[0]) goto LAmbig; // This one is hidden by the first one. This one also hides any more in base types. pfHideByName = true; continue; } } // Interface case. // m_fMulti : n n n y y y y y // same-kind : * * * y n n n n // fDiffHidden: * * * * y n n n // meth : * * * * * y n * can n happen? just in case, we better handle it.... // hack : n * y * * y * n // meth-2 : * n y * * * * * // res : A A S R H H A A else if (!_fMulti) { // Give method groups priority. if (!(symCur is MethodSymbol)) goto LAmbig; _swtAmbigWarn = _swtFirst; // Erase previous results so we'll record this method as the first. _prgtype = new List<AggregateType>(); _csym = 0; _swtFirst.Clear(); _swtAmbig.Clear(); } else if (_swtFirst.Sym.getKind() != symCur.getKind()) { if (!typeCur.fDiffHidden) { // Give method groups priority. if (!(_swtFirst.Sym is MethodSymbol)) goto LAmbig; if (!_swtAmbigWarn) _swtAmbigWarn.Set(symCur, typeCur); } // This one is hidden by another. This one also hides any more in base types. pfHideByName = true; continue; } } RecordType(typeCur, symCur); if (methProp != null && methProp.isHideByName) pfHideByName = true; // We've found a symbol in this type but need to make sure there aren't any conflicting // syms here, so keep searching the type. } Debug.Assert(!fInaccess || !fFoundSome); return fFoundSome; LAmbig: // Ambiguous! if (!_swtAmbig) _swtAmbig.Set(symCur, typeCur); pfHideByName = true; return true; } private bool IsDynamicMember(Symbol sym) { System.Runtime.CompilerServices.DynamicAttribute da = null; if (sym is FieldSymbol field) { if (!field.getType().isPredefType(PredefinedType.PT_OBJECT)) { return false; } var o = field.AssociatedFieldInfo.GetCustomAttributes(typeof(System.Runtime.CompilerServices.DynamicAttribute), false).ToArray(); if (o.Length == 1) { da = o[0] as System.Runtime.CompilerServices.DynamicAttribute; } } else { Debug.Assert(sym is PropertySymbol); PropertySymbol prop = (PropertySymbol)sym; if (!prop.getType().isPredefType(PredefinedType.PT_OBJECT)) { return false; } var o = prop.AssociatedPropertyInfo.GetCustomAttributes(typeof(System.Runtime.CompilerServices.DynamicAttribute), false).ToArray(); if (o.Length == 1) { da = o[0] as System.Runtime.CompilerServices.DynamicAttribute; } } if (da == null) { return false; } return (da.TransformFlags.Count == 0 || (da.TransformFlags.Count == 1 && da.TransformFlags[0])); } /****************************************************************************** Lookup in a class and its bases (until *ptypeEnd is hit). ptypeEnd [in/out] - *ptypeEnd should be either null or object. If we find something here that would hide members of object, this sets *ptypeEnd to null. Returns true when searching should continue to the interfaces. ******************************************************************************/ private bool LookupInClass(AggregateType typeStart, ref AggregateType ptypeEnd) { Debug.Assert(!_swtFirst || _fMulti); Debug.Assert(typeStart != null && !typeStart.isInterfaceType() && (ptypeEnd == null || typeStart != ptypeEnd)); AggregateType typeEnd = ptypeEnd; AggregateType typeCur; // Loop through types. Loop until we hit typeEnd (object or null). for (typeCur = typeStart; typeCur != typeEnd && typeCur != null; typeCur = typeCur.GetBaseClass()) { Debug.Assert(!typeCur.isInterfaceType()); bool fHideByName = false; SearchSingleType(typeCur, out fHideByName); _flags &= ~MemLookFlags.TypeVarsAllowed; if (_swtFirst && !_fMulti) { // Everything below this type and in interfaces is hidden. return false; } if (fHideByName) { // This hides everything below it and in object, but not in the interfaces! ptypeEnd = null; // Return true to indicate that it's ok to search additional types. return true; } if ((_flags & MemLookFlags.Ctor) != 0) { // If we're looking for a constructor, don't check base classes or interfaces. return false; } } Debug.Assert(typeCur == typeEnd); return true; } /****************************************************************************** Returns true if searching should continue to object. ******************************************************************************/ private bool LookupInInterfaces(AggregateType typeStart, TypeArray types) { Debug.Assert(!_swtFirst || _fMulti); Debug.Assert(typeStart == null || typeStart.isInterfaceType()); Debug.Assert(typeStart != null || types.Count != 0); // Clear all the hidden flags. Anything found in a class hides any other // kind of member in all the interfaces. if (typeStart != null) { typeStart.fAllHidden = false; typeStart.fDiffHidden = (_swtFirst != null); } for (int i = 0; i < types.Count; i++) { AggregateType type = (AggregateType)types[i]; Debug.Assert(type.isInterfaceType()); type.fAllHidden = false; type.fDiffHidden = !!_swtFirst; } bool fHideObject = false; AggregateType typeCur = typeStart; int itypeNext = 0; if (typeCur == null) { typeCur = (AggregateType)types[itypeNext++]; } Debug.Assert(typeCur != null); // Loop through the interfaces. for (; ;) { Debug.Assert(typeCur != null && typeCur.isInterfaceType()); bool fHideByName = false; if (!typeCur.fAllHidden && SearchSingleType(typeCur, out fHideByName)) { fHideByName |= !_fMulti; // Mark base interfaces appropriately. TypeArray ifaces = typeCur.GetIfacesAll(); for (int i = 0; i < ifaces.Count; i++) { AggregateType type = (AggregateType)ifaces[i]; Debug.Assert(type.isInterfaceType()); if (fHideByName) type.fAllHidden = true; type.fDiffHidden = true; } // If we hide all base types, that includes object! if (fHideByName) fHideObject = true; } _flags &= ~MemLookFlags.TypeVarsAllowed; if (itypeNext >= types.Count) return !fHideObject; // Substitution has already been done. typeCur = types[itypeNext++] as AggregateType; } } private SymbolLoader GetSymbolLoader() { return _pSymbolLoader; } private CSemanticChecker GetSemanticChecker() { return _pSemanticChecker; } private ErrorHandling GetErrorContext() { return GetSymbolLoader().GetErrorContext(); } private RuntimeBinderException ReportBogus(SymWithType swt) { Debug.Assert(CSemanticChecker.CheckBogus(swt.Sym)); MethodSymbol meth1 = swt.Prop().GetterMethod; MethodSymbol meth2 = swt.Prop().SetterMethod; Debug.Assert((meth1 ?? meth2) != null); return meth1 == null | meth2 == null ? GetErrorContext().Error( ErrorCode.ERR_BindToBogusProp1, swt.Sym.name, new SymWithType(meth1 ?? meth2, swt.GetType()), new ErrArgRefOnly(swt.Sym)) : GetErrorContext().Error( ErrorCode.ERR_BindToBogusProp2, swt.Sym.name, new SymWithType(meth1, swt.GetType()), new SymWithType(meth2, swt.GetType()), new ErrArgRefOnly(swt.Sym)); } private bool IsDelegateType(CType pSrcType, AggregateType pAggType) { CType pInstantiatedType = GetSymbolLoader().GetTypeManager().SubstType(pSrcType, pAggType, pAggType.GetTypeArgsAll()); return pInstantiatedType.isDelegateType(); } ///////////////////////////////////////////////////////////////////////////////// // Public methods. public MemberLookup() { _methPropWithTypeList = new List<MethPropWithType>(); _rgtypeStart = new List<AggregateType>(); _swtFirst = new SymWithType(); _swtAmbig = new SymWithType(); _swtInaccess = new SymWithType(); _swtBad = new SymWithType(); _swtBogus = new SymWithType(); _swtBadArity = new SymWithType(); _swtAmbigWarn = new SymWithType(); _swtOverride = new SymWithType(); } /*************************************************************************************************** Lookup must be called before anything else can be called. typeSrc - Must be an AggregateType or TypeParameterType. obj - the expression through which the member is being accessed. This is used for accessibility of protected members and for constructing a MEMGRP from the results of the lookup. It is legal for obj to be an EK_CLASS, in which case it may be used for accessibility, but will not be used for MEMGRP construction. symWhere - the symbol from with the name is being accessed (for checking accessibility). name - the name to look for. arity - the number of type args specified. Only members that support this arity are found. Note that when arity is zero, all methods are considered since we do type argument inferencing. flags - See MemLookFlags. TypeVarsAllowed only applies to the most derived type (not base types). ***************************************************************************************************/ public bool Lookup(CSemanticChecker checker, CType typeSrc, Expr obj, ParentSymbol symWhere, Name name, int arity, MemLookFlags flags) { Debug.Assert((flags & ~MemLookFlags.All) == 0); Debug.Assert(obj == null || obj.Type != null); Debug.Assert(typeSrc is AggregateType || typeSrc is TypeParameterType); Debug.Assert(checker != null); _prgtype = _rgtypeStart; // Save the inputs for error handling, etc. _pSemanticChecker = checker; _pSymbolLoader = checker.SymbolLoader; _typeSrc = typeSrc; _obj = obj is ExprClass ? null : obj; _symWhere = symWhere; _name = name; _arity = arity; _flags = flags; _typeQual = (_flags & MemLookFlags.Ctor) != 0 ? _typeSrc : obj?.Type; // Determine what to search. AggregateType typeCls1 = null; AggregateType typeIface = null; TypeArray ifaces = BSYMMGR.EmptyTypeArray(); AggregateType typeCls2 = null; if (typeSrc is TypeParameterType typeParamSrc) { Debug.Assert((_flags & (MemLookFlags.Ctor | MemLookFlags.NewObj | MemLookFlags.Operator | MemLookFlags.BaseCall | MemLookFlags.TypeVarsAllowed)) == 0); _flags &= ~MemLookFlags.TypeVarsAllowed; ifaces = typeParamSrc.GetInterfaceBounds(); typeCls1 = typeParamSrc.GetEffectiveBaseClass(); if (ifaces.Count > 0 && typeCls1.isPredefType(PredefinedType.PT_OBJECT)) typeCls1 = null; } else if (!typeSrc.isInterfaceType()) { typeCls1 = (AggregateType)typeSrc; if (typeCls1.IsWindowsRuntimeType()) { ifaces = typeCls1.GetWinRTCollectionIfacesAll(GetSymbolLoader()); } } else { Debug.Assert(typeSrc.isInterfaceType()); Debug.Assert((_flags & (MemLookFlags.Ctor | MemLookFlags.NewObj | MemLookFlags.Operator | MemLookFlags.BaseCall)) == 0); typeIface = (AggregateType)typeSrc; ifaces = typeIface.GetIfacesAll(); } if (typeIface != null || ifaces.Count > 0) typeCls2 = GetSymbolLoader().GetPredefindType(PredefinedType.PT_OBJECT); // Search the class first (except possibly object). if (typeCls1 == null || LookupInClass(typeCls1, ref typeCls2)) { // Search the interfaces. if ((typeIface != null || ifaces.Count > 0) && LookupInInterfaces(typeIface, ifaces) && typeCls2 != null) { // Search object last. Debug.Assert(typeCls2 != null && typeCls2.isPredefType(PredefinedType.PT_OBJECT)); AggregateType result = null; LookupInClass(typeCls2, ref result); } } // if we are requested with extension methods _results = new CMemberLookupResults(GetAllTypes(), _name); return !FError(); } public CMemberLookupResults GetResults() { return _results; } // Whether there were errors. private bool FError() { return !_swtFirst || _swtAmbig; } // The first symbol found. public Symbol SymFirst() { return _swtFirst.Sym; } public SymWithType SwtFirst() { return _swtFirst; } public Expr GetObject() { return _obj; } public CType GetSourceType() { return _typeSrc; } public MemLookFlags GetFlags() { return _flags; } // Put all the types in a type array. private TypeArray GetAllTypes() { return GetSymbolLoader().getBSymmgr().AllocParams(_prgtype.Count, _prgtype.ToArray()); } /****************************************************************************** Reports errors. Only call this if FError() is true. ******************************************************************************/ public Exception ReportErrors() { Debug.Assert(FError()); // Report error. // NOTE: If the definition of FError changes, this code will need to change. Debug.Assert(!_swtFirst || _swtAmbig); if (_swtFirst) { // Ambiguous lookup. return GetErrorContext().Error(ErrorCode.ERR_AmbigMember, _swtFirst, _swtAmbig); } if (_swtInaccess) { return !_swtInaccess.Sym.isUserCallable() && ((_flags & MemLookFlags.UserCallable) != 0) ? GetErrorContext().Error(ErrorCode.ERR_CantCallSpecialMethod, _swtInaccess) : GetSemanticChecker().ReportAccessError(_swtInaccess, _symWhere, _typeQual); } if ((_flags & MemLookFlags.Ctor) != 0) { return _arity > 0 ? GetErrorContext().Error(ErrorCode.ERR_BadCtorArgCount, _typeSrc.getAggregate(), _arity) : GetErrorContext().Error(ErrorCode.ERR_NoConstructors, _typeSrc.getAggregate()); } if ((_flags & MemLookFlags.Operator) != 0) { return GetErrorContext().Error(ErrorCode.ERR_NoSuchMember, _typeSrc, _name); } if ((_flags & MemLookFlags.Indexer) != 0) { return GetErrorContext().Error(ErrorCode.ERR_BadIndexLHS, _typeSrc); } if (_swtBad) { return GetErrorContext().Error((_flags & MemLookFlags.MustBeInvocable) != 0 ? ErrorCode.ERR_NonInvocableMemberCalled : ErrorCode.ERR_CantCallSpecialMethod, _swtBad); } if (_swtBogus) { return ReportBogus(_swtBogus); } if (_swtBadArity) { int cvar; switch (_swtBadArity.Sym.getKind()) { case SYMKIND.SK_MethodSymbol: Debug.Assert(_arity != 0); cvar = ((MethodSymbol)_swtBadArity.Sym).typeVars.Count; return GetErrorContext().Error(cvar > 0 ? ErrorCode.ERR_BadArity : ErrorCode.ERR_HasNoTypeVars, _swtBadArity, new ErrArgSymKind(_swtBadArity.Sym), cvar); case SYMKIND.SK_AggregateSymbol: cvar = ((AggregateSymbol)_swtBadArity.Sym).GetTypeVars().Count; return GetErrorContext().Error(cvar > 0 ? ErrorCode.ERR_BadArity : ErrorCode.ERR_HasNoTypeVars, _swtBadArity, new ErrArgSymKind(_swtBadArity.Sym), cvar); default: Debug.Assert(_arity != 0); return GetErrorContext().Error(ErrorCode.ERR_TypeArgsNotAllowed, _swtBadArity, new ErrArgSymKind(_swtBadArity.Sym)); } } return GetErrorContext().Error(ErrorCode.ERR_NoSuchMember, _typeSrc, _name); } } }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog { using System; using System.ComponentModel; using JetBrains.Annotations; /// <summary> /// Logger with only generic methods (passing 'LogLevel' to methods) and core properties. /// </summary> public partial interface ILoggerBase { /// <summary> /// Occurs when logger configuration changes. /// </summary> event EventHandler<EventArgs> LoggerReconfigured; /// <summary> /// Gets the name of the logger. /// </summary> string Name { get; } /// <summary> /// Gets the factory that created this logger. /// </summary> LogFactory Factory { get; } /// <summary> /// Gets a value indicating whether logging is enabled for the specified level. /// </summary> /// <param name="level">Log level to be checked.</param> /// <returns>A value of <see langword="true" /> if logging is enabled for the specified level, otherwise it returns <see langword="false" />.</returns> bool IsEnabled(LogLevel level); #region Log() overloads /// <summary> /// Writes the specified diagnostic message. /// </summary> /// <param name="logEvent">Log event.</param> void Log(LogEventInfo logEvent); /// <summary> /// Writes the specified diagnostic message. /// </summary> /// <param name="wrapperType">The name of the type that wraps Logger.</param> /// <param name="logEvent">Log event.</param> void Log(Type wrapperType, LogEventInfo logEvent); /// <overloads> /// Writes the diagnostic message at the specified level using the specified format provider and format parameters. /// </overloads> /// <summary> /// Writes the diagnostic message at the specified level. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="level">The log level.</param> /// <param name="value">The value to be written.</param> void Log<T>(LogLevel level, T value); /// <summary> /// Writes the diagnostic message at the specified level. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">The value to be written.</param> void Log<T>(LogLevel level, IFormatProvider formatProvider, T value); /// <summary> /// Writes the diagnostic message at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> void Log(LogLevel level, LogMessageGenerator messageFunc); /// <summary> /// Writes the diagnostic message and exception at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks> [Obsolete("Use Log(LogLevel level, Exception exception, [Localizable(false)] string message, params object[] args) instead. Marked obsolete before v4.3.11")] void LogException(LogLevel level, [Localizable(false)] string message, Exception exception); /// <summary> /// Writes the diagnostic message and exception at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="args">Arguments to format.</param> /// <param name="exception">An exception to be logged.</param> [StringFormatMethod("message")] void Log(LogLevel level, Exception exception, [Localizable(false)] string message, params object[] args); /// <summary> /// Writes the diagnostic message and exception at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="args">Arguments to format.</param> /// <param name="exception">An exception to be logged.</param> [StringFormatMethod("message")] void Log(LogLevel level, Exception exception, IFormatProvider formatProvider, [Localizable(false)] string message, params object[] args); /// <summary> /// Writes the diagnostic message at the specified level using the specified parameters and formatting them with the supplied format provider. /// </summary> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [StringFormatMethod("message")] void Log(LogLevel level, IFormatProvider formatProvider, [Localizable(false)] string message, params object[] args); /// <summary> /// Writes the diagnostic message at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">Log message.</param> void Log(LogLevel level, [Localizable(false)] string message); /// <summary> /// Writes the diagnostic message at the specified level using the specified parameters. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [StringFormatMethod("message")] void Log(LogLevel level, [Localizable(false)] string message, params object[] args); /// <summary> /// Writes the diagnostic message and exception at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks> [Obsolete("Use Log(LogLevel level, Exception exception, [Localizable(false)] string message, params object[] args) instead. Marked obsolete before v4.3.11")] void Log(LogLevel level, [Localizable(false)] string message, Exception exception); /// <summary> /// Writes the diagnostic message at the specified level using the specified parameter and formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [StringFormatMethod("message")] void Log<TArgument>(LogLevel level, IFormatProvider formatProvider, [Localizable(false)] string message, TArgument argument); /// <summary> /// Writes the diagnostic message at the specified level using the specified parameter. /// </summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [StringFormatMethod("message")] void Log<TArgument>(LogLevel level, [Localizable(false)] string message, TArgument argument); /// <summary> /// Writes the diagnostic message at the specified level using the specified arguments formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [StringFormatMethod("message")] void Log<TArgument1, TArgument2>(LogLevel level, IFormatProvider formatProvider, [Localizable(false)] string message, TArgument1 argument1, TArgument2 argument2); /// <summary> /// Writes the diagnostic message at the specified level using the specified parameters. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [StringFormatMethod("message")] void Log<TArgument1, TArgument2>(LogLevel level, [Localizable(false)] string message, TArgument1 argument1, TArgument2 argument2); /// <summary> /// Writes the diagnostic message at the specified level using the specified arguments formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [StringFormatMethod("message")] void Log<TArgument1, TArgument2, TArgument3>(LogLevel level, IFormatProvider formatProvider, [Localizable(false)] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3); /// <summary> /// Writes the diagnostic message at the specified level using the specified parameters. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [StringFormatMethod("message")] void Log<TArgument1, TArgument2, TArgument3>(LogLevel level, [Localizable(false)] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3); #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.Specialized; using System.IO; using System.Security.Cryptography; using System.Xml; namespace System.Configuration { // Need the System.Security.Cryptography.Xml package published before this can be enabled, // for now, make it throw PlatformNotSupported. // // https://github.com/dotnet/corefx/issues/14950 public sealed class RsaProtectedConfigurationProvider : ProtectedConfigurationProvider { public override XmlNode Decrypt(XmlNode encryptedNode) { throw new PlatformNotSupportedException(); } public override XmlNode Encrypt(XmlNode node) { throw new PlatformNotSupportedException(); } public void AddKey(int keySize, bool exportable) { throw new PlatformNotSupportedException(); } public void DeleteKey() { throw new PlatformNotSupportedException(); } public void ImportKey(string xmlFileName, bool exportable) { throw new PlatformNotSupportedException(); } public void ExportKey(string xmlFileName, bool includePrivateParameters) { throw new PlatformNotSupportedException(); } public string KeyContainerName { get { throw new PlatformNotSupportedException(); } } public string CspProviderName { get { throw new PlatformNotSupportedException(); } } public bool UseMachineContainer { get { throw new PlatformNotSupportedException(); } } public bool UseOAEP { get { throw new PlatformNotSupportedException(); } } public bool UseFIPS { get { throw new PlatformNotSupportedException(); } } public RSAParameters RsaPublicKey { get { throw new PlatformNotSupportedException(); } } } #if FALSE public sealed class RsaProtectedConfigurationProvider : ProtectedConfigurationProvider { // Note: this name has to match the name used in RegiisUtility const string DefaultRsaKeyContainerName = "NetFrameworkConfigurationKey"; const uint PROV_Rsa_FULL = 1; const uint CRYPT_MACHINE_KEYSET = 0x00000020; private string _keyName; private string _keyContainerName; private string _cspProviderName; private bool _useMachineContainer; private bool _useOAEP; private bool _useFIPS; public override XmlNode Decrypt(XmlNode encryptedNode) { XmlDocument xmlDocument = new XmlDocument(); EncryptedXml exml = null; RSACryptoServiceProvider rsa = GetCryptoServiceProvider(false, true); xmlDocument.PreserveWhitespace = true; xmlDocument.LoadXml(encryptedNode.OuterXml); exml = new FipsAwareEncryptedXml(xmlDocument); exml.AddKeyNameMapping(_keyName, rsa); exml.DecryptDocument(); rsa.Clear(); return xmlDocument.DocumentElement; } public override XmlNode Encrypt(XmlNode node) { XmlDocument xmlDocument; EncryptedXml exml; byte[] rgbOutput; EncryptedData ed; KeyInfoName kin; EncryptedKey ek; KeyInfoEncryptedKey kek; XmlElement inputElement; RSACryptoServiceProvider rsa = GetCryptoServiceProvider(false, false); // Encrypt the node with the new key xmlDocument = new XmlDocument(); xmlDocument.PreserveWhitespace = true; xmlDocument.LoadXml("<foo>" + node.OuterXml + "</foo>"); exml = new EncryptedXml(xmlDocument); inputElement = xmlDocument.DocumentElement; using (SymmetricAlgorithm symAlg = GetSymAlgorithmProvider()) { rgbOutput = exml.EncryptData(inputElement, symAlg, true); ed = new EncryptedData(); ed.Type = EncryptedXml.XmlEncElementUrl; ed.EncryptionMethod = GetSymEncryptionMethod(); ed.KeyInfo = new KeyInfo(); ek = new EncryptedKey(); ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url); ek.KeyInfo = new KeyInfo(); ek.CipherData = new CipherData(); ek.CipherData.CipherValue = EncryptedXml.EncryptKey(symAlg.Key, rsa, UseOAEP); } kin = new KeyInfoName(); kin.Value = _keyName; ek.KeyInfo.AddClause(kin); kek = new KeyInfoEncryptedKey(ek); ed.KeyInfo.AddClause(kek); ed.CipherData = new CipherData(); ed.CipherData.CipherValue = rgbOutput; EncryptedXml.ReplaceElement(inputElement, ed, true); rsa.Clear(); // Get node from the document foreach (XmlNode node2 in xmlDocument.ChildNodes) if (node2.NodeType == XmlNodeType.Element) foreach (XmlNode node3 in node2.ChildNodes) // node2 is the "foo" node if (node3.NodeType == XmlNodeType.Element) return node3; // node3 is the "EncryptedData" node return null; } public void AddKey(int keySize, bool exportable) { RSACryptoServiceProvider rsa = GetCryptoServiceProvider(exportable, false); rsa.KeySize = keySize; rsa.PersistKeyInCsp = true; rsa.Clear(); } public void DeleteKey() { RSACryptoServiceProvider rsa = GetCryptoServiceProvider(false, true); rsa.PersistKeyInCsp = false; rsa.Clear(); } public void ImportKey(string xmlFileName, bool exportable) { RSACryptoServiceProvider rsa = GetCryptoServiceProvider(exportable, false); rsa.FromXmlString(File.ReadAllText(xmlFileName)); rsa.PersistKeyInCsp = true; rsa.Clear(); } public void ExportKey(string xmlFileName, bool includePrivateParameters) { RSACryptoServiceProvider rsa = GetCryptoServiceProvider(false, false); string xmlString = rsa.ToXmlString(includePrivateParameters); File.WriteAllText(xmlFileName, xmlString); rsa.Clear(); } public string KeyContainerName { get { return _keyContainerName; } } public string CspProviderName { get { return _cspProviderName; } } public bool UseMachineContainer { get { return _useMachineContainer; } } public bool UseOAEP { get { return _useOAEP; } } public bool UseFIPS { get { return _useFIPS; } } public override void Initialize(string name, NameValueCollection configurationValues) { base.Initialize(name, configurationValues); _keyName = "Rsa Key"; _keyContainerName = configurationValues["keyContainerName"]; configurationValues.Remove("keyContainerName"); if (_keyContainerName == null || _keyContainerName.Length < 1) _keyContainerName = DefaultRsaKeyContainerName; _cspProviderName = configurationValues["cspProviderName"]; configurationValues.Remove("cspProviderName"); _useMachineContainer = GetBooleanValue(configurationValues, "useMachineContainer", true); _useOAEP = GetBooleanValue(configurationValues, "useOAEP", false); _useFIPS = GetBooleanValue(configurationValues, "useFIPS", false); if (configurationValues.Count > 0) throw new ConfigurationErrorsException(SR.Format(SR.Unrecognized_initialization_value, configurationValues.GetKey(0))); } public RSAParameters RsaPublicKey { get { return GetCryptoServiceProvider(false, false).ExportParameters(false); } } private RSACryptoServiceProvider GetCryptoServiceProvider(bool exportable, bool keyMustExist) { try { CspParameters csp = new CspParameters(); csp.KeyContainerName = KeyContainerName; csp.KeyNumber = 1; csp.ProviderType = 1; // Dev10 Bug #548719: Explicitly require "RSA Full (Signature and Key Exchange)" if (CspProviderName != null && CspProviderName.Length > 0) csp.ProviderName = CspProviderName; if (UseMachineContainer) csp.Flags |= CspProviderFlags.UseMachineKeyStore; if (!exportable && !keyMustExist) csp.Flags |= CspProviderFlags.UseNonExportableKey; if (keyMustExist) csp.Flags |= CspProviderFlags.UseExistingKey; return new RSACryptoServiceProvider(csp); } catch { // On NetFX (Desktop) we try to P/Invoke directly to Windows to get a "better" exception // ThrowBetterException(keyMustExist); throw; } } private byte[] GetRandomKey() { byte[] buf = new byte[24]; (new RNGCryptoServiceProvider()).GetBytes(buf); return buf; } private static bool GetBooleanValue(NameValueCollection configurationValues, string valueName, bool defaultValue) { string s = configurationValues[valueName]; if (s == null) return defaultValue; configurationValues.Remove(valueName); if (s == "true") return true; if (s == "false") return false; throw new ConfigurationErrorsException(SR.Format(SR.Config_invalid_boolean_attribute, valueName)); } private SymmetricAlgorithm GetSymAlgorithmProvider() { SymmetricAlgorithm symAlg; if (UseFIPS) { // AesCryptoServiceProvider implementation is FIPS certified symAlg = new AesCryptoServiceProvider(); } else { // Use the 3DES. FIPS obsoleted 3DES symAlg = new TripleDESCryptoServiceProvider(); byte[] rgbKey1 = GetRandomKey(); symAlg.Key = rgbKey1; symAlg.Mode = CipherMode.ECB; symAlg.Padding = PaddingMode.PKCS7; } return symAlg; } private EncryptionMethod GetSymEncryptionMethod() { return UseFIPS ? new EncryptionMethod(EncryptedXml.XmlEncAES256Url) : new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl); } } #endif }
//----------------------------------------------------------------------------- // Torque // Copyright GarageGames, LLC 2011 //----------------------------------------------------------------------------- // If we got back no prefs path modification if( $Gui::fontCacheDirectory $= "") { $Gui::fontCacheDirectory = expandFilename( "~/fonts" ); } //--------------------------------------------------------------------------------------------- // GuiDefaultProfile is a special profile that all other profiles inherit defaults from. It // must exist. //--------------------------------------------------------------------------------------------- if( !isObject( GuiDefaultProfile ) ) new GuiControlProfile (GuiDefaultProfile) { tab = false; canKeyFocus = false; hasBitmapArray = false; mouseOverSelected = false; // fill color opaque = false; fillColor = "242 241 240"; fillColorHL ="228 228 235"; fillColorSEL = "98 100 137"; fillColorNA = "255 255 255 "; // border color border = 0; borderColor = "100 100 100"; borderColorHL = "50 50 50 50"; borderColorNA = "75 75 75"; // font fontType = "Arial"; fontSize = 14; fontCharset = ANSI; fontColor = "0 0 0"; fontColorHL = "0 0 0"; fontColorNA = "0 0 0"; fontColorSEL= "255 255 255"; // bitmap information bitmap = ""; bitmapBase = ""; textOffset = "0 0"; // used by guiTextControl modal = true; justify = "left"; autoSizeWidth = false; autoSizeHeight = false; returnTab = false; numbersOnly = false; cursorColor = "0 0 0 255"; // sounds //soundButtonDown = ""; //soundButtonOver = ""; }; if( !isObject( GuiSolidDefaultProfile ) ) new GuiControlProfile (GuiSolidDefaultProfile) { opaque = true; border = true; category = "Core"; }; if( !isObject( GuiTransparentProfile ) ) new GuiControlProfile (GuiTransparentProfile) { opaque = false; border = false; category = "Core"; }; if( !isObject( GuiTransparentwbProfile ) ) new GuiControlProfile (GuiTransparentwbProfile) { opaque = false; border = true; //fillcolor ="255 255 255"; borderColor = "100 100 100"; category = "Core"; }; if( !isObject( GuiGroupBorderProfile ) ) new GuiControlProfile( GuiGroupBorderProfile ) { border = false; opaque = false; hasBitmapArray = true; bitmap = "./images/group-border"; category = "Core"; }; if( !isObject( GuiTabBorderProfile ) ) new GuiControlProfile( GuiTabBorderProfile ) { border = false; opaque = false; hasBitmapArray = true; bitmap = "./images/tab-border"; category = "Core"; }; if( !isObject( GuiGroupTitleProfile ) ) new GuiControlProfile( GuiGroupTitleProfile ) { fillColor = "242 241 240"; fillColorHL ="242 241 240"; fillColorNA = "242 241 240"; fontColor = "0 0 0"; opaque = true; category = "Core"; }; if( !isObject( GuiToolTipProfile ) ) new GuiControlProfile (GuiToolTipProfile) { // fill color fillColor = "239 237 222"; // border color borderColor = "138 134 122"; // font fontType = "Arial"; fontSize = 14; fontColor = "0 0 0"; category = "Core"; }; if( !isObject( GuiModelessDialogProfile ) ) new GuiControlProfile( GuiModelessDialogProfile ) { modal = false; category = "Core"; }; if( !isObject( GuiFrameSetProfile ) ) new GuiControlProfile (GuiFrameSetProfile) { fillcolor = "255 255 255";//GuiDefaultProfile.fillColor; borderColor = "246 245 244"; border = 1; //fillColor = "240 239 238"; //borderColor = "50 50 50";//"204 203 202"; //fillColor = GuiDefaultProfile.fillColorNA; //borderColor = GuiDefaultProfile.borderColorNA; opaque = true; border = true; category = "Core"; }; if ($platform $= "macos") { if( !isObject( GuiWindowProfile ) ) new GuiControlProfile (GuiWindowProfile) { opaque = false; border = 2; fillColor = "242 241 240"; fillColorHL = "221 221 221"; fillColorNA = "200 200 200"; fontColor = "50 50 50"; fontColorHL = "0 0 0"; bevelColorHL = "255 255 255"; bevelColorLL = "0 0 0"; text = "untitled"; bitmap = "./images/window"; textOffset = "8 4"; hasBitmapArray = true; justify = "center"; category = "Core"; }; } else { if( !isObject( GuiWindowProfile ) ) new GuiControlProfile (GuiWindowProfile) { opaque = false; border = 2; fillColor = "242 241 240"; fillColorHL = "221 221 221"; fillColorNA = "200 200 200"; fontColor = "50 50 50"; fontColorHL = "0 0 0"; bevelColorHL = "255 255 255"; bevelColorLL = "0 0 0"; text = "untitled"; bitmap = "./images/window"; textOffset = "8 4"; hasBitmapArray = true; justify = "left"; category = "Core"; }; } if( !isObject( GuiToolbarWindowProfile ) ) new GuiControlProfile(GuiToolbarWindowProfile : GuiWindowProfile) { bitmap = "./images/toolbar-window"; text = ""; category = "Core"; }; if( !isObject( GuiHToolbarWindowProfile ) ) new GuiControlProfile (GuiHToolbarWindowProfile : GuiWindowProfile) { bitmap = "./images/htoolbar-window"; text = ""; category = "Core"; }; if( !isObject( GuiMenubarWindowProfile ) ) new GuiControlProfile (GuiMenubarWindowProfile : GuiWindowProfile) { bitmap = "./images/menubar-window"; text = ""; category = "Core"; }; if( !isObject( GuiWindowCollapseProfile ) ) new GuiControlProfile (GuiWindowCollapseProfile : GuiWindowProfile) { category = "Core"; }; if( !isObject( GuiControlProfile ) ) new GuiControlProfile (GuiContentProfile) { opaque = true; fillColor = "255 255 255"; category = "Core"; }; if( !isObject( GuiBlackContentProfile ) ) new GuiControlProfile (GuiBlackContentProfile) { opaque = true; fillColor = "0 0 0"; category = "Core"; }; if( !isObject( GuiInputCtrlProfile ) ) new GuiControlProfile( GuiInputCtrlProfile ) { tab = true; canKeyFocus = true; category = "Core"; }; if( !isObject( GuiTextProfile ) ) new GuiControlProfile (GuiTextProfile) { justify = "left"; fontColor = "20 20 20"; category = "Core"; }; if( !isObject( GuiTextBoldProfile ) ) new GuiControlProfile (GuiTextBoldProfile : GuiTextProfile) { fontType = "Arial Bold"; fontSize = 16; category = "Core"; }; if( !isObject( GuiTextBoldCenterProfile ) ) new GuiControlProfile (GuiTextBoldCenterProfile : GuiTextProfile) { fontColor = "50 50 50"; fontType = "Arial Bold"; fontSize = 16; justify = "center"; category = "Core"; }; if( !isObject( GuiTextRightProfile ) ) new GuiControlProfile (GuiTextRightProfile : GuiTextProfile) { justify = "right"; category = "Core"; }; if( !isObject( GuiTextCenterProfile ) ) new GuiControlProfile (GuiTextCenterProfile : GuiTextProfile) { justify = "center"; category = "Core"; }; if( !isObject( GuiTextSolidProfile ) ) new GuiControlProfile (GuiTextSolidProfile : GuiTextProfile) { opaque = true; border = 5; borderColor = GuiDefaultProfile.fillColor; category = "Core"; }; if( !isObject( InspectorTitleTextProfile ) ) new GuiControlProfile (InspectorTitleTextProfile) { fontColor = "100 100 100"; category = "Core"; }; if( !isObject( GuiTextProfileLight ) ) new GuiControlProfile (GuiTextProfileLight) { fontColor = "220 220 220"; category = "Core"; }; if( !isObject( GuiAutoSizeTextProfile ) ) new GuiControlProfile (GuiAutoSizeTextProfile) { fontColor = "0 0 0"; autoSizeWidth = true; autoSizeHeight = true; category = "Core"; }; if( !isObject( GuiTextRightProfile ) ) new GuiControlProfile (GuiTextRightProfile : GuiTextProfile) { justify = "right"; category = "Core"; }; if( !isObject( GuiMediumTextProfile ) ) new GuiControlProfile( GuiMediumTextProfile : GuiTextProfile ) { fontSize = 24; category = "Core"; }; if( !isObject( GuiBigTextProfile ) ) new GuiControlProfile( GuiBigTextProfile : GuiTextProfile ) { fontSize = 36; category = "Core"; }; if( !isObject( GuiMLTextProfile ) ) new GuiControlProfile( GuiMLTextProfile ) { fontColorLink = "100 100 100"; fontColorLinkHL = "255 255 255"; autoSizeWidth = true; autoSizeHeight = true; border = false; category = "Core"; }; if( !isObject( GuiTextArrayProfile ) ) new GuiControlProfile( GuiTextArrayProfile : GuiTextProfile ) { fontColor = "50 50 50"; fontColorHL = " 0 0 0"; fontColorSEL = "0 0 0"; fillColor ="200 200 200"; fillColorHL = "228 228 235"; fillColorSEL = "200 200 200"; border = false; category = "Core"; }; if( !isObject( GuiTextListProfile ) ) new GuiControlProfile( GuiTextListProfile : GuiTextProfile ) { tab = true; canKeyFocus = true; category = "Core"; }; if( !isObject( GuiTextEditProfile ) ) new GuiControlProfile( GuiTextEditProfile ) { opaque = true; bitmap = "./images/textEdit"; hasBitmapArray = true; border = -2; // fix to display textEdit img //borderWidth = "1"; // fix to display textEdit img //borderColor = "100 100 100"; fillColor = "242 241 240 0"; fillColorHL = "255 255 255"; fontColor = "0 0 0"; fontColorHL = "255 255 255"; fontColorSEL = "98 100 137"; fontColorNA = "200 200 200"; textOffset = "4 2"; autoSizeWidth = false; autoSizeHeight = true; justify = "left"; tab = true; canKeyFocus = true; category = "Core"; }; if( !isObject( GuiTreeViewRenameCtrlProfile ) ) new GuiControlProfile( GuiTreeViewRenameCtrlProfile : GuiTextEditProfile ) { returnTab = true; category = "Core"; }; if( !isObject( GuiTextEditProfileNumbersOnly ) ) new GuiControlProfile( GuiTextEditProfileNumbersOnly : GuiTextEditProfile ) { numbersOnly = true; category = "Core"; }; if( !isObject( GuiTextEditNumericProfile ) ) new GuiControlProfile( GuiTextEditNumericProfile : GuiTextEditProfile ) { numbersOnly = true; category = "Core"; }; if( !isObject( GuiNumericDropSliderTextProfile ) ) new GuiControlProfile( GuiNumericDropSliderTextProfile : GuiTextEditProfile ) { bitmap = "./images/textEditSliderBox"; category = "Core"; }; if( !isObject( GuiTextEditDropSliderNumbersOnly ) ) new GuiControlProfile( GuiTextEditDropSliderNumbersOnly : GuiTextEditProfile ) { numbersOnly = true; bitmap = "./images/textEditSliderBox"; category = "Core"; }; if( !isObject( GuiProgressProfile ) ) new GuiControlProfile( GuiProgressProfile ) { opaque = false; fillColor = "0 162 255 200"; border = true; borderColor = "50 50 50 200"; category = "Core"; }; if( !isObject( GuiProgressBitmapProfile ) ) new GuiControlProfile( GuiProgressBitmapProfile ) { border = false; hasBitmapArray = true; bitmap = "./images/loadingbar"; category = "Core"; }; if( !isObject( GuiRLProgressBitmapProfile ) ) new GuiControlProfile( GuiRLProgressBitmapProfile ) { border = false; hasBitmapArray = true; bitmap = "./images/rl-loadingbar"; category = "Core"; }; if( !isObject( GuiProgressTextProfile ) ) new GuiControlProfile( GuiProgressTextProfile ) { fontSize = "14"; fontType = "Arial"; fontColor = "0 0 0"; justify = "center"; category = "Core"; }; if( !isObject( GuiButtonProfile ) ) new GuiControlProfile( GuiButtonProfile ) { opaque = true; border = true; fontColor = "50 50 50"; fontColorHL = "0 0 0"; fontColorNA = "200 200 200"; //fontColorSEL ="0 0 0"; fixedExtent = false; justify = "center"; canKeyFocus = false; bitmap = "./images/button"; hasBitmapArray = false; category = "Core"; }; if( !isObject( GuiThumbHighlightButtonProfile ) ) new GuiControlProfile( GuiThumbHighlightButtonProfile : GuiButtonProfile ) { bitmap = "./images/thumbHightlightButton"; category = "Core"; }; if( !isObject( InspectorDynamicFieldButton ) ) new GuiControlProfile( InspectorDynamicFieldButton : GuiButtonProfile ) { canKeyFocus = true; category = "Core"; }; if( !isObject( GuiMenuButtonProfile ) ) new GuiControlProfile( GuiMenuButtonProfile ) { opaque = true; border = false; fontSize = 18; fontType = "Arial Bold"; fontColor = "50 50 50"; fontColorHL = "0 0 0"; fontColorNA = "200 200 200"; //fontColorSEL ="0 0 0"; fixedExtent = false; justify = "center"; canKeyFocus = false; bitmap = "./images/selector-button"; hasBitmapArray = false; category = "Core"; }; if( !isObject( GuiIconButtonProfile ) ) new GuiControlProfile( GuiIconButtonProfile ) { opaque = true; border = true; fontColor = "50 50 50"; fontColorHL = "0 0 0"; fontColorNA = "200 200 200"; //fontColorSEL ="0 0 0"; fixedExtent = false; justify = "center"; canKeyFocus = false; bitmap = "./images/iconbutton"; hasBitmapArray = true; category = "Core"; }; if( !isObject( GuiIconButtonSolidProfile ) ) new GuiControlProfile( GuiIconButtonSolidProfile : GuiIconButtonProfile ) { bitmap = "./images/iconbuttonsolid"; category = "Core"; }; if( !isObject( GuiIconButtonSmallProfile ) ) new GuiControlProfile( GuiIconButtonSmallProfile : GuiIconButtonProfile ) { bitmap = "./images/iconbuttonsmall"; category = "Core"; }; if( !isObject( GuiButtonTabProfile ) ) new GuiControlProfile( GuiButtonTabProfile ) { opaque = true; border = true; fontColor = "50 50 50"; fontColorHL = "0 0 0"; fontColorNA = "0 0 0"; //fontColorSEL ="0 0 0"; fixedExtent = false; justify = "center"; canKeyFocus = false; bitmap = "./images/buttontab"; // hasBitmapArray = false; category = "Core"; }; if( !isObject( EditorTabPage ) ) new GuiControlProfile(EditorTabPage) { opaque = true; border = false; //fontSize = 18; //fontType = "Arial"; fontColor = "0 0 0"; fontColorHL = "0 0 0"; fixedExtent = false; justify = "center"; canKeyFocus = false; bitmap = "./images/tab"; hasBitmapArray = true; //false; category = "Core"; }; if( !isObject( GuiCheckBoxProfile ) ) new GuiControlProfile( GuiCheckBoxProfile ) { opaque = false; fillColor = "232 232 232"; border = false; borderColor = "100 100 100"; fontSize = 14; fontColor = "20 20 20"; fontColorHL = "80 80 80"; fontColorNA = "200 200 200"; fixedExtent = true; justify = "left"; bitmap = "./images/checkbox"; hasBitmapArray = true; category = "Core"; }; if( !isObject( GuiCheckBoxListProfile ) ) new GuiControlProfile( GuiCheckBoxListProfile : GuiCheckBoxProfile) { bitmap = "./images/checkbox-list"; category = "Core"; }; if( !isObject( GuiCheckBoxListFlipedProfile ) ) new GuiControlProfile( GuiCheckBoxListFlipedProfile : GuiCheckBoxProfile) { bitmap = "./images/checkbox-list_fliped"; category = "Core"; }; if( !isObject( InspectorCheckBoxTitleProfile ) ) new GuiControlProfile( InspectorCheckBoxTitleProfile : GuiCheckBoxProfile ){ fontColor = "100 100 100"; category = "Core"; }; if( !isObject( GuiRadioProfile ) ) new GuiControlProfile( GuiRadioProfile ) { fontSize = 14; fillColor = "232 232 232"; /*fontColor = "200 200 200"; fontColorHL = "255 255 255";*/ fontColor = "20 20 20"; fontColorHL = "80 80 80"; fixedExtent = true; bitmap = "./images/radioButton"; hasBitmapArray = true; category = "Core"; }; if( !isObject( GuiScrollProfile ) ) new GuiControlProfile( GuiScrollProfile ) { opaque = true; fillcolor = "255 255 255"; fontColor = "0 0 0"; fontColorHL = "150 150 150"; //borderColor = GuiDefaultProfile.borderColor; border = true; bitmap = "./images/scrollBar"; hasBitmapArray = true; category = "Core"; }; if( !isObject( GuiOverlayProfile ) ) new GuiControlProfile( GuiOverlayProfile ) { opaque = true; fillcolor = "255 255 255"; fontColor = "0 0 0"; fontColorHL = "255 255 255"; fillColor = "0 0 0 100"; category = "Core"; }; if( !isObject( GuiTransparentScrollProfile ) ) new GuiControlProfile( GuiTransparentScrollProfile ) { opaque = false; fillColor = "255 255 255"; fontColor = "0 0 0"; border = false; borderThickness = 2; borderColor = "100 100 100"; bitmap = "./images/scrollBar"; hasBitmapArray = true; category = "Core"; }; if( !isObject( GuiSliderProfile ) ) new GuiControlProfile( GuiSliderProfile ) { bitmap = "./images/slider"; category = "Core"; }; if( !isObject( GuiSliderBoxProfile ) ) new GuiControlProfile( GuiSliderBoxProfile ) { bitmap = "./images/slider-w-box"; category = "Core"; }; if( !isObject( GuiPaneProfile ) ) new GuiControlProfile( GuiPaneProfile ) { bitmap = "./images/popupMenu"; hasBitmapArray = true; category = "Core"; }; if( !isObject( GuiPopupMenuItemBorder ) ) new GuiControlProfile( GuiPopupMenuItemBorder : GuiButtonProfile ) { // borderThickness = 1; //borderColor = "100 100 100 220"; //200 //borderColorHL = "51 51 51 220"; //200 opaque = true; border = true; fontColor = "0 0 0"; fontColorHL = "0 0 0"; fontColorNA = "255 255 255"; fixedExtent = false; justify = "center"; canKeyFocus = false; bitmap = "./images/button"; // hasBitmapArray = false; category = "Core"; }; if( !isObject( GuiPopUpMenuDefault ) ) new GuiControlProfile( GuiPopUpMenuDefault : GuiDefaultProfile ) { opaque = true; mouseOverSelected = true; textOffset = "3 3"; border = 0; borderThickness = 0; fixedExtent = true; bitmap = "./images/scrollbar"; hasBitmapArray = true; profileForChildren = GuiPopupMenuItemBorder; fillColor = "242 241 240 ";//"255 255 255";//100 fillColorHL = "228 228 235 ";//"204 203 202"; fillColorSEL = "98 100 137 ";//"204 203 202"; // font color is black fontColorHL = "0 0 0 ";//"0 0 0"; fontColorSEL = "255 255 255";//"0 0 0"; borderColor = "100 100 100"; category = "Core"; }; if( !isObject( GuiPopupBackgroundProfile ) ) new GuiControlProfile( GuiPopupBackgroundProfile ) { modal = true; category = "Core"; }; if( !isObject( GuiPopUpMenuProfile ) ) new GuiControlProfile( GuiPopUpMenuProfile : GuiPopUpMenuDefault ) { textOffset = "6 4"; bitmap = "./images/dropDown"; hasBitmapArray = true; border = 1; profileForChildren = GuiPopUpMenuDefault; category = "Core"; }; if( !isObject( GuiPopUpMenuTabProfile ) ) new GuiControlProfile( GuiPopUpMenuTabProfile : GuiPopUpMenuDefault ) { bitmap = "./images/dropDown-tab"; textOffset = "6 4"; canKeyFocus = true; hasBitmapArray = true; border = 1; profileForChildren = GuiPopUpMenuDefault; category = "Core"; }; if( !isObject( GuiPopUpMenuEditProfile ) ) new GuiControlProfile( GuiPopUpMenuEditProfile : GuiPopUpMenuDefault ) { textOffset = "6 4"; canKeyFocus = true; bitmap = "./images/dropDown"; hasBitmapArray = true; border = 1; profileForChildren = GuiPopUpMenuDefault; category = "Core"; }; if( !isObject( GuiListBoxProfile ) ) new GuiControlProfile( GuiListBoxProfile ) { tab = true; canKeyFocus = true; category = "Core"; }; if( !isObject( GuiTabBookProfile ) ) new GuiControlProfile( GuiTabBookProfile ) { fillColorHL = "100 100 100"; fillColorNA = "150 150 150"; fontColor = "30 30 30"; fontColorHL = "0 0 0"; fontColorNA = "50 50 50"; fontType = "Arial"; fontSize = 14; justify = "center"; bitmap = "./images/tab"; tabWidth = 64; tabHeight = 24; tabPosition = "Top"; tabRotation = "Horizontal"; textOffset = "0 -3"; tab = true; cankeyfocus = true; //border = false; //opaque = false; category = "Core"; }; if( !isObject( GuiTabBookNoBitmapProfile ) ) new GuiControlProfile( GuiTabBookNoBitmapProfile : GuiTabBookProfile ) { bitmap = ""; category = "Core"; }; if( !isObject( GuiTabPageProfile ) ) new GuiControlProfile( GuiTabPageProfile : GuiDefaultProfile ) { fontType = "Arial"; fontSize = 10; justify = "center"; bitmap = "./images/tab"; opaque = false; fillColor = "240 239 238"; category = "Core"; }; if( !isObject( GuiMenuBarProfile ) ) new GuiControlProfile( GuiMenuBarProfile ) { fontType = "Arial"; fontSize = 14; opaque = true; fillColor = "240 239 238"; fillColorHL = "202 201 200"; fillColorSEL = "202 0 0"; borderColorNA = "202 201 200"; borderColorHL = "50 50 50"; border = 0; fontColor = "20 20 20"; fontColorHL = "0 0 0"; fontColorNA = "255 255 255"; //fixedExtent = true; justify = "center"; canKeyFocus = false; mouseOverSelected = true; bitmap = "./images/menu"; hasBitmapArray = true; category = "Core"; }; if( !isObject( GuiConsoleProfile ) ) new GuiControlProfile( GuiConsoleProfile ) { fontType = ($platform $= "macos") ? "Monaco" : "Lucida Console"; fontSize = ($platform $= "macos") ? 13 : 12; fontColor = "255 255 255"; fontColorHL = "0 255 255"; fontColorNA = "255 0 0"; fontColors[6] = "100 100 100"; fontColors[7] = "100 100 0"; fontColors[8] = "0 0 100"; fontColors[9] = "0 100 0"; category = "Core"; }; if( !isObject( GuiConsoleTextEditProfile ) ) new GuiControlProfile( GuiConsoleTextEditProfile : GuiTextEditProfile ) { fontType = ($platform $= "macos") ? "Monaco" : "Lucida Console"; fontSize = ($platform $= "macos") ? 13 : 12; category = "Core"; }; if( !isObject( GuiConsoleTextProfile ) ) new GuiControlProfile( GuiConsoleTextProfile ) { fontColor = "0 0 0"; autoSizeWidth = true; autoSizeHeight = true; textOffset = "2 2"; opaque = true; fillColor = "255 255 255"; border = true; borderThickness = 1; borderColor = "0 0 0"; category = "Core"; }; if( !isObject( GuiTreeViewProfile ) ) new GuiControlProfile( GuiTreeViewProfile ) { bitmap = "./images/treeView"; autoSizeHeight = true; canKeyFocus = true; fillColor = "255 255 255"; //GuiDefaultProfile.fillColor; fillColorHL = "228 228 235";//GuiDefaultProfile.fillColorHL; fillColorSEL = "98 100 137"; fillColorNA = "255 255 255";//GuiDefaultProfile.fillColorNA; fontColor = "0 0 0";//GuiDefaultProfile.fontColor; fontColorHL = "0 0 0";//GuiDefaultProfile.fontColorHL; fontColorSEL= "255 255 255";//GuiDefaultProfile.fontColorSEL; fontColorNA = "200 200 200";//GuiDefaultProfile.fontColorNA; borderColor = "128 000 000"; borderColorHL = "255 228 235"; fontSize = 14; opaque = false; border = false; category = "Core"; }; if( !isObject( GuiSimpleTreeProfile ) ) new GuiControlProfile( GuiSimpleTreeProfile : GuiTreeViewProfile ) { opaque = true; fillColor = "255 255 255 255"; border = true; category = "Core"; }; if( !isObject( GuiText24Profile ) ) new GuiControlProfile( GuiText24Profile : GuiTextProfile ) { fontSize = 24; category = "Core"; }; if( !isObject( GuiRSSFeedMLTextProfile ) ) new GuiControlProfile( GuiRSSFeedMLTextProfile ) { fontColorLink = "55 55 255"; fontColorLinkHL = "255 55 55"; category = "Core"; }; $ConsoleDefaultFillColor = "0 0 0 175"; if( !isObject( ConsoleScrollProfile ) ) new GuiControlProfile( ConsoleScrollProfile : GuiScrollProfile ) { opaque = true; fillColor = $ConsoleDefaultFillColor; border = 1; //borderThickness = 0; borderColor = "0 0 0"; category = "Core"; }; if( !isObject( ConsoleTextEditProfile ) ) new GuiControlProfile( ConsoleTextEditProfile : GuiTextEditProfile ) { fillColor = "242 241 240 255"; fillColorHL = "255 255 255"; category = "Core"; }; if( !isObject( GuiTextPadProfile ) ) new GuiControlProfile( GuiTextPadProfile ) { fontType = ($platform $= "macos") ? "Monaco" : "Lucida Console"; fontSize = ($platform $= "macos") ? 13 : 12; tab = true; canKeyFocus = true; // Deviate from the Default opaque=true; fillColor = "255 255 255"; border = 0; category = "Core"; }; if( !isObject( GuiTransparentProfileModeless ) ) new GuiControlProfile( GuiTransparentProfileModeless : GuiTransparentProfile ) { modal = false; category = "Core"; }; if( !isObject( GuiFormProfile ) ) new GuiControlProfile( GuiFormProfile : GuiTextProfile ) { opaque = false; border = 5; bitmap = "./images/form"; hasBitmapArray = true; justify = "center"; profileForChildren = GuiButtonProfile; // border color opaque = false; //border = 5; bitmap = "./images/button"; // borderColor = "153 153 153"; // borderColorHL = "230 230 230"; // borderColorNA = "126 79 37"; category = "Core"; }; if( !isObject( GuiNumericTextEditSliderProfile ) ) new GuiControlProfile( GuiNumericTextEditSliderProfile ) { // Transparent Background opaque = true; fillColor = "0 0 0 0"; fillColorHL = "255 255 255"; border = true; tab = false; canKeyFocus = true; // font fontType = "Arial"; fontSize = 14; fontColor = "0 0 0"; fontColorSEL = "43 107 206"; fontColorHL = "244 244 244"; fontColorNA = "100 100 100"; numbersOnly = true; category = "Core"; }; if( !isObject( GuiNumericTextEditSliderBitmapProfile ) ) new GuiControlProfile( GuiNumericTextEditSliderBitmapProfile ) { // Transparent Background opaque = true; border = true; borderColor = "100 100 100"; tab = false; canKeyFocus = true; // font fontType = "Arial"; fontSize = 14; fillColor = "242 241 240";//"255 255 255"; fillColorHL = "255 255 255";//"222 222 222"; fontColor = "0 0 0";//"0 0 0"; fontColorHL = "255 255 255";//"0 0 0"; fontColorSEL = "98 100 137";//"230 230 230"; fontColorNA = "200 200 200";//"0 0 0"; numbersOnly = true; hasBitmapArray = true; bitmap = "./images/numericslider"; category = "Core"; }; if( !isObject( GuiMultiFieldTextEditProfile ) ) new GuiControlProfile( GuiMultiFieldTextEditProfile : GuiTextEditProfile ) { category = "Core"; }; if( !isObject( GuiModalDialogBackgroundProfile ) ) new GuiControlProfile( GuiModalDialogBackgroundProfile ) { opaque = true; fillColor = "221 221 221 150"; category = "Core"; }; //----------------------------------------------------------------------------- // Center and bottom print //----------------------------------------------------------------------------- if( !isObject( CenterPrintProfile ) ) new GuiControlProfile ( CenterPrintProfile ) { opaque = false; fillColor = "128 128 128"; fontColor = "0 255 0"; border = true; borderColor = "0 255 0"; category = "Core"; }; if( !isObject( CenterPrintTextProfile ) ) new GuiControlProfile ( CenterPrintTextProfile ) { opaque = false; fontType = "Arial"; fontSize = 12; fontColor = "0 255 0"; category = "Core"; };
// 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 Microsoft.Win32.SafeHandles; using System; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Text; namespace System.Security.Principal { // // Identifier authorities // internal enum IdentifierAuthority : long { NullAuthority = 0, WorldAuthority = 1, LocalAuthority = 2, CreatorAuthority = 3, NonUniqueAuthority = 4, NTAuthority = 5, SiteServerAuthority = 6, InternetSiteAuthority = 7, ExchangeAuthority = 8, ResourceManagerAuthority = 9, } // // SID name usage // internal enum SidNameUse { User = 1, Group = 2, Domain = 3, Alias = 4, WellKnownGroup = 5, DeletedAccount = 6, Invalid = 7, Unknown = 8, Computer = 9, } // // Well-known SID types // public enum WellKnownSidType { /// <summary>Indicates a null SID.</summary> NullSid = 0, /// <summary>Indicates a SID that matches everyone.</summary> WorldSid = 1, /// <summary>Indicates a local SID.</summary> LocalSid = 2, /// <summary>Indicates a SID that matches the owner or creator of an object.</summary> CreatorOwnerSid = 3, /// <summary>Indicates a SID that matches the creator group of an object.</summary> CreatorGroupSid = 4, /// <summary>Indicates a creator owner server SID.</summary> CreatorOwnerServerSid = 5, /// <summary>Indicates a creator group server SID.</summary> CreatorGroupServerSid = 6, /// <summary>Indicates a SID for the Windows NT authority account.</summary> NTAuthoritySid = 7, /// <summary>Indicates a SID for a dial-up account.</summary> DialupSid = 8, /// <summary>Indicates a SID for a network account. This SID is added to the process of a token when it logs on across a network.</summary> NetworkSid = 9, /// <summary>Indicates a SID for a batch process. This SID is added to the process of a token when it logs on as a batch job.</summary> BatchSid = 10, /// <summary>Indicates a SID for an interactive account. This SID is added to the process of a token when it logs on interactively.</summary> InteractiveSid = 11, /// <summary>Indicates a SID for a service. This SID is added to the process of a token when it logs on as a service.</summary> ServiceSid = 12, /// <summary>Indicates a SID for the anonymous account.</summary> AnonymousSid = 13, /// <summary>Indicates a proxy SID.</summary> ProxySid = 14, /// <summary>Indicates a SID for an enterprise controller.</summary> EnterpriseControllersSid = 15, /// <summary>Indicates a SID for self.</summary> SelfSid = 16, /// <summary>Indicates a SID that matches any authenticated user.</summary> AuthenticatedUserSid = 17, /// <summary>Indicates a SID for restricted code.</summary> RestrictedCodeSid = 18, /// <summary>Indicates a SID that matches a terminal server account.</summary> TerminalServerSid = 19, /// <summary>Indicates a SID that matches remote logons.</summary> RemoteLogonIdSid = 20, /// <summary>Indicates a SID that matches logon IDs.</summary> LogonIdsSid = 21, /// <summary>Indicates a SID that matches the local system.</summary> LocalSystemSid = 22, /// <summary>Indicates a SID that matches a local service.</summary> LocalServiceSid = 23, /// <summary>Indicates a SID that matches a network service.</summary> NetworkServiceSid = 24, /// <summary>Indicates a SID that matches the domain account.</summary> BuiltinDomainSid = 25, /// <summary>Indicates a SID that matches the administrator group.</summary> BuiltinAdministratorsSid = 26, /// <summary>Indicates a SID that matches built-in user accounts.</summary> BuiltinUsersSid = 27, /// <summary>Indicates a SID that matches the guest account.</summary> BuiltinGuestsSid = 28, /// <summary>Indicates a SID that matches the power users group.</summary> BuiltinPowerUsersSid = 29, /// <summary>Indicates a SID that matches the account operators account.</summary> BuiltinAccountOperatorsSid = 30, /// <summary>Indicates a SID that matches the system operators group.</summary> BuiltinSystemOperatorsSid = 31, /// <summary>Indicates a SID that matches the print operators group.</summary> BuiltinPrintOperatorsSid = 32, /// <summary>Indicates a SID that matches the backup operators group.</summary> BuiltinBackupOperatorsSid = 33, /// <summary>Indicates a SID that matches the replicator account.</summary> BuiltinReplicatorSid = 34, /// <summary>Indicates a SID that matches pre-Windows 2000 compatible accounts.</summary> BuiltinPreWindows2000CompatibleAccessSid = 35, /// <summary>Indicates a SID that matches remote desktop users.</summary> BuiltinRemoteDesktopUsersSid = 36, /// <summary>Indicates a SID that matches the network operators group.</summary> BuiltinNetworkConfigurationOperatorsSid = 37, /// <summary>Indicates a SID that matches the account administrator's account.</summary> AccountAdministratorSid = 38, /// <summary>Indicates a SID that matches the account guest group.</summary> AccountGuestSid = 39, /// <summary>Indicates a SID that matches account Kerberos target group.</summary> AccountKrbtgtSid = 40, /// <summary>Indicates a SID that matches the account domain administrator group.</summary> AccountDomainAdminsSid = 41, /// <summary>Indicates a SID that matches the account domain users group.</summary> AccountDomainUsersSid = 42, /// <summary>Indicates a SID that matches the account domain guests group.</summary> AccountDomainGuestsSid = 43, /// <summary>Indicates a SID that matches the account computer group.</summary> AccountComputersSid = 44, /// <summary>Indicates a SID that matches the account controller group.</summary> AccountControllersSid = 45, /// <summary>Indicates a SID that matches the certificate administrators group.</summary> AccountCertAdminsSid = 46, /// <summary>Indicates a SID that matches the schema administrators group.</summary> AccountSchemaAdminsSid = 47, /// <summary>Indicates a SID that matches the enterprise administrators group.</summary> AccountEnterpriseAdminsSid = 48, /// <summary>Indicates a SID that matches the policy administrators group.</summary> AccountPolicyAdminsSid = 49, /// <summary>Indicates a SID that matches the RAS and IAS server account.</summary> AccountRasAndIasServersSid = 50, /// <summary>Indicates a SID present when the Microsoft NTLM authentication package authenticated the client.</summary> NtlmAuthenticationSid = 51, /// <summary>Indicates a SID present when the Microsoft Digest authentication package authenticated the client.</summary> DigestAuthenticationSid = 52, /// <summary>Indicates a SID present when the Secure Channel (SSL/TLS) authentication package authenticated the client.</summary> SChannelAuthenticationSid = 53, /// <summary>Indicates a SID present when the user authenticated from within the forest or across a trust that does not have the selective authentication option enabled. If this SID is present, then <see cref="WinOtherOrganizationSid"/> cannot be present.</summary> ThisOrganizationSid = 54, /// <summary>Indicates a SID present when the user authenticated across a forest with the selective authentication option enabled. If this SID is present, then <see cref="WinThisOrganizationSid"/> cannot be present.</summary> OtherOrganizationSid = 55, /// <summary>Indicates a SID that allows a user to create incoming forest trusts. It is added to the token of users who are a member of the Incoming Forest Trust Builders built-in group in the root domain of the forest.</summary> BuiltinIncomingForestTrustBuildersSid = 56, /// <summary>Indicates a SID that matches the performance monitor user group.</summary> BuiltinPerformanceMonitoringUsersSid = 57, /// <summary>Indicates a SID that matches the performance log user group.</summary> BuiltinPerformanceLoggingUsersSid = 58, /// <summary>Indicates a SID that matches the Windows Authorization Access group.</summary> BuiltinAuthorizationAccessSid = 59, /// <summary>Indicates a SID is present in a server that can issue terminal server licenses.</summary> WinBuiltinTerminalServerLicenseServersSid = 60, [Obsolete("This member has been depcreated and is only maintained for backwards compatability. WellKnownSidType values greater than MaxDefined may be defined in future releases.")] [EditorBrowsable(EditorBrowsableState.Never)] MaxDefined = WinBuiltinTerminalServerLicenseServersSid, /// <summary>Indicates a SID that matches the distributed COM user group.</summary> WinBuiltinDCOMUsersSid = 61, /// <summary>Indicates a SID that matches the Internet built-in user group.</summary> WinBuiltinIUsersSid = 62, /// <summary>Indicates a SID that matches the Internet user group.</summary> WinIUserSid = 63, /// <summary>Indicates a SID that allows a user to use cryptographic operations. It is added to the token of users who are a member of the CryptoOperators built-in group. </summary> WinBuiltinCryptoOperatorsSid = 64, /// <summary>Indicates a SID that matches an untrusted label.</summary> WinUntrustedLabelSid = 65, /// <summary>Indicates a SID that matches an low level of trust label.</summary> WinLowLabelSid = 66, /// <summary>Indicates a SID that matches an medium level of trust label.</summary> WinMediumLabelSid = 67, /// <summary>Indicates a SID that matches a high level of trust label.</summary> WinHighLabelSid = 68, /// <summary>Indicates a SID that matches a system label.</summary> WinSystemLabelSid = 69, /// <summary>Indicates a SID that matches a write restricted code group.</summary> WinWriteRestrictedCodeSid = 70, /// <summary>Indicates a SID that matches a creator and owner rights group.</summary> WinCreatorOwnerRightsSid = 71, /// <summary>Indicates a SID that matches a cacheable principals group.</summary> WinCacheablePrincipalsGroupSid = 72, /// <summary>Indicates a SID that matches a non-cacheable principals group.</summary> WinNonCacheablePrincipalsGroupSid = 73, /// <summary>Indicates a SID that matches an enterprise wide read-only controllers group.</summary> WinEnterpriseReadonlyControllersSid = 74, /// <summary>Indicates a SID that matches an account read-only controllers group.</summary> WinAccountReadonlyControllersSid = 75, /// <summary>Indicates a SID that matches an event log readers group.</summary> WinBuiltinEventLogReadersGroup = 76, /// <summary>Indicates a SID that matches a read-only enterprise domain controller.</summary> WinNewEnterpriseReadonlyControllersSid = 77, /// <summary>Indicates a SID that matches the built-in DCOM certification services access group.</summary> WinBuiltinCertSvcDComAccessGroup = 78, /// <summary>Indicates a SID that matches the medium plus integrity label.</summary> WinMediumPlusLabelSid = 79, /// <summary>Indicates a SID that matches a local logon group.</summary> WinLocalLogonSid = 80, /// <summary>Indicates a SID that matches a console logon group.</summary> WinConsoleLogonSid = 81, /// <summary>Indicates a SID that matches a certificate for the given organization.</summary> WinThisOrganizationCertificateSid = 82, /// <summary>Indicates a SID that matches the application package authority.</summary> WinApplicationPackageAuthoritySid = 83, /// <summary>Indicates a SID that applies to all app containers.</summary> WinBuiltinAnyPackageSid = 84, /// <summary>Indicates a SID of Internet client capability for app containers.</summary> WinCapabilityInternetClientSid = 85, /// <summary>Indicates a SID of Internet client and server capability for app containers.</summary> WinCapabilityInternetClientServerSid = 86, /// <summary>Indicates a SID of private network client and server capability for app containers.</summary> WinCapabilityPrivateNetworkClientServerSid = 87, /// <summary>Indicates a SID for pictures library capability for app containers.</summary> WinCapabilityPicturesLibrarySid = 88, /// <summary>Indicates a SID for videos library capability for app containers.</summary> WinCapabilityVideosLibrarySid = 89, /// <summary>Indicates a SID for music library capability for app containers.</summary> WinCapabilityMusicLibrarySid = 90, /// <summary>Indicates a SID for documents library capability for app containers.</summary> WinCapabilityDocumentsLibrarySid = 91, /// <summary>Indicates a SID for shared user certificates capability for app containers.</summary> WinCapabilitySharedUserCertificatesSid = 92, /// <summary>Indicates a SID for Windows credentials capability for app containers.</summary> WinCapabilityEnterpriseAuthenticationSid = 93, /// <summary>Indicates a SID for removable storage capability for app containers.</summary> WinCapabilityRemovableStorageSid = 94 // Note: Adding additional values require changes everywhere where the value above is used as the maximum defined WellKnownSidType value. // E.g. System.Security.Principal.SecurityIdentifier constructor } // // This class implements revision 1 SIDs // NOTE: The SecurityIdentifier class is immutable and must remain this way // public sealed class SecurityIdentifier : IdentityReference, IComparable<SecurityIdentifier> { #region Public Constants // // Identifier authority must be at most six bytes long // internal static readonly long MaxIdentifierAuthority = 0xFFFFFFFFFFFF; // // Maximum number of subauthorities in a SID // internal static readonly byte MaxSubAuthorities = 15; // // Minimum length of a binary representation of a SID // public static readonly int MinBinaryLength = 1 + 1 + 6; // Revision (1) + subauth count (1) + identifier authority (6) // // Maximum length of a binary representation of a SID // public static readonly int MaxBinaryLength = 1 + 1 + 6 + MaxSubAuthorities * 4; // 4 bytes for each subauth #endregion #region Private Members // // Immutable properties of a SID // private IdentifierAuthority _identifierAuthority; private int[] _subAuthorities; private byte[] _binaryForm; private SecurityIdentifier _accountDomainSid; private bool _accountDomainSidInitialized = false; // // Computed attributes of a SID // private string _sddlForm = null; #endregion #region Constructors // // Shared constructor logic // NOTE: subauthorities are really unsigned integers, but due to CLS // lack of support for unsigned integers the caller must perform // the typecast // private void CreateFromParts(IdentifierAuthority identifierAuthority, int[] subAuthorities) { if (subAuthorities == null) { throw new ArgumentNullException(nameof(subAuthorities)); } // // Check the number of subauthorities passed in // if (subAuthorities.Length > MaxSubAuthorities) { throw new ArgumentOutOfRangeException( "subAuthorities.Length", subAuthorities.Length, SR.Format(SR.IdentityReference_InvalidNumberOfSubauthorities, MaxSubAuthorities)); } // // Identifier authority is at most 6 bytes long // if (identifierAuthority < 0 || (long)identifierAuthority > MaxIdentifierAuthority) { throw new ArgumentOutOfRangeException( nameof(identifierAuthority), identifierAuthority, SR.IdentityReference_IdentifierAuthorityTooLarge); } // // Create a local copy of the data passed in // _identifierAuthority = identifierAuthority; _subAuthorities = new int[subAuthorities.Length]; subAuthorities.CopyTo(_subAuthorities, 0); // // Compute and store the binary form // // typedef struct _SID { // UCHAR Revision; // UCHAR SubAuthorityCount; // SID_IDENTIFIER_AUTHORITY IdentifierAuthority; // ULONG SubAuthority[ANYSIZE_ARRAY] // } SID, *PISID; // byte i; _binaryForm = new byte[1 + 1 + 6 + 4 * this.SubAuthorityCount]; // // First two bytes contain revision and subauthority count // _binaryForm[0] = Revision; _binaryForm[1] = (byte)this.SubAuthorityCount; // // Identifier authority takes up 6 bytes // for (i = 0; i < 6; i++) { _binaryForm[2 + i] = (byte)((((ulong)_identifierAuthority) >> ((5 - i) * 8)) & 0xFF); } // // Subauthorities go last, preserving big-endian representation // for (i = 0; i < this.SubAuthorityCount; i++) { byte shift; for (shift = 0; shift < 4; shift += 1) { _binaryForm[8 + 4 * i + shift] = unchecked((byte)(((ulong)_subAuthorities[i]) >> (shift * 8))); } } } private void CreateFromBinaryForm(byte[] binaryForm, int offset) { // // Give us something to work with // if (binaryForm == null) { throw new ArgumentNullException(nameof(binaryForm)); } // // Negative offsets are not allowed // if (offset < 0) { throw new ArgumentOutOfRangeException( nameof(offset), offset, SR.ArgumentOutOfRange_NeedNonNegNum); } // // At least a minimum-size SID should fit in the buffer // if (binaryForm.Length - offset < SecurityIdentifier.MinBinaryLength) { throw new ArgumentOutOfRangeException( nameof(binaryForm), SR.ArgumentOutOfRange_ArrayTooSmall); } IdentifierAuthority Authority; int[] SubAuthorities; // // Extract the elements of a SID // if (binaryForm[offset] != Revision) { // // Revision is incorrect // throw new ArgumentException( SR.IdentityReference_InvalidSidRevision, nameof(binaryForm)); } // // Insist on the correct number of subauthorities // if (binaryForm[offset + 1] > MaxSubAuthorities) { throw new ArgumentException( SR.Format(SR.IdentityReference_InvalidNumberOfSubauthorities, MaxSubAuthorities), nameof(binaryForm)); } // // Make sure the buffer is big enough // int Length = 1 + 1 + 6 + 4 * binaryForm[offset + 1]; if (binaryForm.Length - offset < Length) { throw new ArgumentException( SR.ArgumentOutOfRange_ArrayTooSmall, nameof(binaryForm)); } Authority = (IdentifierAuthority)( (((long)binaryForm[offset + 2]) << 40) + (((long)binaryForm[offset + 3]) << 32) + (((long)binaryForm[offset + 4]) << 24) + (((long)binaryForm[offset + 5]) << 16) + (((long)binaryForm[offset + 6]) << 8) + (((long)binaryForm[offset + 7]))); SubAuthorities = new int[binaryForm[offset + 1]]; // // Subauthorities are represented in big-endian format // for (byte i = 0; i < binaryForm[offset + 1]; i++) { unchecked { SubAuthorities[i] = (int)( (((uint)binaryForm[offset + 8 + 4 * i + 0]) << 0) + (((uint)binaryForm[offset + 8 + 4 * i + 1]) << 8) + (((uint)binaryForm[offset + 8 + 4 * i + 2]) << 16) + (((uint)binaryForm[offset + 8 + 4 * i + 3]) << 24)); } } CreateFromParts(Authority, SubAuthorities); return; } // // Constructs a SecurityIdentifier object from its string representation // Returns 'null' if string passed in is not a valid SID // NOTE: although there is a P/Invoke call involved in the implementation of this method, // there is no security risk involved, so no security demand is being made. // public SecurityIdentifier(string sddlForm) { byte[] resultSid; // // Give us something to work with // if (sddlForm == null) { throw new ArgumentNullException(nameof(sddlForm)); } // // Call into the underlying O/S conversion routine // int Error = Win32.CreateSidFromString(sddlForm, out resultSid); if (Error == Interop.Errors.ERROR_INVALID_SID) { throw new ArgumentException(SR.Argument_InvalidValue, nameof(sddlForm)); } else if (Error == Interop.Errors.ERROR_NOT_ENOUGH_MEMORY) { throw new OutOfMemoryException(); } else if (Error != Interop.Errors.ERROR_SUCCESS) { Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.CreateSidFromString returned unrecognized error {0}", Error)); throw new Win32Exception(Error); } CreateFromBinaryForm(resultSid, 0); } // // Constructs a SecurityIdentifier object from its binary representation // public SecurityIdentifier(byte[] binaryForm, int offset) { CreateFromBinaryForm(binaryForm, offset); } // // Constructs a SecurityIdentifier object from an IntPtr // public SecurityIdentifier(IntPtr binaryForm) : this(binaryForm, true) { } internal SecurityIdentifier(IntPtr binaryForm, bool noDemand) : this(Win32.ConvertIntPtrSidToByteArraySid(binaryForm), 0) { } // // Constructs a well-known SID // The 'domainSid' parameter is optional and only used // by the well-known types that require it // NOTE: although there is a P/Invoke call involved in the implementation of this constructor, // there is no security risk involved, so no security demand is being made. // public SecurityIdentifier(WellKnownSidType sidType, SecurityIdentifier domainSid) { // // sidType must not be equal to LogonIdsSid // if (sidType == WellKnownSidType.LogonIdsSid) { throw new ArgumentException(SR.IdentityReference_CannotCreateLogonIdsSid, nameof(sidType)); } byte[] resultSid; int Error; // // sidType should not exceed the max defined value // if ((sidType < WellKnownSidType.NullSid) || (sidType > WellKnownSidType.WinCapabilityRemovableStorageSid)) { throw new ArgumentException(SR.Argument_InvalidValue, nameof(sidType)); } // // for sidType between 38 to 50, the domainSid parameter must be specified // if ((sidType >= WellKnownSidType.AccountAdministratorSid) && (sidType <= WellKnownSidType.AccountRasAndIasServersSid)) { if (domainSid == null) { throw new ArgumentNullException(nameof(domainSid), SR.Format(SR.IdentityReference_DomainSidRequired, sidType)); } // // verify that the domain sid is a valid windows domain sid // to do that we call GetAccountDomainSid and the return value should be the same as the domainSid // SecurityIdentifier resultDomainSid; int ErrorCode; ErrorCode = Win32.GetWindowsAccountDomainSid(domainSid, out resultDomainSid); if (ErrorCode == Interop.Errors.ERROR_INSUFFICIENT_BUFFER) { throw new OutOfMemoryException(); } else if (ErrorCode == Interop.Errors.ERROR_NON_ACCOUNT_SID) { // this means that the domain sid is not valid throw new ArgumentException(SR.IdentityReference_NotAWindowsDomain, nameof(domainSid)); } else if (ErrorCode != Interop.Errors.ERROR_SUCCESS) { Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.GetWindowsAccountDomainSid returned unrecognized error {0}", ErrorCode)); throw new Win32Exception(ErrorCode); } // // if domainSid is passed in as S-1-5-21-3-4-5-6, the above api will return S-1-5-21-3-4-5 as the domainSid // Since these do not match S-1-5-21-3-4-5-6 is not a valid domainSid (wrong number of subauthorities) // if (resultDomainSid != domainSid) { throw new ArgumentException(SR.IdentityReference_NotAWindowsDomain, nameof(domainSid)); } } Error = Win32.CreateWellKnownSid(sidType, domainSid, out resultSid); if (Error == Interop.Errors.ERROR_INVALID_PARAMETER) { throw new ArgumentException(new Win32Exception(Error).Message, "sidType/domainSid"); } else if (Error != Interop.Errors.ERROR_SUCCESS) { Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.CreateWellKnownSid returned unrecognized error {0}", Error)); throw new Win32Exception(Error); } CreateFromBinaryForm(resultSid, 0); } internal SecurityIdentifier(SecurityIdentifier domainSid, uint rid) { int i; int[] SubAuthorities = new int[domainSid.SubAuthorityCount + 1]; for (i = 0; i < domainSid.SubAuthorityCount; i++) { SubAuthorities[i] = domainSid.GetSubAuthority(i); } SubAuthorities[i] = (int)rid; CreateFromParts(domainSid.IdentifierAuthority, SubAuthorities); } internal SecurityIdentifier(IdentifierAuthority identifierAuthority, int[] subAuthorities) { CreateFromParts(identifierAuthority, subAuthorities); } #endregion #region Static Properties // // Revision is always '1' // internal static byte Revision { get { return 1; } } #endregion #region Non-static Properties // // This is for internal consumption only, hence it is marked 'internal' // Making this call public would require a deep copy of the data to // prevent the caller from messing with the internal representation. // internal byte[] BinaryForm { get { return _binaryForm; } } internal IdentifierAuthority IdentifierAuthority { get { return _identifierAuthority; } } internal int SubAuthorityCount { get { return _subAuthorities.Length; } } public int BinaryLength { get { return _binaryForm.Length; } } // // Returns the domain portion of a SID or null if the specified // SID is not an account SID // NOTE: although there is a P/Invoke call involved in the implementation of this method, // there is no security risk involved, so no security demand is being made. // public SecurityIdentifier AccountDomainSid { get { if (!_accountDomainSidInitialized) { _accountDomainSid = GetAccountDomainSid(); _accountDomainSidInitialized = true; } return _accountDomainSid; } } #endregion #region Inherited properties and methods public override bool Equals(object o) { return (this == o as SecurityIdentifier); // invokes operator== } public bool Equals(SecurityIdentifier sid) { return (this == sid); // invokes operator== } public override int GetHashCode() { int hashCode = ((long)this.IdentifierAuthority).GetHashCode(); for (int i = 0; i < SubAuthorityCount; i++) { hashCode ^= this.GetSubAuthority(i); } return hashCode; } public override string ToString() { if (_sddlForm == null) { StringBuilder result = new StringBuilder(); // // Typecasting of _IdentifierAuthority to a long below is important, since // otherwise you would see this: "S-1-NTAuthority-32-544" // result.Append("S-1-").Append((long)_identifierAuthority); for (int i = 0; i < SubAuthorityCount; i++) { result.Append('-').Append((uint)(_subAuthorities[i])); } _sddlForm = result.ToString(); } return _sddlForm; } public override string Value { get { return ToString().ToUpperInvariant(); } } internal static bool IsValidTargetTypeStatic(Type targetType) { if (targetType == typeof(NTAccount)) { return true; } else if (targetType == typeof(SecurityIdentifier)) { return true; } else { return false; } } public override bool IsValidTargetType(Type targetType) { return IsValidTargetTypeStatic(targetType); } internal SecurityIdentifier GetAccountDomainSid() { SecurityIdentifier ResultSid; int Error; Error = Win32.GetWindowsAccountDomainSid(this, out ResultSid); if (Error == Interop.Errors.ERROR_INSUFFICIENT_BUFFER) { throw new OutOfMemoryException(); } else if (Error == Interop.Errors.ERROR_NON_ACCOUNT_SID) { ResultSid = null; } else if (Error != Interop.Errors.ERROR_SUCCESS) { Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.GetWindowsAccountDomainSid returned unrecognized error {0}", Error)); throw new Win32Exception(Error); } return ResultSid; } public bool IsAccountSid() { if (!_accountDomainSidInitialized) { _accountDomainSid = GetAccountDomainSid(); _accountDomainSidInitialized = true; } if (_accountDomainSid == null) { return false; } return true; } public override IdentityReference Translate(Type targetType) { if (targetType == null) { throw new ArgumentNullException(nameof(targetType)); } if (targetType == typeof(SecurityIdentifier)) { return this; // assumes SecurityIdentifier objects are immutable } else if (targetType == typeof(NTAccount)) { IdentityReferenceCollection irSource = new IdentityReferenceCollection(1); irSource.Add(this); IdentityReferenceCollection irTarget; irTarget = SecurityIdentifier.Translate(irSource, targetType, true); return irTarget[0]; } else { throw new ArgumentException(SR.IdentityReference_MustBeIdentityReference, nameof(targetType)); } } #endregion #region Operators public static bool operator ==(SecurityIdentifier left, SecurityIdentifier right) { object l = left; object r = right; if (l == r) { return true; } else if (l == null || r == null) { return false; } else { return (left.CompareTo(right) == 0); } } public static bool operator !=(SecurityIdentifier left, SecurityIdentifier right) { return !(left == right); } #endregion #region IComparable implementation public int CompareTo(SecurityIdentifier sid) { if (sid == null) { throw new ArgumentNullException(nameof(sid)); } if (this.IdentifierAuthority < sid.IdentifierAuthority) { return -1; } if (this.IdentifierAuthority > sid.IdentifierAuthority) { return 1; } if (this.SubAuthorityCount < sid.SubAuthorityCount) { return -1; } if (this.SubAuthorityCount > sid.SubAuthorityCount) { return 1; } for (int i = 0; i < this.SubAuthorityCount; i++) { int diff = this.GetSubAuthority(i) - sid.GetSubAuthority(i); if (diff != 0) { return diff; } } return 0; } #endregion #region Public Methods internal int GetSubAuthority(int index) { return _subAuthorities[index]; } // // Determines whether this SID is a well-known SID of the specified type // // NOTE: although there is a P/Invoke call involved in the implementation of this method, // there is no security risk involved, so no security demand is being made. // public bool IsWellKnown(WellKnownSidType type) { return Win32.IsWellKnownSid(this, type); } public void GetBinaryForm(byte[] binaryForm, int offset) { _binaryForm.CopyTo(binaryForm, offset); } // // NOTE: although there is a P/Invoke call involved in the implementation of this method, // there is no security risk involved, so no security demand is being made. // public bool IsEqualDomainSid(SecurityIdentifier sid) { return Win32.IsEqualDomainSid(this, sid); } private static IdentityReferenceCollection TranslateToNTAccounts(IdentityReferenceCollection sourceSids, out bool someFailed) { if (sourceSids == null) { throw new ArgumentNullException(nameof(sourceSids)); } if (sourceSids.Count == 0) { throw new ArgumentException(SR.Arg_EmptyCollection, nameof(sourceSids)); } IntPtr[] SidArrayPtr = new IntPtr[sourceSids.Count]; GCHandle[] HandleArray = new GCHandle[sourceSids.Count]; SafeLsaPolicyHandle LsaHandle = SafeLsaPolicyHandle.InvalidHandle; SafeLsaMemoryHandle ReferencedDomainsPtr = SafeLsaMemoryHandle.InvalidHandle; SafeLsaMemoryHandle NamesPtr = SafeLsaMemoryHandle.InvalidHandle; try { // // Pin all elements in the array of SIDs // int currentSid = 0; foreach (IdentityReference id in sourceSids) { SecurityIdentifier sid = id as SecurityIdentifier; if (sid == null) { throw new ArgumentException(SR.Argument_ImproperType, nameof(sourceSids)); } HandleArray[currentSid] = GCHandle.Alloc(sid.BinaryForm, GCHandleType.Pinned); SidArrayPtr[currentSid] = HandleArray[currentSid].AddrOfPinnedObject(); currentSid++; } // // Open LSA policy (for lookup requires it) // LsaHandle = Win32.LsaOpenPolicy(null, PolicyRights.POLICY_LOOKUP_NAMES); // // Perform the actual lookup // someFailed = false; uint ReturnCode; ReturnCode = Interop.Advapi32.LsaLookupSids(LsaHandle, sourceSids.Count, SidArrayPtr, ref ReferencedDomainsPtr, ref NamesPtr); // // Make a decision regarding whether it makes sense to proceed // based on the return code and the value of the forceSuccess argument // if (ReturnCode == Interop.StatusOptions.STATUS_NO_MEMORY || ReturnCode == Interop.StatusOptions.STATUS_INSUFFICIENT_RESOURCES) { throw new OutOfMemoryException(); } else if (ReturnCode == Interop.StatusOptions.STATUS_ACCESS_DENIED) { throw new UnauthorizedAccessException(); } else if (ReturnCode == Interop.StatusOptions.STATUS_NONE_MAPPED || ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED) { someFailed = true; } else if (ReturnCode != 0) { uint win32ErrorCode = Interop.Advapi32.LsaNtStatusToWinError(ReturnCode); Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Interop.LsaLookupSids returned {0}", win32ErrorCode)); throw new Win32Exception(unchecked((int)win32ErrorCode)); } NamesPtr.Initialize((uint)sourceSids.Count, (uint)Marshal.SizeOf<Interop.LSA_TRANSLATED_NAME>()); Win32.InitializeReferencedDomainsPointer(ReferencedDomainsPtr); // // Interpret the results and generate NTAccount objects // IdentityReferenceCollection Result = new IdentityReferenceCollection(sourceSids.Count); if (ReturnCode == 0 || ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED) { // // Interpret the results and generate NT Account objects // Interop.LSA_REFERENCED_DOMAIN_LIST rdl = ReferencedDomainsPtr.Read<Interop.LSA_REFERENCED_DOMAIN_LIST>(0); string[] ReferencedDomains = new string[rdl.Entries]; for (int i = 0; i < rdl.Entries; i++) { Interop.LSA_TRUST_INFORMATION ti = (Interop.LSA_TRUST_INFORMATION)Marshal.PtrToStructure<Interop.LSA_TRUST_INFORMATION>(new IntPtr((long)rdl.Domains + i * Marshal.SizeOf<Interop.LSA_TRUST_INFORMATION>())); ReferencedDomains[i] = Marshal.PtrToStringUni(ti.Name.Buffer, ti.Name.Length / sizeof(char)); } Interop.LSA_TRANSLATED_NAME[] translatedNames = new Interop.LSA_TRANSLATED_NAME[sourceSids.Count]; NamesPtr.ReadArray(0, translatedNames, 0, translatedNames.Length); for (int i = 0; i < sourceSids.Count; i++) { Interop.LSA_TRANSLATED_NAME Ltn = translatedNames[i]; switch ((SidNameUse)Ltn.Use) { case SidNameUse.User: case SidNameUse.Group: case SidNameUse.Alias: case SidNameUse.Computer: case SidNameUse.WellKnownGroup: string account = Marshal.PtrToStringUni(Ltn.Name.Buffer, Ltn.Name.Length / sizeof(char)); ; string domain = ReferencedDomains[Ltn.DomainIndex]; Result.Add(new NTAccount(domain, account)); break; default: someFailed = true; Result.Add(sourceSids[i]); break; } } } else { for (int i = 0; i < sourceSids.Count; i++) { Result.Add(sourceSids[i]); } } return Result; } finally { for (int i = 0; i < sourceSids.Count; i++) { if (HandleArray[i].IsAllocated) { HandleArray[i].Free(); } } LsaHandle.Dispose(); ReferencedDomainsPtr.Dispose(); NamesPtr.Dispose(); } } internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceSids, Type targetType, bool forceSuccess) { bool SomeFailed = false; IdentityReferenceCollection Result; Result = Translate(sourceSids, targetType, out SomeFailed); if (forceSuccess && SomeFailed) { IdentityReferenceCollection UnmappedIdentities = new IdentityReferenceCollection(); foreach (IdentityReference id in Result) { if (id.GetType() != targetType) { UnmappedIdentities.Add(id); } } throw new IdentityNotMappedException(SR.IdentityReference_IdentityNotMapped, UnmappedIdentities); } return Result; } internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceSids, Type targetType, out bool someFailed) { if (sourceSids == null) { throw new ArgumentNullException(nameof(sourceSids)); } if (targetType == typeof(NTAccount)) { return TranslateToNTAccounts(sourceSids, out someFailed); } throw new ArgumentException(SR.IdentityReference_MustBeIdentityReference, nameof(targetType)); } #endregion } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.EnterpriseServices; namespace WebsitePanel.Installer.Common { public class Global { public const string VisualInstallerShell = "VisualInstallerShell"; public const string SilentInstallerShell = "SilentInstallerShell"; public const string DefaultInstallPathRoot = @"C:\WebsitePanel"; public const string LoopbackIPv4 = "127.0.0.1"; public const string InstallerProductCode = "cfg core"; public abstract class Parameters { public const string ComponentId = "ComponentId"; public const string EnterpriseServerUrl = "EnterpriseServerUrl"; public const string ShellMode = "ShellMode"; public const string ShellVersion = "ShellVersion"; public const string IISVersion = "IISVersion"; public const string BaseDirectory = "BaseDirectory"; public const string Installer = "Installer"; public const string InstallerType = "InstallerType"; public const string InstallerPath = "InstallerPath"; public const string InstallerFolder = "InstallerFolder"; public const string Version = "Version"; public const string ComponentDescription = "ComponentDescription"; public const string ComponentCode = "ComponentCode"; public const string ApplicationName = "ApplicationName"; public const string ComponentName = "ComponentName"; public const string WebSiteIP = "WebSiteIP"; public const string WebSitePort = "WebSitePort"; public const string WebSiteDomain = "WebSiteDomain"; public const string ServerPassword = "ServerPassword"; public const string UserDomain = "UserDomain"; public const string UserAccount = "UserAccount"; public const string UserPassword = "UserPassword"; public const string CryptoKey = "CryptoKey"; public const string ServerAdminPassword = "ServerAdminPassword"; public const string SetupXml = "SetupXml"; public const string ParentForm = "ParentForm"; public const string Component = "Component"; public const string FullFilePath = "FullFilePath"; public const string DatabaseServer = "DatabaseServer"; public const string DbServerAdmin = "DbServerAdmin"; public const string DbServerAdminPassword = "DbServerAdminPassword"; public const string DatabaseName = "DatabaseName"; public const string ConnectionString = "ConnectionString"; public const string InstallConnectionString = "InstallConnectionString"; public const string Release = "Release"; } public abstract class Messages { public const string NotEnoughPermissionsError = "You do not have the appropriate permissions to perform this operation. Make sure you are running the application from the local disk and you have local system administrator privileges."; public const string InstallerVersionIsObsolete = "WebsitePanel Installer {0} or higher required."; public const string ComponentIsAlreadyInstalled = "Component or its part is already installed."; public const string AnotherInstanceIsRunning = "Another instance of the installation process is already running."; public const string NoInputParametersSpecified = "No input parameters specified"; public const int InstallationError = -1000; public const int UnknownComponentCodeError = -999; public const int SuccessInstallation = 0; public const int AnotherInstanceIsRunningError = -998; public const int NotEnoughPermissionsErrorCode = -997; public const int NoInputParametersSpecifiedError = -996; public const int ComponentIsAlreadyInstalledError = -995; } public abstract class Server { public abstract class CLI { public const string ServerPassword = "passw"; }; public const string ComponentName = "Server"; public const string ComponentCode = "server"; public const string ComponentDescription = "WebsitePanel Server is a set of services running on the remote server to be controlled. Server application should be reachable from Enterprise Server one."; public const string ServiceAccount = "WPServer"; public const string DefaultPort = "9003"; public const string DefaultIP = "127.0.0.1"; public const string SetupController = "Server"; } public abstract class StandaloneServer { public const string SetupController = "StandaloneServerSetup"; public const string ComponentCode = "standalone"; public const string ComponentName = "Standalone Server Setup"; } public abstract class WebPortal { public const string ComponentName = "Portal"; public const string ComponentDescription = "WebsitePanel Portal is a control panel itself with user interface which allows managing user accounts, hosting spaces, web sites, FTP accounts, files, etc."; public const string ServiceAccount = "WPPortal"; public const string DefaultPort = "9001"; public const string DefaultIP = ""; public const string DefaultEntServURL = "http://127.0.0.1:9002"; public const string ComponentCode = "portal"; public const string SetupController = "Portal"; public static string[] ServiceUserMembership { get { if (IISVersion.Major >= 7) { return new string[] { "IIS_IUSRS" }; } // return new string[] { "IIS_WPG" }; } } public abstract class CLI { public const string EnterpriseServerUrl = "esurl"; } } public abstract class EntServer { public const string ComponentName = "Enterprise Server"; public const string ComponentDescription = "Enterprise Server is the heart of WebsitePanel system. It includes all business logic of the application. Enterprise Server should have access to Server and be accessible from Portal applications."; public const string ServiceAccount = "WPEnterpriseServer"; public const string DefaultPort = "9002"; public const string DefaultIP = "127.0.0.1"; public const string DefaultDbServer = @"localhost\sqlexpress"; public const string DefaultDatabase = "WebsitePanel"; public const string AspNetConnectionStringFormat = "server={0};database={1};uid={2};pwd={3};"; public const string ComponentCode = "enterprise server"; public const string SetupController = "EnterpriseServer"; public static string[] ServiceUserMembership { get { if (IISVersion.Major >= 7) { return new string[] { "IIS_IUSRS" }; } // return new string[] { "IIS_WPG" }; } } public abstract class CLI { public const string ServeradminPassword = "passw"; public const string DatabaseName = "dbname"; public const string DatabaseServer = "dbserver"; public const string DbServerAdmin = "dbadmin"; public const string DbServerAdminPassword = "dbapassw"; } } public abstract class CLI { public const string WebSiteIP = "webip"; public const string ServiceAccountPassword = "upassw"; public const string ServiceAccountDomain = "udomaim"; public const string ServiceAccountName = "uname"; public const string WebSitePort = "webport"; public const string WebSiteDomain = "webdom"; } private Global() { } private static Version iisVersion; // public static Version IISVersion { get { if (iisVersion == null) { iisVersion = RegistryUtils.GetIISVersion(); } // return iisVersion; } } // private static OS.WindowsVersion osVersion = OS.WindowsVersion.Unknown; /// <summary> /// Represents Setup Control Panel Accounts system settings set (SCPA) /// </summary> public class SCPA { public const string SettingsKeyName = "EnabledSCPA"; } public static OS.WindowsVersion OSVersion { get { if (osVersion == OS.WindowsVersion.Unknown) { osVersion = OS.GetVersion(); } // return osVersion; } } public static XmlDocument SetupXmlDocument { get; set; } } public class SetupEventArgs<T> : EventArgs { public T EventData { get; set; } public string EventMessage { get; set; } } }
// 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.14.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * Prediction API Version v1.6 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/prediction/docs/developer-guide'>Prediction API</a> * <tr><th>API Version<td>v1.6 * <tr><th>API Rev<td>20160511 (496) * <tr><th>API Docs * <td><a href='https://developers.google.com/prediction/docs/developer-guide'> * https://developers.google.com/prediction/docs/developer-guide</a> * <tr><th>Discovery Name<td>prediction * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using Prediction API can be found at * <a href='https://developers.google.com/prediction/docs/developer-guide'>https://developers.google.com/prediction/docs/developer-guide</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.Prediction.v1_6 { /// <summary>The Prediction Service.</summary> public class PredictionService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1.6"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public PredictionService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public PredictionService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { hostedmodels = new HostedmodelsResource(this); trainedmodels = new TrainedmodelsResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "prediction"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://www.googleapis.com/prediction/v1.6/projects/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return "prediction/v1.6/projects/"; } } /// <summary>Available OAuth 2.0 scopes for use with the Prediction API.</summary> public class Scope { /// <summary>View and manage your data across Google Cloud Platform services</summary> public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; /// <summary>Manage your data and permissions in Google Cloud Storage</summary> public static string DevstorageFullControl = "https://www.googleapis.com/auth/devstorage.full_control"; /// <summary>View your data in Google Cloud Storage</summary> public static string DevstorageReadOnly = "https://www.googleapis.com/auth/devstorage.read_only"; /// <summary>Manage your data in Google Cloud Storage</summary> public static string DevstorageReadWrite = "https://www.googleapis.com/auth/devstorage.read_write"; /// <summary>Manage your data in the Google Prediction API</summary> public static string Prediction = "https://www.googleapis.com/auth/prediction"; } private readonly HostedmodelsResource hostedmodels; /// <summary>Gets the Hostedmodels resource.</summary> public virtual HostedmodelsResource Hostedmodels { get { return hostedmodels; } } private readonly TrainedmodelsResource trainedmodels; /// <summary>Gets the Trainedmodels resource.</summary> public virtual TrainedmodelsResource Trainedmodels { get { return trainedmodels; } } } ///<summary>A base abstract class for Prediction requests.</summary> public abstract class PredictionBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new PredictionBaseServiceRequest instance.</summary> protected PredictionBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>Data format for the response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for the response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user /// limits.</summary> [Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)] public virtual string UserIp { get; set; } /// <summary>Initializes Prediction parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userIp", new Google.Apis.Discovery.Parameter { Name = "userIp", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "hostedmodels" collection of methods.</summary> public class HostedmodelsResource { private const string Resource = "hostedmodels"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public HostedmodelsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Submit input and request an output against a hosted model.</summary> /// <param name="body">The body of the request.</param> /// <param name="project">The project associated with the model.</param> /// <param name="hostedModelName">The name /// of a hosted model.</param> public virtual PredictRequest Predict(Google.Apis.Prediction.v1_6.Data.Input body, string project, string hostedModelName) { return new PredictRequest(service, body, project, hostedModelName); } /// <summary>Submit input and request an output against a hosted model.</summary> public class PredictRequest : PredictionBaseServiceRequest<Google.Apis.Prediction.v1_6.Data.Output> { /// <summary>Constructs a new Predict request.</summary> public PredictRequest(Google.Apis.Services.IClientService service, Google.Apis.Prediction.v1_6.Data.Input body, string project, string hostedModelName) : base(service) { Project = project; HostedModelName = hostedModelName; Body = body; InitParameters(); } /// <summary>The project associated with the model.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } /// <summary>The name of a hosted model.</summary> [Google.Apis.Util.RequestParameterAttribute("hostedModelName", Google.Apis.Util.RequestParameterType.Path)] public virtual string HostedModelName { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Prediction.v1_6.Data.Input Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "predict"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/hostedmodels/{hostedModelName}/predict"; } } /// <summary>Initializes Predict parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "hostedModelName", new Google.Apis.Discovery.Parameter { Name = "hostedModelName", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } /// <summary>The "trainedmodels" collection of methods.</summary> public class TrainedmodelsResource { private const string Resource = "trainedmodels"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public TrainedmodelsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Get analysis of the model and the data the model was trained on.</summary> /// <param name="project">The project associated with the model.</param> /// <param name="id">The unique name for /// the predictive model.</param> public virtual AnalyzeRequest Analyze(string project, string id) { return new AnalyzeRequest(service, project, id); } /// <summary>Get analysis of the model and the data the model was trained on.</summary> public class AnalyzeRequest : PredictionBaseServiceRequest<Google.Apis.Prediction.v1_6.Data.Analyze> { /// <summary>Constructs a new Analyze request.</summary> public AnalyzeRequest(Google.Apis.Services.IClientService service, string project, string id) : base(service) { Project = project; Id = id; InitParameters(); } /// <summary>The project associated with the model.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } /// <summary>The unique name for the predictive model.</summary> [Google.Apis.Util.RequestParameterAttribute("id", Google.Apis.Util.RequestParameterType.Path)] public virtual string Id { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "analyze"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/trainedmodels/{id}/analyze"; } } /// <summary>Initializes Analyze parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "id", new Google.Apis.Discovery.Parameter { Name = "id", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Delete a trained model.</summary> /// <param name="project">The project associated with the model.</param> /// <param name="id">The unique name for /// the predictive model.</param> public virtual DeleteRequest Delete(string project, string id) { return new DeleteRequest(service, project, id); } /// <summary>Delete a trained model.</summary> public class DeleteRequest : PredictionBaseServiceRequest<string> { /// <summary>Constructs a new Delete request.</summary> public DeleteRequest(Google.Apis.Services.IClientService service, string project, string id) : base(service) { Project = project; Id = id; InitParameters(); } /// <summary>The project associated with the model.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } /// <summary>The unique name for the predictive model.</summary> [Google.Apis.Util.RequestParameterAttribute("id", Google.Apis.Util.RequestParameterType.Path)] public virtual string Id { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "delete"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "DELETE"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/trainedmodels/{id}"; } } /// <summary>Initializes Delete parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "id", new Google.Apis.Discovery.Parameter { Name = "id", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Check training status of your model.</summary> /// <param name="project">The project associated with the model.</param> /// <param name="id">The unique name for /// the predictive model.</param> public virtual GetRequest Get(string project, string id) { return new GetRequest(service, project, id); } /// <summary>Check training status of your model.</summary> public class GetRequest : PredictionBaseServiceRequest<Google.Apis.Prediction.v1_6.Data.Insert2> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string project, string id) : base(service) { Project = project; Id = id; InitParameters(); } /// <summary>The project associated with the model.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } /// <summary>The unique name for the predictive model.</summary> [Google.Apis.Util.RequestParameterAttribute("id", Google.Apis.Util.RequestParameterType.Path)] public virtual string Id { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/trainedmodels/{id}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "id", new Google.Apis.Discovery.Parameter { Name = "id", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Train a Prediction API model.</summary> /// <param name="body">The body of the request.</param> /// <param name="project">The project associated with the model.</param> public virtual InsertRequest Insert(Google.Apis.Prediction.v1_6.Data.Insert body, string project) { return new InsertRequest(service, body, project); } /// <summary>Train a Prediction API model.</summary> public class InsertRequest : PredictionBaseServiceRequest<Google.Apis.Prediction.v1_6.Data.Insert2> { /// <summary>Constructs a new Insert request.</summary> public InsertRequest(Google.Apis.Services.IClientService service, Google.Apis.Prediction.v1_6.Data.Insert body, string project) : base(service) { Project = project; Body = body; InitParameters(); } /// <summary>The project associated with the model.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Prediction.v1_6.Data.Insert Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "insert"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/trainedmodels"; } } /// <summary>Initializes Insert parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>List available models.</summary> /// <param name="project">The project associated with the model.</param> public virtual ListRequest List(string project) { return new ListRequest(service, project); } /// <summary>List available models.</summary> public class ListRequest : PredictionBaseServiceRequest<Google.Apis.Prediction.v1_6.Data.List> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string project) : base(service) { Project = project; InitParameters(); } /// <summary>The project associated with the model.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } /// <summary>Maximum number of results to return.</summary> /// [minimum: 0] [Google.Apis.Util.RequestParameterAttribute("maxResults", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<long> MaxResults { get; set; } /// <summary>Pagination token.</summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "list"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/trainedmodels/list"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "maxResults", new Google.Apis.Discovery.Parameter { Name = "maxResults", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>Submit model id and request a prediction.</summary> /// <param name="body">The body of the request.</param> /// <param name="project">The project associated with the model.</param> /// <param name="id">The unique name for /// the predictive model.</param> public virtual PredictRequest Predict(Google.Apis.Prediction.v1_6.Data.Input body, string project, string id) { return new PredictRequest(service, body, project, id); } /// <summary>Submit model id and request a prediction.</summary> public class PredictRequest : PredictionBaseServiceRequest<Google.Apis.Prediction.v1_6.Data.Output> { /// <summary>Constructs a new Predict request.</summary> public PredictRequest(Google.Apis.Services.IClientService service, Google.Apis.Prediction.v1_6.Data.Input body, string project, string id) : base(service) { Project = project; Id = id; Body = body; InitParameters(); } /// <summary>The project associated with the model.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } /// <summary>The unique name for the predictive model.</summary> [Google.Apis.Util.RequestParameterAttribute("id", Google.Apis.Util.RequestParameterType.Path)] public virtual string Id { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Prediction.v1_6.Data.Input Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "predict"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/trainedmodels/{id}/predict"; } } /// <summary>Initializes Predict parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "id", new Google.Apis.Discovery.Parameter { Name = "id", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Add new data to a trained model.</summary> /// <param name="body">The body of the request.</param> /// <param name="project">The project associated with the model.</param> /// <param name="id">The unique name for /// the predictive model.</param> public virtual UpdateRequest Update(Google.Apis.Prediction.v1_6.Data.Update body, string project, string id) { return new UpdateRequest(service, body, project, id); } /// <summary>Add new data to a trained model.</summary> public class UpdateRequest : PredictionBaseServiceRequest<Google.Apis.Prediction.v1_6.Data.Insert2> { /// <summary>Constructs a new Update request.</summary> public UpdateRequest(Google.Apis.Services.IClientService service, Google.Apis.Prediction.v1_6.Data.Update body, string project, string id) : base(service) { Project = project; Id = id; Body = body; InitParameters(); } /// <summary>The project associated with the model.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } /// <summary>The unique name for the predictive model.</summary> [Google.Apis.Util.RequestParameterAttribute("id", Google.Apis.Util.RequestParameterType.Path)] public virtual string Id { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Prediction.v1_6.Data.Update Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "update"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "PUT"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/trainedmodels/{id}"; } } /// <summary>Initializes Update parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "id", new Google.Apis.Discovery.Parameter { Name = "id", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.Prediction.v1_6.Data { public class Analyze : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Description of the data the model was trained on.</summary> [Newtonsoft.Json.JsonPropertyAttribute("dataDescription")] public virtual Analyze.DataDescriptionData DataDescription { get; set; } /// <summary>List of errors with the data.</summary> [Newtonsoft.Json.JsonPropertyAttribute("errors")] public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string,string>> Errors { get; set; } /// <summary>The unique name for the predictive model.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>What kind of resource this is.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Description of the model.</summary> [Newtonsoft.Json.JsonPropertyAttribute("modelDescription")] public virtual Analyze.ModelDescriptionData ModelDescription { get; set; } /// <summary>A URL to re-request this resource.</summary> [Newtonsoft.Json.JsonPropertyAttribute("selfLink")] public virtual string SelfLink { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } /// <summary>Description of the data the model was trained on.</summary> public class DataDescriptionData { /// <summary>Description of the input features in the data set.</summary> [Newtonsoft.Json.JsonPropertyAttribute("features")] public virtual System.Collections.Generic.IList<DataDescriptionData.FeaturesData> Features { get; set; } /// <summary>Description of the output value or label.</summary> [Newtonsoft.Json.JsonPropertyAttribute("outputFeature")] public virtual DataDescriptionData.OutputFeatureData OutputFeature { get; set; } public class FeaturesData { /// <summary>Description of the categorical values of this feature.</summary> [Newtonsoft.Json.JsonPropertyAttribute("categorical")] public virtual FeaturesData.CategoricalData Categorical { get; set; } /// <summary>The feature index.</summary> [Newtonsoft.Json.JsonPropertyAttribute("index")] public virtual System.Nullable<long> Index { get; set; } /// <summary>Description of the numeric values of this feature.</summary> [Newtonsoft.Json.JsonPropertyAttribute("numeric")] public virtual FeaturesData.NumericData Numeric { get; set; } /// <summary>Description of multiple-word text values of this feature.</summary> [Newtonsoft.Json.JsonPropertyAttribute("text")] public virtual FeaturesData.TextData Text { get; set; } /// <summary>Description of the categorical values of this feature.</summary> public class CategoricalData { /// <summary>Number of categorical values for this feature in the data.</summary> [Newtonsoft.Json.JsonPropertyAttribute("count")] public virtual System.Nullable<long> Count { get; set; } /// <summary>List of all the categories for this feature in the data set.</summary> [Newtonsoft.Json.JsonPropertyAttribute("values")] public virtual System.Collections.Generic.IList<CategoricalData.ValuesData> Values { get; set; } public class ValuesData { /// <summary>Number of times this feature had this value.</summary> [Newtonsoft.Json.JsonPropertyAttribute("count")] public virtual System.Nullable<long> Count { get; set; } /// <summary>The category name.</summary> [Newtonsoft.Json.JsonPropertyAttribute("value")] public virtual string Value { get; set; } } } /// <summary>Description of the numeric values of this feature.</summary> public class NumericData { /// <summary>Number of numeric values for this feature in the data set.</summary> [Newtonsoft.Json.JsonPropertyAttribute("count")] public virtual System.Nullable<long> Count { get; set; } /// <summary>Mean of the numeric values of this feature in the data set.</summary> [Newtonsoft.Json.JsonPropertyAttribute("mean")] public virtual string Mean { get; set; } /// <summary>Variance of the numeric values of this feature in the data set.</summary> [Newtonsoft.Json.JsonPropertyAttribute("variance")] public virtual string Variance { get; set; } } /// <summary>Description of multiple-word text values of this feature.</summary> public class TextData { /// <summary>Number of multiple-word text values for this feature.</summary> [Newtonsoft.Json.JsonPropertyAttribute("count")] public virtual System.Nullable<long> Count { get; set; } } } /// <summary>Description of the output value or label.</summary> public class OutputFeatureData { /// <summary>Description of the output values in the data set.</summary> [Newtonsoft.Json.JsonPropertyAttribute("numeric")] public virtual OutputFeatureData.NumericData Numeric { get; set; } /// <summary>Description of the output labels in the data set.</summary> [Newtonsoft.Json.JsonPropertyAttribute("text")] public virtual System.Collections.Generic.IList<OutputFeatureData.TextData> Text { get; set; } /// <summary>Description of the output values in the data set.</summary> public class NumericData { /// <summary>Number of numeric output values in the data set.</summary> [Newtonsoft.Json.JsonPropertyAttribute("count")] public virtual System.Nullable<long> Count { get; set; } /// <summary>Mean of the output values in the data set.</summary> [Newtonsoft.Json.JsonPropertyAttribute("mean")] public virtual string Mean { get; set; } /// <summary>Variance of the output values in the data set.</summary> [Newtonsoft.Json.JsonPropertyAttribute("variance")] public virtual string Variance { get; set; } } public class TextData { /// <summary>Number of times the output label occurred in the data set.</summary> [Newtonsoft.Json.JsonPropertyAttribute("count")] public virtual System.Nullable<long> Count { get; set; } /// <summary>The output label.</summary> [Newtonsoft.Json.JsonPropertyAttribute("value")] public virtual string Value { get; set; } } } } /// <summary>Description of the model.</summary> public class ModelDescriptionData { /// <summary>An output confusion matrix. This shows an estimate for how this model will do in predictions. /// This is first indexed by the true class label. For each true class label, this provides a pair /// {predicted_label, count}, where count is the estimated number of times the model will predict the /// predicted label given the true label. Will not output if more then 100 classes (Categorical models /// only).</summary> [Newtonsoft.Json.JsonPropertyAttribute("confusionMatrix")] public virtual System.Collections.Generic.IDictionary<string,System.Collections.Generic.IDictionary<string,string>> ConfusionMatrix { get; set; } /// <summary>A list of the confusion matrix row totals.</summary> [Newtonsoft.Json.JsonPropertyAttribute("confusionMatrixRowTotals")] public virtual System.Collections.Generic.IDictionary<string,string> ConfusionMatrixRowTotals { get; set; } /// <summary>Basic information about the model.</summary> [Newtonsoft.Json.JsonPropertyAttribute("modelinfo")] public virtual Insert2 Modelinfo { get; set; } } } public class Input : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Input to the model for a prediction.</summary> [Newtonsoft.Json.JsonPropertyAttribute("input")] public virtual Input.InputData InputValue { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } /// <summary>Input to the model for a prediction.</summary> public class InputData { /// <summary>A list of input features, these can be strings or doubles.</summary> [Newtonsoft.Json.JsonPropertyAttribute("csvInstance")] public virtual System.Collections.Generic.IList<object> CsvInstance { get; set; } } } public class Insert : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The unique name for the predictive model.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>Type of predictive model (classification or regression).</summary> [Newtonsoft.Json.JsonPropertyAttribute("modelType")] public virtual string ModelType { get; set; } /// <summary>The Id of the model to be copied over.</summary> [Newtonsoft.Json.JsonPropertyAttribute("sourceModel")] public virtual string SourceModel { get; set; } /// <summary>Google storage location of the training data file.</summary> [Newtonsoft.Json.JsonPropertyAttribute("storageDataLocation")] public virtual string StorageDataLocation { get; set; } /// <summary>Google storage location of the preprocessing pmml file.</summary> [Newtonsoft.Json.JsonPropertyAttribute("storagePMMLLocation")] public virtual string StoragePMMLLocation { get; set; } /// <summary>Google storage location of the pmml model file.</summary> [Newtonsoft.Json.JsonPropertyAttribute("storagePMMLModelLocation")] public virtual string StoragePMMLModelLocation { get; set; } /// <summary>Instances to train model on.</summary> [Newtonsoft.Json.JsonPropertyAttribute("trainingInstances")] public virtual System.Collections.Generic.IList<Insert.TrainingInstancesData> TrainingInstances { get; set; } /// <summary>A class weighting function, which allows the importance weights for class labels to be specified /// (Categorical models only).</summary> [Newtonsoft.Json.JsonPropertyAttribute("utility")] public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string,System.Nullable<double>>> Utility { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } public class TrainingInstancesData { /// <summary>The input features for this instance.</summary> [Newtonsoft.Json.JsonPropertyAttribute("csvInstance")] public virtual System.Collections.Generic.IList<object> CsvInstance { get; set; } /// <summary>The generic output value - could be regression or class label.</summary> [Newtonsoft.Json.JsonPropertyAttribute("output")] public virtual string Output { get; set; } } } public class Insert2 : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Insert time of the model (as a RFC 3339 timestamp).</summary> [Newtonsoft.Json.JsonPropertyAttribute("created")] public virtual string CreatedRaw { get; set; } /// <summary><seealso cref="System.DateTime"/> representation of <see cref="CreatedRaw"/>.</summary> [Newtonsoft.Json.JsonIgnore] public virtual System.Nullable<System.DateTime> Created { get { return Google.Apis.Util.Utilities.GetDateTimeFromString(CreatedRaw); } set { CreatedRaw = Google.Apis.Util.Utilities.GetStringFromDateTime(value); } } /// <summary>The unique name for the predictive model.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>What kind of resource this is.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Model metadata.</summary> [Newtonsoft.Json.JsonPropertyAttribute("modelInfo")] public virtual Insert2.ModelInfoData ModelInfo { get; set; } /// <summary>Type of predictive model (CLASSIFICATION or REGRESSION).</summary> [Newtonsoft.Json.JsonPropertyAttribute("modelType")] public virtual string ModelType { get; set; } /// <summary>A URL to re-request this resource.</summary> [Newtonsoft.Json.JsonPropertyAttribute("selfLink")] public virtual string SelfLink { get; set; } /// <summary>Google storage location of the training data file.</summary> [Newtonsoft.Json.JsonPropertyAttribute("storageDataLocation")] public virtual string StorageDataLocation { get; set; } /// <summary>Google storage location of the preprocessing pmml file.</summary> [Newtonsoft.Json.JsonPropertyAttribute("storagePMMLLocation")] public virtual string StoragePMMLLocation { get; set; } /// <summary>Google storage location of the pmml model file.</summary> [Newtonsoft.Json.JsonPropertyAttribute("storagePMMLModelLocation")] public virtual string StoragePMMLModelLocation { get; set; } /// <summary>Training completion time (as a RFC 3339 timestamp).</summary> [Newtonsoft.Json.JsonPropertyAttribute("trainingComplete")] public virtual string TrainingCompleteRaw { get; set; } /// <summary><seealso cref="System.DateTime"/> representation of <see cref="TrainingCompleteRaw"/>.</summary> [Newtonsoft.Json.JsonIgnore] public virtual System.Nullable<System.DateTime> TrainingComplete { get { return Google.Apis.Util.Utilities.GetDateTimeFromString(TrainingCompleteRaw); } set { TrainingCompleteRaw = Google.Apis.Util.Utilities.GetStringFromDateTime(value); } } /// <summary>The current status of the training job. This can be one of following: RUNNING; DONE; ERROR; ERROR: /// TRAINING JOB NOT FOUND</summary> [Newtonsoft.Json.JsonPropertyAttribute("trainingStatus")] public virtual string TrainingStatus { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } /// <summary>Model metadata.</summary> public class ModelInfoData { /// <summary>Estimated accuracy of model taking utility weights into account (Categorical models /// only).</summary> [Newtonsoft.Json.JsonPropertyAttribute("classWeightedAccuracy")] public virtual string ClassWeightedAccuracy { get; set; } /// <summary>A number between 0.0 and 1.0, where 1.0 is 100% accurate. This is an estimate, based on the /// amount and quality of the training data, of the estimated prediction accuracy. You can use this is a /// guide to decide whether the results are accurate enough for your needs. This estimate will be more /// reliable if your real input data is similar to your training data (Categorical models only).</summary> [Newtonsoft.Json.JsonPropertyAttribute("classificationAccuracy")] public virtual string ClassificationAccuracy { get; set; } /// <summary>An estimated mean squared error. The can be used to measure the quality of the predicted model /// (Regression models only).</summary> [Newtonsoft.Json.JsonPropertyAttribute("meanSquaredError")] public virtual string MeanSquaredError { get; set; } /// <summary>Type of predictive model (CLASSIFICATION or REGRESSION).</summary> [Newtonsoft.Json.JsonPropertyAttribute("modelType")] public virtual string ModelType { get; set; } /// <summary>Number of valid data instances used in the trained model.</summary> [Newtonsoft.Json.JsonPropertyAttribute("numberInstances")] public virtual System.Nullable<long> NumberInstances { get; set; } /// <summary>Number of class labels in the trained model (Categorical models only).</summary> [Newtonsoft.Json.JsonPropertyAttribute("numberLabels")] public virtual System.Nullable<long> NumberLabels { get; set; } } } public class List : Google.Apis.Requests.IDirectResponseSchema { /// <summary>List of models.</summary> [Newtonsoft.Json.JsonPropertyAttribute("items")] public virtual System.Collections.Generic.IList<Insert2> Items { get; set; } /// <summary>What kind of resource this is.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Pagination token to fetch the next page, if one exists.</summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>A URL to re-request this resource.</summary> [Newtonsoft.Json.JsonPropertyAttribute("selfLink")] public virtual string SelfLink { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } public class Output : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The unique name for the predictive model.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>What kind of resource this is.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>The most likely class label (Categorical models only).</summary> [Newtonsoft.Json.JsonPropertyAttribute("outputLabel")] public virtual string OutputLabel { get; set; } /// <summary>A list of class labels with their estimated probabilities (Categorical models only).</summary> [Newtonsoft.Json.JsonPropertyAttribute("outputMulti")] public virtual System.Collections.Generic.IList<Output.OutputMultiData> OutputMulti { get; set; } /// <summary>The estimated regression value (Regression models only).</summary> [Newtonsoft.Json.JsonPropertyAttribute("outputValue")] public virtual string OutputValue { get; set; } /// <summary>A URL to re-request this resource.</summary> [Newtonsoft.Json.JsonPropertyAttribute("selfLink")] public virtual string SelfLink { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } public class OutputMultiData { /// <summary>The class label.</summary> [Newtonsoft.Json.JsonPropertyAttribute("label")] public virtual string Label { get; set; } /// <summary>The probability of the class label.</summary> [Newtonsoft.Json.JsonPropertyAttribute("score")] public virtual string Score { get; set; } } } public class Update : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The input features for this instance.</summary> [Newtonsoft.Json.JsonPropertyAttribute("csvInstance")] public virtual System.Collections.Generic.IList<object> CsvInstance { get; set; } /// <summary>The generic output value - could be regression or class label.</summary> [Newtonsoft.Json.JsonPropertyAttribute("output")] public virtual string Output { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
using System; using System.IO; using System.Collections.Generic; using System.Threading; using MCSharp.World; namespace MCSharp { public class CmdLoad : Command { // Constructor public CmdLoad(CommandGroup g, GroupEnum group, string name) : base(g, group, name) { blnConsoleSupported = true; /* By default no console support*/ } // Command usage help public override void Help(Player p) { p.SendMessage("/load <level> [<physics level>] - Loads a level. You can optionally set the physics to 0|1|2"); } // Code to run when used by a player public override void Use(Player p, string message) { try { if (message != "" || message.Split(' ').Length <= 2) { int pos = message.IndexOf(' '); string phys = "0"; bool blnAlreadyLoaded = false; if (pos != -1) { phys = message.Substring(pos + 1); message = message.Substring(0, pos).ToLower(); } else { message = message.ToLower(); } // Make sure the level isn't already loaded foreach (Map l in Server.levels) { if (l.name == message) { blnAlreadyLoaded = true; break; } } if (!blnAlreadyLoaded) { if (Server.levels.Capacity > 1) { if (Server.levels.Count < Server.levels.Capacity) { if (File.Exists("levels/" + message + ".lvl")) { // Attempt to load the level Map level = Map.Load(message); if (level == null) { if (File.Exists("levels/" + message + ".lvl.backup")) { Logger.Log("Atempting to load backup."); File.Copy("levels/" + message + ".lvl.backup", "levels/" + message + ".lvl", true); level = Map.Load(message); } else { p.SendMessage("Backup of " + message + " does not exist."); } } // Make sure we loaded something before adding it the level list if (level != null) { lock (Server.levels) { Server.levels.Add(level); } Player.GlobalMessage("Map \"" + level.name + "\" loaded."); try { int temp = int.Parse(phys); if (temp >= 0 && temp <= 2) { level.Physics = (Physics)temp; } } catch { if (!p.disconnected) p.SendMessage("Physics variable invalid"); } } else { p.SendMessage("Failed to load the backup of " + message); } } else { p.SendMessage("Map \"" + message + "\" doesn't exist!"); } } else { p.SendMessage("You can't load more than " + Server.levels.Capacity + " levels!"); } } else { p.SendMessage("Map capacity is 1 or lower, you can't load any levels!"); } } else { p.SendMessage(message + " is already loaded!"); } } else { Help(p); } } catch (Exception e) { Player.GlobalMessage("An error occured with /load"); Logger.Log("An error occured with /load", LogType.Error); Logger.Log(e.Message, LogType.ErrorMessage); } } // Code to run when used by the console public override void Use(string message) { try { if (message != "" || message.Split(' ').Length <= 2) { int pos = message.IndexOf(' '); string phys = "0"; if (pos != -1) { phys = message.Substring(pos + 1); message = message.Substring(0, pos).ToLower(); } else { message = message.ToLower(); } if (!Map.Loaded(message)) { if (Server.levels.Capacity > 1) { if (Server.levels.Count < Server.levels.Capacity) { if (Map.Exists(message)) { // Attempt to load the level Map level = Map.Load(message); if (level == null) { if (File.Exists("levels/" + message + ".lvl.backup")) { Logger.Log("Atempting to load backup.", LogType.ConsoleOutput); File.Copy("levels/" + message + ".lvl.backup", "levels/" + message + ".lvl", true); level = Map.Load(message); } else { Logger.Log("Backup of " + message + " does not exist.", LogType.ConsoleOutput); } } // Make sure we loaded something before adding it the level list if (level != null) { lock (Server.levels) { Server.levels.Add(level); } Player.GlobalMessage("Map \"" + level.name + "\" loaded."); try { int temp = int.Parse(phys); if (temp >= 0 && temp <= 2) { level.Physics = (Physics)temp; } } catch { Logger.Log("Physics variable invalid", LogType.ConsoleOutput); } } else { Logger.Log("Failed to load the backup of " + message, LogType.ConsoleOutput); } } else { Logger.Log("Map \"" + message + "\" doesn't exist!", LogType.ConsoleOutput); } } else { Logger.Log("You can't load more than " + Server.levels.Capacity + " levels!", LogType.ConsoleOutput); } } else { Logger.Log("Map capacity is 1 or lower, you can't load any levels!", LogType.ConsoleOutput); } } else { Logger.Log(message + " is already loaded!", LogType.ConsoleOutput); } } else { // We need to print help to the console somehow Logger.Log("Someday the console will support help messages", LogType.ConsoleOutput); } } catch (Exception e) { Logger.Log("An error occured with /load", LogType.Error); Logger.Log(e.Message, LogType.ErrorMessage); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Linq.Expressions; using System.Diagnostics; using System.Text; namespace Breeze.ContextProvider { /// <summary> /// A collection of static methods used to provide additional <see cref="System.Type"/> related services. /// </summary> public static class TypeFns { /// <summary> /// Returns an array of numeric types. /// </summary> public static readonly Type[] NumericTypes = new Type[] { typeof(Byte), typeof(Int16), typeof(UInt16), typeof(Int32), typeof(UInt32), typeof(Int64), typeof(UInt64), typeof(Single), typeof(Double), typeof(Decimal) }; /// <summary> /// Returns an array of integer types. /// </summary> public static readonly Type[] IntegerTypes = new Type[] { typeof(Byte), typeof(Int16), typeof(UInt16), typeof(Int32), typeof(UInt32), typeof(Int64), typeof(UInt64), }; /// <summary> /// Returns an array of decimal types. /// </summary> public static readonly Type[] DecimalTypes = new Type[] { typeof(Single), typeof(Double), typeof(Decimal) }; /// <summary> /// Returns an array of predefined types. /// </summary> public static readonly Type[] PredefinedTypes = { typeof(Object), typeof(Boolean), typeof(Char), typeof(String), typeof(SByte), typeof(Byte), typeof(Int16), typeof(UInt16), typeof(Int32), typeof(UInt32), typeof(Int64), typeof(UInt64), typeof(Single), typeof(Double), typeof(Decimal), typeof(DateTime), typeof(DateTimeOffset), typeof(TimeSpan), typeof(Guid), typeof(Math), typeof(Convert) }; /// <summary> /// Returns the name of either the specified type or its non-nullable counterpart. /// </summary> /// <param name="type"></param> /// <returns>the name of the given type</returns> public static string GetTypeName(Type type) { Type baseType = GetNonNullableType(type); string s = baseType.Name; if (type != baseType) s += '?'; return s; } /// <summary> /// Returns whether the specified type (or its non-nullable counterpart) represents an enumeration. /// </summary> /// <param name="type"></param> /// <returns>true if the specified type represents an enumeration; false otherwise</returns> public static bool IsEnumType(Type type) { return GetNonNullableType(type).IsEnum; } /// <summary> /// Returns whether the specified type (or its non-nullable counterpart) represents a numeric type. /// </summary> /// <param name="type"></param> /// <returns>true if the specified type is numeric; false otherwise</returns> public static bool IsNumericType(Type type) { return GetNumericTypeKind(type) != 0; } /// <summary> /// Returns whether the specified type (or its non-nullable counterpart) represents an integer type. /// </summary> /// <param name="type"></param> /// <returns></returns> public static bool IsIntegralType(Type type) { return GetNumericTypeKind(type) >= 2; } /// <summary> /// Returns whether the specified type (or its non-nullable counterpart) represents a signed integer type. /// </summary> /// <param name="type"></param> /// <returns></returns> public static bool IsSignedIntegralType(Type type) { return GetNumericTypeKind(type) == 2; } /// <summary> /// Returns whether the specified type (or its non-nullable counterpart) represents an unsigned integer type. /// </summary> /// <param name="type"></param> /// <returns></returns> public static bool IsUnsignedIntegralType(Type type) { return GetNumericTypeKind(type) == 3; } private static int GetNumericTypeKind(Type type) { type = GetNonNullableType(type); if (type.IsEnum) return 0; switch (Type.GetTypeCode(type)) { case TypeCode.Char: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return 1; case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: return 2; case TypeCode.Byte: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: return 3; default: return 0; } } /// <summary> /// Think about making public if used again. /// </summary> /// <param name="t"></param> /// <returns></returns> internal static bool IsGenericQueryableType(Type t) { if (typeof(IQueryable).IsAssignableFrom(t)) { var queryableType = typeof(IQueryable<>).MakeGenericType(TypeFns.GetElementType(t)); if (queryableType.IsAssignableFrom(t)) { return true; } } return false; } /// <summary> /// Returns true if the Type is an IGrouping. /// </summary> /// <param name="type"></param> /// <returns></returns> public static bool IsGroupingType(Type type) { return GetGroupingInterface(type) != null; } // may return null; /// <summary> /// Returns the IGrouping interface implemented by the type. /// </summary> /// <param name="type"></param> /// <returns>May return null if the specified type is not a grouping type</returns> public static Type GetGroupingInterface(Type type) { if (type.IsInterface && type.Name.StartsWith("IGrouping")) return type; return type.GetInterfaces().FirstOrDefault(i => i.Name.StartsWith("IGrouping")); } /// <summary> /// Gets a single generic argument from a specified type. /// </summary> /// <param name="type"></param> /// <returns>null if it can't find one or result is ambiguous</returns> public static Type GetGenericArgument(Type type) { if (!type.IsGenericType) return null; var genArgs = type.GetGenericArguments(); if (genArgs.Length != 1) return null; return genArgs[0]; } /// <summary> /// Gets the nullable type that corresponds to the given type. /// </summary> /// <param name="type"></param> /// <returns></returns> public static Type GetNullableType(Type type) { if (!type.IsValueType) { return type; } NullableInfo result; if (NullableInfoMap.TryGetValue(type, out result)) { return result.NullableType; } else { return null; } } /// <summary> /// Returns either the specified type or its non-nullable counterpart. /// </summary> /// <param name="type"></param> /// <returns></returns> public static Type GetNonNullableType(Type type) { return IsNullableType(type) ? type.GetGenericArguments()[0] : type; } /// <summary> /// Returns the element type of any enumerable type; /// </summary> /// <param name="seqType"></param> /// <returns></returns> public static Type GetElementType(Type seqType) { Type ienum = FindIEnumerable(seqType); if (ienum == null) return null; return ienum.GetGenericArguments()[0]; } /// <summary> /// /// </summary> /// <param name="seqType"></param> /// <returns></returns> public static Type FindIEnumerable(Type seqType) { if (seqType == null || seqType == typeof(string)) { return null; } if (seqType.IsArray) { return typeof(IEnumerable<>).MakeGenericType(seqType.GetElementType()); } if (seqType.IsGenericType) { foreach (Type arg in seqType.GetGenericArguments()) { Type ienum = typeof(IEnumerable<>).MakeGenericType(arg); if (ienum.IsAssignableFrom(seqType)) { return ienum; } } } Type[] ifaces = seqType.GetInterfaces(); if (ifaces != null && ifaces.Length > 0) { foreach (Type iface in ifaces) { Type ienum = FindIEnumerable(iface); if (ienum != null) return ienum; } } if (seqType.BaseType != null && seqType.BaseType != typeof(object)) { return FindIEnumerable(seqType.BaseType); } return null; } /// <summary> /// Returns whether the specified type is one of the <see cref="PredefinedTypes"/>. /// </summary> /// <param name="type"></param> /// <returns>true if the specified type is a predefined type; false otherwise</returns> public static bool IsPredefinedType(Type type) { foreach (Type t in PredefinedTypes) if (t == type) return true; return false; } /// <summary> /// Returns whether the specified type is one of the <see cref="PredefinedTypes"/> and /// optionally includes nullable versions of the same in the check. /// </summary> /// <param name="type"></param> /// <param name="includeNullable"></param> /// <returns></returns> public static bool IsPredefinedType(Type type, bool includeNullable) { if (includeNullable) { var nonnullType = GetNonNullableType(type); if (nonnullType != type) { return IsPredefinedType(nonnullType); } } return IsPredefinedType(type); } /// <summary> /// Returns whether the specified type is a nullable generic type, i.e. Nullable{T}. /// </summary> /// <param name="type"></param> /// <returns>true if the specified type is a nullable generic type; false otherwise</returns> public static bool IsNullableType(Type type) { return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } /// <summary> /// Gets the default value for a specified type. /// </summary> /// <param name="type"></param> /// <returns></returns> public static object GetDefaultValue(Type type) { if (type == null) return null; if (!type.IsValueType) return null; NullableInfo result; if (NullableInfoMap.TryGetValue(type, out result )) { return result.DefaultValue; } else { return Activator.CreateInstance(type); } } /// <summary> /// For internal use only. /// </summary> /// <typeparam name="TIn"></typeparam> /// <typeparam name="TOut"></typeparam> /// <param name="prototypeLambda"></param> /// <param name="resolvedTypes"></param> /// <returns></returns> public static MethodInfo GetMethodByExample<TIn, TOut>(Expression<Func<TIn, TOut>> prototypeLambda, params Type[] resolvedTypes) { var mi = (prototypeLambda.Body as MethodCallExpression).Method; if (!resolvedTypes.Any()) return mi; if (!mi.IsGenericMethod) return mi; var mi2 = mi.GetGenericMethodDefinition(); var mi3 = mi2.MakeGenericMethod(resolvedTypes); return mi3; } public static MethodInfo GetMethodByExample<TIn1, TIn2, TOut>(Expression<Func<TIn1, TIn2, TOut>> prototypeLambda, params Type[] resolvedTypes) { var mi = (prototypeLambda.Body as MethodCallExpression).Method; if (!resolvedTypes.Any()) return mi; if (!mi.IsGenericMethod) return mi; var mi2 = mi.GetGenericMethodDefinition(); var mi3 = mi2.MakeGenericMethod(resolvedTypes); return mi3; } /// <summary> /// Finds a specific public property or field. Will be automatically restricted as well by execution environment restrictions ( e.g. Silverlight). /// </summary> /// <param name="type"></param> /// <param name="memberName"></param> /// <param name="isPublic"></param> /// <param name="isStatic"></param> /// <returns></returns> public static MemberInfo FindPropertyOrField(Type type, string memberName, bool isPublic, bool isStatic) { var flags = isStatic ? BindingFlags.Static : BindingFlags.Instance; if (isPublic) { flags |= BindingFlags.Public; } else { flags |= BindingFlags.Public | BindingFlags.NonPublic; } return FindPropertyOrField(type, memberName, flags); } /// <summary> /// Finds a specific property or field /// </summary> /// <param name="type"></param> /// <param name="memberName"></param> /// <param name="bindingFlags"></param> /// <returns></returns> public static MemberInfo FindPropertyOrField(Type type, string memberName, BindingFlags bindingFlags) { foreach (Type t in GetSelfAndBaseTypes(type)) { MemberInfo[] members = t.FindMembers(MemberTypes.Property | MemberTypes.Field, bindingFlags, Type.FilterNameIgnoreCase, memberName); if (members.Length != 0) return members[0]; } return null; } /// <summary> /// Finds a specific public method. /// </summary> /// <param name="type"></param> /// <param name="methodName"></param> /// <param name="parameterTypes"></param> /// <returns></returns> public static MethodInfo FindMethod(Type type, string methodName, Type[] parameterTypes) { BindingFlags flags = BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Instance; return FindMethod(type, methodName, flags, parameterTypes); } /// <summary> /// Finds a specific method. /// </summary> /// <param name="type"></param> /// <param name="methodName"></param> /// <param name="flags"></param> /// <param name="genericArgTypes"></param> /// <param name="parameterTypes"></param> /// <returns></returns> public static MethodInfo FindMethod(Type type, string methodName, BindingFlags flags, Type[] genericArgTypes, Type[] parameterTypes) { var methods = FindMethods(type, methodName, flags, genericArgTypes, parameterTypes).ToList(); if (!methods.Any()) return null; var counts = methods.Select(m => { var candidateParameterTypes = m.GetParameters().Select(p => p.ParameterType); return candidateParameterTypes.Zip(parameterTypes, (a, b) => Object.Equals(a, b) ? 1 : 0).Sum(); }).ToList(); // best method is where most number of parameters are an exact match. var bestMethod = methods.OrderByDescending(m => { var candidateParameterTypes = m.GetParameters().Select(p => p.ParameterType); return candidateParameterTypes.Zip(parameterTypes, (a, b) => Object.Equals(a, b) ? 1 : 0).Sum(); }).First(); return bestMethod; } /// <summary> /// Finds all the methods that match specific criteria. /// </summary> /// <param name="type"></param> /// <param name="methodName"></param> /// <param name="flags"></param> /// <param name="genericArgTypes"></param> /// <param name="parameterTypes"></param> /// <returns></returns> public static IEnumerable<MethodInfo> FindMethods(Type type, string methodName, BindingFlags flags, Type[] genericArgTypes, Type[] parameterTypes) { foreach (Type t in GetSelfAndBaseTypes(type)) { MemberInfo[] members = t.FindMembers(MemberTypes.Method, flags, Type.FilterNameIgnoreCase, methodName); foreach (MethodInfo method in members.OfType<MethodInfo>()) { MethodInfo resolvedMethod; if (genericArgTypes != null && genericArgTypes.Length > 0) { var genericArgs = method.GetGenericArguments(); if (genericArgs.Length != genericArgTypes.Length) continue; // TODO: may need a try/catch around this call resolvedMethod = method.MakeGenericMethod(genericArgTypes); } else { resolvedMethod = method; } var parameters = resolvedMethod.GetParameters(); if (parameters.Length != parameterTypes.Length) continue; var candidateParameterTypes = parameters.Select(p => p.ParameterType); var ok = parameterTypes.Zip(candidateParameterTypes, (p, cp) => cp.IsAssignableFrom(p)).All(x => x); if (ok) { yield return resolvedMethod; } } } } /// <summary> /// Finds specific methods. /// </summary> /// <param name="type"></param> /// <param name="methodName"></param> /// <param name="flags"></param> /// <param name="parameterTypes"></param> /// <returns></returns> public static IEnumerable<MethodInfo> FindMethods(Type type, string methodName, BindingFlags flags, Type[] parameterTypes) { foreach (Type t in GetSelfAndBaseTypes(type)) { MemberInfo[] members = t.FindMembers(MemberTypes.Method, flags, Type.FilterNameIgnoreCase, methodName); foreach (MethodBase method in members.Cast<MethodBase>()) { var parameters = method.GetParameters(); if (parameters.Length != parameterTypes.Length) continue; var candidateParameterTypes = parameters.Select(p => p.ParameterType); candidateParameterTypes = candidateParameterTypes.Select((cpt, i) => parameterTypes[i].IsGenericTypeDefinition ? cpt.GetGenericTypeDefinition() : cpt); var ok = parameterTypes.Zip(candidateParameterTypes, (p, cp) => cp.IsAssignableFrom(p)).All(x => x); if (ok) { yield return (MethodInfo)method; } } } yield break; } /// <summary> /// Finds a specific method. /// </summary> /// <param name="type"></param> /// <param name="methodName"></param> /// <param name="isStatic"></param> /// <param name="parameterTypes"></param> /// <returns></returns> public static MethodInfo FindMethod(Type type, string methodName, bool isStatic, Type[] parameterTypes) { BindingFlags flags = BindingFlags.Public | BindingFlags.DeclaredOnly | (isStatic ? BindingFlags.Static : BindingFlags.Instance); return FindMethod(type, methodName, flags, parameterTypes); } /// <summary> /// Finds a specific method. /// </summary> /// <param name="type"></param> /// <param name="methodName"></param> /// <param name="flags"></param> /// <param name="parameterTypes"></param> /// <returns></returns> public static MethodInfo FindMethod(Type type, string methodName, BindingFlags flags, Type[] parameterTypes) { return FindMethods(type, methodName, flags, parameterTypes).FirstOrDefault(); } /// <summary> /// Finds a collection of generic methods. /// </summary> /// <param name="type"></param> /// <param name="methodName">Is case insensitive</param> /// <param name="flags"></param> /// <param name="genericArgTypes"></param> /// <returns></returns> public static IEnumerable<MethodInfo> FindGenericMethods(Type type, string methodName, BindingFlags flags, Type[] genericArgTypes) { foreach (Type t in GetSelfAndBaseTypes(type)) { MemberInfo[] members = t.FindMembers(MemberTypes.Method, flags, Type.FilterNameIgnoreCase, methodName); foreach (MethodInfo method in members.OfType<MethodInfo>()) { MethodInfo resolvedMethod; if (genericArgTypes != null && genericArgTypes.Length > 0) { var genericArgs = method.GetGenericArguments(); if (genericArgs.Length != genericArgTypes.Length) continue; // TODO: may need a try/catch around this call resolvedMethod = method.MakeGenericMethod(genericArgTypes); } else { resolvedMethod = method; } yield return resolvedMethod; } } } /// <summary> /// Returns a collection of types from which the given type directly inherits or implements. /// </summary> /// <param name="type"></param> /// <returns></returns> public static IEnumerable<Type> GetSelfAndBaseTypes(Type type) { if (type.IsInterface) return (new List<Type>() { type }).Concat(type.GetInterfaces()); if (type == typeof(Object)) return new List<Type>() { type }; var ifaceTypes = type.GetInterfaces(); var baseTypes = GetSelfAndBaseTypes(type.BaseType); var results = new[] { type }.Concat(baseTypes).Concat(ifaceTypes).Distinct().ToList(); return results; } /// <summary> /// Returns a collection of classes (not interfaces) from which the given type directly inherits. /// </summary> /// <param name="type"></param> /// <returns></returns> public static IEnumerable<Type> GetSelfAndBaseClasses(Type type) { while (type != null) { yield return type; type = type.BaseType; } } /// <summary> /// Determines whether the source type is compatible with the given target type. /// </summary> /// <remarks>This is a better implementation than <see cref="Type.IsAssignableFrom"/>.</remarks> /// <param name="source"></param> /// <param name="target"></param> /// <returns></returns> public static bool IsCompatibleWith(Type source, Type target) { if (source == target) return true; if (!target.IsValueType) return target.IsAssignableFrom(source); Type st = GetNonNullableType(source); Type tt = GetNonNullableType(target); if (st != source && tt == target) return false; TypeCode sc = st.IsEnum ? TypeCode.Object : Type.GetTypeCode(st); TypeCode tc = tt.IsEnum ? TypeCode.Object : Type.GetTypeCode(tt); switch (sc) { case TypeCode.SByte: switch (tc) { case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.Byte: switch (tc) { case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.Int16: switch (tc) { case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.UInt16: switch (tc) { case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.Int32: switch (tc) { case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.UInt32: switch (tc) { case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.Int64: switch (tc) { case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.UInt64: switch (tc) { case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.Single: switch (tc) { case TypeCode.Single: case TypeCode.Double: return true; } break; default: if (st == tt) return true; break; } return false; } /// <summary> /// Constructs a generic instance. /// </summary> /// <param name="genericType"></param> /// <param name="argTypes"></param> /// <returns></returns> public static Object ConstructGenericInstance(Type genericType, params Type[] argTypes) { if (genericType == null) { throw new ArgumentNullException("genericType"); } Type finalType = genericType.MakeGenericType(argTypes); return Activator.CreateInstance(finalType); } /// <summary> /// Constructs a generic list. /// </summary> /// <param name="type"></param> /// <returns></returns> public static IList MakeGenericList(Type type) { return (IList)TypeFns.ConstructGenericInstance(typeof(List<>), type); } /// <summary> /// Constructs a generic instance. Can only access public constructors. /// </summary> /// <param name="genericType"></param> /// <param name="argTypes"></param> /// <param name="constructorParams"></param> /// <returns></returns> public static Object ConstructGenericInstance(Type genericType, Type[] argTypes, params Object[] constructorParams) { if (genericType == null) { throw new ArgumentNullException("genericType"); } Type finalType = genericType.MakeGenericType(argTypes); return Activator.CreateInstance(finalType, constructorParams); } private static Dictionary<Type, NullableInfo> NullableInfoMap { get { lock (__nullableInfoMap) { if (__nullableInfoMap.Count == 0) { UpdateNullableInfoMap<Byte>(); UpdateNullableInfoMap<Int16>(); UpdateNullableInfoMap<UInt16>(); UpdateNullableInfoMap<Int32>(); UpdateNullableInfoMap<UInt32>(); UpdateNullableInfoMap<Int64>(); UpdateNullableInfoMap<UInt64>(); UpdateNullableInfoMap<Single>(); UpdateNullableInfoMap<Double>(); UpdateNullableInfoMap<Decimal>(); UpdateNullableInfoMap<Boolean>(); UpdateNullableInfoMap<Char>(); UpdateNullableInfoMap<DateTime>(); UpdateNullableInfoMap<DateTimeOffset>(); UpdateNullableInfoMap<TimeSpan>(); UpdateNullableInfoMap<Guid>(); } return __nullableInfoMap; } } } private static void UpdateNullableInfoMap<T>() where T : struct { __nullableInfoMap[typeof(T)] = new NullableInfo(typeof(Nullable<T>), default(T)); } private static Dictionary<Type, NullableInfo> __nullableInfoMap = new Dictionary<Type, NullableInfo>(); private class NullableInfo { public NullableInfo(Type pNullableType, Object pDefaultValue) { NullableType = pNullableType; DefaultValue = pDefaultValue; } public Type NullableType; public Object DefaultValue; } } public static class EnumerableExtns { // Not named GetHashCode to avoid naming conflict; object.GetHashCode would // always take precedence /// <summary> /// Returns a hashcode for a collection that /// uses a similar algorithm to that used by the .NET Tuple class. /// Order matters. /// </summary> /// <remarks> /// </remarks> /// <param name="items"></param> /// <returns></returns> public static int GetAggregateHashCode(this IEnumerable items) { // Old code - talk to Jay about issues with this. //int hash = 0; //foreach (Object item in items) { // if (item != null) { // hash ^= item.GetHashCode(); // } //} int hash = 0; foreach (Object item in items) { if (item != null) { if (hash == 0) { hash = item.GetHashCode(); } else { hash = ((hash << 5) + hash) ^ item.GetHashCode(); } } } return hash; } /// <summary> /// Concatenates the string version of each element in a collection using the delimiter provided. /// </summary> /// <param name="items">The enumerated items whose string formated elements will be concatenated</param> /// <param name="delimiter">Delimiter</param> /// <returns>A delimited string</returns> public static string ToAggregateString(this IEnumerable items, string delimiter) { StringBuilder sb = null; foreach (object aObject in items) { if (sb == null) { sb = new StringBuilder(); } else { sb.Append(delimiter); } sb.Append(aObject.ToString()); } if (sb == null) return String.Empty; return sb.ToString(); } } }
/* * ASCIIEncoding.cs - Implementation of the "System.Text.ASCIIEncoding" class. * * Copyright (C) 2001 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Text { using System; [Serializable] public class ASCIIEncoding : Encoding { // Magic number used by Windows for "ASCII". internal const int ASCII_CODE_PAGE = 20127; // Constructor. public ASCIIEncoding() : base(ASCII_CODE_PAGE) {} // Get the number of bytes needed to encode a character buffer. public override int GetByteCount(char[] chars, int index, int count) { if(chars == null) { throw new ArgumentNullException("chars"); } if(index < 0 || index > chars.Length) { throw new ArgumentOutOfRangeException ("index", _("ArgRange_Array")); } if(count < 0 || count > (chars.Length - index)) { throw new ArgumentOutOfRangeException ("count", _("ArgRange_Array")); } return count; } // Convenience wrappers for "GetByteCount". public override int GetByteCount(String s) { if(s == null) { throw new ArgumentNullException("s"); } return s.Length; } // Get the bytes that result from encoding a character buffer. public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if(chars == null) { throw new ArgumentNullException("chars"); } if(bytes == null) { throw new ArgumentNullException("bytes"); } if(charIndex < 0 || charIndex > chars.Length) { throw new ArgumentOutOfRangeException ("charIndex", _("ArgRange_Array")); } if(charCount < 0 || charCount > (chars.Length - charIndex)) { throw new ArgumentOutOfRangeException ("charCount", _("ArgRange_Array")); } if(byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException ("byteIndex", _("ArgRange_Array")); } if((bytes.Length - byteIndex) < charCount) { throw new ArgumentException (_("Arg_InsufficientSpace")); } int count = charCount; char ch; while(count-- > 0) { ch = chars[charIndex++]; if(ch < (char)0x80) { bytes[byteIndex++] = (byte)ch; } else { bytes[byteIndex++] = (byte)'?'; } } return charCount; } // Convenience wrappers for "GetBytes". public override int GetBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if(s == null) { throw new ArgumentNullException("s"); } if(bytes == null) { throw new ArgumentNullException("bytes"); } if(charIndex < 0 || charIndex > s.Length) { throw new ArgumentOutOfRangeException ("charIndex", _("ArgRange_StringIndex")); } if(charCount < 0 || charCount > (s.Length - charIndex)) { throw new ArgumentOutOfRangeException ("charCount", _("ArgRange_StringRange")); } if(byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException ("byteIndex", _("ArgRange_Array")); } if((bytes.Length - byteIndex) < charCount) { throw new ArgumentException(_("Arg_InsufficientSpace")); } int count = charCount; char ch; while(count-- > 0) { ch = s[charIndex++]; if(ch < (char)0x80) { bytes[byteIndex++] = (byte)ch; } else { bytes[byteIndex++] = (byte)'?'; } } return charCount; } // Get the number of characters needed to decode a byte buffer. public override int GetCharCount(byte[] bytes, int index, int count) { if(bytes == null) { throw new ArgumentNullException("bytes"); } if(index < 0 || index > bytes.Length) { throw new ArgumentOutOfRangeException ("index", _("ArgRange_Array")); } if(count < 0 || count > (bytes.Length - index)) { throw new ArgumentOutOfRangeException ("count", _("ArgRange_Array")); } return count; } // Get the characters that result from decoding a byte buffer. public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { if(bytes == null) { throw new ArgumentNullException("bytes"); } if(chars == null) { throw new ArgumentNullException("chars"); } if(byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException ("byteIndex", _("ArgRange_Array")); } if(byteCount < 0 || byteCount > (bytes.Length - byteIndex)) { throw new ArgumentOutOfRangeException ("byteCount", _("ArgRange_Array")); } if(charIndex < 0 || charIndex > chars.Length) { throw new ArgumentOutOfRangeException ("charIndex", _("ArgRange_Array")); } if((chars.Length - charIndex) < byteCount) { throw new ArgumentException(_("Arg_InsufficientSpace")); } int count = byteCount; byte ch; while(count-- > 0) { ch = bytes[byteIndex++]; if(ch < 0x80) { chars[charIndex++] = (char)ch; } else { chars[charIndex++] = '?'; } } return byteCount; } // Get the maximum number of bytes needed to encode a // specified number of characters. public override int GetMaxByteCount(int charCount) { if(charCount < 0) { throw new ArgumentOutOfRangeException ("charCount", _("ArgRange_NonNegative")); } return charCount; } // Get the maximum number of characters needed to decode a // specified number of bytes. public override int GetMaxCharCount(int byteCount) { if(byteCount < 0) { throw new ArgumentOutOfRangeException ("byteCount", _("ArgRange_NonNegative")); } return byteCount; } // Decode a buffer of bytes into a string. public override String GetString(byte[] bytes, int index, int count) { if(bytes == null) { throw new ArgumentNullException("bytes"); } if(index < 0 || index > bytes.Length) { throw new ArgumentOutOfRangeException ("index", _("ArgRange_Array")); } if(count < 0 || count > (bytes.Length - index)) { throw new ArgumentOutOfRangeException ("count", _("ArgRange_Array")); } if(count == 0) { return String.Empty; } String s = String.NewString(count); int posn = 0; while(count-- > 0) { s.SetChar(posn++, (char)(bytes[index++])); } return s; } public override String GetString(byte[] bytes) { if(bytes == null) { throw new ArgumentNullException("bytes"); } if(bytes.Length == 0) { return String.Empty; } int count = bytes.Length; int posn = 0; String s = String.NewString(count); while(count-- > 0) { s.SetChar(posn, (char)(bytes[posn])); ++posn; } return s; } #if !ECMA_COMPAT // Get the mail body name for this encoding. internal override String InternalBodyName { get { return "us-ascii"; } } // Get the human-readable name for this encoding. internal override String InternalEncodingName { get { return "US-ASCII"; } } // Get the mail agent header name for this encoding. internal override String InternalHeaderName { get { return "us-ascii"; } } // Determine if this encoding can be displayed in a mail/news agent. internal override bool InternalIsMailNewsDisplay { get { return true; } } // Determine if this encoding can be saved from a mail/news agent. internal override bool InternalIsMailNewsSave { get { return true; } } // Get the IANA-preferred Web name for this encoding. internal override String InternalWebName { get { return "us-ascii"; } } #endif // !ECMA_COMPAT }; // class ASCIIEncoding }; // namespace System.Text
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2009 Oracle. All rights reserved. * */ using System; using System.Collections.Generic; using System.Text; namespace BerkeleyDB { /// <summary> /// A class representing configuration parameters for <see cref="Database"/> /// </summary> public class DatabaseConfig { /// <summary> /// The Berkeley DB environment within which to create a database. If /// null, the database will be created stand-alone; that is, it is not /// part of any Berkeley DB environment. /// </summary> /// <remarks> /// The database access methods automatically make calls to the other /// subsystems in Berkeley DB, based on the enclosing environment. For /// example, if the environment has been configured to use locking, the /// access methods will automatically acquire the correct locks when /// reading and writing pages of the database. /// </remarks> public DatabaseEnvironment Env; /// <summary> /// The cache priority for pages referenced by the database. /// </summary> /// <remarks> /// The priority of a page biases the replacement algorithm to be more /// or less likely to discard a page when space is needed in the buffer /// pool. The bias is temporary, and pages will eventually be discarded /// if they are not referenced again. This priority is only advisory, /// and does not guarantee pages will be treated in a specific way. /// </remarks> public CachePriority Priority; /// <summary> /// The size of the shared memory buffer pool -- that is, the cache. /// </summary> /// <remarks> /// <para> /// The cache should be the size of the normal working data set of the /// application, with some small amount of additional memory for unusual /// situations. (Note: the working set is not the same as the number of /// pages accessed simultaneously, and is usually much larger.) /// </para> /// <para> /// The default cache size is 256KB, and may not be specified as less /// than 20KB. Any cache size less than 500MB is automatically increased /// by 25% to account for buffer pool overhead; cache sizes larger than /// 500MB are used as specified. The maximum size of a single cache is /// 4GB on 32-bit systems and 10TB on 64-bit systems. (All sizes are in /// powers-of-two, that is, 256KB is 2^18 not 256,000.) For information /// on tuning the Berkeley DB cache size, see Selecting a cache size in /// the Programmer's Reference Guide. /// </para> /// </remarks> public CacheInfo CacheSize; /// <summary> /// The byte order for integers in the stored database metadata. The /// host byte order of the machine where the Berkeley DB library was /// compiled is the default value. /// </summary> /// <remarks> /// <para> /// The access methods provide no guarantees about the byte ordering of /// the application data stored in the database, and applications are /// responsible for maintaining any necessary ordering. /// </para> /// <para> /// If creating additional databases in a single physical file, this /// parameter will be ignored and the byte order of the existing /// databases will be used. /// </para> /// </remarks> public ByteOrder ByteOrder = ByteOrder.MACHINE; internal bool pagesizeIsSet; private uint pgsz; /// <summary> /// The size of the pages used to hold items in the database, in bytes. /// </summary> /// <remarks> /// <para> /// The minimum page size is 512 bytes, the maximum page size is 64K /// bytes, and the page size must be a power-of-two. If the page size is /// not explicitly set, one is selected based on the underlying /// filesystem I/O block size. The automatically selected size has a /// lower limit of 512 bytes and an upper limit of 16K bytes. /// </para> /// <para> /// For information on tuning the Berkeley DB page size, see Selecting a /// page size in the Programmer's Reference Guide. /// </para> /// <para> /// If creating additional databases in a single physical file, this /// parameter will be ignored and the page size of the existing /// databases will be used. /// </para> /// </remarks> public uint PageSize { get { return pgsz; } set { pagesizeIsSet = true; pgsz = value; } } internal bool encryptionIsSet; private String encryptPwd; private EncryptionAlgorithm encryptAlg; /// <summary> /// Set the password and algorithm used by the Berkeley DB library to /// perform encryption and decryption. /// </summary> /// <param name="password"> /// The password used to perform encryption and decryption. /// </param> /// <param name="alg"> /// The algorithm used to perform encryption and decryption. /// </param> public void SetEncryption(String password, EncryptionAlgorithm alg) { encryptionIsSet = true; encryptPwd = password; encryptAlg = alg; } /// <summary> /// The password used to perform encryption and decryption. /// </summary> public string EncryptionPassword { get { return encryptPwd; } } /// <summary> /// The algorithm used to perform encryption and decryption. /// </summary> public EncryptionAlgorithm EncryptAlgorithm { get { return encryptAlg; } } /// <summary> /// The prefix string that appears before error messages issued by /// Berkeley DB. /// </summary> public String ErrorPrefix; /// <summary> /// The mechanism for reporting error messages to the application. /// </summary> /// <remarks> /// <para> /// In some cases, when an error occurs, Berkeley DB will call /// ErrorFeedback with additional error information. It is up to the /// delegate function to display the error message in an appropriate /// manner. /// </para> /// <para> /// This error-logging enhancement does not slow performance or /// significantly increase application size, and may be run during /// normal operation as well as during application debugging. /// </para> /// <para> /// For databases opened inside of Berkeley DB environments, setting /// ErrorFeedback affects the entire environment and is equivalent to /// setting <see cref="DatabaseEnvironment.ErrorFeedback"/>. /// </para> /// </remarks> public ErrorFeedbackDelegate ErrorFeedback; /// <summary> /// /// </summary> public DatabaseFeedbackDelegate Feedback; /// <summary> /// If true, do checksum verification of pages read into the cache from /// the backing filestore. /// </summary> /// <remarks> /// <para> /// Berkeley DB uses the SHA1 Secure Hash Algorithm if encryption is /// configured and a general hash algorithm if it is not. /// </para> /// <para> /// If the database already exists, this setting will be ignored. /// </para> /// </remarks> public bool DoChecksum; /// <summary> /// If true, Berkeley DB will not write log records for this database. /// </summary> /// <remarks> /// If Berkeley DB does not write log records, updates of this database /// will exhibit the ACI (atomicity, consistency, and isolation) /// properties, but not D (durability); that is, database integrity will /// be maintained, but if the application or system fails, integrity /// will not persist. The database file must be verified and/or restored /// from backup after a failure. In order to ensure integrity after /// application shut down, the database must be synced when closed, or /// all database changes must be flushed from the database environment /// cache using either /// <see cref="DatabaseEnvironment.Checkpoint"/> or /// <see cref="DatabaseEnvironment.SyncMemPool"/>. All database objects /// for a single physical file must set NonDurableTxns, including /// database objects for different databases in a physical file. /// </remarks> public bool NonDurableTxns; internal uint flags { get { uint ret = 0; ret |= DoChecksum ? Internal.DbConstants.DB_CHKSUM : 0; ret |= encryptionIsSet ? Internal.DbConstants.DB_ENCRYPT : 0; ret |= NonDurableTxns ? Internal.DbConstants.DB_TXN_NOT_DURABLE : 0; return ret; } } /// <summary> /// Enclose the open call within a transaction. If the call succeeds, /// the open operation will be recoverable and all subsequent database /// modification operations based on this handle will be transactionally /// protected. If the call fails, no database will have been created. /// </summary> public bool AutoCommit; /// <summary> /// Cause the database object to be free-threaded; that is, concurrently /// usable by multiple threads in the address space. /// </summary> public bool FreeThreaded; /// <summary> /// Do not map this database into process memory. /// </summary> public bool NoMMap; /// <summary> /// Open the database for reading only. Any attempt to modify items in /// the database will fail, regardless of the actual permissions of any /// underlying files. /// </summary> public bool ReadOnly; /// <summary> /// Support transactional read operations with degree 1 isolation. /// </summary> /// <remarks> /// Read operations on the database may request the return of modified /// but not yet committed data. This flag must be specified on all /// database objects used to perform dirty reads or database updates, /// otherwise requests for dirty reads may not be honored and the read /// may block. /// </remarks> public bool ReadUncommitted; /// <summary> /// Physically truncate the underlying file, discarding all previous databases it might have held. /// </summary> /// <remarks> /// <para> /// Underlying filesystem primitives are used to implement this flag. /// For this reason, it is applicable only to the file and cannot be /// used to discard databases within a file. /// </para> /// <para> /// This setting cannot be lock or transaction-protected, and it is an /// error to specify it in a locking or transaction-protected /// environment. /// </para> /// </remarks> public bool Truncate; /// <summary> /// Open the database with support for multiversion concurrency control. /// </summary> /// <remarks> /// This will cause updates to the database to follow a copy-on-write /// protocol, which is required to support snapshot isolation. This /// settting requires that the database be transactionally protected /// during its open and is not supported by the queue format. /// </remarks> public bool UseMVCC; internal uint openFlags { get { uint ret = 0; ret |= AutoCommit ? Internal.DbConstants.DB_AUTO_COMMIT : 0; ret |= FreeThreaded ? Internal.DbConstants.DB_THREAD : 0; ret |= NoMMap ? Internal.DbConstants.DB_NOMMAP : 0; ret |= ReadOnly ? Internal.DbConstants.DB_RDONLY : 0; ret |= ReadUncommitted ? Internal.DbConstants.DB_READ_UNCOMMITTED : 0; ret |= Truncate ? Internal.DbConstants.DB_TRUNCATE : 0; ret |= UseMVCC ? Internal.DbConstants.DB_MULTIVERSION : 0; return ret; } } /// <summary> /// Instantiate a new DatabaseConfig object /// </summary> public DatabaseConfig() { Env = null; Priority = CachePriority.DEFAULT; pagesizeIsSet = false; encryptionIsSet = false; ErrorPrefix = null; Feedback = null; DoChecksum = false; NonDurableTxns = false; AutoCommit = false; FreeThreaded = false; NoMMap = false; ReadOnly = false; ReadUncommitted = false; Truncate = false; UseMVCC = false; } } }
using System; using System.Net; using System.Collections.Generic; using System.Linq; using Rouse.Data; using System.Text; namespace Rouse.Server { public abstract class Responder { protected readonly Repository _repository; protected readonly ServerOptions _options; public Responder (Repository repository, ServerOptions options) { _repository = repository; _options = options; } public abstract void Respond (HttpListenerContext context); protected void RespondWithPlainText (int status, Action<System.IO.TextWriter> write, HttpListenerResponse res) { var encoding = Encoding.UTF8; res.StatusCode = status; if (_options.Debug) { res.ContentType = "text/plain"; res.ContentEncoding = encoding; var mem = new System.IO.MemoryStream (); using (var writer = new System.IO.StreamWriter (mem, System.Text.Encoding.UTF8)) { write (writer); } var b = mem.ToArray (); res.ContentLength64 = b.Length; using (var s = res.OutputStream) { s.Write (b, 0, b.Length); } } res.Close (); } protected void RespondWithPlainText (int status, string text, HttpListenerResponse res) { RespondWithPlainText (status, (w) => { w.Write (text); }, res); } protected void RespondWithError (Exception err, HttpListenerResponse res) { RespondWithPlainText (500, _options.Debug ? err.ToString () : "", res); } protected void RespondWithXml (int status, Action<System.Xml.XmlWriter> write, HttpListenerResponse res) { var settings = new System.Xml.XmlWriterSettings { Indent = true, }; RespondWithPlainText (status, (w) => { using (var xw = System.Xml.XmlWriter.Create (w, settings)) { write (xw); } }, res); } } public class ResourceResponder : Responder { Resource _prototype; public ResourceResponder (Resource prototype, Repository repository, ServerOptions options) : base (repository, options) { _prototype = prototype; } public override void Respond (HttpListenerContext context) { var resource = (Resource)Activator.CreateInstance (_prototype.GetType ()); var req = context.Request; var res = context.Response; try { if (req.HttpMethod == "POST") { Console.WriteLine ("POST"); using (var reqStream = req.InputStream) { resource.ReadXml (reqStream); } var val = resource.Validate (); if (val.IsValid) { throw new NotImplementedException (); res.StatusCode = 302; res.RedirectLocation = resource.Path; res.Close (); } else { RespondWithXml (400, val.WriteXml, res); } } //else if (req.HttpMethod == "GET") { //} else { res.StatusCode = 405; res.Close (); } } catch (Exception ex) { RespondWithError (ex, res); } } } public class QueryResponder : Responder { Query _prototype; public QueryResponder (Query prototype, Repository repository, ServerOptions options) : base (repository, options) { _prototype = prototype; } public override void Respond (HttpListenerContext context) { var list = (Query)Activator.CreateInstance (_prototype.GetType ()); _repository .Get (list) .ContinueWith ((task) => { var encoding = System.Text.Encoding.UTF8; Exception err = task.Exception; if (err == null) { var result = task.Result; try { var contentType = "application/xml"; var mem = new System.IO.MemoryStream (); result.WriteContent (contentType, mem, encoding); context.Response.StatusCode = 200; context.Response.ContentType = contentType; context.Response.ContentEncoding = encoding; var b = mem.ToArray (); context.Response.ContentLength64 = b.Length; using (var s = context.Response.OutputStream) { s.Write (b, 0, b.Length); } context.Response.Close (); } catch (Exception ex) { err = ex; } } if (err != null) { RespondWithError (err, context.Response); } }); } } public class ServerOptions { public string PathToProjectFile { get; set; } public string Hostname { get; set; } public int Port { get; set; } public bool Debug { get; set; } } public class App { ServerOptions _options; HttpListener _listener; Dictionary<string, Responder> _responders; Repository _repository; public static void Main (string[] args) { var options = new ServerOptions { PathToProjectFile = "", Hostname = "*", Port = 1337, Debug = true, }; foreach (var a in args) { options.PathToProjectFile = a; } new App (options).Run (); } public App (ServerOptions options) { _options = options; } void GetResponders () { _responders = new Dictionary<string, Responder>(); var asm = typeof (App).Assembly; var queryType = typeof (Query); var resourceType = typeof (Resource); foreach (var t in asm.GetTypes ()) { if (queryType.IsAssignableFrom (t) && !t.IsAbstract) { var query = (Query)Activator.CreateInstance (t); var r = new QueryResponder (query, _repository, _options); _responders [query.Path] = r; Console.WriteLine ("{0} -> {1}", query.Path, r); } else if (resourceType.IsAssignableFrom (t) && !t.IsAbstract) { var resource = (Resource)Activator.CreateInstance (t); var r = new ResourceResponder (resource, _repository, _options); _responders [resource.Path] = r; Console.WriteLine ("{0} -> {1}", resource.Path, r); } } } public void Run () { if (string.IsNullOrEmpty (_options.PathToProjectFile)) { _repository = new CacheRepository (new DataRepository (new Mono.Data.Sqlite.SqliteConnection ("Data Source=file::memory:"))); GetResponders (); RunHttpServer (); } } void RunHttpServer () { var prefix = "http://" + _options.Hostname + ":" + _options.Port + "/"; _listener = new HttpListener (); _listener.Prefixes.Add (prefix); _listener.Start (); _listener.BeginGetContext (OnGetContext, null); Console.WriteLine ("Listing at " + prefix); for (;;) { System.Threading.Thread.Sleep (5000); } } void OnGetContext (IAsyncResult ar) { var context = default(HttpListenerContext); try { context = _listener.EndGetContext (ar); } catch (Exception ex) { Console.WriteLine (ex); } _listener.BeginGetContext (OnGetContext, null); if (context != null) { var path = context.Request.Url.AbsolutePath; Responder resource; if (_responders.TryGetValue (path, out resource)) { resource.Respond (context); } else { context.Response.StatusCode = 404; context.Response.Close (); } } } } }
//#define DEBUGREADERS using System; using System.Collections.Generic; using System.IO; using Excel.Core; using System.Data; using System.Xml; using System.Globalization; using ExcelDataReader.Portable.Core.OpenXmlFormat; namespace Excel { public class ExcelOpenXmlReader : IExcelDataReader { #region Members private XlsxWorkbook _workbook; private bool _isValid; private bool _isClosed; private bool _isFirstRead; private string _exceptionMessage; private int _depth; private int _resultIndex; private int _emptyRowCount; private ZipWorker _zipWorker; private XmlReader _xmlReader; private Stream _sheetStream; private object[] _cellsValues; private object[] _savedCellsValues; private bool disposed; private bool _isFirstRowAsColumnNames; private const string COLUMN = "Column"; private string instanceId = Guid.NewGuid().ToString(); private List<int> _defaultDateTimeStyles; private string _namespaceUri; #endregion internal ExcelOpenXmlReader() { _isValid = true; _isFirstRead = true; _defaultDateTimeStyles = new List<int>(new int[] { 14, 15, 16, 17, 18, 19, 20, 21, 22, 45, 46, 47 }); } private void ReadGlobals() { _workbook = new XlsxWorkbook( _zipWorker.GetWorkbookStream(), _zipWorker.GetWorkbookRelsStream(), _zipWorker.GetSharedStringsStream(), _zipWorker.GetStylesStream()); CheckDateTimeNumFmts(_workbook.Styles.NumFmts); } private void CheckDateTimeNumFmts(List<XlsxNumFmt> list) { if (list.Count == 0) return; foreach (XlsxNumFmt numFmt in list) { if (string.IsNullOrEmpty(numFmt.FormatCode)) continue; string fc = numFmt.FormatCode.ToLower(); int pos; while ((pos = fc.IndexOf('"')) > 0) { int endPos = fc.IndexOf('"', pos + 1); if (endPos > 0) fc = fc.Remove(pos, endPos - pos + 1); } //it should only detect it as a date if it contains //dd mm mmm yy yyyy //h hh ss //AM PM //and only if these appear as "words" so either contained in [ ] //or delimted in someway //updated to not detect as date if format contains a # var formatReader = new FormatReader() {FormatString = fc}; if (formatReader.IsDateFormatString()) { _defaultDateTimeStyles.Add(numFmt.Id); } } } private void ReadSheetGlobals(XlsxWorksheet sheet) { if (_xmlReader != null) _xmlReader.Close(); if (_sheetStream != null) _sheetStream.Close(); _sheetStream = _zipWorker.GetWorksheetStream(sheet.Path); if (null == _sheetStream) return; _xmlReader = XmlReader.Create(_sheetStream); //count rows and cols in case there is no dimension elements int rows = 0; int cols = 0; _namespaceUri = null; int biggestColumn = 0; //used when no col elements and no dimension while (_xmlReader.Read()) { if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_worksheet) { //grab the namespaceuri from the worksheet element _namespaceUri = _xmlReader.NamespaceURI; } if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_dimension) { string dimValue = _xmlReader.GetAttribute(XlsxWorksheet.A_ref); sheet.Dimension = new XlsxDimension(dimValue); break; } //removed: Do not use col to work out number of columns as this is really for defining formatting, so may not contain all columns //if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_col) // cols++; if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_row) rows++; //check cells so we can find size of sheet if can't work it out from dimension or col elements (dimension should have been set before the cells if it was available) //ditto for cols if (sheet.Dimension == null && cols == 0 && _xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_c) { var refAttribute = _xmlReader.GetAttribute(XlsxWorksheet.A_r); if (refAttribute != null) { var thisRef = ReferenceHelper.ReferenceToColumnAndRow(refAttribute); if (thisRef[1] > biggestColumn) biggestColumn = thisRef[1]; } } } //if we didn't get a dimension element then use the calculated rows/cols to create it if (sheet.Dimension == null) { if (cols == 0) cols = biggestColumn; if (rows == 0 || cols == 0) { sheet.IsEmpty = true; return; } sheet.Dimension = new XlsxDimension(rows, cols); //we need to reset our position to sheet data _xmlReader.Close(); _sheetStream.Close(); _sheetStream = _zipWorker.GetWorksheetStream(sheet.Path); _xmlReader = XmlReader.Create(_sheetStream); } //read up to the sheetData element. if this element is empty then there aren't any rows and we need to null out dimension _xmlReader.ReadToFollowing(XlsxWorksheet.N_sheetData, _namespaceUri); if (_xmlReader.IsEmptyElement) { sheet.IsEmpty = true; } } private bool ReadSheetRow(XlsxWorksheet sheet) { if (null == _xmlReader) return false; if (_emptyRowCount != 0) { _cellsValues = new object[sheet.ColumnsCount]; _emptyRowCount--; _depth++; return true; } if (_savedCellsValues != null) { _cellsValues = _savedCellsValues; _savedCellsValues = null; _depth++; return true; } if ((_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_row) || _xmlReader.ReadToFollowing(XlsxWorksheet.N_row, _namespaceUri)) { _cellsValues = new object[sheet.ColumnsCount]; int rowIndex = int.Parse(_xmlReader.GetAttribute(XlsxWorksheet.A_r)); if (rowIndex != (_depth + 1)) if (rowIndex != (_depth + 1)) { _emptyRowCount = rowIndex - _depth - 1; } bool hasValue = false; string a_s = String.Empty; string a_t = String.Empty; string a_r = String.Empty; int col = 0; int row = 0; while (_xmlReader.Read()) { if (_xmlReader.Depth == 2) break; if (_xmlReader.NodeType == XmlNodeType.Element) { hasValue = false; if (_xmlReader.LocalName == XlsxWorksheet.N_c) { a_s = _xmlReader.GetAttribute(XlsxWorksheet.A_s); a_t = _xmlReader.GetAttribute(XlsxWorksheet.A_t); a_r = _xmlReader.GetAttribute(XlsxWorksheet.A_r); XlsxDimension.XlsxDim(a_r, out col, out row); } else if (_xmlReader.LocalName == XlsxWorksheet.N_v || _xmlReader.LocalName == XlsxWorksheet.N_t) { hasValue = true; } } if (_xmlReader.NodeType == XmlNodeType.Text && hasValue) { double number; object o = _xmlReader.Value; var style = NumberStyles.Any; var culture = CultureInfo.InvariantCulture; if (double.TryParse(o.ToString(), style, culture, out number)) o = number; if (null != a_t && a_t == XlsxWorksheet.A_s) //if string { o = Helpers.ConvertEscapeChars(_workbook.SST[int.Parse(o.ToString())]); } // Requested change 4: missing (it appears that if should be else if) else if (null != a_t && a_t == XlsxWorksheet.N_inlineStr) //if string inline { o = Helpers.ConvertEscapeChars(o.ToString()); } else if (a_t == "b") //boolean { o = _xmlReader.Value == "1"; } else if (null != a_s) //if something else { XlsxXf xf = _workbook.Styles.CellXfs[int.Parse(a_s)]; if (o != null && o.ToString() != string.Empty && IsDateTimeStyle(xf.NumFmtId)) o = Helpers.ConvertFromOATime(number); else if (xf.NumFmtId == 49) o = o.ToString(); } if (col - 1 < _cellsValues.Length) _cellsValues[col - 1] = o; } } if (_emptyRowCount > 0) { _savedCellsValues = _cellsValues; return ReadSheetRow(sheet); } _depth++; return true; } _xmlReader.Close(); if (_sheetStream != null) _sheetStream.Close(); return false; } private bool InitializeSheetRead() { if (ResultsCount <= 0) return false; ReadSheetGlobals(_workbook.Sheets[_resultIndex]); if (_workbook.Sheets[_resultIndex].Dimension == null) return false; _isFirstRead = false; _depth = 0; _emptyRowCount = 0; return true; } private bool IsDateTimeStyle(int styleId) { return _defaultDateTimeStyles.Contains(styleId); } #region IExcelDataReader Members public void Initialize(System.IO.Stream fileStream) { _zipWorker = new ZipWorker(); _zipWorker.Extract(fileStream); if (!_zipWorker.IsValid) { _isValid = false; _exceptionMessage = _zipWorker.ExceptionMessage; Close(); return; } ReadGlobals(); } public System.Data.DataSet AsDataSet() { return AsDataSet(true); } public System.Data.DataSet AsDataSet(bool convertOADateTime) { if (!_isValid) return null; DataSet dataset = new DataSet(); for (int ind = 0; ind < _workbook.Sheets.Count; ind++) { DataTable table = new DataTable(_workbook.Sheets[ind].Name); table.ExtendedProperties.Add("visiblestate", _workbook.Sheets[ind].VisibleState); ReadSheetGlobals(_workbook.Sheets[ind]); if (_workbook.Sheets[ind].Dimension == null) continue; _depth = 0; _emptyRowCount = 0; //DataTable columns if (!_isFirstRowAsColumnNames) { for (int i = 0; i < _workbook.Sheets[ind].ColumnsCount; i++) { table.Columns.Add(null, typeof(Object)); } } else if (ReadSheetRow(_workbook.Sheets[ind])) { for (int index = 0; index < _cellsValues.Length; index++) { if (_cellsValues[index] != null && _cellsValues[index].ToString().Length > 0) Helpers.AddColumnHandleDuplicate(table, _cellsValues[index].ToString()); else Helpers.AddColumnHandleDuplicate(table, string.Concat(COLUMN, index)); } } else continue; table.BeginLoadData(); while (ReadSheetRow(_workbook.Sheets[ind])) { table.Rows.Add(_cellsValues); } if (table.Rows.Count > 0) dataset.Tables.Add(table); table.EndLoadData(); } dataset.AcceptChanges(); Helpers.FixDataTypes(dataset); return dataset; } public bool IsFirstRowAsColumnNames { get { return _isFirstRowAsColumnNames; } set { _isFirstRowAsColumnNames = value; } } public bool IsValid { get { return _isValid; } } public string ExceptionMessage { get { return _exceptionMessage; } } public string Name { get { return (_resultIndex >= 0 && _resultIndex < ResultsCount) ? _workbook.Sheets[_resultIndex].Name : null; } } public string VisibleState { get { return (_resultIndex >= 0 && _resultIndex < ResultsCount) ? _workbook.Sheets[_resultIndex].VisibleState : null; } } public void Close() { _isClosed = true; if (_xmlReader != null) _xmlReader.Close(); if (_sheetStream != null) _sheetStream.Close(); if (_zipWorker != null) _zipWorker.Dispose(); } public int Depth { get { return _depth; } } public int ResultsCount { get { return _workbook == null ? -1 : _workbook.Sheets.Count; } } public bool IsClosed { get { return _isClosed; } } public bool NextResult() { if (_resultIndex >= (this.ResultsCount - 1)) return false; _resultIndex++; _isFirstRead = true; _savedCellsValues = null; return true; } public bool Read() { if (!_isValid) return false; if (_isFirstRead && !InitializeSheetRead()) { return false; } return ReadSheetRow(_workbook.Sheets[_resultIndex]); } public int FieldCount { get { return (_resultIndex >= 0 && _resultIndex < ResultsCount) ? _workbook.Sheets[_resultIndex].ColumnsCount : -1; } } public bool GetBoolean(int i) { if (IsDBNull(i)) return false; return Boolean.Parse(_cellsValues[i].ToString()); } public DateTime GetDateTime(int i) { if (IsDBNull(i)) return DateTime.MinValue; try { return (DateTime)_cellsValues[i]; } catch (InvalidCastException) { return DateTime.MinValue; } } public decimal GetDecimal(int i) { if (IsDBNull(i)) return decimal.MinValue; return decimal.Parse(_cellsValues[i].ToString()); } public double GetDouble(int i) { if (IsDBNull(i)) return double.MinValue; return double.Parse(_cellsValues[i].ToString()); } public float GetFloat(int i) { if (IsDBNull(i)) return float.MinValue; return float.Parse(_cellsValues[i].ToString()); } public short GetInt16(int i) { if (IsDBNull(i)) return short.MinValue; return short.Parse(_cellsValues[i].ToString()); } public int GetInt32(int i) { if (IsDBNull(i)) return int.MinValue; return int.Parse(_cellsValues[i].ToString()); } public long GetInt64(int i) { if (IsDBNull(i)) return long.MinValue; return long.Parse(_cellsValues[i].ToString()); } public string GetString(int i) { if (IsDBNull(i)) return null; return _cellsValues[i].ToString(); } public object GetValue(int i) { return _cellsValues[i]; } public bool IsDBNull(int i) { return (null == _cellsValues[i]) || (DBNull.Value == _cellsValues[i]); } public object this[int i] { get { return _cellsValues[i]; } } #endregion #region IDisposable Members public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!this.disposed) { if (disposing) { if (_xmlReader != null) ((IDisposable) _xmlReader).Dispose(); if (_sheetStream != null) _sheetStream.Dispose(); if (_zipWorker != null) _zipWorker.Dispose(); } _zipWorker = null; _xmlReader = null; _sheetStream = null; _workbook = null; _cellsValues = null; _savedCellsValues = null; disposed = true; } } ~ExcelOpenXmlReader() { Dispose(false); } #endregion #region Not Supported IDataReader Members public DataTable GetSchemaTable() { throw new NotSupportedException(); } public int RecordsAffected { get { throw new NotSupportedException(); } } #endregion #region Not Supported IDataRecord Members public byte GetByte(int i) { throw new NotSupportedException(); } public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length) { throw new NotSupportedException(); } public char GetChar(int i) { throw new NotSupportedException(); } public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length) { throw new NotSupportedException(); } public IDataReader GetData(int i) { throw new NotSupportedException(); } public string GetDataTypeName(int i) { throw new NotSupportedException(); } public Type GetFieldType(int i) { throw new NotSupportedException(); } public Guid GetGuid(int i) { throw new NotSupportedException(); } public string GetName(int i) { throw new NotSupportedException(); } public int GetOrdinal(string name) { throw new NotSupportedException(); } public int GetValues(object[] values) { throw new NotSupportedException(); } public object this[string name] { get { throw new NotSupportedException(); } } #endregion } }
#region Apache License, Version 2.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. // #endregion using System; using System.Collections.Generic; using System.Diagnostics; using EnvDTE; using EnvDTE80; using log4net; using Microsoft.VisualStudio.CommandBars; namespace NPanday.VisualStudio.Addin.Helper { public class VisualStudioControlsFinder { private readonly DTE2 _application; readonly IDictionary<string, List<string>> _containingCommandBarsByControlCaption = new Dictionary<string, List<string>>(); readonly IDictionary<string, List<string>> _containingCommandBarsByCammandName = new Dictionary<string, List<string>>(); readonly IDictionary<string, CommandBarControl> _controlByCaptionPath = new Dictionary<string, CommandBarControl>(); readonly IDictionary<string, CommandBarControl> _controlByBarAndCommandNamePath = new Dictionary<string, CommandBarControl>(); private bool _indexed; private static readonly ILog log = LogManager.GetLogger(typeof(VisualStudioControlsFinder)); public VisualStudioControlsFinder(DTE2 application) { _application = application; } /// <summary> /// Finds command controls using a <paramref name="lookup"/>. /// </summary> /// <param name="lookup"> /// Possible Formats: /// "buttoncaption", "commandname", "barname->buttoncaption", "barname->buttoncaption" /// </param> public bool TryFindCommands(string lookup, out CommandBarControl[] controls) { ensureIsIndexed(); CommandBars bars = ((CommandBars)_application.CommandBars); if (!lookup.Contains("->")) { List<string> barNames; if (_containingCommandBarsByCammandName.TryGetValue(lookup, out barNames)) { List<CommandBarControl> controlList = new List<CommandBarControl>(); foreach (string barName in barNames) { CommandBarControl commandOrNull = FindCommandOrNull(bars[barName], lookup); Debug.Assert(commandOrNull != null, "controls index seems to be incositent"); controlList.Add(commandOrNull); } controls = controlList.ToArray(); log.Debug( string.Format("Found {0} command bars containing a control bound to command '{1}': {2}", barNames.Count, lookup, String.Join(",", barNames.ToArray()))); return true; } string normalizedCaption = normalizeControlCaption(lookup); if (_containingCommandBarsByControlCaption.TryGetValue(normalizedCaption, out barNames)) { List<CommandBarControl> controlList = new List<CommandBarControl>(); foreach (string barName in barNames) { CommandBarControl commandOrNull = FindCommandOrNull(bars[barName], normalizedCaption); Debug.Assert(commandOrNull != null, "controls index seems to be incositent"); controlList.Add(commandOrNull); } controls = controlList.ToArray(); log.Debug( string.Format("Found {0} command bars containing a control with caption '{1}': {2}", barNames.Count, normalizedCaption, String.Join(",", barNames.ToArray()))); return true; } controls = new CommandBarControl[0]; log.Debug("Could not find any command bar containing a command or caption named: '" + lookup + "'."); return false; } string[] parts = lookup.Split(new string[] { "=>" }, 2, StringSplitOptions.RemoveEmptyEntries); string commandBarName = parts[0]; string controlCaptionOrCommandName = parts[1]; CommandBar commandBar = bars[commandBarName]; if (commandBar == null) { controls = new CommandBarControl[0]; log.Debug("Could not find any command bar named: '" + commandBarName + "', and hence no contained command or caption named: " + controlCaptionOrCommandName + "."); return false; } CommandBarControl control = FindCommandOrNull(commandBar, controlCaptionOrCommandName); if (control == null) { controls = new CommandBarControl[0]; log.Debug("Found commandbar '" + commandBarName + "', but it did not contain a control with command name or caption '" + controlCaptionOrCommandName + "'."); return false; } controls = new CommandBarControl[] { control }; return true; } public CommandBarControl FindCommandOrNull(CommandBar commandBar, string controlCaptionOrCommandName) { ensureIsIndexed(); CommandBarControl control; string commandNamePath = buildCommandCaptionPath(commandBar, controlCaptionOrCommandName); if (_controlByBarAndCommandNamePath.TryGetValue(commandNamePath, out control)) { return control; } string commandCaptionPath = buildCommandCaptionPath(commandBar, controlCaptionOrCommandName); if (_controlByCaptionPath.TryGetValue(commandCaptionPath, out control)) { string commandName = getButtonTargetCommand(control).Name; if (!string.IsNullOrEmpty(commandName)) { log.Debug( "Control found using it's caption path '" + commandCaptionPath + "'; its better to use the command name path: " + commandNamePath); } return control; } return null; } private static string buildCommandCaptionPath(CommandBar commandBar, string controlCaptionOrCommandName) { return commandBar.Name + "->" + controlCaptionOrCommandName.Replace("&", ""); } public void IndexCommands() { _indexed = true; Stopwatch watch = new Stopwatch(); watch.Start(); CommandBars commandBars = (CommandBars)_application.CommandBars; foreach (CommandBar commandBar in commandBars) { try { // sometimes accessing the commandbar name fails string dummy = commandBar.Name; } catch { // if this is the case, we simply omit it from the index continue; } foreach (CommandBarControl control in commandBar.Controls) { try { if (control is CommandBarButton) { string captionPath = indexByCaption(commandBar, control); indexByCommandName(captionPath, commandBar, control); //_logger.Log(Level.DEBUG, commandBar.Name + "->" + control.Caption + " -> " + command.Name); } else if (control is CommandBarPopup) { // TODO: Handle submenus // http://www.mztools.com/articles/2010/MZ2010001.aspx } } catch (Exception e) { log.Debug("Error on getting details for " + commandBar.Name + "->" + control.Caption + ":" + e.Message); } } } watch.Stop(); log.DebugFormat("Indexed {0} command items in {1:0.00} seconds.", 0, watch.Elapsed.TotalSeconds); } private void indexByCommandName(string captionPath, CommandBar commandBar, CommandBarControl control) { Command command = getButtonTargetCommand(control); if (!string.IsNullOrEmpty(command.Name)) { ensureValueForKey(_containingCommandBarsByCammandName, command.Name).Add(commandBar.Name); string commandPath = buildCommandCaptionPath(commandBar, command.Name); if (_controlByBarAndCommandNamePath.ContainsKey(commandPath)) { log.Debug( "Command path " + commandPath + " is ambiguous; " + captionPath + " ignored, first occurance wins."); } else { _controlByBarAndCommandNamePath.Add(commandPath, control); } } } private string indexByCaption(CommandBar commandBar, CommandBarControl control) { ensureValueForKey(_containingCommandBarsByControlCaption, normalizeControlCaption(control.Caption)).Add( commandBar.Name); string captionPath = buildCommandCaptionPath(commandBar, control.Caption); ; if (_controlByCaptionPath.ContainsKey(captionPath)) { log.Debug("Caption path '" + captionPath + "' is ambiguous; first occurance wins."); } else { _controlByCaptionPath[captionPath] = control; } return captionPath; } private Command getButtonTargetCommand(CommandBarControl control) { string guid; int id; _application.Commands.CommandInfo(control, out guid, out id); Command command = _application.Commands.Item(guid, id); return command; } public bool IsThisCommand(CommandBarControl control, string commandCaption) { CommandBar bar = control.Parent; string caption = control.Caption; if (string.IsNullOrEmpty(caption)) return false; if (control.Caption == commandCaption) return true; if (normalizeControlCaption(caption) == commandCaption) return true; try { string barName = bar.Name; // fails sometimes } catch { return false; } return (buildCommandCaptionPath(bar, caption) == commandCaption); } private static string normalizeControlCaption(string caption) { return caption.Replace("&", ""); } private void ensureIsIndexed() { if (!_indexed) { throw new InvalidOperationException("Please make sure IndexControls() ran, before any other methods are called."); } } private static TValue ensureValueForKey<TKey, TValue>(IDictionary<TKey, TValue> dict, TKey key) where TValue : new() { TValue list; if (!dict.TryGetValue(key, out list)) { dict.Add(key, list = new TValue()); } return list; } } }
// 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.NativeCrypto; namespace System.Security.Cryptography { #if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS internal static partial class ECDiffieHellmanImplementation { #endif public sealed partial class ECDiffieHellmanCng : ECDiffieHellman { public override void ImportParameters(ECParameters parameters) { parameters.Validate(); ECCurve curve = parameters.Curve; bool includePrivateParamerters = (parameters.D != null); if (curve.IsPrime) { byte[] ecExplicitBlob = ECCng.GetPrimeCurveBlob(ref parameters, ecdh: true); ImportFullKeyBlob(ecExplicitBlob, includePrivateParamerters); } else if (curve.IsNamed) { // FriendlyName is required; an attempt was already made to default it in ECCurve if (string.IsNullOrEmpty(curve.Oid.FriendlyName)) { throw new PlatformNotSupportedException( string.Format(SR.Cryptography_InvalidCurveOid, curve.Oid.Value)); } byte[] ecNamedCurveBlob = ECCng.GetNamedCurveBlob(ref parameters, ecdh: true); ImportKeyBlob(ecNamedCurveBlob, curve.Oid.FriendlyName, includePrivateParamerters); } else { throw new PlatformNotSupportedException( string.Format(SR.Cryptography_CurveNotSupported, curve.CurveType.ToString())); } } public override ECParameters ExportExplicitParameters(bool includePrivateParameters) { byte[] blob = ExportFullKeyBlob(includePrivateParameters); try { ECParameters ecparams = new ECParameters(); ECCng.ExportPrimeCurveParameters(ref ecparams, blob, includePrivateParameters); return ecparams; } finally { Array.Clear(blob, 0, blob.Length); } } public override ECParameters ExportParameters(bool includePrivateParameters) { ECParameters ecparams = new ECParameters(); string curveName = GetCurveName(out string oidValue); byte[] blob = null; try { if (string.IsNullOrEmpty(curveName)) { blob = ExportFullKeyBlob(includePrivateParameters); ECCng.ExportPrimeCurveParameters(ref ecparams, blob, includePrivateParameters); } else { blob = ExportKeyBlob(includePrivateParameters); ECCng.ExportNamedCurveParameters(ref ecparams, blob, includePrivateParameters); ecparams.Curve = ECCurve.CreateFromOid(new Oid(oidValue, curveName)); } return ecparams; } finally { if (blob != null) { Array.Clear(blob, 0, blob.Length); } } } public override void ImportPkcs8PrivateKey(ReadOnlySpan<byte> source, out int bytesRead) { CngPkcs8.Pkcs8Response response = CngPkcs8.ImportPkcs8PrivateKey(source, out int localRead); ProcessPkcs8Response(response); bytesRead = localRead; } public override void ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, ReadOnlySpan<byte> source, out int bytesRead) { CngPkcs8.Pkcs8Response response = CngPkcs8.ImportEncryptedPkcs8PrivateKey( passwordBytes, source, out int localRead); ProcessPkcs8Response(response); bytesRead = localRead; } public override void ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, ReadOnlySpan<byte> source, out int bytesRead) { CngPkcs8.Pkcs8Response response = CngPkcs8.ImportEncryptedPkcs8PrivateKey( password, source, out int localRead); ProcessPkcs8Response(response); bytesRead = localRead; } private void ProcessPkcs8Response(CngPkcs8.Pkcs8Response response) { // Wrong algorithm? if (response.GetAlgorithmGroup() != BCryptNative.AlgorithmName.ECDH) { response.FreeKey(); throw new CryptographicException(SR.Cryptography_NotValidPublicOrPrivateKey); } AcceptImport(response); } public override byte[] ExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, PbeParameters pbeParameters) { if (pbeParameters == null) throw new ArgumentNullException(nameof(pbeParameters)); return CngPkcs8.ExportEncryptedPkcs8PrivateKey( this, passwordBytes, pbeParameters); } public override byte[] ExportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, PbeParameters pbeParameters) { if (pbeParameters == null) { throw new ArgumentNullException(nameof(pbeParameters)); } PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, ReadOnlySpan<byte>.Empty); if (CngPkcs8.IsPlatformScheme(pbeParameters)) { return ExportEncryptedPkcs8(password, pbeParameters.IterationCount); } return CngPkcs8.ExportEncryptedPkcs8PrivateKey( this, password, pbeParameters); } public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, PbeParameters pbeParameters, Span<byte> destination, out int bytesWritten) { if (pbeParameters == null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan<char>.Empty, passwordBytes); return CngPkcs8.TryExportEncryptedPkcs8PrivateKey( this, passwordBytes, pbeParameters, destination, out bytesWritten); } public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, PbeParameters pbeParameters, Span<byte> destination, out int bytesWritten) { if (pbeParameters == null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, ReadOnlySpan<byte>.Empty); if (CngPkcs8.IsPlatformScheme(pbeParameters)) { return TryExportEncryptedPkcs8( password, pbeParameters.IterationCount, destination, out bytesWritten); } return CngPkcs8.TryExportEncryptedPkcs8PrivateKey( this, password, pbeParameters, destination, out bytesWritten); } } #if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS } #endif }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition.Hosting; using System.Linq; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.Commands; using Microsoft.CodeAnalysis.Editor.CSharp.CallHierarchy; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy; using Microsoft.CodeAnalysis.Editor.Implementation.Notification; using Microsoft.CodeAnalysis.Editor.SymbolMapping; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Notification; using Microsoft.VisualStudio.Language.CallHierarchy; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CallHierarchy { public class CallHierarchyTestState { private readonly CallHierarchyCommandHandler _commandHandler; private readonly MockCallHierarchyPresenter _presenter; internal TestWorkspace Workspace; private readonly ITextBuffer _subjectBuffer; private readonly IWpfTextView _textView; private class MockCallHierarchyPresenter : ICallHierarchyPresenter { public CallHierarchyItem PresentedRoot; public void PresentRoot(CallHierarchyItem root) { this.PresentedRoot = root; } } private class MockSearchCallback : ICallHierarchySearchCallback { private readonly Action<CallHierarchyItem> _verifyMemberItem; private readonly TaskCompletionSource<object> _completionSource = new TaskCompletionSource<object>(); private readonly Action<ICallHierarchyNameItem> _verifyNameItem; public MockSearchCallback(Action<CallHierarchyItem> verify) { _verifyMemberItem = verify; } public MockSearchCallback(Action<ICallHierarchyNameItem> verify) { _verifyNameItem = verify; } public void AddResult(ICallHierarchyNameItem item) { _verifyNameItem(item); } public void AddResult(ICallHierarchyMemberItem item) { _verifyMemberItem((CallHierarchyItem)item); } public void InvalidateResults() { } public void ReportProgress(int current, int maximum) { } public void SearchFailed(string message) { _completionSource.SetException(new Exception(message)); } public void SearchSucceeded() { _completionSource.SetResult(null); } internal void WaitForCompletion() { _completionSource.Task.Wait(); } } public static async Task<CallHierarchyTestState> CreateAsync(XElement markup, params Type[] additionalTypes) { var exportProvider = CreateExportProvider(additionalTypes); var workspace = await TestWorkspaceFactory.CreateWorkspaceAsync(markup, exportProvider: exportProvider); return new CallHierarchyTestState(workspace); } private CallHierarchyTestState(TestWorkspace workspace) { this.Workspace = workspace; var testDocument = Workspace.Documents.Single(d => d.CursorPosition.HasValue); _textView = testDocument.GetTextView(); _subjectBuffer = testDocument.GetTextBuffer(); var provider = Workspace.GetService<CallHierarchyProvider>(); var notificationService = Workspace.Services.GetService<INotificationService>() as INotificationServiceCallback; var callback = new Action<string, string, NotificationSeverity>((message, title, severity) => NotificationMessage = message); notificationService.NotificationCallback = callback; _presenter = new MockCallHierarchyPresenter(); _commandHandler = new CallHierarchyCommandHandler(new[] { _presenter }, provider, TestWaitIndicator.Default); } private static VisualStudio.Composition.ExportProvider CreateExportProvider(Type[] additionalTypes) { var catalog = TestExportProvider.MinimumCatalogWithCSharpAndVisualBasic .WithPart(typeof(CallHierarchyProvider)) .WithPart(typeof(SymbolMappingServiceFactory)) .WithPart(typeof(EditorNotificationServiceFactory)) .WithParts(additionalTypes); return MinimalTestExportProvider.CreateExportProvider(catalog); } public static async Task<CallHierarchyTestState> CreateAsync(string markup, params Type[] additionalTypes) { var exportProvider = CreateExportProvider(additionalTypes); var workspace = await CSharpWorkspaceFactory.CreateWorkspaceFromFileAsync(markup, exportProvider: exportProvider); return new CallHierarchyTestState(markup, workspace); } private CallHierarchyTestState(string markup, TestWorkspace workspace) { this.Workspace = workspace; var testDocument = Workspace.Documents.Single(d => d.CursorPosition.HasValue); _textView = testDocument.GetTextView(); _subjectBuffer = testDocument.GetTextBuffer(); var provider = Workspace.GetService<CallHierarchyProvider>(); var notificationService = Workspace.Services.GetService<INotificationService>() as INotificationServiceCallback; var callback = new Action<string, string, NotificationSeverity>((message, title, severity) => NotificationMessage = message); notificationService.NotificationCallback = callback; _presenter = new MockCallHierarchyPresenter(); _commandHandler = new CallHierarchyCommandHandler(new[] { _presenter }, provider, TestWaitIndicator.Default); } internal string NotificationMessage { get; private set; } internal CallHierarchyItem GetRoot() { var args = new ViewCallHierarchyCommandArgs(_textView, _subjectBuffer); _commandHandler.ExecuteCommand(args, () => { }); return _presenter.PresentedRoot; } internal IImmutableSet<Document> GetDocuments(string[] documentNames) { var selectedDocuments = new List<Document>(); this.Workspace.CurrentSolution.Projects.Do(p => p.Documents.Where(d => documentNames.Contains(d.Name)).Do(d => selectedDocuments.Add(d))); return ImmutableHashSet.CreateRange<Document>(selectedDocuments); } internal void SearchRoot(CallHierarchyItem root, string displayName, Action<CallHierarchyItem> verify, CallHierarchySearchScope scope, IImmutableSet<Document> documents = null) { var callback = new MockSearchCallback(verify); var category = root.SupportedSearchCategories.First(c => c.DisplayName == displayName).Name; if (documents != null) { root.StartSearchWithDocuments(category, scope, callback, documents); } else { root.StartSearch(category, scope, callback); } callback.WaitForCompletion(); } internal void SearchRoot(CallHierarchyItem root, string displayName, Action<ICallHierarchyNameItem> verify, CallHierarchySearchScope scope, IImmutableSet<Document> documents = null) { var callback = new MockSearchCallback(verify); var category = root.SupportedSearchCategories.First(c => c.DisplayName == displayName).Name; if (documents != null) { root.StartSearchWithDocuments(category, scope, callback, documents); } else { root.StartSearch(category, scope, callback); } callback.WaitForCompletion(); } internal string ConvertToName(ICallHierarchyMemberItem root) { var name = root.MemberName; if (!string.IsNullOrEmpty(root.ContainingTypeName)) { name = root.ContainingTypeName + "." + name; } if (!string.IsNullOrEmpty(root.ContainingNamespaceName)) { name = root.ContainingNamespaceName + "." + name; } return name; } internal string ConvertToName(ICallHierarchyNameItem root) { return root.Name; } internal void VerifyRoot(CallHierarchyItem root, string name = "", string[] expectedCategories = null) { Assert.Equal(name, ConvertToName(root)); if (expectedCategories != null) { var categories = root.SupportedSearchCategories.Select(s => s.DisplayName); foreach (var category in expectedCategories) { Assert.Contains(category, categories); } } } internal void VerifyResultName(CallHierarchyItem root, string searchCategory, string[] expectedCallers, CallHierarchySearchScope scope = CallHierarchySearchScope.EntireSolution, IImmutableSet<Document> documents = null) { this.SearchRoot(root, searchCategory, (ICallHierarchyNameItem c) => { Assert.True(expectedCallers.Any()); Assert.True(expectedCallers.Contains(ConvertToName(c))); }, scope, documents); } internal void VerifyResult(CallHierarchyItem root, string searchCategory, string[] expectedCallers, CallHierarchySearchScope scope = CallHierarchySearchScope.EntireSolution, IImmutableSet<Document> documents = null) { this.SearchRoot(root, searchCategory, (CallHierarchyItem c) => { Assert.True(expectedCallers.Any()); Assert.True(expectedCallers.Contains(ConvertToName(c))); }, scope, documents); } internal void Navigate(CallHierarchyItem root, string searchCategory, string callSite, CallHierarchySearchScope scope = CallHierarchySearchScope.EntireSolution, IImmutableSet<Document> documents = null) { CallHierarchyItem item = null; this.SearchRoot(root, searchCategory, (CallHierarchyItem c) => item = c, scope, documents); if (callSite == ConvertToName(item)) { var detail = item.Details.FirstOrDefault(); if (detail != null) { detail.NavigateTo(); } else { item.NavigateTo(); } } } } }
using System; using System.Windows.Forms; using System.Drawing; using System.Runtime.InteropServices; using System.ComponentModel; namespace WeifenLuo.WinFormsUI.Docking { [ToolboxItem(false)] public partial class DockWindow : Panel, INestedPanesContainer, ISplitterDragSource { private DockPanel m_dockPanel; private DockState m_dockState; private SplitterControl m_splitter; private NestedPaneCollection m_nestedPanes; internal DockWindow(DockPanel dockPanel, DockState dockState) { m_nestedPanes = new NestedPaneCollection(this); m_dockPanel = dockPanel; m_dockState = dockState; Visible = false; SuspendLayout(); if (DockState == DockState.DockLeft || DockState == DockState.DockRight || DockState == DockState.DockTop || DockState == DockState.DockBottom) { m_splitter = new SplitterControl(); Controls.Add(m_splitter); } if (DockState == DockState.DockLeft) { Dock = DockStyle.Left; m_splitter.Dock = DockStyle.Right; } else if (DockState == DockState.DockRight) { Dock = DockStyle.Right; m_splitter.Dock = DockStyle.Left; } else if (DockState == DockState.DockTop) { Dock = DockStyle.Top; m_splitter.Dock = DockStyle.Bottom; } else if (DockState == DockState.DockBottom) { Dock = DockStyle.Bottom; m_splitter.Dock = DockStyle.Top; } else if (DockState == DockState.Document) { Dock = DockStyle.Fill; } ResumeLayout(); } public VisibleNestedPaneCollection VisibleNestedPanes { get { return NestedPanes.VisibleNestedPanes; } } public NestedPaneCollection NestedPanes { get { return m_nestedPanes; } } public DockPanel DockPanel { get { return m_dockPanel; } } public DockState DockState { get { return m_dockState; } } public bool IsFloat { get { return DockState == DockState.Float; } } internal DockPane DefaultPane { get { return VisibleNestedPanes.Count == 0 ? null : VisibleNestedPanes[0]; } } public virtual Rectangle DisplayingRectangle { get { Rectangle rect = ClientRectangle; // if DockWindow is document, exclude the border if (DockState == DockState.Document) { rect.X += 1; rect.Y += 1; rect.Width -= 2; rect.Height -= 2; } // exclude the splitter else if (DockState == DockState.DockLeft) rect.Width -= Measures.SplitterSize; else if (DockState == DockState.DockRight) { rect.X += Measures.SplitterSize; rect.Width -= Measures.SplitterSize; } else if (DockState == DockState.DockTop) rect.Height -= Measures.SplitterSize; else if (DockState == DockState.DockBottom) { rect.Y += Measures.SplitterSize; rect.Height -= Measures.SplitterSize; } return rect; } } protected override void OnPaint(PaintEventArgs e) { // if DockWindow is document, draw the border // orzFly changed this //if (DockState == DockState.Document) //e.Graphics.DrawRectangle(SystemPens.ControlDark, ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width - 1, ClientRectangle.Height - 1); base.OnPaint(e); } protected override void OnLayout(LayoutEventArgs levent) { VisibleNestedPanes.Refresh(); if (VisibleNestedPanes.Count == 0) { if (Visible) Visible = false; } else if (!Visible) { Visible = true; VisibleNestedPanes.Refresh(); } base.OnLayout (levent); } #region ISplitterDragSource Members void ISplitterDragSource.BeginDrag(Rectangle rectSplitter) { } void ISplitterDragSource.EndDrag() { } bool ISplitterDragSource.IsVertical { get { return (DockState == DockState.DockLeft || DockState == DockState.DockRight); } } Rectangle ISplitterDragSource.DragLimitBounds { get { Rectangle rectLimit = DockPanel.DockArea; Point location; if ((Control.ModifierKeys & Keys.Shift) == 0) location = Location; else location = DockPanel.DockArea.Location; if (((ISplitterDragSource)this).IsVertical) { rectLimit.X += MeasurePane.MinSize; rectLimit.Width -= 2 * MeasurePane.MinSize; rectLimit.Y = location.Y; if ((Control.ModifierKeys & Keys.Shift) == 0) rectLimit.Height = Height; } else { rectLimit.Y += MeasurePane.MinSize; rectLimit.Height -= 2 * MeasurePane.MinSize; rectLimit.X = location.X; if ((Control.ModifierKeys & Keys.Shift) == 0) rectLimit.Width = Width; } return DockPanel.RectangleToScreen(rectLimit); } } void ISplitterDragSource.MoveSplitter(int offset) { if ((Control.ModifierKeys & Keys.Shift) != 0) SendToBack(); Rectangle rectDockArea = DockPanel.DockArea; if (DockState == DockState.DockLeft && rectDockArea.Width > 0) { if (DockPanel.DockLeftPortion > 1) DockPanel.DockLeftPortion = Width + offset; else DockPanel.DockLeftPortion += ((double)offset) / (double)rectDockArea.Width; } else if (DockState == DockState.DockRight && rectDockArea.Width > 0) { if (DockPanel.DockRightPortion > 1) DockPanel.DockRightPortion = Width - offset; else DockPanel.DockRightPortion -= ((double)offset) / (double)rectDockArea.Width; } else if (DockState == DockState.DockBottom && rectDockArea.Height > 0) { if (DockPanel.DockBottomPortion > 1) DockPanel.DockBottomPortion = Height - offset; else DockPanel.DockBottomPortion -= ((double)offset) / (double)rectDockArea.Height; } else if (DockState == DockState.DockTop && rectDockArea.Height > 0) { if (DockPanel.DockTopPortion > 1) DockPanel.DockTopPortion = Height + offset; else DockPanel.DockTopPortion += ((double)offset) / (double)rectDockArea.Height; } } #region IDragSource Members Control IDragSource.DragControl { get { return this; } } #endregion #endregion } }
/* * Copyright (c) 2014 Behrooz Amoozad * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the bd2 nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL Behrooz Amoozad 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.Concurrent; using BD2.Daemon.Buses; namespace BD2.Daemon.Streams { public sealed class TransparentStream : System.IO.Stream { ConcurrentDictionary<Guid, TransparentStreamAsyncResult> pendingCanReadRequests = new ConcurrentDictionary<Guid, TransparentStreamAsyncResult> (); ConcurrentDictionary<Guid, TransparentStreamAsyncResult> pendingCanSeekRequests = new ConcurrentDictionary<Guid, TransparentStreamAsyncResult> (); ConcurrentDictionary<Guid, TransparentStreamAsyncResult> pendingCanTimeoutRequests = new ConcurrentDictionary<Guid, TransparentStreamAsyncResult> (); ConcurrentDictionary<Guid, TransparentStreamAsyncResult> pendingCanWriteRequests = new ConcurrentDictionary<Guid, TransparentStreamAsyncResult> (); ConcurrentDictionary<Guid, TransparentStreamAsyncResult> pendingCloseRequests = new ConcurrentDictionary<Guid, TransparentStreamAsyncResult> (); ConcurrentDictionary<Guid, TransparentStreamAsyncResult> pendingWriteRequests = new ConcurrentDictionary<Guid, TransparentStreamAsyncResult> (); ConcurrentDictionary<Guid, TransparentStreamAsyncResult> pendingFlushRequests = new ConcurrentDictionary<Guid, TransparentStreamAsyncResult> (); ConcurrentDictionary<Guid, TransparentStreamAsyncResult> pendingGetLengthRequests = new ConcurrentDictionary<Guid, TransparentStreamAsyncResult> (); ConcurrentDictionary<Guid, TransparentStreamAsyncResult> pendingGetPositionRequests = new ConcurrentDictionary<Guid, TransparentStreamAsyncResult> (); ConcurrentDictionary<Guid, TransparentStreamAsyncResult> pendingGetReadTimeoutRequests = new ConcurrentDictionary<Guid, TransparentStreamAsyncResult> (); ConcurrentDictionary<Guid, TransparentStreamAsyncResult> pendingSeekRequests = new ConcurrentDictionary<Guid, TransparentStreamAsyncResult> (); ConcurrentDictionary<Guid, TransparentStreamAsyncResult> pendingGetWriteTimeoutRequests = new ConcurrentDictionary<Guid, TransparentStreamAsyncResult> (); ConcurrentDictionary<Guid, TransparentStreamAsyncResult> pendingSetLengthRequests = new ConcurrentDictionary<Guid, TransparentStreamAsyncResult> (); ConcurrentDictionary<Guid, TransparentStreamAsyncResult> pendingSetPositionRequests = new ConcurrentDictionary<Guid, TransparentStreamAsyncResult> (); ConcurrentDictionary<Guid, Tuple <TransparentStreamAsyncResult, byte[], int, int>> pendingReadRequests = new ConcurrentDictionary<Guid, Tuple <TransparentStreamAsyncResult, byte[], int, int>> (); ConcurrentDictionary<Guid, TransparentStreamAsyncResult> pendingSetReadTimeoutRequests = new ConcurrentDictionary<Guid, TransparentStreamAsyncResult> (); ConcurrentDictionary<Guid, TransparentStreamAsyncResult> pendingSetWriteTimeoutRequests = new ConcurrentDictionary<Guid, TransparentStreamAsyncResult> (); ServiceAgent agent; public ServiceAgent Agent { get { return agent; } } Guid streamID; public Guid StreamID { get { return streamID; } } ObjectBusSession objectBusSession; public ObjectBusSession ObjectBusSession { get { return objectBusSession; } } internal TransparentStream (ServiceAgent agent, Guid streamID, ObjectBusSession objectBusSession) { if (agent == null) throw new ArgumentNullException ("agent"); if (objectBusSession == null) throw new ArgumentNullException ("objectBusSession"); this.agent = agent; this.streamID = streamID; this.objectBusSession = objectBusSession; } #region implemented abstract members of Stream public override void Flush () { EndFlush (BeginFlush ()); } public IAsyncResult BeginFlush () { TransparentStreamFlushRequestMessage request = new TransparentStreamFlushRequestMessage (Guid.NewGuid (), streamID); TransparentStreamAsyncResult result = new TransparentStreamAsyncResult (null); if (!pendingFlushRequests.TryAdd (request.ID, result)) { throw new Exception ("request failed before sending."); } objectBusSession.SendMessage (request); return result; } public void EndFlush (IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); if (!(asyncResult is TransparentStreamAsyncResult)) { throw new ArgumentException ("asyncResult must be of type TransparentStreamAsyncResult."); } TransparentStreamAsyncResult result = (TransparentStreamAsyncResult)asyncResult; TransparentStreamFlushResponseMessage response = (TransparentStreamFlushResponseMessage)result.Response; if (response.Exception != null) throw response.Exception; } public override int Read (byte[] buffer, int offset, int count) { return EndRead (BeginRead (buffer, offset, count, null, null)); } public override long Seek (long offset, System.IO.SeekOrigin origin) { return EndSeek (BeginSeek (offset, origin)); } public IAsyncResult BeginSeek (long offset, System.IO.SeekOrigin origin) { TransparentStreamSeekRequestMessage request = new TransparentStreamSeekRequestMessage (Guid.NewGuid (), streamID, offset, origin); TransparentStreamAsyncResult result = new TransparentStreamAsyncResult (null); if (!pendingSeekRequests.TryAdd (request.ID, result)) { throw new Exception ("request failed before sending."); } objectBusSession.SendMessage (request); return result; } public long EndSeek (IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); if (!(asyncResult is TransparentStreamAsyncResult)) { throw new ArgumentException ("asyncResult must be of type TransparentStreamAsyncResult."); } TransparentStreamAsyncResult result = (TransparentStreamAsyncResult)asyncResult; TransparentStreamSeekResponseMessage response = (TransparentStreamSeekResponseMessage)result.Response; if (response.Exception != null) throw response.Exception; return response.Seek; } public override void SetLength (long value) { EndSetLength (BeginSetLength (value)); } public IAsyncResult BeginSetLength (long value) { TransparentStreamSetLengthRequestMessage request = new TransparentStreamSetLengthRequestMessage (Guid.NewGuid (), streamID, value); TransparentStreamAsyncResult result = new TransparentStreamAsyncResult (null); if (!pendingSetLengthRequests.TryAdd (request.ID, result)) { throw new Exception ("request failed before sending."); } objectBusSession.SendMessage (request); return result; } public void EndSetLength (IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); if (!(asyncResult is TransparentStreamAsyncResult)) { throw new ArgumentException ("asyncResult must be of type TransparentStreamAsyncResult."); } TransparentStreamAsyncResult result = (TransparentStreamAsyncResult)asyncResult; TransparentStreamSetLengthResponseMessage response = (TransparentStreamSetLengthResponseMessage)result.Response; if (response.Exception != null) throw response.Exception; } public override void Write (byte[] buffer, int offset, int count) { EndWrite (BeginWrite (buffer, offset, count, null, null)); } public override bool CanRead { get { return EndCanRead (BeginCanRead ()); } } public IAsyncResult BeginCanRead () { TransparentStreamCanReadRequestMessage request = new TransparentStreamCanReadRequestMessage (Guid.NewGuid (), streamID); TransparentStreamAsyncResult result = new TransparentStreamAsyncResult (null); if (!pendingCanReadRequests.TryAdd (request.ID, result)) { throw new Exception ("request failed before sending."); } objectBusSession.SendMessage (request); return result; } public bool EndCanRead (IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); if (!(asyncResult is TransparentStreamAsyncResult)) { throw new ArgumentException ("asyncResult must be of type TransparentStreamAsyncResult."); } TransparentStreamAsyncResult result = (TransparentStreamAsyncResult)asyncResult; TransparentStreamCanReadResponseMessage response = (TransparentStreamCanReadResponseMessage)result.Response; if (response.Exception != null) throw response.Exception; return response.CanRead; } public override bool CanSeek { get { return EndCanSeek (BeginCanSeek ()); } } public IAsyncResult BeginCanSeek () { TransparentStreamCanSeekRequestMessage request = new TransparentStreamCanSeekRequestMessage (Guid.NewGuid (), streamID); TransparentStreamAsyncResult result = new TransparentStreamAsyncResult (null); if (!pendingCanSeekRequests.TryAdd (request.ID, result)) { throw new Exception ("request failed before sending."); } objectBusSession.SendMessage (request); return result; } public bool EndCanSeek (IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); if (!(asyncResult is TransparentStreamAsyncResult)) { throw new ArgumentException ("asyncResult must be of type TransparentStreamAsyncResult."); } TransparentStreamAsyncResult result = (TransparentStreamAsyncResult)asyncResult; TransparentStreamCanSeekResponseMessage response = (TransparentStreamCanSeekResponseMessage)result.Response; if (response.Exception != null) throw response.Exception; return response.CanSeek; } public override bool CanWrite { get { return EndCanWrite (BeginCanWrite ()); } } public IAsyncResult BeginCanWrite () { TransparentStreamCanWriteRequestMessage request = new TransparentStreamCanWriteRequestMessage (Guid.NewGuid (), streamID); TransparentStreamAsyncResult result = new TransparentStreamAsyncResult (null); if (!pendingCanWriteRequests.TryAdd (request.ID, result)) { throw new Exception ("request failed before sending."); } objectBusSession.SendMessage (request); return result; } public bool EndCanWrite (IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); if (!(asyncResult is TransparentStreamAsyncResult)) { throw new ArgumentException ("asyncResult must be of type TransparentStreamAsyncResult."); } TransparentStreamAsyncResult result = (TransparentStreamAsyncResult)asyncResult; TransparentStreamCanWriteResponseMessage response = (TransparentStreamCanWriteResponseMessage)result.Response; if (response.Exception != null) throw response.Exception; return response.CanWrite; } public override long Length { get { return EndGetLength (BeginGetLength ()); } } public IAsyncResult BeginGetLength () { TransparentStreamGetLengthRequestMessage request = new TransparentStreamGetLengthRequestMessage (Guid.NewGuid (), streamID); TransparentStreamAsyncResult result = new TransparentStreamAsyncResult (null); if (!pendingGetLengthRequests.TryAdd (request.ID, result)) { throw new Exception ("request failed before sending."); } objectBusSession.SendMessage (request); return result; } public long EndGetLength (IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); if (!(asyncResult is TransparentStreamAsyncResult)) { throw new ArgumentException ("asyncResult must be of type TransparentStreamAsyncResult."); } TransparentStreamAsyncResult result = (TransparentStreamAsyncResult)asyncResult; TransparentStreamGetLengthResponseMessage response = (TransparentStreamGetLengthResponseMessage)result.Response; if (response.Exception != null) throw response.Exception; return response.Length; } public override long Position { get { return EndGetPosition (BeginGetPosition ()); } set { EndSetPosition (BeginSetPosition (value)); } } public IAsyncResult BeginGetPosition () { TransparentStreamGetPositionRequestMessage request = new TransparentStreamGetPositionRequestMessage (Guid.NewGuid (), streamID); TransparentStreamAsyncResult result = new TransparentStreamAsyncResult (null); if (!pendingGetPositionRequests.TryAdd (request.ID, result)) { throw new Exception ("request failed before sending."); } objectBusSession.SendMessage (request); return result; } public long EndGetPosition (IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); if (!(asyncResult is TransparentStreamAsyncResult)) { throw new ArgumentException ("asyncResult must be of type TransparentStreamAsyncResult."); } TransparentStreamAsyncResult result = (TransparentStreamAsyncResult)asyncResult; TransparentStreamGetPositionResponseMessage response = (TransparentStreamGetPositionResponseMessage)result.Response; if (response.Exception != null) throw response.Exception; return response.Position; } public IAsyncResult BeginSetPosition (long value) { TransparentStreamSetPositionRequestMessage request = new TransparentStreamSetPositionRequestMessage (Guid.NewGuid (), streamID, value); TransparentStreamAsyncResult result = new TransparentStreamAsyncResult (null); if (!pendingSetPositionRequests.TryAdd (request.ID, result)) { throw new Exception ("request failed before sending."); } objectBusSession.SendMessage (request); return result; } public void EndSetPosition (IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); if (!(asyncResult is TransparentStreamAsyncResult)) { throw new ArgumentException ("asyncResult must be of type TransparentStreamAsyncResult."); } TransparentStreamAsyncResult result = (TransparentStreamAsyncResult)asyncResult; TransparentStreamSetPositionResponseMessage response = (TransparentStreamSetPositionResponseMessage)result.Response; if (response.Exception != null) throw response.Exception; } #endregion public override IAsyncResult BeginRead (byte[] buffer, int offset, int count, AsyncCallback callback, object state) { TransparentStreamReadRequestMessage request = new TransparentStreamReadRequestMessage (Guid.NewGuid (), streamID, count); TransparentStreamAsyncResult result = new TransparentStreamAsyncResult (callback, state); if (!pendingReadRequests.TryAdd (request.ID, new Tuple <TransparentStreamAsyncResult, byte[], int, int> (result, buffer, offset, count))) { throw new Exception ("request failed before sending."); } objectBusSession.SendMessage (request); return result; } public override IAsyncResult BeginWrite (byte[] buffer, int offset, int count, AsyncCallback callback, object state) { byte[] nbuf = new byte[count]; System.Buffer.BlockCopy (buffer, offset, nbuf, 0, count); TransparentStreamWriteRequestMessage request = new TransparentStreamWriteRequestMessage (Guid.NewGuid (), streamID, nbuf); TransparentStreamAsyncResult result = new TransparentStreamAsyncResult (null); if (!pendingWriteRequests.TryAdd (request.ID, result)) { throw new Exception ("request failed before sending."); } objectBusSession.SendMessage (request); return result; } public override int EndRead (IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); if (!(asyncResult is TransparentStreamAsyncResult)) { throw new ArgumentException ("asyncResult must be of type TransparentStreamAsyncResult."); } TransparentStreamAsyncResult result = (TransparentStreamAsyncResult)asyncResult; TransparentStreamReadResponseMessage response = (TransparentStreamReadResponseMessage)result.Response; Tuple <TransparentStreamAsyncResult, byte[], int, int> rtuple; pendingReadRequests.TryRemove (response.RequestID, out rtuple); if (response.Exception != null) throw response.Exception; if (rtuple.Item4 < response.Data.Length) throw new Exception ("Something is inherently wrong with remote stream."); Buffer.BlockCopy (response.Data, 0, rtuple.Item2, rtuple.Item3, Math.Min (rtuple.Item4, response.Data.Length)); return response.Data.Length; } public override void EndWrite (IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); if (!(asyncResult is TransparentStreamAsyncResult)) { throw new ArgumentException ("asyncResult must be of type TransparentStreamAsyncResult."); } TransparentStreamAsyncResult result = (TransparentStreamAsyncResult)asyncResult; TransparentStreamWriteResponseMessage response = (TransparentStreamWriteResponseMessage)result.Response; if (response.Exception != null) throw response.Exception; } protected override void Dispose (bool disposing) { base.Dispose (disposing); } public override int ReadTimeout { get { return EndGetReadTimeout (BeginGetReadTimeout ()); } set { EndSetReadTimeout (BeginSetReadTimeout (value)); } } public override int WriteTimeout { get { return EndGetWriteTimeout (BeginGetWriteTimeout ()); } set { EndSetWriteTimeout (BeginSetWriteTimeout (value)); } } public IAsyncResult BeginGetWriteTimeout () { TransparentStreamGetWriteTimeoutRequestMessage request = new TransparentStreamGetWriteTimeoutRequestMessage (Guid.NewGuid (), streamID); TransparentStreamAsyncResult result = new TransparentStreamAsyncResult (null); if (!pendingGetWriteTimeoutRequests.TryAdd (request.ID, result)) { throw new Exception ("request failed before sending."); } objectBusSession.SendMessage (request); return result; } public int EndGetWriteTimeout (IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); if (!(asyncResult is TransparentStreamAsyncResult)) { throw new ArgumentException ("asyncResult must be of type TransparentStreamAsyncResult."); } TransparentStreamAsyncResult result = (TransparentStreamAsyncResult)asyncResult; TransparentStreamGetWriteTimeoutResponseMessage response = (TransparentStreamGetWriteTimeoutResponseMessage)result.Response; if (response.Exception != null) throw response.Exception; return response.WriteTimeout; } public IAsyncResult BeginSetWriteTimeout (int value) { TransparentStreamSetWriteTimeoutRequestMessage request = new TransparentStreamSetWriteTimeoutRequestMessage (Guid.NewGuid (), streamID, value); TransparentStreamAsyncResult result = new TransparentStreamAsyncResult (null); if (!pendingSetWriteTimeoutRequests.TryAdd (request.ID, result)) { throw new Exception ("request failed before sending."); } objectBusSession.SendMessage (request); return result; } public void EndSetWriteTimeout (IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); if (!(asyncResult is TransparentStreamAsyncResult)) { throw new ArgumentException ("asyncResult must be of type TransparentStreamAsyncResult."); } TransparentStreamAsyncResult result = (TransparentStreamAsyncResult)asyncResult; TransparentStreamSetWriteTimeoutResponseMessage response = (TransparentStreamSetWriteTimeoutResponseMessage)result.Response; if (response.Exception != null) throw response.Exception; } public IAsyncResult BeginGetReadTimeout () { TransparentStreamGetReadTimeoutRequestMessage request = new TransparentStreamGetReadTimeoutRequestMessage (Guid.NewGuid (), streamID); TransparentStreamAsyncResult result = new TransparentStreamAsyncResult (null); if (!pendingGetReadTimeoutRequests.TryAdd (request.ID, result)) { throw new Exception ("request failed before sending."); } objectBusSession.SendMessage (request); return result; } public int EndGetReadTimeout (IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); if (!(asyncResult is TransparentStreamAsyncResult)) { throw new ArgumentException ("asyncResult must be of type TransparentStreamAsyncResult."); } TransparentStreamAsyncResult result = (TransparentStreamAsyncResult)asyncResult; TransparentStreamGetReadTimeoutResponseMessage response = (TransparentStreamGetReadTimeoutResponseMessage)result.Response; if (response.Exception != null) throw response.Exception; return response.ReadTimeout; } public IAsyncResult BeginSetReadTimeout (int value) { TransparentStreamSetReadTimeoutRequestMessage request = new TransparentStreamSetReadTimeoutRequestMessage (Guid.NewGuid (), streamID, value); TransparentStreamAsyncResult result = new TransparentStreamAsyncResult (null); if (!pendingSetReadTimeoutRequests.TryAdd (request.ID, result)) { throw new Exception ("request failed before sending."); } objectBusSession.SendMessage (request); return result; } public void EndSetReadTimeout (IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); if (!(asyncResult is TransparentStreamAsyncResult)) { throw new ArgumentException ("asyncResult must be of type TransparentStreamAsyncResult."); } TransparentStreamAsyncResult result = (TransparentStreamAsyncResult)asyncResult; TransparentStreamSetReadTimeoutResponseMessage response = (TransparentStreamSetReadTimeoutResponseMessage)result.Response; if (response.Exception != null) throw response.Exception; } public override bool CanTimeout { get { return EndCanTimeout (BeginCanTimeout ()); } } public IAsyncResult BeginCanTimeout () { TransparentStreamCanTimeoutRequestMessage request = new TransparentStreamCanTimeoutRequestMessage (Guid.NewGuid (), streamID); TransparentStreamAsyncResult result = new TransparentStreamAsyncResult (null); if (!pendingCanTimeoutRequests.TryAdd (request.ID, result)) { throw new Exception ("request failed before sending."); } objectBusSession.SendMessage (request); return result; } public bool EndCanTimeout (IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); if (!(asyncResult is TransparentStreamAsyncResult)) { throw new ArgumentException ("asyncResult must be of type TransparentStreamAsyncResult."); } TransparentStreamAsyncResult result = (TransparentStreamAsyncResult)asyncResult; TransparentStreamCanTimeoutResponseMessage response = (TransparentStreamCanTimeoutResponseMessage)result.Response; if (response.Exception != null) throw response.Exception; return response.CanTimeout; } public override void Close () { EndClose (BeginClose ()); } public IAsyncResult BeginClose () { TransparentStreamCloseRequestMessage request = new TransparentStreamCloseRequestMessage (Guid.NewGuid (), streamID); TransparentStreamAsyncResult result = new TransparentStreamAsyncResult (null); if (!pendingCloseRequests.TryAdd (request.ID, result)) { throw new Exception ("request failed before sending."); } objectBusSession.SendMessage (request); return result; } public void EndClose (IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); if (!(asyncResult is TransparentStreamAsyncResult)) { throw new ArgumentException ("asyncResult must be of type TransparentStreamAsyncResult."); } TransparentStreamAsyncResult result = (TransparentStreamAsyncResult)asyncResult; TransparentStreamCloseResponseMessage response = (TransparentStreamCloseResponseMessage)result.Response; if (response.Exception != null) throw response.Exception; } internal void ResponseReceived (TransparentStreamMessageBase transparentStreamMessageBase) { if (transparentStreamMessageBase is TransparentStreamCanReadResponseMessage) { TransparentStreamCanReadResponseMessageReceived (transparentStreamMessageBase); } else if (transparentStreamMessageBase is TransparentStreamCanSeekResponseMessage) { TransparentStreamCanSeekResponseMessageReceived (transparentStreamMessageBase); } else if (transparentStreamMessageBase is TransparentStreamCanTimeoutResponseMessage) { TransparentStreamCanTimeoutResponseMessageReceived (transparentStreamMessageBase); } else if (transparentStreamMessageBase is TransparentStreamCanWriteResponseMessage) { TransparentStreamCanWriteResponseMessageReceived (transparentStreamMessageBase); } else if (transparentStreamMessageBase is TransparentStreamCloseResponseMessage) { TransparentStreamCloseResponseMessageReceived (transparentStreamMessageBase); } else if (transparentStreamMessageBase is TransparentStreamFlushResponseMessage) { TransparentStreamFlushResponseMessageReceived (transparentStreamMessageBase); } else if (transparentStreamMessageBase is TransparentStreamGetLengthResponseMessage) { TransparentStreamGetLengthResponseMessageReceived (transparentStreamMessageBase); } else if (transparentStreamMessageBase is TransparentStreamGetPositionResponseMessage) { TransparentStreamGetPositionResponseMessageReceived (transparentStreamMessageBase); } else if (transparentStreamMessageBase is TransparentStreamGetReadTimeoutResponseMessage) { TransparentStreamGetReadTimeoutResponseMessageReceived (transparentStreamMessageBase); } else if (transparentStreamMessageBase is TransparentStreamGetWriteTimeoutResponseMessage) { TransparentStreamGetWriteTimeoutResponseMessageReceived (transparentStreamMessageBase); } else if (transparentStreamMessageBase is TransparentStreamReadResponseMessage) { TransparentStreamReadResponseMessageReceived (transparentStreamMessageBase); } else if (transparentStreamMessageBase is TransparentStreamSeekResponseMessage) { TransparentStreamSeekResponseMessageReceived (transparentStreamMessageBase); } else if (transparentStreamMessageBase is TransparentStreamSetLengthResponseMessage) { TransparentStreamSetLengthResponseMessageReceived (transparentStreamMessageBase); } else if (transparentStreamMessageBase is TransparentStreamSetPositionResponseMessage) { TransparentStreamSetPositionResponseMessageReceived (transparentStreamMessageBase); } else if (transparentStreamMessageBase is TransparentStreamSetReadTimeoutResponseMessage) { TransparentStreamSetReadTimeoutResponseMessageReceived (transparentStreamMessageBase); } else if (transparentStreamMessageBase is TransparentStreamSetWriteTimeoutResponseMessage) { TransparentStreamSetWriteTimeoutResponseMessageReceived (transparentStreamMessageBase); } else if (transparentStreamMessageBase is TransparentStreamWriteResponseMessage) { TransparentStreamWriteResponseMessageReceived (transparentStreamMessageBase); } } #region "Callbacks" void TransparentStreamCanReadResponseMessageReceived (TransparentStreamMessageBase transparentStreamMessageBase) { if (transparentStreamMessageBase == null) throw new ArgumentNullException ("transparentStreamMessageBase"); if (transparentStreamMessageBase.StreamID != streamID) throw new Exception ("TransparentStreamMessageBase instance does not belong to this stream"); if (!(transparentStreamMessageBase is TransparentStreamCanReadResponseMessage)) { throw new ArgumentException ("transparentStreamMessageBase must be of type TransparentStreamCanReadResponseMessage."); } TransparentStreamCanReadResponseMessage response = (TransparentStreamCanReadResponseMessage)transparentStreamMessageBase; TransparentStreamAsyncResult ar; pendingCanReadRequests.TryRemove (response.RequestID, out ar); ar.Set (response); } void TransparentStreamCanSeekResponseMessageReceived (TransparentStreamMessageBase transparentStreamMessageBase) { if (transparentStreamMessageBase == null) throw new ArgumentNullException ("transparentStreamMessageBase"); if (transparentStreamMessageBase.StreamID != streamID) throw new Exception ("TransparentStreamMessageBase instance does not belong to this stream"); if (!(transparentStreamMessageBase is TransparentStreamCanSeekResponseMessage)) { throw new ArgumentException ("transparentStreamMessageBase must be of type TransparentStreamCanSeekResponseMessage."); } TransparentStreamCanSeekResponseMessage response = (TransparentStreamCanSeekResponseMessage)transparentStreamMessageBase; TransparentStreamAsyncResult ar; pendingCanSeekRequests.TryRemove (response.RequestID, out ar); ar.Set (response); } void TransparentStreamCanTimeoutResponseMessageReceived (TransparentStreamMessageBase transparentStreamMessageBase) { if (transparentStreamMessageBase == null) throw new ArgumentNullException ("transparentStreamMessageBase"); if (transparentStreamMessageBase.StreamID != streamID) throw new Exception ("TransparentStreamMessageBase instance does not belong to this stream"); if (!(transparentStreamMessageBase is TransparentStreamCanTimeoutResponseMessage)) { throw new ArgumentException ("transparentStreamMessageBase must be of type TransparentStreamCanTimeoutResponseMessage."); } TransparentStreamCanTimeoutResponseMessage response = (TransparentStreamCanTimeoutResponseMessage)transparentStreamMessageBase; TransparentStreamAsyncResult ar; pendingCanTimeoutRequests.TryRemove (response.RequestID, out ar); ar.Set (response); } void TransparentStreamCanWriteResponseMessageReceived (TransparentStreamMessageBase transparentStreamMessageBase) { if (transparentStreamMessageBase == null) throw new ArgumentNullException ("transparentStreamMessageBase"); if (transparentStreamMessageBase.StreamID != streamID) throw new Exception ("TransparentStreamMessageBase instance does not belong to this stream"); if (!(transparentStreamMessageBase is TransparentStreamCanWriteResponseMessage)) { throw new ArgumentException ("transparentStreamMessageBase must be of type TransparentStreamCanWriteResponseMessage."); } TransparentStreamCanWriteResponseMessage response = (TransparentStreamCanWriteResponseMessage)transparentStreamMessageBase; TransparentStreamAsyncResult ar; pendingCanWriteRequests.TryRemove (response.RequestID, out ar); ar.Set (response); } void TransparentStreamCloseResponseMessageReceived (TransparentStreamMessageBase transparentStreamMessageBase) { if (transparentStreamMessageBase == null) throw new ArgumentNullException ("transparentStreamMessageBase"); if (transparentStreamMessageBase.StreamID != streamID) throw new Exception ("TransparentStreamMessageBase instance does not belong to this stream"); if (!(transparentStreamMessageBase is TransparentStreamCloseResponseMessage)) { throw new ArgumentException ("transparentStreamMessageBase must be of type TransparentStreamCloseResponseMessage."); } TransparentStreamCloseResponseMessage response = (TransparentStreamCloseResponseMessage)transparentStreamMessageBase; if (response.Exception != null) { agent.RemoveStream (this); } TransparentStreamAsyncResult ar; pendingCloseRequests.TryRemove (response.RequestID, out ar); ar.Set (response); } void TransparentStreamFlushResponseMessageReceived (TransparentStreamMessageBase transparentStreamMessageBase) { if (transparentStreamMessageBase == null) throw new ArgumentNullException ("transparentStreamMessageBase"); if (transparentStreamMessageBase.StreamID != streamID) throw new Exception ("TransparentStreamMessageBase instance does not belong to this stream"); if (!(transparentStreamMessageBase is TransparentStreamFlushResponseMessage)) { throw new ArgumentException ("transparentStreamMessageBase must be of type TransparentStreamFlushResponseMessage."); } TransparentStreamFlushResponseMessage response = (TransparentStreamFlushResponseMessage)transparentStreamMessageBase; TransparentStreamAsyncResult ar; pendingFlushRequests.TryRemove (response.RequestID, out ar); ar.Set (response); } void TransparentStreamGetLengthResponseMessageReceived (TransparentStreamMessageBase transparentStreamMessageBase) { if (transparentStreamMessageBase == null) throw new ArgumentNullException ("transparentStreamMessageBase"); if (transparentStreamMessageBase.StreamID != streamID) throw new Exception ("TransparentStreamMessageBase instance does not belong to this stream"); if (!(transparentStreamMessageBase is TransparentStreamGetLengthResponseMessage)) { throw new ArgumentException ("transparentStreamMessageBase must be of type TransparentStreamGetLengthResponseMessage."); } TransparentStreamGetLengthResponseMessage response = (TransparentStreamGetLengthResponseMessage)transparentStreamMessageBase; TransparentStreamAsyncResult ar; pendingGetLengthRequests.TryRemove (response.RequestID, out ar); ar.Set (response); } void TransparentStreamGetPositionResponseMessageReceived (TransparentStreamMessageBase transparentStreamMessageBase) { if (transparentStreamMessageBase == null) throw new ArgumentNullException ("transparentStreamMessageBase"); if (transparentStreamMessageBase.StreamID != streamID) throw new Exception ("TransparentStreamMessageBase instance does not belong to this stream"); if (!(transparentStreamMessageBase is TransparentStreamGetPositionResponseMessage)) { throw new ArgumentException ("transparentStreamMessageBase must be of type TransparentStreamGetPositionResponseMessage."); } TransparentStreamGetPositionResponseMessage response = (TransparentStreamGetPositionResponseMessage)transparentStreamMessageBase; TransparentStreamAsyncResult ar; pendingGetPositionRequests.TryRemove (response.RequestID, out ar); ar.Set (response); } void TransparentStreamGetReadTimeoutResponseMessageReceived (TransparentStreamMessageBase transparentStreamMessageBase) { if (transparentStreamMessageBase == null) throw new ArgumentNullException ("transparentStreamMessageBase"); if (transparentStreamMessageBase.StreamID != streamID) throw new Exception ("TransparentStreamMessageBase instance does not belong to this stream"); if (!(transparentStreamMessageBase is TransparentStreamGetReadTimeoutResponseMessage)) { throw new ArgumentException ("transparentStreamMessageBase must be of type TransparentStreamGetReadTimeoutResponseMessage."); } TransparentStreamGetReadTimeoutResponseMessage response = (TransparentStreamGetReadTimeoutResponseMessage)transparentStreamMessageBase; TransparentStreamAsyncResult ar; pendingGetReadTimeoutRequests.TryRemove (response.RequestID, out ar); ar.Set (response); } void TransparentStreamGetWriteTimeoutResponseMessageReceived (TransparentStreamMessageBase transparentStreamMessageBase) { if (transparentStreamMessageBase == null) throw new ArgumentNullException ("transparentStreamMessageBase"); if (transparentStreamMessageBase.StreamID != streamID) throw new Exception ("TransparentStreamMessageBase instance does not belong to this stream"); if (!(transparentStreamMessageBase is TransparentStreamGetWriteTimeoutResponseMessage)) { throw new ArgumentException ("transparentStreamMessageBase must be of type TransparentStreamGetWriteTimeoutResponseMessage."); } TransparentStreamGetWriteTimeoutResponseMessage response = (TransparentStreamGetWriteTimeoutResponseMessage)transparentStreamMessageBase; TransparentStreamAsyncResult ar; pendingGetWriteTimeoutRequests.TryRemove (response.RequestID, out ar); ar.Set (response); } void TransparentStreamReadResponseMessageReceived (TransparentStreamMessageBase transparentStreamMessageBase) { if (transparentStreamMessageBase == null) throw new ArgumentNullException ("transparentStreamMessageBase"); if (transparentStreamMessageBase.StreamID != streamID) throw new Exception ("TransparentStreamMessageBase instance does not belong to this stream"); if (!(transparentStreamMessageBase is TransparentStreamReadResponseMessage)) { throw new ArgumentException ("transparentStreamMessageBase must be of type TransparentStreamReadResponseMessage."); } TransparentStreamReadResponseMessage response = (TransparentStreamReadResponseMessage)transparentStreamMessageBase; Tuple <TransparentStreamAsyncResult, byte[], int, int> tuple; pendingReadRequests.TryGetValue (response.RequestID, out tuple); tuple.Item1.Set (response); } void TransparentStreamSeekResponseMessageReceived (TransparentStreamMessageBase transparentStreamMessageBase) { if (transparentStreamMessageBase == null) throw new ArgumentNullException ("transparentStreamMessageBase"); if (transparentStreamMessageBase.StreamID != streamID) throw new Exception ("TransparentStreamMessageBase instance does not belong to this stream"); if (!(transparentStreamMessageBase is TransparentStreamSeekResponseMessage)) { throw new ArgumentException ("transparentStreamMessageBase must be of type TransparentStreamSeekResponseMessage."); } TransparentStreamSeekResponseMessage response = (TransparentStreamSeekResponseMessage)transparentStreamMessageBase; TransparentStreamAsyncResult ar; pendingSeekRequests.TryRemove (response.RequestID, out ar); ar.Set (response); } void TransparentStreamSetLengthResponseMessageReceived (TransparentStreamMessageBase transparentStreamMessageBase) { if (transparentStreamMessageBase == null) throw new ArgumentNullException ("transparentStreamMessageBase"); if (transparentStreamMessageBase.StreamID != streamID) throw new Exception ("TransparentStreamMessageBase instance does not belong to this stream"); if (!(transparentStreamMessageBase is TransparentStreamSetLengthResponseMessage)) { throw new ArgumentException ("transparentStreamMessageBase must be of type TransparentStreamSetLengthResponseMessage."); } TransparentStreamSetLengthResponseMessage response = (TransparentStreamSetLengthResponseMessage)transparentStreamMessageBase; TransparentStreamAsyncResult ar; pendingSetLengthRequests.TryRemove (response.RequestID, out ar); ar.Set (response); } void TransparentStreamSetPositionResponseMessageReceived (TransparentStreamMessageBase transparentStreamMessageBase) { if (transparentStreamMessageBase == null) throw new ArgumentNullException ("transparentStreamMessageBase"); if (transparentStreamMessageBase.StreamID != streamID) throw new Exception ("TransparentStreamMessageBase instance does not belong to this stream"); if (!(transparentStreamMessageBase is TransparentStreamSetPositionResponseMessage)) { throw new ArgumentException ("transparentStreamMessageBase must be of type TransparentStreamSetPositionResponseMessage."); } TransparentStreamSetPositionResponseMessage response = (TransparentStreamSetPositionResponseMessage)transparentStreamMessageBase; TransparentStreamAsyncResult ar; pendingSetPositionRequests.TryRemove (response.RequestID, out ar); ar.Set (response); } void TransparentStreamSetReadTimeoutResponseMessageReceived (TransparentStreamMessageBase transparentStreamMessageBase) { if (transparentStreamMessageBase == null) throw new ArgumentNullException ("transparentStreamMessageBase"); if (transparentStreamMessageBase.StreamID != streamID) throw new Exception ("TransparentStreamMessageBase instance does not belong to this stream"); if (!(transparentStreamMessageBase is TransparentStreamSetReadTimeoutResponseMessage)) { throw new ArgumentException ("transparentStreamMessageBase must be of type TransparentStreamSetReadTimeoutResponseMessage."); } TransparentStreamSetReadTimeoutResponseMessage response = (TransparentStreamSetReadTimeoutResponseMessage)transparentStreamMessageBase; TransparentStreamAsyncResult ar; pendingSetReadTimeoutRequests.TryRemove (response.RequestID, out ar); ar.Set (response); } void TransparentStreamSetWriteTimeoutResponseMessageReceived (TransparentStreamMessageBase transparentStreamMessageBase) { if (transparentStreamMessageBase == null) throw new ArgumentNullException ("transparentStreamMessageBase"); if (transparentStreamMessageBase.StreamID != streamID) throw new Exception ("TransparentStreamMessageBase instance does not belong to this stream"); if (!(transparentStreamMessageBase is TransparentStreamSetWriteTimeoutResponseMessage)) { throw new ArgumentException ("transparentStreamMessageBase must be of type TransparentStreamSetWriteTimeoutResponseMessage."); } TransparentStreamSetWriteTimeoutResponseMessage response = (TransparentStreamSetWriteTimeoutResponseMessage)transparentStreamMessageBase; TransparentStreamAsyncResult ar; pendingSetWriteTimeoutRequests.TryRemove (response.RequestID, out ar); ar.Set (response); } void TransparentStreamWriteResponseMessageReceived (TransparentStreamMessageBase transparentStreamMessageBase) { if (transparentStreamMessageBase == null) throw new ArgumentNullException ("transparentStreamMessageBase"); if (transparentStreamMessageBase.StreamID != streamID) throw new Exception ("TransparentStreamMessageBase instance does not belong to this stream"); if (!(transparentStreamMessageBase is TransparentStreamWriteResponseMessage)) { throw new ArgumentException ("transparentStreamMessageBase must be of type TransparentStreamWriteResponseMessage."); } TransparentStreamWriteResponseMessage response = (TransparentStreamWriteResponseMessage)transparentStreamMessageBase; TransparentStreamAsyncResult ar; pendingWriteRequests.TryRemove (response.RequestID, out ar); ar.Set (response); } #endregion public void CopyTo (System.IO.Stream destination, int minAwaits, int maxAwaits) { System.Collections.Generic.Queue<IAsyncResult> ars = new System.Collections.Generic.Queue<IAsyncResult> (); //todo: add automatic unit size tuning support int unit = 16384; long l; try { l = Length; } catch { l = long.MaxValue; } try { while (l != 0) { int lt = (int)Math.Min (unit, l); if (l != long.MaxValue) l -= lt; byte[] bytes = new byte[lt]; ars.Enqueue (BeginRead (bytes, 0, lt, (ar) => { int readbytes = EndRead (ar); byte[] buf = (byte[])ar.AsyncState; destination.BeginWrite (buf, 0, readbytes, (dar) => { destination.EndWrite (dar); }, null); }, bytes)); if (ars.Count > maxAwaits) { while (ars.Count > minAwaits) ars.Dequeue ().AsyncWaitHandle.WaitOne (); } } } catch { //unknown length if (l != long.MaxValue) throw; } while (ars.Count != 0) ars.Dequeue ().AsyncWaitHandle.WaitOne (); destination.Flush (); } } }
using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using Kemel.Orm.Schema; using Kemel.Orm.Entity; using Kemel.Orm.NQuery.Storage.Table; using Kemel.Orm.NQuery.Storage.Column; using Kemel.Orm.NQuery.Storage.Value; using Kemel.Orm.NQuery.Storage.Join; using Kemel.Orm.NQuery.Storage.Function; using Kemel.Orm.NQuery.Storage.Constraint; using Kemel.Orm.NQuery.Storage.StoredSelect; using Kemel.Orm.Base; using Kemel.Orm.Providers; using Kemel.Orm.NQuery.Storage.Function.Aggregated; using Kemel.Orm.NQuery.Storage.Function.Scalar; using Kemel.Orm.NQuery.Storage.StoredSelect.Case; namespace Kemel.Orm.NQuery.Storage { public class StorageFactory { public class Column { public static StoredColumn Create(Schema.ColumnSchema columnSchema, Query query) { return Create(columnSchema, Table.Create(columnSchema.Parent, query), query); } public static StoredColumn Create(Schema.ColumnSchema columnSchema, StoredTable table, Query query) { return new StoredColumn(columnSchema, StoredColumn.StoredTypes.Schema, table, query); } public static StoredColumn Create(string name, StoredTable table, Query query) { if ((table.Type == StoredTable.StoredTypes.Schema)) { IColumnDefinition colDef = table.TableDefinition.GetColumn(name); return new StoredColumn(colDef, StoredColumn.StoredTypes.Schema, table, query); } else { return new StoredColumn(new ColumnNameDefinition(name, table.TableDefinition), StoredColumn.StoredTypes.Name, table, query); } } static internal StoredColumn Create(StoredTable table, string nickName, Query query) { return new StoredColumn(new ColumnAliasDefinition(nickName, table.TableDefinition), StoredColumn.StoredTypes.OnlyAlias, table, query); } public static StoredColumn Create(string name, Query query) { return new StoredColumn(new ColumnUnknowTableDefinition(name), StoredColumn.StoredTypes.UnknowTable, query); } public static StoredColumn Create(Schema.ColumnSchema columnSchema, string tableName, Query query) { StoredTable storedTable = query.GetTableByAlias(tableName); if(storedTable == null) storedTable = Table.Create(tableName, query); return Create(columnSchema, storedTable, query); } public static StoredColumn Create(string name, string tableName, Query query) { StoredTable storedTable = Table.Create(tableName, query); return Create(name, storedTable, query); } public static StoredColumn Create(string name, TableSchema tableSchema, Query query) { StoredTable storedTable = Table.Create(tableSchema, query); return Create(name, storedTable, query); } public static StoredColumn Create(string name, EntityBase entity, Query query) { StoredTable storedTable = Table.Create(entity, query); return Create(name, storedTable, query); } public static StoredColumn Create<TEtt>(string name, Query query) where TEtt : EntityBase { StoredTable storedTable = Table.Create<TEtt>(query); return Create(name, storedTable, query); } public static StoredColumn Create(StringConstant constant, Query query) { return new StoredColumn(new ColumnConstantDefinition(constant), StoredColumn.StoredTypes.StringConstant, query); } static internal StoredColumn Create(StoredFunction stFunction, StoredTable table, Query query) { return new StoredColumn(new ColumnFunctionDefinition(stFunction, table.TableDefinition), StoredColumn.StoredTypes.StoredFunction, table, query); } public static StoredColumn Create(StoredFunction stFunction, Query query) { return new StoredColumn(new ColumnFunctionDefinition(stFunction), StoredColumn.StoredTypes.StoredFunction, query); } static internal StoredColumn CreateNick(string tableName, string nickName, Query query) { StoredTable storedTable = Table.Create(tableName, query); return Create(storedTable, nickName, query); } public static StoredColumn Create(StoredConcat concat, Query query) { return new StoredColumn(new ColumnConcatDefinition(concat), StoredColumn.StoredTypes.Concat, query); } } public class JoinColumn { public static StoredJoinColumn Create(Schema.ColumnSchema columnSchema, Query query) { return new StoredJoinColumn(columnSchema, StoredColumn.StoredTypes.Schema, query); } public static StoredJoinColumn Create(Schema.ColumnSchema columnSchema, StoredTable table, Query query) { return new StoredJoinColumn(columnSchema, StoredColumn.StoredTypes.Schema, table, query); } public static StoredJoinColumn Create(string name, StoredTable table, Query query) { if ((table.Type == StoredTable.StoredTypes.Schema)) { IColumnDefinition colDef = table.TableDefinition.GetColumn(name); return new StoredJoinColumn(colDef, StoredColumn.StoredTypes.Schema, table, query); } else { return new StoredJoinColumn(new ColumnNameDefinition(name, table.TableDefinition), StoredColumn.StoredTypes.Name, table, query); } } static internal StoredJoinColumn Create(StoredTable table, string nickName, Query query) { return new StoredJoinColumn(new ColumnAliasDefinition(nickName, table.TableDefinition), StoredColumn.StoredTypes.OnlyAlias, table, query); } public static StoredJoinColumn Create(string name, Query query) { return new StoredJoinColumn(new ColumnUnknowTableDefinition(name), StoredColumn.StoredTypes.UnknowTable, query); } static internal StoredJoinColumn Create(StoredFunction stFunction, StoredTable table, Query query) { return new StoredJoinColumn(new ColumnFunctionDefinition(stFunction, table.TableDefinition), StoredColumn.StoredTypes.StoredFunction, table, query); } public static StoredJoinColumn Create(StoredFunction stFunction, Query query) { return new StoredJoinColumn(new ColumnFunctionDefinition(stFunction), StoredColumn.StoredTypes.StoredFunction, query); } } public class Table { public static StoredTable Create(TableSchema table, Query parent) { return new StoredTable(table, StoredTable.StoredTypes.Schema, parent); } public static StoredTable Create<TEtt>(Query parent) where TEtt : EntityBase { TableSchema table = SchemaContainer.GetSchema<TEtt>(); return Create(table, parent); } public static StoredTable Create(EntityBase entity, Query parent) { TableSchema table = SchemaContainer.GetSchema(entity); return Create(table, parent); } public static StoredTable Create(string tableName, Query parent) { TableSchema table = SchemaContainer.GetSchema(tableName); if (table != null) { return Create(table, parent); } else { return new StoredTable(new TableNameDefinition(tableName), StoredTable.StoredTypes.Name, parent); } } public static StoredTable Create(Query subQuery, Query parent) { subQuery.Parent = parent; return new StoredTable(new TableSubQueryDefinition(subQuery), StoredTable.StoredTypes.SubQuery, parent); } public static StoredTable Create(StoredFunction stFunction, Query parent) { return new StoredTable(new TableFunctionDefinition(stFunction), StoredTable.StoredTypes.SubQuery, parent); } } public class Join { public static StoredJoin Create(TableSchema table, Query parent) { return new StoredJoin(table, StoredTable.StoredTypes.Schema, parent); } public static StoredJoin Create<TEtt>(Query parent) where TEtt : EntityBase { TableSchema table = SchemaContainer.GetSchema<TEtt>(); return Create(table, parent); } public static StoredJoin Create(EntityBase entity, Query parent) { TableSchema table = SchemaContainer.GetSchema(entity); return Create(table, parent); } public static StoredJoin Create(string tableName, Query parent) { TableSchema table = SchemaContainer.GetSchema(tableName); if (table != null) { return Create(table, parent); } else { return new StoredJoin(new TableNameDefinition(tableName), StoredTable.StoredTypes.Name, parent); } } public static StoredJoin Create(Query subQuery, Query parent) { subQuery.Parent = parent; return new StoredJoin(new TableSubQueryDefinition(subQuery), StoredTable.StoredTypes.SubQuery, parent); } public static StoredJoin Create(StoredFunction stFunction, Query parent) { return new StoredJoin(new TableFunctionDefinition(stFunction), StoredTable.StoredTypes.SubQuery, parent); } } public class Value { public static StoredValue Create(ColumnSchema column, Query query) { return new StoredValue(new ValueStoredColumnDefinition(StorageFactory.Column.Create(column, query)), StoredValue.StoredTypes.StoredColumn); } public static StoredValue Create(ColumnSchema column, StoredTable table, Query query) { return new StoredValue(new ValueStoredColumnDefinition(StorageFactory.Column.Create(column, table, query)), StoredValue.StoredTypes.StoredColumn); } public static StoredValue Create(string columnName, StoredTable table, Query query) { return new StoredValue(new ValueStoredColumnDefinition(StorageFactory.Column.Create(columnName, table, query)), StoredValue.StoredTypes.StoredColumn); } public static StoredValue Create(object value) { return new StoredValue(new ValueObjectDefinition(value), StoredValue.StoredTypes.ObjectValue); } public static StoredValue Create(object startValue, object endValue) { return new StoredValue(new ValueIntervalDefinition(startValue, endValue), StoredValue.StoredTypes.Interval); } public static StoredValue Create(Query subQuery) { return new StoredValue(new ValueSubQueryDefinition(subQuery), StoredValue.StoredTypes.SubQuery); } public static StoredValue Create(StoredFunction stFunction) { return new StoredValue(new ValueStoredFunctionDefinition(stFunction), StoredValue.StoredTypes.StoredFunction); } public static StoredValue Create(StoredFunction startFunction, StoredFunction endFunction) { return new StoredValue(new ValueStoredFunctionIntervalDefinition(startFunction, endFunction), StoredValue.StoredTypes.IntervalStoredFunction); } public static StoredValue Create(IEnumerable values) { return new StoredValue(new ValueArrayDefinition(values), StoredValue.StoredTypes.Array); } public static StoredValue Create(object[] values) { return new StoredValue(new ValueArrayDefinition(values), StoredValue.StoredTypes.Array); } public static StoredValue Create(List<object> values) { return new StoredValue(new ValueArrayDefinition(values), StoredValue.StoredTypes.Array); } public static StoredValue Create(ColumnSchema startColumn, ColumnSchema endColumn, StoredTable table, Query query) { return Create(StorageFactory.Column.Create(startColumn, table, query), StorageFactory.Column.Create(endColumn, table, query)); } public static StoredValue Create(string startColumnName, string endColumnName, StoredTable table, Query query) { return Create(StorageFactory.Column.Create(startColumnName, table, query), StorageFactory.Column.Create(endColumnName, table, query)); } public static StoredValue Create(ColumnSchema startColumn, StoredTable startTable, ColumnSchema endColumn, StoredTable endTable, Query query) { return Create(StorageFactory.Column.Create(startColumn, startTable, query), StorageFactory.Column.Create(endColumn, endTable, query)); } public static StoredValue Create(string startColumnName, StoredTable startTable, string endColumnName, StoredTable endTable, Query query) { return Create(StorageFactory.Column.Create(startColumnName, startTable, query), StorageFactory.Column.Create(endColumnName, endTable, query)); } public static StoredValue Create(ColumnSchema startColumn, string endColumnName, StoredTable table, Query query) { return Create(StorageFactory.Column.Create(startColumn, table, query), StorageFactory.Column.Create(endColumnName, table, query)); } public static StoredValue Create(string startColumnName, ColumnSchema endColumn, StoredTable table, Query query) { return Create(StorageFactory.Column.Create(startColumnName, table, query), StorageFactory.Column.Create(endColumn, table, query)); } public static StoredValue Create(ColumnSchema startColumn, StoredTable startTable, string endColumnName, StoredTable endTable, Query query) { return Create(StorageFactory.Column.Create(startColumn, startTable, query), StorageFactory.Column.Create(endColumnName, endTable, query)); } public static StoredValue Create(string startColumnName, StoredTable startTable, ColumnSchema endColumn, StoredTable endTable, Query query) { return Create(StorageFactory.Column.Create(startColumnName, startTable, query), StorageFactory.Column.Create(endColumn, endTable, query)); } private static StoredValue Create(StoredColumn startColumn, StoredColumn endColumn) { return new StoredValue(new ValueStoredColumnIntervalDefinition(startColumn, endColumn), StoredValue.StoredTypes.IntervalStoredColumns); } public static StoredValue Create(ColumnSchema startColumn, ColumnSchema endColumn, Query query) { return Create(StorageFactory.Column.Create(startColumn, query), StorageFactory.Column.Create(endColumn, query)); } public static StoredValue CreateValue(TableSchema table, string columnName, Query query) { ColumnSchema colSc = table.Columns[columnName]; StoredTable stTable = StorageFactory.Table.Create(table, query); return Create(colSc, stTable, query); } public static StoredValue CreateValue(TableSchema table, string startColumnName, string endColumnName, Query query) { ColumnSchema startCol = table.Columns[startColumnName]; ColumnSchema endCol = table.Columns[endColumnName]; StoredTable stTable = StorageFactory.Table.Create(table, query); return Create(startCol, endCol, stTable, query); } public static StoredValue CreateValue(TableSchema startTable, string startColumnName, TableSchema endTable, string endColumnName, Query query) { ColumnSchema startCol = startTable.Columns[startColumnName]; ColumnSchema endCol = endTable.Columns[endColumnName]; StoredTable stStartTable = StorageFactory.Table.Create(startTable, query); StoredTable stEndTable = StorageFactory.Table.Create(endTable, query); return Create(startCol, stStartTable, endCol, stEndTable, query); } public static StoredValue CreateValue<TEtt>(string columnName, Query query) where TEtt : EntityBase { StoredTable stTable = StorageFactory.Table.Create<TEtt>(query); return Create(columnName, stTable, query); } public static StoredValue CreateValue(string tableName, string columnName, Query query) { StoredTable stTable = StorageFactory.Table.Create(tableName, query); return Create(columnName, stTable, query); } public static StoredValue CreateValue(string tableName, string startColumnName, string endColumnName, Query query) { StoredTable stTable = StorageFactory.Table.Create(tableName, query); return Create(startColumnName, endColumnName, stTable, query); } public static StoredValue CreateValue(string startTableName, string startColumnName, string endTableName, string endColumnName, Query query) { StoredTable stStartTable = StorageFactory.Table.Create(startTableName, query); StoredTable stEndTable = StorageFactory.Table.Create(endTableName, query); return Create(startColumnName, stStartTable, endColumnName, stEndTable, query); } public static StoredValue CreateValue(string columnName, Query query) { return new StoredValue(new ValueStoredColumnDefinition( Column.Create(columnName, query)), StoredValue.StoredTypes.StoredColumn); } } public class Constraint { public static StoredConstraint Create(StoredColumn storedColumn, StoredConstraint.ConstraintType type, Query parent) { StoredConstraint ret = new StoredConstraint(); ret.Column = storedColumn; ret.Type = type; ret.Parent = parent; return ret; } public static StoredConstraint Create(StoredColumn storedColumn, StoredConstraint.ConstraintType type, ComparisonOperator comparison, Query parent) { StoredConstraint ret = new StoredConstraint(); ret.Column = storedColumn; ret.Type = type; ret.Parent = parent; return ret; } public static StoredConstraint Create(ComparisonOperator comparison, Query parent) { StoredConstraint ret = new StoredConstraint(); ret.Type = StoredConstraint.ConstraintType.None; ret.Comparison = comparison; ret.Parent = parent; return ret; } public static StoredConstraint Create(StoredConstraint.ConstraintType type, ComparisonOperator comparison, Query parent) { StoredConstraint ret = new StoredConstraint(); ret.Type = type; ret.Comparison = comparison; ret.Parent = parent; return ret; } public static StoredConstraint CreateWhere(StoredColumn storedColumn, Query parent) { return Create(storedColumn, StoredConstraint.ConstraintType.Where, parent); } public static StoredConstraint CreateAnd(StoredColumn storedColumn, Query parent) { return Create(storedColumn, StoredConstraint.ConstraintType.And, parent); } public static StoredConstraint CreateOr(StoredColumn storedColumn, Query parent) { return Create(storedColumn, StoredConstraint.ConstraintType.Or, parent); } public static StoredConstraint CreateWhereOpenParentesis(StoredColumn storedColumn, Query parent) { return Create(storedColumn, StoredConstraint.ConstraintType.Where, ComparisonOperator.OpenParentheses, parent); } public static StoredConstraint CreateAndOpenParentesis(StoredColumn storedColumn, Query parent) { return Create(storedColumn, StoredConstraint.ConstraintType.And, ComparisonOperator.OpenParentheses, parent); } public static StoredConstraint CreateOrOpenParentesis(StoredColumn storedColumn, Query parent) { return Create(storedColumn, StoredConstraint.ConstraintType.Or, ComparisonOperator.OpenParentheses, parent); } public static StoredConstraint CreateWhereOpenParentesis(Query parent) { return Create(StoredConstraint.ConstraintType.Where, ComparisonOperator.OpenParentheses, parent); } public static StoredConstraint CreateAndOpenParentesis(Query parent) { return Create(StoredConstraint.ConstraintType.And, ComparisonOperator.OpenParentheses, parent); } public static StoredConstraint CreateOrOpenParentesis(Query parent) { return Create(StoredConstraint.ConstraintType.Or, ComparisonOperator.OpenParentheses, parent); } public static StoredConstraint CreateOpenParentesis(Query parent) { return Create(ComparisonOperator.OpenParentheses, parent); } public static StoredConstraint CreateCloseParentesis(Query parent) { return Create(ComparisonOperator.CloseParentheses, parent); } } public class JoinConstraint { public static StoredJoinConstraint Create(StoredColumn storedColumn, StoredJoinConstraint.ConstraintType type, StoredJoin parent) { StoredJoinConstraint ret = new StoredJoinConstraint(); ret.Column = storedColumn; ret.Type = type; ret.Parent = parent; return ret; } public static StoredJoinConstraint Create(StoredColumn storedColumn, StoredJoinConstraint.ConstraintType type, ComparisonOperator comparison, StoredJoin parent) { StoredJoinConstraint ret = new StoredJoinConstraint(); ret.Column = storedColumn; ret.Type = type; ret.Parent = parent; return ret; } public static StoredJoinConstraint Create(ComparisonOperator comparison, StoredJoin parent) { StoredJoinConstraint ret = new StoredJoinConstraint(); ret.Type = StoredJoinConstraint.ConstraintType.None; ret.Comparison = comparison; ret.Parent = parent; return ret; } public static StoredJoinConstraint Create(StoredJoinConstraint.ConstraintType type, ComparisonOperator comparison, StoredJoin parent) { StoredJoinConstraint ret = new StoredJoinConstraint(); ret.Type = type; ret.Comparison = comparison; ret.Parent = parent; return ret; } public static StoredJoinConstraint CreateWhere(StoredColumn storedColumn, StoredJoin parent) { return Create(storedColumn, StoredJoinConstraint.ConstraintType.Where, parent); } public static StoredJoinConstraint CreateAnd(StoredColumn storedColumn, StoredJoin parent) { return Create(storedColumn, StoredJoinConstraint.ConstraintType.And, parent); } public static StoredJoinConstraint CreateOr(StoredColumn storedColumn, StoredJoin parent) { return Create(storedColumn, StoredJoinConstraint.ConstraintType.Or, parent); } public static StoredJoinConstraint CreateWhereOpenParentesis(StoredColumn storedColumn, StoredJoin parent) { return Create(storedColumn, StoredJoinConstraint.ConstraintType.Where, ComparisonOperator.OpenParentheses, parent); } public static StoredJoinConstraint CreateAndOpenParentesis(StoredColumn storedColumn, StoredJoin parent) { return Create(storedColumn, StoredJoinConstraint.ConstraintType.And, ComparisonOperator.OpenParentheses, parent); } public static StoredJoinConstraint CreateOrOpenParentesis(StoredColumn storedColumn, StoredJoin parent) { return Create(storedColumn, StoredJoinConstraint.ConstraintType.Or, ComparisonOperator.OpenParentheses, parent); } public static StoredJoinConstraint CreateWhereOpenParentesis(StoredJoin parent) { return Create(StoredJoinConstraint.ConstraintType.Where, ComparisonOperator.OpenParentheses, parent); } public static StoredJoinConstraint CreateAndOpenParentesis(StoredJoin parent) { return Create(StoredJoinConstraint.ConstraintType.And, ComparisonOperator.OpenParentheses, parent); } public static StoredJoinConstraint CreateOrOpenParentesis(StoredJoin parent) { return Create(StoredJoinConstraint.ConstraintType.Or, ComparisonOperator.OpenParentheses, parent); } public static StoredJoinConstraint CreateOpenParentesis(StoredJoin parent) { return Create(ComparisonOperator.OpenParentheses, parent); } public static StoredJoinConstraint CreateCloseParentesis(StoredJoin parent) { return Create(ComparisonOperator.OpenParentheses, parent); } } public class CaseConstraint { public static CaseCondition Create(StoredColumn storedColumn, StoredCaseWhen parent) { CaseCondition ret = new CaseCondition(parent); ret.Column = storedColumn; ret.Type = StoredConstraint.ConstraintType.None; return ret; } public static CaseCondition Create(StoredColumn storedColumn, ComparisonOperator comparison, StoredCaseWhen parent) { CaseCondition ret = new CaseCondition(parent); ret.Column = storedColumn; ret.Type = StoredConstraint.ConstraintType.None; return ret; } public static CaseCondition Create(ComparisonOperator comparison, StoredCaseWhen parent) { CaseCondition ret = new CaseCondition(parent); ret.Comparison = comparison; ret.Type = StoredConstraint.ConstraintType.None; return ret; } public static CaseCondition CreateCondition(StoredColumn storedColumn, StoredCaseWhen parent) { return Create(storedColumn, parent); } } public class SetColumnValue { public static SetColumnValueRet<T> Create<T>(Schema.ColumnSchema columnSchema, Query query, T parent) { return Create<T>(columnSchema, Table.Create(columnSchema.Parent, query), query, parent); } public static SetColumnValueRet<T> Create<T>(Schema.ColumnSchema columnSchema, StoredTable table, Query query, T parent) { return new SetColumnValueRet<T>(columnSchema, StoredColumn.StoredTypes.Schema, table, query, parent); } public static SetColumnValueRet<T> Create<T>(string name, StoredTable table, Query query, T parent) { if ((table.Type == StoredTable.StoredTypes.Schema)) { IColumnDefinition colDef = table.TableDefinition.GetColumn(name); return new SetColumnValueRet<T>(colDef, StoredColumn.StoredTypes.Schema, table, query, parent); } else { return new SetColumnValueRet<T>(new ColumnNameDefinition(name, table.TableDefinition), StoredColumn.StoredTypes.Name, table, query, parent); } } static internal SetColumnValueRet<T> Create<T>(StoredTable table, string nickName, Query query, T parent) { return new SetColumnValueRet<T>(new ColumnAliasDefinition(nickName, table.TableDefinition), StoredColumn.StoredTypes.OnlyAlias, table, query, parent); } public static SetColumnValueRet<T> Create<T>(string name, Query query, T parent) { return new SetColumnValueRet<T>(new ColumnUnknowTableDefinition(name), StoredColumn.StoredTypes.UnknowTable, query, parent); } public static SetColumnValueRet<T> Create<T>(Schema.ColumnSchema columnSchema, string tableName, Query query, T parent) { StoredTable storedTable = Table.Create(tableName, query); return Create<T>(columnSchema, storedTable, query, parent); } public static SetColumnValueRet<T> Create<T>(string name, string tableName, Query query, T parent) { StoredTable storedTable = Table.Create(tableName, query); return Create<T>(name, storedTable, query, parent); } public static SetColumnValueRet<T> Create<T>(string name, TableSchema tableSchema, Query query, T parent) { StoredTable storedTable = Table.Create(tableSchema, query); return Create<T>(name, storedTable, query, parent); } public static SetColumnValueRet<T> Create<T>(string name, EntityBase entity, Query query, T parent) { StoredTable storedTable = Table.Create(entity, query); return Create<T>(name, storedTable, query, parent); } public static SetColumnValueRet<T> Create<TEtt, T>(string name, Query query, T parent) where TEtt : EntityBase { StoredTable storedTable = Table.Create<TEtt>(query); return Create<T>(name, storedTable, query, parent); } static internal SetColumnValueRet<T> Create<T>(StoredFunction stFunction, StoredTable table, Query query, T parent) { return new SetColumnValueRet<T>(new ColumnFunctionDefinition(stFunction, table.TableDefinition), StoredColumn.StoredTypes.StoredFunction, table, query, parent); } public static SetColumnValueRet<T> Create<T>(StoredFunction stFunction, Query query, T parent) { return new SetColumnValueRet<T>(new ColumnFunctionDefinition(stFunction), StoredColumn.StoredTypes.StoredFunction, query, parent); } static internal SetColumnValueRet<T> CreateNick<T>(string tableName, string nickName, Query query, T parent) { StoredTable storedTable = Table.Create(tableName, query); return Create<T>(storedTable, nickName, query, parent); } public static Storage.Value.SetColumnValue Create(Schema.ColumnSchema columnSchema, Query query) { return Create(columnSchema, Table.Create(columnSchema.Parent, query), query); } public static Storage.Value.SetColumnValue Create(Schema.ColumnSchema columnSchema, StoredTable table, Query query) { return new Storage.Value.SetColumnValue(columnSchema, StoredColumn.StoredTypes.Schema, table, query); } public static Storage.Value.SetColumnValue Create(string name, StoredTable table, Query query) { if ((table.Type == StoredTable.StoredTypes.Schema)) { IColumnDefinition colDef = table.TableDefinition.GetColumn(name); return new Storage.Value.SetColumnValue(colDef, StoredColumn.StoredTypes.Schema, table, query); } else { return new Storage.Value.SetColumnValue(new ColumnNameDefinition(name, table.TableDefinition), StoredColumn.StoredTypes.Name, table, query); } } static internal Storage.Value.SetColumnValue Create(StoredTable table, string nickName, Query query) { return new Storage.Value.SetColumnValue(new ColumnAliasDefinition(nickName, table.TableDefinition), StoredColumn.StoredTypes.OnlyAlias, table, query); } public static Storage.Value.SetColumnValue Create(string name, Query query) { return new Storage.Value.SetColumnValue(new ColumnUnknowTableDefinition(name), StoredColumn.StoredTypes.UnknowTable, query); } public static Storage.Value.SetColumnValue Create(Schema.ColumnSchema columnSchema, string tableName, Query query) { StoredTable storedTable = Table.Create(tableName, query); return Create(columnSchema, storedTable, query); } public static Storage.Value.SetColumnValue Create(string name, string tableName, Query query) { StoredTable storedTable = Table.Create(tableName, query); return Create(name, storedTable, query); } public static Storage.Value.SetColumnValue Create(string name, TableSchema tableSchema, Query query) { StoredTable storedTable = Table.Create(tableSchema, query); return Create(name, storedTable, query); } public static Storage.Value.SetColumnValue Create(string name, EntityBase entity, Query query) { StoredTable storedTable = Table.Create(entity, query); return Create(name, storedTable, query); } public static Storage.Value.SetColumnValue Create<TEtt>(string name, Query query) where TEtt : EntityBase { StoredTable storedTable = Table.Create<TEtt>(query); return Create(name, storedTable, query); } static internal Storage.Value.SetColumnValue Create(StoredFunction stFunction, StoredTable table, Query query) { return new Storage.Value.SetColumnValue(new ColumnFunctionDefinition(stFunction, table.TableDefinition), StoredColumn.StoredTypes.StoredFunction, table, query); } public static Storage.Value.SetColumnValue Create(StoredFunction stFunction, Query query) { return new Storage.Value.SetColumnValue(new ColumnFunctionDefinition(stFunction), StoredColumn.StoredTypes.StoredFunction, query); } static internal Storage.Value.SetColumnValue CreateNick<T>(string tableName, string nickName, Query query) { StoredTable storedTable = Table.Create(tableName, query); return Create(storedTable, nickName, query); } } public class SFunction { public static StoredFunction Create(string name) { return new StoredFunction(name); } public static StoredFunction Create(string name, string owner) { return new StoredFunction(name, owner); } public static StoredFunction Create(string name, Query query) { return new StoredFunction(name, query); } public static StoredFunction Create(string name, string owner, Query query) { return new StoredFunction(name, owner, query); } public class Avg { public static FunctionAvg Create() { return new FunctionAvg(); } public static FunctionAvg Create(Query query) { return new FunctionAvg(query); } } public class Count { public static FunctionCount Create() { return new FunctionCount(); } public static FunctionCount Create(Query query) { return new FunctionCount(query); } } public class Max { public static FunctionMax Create() { return new FunctionMax(); } public static FunctionMax Create(Query query) { return new FunctionMax(query); } } public class Min { public static FunctionMin Create() { return new FunctionMin(); } public static FunctionMin Create(Query query) { return new FunctionMin(query); } } public class Sum { public static FunctionSum Create() { return new FunctionSum(); } public static FunctionSum Create(Query query) { return new FunctionSum(query); } } public class Convert { public static FunctionConvert Create() { return new FunctionConvert(); } public static FunctionConvert Create(Query query) { return new FunctionConvert(query); } } public class SequenciaParam { public static SequenciaParamStoredFunction Create(string name) { return new SequenciaParamStoredFunction(name); } public static SequenciaParamStoredFunction Create(string name, string owner) { return new SequenciaParamStoredFunction(name, owner); } public static SequenciaParamStoredFunction Create(string name, Query query) { return new SequenciaParamStoredFunction(name, query); } public static SequenciaParamStoredFunction Create(string name, string owner, Query query) { return new SequenciaParamStoredFunction(name, owner, query); } } } public class OrderBy { public static StoredOrderBy Create(Schema.ColumnSchema columnSchema, Query query) { return Create(columnSchema, Table.Create(columnSchema.Parent, query), query); } public static StoredOrderBy Create(Schema.ColumnSchema columnSchema, StoredTable table, Query query) { return new StoredOrderBy(columnSchema, StoredColumn.StoredTypes.Schema, table, query); } public static StoredOrderBy Create(string name, StoredTable table, Query query) { if ((table.Type == StoredTable.StoredTypes.Schema)) { IColumnDefinition colDef = table.TableDefinition.GetColumn(name); return new StoredOrderBy(colDef, StoredColumn.StoredTypes.Schema, table, query); } else { return new StoredOrderBy(new ColumnNameDefinition(name, table.TableDefinition), StoredColumn.StoredTypes.Name, table, query); } } static internal StoredOrderBy Create(StoredTable table, string nickName, Query query) { return new StoredOrderBy(new ColumnAliasDefinition(nickName, table.TableDefinition), StoredColumn.StoredTypes.OnlyAlias, table, query); } public static StoredOrderBy Create(string name, Query query) { return new StoredOrderBy(new ColumnUnknowTableDefinition(name), StoredColumn.StoredTypes.UnknowTable, query); } public static StoredOrderBy Create(Schema.ColumnSchema columnSchema, string tableName, Query query) { StoredTable storedTable = Table.Create(tableName, query); return Create(columnSchema, storedTable, query); } public static StoredOrderBy Create(string name, string tableName, Query query) { StoredTable storedTable = Table.Create(tableName, query); return Create(name, storedTable, query); } public static StoredOrderBy Create(string name, TableSchema tableSchema, Query query) { StoredTable storedTable = Table.Create(tableSchema, query); return Create(name, storedTable, query); } public static StoredOrderBy Create(string name, EntityBase entity, Query query) { StoredTable storedTable = Table.Create(entity, query); return Create(name, storedTable, query); } public static StoredOrderBy Create<TEtt>(string name, Query query) where TEtt : EntityBase { StoredTable storedTable = Table.Create<TEtt>(query); return Create(name, storedTable, query); } static internal StoredOrderBy Create(StoredFunction stFunction, StoredTable table, Query query) { return new StoredOrderBy(new ColumnFunctionDefinition(stFunction, table.TableDefinition), StoredColumn.StoredTypes.StoredFunction, table, query); } public static StoredOrderBy Create(StoredFunction stFunction, Query query) { return new StoredOrderBy(new ColumnFunctionDefinition(stFunction), StoredColumn.StoredTypes.StoredFunction, query); } } public class GroupBy { public static StoredGroupBy Create(Schema.ColumnSchema columnSchema, Query query) { return Create(columnSchema, Table.Create(columnSchema.Parent, query), query); } public static StoredGroupBy Create(Schema.ColumnSchema columnSchema, StoredTable table, Query query) { return new StoredGroupBy(columnSchema, StoredColumn.StoredTypes.Schema, table, query); } public static StoredGroupBy Create(string name, StoredTable table, Query query) { if ((table.Type == StoredTable.StoredTypes.Schema)) { IColumnDefinition colDef = table.TableDefinition.GetColumn(name); return new StoredGroupBy(colDef, StoredColumn.StoredTypes.Schema, table, query); } else { return new StoredGroupBy(new ColumnNameDefinition(name, table.TableDefinition), StoredColumn.StoredTypes.Name, table, query); } } static internal StoredGroupBy Create(StoredTable table, string nickName, Query query) { return new StoredGroupBy(new ColumnAliasDefinition(nickName, table.TableDefinition), StoredColumn.StoredTypes.OnlyAlias, table, query); } public static StoredGroupBy Create(string name, Query query) { return new StoredGroupBy(new ColumnUnknowTableDefinition(name), StoredColumn.StoredTypes.UnknowTable, query); } public static StoredGroupBy Create(Schema.ColumnSchema columnSchema, string tableName, Query query) { StoredTable storedTable = Table.Create(tableName, query); return Create(columnSchema, storedTable, query); } public static StoredGroupBy Create(string name, string tableName, Query query) { StoredTable storedTable = Table.Create(tableName, query); return Create(name, storedTable, query); } public static StoredGroupBy Create(string name, TableSchema tableSchema, Query query) { StoredTable storedTable = Table.Create(tableSchema, query); return Create(name, storedTable, query); } public static StoredGroupBy Create(string name, EntityBase entity, Query query) { StoredTable storedTable = Table.Create(entity, query); return Create(name, storedTable, query); } public static StoredGroupBy Create<TEtt>(string name, Query query) where TEtt : EntityBase { StoredTable storedTable = Table.Create<TEtt>(query); return Create(name, storedTable, query); } static internal StoredGroupBy Create(StoredFunction stFunction, StoredTable table, Query query) { return new StoredGroupBy(new ColumnFunctionDefinition(stFunction, table.TableDefinition), StoredColumn.StoredTypes.StoredFunction, table, query); } public static StoredGroupBy Create(StoredFunction stFunction, Query query) { return new StoredGroupBy(new ColumnFunctionDefinition(stFunction), StoredColumn.StoredTypes.StoredFunction, query); } } public class CaseFactory { /// <summary> /// Where the column. /// </summary> /// <param name="column">The column.</param> /// <returns></returns> public StoredCaseWhen Create(Query query) { return new StoredCaseWhen(query); } /// <summary> /// Where the column. /// </summary> /// <param name="column">The column.</param> /// <returns></returns> public StoredCase Create(StoredValue value, Query query) { return new StoredCase(); } } public class Having { } public class NQuery { /// <summary> /// Initialize Select query. /// </summary> /// <returns></returns> static public Query Select(Provider provider) { return new Query(Query.QueryType.Select, provider); } /// <summary> /// Initialize Insert query. /// </summary> /// <returns></returns> static public Query Insert(Provider provider) { return new Query(Query.QueryType.Insert, provider); } /// <summary> /// Initialize Update query. /// </summary> /// <returns></returns> static public Query Update(Provider provider) { return new Query(Query.QueryType.Update, provider); } /// <summary> /// Initialize Delete query. /// </summary> /// <returns></returns> static public Query Delete(Provider provider) { return new Query(Query.QueryType.Delete, provider); } /// <summary> /// Initialize Procedure query. /// </summary> /// <returns></returns> static public Query Procedure(string procedureName, Provider provider) { Query query = new Query(Query.QueryType.Procedure, provider); query.Into(procedureName); return query; } /// <summary> /// Initialize Procedure query. /// </summary> /// <returns></returns> static public Query Procedure<TEtt>() where TEtt : EntityBase { Provider provider = Provider.GetProvider<TEtt>(); Query query = new Query(Query.QueryType.Procedure, provider); query.Into<TEtt>(); return query; } } } }
// 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 Xunit; using System.Collections.Generic; using System.Diagnostics; using System.Security; using System.Reflection; using System.Collections.Concurrent; using System.Linq; namespace System.Threading.Tasks.Tests { // // Task scheduler basics. // public static class TaskSchedulerTests { // Just ensure we eventually complete when many blocked tasks are created. [Fact] public static void RunBlockedInjectionTest() { Debug.WriteLine("* RunBlockedInjectionTest() -- if it deadlocks, it failed"); ManualResetEvent mre = new ManualResetEvent(false); // we need to run this test in a local task scheduler, because it needs to to perform // the verification based on a known number of initially available threads. // // // @TODO: When we reach the _planB branch we need to add a trick here using ThreadPool.SetMaxThread // to bring down the TP worker count. This is because previous activity in the test process might have // injected workers. TaskScheduler tm = TaskScheduler.Default; // Create many tasks blocked on the MRE. int processorCount = Environment.ProcessorCount; Task[] tasks = new Task[processorCount]; for (int i = 0; i < tasks.Length; i++) { tasks[i] = Task.Factory.StartNew(delegate { mre.WaitOne(); }, CancellationToken.None, TaskCreationOptions.None, tm); } // Create one task that signals the MRE, and wait for it. Task.Factory.StartNew(delegate { mre.Set(); }, CancellationToken.None, TaskCreationOptions.None, tm).Wait(); // Lastly, wait for the others to complete. Task.WaitAll(tasks); } [Fact] public static void RunBuggySchedulerTests() { Debug.WriteLine("* RunBuggySchedulerTests()"); BuggyTaskScheduler bts = new BuggyTaskScheduler(); Task t1 = new Task(delegate { }); Task t2 = new Task(delegate { }); // // Test Task.Start(buggy scheduler) // Debug.WriteLine(" -- testing Task.Start(buggy scheduler)"); try { t1.Start(bts); Assert.True(false, string.Format(" > FAILED. No exception thrown.")); } catch (TaskSchedulerException) { } catch (Exception e) { Assert.True(false, string.Format(" > FAILED. Wrong exception thrown (expected TaskSchedulerException): {0}", e)); } if (t1.Status != TaskStatus.Faulted) { Assert.True(false, string.Format(" > FAILED. Task ended up in wrong status (expected Faulted): {0}", t1.Status)); } Debug.WriteLine(" -- Waiting on Faulted task (there's a problem if we deadlock)..."); try { t1.Wait(); Assert.True(false, string.Format(" > FAILED. No exception thrown from Wait().")); } catch (AggregateException ae) { if (!(ae.InnerExceptions[0] is TaskSchedulerException)) { Assert.True(false, string.Format(" > FAILED. Wrong inner exception thrown from Wait(): {0}", ae.InnerExceptions[0].GetType().Name)); } } // // Test Task.RunSynchronously(buggy scheduler) // Debug.WriteLine(" -- testing Task.RunSynchronously(buggy scheduler)"); try { t2.RunSynchronously(bts); Assert.True(false, string.Format(" > FAILED. No exception thrown.")); } catch (TaskSchedulerException) { } catch (Exception e) { Assert.True(false, string.Format(" > FAILED. Wrong exception thrown (expected TaskSchedulerException): {0}", e)); } if (t2.Status != TaskStatus.Faulted) { Assert.True(false, string.Format(" > FAILED. Task ended up in wrong status (expected Faulted): {0}", t1.Status)); } Debug.WriteLine(" -- Waiting on Faulted task (there's a problem if we deadlock)..."); try { t2.Wait(); Assert.True(false, string.Format(" > FAILED. No exception thrown from Wait().")); } catch (AggregateException ae) { if (!(ae.InnerExceptions[0] is TaskSchedulerException)) { Assert.True(false, string.Format(" > FAILED. Wrong inner exception thrown from Wait(): {0}", ae.InnerExceptions[0].GetType().Name)); } } // // Test StartNew(buggy scheduler) // Debug.WriteLine(" -- testing Task.Factory.StartNew(buggy scheduler)"); try { Task t3 = Task.Factory.StartNew(delegate { }, CancellationToken.None, TaskCreationOptions.None, bts); Assert.True(false, string.Format(" > FAILED. No exception thrown.")); } catch (TaskSchedulerException) { } catch (Exception e) { Assert.True(false, string.Format(" > FAILED. Wrong exception thrown (expected TaskSchedulerException): {0}", e)); } // // Test continuations // Debug.WriteLine(" -- testing Task.ContinueWith(buggy scheduler)"); Task completedTask = Task.Factory.StartNew(delegate { }); completedTask.Wait(); Task tc1 = completedTask.ContinueWith(delegate { }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, bts); Debug.WriteLine(" -- Waiting on Faulted task (there's a problem if we deadlock)..."); try { tc1.Wait(); Assert.True(false, string.Format(" > FAILED. No exception thrown (sync).")); } catch (AggregateException ae) { if (!(ae.InnerExceptions[0] is TaskSchedulerException)) { Assert.True(false, string.Format(" > FAILED. Wrong inner exception thrown from Wait() (sync): {0}", ae.InnerExceptions[0].GetType().Name)); } } catch (Exception e) { Assert.True(false, string.Format(" > FAILED. Wrong exception thrown (sync): {0}", e)); } Task tc2 = completedTask.ContinueWith(delegate { }, CancellationToken.None, TaskContinuationOptions.None, bts); Debug.WriteLine(" -- Waiting on Faulted task (there's a problem if we deadlock)..."); try { tc2.Wait(); Assert.True(false, string.Format(" > FAILED. No exception thrown (async).")); } catch (AggregateException ae) { if (!(ae.InnerExceptions[0] is TaskSchedulerException)) { Assert.True(false, string.Format(" > FAILED. Wrong inner exception thrown from Wait() (async): {0}", ae.InnerExceptions[0].GetType().Name)); } } catch (Exception e) { Assert.True(false, string.Format(" > FAILED. Wrong exception thrown (async): {0}", e)); } // Test Wait()/inlining Debug.WriteLine(" -- testing Task.Wait(task started on buggy scheduler)"); BuggyTaskScheduler bts2 = new BuggyTaskScheduler(false); // won't throw on QueueTask Task t4 = new Task(delegate { }); t4.Start(bts2); try { t4.Wait(); Assert.True(false, string.Format(" > FAILED. Expected inlining exception")); } catch (TaskSchedulerException) { } catch (Exception e) { Assert.True(false, string.Format(" > FAILED. Wrong exception thrown: {0}", e)); } } [Fact] [OuterLoop] public static void RunSynchronizationContextTaskSchedulerTests() { // Remember the current SynchronizationContext, so that we can restore it SynchronizationContext previousSC = SynchronizationContext.Current; // Now make up a "real" SynchronizationContext abd install it SimpleSynchronizationContext newSC = new SimpleSynchronizationContext(); SetSynchronizationContext(newSC); // Create a scheduler based on the current SC TaskScheduler scTS = TaskScheduler.FromCurrentSynchronizationContext(); // // Launch a Task on scTS, make sure that it is processed in the expected fashion // bool sideEffect = false; Task task = Task.Factory.StartNew(() => { sideEffect = true; }, CancellationToken.None, TaskCreationOptions.None, scTS); Exception ex = null; try { task.Wait(); } catch (Exception e) { ex = e; } Assert.True(task.IsCompleted, "Expected task to have completed"); Assert.True(ex == null, "Did not expect exception on Wait"); Assert.True(sideEffect, "Task appears not to have run"); Assert.True(newSC.PostCount == 1, "Expected exactly one post to underlying SynchronizationContext"); // // Run a Task synchronously on scTS, make sure that it completes // sideEffect = false; Task syncTask = new Task(() => { sideEffect = true; }); ex = null; try { syncTask.RunSynchronously(scTS); } catch (Exception e) { ex = e; } Assert.True(task.IsCompleted, "Expected task to have completed"); Assert.True(ex == null, "Did not expect exception on RunSynchronously"); Assert.True(sideEffect, "Task appears not to have run"); Assert.True(newSC.PostCount == 1, "Did not expect a new Post to underlying SynchronizationContext"); // // Miscellaneous things to test // Assert.True(scTS.MaximumConcurrencyLevel == 1, "Expected scTS.MaximumConcurrencyLevel to be 1"); // restore original SC SetSynchronizationContext(previousSC); } [Fact] public static void RunSynchronizationContextTaskSchedulerTests_Negative() { // Remember the current SynchronizationContext, so that we can restore it SynchronizationContext previousSC = SynchronizationContext.Current; // // Test exceptions on construction of SCTaskScheduler // SetSynchronizationContext(null); Assert.Throws<InvalidOperationException>( () => { TaskScheduler.FromCurrentSynchronizationContext(); }); } [Fact] public static void GetTaskSchedulersForDebugger_ReturnsDefaultScheduler() { MethodInfo getTaskSchedulersForDebuggerMethod = typeof(TaskScheduler).GetTypeInfo().GetDeclaredMethod("GetTaskSchedulersForDebugger"); TaskScheduler[] foundSchedulers = getTaskSchedulersForDebuggerMethod.Invoke(null, null) as TaskScheduler[]; Assert.NotNull(foundSchedulers); Assert.Contains(TaskScheduler.Default, foundSchedulers); } [ConditionalFact(nameof(DebuggerIsAttached))] public static void GetTaskSchedulersForDebugger_DebuggerAttached_ReturnsAllSchedulers() { MethodInfo getTaskSchedulersForDebuggerMethod = typeof(TaskScheduler).GetTypeInfo().GetDeclaredMethod("GetTaskSchedulersForDebugger"); var cesp = new ConcurrentExclusiveSchedulerPair(); TaskScheduler[] foundSchedulers = getTaskSchedulersForDebuggerMethod.Invoke(null, null) as TaskScheduler[]; Assert.NotNull(foundSchedulers); Assert.Contains(TaskScheduler.Default, foundSchedulers); Assert.Contains(cesp.ConcurrentScheduler, foundSchedulers); Assert.Contains(cesp.ExclusiveScheduler, foundSchedulers); GC.KeepAlive(cesp); } [ConditionalFact(nameof(DebuggerIsAttached))] public static void GetScheduledTasksForDebugger_DebuggerAttached_ReturnsTasksFromCustomSchedulers() { var nonExecutingScheduler = new BuggyTaskScheduler(faultQueues: false); Task[] queuedTasks = (from i in Enumerable.Range(0, 10) select Task.Factory.StartNew(() => { }, CancellationToken.None, TaskCreationOptions.None, nonExecutingScheduler)).ToArray(); MethodInfo getScheduledTasksForDebuggerMethod = typeof(TaskScheduler).GetTypeInfo().GetDeclaredMethod("GetScheduledTasksForDebugger"); Task[] foundTasks = getScheduledTasksForDebuggerMethod.Invoke(nonExecutingScheduler, null) as Task[]; Assert.Superset(new HashSet<Task>(queuedTasks), new HashSet<Task>(foundTasks)); GC.KeepAlive(nonExecutingScheduler); } private static bool DebuggerIsAttached { get { return Debugger.IsAttached; } } #region Helper Methods / Helper Classes // Buggy task scheduler to make sure that we handle QueueTask()/TryExecuteTaskInline() // exceptions correctly. Used in RunBuggySchedulerTests() below. [SecuritySafeCritical] public class BuggyTaskScheduler : TaskScheduler { private readonly ConcurrentQueue<Task> _tasks = new ConcurrentQueue<Task>(); private bool _faultQueues; [SecurityCritical] protected override void QueueTask(Task task) { if (_faultQueues) throw new InvalidOperationException("I don't queue tasks!"); // else do nothing other than store the task -- still a pretty buggy scheduler!! _tasks.Enqueue(task); } [SecurityCritical] protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { throw new ArgumentException("I am your worst nightmare!"); } [SecurityCritical] protected override IEnumerable<Task> GetScheduledTasks() { return _tasks; } public BuggyTaskScheduler() : this(true) { } public BuggyTaskScheduler(bool faultQueues) { _faultQueues = faultQueues; } } private class SimpleSynchronizationContext : SynchronizationContext { private int _postCount = 0; public override void Post(SendOrPostCallback d, object state) { _postCount++; base.Post(d, state); } public int PostCount { get { return _postCount; } } } private static void SetSynchronizationContext(SynchronizationContext sc) { SynchronizationContext.SetSynchronizationContext(sc); } #endregion } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace ParentLoadSoftDelete.Business.ERCLevel { /// <summary> /// F01_ContinentColl (editable root list).<br/> /// This is a generated base class of <see cref="F01_ContinentColl"/> business object. /// </summary> /// <remarks> /// The items of the collection are <see cref="F02_Continent"/> objects. /// </remarks> [Serializable] public partial class F01_ContinentColl : BusinessListBase<F01_ContinentColl, F02_Continent> { #region Collection Business Methods /// <summary> /// Removes a <see cref="F02_Continent"/> item from the collection. /// </summary> /// <param name="continent_ID">The Continent_ID of the item to be removed.</param> public void Remove(int continent_ID) { foreach (var f02_Continent in this) { if (f02_Continent.Continent_ID == continent_ID) { Remove(f02_Continent); break; } } } /// <summary> /// Determines whether a <see cref="F02_Continent"/> item is in the collection. /// </summary> /// <param name="continent_ID">The Continent_ID of the item to search for.</param> /// <returns><c>true</c> if the F02_Continent is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int continent_ID) { foreach (var f02_Continent in this) { if (f02_Continent.Continent_ID == continent_ID) { return true; } } return false; } /// <summary> /// Determines whether a <see cref="F02_Continent"/> item is in the collection's DeletedList. /// </summary> /// <param name="continent_ID">The Continent_ID of the item to search for.</param> /// <returns><c>true</c> if the F02_Continent is a deleted collection item; otherwise, <c>false</c>.</returns> public bool ContainsDeleted(int continent_ID) { foreach (var f02_Continent in DeletedList) { if (f02_Continent.Continent_ID == continent_ID) { return true; } } return false; } #endregion #region Find Methods /// <summary> /// Finds a <see cref="F02_Continent"/> item of the <see cref="F01_ContinentColl"/> collection, based on item key properties. /// </summary> /// <param name="continent_ID">The Continent_ID.</param> /// <returns>A <see cref="F02_Continent"/> object.</returns> public F02_Continent FindF02_ContinentByParentProperties(int continent_ID) { for (var i = 0; i < this.Count; i++) { if (this[i].Continent_ID.Equals(continent_ID)) { return this[i]; } } return null; } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="F01_ContinentColl"/> collection. /// </summary> /// <returns>A reference to the created <see cref="F01_ContinentColl"/> collection.</returns> public static F01_ContinentColl NewF01_ContinentColl() { return DataPortal.Create<F01_ContinentColl>(); } /// <summary> /// Factory method. Loads a <see cref="F01_ContinentColl"/> collection. /// </summary> /// <returns>A reference to the fetched <see cref="F01_ContinentColl"/> collection.</returns> public static F01_ContinentColl GetF01_ContinentColl() { return DataPortal.Fetch<F01_ContinentColl>(); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="F01_ContinentColl"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public F01_ContinentColl() { // Use factory methods and do not use direct creation. var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = true; AllowEdit = true; AllowRemove = true; RaiseListChangedEvents = rlce; } #endregion #region Data Access /// <summary> /// Loads a <see cref="F01_ContinentColl"/> collection from the database. /// </summary> protected void DataPortal_Fetch() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetF01_ContinentColl", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; var args = new DataPortalHookArgs(cmd); OnFetchPre(args); LoadCollection(cmd); OnFetchPost(args); } } } private void LoadCollection(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { Fetch(dr); if (this.Count > 0) this[0].FetchChildren(dr); } } /// <summary> /// Loads all <see cref="F01_ContinentColl"/> collection items from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; while (dr.Read()) { Add(F02_Continent.GetF02_Continent(dr)); } RaiseListChangedEvents = rlce; } /// <summary> /// Updates in the database all changes made to the <see cref="F01_ContinentColl"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Update() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { base.Child_Update(); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); #endregion } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: SampleOptionQuoting.SampleOptionQuotingPublic File: MainWindow.xaml.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace SampleOptionQuoting { using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Threading; using Ecng.ComponentModel; using Ecng.Common; using Ecng.Xaml; using StockSharp.Algo; using StockSharp.BusinessEntities; //using StockSharp.Plaza; using StockSharp.Quik; using StockSharp.Algo.Derivatives; using StockSharp.Algo.Strategies.Derivatives; using StockSharp.Messages; using StockSharp.Xaml; public partial class MainWindow { private class FakeConnector : Connector, IMarketDataProvider { public FakeConnector(IEnumerable<Security> securities) { Securities = securities; } public override IEnumerable<Security> Securities { get; } public override DateTimeOffset CurrentTime => DateTime.Now; object IMarketDataProvider.GetSecurityValue(Security security, Level1Fields field) { switch (field) { case Level1Fields.ImpliedVolatility: return security.ImpliedVolatility; } return null; } } private readonly ThreadSafeObservableCollection<Security> _options; private readonly ThreadSafeObservableCollection<Security> _assets; //private QuikTrader _trader; //private PlazaTrader _trader; private bool _isDirty; public IConnector Connector; public MainWindow() { InitializeComponent(); var assetsSource = new ObservableCollectionEx<Security>(); var optionsSource = new ObservableCollectionEx<Security>(); Options.ItemsSource = optionsSource; Assets.ItemsSource = assetsSource; _assets = new ThreadSafeObservableCollection<Security>(assetsSource); _options = new ThreadSafeObservableCollection<Security>(optionsSource); var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) }; timer.Tick += (sender, args) => { if (!_isDirty) return; _isDirty = false; RefreshChart(); }; timer.Start(); // // draw test data on the chart var asset = new Security { Id = "RIM4@FORTS" }; Connector = new FakeConnector(new[] { asset }); PosChart.AssetPosition = new Position { Security = asset, CurrentValue = -1, }; PosChart.MarketDataProvider = Connector; PosChart.SecurityProvider = Connector; var expDate = new DateTime(2014, 6, 14); PosChart.Positions.Add(new Position { Security = new Security { Code = "RI C 110000", Strike = 110000, ImpliedVolatility = 45, OptionType = OptionTypes.Call, ExpiryDate = expDate, Board = ExchangeBoard.Forts, UnderlyingSecurityId = asset.Id }, CurrentValue = 10, }); PosChart.Positions.Add(new Position { Security = new Security { Code = "RI P 95000", Strike = 95000, ImpliedVolatility = 30, OptionType = OptionTypes.Put, ExpiryDate = expDate, Board = ExchangeBoard.Forts, UnderlyingSecurityId = asset.Id }, CurrentValue = -3, }); PosChart.Refresh(100000, 10, new DateTime(2014, 5, 5), expDate); Instance = this; } public static MainWindow Instance { get; private set; } protected override void OnClosing(CancelEventArgs e) { Connector?.Dispose(); base.OnClosing(e); } private void ConnectClick(object sender, RoutedEventArgs e) { if (Connector != null && !(Connector is FakeConnector)) return; PosChart.Positions.Clear(); PosChart.AssetPosition = null; PosChart.Refresh(1, 1, default(DateTimeOffset), default(DateTimeOffset)); // create connection Connector = new QuikTrader(); //_trader = new PlazaTrader { IsCGate = true }; //_trader.Tables.Add(_trader.TableRegistry.Volatility); Portfolio.Portfolios = new PortfolioDataSource(Connector); PosChart.MarketDataProvider = Connector; PosChart.SecurityProvider = Connector; // fill underlying asset's list Connector.NewSecurities += securities => _assets.AddRange(securities.Where(s => s.Type == SecurityTypes.Future)); Connector.SecuritiesChanged += securities => { if ((PosChart.AssetPosition != null && securities.Contains(PosChart.AssetPosition.Security)) || PosChart.Positions.Cache.Select(p => p.Security).Intersect(securities).Any()) _isDirty = true; }; // subscribing on tick prices and updating asset price Connector.NewTrades += trades => { var assetPos = PosChart.AssetPosition; if (assetPos != null && trades.Any(t => t.Security == assetPos.Security)) _isDirty = true; }; Connector.NewPositions += positions => this.GuiAsync(() => { var asset = SelectedAsset; if (asset == null) return; var assetPos = positions.FirstOrDefault(p => p.Security == asset); var newPos = positions.Where(p => p.Security.UnderlyingSecurityId == asset.Id).ToArray(); if (assetPos == null && newPos.Length == 0) return; if (assetPos != null) PosChart.AssetPosition = assetPos; if (newPos.Length > 0) PosChart.Positions.AddRange(newPos); RefreshChart(); }); Connector.PositionsChanged += positions => this.GuiAsync(() => { if ((PosChart.AssetPosition != null && positions.Contains(PosChart.AssetPosition)) || positions.Intersect(PosChart.Positions.Cache).Any()) RefreshChart(); }); Connector.Connect(); } private void RefreshChart() { var asset = SelectedAsset; var trade = asset.LastTrade; if (trade != null) PosChart.Refresh(trade.Price, asset.PriceStep ?? 1m, TimeHelper.NowWithOffset, asset.ExpiryDate ?? DateTimeOffset.Now.Date + TimeSpan.FromDays(1)); } private Security SelectedOption => (Security)Options.SelectedItem; private Security SelectedAsset => (Security)Assets.SelectedItem; private void Assets_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { var asset = SelectedAsset; _options.Clear(); _options.AddRange(asset.GetDerivatives(Connector)); ProcessPositions(); } private void Portfolio_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { ProcessPositions(); } private void ProcessPositions() { var portfolio = Portfolio.SelectedPortfolio; if (portfolio == null) return; PosChart.Positions.AddRange(_options.Select(s => Connector.GetPosition(portfolio, s))); if (SelectedAsset != null) PosChart.AssetPosition = Connector.GetPosition(portfolio, SelectedAsset); RefreshChart(); } private void Options_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { var option = SelectedOption; if (option != null) { ImpliedVolatility.Text = option.ImpliedVolatility.To<string>(); ImpliedVolatilityMin.Value = ImpliedVolatilityMax.Value = option.ImpliedVolatility; } Start.IsEnabled = option != null; } private void StartClick(object sender, RoutedEventArgs e) { var option = SelectedOption; // create DOM window var wnd = new QuotesWindow { Title = option.Name }; wnd.Init(option); // create delta hedge strategy var hedge = new DeltaHedgeStrategy { Security = option.GetUnderlyingAsset(Connector), Portfolio = Portfolio.SelectedPortfolio, Connector = Connector, }; // create option quoting for 20 contracts var quoting = new VolatilityQuotingStrategy(Sides.Buy, 20, new Range<decimal>(ImpliedVolatilityMin.Value ?? 0, ImpliedVolatilityMax.Value ?? 100)) { // working size is 1 contract Volume = 1, Security = option, Portfolio = Portfolio.SelectedPortfolio, Connector = Connector, }; // link quoting and hending hedge.ChildStrategies.Add(quoting); // start henging hedge.Start(); wnd.Closed += (s1, e1) => { // force close all strategies while the DOM was closed hedge.Stop(); }; // show DOM wnd.Show(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System { // This file defines an internal class used to throw exceptions in BCL code. // The main purpose is to reduce code size. // // The old way to throw an exception generates quite a lot IL code and assembly code. // Following is an example: // C# source // throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key")); // IL code: // IL_0003: ldstr "key" // IL_0008: ldstr "ArgumentNull_Key" // IL_000d: call string System.Environment::GetResourceString(string) // IL_0012: newobj instance void System.ArgumentNullException::.ctor(string,string) // IL_0017: throw // which is 21bytes in IL. // // So we want to get rid of the ldstr and call to Environment.GetResource in IL. // In order to do that, I created two enums: ExceptionResource, ExceptionArgument to represent the // argument name and resource name in a small integer. The source code will be changed to // ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key, ExceptionResource.ArgumentNull_Key); // // The IL code will be 7 bytes. // IL_0008: ldc.i4.4 // IL_0009: ldc.i4.4 // IL_000a: call void System.ThrowHelper::ThrowArgumentNullException(valuetype System.ExceptionArgument) // IL_000f: ldarg.0 // // This will also reduce the Jitted code size a lot. // // It is very important we do this for generic classes because we can easily generate the same code // multiple times for different instantiation. // using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Diagnostics.Contracts; [Pure] internal static class ThrowHelper { internal static void ThrowArgumentOutOfRangeException() { ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index); } internal static void ThrowWrongKeyTypeArgumentException(object key, Type targetType) { throw new ArgumentException(Environment.GetResourceString("Arg_WrongType", key, targetType), "key"); } internal static void ThrowWrongValueTypeArgumentException(object value, Type targetType) { throw new ArgumentException(Environment.GetResourceString("Arg_WrongType", value, targetType), "value"); } #if FEATURE_CORECLR internal static void ThrowAddingDuplicateWithKeyArgumentException(object key) { throw new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicateWithKey", key)); } #endif internal static void ThrowKeyNotFoundException() { throw new System.Collections.Generic.KeyNotFoundException(); } internal static void ThrowArgumentException(ExceptionResource resource) { throw new ArgumentException(Environment.GetResourceString(GetResourceName(resource))); } internal static void ThrowArgumentException(ExceptionResource resource, ExceptionArgument argument) { throw new ArgumentException(Environment.GetResourceString(GetResourceName(resource)), GetArgumentName(argument)); } internal static void ThrowArgumentNullException(ExceptionArgument argument) { throw new ArgumentNullException(GetArgumentName(argument)); } internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument) { throw new ArgumentOutOfRangeException(GetArgumentName(argument)); } internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) { if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { // Dev11 474369 quirk: Mango had an empty message string: throw new ArgumentOutOfRangeException(GetArgumentName(argument), String.Empty); } else { throw new ArgumentOutOfRangeException(GetArgumentName(argument), Environment.GetResourceString(GetResourceName(resource))); } } internal static void ThrowInvalidOperationException(ExceptionResource resource) { throw new InvalidOperationException(Environment.GetResourceString(GetResourceName(resource))); } internal static void ThrowSerializationException(ExceptionResource resource) { throw new SerializationException(Environment.GetResourceString(GetResourceName(resource))); } internal static void ThrowSecurityException(ExceptionResource resource) { throw new System.Security.SecurityException(Environment.GetResourceString(GetResourceName(resource))); } internal static void ThrowNotSupportedException(ExceptionResource resource) { throw new NotSupportedException(Environment.GetResourceString(GetResourceName(resource))); } internal static void ThrowUnauthorizedAccessException(ExceptionResource resource) { throw new UnauthorizedAccessException(Environment.GetResourceString(GetResourceName(resource))); } internal static void ThrowObjectDisposedException(string objectName, ExceptionResource resource) { throw new ObjectDisposedException(objectName, Environment.GetResourceString(GetResourceName(resource))); } // Allow nulls for reference types and Nullable<U>, but not for value types. internal static void IfNullAndNullsAreIllegalThenThrow<T>(object value, ExceptionArgument argName) { // Note that default(T) is not equal to null for value types except when T is Nullable<U>. if (value == null && !(default(T) == null)) ThrowHelper.ThrowArgumentNullException(argName); } // // This function will convert an ExceptionArgument enum value to the argument name string. // internal static string GetArgumentName(ExceptionArgument argument) { string argumentName = null; switch (argument) { case ExceptionArgument.action: argumentName = "action"; break; case ExceptionArgument.array: argumentName = "array"; break; case ExceptionArgument.arrayIndex: argumentName = "arrayIndex"; break; case ExceptionArgument.capacity: argumentName = "capacity"; break; case ExceptionArgument.collection: argumentName = "collection"; break; case ExceptionArgument.comparison: argumentName = "comparison"; break; case ExceptionArgument.list: argumentName = "list"; break; case ExceptionArgument.converter: argumentName = "converter"; break; case ExceptionArgument.count: argumentName = "count"; break; case ExceptionArgument.dictionary: argumentName = "dictionary"; break; case ExceptionArgument.dictionaryCreationThreshold: argumentName = "dictionaryCreationThreshold"; break; case ExceptionArgument.index: argumentName = "index"; break; case ExceptionArgument.info: argumentName = "info"; break; case ExceptionArgument.key: argumentName = "key"; break; case ExceptionArgument.match: argumentName = "match"; break; case ExceptionArgument.obj: argumentName = "obj"; break; case ExceptionArgument.queue: argumentName = "queue"; break; case ExceptionArgument.stack: argumentName = "stack"; break; case ExceptionArgument.startIndex: argumentName = "startIndex"; break; case ExceptionArgument.value: argumentName = "value"; break; case ExceptionArgument.name: argumentName = "name"; break; case ExceptionArgument.mode: argumentName = "mode"; break; case ExceptionArgument.item: argumentName = "item"; break; case ExceptionArgument.options: argumentName = "options"; break; case ExceptionArgument.view: argumentName = "view"; break; case ExceptionArgument.sourceBytesToCopy: argumentName = "sourceBytesToCopy"; break; default: Contract.Assert(false, "The enum value is not defined, please checked ExceptionArgumentName Enum."); return string.Empty; } return argumentName; } // // This function will convert an ExceptionResource enum value to the resource string. // internal static string GetResourceName(ExceptionResource resource) { string resourceName = null; switch (resource) { case ExceptionResource.Argument_ImplementIComparable: resourceName = "Argument_ImplementIComparable"; break; case ExceptionResource.Argument_AddingDuplicate: resourceName = "Argument_AddingDuplicate"; break; case ExceptionResource.ArgumentOutOfRange_BiggerThanCollection: resourceName = "ArgumentOutOfRange_BiggerThanCollection"; break; case ExceptionResource.ArgumentOutOfRange_Count: resourceName = "ArgumentOutOfRange_Count"; break; case ExceptionResource.ArgumentOutOfRange_Index: resourceName = "ArgumentOutOfRange_Index"; break; case ExceptionResource.ArgumentOutOfRange_InvalidThreshold: resourceName = "ArgumentOutOfRange_InvalidThreshold"; break; case ExceptionResource.ArgumentOutOfRange_ListInsert: resourceName = "ArgumentOutOfRange_ListInsert"; break; case ExceptionResource.ArgumentOutOfRange_NeedNonNegNum: resourceName = "ArgumentOutOfRange_NeedNonNegNum"; break; case ExceptionResource.ArgumentOutOfRange_SmallCapacity: resourceName = "ArgumentOutOfRange_SmallCapacity"; break; case ExceptionResource.Arg_ArrayPlusOffTooSmall: resourceName = "Arg_ArrayPlusOffTooSmall"; break; case ExceptionResource.Arg_RankMultiDimNotSupported: resourceName = "Arg_RankMultiDimNotSupported"; break; case ExceptionResource.Arg_NonZeroLowerBound: resourceName = "Arg_NonZeroLowerBound"; break; case ExceptionResource.Argument_InvalidArrayType: resourceName = "Argument_InvalidArrayType"; break; case ExceptionResource.Argument_InvalidOffLen: resourceName = "Argument_InvalidOffLen"; break; case ExceptionResource.Argument_ItemNotExist: resourceName = "Argument_ItemNotExist"; break; case ExceptionResource.InvalidOperation_CannotRemoveFromStackOrQueue: resourceName = "InvalidOperation_CannotRemoveFromStackOrQueue"; break; case ExceptionResource.InvalidOperation_EmptyQueue: resourceName = "InvalidOperation_EmptyQueue"; break; case ExceptionResource.InvalidOperation_EnumOpCantHappen: resourceName = "InvalidOperation_EnumOpCantHappen"; break; case ExceptionResource.InvalidOperation_EnumFailedVersion: resourceName = "InvalidOperation_EnumFailedVersion"; break; case ExceptionResource.InvalidOperation_EmptyStack: resourceName = "InvalidOperation_EmptyStack"; break; case ExceptionResource.InvalidOperation_EnumNotStarted: resourceName = "InvalidOperation_EnumNotStarted"; break; case ExceptionResource.InvalidOperation_EnumEnded: resourceName = "InvalidOperation_EnumEnded"; break; case ExceptionResource.NotSupported_KeyCollectionSet: resourceName = "NotSupported_KeyCollectionSet"; break; case ExceptionResource.NotSupported_ReadOnlyCollection: resourceName = "NotSupported_ReadOnlyCollection"; break; case ExceptionResource.NotSupported_ValueCollectionSet: resourceName = "NotSupported_ValueCollectionSet"; break; case ExceptionResource.NotSupported_SortedListNestedWrite: resourceName = "NotSupported_SortedListNestedWrite"; break; case ExceptionResource.Serialization_InvalidOnDeser: resourceName = "Serialization_InvalidOnDeser"; break; case ExceptionResource.Serialization_MissingKeys: resourceName = "Serialization_MissingKeys"; break; case ExceptionResource.Serialization_NullKey: resourceName = "Serialization_NullKey"; break; case ExceptionResource.Argument_InvalidType: resourceName = "Argument_InvalidType"; break; case ExceptionResource.Argument_InvalidArgumentForComparison: resourceName = "Argument_InvalidArgumentForComparison"; break; case ExceptionResource.InvalidOperation_NoValue: resourceName = "InvalidOperation_NoValue"; break; case ExceptionResource.InvalidOperation_RegRemoveSubKey: resourceName = "InvalidOperation_RegRemoveSubKey"; break; case ExceptionResource.Arg_RegSubKeyAbsent: resourceName = "Arg_RegSubKeyAbsent"; break; case ExceptionResource.Arg_RegSubKeyValueAbsent: resourceName = "Arg_RegSubKeyValueAbsent"; break; case ExceptionResource.Arg_RegKeyDelHive: resourceName = "Arg_RegKeyDelHive"; break; case ExceptionResource.Security_RegistryPermission: resourceName = "Security_RegistryPermission"; break; case ExceptionResource.Arg_RegSetStrArrNull: resourceName = "Arg_RegSetStrArrNull"; break; case ExceptionResource.Arg_RegSetMismatchedKind: resourceName = "Arg_RegSetMismatchedKind"; break; case ExceptionResource.UnauthorizedAccess_RegistryNoWrite: resourceName = "UnauthorizedAccess_RegistryNoWrite"; break; case ExceptionResource.ObjectDisposed_RegKeyClosed: resourceName = "ObjectDisposed_RegKeyClosed"; break; case ExceptionResource.Arg_RegKeyStrLenBug: resourceName = "Arg_RegKeyStrLenBug"; break; case ExceptionResource.Argument_InvalidRegistryKeyPermissionCheck: resourceName = "Argument_InvalidRegistryKeyPermissionCheck"; break; case ExceptionResource.NotSupported_InComparableType: resourceName = "NotSupported_InComparableType"; break; case ExceptionResource.Argument_InvalidRegistryOptionsCheck: resourceName = "Argument_InvalidRegistryOptionsCheck"; break; case ExceptionResource.Argument_InvalidRegistryViewCheck: resourceName = "Argument_InvalidRegistryViewCheck"; break; default: Contract.Assert( false, "The enum value is not defined, please checked ExceptionArgumentName Enum."); return string.Empty; } return resourceName; } } // // The convention for this enum is using the argument name as the enum name // internal enum ExceptionArgument { obj, dictionary, dictionaryCreationThreshold, array, info, key, collection, list, match, converter, queue, stack, capacity, index, startIndex, value, count, arrayIndex, name, mode, item, options, view, sourceBytesToCopy, action, comparison } // // The convention for this enum is using the resource name as the enum name // internal enum ExceptionResource { Argument_ImplementIComparable, Argument_InvalidType, Argument_InvalidArgumentForComparison, Argument_InvalidRegistryKeyPermissionCheck, ArgumentOutOfRange_NeedNonNegNum, Arg_ArrayPlusOffTooSmall, Arg_NonZeroLowerBound, Arg_RankMultiDimNotSupported, Arg_RegKeyDelHive, Arg_RegKeyStrLenBug, Arg_RegSetStrArrNull, Arg_RegSetMismatchedKind, Arg_RegSubKeyAbsent, Arg_RegSubKeyValueAbsent, Argument_AddingDuplicate, Serialization_InvalidOnDeser, Serialization_MissingKeys, Serialization_NullKey, Argument_InvalidArrayType, NotSupported_KeyCollectionSet, NotSupported_ValueCollectionSet, ArgumentOutOfRange_SmallCapacity, ArgumentOutOfRange_Index, Argument_InvalidOffLen, Argument_ItemNotExist, ArgumentOutOfRange_Count, ArgumentOutOfRange_InvalidThreshold, ArgumentOutOfRange_ListInsert, NotSupported_ReadOnlyCollection, InvalidOperation_CannotRemoveFromStackOrQueue, InvalidOperation_EmptyQueue, InvalidOperation_EnumOpCantHappen, InvalidOperation_EnumFailedVersion, InvalidOperation_EmptyStack, ArgumentOutOfRange_BiggerThanCollection, InvalidOperation_EnumNotStarted, InvalidOperation_EnumEnded, NotSupported_SortedListNestedWrite, InvalidOperation_NoValue, InvalidOperation_RegRemoveSubKey, Security_RegistryPermission, UnauthorizedAccess_RegistryNoWrite, ObjectDisposed_RegKeyClosed, NotSupported_InComparableType, Argument_InvalidRegistryOptionsCheck, Argument_InvalidRegistryViewCheck } }
// 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 Microsoft.Build.Framework; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Microsoft.DotNet.Build.Tasks { public class ConfigurationFactory { internal const char PropertySeperator = '-'; private Dictionary<string, PropertyInfo> Properties { get; } private PropertyInfo[] PropertiesByOrder { get; } private PropertyInfo[] PropertiesByPrecedence { get; } private Dictionary<PropertyInfo, PropertyValue[]> PropertyValues { get; } private Dictionary<string, PropertyValue> AllPropertyValues { get; } public Configuration IdentityConfiguration { get; } public ConfigurationFactory(ITaskItem[] properties, ITaskItem[] propertyValues) { Properties = properties.Select(p => new PropertyInfo(p)) .ToDictionary(p => p.Name, p => p); PropertiesByOrder = Properties.Values.OrderBy(p => p.Order).ToArray(); PropertiesByPrecedence = Properties.Values.OrderBy(p => p.Precedence).ToArray(); var propertyValueGrouping = propertyValues.Select(v => new PropertyValue(v, Properties)).GroupBy(p => p.Value); var duplicateValueGrouping = propertyValueGrouping.Where(g => g.Count() > 1); if (duplicateValueGrouping.Any()) { var duplicatesMessage = String.Join("; ", duplicateValueGrouping.Select(g => $"Value: {g.Key} Properties: {String.Join(", ", g.Select(p => p.Property.Name))}")); throw new ArgumentException($"Duplicate values are not permitted. {duplicatesMessage}"); } AllPropertyValues = propertyValueGrouping .ToDictionary(g => g.Key, g => g.Single()); PropertyValues = AllPropertyValues.Values .GroupBy(v => v.Property) .ToDictionary(g => g.Key, g => g.ToArray()); // connect the graph foreach (var propertyValue in AllPropertyValues.Values) { propertyValue.ConnectValues(AllPropertyValues); } // connect property to value foreach (var property in Properties.Values) { property.ConnectDefault(AllPropertyValues); } IdentityConfiguration = new Configuration(PropertiesByOrder.Select(p => p.IdentityValue).ToArray()); } public IEnumerable<PropertyInfo> GetProperties() { return PropertiesByOrder; } /// <summary> /// Get known values for a property /// </summary> /// <param name="property">name of property to retrieve values</param> /// <returns></returns> public IEnumerable<PropertyValue> GetValues(string property) { PropertyInfo propertyInfo; if (!Properties.TryGetValue(property, out propertyInfo)) { throw new ArgumentException($"Unknown property name {property}"); } return GetValues(propertyInfo); } /// <summary> /// Get known values for a property /// </summary> /// <param name="property">property to retrieve values</param> /// <returns></returns> public IEnumerable<PropertyValue> GetValues(PropertyInfo property) { PropertyValue[] values; if (!PropertyValues.TryGetValue(property, out values)) { throw new ArgumentException($"Unknown property {property}."); } return values; } /// <summary> /// Calculates all value combinations for properties. /// </summary> /// <param name="properties">List of properties, ordered by precedence</param> /// <param name="selectValues">Value selector that returns values for each property, ordered by precedence</param> /// <returns>All combinations of values</returns> public IEnumerable<Configuration> GetConfigurations(Func<PropertyInfo, IEnumerable<PropertyValue>> selectValues) { // get all property values, ordered by precedence var values = PropertiesByPrecedence.Select(selectValues); // start with an empty enumerable IEnumerable<IEnumerable<PropertyValue>> emptySet = new[] { Enumerable.Empty<PropertyValue>() }; // accumulate the cross-product var allValues = values.Aggregate( emptySet, (valueSets, propertyValues) => valueSets.SelectMany(valueSet => propertyValues.Select(propertyValue => valueSet.Concat(new[] { propertyValue }) ))); // convert into configuration return allValues.Select( valueSet => new Configuration( valueSet.OrderBy(v => v.Property.Order).ToArray())); } /// <summary> /// Gets all possible value combinations in order of precedence /// </summary> /// <returns></returns> public IEnumerable<Configuration> GetAllConfigurations() { return GetConfigurations(p => GetValues(p)); } /// <summary> /// Gets all significant combinations in order of precedence /// </summary> /// <returns></returns> public IEnumerable<Configuration> GetSignficantConfigurations() { return GetConfigurations(p => p.Insignificant ? new[] { p.IdentityValue } : GetValues(p)); } /// <summary> /// Gets value combinations compatible with the specify value combination in order of precedence /// </summary> /// <param name="valueSet"></param> /// <returns></returns> public IEnumerable<Configuration> GetCompatibleConfigurations(Configuration configuration, bool doNotAllowCompatibleValues = false) { var propTable = configuration.Values.ToDictionary(v => v.Property, v => v); return GetConfigurations(p => propTable[p].GetCompatibleValues(doNotAllowCompatibleValues)); } /// <summary> /// Parses a configuration string to return a Configuration. /// </summary> /// <param name="configurationString"></param> /// <returns></returns> internal Configuration ParseConfiguration(string configurationString, bool permitUnknownValues = false) { var values = configurationString.Split(PropertySeperator); var valueSet = new PropertyValue[PropertiesByOrder.Length]; for(int propertyIndex = 0, valueIndex = 0; propertyIndex < PropertiesByOrder.Length; propertyIndex++, valueIndex++) { var value = valueIndex < values.Length ? values[valueIndex] : null; var property = PropertiesByOrder[propertyIndex]; if (String.IsNullOrEmpty(value)) { if (property.DefaultValue != null) { valueSet[propertyIndex] = property.DefaultValue; continue; } else { throw new ArgumentException($"No value was provided for property '{property.Name}' and no default value exists"); } } PropertyValue propertyValue; if (!AllPropertyValues.TryGetValue(value, out propertyValue)) { if (permitUnknownValues) { valueSet[propertyIndex] = new PropertyValue(value, property); continue; } else { throw new ArgumentException($"Unknown value '{value}' found in configuration '{configurationString}'. Expected property '{property.Name}' with one of values {String.Join(", ", PropertyValues[property].Select(v => v.Value))}."); } } if (propertyValue.Property != property) { // we have a known value but it is not for the expected property. // so long as we have properties with defaultValues, set them while(propertyValue.Property != property) { if (property.DefaultValue == null) { // we can't use this property at this index throw new ArgumentException($"Property '{propertyValue.Property.Name}' value '{propertyValue.Value}' occurred at unexpected position in configuration '{configurationString}'"); } // give this property its default value and advance to the next property valueSet[propertyIndex++] = property.DefaultValue; if (propertyIndex > PropertiesByOrder.Length) { // we ran out of possible properties. throw new ArgumentException($"Property '{propertyValue.Property.Name}' value '{propertyValue.Value}' occurred at unexpected position in configuration '{configurationString}'"); } property = PropertiesByOrder[propertyIndex]; } } // we found the position for this value. Debug.Assert(propertyValue.Property == property); valueSet[propertyIndex] = propertyValue; } return new Configuration(valueSet); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/runtimeconfig/v1beta1/resources.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Cloud.Runtimeconfig.V1Beta1 { /// <summary>Holder for reflection information generated from google/cloud/runtimeconfig/v1beta1/resources.proto</summary> public static partial class ResourcesReflection { #region Descriptor /// <summary>File descriptor for google/cloud/runtimeconfig/v1beta1/resources.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ResourcesReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjJnb29nbGUvY2xvdWQvcnVudGltZWNvbmZpZy92MWJldGExL3Jlc291cmNl", "cy5wcm90bxIiZ29vZ2xlLmNsb3VkLnJ1bnRpbWVjb25maWcudjFiZXRhMRoc", "Z29vZ2xlL2FwaS9hbm5vdGF0aW9ucy5wcm90bxoeZ29vZ2xlL3Byb3RvYnVm", "L2R1cmF0aW9uLnByb3RvGh9nb29nbGUvcHJvdG9idWYvdGltZXN0YW1wLnBy", "b3RvGhdnb29nbGUvcnBjL3N0YXR1cy5wcm90byIyCg1SdW50aW1lQ29uZmln", "EgwKBG5hbWUYASABKAkSEwoLZGVzY3JpcHRpb24YAiABKAkiuAEKCFZhcmlh", "YmxlEgwKBG5hbWUYASABKAkSDwoFdmFsdWUYAiABKAxIABIOCgR0ZXh0GAUg", "ASgJSAASLwoLdXBkYXRlX3RpbWUYAyABKAsyGi5nb29nbGUucHJvdG9idWYu", "VGltZXN0YW1wEkAKBXN0YXRlGAQgASgOMjEuZ29vZ2xlLmNsb3VkLnJ1bnRp", "bWVjb25maWcudjFiZXRhMS5WYXJpYWJsZVN0YXRlQgoKCGNvbnRlbnRzIp0B", "CgxFbmRDb25kaXRpb24SUwoLY2FyZGluYWxpdHkYASABKAsyPC5nb29nbGUu", "Y2xvdWQucnVudGltZWNvbmZpZy52MWJldGExLkVuZENvbmRpdGlvbi5DYXJk", "aW5hbGl0eUgAGisKC0NhcmRpbmFsaXR5EgwKBHBhdGgYASABKAkSDgoGbnVt", "YmVyGAIgASgFQgsKCWNvbmRpdGlvbiKqAgoGV2FpdGVyEgwKBG5hbWUYASAB", "KAkSKgoHdGltZW91dBgCIAEoCzIZLmdvb2dsZS5wcm90b2J1Zi5EdXJhdGlv", "bhJBCgdmYWlsdXJlGAMgASgLMjAuZ29vZ2xlLmNsb3VkLnJ1bnRpbWVjb25m", "aWcudjFiZXRhMS5FbmRDb25kaXRpb24SQQoHc3VjY2VzcxgEIAEoCzIwLmdv", "b2dsZS5jbG91ZC5ydW50aW1lY29uZmlnLnYxYmV0YTEuRW5kQ29uZGl0aW9u", "Ei8KC2NyZWF0ZV90aW1lGAUgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVz", "dGFtcBIMCgRkb25lGAYgASgIEiEKBWVycm9yGAcgASgLMhIuZ29vZ2xlLnJw", "Yy5TdGF0dXMqSQoNVmFyaWFibGVTdGF0ZRIeChpWQVJJQUJMRV9TVEFURV9V", "TlNQRUNJRklFRBAAEgsKB1VQREFURUQQARILCgdERUxFVEVEEAJCewomY29t", "Lmdvb2dsZS5jbG91ZC5ydW50aW1lY29uZmlnLnYxYmV0YTFQAVpPZ29vZ2xl", "LmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9jbG91ZC9ydW50aW1l", "Y29uZmlnL3YxYmV0YTE7cnVudGltZWNvbmZpZ2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.DurationReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, global::Google.Rpc.StatusReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Google.Cloud.Runtimeconfig.V1Beta1.VariableState), }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Runtimeconfig.V1Beta1.RuntimeConfig), global::Google.Cloud.Runtimeconfig.V1Beta1.RuntimeConfig.Parser, new[]{ "Name", "Description" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Runtimeconfig.V1Beta1.Variable), global::Google.Cloud.Runtimeconfig.V1Beta1.Variable.Parser, new[]{ "Name", "Value", "Text", "UpdateTime", "State" }, new[]{ "Contents" }, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Runtimeconfig.V1Beta1.EndCondition), global::Google.Cloud.Runtimeconfig.V1Beta1.EndCondition.Parser, new[]{ "Cardinality" }, new[]{ "Condition" }, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Runtimeconfig.V1Beta1.EndCondition.Types.Cardinality), global::Google.Cloud.Runtimeconfig.V1Beta1.EndCondition.Types.Cardinality.Parser, new[]{ "Path", "Number" }, null, null, null)}), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Runtimeconfig.V1Beta1.Waiter), global::Google.Cloud.Runtimeconfig.V1Beta1.Waiter.Parser, new[]{ "Name", "Timeout", "Failure", "Success", "CreateTime", "Done", "Error" }, null, null, null) })); } #endregion } #region Enums /// <summary> /// The `VariableState` describes the last known state of the variable and is /// used during a `variables().watch` call to distinguish the state of the /// variable. /// </summary> public enum VariableState { /// <summary> /// Default variable state. /// </summary> [pbr::OriginalName("VARIABLE_STATE_UNSPECIFIED")] Unspecified = 0, /// <summary> /// The variable was updated, while `variables().watch` was executing. /// </summary> [pbr::OriginalName("UPDATED")] Updated = 1, /// <summary> /// The variable was deleted, while `variables().watch` was executing. /// </summary> [pbr::OriginalName("DELETED")] Deleted = 2, } #endregion #region Messages /// <summary> /// A RuntimeConfig resource is the primary resource in the Cloud RuntimeConfig /// service. A RuntimeConfig resource consists of metadata and a hierarchy of /// variables. /// </summary> public sealed partial class RuntimeConfig : pb::IMessage<RuntimeConfig> { private static readonly pb::MessageParser<RuntimeConfig> _parser = new pb::MessageParser<RuntimeConfig>(() => new RuntimeConfig()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<RuntimeConfig> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Runtimeconfig.V1Beta1.ResourcesReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RuntimeConfig() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RuntimeConfig(RuntimeConfig other) : this() { name_ = other.name_; description_ = other.description_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RuntimeConfig Clone() { return new RuntimeConfig(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// The resource name of a runtime config. The name must have the format: /// /// projects/[PROJECT_ID]/configs/[CONFIG_NAME] /// /// The `[PROJECT_ID]` must be a valid project ID, and `[CONFIG_NAME]` is an /// arbitrary name that matches RFC 1035 segment specification. The length of /// `[CONFIG_NAME]` must be less than 64 bytes. /// /// You pick the RuntimeConfig resource name, but the server will validate that /// the name adheres to this format. After you create the resource, you cannot /// change the resource's name. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "description" field.</summary> public const int DescriptionFieldNumber = 2; private string description_ = ""; /// <summary> /// An optional description of the RuntimeConfig object. /// The length of the description must be less than 256 bytes. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Description { get { return description_; } set { description_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as RuntimeConfig); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(RuntimeConfig other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (Description != other.Description) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (Description.Length != 0) hash ^= Description.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (Description.Length != 0) { output.WriteRawTag(18); output.WriteString(Description); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Description.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Description); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(RuntimeConfig other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.Description.Length != 0) { Description = other.Description; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { Description = input.ReadString(); break; } } } } } /// <summary> /// Describes a single variable within a RuntimeConfig resource. /// The name denotes the hierarchical variable name. For example, /// `ports/serving_port` is a valid variable name. The variable value is an /// opaque string and only leaf variables can have values (that is, variables /// that do not have any child variables). /// </summary> public sealed partial class Variable : pb::IMessage<Variable> { private static readonly pb::MessageParser<Variable> _parser = new pb::MessageParser<Variable>(() => new Variable()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Variable> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Runtimeconfig.V1Beta1.ResourcesReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Variable() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Variable(Variable other) : this() { name_ = other.name_; UpdateTime = other.updateTime_ != null ? other.UpdateTime.Clone() : null; state_ = other.state_; switch (other.ContentsCase) { case ContentsOneofCase.Value: Value = other.Value; break; case ContentsOneofCase.Text: Text = other.Text; break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Variable Clone() { return new Variable(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// The name of the variable resource, in the format: /// /// projects/[PROJECT_ID]/configs/[CONFIG_NAME]/variables/[VARIABLE_NAME] /// /// The `[PROJECT_ID]` must be a valid project ID, `[CONFIG_NAME]` must be a /// valid RuntimeConfig reource and `[VARIABLE_NAME]` follows Unix file system /// file path naming. /// /// The `[VARIABLE_NAME]` can contain ASCII letters, numbers, slashes and /// dashes. Slashes are used as path element separators and are not part of the /// `[VARIABLE_NAME]` itself, so `[VARIABLE_NAME]` must contain at least one /// non-slash character. Multiple slashes are coalesced into single slash /// character. Each path segment should follow RFC 1035 segment specification. /// The length of a `[VARIABLE_NAME]` must be less than 256 bytes. /// /// Once you create a variable, you cannot change the variable name. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "value" field.</summary> public const int ValueFieldNumber = 2; /// <summary> /// The binary value of the variable. The length of the value must be less /// than 4096 bytes. Empty values are also accepted. The value must be /// Base64 encoded. /// NB: Only one of value and string_value can be set at the same time. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pb::ByteString Value { get { return contentsCase_ == ContentsOneofCase.Value ? (pb::ByteString) contents_ : pb::ByteString.Empty; } set { contents_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); contentsCase_ = ContentsOneofCase.Value; } } /// <summary>Field number for the "text" field.</summary> public const int TextFieldNumber = 5; /// <summary> /// The textual value of the variable. The length of the value must be less /// than 4096 bytes. Empty values are also accepted. /// NB: Only one of value and string_value can be set at the same time. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Text { get { return contentsCase_ == ContentsOneofCase.Text ? (string) contents_ : ""; } set { contents_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); contentsCase_ = ContentsOneofCase.Text; } } /// <summary>Field number for the "update_time" field.</summary> public const int UpdateTimeFieldNumber = 3; private global::Google.Protobuf.WellKnownTypes.Timestamp updateTime_; /// <summary> /// [Output Only] The time of the last variable update. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Timestamp UpdateTime { get { return updateTime_; } set { updateTime_ = value; } } /// <summary>Field number for the "state" field.</summary> public const int StateFieldNumber = 4; private global::Google.Cloud.Runtimeconfig.V1Beta1.VariableState state_ = 0; /// <summary> /// [Ouput only] The current state of the variable. The variable state indicates /// the outcome of the `variables().watch` call and is visible through the /// `get` and `list` calls. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Runtimeconfig.V1Beta1.VariableState State { get { return state_; } set { state_ = value; } } private object contents_; /// <summary>Enum of possible cases for the "contents" oneof.</summary> public enum ContentsOneofCase { None = 0, Value = 2, Text = 5, } private ContentsOneofCase contentsCase_ = ContentsOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ContentsOneofCase ContentsCase { get { return contentsCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void ClearContents() { contentsCase_ = ContentsOneofCase.None; contents_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Variable); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Variable other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (Value != other.Value) return false; if (Text != other.Text) return false; if (!object.Equals(UpdateTime, other.UpdateTime)) return false; if (State != other.State) return false; if (ContentsCase != other.ContentsCase) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (contentsCase_ == ContentsOneofCase.Value) hash ^= Value.GetHashCode(); if (contentsCase_ == ContentsOneofCase.Text) hash ^= Text.GetHashCode(); if (updateTime_ != null) hash ^= UpdateTime.GetHashCode(); if (State != 0) hash ^= State.GetHashCode(); hash ^= (int) contentsCase_; return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (contentsCase_ == ContentsOneofCase.Value) { output.WriteRawTag(18); output.WriteBytes(Value); } if (updateTime_ != null) { output.WriteRawTag(26); output.WriteMessage(UpdateTime); } if (State != 0) { output.WriteRawTag(32); output.WriteEnum((int) State); } if (contentsCase_ == ContentsOneofCase.Text) { output.WriteRawTag(42); output.WriteString(Text); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (contentsCase_ == ContentsOneofCase.Value) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(Value); } if (contentsCase_ == ContentsOneofCase.Text) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Text); } if (updateTime_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(UpdateTime); } if (State != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) State); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Variable other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.updateTime_ != null) { if (updateTime_ == null) { updateTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } UpdateTime.MergeFrom(other.UpdateTime); } if (other.State != 0) { State = other.State; } switch (other.ContentsCase) { case ContentsOneofCase.Value: Value = other.Value; break; case ContentsOneofCase.Text: Text = other.Text; break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { Value = input.ReadBytes(); break; } case 26: { if (updateTime_ == null) { updateTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(updateTime_); break; } case 32: { state_ = (global::Google.Cloud.Runtimeconfig.V1Beta1.VariableState) input.ReadEnum(); break; } case 42: { Text = input.ReadString(); break; } } } } } /// <summary> /// The condition that a Waiter resource is waiting for. /// </summary> public sealed partial class EndCondition : pb::IMessage<EndCondition> { private static readonly pb::MessageParser<EndCondition> _parser = new pb::MessageParser<EndCondition>(() => new EndCondition()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<EndCondition> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Runtimeconfig.V1Beta1.ResourcesReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EndCondition() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EndCondition(EndCondition other) : this() { switch (other.ConditionCase) { case ConditionOneofCase.Cardinality: Cardinality = other.Cardinality.Clone(); break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EndCondition Clone() { return new EndCondition(this); } /// <summary>Field number for the "cardinality" field.</summary> public const int CardinalityFieldNumber = 1; /// <summary> /// The cardinality of the `EndCondition`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Runtimeconfig.V1Beta1.EndCondition.Types.Cardinality Cardinality { get { return conditionCase_ == ConditionOneofCase.Cardinality ? (global::Google.Cloud.Runtimeconfig.V1Beta1.EndCondition.Types.Cardinality) condition_ : null; } set { condition_ = value; conditionCase_ = value == null ? ConditionOneofCase.None : ConditionOneofCase.Cardinality; } } private object condition_; /// <summary>Enum of possible cases for the "condition" oneof.</summary> public enum ConditionOneofCase { None = 0, Cardinality = 1, } private ConditionOneofCase conditionCase_ = ConditionOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConditionOneofCase ConditionCase { get { return conditionCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void ClearCondition() { conditionCase_ = ConditionOneofCase.None; condition_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as EndCondition); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(EndCondition other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Cardinality, other.Cardinality)) return false; if (ConditionCase != other.ConditionCase) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (conditionCase_ == ConditionOneofCase.Cardinality) hash ^= Cardinality.GetHashCode(); hash ^= (int) conditionCase_; return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (conditionCase_ == ConditionOneofCase.Cardinality) { output.WriteRawTag(10); output.WriteMessage(Cardinality); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (conditionCase_ == ConditionOneofCase.Cardinality) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Cardinality); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(EndCondition other) { if (other == null) { return; } switch (other.ConditionCase) { case ConditionOneofCase.Cardinality: Cardinality = other.Cardinality; break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { global::Google.Cloud.Runtimeconfig.V1Beta1.EndCondition.Types.Cardinality subBuilder = new global::Google.Cloud.Runtimeconfig.V1Beta1.EndCondition.Types.Cardinality(); if (conditionCase_ == ConditionOneofCase.Cardinality) { subBuilder.MergeFrom(Cardinality); } input.ReadMessage(subBuilder); Cardinality = subBuilder; break; } } } } #region Nested types /// <summary>Container for nested types declared in the EndCondition message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// A Cardinality condition for the Waiter resource. A cardinality condition is /// met when the number of variables under a specified path prefix reaches a /// predefined number. For example, if you set a Cardinality condition where /// the `path` is set to `/foo` and the number of paths is set to 2, the /// following variables would meet the condition in a RuntimeConfig resource: /// /// + `/foo/variable1 = "value1"` /// + `/foo/variable2 = "value2"` /// + `/bar/variable3 = "value3"` /// /// It would not would not satisify the same condition with the `number` set to /// 3, however, because there is only 2 paths that start with `/foo`. /// Cardinality conditions are recursive; all subtrees under the specific /// path prefix are counted. /// </summary> public sealed partial class Cardinality : pb::IMessage<Cardinality> { private static readonly pb::MessageParser<Cardinality> _parser = new pb::MessageParser<Cardinality>(() => new Cardinality()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Cardinality> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Runtimeconfig.V1Beta1.EndCondition.Descriptor.NestedTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Cardinality() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Cardinality(Cardinality other) : this() { path_ = other.path_; number_ = other.number_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Cardinality Clone() { return new Cardinality(this); } /// <summary>Field number for the "path" field.</summary> public const int PathFieldNumber = 1; private string path_ = ""; /// <summary> /// The root of the variable subtree to monitor. For example, `/foo`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Path { get { return path_; } set { path_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "number" field.</summary> public const int NumberFieldNumber = 2; private int number_; /// <summary> /// The number variables under the `path` that must exist to meet this /// condition. Defaults to 1 if not specified. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Number { get { return number_; } set { number_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Cardinality); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Cardinality other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Path != other.Path) return false; if (Number != other.Number) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Path.Length != 0) hash ^= Path.GetHashCode(); if (Number != 0) hash ^= Number.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Path.Length != 0) { output.WriteRawTag(10); output.WriteString(Path); } if (Number != 0) { output.WriteRawTag(16); output.WriteInt32(Number); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Path.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Path); } if (Number != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Number); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Cardinality other) { if (other == null) { return; } if (other.Path.Length != 0) { Path = other.Path; } if (other.Number != 0) { Number = other.Number; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Path = input.ReadString(); break; } case 16: { Number = input.ReadInt32(); break; } } } } } } #endregion } /// <summary> /// A Waiter resource waits for some end condition within a RuntimeConfig resource /// to be met before it returns. For example, assume you have a distributed /// system where each node writes to a Variable resource indidicating the node's /// readiness as part of the startup process. /// /// You then configure a Waiter resource with the success condition set to wait /// until some number of nodes have checked in. Afterwards, your application /// runs some arbitrary code after the condition has been met and the waiter /// returns successfully. /// /// Once created, a Waiter resource is immutable. /// /// To learn more about using waiters, read the /// [Creating a Waiter](/deployment-manager/runtime-configurator/creating-a-waiter) /// documentation. /// </summary> public sealed partial class Waiter : pb::IMessage<Waiter> { private static readonly pb::MessageParser<Waiter> _parser = new pb::MessageParser<Waiter>(() => new Waiter()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Waiter> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Runtimeconfig.V1Beta1.ResourcesReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Waiter() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Waiter(Waiter other) : this() { name_ = other.name_; Timeout = other.timeout_ != null ? other.Timeout.Clone() : null; Failure = other.failure_ != null ? other.Failure.Clone() : null; Success = other.success_ != null ? other.Success.Clone() : null; CreateTime = other.createTime_ != null ? other.CreateTime.Clone() : null; done_ = other.done_; Error = other.error_ != null ? other.Error.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Waiter Clone() { return new Waiter(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// The name of the Waiter resource, in the format: /// /// projects/[PROJECT_ID]/configs/[CONFIG_NAME]/waiters/[WAITER_NAME] /// /// The `[PROJECT_ID]` must be a valid Google Cloud project ID, /// the `[CONFIG_NAME]` must be a valid RuntimeConfig resource, the /// `[WAITER_NAME]` must match RFC 1035 segment specification, and the length /// of `[WAITER_NAME]` must be less than 64 bytes. /// /// After you create a Waiter resource, you cannot change the resource name. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "timeout" field.</summary> public const int TimeoutFieldNumber = 2; private global::Google.Protobuf.WellKnownTypes.Duration timeout_; /// <summary> /// [Required] Specifies the timeout of the waiter in seconds, beginning from /// the instant that `waiters().create` method is called. If this time elapses /// before the success or failure conditions are met, the waiter fails and sets /// the `error` code to `DEADLINE_EXCEEDED`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Duration Timeout { get { return timeout_; } set { timeout_ = value; } } /// <summary>Field number for the "failure" field.</summary> public const int FailureFieldNumber = 3; private global::Google.Cloud.Runtimeconfig.V1Beta1.EndCondition failure_; /// <summary> /// [Optional] The failure condition of this waiter. If this condition is met, /// `done` will be set to `true` and the `error` code will be set to `ABORTED`. /// The failure condition takes precedence over the success condition. If both /// conditions are met, a failure will be indicated. This value is optional; if /// no failure condition is set, the only failure scenario will be a timeout. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Runtimeconfig.V1Beta1.EndCondition Failure { get { return failure_; } set { failure_ = value; } } /// <summary>Field number for the "success" field.</summary> public const int SuccessFieldNumber = 4; private global::Google.Cloud.Runtimeconfig.V1Beta1.EndCondition success_; /// <summary> /// [Required] The success condition. If this condition is met, `done` will be /// set to `true` and the `error` value will remain unset. The failure condition /// takes precedence over the success condition. If both conditions are met, a /// failure will be indicated. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Runtimeconfig.V1Beta1.EndCondition Success { get { return success_; } set { success_ = value; } } /// <summary>Field number for the "create_time" field.</summary> public const int CreateTimeFieldNumber = 5; private global::Google.Protobuf.WellKnownTypes.Timestamp createTime_; /// <summary> /// [Output Only] The instant at which this Waiter resource was created. Adding /// the value of `timeout` to this instant yields the timeout deadline for the /// waiter. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Timestamp CreateTime { get { return createTime_; } set { createTime_ = value; } } /// <summary>Field number for the "done" field.</summary> public const int DoneFieldNumber = 6; private bool done_; /// <summary> /// [Output Only] If the value is `false`, it means the waiter is still waiting /// for one of its conditions to be met. /// /// If true, the waiter has finished. If the waiter finished due to a timeout /// or failure, `error` will be set. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Done { get { return done_; } set { done_ = value; } } /// <summary>Field number for the "error" field.</summary> public const int ErrorFieldNumber = 7; private global::Google.Rpc.Status error_; /// <summary> /// [Output Only] If the waiter ended due to a failure or timeout, this value /// will be set. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Rpc.Status Error { get { return error_; } set { error_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Waiter); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Waiter other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (!object.Equals(Timeout, other.Timeout)) return false; if (!object.Equals(Failure, other.Failure)) return false; if (!object.Equals(Success, other.Success)) return false; if (!object.Equals(CreateTime, other.CreateTime)) return false; if (Done != other.Done) return false; if (!object.Equals(Error, other.Error)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (timeout_ != null) hash ^= Timeout.GetHashCode(); if (failure_ != null) hash ^= Failure.GetHashCode(); if (success_ != null) hash ^= Success.GetHashCode(); if (createTime_ != null) hash ^= CreateTime.GetHashCode(); if (Done != false) hash ^= Done.GetHashCode(); if (error_ != null) hash ^= Error.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (timeout_ != null) { output.WriteRawTag(18); output.WriteMessage(Timeout); } if (failure_ != null) { output.WriteRawTag(26); output.WriteMessage(Failure); } if (success_ != null) { output.WriteRawTag(34); output.WriteMessage(Success); } if (createTime_ != null) { output.WriteRawTag(42); output.WriteMessage(CreateTime); } if (Done != false) { output.WriteRawTag(48); output.WriteBool(Done); } if (error_ != null) { output.WriteRawTag(58); output.WriteMessage(Error); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (timeout_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Timeout); } if (failure_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Failure); } if (success_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Success); } if (createTime_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(CreateTime); } if (Done != false) { size += 1 + 1; } if (error_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Error); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Waiter other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.timeout_ != null) { if (timeout_ == null) { timeout_ = new global::Google.Protobuf.WellKnownTypes.Duration(); } Timeout.MergeFrom(other.Timeout); } if (other.failure_ != null) { if (failure_ == null) { failure_ = new global::Google.Cloud.Runtimeconfig.V1Beta1.EndCondition(); } Failure.MergeFrom(other.Failure); } if (other.success_ != null) { if (success_ == null) { success_ = new global::Google.Cloud.Runtimeconfig.V1Beta1.EndCondition(); } Success.MergeFrom(other.Success); } if (other.createTime_ != null) { if (createTime_ == null) { createTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } CreateTime.MergeFrom(other.CreateTime); } if (other.Done != false) { Done = other.Done; } if (other.error_ != null) { if (error_ == null) { error_ = new global::Google.Rpc.Status(); } Error.MergeFrom(other.Error); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { if (timeout_ == null) { timeout_ = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(timeout_); break; } case 26: { if (failure_ == null) { failure_ = new global::Google.Cloud.Runtimeconfig.V1Beta1.EndCondition(); } input.ReadMessage(failure_); break; } case 34: { if (success_ == null) { success_ = new global::Google.Cloud.Runtimeconfig.V1Beta1.EndCondition(); } input.ReadMessage(success_); break; } case 42: { if (createTime_ == null) { createTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(createTime_); break; } case 48: { Done = input.ReadBool(); break; } case 58: { if (error_ == null) { error_ = new global::Google.Rpc.Status(); } input.ReadMessage(error_); break; } } } } } #endregion } #endregion Designer generated code
/* * TestXmlText.cs - Tests for the "System.Xml.TestXmlText" class. * * Copyright (C) 2002 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using CSUnit; using System; using System.Xml; #if !ECMA_COMPAT // Note: this class also tests the behaviour of "XmlCharacterData". public class TestXmlText : TestCase { // Internal state. private XmlDocument doc; private int changeBefore; private int changeAfter; private XmlNode expectedNode; private XmlNodeChangedEventHandler handleBefore; private XmlNodeChangedEventHandler handleAfter; // Constructor. public TestXmlText(String name) : base(name) { // Nothing to do here. } // Set up for the tests. protected override void Setup() { doc = new XmlDocument(); handleBefore = new XmlNodeChangedEventHandler(WatchBefore); handleAfter = new XmlNodeChangedEventHandler(WatchAfter); } // Clean up after the tests. protected override void Cleanup() { // Nothing to do here. } // Check the properties on a newly constructed text node. private void CheckProperties(String msg, XmlText text, String value, String xmlValue) { String temp; AssertEquals(msg + " [1]", "#text", text.LocalName); AssertEquals(msg + " [2]", "#text", text.Name); AssertEquals(msg + " [3]", String.Empty, text.Prefix); AssertEquals(msg + " [4]", String.Empty, text.NamespaceURI); AssertEquals(msg + " [5]", XmlNodeType.Text, text.NodeType); AssertEquals(msg + " [6]", value, text.Data); AssertEquals(msg + " [7]", value, text.Value); AssertEquals(msg + " [8]", value, text.InnerText); AssertEquals(msg + " [9]", value.Length, text.Length); AssertEquals(msg + " [10]", String.Empty, text.InnerXml); AssertEquals(msg + " [11]", xmlValue, text.OuterXml); } private void CheckProperties(String msg, XmlText text, String value) { CheckProperties(msg, text, value, value); } // Test the construction of text nodes. public void TestXmlTextConstruct() { CheckProperties("Construct (1)", doc.CreateTextNode(null), String.Empty); CheckProperties("Construct (2)", doc.CreateTextNode(String.Empty), String.Empty); CheckProperties("Construct (3)", doc.CreateTextNode("xyzzy"), "xyzzy"); CheckProperties("Construct (4)", doc.CreateTextNode("<&>\"'"), "<&>\"'", "&lt;&amp;&gt;\"'"); } // Watch for change events. private void WatchBefore(Object sender, XmlNodeChangedEventArgs args) { AssertEquals("Sender", expectedNode.OwnerDocument, sender); AssertEquals ("Action", XmlNodeChangedAction.Change, args.Action); AssertEquals("Node", expectedNode, args.Node); AssertEquals("OldParent", expectedNode.ParentNode, args.OldParent); AssertEquals("NewParent", expectedNode.ParentNode, args.NewParent); ++changeBefore; } private void WatchAfter(Object sender, XmlNodeChangedEventArgs args) { AssertEquals("Sender", expectedNode.OwnerDocument, sender); AssertEquals ("Action", XmlNodeChangedAction.Change, args.Action); AssertEquals("Node", expectedNode, args.Node); AssertEquals("OldParent", expectedNode.ParentNode, args.OldParent); AssertEquals("NewParent", expectedNode.ParentNode, args.NewParent); ++changeAfter; } // Register to watch for change events. private void RegisterWatchNeither(XmlNode node) { expectedNode = node; changeBefore = 0; changeAfter = 0; } private void RegisterWatchBoth(XmlNode node) { doc.NodeChanging += handleBefore; doc.NodeChanged += handleAfter; expectedNode = node; changeBefore = 0; changeAfter = 0; } private void RegisterWatchBefore(XmlNode node) { doc.NodeChanging += handleBefore; expectedNode = node; changeBefore = 0; changeAfter = 0; } private void RegisterWatchAfter(XmlNode node) { doc.NodeChanged += handleAfter; expectedNode = node; changeBefore = 0; changeAfter = 0; } // Check that change events were fired. private void CheckForChangeNeither() { doc.NodeChanging -= handleBefore; doc.NodeChanged -= handleAfter; AssertEquals("CheckForChange (Before)", 0, changeBefore); AssertEquals("CheckForChange (After)", 0, changeAfter); } private void CheckForChangeBoth() { doc.NodeChanging -= handleBefore; doc.NodeChanged -= handleAfter; AssertEquals("CheckForChange (Before)", 1, changeBefore); AssertEquals("CheckForChange (After)", 1, changeAfter); } private void CheckForChangeBefore() { doc.NodeChanging -= handleBefore; doc.NodeChanged -= handleAfter; AssertEquals("CheckForChange (Before)", 1, changeBefore); AssertEquals("CheckForChange (After)", 0, changeAfter); } private void CheckForChangeAfter() { doc.NodeChanging -= handleBefore; doc.NodeChanged -= handleAfter; AssertEquals("CheckForChange (Before)", 0, changeBefore); AssertEquals("CheckForChange (After)", 1, changeAfter); } // Test the appending of text data. public void TestXmlTextAppendData() { // Test simple appending. XmlText text = doc.CreateTextNode("hello"); RegisterWatchNeither(text); text.AppendData(" and goodbye"); CheckForChangeNeither(); AssertEquals("AppendData (1)", 17, text.Length); AssertEquals("AppendData (2)", "hello and goodbye", text.Data); // Test event handling. RegisterWatchBoth(text); text.AppendData("blah"); CheckForChangeBoth(); RegisterWatchBefore(text); text.AppendData("blah2"); CheckForChangeBefore(); RegisterWatchAfter(text); text.AppendData("blah3"); CheckForChangeAfter(); AssertEquals("AppendData (3)", "hello and goodbyeblahblah2blah3", text.Data); } // Test the deleting of text data. public void TestXmlTextDeleteData() { // Test simple deleting. XmlText text = doc.CreateTextNode("hello"); RegisterWatchNeither(text); text.DeleteData(1, 3); AssertEquals("DeleteData (1)", 2, text.Length); AssertEquals("DeleteData (2)", "ho", text.Data); // Test out of range deletions. text.DeleteData(-10, 3); text.DeleteData(2, 30); AssertEquals("DeleteData (3)", "ho", text.Data); text.DeleteData(-1000, 4000); AssertEquals("DeleteData (4)", String.Empty, text.Data); CheckForChangeNeither(); // Test event handling. text = doc.CreateTextNode("hello"); RegisterWatchBoth(text); text.DeleteData(1, 3); CheckForChangeBoth(); RegisterWatchBefore(text); text.DeleteData(-5, 1); CheckForChangeBefore(); RegisterWatchAfter(text); text.DeleteData(0, 5); CheckForChangeAfter(); } // Test the inserting of text data. public void TestXmlTextInsertData() { // Test simple insertions. XmlText text = doc.CreateTextNode("hello"); RegisterWatchNeither(text); text.InsertData(3, "lll"); AssertEquals("InsertData (1)", 8, text.Length); AssertEquals("InsertData (2)", "helllllo", text.Data); CheckForChangeNeither(); // Test out of range insertions. The before event will // fire, but not the after event, due to exceptions between. RegisterWatchBoth(text); try { text.InsertData(-1, "x"); Fail("InsertData (3)"); } catch(ArgumentOutOfRangeException) { // Success } CheckForChangeBefore(); RegisterWatchBoth(text); try { text.InsertData(9, "x"); Fail("InsertData (4)"); } catch(ArgumentOutOfRangeException) { // Success } CheckForChangeBefore(); // Test event handling. RegisterWatchBoth(text); text.InsertData(8, "x"); AssertEquals("InsertData (5)", 9, text.Length); AssertEquals("InsertData (6)", "helllllox", text.Data); CheckForChangeBoth(); RegisterWatchBefore(text); text.InsertData(8, "y"); AssertEquals("InsertData (7)", 10, text.Length); AssertEquals("InsertData (8)", "hellllloyx", text.Data); CheckForChangeBefore(); RegisterWatchBefore(text); text.InsertData(8, "z"); AssertEquals("InsertData (9)", 11, text.Length); AssertEquals("InsertData (10)", "helllllozyx", text.Data); CheckForChangeBefore(); } // Test the inserting of text data. public void TestXmlTextReplaceData() { // Test simple replacing. XmlText text = doc.CreateTextNode("hello"); RegisterWatchNeither(text); text.ReplaceData(1, 3, "xyzzy"); AssertEquals("ReplaceData (1)", 7, text.Length); AssertEquals("ReplaceData (2)", "hxyzzyo", text.Data); // Test out of range replaces. text.ReplaceData(-10, 3, "abc"); text.ReplaceData(10, 30, "def"); AssertEquals("ReplaceData (3)", "abchxyzzyodef", text.Data); text.ReplaceData(-1000, 4000, ""); AssertEquals("ReplaceData (4)", String.Empty, text.Data); CheckForChangeNeither(); // Test event handling. text = doc.CreateTextNode("hello"); RegisterWatchBoth(text); text.ReplaceData(1, 3, "blah"); CheckForChangeBoth(); RegisterWatchBefore(text); text.ReplaceData(-5, 1, "blah2"); CheckForChangeBefore(); RegisterWatchAfter(text); text.ReplaceData(0, 5, "blah3"); CheckForChangeAfter(); } // Test the setting of text data. public void TestXmlTextSetData() { // Test simple setting. XmlText text = doc.CreateTextNode(null); AssertEquals("SetData (1)", String.Empty, text.Data); RegisterWatchNeither(text); text.Data = "hello"; CheckForChangeNeither(); AssertEquals("SetData (2)", "hello", text.Data); AssertEquals("SetData (3)", 5, text.Length); // Test event handling. RegisterWatchBoth(text); text.Data = "blah"; CheckForChangeBoth(); AssertEquals("SetData (4)", "blah", text.Data); AssertEquals("SetData (5)", 4, text.Length); RegisterWatchBefore(text); text.Data = "blah2"; CheckForChangeBefore(); AssertEquals("SetData (6)", "blah2", text.Data); AssertEquals("SetData (7)", 5, text.Length); RegisterWatchAfter(text); text.Data = "blah3"; CheckForChangeAfter(); AssertEquals("SetData (8)", "blah3", text.Data); AssertEquals("SetData (9)", 5, text.Length); } // Test the splitting of text nodes. public void TestXmlTextSplitText() { // Perform simple splits at various points. XmlAttribute attr = doc.CreateAttribute("foo"); XmlText text = doc.CreateTextNode("hello and goodbye"); RegisterWatchNeither(text); attr.AppendChild(text); XmlText split = text.SplitText(6); CheckForChangeNeither(); Assert("SplitText (1)", text != split); AssertEquals("SplitText (2)", "hello ", text.Value); AssertEquals("SplitText (3)", "and goodbye", split.Value); attr = doc.CreateAttribute("foo"); text = doc.CreateTextNode("hello and goodbye"); attr.AppendChild(text); split = text.SplitText(-1); Assert("SplitText (4)", text != split); AssertEquals("SplitText (5)", "", text.Value); AssertEquals("SplitText (6)", "hello and goodbye", split.Value); attr = doc.CreateAttribute("foo"); text = doc.CreateTextNode("hello and goodbye"); attr.AppendChild(text); split = text.SplitText(100); Assert("SplitText (7)", text != split); AssertEquals("SplitText (8)", "hello and goodbye", text.Value); AssertEquals("SplitText (9)", "", split.Value); // Test event handling. attr = doc.CreateAttribute("foo"); text = doc.CreateTextNode("hello and goodbye"); attr.AppendChild(text); RegisterWatchBoth(text); text.SplitText(6); CheckForChangeBoth(); attr = doc.CreateAttribute("foo"); text = doc.CreateTextNode("hello and goodbye"); attr.AppendChild(text); RegisterWatchBefore(text); text.SplitText(6); CheckForChangeBefore(); attr = doc.CreateAttribute("foo"); text = doc.CreateTextNode("hello and goodbye"); attr.AppendChild(text); RegisterWatchAfter(text); text.SplitText(6); CheckForChangeAfter(); } // Test the substring operator on text data. public void TestXmlTextSubstring() { XmlText text = doc.CreateTextNode("hello and goodbye"); RegisterWatchNeither(text); AssertEquals("Substring (1)", String.Empty, text.Substring(3, 0)); AssertEquals("Substring (2)", "ello", text.Substring(1, 4)); AssertEquals("Substring (3)", "hello", text.Substring(-1, 6)); AssertEquals("Substring (4)", "llo and goodbye", text.Substring(2, 2000)); CheckForChangeNeither(); } }; // class TestXmlText #endif // !ECMA_COMPAT
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the dynamodb-2012-08-10.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DynamoDBv2.Model { /// <summary> /// Container for the parameters to the DeleteItem operation. /// Deletes a single item in a table by primary key. You can perform a conditional delete /// operation that deletes the item if it exists, or if it has an expected attribute value. /// /// /// <para> /// In addition to deleting an item, you can also return the item's attribute values in /// the same operation, using the <i>ReturnValues</i> parameter. /// </para> /// /// <para> /// Unless you specify conditions, the <i>DeleteItem</i> is an idempotent operation; running /// it multiple times on the same item or attribute does <i>not</i> result in an error /// response. /// </para> /// /// <para> /// Conditional deletes are useful for deleting items only if specific conditions are /// met. If those conditions are met, DynamoDB performs the delete. Otherwise, the item /// is not deleted. /// </para> /// </summary> public partial class DeleteItemRequest : AmazonDynamoDBRequest { private ConditionalOperator _conditionalOperator; private string _conditionExpression; private Dictionary<string, ExpectedAttributeValue> _expected = new Dictionary<string, ExpectedAttributeValue>(); private Dictionary<string, string> _expressionAttributeNames = new Dictionary<string, string>(); private Dictionary<string, AttributeValue> _expressionAttributeValues = new Dictionary<string, AttributeValue>(); private Dictionary<string, AttributeValue> _key = new Dictionary<string, AttributeValue>(); private ReturnConsumedCapacity _returnConsumedCapacity; private ReturnItemCollectionMetrics _returnItemCollectionMetrics; private ReturnValue _returnValues; private string _tableName; /// <summary> /// Empty constructor used to set properties independently even when a simple constructor is available /// </summary> public DeleteItemRequest() { } /// <summary> /// Instantiates DeleteItemRequest with the parameterized properties /// </summary> /// <param name="tableName">The name of the table from which to delete the item.</param> /// <param name="key">A map of attribute names to <i>AttributeValue</i> objects, representing the primary key of the item to delete. For the primary key, you must provide all of the attributes. For example, with a hash type primary key, you only need to provide the hash attribute. For a hash-and-range type primary key, you must provide both the hash attribute and the range attribute.</param> public DeleteItemRequest(string tableName, Dictionary<string, AttributeValue> key) { _tableName = tableName; _key = key; } /// <summary> /// Instantiates DeleteItemRequest with the parameterized properties /// </summary> /// <param name="tableName">The name of the table from which to delete the item.</param> /// <param name="key">A map of attribute names to <i>AttributeValue</i> objects, representing the primary key of the item to delete. For the primary key, you must provide all of the attributes. For example, with a hash type primary key, you only need to provide the hash attribute. For a hash-and-range type primary key, you must provide both the hash attribute and the range attribute.</param> /// <param name="returnValues">Use <i>ReturnValues</i> if you want to get the item attributes as they appeared before they were deleted. For <i>DeleteItem</i>, the valid values are: <ul> <li> <code>NONE</code> - If <i>ReturnValues</i> is not specified, or if its value is <code>NONE</code>, then nothing is returned. (This setting is the default for <i>ReturnValues</i>.) </li> <li> <code>ALL_OLD</code> - The content of the old item is returned. </li> </ul></param> public DeleteItemRequest(string tableName, Dictionary<string, AttributeValue> key, ReturnValue returnValues) { _tableName = tableName; _key = key; _returnValues = returnValues; } /// <summary> /// Gets and sets the property ConditionalOperator. <important> /// <para> /// There is a newer parameter available. Use <i>ConditionExpression</i> instead. Note /// that if you use <i>ConditionalOperator</i> and <i> ConditionExpression </i> at the /// same time, DynamoDB will return a <i>ValidationException</i> exception. /// </para> /// </important> /// <para> /// A logical operator to apply to the conditions in the <i>Expected</i> map: /// </para> /// <ul> <li> /// <para> /// <code>AND</code> - If all of the conditions evaluate to true, then the entire map /// evaluates to true. /// </para> /// </li> <li> /// <para> /// <code>OR</code> - If at least one of the conditions evaluate to true, then the entire /// map evaluates to true. /// </para> /// </li> </ul> /// <para> /// If you omit <i>ConditionalOperator</i>, then <code>AND</code> is the default. /// </para> /// /// <para> /// The operation will succeed only if the entire map evaluates to true. /// </para> /// <note> /// <para> /// This parameter does not support attributes of type List or Map. /// </para> /// </note> /// </summary> public ConditionalOperator ConditionalOperator { get { return this._conditionalOperator; } set { this._conditionalOperator = value; } } // Check to see if ConditionalOperator property is set internal bool IsSetConditionalOperator() { return this._conditionalOperator != null; } /// <summary> /// Gets and sets the property ConditionExpression. /// <para> /// A condition that must be satisfied in order for a conditional <i>DeleteItem</i> to /// succeed. /// </para> /// /// <para> /// An expression can contain any of the following: /// </para> /// <ul> <li> /// <para> /// Boolean functions: <code>attribute_exists | attribute_not_exists | contains | begins_with</code> /// /// </para> /// /// <para> /// These function names are case-sensitive. /// </para> /// </li> <li> /// <para> /// Comparison operators: <code> = | &#x3C;&#x3E; | &#x3C; | &#x3E; | &#x3C;= | &#x3E;= /// | BETWEEN | IN</code> /// </para> /// </li> <li> /// <para> /// Logical operators: <code>AND | OR | NOT</code> /// </para> /// </li> </ul> /// <para> /// For more information on condition expressions, go to <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html">Specifying /// Conditions</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// </summary> public string ConditionExpression { get { return this._conditionExpression; } set { this._conditionExpression = value; } } // Check to see if ConditionExpression property is set internal bool IsSetConditionExpression() { return this._conditionExpression != null; } /// <summary> /// Gets and sets the property Expected. <important> /// <para> /// There is a newer parameter available. Use <i>ConditionExpression</i> instead. Note /// that if you use <i>Expected</i> and <i> ConditionExpression </i> at the same time, /// DynamoDB will return a <i>ValidationException</i> exception. /// </para> /// </important> /// <para> /// A map of attribute/condition pairs. <i>Expected</i> provides a conditional block for /// the <i>DeleteItem</i> operation. /// </para> /// /// <para> /// Each element of <i>Expected</i> consists of an attribute name, a comparison operator, /// and one or more values. DynamoDB compares the attribute with the value(s) you supplied, /// using the comparison operator. For each <i>Expected</i> element, the result of the /// evaluation is either true or false. /// </para> /// /// <para> /// If you specify more than one element in the <i>Expected</i> map, then by default all /// of the conditions must evaluate to true. In other words, the conditions are ANDed /// together. (You can use the <i>ConditionalOperator</i> parameter to OR the conditions /// instead. If you do this, then at least one of the conditions must evaluate to true, /// rather than all of them.) /// </para> /// /// <para> /// If the <i>Expected</i> map evaluates to true, then the conditional operation succeeds; /// otherwise, it fails. /// </para> /// /// <para> /// <i>Expected</i> contains the following: /// </para> /// <ul> <li> /// <para> /// <i>AttributeValueList</i> - One or more values to evaluate against the supplied attribute. /// The number of values in the list depends on the <i>ComparisonOperator</i> being used. /// </para> /// /// <para> /// For type Number, value comparisons are numeric. /// </para> /// /// <para> /// String value comparisons for greater than, equals, or less than are based on ASCII /// character code values. For example, <code>a</code> is greater than <code>A</code>, /// and <code>a</code> is greater than <code>B</code>. For a list of code values, see /// <a href="http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters" >http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters</a>. /// </para> /// /// <para> /// For type Binary, DynamoDB treats each byte of the binary data as unsigned when it /// compares binary values. /// </para> /// </li> <li> /// <para> /// <i>ComparisonOperator</i> - A comparator for evaluating attributes in the <i>AttributeValueList</i>. /// When performing the comparison, DynamoDB uses strongly consistent reads. /// </para> /// /// <para> /// The following comparison operators are available: /// </para> /// /// <para> /// <code>EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH /// | IN | BETWEEN</code> /// </para> /// /// <para> /// The following are descriptions of each comparison operator. /// </para> /// <ul> <li> /// <para> /// <code>EQ</code> : Equal. <code>EQ</code> is supported for all datatypes, including /// lists and maps. /// </para> /// /// <para> /// <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> element of type /// String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains /// an <i>AttributeValue</i> element of a different type than the one provided in the /// request, the value does not match. For example, <code>{"S":"6"}</code> does not equal /// <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code> does not equal <code>{"NS":["6", /// "2", "1"]}</code>. /// </para> /// <p/> </li> <li> /// <para> /// <code>NE</code> : Not equal. <code>NE</code> is supported for all datatypes, including /// lists and maps. /// </para> /// /// <para> /// <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of type String, /// Number, Binary, String Set, Number Set, or Binary Set. If an item contains an <i>AttributeValue</i> /// of a different type than the one provided in the request, the value does not match. /// For example, <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code> /// does not equal <code>{"NS":["6", "2", "1"]}</code>. /// </para> /// <p/> </li> <li> /// <para> /// <code>LE</code> : Less than or equal. /// </para> /// /// <para> /// <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> element of type /// String, Number, or Binary (not a set type). If an item contains an <i>AttributeValue</i> /// element of a different type than the one provided in the request, the value does not /// match. For example, <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. /// Also, <code>{"N":"6"}</code> does not compare to <code>{"NS":["6", "2", "1"]}</code>. /// </para> /// <p/> </li> <li> /// <para> /// <code>LT</code> : Less than. /// </para> /// /// <para> /// <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of type String, /// Number, or Binary (not a set type). If an item contains an <i>AttributeValue</i> element /// of a different type than the one provided in the request, the value does not match. /// For example, <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code> /// does not compare to <code>{"NS":["6", "2", "1"]}</code>. /// </para> /// <p/> </li> <li> /// <para> /// <code>GE</code> : Greater than or equal. /// </para> /// /// <para> /// <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> element of type /// String, Number, or Binary (not a set type). If an item contains an <i>AttributeValue</i> /// element of a different type than the one provided in the request, the value does not /// match. For example, <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. /// Also, <code>{"N":"6"}</code> does not compare to <code>{"NS":["6", "2", "1"]}</code>. /// </para> /// <p/> </li> <li> /// <para> /// <code>GT</code> : Greater than. /// </para> /// /// <para> /// <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> element of type /// String, Number, or Binary (not a set type). If an item contains an <i>AttributeValue</i> /// element of a different type than the one provided in the request, the value does not /// match. For example, <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. /// Also, <code>{"N":"6"}</code> does not compare to <code>{"NS":["6", "2", "1"]}</code>. /// </para> /// <p/> </li> <li> /// <para> /// <code>NOT_NULL</code> : The attribute exists. <code>NOT_NULL</code> is supported for /// all datatypes, including lists and maps. /// </para> /// <note> /// <para> /// This operator tests for the existence of an attribute, not its data type. If the data /// type of attribute "<code>a</code>" is null, and you evaluate it using <code>NOT_NULL</code>, /// the result is a Boolean <i>true</i>. This result is because the attribute "<code>a</code>" /// exists; its data type is not relevant to the <code>NOT_NULL</code> comparison operator. /// </para> /// </note> </li> <li> /// <para> /// <code>NULL</code> : The attribute does not exist. <code>NULL</code> is supported for /// all datatypes, including lists and maps. /// </para> /// <note> /// <para> /// This operator tests for the nonexistence of an attribute, not its data type. If the /// data type of attribute "<code>a</code>" is null, and you evaluate it using <code>NULL</code>, /// the result is a Boolean <i>false</i>. This is because the attribute "<code>a</code>" /// exists; its data type is not relevant to the <code>NULL</code> comparison operator. /// </para> /// </note> </li> <li> /// <para> /// <code>CONTAINS</code> : Checks for a subsequence, or value in a set. /// </para> /// /// <para> /// <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> element of type /// String, Number, or Binary (not a set type). If the target attribute of the comparison /// is of type String, then the operator checks for a substring match. If the target attribute /// of the comparison is of type Binary, then the operator looks for a subsequence of /// the target that matches the input. If the target attribute of the comparison is a /// set ("<code>SS</code>", "<code>NS</code>", or "<code>BS</code>"), then the operator /// evaluates to true if it finds an exact match with any member of the set. /// </para> /// /// <para> /// CONTAINS is supported for lists: When evaluating "<code>a CONTAINS b</code>", "<code>a</code>" /// can be a list; however, "<code>b</code>" cannot be a set, a map, or a list. /// </para> /// </li> <li> /// <para> /// <code>NOT_CONTAINS</code> : Checks for absence of a subsequence, or absence of a value /// in a set. /// </para> /// /// <para> /// <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> element of type /// String, Number, or Binary (not a set type). If the target attribute of the comparison /// is a String, then the operator checks for the absence of a substring match. If the /// target attribute of the comparison is Binary, then the operator checks for the absence /// of a subsequence of the target that matches the input. If the target attribute of /// the comparison is a set ("<code>SS</code>", "<code>NS</code>", or "<code>BS</code>"), /// then the operator evaluates to true if it <i>does not</i> find an exact match with /// any member of the set. /// </para> /// /// <para> /// NOT_CONTAINS is supported for lists: When evaluating "<code>a NOT CONTAINS b</code>", /// "<code>a</code>" can be a list; however, "<code>b</code>" cannot be a set, a map, /// or a list. /// </para> /// </li> <li> /// <para> /// <code>BEGINS_WITH</code> : Checks for a prefix. /// </para> /// /// <para> /// <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of type String /// or Binary (not a Number or a set type). The target attribute of the comparison must /// be of type String or Binary (not a Number or a set type). /// </para> /// <p/> </li> <li> /// <para> /// <code>IN</code> : Checks for matching elements within two sets. /// </para> /// /// <para> /// <i>AttributeValueList</i> can contain one or more <i>AttributeValue</i> elements of /// type String, Number, or Binary (not a set type). These attributes are compared against /// an existing set type attribute of an item. If any elements of the input set are present /// in the item attribute, the expression evaluates to true. /// </para> /// </li> <li> /// <para> /// <code>BETWEEN</code> : Greater than or equal to the first value, and less than or /// equal to the second value. /// </para> /// /// <para> /// <i>AttributeValueList</i> must contain two <i>AttributeValue</i> elements of the same /// type, either String, Number, or Binary (not a set type). A target attribute matches /// if the target value is greater than, or equal to, the first element and less than, /// or equal to, the second element. If an item contains an <i>AttributeValue</i> element /// of a different type than the one provided in the request, the value does not match. /// For example, <code>{"S":"6"}</code> does not compare to <code>{"N":"6"}</code>. Also, /// <code>{"N":"6"}</code> does not compare to <code>{"NS":["6", "2", "1"]}</code> /// </para> /// </li> </ul> </li> </ul> /// <para> /// For usage examples of <i>AttributeValueList</i> and <i>ComparisonOperator</i>, see /// <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.html">Legacy /// Conditional Parameters</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// /// <para> /// For backward compatibility with previous DynamoDB releases, the following parameters /// can be used instead of <i>AttributeValueList</i> and <i>ComparisonOperator</i>: /// </para> /// <ul> <li> /// <para> /// <i>Value</i> - A value for DynamoDB to compare with an attribute. /// </para> /// </li> <li> /// <para> /// <i>Exists</i> - A Boolean value that causes DynamoDB to evaluate the value before /// attempting the conditional operation: /// </para> /// <ul> <li> /// <para> /// If <i>Exists</i> is <code>true</code>, DynamoDB will check to see if that attribute /// value already exists in the table. If it is found, then the condition evaluates to /// true; otherwise the condition evaluate to false. /// </para> /// </li> <li> /// <para> /// If <i>Exists</i> is <code>false</code>, DynamoDB assumes that the attribute value /// does <i>not</i> exist in the table. If in fact the value does not exist, then the /// assumption is valid and the condition evaluates to true. If the value is found, despite /// the assumption that it does not exist, the condition evaluates to false. /// </para> /// </li> </ul> /// <para> /// Note that the default value for <i>Exists</i> is <code>true</code>. /// </para> /// </li> </ul> /// <para> /// The <i>Value</i> and <i>Exists</i> parameters are incompatible with <i>AttributeValueList</i> /// and <i>ComparisonOperator</i>. Note that if you use both sets of parameters at once, /// DynamoDB will return a <i>ValidationException</i> exception. /// </para> /// <note> /// <para> /// This parameter does not support attributes of type List or Map. /// </para> /// </note> /// </summary> public Dictionary<string, ExpectedAttributeValue> Expected { get { return this._expected; } set { this._expected = value; } } // Check to see if Expected property is set internal bool IsSetExpected() { return this._expected != null && this._expected.Count > 0; } /// <summary> /// Gets and sets the property ExpressionAttributeNames. /// <para> /// One or more substitution tokens for attribute names in an expression. The following /// are some use cases for using <i>ExpressionAttributeNames</i>: /// </para> /// <ul> <li> /// <para> /// To access an attribute whose name conflicts with a DynamoDB reserved word. /// </para> /// </li> <li> /// <para> /// To create a placeholder for repeating occurrences of an attribute name in an expression. /// </para> /// </li> <li> /// <para> /// To prevent special characters in an attribute name from being misinterpreted in an /// expression. /// </para> /// </li> </ul> /// <para> /// Use the <b>#</b> character in an expression to dereference an attribute name. For /// example, consider the following attribute name: /// </para> /// <ul><li> /// <para> /// <code>Percentile</code> /// </para> /// </li></ul> /// <para> /// The name of this attribute conflicts with a reserved word, so it cannot be used directly /// in an expression. (For the complete list of reserved words, go to <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ReservedWords.html">Reserved /// Words</a> in the <i>Amazon DynamoDB Developer Guide</i>). To work around this, you /// could specify the following for <i>ExpressionAttributeNames</i>: /// </para> /// <ul><li> /// <para> /// <code>{"#P":"Percentile"}</code> /// </para> /// </li></ul> /// <para> /// You could then use this substitution in an expression, as in this example: /// </para> /// <ul><li> /// <para> /// <code>#P = :val</code> /// </para> /// </li></ul> <note> /// <para> /// Tokens that begin with the <b>:</b> character are <i>expression attribute values</i>, /// which are placeholders for the actual value at runtime. /// </para> /// </note> /// <para> /// For more information on expression attribute names, go to <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html">Accessing /// Item Attributes</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// </summary> public Dictionary<string, string> ExpressionAttributeNames { get { return this._expressionAttributeNames; } set { this._expressionAttributeNames = value; } } // Check to see if ExpressionAttributeNames property is set internal bool IsSetExpressionAttributeNames() { return this._expressionAttributeNames != null && this._expressionAttributeNames.Count > 0; } /// <summary> /// Gets and sets the property ExpressionAttributeValues. /// <para> /// One or more values that can be substituted in an expression. /// </para> /// /// <para> /// Use the <b>:</b> (colon) character in an expression to dereference an attribute value. /// For example, suppose that you wanted to check whether the value of the <i>ProductStatus</i> /// attribute was one of the following: /// </para> /// /// <para> /// <code>Available | Backordered | Discontinued</code> /// </para> /// /// <para> /// You would first need to specify <i>ExpressionAttributeValues</i> as follows: /// </para> /// /// <para> /// <code>{ ":avail":{"S":"Available"}, ":back":{"S":"Backordered"}, ":disc":{"S":"Discontinued"} /// }</code> /// </para> /// /// <para> /// You could then use these values in an expression, such as this: /// </para> /// /// <para> /// <code>ProductStatus IN (:avail, :back, :disc)</code> /// </para> /// /// <para> /// For more information on expression attribute values, go to <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html">Specifying /// Conditions</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// </summary> public Dictionary<string, AttributeValue> ExpressionAttributeValues { get { return this._expressionAttributeValues; } set { this._expressionAttributeValues = value; } } // Check to see if ExpressionAttributeValues property is set internal bool IsSetExpressionAttributeValues() { return this._expressionAttributeValues != null && this._expressionAttributeValues.Count > 0; } /// <summary> /// Gets and sets the property Key. /// <para> /// A map of attribute names to <i>AttributeValue</i> objects, representing the primary /// key of the item to delete. /// </para> /// /// <para> /// For the primary key, you must provide all of the attributes. For example, with a hash /// type primary key, you only need to provide the hash attribute. For a hash-and-range /// type primary key, you must provide both the hash attribute and the range attribute. /// </para> /// </summary> public Dictionary<string, AttributeValue> Key { get { return this._key; } set { this._key = value; } } // Check to see if Key property is set internal bool IsSetKey() { return this._key != null && this._key.Count > 0; } /// <summary> /// Gets and sets the property ReturnConsumedCapacity. /// </summary> public ReturnConsumedCapacity ReturnConsumedCapacity { get { return this._returnConsumedCapacity; } set { this._returnConsumedCapacity = value; } } // Check to see if ReturnConsumedCapacity property is set internal bool IsSetReturnConsumedCapacity() { return this._returnConsumedCapacity != null; } /// <summary> /// Gets and sets the property ReturnItemCollectionMetrics. /// <para> /// A value that if set to <code>SIZE</code>, the response includes statistics about item /// collections, if any, that were modified during the operation are returned in the response. /// If set to <code>NONE</code> (the default), no statistics are returned. /// </para> /// </summary> public ReturnItemCollectionMetrics ReturnItemCollectionMetrics { get { return this._returnItemCollectionMetrics; } set { this._returnItemCollectionMetrics = value; } } // Check to see if ReturnItemCollectionMetrics property is set internal bool IsSetReturnItemCollectionMetrics() { return this._returnItemCollectionMetrics != null; } /// <summary> /// Gets and sets the property ReturnValues. /// <para> /// Use <i>ReturnValues</i> if you want to get the item attributes as they appeared before /// they were deleted. For <i>DeleteItem</i>, the valid values are: /// </para> /// <ul> <li> /// <para> /// <code>NONE</code> - If <i>ReturnValues</i> is not specified, or if its value is <code>NONE</code>, /// then nothing is returned. (This setting is the default for <i>ReturnValues</i>.) /// </para> /// </li> <li> /// <para> /// <code>ALL_OLD</code> - The content of the old item is returned. /// </para> /// </li> </ul> /// </summary> public ReturnValue ReturnValues { get { return this._returnValues; } set { this._returnValues = value; } } // Check to see if ReturnValues property is set internal bool IsSetReturnValues() { return this._returnValues != null; } /// <summary> /// Gets and sets the property TableName. /// <para> /// The name of the table from which to delete the item. /// </para> /// </summary> public string TableName { get { return this._tableName; } set { this._tableName = value; } } // Check to see if TableName property is set internal bool IsSetTableName() { return this._tableName != null; } } }
// Copyright 2016 MaterialUI for Unity http://materialunity.com // Please see license file for terms and conditions of use, and more information. namespace MaterialUI { public enum MaterialIconEnum { _3D_ROTATION, AC_UNIT, ACCESS_ALARM, ACCESS_ALARMS, ACCESS_TIME, ACCESSIBILITY, ACCESSIBLE, ACCOUNT_BALANCE, ACCOUNT_BALANCE_WALLET, ACCOUNT_BOX, ACCOUNT_CIRCLE, ADB, ADD, ADD_A_PHOTO, ADD_ALARM, ADD_ALERT, ADD_BOX, ADD_CIRCLE, ADD_CIRCLE_OUTLINE, ADD_LOCATION, ADD_SHOPPING_CART, ADD_TO_PHOTOS, ADD_TO_QUEUE, ADJUST, AIRLINE_SEAT_FLAT, AIRLINE_SEAT_FLAT_ANGLED, AIRLINE_SEAT_INDIVIDUAL_SUITE, AIRLINE_SEAT_LEGROOM_EXTRA, AIRLINE_SEAT_LEGROOM_NORMAL, AIRLINE_SEAT_LEGROOM_REDUCED, AIRLINE_SEAT_RECLINE_EXTRA, AIRLINE_SEAT_RECLINE_NORMAL, AIRPLANEMODE_ACTIVE, AIRPLANEMODE_INACTIVE, AIRPLAY, AIRPORT_SHUTTLE, ALARM, ALARM_ADD, ALARM_OFF, ALARM_ON, ALBUM, ALL_INCLUSIVE, ALL_OUT, ANDROID, ANNOUNCEMENT, APPS, ARCHIVE, ARROW_BACK, ARROW_DOWNWARD, ARROW_DROP_DOWN, ARROW_DROP_DOWN_CIRCLE, ARROW_DROP_UP, ARROW_FORWARD, ARROW_UPWARD, ART_TRACK, ASPECT_RATIO, ASSESSMENT, ASSIGNMENT, ASSIGNMENT_IND, ASSIGNMENT_LATE, ASSIGNMENT_RETURN, ASSIGNMENT_RETURNED, ASSIGNMENT_TURNED_IN, ASSISTANT, ASSISTANT_PHOTO, ATTACH_FILE, ATTACH_MONEY, ATTACHMENT, AUDIOTRACK, AUTORENEW, AV_TIMER, BACKSPACE, BACKUP, BATTERY_ALERT, BATTERY_CHARGING_FULL, BATTERY_FULL, BATTERY_STD, BATTERY_UNKNOWN, BEACH_ACCESS, BEENHERE, BLOCK, BLUETOOTH, BLUETOOTH_AUDIO, BLUETOOTH_CONNECTED, BLUETOOTH_DISABLED, BLUETOOTH_SEARCHING, BLUR_CIRCULAR, BLUR_LINEAR, BLUR_OFF, BLUR_ON, BOOK, BOOKMARK, BOOKMARK_BORDER, BORDER_ALL, BORDER_BOTTOM, BORDER_CLEAR, BORDER_COLOR, BORDER_HORIZONTAL, BORDER_INNER, BORDER_LEFT, BORDER_OUTER, BORDER_RIGHT, BORDER_STYLE, BORDER_TOP, BORDER_VERTICAL, BRANDING_WATERMARK, BRIGHTNESS_1, BRIGHTNESS_2, BRIGHTNESS_3, BRIGHTNESS_4, BRIGHTNESS_5, BRIGHTNESS_6, BRIGHTNESS_7, BRIGHTNESS_AUTO, BRIGHTNESS_HIGH, BRIGHTNESS_LOW, BRIGHTNESS_MEDIUM, BROKEN_IMAGE, BRUSH, BUBBLE_CHART, BUG_REPORT, BUILD, BURST_MODE, BUSINESS, BUSINESS_CENTER, CACHED, CAKE, CALL, CALL_END, CALL_MADE, CALL_MERGE, CALL_MISSED, CALL_MISSED_OUTGOING, CALL_RECEIVED, CALL_SPLIT, CALL_TO_ACTION, CAMERA, CAMERA_ALT, CAMERA_ENHANCE, CAMERA_FRONT, CAMERA_REAR, CAMERA_ROLL, CANCEL, CARD_GIFTCARD, CARD_MEMBERSHIP, CARD_TRAVEL, CASINO, CAST, CAST_CONNECTED, CENTER_FOCUS_STRONG, CENTER_FOCUS_WEAK, CHANGE_HISTORY, CHAT, CHAT_BUBBLE, CHAT_BUBBLE_OUTLINE, CHECK, CHECK_BOX, CHECK_BOX_OUTLINE_BLANK, CHECK_CIRCLE, CHEVRON_LEFT, CHEVRON_RIGHT, CHILD_CARE, CHILD_FRIENDLY, CHROME_READER_MODE, CLASS, CLEAR, CLEAR_ALL, CLOSE, CLOSED_CAPTION, CLOUD, CLOUD_CIRCLE, CLOUD_DONE, CLOUD_DOWNLOAD, CLOUD_OFF, CLOUD_QUEUE, CLOUD_UPLOAD, CODE, COLLECTIONS, COLLECTIONS_BOOKMARK, COLOR_LENS, COLORIZE, COMMENT, COMPARE, COMPARE_ARROWS, COMPUTER, CONFIRMATION_NUMBER, CONTACT_MAIL, CONTACT_PHONE, CONTACTS, CONTENT_COPY, CONTENT_CUT, CONTENT_PASTE, CONTROL_POINT, CONTROL_POINT_DUPLICATE, COPYRIGHT, CREATE, CREATE_NEW_FOLDER, CREDIT_CARD, CROP, CROP_16_9, CROP_3_2, CROP_5_4, CROP_7_5, CROP_DIN, CROP_FREE, CROP_LANDSCAPE, CROP_ORIGINAL, CROP_PORTRAIT, CROP_ROTATE, CROP_SQUARE, DASHBOARD, DATA_USAGE, DATE_RANGE, DEHAZE, DELETE, DELETE_FOREVER, DELETE_SWEEP, DESCRIPTION, DESKTOP_MAC, DESKTOP_WINDOWS, DETAILS, DEVELOPER_BOARD, DEVELOPER_MODE, DEVICE_HUB, DEVICES, DEVICES_OTHER, DIALER_SIP, DIALPAD, DIRECTIONS, DIRECTIONS_BIKE, DIRECTIONS_BOAT, DIRECTIONS_BUS, DIRECTIONS_CAR, DIRECTIONS_RAILWAY, DIRECTIONS_RUN, DIRECTIONS_SUBWAY, DIRECTIONS_TRANSIT, DIRECTIONS_WALK, DISC_FULL, DNS, DO_NOT_DISTURB, DO_NOT_DISTURB_ALT, DO_NOT_DISTURB_OFF, DO_NOT_DISTURB_ON, DOCK, DOMAIN, DONE, DONE_ALL, DONUT_LARGE, DONUT_SMALL, DRAFTS, DRAG_HANDLE, DRIVE_ETA, DVR, EDIT, EDIT_LOCATION, EJECT, EMAIL, ENHANCED_ENCRYPTION, EQUALIZER, ERROR, ERROR_OUTLINE, EURO_SYMBOL, EV_STATION, EVENT, EVENT_AVAILABLE, EVENT_BUSY, EVENT_NOTE, EVENT_SEAT, EXIT_TO_APP, EXPAND_LESS, EXPAND_MORE, EXPLICIT, EXPLORE, EXPOSURE, EXPOSURE_NEG_1, EXPOSURE_NEG_2, EXPOSURE_PLUS_1, EXPOSURE_PLUS_2, EXPOSURE_ZERO, EXTENSION, FACE, FAST_FORWARD, FAST_REWIND, FAVORITE, FAVORITE_BORDER, FEATURED_PLAY_LIST, FEATURED_VIDEO, FEEDBACK, FIBER_DVR, FIBER_MANUAL_RECORD, FIBER_NEW, FIBER_PIN, FIBER_SMART_RECORD, FILE_DOWNLOAD, FILE_UPLOAD, FILTER, FILTER_1, FILTER_2, FILTER_3, FILTER_4, FILTER_5, FILTER_6, FILTER_7, FILTER_8, FILTER_9, FILTER_9_PLUS, FILTER_B_AND_W, FILTER_CENTER_FOCUS, FILTER_DRAMA, FILTER_FRAMES, FILTER_HDR, FILTER_LIST, FILTER_NONE, FILTER_TILT_SHIFT, FILTER_VINTAGE, FIND_IN_PAGE, FIND_REPLACE, FINGERPRINT, FIRST_PAGE, FITNESS_CENTER, FLAG, FLARE, FLASH_AUTO, FLASH_OFF, FLASH_ON, FLIGHT, FLIGHT_LAND, FLIGHT_TAKEOFF, FLIP, FLIP_TO_BACK, FLIP_TO_FRONT, FOLDER, FOLDER_OPEN, FOLDER_SHARED, FOLDER_SPECIAL, FONT_DOWNLOAD, FORMAT_ALIGN_CENTER, FORMAT_ALIGN_JUSTIFY, FORMAT_ALIGN_LEFT, FORMAT_ALIGN_RIGHT, FORMAT_BOLD, FORMAT_CLEAR, FORMAT_COLOR_FILL, FORMAT_COLOR_RESET, FORMAT_COLOR_TEXT, FORMAT_INDENT_DECREASE, FORMAT_INDENT_INCREASE, FORMAT_ITALIC, FORMAT_LINE_SPACING, FORMAT_LIST_BULLETED, FORMAT_LIST_NUMBERED, FORMAT_PAINT, FORMAT_QUOTE, FORMAT_SHAPES, FORMAT_SIZE, FORMAT_STRIKETHROUGH, FORMAT_TEXTDIRECTION_L_TO_R, FORMAT_TEXTDIRECTION_R_TO_L, FORMAT_UNDERLINED, FORUM, FORWARD, FORWARD_10, FORWARD_30, FORWARD_5, FREE_BREAKFAST, FULLSCREEN, FULLSCREEN_EXIT, FUNCTIONS, G_TRANSLATE, GAMEPAD, GAMES, GAVEL, GESTURE, GET_APP, GIF, GOLF_COURSE, GPS_FIXED, GPS_NOT_FIXED, GPS_OFF, GRADE, GRADIENT, GRAIN, GRAPHIC_EQ, GRID_OFF, GRID_ON, GROUP, GROUP_ADD, GROUP_WORK, HD, HDR_OFF, HDR_ON, HDR_STRONG, HDR_WEAK, HEADSET, HEADSET_MIC, HEALING, HEARING, HELP, HELP_OUTLINE, HIGH_QUALITY, HIGHLIGHT, HIGHLIGHT_OFF, HISTORY, HOME, HOT_TUB, HOTEL, HOURGLASS_EMPTY, HOURGLASS_FULL, HTTP, HTTPS, IMAGE, IMAGE_ASPECT_RATIO, IMPORT_CONTACTS, IMPORT_EXPORT, IMPORTANT_DEVICES, INBOX, INDETERMINATE_CHECK_BOX, INFO, INFO_OUTLINE, INPUT, INSERT_CHART, INSERT_COMMENT, INSERT_DRIVE_FILE, INSERT_EMOTICON, INSERT_INVITATION, INSERT_LINK, INSERT_PHOTO, INVERT_COLORS, INVERT_COLORS_OFF, ISO, KEYBOARD, KEYBOARD_ARROW_DOWN, KEYBOARD_ARROW_LEFT, KEYBOARD_ARROW_RIGHT, KEYBOARD_ARROW_UP, KEYBOARD_BACKSPACE, KEYBOARD_CAPSLOCK, KEYBOARD_HIDE, KEYBOARD_RETURN, KEYBOARD_TAB, KEYBOARD_VOICE, KITCHEN, LABEL, LABEL_OUTLINE, LANDSCAPE, LANGUAGE, LAPTOP, LAPTOP_CHROMEBOOK, LAPTOP_MAC, LAPTOP_WINDOWS, LAST_PAGE, LAUNCH, LAYERS, LAYERS_CLEAR, LEAK_ADD, LEAK_REMOVE, LENS, LIBRARY_ADD, LIBRARY_BOOKS, LIBRARY_MUSIC, LIGHTBULB_OUTLINE, LINE_STYLE, LINE_WEIGHT, LINEAR_SCALE, LINK, LINKED_CAMERA, LIST, LIVE_HELP, LIVE_TV, LOCAL_ACTIVITY, LOCAL_AIRPORT, LOCAL_ATM, LOCAL_BAR, LOCAL_CAFE, LOCAL_CAR_WASH, LOCAL_CONVENIENCE_STORE, LOCAL_DINING, LOCAL_DRINK, LOCAL_FLORIST, LOCAL_GAS_STATION, LOCAL_GROCERY_STORE, LOCAL_HOSPITAL, LOCAL_HOTEL, LOCAL_LAUNDRY_SERVICE, LOCAL_LIBRARY, LOCAL_MALL, LOCAL_MOVIES, LOCAL_OFFER, LOCAL_PARKING, LOCAL_PHARMACY, LOCAL_PHONE, LOCAL_PIZZA, LOCAL_PLAY, LOCAL_POST_OFFICE, LOCAL_PRINTSHOP, LOCAL_SEE, LOCAL_SHIPPING, LOCAL_TAXI, LOCATION_CITY, LOCATION_DISABLED, LOCATION_OFF, LOCATION_ON, LOCATION_SEARCHING, LOCK, LOCK_OPEN, LOCK_OUTLINE, LOOKS, LOOKS_3, LOOKS_4, LOOKS_5, LOOKS_6, LOOKS_ONE, LOOKS_TWO, LOOP, LOUPE, LOW_PRIORITY, LOYALTY, MAIL, MAIL_OUTLINE, MAP, MARKUNREAD, MARKUNREAD_MAILBOX, MEMORY, MENU, MERGE_TYPE, MESSAGE, MIC, MIC_NONE, MIC_OFF, MMS, MODE_COMMENT, MODE_EDIT, MONETIZATION_ON, MONEY_OFF, MONOCHROME_PHOTOS, MOOD, MOOD_BAD, MORE, MORE_HORIZ, MORE_VERT, MOTORCYCLE, MOUSE, MOVE_TO_INBOX, MOVIE, MOVIE_CREATION, MOVIE_FILTER, MULTILINE_CHART, MUSIC_NOTE, MUSIC_VIDEO, MY_LOCATION, NATURE, NATURE_PEOPLE, NAVIGATE_BEFORE, NAVIGATE_NEXT, NAVIGATION, NEAR_ME, NETWORK_CELL, NETWORK_CHECK, NETWORK_LOCKED, NETWORK_WIFI, NEW_RELEASES, NEXT_WEEK, NFC, NO_ENCRYPTION, NO_SIM, NOT_INTERESTED, NOTE, NOTE_ADD, NOTIFICATIONS, NOTIFICATIONS_ACTIVE, NOTIFICATIONS_NONE, NOTIFICATIONS_OFF, NOTIFICATIONS_PAUSED, OFFLINE_PIN, ONDEMAND_VIDEO, OPACITY, OPEN_IN_BROWSER, OPEN_IN_NEW, OPEN_WITH, PAGES, PAGEVIEW, PALETTE, PAN_TOOL, PANORAMA, PANORAMA_FISH_EYE, PANORAMA_HORIZONTAL, PANORAMA_VERTICAL, PANORAMA_WIDE_ANGLE, PARTY_MODE, PAUSE, PAUSE_CIRCLE_FILLED, PAUSE_CIRCLE_OUTLINE, PAYMENT, PEOPLE, PEOPLE_OUTLINE, PERM_CAMERA_MIC, PERM_CONTACT_CALENDAR, PERM_DATA_SETTING, PERM_DEVICE_INFORMATION, PERM_IDENTITY, PERM_MEDIA, PERM_PHONE_MSG, PERM_SCAN_WIFI, PERSON, PERSON_ADD, PERSON_OUTLINE, PERSON_PIN, PERSON_PIN_CIRCLE, PERSONAL_VIDEO, PETS, PHONE, PHONE_ANDROID, PHONE_BLUETOOTH_SPEAKER, PHONE_FORWARDED, PHONE_IN_TALK, PHONE_IPHONE, PHONE_LOCKED, PHONE_MISSED, PHONE_PAUSED, PHONELINK, PHONELINK_ERASE, PHONELINK_LOCK, PHONELINK_OFF, PHONELINK_RING, PHONELINK_SETUP, PHOTO, PHOTO_ALBUM, PHOTO_CAMERA, PHOTO_FILTER, PHOTO_LIBRARY, PHOTO_SIZE_SELECT_ACTUAL, PHOTO_SIZE_SELECT_LARGE, PHOTO_SIZE_SELECT_SMALL, PICTURE_AS_PDF, PICTURE_IN_PICTURE, PICTURE_IN_PICTURE_ALT, PIE_CHART, PIE_CHART_OUTLINED, PIN_DROP, PLACE, PLAY_ARROW, PLAY_CIRCLE_FILLED, PLAY_CIRCLE_OUTLINE, PLAY_FOR_WORK, PLAYLIST_ADD, PLAYLIST_ADD_CHECK, PLAYLIST_PLAY, PLUS_ONE, POLL, POLYMER, POOL, PORTABLE_WIFI_OFF, PORTRAIT, POWER, POWER_INPUT, POWER_SETTINGS_NEW, PREGNANT_WOMAN, PRESENT_TO_ALL, PRINT, PRIORITY_HIGH, PUBLIC, PUBLISH, QUERY_BUILDER, QUESTION_ANSWER, QUEUE, QUEUE_MUSIC, QUEUE_PLAY_NEXT, RADIO, RADIO_BUTTON_CHECKED, RADIO_BUTTON_UNCHECKED, RATE_REVIEW, RECEIPT, RECENT_ACTORS, RECORD_VOICE_OVER, REDEEM, REDO, REFRESH, REMOVE, REMOVE_CIRCLE, REMOVE_CIRCLE_OUTLINE, REMOVE_FROM_QUEUE, REMOVE_RED_EYE, REMOVE_SHOPPING_CART, REORDER, REPEAT, REPEAT_ONE, REPLAY, REPLAY_10, REPLAY_30, REPLAY_5, REPLY, REPLY_ALL, REPORT, REPORT_PROBLEM, RESTAURANT, RESTAURANT_MENU, RESTORE, RESTORE_PAGE, RING_VOLUME, ROOM, ROOM_SERVICE, ROTATE_90_DEGREES_CCW, ROTATE_LEFT, ROTATE_RIGHT, ROUNDED_CORNER, ROUTER, ROWING, RSS_FEED, RV_HOOKUP, SATELLITE, SAVE, SCANNER, SCHEDULE, SCHOOL, SCREEN_LOCK_LANDSCAPE, SCREEN_LOCK_PORTRAIT, SCREEN_LOCK_ROTATION, SCREEN_ROTATION, SCREEN_SHARE, SD_CARD, SD_STORAGE, SEARCH, SECURITY, SELECT_ALL, SEND, SENTIMENT_DISSATISFIED, SENTIMENT_NEUTRAL, SENTIMENT_SATISFIED, SENTIMENT_VERY_DISSATISFIED, SENTIMENT_VERY_SATISFIED, SETTINGS, SETTINGS_APPLICATIONS, SETTINGS_BACKUP_RESTORE, SETTINGS_BLUETOOTH, SETTINGS_BRIGHTNESS, SETTINGS_CELL, SETTINGS_ETHERNET, SETTINGS_INPUT_ANTENNA, SETTINGS_INPUT_COMPONENT, SETTINGS_INPUT_COMPOSITE, SETTINGS_INPUT_HDMI, SETTINGS_INPUT_SVIDEO, SETTINGS_OVERSCAN, SETTINGS_PHONE, SETTINGS_POWER, SETTINGS_REMOTE, SETTINGS_SYSTEM_DAYDREAM, SETTINGS_VOICE, SHARE, SHOP, SHOP_TWO, SHOPPING_BASKET, SHOPPING_CART, SHORT_TEXT, SHOW_CHART, SHUFFLE, SIGNAL_CELLULAR_4_BAR, SIGNAL_CELLULAR_CONNECTED_NO_INTERNET_4_BAR, SIGNAL_CELLULAR_NO_SIM, SIGNAL_CELLULAR_NULL, SIGNAL_CELLULAR_OFF, SIGNAL_WIFI_4_BAR, SIGNAL_WIFI_4_BAR_LOCK, SIGNAL_WIFI_OFF, SIM_CARD, SIM_CARD_ALERT, SKIP_NEXT, SKIP_PREVIOUS, SLIDESHOW, SLOW_MOTION_VIDEO, SMARTPHONE, SMOKE_FREE, SMOKING_ROOMS, SMS, SMS_FAILED, SNOOZE, SORT, SORT_BY_ALPHA, SPA, SPACE_BAR, SPEAKER, SPEAKER_GROUP, SPEAKER_NOTES, SPEAKER_NOTES_OFF, SPEAKER_PHONE, SPELLCHECK, STAR, STAR_BORDER, STAR_HALF, STARS, STAY_CURRENT_LANDSCAPE, STAY_CURRENT_PORTRAIT, STAY_PRIMARY_LANDSCAPE, STAY_PRIMARY_PORTRAIT, STOP, STOP_SCREEN_SHARE, STORAGE, STORE, STORE_MALL_DIRECTORY, STRAIGHTEN, STREETVIEW, STRIKETHROUGH_S, STYLE, SUBDIRECTORY_ARROW_LEFT, SUBDIRECTORY_ARROW_RIGHT, SUBJECT, SUBSCRIPTIONS, SUBTITLES, SUBWAY, SUPERVISOR_ACCOUNT, SURROUND_SOUND, SWAP_CALLS, SWAP_HORIZ, SWAP_VERT, SWAP_VERTICAL_CIRCLE, SWITCH_CAMERA, SWITCH_VIDEO, SYNC, SYNC_DISABLED, SYNC_PROBLEM, SYSTEM_UPDATE, SYSTEM_UPDATE_ALT, TAB, TAB_UNSELECTED, TABLET, TABLET_ANDROID, TABLET_MAC, TAG_FACES, TAP_AND_PLAY, TERRAIN, TEXT_FIELDS, TEXT_FORMAT, TEXTSMS, TEXTURE, THEATERS, THUMB_DOWN, THUMB_UP, THUMBS_UP_DOWN, TIME_TO_LEAVE, TIMELAPSE, TIMELINE, TIMER, TIMER_10, TIMER_3, TIMER_OFF, TITLE, TOC, TODAY, TOLL, TONALITY, TOUCH_APP, TOYS, TRACK_CHANGES, TRAFFIC, TRAIN, TRAM, TRANSFER_WITHIN_A_STATION, TRANSFORM, TRANSLATE, TRENDING_DOWN, TRENDING_FLAT, TRENDING_UP, TUNE, TURNED_IN, TURNED_IN_NOT, TV, UNARCHIVE, UNDO, UNFOLD_LESS, UNFOLD_MORE, UPDATE, USB, VERIFIED_USER, VERTICAL_ALIGN_BOTTOM, VERTICAL_ALIGN_CENTER, VERTICAL_ALIGN_TOP, VIBRATION, VIDEO_CALL, VIDEO_LABEL, VIDEO_LIBRARY, VIDEOCAM, VIDEOCAM_OFF, VIDEOGAME_ASSET, VIEW_AGENDA, VIEW_ARRAY, VIEW_CAROUSEL, VIEW_COLUMN, VIEW_COMFY, VIEW_COMPACT, VIEW_DAY, VIEW_HEADLINE, VIEW_LIST, VIEW_MODULE, VIEW_QUILT, VIEW_STREAM, VIEW_WEEK, VIGNETTE, VISIBILITY, VISIBILITY_OFF, VOICE_CHAT, VOICEMAIL, VOLUME_DOWN, VOLUME_MUTE, VOLUME_OFF, VOLUME_UP, VPN_KEY, VPN_LOCK, WALLPAPER, WARNING, WATCH, WATCH_LATER, WB_AUTO, WB_CLOUDY, WB_INCANDESCENT, WB_IRIDESCENT, WB_SUNNY, WC, WEB, WEB_ASSET, WEEKEND, WHATSHOT, WIDGETS, WIFI, WIFI_LOCK, WIFI_TETHERING, WORK, WRAP_TEXT, YOUTUBE_SEARCHED_FOR, ZOOM_IN, ZOOM_OUT, ZOOM_OUT_MAP, } }
// 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.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.Runtime.InteropServices { #if ENABLE_MIN_WINRT public static partial class McgMarshal { /// <summary> /// Creates a temporary HSTRING on the staack /// NOTE: pchPinnedSourceString must be pinned before calling this function, making sure the pointer /// is valid during the entire interop call /// </summary> [MethodImplAttribute(MethodImplOptions.NoInlining)] public static unsafe void StringToHStringReference( char* pchPinnedSourceString, string sourceString, HSTRING_HEADER* pHeader, HSTRING* phString) { if (sourceString == null) throw new ArgumentNullException(nameof(sourceString), SR.Null_HString); int hr = ExternalInterop.WindowsCreateStringReference( pchPinnedSourceString, (uint)sourceString.Length, pHeader, (void**)phString); if (hr < 0) throw Marshal.GetExceptionForHR(hr); } [MethodImplAttribute(MethodImplOptions.NoInlining)] internal static unsafe string HStringToString(IntPtr hString) { HSTRING hstring = new HSTRING(hString); return HStringToString(hstring); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static unsafe string HStringToString(HSTRING pHString) { if (pHString.handle == IntPtr.Zero) { return String.Empty; } uint length = 0; char* pchBuffer = ExternalInterop.WindowsGetStringRawBuffer(pHString.handle.ToPointer(), &length); return new string(pchBuffer, 0, (int)length); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static unsafe void FreeHString(IntPtr pHString) { ExternalInterop.WindowsDeleteString(pHString.ToPointer()); } } #endif public static partial class ExternalInterop { [DllImport(Libraries.CORE_WINRT)] [McgGeneratedNativeCallCodeAttribute] [MethodImplAttribute(MethodImplOptions.NoInlining)] public static extern unsafe int RoGetActivationFactory(void* hstring_typeName, Guid* iid, void* ppv); [DllImport(Libraries.CORE_WINRT_STRING)] [McgGeneratedNativeCallCodeAttribute] [MethodImplAttribute(MethodImplOptions.NoInlining)] internal static extern unsafe int WindowsCreateStringReference(char* sourceString, uint length, HSTRING_HEADER* phstringHeader, void* hstring); [DllImport(Libraries.CORE_COM)] [McgGeneratedNativeCallCodeAttribute] internal static extern unsafe int CoCreateFreeThreadedMarshaler(void* pOuter, void** ppunkMarshal); [DllImport(Libraries.CORE_COM)] [McgGeneratedNativeCallCodeAttribute] public static extern unsafe int CoGetContextToken(IntPtr* ppToken); [DllImport(Libraries.CORE_COM)] [McgGeneratedNativeCallCodeAttribute] internal static extern unsafe int CoGetObjectContext(Guid* iid, void* ppv); [DllImport(Libraries.CORE_COM)] [McgGeneratedNativeCallCodeAttribute] private static extern unsafe int CoGetMarshalSizeMax(ulong* pulSize, Guid* iid, IntPtr pUnk, Interop.COM.MSHCTX dwDestContext, IntPtr pvDestContext, Interop.COM.MSHLFLAGS mshlflags); [DllImport(Libraries.CORE_COM)] [McgGeneratedNativeCallCodeAttribute] private extern static unsafe int CoMarshalInterface(IntPtr pStream, Guid* iid, IntPtr pUnk, Interop.COM.MSHCTX dwDestContext, IntPtr pvDestContext, Interop.COM.MSHLFLAGS mshlflags); [DllImport(Libraries.CORE_COM)] [McgGeneratedNativeCallCodeAttribute] private static extern unsafe int CoUnmarshalInterface(IntPtr pStream, Guid* iid, void** ppv); [DllImport(Libraries.CORE_COM)] [McgGeneratedNativeCallCodeAttribute] [MethodImplAttribute(MethodImplOptions.NoInlining)] internal static extern int CoReleaseMarshalData(IntPtr pStream); /// <summary> /// Marshal IUnknown * into IStream* /// </summary> /// <returns>HResult</returns> internal static unsafe int CoMarshalInterface(IntPtr pStream, ref Guid iid, IntPtr pUnk, Interop.COM.MSHCTX dwDestContext, IntPtr pvDestContext, Interop.COM.MSHLFLAGS mshlflags) { fixed (Guid* unsafe_iid = &iid) { return CoMarshalInterface(pStream, unsafe_iid, pUnk, dwDestContext, pvDestContext, mshlflags); } } /// <summary> /// Marshal IStream* into IUnknown* /// </summary> /// <returns>HResult</returns> internal static unsafe int CoUnmarshalInterface(IntPtr pStream, ref Guid iid, out IntPtr ppv) { fixed (Guid* unsafe_iid = &iid) { fixed (void* unsafe_ppv = &ppv) { return CoUnmarshalInterface(pStream, unsafe_iid, (void**)unsafe_ppv); } } } /// <summary> /// Returns an upper bound on the number of bytes needed to marshal the specified interface pointer to the specified object. /// </summary> /// <returns>HResult</returns> internal static unsafe int CoGetMarshalSizeMax(out ulong pulSize, ref Guid iid, IntPtr pUnk, Interop.COM.MSHCTX dwDestContext, IntPtr pvDestContext, Interop.COM.MSHLFLAGS mshlflags) { fixed (ulong* unsafe_pulSize = &pulSize) { fixed (Guid* unsafe_iid = &iid) { return CoGetMarshalSizeMax(unsafe_pulSize, unsafe_iid, pUnk, dwDestContext, pvDestContext, mshlflags); } } } internal static unsafe void RoGetActivationFactory(string className, ref Guid iid, out IntPtr ppv) { fixed (char* unsafe_className = className) { void* hstring_typeName = null; HSTRING_HEADER hstringHeader; int hr = WindowsCreateStringReference( unsafe_className, (uint)className.Length, &hstringHeader, &hstring_typeName); if (hr < 0) throw Marshal.GetExceptionForHR(hr); fixed (Guid* unsafe_iid = &iid) { fixed (void* unsafe_ppv = &ppv) { hr = ExternalInterop.RoGetActivationFactory( hstring_typeName, unsafe_iid, unsafe_ppv); if (hr < 0) throw Marshal.GetExceptionForHR(hr); } } } } public static unsafe int CoGetContextToken(out IntPtr ppToken) { ppToken = IntPtr.Zero; fixed (IntPtr* unsafePpToken = &ppToken) { return CoGetContextToken(unsafePpToken); } } internal static unsafe int CoGetObjectContext(ref Guid iid, out IntPtr ppv) { fixed (void* unsafe_ppv = &ppv) { fixed (Guid* unsafe_iid = &iid) { return CoGetObjectContext(unsafe_iid, (void**)unsafe_ppv); } } } } }
// MvxAndroidLocalFileImageLoader.cs // (c) Copyright Cirrious Ltd. http://www.cirrious.com // MvvmCross is licensed using Microsoft Public License (Ms-PL) // Contributions and inspirations noted in readme.md and license.txt // // Project Lead - Stuart Lodge, @slodge, me@slodge.com using Android.Graphics; using MvvmCross.Platform; using MvvmCross.Platform.Droid; using MvvmCross.Platform.Platform; using MvvmCross.Binding; using MvvmCross.Plugins.File; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace MvvmCross.Plugins.DownloadCache.Droid { [Preserve(AllMembers = true)] public class MvxAndroidLocalFileImageLoader : IMvxLocalFileImageLoader<Bitmap> { private const string ResourcePrefix = "res:"; private readonly IDictionary<CacheKey, WeakReference<Bitmap>> _memCache = new Dictionary<CacheKey, WeakReference<Bitmap>>(); public async Task<MvxImage<Bitmap>> Load(string localPath, bool shouldCache, int maxWidth, int maxHeight) { Bitmap bitmap; var shouldAddToCache = shouldCache; if (shouldCache && TryGetCachedBitmap(localPath, maxWidth, maxHeight, out bitmap)) { shouldAddToCache = false; } else if (localPath.StartsWith(ResourcePrefix)) { var resourcePath = localPath.Substring(ResourcePrefix.Length); bitmap = await LoadResourceBitmapAsync(resourcePath).ConfigureAwait(false); } else { bitmap = await LoadBitmapAsync(localPath, maxWidth, maxHeight).ConfigureAwait(false); } if (shouldAddToCache) { AddToCache(localPath, maxWidth, maxHeight, bitmap); } return (MvxImage<Bitmap>)new MvxAndroidImage(bitmap); } private IMvxAndroidGlobals _androidGlobals; protected IMvxAndroidGlobals AndroidGlobals => _androidGlobals ?? (_androidGlobals = Mvx.Resolve<IMvxAndroidGlobals>()); private async Task<Bitmap> LoadResourceBitmapAsync(string resourcePath) { var resources = AndroidGlobals.ApplicationContext.Resources; var id = resources.GetIdentifier(resourcePath, "drawable", AndroidGlobals.ApplicationContext.PackageName); if (id == 0) { MvxBindingTrace.Trace(MvxTraceLevel.Warning, "Value '{0}' was not a known drawable name", resourcePath); return null; } return await BitmapFactory.DecodeResourceAsync(resources, id, new BitmapFactory.Options { InPurgeable = true }).ConfigureAwait(false); } private static async Task<Bitmap> LoadBitmapAsync(string localPath, int maxWidth, int maxHeight) { // If the localPath is a content:// url, // try to load with a FileDescriptor if (localPath.ToLower().StartsWith("content")) { Bitmap bmp = null; // There is no Async version of DecodeFileDescriptor that // takes Options object. Wrapping with a Task Factory // to maintain async nature of the method call await Task.Run(() => { var globals = Mvx.Resolve<IMvxAndroidGlobals>(); var uri = Android.Net.Uri.Parse(localPath); var parcelFileDescriptor = globals?.ApplicationContext?.ContentResolver.OpenFileDescriptor(uri, "r"); var fileDescriptor = parcelFileDescriptor?.FileDescriptor; var opts = new BitmapFactory.Options { InJustDecodeBounds = true }; BitmapFactory.DecodeFileDescriptor(fileDescriptor, null, opts); // Calculate inSampleSize opts.InSampleSize = CalculateInSampleSize(opts, maxWidth, maxHeight); // see http://slodge.blogspot.co.uk/2013/02/huge-android-memory-bug-and-bug-hunting.html opts.InPurgeable = true; // Decode bitmap with inSampleSize set opts.InJustDecodeBounds = false; bmp = BitmapFactory.DecodeFileDescriptor(fileDescriptor, null, opts); parcelFileDescriptor?.Close(); }).ConfigureAwait(false); return bmp; } if (maxWidth > 0 || maxHeight > 0) { // load thumbnail - see: http://developer.android.com/training/displaying-bitmaps/load-bitmap.html var options = new BitmapFactory.Options { InJustDecodeBounds = true }; await BitmapFactory.DecodeFileAsync(localPath, options).ConfigureAwait(false); // Calculate inSampleSize options.InSampleSize = CalculateInSampleSize(options, maxWidth, maxHeight); // see http://slodge.blogspot.co.uk/2013/02/huge-android-memory-bug-and-bug-hunting.html options.InPurgeable = true; // Decode bitmap with inSampleSize set options.InJustDecodeBounds = false; return await BitmapFactory.DecodeFileAsync(localPath, options).ConfigureAwait(false); } else { var fileStore = Mvx.Resolve<IMvxFileStore>(); byte[] contents; if (!fileStore.TryReadBinaryFile(localPath, out contents)) return null; // the InPurgeable option is very important for Droid memory management. // see http://slodge.blogspot.co.uk/2013/02/huge-android-memory-bug-and-bug-hunting.html var options = new BitmapFactory.Options { InPurgeable = true }; var image = await BitmapFactory.DecodeByteArrayAsync(contents, 0, contents.Length, options) .ConfigureAwait(false); return image; } } private static int CalculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image int height = options.OutHeight; int width = options.OutWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { int halfHeight = height / 2; int halfWidth = width / 2; // Calculate the largest inSampleSize value that is a power of 2 and keeps both // height and width larger than the requested height and width. while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { inSampleSize *= 2; } } return inSampleSize; } private bool TryGetCachedBitmap(string localPath, int maxWidth, int maxHeight, out Bitmap bitmap) { var key = new CacheKey(localPath, maxWidth, maxHeight); WeakReference<Bitmap> reference; if (_memCache.TryGetValue(key, out reference)) { Bitmap target; if (reference.TryGetTarget(out target) && target != null && target.Handle != IntPtr.Zero && !target.IsRecycled) { bitmap = target; return true; } _memCache.Remove(key); } bitmap = null; return false; } private void AddToCache(string localPath, int maxWidth, int maxHeight, Bitmap bitmap) { if (bitmap == null) return; var key = new CacheKey(localPath, maxWidth, maxHeight); _memCache[key] = new WeakReference<Bitmap>(bitmap); } private class CacheKey { private string LocalPath { get; set; } private int MaxWidth { get; set; } private int MaxHeight { get; set; } public CacheKey(string localPath, int maxWidth, int maxHeight) { if (localPath == null) throw new ArgumentNullException(nameof(localPath)); LocalPath = localPath; MaxWidth = maxWidth; MaxHeight = maxHeight; } public override int GetHashCode() { return LocalPath.GetHashCode() + MaxWidth.GetHashCode() + MaxHeight.GetHashCode(); } public override bool Equals(object obj) { var other = obj as CacheKey; if (other == null) return false; return Equals(LocalPath, other.LocalPath) && Equals(MaxWidth, other.MaxWidth) && Equals(MaxHeight, other.MaxHeight); } } } }
// 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.IO; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.Metadata.Tests; using Xunit; namespace System.Reflection.PortableExecutable.Tests { public class PEReaderTests { [Fact] public void Ctor() { Assert.Throws<ArgumentNullException>(() => new PEReader(null, PEStreamOptions.Default)); var invalid = new MemoryStream(new byte[] { 1, 2, 3, 4 }); // the stream should not be disposed if the arguments are bad Assert.Throws<ArgumentOutOfRangeException>(() => new PEReader(invalid, (PEStreamOptions)int.MaxValue)); Assert.True(invalid.CanRead); // no BadImageFormatException if we're prefetching the entire image: var peReader0 = new PEReader(invalid, PEStreamOptions.PrefetchEntireImage | PEStreamOptions.LeaveOpen); Assert.True(invalid.CanRead); Assert.Throws<BadImageFormatException>(() => peReader0.PEHeaders); invalid.Position = 0; // BadImageFormatException if we're prefetching the entire image and metadata: Assert.Throws<BadImageFormatException>(() => new PEReader(invalid, PEStreamOptions.PrefetchEntireImage | PEStreamOptions.PrefetchMetadata | PEStreamOptions.LeaveOpen)); Assert.True(invalid.CanRead); invalid.Position = 0; // the stream should be disposed if the content is bad: Assert.Throws<BadImageFormatException>(() => new PEReader(invalid, PEStreamOptions.PrefetchMetadata)); Assert.False(invalid.CanRead); // the stream should not be disposed if we specified LeaveOpen flag: invalid = new MemoryStream(new byte[] { 1, 2, 3, 4 }); Assert.Throws<BadImageFormatException>(() => new PEReader(invalid, PEStreamOptions.PrefetchMetadata | PEStreamOptions.LeaveOpen)); Assert.True(invalid.CanRead); // valid metadata: var valid = new MemoryStream(Misc.Members); var peReader = new PEReader(valid, PEStreamOptions.Default); Assert.True(valid.CanRead); peReader.Dispose(); Assert.False(valid.CanRead); } [Fact] public void Ctor_Streams() { AssertExtensions.Throws<ArgumentException>("peStream", () => new PEReader(new CustomAccessMemoryStream(canRead: false, canSeek: false, canWrite: false))); AssertExtensions.Throws<ArgumentException>("peStream", () => new PEReader(new CustomAccessMemoryStream(canRead: true, canSeek: false, canWrite: false))); var s = new CustomAccessMemoryStream(canRead: true, canSeek: true, canWrite: false); new PEReader(s); new PEReader(s, PEStreamOptions.Default, 0); Assert.Throws<ArgumentOutOfRangeException>(() => new PEReader(s, PEStreamOptions.Default, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => new PEReader(s, PEStreamOptions.Default, 1)); } [Fact] public unsafe void Ctor_Loaded() { byte b = 1; Assert.True(new PEReader(&b, 1, isLoadedImage: true).IsLoadedImage); Assert.False(new PEReader(&b, 1, isLoadedImage: false).IsLoadedImage); Assert.True(new PEReader(new MemoryStream(), PEStreamOptions.IsLoadedImage).IsLoadedImage); Assert.False(new PEReader(new MemoryStream()).IsLoadedImage); } [Fact] public void FromEmptyStream() { Assert.Throws<BadImageFormatException>(() => new PEReader(new MemoryStream(), PEStreamOptions.PrefetchMetadata)); Assert.Throws<BadImageFormatException>(() => new PEReader(new MemoryStream(), PEStreamOptions.PrefetchMetadata | PEStreamOptions.PrefetchEntireImage)); } [Fact(Skip = "https://github.com/dotnet/corefx/issues/7996")] [ActiveIssue(7996)] public void SubStream() { var stream = new MemoryStream(); stream.WriteByte(0xff); stream.Write(Misc.Members, 0, Misc.Members.Length); stream.WriteByte(0xff); stream.WriteByte(0xff); stream.Position = 1; var peReader1 = new PEReader(stream, PEStreamOptions.LeaveOpen, Misc.Members.Length); Assert.Equal(Misc.Members.Length, peReader1.GetEntireImage().Length); peReader1.GetMetadataReader(); stream.Position = 1; var peReader2 = new PEReader(stream, PEStreamOptions.LeaveOpen | PEStreamOptions.PrefetchMetadata, Misc.Members.Length); Assert.Equal(Misc.Members.Length, peReader2.GetEntireImage().Length); peReader2.GetMetadataReader(); stream.Position = 1; var peReader3 = new PEReader(stream, PEStreamOptions.LeaveOpen | PEStreamOptions.PrefetchEntireImage, Misc.Members.Length); Assert.Equal(Misc.Members.Length, peReader3.GetEntireImage().Length); peReader3.GetMetadataReader(); } // TODO: Switch to small checked in native image. /* [Fact] public void OpenNativeImage() { using (var reader = new PEReader(File.OpenRead(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "kernel32.dll")))) { Assert.False(reader.HasMetadata); Assert.True(reader.PEHeaders.IsDll); Assert.False(reader.PEHeaders.IsExe); Assert.Throws<InvalidOperationException>(() => reader.GetMetadataReader()); } } */ [Fact] public void IL_LazyLoad() { var peStream = new MemoryStream(Misc.Members); using (var reader = new PEReader(peStream, PEStreamOptions.LeaveOpen)) { var md = reader.GetMetadataReader(); var il = reader.GetMethodBody(md.GetMethodDefinition(MetadataTokens.MethodDefinitionHandle(1)).RelativeVirtualAddress); Assert.Equal(new byte[] { 0, 42 }, il.GetILBytes()); Assert.Equal(8, il.MaxStack); } } [Fact] public void IL_EagerLoad() { var peStream = new MemoryStream(Misc.Members); using (var reader = new PEReader(peStream, PEStreamOptions.LeaveOpen | PEStreamOptions.PrefetchMetadata | PEStreamOptions.PrefetchEntireImage)) { var md = reader.GetMetadataReader(); var il = reader.GetMethodBody(md.GetMethodDefinition(MetadataTokens.MethodDefinitionHandle(1)).RelativeVirtualAddress); Assert.Equal(new byte[] { 0, 42 }, il.GetILBytes()); Assert.Equal(8, il.MaxStack); } } [Fact] public void Metadata_LazyLoad() { var peStream = new MemoryStream(Misc.Members); using (var reader = new PEReader(peStream, PEStreamOptions.LeaveOpen)) { var md = reader.GetMetadataReader(); var method = md.GetMethodDefinition(MetadataTokens.MethodDefinitionHandle(1)); Assert.Equal("MC1", md.GetString(method.Name)); } } [Fact] public void Metadata_EagerLoad() { var peStream = new MemoryStream(Misc.Members); using (var reader = new PEReader(peStream, PEStreamOptions.LeaveOpen | PEStreamOptions.PrefetchMetadata)) { var md = reader.GetMetadataReader(); var method = md.GetMethodDefinition(MetadataTokens.MethodDefinitionHandle(1)); Assert.Equal("MC1", md.GetString(method.Name)); Assert.Throws<InvalidOperationException>(() => reader.GetEntireImage()); Assert.Throws<InvalidOperationException>(() => reader.GetMethodBody(method.RelativeVirtualAddress)); } } [Fact] public void EntireImage_LazyLoad() { var peStream = new MemoryStream(Misc.Members); using (var reader = new PEReader(peStream, PEStreamOptions.LeaveOpen)) { Assert.Equal(4608, reader.GetEntireImage().Length); } } [Fact] public void EntireImage_EagerLoad() { var peStream = new MemoryStream(Misc.Members); using (var reader = new PEReader(peStream, PEStreamOptions.LeaveOpen | PEStreamOptions.PrefetchMetadata | PEStreamOptions.PrefetchEntireImage)) { Assert.Equal(4608, reader.GetEntireImage().Length); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get module handles public void GetMethodBody_Loaded() { LoaderUtilities.LoadPEAndValidate(Misc.Members, reader => { var md = reader.GetMetadataReader(); var il = reader.GetMethodBody(md.GetMethodDefinition(MetadataTokens.MethodDefinitionHandle(1)).RelativeVirtualAddress); Assert.Equal(new byte[] { 0, 42 }, il.GetILBytes()); Assert.Equal(8, il.MaxStack); }); } [Fact] public void GetSectionData() { var peStream = new MemoryStream(Misc.Members); using (var reader = new PEReader(peStream)) { ValidateSectionData(reader); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get module handles public void GetSectionData_Loaded() { LoaderUtilities.LoadPEAndValidate(Misc.Members, ValidateSectionData); } private unsafe void ValidateSectionData(PEReader reader) { var relocBlob1 = reader.GetSectionData(".reloc").GetContent(); var relocBlob2 = reader.GetSectionData(0x6000).GetContent(); AssertEx.Equal(new byte[] { 0x00, 0x20, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0xD0, 0x38, 0x00, 0x00 }, relocBlob1); AssertEx.Equal(relocBlob1, relocBlob2); var data = reader.GetSectionData(0x5fff); Assert.True(data.Pointer == null); Assert.Equal(0, data.Length); AssertEx.Equal(new byte[0], data.GetContent()); data = reader.GetSectionData(0x600B); Assert.True(data.Pointer != null); Assert.Equal(1, data.Length); AssertEx.Equal(new byte[] { 0x00 }, data.GetContent()); data = reader.GetSectionData(0x600C); Assert.True(data.Pointer == null); Assert.Equal(0, data.Length); AssertEx.Equal(new byte[0], data.GetContent()); data = reader.GetSectionData(0x600D); Assert.True(data.Pointer == null); Assert.Equal(0, data.Length); AssertEx.Equal(new byte[0], data.GetContent()); data = reader.GetSectionData(int.MaxValue); Assert.True(data.Pointer == null); Assert.Equal(0, data.Length); AssertEx.Equal(new byte[0], data.GetContent()); data = reader.GetSectionData(".nonexisting"); Assert.True(data.Pointer == null); Assert.Equal(0, data.Length); AssertEx.Equal(new byte[0], data.GetContent()); data = reader.GetSectionData(""); Assert.True(data.Pointer == null); Assert.Equal(0, data.Length); AssertEx.Equal(new byte[0], data.GetContent()); } [Fact] public void GetSectionData_Errors() { var peStream = new MemoryStream(Misc.Members); using (var reader = new PEReader(peStream)) { Assert.Throws<ArgumentNullException>(() => reader.GetSectionData(null)); Assert.Throws<ArgumentOutOfRangeException>(() => reader.GetSectionData(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => reader.GetSectionData(int.MinValue)); } } [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)] public void TryOpenAssociatedPortablePdb_Args() { var peStream = new MemoryStream(PortablePdbs.DocumentsDll); using (var reader = new PEReader(peStream)) { MetadataReaderProvider pdbProvider; string pdbPath; Assert.False(reader.TryOpenAssociatedPortablePdb(@"b.dll", _ => null, out pdbProvider, out pdbPath)); Assert.Throws<ArgumentNullException>(() => reader.TryOpenAssociatedPortablePdb(@"b.dll", null, out pdbProvider, out pdbPath)); Assert.Throws<ArgumentNullException>(() => reader.TryOpenAssociatedPortablePdb(null, _ => null, out pdbProvider, out pdbPath)); AssertExtensions.Throws<ArgumentException>("peImagePath", () => reader.TryOpenAssociatedPortablePdb("C:\\a\\\0\\b", _ => null, out pdbProvider, out pdbPath)); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public void TryOpenAssociatedPortablePdb_Args_Core() { var peStream = new MemoryStream(PortablePdbs.DocumentsDll); using (var reader = new PEReader(peStream)) { MetadataReaderProvider pdbProvider; string pdbPath; Assert.False(reader.TryOpenAssociatedPortablePdb(@"b.dll", _ => null, out pdbProvider, out pdbPath)); Assert.Throws<ArgumentNullException>(() => reader.TryOpenAssociatedPortablePdb(@"b.dll", null, out pdbProvider, out pdbPath)); Assert.Throws<ArgumentNullException>(() => reader.TryOpenAssociatedPortablePdb(null, _ => null, out pdbProvider, out pdbPath)); Assert.False(reader.TryOpenAssociatedPortablePdb("C:\\a\\\0\\b", _ => null, out pdbProvider, out pdbPath)); } } [Fact] public void TryOpenAssociatedPortablePdb_CollocatedFile() { var peStream = new MemoryStream(PortablePdbs.DocumentsDll); using (var reader = new PEReader(peStream)) { string pathQueried = null; Func<string, Stream> streamProvider = p => { Assert.Null(pathQueried); pathQueried = p; return new MemoryStream(PortablePdbs.DocumentsPdb); }; MetadataReaderProvider pdbProvider; string pdbPath; Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath)); Assert.Equal(Path.Combine("pedir", "Documents.pdb"), pathQueried); Assert.Equal(Path.Combine("pedir", "Documents.pdb"), pdbPath); var pdbReader = pdbProvider.GetMetadataReader(); Assert.Equal(13, pdbReader.Documents.Count); } } [Fact] public void TryOpenAssociatedPortablePdb_Embedded() { var peStream = new MemoryStream(PortablePdbs.DocumentsEmbeddedDll); using (var reader = new PEReader(peStream)) { string pathQueried = null; Func<string, Stream> streamProvider = p => { Assert.Null(pathQueried); pathQueried = p; return null; }; MetadataReaderProvider pdbProvider; string pdbPath; Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath)); Assert.Equal(Path.Combine("pedir", "Documents.Embedded.pdb"), pathQueried); Assert.Null(pdbPath); var pdbReader = pdbProvider.GetMetadataReader(); Assert.Equal(13, pdbReader.Documents.Count); } } [Fact] public void TryOpenAssociatedPortablePdb_EmbeddedOnly() { var peStream = new MemoryStream(PortablePdbs.DocumentsEmbeddedDll); using (var reader = new PEReader(peStream)) { MetadataReaderProvider pdbProvider; string pdbPath; Assert.True(reader.TryOpenAssociatedPortablePdb(@"x", _ => null, out pdbProvider, out pdbPath)); Assert.Null(pdbPath); var pdbReader = pdbProvider.GetMetadataReader(); Assert.Equal(13, pdbReader.Documents.Count); } } [Fact] public unsafe void TryOpenAssociatedPortablePdb_EmbeddedUnused() { var peStream = new MemoryStream(PortablePdbs.DocumentsEmbeddedDll); using (var reader = new PEReader(peStream)) { using (MetadataReaderProvider embeddedProvider = reader.ReadEmbeddedPortablePdbDebugDirectoryData(reader.ReadDebugDirectory()[2])) { var embeddedReader = embeddedProvider.GetMetadataReader(); var embeddedBytes = new BlobReader(embeddedReader.MetadataPointer, embeddedReader.MetadataLength).ReadBytes(embeddedReader.MetadataLength); string pathQueried = null; Func<string, Stream> streamProvider = p => { Assert.Null(pathQueried); pathQueried = p; return new MemoryStream(embeddedBytes); }; MetadataReaderProvider pdbProvider; string pdbPath; Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath)); Assert.Equal(Path.Combine("pedir", "Documents.Embedded.pdb"), pathQueried); Assert.Equal(Path.Combine("pedir", "Documents.Embedded.pdb"), pdbPath); var pdbReader = pdbProvider.GetMetadataReader(); Assert.Equal(13, pdbReader.Documents.Count); } } } [Fact] public void TryOpenAssociatedPortablePdb_UnixStylePath() { var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678); var ddBuilder = new DebugDirectoryBuilder(); ddBuilder.AddCodeViewEntry(@"/abc/def.xyz", id, portablePdbVersion: 0x0100); var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder)); using (var reader = new PEReader(peStream)) { string pathQueried = null; Func<string, Stream> streamProvider = p => { Assert.Null(pathQueried); pathQueried = p; return null; }; MetadataReaderProvider pdbProvider; string pdbPath; Assert.False(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath)); Assert.Equal(Path.Combine("pedir", "def.xyz"), pathQueried); } } [Fact] public void TryOpenAssociatedPortablePdb_WindowsSpecificPath() { var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678); var ddBuilder = new DebugDirectoryBuilder(); ddBuilder.AddCodeViewEntry(@"C:def.xyz", id, portablePdbVersion: 0x0100); var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder)); using (var reader = new PEReader(peStream)) { string pathQueried = null; Func<string, Stream> streamProvider = p => { Assert.Null(pathQueried); pathQueried = p; return null; }; MetadataReaderProvider pdbProvider; string pdbPath; Assert.False(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath)); Assert.Equal(Path.Combine("pedir", "def.xyz"), pathQueried); } } [Fact] public void TryOpenAssociatedPortablePdb_WindowsInvalidCharacters() { var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678); var ddBuilder = new DebugDirectoryBuilder(); ddBuilder.AddCodeViewEntry(@"/a/*/c*.pdb", id, portablePdbVersion: 0x0100); var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder)); using (var reader = new PEReader(peStream)) { string pathQueried = null; Func<string, Stream> streamProvider = p => { Assert.Null(pathQueried); pathQueried = p; return null; }; MetadataReaderProvider pdbProvider; string pdbPath; Assert.False(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath)); Assert.Equal(PathUtilities.CombinePathWithRelativePath("pedir", "c*.pdb"), pathQueried); } } [Fact] public void TryOpenAssociatedPortablePdb_DuplicateEntries_CodeView() { var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678); var ddBuilder = new DebugDirectoryBuilder(); ddBuilder.AddCodeViewEntry(@"/a/b/a.pdb", id, portablePdbVersion: 0); ddBuilder.AddReproducibleEntry(); ddBuilder.AddCodeViewEntry(@"/a/b/c.pdb", id, portablePdbVersion: 0x0100, age: 0x1234); ddBuilder.AddCodeViewEntry(@"/a/b/d.pdb", id, portablePdbVersion: 0x0100); var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder)); using (var reader = new PEReader(peStream)) { string pathQueried = null; Func<string, Stream> streamProvider = p => { Assert.Null(pathQueried); pathQueried = p; return null; }; MetadataReaderProvider pdbProvider; string pdbPath; Assert.False(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath)); Assert.Equal(PathUtilities.CombinePathWithRelativePath("pedir", "c.pdb"), pathQueried); } } [Fact] public void TryOpenAssociatedPortablePdb_DuplicateEntries_Embedded() { var pdbBuilder1 = new BlobBuilder(); pdbBuilder1.WriteBytes(PortablePdbs.DocumentsPdb); var pdbBuilder2 = new BlobBuilder(); pdbBuilder2.WriteByte(1); var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678); var ddBuilder = new DebugDirectoryBuilder(); ddBuilder.AddCodeViewEntry(@"/a/b/a.pdb", id, portablePdbVersion: 0x0100); ddBuilder.AddReproducibleEntry(); ddBuilder.AddEmbeddedPortablePdbEntry(pdbBuilder1, portablePdbVersion: 0x0100); ddBuilder.AddEmbeddedPortablePdbEntry(pdbBuilder2, portablePdbVersion: 0x0100); var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder)); using (var reader = new PEReader(peStream)) { string pathQueried = null; Func<string, Stream> streamProvider = p => { Assert.Null(pathQueried); pathQueried = p; return null; }; MetadataReaderProvider pdbProvider; string pdbPath; Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath)); Assert.Equal(PathUtilities.CombinePathWithRelativePath("pedir", "a.pdb"), pathQueried); Assert.Null(pdbPath); Assert.Equal(13, pdbProvider.GetMetadataReader().Documents.Count); } } [Fact] public void TryOpenAssociatedPortablePdb_CodeViewVsEmbedded_NonMatchingPdbId() { var pdbBuilder = new BlobBuilder(); pdbBuilder.WriteBytes(PortablePdbs.DocumentsPdb); var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678); var ddBuilder = new DebugDirectoryBuilder(); ddBuilder.AddCodeViewEntry(@"/a/b/a.pdb", id, portablePdbVersion: 0x0100); ddBuilder.AddEmbeddedPortablePdbEntry(pdbBuilder, portablePdbVersion: 0x0100); var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder)); using (var reader = new PEReader(peStream)) { string pathQueried = null; Func<string, Stream> streamProvider = p => { Assert.Null(pathQueried); pathQueried = p; // Doesn't match the id return new MemoryStream(PortablePdbs.DocumentsPdb); }; MetadataReaderProvider pdbProvider; string pdbPath; Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath)); Assert.Null(pdbPath); Assert.Equal(PathUtilities.CombinePathWithRelativePath("pedir", "a.pdb"), pathQueried); Assert.Equal(13, pdbProvider.GetMetadataReader().Documents.Count); } } [Fact] public void TryOpenAssociatedPortablePdb_BadPdbFile_FallbackToEmbedded() { var pdbBuilder = new BlobBuilder(); pdbBuilder.WriteBytes(PortablePdbs.DocumentsPdb); var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678); var ddBuilder = new DebugDirectoryBuilder(); ddBuilder.AddCodeViewEntry(@"/a/b/a.pdb", id, portablePdbVersion: 0x0100); ddBuilder.AddEmbeddedPortablePdbEntry(pdbBuilder, portablePdbVersion: 0x0100); var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder)); using (var reader = new PEReader(peStream)) { string pathQueried = null; Func<string, Stream> streamProvider = p => { Assert.Null(pathQueried); pathQueried = p; // Bad PDB return new MemoryStream(new byte[] { 0x01 }); }; MetadataReaderProvider pdbProvider; string pdbPath; Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath)); Assert.Null(pdbPath); Assert.Equal(PathUtilities.CombinePathWithRelativePath("pedir", "a.pdb"), pathQueried); Assert.Equal(13, pdbProvider.GetMetadataReader().Documents.Count); } } [Fact] public void TryOpenAssociatedPortablePdb_ExpectedExceptionFromStreamProvider_FallbackOnEmbedded_Valid() { var pdbBuilder = new BlobBuilder(); pdbBuilder.WriteBytes(PortablePdbs.DocumentsPdb); var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678); var ddBuilder = new DebugDirectoryBuilder(); ddBuilder.AddCodeViewEntry(@"/a/b/a.pdb", id, portablePdbVersion: 0x0100); ddBuilder.AddEmbeddedPortablePdbEntry(pdbBuilder, portablePdbVersion: 0x0100); var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder)); using (var reader = new PEReader(peStream)) { MetadataReaderProvider pdbProvider; string pdbPath; Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new IOException(); }, out pdbProvider, out pdbPath)); Assert.Null(pdbPath); Assert.Equal(13, pdbProvider.GetMetadataReader().Documents.Count); Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new BadImageFormatException(); }, out pdbProvider, out pdbPath)); Assert.Null(pdbPath); Assert.Equal(13, pdbProvider.GetMetadataReader().Documents.Count); Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new FileNotFoundException(); }, out pdbProvider, out pdbPath)); Assert.Null(pdbPath); Assert.Equal(13, pdbProvider.GetMetadataReader().Documents.Count); } } [Fact] public void TryOpenAssociatedPortablePdb_ExpectedExceptionFromStreamProvider_FallbackOnEmbedded_Invalid() { var pdbBuilder = new BlobBuilder(); pdbBuilder.WriteBytes(new byte[] { 0x01 }); var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678); var ddBuilder = new DebugDirectoryBuilder(); ddBuilder.AddCodeViewEntry(@"/a/b/a.pdb", id, portablePdbVersion: 0x0100); ddBuilder.AddEmbeddedPortablePdbEntry(pdbBuilder, portablePdbVersion: 0x0100); var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder)); using (var reader = new PEReader(peStream)) { MetadataReaderProvider pdbProvider; string pdbPath; // reports the first error: Assert.Throws<IOException>(() => reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new IOException(); }, out pdbProvider, out pdbPath)); // reports the first error: AssertEx.Throws<BadImageFormatException>(() => reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new BadImageFormatException("Bang!"); }, out pdbProvider, out pdbPath), e => Assert.Equal("Bang!", e.Message)); // file doesn't exist, fall back to embedded without reporting FileNotFoundExeception Assert.Throws<BadImageFormatException>(() => reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new FileNotFoundException(); }, out pdbProvider, out pdbPath)); Assert.Throws<BadImageFormatException>(() => reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => null, out pdbProvider, out pdbPath)); } } [Fact] public void TryOpenAssociatedPortablePdb_ExpectedExceptionFromStreamProvider_NoFallback() { var pdbBuilder = new BlobBuilder(); pdbBuilder.WriteBytes(PortablePdbs.DocumentsPdb); var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678); var ddBuilder = new DebugDirectoryBuilder(); ddBuilder.AddCodeViewEntry(@"/a/b/a.pdb", id, portablePdbVersion: 0x0100); var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder)); using (var reader = new PEReader(peStream)) { MetadataReaderProvider pdbProvider; string pdbPath; Assert.Throws<IOException>(() => reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new IOException(); }, out pdbProvider, out pdbPath)); AssertEx.Throws<BadImageFormatException>(() => reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new BadImageFormatException("Bang!"); }, out pdbProvider, out pdbPath), e => Assert.Equal("Bang!", e.Message)); // file doesn't exist and no embedded => return false Assert.False(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new FileNotFoundException(); }, out pdbProvider, out pdbPath)); } } [Fact] public void TryOpenAssociatedPortablePdb_BadStreamProvider() { var pdbBuilder = new BlobBuilder(); pdbBuilder.WriteBytes(PortablePdbs.DocumentsPdb); var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678); var ddBuilder = new DebugDirectoryBuilder(); ddBuilder.AddCodeViewEntry(@"/a/b/a.pdb", id, portablePdbVersion: 0x0100); var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder)); using (var reader = new PEReader(peStream)) { MetadataReaderProvider pdbProvider; string pdbPath; // pass-thru: AssertExtensions.Throws<ArgumentException>(null, () => reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new ArgumentException(); }, out pdbProvider, out pdbPath)); Assert.Throws<InvalidOperationException>(() => reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { return new TestStream(canRead: false, canWrite: true, canSeek: true); }, out pdbProvider, out pdbPath)); Assert.Throws<InvalidOperationException>(() => reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { return new TestStream(canRead: true, canWrite: true, canSeek: false); }, out pdbProvider, out pdbPath)); } } [Fact] public void Dispose() { var peStream = new MemoryStream(PortablePdbs.DocumentsEmbeddedDll); var reader = new PEReader(peStream); MetadataReaderProvider pdbProvider; string pdbPath; Assert.True(reader.TryOpenAssociatedPortablePdb(@"x", _ => null, out pdbProvider, out pdbPath)); Assert.NotNull(pdbProvider); Assert.Null(pdbPath); var ddEntries = reader.ReadDebugDirectory(); var ddCodeView = ddEntries[0]; var ddEmbedded = ddEntries[2]; var embeddedPdbProvider = reader.ReadEmbeddedPortablePdbDebugDirectoryData(ddEmbedded); // dispose the PEReader: reader.Dispose(); Assert.False(reader.IsEntireImageAvailable); Assert.Throws<ObjectDisposedException>(() => reader.PEHeaders); Assert.Throws<ObjectDisposedException>(() => reader.HasMetadata); Assert.Throws<ObjectDisposedException>(() => reader.GetMetadata()); Assert.Throws<ObjectDisposedException>(() => reader.GetSectionData(1000)); Assert.Throws<ObjectDisposedException>(() => reader.GetMetadataReader()); Assert.Throws<ObjectDisposedException>(() => reader.GetMethodBody(0)); Assert.Throws<ObjectDisposedException>(() => reader.GetEntireImage()); Assert.Throws<ObjectDisposedException>(() => reader.ReadDebugDirectory()); Assert.Throws<ObjectDisposedException>(() => reader.ReadCodeViewDebugDirectoryData(ddCodeView)); Assert.Throws<ObjectDisposedException>(() => reader.ReadEmbeddedPortablePdbDebugDirectoryData(ddEmbedded)); MetadataReaderProvider __; string ___; Assert.Throws<ObjectDisposedException>(() => reader.TryOpenAssociatedPortablePdb(@"x", _ => null, out __, out ___)); // ok to use providers after PEReader disposed: var pdbReader = pdbProvider.GetMetadataReader(); Assert.Equal(13, pdbReader.Documents.Count); pdbReader = embeddedPdbProvider.GetMetadataReader(); Assert.Equal(13, pdbReader.Documents.Count); embeddedPdbProvider.Dispose(); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; using System.Text; using Commands.Storage.ScenarioTest.BVT; using Commands.Storage.ScenarioTest.Common; using Commands.Storage.ScenarioTest.Util; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using MS.Test.Common.MsTestLib; using StorageTestLib; namespace Commands.Storage.ScenarioTest.Functional { /// <summary> /// function test for storage context /// </summary> [TestClass] class StorageContext: TestBase { [ClassInitialize()] public static void GetBlobClassInit(TestContext testContext) { TestBase.TestClassInitialize(testContext); } [ClassCleanup()] public static void GetBlobClassCleanup() { TestBase.TestClassCleanup(); } /// <summary> /// get containers from multiple storage contexts /// 8.19 New-AzureStorageContext Cmdlet Parameters Positive Functional Cases /// 9. Use pipeline to run PowerShell cmdlets for two valid accounts /// </summary> //TODO should add more test about context and pipeline in each cmdlet [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.StorageContext)] public void GetContainerFromMultipleStorageContext() { CloudStorageAccount account1 = TestBase.GetCloudStorageAccountFromConfig(); CloudStorageAccount account2 = TestBase.GetCloudStorageAccountFromConfig("Secondary"); string connectionString1 = account1.ToString(true); string connectionString2 = account2.ToString(true); Test.Assert(connectionString1 != connectionString2, "Use two different connection string {0} != {1}", connectionString1, connectionString2); CloudBlobUtil blobUtil1 = new CloudBlobUtil(account1); CloudBlobUtil blobUtil2 = new CloudBlobUtil(account2); string containerName = Utility.GenNameString("container"); try { CloudBlobContainer container1 = blobUtil1.CreateContainer(containerName); CloudBlobContainer container2 = blobUtil2.CreateContainer(containerName); int containerCount = 2; string cmd = String.Format("$context1 = new-azurestoragecontext -connectionstring '{0}';$context2 = new-azurestoragecontext -connectionstring '{1}';($context1, $context2)", connectionString1, connectionString2); agent.UseContextParam = false; ((PowerShellAgent)agent).AddPipelineScript(cmd); Test.Assert(agent.GetAzureStorageContainer(containerName), Utility.GenComparisonData("Get-AzureStorageContainer using multiple storage contexts", true)); Test.Assert(agent.Output.Count == containerCount, String.Format("Want to retrieve {0} page blob, but retrieved {1} page blobs", containerCount, agent.Output.Count)); agent.OutputValidation(new List<CloudBlobContainer>() { container1, container2 }); } finally { blobUtil1.RemoveContainer(containerName); blobUtil2.RemoveContainer(containerName); } } /// <summary> /// get containers from valid and invalid storage contexts /// 8.19 New-AzureStorageContext Negative Functional Cases /// 3. Use pipeline to run PowerShell cmdlets for one valid account and one invalid account /// </summary> //TODO should add more test about context and pipeline in each cmdlet [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.StorageContext)] public void GetContainerFromValidAndInvalidStorageContext() { CloudStorageAccount account1 = TestBase.GetCloudStorageAccountFromConfig(); string connectionString1 = account1.ToString(true); string randomAccountName = Utility.GenNameString("account"); string randomAccountKey = Utility.GenNameString("key"); randomAccountKey = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(randomAccountKey)); string containerName = Utility.GenNameString("container"); try { CloudBlobContainer container1 = blobUtil.CreateContainer(containerName); string cmd = String.Format("$context1 = new-azurestoragecontext -connectionstring '{0}';$context2 = new-azurestoragecontext -StorageAccountName '{1}' -StorageAccountKey '{2}';($context1, $context2)", connectionString1, randomAccountName, randomAccountKey); agent.UseContextParam = false; ((PowerShellAgent)agent).AddPipelineScript(cmd); Test.Assert(!agent.GetAzureStorageContainer(containerName), Utility.GenComparisonData("Get-AzureStorageContainer using valid and invalid storage contexts", false)); Test.Assert(agent.Output.Count == 1, "valid storage context should return 1 container"); Test.Assert(agent.ErrorMessages.Count == 1, "invalid storage context should return error"); //the same error may output different error messages in different environments bool expectedError = agent.ErrorMessages[0].StartsWith("The remote server returned an error: (502) Bad Gateway") || agent.ErrorMessages[0].StartsWith("The remote name could not be resolved") || agent.ErrorMessages[0].StartsWith("The operation has timed out"); Test.Assert(expectedError, "use invalid storage account should return 502 or could not be resolved exception or The operation has timed out, actully {0}", agent.ErrorMessages[0]); } finally { //TODO test the invalid storage account in subscription blobUtil.RemoveContainer(containerName); } } /// <summary> /// run cmdlet without storage context /// 8.19 New-AzureStorageContext Negative Functional Cases /// 1. Do not specify the context parameter in the parameter set for each cmdlet /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.StorageContext)] public void RunCmdletWithoutStorageContext() { PowerShellAgent.RemoveAzureSubscriptionIfExists(); CLICommonBVT.SaveAndCleanSubScriptionAndEnvConnectionString(); string containerName = Utility.GenNameString("container"); CloudBlobContainer container = blobUtil.CreateContainer(containerName); try { bool terminated = false; try { agent.GetAzureStorageContainer(containerName); } catch (CmdletInvocationException e) { terminated = true; Test.Info(e.Message); Test.Assert(e.Message.StartsWith("Can not find your azure storage credential."), "Can not find your azure storage credential."); } finally { if (!terminated) { Test.AssertFail("without storage context should return a terminating error"); } } } finally { blobUtil.RemoveContainer(containerName); } CLICommonBVT.RestoreSubScriptionAndEnvConnectionString(); } /// <summary> /// Get storage context with specified storage account name/key/endpoint /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.StorageContext)] public void GetStorageContextWithNameKeyEndPoint() { string accountName = Utility.GenNameString("account"); string accountKey = Utility.GenBase64String("key"); string endPoint = Utility.GenNameString("core.abc.def"); Test.Assert(agent.NewAzureStorageContext(accountName, accountKey, endPoint), "New storage context with specified name/key/endpoint should succeed"); // Verification for returned values Collection<Dictionary<string, object>> comp = GetContextCompareData(accountName, endPoint); agent.OutputValidation(comp); } /// <summary> /// Create anonymous storage context with specified end point /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.StorageContext)] public void GetAnonymousStorageContextEndPoint() { string accountName = Utility.GenNameString("account"); string accountKey = string.Empty; string endPoint = Utility.GenNameString("core.abc.def"); Test.Assert(agent.NewAzureStorageContext(accountName, accountKey, endPoint), "New storage context with specified name/key/endpoint should succeed"); // Verification for returned values Collection<Dictionary<string, object>> comp = GetContextCompareData(accountName, endPoint); comp[0]["StorageAccountName"] = "[Anonymous]"; agent.OutputValidation(comp); } /// <summary> /// Get Container with invalid endpoint /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.StorageContext)] public void GetContainerWithInvalidEndPoint() { string accountName = Utility.GenNameString("account"); string accountKey = Utility.GenBase64String("key"); string endPoint = Utility.GenNameString("core.abc.def"); string cmd = String.Format("new-azurestoragecontext -StorageAccountName {0} " + "-StorageAccountKey {1} -Endpoint {2}", accountName, accountKey, endPoint); ((PowerShellAgent)agent).AddPipelineScript(cmd); agent.UseContextParam = false; Test.Assert(!agent.GetAzureStorageContainer(string.Empty), "Get containers with invalid endpoint should fail"); ExpectedContainErrorMessage("The host was not found."); } /// <summary> /// Generate storage context compare data /// </summary> /// <param name="StorageAccountName">Storage Account Name</param> /// <param name="endPoint">end point</param> /// <returns>storage context compare data</returns> private Collection<Dictionary<string, object>> GetContextCompareData(string StorageAccountName, string endPoint) { Collection<Dictionary<string, object>> comp = new Collection<Dictionary<string, object>>(); string[] endPoints = Utility.GetStorageEndPoints(StorageAccountName, true, endPoint); comp.Add(new Dictionary<string, object>{ {"StorageAccountName", StorageAccountName}, {"BlobEndPoint", endPoints[0]}, {"QueueEndPoint", endPoints[1]}, {"TableEndPoint", endPoints[2]} }); return comp; } } }
using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using TranslatorService.Models.Translation; namespace TranslatorService { /// <summary> /// The <strong>ITranslatorClient</strong> interface specifies properties and methods to translate text in various supported languages. /// </summary> public interface ITranslatorClient : IDisposable { /// <summary> /// Gets or sets the Authentication URI for the Translator service. /// </summary> string AuthenticationUri { get; set; } /// <summary> /// Gets or sets the Subscription key that is necessary to use <strong>Microsoft Translator Service</strong>. /// </summary> /// <value>The Subscription Key.</value> /// <remarks> /// <para>You must register Microsoft Translator on https://portal.azure.com/#create/Microsoft.CognitiveServicesTextTranslation to obtain the Subscription key needed to use the service.</para> /// </remarks> string? SubscriptionKey { get; set; } /// <summary> /// Gets or sets the the Azure region of the the Translator service. /// </summary> /// <remarks>This value is used to automatically set the <see cref="AuthenticationUri"/> property. If the paramter is <strong>null</strong> (<strong>Nothing</strong> in Visual Basic), the global service is used. /// </remarks> string? Region { get; set; } /// <summary> /// Gets or sets the string representing the supported language code to translate the text in. /// </summary> /// <value>The string representing the supported language code to translate the text in. The code must be present in the list of codes returned from the method <see cref="GetLanguagesAsync"/>.</value> /// <seealso cref="GetLanguagesAsync"/> string Language { get; set; } /// <summary> /// Initializes the <see cref="TranslatorClient"/> class by getting an access token for the global (non region-dependent) service, using the current language. /// </summary> /// <returns>A <see cref="Task"/> that represents the initialize operation.</returns> /// <exception cref="ArgumentNullException">The <see cref="SubscriptionKey"/> property hasn't been set.</exception> /// <exception cref="TranslatorServiceException">The provided <see cref="SubscriptionKey"/> isn't valid or has expired.</exception> /// <remarks>Calling this method isn't mandatory, because the token is get/refreshed everytime is needed. However, it is called at startup, it can speed-up subsequest requests.</remarks> Task InitializeAsync(); /// <summary> /// Initializes the <see cref="TranslatorClient"/> class by getting an access token for a specified region service, using the given language. /// </summary> /// <param name="subscriptionKey">The subscription key for the Microsoft Translator Service on Azure.</param> /// <param name="region">The Azure region of the the Speech service. This value is used to automatically set the <see cref="AuthenticationUri"/> property. If the <em>region</em> paramter is <strong>null</strong> (<strong>Nothing</strong> in Visual Basic), the global service is used.</param> /// <param name="language">A string representing the supported language code to speak the text in. The code must be present in the list of codes returned from the method <see cref="GetLanguagesAsync"/>. If the <em>language</em> parameter is <strong>null</strong> (<strong>Nothing</strong> in Visual Basic), the current language is used.</param> /// <returns>A <see cref="Task"/> that represents the initialize operation.</returns> /// <exception cref="ArgumentNullException">The <see cref="SubscriptionKey"/> property hasn't been set.</exception> /// <exception cref="TranslatorServiceException">The provided <see cref="SubscriptionKey"/> isn't valid or has expired.</exception> /// <remarks> /// <para>Calling this method isn't mandatory, because the token is get/refreshed everytime is needed. However, it is called at startup, it can speed-up subsequest requests.</para> /// <para>You must register Microsoft Translator on https://portal.azure.com/#create/Microsoft.CognitiveServicesTextTranslation to obtain the Subscription key needed to use the service.</para> /// </remarks> Task InitializeAsync(string? subscriptionKey, string? region, string? language = null); /// <summary> /// Initializes the <see cref="TranslatorClient"/> class by getting an access token for a specified region service, using an existing <see cref="HttpClient"/>, using the given language. /// </summary> /// <param name="httpClient">An instance of the <see cref="HttpClient"/> object to use to network communication.</param> /// <param name="region">The Azure region of the the Speech service. This value is used to automatically set the <see cref="AuthenticationUri"/> property. If the <em>region</em> paramter is <strong>null</strong> (<strong>Nothing</strong> in Visual Basic), the global service is used.</param> /// <param name="subscriptionKey">The subscription key for the Microsoft Translator Service on Azure.</param> /// <param name="language">A string representing the supported language code to speak the text in. The code must be present in the list of codes returned from the method <see cref="GetLanguagesAsync"/>. If the <em>language</em> parameter is <strong>null</strong> (<strong>Nothing</strong> in Visual Basic), the current language is used.</param> /// <returns>A <see cref="Task"/> that represents the initialize operation.</returns> /// <exception cref="ArgumentNullException">The <see cref="SubscriptionKey"/> property hasn't been set.</exception> /// <exception cref="TranslatorServiceException">The provided <see cref="SubscriptionKey"/> isn't valid or has expired.</exception> /// <remarks> /// <para>Calling this method isn't mandatory, because the token is get/refreshed everytime is needed. However, it is called at startup, it can speed-up subsequest requests.</para> /// <para>You must register Microsoft Translator on https://portal.azure.com/#create/Microsoft.CognitiveServicesTextTranslation to obtain the Subscription key needed to use the service.</para> /// </remarks> /// <seealso cref="HttpClient"/> Task InitializeAsync(HttpClient? httpClient, string? region, string? subscriptionKey, string? language = null); /// <summary> /// Detects the language of a text. /// </summary> /// <param name="input">A string representing the text whose language must be detected.</param> /// <returns>A <see cref="DetectedLanguageResponse"/> object containing information about the detected language.</returns> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <term>The <see cref="SubscriptionKey"/> property hasn't been set.</term> /// <term>The <paramref name="input"/> parameter is <strong>null</strong> (<strong>Nothing</strong> in Visual Basic) or empty.</term> /// </list> /// </exception> /// <exception cref="TranslatorServiceException">The provided <see cref="SubscriptionKey"/> isn't valid or has expired.</exception> /// <remarks><para>This method performs a non-blocking request for language detection.</para> /// <para>For more information, go to https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-detect. /// </para></remarks> /// <seealso cref="GetLanguagesAsync"/> /// <seealso cref="Language"/> Task<DetectedLanguageResponse> DetectLanguageAsync(string input); /// <summary> /// Detects the language of a text. /// </summary> /// <param name="input">A string array containing the sentences whose language must be detected.</param> /// <returns>A <see cref="DetectedLanguageResponse"/> array with one result for each string in the input array. Each object contains information about the detected language.</returns> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <term>The <paramref name="input"/> parameter doesn't contain any element.</term> /// <term>The <paramref name="input"/> array contains more than 100 elements.</term> /// </list> /// </exception> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <term>The <see cref="SubscriptionKey"/> property hasn't been set.</term> /// <term>The <paramref name="input"/> array is <strong>null</strong> (<strong>Nothing</strong> in Visual Basic).</term> /// </list> /// </exception> /// <exception cref="TranslatorServiceException"> /// <list type="bullet"> /// <term>The provided <see cref="SubscriptionKey"/> isn't valid or has expired.</term> /// <term>The call to the method has encountered an unexpected error.</term> /// </list> /// </exception> /// <remarks><para>This method performs a non-blocking request for language detection.</para> /// <para>For more information, go to https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-detect. /// </para></remarks> /// <seealso cref="GetLanguagesAsync"/> /// <seealso cref="Language"/> Task<IEnumerable<DetectedLanguageResponse>> DetectLanguagesAsync(IEnumerable<string> input); /// <summary> /// Retrieves friendly names for the languages available for text translation. /// </summary> /// <param name="language">The language used to localize the language names. If the parameter is set to <strong>null</strong>, the language specified in the <seealso cref="Language"/> property will be used.</param> /// <returns>An array of <see cref="ServiceLanguage"/> containing the language codes and names supported for translation by <strong>Microsoft Translator Service</strong>.</returns> /// <exception cref="ArgumentNullException">The <see cref="SubscriptionKey"/> property hasn't been set.</exception> /// <exception cref="TranslatorServiceException"> /// <list type="bullet"> /// <term>The provided <see cref="SubscriptionKey"/> isn't valid or has expired.</term> /// <term>The call to the method has encountered an unexpected error.</term> /// </list> /// </exception> /// <remarks><para>This method performs a non-blocking request for language names.</para> /// <para>For more information, go to https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-languages. /// </para> /// </remarks> Task<IEnumerable<ServiceLanguage>> GetLanguagesAsync(string? language = null); /// <summary> /// Translates a text string into the specified language. /// </summary> /// <returns>A <see cref="TranslationResponse"/> object containing translated text and information.</returns> /// <param name="input">A string representing the text to translate.</param> /// <param name="to">A string representing the language code to translate the text into. The code must be present in the list of codes returned from the <see cref="GetLanguagesAsync"/> method. If the parameter is set to <strong>null</strong>, the language specified in the <seealso cref="Language"/> property will be used.</param> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <term>The <see cref="SubscriptionKey"/> property hasn't been set.</term> /// <term>The <paramref name="input"/> parameter is <strong>null</strong> (<strong>Nothing</strong> in Visual Basic) or empty.</term> /// </list> /// </exception> /// <exception cref="ArgumentException">The <paramref name="input"/> parameter is longer than 1000 characters.</exception> /// <exception cref="TranslatorServiceException"> /// <list type="bullet"> /// <term>The provided <see cref="SubscriptionKey"/> isn't valid or has expired.</term> /// <term>The call to the method has encountered an unexpected error.</term> /// </list> /// </exception> /// <remarks><para>This method perform a non-blocking request for text translation.</para> /// <para>For more information, go to https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate. /// </para> /// </remarks> /// <seealso cref="Language"/> /// <seealso cref="GetLanguagesAsync"/> Task<TranslationResponse> TranslateAsync(string input, string? to = null); /// <summary> /// Translates a text string into the specified languages. /// </summary> /// <returns>A <see cref="TranslationResponse"/> object containing translated text and information.</returns> /// <param name="input">A string representing the text to translate.</param> /// <param name="from">A string representing the language code of the original text. The code must be present in the list of codes returned from the <see cref="GetLanguagesAsync"/> method. If the parameter is set to <strong>null</strong>, the language specified in the <seealso cref="Language"/> property will be used.</param> /// <param name="to">A string representing the language code to translate the text into. The code must be present in the list of codes returned from the <see cref="GetLanguagesAsync"/> method. If the parameter is set to <strong>null</strong>, the language specified in the <seealso cref="Language"/> property will be used.</param> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <term>The <see cref="SubscriptionKey"/> property hasn't been set.</term> /// <term>The <paramref name="input"/> parameter is <strong>null</strong> (<strong>Nothing</strong> in Visual Basic) or empty.</term> /// </list> /// </exception> /// <exception cref="ArgumentException">The <paramref name="input"/> parameter is longer than 1000 characters.</exception> /// <exception cref="TranslatorServiceException"> /// <list type="bullet"> /// <term>The provided <see cref="SubscriptionKey"/> isn't valid or has expired.</term> /// <term>The call to the method has encountered an unexpected error.</term> /// </list> /// </exception> /// <remarks><para>This method perform a non-blocking request for text translation.</para> /// <para>For more information, go to https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate. /// </para> /// </remarks> /// <seealso cref="Language"/> /// <seealso cref="GetLanguagesAsync"/> Task<TranslationResponse> TranslateAsync(string input, string from, string to); /// <summary> /// Translates a list of sentences into the specified language. /// </summary> /// <returns>A <see cref="TranslationResponse"/> array with one result for each language code in the <paramref name="to"/> array. Each object contains translated text and information.</returns> /// <param name="input">A string array containing the sentences to translate.</param> /// <param name="from">A string representing the language code of the original text. The code must be present in the list of codes returned from the <see cref="GetLanguagesAsync"/> method. If the parameter is set to <strong>null</strong>, the language specified in the <seealso cref="Language"/> property will be used.</param> /// <param name="to">A string representing the language code to translate the text into. The code must be present in the list of codes returned from the <see cref="GetLanguagesAsync"/> method. If the parameter is set to <strong>null</strong>, the language specified in the <seealso cref="Language"/> property will be used.</param> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <term>The <see cref="SubscriptionKey"/> property hasn't been set.</term> /// <term>The <paramref name="input"/> parameter is <strong>null</strong> (<strong>Nothing</strong> in Visual Basic).</term> /// </list> /// </exception> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <term>The <paramref name="input"/> parameter is longer than 1000 characters.</term> /// <term>The <paramref name="input"/> array contains more than 25 elements.</term> /// </list> /// </exception> /// <exception cref="TranslatorServiceException"> /// <list type="bullet"> /// <term>The provided <see cref="SubscriptionKey"/> isn't valid or has expired.</term> /// <term>The call to the method has encountered an unexpected error.</term> /// </list> /// </exception> /// <remarks><para>This method perform a non-blocking request for text translation.</para> /// <para>For more information, go to https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate. /// </para> /// </remarks> /// <seealso cref="Language"/> /// <seealso cref="GetLanguagesAsync"/> Task<IEnumerable<TranslationResponse>> TranslateAsync(IEnumerable<string> input, string from, string to); /// <summary> /// Translates a text into the specified languages. /// </summary> /// <returns>A <see cref="TranslationResponse"/> object containing translated text and information.</returns> /// <param name="input">A string representing the text to translate.</param> /// <param name="from">A string representing the language code of the original text. The code must be present in the list of codes returned from the <see cref="GetLanguagesAsync"/> method. If the parameter is set to <strong>null</strong>, the language specified in the <seealso cref="Language"/> property will be used.</param> /// <param name="to">A string array representing the language codes to translate the text into. The code must be present in the list of codes returned from the <see cref="GetLanguagesAsync"/> method. If the parameter is set to <strong>null</strong>, the language specified in the <seealso cref="Language"/> property will be used.</param> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <term>The <see cref="SubscriptionKey"/> property hasn't been set.</term> /// <term>The <paramref name="input"/> parameter is <strong>null</strong> (<strong>Nothing</strong> in Visual Basic) or empty.</term> /// </list> /// </exception> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <term>The <paramref name="input"/> parameter is longer than 1000 characters.</term> /// <term>The <paramref name="to"/> array contains more than 25 elements.</term> /// </list> /// </exception> /// <exception cref="TranslatorServiceException"> /// <list type="bullet"> /// <term>The provided <see cref="SubscriptionKey"/> isn't valid or has expired.</term> /// <term>The call to the method has encountered an unexpected error.</term> /// </list> /// </exception> /// <remarks><para>This method perform a non-blocking request for text translation.</para> /// <para>For more information, go to https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate. /// </para> /// </remarks> /// <seealso cref="Language"/> /// <seealso cref="GetLanguagesAsync"/> Task<TranslationResponse> TranslateAsync(string input, string from, IEnumerable<string> to); /// <summary> /// Translates a text string into the specified languages. /// </summary> /// <returns>A <see cref="TranslationResponse"/> object containing translated text and information.</returns> /// <param name="input">A string representing the text to translate.</param> /// <param name="to">A string array representing the language codes to translate the text into. The code must be present in the list of codes returned from the <see cref="GetLanguagesAsync"/> method. If the parameter is set to <strong>null</strong>, the language specified in the <seealso cref="Language"/> property will be used.</param> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <term>The <see cref="SubscriptionKey"/> property hasn't been set.</term> /// <term>The <paramref name="input"/> parameter is <strong>null</strong> (<strong>Nothing</strong> in Visual Basic) or empty.</term> /// </list> /// </exception> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <term>The <paramref name="input"/> parameter is longer than 1000 characters.</term> /// <term>The <paramref name="to"/> array contains more than 25 elements.</term> /// </list> /// </exception> /// <exception cref="TranslatorServiceException"> /// <list type="bullet"> /// <term>The provided <see cref="SubscriptionKey"/> isn't valid or has expired.</term> /// <term>The call to the method has encountered an unexpected error.</term> /// </list> /// </exception> /// <remarks><para>This method perform a non-blocking request for text translation.</para> /// <para>For more information, go to https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate. /// </para> /// </remarks> /// <seealso cref="Language"/> /// <seealso cref="GetLanguagesAsync"/> Task<TranslationResponse> TranslateAsync(string input, IEnumerable<string> to); /// <summary> /// Translates a list of sentences into the specified languages. /// </summary> /// <returns>A <see cref="TranslationResponse"/> array with one result for each language code in the <paramref name="to"/> array. Each object contains translated text and information.</returns> /// <param name="input">A string array containing the sentences to translate.</param> /// <param name="to">A string array representing the language codes to translate the text into. The code must be present in the list of codes returned from the <see cref="GetLanguagesAsync"/> method. If the parameter is set to <strong>null</strong>, the language specified in the <seealso cref="Language"/> property will be used.</param> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <term>The <see cref="SubscriptionKey"/> property hasn't been set.</term> /// <term>The <paramref name="input"/> parameter is <strong>null</strong> (<strong>Nothing</strong> in Visual Basic).</term> /// </list> /// </exception> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <term>The <paramref name="input"/> parameter is longer than 1000 characters.</term> /// <term>The <paramref name="input"/> array contains more than 25 elements.</term> /// </list> /// </exception> /// <exception cref="TranslatorServiceException"> /// <list type="bullet"> /// <term>The provided <see cref="SubscriptionKey"/> isn't valid or has expired.</term> /// <term>The call to the method has encountered an unexpected error.</term> /// </list> /// </exception> /// <remarks><para>This method perform a non-blocking request for text translation.</para> /// <para>For more information, go to https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate. /// </para> /// </remarks> /// <seealso cref="Language"/> /// <seealso cref="GetLanguagesAsync"/> Task<IEnumerable<TranslationResponse>> TranslateAsync(IEnumerable<string> input, IEnumerable<string>? to = null); /// <summary> /// Translates a list of sentences into the specified languages. /// </summary> /// <returns>A <see cref="TranslationResponse"/> array with one result for each language code in the <paramref name="to"/> array. Each object contains translated text and information.</returns> /// <param name="input">A string array containing the sentences to translate.</param> /// <param name="from">A string representing the language code of the original text. The code must be present in the list of codes returned from the <see cref="GetLanguagesAsync"/> method. If the parameter is set to <strong>null</strong>, the language specified in the <seealso cref="Language"/> property will be used.</param> /// <param name="to">A string array representing the language codes to translate the text into. The code must be present in the list of codes returned from the <see cref="GetLanguagesAsync"/> method. If the parameter is set to <strong>null</strong>, the language specified in the <seealso cref="Language"/> property will be used.</param> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <term>The <see cref="SubscriptionKey"/> property hasn't been set.</term> /// <term>The <paramref name="input"/> parameter is <strong>null</strong> (<strong>Nothing</strong> in Visual Basic).</term> /// </list> /// </exception> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <term>The <paramref name="input"/> parameter is longer than 1000 characters.</term> /// <term>The <paramref name="input"/> array contains more than 25 elements.</term> /// </list> /// </exception> /// <exception cref="TranslatorServiceException"> /// <list type="bullet"> /// <term>The provided <see cref="SubscriptionKey"/> isn't valid or has expired.</term> /// <term>The call to the method has encountered an unexpected error.</term> /// </list> /// </exception> /// <remarks><para>This method perform a non-blocking request for text translation.</para> /// <para>For more information, go to https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate. /// </para> /// </remarks> /// <seealso cref="Language"/> /// <seealso cref="GetLanguagesAsync"/> Task<IEnumerable<TranslationResponse>> TranslateAsync(IEnumerable<string> input, string from, IEnumerable<string> to); } }
/* * 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 System.Reflection; using QuantConnect.Data; using QuantConnect.Interfaces; using QuantConnect.Orders; using QuantConnect.Securities; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// This regression algorithm tests Out of The Money (OTM) index option expiry for puts. /// We expect 2 orders from the algorithm, which are: /// /// * Initial entry, buy SPX Put Option (expiring OTM) /// - contract expires worthless, not exercised, so never opened a position in the underlying /// /// * Liquidation of worthless SPX Put OTM contract /// /// Additionally, we test delistings for index options and assert that our /// portfolio holdings reflect the orders the algorithm has submitted. /// </summary> /// <remarks> /// Total Trades in regression algorithm should be 1, but expiration is counted as a trade. /// </remarks> public class IndexOptionPutOTMExpiryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition { private Symbol _spx; private Symbol _spxOption; private Symbol _expectedContract; public override void Initialize() { SetStartDate(2021, 1, 4); SetEndDate(2021, 1, 31); _spx = AddIndex("SPX", Resolution.Minute).Symbol; // Select a index option expiring ITM, and adds it to the algorithm. _spxOption = AddIndexOptionContract(OptionChainProvider.GetOptionContractList(_spx, Time) .Where(x => x.ID.StrikePrice <= 3200m && x.ID.OptionRight == OptionRight.Put && x.ID.Date.Year == 2021 && x.ID.Date.Month == 1) .OrderByDescending(x => x.ID.StrikePrice) .Take(1) .Single(), Resolution.Minute).Symbol; _expectedContract = QuantConnect.Symbol.CreateOption(_spx, Market.USA, OptionStyle.European, OptionRight.Put, 3200m, new DateTime(2021, 1, 15)); if (_spxOption != _expectedContract) { throw new Exception($"Contract {_expectedContract} was not found in the chain"); } Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_spx, 1), () => { MarketOrder(_spxOption, 1); }); } public override void OnData(Slice data) { // Assert delistings, so that we can make sure that we receive the delisting warnings at // the expected time. These assertions detect bug #4872 foreach (var delisting in data.Delistings.Values) { if (delisting.Type == DelistingType.Warning) { if (delisting.Time != new DateTime(2021, 1, 15)) { throw new Exception($"Delisting warning issued at unexpected date: {delisting.Time}"); } } if (delisting.Type == DelistingType.Delisted) { if (delisting.Time != new DateTime(2021, 1, 16)) { throw new Exception($"Delisting happened at unexpected date: {delisting.Time}"); } } } } public override void OnOrderEvent(OrderEvent orderEvent) { if (orderEvent.Status != OrderStatus.Filled) { // There's lots of noise with OnOrderEvent, but we're only interested in fills. return; } if (!Securities.ContainsKey(orderEvent.Symbol)) { throw new Exception($"Order event Symbol not found in Securities collection: {orderEvent.Symbol}"); } var security = Securities[orderEvent.Symbol]; if (security.Symbol == _spx) { throw new Exception("Invalid state: did not expect a position for the underlying to be opened, since this contract expires OTM and is not tradable"); } if (security.Symbol == _expectedContract) { AssertIndexOptionContractOrder(orderEvent, security); } else { throw new Exception($"Received order event for unknown Symbol: {orderEvent.Symbol}"); } Log($"{orderEvent}"); } private void AssertIndexOptionContractOrder(OrderEvent orderEvent, Security option) { if (orderEvent.Direction == OrderDirection.Buy && option.Holdings.Quantity != 1) { throw new Exception($"No holdings were created for option contract {option.Symbol}"); } if (orderEvent.Direction == OrderDirection.Sell && option.Holdings.Quantity != 0) { throw new Exception("Holdings were found after a filled option exercise"); } if (orderEvent.Direction == OrderDirection.Sell && !orderEvent.Message.Contains("OTM")) { throw new Exception("Contract did not expire OTM"); } if (orderEvent.Message.Contains("Exercise")) { throw new Exception("Exercised option, even though it expires OTM"); } } /// <summary> /// Ran at the end of the algorithm to ensure the algorithm has no holdings /// </summary> /// <exception cref="Exception">The algorithm has holdings</exception> public override void OnEndOfAlgorithm() { if (Portfolio.Invested) { throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}"); } } /// <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", "2"}, {"Average Win", "0%"}, {"Average Loss", "-0.37%"}, {"Compounding Annual Return", "-5.132%"}, {"Drawdown", "0.400%"}, {"Expectancy", "-1"}, {"Net Profit", "-0.370%"}, {"Sharpe Ratio", "-3.622"}, {"Probabilistic Sharpe Ratio", "0.270%"}, {"Loss Rate", "100%"}, {"Win Rate", "0%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "-0.046"}, {"Beta", "0.007"}, {"Annual Standard Deviation", "0.013"}, {"Annual Variance", "0"}, {"Information Ratio", "-0.662"}, {"Tracking Error", "0.154"}, {"Treynor Ratio", "-6.383"}, {"Total Fees", "$0.00"}, {"Estimated Strategy Capacity", "$0"}, {"Lowest Capacity Asset", "SPX 31KC0UJFONTBI|SPX 31"}, {"Fitness Score", "0"}, {"Kelly Criterion Estimate", "0"}, {"Kelly Criterion Probability Value", "0"}, {"Sortino Ratio", "-1.628"}, {"Return Over Maximum Drawdown", "-14.021"}, {"Portfolio Turnover", "0"}, {"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", "6faffe52c64c2148458af1d2deb68a6f"} }; } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace WebApiContrib.Tracing.Slab.DemoApp.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Windows; using System.Windows.Media; using System.Windows.Ink; using System.Windows.Input; using System.Diagnostics; namespace MS.Internal.Ink { /// <summary> /// StrokeNodeOperations implementation for elliptical nodes /// </summary> internal class EllipticalNodeOperations : StrokeNodeOperations { /// <summary> /// Constructor /// </summary> /// <param name="nodeShape"></param> internal EllipticalNodeOperations(StylusShape nodeShape) : base(nodeShape) { System.Diagnostics.Debug.Assert((nodeShape != null) && nodeShape.IsEllipse); _radii = new Size(nodeShape.Width * 0.5, nodeShape.Height * 0.5); // All operations with ellipses become simple(r) if transfrom ellipses into circles. // Use the max of the radii for the radius of the circle _radius = Math.Max(_radii.Width, _radii.Height); // Compute ellipse-to-circle and circle-to-elliipse transforms. The former is used // in hit-testing operations while the latter is used when computing vertices of // a quadrangle connecting two ellipses _transform = nodeShape.Transform; _nodeShapeToCircle = _transform; Debug.Assert(_nodeShapeToCircle.HasInverse, "About to invert a non-invertible transform"); _nodeShapeToCircle.Invert(); if (DoubleUtil.AreClose(_radii.Width, _radii.Height)) { _circleToNodeShape = _transform; } else { // Reverse the rotation if (false == DoubleUtil.IsZero(nodeShape.Rotation)) { _nodeShapeToCircle.Rotate(-nodeShape.Rotation); Debug.Assert(_nodeShapeToCircle.HasInverse, "Just rotated an invertible transform and produced a non-invertible one"); } // Scale to enlarge double sx, sy; if (_radii.Width > _radii.Height) { sx = 1; sy = _radii.Width / _radii.Height; } else { sx = _radii.Height / _radii.Width; sy = 1; } _nodeShapeToCircle.Scale(sx, sy); Debug.Assert(_nodeShapeToCircle.HasInverse, "Just scaled an invertible transform and produced a non-invertible one"); _circleToNodeShape = _nodeShapeToCircle; _circleToNodeShape.Invert(); } } /// <summary> /// This is probably not the best (design-wise) but the cheapest way to tell /// EllipticalNodeOperations from all other implementations of node operations. /// </summary> internal override bool IsNodeShapeEllipse { get { return true; } } /// <summary> /// Finds connecting points for a pair of stroke nodes /// </summary> /// <param name="beginNode">a node to connect</param> /// <param name="endNode">another node, next to beginNode</param> /// <returns>connecting quadrangle</returns> internal override Quad GetConnectingQuad(in StrokeNodeData beginNode,in StrokeNodeData endNode) { if (beginNode.IsEmpty || endNode.IsEmpty || DoubleUtil.AreClose(beginNode.Position, endNode.Position)) { return Quad.Empty; } // Get the vector between the node positions Vector spine = endNode.Position - beginNode.Position; if (_nodeShapeToCircle.IsIdentity == false) { spine = _nodeShapeToCircle.Transform(spine); } double beginRadius = _radius * beginNode.PressureFactor; double endRadius = _radius * endNode.PressureFactor; // Get the vector and the distance between the node positions double distanceSquared = spine.LengthSquared; double delta = endRadius - beginRadius; double deltaSquared = DoubleUtil.IsZero(delta) ? 0 : (delta * delta); if (DoubleUtil.LessThanOrClose(distanceSquared, deltaSquared)) { // One circle is contained within the other return Quad.Empty; } // Thus, at this point, distance > 0, which avoids the DivideByZero error // Also, here, distanceSquared > deltaSquared // Thus, 0 <= rSin < 1 // Get the components of the radius vectors double distance = Math.Sqrt(distanceSquared); spine /= distance; Vector rad = spine; // Turn left double temp = rad.Y; rad.Y = -rad.X; rad.X = temp; Vector vectorToLeftTangent, vectorToRightTangent; double rSinSquared = deltaSquared / distanceSquared; if (DoubleUtil.IsZero(rSinSquared)) { vectorToLeftTangent = rad; vectorToRightTangent = -rad; } else { rad *= Math.Sqrt(1 - rSinSquared); spine *= Math.Sqrt(rSinSquared); if (beginNode.PressureFactor < endNode.PressureFactor) { spine = -spine; } vectorToLeftTangent = spine + rad; vectorToRightTangent = spine - rad; } // Get the common tangent points if (_circleToNodeShape.IsIdentity == false) { vectorToLeftTangent = _circleToNodeShape.Transform(vectorToLeftTangent); vectorToRightTangent = _circleToNodeShape.Transform(vectorToRightTangent); } return new Quad(beginNode.Position + (vectorToLeftTangent * beginRadius), endNode.Position + (vectorToLeftTangent * endRadius), endNode.Position + (vectorToRightTangent * endRadius), beginNode.Position + (vectorToRightTangent * beginRadius)); } /// <summary> /// /// </summary> /// <param name="node"></param> /// <param name="quad"></param> /// <returns></returns> internal override IEnumerable<ContourSegment> GetContourSegments(StrokeNodeData node, Quad quad) { System.Diagnostics.Debug.Assert(node.IsEmpty == false); if (quad.IsEmpty) { Point point = node.Position; point.X += _radius; yield return new ContourSegment(point, point, node.Position); } else if (_nodeShapeToCircle.IsIdentity) { yield return new ContourSegment(quad.A, quad.B); yield return new ContourSegment(quad.B, quad.C, node.Position); yield return new ContourSegment(quad.C, quad.D); yield return new ContourSegment(quad.D, quad.A); } } /// <summary> /// ISSUE-2004/06/15- temporary workaround to avoid hit-testing ellipses with ellipses /// </summary> /// <param name="beginNode"></param> /// <param name="endNode"></param> /// <returns></returns> internal override IEnumerable<ContourSegment> GetNonBezierContourSegments(StrokeNodeData beginNode, StrokeNodeData endNode) { Quad quad = beginNode.IsEmpty ? Quad.Empty : base.GetConnectingQuad(beginNode, endNode); return base.GetContourSegments(endNode, quad); } /// <summary> /// Hit-tests a stroke segment defined by two nodes against a linear segment. /// </summary> /// <param name="beginNode">Begin node of the stroke segment to hit-test. Can be empty (none)</param> /// <param name="endNode">End node of the stroke segment</param> /// <param name="quad">Pre-computed quadrangle connecting the two nodes. /// Can be empty if the begion node is empty or when one node is entirely inside the other</param> /// <param name="hitBeginPoint">an end point of the hitting linear segment</param> /// <param name="hitEndPoint">an end point of the hitting linear segment</param> /// <returns>true if the hitting segment intersect the contour comprised of the two stroke nodes</returns> internal override bool HitTest( in StrokeNodeData beginNode, in StrokeNodeData endNode, Quad quad, Point hitBeginPoint, Point hitEndPoint) { StrokeNodeData bigNode, smallNode; if (beginNode.IsEmpty || (quad.IsEmpty && (endNode.PressureFactor > beginNode.PressureFactor))) { // Need to test one node only bigNode = endNode; smallNode = StrokeNodeData.Empty; } else { // In this case the size doesn't matter. bigNode = beginNode; smallNode = endNode; } // Compute the positions of the involved points relative to bigNode. Vector hitBegin = hitBeginPoint - bigNode.Position; Vector hitEnd = hitEndPoint - bigNode.Position; // If the node shape is an ellipse, transform the scene to turn the shape to a circle if (_nodeShapeToCircle.IsIdentity == false) { hitBegin = _nodeShapeToCircle.Transform(hitBegin); hitEnd = _nodeShapeToCircle.Transform(hitEnd); } bool isHit = false; // Hit-test the big node double bigRadius = _radius * bigNode.PressureFactor; Vector nearest = GetNearest(hitBegin, hitEnd); if (nearest.LengthSquared <= (bigRadius * bigRadius)) { isHit = true; } else if (quad.IsEmpty == false) { // Hit-test the other node Vector spineVector = smallNode.Position - bigNode.Position; if (_nodeShapeToCircle.IsIdentity == false) { spineVector = _nodeShapeToCircle.Transform(spineVector); } double smallRadius = _radius * smallNode.PressureFactor; nearest = GetNearest(hitBegin - spineVector, hitEnd - spineVector); if ((nearest.LengthSquared <= (smallRadius * smallRadius)) || HitTestQuadSegment(quad, hitBeginPoint, hitEndPoint)) { isHit = true; } } return isHit; } /// <summary> /// Hit-tests a stroke segment defined by two nodes against another stroke segment. /// </summary> /// <param name="beginNode">Begin node of the stroke segment to hit-test. Can be empty (none)</param> /// <param name="endNode">End node of the stroke segment</param> /// <param name="quad">Pre-computed quadrangle connecting the two nodes. /// Can be empty if the begion node is empty or when one node is entirely inside the other</param> /// <param name="hitContour">a collection of basic segments outlining the hitting contour</param> /// <returns>true if the contours intersect or overlap</returns> internal override bool HitTest( in StrokeNodeData beginNode, in StrokeNodeData endNode, Quad quad, IEnumerable<ContourSegment> hitContour) { StrokeNodeData bigNode, smallNode; double bigRadiusSquared, smallRadiusSquared = 0; Vector spineVector; if (beginNode.IsEmpty || (quad.IsEmpty && (endNode.PressureFactor > beginNode.PressureFactor))) { // Need to test one node only bigNode = endNode; smallNode = StrokeNodeData.Empty; spineVector = new Vector(); } else { // In this case the size doesn't matter. bigNode = beginNode; smallNode = endNode; smallRadiusSquared = _radius * smallNode.PressureFactor; smallRadiusSquared *= smallRadiusSquared; // Find position of smallNode relative to the bigNode. spineVector = smallNode.Position - bigNode.Position; // If the node shape is an ellipse, transform the scene to turn the shape to a circle if (_nodeShapeToCircle.IsIdentity == false) { spineVector = _nodeShapeToCircle.Transform(spineVector); } } bigRadiusSquared = _radius * bigNode.PressureFactor; bigRadiusSquared *= bigRadiusSquared; bool isHit = false; // When hit-testing a contour against another contour, like in this case, // the default implementation checks whether any edge (segment) of the hitting // contour intersects with the contour of the ink segment. But this doesn't cover // the case when the ink segment is entirely inside of the hitting segment. // The bool variable isInside is used here to track that case. It answers the question // 'Is ink contour inside if the hitting contour?'. It's initialized to 'true" // and then verified for each edge of the hitting contour until there's a hit or // until it's false. bool isInside = true; foreach (ContourSegment hitSegment in hitContour) { if (hitSegment.IsArc) { // ISSUE-2004/06/15-vsmirnov - ellipse vs arc hit-testing is not implemented // and currently disabled in ErasingStroke } else { // Find position of the hitting segment relative to bigNode transformed to circle. Vector hitBegin = hitSegment.Begin - bigNode.Position; Vector hitEnd = hitBegin + hitSegment.Vector; if (_nodeShapeToCircle.IsIdentity == false) { hitBegin = _nodeShapeToCircle.Transform(hitBegin); hitEnd = _nodeShapeToCircle.Transform(hitEnd); } // Hit-test the big node Vector nearest = GetNearest(hitBegin, hitEnd); if (nearest.LengthSquared <= bigRadiusSquared) { isHit = true; break; } // Hit-test the other node if (quad.IsEmpty == false) { nearest = GetNearest(hitBegin - spineVector, hitEnd - spineVector); if ((nearest.LengthSquared <= smallRadiusSquared) || HitTestQuadSegment(quad, hitSegment.Begin, hitSegment.End)) { isHit = true; break; } } // While there's still a chance to find the both nodes inside the hitting contour, // continue checking on position of the endNode relative to the edges of the hitting contour. if (isInside && (WhereIsVectorAboutVector(endNode.Position - hitSegment.Begin, hitSegment.Vector) != HitResult.Right)) { isInside = false; } } } return (isHit || isInside); } /// <summary> /// Cut-test ink segment defined by two nodes and a connecting quad against a linear segment /// </summary> /// <param name="beginNode">Begin node of the ink segment</param> /// <param name="endNode">End node of the ink segment</param> /// <param name="quad">Pre-computed quadrangle connecting the two ink nodes</param> /// <param name="hitBeginPoint">egin point of the hitting segment</param> /// <param name="hitEndPoint">End point of the hitting segment</param> /// <returns>Exact location to cut at represented by StrokeFIndices</returns> internal override StrokeFIndices CutTest( in StrokeNodeData beginNode, in StrokeNodeData endNode, Quad quad, Point hitBeginPoint, Point hitEndPoint) { // Compute the positions of the involved points relative to the endNode. Vector spineVector = beginNode.IsEmpty ? new Vector(0, 0) : (beginNode.Position - endNode.Position); Vector hitBegin = hitBeginPoint - endNode.Position; Vector hitEnd = hitEndPoint - endNode.Position; // If the node shape is an ellipse, transform the scene to turn the shape to a circle if (_nodeShapeToCircle.IsIdentity == false) { spineVector = _nodeShapeToCircle.Transform(spineVector); hitBegin = _nodeShapeToCircle.Transform(hitBegin); hitEnd = _nodeShapeToCircle.Transform(hitEnd); } StrokeFIndices result = StrokeFIndices.Empty; // Hit-test the end node double beginRadius = 0, endRadius = _radius * endNode.PressureFactor; Vector nearest = GetNearest(hitBegin, hitEnd); if (nearest.LengthSquared <= (endRadius * endRadius)) { result.EndFIndex = StrokeFIndices.AfterLast; result.BeginFIndex = beginNode.IsEmpty ? StrokeFIndices.BeforeFirst : 1; } if (beginNode.IsEmpty == false) { // Hit-test the first node beginRadius = _radius * beginNode.PressureFactor; nearest = GetNearest(hitBegin - spineVector, hitEnd - spineVector); if (nearest.LengthSquared <= (beginRadius * beginRadius)) { result.BeginFIndex = StrokeFIndices.BeforeFirst; if (!DoubleUtil.AreClose(result.EndFIndex, StrokeFIndices.AfterLast)) { result.EndFIndex = 0; } } } // If both nodes are hit or nothing is hit at all, return. if (result.IsFull || quad.IsEmpty || (result.IsEmpty && (HitTestQuadSegment(quad, hitBeginPoint, hitEndPoint) == false))) { return result; } // Find out whether the {begin, end} segment intersects with the contour // of the stroke segment {_lastNode, _thisNode}, and find the lower index // of the fragment to cut out. if (!DoubleUtil.AreClose(result.BeginFIndex, StrokeFIndices.BeforeFirst)) { result.BeginFIndex = ClipTest(-spineVector, beginRadius, endRadius, hitBegin - spineVector, hitEnd - spineVector); } if (!DoubleUtil.AreClose(result.EndFIndex, StrokeFIndices.AfterLast)) { result.EndFIndex = 1 - ClipTest(spineVector, endRadius, beginRadius, hitBegin, hitEnd); } if (IsInvalidCutTestResult(result)) { return StrokeFIndices.Empty; } return result; } /// <summary> /// CutTest an inking StrokeNode segment (two nodes and a connecting quadrangle) against a hitting contour /// (represented by an enumerator of Contoursegments). /// </summary> /// <param name="beginNode">The begin StrokeNodeData</param> /// <param name="endNode">The end StrokeNodeData</param> /// <param name="quad">Connecing quadrangle between the begin and end inking node</param> /// <param name="hitContour">The hitting ContourSegments</param> /// <returns>StrokeFIndices representing the location for cutting</returns> internal override StrokeFIndices CutTest( in StrokeNodeData beginNode, in StrokeNodeData endNode, Quad quad, IEnumerable<ContourSegment> hitContour) { // Compute the positions of the beginNode relative to the endNode. Vector spineVector = beginNode.IsEmpty ? new Vector(0, 0) : (beginNode.Position - endNode.Position); // If the node shape is an ellipse, transform the scene to turn the shape to a circle if (_nodeShapeToCircle.IsIdentity == false) { spineVector = _nodeShapeToCircle.Transform(spineVector); } double beginRadius = 0, endRadius; double beginRadiusSquared = 0, endRadiusSquared; endRadius = _radius * endNode.PressureFactor; endRadiusSquared = endRadius * endRadius; if (beginNode.IsEmpty == false) { beginRadius = _radius * beginNode.PressureFactor; beginRadiusSquared = beginRadius * beginRadius; } bool isInside = true; StrokeFIndices result = StrokeFIndices.Empty; foreach (ContourSegment hitSegment in hitContour) { if (hitSegment.IsArc) { // ISSUE-2004/06/15-vsmirnov - ellipse vs arc hit-testing is not implemented // and currently disabled in ErasingStroke } else { Vector hitBegin = hitSegment.Begin - endNode.Position; Vector hitEnd = hitBegin + hitSegment.Vector; // If the node shape is an ellipse, transform the scene to turn // the shape into circle. if (_nodeShapeToCircle.IsIdentity == false) { hitBegin = _nodeShapeToCircle.Transform(hitBegin); hitEnd = _nodeShapeToCircle.Transform(hitEnd); } bool isHit = false; // Hit-test the end node Vector nearest = GetNearest(hitBegin, hitEnd); if (nearest.LengthSquared < endRadiusSquared) { isHit = true; if (!DoubleUtil.AreClose(result.EndFIndex, StrokeFIndices.AfterLast)) { result.EndFIndex = StrokeFIndices.AfterLast; if (beginNode.IsEmpty) { result.BeginFIndex = StrokeFIndices.BeforeFirst; break; } if (DoubleUtil.AreClose(result.BeginFIndex, StrokeFIndices.BeforeFirst)) { break; } } } if ((beginNode.IsEmpty == false) && (!isHit || !DoubleUtil.AreClose(result.BeginFIndex, StrokeFIndices.BeforeFirst))) { // Hit-test the first node nearest = GetNearest(hitBegin - spineVector, hitEnd - spineVector); if (nearest.LengthSquared < beginRadiusSquared) { isHit = true; if (!DoubleUtil.AreClose(result.BeginFIndex, StrokeFIndices.BeforeFirst)) { result.BeginFIndex = StrokeFIndices.BeforeFirst; if (DoubleUtil.AreClose(result.EndFIndex, StrokeFIndices.AfterLast)) { break; } } } } // If both nodes are hit or nothing is hit at all, return. if (beginNode.IsEmpty || (!isHit && (quad.IsEmpty || (HitTestQuadSegment(quad, hitSegment.Begin, hitSegment.End) == false)))) { if (isInside && (WhereIsVectorAboutVector( endNode.Position - hitSegment.Begin, hitSegment.Vector) != HitResult.Right)) { isInside = false; } continue; } isInside = false; // Calculate the exact locations to cut. CalculateCutLocations(spineVector, hitBegin, hitEnd, endRadius, beginRadius, ref result); if (result.IsFull) { break; } } } // if (!result.IsFull) { if (isInside == true) { System.Diagnostics.Debug.Assert(result.IsEmpty); result = StrokeFIndices.Full; } else if ((DoubleUtil.AreClose(result.EndFIndex, StrokeFIndices.BeforeFirst)) && (!DoubleUtil.AreClose(result.BeginFIndex, StrokeFIndices.AfterLast))) { result.EndFIndex = StrokeFIndices.AfterLast; } else if ((DoubleUtil.AreClose(result.BeginFIndex,StrokeFIndices.AfterLast)) && (!DoubleUtil.AreClose(result.EndFIndex, StrokeFIndices.BeforeFirst))) { result.BeginFIndex = StrokeFIndices.BeforeFirst; } } if (IsInvalidCutTestResult(result)) { return StrokeFIndices.Empty; } return result; } /// <summary> /// Clip-Testing a circluar inking segment against a linear segment. /// See http://tabletpc/longhorn/Specs/Rendering%20and%20Hit-Testing%20Ink%20in%20Avalon%20M11.doc section /// 5.4.4.14 Clip-Testing a Circular Inking Segment against a Linear Segment for details of the algorithm /// </summary> /// <param name="spineVector">Represent the spine of the inking segment pointing from the beginNode to endNode</param> /// <param name="beginRadius">Radius of the beginNode</param> /// <param name="endRadius">Radius of the endNode</param> /// <param name="hitBegin">Hitting segment start point</param> /// <param name="hitEnd">Hitting segment end point</param> /// <returns>A double which represents the location for cutting</returns> private static double ClipTest(Vector spineVector, double beginRadius, double endRadius, Vector hitBegin, Vector hitEnd) { // First handle the special case when the spineVector is (0,0). In other words, this is the case // when the stylus stays at the the location but pressure changes. if (DoubleUtil.IsZero(spineVector.X) && DoubleUtil.IsZero(spineVector.Y)) { System.Diagnostics.Debug.Assert(DoubleUtil.AreClose(beginRadius, endRadius) == false); Vector nearest = GetNearest(hitBegin, hitEnd); double radius; if (nearest.X == 0) { radius = Math.Abs(nearest.Y); } else if (nearest.Y == 0) { radius = Math.Abs(nearest.X); } else { radius = nearest.Length; } return AdjustFIndex((radius - beginRadius) / (endRadius - beginRadius)); } // This change to ClipTest with a point if the two hitting segment are close enough. if (DoubleUtil.AreClose(hitBegin, hitEnd)) { return ClipTest(spineVector, beginRadius, endRadius, hitBegin); } double findex; Vector hitVector = hitEnd - hitBegin; if (DoubleUtil.IsZero(Vector.Determinant(spineVector, hitVector))) { // hitVector and spineVector are parallel findex = ClipTest(spineVector, beginRadius, endRadius, GetNearest(hitBegin, hitEnd)); System.Diagnostics.Debug.Assert(!double.IsNaN(findex)); } else { // On the line defined by the segment find point P1Xp, the nearest to the beginNode.Position double x = GetProjectionFIndex(hitBegin, hitEnd); Vector P1Xp = hitBegin + (hitVector * x); if (P1Xp.LengthSquared < (beginRadius * beginRadius)) { System.Diagnostics.Debug.Assert(DoubleUtil.IsBetweenZeroAndOne(x) == false); findex = ClipTest(spineVector, beginRadius, endRadius, (0 > x) ? hitBegin : hitEnd); System.Diagnostics.Debug.Assert(!double.IsNaN(findex)); } else { // Find the projection point P of endNode.Position to the line (beginNode.Position, B). Vector P1P2p = spineVector + GetProjection(-spineVector, P1Xp - spineVector); //System.Diagnostics.Debug.Assert(false == DoubleUtil.IsZero(P1P2p.LengthSquared)); //System.Diagnostics.Debug.Assert(false == DoubleUtil.IsZero(endRadius - beginRadius + P1P2p.Length)); // There checks are here since if either fail no real solution can be caculated and we may // as well bail out now and save the caculations that are below. if (DoubleUtil.IsZero(P1P2p.LengthSquared) || DoubleUtil.IsZero(endRadius - beginRadius + P1P2p.Length)) return 1d; // Calculate the findex of the point to split the ink segment at. findex = (P1Xp.Length - beginRadius) / (endRadius - beginRadius + P1P2p.Length); System.Diagnostics.Debug.Assert(!double.IsNaN(findex)); // Find the projection of the split point to the line of this segment. Vector S = spineVector * findex; double r = GetProjectionFIndex(hitBegin - S, hitEnd - S); // If the nearest point misses the segment, then find the findex // of the node nearest to the segment. if (false == DoubleUtil.IsBetweenZeroAndOne(r)) { findex = ClipTest(spineVector, beginRadius, endRadius, (0 > r) ? hitBegin : hitEnd); System.Diagnostics.Debug.Assert(!double.IsNaN(findex)); } } } return AdjustFIndex(findex); } /// <summary> /// Clip-Testing a circular inking segment again a hitting point. /// /// What need to find out a doulbe value s, which is between 0 and 1, such that /// DistanceOf(hit - s*spine) = beginRadius + s * (endRadius - beginRadius) /// That is /// (hit.X-s*spine.X)^2 + (hit.Y-s*spine.Y)^2 = [beginRadius + s*(endRadius-beginRadius)]^2 /// Rearrange /// A*s^2 + B*s + C = 0 /// where the value of A, B and C are described in the source code. /// Solving for s: /// s = (-B + sqrt(B^2-4A*C))/(2A) or s = (-B - sqrt(B^2-4A*C))/(2A) /// The smaller value between 0 and 1 is the one we want and discard the other one. /// </summary> /// <param name="spine">Represent the spine of the inking segment pointing from the beginNode to endNode</param> /// <param name="beginRadius">Radius of the beginNode</param> /// <param name="endRadius">Radius of the endNode</param> /// <param name="hit">The hitting point</param> /// <returns>A double which represents the location for cutting</returns> private static double ClipTest(Vector spine, double beginRadius, double endRadius, Vector hit) { double radDiff = endRadius - beginRadius; double A = spine.X*spine.X + spine.Y*spine.Y - radDiff*radDiff; double B = -2.0f*(hit.X*spine.X + hit.Y * spine.Y + beginRadius*radDiff); double C = hit.X * hit.X + hit.Y * hit.Y - beginRadius * beginRadius; // There checks are here since if either fail no real solution can be caculated and we may // as well bail out now and save the caculations that are below. if (DoubleUtil.IsZero(A) || !DoubleUtil.GreaterThanOrClose(B*B, 4.0f*A*C)) return 1d; double tmp = Math.Sqrt(B*B-4.0f * A * C); double s1 = (-B + tmp)/(2.0f * A); double s2 = (-B - tmp)/(2.0f * A); double findex; if (DoubleUtil.IsBetweenZeroAndOne(s1) && DoubleUtil.IsBetweenZeroAndOne(s1)) { findex = Math.Min(s1, s2); } else if (DoubleUtil.IsBetweenZeroAndOne(s1)) { findex = s1; } else if (DoubleUtil.IsBetweenZeroAndOne(s2)) { findex = s2; } else { // There is still possiblity that value like 1.0000000000000402 is not considered // as "IsOne" by DoubleUtil class. We should be at either one of the following two cases: // 1. s1/s2 around 0 but not close enough (say -0.0000000000001) // 2. s1/s2 around 1 but not close enought (say 1.0000000000000402) if (s1 > 1d && s2 > 1d) { findex = 1d; } else if (s1 < 0d && s2 < 0d) { findex = 0d; } else { findex = Math.Abs(Math.Min(s1, s2) - 0d) < Math.Abs(Math.Max(s1, s2) - 1d) ? 0d : 1d; } } return AdjustFIndex(findex); } /// <summary> /// Helper function to find out the relative location of a segment {segBegin, segEnd} against /// a strokeNode (spine). /// </summary> /// <param name="spine">the spineVector of the StrokeNode</param> /// <param name="segBegin">Start position of the line segment</param> /// <param name="segEnd">End position of the line segment</param> /// <returns>HitResult</returns> private static HitResult WhereIsNodeAboutSegment(Vector spine, Vector segBegin, Vector segEnd) { HitResult whereabout = HitResult.Right; Vector segVector = segEnd - segBegin; if ((WhereIsVectorAboutVector(-segBegin, segVector) == HitResult.Left) && !DoubleUtil.IsZero(Vector.Determinant(spine, segVector))) { whereabout = HitResult.Left; } return whereabout; } /// <summary> /// Helper method to calculate the exact location to cut /// </summary> /// <param name="spineVector">Vector the relative location of the two inking nodes</param> /// <param name="hitBegin">the begin point of the hitting segment</param> /// <param name="hitEnd">the end point of the hitting segment</param> /// <param name="endRadius">endNode radius</param> /// <param name="beginRadius">beginNode radius</param> /// <param name="result">StrokeFIndices representing the location for cutting</param> private void CalculateCutLocations( Vector spineVector, Vector hitBegin, Vector hitEnd, double endRadius, double beginRadius, ref StrokeFIndices result) { // Find out whether the {hitBegin, hitEnd} segment intersects with the contour // of the stroke segment, and find the lower index of the fragment to cut out. if (!DoubleUtil.AreClose(result.EndFIndex, StrokeFIndices.AfterLast)) { if (WhereIsNodeAboutSegment(spineVector, hitBegin, hitEnd) == HitResult.Left) { double findex = 1 - ClipTest(spineVector, endRadius, beginRadius, hitBegin, hitEnd); if (findex > result.EndFIndex) { result.EndFIndex = findex; } } } // Find out whether the {hitBegin, hitEnd} segment intersects with the contour // of the stroke segment, and find the higher index of the fragment to cut out. if (!DoubleUtil.AreClose(result.BeginFIndex, StrokeFIndices.BeforeFirst)) { hitBegin -= spineVector; hitEnd -= spineVector; if (WhereIsNodeAboutSegment(-spineVector, hitBegin, hitEnd) == HitResult.Left) { double findex = ClipTest(-spineVector, beginRadius, endRadius, hitBegin, hitEnd); if (findex < result.BeginFIndex) { result.BeginFIndex = findex; } } } } private double _radius = 0; private Size _radii; private Matrix _transform; private Matrix _nodeShapeToCircle; private Matrix _circleToNodeShape; } }
// 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.Threading; using Xunit; public class ChangedTests { [Fact] [ActiveIssue(2011, PlatformID.OSX)] public static void FileSystemWatcher_Changed_LastWrite_File() { using (var file = Utility.CreateTestFile()) using (var watcher = new FileSystemWatcher(".")) { watcher.Filter = Path.GetFileName(file.Path); AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); watcher.EnableRaisingEvents = true; File.SetLastWriteTime(file.Path, DateTime.Now + TimeSpan.FromSeconds(10)); Utility.ExpectEvent(eventOccured, "changed"); } } [Fact] [ActiveIssue(2011, PlatformID.OSX)] public static void FileSystemWatcher_Changed_LastWrite_Directory() { using (var dir = Utility.CreateTestDirectory()) using (var watcher = new FileSystemWatcher(".")) { watcher.Filter = Path.GetFileName(dir.Path); AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); watcher.EnableRaisingEvents = true; Directory.SetLastWriteTime(dir.Path, DateTime.Now + TimeSpan.FromSeconds(10)); Utility.ExpectEvent(eventOccured, "changed"); } } [Fact] public static void FileSystemWatcher_Changed_Negative() { using (var dir = Utility.CreateTestDirectory()) using (var watcher = new FileSystemWatcher()) { // put everything in our own directory to avoid collisions watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*.*"; AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); // run all scenarios together to avoid unnecessary waits, // assert information is verbose enough to trace to failure cause watcher.EnableRaisingEvents = true; // create a file using (var testFile = new TemporaryTestFile(Path.Combine(dir.Path, "file"))) using (var testDir = new TemporaryTestDirectory(Path.Combine(dir.Path, "dir"))) { // rename a file in the same directory testFile.Move(testFile.Path + "_rename"); // renaming a directory testDir.Move(testDir.Path + "_rename"); // deleting a file & directory by leaving the using block } Utility.ExpectNoEvent(eventOccured, "changed"); } } [Fact, ActiveIssue(2279)] public static void FileSystemWatcher_Changed_WatchedFolder() { using (var dir = Utility.CreateTestDirectory()) using (var watcher = new FileSystemWatcher()) { watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); watcher.EnableRaisingEvents = true; Directory.SetLastAccessTime(watcher.Path, DateTime.Now); Utility.ExpectEvent(eventOccured, "changed"); } } [Fact] public static void FileSystemWatcher_Changed_NestedDirectories() { Utility.TestNestedDirectoriesHelper(WatcherChangeTypes.Changed, (AutoResetEvent are, TemporaryTestDirectory ttd) => { Directory.SetLastAccessTime(ttd.Path, DateTime.Now); Utility.ExpectEvent(are, "changed"); }, NotifyFilters.DirectoryName | NotifyFilters.LastAccess); } [Fact] public static void FileSystemWatcher_Changed_FileInNestedDirectory() { Utility.TestNestedDirectoriesHelper(WatcherChangeTypes.Changed, (AutoResetEvent are, TemporaryTestDirectory ttd) => { using (var nestedFile = new TemporaryTestFile(Path.Combine(ttd.Path, "nestedFile"))) { Directory.SetLastAccessTime(nestedFile.Path, DateTime.Now); Utility.ExpectEvent(are, "changed"); } }, NotifyFilters.DirectoryName | NotifyFilters.LastAccess | NotifyFilters.FileName); } [Fact] public static void FileSystemWatcher_Changed_FileDataChange() { using (var dir = Utility.CreateTestDirectory()) using (var watcher = new FileSystemWatcher()) { AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); // Attach the FSW to the existing structure watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size; using (var file = File.Create(Path.Combine(dir.Path, "testfile.txt"))) { watcher.EnableRaisingEvents = true; // Change the nested file and verify we get the changed event byte[] bt = new byte[4096]; file.Write(bt, 0, bt.Length); file.Flush(); } Utility.ExpectEvent(eventOccured, "file changed"); } } [Theory] [InlineData(true)] [InlineData(false)] public static void FileSystemWatcher_Changed_PreSeededNestedStructure(bool includeSubdirectories) { // Make a nested structure before the FSW is setup using (var dir = Utility.CreateTestDirectory()) using (var watcher = new FileSystemWatcher()) using (var dir1 = Utility.CreateTestDirectory(Path.Combine(dir.Path, "dir1"))) using (var dir2 = Utility.CreateTestDirectory(Path.Combine(dir1.Path, "dir2"))) using (var dir3 = Utility.CreateTestDirectory(Path.Combine(dir2.Path, "dir3"))) { string filePath = Path.Combine(dir3.Path, "testfile.txt"); File.WriteAllBytes(filePath, new byte[4096]); // Attach the FSW to the existing structure AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; watcher.NotifyFilter = NotifyFilters.Attributes; watcher.IncludeSubdirectories = includeSubdirectories; watcher.EnableRaisingEvents = true; File.SetAttributes(filePath, FileAttributes.ReadOnly); File.SetAttributes(filePath, FileAttributes.Normal); if (includeSubdirectories) Utility.ExpectEvent(eventOccured, "file changed"); else Utility.ExpectNoEvent(eventOccured, "file changed"); // Restart the FSW watcher.EnableRaisingEvents = false; watcher.EnableRaisingEvents = true; File.SetAttributes(filePath, FileAttributes.ReadOnly); File.SetAttributes(filePath, FileAttributes.Normal); if (includeSubdirectories) Utility.ExpectEvent(eventOccured, "second file change"); else Utility.ExpectNoEvent(eventOccured, "second file change"); } } [Fact, ActiveIssue(1477, PlatformID.Windows)] public static void FileSystemWatcher_Changed_SymLinkFileDoesntFireEvent() { using (var dir = Utility.CreateTestDirectory()) using (var watcher = new FileSystemWatcher()) { AutoResetEvent are = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); // Setup the watcher watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size; using (var file = Utility.CreateTestFile(Path.GetTempFileName())) { Utility.CreateSymLink(file.Path, Path.Combine(dir.Path, "link"), false); watcher.EnableRaisingEvents = true; // Changing the temp file should not fire an event through the symlink byte[] bt = new byte[4096]; file.Write(bt, 0, bt.Length); file.Flush(); } Utility.ExpectNoEvent(are, "symlink'd file change"); } } [Fact, ActiveIssue(1477, PlatformID.Windows)] public static void FileSystemWatcher_Changed_SymLinkFolderDoesntFireEvent() { using (var dir = Utility.CreateTestDirectory()) using (var tempDir = Utility.CreateTestDirectory(Path.Combine(Path.GetTempPath(), "FooBar"))) using (var watcher = new FileSystemWatcher()) { AutoResetEvent are = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); // Setup the watcher watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size; watcher.IncludeSubdirectories = true; using (var file = Utility.CreateTestFile(Path.Combine(tempDir.Path, "test"))) { // Create the symlink first Utility.CreateSymLink(tempDir.Path, Path.Combine(dir.Path, "link"), true); watcher.EnableRaisingEvents = true; // Changing the temp file should not fire an event through the symlink byte[] bt = new byte[4096]; file.Write(bt, 0, bt.Length); file.Flush(); } Utility.ExpectNoEvent(are, "symlink'd file change"); } } }
#region License // Distributed under the MIT License // ============================================================ // Copyright (c) 2019 Hotcakes Commerce, LLC // // 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.Linq; using System.Web.UI; using System.Web.UI.WebControls; using Hotcakes.Commerce; using Hotcakes.Commerce.BusinessRules; using Hotcakes.Commerce.Membership; using Hotcakes.Commerce.Orders; using Hotcakes.Commerce.Shipping; using Hotcakes.Commerce.Utilities; using Hotcakes.Modules.Core.Admin.AppCode; using Hotcakes.Shipping; namespace Hotcakes.Modules.Core.Admin.Orders { partial class ShipOrder : BaseOrderPage { protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); PageTitle = "Shipping"; CurrentTab = AdminTabType.Orders; ValidateCurrentUserHasPermission(SystemPermissions.OrdersEdit); } protected override void OnInit(EventArgs e) { base.OnInit(e); ucOrderStatusDisplay.CurrentOrder = CurrentOrder; lstTrackingProvider.SelectedIndexChanged += lstTrackingProvider_SelectedIndexChanged; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!Page.IsPostBack) { PopulateShippingProviders(); LoadOrder(); } } private void LoadOrder() { if (CurrentOrder != null) { lblOrderNumber.Text = "Order " + CurrentOrder.OrderNumber + " "; lblShippingAddress.Text = CurrentOrder.ShippingAddress.ToHtmlString(); lblShippingTotal.Text = CurrentOrder.TotalShippingAfterDiscounts.ToString("c"); ItemsGridView.DataSource = CurrentOrder.Items; ItemsGridView.DataBind(); if (!CurrentOrder.Items.Any()) { pnlShip.Visible = false; } var packages = CurrentOrder.FindShippedPackages(); packages.ForEach(p => { p.ShipDateUtc = DateHelper.ConvertUtcToStoreTime(HccApp, p.ShipDateUtc); }); PackagesGridView.DataSource = packages; PackagesGridView.DataBind(); if (packages == null || !packages.Any()) { hPackage.Visible = false; } else { hPackage.Visible = true; } lblUserSelectedShippingMethod.Text = "User Selected Shipping Method: <strong>" + CurrentOrder.ShippingMethodDisplayName + "</strong>"; if (lstTrackingProvider.Items.FindByValue(CurrentOrder.ShippingMethodId) != null) { lstTrackingProvider.ClearSelection(); lstTrackingProvider.Items.FindByValue(CurrentOrder.ShippingMethodId).Selected = true; lstTrackingProvider.SelectedValue = CurrentOrder.ShippingMethodId; } ShippingProviderServices(); if (lstTrackingProviderServices.Items.FindByValue(CurrentOrder.ShippingProviderServiceCode) != null) { lstTrackingProviderServices.ClearSelection(); lstTrackingProviderServices.Items.FindByValue(CurrentOrder.ShippingProviderServiceCode).Selected = true; lstTrackingProviderServices.SelectedValue = CurrentOrder.ShippingProviderServiceCode; } CheckShippedQty(CurrentOrder.Items); } else { pnlShip.Visible = false; } } private void CheckShippedQty(List<LineItem> items) { var totalqty = 0; foreach (var li in items) { if (!li.IsNonShipping) { var q = li.Quantity - li.QuantityShipped; if (q > 0) { totalqty += q; } } } if (totalqty <= 0) { pnlShip.Visible = false; } else { pnlShip.Visible = true; } } private void ReloadOrder(OrderShippingStatus previousShippingStatus, bool SendEmail = true) { CurrentOrder.EvaluateCurrentShippingStatus(); HccApp.OrderServices.Orders.Update(CurrentOrder); var context = new OrderTaskContext { Order = CurrentOrder, UserId = CurrentOrder.UserID }; context.Inputs.Add("hcc", "PreviousShippingStatus", previousShippingStatus.ToString()); Workflow.RunByName(context, WorkflowNames.ShippingChanged); LoadOrder(); } private void PopulateShippingProviders() { var shippingProviders = HccApp.OrderServices.ShippingMethods.FindAll(HccApp.CurrentStore.Id); if (shippingProviders != null && shippingProviders.Count > 0) { lstTrackingProvider.DataSource = shippingProviders; lstTrackingProvider.DataTextField = "Name"; lstTrackingProvider.DataValueField = "Bvin"; lstTrackingProvider.DataBind(); } else { MessageBox1.ShowInformation("We suggest to add shipping method to serve you better."); lstTrackingProvider.Visible = false; lblShippingBy.Visible = false; } } protected void ItemsGridView_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { var lineItem = e.Row.DataItem as LineItem; var SKUField = (Label) e.Row.FindControl("SKUField"); if (SKUField != null) { SKUField.Text = lineItem.ProductSku; } var description = (Label) e.Row.FindControl("DescriptionField"); if (description != null) { description.Text = lineItem.ProductName; var associatedProduct = lineItem.GetAssociatedProduct(HccApp); if (associatedProduct != null) { if (lineItem.ShippingStatus == OrderShippingStatus.NonShipping) { description.Text += "<br />Non-Shipping "; } if (associatedProduct.ShippingMode == ShippingMode.ShipFromManufacturer) { description.Text += "<br />Ships From Manufacturer "; } else if (associatedProduct.ShippingMode == ShippingMode.ShipFromVendor) { description.Text += "<br />Ships From Vendor "; } if (associatedProduct.ShippingDetails.ShipSeparately) { description.Text += "<br /> Ships Separately "; } } } var QtyToShip = (TextBox) e.Row.FindControl("QtyToShip"); if (QtyToShip != null) { if (lineItem.ShippingStatus == OrderShippingStatus.NonShipping) { QtyToShip.Visible = false; } else { QtyToShip.Visible = true; } var q = lineItem.Quantity - lineItem.QuantityShipped; if (q > 0) { QtyToShip.Text = string.Format("{0:#}", q); } } if (lineItem.IsNonShipping) { QtyToShip.Visible = false; } if (lineItem.QuantityShipped > 0m) { var shipped = (Label) e.Row.FindControl("shipped"); if (shipped != null) { shipped.Text = string.Format("{0:#}", lineItem.QuantityShipped); } } if (lineItem.QuantityShipped == lineItem.Quantity) { QtyToShip.ReadOnly = true; QtyToShip.Enabled = false; } } } protected void btnShipItems_Click(object sender, EventArgs e) { ShipOrPackageItems(false); } protected void btnCreatePackage_Click(object sender, EventArgs e) { ShipOrPackageItems(true); } private void ShipOrPackageItems(bool dontShip) { var previousShippingStatus = CurrentOrder.ShippingStatus; var serviceCode = string.Empty; var serviceProviderId = string.Empty; var shippinMethodBvin = string.Empty; var shippingMethod = HccApp.OrderServices.ShippingMethods.Find(lstTrackingProvider.SelectedValue); if (shippingMethod != null) { serviceProviderId = shippingMethod.ShippingProviderId; shippinMethodBvin = shippingMethod.Bvin; } if (lstTrackingProviderServices.Visible) { serviceCode = lstTrackingProviderServices.SelectedValue; } var p = ShipItems(CurrentOrder, TrackingNumberField.Text.Trim(), serviceProviderId, serviceCode, dontShip, shippinMethodBvin); ReloadOrder(previousShippingStatus, true); } private OrderPackage ShipItems(Order order, string trackingNumber, string serviceProvider, string serviceCode, bool dontShip, string shippingMethodId = null) { var p = new OrderPackage { ShipDateUtc = DateTime.UtcNow, TrackingNumber = trackingNumber, ShippingProviderId = serviceProvider, ShippingProviderServiceCode = serviceCode, OrderId = order.bvin, ShippingMethodId = string.IsNullOrEmpty(shippingMethodId) == false ? shippingMethodId : string.Empty }; foreach (GridViewRow gvr in ItemsGridView.Rows) { if (gvr.RowType == DataControlRowType.DataRow) { var lineItemId = (long) ItemsGridView.DataKeys[gvr.RowIndex].Value; var lineItem = order.GetLineItem(lineItemId); if (lineItem == null || lineItem.IsNonShipping) continue; var qty = 0; var QtyToShip = (TextBox) gvr.FindControl("QtyToShip"); if (QtyToShip != null) { if (!int.TryParse(QtyToShip.Text, out qty)) { qty = 0; } } // Prevent shipping more than ordered if order is not recurring if (!order.IsRecurring && qty > lineItem.Quantity - lineItem.QuantityShipped) { qty = lineItem.Quantity - lineItem.QuantityShipped; } if (qty > 0) { p.Items.Add(new OrderPackageItem(lineItem.ProductId, lineItem.Id, qty)); p.Weight += lineItem.ProductShippingWeight*qty; } } } p.WeightUnits = WebAppSettings.ApplicationWeightUnits; if (p.Items.Count > 0) { order.Packages.Add(p); if (!dontShip) { HccApp.OrdersShipPackage(p, order); } HccApp.OrderServices.Orders.Update(order); } return p; } protected void PackagesGridView_RowDataBound(object sender, GridViewRowEventArgs e) { var p = (OrderPackage) e.Row.DataItem; if (p != null) { var provider = AvailableServices.FindById(p.ShippingProviderId, HccApp.CurrentStore); var ShippedByField = (Label) e.Row.FindControl("ShippedByField"); if (ShippedByField != null) { if (provider != null) { var codes = provider.ListAllServiceCodes(); var serviceCode = codes.FirstOrDefault(c => c.Code == p.ShippingProviderServiceCode); if (serviceCode != null) { ShippedByField.Text = serviceCode.DisplayName; } else { ShippedByField.Text = provider.Name; } } } var TrackingLink = (HyperLink) e.Row.FindControl("TrackingLink"); var TrackingText = (Label) e.Row.FindControl("TrackingText"); if (TrackingLink != null) { TrackingLink.Text = p.TrackingNumber; TrackingText.Text = p.TrackingNumber; if (provider != null) { if (provider.IsSupportsTracking) { TrackingLink.NavigateUrl = provider.GetTrackingUrl(p.TrackingNumber); TrackingLink.Visible = true; TrackingText.Visible = false; } else { TrackingLink.Visible = false; TrackingText.Visible = true; } } else { TrackingLink.Visible = false; TrackingText.Visible = false; } } var TrackingTextBox = (TextBox) e.Row.FindControl("TrackingNumberTextBox"); if (TrackingTextBox != null) { TrackingTextBox.Text = p.TrackingNumber; } var items = (Label) e.Row.FindControl("items"); if (items != null) { items.Text = string.Empty; foreach (var pi in p.Items) { if (pi.Quantity > 0) { items.Text += pi.Quantity.ToString("#") + " - "; foreach (var li in CurrentOrder.Items) { if (li.Id == pi.LineItemId) { items.Text += li.ProductSku + ": " + li.ProductName + "<br />"; } } } } } } } protected void PackagesGridView_RowDeleting(object sender, GridViewDeleteEventArgs e) { var previousShippingStatus = CurrentOrder.ShippingStatus; var Id = (long) PackagesGridView.DataKeys[e.RowIndex].Value; var p = CurrentOrder.Packages.SingleOrDefault(y => y.Id == Id); if (p != null) { HccApp.OrdersUnshipItems(p, CurrentOrder); CurrentOrder.Packages.Remove(p); HccApp.OrderServices.Orders.Update(CurrentOrder); } ReloadOrder(previousShippingStatus); } protected void PackagesGridView_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "UpdateTrackingNumber") { if (e.CommandSource is Control) { var row = (GridViewRow) ((Control) e.CommandSource).NamingContainer; var trackingNumberTextBox = (TextBox) row.FindControl("TrackingNumberTextBox"); if (trackingNumberTextBox != null) { var idstring = (string) e.CommandArgument; long pid = 0; long.TryParse(idstring, out pid); var package = CurrentOrder.Packages.SingleOrDefault(y => y.Id == pid); if (package != null) { package.TrackingNumber = trackingNumberTextBox.Text; HccApp.OrderServices.Orders.Update(CurrentOrder); } } } } LoadOrder(); } protected void lstTrackingProvider_SelectedIndexChanged(object sender, EventArgs e) { ShippingProviderServices(); } private void ShippingProviderServices() { var selectedValue = lstTrackingProvider.SelectedValue; var services = new List<IServiceCode>(); if (!string.IsNullOrEmpty(selectedValue)) { var shippingMethod = HccApp.OrderServices.ShippingMethods.Find(selectedValue); var provider = AvailableServices.FindById(shippingMethod.ShippingProviderId, HccApp.CurrentStore); services = provider.ListAllServiceCodes(); } if (services != null && services.Any()) { var removeItem = services.FirstOrDefault(x => x.DisplayName == "All Available Services"); if (removeItem != null) { services.Remove(removeItem); } } if (services != null && services.Any()) { lstTrackingProviderServices.ClearSelection(); lblShippingServices.Visible = true; lstTrackingProviderServices.Visible = true; lstTrackingProviderServices.DataSource = services; lstTrackingProviderServices.DataTextField = "DisplayName"; lstTrackingProviderServices.DataValueField = "Code"; lstTrackingProviderServices.DataBind(); } else { lstTrackingProviderServices.Items.Clear(); lstTrackingProviderServices.Visible = false; lblShippingServices.Visible = false; } } } }
//#define Trace // Tar.cs // // version: 1.4.0.2 // - built more flexibility into the checksum verification // to handle non-compliant checksums . // // version: 1.4.0.1 // - now supports Gnu LongName entries and reads/writes GZIP'd tar // files (tgz). // // ------------------------------------------------------------------ // // This is source code for a library/EXE for reading tar files. // See doc for the unix TAR format on // http://www.mkssoftware.com/docs/man4/tar.4.asp // // Requirements: // .NET 3.5 // // You can build this as either a Tar library, suitable for use within // any application, or a standalone executable, suitable for use as a // console application. // // To build the exe: // // csc.exe /t:exe /debug+ /define:EXE /out:Tar.exe Tar.cs // // To build the dll: // // csc.exe /t:library /debug+ /out:Tar.dll Tar.cs // // ------------------------------------------------------------------ // // Bugs: // // - does not read or write bzip compressed tarballs (.tar.bz2) // - does not archive symbolic links. // - uses Marshal.StructureToPtr and thus requires a LinkDemand, full trust. // // ------------------------------------------------------------------ // // Copyright (c) 2009-2011 by Dino Chiesa // All rights reserved! // // This program is licensed under the Microsoft Public License (Ms-PL) // See the accompanying License.txt file for details. // // ------------------------------------------------------------------ // // compile: csc.exe /t:exe /debug+ /define:EXE /out:Tar.exe Tar.cs // using System; using System.IO; using System.Reflection; using System.Collections.Generic; using System.Runtime.InteropServices; // to allow fast ngen //[assembly: AssemblyTitle("Tar.cs")] //[assembly: AssemblyDescription("A quick and easy TAR library, for reading or writing the Unix(tm) tar file formt")] //[assembly: AssemblyConfiguration("")] //[assembly: AssemblyCompany("Dino Chiesa")] //[assembly: AssemblyProduct("Tools")] //[assembly: AssemblyCopyright("Copyright ?Dino Chiesa 2009-2011")] //[assembly: AssemblyTrademark("")] //[assembly: AssemblyCulture("")] //[assembly: AssemblyVersion("1.4.0.1")] namespace Ionic { /// <summary> /// A class to create, list, or extract TAR archives. This is the /// primary, central class for the Tar library. /// </summary> /// /// <remarks> /// Bugs: /// <list type="bullet"> /// <item> does not read or write bzip2 compressed tarballs (.tar.bz2)</item> /// <item> uses Marshal.StructureToPtr and thus requires a LinkDemand, full trust.d </item> /// </list> /// </remarks> public class Tar { /// <summary> /// Specifies the options to use for tar creation or extraction /// </summary> public class Options { /// <summary> /// The compression to use. Applies only during archive /// creation. Ignored during extraction. /// </summary> public TarCompression Compression { get; set; } /// <summary> /// A TextWriter to which verbose status messages will be /// written during operation. /// </summary> /// <remarks> /// <para> /// Use this to see messages emitted by the Tar logic. /// You can use this whether Extracting or creating an archive. /// </para> /// </remarks> /// <example> /// <code lang="C#"> /// var options = new Tar.Options(); /// options.StatusWriter = Console.Out; /// Ionic.Tar.Extract("Archive2.tgz", options); /// </code> /// </example> public TextWriter StatusWriter { get; set; } /// <summary> /// Whether to follow symbolic links when creating archives. /// </summary> public bool FollowSymLinks { get; set; } /// <summary> /// Whether to overwrite existing files when extracting archives. /// </summary> public bool Overwrite { get; set; } /// <summary> /// If true, the modified times of the extracted entries is /// NOT set according to the time set in the archive. By /// default, the modified time is set. /// </summary> public bool DoNotSetTime { get; set; } } /// <summary> /// Represents an entry in a TAR archive. /// </summary> public enum TarCompression { /// <summary> /// No compression - just a vanilla tar. /// </summary> None = 0, /// <summary> /// GZIP compression is applied to the tar to produce a .tgz file /// </summary> GZip, } /// <summary> /// Represents an entry in a TAR archive. /// </summary> public class TarEntry { /// <summary>Intended for internal use only.</summary> internal TarEntry() { } /// <summary>The name of the file contained within the entry</summary> public string Name { get; internal set; } /// <summary> /// The size of the file contained within the entry. If the /// entry is a directory, this is zero. /// </summary> public int Size { get; internal set; } /// <summary>The last-modified time on the file or directory.</summary> public DateTime Mtime { get; internal set; } /// <summary>the type of the entry.</summary> public TarEntryType @Type { get; internal set; } /// <summary>a char representation of the type of the entry.</summary> public char TypeChar { get { switch(@Type) { case TarEntryType.File_Old: case TarEntryType.File: case TarEntryType.File_Contiguous: return 'f'; case TarEntryType.HardLink: return 'l'; case TarEntryType.SymbolicLink: return 's'; case TarEntryType.CharSpecial: return 'c'; case TarEntryType.BlockSpecial: return 'b'; case TarEntryType.Directory: return 'd'; case TarEntryType.Fifo: return 'p'; case TarEntryType.GnuLongLink: case TarEntryType.GnuLongName: case TarEntryType.GnuSparseFile: case TarEntryType.GnuVolumeHeader: return (char)(@Type); default: return '?'; } } } } ///<summary>the type of Tar Entry</summary> public enum TarEntryType : byte { ///<summary>a file (old version)</summary> File_Old = 0, ///<summary>a file</summary> File = 48, ///<summary>a hard link</summary> HardLink = 49, ///<summary>a symbolic link</summary> SymbolicLink = 50, ///<summary>a char special device</summary> CharSpecial = 51, ///<summary>a block special device</summary> BlockSpecial = 52, ///<summary>a directory</summary> Directory = 53, ///<summary>a pipe</summary> Fifo = 54, ///<summary>Contiguous file</summary> File_Contiguous = 55, ///<summary>a GNU Long name?</summary> GnuLongLink = (byte)'K', // "././@LongLink" ///<summary>a GNU Long name?</summary> GnuLongName = (byte)'L', // "././@LongLink" ///<summary>a GNU sparse file</summary> GnuSparseFile = (byte)'S', ///<summary>a GNU volume header</summary> GnuVolumeHeader = (byte)'V', } // Numeric values are encoded in octal numbers using ASCII digits, with // leading zeroes. For historical reasons, a final null or space // character should be used. Thus although there are 12 bytes reserved // for storing the file size, only 11 octal digits can be stored. /// <summary> /// This class is intended for internal use only, by the Tar library. /// </summary> [StructLayout(LayoutKind.Sequential, Size=512)] internal struct HeaderBlock { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 100)] public byte[] name; // name of file. A directory is indicated by a trailing slash (/) in its name. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public byte[] mode; // file mode [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public byte[] uid; // owner user ID [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public byte[] gid; // owner group ID [MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)] public byte[] size; // length of file in bytes, encoded as octal digits in ASCII [MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)] public byte[] mtime; // modify time of file [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public byte[] chksum; // checksum for header (use all blanks for chksum itself, when calculating) // The checksum is calculated by taking the sum of the // unsigned byte values of the header block with the eight // checksum bytes taken to be ascii spaces (decimal value // 32). // It is stored as a six digit octal number with leading // zeroes followed by a null and then a space. public byte typeflag; // type of file [MarshalAs(UnmanagedType.ByValArray, SizeConst = 100)] public byte[] linkname; // name of linked file (only if typeflag = '2') [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)] public byte[] magic; // USTAR indicator [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] public byte[] version; // USTAR version [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] public byte[] uname; // owner user name [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] public byte[] gname; // owner group name [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public byte[] devmajor; // device major number [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public byte[] devminor; // device minor number [MarshalAs(UnmanagedType.ByValArray, SizeConst = 155)] public byte[] prefix; // prefix for file name [MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)] public byte[] pad; // ignored public static HeaderBlock CreateOne() { HeaderBlock hb = new HeaderBlock { name = new byte[100], mode = new byte[8], uid = new byte[8], // owner user ID gid = new byte[8], // owner group ID size = new byte[12], // length of file in bytes, encoded in octal mtime = new byte[12], // modify time of file chksum = new byte[8], // checksum for header linkname = new byte[100], // name of linked file magic = new byte[6], // USTAR indicator version = new byte[2], // USTAR version uname = new byte[32], // owner user name gname = new byte[32], // owner group name devmajor = new byte[8], // device major number devminor = new byte[8], // device minor number prefix = new byte[155], // prefix for file name pad = new byte[12], // ignored }; Array.Copy(System.Text.Encoding.ASCII.GetBytes("ustar "), 0, hb.magic, 0, 6 ); hb.version[0]=hb.version[1]=(byte) TarEntryType.File; return hb; } public bool VerifyChksum() { int stored = GetChksum(); int calculated = SetChksum(); TraceOutput("stored({0}) calc({1})", stored, calculated); return (stored == calculated); } public int GetChksum() { TraceData("chksum", this.chksum); // The tar spec says that the Checksum must be stored as a // six digit octal number with leading zeroes followed by a // null and then a space. // Various implementations do not adhere to this, so reader // programs should be flexible. // A more compatible approach may be to use the // first white-space-trimmed six digits for checksum. // // In addition, some older tar implementations treated // bytes as signed. Readers must calculate the checksum // both ways, and treat it as good if either the signed // or unsigned sum matches the included checksum. // special case bool allZeros = true; Array.ForEach(this.chksum, (x) => {if (x!=0) allZeros= false; }); if (allZeros) return 256; // validation 6 and 7 have to be 0 and 0x20, in some order. if (!(((this.chksum[6]==0) && (this.chksum[7]==0x20)) || ((this.chksum[7]==0) && (this.chksum[6]==0x20)))) return -1; string v = System.Text.Encoding.ASCII.GetString(this.chksum, 0, 6).Trim(); TraceOutput("chksum string: '{0}'", v); return Convert.ToInt32(v, 8); } public int SetChksum() { // first set the checksum to all ASCII _space_ (dec 32) var a = System.Text.Encoding.ASCII.GetBytes(new String(' ',8)); Array.Copy(a, 0, this.chksum, 0, a.Length); // always 8 // then sum all the bytes int rawSize = 512; byte[] block = new byte[ rawSize ]; IntPtr buffer = Marshal.AllocHGlobal( rawSize ); try { Marshal.StructureToPtr( this, buffer, false ); Marshal.Copy( buffer, block, 0, rawSize ); } finally { Marshal.FreeHGlobal( buffer ); } // format as octal int sum= 0; Array.ForEach(block, (x) => sum+=x ); string s = "000000" + Convert.ToString(sum, 8); // put that into the checksum block a = System.Text.Encoding.ASCII.GetBytes(s.Substring(s.Length-6)); Array.Copy(a, 0, this.chksum, 0, a.Length); // always 6 this.chksum[6]=0; this.chksum[7]=0x20; return sum; } public void SetSize(int sz) { string ssz = String.Format(" {0} ", Convert.ToString(sz, 8)); // get last 12 chars var a = System.Text.Encoding.ASCII.GetBytes(ssz.Substring(ssz.Length-12)); Array.Copy(a, 0, this.size, 0, a.Length); // always 12 } public int GetSize() { return Convert.ToInt32(System.Text.Encoding.ASCII.GetString(this.size).TrimNull(), 8); } public void InsertLinkName(string linkName) { // if greater than 100, then an exception occurs var a = System.Text.Encoding.ASCII.GetBytes(linkName); Array.Copy(a, 0, this.linkname, 0, a.Length); } public void InsertName(string itemName) { if (itemName.Length <= 100) { var a = System.Text.Encoding.ASCII.GetBytes(itemName); Array.Copy(a, 0, this.name, 0, a.Length); } else { var a = System.Text.Encoding.ASCII.GetBytes(itemName); Array.Copy(a, a.Length-100, this.name, 0, 100); Array.Copy(a, 0, this.prefix, 0, a.Length-100); } // insert the modified time for the file or directory, also DateTime dt = File.GetLastWriteTimeUtc(itemName); int time_t = TimeConverter.DateTime2TimeT(dt); string mtime = " " + Convert.ToString(time_t, 8) + " "; var a1 = System.Text.Encoding.ASCII.GetBytes(mtime.Substring(mtime.Length-12)); Array.Copy(a1, 0, this.mtime, 0, a1.Length); // always 12 } public DateTime GetMtime() { int time_t = Convert.ToInt32(System.Text.Encoding.ASCII.GetString(this.mtime).TrimNull(), 8); return DateTime.SpecifyKind(TimeConverter.TimeT2DateTime(time_t), DateTimeKind.Utc); } public string GetName() { string n = null; string m = GetMagic(); if (m != null && m.Equals("ustar")) { n = (this.prefix[0]==0) ? System.Text.Encoding.ASCII.GetString(this.name).TrimNull() : System.Text.Encoding.ASCII.GetString(this.prefix).TrimNull() + System.Text.Encoding.ASCII.GetString(this.name).TrimNull(); } else { n = System.Text.Encoding.ASCII.GetString(this.name).TrimNull(); } return n; } private string GetMagic() { string m = (this.magic[0]==0) ? null : System.Text.Encoding.ASCII.GetString(this.magic).Trim(); return m; } } private Options TarOptions { get; set; } private Tar () {} /// <summary> /// Extract the named tar archive to the current directory /// </summary> /// <param name="archive"> /// The name of the tar archive to extract. /// </param> /// <returns> /// A <c>ReadOnlyCollection</c> of TarEntry instances contained within /// the archive. /// </returns> /// <example> /// <code lang="VB"> /// ' extract a regular tar archive, placing files in the current dir: /// Ionic.Tar.Extract("MyArchive.tar") /// ' extract a compressed tar archive, placing files in the current dir: /// Ionic.Tar.Extract("Archive2.tgz") /// </code> /// <code lang="C#"> /// // extract a regular tar archive, placing files in the current dir: /// Ionic.Tar.Extract("MyArchive.tar"); /// // extract a compressed tar archive, placing files in the current dir: /// Ionic.Tar.Extract("Archive2.tgz") /// </code> /// </example> public static System.Collections.ObjectModel.ReadOnlyCollection<TarEntry> Extract(string archive) { return ListOrExtract(archive, true, null).AsReadOnly(); } /// <summary> /// Extract the named tar archive to the current directory /// </summary> /// <param name="archive"> /// The name of the tar archive to extract. /// </param> /// <param name="options"> /// A set of options for extracting. /// </param> /// <returns> /// A <c>ReadOnlyCollection</c> of TarEntry instances /// contained within the archive. /// </returns> public static System.Collections.ObjectModel.ReadOnlyCollection<TarEntry> Extract(string archive, Options options) { return ListOrExtract(archive, true, options).AsReadOnly(); } /// <summary> /// Get a list of the TarEntry items contained within the named archive. /// </summary> /// <param name="archive"> /// The name of the tar archive. /// </param> /// <returns> /// A <c>ReadOnlyCollection</c> of TarEntry instances /// contained within the archive. /// </returns> /// /// <example> /// <code lang="C#"> /// private void ListContents(string archiveName) /// { /// var list = Ionic.Tar.List(archiveName); /// foreach (var item in list) /// { /// Console.WriteLine("{0,-20} {1,9} {2}", /// item.Mtime.ToString("u"), /// item.Size, item.Name); /// } /// Console.WriteLine(new String('-', 66)); /// Console.WriteLine(" {0} entries", /// list.Count); /// } /// </code> /// /// <code lang="VB"> /// Private Sub ListContents(ByVal archiveName as String) /// Dim list As System.Collections.ObjectModel.ReadOnlyCollection(Of Ionic.Tar.TarEntry) = _ /// Ionic.Tar.List(archiveName) /// Dim item As Ionic.Tar.TarEntry /// For Each s In list /// Console.WriteLine("{0,-20} {1,9} {2}", _ /// item.Mtime.ToString("u"), _ /// item.Size, item.Name) /// Next /// Console.WriteLine(New String("-"c, 66)) /// Console.WriteLine(" {0} entries", _ /// list.Count) /// End Sub /// </code> /// </example> public static System.Collections.ObjectModel.ReadOnlyCollection<TarEntry> List(string archive) { return ListOrExtract(archive, false, null).AsReadOnly(); } private static List<TarEntry> ListOrExtract(string archive, bool wantExtract, Options options) { var t = new Tar(); t.TarOptions = options ?? new Options(); return t._internal_ListOrExtract(archive, wantExtract); } [DllImport("kernel32.dll", EntryPoint="CreateSymbolicLinkW", CharSet=CharSet.Unicode)] private static extern int CreateSymbolicLink(string symlinkFileName, string targetFileName, int flags); private List<TarEntry> _internal_ListOrExtract(string archive, bool wantExtract) { var entryList = new List<TarEntry>(); byte[] block = new byte[512]; int n = 0; int blocksToMunch = 0; int remainingBytes = 0; Stream output= null; DateTime mtime = DateTime.Now; string name = null; TarEntry entry = null; var deferredDirTimestamp= new Dictionary<String,DateTime>(); if (!File.Exists(archive)) throw new InvalidOperationException("The specified file does not exist."); using (Stream fs = _internal_GetInputStream(archive)) { while ((n = fs.Read(block, 0, block.Length)) > 0) { if (blocksToMunch > 0) { if (output!=null) { int bytesToWrite = (block.Length < remainingBytes) ? block.Length : remainingBytes; output.Write(block, 0, bytesToWrite); remainingBytes -= bytesToWrite; } blocksToMunch--; //System.Diagnostics.Debugger.Break(); if (blocksToMunch == 0) { if (output!= null) { if (output is MemoryStream) { entry.Name = name = System.Text.Encoding.ASCII.GetString((output as MemoryStream).ToArray()).TrimNull(); } output.Close(); output.Dispose(); if (output is FileStream && !TarOptions.DoNotSetTime) { File.SetLastWriteTimeUtc(name, mtime); } output = null; } } continue; } HeaderBlock hb = serializer.RawDeserialize(block); //System.Diagnostics.Debugger.Break(); if (!hb.VerifyChksum()) throw new Exception("header checksum is invalid."); // if this is the first entry, or if the prior entry is not a GnuLongName if (entry==null || entry.Type!=TarEntryType.GnuLongName) name = hb.GetName(); if (name== null || name.Length == 0) break; // EOF mtime = hb.GetMtime(); remainingBytes = hb.GetSize(); if (hb.typeflag==0) hb.typeflag=(byte)'0'; // coerce old-style GNU type to posix tar type entry = new TarEntry() {Name = name, Mtime = mtime, Size = remainingBytes, @Type = (TarEntryType)hb.typeflag } ; if (entry.Type!=TarEntryType.GnuLongName) entryList.Add(entry); blocksToMunch = (remainingBytes > 0) ? ((remainingBytes - 1) / 512) +1 : 0; if (entry.Type==TarEntryType.GnuLongName) { if (name != "././@LongLink") { if (wantExtract) throw new Exception(String.Format("unexpected name for type 'L' (expected '././@LongLink', got '{0}')", name)); } // for GNU long names, we extract the long name info into a memory stream output = new MemoryStream(); continue; } if (wantExtract) { switch (entry.Type) { case TarEntryType.Directory: if (!Directory.Exists(name)) { Directory.CreateDirectory(name); // cannot set the time on the directory now, or it will be updated // by future file writes. Defer until after all file writes are done. if (!TarOptions.DoNotSetTime) deferredDirTimestamp.Add(name.TrimSlash(), mtime); } else if (TarOptions.Overwrite) { if (!TarOptions.DoNotSetTime) deferredDirTimestamp.Add(name.TrimSlash(), mtime); } break; case TarEntryType.File_Old: case TarEntryType.File: case TarEntryType.File_Contiguous: string p = Path.GetDirectoryName(name); if (!String.IsNullOrEmpty(p)) { if (!Directory.Exists(p)) Directory.CreateDirectory(p); } output = _internal_GetExtractOutputStream(name); break; case TarEntryType.GnuVolumeHeader: case TarEntryType.CharSpecial: case TarEntryType.BlockSpecial: // do nothing on extract break; case TarEntryType.SymbolicLink: break; // can support other types here - links, etc default: throw new Exception(String.Format("unsupported entry type ({0})", hb.typeflag)); } } } } // apply the deferred timestamps on the directories if (deferredDirTimestamp.Count > 0) { foreach (var s in deferredDirTimestamp.Keys) { Directory.SetLastWriteTimeUtc(s, deferredDirTimestamp[s]); } } return entryList; } private Stream _internal_GetInputStream(string archive) { if (archive.EndsWith(".tgz") || archive.EndsWith(".tar.gz")) { var fs = File.Open(archive, FileMode.Open, FileAccess.Read); return new System.IO.Compression.GZipStream(fs, System.IO.Compression.CompressionMode.Decompress, false); } return File.Open(archive, FileMode.Open, FileAccess.Read); } private Stream _internal_GetExtractOutputStream(string name) { if (TarOptions.Overwrite || !File.Exists(name)) { if (TarOptions.StatusWriter != null) TarOptions.StatusWriter.WriteLine("{0}", name); return File.Open(name, FileMode.Create, FileAccess.ReadWrite); } if (TarOptions.StatusWriter != null) TarOptions.StatusWriter.WriteLine("{0} (not overwriting)", name); return null; } /// <summary> /// Create a tar archive with the given name, and containing /// the given set of files or directories. /// </summary> /// <param name="outputFile"> /// The name of the tar archive to create. The file must not /// exist at the time of the call. /// </param> /// <param name="filesOrDirectories"> /// A list of filenames and/or directory names to be added to the archive. /// </param> /// /// <example> /// <code lang="VB"> /// Ionic.Tar.CreateArchive("MyArchive.tar", _ /// new String() {"file1.txt", "file2.txt"}) /// </code> /// <code lang="C#"> /// Ionic.Tar.CreateArchive("MyArchive.tar", /// new String[] {"file1.txt", "file2.txt"}); /// </code> /// </example> public static void CreateArchive(string outputFile, IEnumerable<String> filesOrDirectories) { var t = new Tar(); t._internal_CreateArchive(outputFile, filesOrDirectories); } /// <summary> /// Create a tar archive with the given name, and containing /// the given set of files or directories, and using the given options. /// </summary> /// <param name="outputFile"> /// The name of the tar archive to create. The file must not /// exist at the time of the call. /// </param> /// <param name="filesOrDirectories"> /// A list of filenames and/or directory names to be added to the archive. /// </param> /// <param name="options"> /// The options to use during Tar operation. /// </param> public static void CreateArchive(string outputFile, IEnumerable<String> filesOrDirectories, Options options) { var t = new Tar(); t.TarOptions = options; t._internal_CreateArchive(outputFile, filesOrDirectories); } private void _internal_CreateArchive(string outputFile, IEnumerable<String> files) { if (String.IsNullOrEmpty(outputFile)) throw new InvalidOperationException("You must specify an output file."); if (File.Exists(outputFile)) throw new InvalidOperationException("The output file you specified already exists."); if (Directory.Exists(outputFile)) throw new InvalidOperationException("The output file you specified is a directory."); int fcount = 0; try { using (_outfs = _internal_GetOutputArchiveStream(outputFile)) { foreach (var f in files) { fcount++; if (Directory.Exists(f)) AddDirectory(f); else if (File.Exists(f)) AddFile(f); else throw new InvalidOperationException(String.Format("The file you specified ({0}) was not found.", f)); } if (fcount < 1) throw new InvalidOperationException("Specify one or more input files to place into the archive."); // terminator byte[] block = new byte[512]; _outfs.Write(block, 0, block.Length); _outfs.Write(block, 0, block.Length); } } finally { if (fcount < 1) try { File.Delete(outputFile); } catch { } } } private Stream _internal_GetOutputArchiveStream(string filename) { switch(TarOptions.Compression) { case TarCompression.None: return File.Open(filename, FileMode.Create, FileAccess.ReadWrite); case TarCompression.GZip: { var fs = File.Open(filename, FileMode.Create, FileAccess.ReadWrite); return new System.IO.Compression.GZipStream(fs, System.IO.Compression.CompressionMode.Compress, false); } default: throw new Exception("bad state"); } } private void AddDirectory(string dirName) { dirName = dirName.TrimVolume(); // insure trailing slash if (!dirName.EndsWith("/")) dirName += "/"; if (TarOptions.StatusWriter != null) TarOptions.StatusWriter.WriteLine("{0}", dirName); // add the block for the dir, right here. HeaderBlock hb = HeaderBlock.CreateOne(); hb.InsertName(dirName); hb.typeflag = 5 + (byte)'0' ; hb.SetSize(0); // some impls use agg size of all files contained hb.SetChksum(); byte[] block = serializer.RawSerialize(hb); _outfs.Write(block, 0, block.Length); // add the files: String[] filenames = Directory.GetFiles(dirName); foreach (String filename in filenames) { AddFile(filename); } // add the subdirectories: String[] dirnames = Directory.GetDirectories(dirName); foreach (String d in dirnames) { // handle reparse points var a = System.IO.File.GetAttributes(d); if ((a & FileAttributes.ReparsePoint) == 0) // not a symlink AddDirectory(d); else if (this.TarOptions.FollowSymLinks) // isa symlink, and we want to follow it AddDirectory(d); else // not following symlinks; add it AddSymlink(d); } } private void AddSymlink(string name) { if (TarOptions.StatusWriter != null) TarOptions.StatusWriter.WriteLine("{0}", name); // add the block for the symlink, right here. HeaderBlock hb = HeaderBlock.CreateOne(); hb.InsertName(name); hb.InsertLinkName(name); hb.typeflag = (byte)TarEntryType.SymbolicLink; hb.SetSize(0); hb.SetChksum(); byte[] block = serializer.RawSerialize(hb); _outfs.Write(block, 0, block.Length); } private void AddFile(string fileName) { // is it a symlink (ReparsePoint)? var a = System.IO.File.GetAttributes(fileName); if ((a & FileAttributes.ReparsePoint) != 0) { AddSymlink(fileName); return; } if (TarOptions.StatusWriter != null) TarOptions.StatusWriter.WriteLine("{0}", fileName); HeaderBlock hb = HeaderBlock.CreateOne(); hb.InsertName(fileName); hb.typeflag = (byte)TarEntryType.File; // 0 + (byte)'0' ; FileInfo fi = new FileInfo(fileName); hb.SetSize((int)fi.Length); hb.SetChksum(); byte[] block = serializer.RawSerialize(hb); _outfs.Write(block, 0, block.Length); using (FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Read)) { int n= 0; Array.Clear(block, 0, block.Length); while ((n = fs.Read(block, 0, block.Length)) > 0) { _outfs.Write(block, 0, block.Length); // not n!! Array.Clear(block, 0, block.Length); } } } private RawSerializer<HeaderBlock> _s; private RawSerializer<HeaderBlock> serializer { get { if (_s == null) _s= new RawSerializer<HeaderBlock>(); return _s; } } [System.Diagnostics.ConditionalAttribute("Trace")] private static void TraceData(string label, byte[] data) { Console.WriteLine("{0}:", label); Array.ForEach(data, (x) => Console.Write("{0:X} ", (byte)x)); System.Console.WriteLine(); } [System.Diagnostics.ConditionalAttribute("Trace")] private static void TraceOutput(string format, params object[] varParams) { Console.WriteLine(format, varParams); } // member variables private Stream _outfs = null; //private System.Text.Encoding _ascii = System.Text.Encoding.ASCII; } /// <summary> /// This class is intended for internal use only, by the Tar library. /// </summary> internal static class Extensions { public static string TrimNull(this string t) { return t.Trim( new char[] { (char)0x20, (char)0x00 } ); } public static string TrimSlash(this string t) { return t.TrimEnd( new char[] { (char)'/' } ); } public static string TrimVolume(this string t) { if (t.Length > 3 && t[1]==':' && t[2]=='/') return t.Substring(3); if (t.Length > 2 && t[0]=='/' && t[1]=='/') return t.Substring(2); return t; } } /// <summary> /// This class is intended for internal use only, by the Tar library. /// </summary> internal static class TimeConverter { private static System.DateTime _unixEpoch = new System.DateTime(1970,1,1, 0,0,0, DateTimeKind.Utc); private static System.DateTime _win32Epoch = new System.DateTime(1601,1,1, 0,0,0, DateTimeKind.Utc); public static Int32 DateTime2TimeT(System.DateTime datetime) { System.TimeSpan delta = datetime - _unixEpoch; return (System.Int32)(delta.TotalSeconds); } public static System.DateTime TimeT2DateTime(int timet) { return _unixEpoch.AddSeconds(timet); } public static Int64 DateTime2Win32Ticks(System.DateTime datetime) { System.TimeSpan delta = datetime - _win32Epoch; return (Int64) (delta.TotalSeconds * 10000000L); } public static DateTime Win32Ticks2DateTime(Int64 ticks) { return _win32Epoch.AddSeconds(ticks/10000000); } } /// <summary> /// This class is intended for internal use only, by the Tar library. /// </summary> internal class RawSerializer<T> { public T RawDeserialize( byte[] rawData ) { return RawDeserialize( rawData , 0 ); } public T RawDeserialize( byte[] rawData , int position ) { int rawsize = Marshal.SizeOf( typeof(T) ); if( rawsize > rawData.Length ) return default(T); IntPtr buffer = Marshal.AllocHGlobal( rawsize ); try { Marshal.Copy( rawData, position, buffer, rawsize ); return (T) Marshal.PtrToStructure( buffer, typeof(T) ); } finally { Marshal.FreeHGlobal( buffer ); } } public byte[] RawSerialize( T item ) { int rawSize = Marshal.SizeOf( typeof(T) ); byte[] rawData = new byte[ rawSize ]; IntPtr buffer = Marshal.AllocHGlobal( rawSize ); try { Marshal.StructureToPtr( item, buffer, false ); Marshal.Copy( buffer, rawData, 0, rawSize ); } finally { Marshal.FreeHGlobal( buffer ); } return rawData; } } // (setq c-symbol-start "\\<[[:alpha:]_]") // (modify-syntax-entry ?# "w" csharp-mode-syntax-table) #if EXE public class TarApp { // ctor public TarApp () {} private bool _verbose; private Tar.Options _options; private bool _expectFile; private string _archiveName; private List<string> _fileNames; private TarAction _action; delegate void TarAction(); private void ProcessOptionString(string arg) { _options = new Tar.Options(); foreach (char c in arg.ToCharArray()) { switch(c) { case 'c': if (_action != null) throw new ArgumentException("c"); _action = CreateArchive; break; case 'x': if (_action != null) throw new ArgumentException("x"); _action = ExtractArchive; break; case 't': if (_action != null) throw new ArgumentException("t"); _action = ListContents; break; case 'f': if (_expectFile) throw new ArgumentException("f"); _expectFile = true; break; case 'k': if (_options.Overwrite) throw new ArgumentException("k"); _options.Overwrite = true; break; case 'm': if (_options.DoNotSetTime) throw new ArgumentException("m"); _options.DoNotSetTime = true; break; case 'L': if (_options.FollowSymLinks) throw new ArgumentException("L"); _options.FollowSymLinks = true; break; case 'z': if (_options.Compression!=Tar.TarCompression.None) throw new ArgumentException("z"); _options.Compression = Tar.TarCompression.GZip; break; case 'v': if (_verbose) throw new ArgumentException("v"); _verbose = true; _options.StatusWriter = System.Console.Out; break; default: throw new ArgumentException(new String(c, 1)); } } } public TarApp (string[] args) { if (args.Length ==0) Usage(); ProcessOptionString((args[0][0]=='-') ? args[0].Substring(1) : args[0]); for (int i=1; i < args.Length; i++) { if (args[i]=="-?") Usage(); if (_expectFile) { if (_fileNames== null) { _fileNames = new List<String>(); _archiveName = args[i]; } else { if (_action != CreateArchive) throw new ArgumentException(); _fileNames.Add(args[i]); } } } // validation if (String.IsNullOrEmpty(_archiveName)) throw new ArgumentException(); if (_action == null) throw new ArgumentException(); if (_action == CreateArchive) { if (_options.Compression != Tar.TarCompression.None && !_archiveName.EndsWith(".tar.gz") && !_archiveName.EndsWith(".tgz")) System.Console.Error.WriteLine("Warning: non-standard extension used on a compressed archive."); else if (_options.Compression == Tar.TarCompression.None && !_archiveName.EndsWith(".tar")) System.Console.Error.WriteLine("Warning: non-standard extension used on an archive."); } else if (!_archiveName.EndsWith(".tar.gz") && !_archiveName.EndsWith(".tgz") && !_archiveName.EndsWith(".tar")) System.Console.Error.WriteLine("Warning: non-standard extension used on a compressed archive."); } public void Run() { _action(); } private void ListContents() { var list = Ionic.Tar.List(_archiveName); foreach (var entry in list) { if (_verbose) System.Console.WriteLine("{0} {1,-20} {2,9} {3}", entry.TypeChar, entry.Mtime.ToString("u"), entry.Size, entry.Name); else System.Console.WriteLine("{0}", entry.Name); } if (_verbose) { System.Console.WriteLine(new String('-', 66)); System.Console.WriteLine(" {0} entries", list.Count); } } private void CreateArchive() { Ionic.Tar.CreateArchive(_archiveName, _fileNames, _options); } private void ExtractArchive() { Ionic.Tar.Extract(_archiveName, _options); } public static void Usage() { Console.WriteLine("\nTar: process tar archives.\n" + "a utility by Dino Chiesa\n\n" + "Usage:\n Tar [-] [x|c|t] [options] [tarfile] ...\n" + "\n" + " tar -c ... creates an archive\n" + " tar -x ... extracts an archive\n" + " tar -t ... lists the contents of an archive\n" + "options:\n" + " -k (x mode only) Do not overwrite existing files. In case a file\n" + " a file appears more than once in an archive, later copies will\n" + " not overwrite earlier copies.\n" + " -L (c mode only) All symbolic links will be followed.\n" + " Normally, symbolic links (Reparse Points0 are ignored. With \n" + " this option, the target of the link will be archived instead.\n" + " -m (x mode only) Do not extract modification time. By default, the\n"+ " modification time is set to the time stored in the archive.\n" + " -v emit verbose output during operation.\n" + " -z (c mode only) the resulting archive will be GZIP compressed.\n" + "\n" + "Examples:\n" + "\n" + " to list the entries in a tar archive:\n" + " tar -tvf archive.tar\n" + "\n" + " to silently extract a tar archive:\n" + " tar -xf newarchive.tar \n" + "\n" + " to verbosely create a tar archive, compressed with gzip:\n" + " tar -cvfz newarchive.tgz dir1 file1 ..\n" + "\n" ); System.Environment.Exit(1); // todo, other tar options: // -U (x mode only) Unlink files before creating them. Without this // option, tar overwrites existing files, which preserves existing // hardlinks. With this option, existing hardlinks will be broken, // as will any symlink that would affect the location of an // extracted file. } public static void Main(string[] args) { try { new TarApp(args) .Run(); } catch (System.Exception exc1) { Console.WriteLine("Exception: {0}", exc1.ToString()); Usage(); } } } #endif }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Description { using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Net.Mime; using System.Runtime; using System.Runtime.Diagnostics; using System.Security; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Configuration; using System.ServiceModel.Diagnostics; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using WsdlNS = System.Web.Services.Description; using XsdNS = System.Xml.Schema; public class MetadataExchangeClient { ChannelFactory<IMetadataExchange> factory; ICredentials webRequestCredentials; TimeSpan resolveTimeout = TimeSpan.FromMinutes(1); int maximumResolvedReferences = 10; bool resolveMetadataReferences = true; long maxMessageSize; XmlDictionaryReaderQuotas readerQuotas; EndpointAddress ctorEndpointAddress = null; Uri ctorUri = null; object thisLock = new object(); internal const string MetadataExchangeClientKey = "MetadataExchangeClientKey"; public MetadataExchangeClient() { this.factory = new ChannelFactory<IMetadataExchange>("*"); this.maxMessageSize = GetMaxMessageSize(this.factory.Endpoint.Binding); } public MetadataExchangeClient(Uri address, MetadataExchangeClientMode mode) { Validate(address, mode); if (mode == MetadataExchangeClientMode.HttpGet) { this.ctorUri = address; } else { this.ctorEndpointAddress = new EndpointAddress(address); } CreateChannelFactory(address.Scheme); } public MetadataExchangeClient(EndpointAddress address) { if (address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address"); } this.ctorEndpointAddress = address; CreateChannelFactory(address.Uri.Scheme); } public MetadataExchangeClient(string endpointConfigurationName) { if (endpointConfigurationName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpointConfigurationName"); } this.factory = new ChannelFactory<IMetadataExchange>(endpointConfigurationName); this.maxMessageSize = GetMaxMessageSize(this.factory.Endpoint.Binding); } public MetadataExchangeClient(Binding mexBinding) { if (mexBinding == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("mexBinding"); } this.factory = new ChannelFactory<IMetadataExchange>(mexBinding); this.maxMessageSize = GetMaxMessageSize(this.factory.Endpoint.Binding); } //Configuration for credentials public ClientCredentials SoapCredentials { get { return this.factory.Credentials; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } this.factory.Endpoint.Behaviors.RemoveAll<ClientCredentials>(); this.factory.Endpoint.Behaviors.Add(value); } } public ICredentials HttpCredentials { get { return this.webRequestCredentials; } set { this.webRequestCredentials = value; } } // Configuration options for the entire MetadataResolver public TimeSpan OperationTimeout { get { return this.resolveTimeout; } set { if (value < TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.GetString(SR.SFxTimeoutOutOfRange0))); } if (TimeoutHelper.IsTooLarge(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.GetString(SR.SFxTimeoutOutOfRangeTooBig))); } this.resolveTimeout = value; } } public int MaximumResolvedReferences { get { return this.maximumResolvedReferences; } set { if (value < 1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.GetString(SR.SFxMaximumResolvedReferencesOutOfRange, value))); } this.maximumResolvedReferences = value; } } public bool ResolveMetadataReferences { get { return this.resolveMetadataReferences; } set { this.resolveMetadataReferences = value; } } internal object ThisLock { get { return this.thisLock; } } internal long MaxMessageSize { get { return this.maxMessageSize; } set { this.maxMessageSize = value; } } internal XmlDictionaryReaderQuotas ReaderQuotas { get { if (this.readerQuotas == null) { if (this.factory != null) { BindingElementCollection bindingElementCollection = this.factory.Endpoint.Binding.CreateBindingElements(); if (bindingElementCollection != null) { MessageEncodingBindingElement bindingElement = bindingElementCollection.Find<MessageEncodingBindingElement>(); if (bindingElement != null) { this.readerQuotas = bindingElement.GetIndividualProperty<XmlDictionaryReaderQuotas>(); } } } this.readerQuotas = this.readerQuotas ?? EncoderDefaults.ReaderQuotas; } return this.readerQuotas; } } [Fx.Tag.SecurityNote(Critical = "Uses ClientSection.UnsafeGetSection to get config in PT.", Safe = "Does not leak config object, just calculates a bool.")] [SecuritySafeCritical] bool ClientEndpointExists(string name) { ClientSection clientSection = ClientSection.UnsafeGetSection(); if (clientSection == null) return false; foreach (ChannelEndpointElement endpoint in clientSection.Endpoints) { if (endpoint.Name == name && endpoint.Contract == ServiceMetadataBehavior.MexContractName) return true; } return false; } bool IsHttpOrHttps(Uri address) { return address.Scheme == Uri.UriSchemeHttp || address.Scheme == Uri.UriSchemeHttps; } void CreateChannelFactory(string scheme) { if (ClientEndpointExists(scheme)) { this.factory = new ChannelFactory<IMetadataExchange>(scheme); } else { Binding mexBinding = null; if (MetadataExchangeBindings.TryGetBindingForScheme(scheme, out mexBinding)) { this.factory = new ChannelFactory<IMetadataExchange>(mexBinding); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("scheme", SR.GetString(SR.SFxMetadataExchangeClientCouldNotCreateChannelFactoryBadScheme, scheme)); } } this.maxMessageSize = GetMaxMessageSize(this.factory.Endpoint.Binding); } void Validate(Uri address, MetadataExchangeClientMode mode) { if (address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address"); } if (!address.IsAbsoluteUri) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("address", SR.GetString(SR.SFxCannotGetMetadataFromRelativeAddress, address)); } if (mode == MetadataExchangeClientMode.HttpGet && !IsHttpOrHttps(address)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("address", SR.GetString(SR.SFxCannotHttpGetMetadataFromAddress, address)); } MetadataExchangeClientModeHelper.Validate(mode); } public IAsyncResult BeginGetMetadata(AsyncCallback callback, object asyncState) { if (ctorUri != null) return BeginGetMetadata(ctorUri, MetadataExchangeClientMode.HttpGet, callback, asyncState); if (ctorEndpointAddress != null) return BeginGetMetadata(ctorEndpointAddress, callback, asyncState); else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxMetadataExchangeClientNoMetadataAddress))); } public IAsyncResult BeginGetMetadata(Uri address, MetadataExchangeClientMode mode, AsyncCallback callback, object asyncState) { Validate(address, mode); if (mode == MetadataExchangeClientMode.HttpGet) { return this.BeginGetMetadata(new MetadataLocationRetriever(address, this), callback, asyncState); } else { return this.BeginGetMetadata(new MetadataReferenceRetriever(new EndpointAddress(address), this), callback, asyncState); } } public IAsyncResult BeginGetMetadata(EndpointAddress address, AsyncCallback callback, object asyncState) { if (address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address"); } return this.BeginGetMetadata(new MetadataReferenceRetriever(address, this), callback, asyncState); } IAsyncResult BeginGetMetadata(MetadataRetriever retriever, AsyncCallback callback, object asyncState) { ResolveCallState state = new ResolveCallState(this.maximumResolvedReferences, this.resolveMetadataReferences, new TimeoutHelper(this.OperationTimeout), this); state.StackedRetrievers.Push(retriever); return new AsyncMetadataResolver(state, callback, asyncState); } public MetadataSet EndGetMetadata(IAsyncResult result) { return AsyncMetadataResolver.End(result); } public Task<MetadataSet> GetMetadataAsync() { if (ctorUri != null) return GetMetadataAsync(ctorUri, MetadataExchangeClientMode.HttpGet); if (ctorEndpointAddress != null) return GetMetadataAsync(ctorEndpointAddress); else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxMetadataExchangeClientNoMetadataAddress))); } public Task<MetadataSet> GetMetadataAsync(Uri address, MetadataExchangeClientMode mode) { Validate(address, mode); MetadataRetriever retriever = (mode == MetadataExchangeClientMode.HttpGet) ? (MetadataRetriever) new MetadataLocationRetriever(address, this) : (MetadataRetriever) new MetadataReferenceRetriever(new EndpointAddress(address), this); return Task.Factory.FromAsync<MetadataRetriever, MetadataSet>(this.BeginGetMetadata, this.EndGetMetadata, retriever, /* state */ null); } public Task<MetadataSet> GetMetadataAsync(EndpointAddress address) { if (address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address"); } return Task.Factory.FromAsync<MetadataRetriever, MetadataSet>(this.BeginGetMetadata, this.EndGetMetadata, new MetadataReferenceRetriever(address, this), /* state */ null); } public Task<MetadataSet> GetMetadataAsync(EndpointAddress address, Uri via) { if (address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address"); } if (via == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("via"); } return Task.Factory.FromAsync<MetadataRetriever, MetadataSet>(this.BeginGetMetadata, this.EndGetMetadata, new MetadataReferenceRetriever(address, via, this), /* state */ null); } public MetadataSet GetMetadata() { if (ctorUri != null) return GetMetadata(ctorUri, MetadataExchangeClientMode.HttpGet); if (ctorEndpointAddress != null) return GetMetadata(ctorEndpointAddress); else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxMetadataExchangeClientNoMetadataAddress))); } public MetadataSet GetMetadata(Uri address, MetadataExchangeClientMode mode) { Validate(address, mode); MetadataRetriever retriever; if (mode == MetadataExchangeClientMode.HttpGet) { retriever = new MetadataLocationRetriever(address, this); } else { retriever = new MetadataReferenceRetriever(new EndpointAddress(address), this); } return GetMetadata(retriever); } public MetadataSet GetMetadata(EndpointAddress address) { if (address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address"); } MetadataReferenceRetriever retriever = new MetadataReferenceRetriever(address, this); return GetMetadata(retriever); } public MetadataSet GetMetadata(EndpointAddress address, Uri via) { if (address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address"); } if (via == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("via"); } MetadataReferenceRetriever retriever = new MetadataReferenceRetriever(address, via, this); return GetMetadata(retriever); } MetadataSet GetMetadata(MetadataRetriever retriever) { ResolveCallState resolveCallState = new ResolveCallState(this.maximumResolvedReferences, this.resolveMetadataReferences, new TimeoutHelper(this.OperationTimeout), this); resolveCallState.StackedRetrievers.Push(retriever); this.ResolveNext(resolveCallState); return resolveCallState.MetadataSet; } void ResolveNext(ResolveCallState resolveCallState) { if (resolveCallState.StackedRetrievers.Count > 0) { MetadataRetriever retriever = resolveCallState.StackedRetrievers.Pop(); if (resolveCallState.HasBeenUsed(retriever)) { this.ResolveNext(resolveCallState); } else { if (resolveCallState.ResolvedMaxResolvedReferences) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxResolvedMaxResolvedReferences))); } resolveCallState.LogUse(retriever); resolveCallState.HandleSection(retriever.Retrieve(resolveCallState.TimeoutHelper)); this.ResolveNext(resolveCallState); } } } protected internal virtual ChannelFactory<IMetadataExchange> GetChannelFactory(EndpointAddress metadataAddress, string dialect, string identifier) { return this.factory; } static long GetMaxMessageSize(Binding mexBinding) { BindingElementCollection bindingElementCollection = mexBinding.CreateBindingElements(); TransportBindingElement bindingElement = bindingElementCollection.Find<TransportBindingElement>(); if (bindingElement == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxBindingDoesNotHaveATransportBindingElement))); } return bindingElement.MaxReceivedMessageSize; } protected internal virtual HttpWebRequest GetWebRequest(Uri location, string dialect, string identifier) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(location); request.Method = "GET"; request.Credentials = this.HttpCredentials; return request; } internal static void TraceSendRequest(Uri address) { TraceSendRequest(TraceCode.MetadataExchangeClientSendRequest, SR.GetString(SR.TraceCodeMetadataExchangeClientSendRequest), address.ToString(), MetadataExchangeClientMode.HttpGet.ToString()); } internal static void TraceSendRequest(EndpointAddress address) { TraceSendRequest(TraceCode.MetadataExchangeClientSendRequest, SR.GetString(SR.TraceCodeMetadataExchangeClientSendRequest), address.ToString(), MetadataExchangeClientMode.MetadataExchange.ToString()); } static void TraceSendRequest(int traceCode, string traceDescription, string address, string mode) { if (DiagnosticUtility.ShouldTraceInformation) { Hashtable h = new Hashtable(2) { { "Address", address }, { "Mode", mode } }; TraceUtility.TraceEvent(TraceEventType.Information, traceCode, traceDescription, new DictionaryTraceRecord(h), null, null); } } internal static void TraceReceiveReply(string sourceUrl, Type metadataType) { if (DiagnosticUtility.ShouldTraceInformation) { Hashtable h = new Hashtable(2); h.Add("SourceUrl", sourceUrl); h.Add("MetadataType", metadataType.ToString()); TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.MetadataExchangeClientReceiveReply, SR.GetString(SR.TraceCodeMetadataExchangeClientReceiveReply), new DictionaryTraceRecord(h), null, null); } } class ResolveCallState { Dictionary<MetadataRetriever, MetadataRetriever> usedRetrievers; // to prevent looping when chasing MetadataReferences MetadataSet metadataSet; int maxResolvedReferences; bool resolveMetadataReferences; Stack<MetadataRetriever> stackedRetrievers; MetadataExchangeClient resolver; TimeoutHelper timeoutHelper; internal ResolveCallState(int maxResolvedReferences, bool resolveMetadataReferences, TimeoutHelper timeoutHelper, MetadataExchangeClient resolver) { this.maxResolvedReferences = maxResolvedReferences; this.resolveMetadataReferences = resolveMetadataReferences; this.resolver = resolver; this.timeoutHelper = timeoutHelper; this.metadataSet = new MetadataSet(); this.usedRetrievers = new Dictionary<MetadataRetriever, MetadataRetriever>(); this.stackedRetrievers = new Stack<MetadataRetriever>(); } internal MetadataSet MetadataSet { get { return this.metadataSet; } } internal Stack<MetadataRetriever> StackedRetrievers { get { return this.stackedRetrievers; } } internal bool ResolvedMaxResolvedReferences { get { return this.usedRetrievers.Count == this.maxResolvedReferences; } } internal TimeoutHelper TimeoutHelper { get { return this.timeoutHelper; } } internal void HandleSection(MetadataSection section) { if (section.Metadata is MetadataSet) { foreach (MetadataSection innerSection in ((MetadataSet)section.Metadata).MetadataSections) { innerSection.SourceUrl = section.SourceUrl; this.HandleSection(innerSection); } } else if (section.Metadata is MetadataReference) { if (this.resolveMetadataReferences) { EndpointAddress address = ((MetadataReference)section.Metadata).Address; MetadataRetriever retriever = new MetadataReferenceRetriever(address, this.resolver, section.Dialect, section.Identifier); this.stackedRetrievers.Push(retriever); } else { this.metadataSet.MetadataSections.Add(section); } } else if (section.Metadata is MetadataLocation) { if (this.resolveMetadataReferences) { string location = ((MetadataLocation)section.Metadata).Location; MetadataRetriever retriever = new MetadataLocationRetriever(this.CreateUri(section.SourceUrl, location), this.resolver, section.Dialect, section.Identifier); this.stackedRetrievers.Push(retriever); } else { this.metadataSet.MetadataSections.Add(section); } } else if (section.Metadata is WsdlNS.ServiceDescription) { if (this.resolveMetadataReferences) { this.HandleWsdlImports(section); } this.metadataSet.MetadataSections.Add(section); } else if (section.Metadata is XsdNS.XmlSchema) { if (this.resolveMetadataReferences) { this.HandleSchemaImports(section); } this.metadataSet.MetadataSections.Add(section); } else { this.metadataSet.MetadataSections.Add(section); } } void HandleSchemaImports(MetadataSection section) { XsdNS.XmlSchema schema = (XsdNS.XmlSchema)section.Metadata; foreach (XsdNS.XmlSchemaExternal external in schema.Includes) { if (!String.IsNullOrEmpty(external.SchemaLocation)) { EnqueueRetrieverIfShouldResolve( new MetadataLocationRetriever( this.CreateUri(section.SourceUrl, external.SchemaLocation), this.resolver)); } } } void HandleWsdlImports(MetadataSection section) { WsdlNS.ServiceDescription wsdl = (WsdlNS.ServiceDescription)section.Metadata; foreach (WsdlNS.Import import in wsdl.Imports) { if (!String.IsNullOrEmpty(import.Location)) { EnqueueRetrieverIfShouldResolve(new MetadataLocationRetriever(this.CreateUri(section.SourceUrl, import.Location), this.resolver)); } } foreach (XsdNS.XmlSchema schema in wsdl.Types.Schemas) { MetadataSection schemaSection = new MetadataSection(null, null, schema); schemaSection.SourceUrl = section.SourceUrl; this.HandleSchemaImports(schemaSection); } } Uri CreateUri(string baseUri, string relativeUri) { return new Uri(new Uri(baseUri), relativeUri); } void EnqueueRetrieverIfShouldResolve(MetadataRetriever retriever) { if (this.resolveMetadataReferences) { this.stackedRetrievers.Push(retriever); } } internal bool HasBeenUsed(MetadataRetriever retriever) { return this.usedRetrievers.ContainsKey(retriever); } internal void LogUse(MetadataRetriever retriever) { this.usedRetrievers.Add(retriever, retriever); } } abstract class MetadataRetriever { protected MetadataExchangeClient resolver; protected string dialect; protected string identifier; public MetadataRetriever(MetadataExchangeClient resolver, string dialect, string identifier) { this.resolver = resolver; this.dialect = dialect; this.identifier = identifier; } internal MetadataSection Retrieve(TimeoutHelper timeoutHelper) { try { using (XmlReader reader = this.DownloadMetadata(timeoutHelper)) { return MetadataRetriever.CreateMetadataSection(reader, this.SourceUrl); } } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.SFxBadMetadataReference, this.SourceUrl), e)); } } internal abstract IAsyncResult BeginRetrieve(TimeoutHelper timeoutHelper, AsyncCallback callback, object state); internal abstract MetadataSection EndRetrieve(IAsyncResult result); static internal MetadataSection CreateMetadataSection(XmlReader reader, string sourceUrl) { MetadataSection section = null; Type metadataType = null; if (CanReadMetadataSet(reader)) { MetadataSet newSet = MetadataSet.ReadFrom(reader); section = new MetadataSection(MetadataSection.MetadataExchangeDialect, null, newSet); metadataType = typeof(MetadataSet); } else if (WsdlNS.ServiceDescription.CanRead(reader)) { WsdlNS.ServiceDescription wsdl = WsdlNS.ServiceDescription.Read(reader); section = MetadataSection.CreateFromServiceDescription(wsdl); metadataType = typeof(WsdlNS.ServiceDescription); } else if (CanReadSchema(reader)) { XsdNS.XmlSchema schema = XsdNS.XmlSchema.Read(reader, null); section = MetadataSection.CreateFromSchema(schema); metadataType = typeof(XsdNS.XmlSchema); } else { XmlDocument doc = new XmlDocument(); doc.Load(reader); section = new MetadataSection(null, null, doc.DocumentElement); metadataType = typeof(XmlElement); } section.SourceUrl = sourceUrl; TraceReceiveReply(sourceUrl, metadataType); return section; } protected abstract XmlReader DownloadMetadata(TimeoutHelper timeoutHelper); protected abstract string SourceUrl { get; } static bool CanReadSchema(XmlReader reader) { return reader.LocalName == MetadataStrings.XmlSchema.Schema && reader.NamespaceURI == XsdNS.XmlSchema.Namespace; } static bool CanReadMetadataSet(XmlReader reader) { return reader.LocalName == MetadataStrings.MetadataExchangeStrings.Metadata && reader.NamespaceURI == MetadataStrings.MetadataExchangeStrings.Namespace; } } class MetadataLocationRetriever : MetadataRetriever { Uri location; Uri responseLocation; internal MetadataLocationRetriever(Uri location, MetadataExchangeClient resolver) : this(location, resolver, null, null) { } internal MetadataLocationRetriever(Uri location, MetadataExchangeClient resolver, string dialect, string identifier) : base(resolver, dialect, identifier) { ValidateLocation(location); this.location = location; this.responseLocation = location; } internal static void ValidateLocation(Uri location) { if (location == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("location"); } if (location.Scheme != Uri.UriSchemeHttp && location.Scheme != Uri.UriSchemeHttps) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("location", SR.GetString(SR.SFxCannotGetMetadataFromLocation, location.ToString())); } } public override bool Equals(object obj) { return obj is MetadataLocationRetriever && ((MetadataLocationRetriever)obj).location == this.location; } public override int GetHashCode() { return location.GetHashCode(); } protected override XmlReader DownloadMetadata(TimeoutHelper timeoutHelper) { HttpWebResponse response; HttpWebRequest request; try { request = this.resolver.GetWebRequest(this.location, this.dialect, this.identifier); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.SFxMetadataExchangeClientCouldNotCreateWebRequest, this.location, this.dialect, this.identifier), e)); } TraceSendRequest(this.location); request.Timeout = TimeoutHelper.ToMilliseconds(timeoutHelper.RemainingTime()); response = (HttpWebResponse)request.GetResponse(); responseLocation = request.Address; return MetadataLocationRetriever.GetXmlReader(response, this.resolver.MaxMessageSize, this.resolver.ReaderQuotas); } internal static XmlReader GetXmlReader(HttpWebResponse response, long maxMessageSize, XmlDictionaryReaderQuotas readerQuotas) { readerQuotas = readerQuotas ?? EncoderDefaults.ReaderQuotas; XmlReader reader = XmlDictionaryReader.CreateTextReader( new MaxMessageSizeStream(response.GetResponseStream(), maxMessageSize), EncodingHelper.GetDictionaryReaderEncoding(response.ContentType), readerQuotas, null); reader.Read(); reader.MoveToContent(); return reader; } internal override IAsyncResult BeginRetrieve(TimeoutHelper timeoutHelper, AsyncCallback callback, object state) { AsyncMetadataLocationRetriever result; try { HttpWebRequest request; try { request = this.resolver.GetWebRequest(this.location, this.dialect, this.identifier); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.SFxMetadataExchangeClientCouldNotCreateWebRequest, this.location, this.dialect, this.identifier), e)); } TraceSendRequest(this.location); result = new AsyncMetadataLocationRetriever(request, this.resolver.MaxMessageSize, this.resolver.ReaderQuotas, timeoutHelper, callback, state); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.SFxBadMetadataReference, this.SourceUrl), e)); } return result; } internal override MetadataSection EndRetrieve(IAsyncResult result) { try { return AsyncMetadataLocationRetriever.End(result); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.SFxBadMetadataReference, this.SourceUrl), e)); } } protected override string SourceUrl { get { return this.responseLocation.ToString(); } } class AsyncMetadataLocationRetriever : AsyncResult { MetadataSection section; long maxMessageSize; XmlDictionaryReaderQuotas readerQuotas; internal AsyncMetadataLocationRetriever(WebRequest request, long maxMessageSize, XmlDictionaryReaderQuotas readerQuotas, TimeoutHelper timeoutHelper, AsyncCallback callback, object state) : base(callback, state) { this.maxMessageSize = maxMessageSize; this.readerQuotas = readerQuotas; IAsyncResult result = request.BeginGetResponse(Fx.ThunkCallback(new AsyncCallback(this.GetResponseCallback)), request); //Register a callback to abort the request if we hit the timeout. ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, Fx.ThunkCallback(new WaitOrTimerCallback(RetrieveTimeout)), request, TimeoutHelper.ToMilliseconds(timeoutHelper.RemainingTime()), /* executeOnlyOnce */ true); if (result.CompletedSynchronously) { HandleResult(result); this.Complete(true); } } static void RetrieveTimeout(object state, bool timedOut) { if (timedOut) { HttpWebRequest request = state as HttpWebRequest; if (request != null) { request.Abort(); } } } internal static MetadataSection End(IAsyncResult result) { AsyncMetadataLocationRetriever retrieverResult = AsyncResult.End<AsyncMetadataLocationRetriever>(result); return retrieverResult.section; } internal void GetResponseCallback(IAsyncResult result) { if (result.CompletedSynchronously) return; Exception exception = null; try { HandleResult(result); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) throw; exception = e; } this.Complete(false, exception); } void HandleResult(IAsyncResult result) { HttpWebRequest request = (HttpWebRequest)result.AsyncState; using (XmlReader reader = MetadataLocationRetriever.GetXmlReader((HttpWebResponse)request.EndGetResponse(result), this.maxMessageSize, this.readerQuotas)) { section = MetadataRetriever.CreateMetadataSection(reader, request.Address.ToString()); } } } } class MetadataReferenceRetriever : MetadataRetriever { EndpointAddress address; Uri via; public MetadataReferenceRetriever(EndpointAddress address, MetadataExchangeClient resolver) : this(address, null, resolver, null, null) { } public MetadataReferenceRetriever(EndpointAddress address, Uri via, MetadataExchangeClient resolver) : this(address, via, resolver, null, null) { } public MetadataReferenceRetriever(EndpointAddress address, MetadataExchangeClient resolver, string dialect, string identifier) : this(address, null, resolver, dialect, identifier) { } MetadataReferenceRetriever(EndpointAddress address, Uri via, MetadataExchangeClient resolver, string dialect, string identifier) : base(resolver, dialect, identifier) { if (address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address"); } this.address = address; this.via = via; } protected override string SourceUrl { get { return this.address.Uri.ToString(); } } internal override IAsyncResult BeginRetrieve(TimeoutHelper timeoutHelper, AsyncCallback callback, object state) { try { IMetadataExchange metadataClient; MessageVersion messageVersion; lock (this.resolver.ThisLock) { ChannelFactory<IMetadataExchange> channelFactory; try { channelFactory = this.resolver.GetChannelFactory(this.address, this.dialect, this.identifier); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.SFxMetadataExchangeClientCouldNotCreateChannelFactory, this.address, this.dialect, this.identifier), e)); } metadataClient = CreateChannel(channelFactory); messageVersion = channelFactory.Endpoint.Binding.MessageVersion; } TraceSendRequest(this.address); return new AsyncMetadataReferenceRetriever(metadataClient, messageVersion, timeoutHelper, callback, state); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.SFxBadMetadataReference, this.SourceUrl), e)); } } IMetadataExchange CreateChannel(ChannelFactory<IMetadataExchange> channelFactory) { if (this.via != null) { return channelFactory.CreateChannel(this.address, this.via); } else { return channelFactory.CreateChannel(this.address); } } static Message CreateGetMessage(MessageVersion messageVersion) { return Message.CreateMessage(messageVersion, MetadataStrings.WSTransfer.GetAction); } protected override XmlReader DownloadMetadata(TimeoutHelper timeoutHelper) { IMetadataExchange metadataClient; MessageVersion messageVersion; lock (this.resolver.ThisLock) { ChannelFactory<IMetadataExchange> channelFactory; try { channelFactory = this.resolver.GetChannelFactory(this.address, this.dialect, this.identifier); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.SFxMetadataExchangeClientCouldNotCreateChannelFactory, this.address, this.dialect, this.identifier), e)); } metadataClient = CreateChannel(channelFactory); messageVersion = channelFactory.Endpoint.Binding.MessageVersion; } Message response; TraceSendRequest(this.address); try { using (Message getMessage = CreateGetMessage(messageVersion)) { ((IClientChannel)metadataClient).OperationTimeout = timeoutHelper.RemainingTime(); response = metadataClient.Get(getMessage); } ((IClientChannel)metadataClient).Close(); } finally { ((IClientChannel)metadataClient).Abort(); } if (response.IsFault) { MessageFault fault = MessageFault.CreateFault(response, 64 * 1024); StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture); XmlWriter xmlWriter = XmlWriter.Create(stringWriter); fault.WriteTo(xmlWriter, response.Version.Envelope); xmlWriter.Flush(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(stringWriter.ToString())); } return response.GetReaderAtBodyContents(); } internal override MetadataSection EndRetrieve(IAsyncResult result) { try { return AsyncMetadataReferenceRetriever.End(result); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.SFxBadMetadataReference, this.SourceUrl), e)); } } public override bool Equals(object obj) { return obj is MetadataReferenceRetriever && ((MetadataReferenceRetriever)obj).address == this.address; } public override int GetHashCode() { return address.GetHashCode(); } class AsyncMetadataReferenceRetriever : AsyncResult { MetadataSection section; Message message; internal AsyncMetadataReferenceRetriever(IMetadataExchange metadataClient, MessageVersion messageVersion, TimeoutHelper timeoutHelper, AsyncCallback callback, object state) : base(callback, state) { message = MetadataReferenceRetriever.CreateGetMessage(messageVersion); ((IClientChannel)metadataClient).OperationTimeout = timeoutHelper.RemainingTime(); IAsyncResult result = metadataClient.BeginGet(message, Fx.ThunkCallback(new AsyncCallback(this.RequestCallback)), metadataClient); if (result.CompletedSynchronously) { HandleResult(result); this.Complete(true); } } internal static MetadataSection End(IAsyncResult result) { AsyncMetadataReferenceRetriever retrieverResult = AsyncResult.End<AsyncMetadataReferenceRetriever>(result); return retrieverResult.section; } internal void RequestCallback(IAsyncResult result) { if (result.CompletedSynchronously) return; Exception exception = null; try { HandleResult(result); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) throw; exception = e; } this.Complete(false, exception); } void HandleResult(IAsyncResult result) { IMetadataExchange metadataClient = (IMetadataExchange)result.AsyncState; Message response = metadataClient.EndGet(result); using (this.message) { if (response.IsFault) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxBadMetadataReference, ((IClientChannel)metadataClient).RemoteAddress.Uri.ToString()))); } else { using (XmlReader reader = response.GetReaderAtBodyContents()) { section = MetadataRetriever.CreateMetadataSection(reader, ((IClientChannel)metadataClient).RemoteAddress.Uri.ToString()); } } } } } } class AsyncMetadataResolver : AsyncResult { ResolveCallState resolveCallState; internal AsyncMetadataResolver(ResolveCallState resolveCallState, AsyncCallback callerCallback, object callerAsyncState) : base(callerCallback, callerAsyncState) { if (resolveCallState == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("resolveCallState"); } this.resolveCallState = resolveCallState; Exception exception = null; bool doneResolving = false; try { doneResolving = this.ResolveNext(); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) throw; exception = e; doneResolving = true; } if (doneResolving) { this.Complete(true, exception); } } bool ResolveNext() { bool doneResolving = false; if (this.resolveCallState.StackedRetrievers.Count > 0) { MetadataRetriever retriever = this.resolveCallState.StackedRetrievers.Pop(); if (resolveCallState.HasBeenUsed(retriever)) { doneResolving = this.ResolveNext(); } else { if (resolveCallState.ResolvedMaxResolvedReferences) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxResolvedMaxResolvedReferences))); } else { resolveCallState.LogUse(retriever); IAsyncResult result = retriever.BeginRetrieve(this.resolveCallState.TimeoutHelper, Fx.ThunkCallback(new AsyncCallback(this.RetrieveCallback)), retriever); if (result.CompletedSynchronously) { doneResolving = HandleResult(result); } } } } else { doneResolving = true; } return doneResolving; } internal static MetadataSet End(IAsyncResult result) { AsyncMetadataResolver resolverResult = AsyncResult.End<AsyncMetadataResolver>(result); return resolverResult.resolveCallState.MetadataSet; } internal void RetrieveCallback(IAsyncResult result) { if (result.CompletedSynchronously) return; Exception exception = null; bool doneResolving = false; try { doneResolving = HandleResult(result); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) throw; exception = e; doneResolving = true; } if (doneResolving) { this.Complete(false, exception); } } bool HandleResult(IAsyncResult result) { MetadataRetriever retriever = (MetadataRetriever)result.AsyncState; MetadataSection section = retriever.EndRetrieve(result); this.resolveCallState.HandleSection(section); return this.ResolveNext(); } } internal class EncodingHelper { internal const string ApplicationBase = "application"; internal static Encoding GetRfcEncoding(string contentTypeStr) { Encoding e = null; ContentType contentType = null; try { contentType = new ContentType(contentTypeStr); string charset = contentType == null ? string.Empty : contentType.CharSet; if (charset != null && charset.Length > 0) e = Encoding.GetEncoding(charset); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception ex) { if (Fx.IsFatal(ex)) throw; } // default to ASCII encoding per RFC 2376/3023 if (IsApplication(contentType)) return e == null ? new ASCIIEncoding() : e; else return e; } internal static bool IsApplication(ContentType contentType) { return string.Compare(contentType == null ? string.Empty : contentType.MediaType, ApplicationBase, StringComparison.OrdinalIgnoreCase) == 0; } internal static Encoding GetDictionaryReaderEncoding(string contentTypeStr) { if (String.IsNullOrEmpty(contentTypeStr)) return TextEncoderDefaults.Encoding; Encoding encoding = GetRfcEncoding(contentTypeStr); if (encoding == null) return TextEncoderDefaults.Encoding; string charSet = encoding.WebName; Encoding[] supportedEncodings = TextEncoderDefaults.SupportedEncodings; for (int i = 0; i < supportedEncodings.Length; i++) { if (charSet == supportedEncodings[i].WebName) return encoding; } return TextEncoderDefaults.Encoding; } } } public enum MetadataExchangeClientMode { MetadataExchange, HttpGet, } static class MetadataExchangeClientModeHelper { static public bool IsDefined(MetadataExchangeClientMode x) { return x == MetadataExchangeClientMode.MetadataExchange || x == MetadataExchangeClientMode.HttpGet || false; } public static void Validate(MetadataExchangeClientMode value) { if (!IsDefined(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("value", (int)value, typeof(MetadataExchangeClientMode))); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; using static System.Runtime.Intrinsics.X86.Sse; using static System.Runtime.Intrinsics.X86.Sse2; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void InsertVector128Int321() { var test = new InsertVector128Test__InsertVector128Int321(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class InsertVector128Test__InsertVector128Int321 { private struct TestStruct { public Vector256<Int32> _fld1; public Vector128<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(InsertVector128Test__InsertVector128Int321 testClass) { var result = Avx2.InsertVector128(_fld1, _fld2, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector256<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector256<Int32> _fld1; private Vector128<Int32> _fld2; private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable; static InsertVector128Test__InsertVector128Int321() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public InsertVector128Test__InsertVector128Int321() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.InsertVector128( Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.InsertVector128( Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), LoadVector128((Int32*)(_dataTable.inArray2Ptr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.InsertVector128( Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.InsertVector128), new Type[] { typeof(Vector256<Int32>), typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.InsertVector128), new Type[] { typeof(Vector256<Int32>), typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), LoadVector128((Int32*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.InsertVector128), new Type[] { typeof(Vector256<Int32>), typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.InsertVector128( _clsVar1, _clsVar2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = Avx2.InsertVector128(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)); var right = LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.InsertVector128(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)); var right = LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.InsertVector128(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertVector128Test__InsertVector128Int321(); var result = Avx2.InsertVector128(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.InsertVector128(_fld1, _fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.InsertVector128(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int32> left, Vector128<Int32> right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != left[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((i > 3 ? result[i] != right[i - 4] : result[i] != left[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.InsertVector128)}<Int32>(Vector256<Int32>, Vector128<Int32>.1): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = 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 NPOI.POIFS.Common; using NPOI.POIFS.Dev; using NPOI.POIFS.Properties; using NPOI.Util; using System.IO; using System.Collections.Generic; using System; using System.Text; using System.Collections; namespace NPOI.POIFS.FileSystem { /** * This class manages a document in the NIO POIFS filesystem. * This is the {@link NPOIFSFileSystem} version. */ public class NPOIFSDocument : POIFSViewable { private DocumentProperty _property; private NPOIFSFileSystem _filesystem; private NPOIFSStream _stream; private int _block_size; /** * Constructor for an existing Document */ public NPOIFSDocument(DocumentProperty property, NPOIFSFileSystem filesystem) { this._property = property; this._filesystem = filesystem; if (property.Size < POIFSConstants.BIG_BLOCK_MINIMUM_DOCUMENT_SIZE) { _stream = new NPOIFSStream(_filesystem.GetMiniStore(), property.StartBlock); _block_size = _filesystem.GetMiniStore().GetBlockStoreBlockSize(); } else { _stream = new NPOIFSStream(_filesystem, property.StartBlock); _block_size = _filesystem.GetBlockStoreBlockSize(); } } /** * Constructor for a new Document * * @param name the name of the POIFSDocument * @param stream the InputStream we read data from */ public NPOIFSDocument(String name, NPOIFSFileSystem filesystem, Stream stream) { this._filesystem = filesystem; // Buffer the contents into memory. This is a bit icky... // TODO Replace with a buffer up to the mini stream size, then streaming write byte[] contents; if (stream is MemoryStream) { MemoryStream bais = (MemoryStream)stream; contents = new byte[bais.Length]; bais.Read(contents, 0, contents.Length); } else { MemoryStream baos = new MemoryStream(); IOUtils.Copy(stream, baos); contents = baos.ToArray(); } // Do we need to store as a mini stream or a full one? if (contents.Length <= POIFSConstants.BIG_BLOCK_MINIMUM_DOCUMENT_SIZE) { _stream = new NPOIFSStream(filesystem.GetMiniStore()); _block_size = _filesystem.GetMiniStore().GetBlockStoreBlockSize(); } else { _stream = new NPOIFSStream(filesystem); _block_size = _filesystem.GetBlockStoreBlockSize(); } // Store it _stream.UpdateContents(contents); // And build the property for it this._property = new DocumentProperty(name, contents.Length); _property.StartBlock = _stream.GetStartBlock(); } public int GetDocumentBlockSize() { return _block_size; } public IEnumerator<ByteBuffer> GetBlockIterator() { if (Size > 0) { return _stream.GetBlockIterator(); } else { //List<byte[]> empty = Collections.emptyList(); List<ByteBuffer> empty = new List<ByteBuffer>(); return empty.GetEnumerator(); } } /** * @return size of the document */ public int Size { get { return _property.Size; } } /** * @return the instance's DocumentProperty */ public DocumentProperty DocumentProperty { get { return _property; } } /** * Get an array of objects, some of which may implement POIFSViewable * * @return an array of Object; may not be null, but may be empty */ protected Object[] GetViewableArray() { Object[] results = new Object[1]; String result; try { if (Size > 0) { // Get all the data into a single array byte[] data = new byte[Size]; int offset = 0; foreach (ByteBuffer buffer in _stream) { int length = Math.Min(_block_size, data.Length - offset); buffer.Read(data, offset, length); offset += length; } MemoryStream output = new MemoryStream(); HexDump.Dump(data, 0, output, 0); result = output.ToString(); } else { result = "<NO DATA>"; } } catch (IOException e) { result = e.Message; } results[0] = result; return results; } /** * Get an Iterator of objects, some of which may implement POIFSViewable * * @return an Iterator; may not be null, but may have an empty back end * store */ protected IEnumerator GetViewableIterator() { // return Collections.EMPTY_LIST.iterator(); return null; } /** * Provides a short description of the object, to be used when a * POIFSViewable object has not provided its contents. * * @return short description */ protected String GetShortDescription() { StringBuilder buffer = new StringBuilder(); buffer.Append("Document: \"").Append(_property.Name).Append("\""); buffer.Append(" size = ").Append(Size); return buffer.ToString(); } #region POIFSViewable Members public bool PreferArray { get { return true; } } public string ShortDescription { get { return GetShortDescription(); } } public Array ViewableArray { get { return GetViewableArray(); } } public IEnumerator ViewableIterator { get { return GetViewableIterator(); } } #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.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue { internal sealed class StatementSyntaxComparer : SyntaxComparer { internal static readonly StatementSyntaxComparer Default = new StatementSyntaxComparer(); private readonly SyntaxNode _oldRootChild; private readonly SyntaxNode _newRootChild; private readonly SyntaxNode _oldRoot; private readonly SyntaxNode _newRoot; private StatementSyntaxComparer() { } internal StatementSyntaxComparer(SyntaxNode oldRootChild, SyntaxNode newRootChild) { _oldRootChild = oldRootChild; _newRootChild = newRootChild; _oldRoot = oldRootChild.Parent; _newRoot = newRootChild.Parent; } #region Tree Traversal protected internal override bool TryGetParent(SyntaxNode node, out SyntaxNode parent) { parent = node.Parent; while (parent != null && !HasLabel(parent)) { parent = parent.Parent; } return parent != null; } protected internal override IEnumerable<SyntaxNode> GetChildren(SyntaxNode node) { Debug.Assert(HasLabel(node)); if (node == _oldRoot || node == _newRoot) { return EnumerateRootChildren(node); } return IsLeaf(node) ? null : EnumerateNonRootChildren(node); } private IEnumerable<SyntaxNode> EnumerateNonRootChildren(SyntaxNode node) { foreach (var child in node.ChildNodes()) { if (LambdaUtilities.IsLambdaBodyStatementOrExpression(child)) { continue; } if (HasLabel(child)) { yield return child; } else { foreach (var descendant in child.DescendantNodes(DescendIntoChildren)) { if (HasLabel(descendant)) { yield return descendant; } } } } } private IEnumerable<SyntaxNode> EnumerateRootChildren(SyntaxNode root) { Debug.Assert(_oldRoot != null && _newRoot != null); var child = (root == _oldRoot) ? _oldRootChild : _newRootChild; if (GetLabelImpl(child) != Label.Ignored) { yield return child; } else { foreach (var descendant in child.DescendantNodes(DescendIntoChildren)) { if (HasLabel(descendant)) { yield return descendant; } } } } private bool DescendIntoChildren(SyntaxNode node) { return !LambdaUtilities.IsLambdaBodyStatementOrExpression(node) && !HasLabel(node); } protected internal sealed override IEnumerable<SyntaxNode> GetDescendants(SyntaxNode node) { if (node == _oldRoot || node == _newRoot) { Debug.Assert(_oldRoot != null && _newRoot != null); var rootChild = (node == _oldRoot) ? _oldRootChild : _newRootChild; if (HasLabel(rootChild)) { yield return rootChild; } node = rootChild; } // TODO: avoid allocation of closure foreach (var descendant in node.DescendantNodes(descendIntoChildren: c => !IsLeaf(c) && (c == node || !LambdaUtilities.IsLambdaBodyStatementOrExpression(c)))) { if (!LambdaUtilities.IsLambdaBodyStatementOrExpression(descendant) && HasLabel(descendant)) { yield return descendant; } } } private static bool IsLeaf(SyntaxNode node) { Classify(node.Kind(), node, out var isLeaf); return isLeaf; } #endregion #region Labels // Assumptions: // - Each listed label corresponds to one or more syntax kinds. // - Nodes with same labels might produce Update edits, nodes with different labels don't. // - If IsTiedToParent(label) is true for a label then all its possible parent labels must precede the label. // (i.e. both MethodDeclaration and TypeDeclaration must precede TypeParameter label). internal enum Label { ConstructorDeclaration, Block, CheckedStatement, UnsafeStatement, TryStatement, CatchClause, // tied to parent CatchDeclaration, // tied to parent CatchFilterClause, // tied to parent FinallyClause, // tied to parent ForStatement, ForStatementPart, // tied to parent ForEachStatement, UsingStatement, FixedStatement, LockStatement, WhileStatement, DoStatement, IfStatement, ElseClause, // tied to parent SwitchStatement, SwitchSection, CasePatternSwitchLabel, // tied to parent WhenClause, YieldStatement, // tied to parent GotoStatement, GotoCaseStatement, BreakContinueStatement, ReturnThrowStatement, ExpressionStatement, LabeledStatement, LocalFunction, // TODO: // Ideally we could declare LocalVariableDeclarator tied to the first enclosing node that defines local scope (block, foreach, etc.) // Also consider handling LocalDeclarationStatement as just a bag of variable declarators, // so that variable declarators contained in one can be matched with variable declarators contained in the other. LocalDeclarationStatement, // tied to parent LocalVariableDeclaration, // tied to parent LocalVariableDeclarator, // tied to parent SingleVariableDesignation, AwaitExpression, Lambda, FromClause, QueryBody, FromClauseLambda, // tied to parent LetClauseLambda, // tied to parent WhereClauseLambda, // tied to parent OrderByClause, // tied to parent OrderingLambda, // tied to parent SelectClauseLambda, // tied to parent JoinClauseLambda, // tied to parent JoinIntoClause, // tied to parent GroupClauseLambda, // tied to parent QueryContinuation, // tied to parent // helpers: Count, Ignored = IgnoredNode } private static int TiedToAncestor(Label label) { switch (label) { case Label.LocalDeclarationStatement: case Label.LocalVariableDeclaration: case Label.LocalVariableDeclarator: case Label.GotoCaseStatement: case Label.BreakContinueStatement: case Label.ElseClause: case Label.CatchClause: case Label.CatchDeclaration: case Label.CatchFilterClause: case Label.FinallyClause: case Label.ForStatementPart: case Label.YieldStatement: case Label.LocalFunction: case Label.FromClauseLambda: case Label.LetClauseLambda: case Label.WhereClauseLambda: case Label.OrderByClause: case Label.OrderingLambda: case Label.SelectClauseLambda: case Label.JoinClauseLambda: case Label.JoinIntoClause: case Label.GroupClauseLambda: case Label.QueryContinuation: case Label.CasePatternSwitchLabel: return 1; default: return 0; } } /// <summary> /// <paramref name="nodeOpt"/> is null only when comparing value equality of a tree node. /// </summary> internal static Label Classify(SyntaxKind kind, SyntaxNode nodeOpt, out bool isLeaf) { // Notes: // A descendant of a leaf node may be a labeled node that we don't want to visit if // we are comparing its parent node (used for lambda bodies). // // Expressions are ignored but they may contain nodes that should be matched by tree comparer. // (e.g. lambdas, declaration expressions). Descending to these nodes is handled in EnumerateChildren. isLeaf = false; // If the node is a for loop Initializer, Condition, or Incrementor expression we label it as "ForStatementPart". // We need to capture it in the match since these expressions can be "active statements" and as such we need to map them. // // The parent is not available only when comparing nodes for value equality. if (nodeOpt != null && nodeOpt.Parent.IsKind(SyntaxKind.ForStatement) && nodeOpt is ExpressionSyntax) { return Label.ForStatementPart; } switch (kind) { case SyntaxKind.ConstructorDeclaration: // Root when matching constructor bodies. return Label.ConstructorDeclaration; case SyntaxKind.Block: return Label.Block; case SyntaxKind.LocalDeclarationStatement: return Label.LocalDeclarationStatement; case SyntaxKind.VariableDeclaration: return Label.LocalVariableDeclaration; case SyntaxKind.VariableDeclarator: return Label.LocalVariableDeclarator; case SyntaxKind.SingleVariableDesignation: return Label.SingleVariableDesignation; case SyntaxKind.LabeledStatement: return Label.LabeledStatement; case SyntaxKind.EmptyStatement: isLeaf = true; return Label.Ignored; case SyntaxKind.GotoStatement: isLeaf = true; return Label.GotoStatement; case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: isLeaf = true; return Label.GotoCaseStatement; case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: isLeaf = true; return Label.BreakContinueStatement; case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: return Label.ReturnThrowStatement; case SyntaxKind.ExpressionStatement: return Label.ExpressionStatement; case SyntaxKind.YieldBreakStatement: case SyntaxKind.YieldReturnStatement: return Label.YieldStatement; case SyntaxKind.DoStatement: return Label.DoStatement; case SyntaxKind.WhileStatement: return Label.WhileStatement; case SyntaxKind.ForStatement: return Label.ForStatement; case SyntaxKind.ForEachVariableStatement: case SyntaxKind.ForEachStatement: return Label.ForEachStatement; case SyntaxKind.UsingStatement: return Label.UsingStatement; case SyntaxKind.FixedStatement: return Label.FixedStatement; case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return Label.CheckedStatement; case SyntaxKind.UnsafeStatement: return Label.UnsafeStatement; case SyntaxKind.LockStatement: return Label.LockStatement; case SyntaxKind.IfStatement: return Label.IfStatement; case SyntaxKind.ElseClause: return Label.ElseClause; case SyntaxKind.SwitchStatement: return Label.SwitchStatement; case SyntaxKind.SwitchSection: return Label.SwitchSection; case SyntaxKind.CaseSwitchLabel: case SyntaxKind.DefaultSwitchLabel: // Switch labels are included in the "value" of the containing switch section. // We don't need to analyze case expressions. isLeaf = true; return Label.Ignored; case SyntaxKind.WhenClause: return Label.WhenClause; case SyntaxKind.CasePatternSwitchLabel: return Label.CasePatternSwitchLabel; case SyntaxKind.TryStatement: return Label.TryStatement; case SyntaxKind.CatchClause: return Label.CatchClause; case SyntaxKind.CatchDeclaration: // the declarator of the exception variable return Label.CatchDeclaration; case SyntaxKind.CatchFilterClause: return Label.CatchFilterClause; case SyntaxKind.FinallyClause: return Label.FinallyClause; case SyntaxKind.LocalFunctionStatement: return Label.LocalFunction; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: return Label.Lambda; case SyntaxKind.FromClause: // The first from clause of a query is not a lambda. // We have to assign it a label different from "FromClauseLambda" // so that we won't match lambda-from to non-lambda-from. // // Since FromClause declares range variables we need to include it in the map, // so that we are able to map range variable declarations. // Therefore we assign it a dedicated label. // // The parent is not available only when comparing nodes for value equality. // In that case it doesn't matter what label the node has as long as it has some. if (nodeOpt == null || nodeOpt.Parent.IsKind(SyntaxKind.QueryExpression)) { return Label.FromClause; } return Label.FromClauseLambda; case SyntaxKind.QueryBody: return Label.QueryBody; case SyntaxKind.QueryContinuation: return Label.QueryContinuation; case SyntaxKind.LetClause: return Label.LetClauseLambda; case SyntaxKind.WhereClause: return Label.WhereClauseLambda; case SyntaxKind.OrderByClause: return Label.OrderByClause; case SyntaxKind.AscendingOrdering: case SyntaxKind.DescendingOrdering: return Label.OrderingLambda; case SyntaxKind.SelectClause: return Label.SelectClauseLambda; case SyntaxKind.JoinClause: return Label.JoinClauseLambda; case SyntaxKind.JoinIntoClause: return Label.JoinIntoClause; case SyntaxKind.GroupClause: return Label.GroupClauseLambda; case SyntaxKind.IdentifierName: case SyntaxKind.QualifiedName: case SyntaxKind.GenericName: case SyntaxKind.TypeArgumentList: case SyntaxKind.AliasQualifiedName: case SyntaxKind.PredefinedType: case SyntaxKind.ArrayType: case SyntaxKind.ArrayRankSpecifier: case SyntaxKind.PointerType: case SyntaxKind.NullableType: case SyntaxKind.TupleType: case SyntaxKind.RefType: case SyntaxKind.OmittedTypeArgument: case SyntaxKind.NameColon: case SyntaxKind.StackAllocArrayCreationExpression: case SyntaxKind.OmittedArraySizeExpression: case SyntaxKind.ThisExpression: case SyntaxKind.BaseExpression: case SyntaxKind.ArgListExpression: case SyntaxKind.NumericLiteralExpression: case SyntaxKind.StringLiteralExpression: case SyntaxKind.CharacterLiteralExpression: case SyntaxKind.TrueLiteralExpression: case SyntaxKind.FalseLiteralExpression: case SyntaxKind.NullLiteralExpression: case SyntaxKind.TypeOfExpression: case SyntaxKind.SizeOfExpression: case SyntaxKind.DefaultExpression: case SyntaxKind.ConstantPattern: case SyntaxKind.DiscardDesignation: // can't contain a lambda/await/anonymous type: isLeaf = true; return Label.Ignored; case SyntaxKind.AwaitExpression: return Label.AwaitExpression; default: // any other node may contain a lambda: return Label.Ignored; } } protected internal override int GetLabel(SyntaxNode node) { return (int)GetLabelImpl(node); } internal static Label GetLabelImpl(SyntaxNode node) { return Classify(node.Kind(), node, out var isLeaf); } internal static bool HasLabel(SyntaxNode node) { return GetLabelImpl(node) != Label.Ignored; } protected internal override int LabelCount { get { return (int)Label.Count; } } protected internal override int TiedToAncestor(int label) { return TiedToAncestor((Label)label); } #endregion #region Comparisons internal static bool IgnoreLabeledChild(SyntaxKind kind) { // In most cases we can determine Label based on child kind. // The only cases when we can't are // - for Initializer, Condition and Incrementor expressions in ForStatement. // - first from clause of a query expression. return Classify(kind, null, out var isLeaf) != Label.Ignored; } public override bool ValuesEqual(SyntaxNode left, SyntaxNode right) { // only called from the tree matching alg, which only operates on nodes that are labeled. Debug.Assert(HasLabel(left)); Debug.Assert(HasLabel(right)); Func<SyntaxKind, bool> ignoreChildNode; switch (left.Kind()) { case SyntaxKind.SwitchSection: return Equal((SwitchSectionSyntax)left, (SwitchSectionSyntax)right); case SyntaxKind.ForStatement: // The only children of ForStatement are labeled nodes and punctuation. return true; default: // When comparing the value of a node with its partner we are deciding whether to add an Update edit for the pair. // If the actual change is under a descendant labeled node we don't want to attribute it to the node being compared, // so we skip all labeled children when recursively checking for equivalence. if (IsLeaf(left)) { ignoreChildNode = null; } else { ignoreChildNode = IgnoreLabeledChild; } break; } return SyntaxFactory.AreEquivalent(left, right, ignoreChildNode); } private bool Equal(SwitchSectionSyntax left, SwitchSectionSyntax right) { return SyntaxFactory.AreEquivalent(left.Labels, right.Labels, null) && SyntaxFactory.AreEquivalent(left.Statements, right.Statements, ignoreChildNode: IgnoreLabeledChild); } protected override bool TryComputeWeightedDistance(SyntaxNode leftNode, SyntaxNode rightNode, out double distance) { switch (leftNode.Kind()) { case SyntaxKind.VariableDeclarator: distance = ComputeDistance( ((VariableDeclaratorSyntax)leftNode).Identifier, ((VariableDeclaratorSyntax)rightNode).Identifier); return true; case SyntaxKind.ForStatement: var leftFor = (ForStatementSyntax)leftNode; var rightFor = (ForStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftFor, rightFor); return true; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: { var leftForEach = (CommonForEachStatementSyntax)leftNode; var rightForEach = (CommonForEachStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftForEach, rightForEach); return true; } case SyntaxKind.UsingStatement: var leftUsing = (UsingStatementSyntax)leftNode; var rightUsing = (UsingStatementSyntax)rightNode; if (leftUsing.Declaration != null && rightUsing.Declaration != null) { distance = ComputeWeightedDistance( leftUsing.Declaration, leftUsing.Statement, rightUsing.Declaration, rightUsing.Statement); } else { distance = ComputeWeightedDistance( (SyntaxNode)leftUsing.Expression ?? leftUsing.Declaration, leftUsing.Statement, (SyntaxNode)rightUsing.Expression ?? rightUsing.Declaration, rightUsing.Statement); } return true; case SyntaxKind.LockStatement: var leftLock = (LockStatementSyntax)leftNode; var rightLock = (LockStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftLock.Expression, leftLock.Statement, rightLock.Expression, rightLock.Statement); return true; case SyntaxKind.FixedStatement: var leftFixed = (FixedStatementSyntax)leftNode; var rightFixed = (FixedStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftFixed.Declaration, leftFixed.Statement, rightFixed.Declaration, rightFixed.Statement); return true; case SyntaxKind.WhileStatement: var leftWhile = (WhileStatementSyntax)leftNode; var rightWhile = (WhileStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftWhile.Condition, leftWhile.Statement, rightWhile.Condition, rightWhile.Statement); return true; case SyntaxKind.DoStatement: var leftDo = (DoStatementSyntax)leftNode; var rightDo = (DoStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftDo.Condition, leftDo.Statement, rightDo.Condition, rightDo.Statement); return true; case SyntaxKind.IfStatement: var leftIf = (IfStatementSyntax)leftNode; var rightIf = (IfStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftIf.Condition, leftIf.Statement, rightIf.Condition, rightIf.Statement); return true; case SyntaxKind.Block: BlockSyntax leftBlock = (BlockSyntax)leftNode; BlockSyntax rightBlock = (BlockSyntax)rightNode; return TryComputeWeightedDistance(leftBlock, rightBlock, out distance); case SyntaxKind.CatchClause: distance = ComputeWeightedDistance((CatchClauseSyntax)leftNode, (CatchClauseSyntax)rightNode); return true; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: distance = ComputeWeightedDistanceOfLambdas(leftNode, rightNode); return true; case SyntaxKind.LocalFunctionStatement: distance = ComputeWeightedDistanceOfLocalFunctions((LocalFunctionStatementSyntax)leftNode, (LocalFunctionStatementSyntax)rightNode); return true; case SyntaxKind.YieldBreakStatement: case SyntaxKind.YieldReturnStatement: // Ignore the expression of yield return. The structure of the state machine is more important than the yielded values. distance = (leftNode.RawKind == rightNode.RawKind) ? 0.0 : 0.1; return true; case SyntaxKind.SingleVariableDesignation: distance = ComputeWeightedDistance((SingleVariableDesignationSyntax)leftNode, (SingleVariableDesignationSyntax)rightNode); return true; default: distance = 0; return false; } } private static double ComputeWeightedDistanceOfLocalFunctions(LocalFunctionStatementSyntax leftNode, LocalFunctionStatementSyntax rightNode) { double modifierDistance = ComputeDistance(leftNode.Modifiers, rightNode.Modifiers); double returnTypeDistance = ComputeDistance(leftNode.ReturnType, rightNode.ReturnType); double identifierDistance = ComputeDistance(leftNode.Identifier, rightNode.Identifier); double typeParameterDistance = ComputeDistance(leftNode.TypeParameterList, rightNode.TypeParameterList); double parameterDistance = ComputeDistance(leftNode.ParameterList.Parameters, rightNode.ParameterList.Parameters); double bodyDistance = ComputeDistance((SyntaxNode)leftNode.Body ?? leftNode.ExpressionBody, (SyntaxNode)rightNode.Body ?? rightNode.ExpressionBody); return modifierDistance * 0.1 + returnTypeDistance * 0.1 + identifierDistance * 0.2 + typeParameterDistance * 0.2 + parameterDistance * 0.2 + bodyDistance * 0.2; } private static double ComputeWeightedDistanceOfLambdas(SyntaxNode leftNode, SyntaxNode rightNode) { GetLambdaParts(leftNode, out var leftParameters, out var leftAsync, out var leftBody); GetLambdaParts(rightNode, out var rightParameters, out var rightAsync, out var rightBody); if ((leftAsync.Kind() == SyntaxKind.AsyncKeyword) != (rightAsync.Kind() == SyntaxKind.AsyncKeyword)) { return 1.0; } double parameterDistance = ComputeDistance(leftParameters, rightParameters); double bodyDistance = ComputeDistance(leftBody, rightBody); return parameterDistance * 0.6 + bodyDistance * 0.4; } private static void GetLambdaParts(SyntaxNode lambda, out IEnumerable<SyntaxToken> parameters, out SyntaxToken asyncKeyword, out SyntaxNode body) { switch (lambda.Kind()) { case SyntaxKind.SimpleLambdaExpression: var simple = (SimpleLambdaExpressionSyntax)lambda; parameters = simple.Parameter.DescendantTokens(); asyncKeyword = simple.AsyncKeyword; body = simple.Body; break; case SyntaxKind.ParenthesizedLambdaExpression: var parenthesized = (ParenthesizedLambdaExpressionSyntax)lambda; parameters = GetDescendantTokensIgnoringSeparators(parenthesized.ParameterList.Parameters); asyncKeyword = parenthesized.AsyncKeyword; body = parenthesized.Body; break; case SyntaxKind.AnonymousMethodExpression: var anonymous = (AnonymousMethodExpressionSyntax)lambda; if (anonymous.ParameterList != null) { parameters = GetDescendantTokensIgnoringSeparators(anonymous.ParameterList.Parameters); } else { parameters = SpecializedCollections.EmptyEnumerable<SyntaxToken>(); } asyncKeyword = anonymous.AsyncKeyword; body = anonymous.Block; break; default: throw ExceptionUtilities.UnexpectedValue(lambda.Kind()); } } private bool TryComputeWeightedDistance(BlockSyntax leftBlock, BlockSyntax rightBlock, out double distance) { // No block can be matched with the root block. // Note that in constructors the root is the constructor declaration, since we need to include // the constructor initializer in the match. if (leftBlock.Parent == null || rightBlock.Parent == null || leftBlock.Parent.IsKind(SyntaxKind.ConstructorDeclaration) || rightBlock.Parent.IsKind(SyntaxKind.ConstructorDeclaration)) { distance = 0.0; return true; } if (GetLabel(leftBlock.Parent) != GetLabel(rightBlock.Parent)) { distance = 0.2 + 0.8 * ComputeWeightedBlockDistance(leftBlock, rightBlock); return true; } switch (leftBlock.Parent.Kind()) { case SyntaxKind.IfStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: case SyntaxKind.ForStatement: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.FixedStatement: case SyntaxKind.LockStatement: case SyntaxKind.UsingStatement: case SyntaxKind.SwitchSection: case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: // value distance of the block body is included: distance = GetDistance(leftBlock.Parent, rightBlock.Parent); return true; case SyntaxKind.CatchClause: var leftCatch = (CatchClauseSyntax)leftBlock.Parent; var rightCatch = (CatchClauseSyntax)rightBlock.Parent; if (leftCatch.Declaration == null && leftCatch.Filter == null && rightCatch.Declaration == null && rightCatch.Filter == null) { var leftTry = (TryStatementSyntax)leftCatch.Parent; var rightTry = (TryStatementSyntax)rightCatch.Parent; distance = 0.5 * ComputeValueDistance(leftTry.Block, rightTry.Block) + 0.5 * ComputeValueDistance(leftBlock, rightBlock); } else { // value distance of the block body is included: distance = GetDistance(leftBlock.Parent, rightBlock.Parent); } return true; case SyntaxKind.Block: case SyntaxKind.LabeledStatement: distance = ComputeWeightedBlockDistance(leftBlock, rightBlock); return true; case SyntaxKind.UnsafeStatement: case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: case SyntaxKind.ElseClause: case SyntaxKind.FinallyClause: case SyntaxKind.TryStatement: distance = 0.2 * ComputeValueDistance(leftBlock, rightBlock); return true; default: throw ExceptionUtilities.UnexpectedValue(leftBlock.Parent.Kind()); } } private double ComputeWeightedDistance(SingleVariableDesignationSyntax leftNode, SingleVariableDesignationSyntax rightNode) { double distance = ComputeDistance(leftNode, rightNode); double parentDistance; if (leftNode.Parent != null && rightNode.Parent != null && GetLabel(leftNode.Parent) == GetLabel(rightNode.Parent)) { parentDistance = ComputeDistance(leftNode.Parent, rightNode.Parent); } else { parentDistance = 1; } return 0.5 * parentDistance + 0.5 * distance; } private static double ComputeWeightedBlockDistance(BlockSyntax leftBlock, BlockSyntax rightBlock) { if (TryComputeLocalsDistance(leftBlock, rightBlock, out var distance)) { return distance; } return ComputeValueDistance(leftBlock, rightBlock); } private static double ComputeWeightedDistance(CatchClauseSyntax left, CatchClauseSyntax right) { double blockDistance = ComputeDistance(left.Block, right.Block); double distance = CombineOptional(blockDistance, left.Declaration, right.Declaration, left.Filter, right.Filter); return AdjustForLocalsInBlock(distance, left.Block, right.Block, localsWeight: 0.3); } private static double ComputeWeightedDistance( CommonForEachStatementSyntax leftCommonForEach, CommonForEachStatementSyntax rightCommonForEach) { double statementDistance = ComputeDistance(leftCommonForEach.Statement, rightCommonForEach.Statement); double expressionDistance = ComputeDistance(leftCommonForEach.Expression, rightCommonForEach.Expression); List<SyntaxToken> leftLocals = null; List<SyntaxToken> rightLocals = null; GetLocalNames(leftCommonForEach, ref leftLocals); GetLocalNames(rightCommonForEach, ref rightLocals); double localNamesDistance = ComputeDistance(leftLocals, rightLocals); double distance = localNamesDistance * 0.6 + expressionDistance * 0.2 + statementDistance * 0.2; return AdjustForLocalsInBlock(distance, leftCommonForEach.Statement, rightCommonForEach.Statement, localsWeight: 0.6); } private static double ComputeWeightedDistance(ForStatementSyntax left, ForStatementSyntax right) { double statementDistance = ComputeDistance(left.Statement, right.Statement); double conditionDistance = ComputeDistance(left.Condition, right.Condition); double incDistance = ComputeDistance( GetDescendantTokensIgnoringSeparators(left.Incrementors), GetDescendantTokensIgnoringSeparators(right.Incrementors)); double distance = conditionDistance * 0.3 + incDistance * 0.3 + statementDistance * 0.4; if (TryComputeLocalsDistance(left.Declaration, right.Declaration, out var localsDistance)) { distance = distance * 0.4 + localsDistance * 0.6; } return distance; } private static double ComputeWeightedDistance( VariableDeclarationSyntax leftVariables, StatementSyntax leftStatement, VariableDeclarationSyntax rightVariables, StatementSyntax rightStatement) { double distance = ComputeDistance(leftStatement, rightStatement); // Put maximum weight behind the variables declared in the header of the statement. if (TryComputeLocalsDistance(leftVariables, rightVariables, out var localsDistance)) { distance = distance * 0.4 + localsDistance * 0.6; } // If the statement is a block that declares local variables, // weight them more than the rest of the statement. return AdjustForLocalsInBlock(distance, leftStatement, rightStatement, localsWeight: 0.2); } private static double ComputeWeightedDistance( SyntaxNode leftHeaderOpt, StatementSyntax leftStatement, SyntaxNode rightHeaderOpt, StatementSyntax rightStatement) { Debug.Assert(leftStatement != null); Debug.Assert(rightStatement != null); double headerDistance = ComputeDistance(leftHeaderOpt, rightHeaderOpt); double statementDistance = ComputeDistance(leftStatement, rightStatement); double distance = headerDistance * 0.6 + statementDistance * 0.4; return AdjustForLocalsInBlock(distance, leftStatement, rightStatement, localsWeight: 0.5); } private static double AdjustForLocalsInBlock( double distance, StatementSyntax leftStatement, StatementSyntax rightStatement, double localsWeight) { // If the statement is a block that declares local variables, // weight them more than the rest of the statement. if (leftStatement.Kind() == SyntaxKind.Block && rightStatement.Kind() == SyntaxKind.Block) { if (TryComputeLocalsDistance((BlockSyntax)leftStatement, (BlockSyntax)rightStatement, out var localsDistance)) { return localsDistance * localsWeight + distance * (1 - localsWeight); } } return distance; } private static bool TryComputeLocalsDistance(VariableDeclarationSyntax leftOpt, VariableDeclarationSyntax rightOpt, out double distance) { List<SyntaxToken> leftLocals = null; List<SyntaxToken> rightLocals = null; if (leftOpt != null) { GetLocalNames(leftOpt, ref leftLocals); } if (rightOpt != null) { GetLocalNames(rightOpt, ref rightLocals); } if (leftLocals == null || rightLocals == null) { distance = 0; return false; } distance = ComputeDistance(leftLocals, rightLocals); return true; } private static bool TryComputeLocalsDistance(BlockSyntax left, BlockSyntax right, out double distance) { List<SyntaxToken> leftLocals = null; List<SyntaxToken> rightLocals = null; GetLocalNames(left, ref leftLocals); GetLocalNames(right, ref rightLocals); if (leftLocals == null || rightLocals == null) { distance = 0; return false; } distance = ComputeDistance(leftLocals, rightLocals); return true; } // doesn't include variables declared in declaration expressions private static void GetLocalNames(BlockSyntax block, ref List<SyntaxToken> result) { foreach (var child in block.ChildNodes()) { if (child.IsKind(SyntaxKind.LocalDeclarationStatement)) { GetLocalNames(((LocalDeclarationStatementSyntax)child).Declaration, ref result); } } } // doesn't include variables declared in declaration expressions private static void GetLocalNames(VariableDeclarationSyntax localDeclaration, ref List<SyntaxToken> result) { foreach (var local in localDeclaration.Variables) { GetLocalNames(local.Identifier, ref result); } } internal static void GetLocalNames(CommonForEachStatementSyntax commonForEach, ref List<SyntaxToken> result) { switch (commonForEach.Kind()) { case SyntaxKind.ForEachStatement: GetLocalNames(((ForEachStatementSyntax)commonForEach).Identifier, ref result); return; case SyntaxKind.ForEachVariableStatement: var forEachVariable = (ForEachVariableStatementSyntax)commonForEach; GetLocalNames(forEachVariable.Variable, ref result); return; default: throw ExceptionUtilities.UnexpectedValue(commonForEach.Kind()); } } private static void GetLocalNames(ExpressionSyntax expression, ref List<SyntaxToken> result) { switch (expression.Kind()) { case SyntaxKind.DeclarationExpression: var declarationExpression = (DeclarationExpressionSyntax)expression; var localDeclaration = declarationExpression.Designation; GetLocalNames(localDeclaration, ref result); return; case SyntaxKind.TupleExpression: var tupleExpression = (TupleExpressionSyntax)expression; foreach(var argument in tupleExpression.Arguments) { GetLocalNames(argument.Expression, ref result); } return; default: // Do nothing for node that cannot have variable declarations inside. return; } } private static void GetLocalNames(VariableDesignationSyntax designation, ref List<SyntaxToken> result) { switch (designation.Kind()) { case SyntaxKind.SingleVariableDesignation: GetLocalNames(((SingleVariableDesignationSyntax)designation).Identifier, ref result); return; case SyntaxKind.ParenthesizedVariableDesignation: var parenthesizedVariableDesignation = (ParenthesizedVariableDesignationSyntax)designation; foreach(var variableDesignation in parenthesizedVariableDesignation.Variables) { GetLocalNames(variableDesignation, ref result); } return; default: throw ExceptionUtilities.UnexpectedValue(designation.Kind()); } } private static void GetLocalNames(SyntaxToken syntaxToken, ref List<SyntaxToken> result) { if (result == null) { result = new List<SyntaxToken>(); } result.Add(syntaxToken); } private static double CombineOptional( double distance0, SyntaxNode leftOpt1, SyntaxNode rightOpt1, SyntaxNode leftOpt2, SyntaxNode rightOpt2, double weight0 = 0.8, double weight1 = 0.5) { bool one = leftOpt1 != null || rightOpt1 != null; bool two = leftOpt2 != null || rightOpt2 != null; if (!one && !two) { return distance0; } double distance1 = ComputeDistance(leftOpt1, rightOpt1); double distance2 = ComputeDistance(leftOpt2, rightOpt2); double d; if (one && two) { d = distance1 * weight1 + distance2 * (1 - weight1); } else if (one) { d = distance1; } else { d = distance2; } return distance0 * weight0 + d * (1 - weight0); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // System.Drawing.Image.cs // // Authors: Christian Meyer (Christian.Meyer@cs.tum.edu) // Alexandre Pigolkine (pigolkine@gmx.de) // Jordi Mas i Hernandez (jordi@ximian.com) // Sanjay Gupta (gsanjay@novell.com) // Ravindra (rkumar@novell.com) // Sebastien Pouliot <sebastien@ximian.com> // // Copyright (C) 2002 Ximian, Inc. http://www.ximian.com // Copyright (C) 2004, 2007 Novell, Inc (http://www.novell.com) // Copyright (C) 2013 Kristof Ralovich, changes are available under the terms of the MIT X11 license // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Runtime.Serialization; using System.Runtime.InteropServices; using System.ComponentModel; using System.Drawing.Imaging; using System.IO; using System.Reflection; namespace System.Drawing { [ComVisible(true)] [Serializable] #if !NETCORE [Editor ("System.Drawing.Design.ImageEditor, " + Consts.AssemblySystem_Drawing_Design, typeof (System.Drawing.Design.UITypeEditor))] [TypeConverter (typeof(ImageConverter))] #endif [ImmutableObject(true)] public abstract class Image : MarshalByRefObject, IDisposable, ICloneable, ISerializable { public delegate bool GetThumbnailImageAbort(); private object tag; internal IntPtr nativeObject = IntPtr.Zero; // when using MS GDI+ and IStream we must ensure the stream stays alive for all the life of the Image // http://groups.google.com/group/microsoft.public.win32.programmer.gdi/browse_thread/thread/4967097db1469a27/4d36385b83532126?lnk=st&q=IStream+gdi&rnum=3&hl=en#4d36385b83532126 internal Stream stream; // constructor internal Image() { } #if NETCORE protected Image(SerializationInfo info, StreamingContext context) #else internal Image (SerializationInfo info, StreamingContext context) #endif { foreach (SerializationEntry serEnum in info) { if (String.Compare(serEnum.Name, "Data", true) == 0) { byte[] bytes = (byte[])serEnum.Value; if (bytes != null) { MemoryStream ms = new MemoryStream(bytes); nativeObject = InitFromStream(ms); // under Win32 stream is owned by SD/GDI+ code if (GDIPlus.RunningOnWindows()) stream = ms; } } } } // FIXME - find out how metafiles (another decoder-only codec) are handled void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) { using (MemoryStream ms = new MemoryStream()) { // Icon is a decoder-only codec if (RawFormat.Equals(ImageFormat.Icon)) { Save(ms, ImageFormat.Png); } else { Save(ms, RawFormat); } si.AddValue("Data", ms.ToArray()); } } // public methods // static public static Image FromFile(string filename) { return FromFile(filename, false); } public static Image FromFile(string filename, bool useEmbeddedColorManagement) { IntPtr imagePtr; Status st; if (!File.Exists(filename)) throw new FileNotFoundException(filename); if (useEmbeddedColorManagement) st = SafeNativeMethods.Gdip.GdipLoadImageFromFileICM(filename, out imagePtr); else st = SafeNativeMethods.Gdip.GdipLoadImageFromFile(filename, out imagePtr); SafeNativeMethods.Gdip.CheckStatus(st); return CreateFromHandle(imagePtr); } public static Bitmap FromHbitmap(IntPtr hbitmap) { return FromHbitmap(hbitmap, IntPtr.Zero); } public static Bitmap FromHbitmap(IntPtr hbitmap, IntPtr hpalette) { IntPtr imagePtr; Status st; st = SafeNativeMethods.Gdip.GdipCreateBitmapFromHBITMAP(hbitmap, hpalette, out imagePtr); SafeNativeMethods.Gdip.CheckStatus(st); return new Bitmap(imagePtr); } // note: FromStream can return either a Bitmap or Metafile instance public static Image FromStream(Stream stream) { return LoadFromStream(stream, false); } [MonoLimitation("useEmbeddedColorManagement isn't supported.")] public static Image FromStream(Stream stream, bool useEmbeddedColorManagement) { return LoadFromStream(stream, false); } // See http://support.microsoft.com/default.aspx?scid=kb;en-us;831419 for performance discussion [MonoLimitation("useEmbeddedColorManagement and validateImageData aren't supported.")] public static Image FromStream(Stream stream, bool useEmbeddedColorManagement, bool validateImageData) { return LoadFromStream(stream, false); } internal static Image LoadFromStream(Stream stream, bool keepAlive) { if (stream == null) throw new ArgumentNullException("stream"); Image img = CreateFromHandle(InitFromStream(stream)); // Under Windows, we may need to keep a reference on the stream as long as the image is alive // (GDI+ seems to use a lazy loader) if (keepAlive && GDIPlus.RunningOnWindows()) img.stream = stream; return img; } internal static Image CreateImageObject(IntPtr nativeImage) { return CreateFromHandle(nativeImage); } internal static Image CreateFromHandle(IntPtr handle) { ImageType type; SafeNativeMethods.Gdip.CheckStatus(SafeNativeMethods.Gdip.GdipGetImageType(handle, out type)); switch (type) { case ImageType.Bitmap: return new Bitmap(handle); case ImageType.Metafile: return new Metafile(handle); default: throw new NotSupportedException("Unknown image type."); } } public static int GetPixelFormatSize(PixelFormat pixfmt) { int result = 0; switch (pixfmt) { case PixelFormat.Format16bppArgb1555: case PixelFormat.Format16bppGrayScale: case PixelFormat.Format16bppRgb555: case PixelFormat.Format16bppRgb565: result = 16; break; case PixelFormat.Format1bppIndexed: result = 1; break; case PixelFormat.Format24bppRgb: result = 24; break; case PixelFormat.Format32bppArgb: case PixelFormat.Format32bppPArgb: case PixelFormat.Format32bppRgb: result = 32; break; case PixelFormat.Format48bppRgb: result = 48; break; case PixelFormat.Format4bppIndexed: result = 4; break; case PixelFormat.Format64bppArgb: case PixelFormat.Format64bppPArgb: result = 64; break; case PixelFormat.Format8bppIndexed: result = 8; break; } return result; } public static bool IsAlphaPixelFormat(PixelFormat pixfmt) { bool result = false; switch (pixfmt) { case PixelFormat.Format16bppArgb1555: case PixelFormat.Format32bppArgb: case PixelFormat.Format32bppPArgb: case PixelFormat.Format64bppArgb: case PixelFormat.Format64bppPArgb: result = true; break; case PixelFormat.Format16bppGrayScale: case PixelFormat.Format16bppRgb555: case PixelFormat.Format16bppRgb565: case PixelFormat.Format1bppIndexed: case PixelFormat.Format24bppRgb: case PixelFormat.Format32bppRgb: case PixelFormat.Format48bppRgb: case PixelFormat.Format4bppIndexed: case PixelFormat.Format8bppIndexed: result = false; break; } return result; } public static bool IsCanonicalPixelFormat(PixelFormat pixfmt) { return ((pixfmt & PixelFormat.Canonical) != 0); } public static bool IsExtendedPixelFormat(PixelFormat pixfmt) { return ((pixfmt & PixelFormat.Extended) != 0); } internal static IntPtr InitFromStream(Stream stream) { if (stream == null) throw new ArgumentException("stream"); IntPtr imagePtr; Status st; // Seeking required if (!stream.CanSeek) { byte[] buffer = new byte[256]; int index = 0; int count; do { if (buffer.Length < index + 256) { byte[] newBuffer = new byte[buffer.Length * 2]; Array.Copy(buffer, newBuffer, buffer.Length); buffer = newBuffer; } count = stream.Read(buffer, index, 256); index += count; } while (count != 0); stream = new MemoryStream(buffer, 0, index); } if (GDIPlus.RunningOnUnix()) { // Unix, with libgdiplus // We use a custom API for this, because there's no easy way // to get the Stream down to libgdiplus. So, we wrap the stream // with a set of delegates. GDIPlus.GdiPlusStreamHelper sh = new GDIPlus.GdiPlusStreamHelper(stream, true); st = SafeNativeMethods.Gdip.GdipLoadImageFromDelegate_linux(sh.GetHeaderDelegate, sh.GetBytesDelegate, sh.PutBytesDelegate, sh.SeekDelegate, sh.CloseDelegate, sh.SizeDelegate, out imagePtr); } else { st = SafeNativeMethods.Gdip.GdipLoadImageFromStream(new ComIStreamWrapper(stream), out imagePtr); } return st == Status.Ok ? imagePtr : IntPtr.Zero; } // non-static public RectangleF GetBounds(ref GraphicsUnit pageUnit) { RectangleF source; Status status = SafeNativeMethods.Gdip.GdipGetImageBounds(nativeObject, out source, ref pageUnit); SafeNativeMethods.Gdip.CheckStatus(status); return source; } public EncoderParameters GetEncoderParameterList(Guid encoder) { Status status; uint sz; status = SafeNativeMethods.Gdip.GdipGetEncoderParameterListSize(nativeObject, ref encoder, out sz); SafeNativeMethods.Gdip.CheckStatus(status); IntPtr rawEPList = Marshal.AllocHGlobal((int)sz); EncoderParameters eps; try { status = SafeNativeMethods.Gdip.GdipGetEncoderParameterList(nativeObject, ref encoder, sz, rawEPList); eps = EncoderParameters.ConvertFromMemory(rawEPList); SafeNativeMethods.Gdip.CheckStatus(status); } finally { Marshal.FreeHGlobal(rawEPList); } return eps; } public int GetFrameCount(FrameDimension dimension) { uint count; Guid guid = dimension.Guid; Status status = SafeNativeMethods.Gdip.GdipImageGetFrameCount(nativeObject, ref guid, out count); SafeNativeMethods.Gdip.CheckStatus(status); return (int)count; } public PropertyItem GetPropertyItem(int propid) { int propSize; IntPtr property; PropertyItem item = new PropertyItem(); GdipPropertyItem gdipProperty = new GdipPropertyItem(); Status status; status = SafeNativeMethods.Gdip.GdipGetPropertyItemSize(nativeObject, propid, out propSize); SafeNativeMethods.Gdip.CheckStatus(status); /* Get PropertyItem */ property = Marshal.AllocHGlobal(propSize); try { status = SafeNativeMethods.Gdip.GdipGetPropertyItem(nativeObject, propid, propSize, property); SafeNativeMethods.Gdip.CheckStatus(status); gdipProperty = (GdipPropertyItem)Marshal.PtrToStructure(property, typeof(GdipPropertyItem)); GdipPropertyItem.MarshalTo(gdipProperty, item); } finally { Marshal.FreeHGlobal(property); } return item; } public Image GetThumbnailImage(int thumbWidth, int thumbHeight, Image.GetThumbnailImageAbort callback, IntPtr callbackData) { if ((thumbWidth <= 0) || (thumbHeight <= 0)) throw new OutOfMemoryException("Invalid thumbnail size"); Image ThumbNail = new Bitmap(thumbWidth, thumbHeight); using (Graphics g = Graphics.FromImage(ThumbNail)) { Status status = SafeNativeMethods.Gdip.GdipDrawImageRectRectI(g.nativeObject, nativeObject, 0, 0, thumbWidth, thumbHeight, 0, 0, this.Width, this.Height, GraphicsUnit.Pixel, IntPtr.Zero, null, IntPtr.Zero); SafeNativeMethods.Gdip.CheckStatus(status); } return ThumbNail; } public void RemovePropertyItem(int propid) { Status status = SafeNativeMethods.Gdip.GdipRemovePropertyItem(nativeObject, propid); SafeNativeMethods.Gdip.CheckStatus(status); } public void RotateFlip(RotateFlipType rotateFlipType) { Status status = SafeNativeMethods.Gdip.GdipImageRotateFlip(nativeObject, rotateFlipType); SafeNativeMethods.Gdip.CheckStatus(status); } internal ImageCodecInfo findEncoderForFormat(ImageFormat format) { ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo encoder = null; if (format.Guid.Equals(ImageFormat.MemoryBmp.Guid)) format = ImageFormat.Png; /* Look for the right encoder for our format*/ for (int i = 0; i < encoders.Length; i++) { if (encoders[i].FormatID.Equals(format.Guid)) { encoder = encoders[i]; break; } } return encoder; } public void Save(string filename) { Save(filename, RawFormat); } public void Save(string filename, ImageFormat format) { ImageCodecInfo encoder = findEncoderForFormat(format); if (encoder == null) { // second chance encoder = findEncoderForFormat(RawFormat); if (encoder == null) { string msg = string.Format("No codec available for saving format '{0}'.", format.Guid); throw new ArgumentException(msg, "format"); } } Save(filename, encoder, null); } public void Save(string filename, ImageCodecInfo encoder, EncoderParameters encoderParams) { Status st; Guid guid = encoder.Clsid; if (encoderParams == null) { st = SafeNativeMethods.Gdip.GdipSaveImageToFile(nativeObject, filename, ref guid, IntPtr.Zero); } else { IntPtr nativeEncoderParams = encoderParams.ConvertToMemory(); st = SafeNativeMethods.Gdip.GdipSaveImageToFile(nativeObject, filename, ref guid, nativeEncoderParams); Marshal.FreeHGlobal(nativeEncoderParams); } SafeNativeMethods.Gdip.CheckStatus(st); } public void Save(Stream stream, ImageFormat format) { ImageCodecInfo encoder = findEncoderForFormat(format); if (encoder == null) throw new ArgumentException("No codec available for format:" + format.Guid); Save(stream, encoder, null); } public void Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams) { Status st; IntPtr nativeEncoderParams; Guid guid = encoder.Clsid; if (encoderParams == null) nativeEncoderParams = IntPtr.Zero; else nativeEncoderParams = encoderParams.ConvertToMemory(); try { if (GDIPlus.RunningOnUnix()) { GDIPlus.GdiPlusStreamHelper sh = new GDIPlus.GdiPlusStreamHelper(stream, false); st = SafeNativeMethods.Gdip.GdipSaveImageToDelegate_linux(nativeObject, sh.GetBytesDelegate, sh.PutBytesDelegate, sh.SeekDelegate, sh.CloseDelegate, sh.SizeDelegate, ref guid, nativeEncoderParams); } else { st = SafeNativeMethods.Gdip.GdipSaveImageToStream(new HandleRef(this, nativeObject), new ComIStreamWrapper(stream), ref guid, new HandleRef(encoderParams, nativeEncoderParams)); } } finally { if (nativeEncoderParams != IntPtr.Zero) Marshal.FreeHGlobal(nativeEncoderParams); } SafeNativeMethods.Gdip.CheckStatus(st); } public void SaveAdd(EncoderParameters encoderParams) { Status st; IntPtr nativeEncoderParams = encoderParams.ConvertToMemory(); st = SafeNativeMethods.Gdip.GdipSaveAdd(nativeObject, nativeEncoderParams); Marshal.FreeHGlobal(nativeEncoderParams); SafeNativeMethods.Gdip.CheckStatus(st); } public void SaveAdd(Image image, EncoderParameters encoderParams) { Status st; IntPtr nativeEncoderParams = encoderParams.ConvertToMemory(); st = SafeNativeMethods.Gdip.GdipSaveAddImage(nativeObject, image.NativeObject, nativeEncoderParams); Marshal.FreeHGlobal(nativeEncoderParams); SafeNativeMethods.Gdip.CheckStatus(st); } public int SelectActiveFrame(FrameDimension dimension, int frameIndex) { Guid guid = dimension.Guid; Status st = SafeNativeMethods.Gdip.GdipImageSelectActiveFrame(nativeObject, ref guid, frameIndex); SafeNativeMethods.Gdip.CheckStatus(st); return frameIndex; } public void SetPropertyItem(PropertyItem propitem) { if (propitem == null) throw new ArgumentNullException("propitem"); int nItemSize = Marshal.SizeOf(propitem.Value[0]); int size = nItemSize * propitem.Value.Length; IntPtr dest = Marshal.AllocHGlobal(size); try { GdipPropertyItem pi = new GdipPropertyItem(); pi.id = propitem.Id; pi.len = propitem.Len; pi.type = propitem.Type; Marshal.Copy(propitem.Value, 0, dest, size); pi.value = dest; unsafe { Status status = SafeNativeMethods.Gdip.GdipSetPropertyItem(nativeObject, &pi); SafeNativeMethods.Gdip.CheckStatus(status); } } finally { Marshal.FreeHGlobal(dest); } } // properties [Browsable(false)] public int Flags { get { int flags; Status status = SafeNativeMethods.Gdip.GdipGetImageFlags(nativeObject, out flags); SafeNativeMethods.Gdip.CheckStatus(status); return flags; } } [Browsable(false)] public Guid[] FrameDimensionsList { get { uint found; Status status = SafeNativeMethods.Gdip.GdipImageGetFrameDimensionsCount(nativeObject, out found); SafeNativeMethods.Gdip.CheckStatus(status); Guid[] guid = new Guid[found]; status = SafeNativeMethods.Gdip.GdipImageGetFrameDimensionsList(nativeObject, guid, found); SafeNativeMethods.Gdip.CheckStatus(status); return guid; } } [DefaultValue(false)] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int Height { get { uint height; Status status = SafeNativeMethods.Gdip.GdipGetImageHeight(nativeObject, out height); SafeNativeMethods.Gdip.CheckStatus(status); return (int)height; } } public float HorizontalResolution { get { float resolution; Status status = SafeNativeMethods.Gdip.GdipGetImageHorizontalResolution(nativeObject, out resolution); SafeNativeMethods.Gdip.CheckStatus(status); return resolution; } } [Browsable(false)] public ColorPalette Palette { get { return retrieveGDIPalette(); } set { storeGDIPalette(value); } } internal ColorPalette retrieveGDIPalette() { int bytes; ColorPalette ret = new ColorPalette(); Status st = SafeNativeMethods.Gdip.GdipGetImagePaletteSize(nativeObject, out bytes); SafeNativeMethods.Gdip.CheckStatus(st); IntPtr palette_data = Marshal.AllocHGlobal(bytes); try { st = SafeNativeMethods.Gdip.GdipGetImagePalette(nativeObject, palette_data, bytes); SafeNativeMethods.Gdip.CheckStatus(st); ret.ConvertFromMemory(palette_data); return ret; } finally { Marshal.FreeHGlobal(palette_data); } } internal void storeGDIPalette(ColorPalette palette) { if (palette == null) { throw new ArgumentNullException("palette"); } IntPtr palette_data = palette.ConvertToMemory(); if (palette_data == IntPtr.Zero) { return; } try { Status st = SafeNativeMethods.Gdip.GdipSetImagePalette(nativeObject, palette_data); SafeNativeMethods.Gdip.CheckStatus(st); } finally { Marshal.FreeHGlobal(palette_data); } } public SizeF PhysicalDimension { get { float width, height; Status status = SafeNativeMethods.Gdip.GdipGetImageDimension(nativeObject, out width, out height); SafeNativeMethods.Gdip.CheckStatus(status); return new SizeF(width, height); } } public PixelFormat PixelFormat { get { PixelFormat pixFormat; Status status = SafeNativeMethods.Gdip.GdipGetImagePixelFormat(nativeObject, out pixFormat); SafeNativeMethods.Gdip.CheckStatus(status); return pixFormat; } } [Browsable(false)] public int[] PropertyIdList { get { uint propNumbers; Status status = SafeNativeMethods.Gdip.GdipGetPropertyCount(nativeObject, out propNumbers); SafeNativeMethods.Gdip.CheckStatus(status); int[] idList = new int[propNumbers]; status = SafeNativeMethods.Gdip.GdipGetPropertyIdList(nativeObject, propNumbers, idList); SafeNativeMethods.Gdip.CheckStatus(status); return idList; } } [Browsable(false)] public PropertyItem[] PropertyItems { get { int propNums, propsSize, propSize; IntPtr properties, propPtr; PropertyItem[] items; GdipPropertyItem gdipProperty = new GdipPropertyItem(); Status status; status = SafeNativeMethods.Gdip.GdipGetPropertySize(nativeObject, out propsSize, out propNums); SafeNativeMethods.Gdip.CheckStatus(status); items = new PropertyItem[propNums]; if (propNums == 0) return items; /* Get PropertyItem list*/ properties = Marshal.AllocHGlobal(propsSize * propNums); try { status = SafeNativeMethods.Gdip.GdipGetAllPropertyItems(nativeObject, propsSize, propNums, properties); SafeNativeMethods.Gdip.CheckStatus(status); propSize = Marshal.SizeOf(gdipProperty); propPtr = properties; for (int i = 0; i < propNums; i++, propPtr = new IntPtr(propPtr.ToInt64() + propSize)) { gdipProperty = (GdipPropertyItem)Marshal.PtrToStructure (propPtr, typeof(GdipPropertyItem)); items[i] = new PropertyItem(); GdipPropertyItem.MarshalTo(gdipProperty, items[i]); } } finally { Marshal.FreeHGlobal(properties); } return items; } } public ImageFormat RawFormat { get { Guid guid; Status st = SafeNativeMethods.Gdip.GdipGetImageRawFormat(nativeObject, out guid); SafeNativeMethods.Gdip.CheckStatus(st); return new ImageFormat(guid); } } public Size Size { get { return new Size(Width, Height); } } [DefaultValue(null)] [LocalizableAttribute(false)] #if !NETCORE [BindableAttribute(true)] [TypeConverter (typeof (StringConverter))] #endif public object Tag { get { return tag; } set { tag = value; } } public float VerticalResolution { get { float resolution; Status status = SafeNativeMethods.Gdip.GdipGetImageVerticalResolution(nativeObject, out resolution); SafeNativeMethods.Gdip.CheckStatus(status); return resolution; } } [DefaultValue(false)] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int Width { get { uint width; Status status = SafeNativeMethods.Gdip.GdipGetImageWidth(nativeObject, out width); SafeNativeMethods.Gdip.CheckStatus(status); return (int)width; } } internal IntPtr NativeObject { get { return nativeObject; } set { nativeObject = value; } } internal IntPtr nativeImage { get { return nativeObject; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~Image() { Dispose(false); } protected virtual void Dispose(bool disposing) { if (nativeObject != IntPtr.Zero) { Status status = SafeNativeMethods.Gdip.GdipDisposeImage(nativeObject); // dispose the stream (set under Win32 only if SD owns the stream) and ... if (stream != null) { stream.Dispose(); stream = null; } // ... set nativeObject to null before (possibly) throwing an exception nativeObject = IntPtr.Zero; SafeNativeMethods.Gdip.CheckStatus(status); } } public object Clone() { if (GDIPlus.RunningOnWindows() && stream != null) return CloneFromStream(); IntPtr newimage = IntPtr.Zero; Status status = SafeNativeMethods.Gdip.GdipCloneImage(NativeObject, out newimage); SafeNativeMethods.Gdip.CheckStatus(status); if (this is Bitmap) return new Bitmap(newimage); else return new Metafile(newimage); } // On win32, when cloning images that were originally created from a stream, we need to // clone both the image and the stream to make sure the gc doesn't kill it // (when using MS GDI+ and IStream we must ensure the stream stays alive for all the life of the Image) object CloneFromStream() { byte[] bytes = new byte[stream.Length]; MemoryStream ms = new MemoryStream(bytes); int count = (stream.Length < 4096 ? (int)stream.Length : 4096); byte[] buffer = new byte[count]; stream.Position = 0; do { count = stream.Read(buffer, 0, count); ms.Write(buffer, 0, count); } while (count == 4096); IntPtr newimage = IntPtr.Zero; newimage = InitFromStream(ms); if (this is Bitmap) return new Bitmap(newimage, ms); else return new Metafile(newimage, ms); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace NewsPlus.Api.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
#if ANDROID #define REQUIRES_PRIMARY_THREAD_LOADING #endif using BitmapFont = FlatRedBall.Graphics.BitmapFont; using Cursor = FlatRedBall.Gui.Cursor; using GuiManager = FlatRedBall.Gui.GuiManager; // Generated Usings using FrbTicTacToe.Screens; using FlatRedBall.Graphics; using FlatRedBall.Math; using FrbTicTacToe.Entities; using FlatRedBall; using FlatRedBall.Screens; using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework.Graphics; #if XNA4 || WINDOWS_8 using Color = Microsoft.Xna.Framework.Color; #elif FRB_MDX using Color = System.Drawing.Color; #else using Color = Microsoft.Xna.Framework.Graphics.Color; #endif #if FRB_XNA || SILVERLIGHT using Keys = Microsoft.Xna.Framework.Input.Keys; using Vector3 = Microsoft.Xna.Framework.Vector3; using Texture2D = Microsoft.Xna.Framework.Graphics.Texture2D; #endif #if FRB_XNA && !MONODROID using Model = Microsoft.Xna.Framework.Graphics.Model; #endif namespace FrbTicTacToe.Entities { public partial class Background : PositionedObject, IDestroyable { // This is made global so that static lazy-loaded content can access it. public static string ContentManagerName { get; set; } // Generated Fields #if DEBUG static bool HasBeenLoadedWithGlobalContentManager = false; #endif static object mLockObject = new object(); static List<string> mRegisteredUnloads = new List<string>(); static List<string> LoadedContentManagers = new List<string>(); protected static Microsoft.Xna.Framework.Graphics.Texture2D BackgroundTexture; protected static Microsoft.Xna.Framework.Graphics.Texture2D Background4; protected static Microsoft.Xna.Framework.Graphics.Texture2D Background5; protected static Microsoft.Xna.Framework.Graphics.Texture2D Background1; protected static Microsoft.Xna.Framework.Graphics.Texture2D Background2; protected static Microsoft.Xna.Framework.Graphics.Texture2D Background3; private FlatRedBall.Sprite BackgroundSprite; public bool RandomImage = true; protected Layer LayerProvidedByContainer = null; public Background() : this(FlatRedBall.Screens.ScreenManager.CurrentScreen.ContentManagerName, true) { } public Background(string contentManagerName) : this(contentManagerName, true) { } public Background(string contentManagerName, bool addToManagers) : base() { // Don't delete this: ContentManagerName = contentManagerName; InitializeEntity(addToManagers); } protected virtual void InitializeEntity(bool addToManagers) { // Generated Initialize LoadStaticContent(ContentManagerName); BackgroundSprite = new FlatRedBall.Sprite(); BackgroundSprite.Name = "BackgroundSprite"; PostInitialize(); if (addToManagers) { AddToManagers(null); } } // Generated AddToManagers public virtual void ReAddToManagers (Layer layerToAddTo) { LayerProvidedByContainer = layerToAddTo; SpriteManager.AddPositionedObject(this); SpriteManager.AddToLayer(BackgroundSprite, LayerProvidedByContainer); } public virtual void AddToManagers (Layer layerToAddTo) { LayerProvidedByContainer = layerToAddTo; SpriteManager.AddPositionedObject(this); SpriteManager.AddToLayer(BackgroundSprite, LayerProvidedByContainer); AddToManagersBottomUp(layerToAddTo); CustomInitialize(); } public virtual void Activity() { // Generated Activity CustomActivity(); // After Custom Activity } public virtual void Destroy() { // Generated Destroy SpriteManager.RemovePositionedObject(this); if (BackgroundSprite != null) { SpriteManager.RemoveSprite(BackgroundSprite); } CustomDestroy(); } // Generated Methods public virtual void PostInitialize () { bool oldShapeManagerSuppressAdd = FlatRedBall.Math.Geometry.ShapeManager.SuppressAddingOnVisibilityTrue; FlatRedBall.Math.Geometry.ShapeManager.SuppressAddingOnVisibilityTrue = true; if (BackgroundSprite.Parent == null) { BackgroundSprite.CopyAbsoluteToRelative(); BackgroundSprite.AttachTo(this, false); } BackgroundSprite.Texture = BackgroundTexture; BackgroundSprite.Height = 600f; BackgroundSprite.TextureScale = 0f; BackgroundSprite.Width = 800f; if (BackgroundSprite.Parent == null) { BackgroundSprite.Z = -1f; } else { BackgroundSprite.RelativeZ = -1f; } FlatRedBall.Math.Geometry.ShapeManager.SuppressAddingOnVisibilityTrue = oldShapeManagerSuppressAdd; } public virtual void AddToManagersBottomUp (Layer layerToAddTo) { AssignCustomVariables(false); } public virtual void RemoveFromManagers () { SpriteManager.ConvertToManuallyUpdated(this); if (BackgroundSprite != null) { SpriteManager.RemoveSpriteOneWay(BackgroundSprite); } } public virtual void AssignCustomVariables (bool callOnContainedElements) { if (callOnContainedElements) { } BackgroundSprite.Texture = BackgroundTexture; BackgroundSprite.Height = 600f; BackgroundSprite.TextureScale = 0f; BackgroundSprite.Width = 800f; if (BackgroundSprite.Parent == null) { BackgroundSprite.Z = -1f; } else { BackgroundSprite.RelativeZ = -1f; } RandomImage = true; } public virtual void ConvertToManuallyUpdated () { this.ForceUpdateDependenciesDeep(); SpriteManager.ConvertToManuallyUpdated(this); SpriteManager.ConvertToManuallyUpdated(BackgroundSprite); } public static void LoadStaticContent (string contentManagerName) { if (string.IsNullOrEmpty(contentManagerName)) { throw new ArgumentException("contentManagerName cannot be empty or null"); } ContentManagerName = contentManagerName; #if DEBUG if (contentManagerName == FlatRedBallServices.GlobalContentManager) { HasBeenLoadedWithGlobalContentManager = true; } else if (HasBeenLoadedWithGlobalContentManager) { throw new Exception("This type has been loaded with a Global content manager, then loaded with a non-global. This can lead to a lot of bugs"); } #endif bool registerUnload = false; if (LoadedContentManagers.Contains(contentManagerName) == false) { LoadedContentManagers.Add(contentManagerName); lock (mLockObject) { if (!mRegisteredUnloads.Contains(ContentManagerName) && ContentManagerName != FlatRedBallServices.GlobalContentManager) { FlatRedBallServices.GetContentManagerByName(ContentManagerName).AddUnloadMethod("BackgroundStaticUnload", UnloadStaticContent); mRegisteredUnloads.Add(ContentManagerName); } } if (!FlatRedBallServices.IsLoaded<Microsoft.Xna.Framework.Graphics.Texture2D>(@"content/entities/background/backgroundtexture.png", ContentManagerName)) { registerUnload = true; } BackgroundTexture = FlatRedBallServices.Load<Microsoft.Xna.Framework.Graphics.Texture2D>(@"content/entities/background/backgroundtexture.png", ContentManagerName); if (!FlatRedBallServices.IsLoaded<Microsoft.Xna.Framework.Graphics.Texture2D>(@"content/entities/background/background4.png", ContentManagerName)) { registerUnload = true; } Background4 = FlatRedBallServices.Load<Microsoft.Xna.Framework.Graphics.Texture2D>(@"content/entities/background/background4.png", ContentManagerName); if (!FlatRedBallServices.IsLoaded<Microsoft.Xna.Framework.Graphics.Texture2D>(@"content/entities/background/background5.png", ContentManagerName)) { registerUnload = true; } Background5 = FlatRedBallServices.Load<Microsoft.Xna.Framework.Graphics.Texture2D>(@"content/entities/background/background5.png", ContentManagerName); if (!FlatRedBallServices.IsLoaded<Microsoft.Xna.Framework.Graphics.Texture2D>(@"content/entities/background/background1.png", ContentManagerName)) { registerUnload = true; } Background1 = FlatRedBallServices.Load<Microsoft.Xna.Framework.Graphics.Texture2D>(@"content/entities/background/background1.png", ContentManagerName); if (!FlatRedBallServices.IsLoaded<Microsoft.Xna.Framework.Graphics.Texture2D>(@"content/entities/background/background2.png", ContentManagerName)) { registerUnload = true; } Background2 = FlatRedBallServices.Load<Microsoft.Xna.Framework.Graphics.Texture2D>(@"content/entities/background/background2.png", ContentManagerName); if (!FlatRedBallServices.IsLoaded<Microsoft.Xna.Framework.Graphics.Texture2D>(@"content/entities/background/background3.png", ContentManagerName)) { registerUnload = true; } Background3 = FlatRedBallServices.Load<Microsoft.Xna.Framework.Graphics.Texture2D>(@"content/entities/background/background3.png", ContentManagerName); } if (registerUnload && ContentManagerName != FlatRedBallServices.GlobalContentManager) { lock (mLockObject) { if (!mRegisteredUnloads.Contains(ContentManagerName) && ContentManagerName != FlatRedBallServices.GlobalContentManager) { FlatRedBallServices.GetContentManagerByName(ContentManagerName).AddUnloadMethod("BackgroundStaticUnload", UnloadStaticContent); mRegisteredUnloads.Add(ContentManagerName); } } } CustomLoadStaticContent(contentManagerName); } public static void UnloadStaticContent () { if (LoadedContentManagers.Count != 0) { LoadedContentManagers.RemoveAt(0); mRegisteredUnloads.RemoveAt(0); } if (LoadedContentManagers.Count == 0) { if (BackgroundTexture != null) { BackgroundTexture= null; } if (Background4 != null) { Background4= null; } if (Background5 != null) { Background5= null; } if (Background1 != null) { Background1= null; } if (Background2 != null) { Background2= null; } if (Background3 != null) { Background3= null; } } } [System.Obsolete("Use GetFile instead")] public static object GetStaticMember (string memberName) { switch(memberName) { case "BackgroundTexture": return BackgroundTexture; case "Background4": return Background4; case "Background5": return Background5; case "Background1": return Background1; case "Background2": return Background2; case "Background3": return Background3; } return null; } public static object GetFile (string memberName) { switch(memberName) { case "BackgroundTexture": return BackgroundTexture; case "Background4": return Background4; case "Background5": return Background5; case "Background1": return Background1; case "Background2": return Background2; case "Background3": return Background3; } return null; } object GetMember (string memberName) { switch(memberName) { case "BackgroundTexture": return BackgroundTexture; case "Background4": return Background4; case "Background5": return Background5; case "Background1": return Background1; case "Background2": return Background2; case "Background3": return Background3; } return null; } protected bool mIsPaused; public override void Pause (FlatRedBall.Instructions.InstructionList instructions) { base.Pause(instructions); mIsPaused = true; } public virtual void SetToIgnorePausing () { FlatRedBall.Instructions.InstructionManager.IgnorePausingFor(this); FlatRedBall.Instructions.InstructionManager.IgnorePausingFor(BackgroundSprite); } public virtual void MoveToLayer (Layer layerToMoveTo) { if (LayerProvidedByContainer != null) { LayerProvidedByContainer.Remove(BackgroundSprite); } SpriteManager.AddToLayer(BackgroundSprite, layerToMoveTo); LayerProvidedByContainer = layerToMoveTo; } } // Extra classes }
/* Cordova WeChat Plugin https://github.com/vilic/cordova-plugin-wechat by VILIC VANE https://github.com/vilic MIT License */ using MicroMsg.sdk; using System; using System.Windows.Navigation; using System.Runtime.Serialization; using WPCordovaClassLib.Cordova; using WPCordovaClassLib.Cordova.Commands; using WPCordovaClassLib.Cordova.JSON; using WPCordovaClassLib.CordovaLib; using Windows.Phone.Storage.SharedAccess; using Cordova.Extension.Commands; using System.Windows; using System.IO; using System.Linq; using System.Xml.Linq; using Microsoft.Phone.Shell; class WeChatAssociationUriMapper : UriMapperBase { UriMapperBase upper; public WeChatAssociationUriMapper(UriMapperBase upperMapper = null) { upper = upperMapper; } public override Uri MapUri(Uri uri) { string uriStr = uri.ToString(); if (uriStr.Contains("/FileTypeAssociation")) { int fileIDIndex = uriStr.IndexOf("fileToken=") + 10; string fileID = uriStr.Substring(fileIDIndex); string incommingFileName = SharedStorageAccessManager.GetSharedFileName(fileID); // Path.GetExtension will return String.Empty if no file extension found. int extensionIndex = incommingFileName.LastIndexOf('.') + 1; string incomingFileType = incommingFileName.Substring(extensionIndex).ToLower(); if (incomingFileType == WeChat.appId) { return new Uri("/WeChatCallbackPage.xaml?fileToken=" + fileID, UriKind.Relative); } } if (upper != null) { var upperResult = upper.MapUri(uri); if (upperResult != uri) { return upperResult; } } return new Uri("/MainPage.xaml", UriKind.Relative); } } namespace Cordova.Extension.Commands { [DataContract] enum WeChatShareType { [EnumMember] app = 1, [EnumMember] emotion, [EnumMember] file, [EnumMember] image, [EnumMember] music, [EnumMember] video, [EnumMember] webpage } [DataContract] enum WeChatScene { [EnumMember] chosenByUser, [EnumMember] session, [EnumMember] timeline } [DataContract] class WeChatMessageOptions { [DataMember] public WeChatShareType? type; [DataMember] public string title; [DataMember] public string description; //[DataMember] //public string mediaTagName; [DataMember] public string thumbData; [DataMember] public string url; [DataMember] public string data; } [DataContract] class WeChatShareOptions { [DataMember] public string text; [DataMember] public WeChatMessageOptions message; [DataMember] public WeChatScene? scene; } class WeChat : BaseCommand { public static string appId; static IWXAPI api; public static WeChat current = null; public const string WECHAT_APPID_KEY = "wechatappid"; public const string ERR_INVALID_OPTIONS = "ERR_INVALID_OPTIONS"; public const string ERR_UNSUPPORTED_MEDIA_TYPE = "ERR_UNSUPPORTED_MEDIA_TYPE"; public const string NO_RESULT = "NO_RESULT"; static WeChat() { var streamInfo = Application.GetResourceStream(new Uri("config.xml", UriKind.Relative)); var sr = new StreamReader(streamInfo.Stream); var document = XDocument.Parse(sr.ReadToEnd()); appId = (from results in document.Descendants() where results.Name.LocalName == "preference" && ((string)results.Attribute("name") == WECHAT_APPID_KEY) select (string)results.Attribute("value")).First(); api = WXAPIFactory.CreateWXAPI(appId); } public WeChat() { current = this; } public void share(string argsJSON) { var args = JsonHelper.Deserialize<string[]>(argsJSON); var options = JsonHelper.Deserialize<WeChatShareOptions>(args[0]); if (options == null) { dispatchResult(PluginResult.Status.JSON_EXCEPTION, ERR_INVALID_OPTIONS); return; } WXBaseMessage message = null; var messageOptions = options.message; if (messageOptions != null) { switch (messageOptions.type) { case WeChatShareType.app: break; case WeChatShareType.emotion: break; case WeChatShareType.file: break; case WeChatShareType.image: if (!String.IsNullOrEmpty(messageOptions.url)) { message = new WXImageMessage(messageOptions.url); } else if (!String.IsNullOrEmpty(messageOptions.data)) { message = new WXImageMessage(Convert.FromBase64String(messageOptions.data)); } else { dispatchResult(PluginResult.Status.ERROR, ERR_INVALID_OPTIONS); return; } break; case WeChatShareType.music: break; case WeChatShareType.video: break; case WeChatShareType.webpage: default: message = new WXWebpageMessage(messageOptions.url); break; } if (message == null) { dispatchResult(PluginResult.Status.ERROR, ERR_UNSUPPORTED_MEDIA_TYPE); return; } message.Title = messageOptions.title; message.Description = messageOptions.description; if (!String.IsNullOrEmpty(messageOptions.thumbData)) { message.ThumbData = Convert.FromBase64String(messageOptions.thumbData); } } else if (options.text != null) { message = new WXTextMessage(options.text); } else { dispatchResult(PluginResult.Status.ERROR, ERR_INVALID_OPTIONS); return; } var scene = options.scene; if (scene == null) { scene = WeChatScene.timeline; } try { var request = new SendMessageToWX.Req(message, (int)scene); api.SendReq(request); } catch (WXException e) { dispatchResult(PluginResult.Status.ERROR, e.Message); return; } } public void dispatchResult(PluginResult.Status status, string message) { DispatchCommandResult(new PluginResult(status, message)); } } }
/* * Farseer Physics Engine based on Box2D.XNA port: * Copyright (c) 2010 Ian Qvist * * Box2D.XNA port of Box2D: * Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler * * Original source Box2D: * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using FarseerPhysics.Collision.Shapes; using FarseerPhysics.Common; using FarseerPhysics.Dynamics; using FarseerPhysics.Dynamics.Joints; using FarseerPhysics.Factories; using FarseerPhysics.TestBed.Framework; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; namespace FarseerPhysics.TestBed.Tests { public class TheoJansenTest : Test { private Body _chassis; private RevoluteJoint _motorJoint; private bool _motorOn; private float _motorSpeed; private Vector2 _offset; private Body _wheel; private TheoJansenTest() { _offset = new Vector2(0.0f, 8.0f); _motorSpeed = 2.0f; _motorOn = true; Vector2 pivot = new Vector2(0.0f, 0.8f); // Ground { Body ground = BodyFactory.CreateBody(World); EdgeShape shape = new EdgeShape(new Vector2(-50.0f, 0.0f), new Vector2(50.0f, 0.0f)); ground.CreateFixture(shape); shape = new EdgeShape(new Vector2(-50.0f, 0.0f), new Vector2(-50.0f, 10.0f)); ground.CreateFixture(shape); shape = new EdgeShape(new Vector2(50.0f, 0.0f), new Vector2(50.0f, 10.0f)); ground.CreateFixture(shape); } // Balls for (int i = 0; i < 40; ++i) { CircleShape shape = new CircleShape(0.25f, 1); Body body = BodyFactory.CreateBody(World); body.BodyType = BodyType.Dynamic; body.Position = new Vector2(-40.0f + 2.0f * i, 0.5f); body.CreateFixture(shape); } // Chassis { PolygonShape shape = new PolygonShape(1); shape.SetAsBox(2.5f, 1.0f); _chassis = BodyFactory.CreateBody(World); _chassis.BodyType = BodyType.Dynamic; _chassis.Position = pivot + _offset; Fixture fixture = _chassis.CreateFixture(shape); fixture.CollisionGroup = -1; } { CircleShape shape = new CircleShape(1.6f, 1); _wheel = BodyFactory.CreateBody(World); _wheel.BodyType = BodyType.Dynamic; _wheel.Position = pivot + _offset; Fixture fixture = _wheel.CreateFixture(shape); fixture.CollisionGroup = -1; } { //_motorJoint = new RevoluteJoint(_wheel, _chassis, pivot + _offset); _motorJoint = new RevoluteJoint(_wheel, _chassis, _wheel.GetLocalPoint(_chassis.Position), Vector2.Zero); _motorJoint.CollideConnected = false; _motorJoint.MotorSpeed = _motorSpeed; _motorJoint.MaxMotorTorque = 400.0f; _motorJoint.MotorEnabled = _motorOn; World.AddJoint(_motorJoint); } Vector2 wheelAnchor = pivot + new Vector2(0.0f, -0.8f); CreateLeg(-1.0f, wheelAnchor); CreateLeg(1.0f, wheelAnchor); _wheel.SetTransform(_wheel.Position, 120.0f * Settings.Pi / 180.0f); CreateLeg(-1.0f, wheelAnchor); CreateLeg(1.0f, wheelAnchor); _wheel.SetTransform(_wheel.Position, -120.0f * Settings.Pi / 180.0f); CreateLeg(-1.0f, wheelAnchor); CreateLeg(1.0f, wheelAnchor); } private void CreateLeg(float s, Vector2 wheelAnchor) { Vector2 p1 = new Vector2(5.4f * s, -6.1f); Vector2 p2 = new Vector2(7.2f * s, -1.2f); Vector2 p3 = new Vector2(4.3f * s, -1.9f); Vector2 p4 = new Vector2(3.1f * s, 0.8f); Vector2 p5 = new Vector2(6.0f * s, 1.5f); Vector2 p6 = new Vector2(2.5f * s, 3.7f); PolygonShape poly1 = new PolygonShape(1); PolygonShape poly2 = new PolygonShape(2); Vertices vertices = new Vertices(3); if (s > 0.0f) { vertices.Add(p1); vertices.Add(p2); vertices.Add(p3); poly1.Set(vertices); vertices[0] = Vector2.Zero; vertices[1] = p5 - p4; vertices[2] = p6 - p4; poly2.Set(vertices); } else { vertices.Add(p1); vertices.Add(p3); vertices.Add(p2); poly1.Set(vertices); vertices[0] = Vector2.Zero; vertices[1] = p6 - p4; vertices[2] = p5 - p4; poly2.Set(vertices); } Body body1 = BodyFactory.CreateBody(World); body1.BodyType = BodyType.Dynamic; body1.Position = _offset; body1.AngularDamping = 10.0f; Body body2 = BodyFactory.CreateBody(World); body2.BodyType = BodyType.Dynamic; body2.Position = p4 + _offset; body2.AngularDamping = 10.0f; Fixture f1 = body1.CreateFixture(poly1); f1.CollisionGroup = -1; Fixture f2 = body2.CreateFixture(poly2); f2.CollisionGroup = -1; // Using a soft distanceraint can reduce some jitter. // It also makes the structure seem a bit more fluid by // acting like a suspension system. DistanceJoint djd = new DistanceJoint(body1, body2, body1.GetLocalPoint(p2 + _offset), body2.GetLocalPoint(p5 + _offset)); djd.DampingRatio = 0.5f; djd.Frequency = 10.0f; World.AddJoint(djd); DistanceJoint djd2 = new DistanceJoint(body1, body2, body1.GetLocalPoint(p3 + _offset), body2.GetLocalPoint(p4 + _offset)); djd2.DampingRatio = 0.5f; djd2.Frequency = 10.0f; World.AddJoint(djd2); DistanceJoint djd3 = new DistanceJoint(body1, _wheel, body1.GetLocalPoint(p3 + _offset), _wheel.GetLocalPoint(wheelAnchor + _offset)); djd3.DampingRatio = 0.5f; djd3.Frequency = 10.0f; World.AddJoint(djd3); DistanceJoint djd4 = new DistanceJoint(body2, _wheel, body2.GetLocalPoint(p6 + _offset), _wheel.GetLocalPoint(wheelAnchor + _offset)); djd4.DampingRatio = 0.5f; djd4.Frequency = 10.0f; World.AddJoint(djd4); Vector2 anchor = p4 - new Vector2(0.0f, 0.8f) /*+ _offset*/; RevoluteJoint rjd = new RevoluteJoint(body2, _chassis, body2.GetLocalPoint(_chassis.GetWorldPoint(anchor)), anchor); World.AddJoint(rjd); } public override void Update(GameSettings settings, GameTime gameTime) { DebugView.DrawString(50, TextLine, "Keys: left = a, brake = s, right = d, toggle motor = m"); TextLine += 15; base.Update(settings, gameTime); } public override void Keyboard(KeyboardManager keyboardManager) { if (keyboardManager.IsNewKeyPress(Keys.A)) { _motorJoint.MotorSpeed = -_motorSpeed; } if (keyboardManager.IsNewKeyPress(Keys.S)) { _motorJoint.MotorSpeed = 0.0f; } if (keyboardManager.IsNewKeyPress(Keys.D)) { _motorJoint.MotorSpeed = _motorSpeed; } if (keyboardManager.IsNewKeyPress(Keys.M)) { _motorJoint.MotorEnabled = !_motorJoint.MotorEnabled; } base.Keyboard(keyboardManager); } internal static Test Create() { return new TheoJansenTest(); } } }
// 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.Threading; using System.Diagnostics; using System.Collections.Generic; using System.Diagnostics.Tracing; using System.Runtime.CompilerServices; // TODO when we upgrade to C# V6 you can remove this. // warning CS0420: 'P.x': a reference to a volatile field will not be treated as volatile // This happens when you pass a _subcribers (a volatile field) to interlocked operations (which are byref). // This was fixed in C# V6. #pragma warning disable 0420 namespace System.Diagnostics { /// <summary> /// A DiagnosticListener is something that forwards on events written with DiagnosticSource. /// It is an IObservable (has Subscribe method), and it also has a Subscribe overload that /// lets you specify a 'IsEnabled' predicate that users of DiagnosticSource will use for /// 'quick checks'. /// /// The item in the stream is a KeyValuePair[string, object] where the string is the name /// of the diagnostic item and the object is the payload (typically an anonymous type). /// /// There may be many DiagnosticListeners in the system, but we encourage the use of /// The DiagnosticSource.DefaultSource which goes to the DiagnosticListener.DefaultListener. /// /// If you need to see 'everything' you can subscribe to the 'AllListeners' event that /// will fire for every live DiagnosticListener in the appdomain (past or present). /// </summary> public class DiagnosticListener : DiagnosticSource, IObservable<KeyValuePair<string, object>>, IDisposable { #if false /// <summary> /// This is the DiagnosticListener that is used by default by the class library. /// Generally you don't want to make your own but rather have everyone use this one, which /// ensures that everyone who wished to subscribe gets the callbacks. /// The main reason not to us this one is that you WANT isolation from other /// events in the system (e.g. multi-tenancy). /// </summary> public static DiagnosticListener DefaultListener { get { return s_default; } } #endif /// <summary> /// When you subscribe to this you get callbacks for all NotificationListeners in the appdomain /// as well as those that occurred in the past, and all future Listeners created in the future. /// </summary> public static IObservable<DiagnosticListener> AllListeners { get { if (s_allListenerObservable == null) { s_allListenerObservable = new AllListenerObservable(); } return s_allListenerObservable; } } // Subscription implementation /// <summary> /// Add a subscriber (Observer). If 'IsEnabled' == null (or not present), then the Source's IsEnabled /// will always return true. /// </summary> virtual public IDisposable Subscribe(IObserver<KeyValuePair<string, object>> observer, Predicate<string> isEnabled) { // If we have been disposed, we silently ignore any subscriptions. if (_disposed) { return new DiagnosticSubscription() { Owner = this }; } DiagnosticSubscription newSubscription = new DiagnosticSubscription() { Observer = observer, IsEnabled = isEnabled, Owner = this, Next = _subscriptions }; while (Interlocked.CompareExchange(ref _subscriptions, newSubscription, newSubscription.Next) != newSubscription.Next) newSubscription.Next = _subscriptions; return newSubscription; } /// <summary> /// Same as other Subscribe overload where the predicate is assumed to always return true. /// </summary> public IDisposable Subscribe(IObserver<KeyValuePair<string, object>> observer) { return Subscribe(observer, null); } /// <summary> /// Make a new DiagnosticListener, it is a NotificationSource, which means the returned result can be used to /// log notifications, but it also has a Subscribe method so notifications can be forwarded /// arbitrarily. Thus its job is to forward things from the producer to all the listeners /// (multi-casting). Generally you should not be making your own DiagnosticListener but use the /// DiagnosticListener.Default, so that notifications are as 'public' as possible. /// </summary> public DiagnosticListener(string name) { Name = name; // Insert myself into the list of all Listeners. lock (s_lock) { // Issue the callback for this new diagnostic listener. var allListenerObservable = s_allListenerObservable; if (allListenerObservable != null) allListenerObservable.OnNewDiagnosticListener(this); // And add it to the list of all past listeners. _next = s_allListeners; s_allListeners = this; } // Call IsEnabled just so we insure that the DiagnosticSourceEventSource has been // constructed (and thus is responsive to ETW requests to be enabled). DiagnosticSourceEventSource.Logger.IsEnabled(); } /// <summary> /// Clean up the NotificationListeners. Notification listeners do NOT DIE ON THEIR OWN /// because they are in a global list (for discoverability). You must dispose them explicitly. /// Note that we do not do the Dispose(bool) pattern because we frankly don't want to support /// subclasses that have non-managed state. /// </summary> virtual public void Dispose() { // Remove myself from the list of all listeners. lock (s_lock) { if (_disposed) { return; } _disposed = true; if (s_allListeners == this) s_allListeners = s_allListeners._next; else { var cur = s_allListeners; while (cur != null) { if (cur._next == this) { cur._next = _next; break; } cur = cur._next; } } _next = null; } // Indicate completion to all subscribers. DiagnosticSubscription subscriber = null; Interlocked.Exchange(ref subscriber, _subscriptions); while (subscriber != null) { subscriber.Observer.OnCompleted(); subscriber = subscriber.Next; } // The code above also nulled out all subscriptions. } /// <summary> /// When a DiagnosticListener is created it is given a name. Return this. /// </summary> public string Name { get; private set; } /// <summary> /// Return the name for the ToString() to aid in debugging. /// </summary> /// <returns></returns> public override string ToString() { return Name; } #region private // NotificationSource implementation /// <summary> /// Override abstract method /// </summary> public override bool IsEnabled(string name) { for (DiagnosticSubscription curSubscription = _subscriptions; curSubscription != null; curSubscription = curSubscription.Next) { if (curSubscription.IsEnabled == null || curSubscription.IsEnabled(name)) return true; } return false; } /// <summary> /// Override abstract method /// </summary> public override void Write(string name, object value) { for (DiagnosticSubscription curSubscription = _subscriptions; curSubscription != null; curSubscription = curSubscription.Next) curSubscription.Observer.OnNext(new KeyValuePair<string, object>(name, value)); } // Note that Subscriptions are READ ONLY. This means you never update any fields (even on removal!) private class DiagnosticSubscription : IDisposable { internal IObserver<KeyValuePair<string, object>> Observer; internal Predicate<string> IsEnabled; internal DiagnosticListener Owner; // The DiagnosticListener this is a subscription for. internal DiagnosticSubscription Next; // Linked list of subscribers public void Dispose() { // TO keep this lock free and easy to analyze, the linked list is READ ONLY. Thus we copy for (;;) { DiagnosticSubscription subscriptions = Owner._subscriptions; DiagnosticSubscription newSubscriptions = Remove(subscriptions, this); // Make a new list, with myself removed. // try to update, but if someone beat us to it, then retry. if (Interlocked.CompareExchange(ref Owner._subscriptions, newSubscriptions, subscriptions) == subscriptions) { #if DEBUG var cur = newSubscriptions; while (cur != null) { Debug.Assert(!(cur.Observer == Observer && cur.IsEnabled == IsEnabled), "Did not remove subscription!"); cur = cur.Next; } #endif break; } } } // Create a new linked list where 'subscription has been removed from the linked list of 'subscriptions'. private static DiagnosticSubscription Remove(DiagnosticSubscription subscriptions, DiagnosticSubscription subscription) { if (subscriptions == null) { // May happen if the IDisposable returned from Subscribe is Dispose'd again return null; } if (subscriptions.Observer == subscription.Observer && subscriptions.IsEnabled == subscription.IsEnabled) return subscriptions.Next; #if DEBUG // Delay a bit. This makes it more likely that races will happen. for (int i = 0; i < 100; i++) GC.KeepAlive(""); #endif return new DiagnosticSubscription() { Observer = subscriptions.Observer, Owner = subscriptions.Owner, IsEnabled = subscriptions.IsEnabled, Next = Remove(subscriptions.Next, subscription) }; } } #region AllListenerObservable /// <summary> /// Logically AllListenerObservable has a very simple task. It has a linked list of subscribers that want /// a callback when a new listener gets created. When a new DiagnosticListener gets created it should call /// OnNewDiagnosticListener so that AllListenerObservable can forward it on to all the subscribers. /// </summary> private class AllListenerObservable : IObservable<DiagnosticListener> { public IDisposable Subscribe(IObserver<DiagnosticListener> observer) { lock (s_lock) { // Call back for each existing listener on the new callback (catch-up). for (DiagnosticListener cur = s_allListeners; cur != null; cur = cur._next) observer.OnNext(cur); // Add the observer to the list of subscribers. _subscriptions = new AllListenerSubscription(this, observer, _subscriptions); return _subscriptions; } } /// <summary> /// Called when a new DiagnosticListener gets created to tell anyone who subscribed that this happened. /// </summary> /// <param name="diagnosticListener"></param> internal void OnNewDiagnosticListener(DiagnosticListener diagnosticListener) { Debug.Assert(Monitor.IsEntered(s_lock)); // We should only be called when we hold this lock // Simply send a callback to every subscriber that we have a new listener for (var cur = _subscriptions; cur != null; cur = cur.Next) cur.Subscriber.OnNext(diagnosticListener); } #region private /// <summary> /// Remove 'subscription from the list of subscriptions that the observable has. Called when /// subscriptions are disposed. Returns true if the subscription was removed. /// </summary> private bool Remove(AllListenerSubscription subscription) { lock (s_lock) { if (_subscriptions == subscription) { _subscriptions = subscription.Next; return true; } else if (_subscriptions != null) { for (var cur = _subscriptions; cur.Next != null; cur = cur.Next) { if (cur.Next == subscription) { cur.Next = cur.Next.Next; return true; } } } // Subscriber likely disposed multiple times return false; } } /// <summary> /// One node in the linked list of subscriptions that AllListenerObservable keeps. It is /// IDisposable, and when that is called it removes itself from the list. /// </summary> internal class AllListenerSubscription : IDisposable { internal AllListenerSubscription(AllListenerObservable owner, IObserver<DiagnosticListener> subscriber, AllListenerSubscription next) { this._owner = owner; this.Subscriber = subscriber; this.Next = next; } public void Dispose() { if (_owner.Remove(this)) { Subscriber.OnCompleted(); // Called outside of a lock } } private readonly AllListenerObservable _owner; // the list this is a member of. internal readonly IObserver<DiagnosticListener> Subscriber; internal AllListenerSubscription Next; } private AllListenerSubscription _subscriptions; #endregion } #endregion private volatile DiagnosticSubscription _subscriptions; private DiagnosticListener _next; // We keep a linked list of all NotificationListeners (s_allListeners) private bool _disposed; // Has Dispose been called? private static DiagnosticListener s_allListeners; // linked list of all instances of DiagnosticListeners. private static AllListenerObservable s_allListenerObservable; // to make callbacks to this object when listeners come into existence. private static object s_lock = new object(); // A lock for #if false private static readonly DiagnosticListener s_default = new DiagnosticListener("DiagnosticListener.DefaultListener"); #endif #endregion } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Threading; using Amazon.CloudWatch.Model; using Amazon.CloudWatch.Model.Internal.MarshallTransformations; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.CloudWatch { /// <summary> /// Implementation for accessing AmazonCloudWatch. /// /// Amazon CloudWatch <para>This is the <i>Amazon CloudWatch API Reference</i> . This guide provides detailed information about Amazon /// CloudWatch actions, data types, parameters, and errors. For detailed information about Amazon CloudWatch features and their associated API /// calls, go to the Amazon CloudWatch Developer Guide. </para> <para>Amazon CloudWatch is a web service that enables you to publish, monitor, /// and manage various metrics, as well as configure alarm actions based on data from metrics. For more information about this product go to /// http://aws.amazon.com/cloudwatch. </para> <para> For information about the namespace, metric names, and dimensions that other Amazon Web /// Services products use to send metrics to Cloudwatch, go to Amazon CloudWatch Metrics, Namespaces, and Dimensions Reference in the <i>Amazon /// CloudWatch Developer Guide</i> . /// </para> <para>Use the following links to get started using the <i>Amazon CloudWatch API Reference</i> :</para> /// <ul> /// <li> Actions: An alphabetical list of all Amazon CloudWatch actions.</li> /// <li> Data Types: An alphabetical list of all Amazon CloudWatch data types.</li> /// <li> Common Parameters: Parameters that all Query actions can use.</li> /// <li> Common Errors: Client and server errors that all actions can return.</li> /// <li> Regions and Endpoints: Itemized regions and endpoints for all AWS products.</li> /// <li> WSDL Location: http://monitoring.amazonaws.com/doc/2010-08-01/CloudWatch.wsdl</li> /// /// </ul> /// </summary> public class AmazonCloudWatchClient : AmazonWebServiceClient, AmazonCloudWatch { AbstractAWSSigner signer = new AWS4Signer(); #region Constructors /// <summary> /// Constructs AmazonCloudWatchClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSAccessKey" value="********************"/&gt; /// &lt;add key="AWSSecretKey" value="****************************************"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> public AmazonCloudWatchClient() : base(FallbackCredentialsFactory.GetCredentials(), new AmazonCloudWatchConfig(), true, AuthenticationTypes.User) { } /// <summary> /// Constructs AmazonCloudWatchClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSAccessKey" value="********************"/&gt; /// &lt;add key="AWSSecretKey" value="****************************************"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="region">The region to connect.</param> public AmazonCloudWatchClient(RegionEndpoint region) : base(FallbackCredentialsFactory.GetCredentials(), new AmazonCloudWatchConfig(){RegionEndpoint = region}, true, AuthenticationTypes.User) { } /// <summary> /// Constructs AmazonCloudWatchClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSAccessKey" value="********************"/&gt; /// &lt;add key="AWSSecretKey" value="****************************************"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="config">The AmazonCloudWatch Configuration Object</param> public AmazonCloudWatchClient(AmazonCloudWatchConfig config) : base(FallbackCredentialsFactory.GetCredentials(), config, true, AuthenticationTypes.User) { } /// <summary> /// Constructs AmazonCloudWatchClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonCloudWatchClient(AWSCredentials credentials) : this(credentials, new AmazonCloudWatchConfig()) { } /// <summary> /// Constructs AmazonCloudWatchClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonCloudWatchClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonCloudWatchConfig(){RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonCloudWatchClient with AWS Credentials and an /// AmazonCloudWatchClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonCloudWatchClient Configuration Object</param> public AmazonCloudWatchClient(AWSCredentials credentials, AmazonCloudWatchConfig clientConfig) : base(credentials, clientConfig, false, AuthenticationTypes.User) { } /// <summary> /// Constructs AmazonCloudWatchClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> public AmazonCloudWatchClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonCloudWatchConfig()) { } /// <summary> /// Constructs AmazonCloudWatchClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="region">The region to connect.</param> public AmazonCloudWatchClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonCloudWatchConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonCloudWatchClient with AWS Access Key ID, AWS Secret Key and an /// AmazonCloudWatchClient Configuration object. If the config object's /// UseSecureStringForAwsSecretKey is false, the AWS Secret Key /// is stored as a clear-text string. Please use this option only /// if the application environment doesn't allow the use of SecureStrings. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonCloudWatchClient Configuration Object</param> public AmazonCloudWatchClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonCloudWatchConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig, AuthenticationTypes.User) { } #endregion #region PutMetricAlarm /// <summary> /// <para> Creates or updates an alarm and associates it with the specified Amazon CloudWatch metric. Optionally, this operation can associate /// one or more Amazon Simple Notification Service resources with the alarm. </para> <para> When this operation creates an alarm, the alarm /// state is immediately set to <c>INSUFFICIENT_DATA</c> . The alarm is evaluated and its <c>StateValue</c> is set appropriately. Any actions /// associated with the <c>StateValue</c> is then executed. </para> <para><b>NOTE:</b> When updating an existing alarm, its StateValue is left /// unchanged. </para> /// </summary> /// /// <param name="putMetricAlarmRequest">Container for the necessary parameters to execute the PutMetricAlarm service method on /// AmazonCloudWatch.</param> /// /// <exception cref="LimitExceededException"/> public PutMetricAlarmResponse PutMetricAlarm(PutMetricAlarmRequest putMetricAlarmRequest) { IAsyncResult asyncResult = invokePutMetricAlarm(putMetricAlarmRequest, null, null, true); return EndPutMetricAlarm(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the PutMetricAlarm operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.PutMetricAlarm"/> /// </summary> /// /// <param name="putMetricAlarmRequest">Container for the necessary parameters to execute the PutMetricAlarm operation on /// AmazonCloudWatch.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> public IAsyncResult BeginPutMetricAlarm(PutMetricAlarmRequest putMetricAlarmRequest, AsyncCallback callback, object state) { return invokePutMetricAlarm(putMetricAlarmRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the PutMetricAlarm operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.PutMetricAlarm"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutMetricAlarm.</param> public PutMetricAlarmResponse EndPutMetricAlarm(IAsyncResult asyncResult) { return endOperation<PutMetricAlarmResponse>(asyncResult); } IAsyncResult invokePutMetricAlarm(PutMetricAlarmRequest putMetricAlarmRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new PutMetricAlarmRequestMarshaller().Marshall(putMetricAlarmRequest); var unmarshaller = PutMetricAlarmResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region PutMetricData /// <summary> /// <para> Publishes metric data points to Amazon CloudWatch. Amazon Cloudwatch associates the data points with the specified metric. If the /// specified metric does not exist, Amazon CloudWatch creates the metric. </para> <para><b>NOTE:</b> If you create a metric with the /// PutMetricData action, allow up to fifteen minutes for the metric to appear in calls to the ListMetrics action. </para> <para> The size of a /// PutMetricData request is limited to 8 KB for HTTP GET requests and 40 KB for HTTP POST requests. </para> <para><b>IMPORTANT:</b> Although /// the Value parameter accepts numbers of type Double, Amazon CloudWatch truncates values with very large exponents. Values with base-10 /// exponents greater than 126 (1 x 10^126) are truncated. Likewise, values with base-10 exponents less than -130 (1 x 10^-130) are also /// truncated. </para> /// </summary> /// /// <param name="putMetricDataRequest">Container for the necessary parameters to execute the PutMetricData service method on /// AmazonCloudWatch.</param> /// /// <exception cref="InvalidParameterValueException"/> /// <exception cref="InternalServiceException"/> /// <exception cref="InvalidParameterCombinationException"/> /// <exception cref="MissingRequiredParameterException"/> public PutMetricDataResponse PutMetricData(PutMetricDataRequest putMetricDataRequest) { IAsyncResult asyncResult = invokePutMetricData(putMetricDataRequest, null, null, true); return EndPutMetricData(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the PutMetricData operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.PutMetricData"/> /// </summary> /// /// <param name="putMetricDataRequest">Container for the necessary parameters to execute the PutMetricData operation on /// AmazonCloudWatch.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> public IAsyncResult BeginPutMetricData(PutMetricDataRequest putMetricDataRequest, AsyncCallback callback, object state) { return invokePutMetricData(putMetricDataRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the PutMetricData operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.PutMetricData"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutMetricData.</param> public PutMetricDataResponse EndPutMetricData(IAsyncResult asyncResult) { return endOperation<PutMetricDataResponse>(asyncResult); } IAsyncResult invokePutMetricData(PutMetricDataRequest putMetricDataRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new PutMetricDataRequestMarshaller().Marshall(putMetricDataRequest); var unmarshaller = PutMetricDataResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region ListMetrics /// <summary> /// <para> Returns a list of valid metrics stored for the AWS account owner. Returned metrics can be used with GetMetricStatistics to obtain /// statistical data for a given metric. </para> <para><b>NOTE:</b> Up to 500 results are returned for any one call. To retrieve further /// results, use returned NextToken values with subsequent ListMetrics operations. </para> <para><b>NOTE:</b> If you create a metric with the /// PutMetricData action, allow up to fifteen minutes for the metric to appear in calls to the ListMetrics action. Statistics about the metric, /// however, are available sooner using GetMetricStatistics. </para> /// </summary> /// /// <param name="listMetricsRequest">Container for the necessary parameters to execute the ListMetrics service method on /// AmazonCloudWatch.</param> /// /// <returns>The response from the ListMetrics service method, as returned by AmazonCloudWatch.</returns> /// /// <exception cref="InternalServiceException"/> /// <exception cref="InvalidParameterValueException"/> public ListMetricsResponse ListMetrics(ListMetricsRequest listMetricsRequest) { IAsyncResult asyncResult = invokeListMetrics(listMetricsRequest, null, null, true); return EndListMetrics(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the ListMetrics operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.ListMetrics"/> /// </summary> /// /// <param name="listMetricsRequest">Container for the necessary parameters to execute the ListMetrics operation on AmazonCloudWatch.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListMetrics /// operation.</returns> public IAsyncResult BeginListMetrics(ListMetricsRequest listMetricsRequest, AsyncCallback callback, object state) { return invokeListMetrics(listMetricsRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the ListMetrics operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.ListMetrics"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListMetrics.</param> /// /// <returns>Returns a ListMetricsResult from AmazonCloudWatch.</returns> public ListMetricsResponse EndListMetrics(IAsyncResult asyncResult) { return endOperation<ListMetricsResponse>(asyncResult); } IAsyncResult invokeListMetrics(ListMetricsRequest listMetricsRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new ListMetricsRequestMarshaller().Marshall(listMetricsRequest); var unmarshaller = ListMetricsResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } /// <summary> /// <para> Returns a list of valid metrics stored for the AWS account owner. Returned metrics can be used with GetMetricStatistics to obtain /// statistical data for a given metric. </para> <para><b>NOTE:</b> Up to 500 results are returned for any one call. To retrieve further /// results, use returned NextToken values with subsequent ListMetrics operations. </para> <para><b>NOTE:</b> If you create a metric with the /// PutMetricData action, allow up to fifteen minutes for the metric to appear in calls to the ListMetrics action. Statistics about the metric, /// however, are available sooner using GetMetricStatistics. </para> /// </summary> /// /// <returns>The response from the ListMetrics service method, as returned by AmazonCloudWatch.</returns> /// /// <exception cref="InternalServiceException"/> /// <exception cref="InvalidParameterValueException"/> public ListMetricsResponse ListMetrics() { return ListMetrics(new ListMetricsRequest()); } #endregion #region GetMetricStatistics /// <summary> /// <para> Gets statistics for the specified metric. </para> <para><b>NOTE:</b> The maximum number of data points returned from a single /// GetMetricStatistics request is 1,440. If a request is made that generates more than 1,440 data points, Amazon CloudWatch returns an error. /// In such a case, alter the request by narrowing the specified time range or increasing the specified period. Alternatively, make multiple /// requests across adjacent time ranges. </para> <para> Amazon CloudWatch aggregates data points based on the length of the <c>period</c> that /// you specify. For example, if you request statistics with a one-minute granularity, Amazon CloudWatch aggregates data points with time stamps /// that fall within the same one-minute period. In such a case, the data points queried can greatly outnumber the data points returned. </para> /// <para><b>NOTE:</b> The maximum number of data points that can be queried is 50,850; whereas the maximum number of data points returned is /// 1,440. </para> <para> The following examples show various statistics allowed by the data point query maximum of 50,850 when you call /// <c>GetMetricStatistics</c> on Amazon EC2 instances with detailed (one-minute) monitoring enabled: </para> /// <ul> /// <li>Statistics for up to 400 instances for a span of one hour</li> /// <li>Statistics for up to 35 instances over a span of 24 hours</li> /// <li>Statistics for up to 2 instances over a span of 2 weeks</li> /// /// </ul> /// <para> For information about the namespace, metric names, and dimensions that other Amazon Web Services products use to send metrics to /// Cloudwatch, go to Amazon CloudWatch Metrics, Namespaces, and Dimensions Reference in the <i>Amazon CloudWatch Developer Guide</i> . /// </para> /// </summary> /// /// <param name="getMetricStatisticsRequest">Container for the necessary parameters to execute the GetMetricStatistics service method on /// AmazonCloudWatch.</param> /// /// <returns>The response from the GetMetricStatistics service method, as returned by AmazonCloudWatch.</returns> /// /// <exception cref="InvalidParameterValueException"/> /// <exception cref="InternalServiceException"/> /// <exception cref="InvalidParameterCombinationException"/> /// <exception cref="MissingRequiredParameterException"/> public GetMetricStatisticsResponse GetMetricStatistics(GetMetricStatisticsRequest getMetricStatisticsRequest) { IAsyncResult asyncResult = invokeGetMetricStatistics(getMetricStatisticsRequest, null, null, true); return EndGetMetricStatistics(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the GetMetricStatistics operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.GetMetricStatistics"/> /// </summary> /// /// <param name="getMetricStatisticsRequest">Container for the necessary parameters to execute the GetMetricStatistics operation on /// AmazonCloudWatch.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndGetMetricStatistics operation.</returns> public IAsyncResult BeginGetMetricStatistics(GetMetricStatisticsRequest getMetricStatisticsRequest, AsyncCallback callback, object state) { return invokeGetMetricStatistics(getMetricStatisticsRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the GetMetricStatistics operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.GetMetricStatistics"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetMetricStatistics.</param> /// /// <returns>Returns a GetMetricStatisticsResult from AmazonCloudWatch.</returns> public GetMetricStatisticsResponse EndGetMetricStatistics(IAsyncResult asyncResult) { return endOperation<GetMetricStatisticsResponse>(asyncResult); } IAsyncResult invokeGetMetricStatistics(GetMetricStatisticsRequest getMetricStatisticsRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new GetMetricStatisticsRequestMarshaller().Marshall(getMetricStatisticsRequest); var unmarshaller = GetMetricStatisticsResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region DisableAlarmActions /// <summary> /// <para> Disables actions for the specified alarms. When an alarm's actions are disabled the alarm's state may change, but none of the alarm's /// actions will execute. </para> /// </summary> /// /// <param name="disableAlarmActionsRequest">Container for the necessary parameters to execute the DisableAlarmActions service method on /// AmazonCloudWatch.</param> /// public DisableAlarmActionsResponse DisableAlarmActions(DisableAlarmActionsRequest disableAlarmActionsRequest) { IAsyncResult asyncResult = invokeDisableAlarmActions(disableAlarmActionsRequest, null, null, true); return EndDisableAlarmActions(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the DisableAlarmActions operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.DisableAlarmActions"/> /// </summary> /// /// <param name="disableAlarmActionsRequest">Container for the necessary parameters to execute the DisableAlarmActions operation on /// AmazonCloudWatch.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> public IAsyncResult BeginDisableAlarmActions(DisableAlarmActionsRequest disableAlarmActionsRequest, AsyncCallback callback, object state) { return invokeDisableAlarmActions(disableAlarmActionsRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the DisableAlarmActions operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.DisableAlarmActions"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDisableAlarmActions.</param> public DisableAlarmActionsResponse EndDisableAlarmActions(IAsyncResult asyncResult) { return endOperation<DisableAlarmActionsResponse>(asyncResult); } IAsyncResult invokeDisableAlarmActions(DisableAlarmActionsRequest disableAlarmActionsRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new DisableAlarmActionsRequestMarshaller().Marshall(disableAlarmActionsRequest); var unmarshaller = DisableAlarmActionsResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region DescribeAlarms /// <summary> /// <para> Retrieves alarms with the specified names. If no name is specified, all alarms for the user are returned. Alarms can be retrieved by /// using only a prefix for the alarm name, the alarm state, or a prefix for any action. </para> /// </summary> /// /// <param name="describeAlarmsRequest">Container for the necessary parameters to execute the DescribeAlarms service method on /// AmazonCloudWatch.</param> /// /// <returns>The response from the DescribeAlarms service method, as returned by AmazonCloudWatch.</returns> /// /// <exception cref="InvalidNextTokenException"/> public DescribeAlarmsResponse DescribeAlarms(DescribeAlarmsRequest describeAlarmsRequest) { IAsyncResult asyncResult = invokeDescribeAlarms(describeAlarmsRequest, null, null, true); return EndDescribeAlarms(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the DescribeAlarms operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.DescribeAlarms"/> /// </summary> /// /// <param name="describeAlarmsRequest">Container for the necessary parameters to execute the DescribeAlarms operation on /// AmazonCloudWatch.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeAlarms /// operation.</returns> public IAsyncResult BeginDescribeAlarms(DescribeAlarmsRequest describeAlarmsRequest, AsyncCallback callback, object state) { return invokeDescribeAlarms(describeAlarmsRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the DescribeAlarms operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.DescribeAlarms"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeAlarms.</param> /// /// <returns>Returns a DescribeAlarmsResult from AmazonCloudWatch.</returns> public DescribeAlarmsResponse EndDescribeAlarms(IAsyncResult asyncResult) { return endOperation<DescribeAlarmsResponse>(asyncResult); } IAsyncResult invokeDescribeAlarms(DescribeAlarmsRequest describeAlarmsRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new DescribeAlarmsRequestMarshaller().Marshall(describeAlarmsRequest); var unmarshaller = DescribeAlarmsResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } /// <summary> /// <para> Retrieves alarms with the specified names. If no name is specified, all alarms for the user are returned. Alarms can be retrieved by /// using only a prefix for the alarm name, the alarm state, or a prefix for any action. </para> /// </summary> /// /// <returns>The response from the DescribeAlarms service method, as returned by AmazonCloudWatch.</returns> /// /// <exception cref="InvalidNextTokenException"/> public DescribeAlarmsResponse DescribeAlarms() { return DescribeAlarms(new DescribeAlarmsRequest()); } #endregion #region DescribeAlarmsForMetric /// <summary> /// <para> Retrieves all alarms for a single metric. Specify a statistic, period, or unit to filter the set of alarms further. </para> /// </summary> /// /// <param name="describeAlarmsForMetricRequest">Container for the necessary parameters to execute the DescribeAlarmsForMetric service method on /// AmazonCloudWatch.</param> /// /// <returns>The response from the DescribeAlarmsForMetric service method, as returned by AmazonCloudWatch.</returns> /// public DescribeAlarmsForMetricResponse DescribeAlarmsForMetric(DescribeAlarmsForMetricRequest describeAlarmsForMetricRequest) { IAsyncResult asyncResult = invokeDescribeAlarmsForMetric(describeAlarmsForMetricRequest, null, null, true); return EndDescribeAlarmsForMetric(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the DescribeAlarmsForMetric operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.DescribeAlarmsForMetric"/> /// </summary> /// /// <param name="describeAlarmsForMetricRequest">Container for the necessary parameters to execute the DescribeAlarmsForMetric operation on /// AmazonCloudWatch.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndDescribeAlarmsForMetric operation.</returns> public IAsyncResult BeginDescribeAlarmsForMetric(DescribeAlarmsForMetricRequest describeAlarmsForMetricRequest, AsyncCallback callback, object state) { return invokeDescribeAlarmsForMetric(describeAlarmsForMetricRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the DescribeAlarmsForMetric operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.DescribeAlarmsForMetric"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeAlarmsForMetric.</param> /// /// <returns>Returns a DescribeAlarmsForMetricResult from AmazonCloudWatch.</returns> public DescribeAlarmsForMetricResponse EndDescribeAlarmsForMetric(IAsyncResult asyncResult) { return endOperation<DescribeAlarmsForMetricResponse>(asyncResult); } IAsyncResult invokeDescribeAlarmsForMetric(DescribeAlarmsForMetricRequest describeAlarmsForMetricRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new DescribeAlarmsForMetricRequestMarshaller().Marshall(describeAlarmsForMetricRequest); var unmarshaller = DescribeAlarmsForMetricResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region DescribeAlarmHistory /// <summary> /// <para> Retrieves history for the specified alarm. Filter alarms by date range or item type. If an alarm name is not specified, Amazon /// CloudWatch returns histories for all of the owner's alarms. </para> <para><b>NOTE:</b> Amazon CloudWatch retains the history of an alarm for /// two weeks, whether or not you delete the alarm. </para> /// </summary> /// /// <param name="describeAlarmHistoryRequest">Container for the necessary parameters to execute the DescribeAlarmHistory service method on /// AmazonCloudWatch.</param> /// /// <returns>The response from the DescribeAlarmHistory service method, as returned by AmazonCloudWatch.</returns> /// /// <exception cref="InvalidNextTokenException"/> public DescribeAlarmHistoryResponse DescribeAlarmHistory(DescribeAlarmHistoryRequest describeAlarmHistoryRequest) { IAsyncResult asyncResult = invokeDescribeAlarmHistory(describeAlarmHistoryRequest, null, null, true); return EndDescribeAlarmHistory(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the DescribeAlarmHistory operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.DescribeAlarmHistory"/> /// </summary> /// /// <param name="describeAlarmHistoryRequest">Container for the necessary parameters to execute the DescribeAlarmHistory operation on /// AmazonCloudWatch.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndDescribeAlarmHistory operation.</returns> public IAsyncResult BeginDescribeAlarmHistory(DescribeAlarmHistoryRequest describeAlarmHistoryRequest, AsyncCallback callback, object state) { return invokeDescribeAlarmHistory(describeAlarmHistoryRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the DescribeAlarmHistory operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.DescribeAlarmHistory"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeAlarmHistory.</param> /// /// <returns>Returns a DescribeAlarmHistoryResult from AmazonCloudWatch.</returns> public DescribeAlarmHistoryResponse EndDescribeAlarmHistory(IAsyncResult asyncResult) { return endOperation<DescribeAlarmHistoryResponse>(asyncResult); } IAsyncResult invokeDescribeAlarmHistory(DescribeAlarmHistoryRequest describeAlarmHistoryRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new DescribeAlarmHistoryRequestMarshaller().Marshall(describeAlarmHistoryRequest); var unmarshaller = DescribeAlarmHistoryResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } /// <summary> /// <para> Retrieves history for the specified alarm. Filter alarms by date range or item type. If an alarm name is not specified, Amazon /// CloudWatch returns histories for all of the owner's alarms. </para> <para><b>NOTE:</b> Amazon CloudWatch retains the history of an alarm for /// two weeks, whether or not you delete the alarm. </para> /// </summary> /// /// <returns>The response from the DescribeAlarmHistory service method, as returned by AmazonCloudWatch.</returns> /// /// <exception cref="InvalidNextTokenException"/> public DescribeAlarmHistoryResponse DescribeAlarmHistory() { return DescribeAlarmHistory(new DescribeAlarmHistoryRequest()); } #endregion #region EnableAlarmActions /// <summary> /// <para> Enables actions for the specified alarms. </para> /// </summary> /// /// <param name="enableAlarmActionsRequest">Container for the necessary parameters to execute the EnableAlarmActions service method on /// AmazonCloudWatch.</param> /// public EnableAlarmActionsResponse EnableAlarmActions(EnableAlarmActionsRequest enableAlarmActionsRequest) { IAsyncResult asyncResult = invokeEnableAlarmActions(enableAlarmActionsRequest, null, null, true); return EndEnableAlarmActions(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the EnableAlarmActions operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.EnableAlarmActions"/> /// </summary> /// /// <param name="enableAlarmActionsRequest">Container for the necessary parameters to execute the EnableAlarmActions operation on /// AmazonCloudWatch.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> public IAsyncResult BeginEnableAlarmActions(EnableAlarmActionsRequest enableAlarmActionsRequest, AsyncCallback callback, object state) { return invokeEnableAlarmActions(enableAlarmActionsRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the EnableAlarmActions operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.EnableAlarmActions"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginEnableAlarmActions.</param> public EnableAlarmActionsResponse EndEnableAlarmActions(IAsyncResult asyncResult) { return endOperation<EnableAlarmActionsResponse>(asyncResult); } IAsyncResult invokeEnableAlarmActions(EnableAlarmActionsRequest enableAlarmActionsRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new EnableAlarmActionsRequestMarshaller().Marshall(enableAlarmActionsRequest); var unmarshaller = EnableAlarmActionsResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region DeleteAlarms /// <summary> /// <para> Deletes all specified alarms. In the event of an error, no alarms are deleted. </para> /// </summary> /// /// <param name="deleteAlarmsRequest">Container for the necessary parameters to execute the DeleteAlarms service method on /// AmazonCloudWatch.</param> /// /// <exception cref="ResourceNotFoundException"/> public DeleteAlarmsResponse DeleteAlarms(DeleteAlarmsRequest deleteAlarmsRequest) { IAsyncResult asyncResult = invokeDeleteAlarms(deleteAlarmsRequest, null, null, true); return EndDeleteAlarms(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the DeleteAlarms operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.DeleteAlarms"/> /// </summary> /// /// <param name="deleteAlarmsRequest">Container for the necessary parameters to execute the DeleteAlarms operation on AmazonCloudWatch.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> public IAsyncResult BeginDeleteAlarms(DeleteAlarmsRequest deleteAlarmsRequest, AsyncCallback callback, object state) { return invokeDeleteAlarms(deleteAlarmsRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the DeleteAlarms operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.DeleteAlarms"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteAlarms.</param> public DeleteAlarmsResponse EndDeleteAlarms(IAsyncResult asyncResult) { return endOperation<DeleteAlarmsResponse>(asyncResult); } IAsyncResult invokeDeleteAlarms(DeleteAlarmsRequest deleteAlarmsRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new DeleteAlarmsRequestMarshaller().Marshall(deleteAlarmsRequest); var unmarshaller = DeleteAlarmsResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region SetAlarmState /// <summary> /// <para> Temporarily sets the state of an alarm. When the updated <c>StateValue</c> differs from the previous value, the action configured for /// the appropriate state is invoked. This is not a permanent change. The next periodic alarm check (in about a minute) will set the alarm to /// its actual state. </para> /// </summary> /// /// <param name="setAlarmStateRequest">Container for the necessary parameters to execute the SetAlarmState service method on /// AmazonCloudWatch.</param> /// /// <exception cref="ResourceNotFoundException"/> /// <exception cref="InvalidFormatException"/> public SetAlarmStateResponse SetAlarmState(SetAlarmStateRequest setAlarmStateRequest) { IAsyncResult asyncResult = invokeSetAlarmState(setAlarmStateRequest, null, null, true); return EndSetAlarmState(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the SetAlarmState operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.SetAlarmState"/> /// </summary> /// /// <param name="setAlarmStateRequest">Container for the necessary parameters to execute the SetAlarmState operation on /// AmazonCloudWatch.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> public IAsyncResult BeginSetAlarmState(SetAlarmStateRequest setAlarmStateRequest, AsyncCallback callback, object state) { return invokeSetAlarmState(setAlarmStateRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the SetAlarmState operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.SetAlarmState"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginSetAlarmState.</param> public SetAlarmStateResponse EndSetAlarmState(IAsyncResult asyncResult) { return endOperation<SetAlarmStateResponse>(asyncResult); } IAsyncResult invokeSetAlarmState(SetAlarmStateRequest setAlarmStateRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new SetAlarmStateRequestMarshaller().Marshall(setAlarmStateRequest); var unmarshaller = SetAlarmStateResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion } }
using System.Collections.Generic; #if ASYNC using System.Threading.Tasks; #endif using ZendeskApi_v2.Extensions; using ZendeskApi_v2.Models.Topics; namespace ZendeskApi_v2.Requests { public interface ITopics : ICore { #if SYNC GroupTopicResponse GetTopics(); IndividualTopicResponse GetTopicById(long topicId); GroupTopicResponse GetMultipleTopicsById(IEnumerable<long> topicIds); GroupTopicResponse GetTopicsByForum(long forumId); GroupTopicResponse GetTopicsByUser(long userId); IndividualTopicResponse CreateTopic(Topic topic); IndividualTopicResponse UpdateTopic(Topic topic); bool DeleteTopic(long topicId); GroupTopicCommentResponse GetTopicCommentsByTopicId(long topicId); GroupTopicCommentResponse GetTopicCommentsByUserId(long userId); IndividualTopicCommentResponse GetSpecificTopicCommentByTopic(long topicId, long commentId); IndividualTopicCommentResponse GetSpecificTopicCommentByUser(long userId, long commentId); IndividualTopicCommentResponse CreateTopicComment(long topicId, TopicComment topicComment); IndividualTopicCommentResponse UpdateTopicComment(TopicComment topicComment); bool DeleteTopicComment(long topicId, long commentId); GroupTopicSubscriptionResponse GetTopicSubscriptionsByTopic(long topicId); GroupTopicSubscriptionResponse GetAllTopicSubscriptions(); IndividualTopicSubscriptionResponse GetTopicSubscriptionById(long topicSubscriptionId); IndividualTopicSubscriptionResponse CreateTopicSubscription(long userId, long topicId); bool DeleteTopicSubscription(long topicSubscriptionId); GroupTopicVoteResponse GetTopicVotes(long topicId); GroupTopicVoteResponse GetTopicVotesByUser(long userId); /// <summary> /// Checks to see if the current user has cast a vote in this topic. Returns null if not /// </summary> /// <param name="topicId"></param> /// <returns></returns> IndividualTopicVoteResponse CheckForVote(long topicId); IndividualTopicVoteResponse CreateVote(long topicId); bool DeleteVote(long topicId); #endif #if ASYNC Task<GroupTopicResponse> GetTopicsAsync(); Task<IndividualTopicResponse> GetTopicByIdAsync(long topicId); Task<GroupTopicResponse> GetMultipleTopicsByIdAsync(IEnumerable<long> topicIds); Task<GroupTopicResponse> GetTopicsByForumAsync(long forumId); Task<GroupTopicResponse> GetTopicsByUserAsync(long userId); Task<IndividualTopicResponse> CreateTopicAsync(Topic topic); Task<IndividualTopicResponse> UpdateTopicAsync(Topic topic); Task<bool> DeleteTopicAsync(long topicId); Task<GroupTopicCommentResponse> GetTopicCommentsByTopicIdAsync(long topicId); Task<GroupTopicCommentResponse> GetTopicCommentsByUserIdAsync(long userId); Task<IndividualTopicCommentResponse> GetSpecificTopicCommentByTopicAsync(long topicId, long commentId); Task<IndividualTopicCommentResponse> GetSpecificTopicCommentByUserAsync(long userId, long commentId); Task<IndividualTopicCommentResponse> CreateTopicCommentAsync(long topicId, TopicComment topicComment); Task<IndividualTopicCommentResponse> UpdateTopicCommentAsync(TopicComment topicComment); Task<bool> DeleteTopicCommentAsync(long topicId, long commentId); Task<GroupTopicSubscriptionResponse> GetTopicSubscriptionsByTopicAsync(long topicId); Task<GroupTopicSubscriptionResponse> GetAllTopicSubscriptionsAsync(); Task<IndividualTopicSubscriptionResponse> GetTopicSubscriptionByIdAsync(long topicSubscriptionId); Task<IndividualTopicSubscriptionResponse> CreateTopicSubscriptionAsync(long userId, long topicId); Task<bool> DeleteTopicSubscriptionAsync(long topicSubscriptionId); Task<GroupTopicVoteResponse> GetTopicVotesAsync(long topicId); Task<GroupTopicVoteResponse> GetTopicVotesByUserAsync(long userId); /// <summary> /// Checks to see if the current user has cast a vote in this topic. Returns null if not /// </summary> /// <param name="topicId"></param> /// <returns></returns> Task<IndividualTopicVoteResponse> CheckForVoteAsync(long topicId); Task<IndividualTopicVoteResponse> CreateVoteAsync(long topicId); Task<bool> DeleteVoteAsync(long topicId); #endif } public class Topics : Core, ITopics { public Topics(string yourZendeskUrl, string user, string password, string apiToken, string p_OAuthToken) : base(yourZendeskUrl, user, password, apiToken, p_OAuthToken) { } #if SYNC public GroupTopicResponse GetTopics() { return GenericGet<GroupTopicResponse>("topics.json"); } public IndividualTopicResponse GetTopicById(long topicId) { return GenericGet<IndividualTopicResponse>($"topics/{topicId}.json"); } public GroupTopicResponse GetMultipleTopicsById(IEnumerable<long> topicIds) { return GenericPost<GroupTopicResponse>($"topics/show_many?ids={topicIds.ToCsv()}.json"); } public GroupTopicResponse GetTopicsByForum(long forumId) { return GenericGet<GroupTopicResponse>($"forums/{forumId}/topics.json"); } public GroupTopicResponse GetTopicsByUser(long userId) { return GenericGet<GroupTopicResponse>($"users/{userId}/topics.json"); } public IndividualTopicResponse CreateTopic(Topic topic) { var body = new {topic}; return GenericPost<IndividualTopicResponse>(string.Format("topics.json"), body); } public IndividualTopicResponse UpdateTopic(Topic topic) { var body = new { topic }; return GenericPut<IndividualTopicResponse>($"topics/{topic.Id}.json", body); } public bool DeleteTopic(long topicId) { return GenericDelete($"topics/{topicId}.json"); } public GroupTopicCommentResponse GetTopicCommentsByTopicId(long topicId) { return GenericGet<GroupTopicCommentResponse>($"topics/{topicId}/comments.json"); } public GroupTopicCommentResponse GetTopicCommentsByUserId(long userId) { return GenericGet<GroupTopicCommentResponse>($"users/{userId}/topic_comments.json"); } public IndividualTopicCommentResponse GetSpecificTopicCommentByTopic(long topicId, long commentId) { return GenericGet<IndividualTopicCommentResponse>($"topics/{topicId}/comments/{commentId}.json"); } public IndividualTopicCommentResponse GetSpecificTopicCommentByUser(long userId, long commentId) { return GenericGet<IndividualTopicCommentResponse>($"users/{userId}/topic_comments/{commentId}.json"); } public IndividualTopicCommentResponse CreateTopicComment(long topicId, TopicComment topicComment) { var body = new { topic_comment = topicComment }; return GenericPost<IndividualTopicCommentResponse>($"topics/{topicId}/comments.json", body); } public IndividualTopicCommentResponse UpdateTopicComment(TopicComment topicComment) { var body = new { topic_comment = topicComment}; return GenericPut<IndividualTopicCommentResponse>($"topics/{topicComment.TopicId}/comments/{topicComment.Id}.json", body); } public bool DeleteTopicComment(long topicId, long commentId) { return GenericDelete($"topics/{topicId}/comments/{commentId}.json"); } public GroupTopicSubscriptionResponse GetTopicSubscriptionsByTopic(long topicId) { return GenericGet<GroupTopicSubscriptionResponse>($"topics/{topicId}/subscriptions.json"); } public GroupTopicSubscriptionResponse GetAllTopicSubscriptions() { return GenericGet<GroupTopicSubscriptionResponse>(string.Format("topic_subscriptions.json")); } public IndividualTopicSubscriptionResponse GetTopicSubscriptionById(long topicSubscriptionId) { return GenericGet<IndividualTopicSubscriptionResponse>($"topic_subscriptions/{topicSubscriptionId}.json"); } public IndividualTopicSubscriptionResponse CreateTopicSubscription(long userId, long topicId) { var body = new { user_id = userId, topic_id = topicId }; return GenericPost<IndividualTopicSubscriptionResponse>(string.Format("topic_subscriptions.json"), body); } public bool DeleteTopicSubscription(long topicSubscriptionId) { return GenericDelete($"topic_subscriptions/{topicSubscriptionId}.json"); } public GroupTopicVoteResponse GetTopicVotes(long topicId) { return GenericGet<GroupTopicVoteResponse>($"topics/{topicId}/votes.json"); } public GroupTopicVoteResponse GetTopicVotesByUser(long userId) { return GenericGet<GroupTopicVoteResponse>($"users/{userId}/topic_votes.json"); } /// <summary> /// Checks to see if the current user has cast a vote in this topic. Returns null if not /// </summary> /// <param name="topicId"></param> /// <returns></returns> public IndividualTopicVoteResponse CheckForVote(long topicId) { return GenericGet<IndividualTopicVoteResponse>($"topics/{topicId}/vote.json"); } public IndividualTopicVoteResponse CreateVote(long topicId) { return GenericPost<IndividualTopicVoteResponse>($"topics/{topicId}/vote.json"); } public bool DeleteVote(long topicId) { return GenericDelete($"topics/{topicId}/vote.json"); } #endif #if ASYNC public async Task<GroupTopicResponse> GetTopicsAsync() { return await GenericGetAsync<GroupTopicResponse>("topics.json"); } public async Task<IndividualTopicResponse> GetTopicByIdAsync(long topicId) { return await GenericGetAsync<IndividualTopicResponse>($"topics/{topicId}.json"); } public async Task<GroupTopicResponse> GetMultipleTopicsByIdAsync(IEnumerable<long> topicIds) { return await GenericPostAsync<GroupTopicResponse>($"topics/show_many?ids={topicIds.ToCsv()}.json"); } public async Task<GroupTopicResponse> GetTopicsByForumAsync(long forumId) { return await GenericGetAsync<GroupTopicResponse>($"forums/{forumId}/topics.json"); } public async Task<GroupTopicResponse> GetTopicsByUserAsync(long userId) { return await GenericGetAsync<GroupTopicResponse>($"users/{userId}/topics.json"); } public async Task<IndividualTopicResponse> CreateTopicAsync(Topic topic) { var body = new {topic}; return await GenericPostAsync<IndividualTopicResponse>(string.Format("topics.json"), body); } public async Task<IndividualTopicResponse> UpdateTopicAsync(Topic topic) { var body = new { topic }; return await GenericPutAsync<IndividualTopicResponse>($"topics/{topic.Id}.json", body); } public async Task<bool> DeleteTopicAsync(long topicId) { return await GenericDeleteAsync($"topics/{topicId}.json"); } public async Task<GroupTopicCommentResponse> GetTopicCommentsByTopicIdAsync(long topicId) { return await GenericGetAsync<GroupTopicCommentResponse>($"topics/{topicId}/comments.json"); } public async Task<GroupTopicCommentResponse> GetTopicCommentsByUserIdAsync(long userId) { return await GenericGetAsync<GroupTopicCommentResponse>($"users/{userId}/topic_comments.json"); } public async Task<IndividualTopicCommentResponse> GetSpecificTopicCommentByTopicAsync(long topicId, long commentId) { return await GenericGetAsync<IndividualTopicCommentResponse>($"topics/{topicId}/comments/{commentId}.json"); } public async Task<IndividualTopicCommentResponse> GetSpecificTopicCommentByUserAsync(long userId, long commentId) { return await GenericGetAsync<IndividualTopicCommentResponse>($"users/{userId}/topic_comments/{commentId}.json"); } public async Task<IndividualTopicCommentResponse> CreateTopicCommentAsync(long topicId, TopicComment topicComment) { var body = new { topic_comment = topicComment }; return await GenericPostAsync<IndividualTopicCommentResponse>($"topics/{topicId}/comments.json", body); } public async Task<IndividualTopicCommentResponse> UpdateTopicCommentAsync(TopicComment topicComment) { var body = new { topic_comment = topicComment}; return await GenericPutAsync<IndividualTopicCommentResponse>($"topics/{topicComment.TopicId}/comments/{topicComment.Id}.json", body); } public async Task<bool> DeleteTopicCommentAsync(long topicId, long commentId) { return await GenericDeleteAsync($"topics/{topicId}/comments/{commentId}.json"); } public async Task<GroupTopicSubscriptionResponse> GetTopicSubscriptionsByTopicAsync(long topicId) { return await GenericGetAsync<GroupTopicSubscriptionResponse>($"topics/{topicId}/subscriptions.json"); } public async Task<GroupTopicSubscriptionResponse> GetAllTopicSubscriptionsAsync() { return await GenericGetAsync<GroupTopicSubscriptionResponse>(string.Format("topic_subscriptions.json")); } public async Task<IndividualTopicSubscriptionResponse> GetTopicSubscriptionByIdAsync(long topicSubscriptionId) { return await GenericGetAsync<IndividualTopicSubscriptionResponse>($"topic_subscriptions/{topicSubscriptionId}.json"); } public async Task<IndividualTopicSubscriptionResponse> CreateTopicSubscriptionAsync(long userId, long topicId) { var body = new { user_id = userId, topic_id = topicId }; return await GenericPostAsync<IndividualTopicSubscriptionResponse>(string.Format("topic_subscriptions.json"), body); } public async Task<bool> DeleteTopicSubscriptionAsync(long topicSubscriptionId) { return await GenericDeleteAsync($"topic_subscriptions/{topicSubscriptionId}.json"); } public async Task<GroupTopicVoteResponse> GetTopicVotesAsync(long topicId) { return await GenericGetAsync<GroupTopicVoteResponse>($"topics/{topicId}/votes.json"); } public async Task<GroupTopicVoteResponse> GetTopicVotesByUserAsync(long userId) { return await GenericGetAsync<GroupTopicVoteResponse>($"users/{userId}/topic_votes.json"); } /// <summary> /// Checks to see if the current user has cast a vote in this topic. Returns null if not /// </summary> /// <param name="topicId"></param> /// <returns></returns> public async Task<IndividualTopicVoteResponse> CheckForVoteAsync(long topicId) { return await GenericGetAsync<IndividualTopicVoteResponse>($"topics/{topicId}/vote.json"); } public async Task<IndividualTopicVoteResponse> CreateVoteAsync(long topicId) { return await GenericPostAsync<IndividualTopicVoteResponse>($"topics/{topicId}/vote.json"); } public async Task<bool> DeleteVoteAsync(long topicId) { return await GenericDeleteAsync($"topics/{topicId}/vote.json"); } #endif } }
using System; using Duality.Resources; using Duality.Editor; using Duality.Properties; using Duality.Cloning; using Duality.Drawing; namespace Duality.Components.Renderers { /// <summary> /// Renders a sprite to represent the <see cref="GameObject"/>. /// </summary> [ManuallyCloned] [EditorHintCategory(CoreResNames.CategoryGraphics)] [EditorHintImage(CoreResNames.ImageSpriteRenderer)] public class SpriteRenderer : Renderer { /// <summary> /// Specifies how the sprites uv-Coordinates are calculated. /// </summary> [Flags] public enum UVMode { /// <summary> /// The uv-Coordinates are constant, stretching the supplied texture to fit the SpriteRenderers dimensions. /// </summary> Stretch = 0x0, /// <summary> /// The u-Coordinate is calculated based on the available horizontal space, allowing the supplied texture to be /// tiled across the SpriteRenderers width. /// </summary> WrapHorizontal = 0x1, /// <summary> /// The v-Coordinate is calculated based on the available vertical space, allowing the supplied texture to be /// tiled across the SpriteRenderers height. /// </summary> WrapVertical = 0x2, /// <summary> /// The uv-Coordinates are calculated based on the available space, allowing the supplied texture to be /// tiled across the SpriteRenderers size. /// </summary> WrapBoth = WrapHorizontal | WrapVertical } /// <summary> /// Specifies whether the sprite should be flipped on a given axis. /// </summary> [Flags] public enum FlipMode { /// <summary> /// The sprite will not be flipped at all. /// </summary> None = 0x0, /// <summary> /// The sprite will be flipped on its horizontal axis. /// </summary> Horizontal = 0x1, /// <summary> /// The sprite will be flipped on its vertical axis. /// </summary> Vertical = 0x2 } protected Rect rect = Rect.Align(Alignment.Center, 0, 0, 256, 256); protected ContentRef<Material> sharedMat = Material.DualityIcon; protected BatchInfo customMat = null; protected ColorRgba colorTint = ColorRgba.White; protected UVMode rectMode = UVMode.Stretch; protected bool pixelGrid = false; protected int offset = 0; protected FlipMode flipMode = FlipMode.None; [DontSerialize] protected VertexC1P3T2[] vertices = null; [EditorHintFlags(MemberFlags.Invisible)] public override float BoundRadius { get { return this.rect.Transformed(this.gameobj.Transform.Scale, this.gameobj.Transform.Scale).BoundingRadius; } } /// <summary> /// [GET / SET] The rectangular area the sprite occupies. Relative to the <see cref="GameObject"/>. /// </summary> [EditorHintDecimalPlaces(1)] public Rect Rect { get { return this.rect; } set { this.rect = value; } } /// <summary> /// [GET / SET] The <see cref="Duality.Resources.Material"/> that is used for rendering the sprite. /// </summary> public ContentRef<Material> SharedMaterial { get { return this.sharedMat; } set { this.sharedMat = value; } } /// <summary> /// [GET / SET] A custom, local <see cref="Duality.Drawing.BatchInfo"/> overriding the <see cref="SharedMaterial"/>, /// allowing this sprite to look unique without having to create its own <see cref="Duality.Resources.Material"/> Resource. /// However, this feature should be used with caution: Performance is better using <see cref="SharedMaterial">shared Materials</see>. /// </summary> public BatchInfo CustomMaterial { get { return this.customMat; } set { this.customMat = value; } } /// <summary> /// [GET / SET] A color by which the sprite is tinted. /// </summary> public ColorRgba ColorTint { get { return this.colorTint; } set { this.colorTint = value; } } /// <summary> /// [GET / SET] Specifies how the sprites uv-Coordinates are calculated. /// </summary> public UVMode RectMode { get { return this.rectMode; } set { this.rectMode = value; } } /// <summary> /// [GET / SET] Specified whether or not the rendered sprite will be aligned to actual screen pixels. /// </summary> public bool AlignToPixelGrid { get { return this.pixelGrid; } set { this.pixelGrid = value; } } /// <summary> /// [GET / SET] A virtual Z offset that affects the order in which objects are drawn. If you want to assure an object is drawn after another one, /// just assign a higher Offset value to the background object. /// </summary> public int Offset { get { return this.offset; } set { this.offset = value; } } /// <summary> /// [GET] The internal Z-Offset added to the renderers vertices based on its <see cref="Offset"/> value. /// </summary> [EditorHintFlags(MemberFlags.Invisible)] public float VertexZOffset { get { return this.offset * 0.01f; } } /// <summary> /// [GET / SET] Specifies whether the sprite should be flipped on a given axis when redered. /// </summary> public FlipMode Flip { get { return this.flipMode; } set { this.flipMode = value; } } public SpriteRenderer() {} public SpriteRenderer(Rect rect, ContentRef<Material> mainMat) { this.rect = rect; this.sharedMat = mainMat; } protected Texture RetrieveMainTex() { if (this.customMat != null) return this.customMat.MainTexture.Res; else if (this.sharedMat.IsAvailable) return this.sharedMat.Res.MainTexture.Res; else return null; } protected ColorRgba RetrieveMainColor() { if (this.customMat != null) return this.customMat.MainColor * this.colorTint; else if (this.sharedMat.IsAvailable) return this.sharedMat.Res.MainColor * this.colorTint; else return this.colorTint; } protected DrawTechnique RetrieveDrawTechnique() { if (this.customMat != null) return this.customMat.Technique.Res; else if (this.sharedMat.IsAvailable) return this.sharedMat.Res.Technique.Res; else return null; } protected void PrepareVertices(ref VertexC1P3T2[] vertices, IDrawDevice device, ColorRgba mainClr, Rect uvRect) { Vector3 posTemp = this.gameobj.Transform.Pos; float scaleTemp = 1.0f; device.PreprocessCoords(ref posTemp, ref scaleTemp); Vector2 xDot, yDot; MathF.GetTransformDotVec(this.GameObj.Transform.Angle, scaleTemp, out xDot, out yDot); Rect rectTemp = this.rect.Transformed(this.gameobj.Transform.Scale, this.gameobj.Transform.Scale); Vector2 edge1 = rectTemp.TopLeft; Vector2 edge2 = rectTemp.BottomLeft; Vector2 edge3 = rectTemp.BottomRight; Vector2 edge4 = rectTemp.TopRight; if ((this.flipMode & FlipMode.Horizontal) != FlipMode.None) { edge1.X = -edge1.X; edge2.X = -edge2.X; edge3.X = -edge3.X; edge4.X = -edge4.X; } if ((this.flipMode & FlipMode.Vertical) != FlipMode.None) { edge1.Y = -edge1.Y; edge2.Y = -edge2.Y; edge3.Y = -edge3.Y; edge4.Y = -edge4.Y; } MathF.TransformDotVec(ref edge1, ref xDot, ref yDot); MathF.TransformDotVec(ref edge2, ref xDot, ref yDot); MathF.TransformDotVec(ref edge3, ref xDot, ref yDot); MathF.TransformDotVec(ref edge4, ref xDot, ref yDot); float left = uvRect.X; float right = uvRect.RightX; float top = uvRect.Y; float bottom = uvRect.BottomY; if (vertices == null || vertices.Length != 4) vertices = new VertexC1P3T2[4]; vertices[0].Pos.X = posTemp.X + edge1.X; vertices[0].Pos.Y = posTemp.Y + edge1.Y; vertices[0].Pos.Z = posTemp.Z + this.VertexZOffset; vertices[0].TexCoord.X = left; vertices[0].TexCoord.Y = top; vertices[0].Color = mainClr; vertices[1].Pos.X = posTemp.X + edge2.X; vertices[1].Pos.Y = posTemp.Y + edge2.Y; vertices[1].Pos.Z = posTemp.Z + this.VertexZOffset; vertices[1].TexCoord.X = left; vertices[1].TexCoord.Y = bottom; vertices[1].Color = mainClr; vertices[2].Pos.X = posTemp.X + edge3.X; vertices[2].Pos.Y = posTemp.Y + edge3.Y; vertices[2].Pos.Z = posTemp.Z + this.VertexZOffset; vertices[2].TexCoord.X = right; vertices[2].TexCoord.Y = bottom; vertices[2].Color = mainClr; vertices[3].Pos.X = posTemp.X + edge4.X; vertices[3].Pos.Y = posTemp.Y + edge4.Y; vertices[3].Pos.Z = posTemp.Z + this.VertexZOffset; vertices[3].TexCoord.X = right; vertices[3].TexCoord.Y = top; vertices[3].Color = mainClr; if (this.pixelGrid) { vertices[0].Pos.X = MathF.Round(vertices[0].Pos.X); vertices[1].Pos.X = MathF.Round(vertices[1].Pos.X); vertices[2].Pos.X = MathF.Round(vertices[2].Pos.X); vertices[3].Pos.X = MathF.Round(vertices[3].Pos.X); if (MathF.RoundToInt(device.TargetSize.X) != (MathF.RoundToInt(device.TargetSize.X) / 2) * 2) { vertices[0].Pos.X += 0.5f; vertices[1].Pos.X += 0.5f; vertices[2].Pos.X += 0.5f; vertices[3].Pos.X += 0.5f; } vertices[0].Pos.Y = MathF.Round(vertices[0].Pos.Y); vertices[1].Pos.Y = MathF.Round(vertices[1].Pos.Y); vertices[2].Pos.Y = MathF.Round(vertices[2].Pos.Y); vertices[3].Pos.Y = MathF.Round(vertices[3].Pos.Y); if (MathF.RoundToInt(device.TargetSize.Y) != (MathF.RoundToInt(device.TargetSize.Y) / 2) * 2) { vertices[0].Pos.Y += 0.5f; vertices[1].Pos.Y += 0.5f; vertices[2].Pos.Y += 0.5f; vertices[3].Pos.Y += 0.5f; } } } public override void Draw(IDrawDevice device) { Texture mainTex = this.RetrieveMainTex(); ColorRgba mainClr = this.RetrieveMainColor(); Rect uvRect; if (mainTex != null) { if (this.rectMode == UVMode.WrapBoth) uvRect = new Rect(mainTex.UVRatio.X * this.rect.W / mainTex.PixelWidth, mainTex.UVRatio.Y * this.rect.H / mainTex.PixelHeight); else if (this.rectMode == UVMode.WrapHorizontal) uvRect = new Rect(mainTex.UVRatio.X * this.rect.W / mainTex.PixelWidth, mainTex.UVRatio.Y); else if (this.rectMode == UVMode.WrapVertical) uvRect = new Rect(mainTex.UVRatio.X, mainTex.UVRatio.Y * this.rect.H / mainTex.PixelHeight); else uvRect = new Rect(mainTex.UVRatio.X, mainTex.UVRatio.Y); } else uvRect = new Rect(1.0f, 1.0f); this.PrepareVertices(ref this.vertices, device, mainClr, uvRect); if (this.customMat != null) device.AddVertices(this.customMat, VertexMode.Quads, this.vertices); else device.AddVertices(this.sharedMat, VertexMode.Quads, this.vertices); } protected override void OnSetupCloneTargets(object targetObj, ICloneTargetSetup setup) { base.OnSetupCloneTargets(targetObj, setup); SpriteRenderer target = targetObj as SpriteRenderer; setup.HandleObject(this.customMat, target.customMat); } protected override void OnCopyDataTo(object targetObj, ICloneOperation operation) { base.OnCopyDataTo(targetObj, operation); SpriteRenderer target = targetObj as SpriteRenderer; target.rect = this.rect; target.colorTint = this.colorTint; target.rectMode = this.rectMode; target.offset = this.offset; target.pixelGrid = this.pixelGrid; target.flipMode = this.flipMode; operation.HandleValue(ref this.sharedMat, ref target.sharedMat); operation.HandleObject(this.customMat, ref target.customMat); } } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System.Globalization { public static class __TaiwanCalendar { public static IObservable<System.DateTime> AddMonths( this IObservable<System.Globalization.TaiwanCalendar> TaiwanCalendarValue, IObservable<System.DateTime> time, IObservable<System.Int32> months) { return Observable.Zip(TaiwanCalendarValue, time, months, (TaiwanCalendarValueLambda, timeLambda, monthsLambda) => TaiwanCalendarValueLambda.AddMonths(timeLambda, monthsLambda)); } public static IObservable<System.DateTime> AddYears( this IObservable<System.Globalization.TaiwanCalendar> TaiwanCalendarValue, IObservable<System.DateTime> time, IObservable<System.Int32> years) { return Observable.Zip(TaiwanCalendarValue, time, years, (TaiwanCalendarValueLambda, timeLambda, yearsLambda) => TaiwanCalendarValueLambda.AddYears(timeLambda, yearsLambda)); } public static IObservable<System.Int32> GetDaysInMonth( this IObservable<System.Globalization.TaiwanCalendar> TaiwanCalendarValue, IObservable<System.Int32> year, IObservable<System.Int32> month, IObservable<System.Int32> era) { return Observable.Zip(TaiwanCalendarValue, year, month, era, (TaiwanCalendarValueLambda, yearLambda, monthLambda, eraLambda) => TaiwanCalendarValueLambda.GetDaysInMonth(yearLambda, monthLambda, eraLambda)); } public static IObservable<System.Int32> GetDaysInYear( this IObservable<System.Globalization.TaiwanCalendar> TaiwanCalendarValue, IObservable<System.Int32> year, IObservable<System.Int32> era) { return Observable.Zip(TaiwanCalendarValue, year, era, (TaiwanCalendarValueLambda, yearLambda, eraLambda) => TaiwanCalendarValueLambda.GetDaysInYear(yearLambda, eraLambda)); } public static IObservable<System.Int32> GetDayOfMonth( this IObservable<System.Globalization.TaiwanCalendar> TaiwanCalendarValue, IObservable<System.DateTime> time) { return Observable.Zip(TaiwanCalendarValue, time, (TaiwanCalendarValueLambda, timeLambda) => TaiwanCalendarValueLambda.GetDayOfMonth(timeLambda)); } public static IObservable<System.DayOfWeek> GetDayOfWeek( this IObservable<System.Globalization.TaiwanCalendar> TaiwanCalendarValue, IObservable<System.DateTime> time) { return Observable.Zip(TaiwanCalendarValue, time, (TaiwanCalendarValueLambda, timeLambda) => TaiwanCalendarValueLambda.GetDayOfWeek(timeLambda)); } public static IObservable<System.Int32> GetDayOfYear( this IObservable<System.Globalization.TaiwanCalendar> TaiwanCalendarValue, IObservable<System.DateTime> time) { return Observable.Zip(TaiwanCalendarValue, time, (TaiwanCalendarValueLambda, timeLambda) => TaiwanCalendarValueLambda.GetDayOfYear(timeLambda)); } public static IObservable<System.Int32> GetMonthsInYear( this IObservable<System.Globalization.TaiwanCalendar> TaiwanCalendarValue, IObservable<System.Int32> year, IObservable<System.Int32> era) { return Observable.Zip(TaiwanCalendarValue, year, era, (TaiwanCalendarValueLambda, yearLambda, eraLambda) => TaiwanCalendarValueLambda.GetMonthsInYear(yearLambda, eraLambda)); } public static IObservable<System.Int32> GetWeekOfYear( this IObservable<System.Globalization.TaiwanCalendar> TaiwanCalendarValue, IObservable<System.DateTime> time, IObservable<System.Globalization.CalendarWeekRule> rule, IObservable<System.DayOfWeek> firstDayOfWeek) { return Observable.Zip(TaiwanCalendarValue, time, rule, firstDayOfWeek, (TaiwanCalendarValueLambda, timeLambda, ruleLambda, firstDayOfWeekLambda) => TaiwanCalendarValueLambda.GetWeekOfYear(timeLambda, ruleLambda, firstDayOfWeekLambda)); } public static IObservable<System.Int32> GetEra( this IObservable<System.Globalization.TaiwanCalendar> TaiwanCalendarValue, IObservable<System.DateTime> time) { return Observable.Zip(TaiwanCalendarValue, time, (TaiwanCalendarValueLambda, timeLambda) => TaiwanCalendarValueLambda.GetEra(timeLambda)); } public static IObservable<System.Int32> GetMonth( this IObservable<System.Globalization.TaiwanCalendar> TaiwanCalendarValue, IObservable<System.DateTime> time) { return Observable.Zip(TaiwanCalendarValue, time, (TaiwanCalendarValueLambda, timeLambda) => TaiwanCalendarValueLambda.GetMonth(timeLambda)); } public static IObservable<System.Int32> GetYear( this IObservable<System.Globalization.TaiwanCalendar> TaiwanCalendarValue, IObservable<System.DateTime> time) { return Observable.Zip(TaiwanCalendarValue, time, (TaiwanCalendarValueLambda, timeLambda) => TaiwanCalendarValueLambda.GetYear(timeLambda)); } public static IObservable<System.Boolean> IsLeapDay( this IObservable<System.Globalization.TaiwanCalendar> TaiwanCalendarValue, IObservable<System.Int32> year, IObservable<System.Int32> month, IObservable<System.Int32> day, IObservable<System.Int32> era) { return Observable.Zip(TaiwanCalendarValue, year, month, day, era, (TaiwanCalendarValueLambda, yearLambda, monthLambda, dayLambda, eraLambda) => TaiwanCalendarValueLambda.IsLeapDay(yearLambda, monthLambda, dayLambda, eraLambda)); } public static IObservable<System.Boolean> IsLeapYear( this IObservable<System.Globalization.TaiwanCalendar> TaiwanCalendarValue, IObservable<System.Int32> year, IObservable<System.Int32> era) { return Observable.Zip(TaiwanCalendarValue, year, era, (TaiwanCalendarValueLambda, yearLambda, eraLambda) => TaiwanCalendarValueLambda.IsLeapYear(yearLambda, eraLambda)); } public static IObservable<System.Int32> GetLeapMonth( this IObservable<System.Globalization.TaiwanCalendar> TaiwanCalendarValue, IObservable<System.Int32> year, IObservable<System.Int32> era) { return Observable.Zip(TaiwanCalendarValue, year, era, (TaiwanCalendarValueLambda, yearLambda, eraLambda) => TaiwanCalendarValueLambda.GetLeapMonth(yearLambda, eraLambda)); } public static IObservable<System.Boolean> IsLeapMonth( this IObservable<System.Globalization.TaiwanCalendar> TaiwanCalendarValue, IObservable<System.Int32> year, IObservable<System.Int32> month, IObservable<System.Int32> era) { return Observable.Zip(TaiwanCalendarValue, year, month, era, (TaiwanCalendarValueLambda, yearLambda, monthLambda, eraLambda) => TaiwanCalendarValueLambda.IsLeapMonth(yearLambda, monthLambda, eraLambda)); } public static IObservable<System.DateTime> ToDateTime( this IObservable<System.Globalization.TaiwanCalendar> TaiwanCalendarValue, IObservable<System.Int32> year, IObservable<System.Int32> month, IObservable<System.Int32> day, IObservable<System.Int32> hour, IObservable<System.Int32> minute, IObservable<System.Int32> second, IObservable<System.Int32> millisecond, IObservable<System.Int32> era) { return Observable.Zip(TaiwanCalendarValue, year, month, day, hour, minute, second, millisecond, era, (TaiwanCalendarValueLambda, yearLambda, monthLambda, dayLambda, hourLambda, minuteLambda, secondLambda, millisecondLambda, eraLambda) => TaiwanCalendarValueLambda.ToDateTime(yearLambda, monthLambda, dayLambda, hourLambda, minuteLambda, secondLambda, millisecondLambda, eraLambda)); } public static IObservable<System.Int32> ToFourDigitYear( this IObservable<System.Globalization.TaiwanCalendar> TaiwanCalendarValue, IObservable<System.Int32> year) { return Observable.Zip(TaiwanCalendarValue, year, (TaiwanCalendarValueLambda, yearLambda) => TaiwanCalendarValueLambda.ToFourDigitYear(yearLambda)); } public static IObservable<System.DateTime> get_MinSupportedDateTime( this IObservable<System.Globalization.TaiwanCalendar> TaiwanCalendarValue) { return Observable.Select(TaiwanCalendarValue, (TaiwanCalendarValueLambda) => TaiwanCalendarValueLambda.MinSupportedDateTime); } public static IObservable<System.DateTime> get_MaxSupportedDateTime( this IObservable<System.Globalization.TaiwanCalendar> TaiwanCalendarValue) { return Observable.Select(TaiwanCalendarValue, (TaiwanCalendarValueLambda) => TaiwanCalendarValueLambda.MaxSupportedDateTime); } public static IObservable<System.Globalization.CalendarAlgorithmType> get_AlgorithmType( this IObservable<System.Globalization.TaiwanCalendar> TaiwanCalendarValue) { return Observable.Select(TaiwanCalendarValue, (TaiwanCalendarValueLambda) => TaiwanCalendarValueLambda.AlgorithmType); } public static IObservable<System.Int32[]> get_Eras( this IObservable<System.Globalization.TaiwanCalendar> TaiwanCalendarValue) { return Observable.Select(TaiwanCalendarValue, (TaiwanCalendarValueLambda) => TaiwanCalendarValueLambda.Eras); } public static IObservable<System.Int32> get_TwoDigitYearMax( this IObservable<System.Globalization.TaiwanCalendar> TaiwanCalendarValue) { return Observable.Select(TaiwanCalendarValue, (TaiwanCalendarValueLambda) => TaiwanCalendarValueLambda.TwoDigitYearMax); } public static IObservable<System.Reactive.Unit> set_TwoDigitYearMax( this IObservable<System.Globalization.TaiwanCalendar> TaiwanCalendarValue, IObservable<System.Int32> value) { return ObservableExt.ZipExecute(TaiwanCalendarValue, value, (TaiwanCalendarValueLambda, valueLambda) => TaiwanCalendarValueLambda.TwoDigitYearMax = valueLambda); } } }
// 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 Microsoft.Xunit.Performance; using System; using System.Linq; using System.Runtime.CompilerServices; using System.Reflection; using System.Collections.Generic; using Xunit; [assembly: OptimizeForBenchmarks] [assembly: MeasureInstructionsRetired] namespace Inlining { public static class ConstantArgsUShort { #if DEBUG public const int Iterations = 1; #else public const int Iterations = 100000; #endif // Ushorts feeding math operations. // // Inlining in Bench0xp should enable constant folding // Inlining in Bench0xn will not enable constant folding static ushort Five = 5; static ushort Ten = 10; static ushort Id(ushort x) { return x; } static ushort F00(ushort x) { return (ushort) (x * x); } static bool Bench00p() { ushort t = 10; ushort f = F00(t); return (f == 100); } static bool Bench00n() { ushort t = Ten; ushort f = F00(t); return (f == 100); } static bool Bench00p1() { ushort t = Id(10); ushort f = F00(t); return (f == 100); } static bool Bench00n1() { ushort t = Id(Ten); ushort f = F00(t); return (f == 100); } static bool Bench00p2() { ushort t = Id(10); ushort f = F00(Id(t)); return (f == 100); } static bool Bench00n2() { ushort t = Id(Ten); ushort f = F00(Id(t)); return (f == 100); } static bool Bench00p3() { ushort t = 10; ushort f = F00(Id(Id(t))); return (f == 100); } static bool Bench00n3() { ushort t = Ten; ushort f = F00(Id(Id(t))); return (f == 100); } static bool Bench00p4() { ushort t = 5; ushort f = F00((ushort)(2 * t)); return (f == 100); } static bool Bench00n4() { ushort t = Five; ushort f = F00((ushort)(2 * t)); return (f == 100); } static ushort F01(ushort x) { return (ushort)(1000 / x); } static bool Bench01p() { ushort t = 10; ushort f = F01(t); return (f == 100); } static bool Bench01n() { ushort t = Ten; ushort f = F01(t); return (f == 100); } static ushort F02(ushort x) { return (ushort) (20 * (x / 2)); } static bool Bench02p() { ushort t = 10; ushort f = F02(t); return (f == 100); } static bool Bench02n() { ushort t = Ten; ushort f = F02(t); return (f == 100); } static ushort F03(ushort x) { return (ushort)(91 + 1009 % x); } static bool Bench03p() { ushort t = 10; ushort f = F03(t); return (f == 100); } static bool Bench03n() { ushort t = Ten; ushort f = F03(t); return (f == 100); } static ushort F04(ushort x) { return (ushort)(50 * (x % 4)); } static bool Bench04p() { ushort t = 10; ushort f = F04(t); return (f == 100); } static bool Bench04n() { ushort t = Ten; ushort f = F04(t); return (f == 100); } static ushort F05(ushort x) { return (ushort)((1 << x) - 924); } static bool Bench05p() { ushort t = 10; ushort f = F05(t); return (f == 100); } static bool Bench05n() { ushort t = Ten; ushort f = F05(t); return (f == 100); } static ushort F051(ushort x) { return (ushort)(102400 >> x); } static bool Bench05p1() { ushort t = 10; ushort f = F051(t); return (f == 100); } static bool Bench05n1() { ushort t = Ten; ushort f = F051(t); return (f == 100); } static ushort F06(ushort x) { return (ushort)(-x + 110); } static bool Bench06p() { ushort t = 10; ushort f = F06(t); return (f == 100); } static bool Bench06n() { ushort t = Ten; ushort f = F06(t); return (f == 100); } static ushort F07(ushort x) { return (ushort)(~x + 111); } static bool Bench07p() { ushort t = 10; ushort f = F07(t); return (f == 100); } static bool Bench07n() { ushort t = Ten; ushort f = F07(t); return (f == 100); } static ushort F071(ushort x) { return (ushort)((x ^ -1) + 111); } static bool Bench07p1() { ushort t = 10; ushort f = F071(t); return (f == 100); } static bool Bench07n1() { ushort t = Ten; ushort f = F071(t); return (f == 100); } static ushort F08(ushort x) { return (ushort)((x & 0x7) + 98); } static bool Bench08p() { ushort t = 10; ushort f = F08(t); return (f == 100); } static bool Bench08n() { ushort t = Ten; ushort f = F08(t); return (f == 100); } static ushort F09(ushort x) { return (ushort)((x | 0x7) + 85); } static bool Bench09p() { ushort t = 10; ushort f = F09(t); return (f == 100); } static bool Bench09n() { ushort t = Ten; ushort f = F09(t); return (f == 100); } // Ushorts feeding comparisons. // // Inlining in Bench1xp should enable branch optimization // Inlining in Bench1xn will not enable branch optimization static ushort F10(ushort x) { return x == 10 ? (ushort) 100 : (ushort) 0; } static bool Bench10p() { ushort t = 10; ushort f = F10(t); return (f == 100); } static bool Bench10n() { ushort t = Ten; ushort f = F10(t); return (f == 100); } static ushort F101(ushort x) { return x != 10 ? (ushort) 0 : (ushort) 100; } static bool Bench10p1() { ushort t = 10; ushort f = F101(t); return (f == 100); } static bool Bench10n1() { ushort t = Ten; ushort f = F101(t); return (f == 100); } static ushort F102(ushort x) { return x >= 10 ? (ushort) 100 : (ushort) 0; } static bool Bench10p2() { ushort t = 10; ushort f = F102(t); return (f == 100); } static bool Bench10n2() { ushort t = Ten; ushort f = F102(t); return (f == 100); } static ushort F103(ushort x) { return x <= 10 ? (ushort) 100 : (ushort) 0; } static bool Bench10p3() { ushort t = 10; ushort f = F103(t); return (f == 100); } static bool Bench10n3() { ushort t = Ten; ushort f = F102(t); return (f == 100); } static ushort F11(ushort x) { if (x == 10) { return 100; } else { return 0; } } static bool Bench11p() { ushort t = 10; ushort f = F11(t); return (f == 100); } static bool Bench11n() { ushort t = Ten; ushort f = F11(t); return (f == 100); } static ushort F111(ushort x) { if (x != 10) { return 0; } else { return 100; } } static bool Bench11p1() { ushort t = 10; ushort f = F111(t); return (f == 100); } static bool Bench11n1() { ushort t = Ten; ushort f = F111(t); return (f == 100); } static ushort F112(ushort x) { if (x > 10) { return 0; } else { return 100; } } static bool Bench11p2() { ushort t = 10; ushort f = F112(t); return (f == 100); } static bool Bench11n2() { ushort t = Ten; ushort f = F112(t); return (f == 100); } static ushort F113(ushort x) { if (x < 10) { return 0; } else { return 100; } } static bool Bench11p3() { ushort t = 10; ushort f = F113(t); return (f == 100); } static bool Bench11n3() { ushort t = Ten; ushort f = F113(t); return (f == 100); } // Ununsed (or effectively unused) parameters // // Simple callee analysis may overstate inline benefit static ushort F20(ushort x) { return 100; } static bool Bench20p() { ushort t = 10; ushort f = F20(t); return (f == 100); } static bool Bench20p1() { ushort t = Ten; ushort f = F20(t); return (f == 100); } static ushort F21(ushort x) { return (ushort)(-x + 100 + x); } static bool Bench21p() { ushort t = 10; ushort f = F21(t); return (f == 100); } static bool Bench21n() { ushort t = Ten; ushort f = F21(t); return (f == 100); } static ushort F211(ushort x) { return (ushort)(x - x + 100); } static bool Bench21p1() { ushort t = 10; ushort f = F211(t); return (f == 100); } static bool Bench21n1() { ushort t = Ten; ushort f = F211(t); return (f == 100); } static ushort F22(ushort x) { if (x > 0) { return 100; } return 100; } static bool Bench22p() { ushort t = 10; ushort f = F22(t); return (f == 100); } static bool Bench22p1() { ushort t = Ten; ushort f = F22(t); return (f == 100); } static ushort F23(ushort x) { if (x > 0) { return (ushort)(90 + x); } return 100; } static bool Bench23p() { ushort t = 10; ushort f = F23(t); return (f == 100); } static bool Bench23n() { ushort t = Ten; ushort f = F23(t); return (f == 100); } // Multiple parameters static ushort F30(ushort x, ushort y) { return (ushort)(y * y); } static bool Bench30p() { ushort t = 10; ushort f = F30(t, t); return (f == 100); } static bool Bench30n() { ushort t = Ten; ushort f = F30(t, t); return (f == 100); } static bool Bench30p1() { ushort s = Ten; ushort t = 10; ushort f = F30(s, t); return (f == 100); } static bool Bench30n1() { ushort s = 10; ushort t = Ten; ushort f = F30(s, t); return (f == 100); } static bool Bench30p2() { ushort s = 10; ushort t = 10; ushort f = F30(s, t); return (f == 100); } static bool Bench30n2() { ushort s = Ten; ushort t = Ten; ushort f = F30(s, t); return (f == 100); } static bool Bench30p3() { ushort s = 10; ushort t = s; ushort f = F30(s, t); return (f == 100); } static bool Bench30n3() { ushort s = Ten; ushort t = s; ushort f = F30(s, t); return (f == 100); } static ushort F31(ushort x, ushort y, ushort z) { return (ushort)(z * z); } static bool Bench31p() { ushort t = 10; ushort f = F31(t, t, t); return (f == 100); } static bool Bench31n() { ushort t = Ten; ushort f = F31(t, t, t); return (f == 100); } static bool Bench31p1() { ushort r = Ten; ushort s = Ten; ushort t = 10; ushort f = F31(r, s, t); return (f == 100); } static bool Bench31n1() { ushort r = 10; ushort s = 10; ushort t = Ten; ushort f = F31(r, s, t); return (f == 100); } static bool Bench31p2() { ushort r = 10; ushort s = 10; ushort t = 10; ushort f = F31(r, s, t); return (f == 100); } static bool Bench31n2() { ushort r = Ten; ushort s = Ten; ushort t = Ten; ushort f = F31(r, s, t); return (f == 100); } static bool Bench31p3() { ushort r = 10; ushort s = r; ushort t = s; ushort f = F31(r, s, t); return (f == 100); } static bool Bench31n3() { ushort r = Ten; ushort s = r; ushort t = s; ushort f = F31(r, s, t); return (f == 100); } // Two args, both used static ushort F40(ushort x, ushort y) { return (ushort)(x * x + y * y - 100); } static bool Bench40p() { ushort t = 10; ushort f = F40(t, t); return (f == 100); } static bool Bench40n() { ushort t = Ten; ushort f = F40(t, t); return (f == 100); } static bool Bench40p1() { ushort s = Ten; ushort t = 10; ushort f = F40(s, t); return (f == 100); } static bool Bench40p2() { ushort s = 10; ushort t = Ten; ushort f = F40(s, t); return (f == 100); } static ushort F41(ushort x, ushort y) { return (ushort)(x * y); } static bool Bench41p() { ushort t = 10; ushort f = F41(t, t); return (f == 100); } static bool Bench41n() { ushort t = Ten; ushort f = F41(t, t); return (f == 100); } static bool Bench41p1() { ushort s = 10; ushort t = Ten; ushort f = F41(s, t); return (f == 100); } static bool Bench41p2() { ushort s = Ten; ushort t = 10; ushort f = F41(s, t); return (f == 100); } private static IEnumerable<object[]> MakeArgs(params string[] args) { return args.Select(arg => new object[] { arg }); } public static IEnumerable<object[]> TestFuncs = MakeArgs( "Bench00p", "Bench00n", "Bench00p1", "Bench00n1", "Bench00p2", "Bench00n2", "Bench00p3", "Bench00n3", "Bench00p4", "Bench00n4", "Bench01p", "Bench01n", "Bench02p", "Bench02n", "Bench03p", "Bench03n", "Bench04p", "Bench04n", "Bench05p", "Bench05n", "Bench05p1", "Bench05n1", "Bench06p", "Bench06n", "Bench07p", "Bench07n", "Bench07p1", "Bench07n1", "Bench08p", "Bench08n", "Bench09p", "Bench09n", "Bench10p", "Bench10n", "Bench10p1", "Bench10n1", "Bench10p2", "Bench10n2", "Bench10p3", "Bench10n3", "Bench11p", "Bench11n", "Bench11p1", "Bench11n1", "Bench11p2", "Bench11n2", "Bench11p3", "Bench11n3", "Bench20p", "Bench20p1", "Bench21p", "Bench21n", "Bench21p1", "Bench21n1", "Bench22p", "Bench22p1", "Bench23p", "Bench23n", "Bench30p", "Bench30n", "Bench30p1", "Bench30n1", "Bench30p2", "Bench30n2", "Bench30p3", "Bench30n3", "Bench31p", "Bench31n", "Bench31p1", "Bench31n1", "Bench31p2", "Bench31n2", "Bench31p3", "Bench31n3", "Bench40p", "Bench40n", "Bench40p1", "Bench40p2", "Bench41p", "Bench41n", "Bench41p1", "Bench41p2" ); static Func<bool> LookupFunc(object o) { TypeInfo t = typeof(ConstantArgsUShort).GetTypeInfo(); MethodInfo m = t.GetDeclaredMethod((string) o); return m.CreateDelegate(typeof(Func<bool>)) as Func<bool>; } [Benchmark] [MemberData(nameof(TestFuncs))] public static void Test(object funcName) { Func<bool> f = LookupFunc(funcName); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Iterations; i++) { f(); } } } } static bool TestBase(Func<bool> f) { bool result = true; for (int i = 0; i < Iterations; i++) { result &= f(); } return result; } public static int Main() { bool result = true; foreach(object[] o in TestFuncs) { string funcName = (string) o[0]; Func<bool> func = LookupFunc(funcName); bool thisResult = TestBase(func); if (!thisResult) { Console.WriteLine("{0} failed", funcName); } result &= thisResult; } return (result ? 100 : -1); } } }
using System; using dotless.Core.Exceptions; namespace dotless.Core.Parser.Tree { using System.Collections.Generic; using System.Linq; using System.Text; using Infrastructure; using Infrastructure.Nodes; using Utils; using Plugins; public class Ruleset : Node { public NodeList<Selector> Selectors { get; set; } public NodeList Rules { get; set; } public bool Evaluated { get; protected set; } public bool IsRoot { get; set; } public bool MultiMedia { get; set; } /// <summary> /// The original Ruleset this was cloned from during evaluation /// (may == this if this is the orginal) /// </summary> public Ruleset OriginalRuleset { get; set; } private Dictionary<string, List<Closure>> _lookups; public Ruleset(NodeList<Selector> selectors, NodeList rules) : this(selectors, rules, null) { } protected Ruleset(NodeList<Selector> selectors, NodeList rules, Ruleset originalRuleset) : this() { Selectors = selectors; Rules = rules; OriginalRuleset = originalRuleset ?? this; } protected Ruleset() { _lookups = new Dictionary<string, List<Closure>>(); OriginalRuleset = this; } /// <summary> /// returns whether this rulset is equal to or cloned from another node /// </summary> public bool IsEqualOrClonedFrom(Node node) { Ruleset ruleset = node as Ruleset; if (ruleset) { return IsEqualOrClonedFrom(ruleset); } return false; } /// <summary> /// returns whether this rulset is equal to or cloned from another ruleset /// </summary> public bool IsEqualOrClonedFrom(Ruleset ruleset) { return ruleset.OriginalRuleset == OriginalRuleset; } public Rule Variable(string name, Node startNode) { Ruleset startNodeRuleset = startNode as Ruleset; return Rules .TakeWhile(r => r != startNode && (startNodeRuleset == null || !startNodeRuleset.IsEqualOrClonedFrom(r))) .OfType<Rule>() .Where(r => r.Variable) .Reverse() .FirstOrDefault(r => r.Name == name); } public List<Ruleset> Rulesets() { return (Rules ?? Enumerable.Empty<Node>()).OfType<Ruleset>().ToList(); } public List<Closure> Find<TRuleset>(Env env, Selector selector, Ruleset self) where TRuleset : Ruleset { var context = new Context(); context.AppendSelectors(new Context(), Selectors ?? new NodeList<Selector>()); var namespacedSelectorContext = new Context(); namespacedSelectorContext.AppendSelectors(context, new NodeList<Selector>(selector)); var namespacedSelector = namespacedSelectorContext .Select(selectors => new Selector(selectors.SelectMany(s => s.Elements))) .First(); return FindInternal(env, namespacedSelector, self, context).ToList(); } private IEnumerable<Closure> FindInternal(Env env, Selector selector, Ruleset self, Context context) { if (!selector.Elements.Any()) { return Enumerable.Empty<Closure>(); } string selectorCss = selector.ToCSS(env); var key = selectorCss; if (_lookups.ContainsKey(key)) return _lookups[key]; self = self ?? this; var rules = new List<Closure>(); var bestMatch = context.Select(selectors => new Selector(selectors.SelectMany(s => s.Elements))) .Where(m => m.Elements.IsSubsequenceOf(selector.Elements, ElementValuesEqual)) .OrderByDescending(m => m.Elements.Count) .FirstOrDefault(); if (bestMatch != null && bestMatch.Elements.Count == selector.Elements.Count) { // exact match, good to go rules.Add(new Closure { Context = new List<Ruleset> { this }, Ruleset = this }); } var validRulesets = Rulesets().Where(rule => { if (rule != self) return true; MixinDefinition mixinRule = rule as MixinDefinition; if (mixinRule != null) { return mixinRule.Condition != null; } return false; }); foreach (var rule in validRulesets) { if (rule.Selectors == null) { continue; } var childContext = new Context(); childContext.AppendSelectors(context, rule.Selectors); var closures = rule.FindInternal(env, selector, self, childContext); foreach (var closure in closures) { closure.Context.Insert(0, this); rules.Add(closure); } } return _lookups[key] = rules; } private static bool ElementValuesEqual(Element e1, Element e2) { if (e1.Value == null && e2.Value == null) { return true; } if (e1.Value == null || e2.Value == null) { return false; } return string.Equals(e1.Value.Trim(), e2.Value.Trim()); } public virtual MixinMatch MatchArguments(List<NamedArgument> arguments, Env env) { return (arguments == null || arguments.Count == 0) ? MixinMatch.Pass : MixinMatch.ArgumentMismatch; } public override Node Evaluate(Env env) { if (Evaluated) return this; // create a clone so it is non destructive var clone = Clone().ReducedFrom<Ruleset>(this); clone.EvaluateRules(env); clone.Evaluated = true; return clone; } private Ruleset Clone() { return new Ruleset(new NodeList<Selector>(Selectors), new NodeList(Rules), OriginalRuleset) { IsReference = IsReference }; } public override void Accept(IVisitor visitor) { Selectors = VisitAndReplace(Selectors, visitor); Rules = VisitAndReplace(Rules, visitor); } /// <summary> /// Evaluate Rules. Must only be run on a copy of the ruleset otherwise it will /// overwrite defintions that might be required later.. /// </summary> protected void EvaluateRules(Env env) { env.Frames.Push(this); for (var i = 0; i < Selectors.Count; i++) { var evaluatedSelector = Selectors[i].Evaluate(env); var expandedSelectors = evaluatedSelector as IEnumerable<Selector>; if (expandedSelectors != null) { Selectors.RemoveAt(i); Selectors.InsertRange(i, expandedSelectors); } else { Selectors[i] = evaluatedSelector as Selector; } } int mediaBlocks = env.MediaBlocks.Count; NodeHelper.ExpandNodes<Import>(env, Rules); NodeHelper.ExpandNodes<MixinCall>(env, Rules); foreach (var r in Rules.OfType<Extend>().ToArray()) { foreach (var s in this.Selectors) { //If we're in a media block, then extenders can only apply to that media block if (env.MediaPath.Any()) { env.MediaPath.Peek().AddExtension(s, (Extend) r.Evaluate(env), env); } else //Global extend { env.AddExtension(s, (Extend) r.Evaluate(env), env); } } } for (var i = 0; i < Rules.Count; i++) { Rules[i] = Rules[i].Evaluate(env); } // if media blocks are inside this ruleset we have to "catch" the bubbling and // make sure they get this rulesets selectors for (var j = mediaBlocks; j < env.MediaBlocks.Count; j++) { env.MediaBlocks[j].BubbleSelectors(Selectors); } env.Frames.Pop(); } protected Ruleset EvaluateRulesForFrame(Ruleset frame, Env context) { var newRules = new NodeList(); foreach (var rule in Rules) { if (rule is MixinDefinition) { var mixin = rule as MixinDefinition; var parameters = Enumerable.Concat(mixin.Params, frame.Rules.Cast<Rule>()); newRules.Add(new MixinDefinition(mixin.Name, new NodeList<Rule>(parameters), mixin.Rules, mixin.Condition, mixin.Variadic)); } else if (rule is Import) { var potentiolNodeList = rule.Evaluate(context); var nodeList = potentiolNodeList as NodeList; if (nodeList != null) { newRules.AddRange(nodeList); } else { newRules.Add(potentiolNodeList); } } else if (rule is Directive || rule is Media) { newRules.Add(rule.Evaluate(context)); } else if (rule is Ruleset) { var ruleset = (rule as Ruleset); newRules.Add(ruleset.Evaluate(context)); } else if (rule is MixinCall) { newRules.AddRange((NodeList)rule.Evaluate(context)); } else { newRules.Add(rule.Evaluate(context)); } } return new Ruleset(Selectors, newRules); } public override void AppendCSS(Env env) { if (Rules == null || !Rules.Any()) return; ((Ruleset) Evaluate(env)).AppendCSS(env, new Context()); } /// <summary> /// Append the rules in a {} block. Used by sub classes. /// </summary> protected void AppendRules(Env env) { if (env.Compress && Rules.Count == 0) { return; } env.Output .Append(env.Compress ? "{" : " {\n") .Push() .AppendMany(Rules, "\n") .Trim() .Indent(env.Compress ? 0 : 2) .PopAndAppend(); if (env.Compress) { env.Output.TrimRight(';'); } env.Output.Append(env.Compress ? "}" : "\n}"); } public virtual void AppendCSS(Env env, Context context) { var rules = new List<StringBuilder>(); // node.Ruleset instances int nonCommentRules = 0; var paths = new Context(); // Current selectors if (!IsRoot) { if (!env.Compress && env.Debug && Location != null) { env.Output.Append(string.Format("/* {0}:L{1} */\n", Location.FileName, Zone.GetLineNumber(Location))); } paths.AppendSelectors(context, Selectors); } env.Output.Push(); bool hasNonReferenceChildRulesets = false; foreach (var node in Rules) { if (node.IgnoreOutput()) continue; var comment = node as Comment; if (comment != null && !comment.IsValidCss) continue; var ruleset = node as Ruleset; if (ruleset != null) { ruleset.AppendCSS(env, paths); if (!ruleset.IsReference) { hasNonReferenceChildRulesets = true; } } else { var rule = node as Rule; if (rule && rule.Variable) continue; if (!IsRoot) { if (!comment) nonCommentRules++; env.Output.Push() .Append(node); rules.Add(env.Output.Pop()); } else { env.Output .Append(node); if (!env.Compress) { env.Output .Append("\n"); } } } } var rulesetOutput = env.Output.Pop(); var hasExtenders = AddExtenders(env, context, paths); if (hasExtenders) { IsReference = false; } // If this is the root node, we don't render // a selector, or {}. // Otherwise, only output if this ruleset has rules. if (!IsReference) { if (IsRoot) { env.Output.AppendMany(rules, env.Compress ? "" : "\n"); } else { if (nonCommentRules > 0) { paths.AppendCSS(env); env.Output.Append(env.Compress ? "{" : " {\n "); env.Output.AppendMany(rules.ConvertAll(stringBuilder => stringBuilder.ToString()).Distinct(), env.Compress ? "" : "\n "); if (env.Compress) { env.Output.TrimRight(';'); } env.Output.Append(env.Compress ? "}" : "\n}\n"); } } } if (!IsReference || hasNonReferenceChildRulesets) { env.Output.Append(rulesetOutput); } } private bool AddExtenders(Env env, Context context, Context paths) { bool hasNonReferenceExtenders = false; foreach (var s in Selectors.Where(s => s.Elements.First().Value != null)) { var local = context.Clone(); local.AppendSelectors(context, new[] {s}); var finalString = local.ToCss(env); var exactExtension = env.FindExactExtension(finalString); if (exactExtension != null) { exactExtension.IsMatched = true; paths.AppendSelectors(context.Clone(), exactExtension.ExtendedBy); } var partials = env.FindPartialExtensions(local); if (partials != null) { foreach (var partialExtension in partials) { partialExtension.IsMatched = true; } paths.AppendSelectors(context.Clone(), partials.SelectMany(p => p.Replacements(finalString))); } bool newExactExtenders = exactExtension != null && exactExtension.ExtendedBy.Any(e => !e.IsReference); bool newPartialExtenders = partials != null && partials.Any(p => p.ExtendedBy.Any(e => !e.IsReference)); hasNonReferenceExtenders = hasNonReferenceExtenders || newExactExtenders || newPartialExtenders; } return hasNonReferenceExtenders; } public override string ToString() { var format = "{0}{{{1}}}"; return Selectors != null && Selectors.Count > 0 ? string.Format(format, Selectors.Select(s => s.ToCSS(new Env(null))).JoinStrings(""), Rules.Count) : string.Format(format, "*", Rules.Count); } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.Linq; using Adxstudio.Xrm.Resources; using Adxstudio.Xrm.Tagging; using Microsoft.Xrm.Portal; using Microsoft.Xrm.Portal.Core; using Microsoft.Xrm.Client; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Client; namespace Adxstudio.Xrm.Forums { public static class OrganizationServiceContextExtensions { public static IEnumerable<Entity> GetForums(this OrganizationServiceContext context) { return context.CreateQuery("adx_communityforum").ToList(); } public static IEnumerable<Entity> GetForumPosts(this OrganizationServiceContext context) { return context.CreateQuery("adx_communityforumpost").ToList(); } public static IEnumerable<Entity> GetForumThreads(this OrganizationServiceContext context) { return context.CreateQuery("adx_communityforumthread").ToList(); } public static IEnumerable<Entity> GetForumThreadTags(this OrganizationServiceContext context) { return context.CreateQuery("adx_communityforumthreadtag").ToList(); } public static IEnumerable<Entity> GetForumThreadTypes(this OrganizationServiceContext context) { return context.CreateQuery("adx_forumthreadtype").ToList(); } /// <summary> /// Marks forum post as an answer. /// </summary> public static void MarkPostAsAnswerAndSave(this OrganizationServiceContext context, Entity post, bool isAnswer) { post.AssertEntityName("adx_communityforumpost"); post["adx_isanswer"] = isAnswer; context.UpdateObject(post); context.SaveChanges(); } /// <summary> /// Increments the helpful vote count for forum post. /// </summary> public static void MarkPostAsHelpfulAndSave(this OrganizationServiceContext context, Entity post) { post.AssertEntityName("adx_communityforumpost"); var count = post.GetAttributeValue<int?>("adx_helpfulvotecount"); post["adx_helpfulvotecount"] = count + 1; context.UpdateObject(post); context.SaveChanges(); } public static void ReportPostAbuseAndSave(this OrganizationServiceContext context, Entity post, string text) { post.AssertEntityName("adx_communityforumpost"); context.AddNoteAndSave(post, string.Empty, text); } public static void AddThreadAlertAndSave(this OrganizationServiceContext context, Entity thread, Entity contact) { thread.AssertEntityName("adx_communityforumthread"); contact.AssertEntityName("contact"); var forumAlerts = thread.GetRelatedEntities(context, "adx_communityforumthread_communityforumaalert"); var alert = ( from e in forumAlerts where e.GetAttributeValue<EntityReference>("adx_subscriberid") == contact.ToEntityReference() select e).FirstOrDefault(); if (alert == null) { alert = new Entity("adx_communityforumalert"); alert["adx_subscriberid"] = contact.ToEntityReference(); alert["adx_threadid"] = thread.ToEntityReference(); context.AddObject(alert); } context.SaveChanges(); } public static void RemoveThreadAlertAndSave(this OrganizationServiceContext context, Entity thread, Entity contact) { thread.AssertEntityName("adx_communityforumthread"); contact.AssertEntityName("contact"); var forumAlerts = thread.GetRelatedEntities(context, "adx_communityforumthread_communityforumaalert"); var alert = ( from e in forumAlerts where e.GetAttributeValue<EntityReference>("adx_subscriberid") == contact.ToEntityReference() select e).FirstOrDefault(); if (alert != null) { context.DeleteObject(alert); } context.SaveChanges(); } private static Entity GetForumThreadTagByName(this OrganizationServiceContext context, string tagName) { return context.CreateQuery("adx_communityforumthreadtag").ToList().Where(ftt => TagName.Equals(ftt.GetAttributeValue<string>("adx_name"), tagName)).FirstOrDefault(); } /// <summary> /// Adds a Forum Thread Tag tag association by name to a Forum Thread. /// </summary> /// <param name="threadId">The ID of the Forum Thread whose tags will be affected.</param> /// <param name="tagName"> /// The name of the tag to be associated with the thread (will be created if necessary). /// </param> /// <remarks> /// <para> /// This operation may call SaveChanges on this context--please ensure any queued /// changes are mananged accordingly. /// </para> /// </remarks> public static void AddTagToForumThreadAndSave(this OrganizationServiceContext context, Guid threadId, string tagName) { if (context.MergeOption == MergeOption.NoTracking) { throw new ArgumentException("The OrganizationServiceContext.MergeOption cannot be MergeOption.NoTracking.", "context"); } if (string.IsNullOrEmpty(tagName)) { throw new ArgumentException("Can't be null or empty.", "tagName"); } if (threadId == Guid.Empty) { throw new ArgumentException("Argument must be a non-empty GUID.", "threadId"); } var thread = context.CreateQuery("adx_communityforumthread").Single(e => e.GetAttributeValue<Guid>("adx_communityforumthreadid") == threadId); var tag = GetForumThreadTagByName(context, tagName); // If the tag doesn't exist, create it if (tag == null) { tag = new Entity("adx_communityforumthreadtag"); tag["adx_name"] = tagName; context.AddObject(tag); context.SaveChanges(); context.ReAttach(thread); context.ReAttach(tag); } if (!thread.GetRelatedEntities(context, "adx_forumthreadtag_forumthread").Any(t => t.GetAttributeValue<Guid>("adx_communityforumthreadtagid") == tag.Id)) { context.AddLink(thread, "adx_forumthreadtag_forumthread", tag); context.SaveChanges(); } } /// <summary> /// Removes a Forum Thread Tag tag association by name from a Forum Thread. /// </summary> /// <param name="threadId">The ID of the Forum Thread whose tags will be affected.</param> /// <param name="tagName"> /// The name of the tag to be dis-associated with from the thread. /// </param> /// <remarks> /// <para> /// This operation may call SaveChanges on this context--please ensure any queued /// changes are mananged accordingly. /// </para> /// </remarks> public static void RemoveTagFromForumThreadAndSave(this OrganizationServiceContext context, Guid threadId, string tagName) { if (context.MergeOption == MergeOption.NoTracking) { throw new ArgumentException("The OrganizationServiceContext.MergeOption cannot be MergeOption.NoTracking.", "context"); } if (string.IsNullOrEmpty(tagName)) { throw new ArgumentException("Can't be null or empty.", "tagName"); } if (threadId == Guid.Empty) { throw new ArgumentException("Argument must be a non-empty GUID.", "threadId"); } var thread = context.CreateQuery("adx_communityforumthread").Single(e => e.GetAttributeValue<Guid>("adx_communityforumthreadid") == threadId); var tag = GetForumThreadTagByName(context, tagName); // If the tag doesn't exist, do nothing if (tag == null) { return; } context.DeleteLink(thread, "adx_forumthreadtag_forumthread", tag); context.SaveChanges(); } #region Forum Moderation Methods /// <summary> /// Deletes a given Forum Thread. /// </summary> /// <param name="threadID">A unique identifier for the thread that will be removed.</param> public static void DeleteForumThread(this OrganizationServiceContext context, Guid threadID) { Entity thread; if (TryGetForumThreadFromID(context, threadID, out thread)) { DeleteForumThread(context, thread); } } public static void DeleteForumThread(this OrganizationServiceContext context, Entity thread) { thread.AssertEntityName("adx_communityforumthread"); context.DeleteObject(thread); context.SaveChanges(); } /// <summary> /// Tries to get the thread for a given ID. /// </summary> /// <param name="threadID">A unique identifier for the thread.</param> /// <param name="thread">Entity output or null if retrieval was unsuccessful.</param> /// <returns>true, if the thread was successfully retrieved; otherwise, false.</returns> public static bool TryGetForumThreadFromID(this OrganizationServiceContext context, Guid threadID, out Entity thread) { thread = context.CreateQuery("adx_communityforumthread").Single(p => p.GetAttributeValue<Guid?>("adx_communityforumthreadid") == threadID); return thread != null; } /// <summary> /// Deletes a given Forum Post. /// </summary> /// <param name="postID">A unique identifier for the post that will be removed.</param> public static void DeleteForumPost(this OrganizationServiceContext context, Guid postID) { Entity post; if (TryGetForumPostFromID(context, postID, out post)) { DeleteForumPost(context, post); } } public static void DeleteForumPost(this OrganizationServiceContext context, Entity post) { post.AssertEntityName("adx_communityforumpost"); UpdateThreadOnPostDelete(context, post); context.ReAttach(post); context.DeleteObject(post); context.SaveChanges(); } /// <summary> /// Tries to get the post for a given ID. /// </summary> /// <param name="postID">A unique identifier for the post.</param> /// <param name="post">Entity output or null if retrieval was unsuccessful.</param> /// <returns>true, if the post was successfully retrieved; otherwise, false.</returns> public static bool TryGetForumPostFromID(this OrganizationServiceContext context, Guid postID, out Entity post) { post = context.CreateQuery("adx_communityforumpost").Single(p => p.GetAttributeValue<Guid?>("adx_communityforumpostid") == postID); return post != null; } /// <summary> /// Updates the post's parent thread. If the the parent thread's Last Post ID or First Post ID match /// the id of the current post being deleted, then those ID's need to be updated. This method will also /// decrement the thread's post count. /// </summary> /// <param name="post"> entity.</param> private static void UpdateThreadOnPostDelete(this OrganizationServiceContext context, Entity post) { post.AssertEntityName("adx_communityforumpost"); var parentThread = post.GetRelatedEntity(context, "adx_communityforumthread_communityforumpost"); if (parentThread == null) throw new NullReferenceException("Error retrieving parent Forum Thread"); var currentLastPostId = parentThread.GetAttributeValue<EntityReference>("adx_lastpostid") == null ? Guid.Empty : parentThread.GetAttributeValue<EntityReference>("adx_lastpostid").Id; var currentFirstPostId = parentThread.GetAttributeValue<EntityReference>("adx_firstpostid") == null ? Guid.Empty : parentThread.GetAttributeValue<EntityReference>("adx_firstpostid").Id; var currentPostId = post.GetAttributeValue<Guid>("adx_communityforumpostid"); if (currentPostId == currentLastPostId) { var lastPost = GetForumPosts(context).Where(p => p.GetAttributeValue<EntityReference>("adx_forumthreadid") != null && p.GetAttributeValue<EntityReference>("adx_forumthreadid").Equals(parentThread.ToEntityReference()) && p.GetAttributeValue<Guid>("adx_communityforumpostid") != currentPostId).OrderByDescending(p => p.GetAttributeValue<DateTime>("adx_date")).First(); if (lastPost != null) { parentThread["adx_lastpostid"] = lastPost.ToEntityReference(); } } if (currentPostId == currentFirstPostId) { var firstPost = GetForumPosts(context).Where(p => p.GetAttributeValue<EntityReference>("adx_forumthreadid") != null && p.GetAttributeValue<EntityReference>("adx_forumthreadid").Equals(parentThread.ToEntityReference()) && p.GetAttributeValue<Guid>("adx_communityforumpostid") != currentPostId).OrderBy(p => p.GetAttributeValue<DateTime>("adx_date")).First(); if (firstPost != null) { parentThread["adx_firstpostid"] = firstPost.ToEntityReference(); } } parentThread["adx_postcount"] = parentThread.GetAttributeValue<int>("adx_postcount") > 0 ? parentThread.GetAttributeValue<int>("adx_postcount") - 1 : 0; context.UpdateObject(parentThread); context.SaveChanges(); } #endregion #region Forum public static IEnumerable<Entity> GetOrderedForumThreads(this OrganizationServiceContext context, Entity forum) { forum.AssertEntityName("adx_communityforum"); var forumThreads = forum.GetRelatedEntities(context, "adx_communityforum_communityforumthread"); var threads = from t in forumThreads orderby GetDate(context, t) descending select t; return threads; } private static DateTime? GetDate(OrganizationServiceContext context, Entity thread) { var lastPost = thread.GetRelatedEntity(context, "adx_communityforumpost_communityforumthread"); if (lastPost != null) { return lastPost.GetAttributeValue<DateTime?>("adx_date"); } var firstPost = thread.GetRelatedEntity(context, "adx_communityforumthrea_firstpost"); if (firstPost != null) { return firstPost.GetAttributeValue<DateTime?>("adx_date"); } return null; } #endregion #region Forum Threads public static bool GetCurrentUserHasAlert(this OrganizationServiceContext context, Entity forumThread) { forumThread.AssertEntityName("adx_communityforumthread"); var contact = PortalContext.Current.User; if (contact != null) { var forumAlerts = forumThread.GetRelatedEntities(context, "adx_communityforumthread_communityforumaalert"); var alerts = from e in forumAlerts where e.GetAttributeValue<EntityReference>("adx_threadid") == forumThread.ToEntityReference() && e.GetAttributeValue<EntityReference>("adx_subscriberid") == contact.ToEntityReference() select e; if (alerts.Count() > 0) { return true; } } return false; } public static IEnumerable<Entity> GetOrderedForumPosts(this OrganizationServiceContext context, Entity forumThread) { forumThread.AssertEntityName("adx_communityforumthread"); var forumPosts = forumThread.GetRelatedEntities(context, "adx_communityforumthread_communityforumpost"); return forumPosts.OrderBy(fp => fp.GetAttributeValue<DateTime?>("adx_date")); } #endregion } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// ServiceResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Notify.V1 { public class ServiceResource : Resource { private static Request BuildCreateRequest(CreateServiceOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Notify, "/v1/Services", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// create /// </summary> /// <param name="options"> Create Service parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Service </returns> public static ServiceResource Create(CreateServiceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="options"> Create Service parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Service </returns> public static async System.Threading.Tasks.Task<ServiceResource> CreateAsync(CreateServiceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// create /// </summary> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="apnCredentialSid"> The SID of the Credential to use for APN Bindings </param> /// <param name="gcmCredentialSid"> The SID of the Credential to use for GCM Bindings </param> /// <param name="messagingServiceSid"> The SID of the Messaging Service to use for SMS Bindings </param> /// <param name="facebookMessengerPageId"> Deprecated </param> /// <param name="defaultApnNotificationProtocolVersion"> The protocol version to use for sending APNS notifications /// </param> /// <param name="defaultGcmNotificationProtocolVersion"> The protocol version to use for sending GCM notifications /// </param> /// <param name="fcmCredentialSid"> The SID of the Credential to use for FCM Bindings </param> /// <param name="defaultFcmNotificationProtocolVersion"> The protocol version to use for sending FCM notifications /// </param> /// <param name="logEnabled"> Whether to log notifications </param> /// <param name="alexaSkillId"> Deprecated </param> /// <param name="defaultAlexaNotificationProtocolVersion"> Deprecated </param> /// <param name="deliveryCallbackUrl"> Webhook URL </param> /// <param name="deliveryCallbackEnabled"> Enable delivery callbacks </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Service </returns> public static ServiceResource Create(string friendlyName = null, string apnCredentialSid = null, string gcmCredentialSid = null, string messagingServiceSid = null, string facebookMessengerPageId = null, string defaultApnNotificationProtocolVersion = null, string defaultGcmNotificationProtocolVersion = null, string fcmCredentialSid = null, string defaultFcmNotificationProtocolVersion = null, bool? logEnabled = null, string alexaSkillId = null, string defaultAlexaNotificationProtocolVersion = null, string deliveryCallbackUrl = null, bool? deliveryCallbackEnabled = null, ITwilioRestClient client = null) { var options = new CreateServiceOptions(){FriendlyName = friendlyName, ApnCredentialSid = apnCredentialSid, GcmCredentialSid = gcmCredentialSid, MessagingServiceSid = messagingServiceSid, FacebookMessengerPageId = facebookMessengerPageId, DefaultApnNotificationProtocolVersion = defaultApnNotificationProtocolVersion, DefaultGcmNotificationProtocolVersion = defaultGcmNotificationProtocolVersion, FcmCredentialSid = fcmCredentialSid, DefaultFcmNotificationProtocolVersion = defaultFcmNotificationProtocolVersion, LogEnabled = logEnabled, AlexaSkillId = alexaSkillId, DefaultAlexaNotificationProtocolVersion = defaultAlexaNotificationProtocolVersion, DeliveryCallbackUrl = deliveryCallbackUrl, DeliveryCallbackEnabled = deliveryCallbackEnabled}; return Create(options, client); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="apnCredentialSid"> The SID of the Credential to use for APN Bindings </param> /// <param name="gcmCredentialSid"> The SID of the Credential to use for GCM Bindings </param> /// <param name="messagingServiceSid"> The SID of the Messaging Service to use for SMS Bindings </param> /// <param name="facebookMessengerPageId"> Deprecated </param> /// <param name="defaultApnNotificationProtocolVersion"> The protocol version to use for sending APNS notifications /// </param> /// <param name="defaultGcmNotificationProtocolVersion"> The protocol version to use for sending GCM notifications /// </param> /// <param name="fcmCredentialSid"> The SID of the Credential to use for FCM Bindings </param> /// <param name="defaultFcmNotificationProtocolVersion"> The protocol version to use for sending FCM notifications /// </param> /// <param name="logEnabled"> Whether to log notifications </param> /// <param name="alexaSkillId"> Deprecated </param> /// <param name="defaultAlexaNotificationProtocolVersion"> Deprecated </param> /// <param name="deliveryCallbackUrl"> Webhook URL </param> /// <param name="deliveryCallbackEnabled"> Enable delivery callbacks </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Service </returns> public static async System.Threading.Tasks.Task<ServiceResource> CreateAsync(string friendlyName = null, string apnCredentialSid = null, string gcmCredentialSid = null, string messagingServiceSid = null, string facebookMessengerPageId = null, string defaultApnNotificationProtocolVersion = null, string defaultGcmNotificationProtocolVersion = null, string fcmCredentialSid = null, string defaultFcmNotificationProtocolVersion = null, bool? logEnabled = null, string alexaSkillId = null, string defaultAlexaNotificationProtocolVersion = null, string deliveryCallbackUrl = null, bool? deliveryCallbackEnabled = null, ITwilioRestClient client = null) { var options = new CreateServiceOptions(){FriendlyName = friendlyName, ApnCredentialSid = apnCredentialSid, GcmCredentialSid = gcmCredentialSid, MessagingServiceSid = messagingServiceSid, FacebookMessengerPageId = facebookMessengerPageId, DefaultApnNotificationProtocolVersion = defaultApnNotificationProtocolVersion, DefaultGcmNotificationProtocolVersion = defaultGcmNotificationProtocolVersion, FcmCredentialSid = fcmCredentialSid, DefaultFcmNotificationProtocolVersion = defaultFcmNotificationProtocolVersion, LogEnabled = logEnabled, AlexaSkillId = alexaSkillId, DefaultAlexaNotificationProtocolVersion = defaultAlexaNotificationProtocolVersion, DeliveryCallbackUrl = deliveryCallbackUrl, DeliveryCallbackEnabled = deliveryCallbackEnabled}; return await CreateAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteServiceOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Notify, "/v1/Services/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// delete /// </summary> /// <param name="options"> Delete Service parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Service </returns> public static bool Delete(DeleteServiceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="options"> Delete Service parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Service </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteServiceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// delete /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Service </returns> public static bool Delete(string pathSid, ITwilioRestClient client = null) { var options = new DeleteServiceOptions(pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Service </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathSid, ITwilioRestClient client = null) { var options = new DeleteServiceOptions(pathSid); return await DeleteAsync(options, client); } #endif private static Request BuildFetchRequest(FetchServiceOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Notify, "/v1/Services/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Service parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Service </returns> public static ServiceResource Fetch(FetchServiceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Service parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Service </returns> public static async System.Threading.Tasks.Task<ServiceResource> FetchAsync(FetchServiceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Service </returns> public static ServiceResource Fetch(string pathSid, ITwilioRestClient client = null) { var options = new FetchServiceOptions(pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Service </returns> public static async System.Threading.Tasks.Task<ServiceResource> FetchAsync(string pathSid, ITwilioRestClient client = null) { var options = new FetchServiceOptions(pathSid); return await FetchAsync(options, client); } #endif private static Request BuildReadRequest(ReadServiceOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Notify, "/v1/Services", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read Service parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Service </returns> public static ResourceSet<ServiceResource> Read(ReadServiceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<ServiceResource>.FromJson("services", response.Content); return new ResourceSet<ServiceResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read Service parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Service </returns> public static async System.Threading.Tasks.Task<ResourceSet<ServiceResource>> ReadAsync(ReadServiceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<ServiceResource>.FromJson("services", response.Content); return new ResourceSet<ServiceResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="friendlyName"> The string that identifies the Service resources to read </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Service </returns> public static ResourceSet<ServiceResource> Read(string friendlyName = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadServiceOptions(){FriendlyName = friendlyName, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="friendlyName"> The string that identifies the Service resources to read </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Service </returns> public static async System.Threading.Tasks.Task<ResourceSet<ServiceResource>> ReadAsync(string friendlyName = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadServiceOptions(){FriendlyName = friendlyName, PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<ServiceResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<ServiceResource>.FromJson("services", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<ServiceResource> NextPage(Page<ServiceResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Notify) ); var response = client.Request(request); return Page<ServiceResource>.FromJson("services", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<ServiceResource> PreviousPage(Page<ServiceResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Notify) ); var response = client.Request(request); return Page<ServiceResource>.FromJson("services", response.Content); } private static Request BuildUpdateRequest(UpdateServiceOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Notify, "/v1/Services/" + options.PathSid + "", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// update /// </summary> /// <param name="options"> Update Service parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Service </returns> public static ServiceResource Update(UpdateServiceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="options"> Update Service parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Service </returns> public static async System.Threading.Tasks.Task<ServiceResource> UpdateAsync(UpdateServiceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// update /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="apnCredentialSid"> The SID of the Credential to use for APN Bindings </param> /// <param name="gcmCredentialSid"> The SID of the Credential to use for GCM Bindings </param> /// <param name="messagingServiceSid"> The SID of the Messaging Service to use for SMS Bindings </param> /// <param name="facebookMessengerPageId"> Deprecated </param> /// <param name="defaultApnNotificationProtocolVersion"> The protocol version to use for sending APNS notifications /// </param> /// <param name="defaultGcmNotificationProtocolVersion"> The protocol version to use for sending GCM notifications /// </param> /// <param name="fcmCredentialSid"> The SID of the Credential to use for FCM Bindings </param> /// <param name="defaultFcmNotificationProtocolVersion"> The protocol version to use for sending FCM notifications /// </param> /// <param name="logEnabled"> Whether to log notifications </param> /// <param name="alexaSkillId"> Deprecated </param> /// <param name="defaultAlexaNotificationProtocolVersion"> Deprecated </param> /// <param name="deliveryCallbackUrl"> Webhook URL </param> /// <param name="deliveryCallbackEnabled"> Enable delivery callbacks </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Service </returns> public static ServiceResource Update(string pathSid, string friendlyName = null, string apnCredentialSid = null, string gcmCredentialSid = null, string messagingServiceSid = null, string facebookMessengerPageId = null, string defaultApnNotificationProtocolVersion = null, string defaultGcmNotificationProtocolVersion = null, string fcmCredentialSid = null, string defaultFcmNotificationProtocolVersion = null, bool? logEnabled = null, string alexaSkillId = null, string defaultAlexaNotificationProtocolVersion = null, string deliveryCallbackUrl = null, bool? deliveryCallbackEnabled = null, ITwilioRestClient client = null) { var options = new UpdateServiceOptions(pathSid){FriendlyName = friendlyName, ApnCredentialSid = apnCredentialSid, GcmCredentialSid = gcmCredentialSid, MessagingServiceSid = messagingServiceSid, FacebookMessengerPageId = facebookMessengerPageId, DefaultApnNotificationProtocolVersion = defaultApnNotificationProtocolVersion, DefaultGcmNotificationProtocolVersion = defaultGcmNotificationProtocolVersion, FcmCredentialSid = fcmCredentialSid, DefaultFcmNotificationProtocolVersion = defaultFcmNotificationProtocolVersion, LogEnabled = logEnabled, AlexaSkillId = alexaSkillId, DefaultAlexaNotificationProtocolVersion = defaultAlexaNotificationProtocolVersion, DeliveryCallbackUrl = deliveryCallbackUrl, DeliveryCallbackEnabled = deliveryCallbackEnabled}; return Update(options, client); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="apnCredentialSid"> The SID of the Credential to use for APN Bindings </param> /// <param name="gcmCredentialSid"> The SID of the Credential to use for GCM Bindings </param> /// <param name="messagingServiceSid"> The SID of the Messaging Service to use for SMS Bindings </param> /// <param name="facebookMessengerPageId"> Deprecated </param> /// <param name="defaultApnNotificationProtocolVersion"> The protocol version to use for sending APNS notifications /// </param> /// <param name="defaultGcmNotificationProtocolVersion"> The protocol version to use for sending GCM notifications /// </param> /// <param name="fcmCredentialSid"> The SID of the Credential to use for FCM Bindings </param> /// <param name="defaultFcmNotificationProtocolVersion"> The protocol version to use for sending FCM notifications /// </param> /// <param name="logEnabled"> Whether to log notifications </param> /// <param name="alexaSkillId"> Deprecated </param> /// <param name="defaultAlexaNotificationProtocolVersion"> Deprecated </param> /// <param name="deliveryCallbackUrl"> Webhook URL </param> /// <param name="deliveryCallbackEnabled"> Enable delivery callbacks </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Service </returns> public static async System.Threading.Tasks.Task<ServiceResource> UpdateAsync(string pathSid, string friendlyName = null, string apnCredentialSid = null, string gcmCredentialSid = null, string messagingServiceSid = null, string facebookMessengerPageId = null, string defaultApnNotificationProtocolVersion = null, string defaultGcmNotificationProtocolVersion = null, string fcmCredentialSid = null, string defaultFcmNotificationProtocolVersion = null, bool? logEnabled = null, string alexaSkillId = null, string defaultAlexaNotificationProtocolVersion = null, string deliveryCallbackUrl = null, bool? deliveryCallbackEnabled = null, ITwilioRestClient client = null) { var options = new UpdateServiceOptions(pathSid){FriendlyName = friendlyName, ApnCredentialSid = apnCredentialSid, GcmCredentialSid = gcmCredentialSid, MessagingServiceSid = messagingServiceSid, FacebookMessengerPageId = facebookMessengerPageId, DefaultApnNotificationProtocolVersion = defaultApnNotificationProtocolVersion, DefaultGcmNotificationProtocolVersion = defaultGcmNotificationProtocolVersion, FcmCredentialSid = fcmCredentialSid, DefaultFcmNotificationProtocolVersion = defaultFcmNotificationProtocolVersion, LogEnabled = logEnabled, AlexaSkillId = alexaSkillId, DefaultAlexaNotificationProtocolVersion = defaultAlexaNotificationProtocolVersion, DeliveryCallbackUrl = deliveryCallbackUrl, DeliveryCallbackEnabled = deliveryCallbackEnabled}; return await UpdateAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a ServiceResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> ServiceResource object represented by the provided JSON </returns> public static ServiceResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<ServiceResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The string that you assigned to describe the resource /// </summary> [JsonProperty("friendly_name")] public string FriendlyName { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT when the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT when the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The SID of the Credential to use for APN Bindings /// </summary> [JsonProperty("apn_credential_sid")] public string ApnCredentialSid { get; private set; } /// <summary> /// The SID of the Credential to use for GCM Bindings /// </summary> [JsonProperty("gcm_credential_sid")] public string GcmCredentialSid { get; private set; } /// <summary> /// The SID of the Credential to use for FCM Bindings /// </summary> [JsonProperty("fcm_credential_sid")] public string FcmCredentialSid { get; private set; } /// <summary> /// The SID of the Messaging Service to use for SMS Bindings /// </summary> [JsonProperty("messaging_service_sid")] public string MessagingServiceSid { get; private set; } /// <summary> /// Deprecated /// </summary> [JsonProperty("facebook_messenger_page_id")] public string FacebookMessengerPageId { get; private set; } /// <summary> /// The protocol version to use for sending APNS notifications /// </summary> [JsonProperty("default_apn_notification_protocol_version")] public string DefaultApnNotificationProtocolVersion { get; private set; } /// <summary> /// The protocol version to use for sending GCM notifications /// </summary> [JsonProperty("default_gcm_notification_protocol_version")] public string DefaultGcmNotificationProtocolVersion { get; private set; } /// <summary> /// The protocol version to use for sending FCM notifications /// </summary> [JsonProperty("default_fcm_notification_protocol_version")] public string DefaultFcmNotificationProtocolVersion { get; private set; } /// <summary> /// Whether to log notifications /// </summary> [JsonProperty("log_enabled")] public bool? LogEnabled { get; private set; } /// <summary> /// The absolute URL of the Service resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// The URLs of the resources related to the service /// </summary> [JsonProperty("links")] public Dictionary<string, string> Links { get; private set; } /// <summary> /// Deprecated /// </summary> [JsonProperty("alexa_skill_id")] public string AlexaSkillId { get; private set; } /// <summary> /// Deprecated /// </summary> [JsonProperty("default_alexa_notification_protocol_version")] public string DefaultAlexaNotificationProtocolVersion { get; private set; } /// <summary> /// Webhook URL /// </summary> [JsonProperty("delivery_callback_url")] public string DeliveryCallbackUrl { get; private set; } /// <summary> /// Enable delivery callbacks /// </summary> [JsonProperty("delivery_callback_enabled")] public bool? DeliveryCallbackEnabled { get; private set; } private ServiceResource() { } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.Sql; using Microsoft.WindowsAzure.Management.Sql.Models; namespace Microsoft.WindowsAzure.Management.Sql { /// <summary> /// Contains the operation to create restore requests for Azure SQL /// Databases. /// </summary> internal partial class RestoreDatabaseOperations : IServiceOperations<SqlManagementClient>, Microsoft.WindowsAzure.Management.Sql.IRestoreDatabaseOperations { /// <summary> /// Initializes a new instance of the RestoreDatabaseOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal RestoreDatabaseOperations(SqlManagementClient client) { this._client = client; } private SqlManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Sql.SqlManagementClient. /// </summary> public SqlManagementClient Client { get { return this._client; } } /// <summary> /// Issues a restore request for an Azure SQL Database. /// </summary> /// <param name='sourceServerName'> /// Required. The name of the Azure SQL Database Server where the /// source database is, or was, hosted. /// </param> /// <param name='parameters'> /// Required. Additional parameters for the Create Restore Database /// Operation request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Contains the response to the Create Restore Database Operation /// request. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Sql.Models.RestoreDatabaseOperationCreateResponse> CreateAsync(string sourceServerName, RestoreDatabaseOperationCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (sourceServerName == null) { throw new ArgumentNullException("sourceServerName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.SourceDatabaseName == null) { throw new ArgumentNullException("parameters.SourceDatabaseName"); } if (parameters.TargetDatabaseName == null) { throw new ArgumentNullException("parameters.TargetDatabaseName"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("sourceServerName", sourceServerName); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters); } // Construct URL string url = "/" + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId) + "/services/sqlservers/servers/" + Uri.EscapeDataString(sourceServerName) + "/restoredatabaseoperations"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2012-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement serviceResourceElement = new XElement(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(serviceResourceElement); XElement sourceDatabaseNameElement = new XElement(XName.Get("SourceDatabaseName", "http://schemas.microsoft.com/windowsazure")); sourceDatabaseNameElement.Value = parameters.SourceDatabaseName; serviceResourceElement.Add(sourceDatabaseNameElement); if (parameters.SourceDatabaseDeletionDate != null) { XElement sourceDatabaseDeletionDateElement = new XElement(XName.Get("SourceDatabaseDeletionDate", "http://schemas.microsoft.com/windowsazure")); sourceDatabaseDeletionDateElement.Value = string.Format(CultureInfo.InvariantCulture, "{0:O}", parameters.SourceDatabaseDeletionDate.Value.ToUniversalTime()); serviceResourceElement.Add(sourceDatabaseDeletionDateElement); } if (parameters.TargetServerName != null) { XElement targetServerNameElement = new XElement(XName.Get("TargetServerName", "http://schemas.microsoft.com/windowsazure")); targetServerNameElement.Value = parameters.TargetServerName; serviceResourceElement.Add(targetServerNameElement); } XElement targetDatabaseNameElement = new XElement(XName.Get("TargetDatabaseName", "http://schemas.microsoft.com/windowsazure")); targetDatabaseNameElement.Value = parameters.TargetDatabaseName; serviceResourceElement.Add(targetDatabaseNameElement); if (parameters.PointInTime != null) { XElement targetUtcPointInTimeElement = new XElement(XName.Get("TargetUtcPointInTime", "http://schemas.microsoft.com/windowsazure")); targetUtcPointInTimeElement.Value = string.Format(CultureInfo.InvariantCulture, "{0:O}", parameters.PointInTime.Value.ToUniversalTime()); serviceResourceElement.Add(targetUtcPointInTimeElement); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result RestoreDatabaseOperationCreateResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RestoreDatabaseOperationCreateResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement serviceResourceElement2 = responseDoc.Element(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure")); if (serviceResourceElement2 != null) { RestoreDatabaseOperation serviceResourceInstance = new RestoreDatabaseOperation(); result.Operation = serviceResourceInstance; XElement requestIDElement = serviceResourceElement2.Element(XName.Get("RequestID", "http://schemas.microsoft.com/windowsazure")); if (requestIDElement != null) { string requestIDInstance = requestIDElement.Value; serviceResourceInstance.Id = requestIDInstance; } XElement sourceDatabaseNameElement2 = serviceResourceElement2.Element(XName.Get("SourceDatabaseName", "http://schemas.microsoft.com/windowsazure")); if (sourceDatabaseNameElement2 != null) { string sourceDatabaseNameInstance = sourceDatabaseNameElement2.Value; serviceResourceInstance.SourceDatabaseName = sourceDatabaseNameInstance; } XElement sourceDatabaseDeletionDateElement2 = serviceResourceElement2.Element(XName.Get("SourceDatabaseDeletionDate", "http://schemas.microsoft.com/windowsazure")); if (sourceDatabaseDeletionDateElement2 != null && string.IsNullOrEmpty(sourceDatabaseDeletionDateElement2.Value) == false) { DateTime sourceDatabaseDeletionDateInstance = DateTime.Parse(sourceDatabaseDeletionDateElement2.Value, CultureInfo.InvariantCulture); serviceResourceInstance.SourceDatabaseDeletionDate = sourceDatabaseDeletionDateInstance; } XElement targetServerNameElement2 = serviceResourceElement2.Element(XName.Get("TargetServerName", "http://schemas.microsoft.com/windowsazure")); if (targetServerNameElement2 != null) { string targetServerNameInstance = targetServerNameElement2.Value; serviceResourceInstance.TargetServerName = targetServerNameInstance; } XElement targetDatabaseNameElement2 = serviceResourceElement2.Element(XName.Get("TargetDatabaseName", "http://schemas.microsoft.com/windowsazure")); if (targetDatabaseNameElement2 != null) { string targetDatabaseNameInstance = targetDatabaseNameElement2.Value; serviceResourceInstance.TargetDatabaseName = targetDatabaseNameInstance; } XElement targetUtcPointInTimeElement2 = serviceResourceElement2.Element(XName.Get("TargetUtcPointInTime", "http://schemas.microsoft.com/windowsazure")); if (targetUtcPointInTimeElement2 != null) { DateTime targetUtcPointInTimeInstance = DateTime.Parse(targetUtcPointInTimeElement2.Value, CultureInfo.InvariantCulture); serviceResourceInstance.PointInTime = targetUtcPointInTimeInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ // // 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 Castle.DynamicProxy.Builder.CodeGenerators { using System; using System.Collections; using System.Collections.Specialized; using System.Reflection; using System.Reflection.Emit; using System.Runtime.Serialization; using System.Threading; using Castle.DynamicProxy.Builder.CodeBuilder; using Castle.DynamicProxy.Builder.CodeBuilder.SimpleAST; #if DOTNET2 using System.Runtime.CompilerServices; #endif /// <summary> /// Summary description for BaseCodeGenerator. /// </summary> [CLSCompliant(false)] public abstract class BaseCodeGenerator { private ModuleScope _moduleScope; private GeneratorContext _context; private EasyType _typeBuilder; private FieldReference _interceptorField; private FieldReference _cacheField; private FieldReference _mixinField; private IList _generated = new ArrayList(); #if DOTNET2 private ReaderWriterLock internalsToDynProxyLock = new ReaderWriterLock(); private System.Collections.Generic.IDictionary<Assembly, bool> internalsToDynProxy = new System.Collections.Generic.Dictionary<Assembly, bool>(); #endif protected Type _baseType = typeof(Object); protected EasyMethod _method2Invocation; protected object[] _mixins = new object[0]; /// <summary> /// Holds instance fields which points to delegates instantiated /// </summary> protected ArrayList _cachedFields = new ArrayList(); /// <summary> /// MethodInfo => Callable delegate /// </summary> protected Hashtable _method2Delegate = new Hashtable(); protected HybridDictionary _interface2mixinIndex = new HybridDictionary(); protected BaseCodeGenerator(ModuleScope moduleScope) : this(moduleScope, new GeneratorContext()) { } protected BaseCodeGenerator(ModuleScope moduleScope, GeneratorContext context) { _moduleScope = moduleScope; _context = context; } protected ModuleScope ModuleScope { get { return _moduleScope; } } protected GeneratorContext Context { get { return _context; } } protected EasyType MainTypeBuilder { get { return _typeBuilder; } } protected FieldReference InterceptorField { get { return _interceptorField; } } protected FieldReference MixinField { get { return _mixinField; } } protected FieldReference CacheField { get { return _cacheField; } } protected abstract Type InvocationType { get; } protected Type GetFromCache(Type baseClass, Type[] interfaces) { return ModuleScope[GenerateTypeName(baseClass, interfaces)] as Type; } protected void RegisterInCache(Type generatedType) { ModuleScope[generatedType.FullName] = generatedType; } protected FieldReference ObtainCallableFieldBuilderDelegate(EasyCallable builder) { foreach(CallableField field in _cachedFields) { if (field.Callable == builder) { return field.Field; } } return null; } protected void RegisterDelegateFieldToBeInitialized( MethodInfo method, FieldReference field, EasyCallable builder, MethodInfo callbackMethod) { int sourceArgIndex = CallableField.EmptyIndex; if (Context.HasMixins && _interface2mixinIndex.Contains(method.DeclaringType)) { sourceArgIndex = ((int) _interface2mixinIndex[method.DeclaringType]); } _cachedFields.Add(new CallableField(field, builder, callbackMethod, sourceArgIndex)); } protected virtual EasyType CreateTypeBuilder(String typeName, Type baseType, Type[] interfaces) { _baseType = baseType; _typeBuilder = new EasyType(ModuleScope, typeName, baseType, interfaces, true); return _typeBuilder; } protected virtual void GenerateFields() { _interceptorField = _typeBuilder.CreateField("__interceptor", Context.Interceptor); _cacheField = _typeBuilder.CreateField("__cache", typeof(HybridDictionary), false); _mixinField = _typeBuilder.CreateField("__mixin", typeof(object[])); } protected abstract String GenerateTypeName(Type type, Type[] interfaces); protected virtual void ImplementGetObjectData(Type[] interfaces) { // To prevent re-implementation of this interface. _generated.Add(typeof(ISerializable)); Type[] get_type_args = new Type[] {typeof(String), typeof(bool), typeof(bool)}; Type[] key_and_object = new Type[] {typeof(String), typeof(Object)}; MethodInfo addValueMethod = typeof(SerializationInfo).GetMethod("AddValue", key_and_object); ArgumentReference arg1 = new ArgumentReference(typeof(SerializationInfo)); ArgumentReference arg2 = new ArgumentReference(typeof(StreamingContext)); EasyMethod getObjectData = MainTypeBuilder.CreateMethod("GetObjectData", new ReturnReferenceExpression(typeof(void)), arg1, arg2); LocalReference typeLocal = getObjectData.CodeBuilder.DeclareLocal(typeof(Type)); getObjectData.CodeBuilder.AddStatement(new AssignStatement( typeLocal, new MethodInvocationExpression(null, typeof(Type).GetMethod("GetType", get_type_args), new FixedReference( Context.ProxyObjectReference. AssemblyQualifiedName).ToExpression(), new FixedReference(1).ToExpression(), new FixedReference(0).ToExpression()))); getObjectData.CodeBuilder.AddStatement(new ExpressionStatement( new VirtualMethodInvocationExpression( arg1, typeof(SerializationInfo).GetMethod("SetType"), typeLocal.ToExpression()))); getObjectData.CodeBuilder.AddStatement(new ExpressionStatement( new VirtualMethodInvocationExpression(arg1, addValueMethod, new FixedReference("__interceptor"). ToExpression(), InterceptorField.ToExpression()))); getObjectData.CodeBuilder.AddStatement(new ExpressionStatement( new VirtualMethodInvocationExpression(arg1, addValueMethod, new FixedReference("__mixins"). ToExpression(), MixinField.ToExpression()))); LocalReference interfacesLocal = getObjectData.CodeBuilder.DeclareLocal(typeof(String[])); getObjectData.CodeBuilder.AddStatement( new AssignStatement(interfacesLocal, new NewArrayExpression(interfaces.Length, typeof(String)))); for(int i = 0; i < interfaces.Length; i++) { getObjectData.CodeBuilder.AddStatement(new AssignArrayStatement( interfacesLocal, i, new FixedReference(interfaces[i].AssemblyQualifiedName).ToExpression())); } getObjectData.CodeBuilder.AddStatement(new ExpressionStatement( new VirtualMethodInvocationExpression(arg1, addValueMethod, new FixedReference("__interfaces"). ToExpression(), interfacesLocal.ToExpression()))); getObjectData.CodeBuilder.AddStatement(new ExpressionStatement( new VirtualMethodInvocationExpression(arg1, addValueMethod, new FixedReference("__baseType"). ToExpression(), new TypeTokenExpression(_baseType)))); CustomizeGetObjectData(getObjectData.CodeBuilder, arg1, arg2); getObjectData.CodeBuilder.AddStatement(new ReturnStatement()); } protected virtual void CustomizeGetObjectData(AbstractCodeBuilder codebuilder, ArgumentReference arg1, ArgumentReference arg2) { } protected virtual void ImplementCacheInvocationCache() { MethodInfo get_ItemMethod = typeof(HybridDictionary).GetMethod("get_Item", new Type[] {typeof(object)}); MethodInfo set_ItemMethod = typeof(HybridDictionary).GetMethod("Add", new Type[] {typeof(object), typeof(object)}); Type[] args = new Type[] {typeof(ICallable), typeof(MethodInfo)}; Type[] invocation_const_args = new Type[] {typeof(ICallable), typeof(object), typeof(MethodInfo), typeof(object)}; ArgumentReference arg1 = new ArgumentReference(typeof(ICallable)); ArgumentReference arg2 = new ArgumentReference(typeof(MethodInfo)); ArgumentReference arg3 = new ArgumentReference(typeof(object)); _method2Invocation = MainTypeBuilder.CreateMethod("_Method2Invocation", new ReturnReferenceExpression(Context.Invocation), MethodAttributes.Family | MethodAttributes.HideBySig, arg1, arg2, arg3); LocalReference invocation_local = _method2Invocation.CodeBuilder.DeclareLocal(Context.Invocation); LockBlockExpression block = new LockBlockExpression(SelfReference.Self); block.AddStatement(new AssignStatement(invocation_local, new ConvertExpression(Context.Invocation, new VirtualMethodInvocationExpression(CacheField, get_ItemMethod, arg2.ToExpression())))); ConditionExpression cond1 = new ConditionExpression(OpCodes.Brfalse_S, invocation_local.ToExpression()); cond1.AddTrueStatement(new AssignStatement( invocation_local, new NewInstanceExpression(InvocationType.GetConstructor(invocation_const_args), arg1.ToExpression(), SelfReference.Self.ToExpression(), arg2.ToExpression(), arg3.ToExpression()))); cond1.AddTrueStatement(new ExpressionStatement( new VirtualMethodInvocationExpression(CacheField, set_ItemMethod, arg2.ToExpression(), invocation_local.ToExpression()))); block.AddStatement(new ExpressionStatement(cond1)); _method2Invocation.CodeBuilder.AddStatement(new ExpressionStatement(block)); _method2Invocation.CodeBuilder.AddStatement(new ReturnStatement(invocation_local)); } protected virtual Type[] AddInterfaces(Type[] interfacesToAdd, Type[] interfaces) { bool[] containsInterface = new bool[interfacesToAdd.Length]; int interfacesToAddCount = 0; for(int i = interfacesToAdd.Length - 1; i >= 0; i--) { containsInterface[i] = Array.Exists(interfaces, delegate(Type type) { //May be somebody should revise this... return interfacesToAdd[i].FullName.Equals(type.FullName); }); if (!containsInterface[i]) { interfacesToAddCount++; } } Type[] newList = new Type[interfaces.Length + interfacesToAddCount]; Array.Copy(interfaces, newList, interfaces.Length); int currentIndex = interfaces.Length; for(int i = 0; i < interfacesToAdd.Length; i++) { if (!containsInterface[i]) // Proxy does not yet implement the interface... { newList[currentIndex++] = interfacesToAdd[i]; } } return newList; } //For backward compatibility... protected virtual Type[] AddISerializable(Type[] interfaces) { return AddInterfaces(new Type[] {typeof(ISerializable)}, interfaces); } protected virtual Type CreateType() { Type newType = MainTypeBuilder.BuildType(); RegisterInCache(newType); return newType; } /// <summary> /// Generates one public constructor receiving /// the <see cref="IInterceptor"/> instance and instantiating a hashtable /// </summary> /// <remarks> /// Should be overrided to provided specific semantics, if necessary /// </remarks> protected virtual EasyConstructor GenerateConstructor() { return null; } /// <summary> /// Common initializatio code for the default constructor /// </summary> /// <param name="codebuilder"></param> /// <param name="interceptorArg"></param> /// <param name="targetArgument"></param> /// <param name="mixinArray"></param> protected virtual void GenerateConstructorCode(ConstructorCodeBuilder codebuilder, Reference interceptorArg, Reference targetArgument, Reference mixinArray) { codebuilder.AddStatement(new AssignStatement( InterceptorField, interceptorArg.ToExpression())); int mixins = Context.MixinsAsArray().Length; codebuilder.AddStatement(new AssignStatement( MixinField, new NewArrayExpression(mixins, typeof(object)))); if (Context.HasMixins) { for(int i = 0; i < mixins; i++) { codebuilder.AddStatement(new AssignArrayStatement( MixinField, i, new LoadRefArrayElementExpression(i, mixinArray))); } } codebuilder.AddStatement(new AssignStatement( CacheField, new NewInstanceExpression( typeof(HybridDictionary).GetConstructor(new Type[0])))); // Initialize the delegate fields foreach(CallableField field in _cachedFields) { field.WriteInitialization(codebuilder, targetArgument, mixinArray); } } protected ConstructorInfo ObtainAvailableConstructor(Type target) { return target.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null); } /// <summary> /// /// </summary> /// <param name="interfaces"></param> protected void GenerateInterfaceImplementation(Type[] interfaces) { foreach(Type inter in interfaces) { GenerateTypeImplementation(inter, false); } } /// <summary> /// Iterates over the interfaces and generate implementation /// for each method in it. /// </summary> /// <param name="type">Type class</param> /// <param name="ignoreInterfaces">if true, we inspect the /// type for implemented interfaces</param> protected void GenerateTypeImplementation(Type type, bool ignoreInterfaces) { if (_generated.Contains(type)) return; if (Context.ShouldSkip(type)) return; _generated.Add(type); if (!ignoreInterfaces) { Type[] baseInterfaces = type.FindInterfaces(new TypeFilter(NoFilterImpl), type); GenerateInterfaceImplementation(baseInterfaces); } EasyProperty[] properties = GenerateProperties(type); GenerateMethods(type, properties); } protected virtual EasyProperty[] GenerateProperties(Type inter) { PropertyInfo[] properties = inter.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); EasyProperty[] propertiesBuilder = new EasyProperty[properties.Length]; for(int i = 0; i < properties.Length; i++) { propertiesBuilder[i] = CreateProperty(properties[i]); } return propertiesBuilder; } protected virtual void GenerateMethods(Type inter, EasyProperty[] properties) { MethodInfo[] methods = inter.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach(MethodInfo method in methods) { if (method.IsFinal) { Context.AddMethodToGenerateNewSlot(method); } if (method.IsPrivate || !method.IsVirtual || method.IsFinal) { continue; } #if DOTNET2 if (method.IsAssembly && !IsInternalToDynamicProxy(method.Module.Assembly)) #else if (method.IsAssembly && !IsInternalToDynamicProxy(inter.Assembly)) #endif { continue; } if (method.DeclaringType.Equals(typeof(Object)) && !method.IsVirtual) { continue; } if (method.DeclaringType.Equals(typeof(Object)) && "Finalize".Equals(method.Name)) { continue; } GenerateMethodImplementation(method, properties); } } /// <summary> /// Naive implementation, but valid for long namespaces /// Works by using only the last piece of the namespace /// </summary> protected String NormalizeNamespaceName(String nsName) { if (nsName == null || nsName == String.Empty) return String.Empty; String[] parts = nsName.Split('.', '+'); return parts[parts.Length - 1]; } /// <summary> /// Gets the name of a type, taking into consideration nested types. /// </summary> protected String GetTypeName(Type type) { System.Text.StringBuilder nameBuilder = new System.Text.StringBuilder(); if (type.Namespace != null) { nameBuilder.Append(type.Namespace.Replace('.', '_')); } if (type.DeclaringType != null) { nameBuilder.Append(type.DeclaringType.Name).Append("_"); } #if DOTNET2 if (type.IsGenericType) { Type[] args = type.GetGenericArguments(); foreach (Type arg in args) { string argName = GetTypeName(arg); nameBuilder.Append(argName).Append("_"); } } #endif if (type.IsArray) { nameBuilder.Append("ArrayOf").Append(GetTypeName(type.GetElementType())); } else { nameBuilder.Append(type.Name); } return nameBuilder.ToString(); } /// <summary> /// Generate property implementation /// </summary> /// <param name="property"></param> protected virtual EasyProperty CreateProperty(PropertyInfo property) { return _typeBuilder.CreateProperty(property); } /// <summary> /// Generates implementation for each method. /// </summary> /// <param name="method"></param> /// <param name="properties"></param> protected void GenerateMethodImplementation(MethodInfo method, EasyProperty[] properties) { if (Context.ShouldSkip(method)) return; ParameterInfo[] parametersInfo = method.GetParameters(); Type[] parameters = new Type[parametersInfo.Length]; for(int i = 0; i < parametersInfo.Length; i++) { parameters[i] = parametersInfo[i].ParameterType; } MethodAttributes atts = ObtainMethodAttributes(method); PreProcessMethod(method); EasyMethod easyMethod = null; bool isSetMethod = method.IsSpecialName && method.Name.StartsWith("set_"); bool isGetMethod = method.IsSpecialName && method.Name.StartsWith("get_"); if (!isSetMethod && !isGetMethod) { easyMethod = _typeBuilder.CreateMethod(method.Name, atts, new ReturnReferenceExpression(method.ReturnType), parameters); } else { if (isSetMethod || isGetMethod) { foreach(EasyProperty property in properties) { if (property == null) { break; } if (!property.Name.Equals(method.Name.Substring(4))) { continue; } if (property.IndexParameters != null) { bool signatureMatches = true; int numOfIndexes = parametersInfo.Length; //A set method already has a value parameter, and everything after //that is an indexer. if (isSetMethod) numOfIndexes--; if (numOfIndexes != property.IndexParameters.Length) continue; for(int i = 0; i < property.IndexParameters.Length; i++) { if (property.IndexParameters[i].ParameterType != parametersInfo[i].ParameterType) { signatureMatches = false; break; } } if (!signatureMatches) continue; } if (isSetMethod) { easyMethod = property.CreateSetMethod(atts, parameters); break; } else { easyMethod = property.CreateGetMethod(atts, parameters); break; } } } } easyMethod.DefineParameters(parametersInfo); WriteInterceptorInvocationMethod(method, easyMethod); PostProcessMethod(method); } private MethodAttributes ObtainMethodAttributes(MethodInfo method) { MethodAttributes atts; if (Context.ShouldCreateNewSlot(method)) atts = MethodAttributes.NewSlot; else atts = MethodAttributes.Virtual; if (method.IsPublic) { atts |= MethodAttributes.Public; } if (IsInternalToDynamicProxy(method.DeclaringType.Assembly) && method.IsAssembly) { atts |= MethodAttributes.Assembly; } if (method.IsHideBySig) { atts |= MethodAttributes.HideBySig; } if (method.IsFamilyAndAssembly) { atts |= MethodAttributes.FamANDAssem; } else if (method.IsFamilyOrAssembly) { atts |= MethodAttributes.FamORAssem; } else if (method.IsFamily) { atts |= MethodAttributes.Family; } if (method.Name.StartsWith("set_") || method.Name.StartsWith("get_")) { atts |= MethodAttributes.SpecialName; } return atts; } protected virtual void PreProcessMethod(MethodInfo method) { MethodInfo callbackMethod = GenerateCallbackMethodIfNecessary(method, null); EasyCallable callable = MainTypeBuilder.CreateCallable(method.ReturnType, method.GetParameters()); _method2Delegate[method] = callable; FieldReference field = MainTypeBuilder.CreateField( String.Format("_cached_{0}", callable.ID), callable.TypeBuilder); RegisterDelegateFieldToBeInitialized(method, field, callable, callbackMethod); } protected virtual MethodInfo GenerateCallbackMethodIfNecessary(MethodInfo method, Reference invocationTarget) { if (Context.HasMixins && _interface2mixinIndex.Contains(method.DeclaringType)) { return method; } String name = String.Format("callback__{0}", method.Name); ParameterInfo[] parameters = method.GetParameters(); ArgumentReference[] args = new ArgumentReference[parameters.Length]; for(int i = 0; i < args.Length; i++) { args[i] = new ArgumentReference(parameters[i].ParameterType); } EasyMethod easymethod = MainTypeBuilder.CreateMethod(name, new ReturnReferenceExpression(method.ReturnType), MethodAttributes.HideBySig | MethodAttributes.Public, args); Expression[] exps = new Expression[parameters.Length]; for(int i = 0; i < args.Length; i++) { exps[i] = args[i].ToExpression(); } if (invocationTarget == null) { easymethod.CodeBuilder.AddStatement( new ReturnStatement( new MethodInvocationExpression(method, exps))); } else { easymethod.CodeBuilder.AddStatement( new ReturnStatement( new MethodInvocationExpression(invocationTarget, method, exps))); } return easymethod.MethodBuilder; } protected virtual void PostProcessMethod(MethodInfo method) { } /// <summary> /// Writes the method implementation. This /// method generates the IL code for property get/set method and /// ordinary methods. /// </summary> /// <param name="method">The method to implement.</param> /// <param name="builder"><see cref="EasyMethod"/> being constructed.</param> protected virtual void WriteInterceptorInvocationMethod(MethodInfo method, EasyMethod builder) { ArgumentReference[] arguments = builder.Arguments; TypeReference[] dereferencedArguments = IndirectReference.WrapIfByRef(builder.Arguments); LocalReference local_inv = builder.CodeBuilder.DeclareLocal(Context.Invocation); EasyCallable callable = _method2Delegate[method] as EasyCallable; FieldReference fieldDelegate = ObtainCallableFieldBuilderDelegate(callable); builder.CodeBuilder.AddStatement( new AssignStatement(local_inv, new MethodInvocationExpression(_method2Invocation, fieldDelegate.ToExpression(), new MethodTokenExpression(GetCorrectMethod(method)), GetPseudoInvocationTarget(method)))); LocalReference ret_local = builder.CodeBuilder.DeclareLocal(typeof(object)); LocalReference args_local = builder.CodeBuilder.DeclareLocal(typeof(object[])); // Store arguments into an object array. builder.CodeBuilder.AddStatement( new AssignStatement(args_local, new ReferencesToObjectArrayExpression(dereferencedArguments))); // Invoke the interceptor. builder.CodeBuilder.AddStatement( new AssignStatement(ret_local, new VirtualMethodInvocationExpression(InterceptorField, Context.Interceptor.GetMethod("Intercept"), local_inv.ToExpression(), args_local.ToExpression()))); // Load possibly modified ByRef arguments from the array. for(int i = 0; i < arguments.Length; i++) { if (arguments[i].Type.IsByRef) { builder.CodeBuilder.AddStatement( new AssignStatement(dereferencedArguments[i], new ConvertExpression(dereferencedArguments[i].Type, new LoadRefArrayElementExpression(i, args_local)))); } } if (builder.ReturnType == typeof(void)) { builder.CodeBuilder.AddStatement(new ReturnStatement()); } else { builder.CodeBuilder.AddStatement(new ReturnStatement( new ConvertExpression(builder.ReturnType, ret_local.ToExpression()))); } } protected virtual Expression GetPseudoInvocationTarget(MethodInfo method) { return NullExpression.Instance; } protected virtual MethodInfo GetCorrectMethod(MethodInfo method) { return method; } protected Type[] InspectAndRegisterInterfaces(object[] mixins) { if (mixins == null) return new Type[0]; Set interfaces = new Set(); for(int i = 0; i < mixins.Length; ++i) { object mixin = mixins[i]; Type[] mixinInterfaces = mixin.GetType().GetInterfaces(); mixinInterfaces = Filter(mixinInterfaces); interfaces.AddArray(mixinInterfaces); // Later we gonna need to say which mixin // handle the method of a specific interface foreach(Type inter in mixinInterfaces) { _interface2mixinIndex.Add(inter, i); } } return (Type[]) interfaces.ToArray(typeof(Type)); } protected Type[] Filter(Type[] mixinInterfaces) { ArrayList retType = new ArrayList(); foreach(Type type in mixinInterfaces) { if (!Context.ShouldSkip(type)) retType.Add(type); } return (Type[]) retType.ToArray(typeof(Type)); } public static bool NoFilterImpl(Type type, object criteria) { return true; } protected bool IsInternalToDynamicProxy(Assembly asm) { #if DOTNET2 internalsToDynProxyLock.AcquireReaderLock(-1); if (internalsToDynProxy.ContainsKey(asm)) { internalsToDynProxyLock.ReleaseReaderLock(); return internalsToDynProxy[asm]; } internalsToDynProxyLock.UpgradeToWriterLock(-1); try { if (internalsToDynProxy.ContainsKey(asm)) { return internalsToDynProxy[asm]; } InternalsVisibleToAttribute[] atts = (InternalsVisibleToAttribute[]) asm.GetCustomAttributes(typeof(InternalsVisibleToAttribute), false); bool found = false; foreach(InternalsVisibleToAttribute internals in atts) { if (internals.AssemblyName.Contains(ModuleScope.ASSEMBLY_NAME)) { found = true; break; } } internalsToDynProxy.Add(asm, found); return found; } finally { internalsToDynProxyLock.ReleaseWriterLock(); } #else return false; #endif } } /// <summary> /// /// </summary> internal class CallableField { private FieldReference _field; private EasyCallable _callable; private MethodInfo _callback; private int _sourceArgIndex; public CallableField(FieldReference field, EasyCallable callable, MethodInfo callback, int sourceArgIndex) { _field = field; _callable = callable; _callback = callback; _sourceArgIndex = sourceArgIndex; } public FieldReference Field { get { return _field; } } public EasyCallable Callable { get { return _callable; } } public int SourceArgIndex { get { return _sourceArgIndex; } } public void WriteInitialization(AbstractCodeBuilder codebuilder, Reference targetArgument, Reference mixinArray) { NewInstanceExpression newInst = null; if (SourceArgIndex == EmptyIndex) { newInst = new NewInstanceExpression(Callable, targetArgument.ToExpression(), new MethodPointerExpression(_callback)); } else { newInst = new NewInstanceExpression(Callable, new LoadRefArrayElementExpression(SourceArgIndex, mixinArray), new MethodPointerExpression(_callback)); } codebuilder.AddStatement(new AssignStatement( Field, newInst)); } public static int EmptyIndex { get { return -1; } } } }
//L // 2007 - 2013 Copyright Northwestern University // // Distributed under the OSI-approved BSD 3-Clause License. // See http://ncip.github.com/annotation-and-image-markup/LICENSE.txt for details. //L namespace AIM.Annotation.View.WinForms { partial class FormUserInfo { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this._btnSave = new System.Windows.Forms.Button(); this._btnCancel = new System.Windows.Forms.Button(); this._lblUserName = new System.Windows.Forms.Label(); this._lblLoginName = new System.Windows.Forms.Label(); this._lblRoleInTrial = new System.Windows.Forms.Label(); this._lblNumberWithinRoleInTrial = new System.Windows.Forms.Label(); this._tboxUserName = new System.Windows.Forms.TextBox(); this._tboxLoginName = new System.Windows.Forms.TextBox(); this._updownNumberWithinRoleInTrial = new System.Windows.Forms.NumericUpDown(); this._cmbRoleInTrial = new System.Windows.Forms.ComboBox(); ((System.ComponentModel.ISupportInitialize)(this._updownNumberWithinRoleInTrial)).BeginInit(); this.SuspendLayout(); // // _btnSave // this._btnSave.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this._btnSave.DialogResult = System.Windows.Forms.DialogResult.OK; this._btnSave.Location = new System.Drawing.Point(275, 150); this._btnSave.Name = "_btnSave"; this._btnSave.Size = new System.Drawing.Size(75, 23); this._btnSave.TabIndex = 8; this._btnSave.Text = "&Save"; this._btnSave.UseVisualStyleBackColor = true; this._btnSave.Click += new System.EventHandler(this.btnSave_Click); // // _btnCancel // this._btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this._btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this._btnCancel.Location = new System.Drawing.Point(356, 150); this._btnCancel.Name = "_btnCancel"; this._btnCancel.Size = new System.Drawing.Size(75, 23); this._btnCancel.TabIndex = 9; this._btnCancel.Text = "&Cancel"; this._btnCancel.UseVisualStyleBackColor = true; this._btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // _lblUserName // this._lblUserName.AutoSize = true; this._lblUserName.Location = new System.Drawing.Point(12, 16); this._lblUserName.Name = "_lblUserName"; this._lblUserName.Size = new System.Drawing.Size(88, 17); this._lblUserName.TabIndex = 0; this._lblUserName.Text = "User Name*:"; this._lblUserName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // _lblLoginName // this._lblLoginName.AutoSize = true; this._lblLoginName.Location = new System.Drawing.Point(12, 45); this._lblLoginName.Name = "_lblLoginName"; this._lblLoginName.Size = new System.Drawing.Size(93, 17); this._lblLoginName.TabIndex = 2; this._lblLoginName.Text = "Login Name*:"; // // _lblRoleInTrial // this._lblRoleInTrial.AutoSize = true; this._lblRoleInTrial.Location = new System.Drawing.Point(12, 74); this._lblRoleInTrial.Name = "_lblRoleInTrial"; this._lblRoleInTrial.Size = new System.Drawing.Size(88, 17); this._lblRoleInTrial.TabIndex = 4; this._lblRoleInTrial.Text = "Role In Trial:"; // // _lblNumberWithinRoleInTrial // this._lblNumberWithinRoleInTrial.AutoSize = true; this._lblNumberWithinRoleInTrial.Location = new System.Drawing.Point(12, 104); this._lblNumberWithinRoleInTrial.Name = "_lblNumberWithinRoleInTrial"; this._lblNumberWithinRoleInTrial.Size = new System.Drawing.Size(138, 17); this._lblNumberWithinRoleInTrial.TabIndex = 6; this._lblNumberWithinRoleInTrial.Text = "Number Within Role:"; // // _tboxUserName // this._tboxUserName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._tboxUserName.Location = new System.Drawing.Point(158, 13); this._tboxUserName.Name = "_tboxUserName"; this._tboxUserName.Size = new System.Drawing.Size(270, 22); this._tboxUserName.TabIndex = 1; // // _tboxLoginName // this._tboxLoginName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._tboxLoginName.Location = new System.Drawing.Point(158, 42); this._tboxLoginName.Name = "_tboxLoginName"; this._tboxLoginName.Size = new System.Drawing.Size(270, 22); this._tboxLoginName.TabIndex = 3; // // _updownNumberWithinRoleInTrial // this._updownNumberWithinRoleInTrial.Location = new System.Drawing.Point(158, 99); this._updownNumberWithinRoleInTrial.Maximum = new decimal(new int[] { 5000, 0, 0, 0}); this._updownNumberWithinRoleInTrial.Minimum = new decimal(new int[] { 1, 0, 0, -2147483648}); this._updownNumberWithinRoleInTrial.Name = "_updownNumberWithinRoleInTrial"; this._updownNumberWithinRoleInTrial.Size = new System.Drawing.Size(87, 22); this._updownNumberWithinRoleInTrial.TabIndex = 7; this._updownNumberWithinRoleInTrial.Value = new decimal(new int[] { 1, 0, 0, -2147483648}); // // _cmbRoleInTrial // this._cmbRoleInTrial.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._cmbRoleInTrial.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this._cmbRoleInTrial.FormattingEnabled = true; this._cmbRoleInTrial.Items.AddRange(new object[] { "<Select Role>", "Performing", "Referring", "Requesting", "Recording", "Verifying", "Assisting", "Circulating", "Standby"}); this._cmbRoleInTrial.Location = new System.Drawing.Point(158, 70); this._cmbRoleInTrial.Name = "_cmbRoleInTrial"; this._cmbRoleInTrial.Size = new System.Drawing.Size(270, 24); this._cmbRoleInTrial.TabIndex = 5; // // FormUserInfo // this.AcceptButton = this._btnSave; this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this._btnCancel; this.ClientSize = new System.Drawing.Size(443, 185); this.Controls.Add(this._cmbRoleInTrial); this.Controls.Add(this._updownNumberWithinRoleInTrial); this.Controls.Add(this._tboxLoginName); this.Controls.Add(this._tboxUserName); this.Controls.Add(this._lblNumberWithinRoleInTrial); this.Controls.Add(this._lblRoleInTrial); this.Controls.Add(this._lblLoginName); this.Controls.Add(this._lblUserName); this.Controls.Add(this._btnCancel); this.Controls.Add(this._btnSave); this.MaximizeBox = false; this.MinimizeBox = false; this.MinimumSize = new System.Drawing.Size(451, 224); this.Name = "FormUserInfo"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "AIM User Information"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FormUserInfo_FormClosing); ((System.ComponentModel.ISupportInitialize)(this._updownNumberWithinRoleInTrial)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button _btnSave; private System.Windows.Forms.Button _btnCancel; private System.Windows.Forms.Label _lblUserName; private System.Windows.Forms.Label _lblLoginName; private System.Windows.Forms.Label _lblRoleInTrial; private System.Windows.Forms.Label _lblNumberWithinRoleInTrial; private System.Windows.Forms.TextBox _tboxUserName; private System.Windows.Forms.TextBox _tboxLoginName; private System.Windows.Forms.NumericUpDown _updownNumberWithinRoleInTrial; private System.Windows.Forms.ComboBox _cmbRoleInTrial; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Compute { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// VirtualMachinesOperations operations. /// </summary> public partial interface IVirtualMachinesOperations { /// <summary> /// Captures the VM by copying virtual hard disks of the VM and /// outputs a template that can be used to create similar VMs. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='parameters'> /// Parameters supplied to the Capture Virtual Machine operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<VirtualMachineCaptureResult>> CaptureWithHttpMessagesAsync(string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Captures the VM by copying virtual hard disks of the VM and /// outputs a template that can be used to create similar VMs. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='parameters'> /// Parameters supplied to the Capture Virtual Machine operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<VirtualMachineCaptureResult>> BeginCaptureWithHttpMessagesAsync(string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to create or update a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='parameters'> /// Parameters supplied to the Create Virtual Machine operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<VirtualMachine>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string vmName, VirtualMachine parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to create or update a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='parameters'> /// Parameters supplied to the Create Virtual Machine operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<VirtualMachine>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string vmName, VirtualMachine parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to delete a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to delete a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to get a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='expand'> /// The expand expression to apply on the operation. Possible values /// include: 'instanceView' /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<VirtualMachine>> GetWithHttpMessagesAsync(string resourceGroupName, string vmName, InstanceViewTypes? expand = default(InstanceViewTypes?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Shuts down the Virtual Machine and releases the compute resources. /// You are not billed for the compute resources that this Virtual /// Machine uses. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> DeallocateWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Shuts down the Virtual Machine and releases the compute resources. /// You are not billed for the compute resources that this Virtual /// Machine uses. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> BeginDeallocateWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Sets the state of the VM as Generalized. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> GeneralizeWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to list virtual machines under a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<VirtualMachine>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the list of Virtual Machines in the subscription. Use /// nextLink property in the response to get the next page of Virtual /// Machines. Do this till nextLink is not null to fetch all the /// Virtual Machines. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<VirtualMachine>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all available virtual machine sizes it can be resized to for /// a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IEnumerable<VirtualMachineSize>>> ListAvailableSizesWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to power off (stop) a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> PowerOffWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to power off (stop) a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> BeginPowerOffWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to restart a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> RestartWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to restart a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> BeginRestartWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to start a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> StartWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to start a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> BeginStartWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to redeploy a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> RedeployWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to redeploy a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> BeginRedeployWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to list virtual machines under a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<VirtualMachine>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the list of Virtual Machines in the subscription. Use /// nextLink property in the response to get the next page of Virtual /// Machines. Do this till nextLink is not null to fetch all the /// Virtual Machines. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<VirtualMachine>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Security; using System.Threading; using System.Threading.Tasks; namespace System.IO { /* * This class is used to access a contiguous block of memory, likely outside * the GC heap (or pinned in place in the GC heap, but a MemoryStream may * make more sense in those cases). It's great if you have a pointer and * a length for a section of memory mapped in by someone else and you don't * want to copy this into the GC heap. UnmanagedMemoryStream assumes these * two things: * * 1) All the memory in the specified block is readable or writable, * depending on the values you pass to the constructor. * 2) The lifetime of the block of memory is at least as long as the lifetime * of the UnmanagedMemoryStream. * 3) You clean up the memory when appropriate. The UnmanagedMemoryStream * currently will do NOTHING to free this memory. * 4) All calls to Write and WriteByte may not be threadsafe currently. * * It may become necessary to add in some sort of * DeallocationMode enum, specifying whether we unmap a section of memory, * call free, run a user-provided delegate to free the memory, etc etc. * We'll suggest user write a subclass of UnmanagedMemoryStream that uses * a SafeHandle subclass to hold onto the memory. * Check for problems when using this in the negative parts of a * process's address space. We may need to use unsigned longs internally * and change the overflow detection logic. * * -----SECURITY MODEL AND SILVERLIGHT----- * A few key notes about exposing UMS in silverlight: * 1. No ctors are exposed to transparent code. This version of UMS only * supports byte* (not SafeBuffer). Therefore, framework code can create * a UMS and hand it to transparent code. Transparent code can use most * operations on a UMS, but not operations that directly expose a * pointer. * * 2. Scope of "unsafe" and non-CLS compliant operations reduced: The * Whidbey version of this class has CLSCompliant(false) at the class * level and unsafe modifiers at the method level. These were reduced to * only where the unsafe operation is performed -- i.e. immediately * around the pointer manipulation. Note that this brings UMS in line * with recent changes in pu/clr to support SafeBuffer. * * 3. Currently, the only caller that creates a UMS is ResourceManager, * which creates read-only UMSs, and therefore operations that can * change the length will throw because write isn't supported. A * conservative option would be to formalize the concept that _only_ * read-only UMSs can be creates, and enforce this by making WriteX and * SetLength SecurityCritical. However, this is a violation of * security inheritance rules, so we must keep these safe. The * following notes make this acceptable for future use. * a. a race condition in WriteX that could have allowed a thread to * read from unzeroed memory was fixed * b. memory region cannot be expanded beyond _capacity; in other * words, a UMS creator is saying a writeable UMS is safe to * write to anywhere in the memory range up to _capacity, specified * in the ctor. Even if the caller doesn't specify a capacity, then * length is used as the capacity. */ /// <summary> /// Stream over a memory pointer or over a SafeBuffer /// </summary> public class UnmanagedMemoryStream : Stream { [System.Security.SecurityCritical] // auto-generated private SafeBuffer _buffer; [SecurityCritical] private unsafe byte* _mem; private long _length; private long _capacity; private long _position; private long _offset; private FileAccess _access; private bool _isOpen; private Task<Int32> _lastReadTask; // The last successful task returned from ReadAsync /// <summary> /// This code is copied from system\buffer.cs in mscorlib /// </summary> /// <param name="src"></param> /// <param name="len"></param> [System.Security.SecurityCritical] // auto-generated private unsafe static void ZeroMemory(byte* src, long len) { while (len-- > 0) *(src + len) = 0; } /// <summary> /// Creates a closed stream. /// </summary> // Needed for subclasses that need to map a file, etc. [System.Security.SecuritySafeCritical] // auto-generated protected UnmanagedMemoryStream() { unsafe { _mem = null; } _isOpen = false; } /// <summary> /// Creates a stream over a SafeBuffer. /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="length"></param> [System.Security.SecuritySafeCritical] // auto-generated public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length) { Initialize(buffer, offset, length, FileAccess.Read, false); } /// <summary> /// Creates a stream over a SafeBuffer. /// </summary> [System.Security.SecuritySafeCritical] // auto-generated public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access) { Initialize(buffer, offset, length, access, false); } /// <summary> /// Subclasses must call this method (or the other overload) to properly initialize all instance fields. /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="length"></param> /// <param name="access"></param> [System.Security.SecuritySafeCritical] // auto-generated protected void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access) { Initialize(buffer, offset, length, access, false); } [System.Security.SecurityCritical] // auto-generated private void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access, bool skipSecurityCheck) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum); } if (length < 0) { throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.ByteLength < (ulong)(offset + length)) { throw new ArgumentException(SR.Argument_InvalidSafeBufferOffLen); } if (access < FileAccess.Read || access > FileAccess.ReadWrite) { throw new ArgumentOutOfRangeException("access"); } Contract.EndContractBlock(); if (_isOpen) { throw new InvalidOperationException(SR.InvalidOperation_CalledTwice); } // check for wraparound unsafe { byte* pointer = null; try { buffer.AcquirePointer(ref pointer); if ((pointer + offset + length) < pointer) { throw new ArgumentException(SR.ArgumentOutOfRange_UnmanagedMemStreamWrapAround); } } finally { if (pointer != null) { buffer.ReleasePointer(); } } } _offset = offset; _buffer = buffer; _length = length; _capacity = length; _access = access; _isOpen = true; } /// <summary> /// Creates a stream over a byte*. /// </summary> [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public unsafe UnmanagedMemoryStream(byte* pointer, long length) { Initialize(pointer, length, length, FileAccess.Read, false); } /// <summary> /// Creates a stream over a byte*. /// </summary> [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access) { Initialize(pointer, length, capacity, access, false); } /// <summary> /// Subclasses must call this method (or the other overload) to properly initialize all instance fields. /// </summary> [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] protected unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access) { Initialize(pointer, length, capacity, access, false); } /// <summary> /// Subclasses must call this method (or the other overload) to properly initialize all instance fields. /// </summary> [System.Security.SecurityCritical] // auto-generated private unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access, bool skipSecurityCheck) { if (pointer == null) throw new ArgumentNullException("pointer"); if (length < 0 || capacity < 0) throw new ArgumentOutOfRangeException((length < 0) ? "length" : "capacity", SR.ArgumentOutOfRange_NeedNonNegNum); if (length > capacity) throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_LengthGreaterThanCapacity); Contract.EndContractBlock(); // Check for wraparound. if (((byte*)((long)pointer + capacity)) < pointer) throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_UnmanagedMemStreamWrapAround); if (access < FileAccess.Read || access > FileAccess.ReadWrite) throw new ArgumentOutOfRangeException("access", SR.ArgumentOutOfRange_Enum); if (_isOpen) throw new InvalidOperationException(SR.InvalidOperation_CalledTwice); _mem = pointer; _offset = 0; _length = length; _capacity = capacity; _access = access; _isOpen = true; } /// <summary> /// Returns true if the stream can be read; otherwise returns false. /// </summary> public override bool CanRead { [Pure] get { return _isOpen && (_access & FileAccess.Read) != 0; } } /// <summary> /// Returns true if the stream can seek; otherwise returns false. /// </summary> public override bool CanSeek { [Pure] get { return _isOpen; } } /// <summary> /// Returns true if the stream can be written to; otherwise returns false. /// </summary> public override bool CanWrite { [Pure] get { return _isOpen && (_access & FileAccess.Write) != 0; } } /// <summary> /// Closes the stream. The stream's memory needs to be dealt with separately. /// </summary> /// <param name="disposing"></param> [System.Security.SecuritySafeCritical] // auto-generated protected override void Dispose(bool disposing) { _isOpen = false; unsafe { _mem = null; } // Stream allocates WaitHandles for async calls. So for correctness // call base.Dispose(disposing) for better perf, avoiding waiting // for the finalizers to run on those types. base.Dispose(disposing); } /// <summary> /// Since it's a memory stream, this method does nothing. /// </summary> public override void Flush() { if (!_isOpen) throw Error.GetStreamIsClosed(); } /// <summary> /// Since it's a memory stream, this method does nothing specific. /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> public override Task FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); try { Flush(); return Task.CompletedTask; } catch (Exception ex) { return Task.FromException(ex); } } /// <summary> /// Number of bytes in the stream. /// </summary> public override long Length { get { if (!_isOpen) throw Error.GetStreamIsClosed(); return Interlocked.Read(ref _length); } } /// <summary> /// Number of bytes that can be written to the stream. /// </summary> public long Capacity { get { if (!_isOpen) throw Error.GetStreamIsClosed(); return _capacity; } } /// <summary> /// ReadByte will read byte at the Position in the stream /// </summary> public override long Position { get { if (!CanSeek) throw Error.GetStreamIsClosed(); Contract.EndContractBlock(); return Interlocked.Read(ref _position); } [System.Security.SecuritySafeCritical] // auto-generated set { if (value < 0) throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_NeedNonNegNum); if (!CanSeek) throw Error.GetStreamIsClosed(); Contract.EndContractBlock(); if (IntPtr.Size == 4) { unsafe { // On 32 bit process, ensure we don't wrap around. if (value > (long)Int32.MaxValue || _mem + value < _mem) throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_StreamLength); } } Interlocked.Exchange(ref _position, value); } } /// <summary> /// Pointer to memory at the current Position in the stream. /// </summary> [CLSCompliant(false)] public unsafe byte* PositionPointer { [System.Security.SecurityCritical] // auto-generated_required get { if (_buffer != null) throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer); if (!_isOpen) throw Error.GetStreamIsClosed(); // Use a temp to avoid a race long pos = Interlocked.Read(ref _position); if (pos > _capacity) throw new IndexOutOfRangeException(SR.IndexOutOfRange_UMSPosition); byte* ptr = _mem + pos; return ptr; } [System.Security.SecurityCritical] // auto-generated_required set { if (_buffer != null) throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer); if (!_isOpen) throw Error.GetStreamIsClosed(); if (value < _mem) throw new IOException(SR.IO_SeekBeforeBegin); Interlocked.Exchange(ref _position, value - _mem); } } /// <summary> /// Reads bytes from stream and puts them into the buffer /// </summary> /// <param name="buffer">Buffer to read the bytes to.</param> /// <param name="offset">Starting index in the buffer.</param> /// <param name="count">Maximum number of bytes to read.</param> /// <returns>Number of bytes actually read.</returns> [System.Security.SecuritySafeCritical] // auto-generated public override int Read([In, Out] byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // Keep this in sync with contract validation in ReadAsync if (!_isOpen) throw Error.GetStreamIsClosed(); if (!CanRead) throw Error.GetReadNotSupported(); // Use a local variable to avoid a race where another thread // changes our position after we decide we can read some bytes. long pos = Interlocked.Read(ref _position); long len = Interlocked.Read(ref _length); long n = len - pos; if (n > count) n = count; if (n <= 0) return 0; int nInt = (int)n; // Safe because n <= count, which is an Int32 if (nInt < 0) return 0; // _position could be beyond EOF Debug.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1. unsafe { fixed (byte* pBuffer = buffer) { if (_buffer != null) { byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); Buffer.MemoryCopy(source: pointer + pos + _offset, destination: pBuffer + offset, destinationSizeInBytes: nInt, sourceBytesToCopy: nInt); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } else { Buffer.MemoryCopy(source: _mem + pos, destination: pBuffer + offset, destinationSizeInBytes: nInt, sourceBytesToCopy: nInt); } } } Interlocked.Exchange(ref _position, pos + n); return nInt; } /// <summary> /// Reads bytes from stream and puts them into the buffer /// </summary> /// <param name="buffer">Buffer to read the bytes to.</param> /// <param name="offset">Starting index in the buffer.</param> /// <param name="count">Maximum number of bytes to read.</param> /// <param name="cancellationToken">Token that can be used to cancell this operation.</param> /// <returns>Task that can be used to access the number of bytes actually read.</returns> public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // contract validation copied from Read(...) if (cancellationToken.IsCancellationRequested) return Task.FromCanceled<Int32>(cancellationToken); try { Int32 n = Read(buffer, offset, count); Task<Int32> t = _lastReadTask; return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<Int32>(n)); } catch (Exception ex) { Debug.Assert(!(ex is OperationCanceledException)); return Task.FromException<Int32>(ex); } } /// <summary> /// Returns the byte at the stream current Position and advances the Position. /// </summary> /// <returns></returns> [System.Security.SecuritySafeCritical] // auto-generated public override int ReadByte() { if (!_isOpen) throw Error.GetStreamIsClosed(); if (!CanRead) throw Error.GetReadNotSupported(); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); if (pos >= len) return -1; Interlocked.Exchange(ref _position, pos + 1); int result; if (_buffer != null) { unsafe { byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); result = *(pointer + pos + _offset); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } else { unsafe { result = _mem[pos]; } } return result; } /// <summary> /// Advanced the Position to specifice location in the stream. /// </summary> /// <param name="offset">Offset from the loc parameter.</param> /// <param name="loc">Origin for the offset parameter.</param> /// <returns></returns> public override long Seek(long offset, SeekOrigin loc) { if (!_isOpen) throw Error.GetStreamIsClosed(); switch (loc) { case SeekOrigin.Begin: if (offset < 0) throw new IOException(SR.IO_SeekBeforeBegin); Interlocked.Exchange(ref _position, offset); break; case SeekOrigin.Current: long pos = Interlocked.Read(ref _position); if (offset + pos < 0) throw new IOException(SR.IO_SeekBeforeBegin); Interlocked.Exchange(ref _position, offset + pos); break; case SeekOrigin.End: long len = Interlocked.Read(ref _length); if (len + offset < 0) throw new IOException(SR.IO_SeekBeforeBegin); Interlocked.Exchange(ref _position, len + offset); break; default: throw new ArgumentException(SR.Argument_InvalidSeekOrigin); } long finalPos = Interlocked.Read(ref _position); Debug.Assert(finalPos >= 0, "_position >= 0"); return finalPos; } /// <summary> /// Sets the Length of the stream. /// </summary> /// <param name="value"></param> [System.Security.SecuritySafeCritical] // auto-generated public override void SetLength(long value) { if (value < 0) throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); if (_buffer != null) throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer); if (!_isOpen) throw Error.GetStreamIsClosed(); if (!CanWrite) throw Error.GetWriteNotSupported(); if (value > _capacity) throw new IOException(SR.IO_FixedCapacity); long pos = Interlocked.Read(ref _position); long len = Interlocked.Read(ref _length); if (value > len) { unsafe { ZeroMemory(_mem + len, value - len); } } Interlocked.Exchange(ref _length, value); if (pos > value) { Interlocked.Exchange(ref _position, value); } } /// <summary> /// Writes buffer into the stream /// </summary> /// <param name="buffer">Buffer that will be written.</param> /// <param name="offset">Starting index in the buffer.</param> /// <param name="count">Number of bytes to write.</param> [System.Security.SecuritySafeCritical] // auto-generated public override void Write(byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // Keep contract validation in sync with WriteAsync(..) if (!_isOpen) throw Error.GetStreamIsClosed(); if (!CanWrite) throw Error.GetWriteNotSupported(); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); long n = pos + count; // Check for overflow if (n < 0) throw new IOException(SR.IO_StreamTooLong); if (n > _capacity) { throw new NotSupportedException(SR.IO_FixedCapacity); } if (_buffer == null) { // Check to see whether we are now expanding the stream and must // zero any memory in the middle. if (pos > len) { unsafe { ZeroMemory(_mem + len, pos - len); } } // set length after zeroing memory to avoid race condition of accessing unzeroed memory if (n > len) { Interlocked.Exchange(ref _length, n); } } unsafe { fixed (byte* pBuffer = buffer) { if (_buffer != null) { long bytesLeft = _capacity - pos; if (bytesLeft < count) { throw new ArgumentException(SR.Arg_BufferTooSmall); } byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); Buffer.MemoryCopy(source: pBuffer + offset, destination: pointer + pos + _offset, destinationSizeInBytes: count, sourceBytesToCopy: count); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } else { Buffer.MemoryCopy(source: pBuffer + offset, destination: _mem + pos, destinationSizeInBytes: count, sourceBytesToCopy: count); } } } Interlocked.Exchange(ref _position, n); return; } /// <summary> /// Writes buffer into the stream. The operation completes synchronously. /// </summary> /// <param name="buffer">Buffer that will be written.</param> /// <param name="offset">Starting index in the buffer.</param> /// <param name="count">Number of bytes to write.</param> /// <param name="cancellationToken">Token that can be used to cancell the operation.</param> /// <returns>Task that can be awaited </returns> public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // contract validation copied from Write(..) if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); try { Write(buffer, offset, count); return Task.CompletedTask; } catch (Exception ex) { Debug.Assert(!(ex is OperationCanceledException)); return Task.FromException(ex); } } /// <summary> /// Writes a byte to the stream and advances the current Position. /// </summary> /// <param name="value"></param> [System.Security.SecuritySafeCritical] // auto-generated public override void WriteByte(byte value) { if (!_isOpen) throw Error.GetStreamIsClosed(); if (!CanWrite) throw Error.GetWriteNotSupported(); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); long n = pos + 1; if (pos >= len) { // Check for overflow if (n < 0) throw new IOException(SR.IO_StreamTooLong); if (n > _capacity) throw new NotSupportedException(SR.IO_FixedCapacity); // Check to see whether we are now expanding the stream and must // zero any memory in the middle. // don't do if created from SafeBuffer if (_buffer == null) { if (pos > len) { unsafe { ZeroMemory(_mem + len, pos - len); } } // set length after zeroing memory to avoid race condition of accessing unzeroed memory Interlocked.Exchange(ref _length, n); } } if (_buffer != null) { unsafe { byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); *(pointer + pos + _offset) = value; } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } else { unsafe { _mem[pos] = value; } } Interlocked.Exchange(ref _position, n); } } }
/* | Version 10.1.84 | Copyright 2013 Esri | | Licensed under the Apache License, Version 2.0 (the "License"); | you may not use this file except in compliance with the License. | You may obtain a copy of the License at | | http://www.apache.org/licenses/LICENSE-2.0 | | Unless required by applicable law or agreed to in writing, software | distributed under the License is distributed on an "AS IS" BASIS, | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | See the License for the specific language governing permissions and | limitations under the License. */ using System; using System.Diagnostics; using System.ComponentModel; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Collections.ObjectModel; using System.Data.Objects.DataClasses; namespace ESRI.ArcLogistics.Data { /// <summary> /// RelationObjectCollection class. /// Represents a collection of data objects on the "many" end of a relationship. /// </summary> internal class RelationObjectCollection<T, TEntity> : IDataObjectCollection<T> where T : DataObject where TEntity : EntityObject { #region constructors /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Creates a new instance of RelationObjectCollection class. /// </summary> public RelationObjectCollection(EntityCollection<TEntity> entities, DataObject owner, bool isReadOnly) { Debug.Assert(entities != null); Debug.Assert(owner != null); if (owner.IsStored) { // load related objects if (!entities.IsLoaded) entities.Load(); } _entities = entities; _owner = owner; _isReadOnly = isReadOnly; // init data objects collection _FillCollection(); // attach to collection events _entities.AssociationChanged += new CollectionChangeEventHandler( _OnAssociationChanged); _dataObjects.CollectionChanged += new NotifyCollectionChangedEventHandler( _dataObjects_CollectionChanged); } #endregion constructors #region INotifyCollectionChanged members /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// public event NotifyCollectionChangedEventHandler CollectionChanged; #endregion INotifyCollectionChanged members #region public methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// public override string ToString() { return CollectionHelper.ToString(this as IList<T>); } #endregion public methods #region IDisposable interface members /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// public void Dispose() { if (_entities != null) { _entities.AssociationChanged -= new CollectionChangeEventHandler( _OnAssociationChanged); } if (_dataObjects != null) { _dataObjects.CollectionChanged -= new NotifyCollectionChangedEventHandler( _dataObjects_CollectionChanged); } } #endregion IDisposable interface members #region IList<T> interface members /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Default accessor for the collection. /// </summary> public T this[int index] { get { return (T)_dataObjects[index]; } set { throw new InvalidOperationException(); } } /// <summary> /// Number of elements in the collection. /// </summary> public int Count { get { return _dataObjects.Count; } } /// <summary> /// Adds data object to the collection. /// </summary> public virtual void Add(T dataObject) { if (dataObject == null) throw new ArgumentNullException(); _CheckReadOnlyFlag(); _entities.Add(DataObjectHelper.GetEntityObject( dataObject) as TEntity); } /// <summary> /// Removes data object from the collection. /// </summary> public virtual bool Remove(T dataObject) { if (dataObject == null) throw new ArgumentNullException(); _CheckReadOnlyFlag(); return _entities.Remove(DataObjectHelper.GetEntityObject( dataObject) as TEntity); } /// <summary> /// Clear the collection of all it's elements. /// </summary> public virtual void Clear() { _CheckReadOnlyFlag(); _entities.Clear(); // explicitly clear collection _dataObjects.Clear(); } /// <summary> /// Returns boolean value based on whether or not it finds the /// requested object in the collection. /// </summary> public bool Contains(T dataObject) { if (dataObject == null) throw new ArgumentNullException(); return _dataObjects.Contains(dataObject); } /// <summary> /// Copies objects from this collection into another array. /// </summary> public void CopyTo(T[] dataObjectArray, int index) { _dataObjects.CopyTo(dataObjectArray, index); } /// <summary> /// Returns custom generic enumerator for this collection. /// </summary> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return _dataObjects.GetEnumerator(); } /// <summary> /// Explicit non-generic interface implementation for IEnumerable /// extended and required by ICollection (implemented by ICollection<T>). /// </summary> IEnumerator IEnumerable.GetEnumerator() { return _dataObjects.GetEnumerator(); } /// <summary> /// Returns a boolean value indicating whether the collection is /// read-only. /// </summary> public bool IsReadOnly { get { return _isReadOnly; } } public int IndexOf(T item) { return _dataObjects.IndexOf(item); } public void Insert(int index, T item) { throw new InvalidOperationException(); } public void RemoveAt(int index) { if (index < 0 || index >= _dataObjects.Count) throw new ArgumentException(); Remove(_dataObjects[index]); } #endregion IList<T> interface members #region protected properties /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// protected ObservableCollection<T> DataObjects { get { return _dataObjects; } } #endregion protected properties #region protected methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// protected DataObject _Owner { get { return _owner; } } protected bool GetObjectContext(out DataObjectContext context) { context = null; bool res = false; if (_owner.IsStored) { context = ContextHelper.GetObjectContext(_entities); res = true; } return res; } #endregion protected methods #region private methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// private void _dataObjects_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (CollectionChanged != null) CollectionChanged(this, e); } private void _OnAssociationChanged(object sender, CollectionChangeEventArgs e) { EntityObject entity = e.Element as EntityObject; if (entity != null) { if (e.Action == CollectionChangeAction.Add) { // add item // TODO: check if sender is underlying collection T obj = _FindObject(entity); if (obj == null) _dataObjects.Add(_GetDataObject(entity)); } else if (e.Action == CollectionChangeAction.Remove) { // remove item T obj = _FindObject(entity); if (obj != null) _dataObjects.Remove(obj); } else if (e.Action == CollectionChangeAction.Refresh) { // TODO: cannot reset collection here since underlying collection is not yet updated } } } private void _FillCollection() { foreach (TEntity entity in _entities) _dataObjects.Add(_GetDataObject(entity)); } private void _CheckReadOnlyFlag() { if (_isReadOnly) { throw new InvalidOperationException( Properties.Messages.Error_ReadOnlyCollectionChange); } } private T _FindObject(EntityObject entity) { T res = null; foreach (T obj in _dataObjects) { IRawDataAccess dataAccess = obj as IRawDataAccess; if (dataAccess != null) { if (dataAccess.RawEntity.Equals(entity)) { res = obj; break; } } } return res; } private T _GetDataObject(EntityObject entity) { T obj = null; if (_owner.IsStored) { // Try to find data object through IWrapDataAccess. obj = DataObjectHelper.GetDataObject(entity) as T; if (obj == null) { DataObjectContext ctx = ContextHelper.GetObjectContext( _entities); obj = DataObjectHelper.GetOrCreateDataObject<T>(ctx, entity); } } else { obj = DataObjectHelper.GetDataObject(entity) as T; if (obj == null) throw new DataException(Properties.Messages.Error_InvalidDataObjectInstance); } return obj; } #endregion private methods #region private members /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// private ObservableCollection<T> _dataObjects = new ObservableCollection<T>(); private EntityCollection<TEntity> _entities; private DataObject _owner; private bool _isReadOnly = false; #endregion private members } }
namespace Cronofy.Test.CronofyAccountClientTests { using System; using NUnit.Framework; internal sealed class Availability : Base { [Test] public void CanPerformAvailabilityQuery() { const string requestBody = @" { ""participants"": [ { ""members"": [ { ""sub"": ""acc_567236000909002"" }, { ""sub"": ""acc_678347111010113"" } ], ""required"": ""all"" } ], ""required_duration"": { ""minutes"": 60 }, ""available_periods"": [ { ""start"": ""2017-01-03 09:00:00Z"", ""end"": ""2017-01-03 18:00:00Z"" }, { ""start"": ""2017-01-04 09:00:00Z"", ""end"": ""2017-01-04 18:00:00Z"" } ] }"; var builder = new AvailabilityRequestBuilder() .RequiredDuration(60) .AddAvailablePeriod( new DateTimeOffset(2017, 1, 3, 9, 0, 0, TimeSpan.Zero), new DateTimeOffset(2017, 1, 3, 18, 0, 0, TimeSpan.Zero)) .AddAvailablePeriod( new DateTimeOffset(2017, 1, 4, 9, 0, 0, TimeSpan.Zero), new DateTimeOffset(2017, 1, 4, 18, 0, 0, TimeSpan.Zero)) .AddRequiredParticipant("acc_567236000909002") .AddRequiredParticipant("acc_678347111010113"); const string responseBody = @" { ""available_periods"": [ { ""start"": ""2017-01-03T09:00:00Z"", ""end"": ""2017-01-03T11:00:00Z"", ""participants"": [ { ""sub"": ""acc_567236000909002"" }, { ""sub"": ""acc_678347111010113"" } ] }, { ""start"": ""2017-01-03T14:00:00Z"", ""end"": ""2017-01-03T16:00:00Z"", ""participants"": [ { ""sub"": ""acc_567236000909002"" }, { ""sub"": ""acc_678347111010113"" } ] }, { ""start"": ""2017-01-04T11:00:00Z"", ""end"": ""2017-01-04T17:00:00Z"", ""participants"": [ { ""sub"": ""acc_567236000909002"" }, { ""sub"": ""acc_678347111010113"" } ] }, ] }"; this.Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/availability") .RequestHeader("Authorization", "Bearer " + AccessToken) .JsonRequest(requestBody) .ResponseCode(200) .ResponseBody(responseBody)); var availability = this.Client.GetAvailability(builder); var expected = new[] { new AvailablePeriod { Start = new DateTimeOffset(2017, 1, 3, 9, 0, 0, TimeSpan.Zero), End = new DateTimeOffset(2017, 1, 3, 11, 0, 0, TimeSpan.Zero), Participants = new[] { new AvailablePeriod.Participant { Sub = "acc_567236000909002" }, new AvailablePeriod.Participant { Sub = "acc_678347111010113" }, }, }, new AvailablePeriod { Start = new DateTimeOffset(2017, 1, 3, 14, 0, 0, TimeSpan.Zero), End = new DateTimeOffset(2017, 1, 3, 16, 0, 0, TimeSpan.Zero), Participants = new[] { new AvailablePeriod.Participant { Sub = "acc_567236000909002" }, new AvailablePeriod.Participant { Sub = "acc_678347111010113" }, }, }, new AvailablePeriod { Start = new DateTimeOffset(2017, 1, 4, 11, 0, 0, TimeSpan.Zero), End = new DateTimeOffset(2017, 1, 4, 17, 0, 0, TimeSpan.Zero), Participants = new[] { new AvailablePeriod.Participant { Sub = "acc_567236000909002" }, new AvailablePeriod.Participant { Sub = "acc_678347111010113" }, }, }, }; Assert.AreEqual(expected, availability); } [Test] public void CanPerformAvailabilityWithBuffersAndIntervalQuery() { const string requestBody = @" { ""participants"": [ { ""members"": [ { ""sub"": ""acc_567236000909002"" }, { ""sub"": ""acc_678347111010113"" } ], ""required"": ""all"" } ], ""required_duration"": { ""minutes"": 60 }, ""available_periods"": [ { ""start"": ""2017-01-03 09:00:00Z"", ""end"": ""2017-01-03 18:00:00Z"" } ], ""start_interval"":{ ""minutes"": 60 }, ""buffer"":{ ""before"":{ ""minimum"":{ ""minutes"": 30 } }, ""after"":{ ""minimum"":{ ""minutes"": 60 } } } }"; var builder = new AvailabilityRequestBuilder() .RequiredDuration(60) .StartInterval(60) .BeforeBuffer(30) .AfterBuffer(60) .AddAvailablePeriod( new DateTimeOffset(2017, 1, 3, 9, 0, 0, TimeSpan.Zero), new DateTimeOffset(2017, 1, 3, 18, 0, 0, TimeSpan.Zero)) .AddRequiredParticipant("acc_567236000909002") .AddRequiredParticipant("acc_678347111010113"); const string responseBody = @" { ""available_periods"": [ ] }"; this.Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/availability") .RequestHeader("Authorization", "Bearer " + AccessToken) .JsonRequest(requestBody) .ResponseCode(200) .ResponseBody(responseBody)); var availability = this.Client.GetAvailability(builder); Assert.IsEmpty(availability); } [Test] public void CanPerformComplexAvailabilityQuery() { const string requestBody = @" { ""participants"": [ { ""members"": [ { ""sub"": ""acc_567236000909002"" }, { ""sub"": ""acc_678347111010113"", ""available_periods"": [ { ""start"": ""2017-01-03 09:00:00Z"", ""end"": ""2017-01-03 12:00:00Z"" } ], ""calendar_ids"": [ ""cal_1234_5678"", ""cal_9876_5432"" ] } ], ""required"": ""all"" }, { ""members"": [ { ""sub"": ""acc_678910200909001"" }, { ""sub"": ""acc_879082061010114"" } ], ""required"": 1 } ], ""required_duration"": { ""minutes"": 60 }, ""available_periods"": [ { ""start"": ""2017-01-03 09:00:00Z"", ""end"": ""2017-01-03 18:00:00Z"" } ] }"; var member = new AvailabilityMemberBuilder() .Sub("acc_678347111010113") .AddAvailablePeriod( new DateTimeOffset(2017, 1, 3, 9, 0, 0, TimeSpan.Zero), new DateTimeOffset(2017, 1, 3, 12, 0, 0, TimeSpan.Zero)) .CalendarIds(new[] { "cal_1234_5678", "cal_9876_5432" }); var requiredGroup = new ParticipantGroupBuilder() .AddMember("acc_567236000909002") .AddMember(member) .AllRequired(); var representedGroup = new ParticipantGroupBuilder() .AddMember("acc_678910200909001") .AddMember("acc_879082061010114") .Required(1); var builder = new AvailabilityRequestBuilder() .RequiredDuration(60) .AddAvailablePeriod( new DateTimeOffset(2017, 1, 3, 9, 0, 0, TimeSpan.Zero), new DateTimeOffset(2017, 1, 3, 18, 0, 0, TimeSpan.Zero)) .AddParticipantGroup(requiredGroup) .AddParticipantGroup(representedGroup); const string responseBody = @" { ""available_periods"": [ { ""start"": ""2017-01-03T09:00:00Z"", ""end"": ""2017-01-03T11:00:00Z"", ""participants"": [ { ""sub"": ""acc_567236000909002"" }, { ""sub"": ""acc_678347111010113"" }, { ""sub"": ""acc_6789010200909001"" } ] } ] }"; this.Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/availability") .RequestHeader("Authorization", "Bearer " + AccessToken) .JsonRequest(requestBody) .ResponseCode(200) .ResponseBody(responseBody)); var availability = this.Client.GetAvailability(builder); var expected = new[] { new AvailablePeriod { Start = new DateTimeOffset(2017, 1, 3, 9, 0, 0, TimeSpan.Zero), End = new DateTimeOffset(2017, 1, 3, 11, 0, 0, TimeSpan.Zero), Participants = new[] { new AvailablePeriod.Participant { Sub = "acc_567236000909002" }, new AvailablePeriod.Participant { Sub = "acc_678347111010113" }, new AvailablePeriod.Participant { Sub = "acc_6789010200909001" }, }, }, }; Assert.AreEqual(expected, availability); } [Test] public void CanPerformAvailabilityQueryWithManagedAvailability() { const string requestBody = @" { ""participants"": [ { ""members"": [ { ""sub"": ""acc_567236000909002"", ""managed_availability"": true, ""availability_rule_ids"": [""default""] }, { ""sub"": ""acc_678347111010113"", ""managed_availability"": true, ""availability_rule_ids"": [] } ], ""required"": ""all"" } ], ""required_duration"": { ""minutes"": 60 }, ""available_periods"": [ { ""start"": ""2017-01-03 09:00:00Z"", ""end"": ""2017-01-03 18:00:00Z"" }, { ""start"": ""2017-01-04 09:00:00Z"", ""end"": ""2017-01-04 18:00:00Z"" } ] }"; var builder = new AvailabilityRequestBuilder() .RequiredDuration(60) .AddAvailablePeriod( new DateTimeOffset(2017, 1, 3, 9, 0, 0, TimeSpan.Zero), new DateTimeOffset(2017, 1, 3, 18, 0, 0, TimeSpan.Zero)) .AddAvailablePeriod( new DateTimeOffset(2017, 1, 4, 9, 0, 0, TimeSpan.Zero), new DateTimeOffset(2017, 1, 4, 18, 0, 0, TimeSpan.Zero)) .AddParticipantGroup( new ParticipantGroupBuilder() .AllRequired() .AddMember(new AvailabilityMemberBuilder() .Sub("acc_567236000909002") .ManagedAvailability(true) .AvailabilityRuleIds(new[] { "default" })) .AddMember(new AvailabilityMemberBuilder() .Sub("acc_678347111010113") .ManagedAvailability(true) .AvailabilityRuleIds(new string[0]))); const string responseBody = @" { ""available_periods"": [ { ""start"": ""2017-01-03T09:00:00Z"", ""end"": ""2017-01-03T11:00:00Z"", ""participants"": [ { ""sub"": ""acc_567236000909002"" }, { ""sub"": ""acc_678347111010113"" } ] }, { ""start"": ""2017-01-03T14:00:00Z"", ""end"": ""2017-01-03T16:00:00Z"", ""participants"": [ { ""sub"": ""acc_567236000909002"" }, { ""sub"": ""acc_678347111010113"" } ] }, { ""start"": ""2017-01-04T11:00:00Z"", ""end"": ""2017-01-04T17:00:00Z"", ""participants"": [ { ""sub"": ""acc_567236000909002"" }, { ""sub"": ""acc_678347111010113"" } ] }, ] }"; this.Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/availability") .RequestHeader("Authorization", "Bearer " + AccessToken) .JsonRequest(requestBody) .ResponseCode(200) .ResponseBody(responseBody)); var availability = this.Client.GetAvailability(builder); var expected = new[] { new AvailablePeriod { Start = new DateTimeOffset(2017, 1, 3, 9, 0, 0, TimeSpan.Zero), End = new DateTimeOffset(2017, 1, 3, 11, 0, 0, TimeSpan.Zero), Participants = new[] { new AvailablePeriod.Participant { Sub = "acc_567236000909002" }, new AvailablePeriod.Participant { Sub = "acc_678347111010113" }, }, }, new AvailablePeriod { Start = new DateTimeOffset(2017, 1, 3, 14, 0, 0, TimeSpan.Zero), End = new DateTimeOffset(2017, 1, 3, 16, 0, 0, TimeSpan.Zero), Participants = new[] { new AvailablePeriod.Participant { Sub = "acc_567236000909002" }, new AvailablePeriod.Participant { Sub = "acc_678347111010113" }, }, }, new AvailablePeriod { Start = new DateTimeOffset(2017, 1, 4, 11, 0, 0, TimeSpan.Zero), End = new DateTimeOffset(2017, 1, 4, 17, 0, 0, TimeSpan.Zero), Participants = new[] { new AvailablePeriod.Participant { Sub = "acc_567236000909002" }, new AvailablePeriod.Participant { Sub = "acc_678347111010113" }, }, }, }; Assert.AreEqual(expected, availability); } } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.Globalization; using NUnit.Framework.Constraints; namespace NUnit.Framework.Internal { /// <summary> /// TextMessageWriter writes constraint descriptions and messages /// in displayable form as a text stream. It tailors the display /// of individual message components to form the standard message /// format of NUnit assertion failure messages. /// </summary> public class TextMessageWriter : MessageWriter { #region Message Formats and Constants private static readonly int DEFAULT_LINE_LENGTH = 78; // Prefixes used in all failure messages. All must be the same // length, which is held in the PrefixLength field. Should not // contain any tabs or newline characters. /// <summary> /// Prefix used for the expected value line of a message /// </summary> public static readonly string Pfx_Expected = " Expected: "; /// <summary> /// Prefix used for the actual value line of a message /// </summary> public static readonly string Pfx_Actual = " But was: "; /// <summary> /// Length of a message prefix /// </summary> public static readonly int PrefixLength = Pfx_Expected.Length; #endregion private int maxLineLength = DEFAULT_LINE_LENGTH; #region Constructors /// <summary> /// Construct a TextMessageWriter /// </summary> public TextMessageWriter() { } /// <summary> /// Construct a TextMessageWriter, specifying a user message /// and optional formatting arguments. /// </summary> /// <param name="userMessage"></param> /// <param name="args"></param> public TextMessageWriter(string userMessage, params object[] args) { if ( userMessage != null && userMessage != string.Empty) this.WriteMessageLine(userMessage, args); } #endregion #region Properties /// <summary> /// Gets or sets the maximum line length for this writer /// </summary> public override int MaxLineLength { get { return maxLineLength; } set { maxLineLength = value; } } #endregion #region Public Methods - High Level /// <summary> /// Method to write single line message with optional args, usually /// written to precede the general failure message, at a given /// indentation level. /// </summary> /// <param name="level">The indentation level of the message</param> /// <param name="message">The message to be written</param> /// <param name="args">Any arguments used in formatting the message</param> public override void WriteMessageLine(int level, string message, params object[] args) { if (message != null) { while (level-- >= 0) Write(" "); if (args != null && args.Length > 0) message = string.Format(message, args); WriteLine(MsgUtils.EscapeNullCharacters(message)); } } /// <summary> /// Display Expected and Actual lines for a constraint. This /// is called by MessageWriter's default implementation of /// WriteMessageTo and provides the generic two-line display. /// </summary> /// <param name="result">The result of the constraint that failed</param> public override void DisplayDifferences(ConstraintResult result) { WriteExpectedLine(result); WriteActualLine(result); } /// <summary> /// Display Expected and Actual lines for given _values. This /// method may be called by constraints that need more control over /// the display of actual and expected _values than is provided /// by the default implementation. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value causing the failure</param> public override void DisplayDifferences(object expected, object actual) { WriteExpectedLine(expected); WriteActualLine(actual); } /// <summary> /// Display Expected and Actual lines for given _values, including /// a tolerance value on the expected line. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value causing the failure</param> /// <param name="tolerance">The tolerance within which the test was made</param> public override void DisplayDifferences(object expected, object actual, Tolerance tolerance) { WriteExpectedLine(expected, tolerance); WriteActualLine(actual); } /// <summary> /// Display the expected and actual string _values on separate lines. /// If the mismatch parameter is >=0, an additional line is displayed /// line containing a caret that points to the mismatch point. /// </summary> /// <param name="expected">The expected string value</param> /// <param name="actual">The actual string value</param> /// <param name="mismatch">The point at which the strings don't match or -1</param> /// <param name="ignoreCase">If true, case is ignored in string comparisons</param> /// <param name="clipping">If true, clip the strings to fit the max line length</param> public override void DisplayStringDifferences(string expected, string actual, int mismatch, bool ignoreCase, bool clipping) { // Maximum string we can display without truncating int maxDisplayLength = MaxLineLength - PrefixLength // Allow for prefix - 2; // 2 quotation marks if ( clipping ) MsgUtils.ClipExpectedAndActual(ref expected, ref actual, maxDisplayLength, mismatch); expected = MsgUtils.EscapeControlChars(expected); actual = MsgUtils.EscapeControlChars(actual); // The mismatch position may have changed due to clipping or white space conversion mismatch = MsgUtils.FindMismatchPosition(expected, actual, 0, ignoreCase); Write( Pfx_Expected ); Write( MsgUtils.FormatValue(expected) ); if ( ignoreCase ) Write( ", ignoring case" ); WriteLine(); WriteActualLine( actual ); //DisplayDifferences(expected, actual); if (mismatch >= 0) WriteCaretLine(mismatch); } #endregion #region Public Methods - Low Level /// <summary> /// Writes the text for an actual value. /// </summary> /// <param name="actual">The actual value.</param> public override void WriteActualValue(object actual) { WriteValue(actual); } /// <summary> /// Writes the text for a generalized value. /// </summary> /// <param name="val">The value.</param> public override void WriteValue(object val) { Write(MsgUtils.FormatValue(val)); } /// <summary> /// Writes the text for a collection value, /// starting at a particular point, to a max length /// </summary> /// <param name="collection">The collection containing elements to write.</param> /// <param name="start">The starting point of the elements to write</param> /// <param name="max">The maximum number of elements to write</param> public override void WriteCollectionElements(IEnumerable collection, long start, int max) { Write(MsgUtils.FormatCollection(collection, start, max)); } #endregion #region Helper Methods /// <summary> /// Write the generic 'Expected' line for a constraint /// </summary> /// <param name="result">The constraint that failed</param> private void WriteExpectedLine(ConstraintResult result) { Write(Pfx_Expected); WriteLine(result.Description); } /// <summary> /// Write the generic 'Expected' line for a given value /// </summary> /// <param name="expected">The expected value</param> private void WriteExpectedLine(object expected) { WriteExpectedLine(expected, null); } /// <summary> /// Write the generic 'Expected' line for a given value /// and tolerance. /// </summary> /// <param name="expected">The expected value</param> /// <param name="tolerance">The tolerance within which the test was made</param> private void WriteExpectedLine(object expected, Tolerance tolerance) { Write(Pfx_Expected); Write(MsgUtils.FormatValue(expected)); if (tolerance != null && !tolerance.IsUnsetOrDefault) { Write(" +/- "); Write(MsgUtils.FormatValue(tolerance.Value)); if (tolerance.Mode != ToleranceMode.Linear) Write(" {0}", tolerance.Mode); } WriteLine(); } /// <summary> /// Write the generic 'Actual' line for a constraint /// </summary> /// <param name="result">The ConstraintResult for which the actual value is to be written</param> private void WriteActualLine(ConstraintResult result) { Write(Pfx_Actual); result.WriteActualValueTo(this); WriteLine(); //WriteLine(MsgUtils.FormatValue(result.ActualValue)); } /// <summary> /// Write the generic 'Actual' line for a given value /// </summary> /// <param name="actual">The actual value causing a failure</param> private void WriteActualLine(object actual) { Write(Pfx_Actual); WriteActualValue(actual); WriteLine(); } private void WriteCaretLine(int mismatch) { // We subtract 2 for the initial 2 blanks and add back 1 for the initial quote WriteLine(" {0}^", new string('-', PrefixLength + mismatch - 2 + 1)); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace AuthApp.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; using Microsoft.WindowsAzure; namespace Microsoft.Azure.Management.Automation { public static partial class ScheduleOperationsExtensions { /// <summary> /// Create a schedule. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IScheduleOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the create schedule operation. /// </param> /// <returns> /// The response model for the create schedule operation. /// </returns> public static ScheduleCreateResponse Create(this IScheduleOperations operations, string automationAccount, ScheduleCreateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IScheduleOperations)s).CreateAsync(automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create a schedule. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IScheduleOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the create schedule operation. /// </param> /// <returns> /// The response model for the create schedule operation. /// </returns> public static Task<ScheduleCreateResponse> CreateAsync(this IScheduleOperations operations, string automationAccount, ScheduleCreateParameters parameters) { return operations.CreateAsync(automationAccount, parameters, CancellationToken.None); } /// <summary> /// Delete the schedule identified by scheduleId. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IScheduleOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='scheduleId'> /// Required. The schedule id. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse Delete(this IScheduleOperations operations, string automationAccount, string scheduleId) { return Task.Factory.StartNew((object s) => { return ((IScheduleOperations)s).DeleteAsync(automationAccount, scheduleId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete the schedule identified by scheduleId. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IScheduleOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='scheduleId'> /// Required. The schedule id. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> DeleteAsync(this IScheduleOperations operations, string automationAccount, string scheduleId) { return operations.DeleteAsync(automationAccount, scheduleId, CancellationToken.None); } /// <summary> /// Retrieve the schedule identified by scheduleId. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IScheduleOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='scheduleId'> /// Required. The schedule id. /// </param> /// <returns> /// The response model for the get schedule operation. /// </returns> public static ScheduleGetResponse Get(this IScheduleOperations operations, string automationAccount, string scheduleId) { return Task.Factory.StartNew((object s) => { return ((IScheduleOperations)s).GetAsync(automationAccount, scheduleId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the schedule identified by scheduleId. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IScheduleOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='scheduleId'> /// Required. The schedule id. /// </param> /// <returns> /// The response model for the get schedule operation. /// </returns> public static Task<ScheduleGetResponse> GetAsync(this IScheduleOperations operations, string automationAccount, string scheduleId) { return operations.GetAsync(automationAccount, scheduleId, CancellationToken.None); } /// <summary> /// Retrieve a list of schedules for the given automation account. /// (see http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IScheduleOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='skipToken'> /// Optional. The skip token. /// </param> /// <returns> /// The response model for the list schedule operation. /// </returns> public static ScheduleListResponse List(this IScheduleOperations operations, string automationAccount, string skipToken) { return Task.Factory.StartNew((object s) => { return ((IScheduleOperations)s).ListAsync(automationAccount, skipToken); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of schedules for the given automation account. /// (see http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IScheduleOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='skipToken'> /// Optional. The skip token. /// </param> /// <returns> /// The response model for the list schedule operation. /// </returns> public static Task<ScheduleListResponse> ListAsync(this IScheduleOperations operations, string automationAccount, string skipToken) { return operations.ListAsync(automationAccount, skipToken, CancellationToken.None); } /// <summary> /// Retrieve a list of one schedule identified by scheduleName. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IScheduleOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='scheduleName'> /// Required. The schedule name. /// </param> /// <returns> /// The response model for the list schedule operation. /// </returns> public static ScheduleListResponse ListByName(this IScheduleOperations operations, string automationAccount, string scheduleName) { return Task.Factory.StartNew((object s) => { return ((IScheduleOperations)s).ListByNameAsync(automationAccount, scheduleName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of one schedule identified by scheduleName. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IScheduleOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='scheduleName'> /// Required. The schedule name. /// </param> /// <returns> /// The response model for the list schedule operation. /// </returns> public static Task<ScheduleListResponse> ListByNameAsync(this IScheduleOperations operations, string automationAccount, string scheduleName) { return operations.ListByNameAsync(automationAccount, scheduleName, CancellationToken.None); } /// <summary> /// Update the schedule identified by scheduleId. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IScheduleOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the update schedule operation. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse Update(this IScheduleOperations operations, string automationAccount, ScheduleUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IScheduleOperations)s).UpdateAsync(automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Update the schedule identified by scheduleId. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IScheduleOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the update schedule operation. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> UpdateAsync(this IScheduleOperations operations, string automationAccount, ScheduleUpdateParameters parameters) { return operations.UpdateAsync(automationAccount, parameters, CancellationToken.None); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Internal.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime { // This is a set of stub methods implementing the support for the IReadOnlyDictionary`2 interface on WinRT // objects that support IMapView`2. Used by the interop mashaling infrastructure. // // The methods on this class must be written VERY carefully to avoid introducing security holes. // That's because they are invoked with special "this"! The "this" object // for all of these methods are not IMapViewToIReadOnlyDictionaryAdapter objects. Rather, they are of type // IMapView<K, V>. No actual IMapViewToIReadOnlyDictionaryAdapter object is ever instantiated. Thus, you will see // a lot of expressions that cast "this" to "IMapView<K, V>". [DebuggerDisplay("Count = {Count}")] internal sealed class IMapViewToIReadOnlyDictionaryAdapter { private IMapViewToIReadOnlyDictionaryAdapter() { Debug.Fail("This class is never instantiated"); } // V this[K key] { get } internal V Indexer_Get<K, V>(K key) { if (key == null) throw new ArgumentNullException(nameof(key)); IMapView<K, V> _this = Unsafe.As<IMapView<K, V>>(this); return Lookup(_this, key); } // IEnumerable<K> Keys { get } internal IEnumerable<K> Keys<K, V>() where K : notnull { IMapView<K, V> _this = Unsafe.As<IMapView<K, V>>(this); IReadOnlyDictionary<K, V> roDictionary = (IReadOnlyDictionary<K, V>)_this; return new ReadOnlyDictionaryKeyCollection<K, V>(roDictionary); } // IEnumerable<V> Values { get } internal IEnumerable<V> Values<K, V>() where K : notnull { IMapView<K, V> _this = Unsafe.As<IMapView<K, V>>(this); IReadOnlyDictionary<K, V> roDictionary = (IReadOnlyDictionary<K, V>)_this; return new ReadOnlyDictionaryValueCollection<K, V>(roDictionary); } // bool ContainsKey(K key) internal bool ContainsKey<K, V>(K key) where K : notnull { if (key == null) throw new ArgumentNullException(nameof(key)); IMapView<K, V> _this = Unsafe.As<IMapView<K, V>>(this); return _this.HasKey(key); } // bool TryGetValue(TKey key, out TValue value) internal bool TryGetValue<K, V>(K key, [MaybeNullWhen(false)] out V value) where K : notnull { if (key == null) throw new ArgumentNullException(nameof(key)); IMapView<K, V> _this = Unsafe.As<IMapView<K, V>>(this); // It may be faster to call HasKey then Lookup. On failure, we would otherwise // throw an exception from Lookup. if (!_this.HasKey(key)) { value = default!; return false; } try { value = _this.Lookup(key); return true; } catch (Exception ex) // Still may hit this case due to a race condition { if (HResults.E_BOUNDS == ex.HResult) { value = default!; return false; } throw; } } #region Helpers private static V Lookup<K, V>(IMapView<K, V> _this, K key) { Debug.Assert(null != key); try { return _this.Lookup(key); } catch (Exception ex) { if (HResults.E_BOUNDS == ex.HResult) throw new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())); throw; } } #endregion Helpers } // Note: One day we may make these return IReadOnlyCollection<T> [DebuggerDisplay("Count = {Count}")] internal sealed class ReadOnlyDictionaryKeyCollection<TKey, TValue> : IEnumerable<TKey> where TKey : notnull { private readonly IReadOnlyDictionary<TKey, TValue> dictionary; public ReadOnlyDictionaryKeyCollection(IReadOnlyDictionary<TKey, TValue> dictionary) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; } /* public void CopyTo(TKey[] array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); if (array.Length <= index && this.Count > 0) throw new ArgumentException(SR.Arg_IndexOutOfRangeException); if (array.Length - index < dictionary.Count) throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection); int i = index; foreach (KeyValuePair<TKey, TValue> mapping in dictionary) { array[i++] = mapping.Key; } } public int Count { get { return dictionary.Count; } } public bool Contains(TKey item) { return dictionary.ContainsKey(item); } */ IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<TKey>)this).GetEnumerator(); } public IEnumerator<TKey> GetEnumerator() { return new ReadOnlyDictionaryKeyEnumerator<TKey, TValue>(dictionary); } } // public class ReadOnlyDictionaryKeyCollection<TKey, TValue> internal sealed class ReadOnlyDictionaryKeyEnumerator<TKey, TValue> : IEnumerator<TKey> where TKey : notnull { private readonly IReadOnlyDictionary<TKey, TValue> dictionary; private IEnumerator<KeyValuePair<TKey, TValue>> enumeration; public ReadOnlyDictionaryKeyEnumerator(IReadOnlyDictionary<TKey, TValue> dictionary) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; enumeration = dictionary.GetEnumerator(); } void IDisposable.Dispose() { enumeration.Dispose(); } public bool MoveNext() { return enumeration.MoveNext(); } object? IEnumerator.Current => ((IEnumerator<TKey>)this).Current; public TKey Current => enumeration.Current.Key; public void Reset() { enumeration = dictionary.GetEnumerator(); } } // class ReadOnlyDictionaryKeyEnumerator<TKey, TValue> [DebuggerDisplay("Count = {Count}")] internal sealed class ReadOnlyDictionaryValueCollection<TKey, TValue> : IEnumerable<TValue> where TKey : notnull { private readonly IReadOnlyDictionary<TKey, TValue> dictionary; public ReadOnlyDictionaryValueCollection(IReadOnlyDictionary<TKey, TValue> dictionary) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; } /* public void CopyTo(TValue[] array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); if (array.Length <= index && this.Count > 0) throw new ArgumentException(SR.Arg_IndexOutOfRangeException); if (array.Length - index < dictionary.Count) throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection); int i = index; foreach (KeyValuePair<TKey, TValue> mapping in dictionary) { array[i++] = mapping.Value; } } public int Count { get { return dictionary.Count; } } public bool Contains(TValue item) { EqualityComparer<TValue> comparer = EqualityComparer<TValue>.Default; foreach (TValue value in this) if (comparer.Equals(item, value)) return true; return false; } */ IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<TValue>)this).GetEnumerator(); } public IEnumerator<TValue> GetEnumerator() { return new ReadOnlyDictionaryValueEnumerator<TKey, TValue>(dictionary); } } // public class ReadOnlyDictionaryValueCollection<TKey, TValue> internal sealed class ReadOnlyDictionaryValueEnumerator<TKey, TValue> : IEnumerator<TValue> where TKey : notnull { private readonly IReadOnlyDictionary<TKey, TValue> dictionary; private IEnumerator<KeyValuePair<TKey, TValue>> enumeration; public ReadOnlyDictionaryValueEnumerator(IReadOnlyDictionary<TKey, TValue> dictionary) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; enumeration = dictionary.GetEnumerator(); } void IDisposable.Dispose() { enumeration.Dispose(); } public bool MoveNext() { return enumeration.MoveNext(); } object? IEnumerator.Current => ((IEnumerator<TValue>)this).Current; public TValue Current => enumeration.Current.Value; public void Reset() { enumeration = dictionary.GetEnumerator(); } } // class ReadOnlyDictionaryValueEnumerator<TKey, TValue> }
// 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.IO; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.Security.Cryptography.Encryption.Tests.Asymmetric { public static class CryptoStreamTests { [Fact] public static void Ctor() { var transform = new IdentityTransform(1, 1, true); AssertExtensions.Throws<ArgumentException>(null, () => new CryptoStream(new MemoryStream(), transform, (CryptoStreamMode)12345)); AssertExtensions.Throws<ArgumentException>(null, "stream", () => new CryptoStream(new MemoryStream(new byte[0], writable: false), transform, CryptoStreamMode.Write)); AssertExtensions.Throws<ArgumentException>(null, "stream", () => new CryptoStream(new CryptoStream(new MemoryStream(new byte[0]), transform, CryptoStreamMode.Write), transform, CryptoStreamMode.Read)); } [Theory] [InlineData(64, 64, true)] [InlineData(64, 128, true)] [InlineData(128, 64, true)] [InlineData(1, 1, true)] [InlineData(37, 24, true)] [InlineData(128, 3, true)] [InlineData(8192, 64, true)] [InlineData(64, 64, false)] public static void Roundtrip(int inputBlockSize, int outputBlockSize, bool canTransformMultipleBlocks) { ICryptoTransform encryptor = new IdentityTransform(inputBlockSize, outputBlockSize, canTransformMultipleBlocks); ICryptoTransform decryptor = new IdentityTransform(inputBlockSize, outputBlockSize, canTransformMultipleBlocks); var stream = new MemoryStream(); using (CryptoStream encryptStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write)) { Assert.True(encryptStream.CanWrite); Assert.False(encryptStream.CanRead); Assert.False(encryptStream.CanSeek); Assert.False(encryptStream.HasFlushedFinalBlock); Assert.Throws<NotSupportedException>(() => encryptStream.SetLength(1)); Assert.Throws<NotSupportedException>(() => encryptStream.Length); Assert.Throws<NotSupportedException>(() => encryptStream.Position); Assert.Throws<NotSupportedException>(() => encryptStream.Position = 0); Assert.Throws<NotSupportedException>(() => encryptStream.Seek(0, SeekOrigin.Begin)); Assert.Throws<NotSupportedException>(() => encryptStream.Read(new byte[0], 0, 0)); Assert.Throws<NullReferenceException>(() => encryptStream.Write(null, 0, 0)); // No arg validation on buffer? Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], 0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], 0, -1)); AssertExtensions.Throws<ArgumentException>(null, () => encryptStream.Write(new byte[3], 1, 4)); byte[] toWrite = Encoding.UTF8.GetBytes(LoremText); // Write it all at once encryptStream.Write(toWrite, 0, toWrite.Length); Assert.False(encryptStream.HasFlushedFinalBlock); // Write in chunks encryptStream.Write(toWrite, 0, toWrite.Length / 2); encryptStream.Write(toWrite, toWrite.Length / 2, toWrite.Length - (toWrite.Length / 2)); Assert.False(encryptStream.HasFlushedFinalBlock); // Write one byte at a time for (int i = 0; i < toWrite.Length; i++) { encryptStream.WriteByte(toWrite[i]); } Assert.False(encryptStream.HasFlushedFinalBlock); // Write async encryptStream.WriteAsync(toWrite, 0, toWrite.Length).GetAwaiter().GetResult(); Assert.False(encryptStream.HasFlushedFinalBlock); // Flush (nops) encryptStream.Flush(); encryptStream.FlushAsync().GetAwaiter().GetResult(); encryptStream.FlushFinalBlock(); Assert.Throws<NotSupportedException>(() => encryptStream.FlushFinalBlock()); Assert.True(encryptStream.HasFlushedFinalBlock); Assert.True(stream.Length > 0); } // Read/decrypt using Read stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) { Assert.False(decryptStream.CanWrite); Assert.True(decryptStream.CanRead); Assert.False(decryptStream.CanSeek); Assert.False(decryptStream.HasFlushedFinalBlock); Assert.Throws<NotSupportedException>(() => decryptStream.SetLength(1)); Assert.Throws<NotSupportedException>(() => decryptStream.Length); Assert.Throws<NotSupportedException>(() => decryptStream.Position); Assert.Throws<NotSupportedException>(() => decryptStream.Position = 0); Assert.Throws<NotSupportedException>(() => decryptStream.Seek(0, SeekOrigin.Begin)); Assert.Throws<NotSupportedException>(() => decryptStream.Write(new byte[0], 0, 0)); Assert.Throws<NullReferenceException>(() => decryptStream.Read(null, 0, 0)); // No arg validation on buffer? Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], 0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], 0, -1)); AssertExtensions.Throws<ArgumentException>(null, () => decryptStream.Read(new byte[3], 1, 4)); using (StreamReader reader = new StreamReader(decryptStream)) { Assert.Equal( LoremText + LoremText + LoremText + LoremText, reader.ReadToEnd()); } } // Read/decrypt using ReadToEnd stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) using (StreamReader reader = new StreamReader(decryptStream)) { Assert.Equal( LoremText + LoremText + LoremText + LoremText, reader.ReadToEndAsync().GetAwaiter().GetResult()); } // Read/decrypt using a small buffer to force multiple calls to Read stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) using (StreamReader reader = new StreamReader(decryptStream, Encoding.UTF8, true, bufferSize: 10)) { Assert.Equal( LoremText + LoremText + LoremText + LoremText, reader.ReadToEndAsync().GetAwaiter().GetResult()); } // Read/decrypt one byte at a time with ReadByte stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) { string expectedStr = LoremText + LoremText + LoremText + LoremText; foreach (char c in expectedStr) { Assert.Equal(c, decryptStream.ReadByte()); // relies on LoremText being ASCII } Assert.Equal(-1, decryptStream.ReadByte()); } } [Fact] public static void NestedCryptoStreams() { ICryptoTransform encryptor = new IdentityTransform(1, 1, true); using (MemoryStream output = new MemoryStream()) using (CryptoStream encryptStream1 = new CryptoStream(output, encryptor, CryptoStreamMode.Write)) using (CryptoStream encryptStream2 = new CryptoStream(encryptStream1, encryptor, CryptoStreamMode.Write)) { encryptStream2.Write(new byte[] { 1, 2, 3, 4, 5 }, 0, 5); } } [Fact] public static void Clear() { ICryptoTransform encryptor = new IdentityTransform(1, 1, true); using (MemoryStream output = new MemoryStream()) using (CryptoStream encryptStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write)) { encryptStream.Clear(); Assert.Throws<NotSupportedException>(() => encryptStream.Write(new byte[] { 1, 2, 3, 4, 5 }, 0, 5)); } } [Fact] public static void FlushAsync() { ICryptoTransform encryptor = new IdentityTransform(1, 1, true); using (MemoryStream output = new MemoryStream()) using (CryptoStream encryptStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write)) { encryptStream.WriteAsync(new byte[] { 1, 2, 3, 4, 5 }, 0, 5); Task waitable = encryptStream.FlushAsync(new Threading.CancellationToken(false)); Assert.False(waitable.IsCanceled); encryptStream.WriteAsync(new byte[] { 1, 2, 3, 4, 5 }, 0, 5); waitable = encryptStream.FlushAsync(new Threading.CancellationToken(true)); Assert.True(waitable.IsCanceled); } } [Fact] public static void FlushCalledOnFlushAsync_DeriveClass() { ICryptoTransform encryptor = new IdentityTransform(1, 1, true); using (MemoryStream output = new MemoryStream()) using (MinimalCryptoStream encryptStream = new MinimalCryptoStream(output, encryptor, CryptoStreamMode.Write)) { encryptStream.WriteAsync(new byte[] { 1, 2, 3, 4, 5 }, 0, 5); Task waitable = encryptStream.FlushAsync(new Threading.CancellationToken(false)); Assert.False(waitable.IsCanceled); waitable.Wait(); Assert.True(encryptStream.FlushCalled); } } [Fact] public static void MultipleDispose() { ICryptoTransform encryptor = new IdentityTransform(1, 1, true); using (MemoryStream output = new MemoryStream()) { using (CryptoStream encryptStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write)) { encryptStream.Dispose(); } Assert.Equal(false, output.CanRead); } #if netcoreapp using (MemoryStream output = new MemoryStream()) { using (CryptoStream encryptStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write, leaveOpen: false)) { encryptStream.Dispose(); } Assert.Equal(false, output.CanRead); } using (MemoryStream output = new MemoryStream()) { using (CryptoStream encryptStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write, leaveOpen: true)) { encryptStream.Dispose(); } Assert.Equal(true, output.CanRead); } #endif } private const string LoremText = @"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci. Aenean nec lorem. In porttitor. Donec laoreet nonummy augue. Suspendisse dui purus, scelerisque at, vulputate vitae, pretium mattis, nunc. Mauris eget neque at sem venenatis eleifend. Ut nonummy."; private sealed class IdentityTransform : ICryptoTransform { private readonly int _inputBlockSize, _outputBlockSize; private readonly bool _canTransformMultipleBlocks; private readonly object _lock = new object(); private long _writePos, _readPos; private MemoryStream _stream; internal IdentityTransform(int inputBlockSize, int outputBlockSize, bool canTransformMultipleBlocks) { _inputBlockSize = inputBlockSize; _outputBlockSize = outputBlockSize; _canTransformMultipleBlocks = canTransformMultipleBlocks; _stream = new MemoryStream(); } public bool CanReuseTransform { get { return true; } } public bool CanTransformMultipleBlocks { get { return _canTransformMultipleBlocks; } } public int InputBlockSize { get { return _inputBlockSize; } } public int OutputBlockSize { get { return _outputBlockSize; } } public void Dispose() { } public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { lock (_lock) { _stream.Position = _writePos; _stream.Write(inputBuffer, inputOffset, inputCount); _writePos = _stream.Position; _stream.Position = _readPos; int copied = _stream.Read(outputBuffer, outputOffset, outputBuffer.Length - outputOffset); _readPos = _stream.Position; return copied; } } public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { lock (_lock) { _stream.Position = _writePos; _stream.Write(inputBuffer, inputOffset, inputCount); _stream.Position = _readPos; long len = _stream.Length - _stream.Position; byte[] outputBuffer = new byte[len]; _stream.Read(outputBuffer, 0, outputBuffer.Length); _stream = new MemoryStream(); _writePos = 0; _readPos = 0; return outputBuffer; } } } public class MinimalCryptoStream : CryptoStream { public bool FlushCalled; public MinimalCryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode) : base(stream, transform, mode) { } public override void Flush() { FlushCalled = true; base.Flush(); } } } }
// ReSharper disable RedundantTypeArgumentsOfMethod #pragma warning disable IDE0001 namespace Gu.Inject { using System; /// <summary> /// Rebind extension methods for <see cref="Kernel"/>. /// </summary> public static class RebindExtensions { /// <summary> /// Check if there is a binding for <paramref name="type"/>. /// </summary> /// <param name="kernel">The <see cref="Kernel"/>.</param> /// <param name="type">The type to resolve.</param> /// <returns>True if there is a binding.</returns> public static bool HasBinding(this Kernel kernel, Type type) { if (kernel is null) { throw new ArgumentNullException(nameof(kernel)); } return kernel.HasBinding(type); } /// <summary> /// Provide an override to the automatic mapping. /// </summary> /// <param name="kernel">The <see cref="Kernel"/>.</param> /// <param name="from">The type to map.</param> /// <param name="to">The mapped type.</param> /// <returns>The same instance.</returns> public static Kernel Rebind(this Kernel kernel, Type from, Type to) { if (kernel is null) { throw new ArgumentNullException(nameof(kernel)); } if (from is null) { throw new ArgumentNullException(nameof(from)); } if (to is null) { throw new ArgumentNullException(nameof(to)); } kernel.Rebind(from, Binding.Map(to), requireExistingBinding: true); return kernel; } /// <summary> /// Use this binding when there are circular dependencies. /// This binds an FormatterServices.GetUninitializedObject() that is used when creating the graph. /// </summary> /// <typeparam name="T">The type to map.</typeparam> /// <param name="kernel">The <see cref="Kernel"/>.</param> /// <returns>The same instance.</returns> public static Kernel RebindUninitialized<T>(this Kernel kernel) where T : class { if (kernel is null) { throw new ArgumentNullException(nameof(kernel)); } kernel.Rebind(typeof(T), Binding.Uninitialized<T>(), requireExistingBinding: true); return kernel; } /// <summary> /// Provide an override to the automatic mapping. /// </summary> /// <typeparam name="TInterface">The type to map.</typeparam> /// <typeparam name="TConcrete">The mapped type.</typeparam> /// <param name="kernel">The <see cref="Kernel"/>.</param> /// <returns>The same instance.</returns> public static Kernel Rebind<TInterface, TConcrete>(this Kernel kernel) where TConcrete : TInterface { if (kernel is null) { throw new ArgumentNullException(nameof(kernel)); } kernel.Rebind(typeof(TInterface), Binding.Map<TConcrete>(), requireExistingBinding: true); return kernel; } /// <summary> /// Provide an override to the automatic mapping. /// </summary> /// <typeparam name="TInterface1">The first type to map.</typeparam> /// <typeparam name="TInterface2">The second type to map.</typeparam> /// <typeparam name="TConcrete">The mapped type.</typeparam> /// <param name="kernel">The <see cref="Kernel"/>.</param> /// <returns>The same instance.</returns> public static Kernel Rebind<TInterface1, TInterface2, TConcrete>(this Kernel kernel) where TConcrete : TInterface1, TInterface2 { if (kernel is null) { throw new ArgumentNullException(nameof(kernel)); } kernel.Rebind(typeof(TInterface1), Binding.Map<TConcrete>(), requireExistingBinding: true); kernel.Rebind(typeof(TInterface2), Binding.Map<TConcrete>(), requireExistingBinding: true); return kernel; } /// <summary> /// Provide an override to the automatic mapping. /// </summary> /// <typeparam name="TInterface1">The first type to map.</typeparam> /// <typeparam name="TInterface2">The second type to map.</typeparam> /// <typeparam name="TInterface3">The third type to map.</typeparam> /// <typeparam name="TConcrete">The mapped type.</typeparam> /// <param name="kernel">The <see cref="Kernel"/>.</param> /// <returns>The same instance.</returns> public static Kernel Rebind<TInterface1, TInterface2, TInterface3, TConcrete>(this Kernel kernel) where TConcrete : TInterface1, TInterface2, TInterface3 { if (kernel is null) { throw new ArgumentNullException(nameof(kernel)); } kernel.Rebind(typeof(TInterface1), Binding.Map<TConcrete>(), requireExistingBinding: true); kernel.Rebind(typeof(TInterface2), Binding.Map<TConcrete>(), requireExistingBinding: true); kernel.Rebind(typeof(TInterface3), Binding.Map<TConcrete>(), requireExistingBinding: true); return kernel; } /// <summary> /// Provide an override for the automatic mapping. /// If the <paramref name="instance"/> implements IDisposable, the responsibility to dispose it remains the caller's, disposing the kernel doesn't do that. /// </summary> /// <typeparam name="T">The mapped type.</typeparam> /// <param name="kernel">The <see cref="Kernel"/>.</param> /// <param name="instance">The instance to bind.</param> /// <returns>The same instance.</returns> public static Kernel Rebind<T>(this Kernel kernel, T instance) { if (kernel is null) { throw new ArgumentNullException(nameof(kernel)); } if (instance is null) { throw new ArgumentNullException(nameof(instance)); } if (typeof(T) == instance.GetType()) { kernel.Rebind(typeof(T), Binding.Instance(instance), requireExistingBinding: true); } else { kernel.Rebind(typeof(T), Binding.Mapped(instance), requireExistingBinding: true); kernel.Rebind(instance.GetType(), Binding.Instance(instance), requireExistingBinding: false); } return kernel; } /// <summary> /// Provide an override for the automatic mapping. /// If the <paramref name="instance"/> implements IDisposable, the responsibility to dispose it remains the caller's, disposing the kernel doesn't do that. /// </summary> /// <typeparam name="TInterface">The type to map.</typeparam> /// <typeparam name="TConcrete">The mapped type.</typeparam> /// <param name="kernel">The <see cref="Kernel"/>.</param> /// <param name="instance">The instance to bind.</param> /// <returns>The same instance.</returns> public static Kernel Rebind<TInterface, TConcrete>(this Kernel kernel, TConcrete instance) where TConcrete : TInterface { if (kernel is null) { throw new ArgumentNullException(nameof(kernel)); } if (instance is null) { throw new ArgumentNullException(nameof(instance)); } kernel.Rebind<TConcrete>(instance); kernel.Rebind(typeof(TInterface), Binding.Mapped(instance), requireExistingBinding: true); return kernel; } /// <summary> /// Provide an override for the automatic mapping. /// If the <paramref name="instance"/> implements IDisposable, the responsibility to dispose it remains the caller's, disposing the kernel doesn't do that. /// </summary> /// <typeparam name="TInterface1">The first type to map.</typeparam> /// <typeparam name="TInterface2">The second type to map.</typeparam> /// <typeparam name="TConcrete">The mapped type.</typeparam> /// <param name="kernel">The <see cref="Kernel"/>.</param> /// <param name="instance">The instance to bind.</param> /// <returns>The same instance.</returns> public static Kernel Rebind<TInterface1, TInterface2, TConcrete>(this Kernel kernel, TConcrete instance) where TConcrete : TInterface1, TInterface2 { if (kernel is null) { throw new ArgumentNullException(nameof(kernel)); } if (instance is null) { throw new ArgumentNullException(nameof(instance)); } kernel.Rebind<TConcrete>(instance); kernel.Rebind(typeof(TInterface1), Binding.Mapped(instance), requireExistingBinding: true); kernel.Rebind(typeof(TInterface2), Binding.Mapped(instance), requireExistingBinding: true); return kernel; } /// <summary> /// Provide an override for the automatic mapping. /// If the <paramref name="instance"/> implements IDisposable, the responsibility to dispose it remains the caller's, disposing the kernel doesn't do that. /// </summary> /// <typeparam name="TInterface1">The first type to map.</typeparam> /// <typeparam name="TInterface2">The second type to map.</typeparam> /// <typeparam name="TInterface3">The third type to map.</typeparam> /// <typeparam name="TConcrete">The mapped type.</typeparam> /// <param name="kernel">The <see cref="Kernel"/>.</param> /// <param name="instance">The instance to bind.</param> /// <returns>The same instance.</returns> public static Kernel Rebind<TInterface1, TInterface2, TInterface3, TConcrete>(this Kernel kernel, TConcrete instance) where TConcrete : TInterface1, TInterface2, TInterface3 { if (kernel is null) { throw new ArgumentNullException(nameof(kernel)); } if (instance is null) { throw new ArgumentNullException(nameof(instance)); } kernel.Rebind<TConcrete>(instance); kernel.Rebind(typeof(TInterface1), Binding.Mapped(instance), requireExistingBinding: true); kernel.Rebind(typeof(TInterface2), Binding.Mapped(instance), requireExistingBinding: true); kernel.Rebind(typeof(TInterface3), Binding.Mapped(instance), requireExistingBinding: true); return kernel; } /// <summary> /// Provide an override for the automatic mapping. /// The instance is created lazily by <paramref name="create"/> and is cached for subsequent calls to .Get(). /// The instance is owned by the kernel, that is, calling .Dispose() on the kernel disposes the instance, if its type implements IDisposable. /// </summary> /// <typeparam name="T">The mapped type.</typeparam> /// <param name="kernel">The <see cref="Kernel"/>.</param> /// <param name="create">The factory function used to create the instance.</param> /// <returns>The same instance.</returns> public static Kernel Rebind<T>(this Kernel kernel, Func<T> create) { if (kernel is null) { throw new ArgumentNullException(nameof(kernel)); } if (create is null) { throw new ArgumentNullException(nameof(create)); } kernel.Rebind(typeof(T), Binding.Func(create), requireExistingBinding: true); return kernel; } /// <summary> /// Provide an override for the automatic mapping. /// The instance is created lazily by <paramref name="create"/> and is cached for subsequent calls to .Get(). /// </summary> /// <typeparam name="TInterface">The type to map.</typeparam> /// <typeparam name="TConcrete">The mapped type.</typeparam> /// <param name="kernel">The <see cref="Kernel"/>.</param> /// <param name="create">The factory function used to create the instance.</param> /// <returns>The same instance.</returns> public static Kernel Rebind<TInterface, TConcrete>(this Kernel kernel, Func<TConcrete> create) where TConcrete : TInterface { if (kernel is null) { throw new ArgumentNullException(nameof(kernel)); } if (create is null) { throw new ArgumentNullException(nameof(create)); } kernel.Rebind(typeof(TInterface), Binding.Map<TConcrete>(), requireExistingBinding: true); kernel.Rebind(typeof(TConcrete), Binding.Func(create), requireExistingBinding: true); return kernel; } /// <summary> /// Provide an override for the automatic mapping. /// The instance is created lazily by <paramref name="create"/> and is cached for subsequent calls to .Get(). /// </summary> /// <typeparam name="TInterface1">The first type to map.</typeparam> /// <typeparam name="TInterface2">The second type to map.</typeparam> /// <typeparam name="TConcrete">The mapped type.</typeparam> /// <param name="kernel">The <see cref="Kernel"/>.</param> /// <param name="create">The factory function used to create the instance.</param> /// <returns>The same instance.</returns> public static Kernel Rebind<TInterface1, TInterface2, TConcrete>(this Kernel kernel, Func<TConcrete> create) where TConcrete : TInterface1, TInterface2 { if (kernel is null) { throw new ArgumentNullException(nameof(kernel)); } if (create is null) { throw new ArgumentNullException(nameof(create)); } kernel.Rebind(typeof(TInterface1), Binding.Map<TConcrete>(), requireExistingBinding: true); kernel.Rebind(typeof(TInterface2), Binding.Map<TConcrete>(), requireExistingBinding: true); kernel.Rebind(typeof(TConcrete), Binding.Func(create), requireExistingBinding: true); return kernel; } /// <summary> /// Provide an override for the automatic mapping. /// The instance is created lazily by <paramref name="create"/> and is cached for subsequent calls to .Get(). /// </summary> /// <typeparam name="TInterface1">The first type to map.</typeparam> /// <typeparam name="TInterface2">The second type to map.</typeparam> /// <typeparam name="TInterface3">The third type to map.</typeparam> /// <typeparam name="TConcrete">The mapped type.</typeparam> /// <param name="kernel">The <see cref="Kernel"/>.</param> /// <param name="create">The factory function used to create the instance.</param> /// <returns>The same instance.</returns> public static Kernel Rebind<TInterface1, TInterface2, TInterface3, TConcrete>(this Kernel kernel, Func<TConcrete> create) where TConcrete : TInterface1, TInterface2, TInterface3 { if (kernel is null) { throw new ArgumentNullException(nameof(kernel)); } if (create is null) { throw new ArgumentNullException(nameof(create)); } kernel.Rebind(typeof(TInterface1), Binding.Map<TConcrete>(), requireExistingBinding: true); kernel.Rebind(typeof(TInterface2), Binding.Map<TConcrete>(), requireExistingBinding: true); kernel.Rebind(typeof(TInterface3), Binding.Map<TConcrete>(), requireExistingBinding: true); kernel.Rebind(typeof(TConcrete), Binding.Func(create), requireExistingBinding: true); return kernel; } /// <summary> /// Provide an override for the automatic mapping. /// The kernel will keep <paramref name="create"/> alive until disposed. /// <paramref name="create"/> is disposed by the kernel if disposable. /// </summary> /// <typeparam name="T">The mapped type.</typeparam> /// <param name="kernel">The <see cref="Kernel"/>.</param> /// <param name="create">The instance to bind.</param> /// <returns>The same instance.</returns> public static Kernel Rebind<T>(this Kernel kernel, Func<IReadOnlyKernel, T> create) { if (kernel is null) { throw new ArgumentNullException(nameof(kernel)); } if (create is null) { throw new ArgumentNullException(nameof(create)); } kernel.Rebind(typeof(T), Binding.Resolver(create), requireExistingBinding: true); return kernel; } /// <summary> /// Provide an override for the automatic mapping. /// The kernel will keep <paramref name="create"/> alive until disposed. /// <paramref name="create"/> is disposed by the kernel if disposable. /// </summary> /// <typeparam name="TInterface">The type to map.</typeparam> /// <typeparam name="TConcrete">The mapped type.</typeparam> /// <param name="kernel">The <see cref="Kernel"/>.</param> /// <param name="create">The instance to bind.</param> /// <returns>The same instance.</returns> public static Kernel Rebind<TInterface, TConcrete>(this Kernel kernel, Func<IReadOnlyKernel, TConcrete> create) where TConcrete : TInterface { if (kernel is null) { throw new ArgumentNullException(nameof(kernel)); } if (create is null) { throw new ArgumentNullException(nameof(create)); } kernel.Rebind(typeof(TInterface), Binding.Map<TConcrete>(), requireExistingBinding: true); kernel.Rebind(typeof(TConcrete), Binding.Resolver(create), requireExistingBinding: true); return kernel; } /// <summary> /// Provide an override for the automatic mapping. /// The kernel will keep <paramref name="create"/> alive until disposed. /// <paramref name="create"/> is disposed by the kernel if disposable. /// </summary> /// <typeparam name="TInterface1">The first type to map.</typeparam> /// <typeparam name="TInterface2">The second type to map.</typeparam> /// <typeparam name="TConcrete">The mapped type.</typeparam> /// <param name="kernel">The <see cref="Kernel"/>.</param> /// <param name="create">The instance to bind.</param> /// <returns>The same instance.</returns> public static Kernel Rebind<TInterface1, TInterface2, TConcrete>(this Kernel kernel, Func<IReadOnlyKernel, TConcrete> create) where TConcrete : TInterface1, TInterface2 { if (kernel is null) { throw new ArgumentNullException(nameof(kernel)); } if (create is null) { throw new ArgumentNullException(nameof(create)); } kernel.Rebind(typeof(TInterface1), Binding.Map<TConcrete>(), requireExistingBinding: true); kernel.Rebind(typeof(TInterface2), Binding.Map<TConcrete>(), requireExistingBinding: true); kernel.Rebind(typeof(TConcrete), Binding.Resolver(create), requireExistingBinding: true); return kernel; } /// <summary> /// Provide an override for the automatic mapping. /// The kernel will keep <paramref name="create"/> alive until disposed. /// <paramref name="create"/> is disposed by the kernel if disposable. /// </summary> /// <typeparam name="TInterface1">The first type to map.</typeparam> /// <typeparam name="TInterface2">The second type to map.</typeparam> /// <typeparam name="TInterface3">The third type to map.</typeparam> /// <typeparam name="TConcrete">The mapped type.</typeparam> /// <param name="kernel">The <see cref="Kernel"/>.</param> /// <param name="create">The instance to bind.</param> /// <returns>The same instance.</returns> public static Kernel Rebind<TInterface1, TInterface2, TInterface3, TConcrete>(this Kernel kernel, Func<IReadOnlyKernel, TConcrete> create) where TConcrete : TInterface1, TInterface2 { if (kernel is null) { throw new ArgumentNullException(nameof(kernel)); } if (create is null) { throw new ArgumentNullException(nameof(create)); } kernel.Rebind(typeof(TInterface1), Binding.Map<TConcrete>(), requireExistingBinding: true); kernel.Rebind(typeof(TInterface2), Binding.Map<TConcrete>(), requireExistingBinding: true); kernel.Rebind(typeof(TInterface3), Binding.Map<TConcrete>(), requireExistingBinding: true); kernel.Rebind(typeof(TConcrete), Binding.Resolver(create), requireExistingBinding: true); return kernel; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Platform; using osu.Framework.Threading; using osu.Game.Graphics.UserInterface; using osu.Game.Overlays.Settings; using osu.Game.Tournament.Components; using osu.Game.Tournament.IPC; using osu.Game.Tournament.Models; using osu.Game.Tournament.Screens.Gameplay.Components; using osu.Game.Tournament.Screens.MapPool; using osu.Game.Tournament.Screens.TeamWin; using osuTK.Graphics; namespace osu.Game.Tournament.Screens.Gameplay { public class GameplayScreen : BeatmapInfoScreen, IProvideVideo { private readonly BindableBool warmup = new BindableBool(); public readonly Bindable<TourneyState> State = new Bindable<TourneyState>(); private OsuButton warmupButton; private MatchIPCInfo ipc; [Resolved(canBeNull: true)] private TournamentSceneManager sceneManager { get; set; } [Resolved] private TournamentMatchChatDisplay chat { get; set; } private Drawable chroma; [BackgroundDependencyLoader] private void load(LadderInfo ladder, MatchIPCInfo ipc, Storage storage) { this.ipc = ipc; AddRangeInternal(new Drawable[] { new TourneyVideo("gameplay") { Loop = true, RelativeSizeAxes = Axes.Both, }, header = new MatchHeader { ShowLogo = false }, new Container { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Y = 110, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Children = new[] { chroma = new Container { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Height = 512, Children = new Drawable[] { new ChromaArea { Name = "Left chroma", RelativeSizeAxes = Axes.Both, Width = 0.5f, }, new ChromaArea { Name = "Right chroma", RelativeSizeAxes = Axes.Both, Anchor = Anchor.TopRight, Origin = Anchor.TopRight, Width = 0.5f, } } }, } }, scoreDisplay = new TournamentMatchScoreDisplay { Y = -147, Anchor = Anchor.BottomCentre, Origin = Anchor.TopCentre, }, new ControlPanel { Children = new Drawable[] { warmupButton = new TourneyButton { RelativeSizeAxes = Axes.X, Text = "Toggle warmup", Action = () => warmup.Toggle() }, new TourneyButton { RelativeSizeAxes = Axes.X, Text = "Toggle chat", Action = () => { State.Value = State.Value == TourneyState.Idle ? TourneyState.Playing : TourneyState.Idle; } }, new SettingsSlider<int> { LabelText = "Chroma width", Current = LadderInfo.ChromaKeyWidth, KeyboardStep = 1, }, new SettingsSlider<int> { LabelText = "Players per team", Current = LadderInfo.PlayersPerTeam, KeyboardStep = 1, } } } }); State.BindTo(ipc.State); State.BindValueChanged(stateChanged, true); ladder.ChromaKeyWidth.BindValueChanged(width => chroma.Width = width.NewValue, true); warmup.BindValueChanged(w => { warmupButton.Alpha = !w.NewValue ? 0.5f : 1; header.ShowScores = !w.NewValue; }, true); } protected override void CurrentMatchChanged(ValueChangedEvent<TournamentMatch> match) { base.CurrentMatchChanged(match); if (match.NewValue == null) return; warmup.Value = match.NewValue.Team1Score.Value + match.NewValue.Team2Score.Value == 0; scheduledOperation?.Cancel(); } private ScheduledDelegate scheduledOperation; private TournamentMatchScoreDisplay scoreDisplay; private TourneyState lastState; private MatchHeader header; private void stateChanged(ValueChangedEvent<TourneyState> state) { try { if (state.NewValue == TourneyState.Ranking) { if (warmup.Value) return; if (ipc.Score1.Value > ipc.Score2.Value) CurrentMatch.Value.Team1Score.Value++; else CurrentMatch.Value.Team2Score.Value++; } scheduledOperation?.Cancel(); void expand() { chat?.Contract(); using (BeginDelayedSequence(300)) { scoreDisplay.FadeIn(100); SongBar.Expanded = true; } } void contract() { SongBar.Expanded = false; scoreDisplay.FadeOut(100); using (chat?.BeginDelayedSequence(500)) chat?.Expand(); } switch (state.NewValue) { case TourneyState.Idle: contract(); const float delay_before_progression = 4000; // if we've returned to idle and the last screen was ranking // we should automatically proceed after a short delay if (lastState == TourneyState.Ranking && !warmup.Value) { if (CurrentMatch.Value?.Completed.Value == true) scheduledOperation = Scheduler.AddDelayed(() => { sceneManager?.SetScreen(typeof(TeamWinScreen)); }, delay_before_progression); else if (CurrentMatch.Value?.Completed.Value == false) scheduledOperation = Scheduler.AddDelayed(() => { sceneManager?.SetScreen(typeof(MapPoolScreen)); }, delay_before_progression); } break; case TourneyState.Ranking: scheduledOperation = Scheduler.AddDelayed(contract, 10000); break; default: chat.Contract(); expand(); break; } } finally { lastState = state.NewValue; } } private class ChromaArea : CompositeDrawable { [Resolved] private LadderInfo ladder { get; set; } [BackgroundDependencyLoader] private void load() { // chroma key area for stable gameplay Colour = new Color4(0, 255, 0, 255); ladder.PlayersPerTeam.BindValueChanged(performLayout, true); } private void performLayout(ValueChangedEvent<int> playerCount) { switch (playerCount.NewValue) { case 3: InternalChildren = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Width = 0.5f, Height = 0.5f, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, }, new Box { RelativeSizeAxes = Axes.Both, Anchor = Anchor.BottomLeft, Origin = Anchor.BottomLeft, Height = 0.5f, }, }; break; default: InternalChild = new Box { RelativeSizeAxes = Axes.Both, }; break; } } } } }
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com> using System; using System.Collections; using System.Collections.Generic; namespace Aphysoft.Share.Html { /// <summary> /// Represents a combined list and collection of HTML nodes. /// </summary> public class HtmlAttributeCollection : IList<HtmlAttribute> { #region Fields internal Dictionary<string, HtmlAttribute> Hashitems = new Dictionary<string, HtmlAttribute>(); private HtmlNode _ownernode; private List<HtmlAttribute> items = new List<HtmlAttribute>(); #endregion #region Constructors internal HtmlAttributeCollection(HtmlNode ownernode) { _ownernode = ownernode; } #endregion #region Properties /// <summary> /// Gets a given attribute from the list using its name. /// </summary> public HtmlAttribute this[string name] { get { if (name == null) { throw new ArgumentNullException("name"); } return Hashitems.ContainsKey(name.ToLower()) ? Hashitems[name.ToLower()] : null; } set { Append(value); } } #endregion #region IList<HtmlAttribute> Members /// <summary> /// Gets the number of elements actually contained in the list. /// </summary> public int Count { get { return items.Count; } } /// <summary> /// Gets readonly status of colelction /// </summary> public bool IsReadOnly { get { return false; } } /// <summary> /// Gets the attribute at the specified index. /// </summary> public HtmlAttribute this[int index] { get { return items[index]; } set { items[index] = value; } } /// <summary> /// Adds supplied item to collection /// </summary> /// <param name="item"></param> public void Add(HtmlAttribute item) { Append(item); } /// <summary> /// Explicit clear /// </summary> void ICollection<HtmlAttribute>.Clear() { items.Clear(); } /// <summary> /// Retreives existence of supplied item /// </summary> /// <param name="item"></param> /// <returns></returns> public bool Contains(HtmlAttribute item) { return items.Contains(item); } /// <summary> /// Copies collection to array /// </summary> /// <param name="array"></param> /// <param name="arrayIndex"></param> public void CopyTo(HtmlAttribute[] array, int arrayIndex) { items.CopyTo(array, arrayIndex); } /// <summary> /// Get Explicit enumerator /// </summary> /// <returns></returns> IEnumerator<HtmlAttribute> IEnumerable<HtmlAttribute>.GetEnumerator() { return items.GetEnumerator(); } /// <summary> /// Explicit non-generic enumerator /// </summary> /// <returns></returns> IEnumerator IEnumerable.GetEnumerator() { return items.GetEnumerator(); } /// <summary> /// Retrieves the index for the supplied item, -1 if not found /// </summary> /// <param name="item"></param> /// <returns></returns> public int IndexOf(HtmlAttribute item) { return items.IndexOf(item); } /// <summary> /// Inserts given item into collection at supplied index /// </summary> /// <param name="index"></param> /// <param name="item"></param> public void Insert(int index, HtmlAttribute item) { if (item == null) { throw new ArgumentNullException("item"); } Hashitems[item.Name] = item; item._ownernode = _ownernode; items.Insert(index, item); _ownernode._innerchanged = true; _ownernode._outerchanged = true; } /// <summary> /// Explicit collection remove /// </summary> /// <param name="item"></param> /// <returns></returns> bool ICollection<HtmlAttribute>.Remove(HtmlAttribute item) { return items.Remove(item); } /// <summary> /// Removes the attribute at the specified index. /// </summary> /// <param name="index">The index of the attribute to remove.</param> public void RemoveAt(int index) { HtmlAttribute att = items[index]; Hashitems.Remove(att.Name); items.RemoveAt(index); _ownernode._innerchanged = true; _ownernode._outerchanged = true; } #endregion #region Public Methods /// <summary> /// Adds a new attribute to the collection with the given values /// </summary> /// <param name="name"></param> /// <param name="value"></param> public void Add(string name, string value) { Append(name, value); } /// <summary> /// Inserts the specified attribute as the last attribute in the collection. /// </summary> /// <param name="newAttribute">The attribute to insert. May not be null.</param> /// <returns>The appended attribute.</returns> public HtmlAttribute Append(HtmlAttribute newAttribute) { if (newAttribute == null) { throw new ArgumentNullException("newAttribute"); } Hashitems[newAttribute.Name] = newAttribute; newAttribute._ownernode = _ownernode; items.Add(newAttribute); _ownernode._innerchanged = true; _ownernode._outerchanged = true; return newAttribute; } /// <summary> /// Creates and inserts a new attribute as the last attribute in the collection. /// </summary> /// <param name="name">The name of the attribute to insert.</param> /// <returns>The appended attribute.</returns> public HtmlAttribute Append(string name) { HtmlAttribute att = _ownernode._ownerdocument.CreateAttribute(name); return Append(att); } /// <summary> /// Creates and inserts a new attribute as the last attribute in the collection. /// </summary> /// <param name="name">The name of the attribute to insert.</param> /// <param name="value">The value of the attribute to insert.</param> /// <returns>The appended attribute.</returns> public HtmlAttribute Append(string name, string value) { HtmlAttribute att = _ownernode._ownerdocument.CreateAttribute(name, value); return Append(att); } /// <summary> /// Checks for existance of attribute with given name /// </summary> /// <param name="name"></param> /// <returns></returns> public bool Contains(string name) { for (int i = 0; i < items.Count; i++) { if (items[i].Name.Equals(name.ToLower())) return true; } return false; } /// <summary> /// Inserts the specified attribute as the first node in the collection. /// </summary> /// <param name="newAttribute">The attribute to insert. May not be null.</param> /// <returns>The prepended attribute.</returns> public HtmlAttribute Prepend(HtmlAttribute newAttribute) { Insert(0, newAttribute); return newAttribute; } /// <summary> /// Removes a given attribute from the list. /// </summary> /// <param name="attribute">The attribute to remove. May not be null.</param> public void Remove(HtmlAttribute attribute) { if (attribute == null) { throw new ArgumentNullException("attribute"); } int index = GetAttributeIndex(attribute); if (index == -1) { throw new IndexOutOfRangeException(); } RemoveAt(index); } /// <summary> /// Removes an attribute from the list, using its name. If there are more than one attributes with this name, they will all be removed. /// </summary> /// <param name="name">The attribute's name. May not be null.</param> public void Remove(string name) { if (name == null) { throw new ArgumentNullException("name"); } string lname = name.ToLower(); for (int i = 0; i < items.Count; i++) { HtmlAttribute att = items[i]; if (att.Name == lname) { RemoveAt(i); } } } /// <summary> /// Remove all attributes in the list. /// </summary> public void RemoveAll() { Hashitems.Clear(); items.Clear(); _ownernode._innerchanged = true; _ownernode._outerchanged = true; } #endregion #region LINQ Methods /// <summary> /// Returns all attributes with specified name. Handles case insentivity /// </summary> /// <param name="attributeName">Name of the attribute</param> /// <returns></returns> public IEnumerable<HtmlAttribute> AttributesWithName(string attributeName) { attributeName = attributeName.ToLower(); for (int i = 0; i < items.Count; i++) { if (items[i].Name.Equals(attributeName)) yield return items[i]; } } /// <summary> /// Removes all attributes from the collection /// </summary> public void Remove() { foreach (HtmlAttribute item in items) item.Remove(); } #endregion #region Internal Methods /// <summary> /// Clears the attribute collection /// </summary> internal void Clear() { Hashitems.Clear(); items.Clear(); } internal int GetAttributeIndex(HtmlAttribute attribute) { if (attribute == null) { throw new ArgumentNullException("attribute"); } for (int i = 0; i < items.Count; i++) { if ((items[i]) == attribute) return i; } return -1; } internal int GetAttributeIndex(string name) { if (name == null) { throw new ArgumentNullException("name"); } string lname = name.ToLower(); for (int i = 0; i < items.Count; i++) { if ((items[i]).Name == lname) return i; } return -1; } #endregion } }
// // This code was created by Jeff Molofee '99 // // If you've found this code useful, please let me know. // // Visit me at www.demonews.com/hosted/nehe // //===================================================================== // Converted to C# and MonoMac by Kenneth J. Pouncey // http://www.cocoa-mono.org // // Copyright (c) 2011 Kenneth J. Pouncey // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Linq; using System.Drawing; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.CoreVideo; using MonoMac.CoreGraphics; using MonoMac.OpenGL; namespace NeHeLesson6 { public partial class MyOpenGLView : MonoMac.AppKit.NSView { NSOpenGLContext openGLContext; NSOpenGLPixelFormat pixelFormat; MainWindowController controller; CVDisplayLink displayLink; NSObject notificationProxy; [Export("initWithFrame:")] public MyOpenGLView (RectangleF frame) : this(frame, null) { } public MyOpenGLView (RectangleF frame,NSOpenGLContext context) : base(frame) { var attribs = new object [] { NSOpenGLPixelFormatAttribute.Accelerated, NSOpenGLPixelFormatAttribute.NoRecovery, NSOpenGLPixelFormatAttribute.DoubleBuffer, NSOpenGLPixelFormatAttribute.ColorSize, 24, NSOpenGLPixelFormatAttribute.DepthSize, 16 }; pixelFormat = new NSOpenGLPixelFormat (attribs); if (pixelFormat == null) Console.WriteLine ("No OpenGL pixel format"); // NSOpenGLView does not handle context sharing, so we draw to a custom NSView instead openGLContext = new NSOpenGLContext (pixelFormat, context); openGLContext.MakeCurrentContext (); // Synchronize buffer swaps with vertical refresh rate openGLContext.SwapInterval = true; // Initialize our newly created view. InitGL (); SetupDisplayLink (); // Look for changes in view size // Note, -reshape will not be called automatically on size changes because NSView does not export it to override notificationProxy = NSNotificationCenter.DefaultCenter.AddObserver (NSView.GlobalFrameChangedNotification, HandleReshape); } public override void DrawRect (RectangleF dirtyRect) { // Ignore if the display link is still running if (!displayLink.IsRunning && controller != null) DrawView (); } public override bool AcceptsFirstResponder () { // We want this view to be able to receive key events return true; } public override void LockFocus () { base.LockFocus (); if (openGLContext.View != this) openGLContext.View = this; } public override void KeyDown (NSEvent theEvent) { controller.KeyDown (theEvent); } public override void MouseDown (NSEvent theEvent) { controller.MouseDown (theEvent); } // All Setup For OpenGL Goes Here public bool InitGL () { // Enable Texture Mapping ( NEW ) GL.Enable (EnableCap.Texture2D); // Enables Smooth Shading GL.ShadeModel (ShadingModel.Smooth); // Set background color to black GL.ClearColor (Color.Black); // Setup Depth Testing // Depth Buffer setup GL.ClearDepth (1.0); // Enables Depth testing GL.Enable (EnableCap.DepthTest); // The type of depth testing to do GL.DepthFunc (DepthFunction.Lequal); // Really Nice Perspective Calculations GL.Hint (HintTarget.PerspectiveCorrectionHint, HintMode.Nicest); return true; } private void DrawView () { var previous = NSApplication.CheckForIllegalCrossThreadCalls; NSApplication.CheckForIllegalCrossThreadCalls = false; // This method will be called on both the main thread (through -drawRect:) and a secondary thread (through the display link rendering loop) // Also, when resizing the view, -reshape is called on the main thread, but we may be drawing on a secondary thread // Add a mutex around to avoid the threads accessing the context simultaneously openGLContext.CGLContext.Lock (); // Make sure we draw to the right context openGLContext.MakeCurrentContext (); // Delegate to the scene object for rendering controller.Scene.DrawGLScene (); openGLContext.FlushBuffer (); openGLContext.CGLContext.Unlock (); NSApplication.CheckForIllegalCrossThreadCalls = previous; } private void SetupDisplayLink () { // Create a display link capable of being used with all active displays displayLink = new CVDisplayLink (); // Set the renderer output callback function displayLink.SetOutputCallback (MyDisplayLinkOutputCallback); // Set the display link for the current renderer CGLContext cglContext = openGLContext.CGLContext; CGLPixelFormat cglPixelFormat = PixelFormat.CGLPixelFormat; displayLink.SetCurrentDisplay (cglContext, cglPixelFormat); } public CVReturn MyDisplayLinkOutputCallback (CVDisplayLink displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut) { CVReturn result = GetFrameForTime (inOutputTime); return result; } private CVReturn GetFrameForTime (CVTimeStamp outputTime) { // There is no autorelease pool when this method is called because it will be called from a background thread // It's important to create one or you will leak objects using (NSAutoreleasePool pool = new NSAutoreleasePool ()) { // Update the animation DrawView (); } return CVReturn.Success; } public NSOpenGLContext OpenGLContext { get { return openGLContext; } } public NSOpenGLPixelFormat PixelFormat { get { return pixelFormat; } } public MainWindowController MainController { set { controller = value; } } public void UpdateView () { // This method will be called on the main thread when resizing, but we may be drawing on a secondary thread through the display link // Add a mutex around to avoid the threads accessing the context simultaneously openGLContext.CGLContext.Lock (); // Delegate to the scene object to update for a change in the view size controller.Scene.ResizeGLScene (Bounds); openGLContext.Update (); openGLContext.CGLContext.Unlock (); } private void HandleReshape (NSNotification note) { UpdateView (); } public void StartAnimation () { if (displayLink != null && !displayLink.IsRunning) displayLink.Start (); } public void StopAnimation () { if (displayLink != null && displayLink.IsRunning) displayLink.Stop (); } // Clean up the notifications public void DeAllocate () { displayLink.Stop (); displayLink.SetOutputCallback (null); NSNotificationCenter.DefaultCenter.RemoveObserver (notificationProxy); } [Export("toggleFullScreen:")] public void toggleFullScreen (NSObject sender) { controller.toggleFullScreen (sender); } } }
// Stephen Toub // Coded and published in January 2007 issue of MSDN Magazine // http://msdn.microsoft.com/msdnmag/issues/07/01/PreviewHandlers/default.aspx using System; using System.IO; using System.Drawing; using System.Windows.Forms; using System.Runtime.InteropServices; using System.ComponentModel; using Microsoft.Win32; using System.Runtime.InteropServices.ComTypes; using System.Threading; using System.Diagnostics; namespace C4F.DevKit.PreviewHandler.PreviewHandlerFramework { public abstract class PreviewHandler : IPreviewHandler, IPreviewHandlerVisuals, IOleWindow, IObjectWithSite { private bool _showPreview; private PreviewHandlerControl _previewControl; private IntPtr _parentHwnd; private Rectangle _windowBounds; private object _unkSite; private IPreviewHandlerFrame _frame; protected PreviewHandler() { _previewControl = CreatePreviewHandlerControl(); // NOTE: shouldn't call virtual function from constructor; see article for more information IntPtr forceCreation = _previewControl.Handle; _previewControl.BackColor = SystemColors.Window; } protected abstract PreviewHandlerControl CreatePreviewHandlerControl(); private void InvokeOnPreviewThread(MethodInvoker d) { _previewControl.Invoke(d); } [DllImport("user32.dll")] private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); private void UpdateWindowBounds() { if (_showPreview) { InvokeOnPreviewThread(delegate() { SetParent(_previewControl.Handle, _parentHwnd); _previewControl.Bounds = _windowBounds; _previewControl.Visible = true; }); } } void IPreviewHandler.SetWindow(IntPtr hwnd, ref RECT rect) { _parentHwnd = hwnd; _windowBounds = rect.ToRectangle(); UpdateWindowBounds(); } void IPreviewHandler.SetRect(ref RECT rect) { _windowBounds = rect.ToRectangle(); UpdateWindowBounds(); } protected abstract void Load(PreviewHandlerControl c); void IPreviewHandler.DoPreview() { _showPreview = true; InvokeOnPreviewThread(delegate() { try { Load(_previewControl); } catch(Exception exc) { _previewControl.Controls.Clear(); TextBox text = new TextBox(); text.ReadOnly = true; text.Multiline = true; text.Dock = DockStyle.Fill; text.Text = exc.ToString(); _previewControl.Controls.Add(text); } UpdateWindowBounds(); }); } void IPreviewHandler.Unload() { _showPreview = false; InvokeOnPreviewThread(delegate() { _previewControl.Visible = false; _previewControl.Unload(); }); } void IPreviewHandler.SetFocus() { InvokeOnPreviewThread(delegate() { _previewControl.Focus(); }); } [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern IntPtr GetFocus(); void IPreviewHandler.QueryFocus(out IntPtr phwnd) { IntPtr result = IntPtr.Zero; InvokeOnPreviewThread(delegate() { result = GetFocus(); }); phwnd = result; if (phwnd == IntPtr.Zero) throw new Win32Exception(); } int IPreviewHandler.TranslateAccelerator(ref MSG pmsg) { if (_frame != null) return (int)_frame.TranslateAccelerator(ref pmsg); const int S_FALSE = 1; return S_FALSE; } void IPreviewHandlerVisuals.SetBackgroundColor(COLORREF color) { Color c = color.Color; InvokeOnPreviewThread(delegate() { _previewControl.BackColor = c; }); } void IPreviewHandlerVisuals.SetTextColor(COLORREF color) { Color c = color.Color; InvokeOnPreviewThread(delegate() { _previewControl.ForeColor = c; }); } void IPreviewHandlerVisuals.SetFont(ref LOGFONT plf) { Font f = Font.FromLogFont(plf); InvokeOnPreviewThread(delegate() { _previewControl.Font = f; }); } void IOleWindow.GetWindow(out IntPtr phwnd) { phwnd = IntPtr.Zero; phwnd = _previewControl.Handle; } void IOleWindow.ContextSensitiveHelp(bool fEnterMode) { throw new NotImplementedException(); } void IObjectWithSite.SetSite(object pUnkSite) { _unkSite = pUnkSite; _frame = _unkSite as IPreviewHandlerFrame; } void IObjectWithSite.GetSite(ref Guid riid, out object ppvSite) { ppvSite = _unkSite; } [ComRegisterFunction] public static void Register(Type t) { if (t != null && t.IsSubclassOf(typeof(PreviewHandler))) { object[] attrs = (object[])t.GetCustomAttributes(typeof(PreviewHandlerAttribute), true); if (attrs != null && attrs.Length == 1) { PreviewHandlerAttribute attr = attrs[0] as PreviewHandlerAttribute; RegisterPreviewHandler(attr.Name, attr.Extension, t.GUID.ToString("B"), attr.AppId); } } } [ComUnregisterFunction] public static void Unregister(Type t) { if (t != null && t.IsSubclassOf(typeof(PreviewHandler))) { object[] attrs = (object[])t.GetCustomAttributes(typeof(PreviewHandlerAttribute), true); if (attrs != null && attrs.Length == 1) { PreviewHandlerAttribute attr = attrs[0] as PreviewHandlerAttribute; UnregisterPreviewHandler(attr.Extension, t.GUID.ToString("B"), attr.AppId); } } } protected static void RegisterPreviewHandler(string name, string extensions, string previewerGuid, string appId) { // Create a new prevhost AppID so that this always runs in its own isolated process using (RegistryKey appIdsKey = Registry.ClassesRoot.OpenSubKey("AppID", true)) using (RegistryKey appIdKey = appIdsKey.CreateSubKey(appId)) { appIdKey.SetValue("DllSurrogate", @"%SystemRoot%\system32\prevhost.exe", RegistryValueKind.ExpandString); } // Add preview handler to preview handler list using (RegistryKey handlersKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\PreviewHandlers", true)) { handlersKey.SetValue(previewerGuid, name, RegistryValueKind.String); } // Modify preview handler registration using (RegistryKey clsidKey = Registry.ClassesRoot.OpenSubKey("CLSID")) using (RegistryKey idKey = clsidKey.OpenSubKey(previewerGuid, true)) { idKey.SetValue("DisplayName", name, RegistryValueKind.String); idKey.SetValue("AppID", appId, RegistryValueKind.String); idKey.SetValue("DisableLowILProcessIsolation", 1, RegistryValueKind.DWord); // optional, depending on what preview handler needs to be able to do } foreach (string extension in extensions.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { // Set preview handler for specific extension using (RegistryKey extensionKey = Registry.ClassesRoot.CreateSubKey(extension)) using (RegistryKey shellexKey = extensionKey.CreateSubKey("shellex")) using (RegistryKey previewKey = shellexKey.CreateSubKey("{8895b1c6-b41f-4c1c-a562-0d564250836f}")) { previewKey.SetValue(null, previewerGuid, RegistryValueKind.String); } } } protected static void UnregisterPreviewHandler(string extensions, string previewerGuid, string appId) { foreach (string extension in extensions.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { using (RegistryKey shellexKey = Registry.ClassesRoot.OpenSubKey(extension + "\\shellex", true)) { shellexKey.DeleteSubKey("{8895b1c6-b41f-4c1c-a562-0d564250836f}"); } } using (RegistryKey appIdsKey = Registry.ClassesRoot.OpenSubKey("AppID", true)) { appIdsKey.DeleteSubKey(appId); } using (RegistryKey classesKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\PreviewHandlers", true)) { classesKey.DeleteValue(previewerGuid); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Binary { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Common; /// <summary> /// Write delegate. /// </summary> /// <param name="writer">Write context.</param> /// <param name="obj">Object to write.</param> internal delegate void BinarySystemWriteDelegate(BinaryWriter writer, object obj); /** * <summary>Collection of predefined handlers for various system types.</summary> */ internal static class BinarySystemHandlers { /** Write handlers. */ private static volatile Dictionary<Type, BinarySystemWriteDelegate> _writeHandlers = new Dictionary<Type, BinarySystemWriteDelegate>(); /** Mutex for write handlers update. */ private static readonly object WriteHandlersMux = new object(); /** Read handlers. */ private static readonly IBinarySystemReader[] ReadHandlers = new IBinarySystemReader[255]; /** Type ids. */ private static readonly Dictionary<Type, byte> TypeIds = new Dictionary<Type, byte> { {typeof (bool), BinaryUtils.TypeBool}, {typeof (byte), BinaryUtils.TypeByte}, {typeof (sbyte), BinaryUtils.TypeByte}, {typeof (short), BinaryUtils.TypeShort}, {typeof (ushort), BinaryUtils.TypeShort}, {typeof (char), BinaryUtils.TypeChar}, {typeof (int), BinaryUtils.TypeInt}, {typeof (uint), BinaryUtils.TypeInt}, {typeof (long), BinaryUtils.TypeLong}, {typeof (ulong), BinaryUtils.TypeLong}, {typeof (float), BinaryUtils.TypeFloat}, {typeof (double), BinaryUtils.TypeDouble}, {typeof (string), BinaryUtils.TypeString}, {typeof (decimal), BinaryUtils.TypeDecimal}, {typeof (Guid), BinaryUtils.TypeGuid}, {typeof (Guid?), BinaryUtils.TypeGuid}, {typeof (ArrayList), BinaryUtils.TypeCollection}, {typeof (Hashtable), BinaryUtils.TypeDictionary}, {typeof (bool[]), BinaryUtils.TypeArrayBool}, {typeof (byte[]), BinaryUtils.TypeArrayByte}, {typeof (sbyte[]), BinaryUtils.TypeArrayByte}, {typeof (short[]), BinaryUtils.TypeArrayShort}, {typeof (ushort[]), BinaryUtils.TypeArrayShort}, {typeof (char[]), BinaryUtils.TypeArrayChar}, {typeof (int[]), BinaryUtils.TypeArrayInt}, {typeof (uint[]), BinaryUtils.TypeArrayInt}, {typeof (long[]), BinaryUtils.TypeArrayLong}, {typeof (ulong[]), BinaryUtils.TypeArrayLong}, {typeof (float[]), BinaryUtils.TypeArrayFloat}, {typeof (double[]), BinaryUtils.TypeArrayDouble}, {typeof (string[]), BinaryUtils.TypeArrayString}, {typeof (decimal?[]), BinaryUtils.TypeArrayDecimal}, {typeof (Guid?[]), BinaryUtils.TypeArrayGuid}, {typeof (object[]), BinaryUtils.TypeArray} }; /// <summary> /// Initializes the <see cref="BinarySystemHandlers"/> class. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Readability.")] static BinarySystemHandlers() { // 1. Primitives. ReadHandlers[BinaryUtils.TypeBool] = new BinarySystemReader<bool>(s => s.ReadBool()); ReadHandlers[BinaryUtils.TypeByte] = new BinarySystemReader<byte>(s => s.ReadByte()); ReadHandlers[BinaryUtils.TypeShort] = new BinarySystemReader<short>(s => s.ReadShort()); ReadHandlers[BinaryUtils.TypeChar] = new BinarySystemReader<char>(s => s.ReadChar()); ReadHandlers[BinaryUtils.TypeInt] = new BinarySystemReader<int>(s => s.ReadInt()); ReadHandlers[BinaryUtils.TypeLong] = new BinarySystemReader<long>(s => s.ReadLong()); ReadHandlers[BinaryUtils.TypeFloat] = new BinarySystemReader<float>(s => s.ReadFloat()); ReadHandlers[BinaryUtils.TypeDouble] = new BinarySystemReader<double>(s => s.ReadDouble()); ReadHandlers[BinaryUtils.TypeDecimal] = new BinarySystemReader<decimal?>(BinaryUtils.ReadDecimal); // 2. Date. ReadHandlers[BinaryUtils.TypeTimestamp] = new BinarySystemReader<DateTime?>(BinaryUtils.ReadTimestamp); // 3. String. ReadHandlers[BinaryUtils.TypeString] = new BinarySystemReader<string>(BinaryUtils.ReadString); // 4. Guid. ReadHandlers[BinaryUtils.TypeGuid] = new BinarySystemReader<Guid?>(BinaryUtils.ReadGuid); // 5. Primitive arrays. ReadHandlers[BinaryUtils.TypeArrayBool] = new BinarySystemReader<bool[]>(BinaryUtils.ReadBooleanArray); ReadHandlers[BinaryUtils.TypeArrayByte] = new BinarySystemDualReader<byte[], sbyte[]>(BinaryUtils.ReadByteArray, BinaryUtils.ReadSbyteArray); ReadHandlers[BinaryUtils.TypeArrayShort] = new BinarySystemDualReader<short[], ushort[]>(BinaryUtils.ReadShortArray, BinaryUtils.ReadUshortArray); ReadHandlers[BinaryUtils.TypeArrayChar] = new BinarySystemReader<char[]>(BinaryUtils.ReadCharArray); ReadHandlers[BinaryUtils.TypeArrayInt] = new BinarySystemDualReader<int[], uint[]>(BinaryUtils.ReadIntArray, BinaryUtils.ReadUintArray); ReadHandlers[BinaryUtils.TypeArrayLong] = new BinarySystemDualReader<long[], ulong[]>(BinaryUtils.ReadLongArray, BinaryUtils.ReadUlongArray); ReadHandlers[BinaryUtils.TypeArrayFloat] = new BinarySystemReader<float[]>(BinaryUtils.ReadFloatArray); ReadHandlers[BinaryUtils.TypeArrayDouble] = new BinarySystemReader<double[]>(BinaryUtils.ReadDoubleArray); ReadHandlers[BinaryUtils.TypeArrayDecimal] = new BinarySystemReader<decimal?[]>(BinaryUtils.ReadDecimalArray); // 6. Date array. ReadHandlers[BinaryUtils.TypeArrayTimestamp] = new BinarySystemReader<DateTime?[]>(BinaryUtils.ReadTimestampArray); // 7. String array. ReadHandlers[BinaryUtils.TypeArrayString] = new BinarySystemTypedArrayReader<string>(); // 8. Guid array. ReadHandlers[BinaryUtils.TypeArrayGuid] = new BinarySystemTypedArrayReader<Guid?>(); // 9. Array. ReadHandlers[BinaryUtils.TypeArray] = new BinarySystemReader(ReadArray); // 11. Arbitrary collection. ReadHandlers[BinaryUtils.TypeCollection] = new BinarySystemReader(ReadCollection); // 13. Arbitrary dictionary. ReadHandlers[BinaryUtils.TypeDictionary] = new BinarySystemReader(ReadDictionary); // 14. Enum. ReadHandlers[BinaryUtils.TypeArrayEnum] = new BinarySystemReader(ReadEnumArray); } /// <summary> /// Try getting write handler for type. /// </summary> /// <param name="type"></param> /// <returns></returns> public static BinarySystemWriteDelegate GetWriteHandler(Type type) { BinarySystemWriteDelegate res; var writeHandlers0 = _writeHandlers; // Have we ever met this type? if (writeHandlers0 != null && writeHandlers0.TryGetValue(type, out res)) return res; // Determine write handler for type and add it. res = FindWriteHandler(type); if (res != null) AddWriteHandler(type, res); return res; } /// <summary> /// Find write handler for type. /// </summary> /// <param name="type">Type.</param> /// <returns>Write handler or NULL.</returns> private static BinarySystemWriteDelegate FindWriteHandler(Type type) { // 1. Well-known types. if (type == typeof(string)) return WriteString; if (type == typeof(decimal)) return WriteDecimal; if (type == typeof(DateTime)) return WriteDate; if (type == typeof(Guid)) return WriteGuid; if (type == typeof (BinaryObject)) return WriteBinary; if (type == typeof (BinaryEnum)) return WriteBinaryEnum; if (type == typeof (ArrayList)) return WriteArrayList; if (type == typeof(Hashtable)) return WriteHashtable; if (type.IsArray) { // We know how to write any array type. Type elemType = type.GetElementType(); // Primitives. if (elemType == typeof (bool)) return WriteBoolArray; if (elemType == typeof(byte)) return WriteByteArray; if (elemType == typeof(short)) return WriteShortArray; if (elemType == typeof(char)) return WriteCharArray; if (elemType == typeof(int)) return WriteIntArray; if (elemType == typeof(long)) return WriteLongArray; if (elemType == typeof(float)) return WriteFloatArray; if (elemType == typeof(double)) return WriteDoubleArray; // Non-CLS primitives. if (elemType == typeof(sbyte)) return WriteSbyteArray; if (elemType == typeof(ushort)) return WriteUshortArray; if (elemType == typeof(uint)) return WriteUintArray; if (elemType == typeof(ulong)) return WriteUlongArray; // Special types. if (elemType == typeof (decimal?)) return WriteDecimalArray; if (elemType == typeof(string)) return WriteStringArray; if (elemType == typeof(Guid?)) return WriteGuidArray; // Enums. if (elemType.IsEnum || elemType == typeof(BinaryEnum)) return WriteEnumArray; // Object array. if (elemType == typeof (object) || elemType == typeof(IBinaryObject) || elemType == typeof(BinaryObject)) return WriteArray; } if (type.IsEnum) // We know how to write enums. return WriteEnum; if (type.IsSerializable) return WriteSerializable; return null; } /// <summary> /// Find write handler for type. /// </summary> /// <param name="type">Type.</param> /// <returns>Write handler or NULL.</returns> public static byte GetTypeId(Type type) { byte res; if (TypeIds.TryGetValue(type, out res)) return res; if (type.IsEnum) return BinaryUtils.TypeEnum; if (type.IsArray && type.GetElementType().IsEnum) return BinaryUtils.TypeArrayEnum; return BinaryUtils.TypeObject; } /// <summary> /// Add write handler for type. /// </summary> /// <param name="type"></param> /// <param name="handler"></param> private static void AddWriteHandler(Type type, BinarySystemWriteDelegate handler) { lock (WriteHandlersMux) { if (_writeHandlers == null) { Dictionary<Type, BinarySystemWriteDelegate> writeHandlers0 = new Dictionary<Type, BinarySystemWriteDelegate>(); writeHandlers0[type] = handler; _writeHandlers = writeHandlers0; } else if (!_writeHandlers.ContainsKey(type)) { Dictionary<Type, BinarySystemWriteDelegate> writeHandlers0 = new Dictionary<Type, BinarySystemWriteDelegate>(_writeHandlers); writeHandlers0[type] = handler; _writeHandlers = writeHandlers0; } } } /// <summary> /// Reads an object of predefined type. /// </summary> public static bool TryReadSystemType<T>(byte typeId, BinaryReader ctx, out T res) { var handler = ReadHandlers[typeId]; if (handler == null) { res = default(T); return false; } res = handler.Read<T>(ctx); return true; } /// <summary> /// Write decimal. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteDecimal(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeDecimal); BinaryUtils.WriteDecimal((decimal)obj, ctx.Stream); } /// <summary> /// Write date. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteDate(BinaryWriter ctx, object obj) { ctx.Write(new DateTimeHolder((DateTime) obj)); } /// <summary> /// Write string. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Object.</param> private static void WriteString(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeString); BinaryUtils.WriteString((string)obj, ctx.Stream); } /// <summary> /// Write Guid. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteGuid(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeGuid); BinaryUtils.WriteGuid((Guid)obj, ctx.Stream); } /// <summary> /// Write boolaen array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteBoolArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayBool); BinaryUtils.WriteBooleanArray((bool[])obj, ctx.Stream); } /// <summary> /// Write byte array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteByteArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayByte); BinaryUtils.WriteByteArray((byte[])obj, ctx.Stream); } /// <summary> /// Write sbyte array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteSbyteArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayByte); BinaryUtils.WriteByteArray((byte[]) obj, ctx.Stream); } /// <summary> /// Write short array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteShortArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayShort); BinaryUtils.WriteShortArray((short[])obj, ctx.Stream); } /// <summary> /// Write ushort array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteUshortArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayShort); BinaryUtils.WriteShortArray((short[]) obj, ctx.Stream); } /// <summary> /// Write char array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteCharArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayChar); BinaryUtils.WriteCharArray((char[])obj, ctx.Stream); } /// <summary> /// Write int array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteIntArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayInt); BinaryUtils.WriteIntArray((int[])obj, ctx.Stream); } /// <summary> /// Write uint array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteUintArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayInt); BinaryUtils.WriteIntArray((int[]) obj, ctx.Stream); } /// <summary> /// Write long array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteLongArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayLong); BinaryUtils.WriteLongArray((long[])obj, ctx.Stream); } /// <summary> /// Write ulong array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteUlongArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayLong); BinaryUtils.WriteLongArray((long[]) obj, ctx.Stream); } /// <summary> /// Write float array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteFloatArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayFloat); BinaryUtils.WriteFloatArray((float[])obj, ctx.Stream); } /// <summary> /// Write double array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteDoubleArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayDouble); BinaryUtils.WriteDoubleArray((double[])obj, ctx.Stream); } /// <summary> /// Write decimal array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteDecimalArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayDecimal); BinaryUtils.WriteDecimalArray((decimal?[])obj, ctx.Stream); } /// <summary> /// Write string array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteStringArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayString); BinaryUtils.WriteStringArray((string[])obj, ctx.Stream); } /// <summary> /// Write nullable GUID array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteGuidArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayGuid); BinaryUtils.WriteGuidArray((Guid?[])obj, ctx.Stream); } /** * <summary>Write enum array.</summary> */ private static void WriteEnumArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayEnum); BinaryUtils.WriteArray((Array)obj, ctx); } /** * <summary>Write array.</summary> */ private static void WriteArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArray); BinaryUtils.WriteArray((Array)obj, ctx); } /** * <summary>Write ArrayList.</summary> */ private static void WriteArrayList(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeCollection); BinaryUtils.WriteCollection((ICollection)obj, ctx, BinaryUtils.CollectionArrayList); } /** * <summary>Write Hashtable.</summary> */ private static void WriteHashtable(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeDictionary); BinaryUtils.WriteDictionary((IDictionary)obj, ctx, BinaryUtils.MapHashMap); } /** * <summary>Write binary object.</summary> */ private static void WriteBinary(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeBinary); BinaryUtils.WriteBinary(ctx.Stream, (BinaryObject)obj); } /// <summary> /// Write enum. /// </summary> private static void WriteEnum(BinaryWriter ctx, object obj) { ctx.WriteEnum(obj); } /// <summary> /// Write enum. /// </summary> private static void WriteBinaryEnum(BinaryWriter ctx, object obj) { var binEnum = (BinaryEnum) obj; ctx.Stream.WriteByte(BinaryUtils.TypeEnum); ctx.WriteInt(binEnum.TypeId); ctx.WriteInt(binEnum.EnumValue); } /// <summary> /// Writes serializable. /// </summary> /// <param name="writer">The writer.</param> /// <param name="o">The object.</param> private static void WriteSerializable(BinaryWriter writer, object o) { writer.Write(new SerializableObjectHolder(o)); } /** * <summary>Read enum array.</summary> */ private static object ReadEnumArray(BinaryReader ctx, Type type) { return BinaryUtils.ReadTypedArray(ctx, true, type.GetElementType()); } /** * <summary>Read array.</summary> */ private static object ReadArray(BinaryReader ctx, Type type) { var elemType = type.IsArray ? type.GetElementType() : typeof(object); return BinaryUtils.ReadTypedArray(ctx, true, elemType); } /** * <summary>Read collection.</summary> */ private static object ReadCollection(BinaryReader ctx, Type type) { return BinaryUtils.ReadCollection(ctx, null, null); } /** * <summary>Read dictionary.</summary> */ private static object ReadDictionary(BinaryReader ctx, Type type) { return BinaryUtils.ReadDictionary(ctx, null); } /** * <summary>Read delegate.</summary> * <param name="ctx">Read context.</param> * <param name="type">Type.</param> */ private delegate object BinarySystemReadDelegate(BinaryReader ctx, Type type); /// <summary> /// System type reader. /// </summary> private interface IBinarySystemReader { /// <summary> /// Reads a value of specified type from reader. /// </summary> T Read<T>(BinaryReader ctx); } /// <summary> /// System type generic reader. /// </summary> private interface IBinarySystemReader<out T> { /// <summary> /// Reads a value of specified type from reader. /// </summary> T Read(BinaryReader ctx); } /// <summary> /// Default reader with boxing. /// </summary> private class BinarySystemReader : IBinarySystemReader { /** */ private readonly BinarySystemReadDelegate _readDelegate; /// <summary> /// Initializes a new instance of the <see cref="BinarySystemReader"/> class. /// </summary> /// <param name="readDelegate">The read delegate.</param> public BinarySystemReader(BinarySystemReadDelegate readDelegate) { Debug.Assert(readDelegate != null); _readDelegate = readDelegate; } /** <inheritdoc /> */ public T Read<T>(BinaryReader ctx) { return (T)_readDelegate(ctx, typeof(T)); } } /// <summary> /// Reader without boxing. /// </summary> private class BinarySystemReader<T> : IBinarySystemReader { /** */ private readonly Func<IBinaryStream, T> _readDelegate; /// <summary> /// Initializes a new instance of the <see cref="BinarySystemReader{T}"/> class. /// </summary> /// <param name="readDelegate">The read delegate.</param> public BinarySystemReader(Func<IBinaryStream, T> readDelegate) { Debug.Assert(readDelegate != null); _readDelegate = readDelegate; } /** <inheritdoc /> */ public TResult Read<TResult>(BinaryReader ctx) { return TypeCaster<TResult>.Cast(_readDelegate(ctx.Stream)); } } /// <summary> /// Reader without boxing. /// </summary> private class BinarySystemTypedArrayReader<T> : IBinarySystemReader { public TResult Read<TResult>(BinaryReader ctx) { return TypeCaster<TResult>.Cast(BinaryUtils.ReadArray<T>(ctx, false)); } } /// <summary> /// Reader with selection based on requested type. /// </summary> private class BinarySystemDualReader<T1, T2> : IBinarySystemReader, IBinarySystemReader<T2> { /** */ private readonly Func<IBinaryStream, T1> _readDelegate1; /** */ private readonly Func<IBinaryStream, T2> _readDelegate2; /// <summary> /// Initializes a new instance of the <see cref="BinarySystemDualReader{T1,T2}"/> class. /// </summary> /// <param name="readDelegate1">The read delegate1.</param> /// <param name="readDelegate2">The read delegate2.</param> public BinarySystemDualReader(Func<IBinaryStream, T1> readDelegate1, Func<IBinaryStream, T2> readDelegate2) { Debug.Assert(readDelegate1 != null); Debug.Assert(readDelegate2 != null); _readDelegate1 = readDelegate1; _readDelegate2 = readDelegate2; } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")] T2 IBinarySystemReader<T2>.Read(BinaryReader ctx) { return _readDelegate2(ctx.Stream); } /** <inheritdoc /> */ public T Read<T>(BinaryReader ctx) { // Can't use "as" because of variance. // For example, IBinarySystemReader<byte[]> can be cast to IBinarySystemReader<sbyte[]>, which // will cause incorrect behavior. if (typeof (T) == typeof (T2)) return ((IBinarySystemReader<T>) this).Read(ctx); return TypeCaster<T>.Cast(_readDelegate1(ctx.Stream)); } } } }
// Copyright 2011, Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Author: api.anash@gmail.com (Anash P. Oommen) using Google.Api.Ads.Common.Lib; using Google.Api.Ads.Common.Util; using Google.Api.Ads.Dfa.Util; using System; using System.IO; using System.Net; using System.Reflection; using System.Text; using System.Web.Services; using System.Web.Services.Protocols; using System.Xml; using System.Xml.Serialization; using System.Web.Services.Configuration; namespace Google.Api.Ads.Dfa.Lib { /// <summary> /// Base class for DFA API services. /// </summary> public class DfaSoapClient : AdsSoapClient { /// <summary> /// The user token for authentication purposes. /// </summary> UserToken token = null; /// <summary> /// The optional request header for sending additional details. /// </summary> RequestHeader requestHeader = null; /// <summary> /// The response header from DFA server. /// </summary> ResponseHeader responseHeader = null; /// <summary> /// Gets or sets the request header. /// </summary> public RequestHeader RequestHeader { get { return requestHeader; } set { requestHeader = value; } } /// <summary> /// Gets or sets the response header. /// </summary> public ResponseHeader ResponseHeader { get { return responseHeader; } set { responseHeader = value; } } /// <summary> /// Gets or sets the token for authentication purposes. /// </summary> public UserToken Token { get { return token; } set { token = value; } } /// <summary> /// Initializes the service before MakeApiCall. /// </summary> /// <param name="methodName">Name of the method.</param> /// <param name="parameters">The method parameters.</param> protected override void InitForCall(string methodName, object[] parameters) { DfaAppConfig config = this.User.Config as DfaAppConfig; string oAuthHeader = null; if (this.GetType().Name == "LoginRemoteService") { // The choice of OAuth comes only when calling LoginRemoteService. // All other services will still use the login token. if (config.AuthorizationMethod == DfaAuthorizationMethod.OAuth2) { if (this.User.OAuthProvider != null) { oAuthHeader = this.User.OAuthProvider.GetAuthHeader(); } else { throw new DfaApiException(null, DfaErrorMessages.OAuthProviderCannotBeNull); } } } else { if (this.Token == null) { this.Token = LoginUtil.GetAuthenticationToken(this.User, this.Signature.Version); } } ContextStore.AddKey("OAuthHeader", oAuthHeader); ContextStore.AddKey("RequestHeader", requestHeader); ContextStore.AddKey("Token", Token); base.InitForCall(methodName, parameters); } /// <summary> /// Cleans up the service after MakeApiCall. /// </summary> /// <param name="methodName">Name of the method.</param> /// <param name="parameters">The method parameters.</param> protected override void CleanupAfterCall(string methodName, object[] parameters) { this.ResponseHeader = (ResponseHeader) ContextStore.GetValue("ResponseHeader"); ContextStore.RemoveKey("OAuthHeader"); ContextStore.RemoveKey("RequestHeader"); ContextStore.RemoveKey("ResponseHeader"); ContextStore.RemoveKey("Token"); base.CleanupAfterCall(methodName, parameters); } /// <summary> /// Creates a WebRequest instance for the specified url. /// </summary> /// <param name="uri">The Uri to use when creating the WebRequest.</param> /// <returns> /// The WebRequest instance. /// </returns> protected override WebRequest GetWebRequest(Uri uri) { WebRequest request = base.GetWebRequest(uri); string oAuthHeader = (string) ContextStore.GetValue("OAuthHeader"); if (!string.IsNullOrEmpty(oAuthHeader)) { request.Headers["Authorization"] = oAuthHeader; } return request; } /// <summary> /// Creates the error handler. /// </summary> /// <returns> /// The error handler instance. /// </returns> protected override ErrorHandler CreateErrorHandler() { return new DfaErrorHandler(this); } /// <summary> /// Gets a custom exception that wraps the SOAP exception thrown /// by the server. /// </summary> /// <param name="ex">SOAPException that was thrown by the server.</param> /// <returns>A custom exception object that wraps the SOAP exception. /// </returns> protected override Exception GetCustomException(SoapException ex) { string defaultNs = GetDefaultNamespace(); object apiException = Activator.CreateInstance(Type.GetType( this.GetType().Namespace + ".ApiException")); XmlNode faultNode = GetDetailsNode(ex); ErrorCode errorCode = null; if (faultNode != null) { errorCode = new ErrorCode(); foreach (XmlElement xNode in faultNode.SelectNodes("*")) { switch (xNode.Name) { case "errorCode": errorCode.Code = int.Parse(xNode.InnerText); break; case "errorMessage": errorCode.Description = xNode.InnerText; break; } } } DfaApiException dfaApiException = new DfaApiException(errorCode, ex.Message, ex); if (DfaErrorHandler.IsTokenExpiredError(dfaApiException)) { return new DfaCredentialsExpiredException(this.Token); } else { return dfaApiException; } } /// <summary> /// Gets the details node for the SOAP exception. /// </summary> /// <param name="ex">The SOAP exception.</param> /// <returns>The details node.</returns> private static XmlNode GetDetailsNode(SoapException ex) { String[] possibleNodeNames = { "com.doubleclick.dart.appserver.dfa.dto.api.ApiException", "com.google.ads.xfa.soapapi.entity.common.ApiException" }; foreach (String nodeName in possibleNodeNames) { XmlNode faultNode = ex.Detail.SelectSingleNode(nodeName); if (faultNode != null) { return faultNode; } } return null; } } }
// 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.Globalization; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml { internal abstract partial class AbstractMethodXmlBuilder { private const string ArgumentElementName = "Argument"; private const string ArrayElementName = "Array"; private const string ArrayElementAccessElementName = "ArrayElementAccess"; private const string ArrayTypeElementName = "ArrayType"; private const string AssignmentElementName = "Assignment"; private const string BaseReferenceElementName = "BaseReference"; private const string BinaryOperationElementName = "BinaryOperation"; private const string BlockElementName = "Block"; private const string BooleanElementName = "Boolean"; private const string BoundElementName = "Bound"; private const string CastElementName = "Cast"; private const string CharElementName = "Char"; private const string CommentElementName = "Comment"; private const string ExpressionElementName = "Expression"; private const string ExpressionStatementElementName = "ExpressionStatement"; private const string LiteralElementName = "Literal"; private const string LocalElementName = "Local"; private const string MethodCallElementName = "MethodCall"; private const string NameElementName = "Name"; private const string NameRefElementName = "NameRef"; private const string NewArrayElementName = "NewArray"; private const string NewClassElementName = "NewClass"; private const string NewDelegateElementName = "NewDelegate"; private const string NullElementName = "Null"; private const string NumberElementName = "Number"; private const string ParenthesesElementName = "Parentheses"; private const string QuoteElementName = "Quote"; private const string StringElementName = "String"; private const string ThisReferenceElementName = "ThisReference"; private const string TypeElementName = "Type"; private const string BinaryOperatorAttributeName = "binaryoperator"; private const string FullNameAttributeName = "fullname"; private const string ImplicitAttributeName = "implicit"; private const string LineAttributeName = "line"; private const string NameAttributeName = "name"; private const string RankAttributeName = "rank"; private const string TypeAttributeName = "type"; private const string VariableKindAttributeName = "variablekind"; private static readonly char[] s_encodedChars = new[] { '<', '>', '&' }; private static readonly string[] s_encodings = new[] { "&lt;", "&gt;", "&amp;" }; private readonly StringBuilder _builder; protected readonly IMethodSymbol Symbol; protected readonly SemanticModel SemanticModel; protected readonly SourceText Text; protected AbstractMethodXmlBuilder(IMethodSymbol symbol, SemanticModel semanticModel) { _builder = new StringBuilder(); this.Symbol = symbol; this.SemanticModel = semanticModel; this.Text = semanticModel.SyntaxTree.GetText(); } public override string ToString() { return _builder.ToString(); } private void AppendEncoded(string text) { var length = text.Length; var startIndex = 0; int index; for (index = 0; index < length; index++) { var encodingIndex = Array.IndexOf(s_encodedChars, text[index]); if (encodingIndex >= 0) { if (index > startIndex) { _builder.Append(text, startIndex, index - startIndex); } _builder.Append(s_encodings[encodingIndex]); startIndex = index + 1; } } if (index > startIndex) { _builder.Append(text, startIndex, index - startIndex); } } private void AppendOpenTag(string name, AttributeInfo[] attributes) { _builder.Append('<'); _builder.Append(name); foreach (var attribute in attributes.Where(a => !a.IsEmpty)) { _builder.Append(' '); _builder.Append(attribute.Name); _builder.Append("=\""); AppendEncoded(attribute.Value); _builder.Append('"'); } _builder.Append('>'); } private void AppendCloseTag(string name) { _builder.Append("</"); _builder.Append(name); _builder.Append('>'); } private void AppendLeafTag(string name) { _builder.Append('<'); _builder.Append(name); _builder.Append("/>"); } private static string GetBinaryOperatorKindText(BinaryOperatorKind kind) { switch (kind) { case BinaryOperatorKind.Plus: return "plus"; case BinaryOperatorKind.BitwiseOr: return "bitor"; case BinaryOperatorKind.BitwiseAnd: return "bitand"; case BinaryOperatorKind.Concatenate: return "concatenate"; case BinaryOperatorKind.AddDelegate: return "adddelegate"; default: throw new InvalidOperationException("Invalid BinaryOperatorKind: " + kind.ToString()); } } private static string GetVariableKindText(VariableKind kind) { switch (kind) { case VariableKind.Property: return "property"; case VariableKind.Method: return "method"; case VariableKind.Field: return "field"; case VariableKind.Local: return "local"; case VariableKind.Unknown: return "unknown"; default: throw new InvalidOperationException("Invalid SymbolKind: " + kind.ToString()); } } private IDisposable Tag(string name, params AttributeInfo[] attributes) { return new AutoTag(this, name, attributes); } private AttributeInfo BinaryOperatorAttribute(BinaryOperatorKind kind) { if (kind == BinaryOperatorKind.None) { return AttributeInfo.Empty; } return new AttributeInfo(BinaryOperatorAttributeName, GetBinaryOperatorKindText(kind)); } private AttributeInfo FullNameAttribute(string name) { if (string.IsNullOrWhiteSpace(name)) { return AttributeInfo.Empty; } return new AttributeInfo(FullNameAttributeName, name); } private AttributeInfo ImplicitAttribute(bool? @implicit) { if (@implicit == null) { return AttributeInfo.Empty; } return new AttributeInfo(ImplicitAttributeName, @implicit.Value ? "yes" : "no"); } private AttributeInfo LineNumberAttribute(int lineNumber) { return new AttributeInfo(LineAttributeName, lineNumber.ToString()); } private AttributeInfo NameAttribute(string name) { if (string.IsNullOrWhiteSpace(name)) { return AttributeInfo.Empty; } return new AttributeInfo(NameAttributeName, name); } private AttributeInfo RankAttribute(int rank) { return new AttributeInfo(RankAttributeName, rank.ToString()); } private AttributeInfo TypeAttribute(string typeName) { if (string.IsNullOrWhiteSpace(typeName)) { return AttributeInfo.Empty; } return new AttributeInfo(TypeAttributeName, typeName); } private AttributeInfo VariableKindAttribute(VariableKind kind) { if (kind == VariableKind.None) { return AttributeInfo.Empty; } return new AttributeInfo(VariableKindAttributeName, GetVariableKindText(kind)); } protected IDisposable ArgumentTag() { return Tag(ArgumentElementName); } protected IDisposable ArrayElementAccessTag() { return Tag(ArrayElementAccessElementName); } protected IDisposable ArrayTag() { return Tag(ArrayElementName); } protected IDisposable ArrayTypeTag(int rank) { return Tag(ArrayTypeElementName, RankAttribute(rank)); } protected IDisposable AssignmentTag(BinaryOperatorKind kind = BinaryOperatorKind.None) { return Tag(AssignmentElementName, BinaryOperatorAttribute(kind)); } protected void BaseReferenceTag() { AppendLeafTag(BaseReferenceElementName); } protected IDisposable BinaryOperationTag(BinaryOperatorKind kind) { return Tag(BinaryOperationElementName, BinaryOperatorAttribute(kind)); } protected IDisposable BlockTag() { return Tag(BlockElementName); } protected IDisposable BooleanTag() { return Tag(BooleanElementName); } protected IDisposable BoundTag() { return Tag(BoundElementName); } protected IDisposable CastTag() { return Tag(CastElementName); } protected IDisposable CharTag() { return Tag(CharElementName); } protected IDisposable CommentTag() { return Tag(CommentElementName); } protected IDisposable ExpressionTag() { return Tag(ExpressionElementName); } protected IDisposable ExpressionStatementTag(int lineNumber) { return Tag(ExpressionStatementElementName, LineNumberAttribute(lineNumber)); } protected IDisposable LiteralTag() { return Tag(LiteralElementName); } protected IDisposable LocalTag(int lineNumber) { return Tag(LocalElementName, LineNumberAttribute(lineNumber)); } protected IDisposable MethodCallTag() { return Tag(MethodCallElementName); } protected IDisposable NameTag() { return Tag(NameElementName); } protected IDisposable NameRefTag(VariableKind kind, string name = null, string fullName = null) { return Tag(NameRefElementName, VariableKindAttribute(kind), NameAttribute(name), FullNameAttribute(fullName)); } protected IDisposable NewArrayTag() { return Tag(NewArrayElementName); } protected IDisposable NewClassTag() { return Tag(NewClassElementName); } protected IDisposable NewDelegateTag(string name) { return Tag(NewDelegateElementName, NameAttribute(name)); } protected void NullTag() { AppendLeafTag(NullElementName); } protected IDisposable NumberTag(string typeName = null) { return Tag(NumberElementName, TypeAttribute(typeName)); } protected IDisposable ParenthesesTag() { return Tag(ParenthesesElementName); } protected IDisposable QuoteTag(int lineNumber) { return Tag(QuoteElementName, LineNumberAttribute(lineNumber)); } protected IDisposable StringTag() { return Tag(StringElementName); } protected void ThisReferenceTag() { AppendLeafTag(ThisReferenceElementName); } protected IDisposable TypeTag(bool? @implicit = null) { return Tag(TypeElementName, ImplicitAttribute(@implicit)); } protected void LineBreak() { _builder.AppendLine(); } protected void EncodedText(string text) { AppendEncoded(text); } protected int GetMark() { return _builder.Length; } protected void Rewind(int mark) { _builder.Length = mark; } protected virtual VariableKind GetVariableKind(ISymbol symbol) { if (symbol == null) { return VariableKind.Unknown; } switch (symbol.Kind) { case SymbolKind.Event: case SymbolKind.Field: return VariableKind.Field; case SymbolKind.Local: case SymbolKind.Parameter: return VariableKind.Local; case SymbolKind.Method: return VariableKind.Method; case SymbolKind.Property: return VariableKind.Property; default: throw new InvalidOperationException("Invalid symbol kind: " + symbol.Kind.ToString()); } } protected string GetTypeName(ITypeSymbol typeSymbol) { return MetadataNameHelpers.GetMetadataName(typeSymbol); } protected int GetLineNumber(SyntaxNode node) { return Text.Lines.IndexOf(node.SpanStart); } protected void GenerateUnknown(SyntaxNode node) { using (QuoteTag(GetLineNumber(node))) { EncodedText(node.ToString()); } } protected void GenerateName(string name) { using (NameTag()) { EncodedText(name); } } protected void GenerateType(ITypeSymbol type, bool? @implicit = null, bool assemblyQualify = false) { if (type.TypeKind == TypeKind.Array) { var arrayType = (IArrayTypeSymbol)type; using (var tag = ArrayTypeTag(arrayType.Rank)) { GenerateType(arrayType.ElementType, @implicit, assemblyQualify); } } else { using (TypeTag(@implicit)) { var typeName = assemblyQualify ? GetTypeName(type) + ", " + type.ContainingAssembly.ToDisplayString() : GetTypeName(type); EncodedText(typeName); } } } protected void GenerateType(SpecialType specialType) { GenerateType(SemanticModel.Compilation.GetSpecialType(specialType)); } protected void GenerateNullLiteral() { using (LiteralTag()) { NullTag(); } } protected void GenerateNumber(object value, ITypeSymbol type) { using (NumberTag(GetTypeName(type))) { if (value is double) { // Note: use G17 for doubles to ensure that we roundtrip properly on 64-bit EncodedText(((double)value).ToString("G17", CultureInfo.InvariantCulture)); } else if (value is float) { EncodedText(((float)value).ToString("R", CultureInfo.InvariantCulture)); } else { EncodedText(Convert.ToString(value, CultureInfo.InvariantCulture)); } } } protected void GenerateNumber(object value, SpecialType specialType) { GenerateNumber(value, SemanticModel.Compilation.GetSpecialType(specialType)); } protected void GenerateChar(char value) { using (CharTag()) { EncodedText(value.ToString()); } } protected void GenerateString(string value) { using (StringTag()) { EncodedText(value); } } protected void GenerateBoolean(bool value) { using (BooleanTag()) { EncodedText(value.ToString().ToLower()); } } protected void GenerateThisReference() { ThisReferenceTag(); } protected void GenerateBaseReference() { BaseReferenceTag(); } } }
// 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 Microsoft.Build.Framework; using Microsoft.Build.Utilities; using NuGet.Frameworks; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Microsoft.DotNet.Build.Tasks.Packaging { public class CreateTrimDependencyGroups : PackagingTask { [Required] public string FrameworkListsPath { get; set; } [Required] public ITaskItem[] Dependencies { get; set; } [Required] public ITaskItem[] Files { get; set; } [Output] public ITaskItem[] TrimmedDependencies { get; set; } public bool UseNetPlatform { get; set; } /* Given a set of available frameworks ("InboxOnTargetFrameworks"), and a list of desired frameworks, reduce the set of frameworks to the minimum set of frameworks which is compatible (preferring inbox frameworks. */ public override bool Execute() { if (null == Dependencies) { Log.LogError("Dependencies argument must be specified"); return false; } if (null == FrameworkListsPath) { Log.LogError("FrameworkListsPath argument must be specified"); return false; } // Retrieve the list of generation dependency group TFM's var dependencyGroups = Dependencies.GroupBy(d => d.GetMetadata("TargetFramework")).Select(dg => new { Framework = NuGetFramework.Parse(dg.Key), Dependencies = dg.ToArray() }); List<ITaskItem> addedDependencies = new List<ITaskItem>(); // Exclude any non-portable frameworks that already have specific dependency groups. var frameworksToExclude = dependencyGroups.Select(dg => dg.Framework).Where(fx => !FrameworkUtilities.IsGenerationMoniker(fx)); // Prepare a resolver for evaluating if candidate frameworks are actually supported by the package PackageItem[] packageItems = Files.Select(f => new PackageItem(f)).ToArray(); var packagePaths = packageItems.Select(pi => pi.TargetPath); var targetFrameworksWithPlaceHolders = packageItems.Where(pi => NuGetAssetResolver.IsPlaceholder(pi.TargetPath)).Select(pi => pi.TargetFramework); NuGetAssetResolver resolver = new NuGetAssetResolver(null, packagePaths); foreach (var portableDependencyGroup in dependencyGroups.Where(dg => FrameworkUtilities.IsGenerationMoniker(dg.Framework))) { // Determine inbox frameworks for this generation that don't already have explicit groups HashSet<NuGetFramework> inboxFrameworksList = new HashSet<NuGetFramework>( Frameworks.GetAlllInboxFrameworks(FrameworkListsPath) .Where(fx => !fx.IsPCL) .Where(fx => Generations.DetermineGenerationForFramework(fx, UseNetPlatform) >= portableDependencyGroup.Framework.Version && !frameworksToExclude.Any(exFx => exFx.Framework == fx.Framework && exFx.Version <= fx.Version))); // Check for assets which have a ref, but not a lib asset. If we have any of these, then they are actually not supported frameworks // and we should not include them. inboxFrameworksList.RemoveWhere(inboxFx => !IsSupported(inboxFx, resolver)); // Only add the lowest version for a particular inbox framework. EG if both net45 and net46 are supported by this generation, // only add net45 inboxFrameworksList.RemoveWhere(fx => inboxFrameworksList.Any(otherFx => (otherFx.Framework.Equals(fx.Framework)) && (otherFx.Version < fx.Version))); // Create dependency items for each inbox framework. foreach (var framework in inboxFrameworksList) { bool addedDependencyToFramework = false; foreach (ITaskItem dependency in portableDependencyGroup.Dependencies) { string version = GetVersion(dependency); if (!Frameworks.IsInbox(FrameworkListsPath, framework, dependency.ItemSpec, version)) { addedDependencyToFramework = true; AddDependency(addedDependencies, new TaskItem(dependency), framework, portableDependencyGroup.Framework); } } if (!addedDependencyToFramework) { AddDependency(addedDependencies, new TaskItem("_._"), framework, portableDependencyGroup.Framework); } } } // Collapse frameworks // For any dependency with a targetframework, if there is another target framework which is compatible and older, remove this dependency. // Get all Dependencies which are not in a portable dependency group so that we can collapse the frameworks. If we include // the portable frameworks, then we'll end up collapsing to those. List<NuGetFramework> allDependencyGroups = new List<NuGetFramework>(); allDependencyGroups.AddRange(Dependencies.Select(d => NuGetFramework.Parse(d.GetMetadata("TargetFramework"))).Where(a => !allDependencyGroups.Contains(a) && !FrameworkUtilities.IsGenerationMoniker(a) && !FrameworkUtilities.IsPortableMoniker(a))); allDependencyGroups.AddRange(addedDependencies.Select(d => NuGetFramework.Parse(d.GetMetadata("TargetFramework"))).Where(a => !allDependencyGroups.Contains(a) && !FrameworkUtilities.IsGenerationMoniker(a) && !FrameworkUtilities.IsPortableMoniker(a))); List<NuGetFramework> collapsedDependencyGroups = FrameworkUtilities.ReduceDownwards(allDependencyGroups).ToList<NuGetFramework>(); // Get the list of dependency groups that we collapsed down so that we can add them back if they contained different dependencies than what is present in the collapsed group. /* TODO: Look into NuGet's sorting algorithm, they may have a bug (fixed in this line). They were not including version in the sort. See ReduceCore in https://github.com/NuGet/NuGet.Client/blob/23ea68b91a439fcfd7f94bcd01bcdee2e8adae92/src/NuGet.Core/NuGet.Frameworks/FrameworkReducer.cs */ IEnumerable<NuGetFramework> removedDependencyGroups = allDependencyGroups.Where(d => !collapsedDependencyGroups.Contains(d))?.OrderBy(f => f.Framework, StringComparer.OrdinalIgnoreCase).ThenBy(f => f.Version); foreach (NuGetFramework removedDependencyGroup in removedDependencyGroups) { // always recalculate collapsedDependencyGroups in case we added an item in a previous iteration. Dependency groups are sorted, so this should be additive and we shouldn't need to restart the collapse / add back cycle var nearest = FrameworkUtilities.GetNearest(removedDependencyGroup, collapsedDependencyGroups.ToArray()); // gather the dependencies for this dependency group and the calculated "nearest" dependency group var nearestDependencies = addedDependencies.Where(d => nearest.Equals(NuGetFramework.Parse(d.GetMetadata("TargetFramework")))).OrderBy(f => f.ToString()); var currentDependencies = addedDependencies.Where(d => removedDependencyGroup.Equals(NuGetFramework.Parse(d.GetMetadata("TargetFramework")))).OrderBy(f => f.ToString()); // The nearest dependency group's dependencies are different than this dependency group's dependencies if (nearestDependencies.Count() != currentDependencies.Count()) { // ignore if dependency is a placeholder if (currentDependencies.Count() > 0) { if (!NuGetAssetResolver.IsPlaceholder(currentDependencies.First().ToString())) { collapsedDependencyGroups.Add(removedDependencyGroup); } } else { collapsedDependencyGroups.Add(removedDependencyGroup); } } // identical dependency count between current and nearest, and the count is > 0 else if (nearestDependencies.Count() > 0) { if (!currentDependencies.SequenceEqual(nearestDependencies, new DependencyITaskItemComparer())) { collapsedDependencyGroups.Add(removedDependencyGroup); } } } List<ITaskItem> collapsedDependencies = new List<ITaskItem>(); foreach (ITaskItem dependency in addedDependencies) { if (collapsedDependencyGroups.Contains(NuGetFramework.Parse(dependency.GetMetadata("TargetFramework")))) { collapsedDependencies.Add(dependency); } } TrimmedDependencies = collapsedDependencies.ToArray(); return !Log.HasLoggedErrors; } private bool IsSupported(NuGetFramework inboxFx, NuGetAssetResolver resolver) { var compileAssets = resolver.ResolveCompileAssets(inboxFx); // We assume that packages will only support inbox frameworks with lib/tfm assets and not runtime specific assets. // This effectively means we'll never reduce dependencies if a package happens to support an inbox framework with // a RID asset, but that is OK because RID assets can only be used by nuget3 + project.json // and we don't care about reducing dependencies for project.json because indirect dependencies are hidden. var runtimeAssets = resolver.ResolveRuntimeAssets(inboxFx, null); foreach (var compileAsset in compileAssets.Where(c => !NuGetAssetResolver.IsPlaceholder(c))) { string fileName = Path.GetFileName(compileAsset); if (!runtimeAssets.Any(r => Path.GetFileName(r).Equals(fileName, StringComparison.OrdinalIgnoreCase))) { // ref with no matching lib return false; } } // Either all compile assets had matching runtime assets, or all were placeholders, make sure we have at // least one runtime asset to cover the placeholder case return runtimeAssets.Any(); } private static string GetVersion(ITaskItem dependency) { // If we don't have the AssemblyVersion metadata (4 part version string), fall back and use Version (3 part version string) string version = dependency.GetMetadata("AssemblyVersion"); if (string.IsNullOrEmpty(version)) { version = dependency.GetMetadata("Version"); int prereleaseIndex = version.IndexOf('-'); if (prereleaseIndex != -1) { version = version.Substring(0, prereleaseIndex); } } return version; } private static void AddDependency(List<ITaskItem> dependencies, ITaskItem item, NuGetFramework targetFramework, NuGetFramework generation) { item.SetMetadata("TargetFramework", targetFramework.GetShortFolderName()); // "Generation" is not required metadata, we just include it because it can be useful for debugging. item.SetMetadata("Generation", generation.GetShortFolderName()); dependencies.Add(item); } } public class DependencyITaskItemComparer : IEqualityComparer<ITaskItem> { public bool Equals(ITaskItem x, ITaskItem y) { if (x.ToString().Equals(y.ToString()) && x.GetMetadata("Version") == y.GetMetadata("Version")) { return true; } return false; } public int GetHashCode(ITaskItem dependency) { //Check whether the object is null if (Object.ReferenceEquals(dependency, null)) return 0; int hashDependencyName = dependency.GetHashCode(); int hashDependencyVersion = dependency.GetMetadata("Version").GetHashCode(); //Calculate the hash code for the NuGetFramework. return hashDependencyName ^ hashDependencyVersion; } } }
using System; using System.IO; using System.Text; using Axiom.Core; using Axiom.MathLib; namespace Axiom.Serialization { /// <summary> /// Summary description for Serializer. /// </summary> public class Serializer { #region Fields /// <summary> /// Version string of this serializer. /// </summary> protected string version; /// <summary> /// Length of the chunk that is currently being processed. /// </summary> protected int currentChunkLength; /// <summary> /// Chunk ID + size (short + long). /// </summary> public const int ChunkOverheadSize = 6; #endregion Fields #region Constructor /// <summary> /// Default constructor. /// </summary> public Serializer() { // default binary file version version = "[Serializer_v1.00]"; } #endregion Constructor #region Methods /// <summary> /// Skips past a particular chunk. /// </summary> /// <remarks> /// Only really used during development, when logic for handling particular chunks is not yet complete. /// </remarks> protected void IgnoreCurrentChunk(BinaryMemoryReader reader) { Seek(reader, currentChunkLength - ChunkOverheadSize); } /// <summary> /// Reads a specified number of floats and copies them into the destination pointer. /// </summary> /// <param name="count">Number of values to read.</param> /// <param name="dest">Pointer to copy the values into.</param> protected void ReadBytes(BinaryMemoryReader reader, int count, IntPtr dest) { // blast the data into the buffer unsafe { byte* pointer = (byte*)dest.ToPointer(); for(int i = 0; i < count; i++) { pointer[i] = reader.ReadByte(); } } } /// <summary> /// Writes a specified number of bytes. /// </summary> /// <param name="count">Number of values to write.</param> /// <param name="src">Pointer that holds the values.</param> protected void WriteBytes(BinaryWriter writer, int count, IntPtr src) { unsafe { byte* pointer = (byte*)src.ToPointer(); for (int i = 0; i < count; i++) { writer.Write(pointer[i]); } } } /// <summary> /// Reads a specified number of floats and copies them into the destination pointer. /// </summary> /// <param name="count">Number of values to read.</param> /// <param name="dest">Pointer to copy the values into.</param> protected void ReadFloats(BinaryMemoryReader reader, int count, IntPtr dest) { // blast the data into the buffer unsafe { float* pointer = (float*)dest.ToPointer(); for(int i = 0; i < count; i++) { pointer[i] = reader.ReadSingle(); } } } /// <summary> /// Writes a specified number of floats. /// </summary> /// <param name="count">Number of values to write.</param> /// <param name="src">Pointer that holds the values.</param> protected void WriteFloats(BinaryWriter writer, int count, IntPtr src) { unsafe { float* pointer = (float*)src.ToPointer(); for (int i = 0; i < count; i++) { writer.Write(pointer[i]); } } } /// <summary> /// Reads a specified number of floats and copies them into the destination pointer. /// </summary> /// <remarks>This overload will also copy the values into the specified destination array.</remarks> /// <param name="count">Number of values to read.</param> /// <param name="dest">Pointer to copy the values into.</param> /// <param name="destArray">A float array that is to have the values copied into it at the same time as 'dest'.</param> protected void ReadFloats(BinaryMemoryReader reader, int count, IntPtr dest, float[] destArray) { // blast the data into the buffer unsafe { float* pointer = (float*)dest.ToPointer(); for(int i = 0; i < count; i++) { float val = reader.ReadSingle(); pointer[i] = val; destArray[i] = val; } } } protected bool ReadBool(BinaryMemoryReader reader) { return reader.ReadBoolean(); } protected void WriteBool(BinaryWriter writer, bool val) { writer.Write(val); } protected float ReadFloat(BinaryMemoryReader reader) { return reader.ReadSingle(); } protected void WriteFloat(BinaryWriter writer, float val) { writer.Write(val); } protected int ReadInt(BinaryMemoryReader reader) { return reader.ReadInt32(); } protected void WriteInt(BinaryWriter writer, int val) { writer.Write(val); } protected uint ReadUInt(BinaryMemoryReader reader) { return reader.ReadUInt32(); } protected void WriteUInt(BinaryWriter writer, uint val) { writer.Write(val); } protected long ReadLong(BinaryMemoryReader reader) { return reader.ReadInt64(); } protected void WriteLong(BinaryWriter writer, long val) { writer.Write(val); } protected ulong ReadULong(BinaryMemoryReader reader) { return reader.ReadUInt64(); } protected void WriteULong(BinaryWriter writer, ulong val) { writer.Write(val); } protected short ReadShort(BinaryMemoryReader reader) { return reader.ReadInt16(); } protected void WriteShort(BinaryWriter writer, short val) { writer.Write(val); } protected ushort ReadUShort(BinaryMemoryReader reader) { return reader.ReadUInt16(); } protected void WriteUShort(BinaryWriter writer, ushort val) { writer.Write(val); } /// <summary> /// Reads a specified number of integers and copies them into the destination pointer. /// </summary> /// <param name="count">Number of values to read.</param> /// <param name="dest">Pointer to copy the values into.</param> protected void ReadInts(BinaryMemoryReader reader, int count, IntPtr dest) { // blast the data into the buffer unsafe { int* pointer = (int*)dest.ToPointer(); for(int i = 0; i < count; i++) { pointer[i] = reader.ReadInt32(); } } } /// <summary> /// Writes a specified number of integers. /// </summary> /// <param name="count">Number of values to write.</param> /// <param name="src">Pointer that holds the values.</param> protected void WriteInts(BinaryWriter writer, int count, IntPtr src) { // blast the data into the buffer unsafe { int* pointer = (int*)src.ToPointer(); for (int i = 0; i < count; i++) { writer.Write(pointer[i]); } } } /// <summary> /// Reads a specified number of shorts and copies them into the destination pointer. /// </summary> /// <param name="count">Number of values to read.</param> /// <param name="dest">Pointer to copy the values into.</param> protected void ReadShorts(BinaryMemoryReader reader, int count, IntPtr dest) { // blast the data into the buffer unsafe { short* pointer = (short*)dest.ToPointer(); for (int i = 0; i < count; i++) { pointer[i] = reader.ReadInt16(); } } } /// <summary> /// Writes a specified number of shorts. /// </summary> /// <param name="count">Number of values to write.</param> /// <param name="src">Pointer that holds the values.</param> protected void WriteShorts(BinaryWriter writer, int count, IntPtr src) { // blast the data into the buffer unsafe { short* pointer = (short*)src.ToPointer(); for (int i = 0; i < count; i++) { writer.Write(pointer[i]); } } } /// <summary> /// Reads from the stream up to the first endline character. /// </summary> /// <returns>A string formed from characters up to the first '\n' character.</returns> protected string ReadString(BinaryMemoryReader reader) { // note: Not using Environment.NewLine here, this character is specifically used in Ogre files. return ReadString(reader, '\n'); } /// <summary> /// Writes the string to the stream including the endline character. /// </summary> protected void WriteString(BinaryWriter writer, string str) { WriteString(writer, str, '\n'); } /// <summary> /// Reads from the stream up to the specified delimiter character. /// </summary> /// <param name="delimiter">The character that signals the end of the string.</param> /// <returns>A string formed from characters up to the first instance of the specified delimeter.</returns> protected string ReadString(BinaryMemoryReader reader, char delimiter) { StringBuilder sb = new StringBuilder(); char c; // sift through each character until we hit the delimiter while((c = reader.ReadChar()) != delimiter) { sb.Append(c); } // return the accumulated string return sb.ToString(); } /// <summary> /// Writes the string to the stream including the specified delimiter character. /// </summary> /// <param name="delimiter">The character that signals the end of the string.</param> protected void WriteString(BinaryWriter writer, string str, char delimiter) { StringBuilder sb = new StringBuilder(str); sb.Append(delimiter); writer.Write(sb.ToString().ToCharArray()); } /// <summary> /// Reads and returns a Quaternion. /// </summary> /// <returns></returns> protected Quaternion ReadQuat(BinaryMemoryReader reader) { Quaternion quat = new Quaternion(); quat.x = reader.ReadSingle(); quat.y = reader.ReadSingle(); quat.z = reader.ReadSingle(); quat.w = reader.ReadSingle(); return quat; } /// <summary> /// Reads and returns a Quaternion. /// </summary> protected void WriteQuat(BinaryWriter writer, Quaternion quat) { writer.Write(quat.x); writer.Write(quat.y); writer.Write(quat.z); writer.Write(quat.w); } /// <summary> /// Reads and returns a Vector3 structure. /// </summary> /// <returns></returns> protected Vector3 ReadVector3(BinaryMemoryReader reader) { Vector3 vector = new Vector3(); vector.x = ReadFloat(reader); vector.y = ReadFloat(reader); vector.z = ReadFloat(reader); return vector; } /// <summary> /// Writes a Vector3 structure. /// </summary> protected void WriteVector3(BinaryWriter writer, Vector3 vector) { WriteFloat(writer, vector.x); WriteFloat(writer, vector.y); WriteFloat(writer, vector.z); } /// <summary> /// Reads and returns a Vector4 structure. /// </summary> /// <returns></returns> protected Vector4 ReadVector4(BinaryMemoryReader reader) { Vector4 vector = new Vector4(); vector.x = ReadFloat(reader); vector.y = ReadFloat(reader); vector.z = ReadFloat(reader); vector.w = ReadFloat(reader); return vector; } /// <summary> /// Writes a Vector4 structure. /// </summary> protected void WriteVector4(BinaryWriter writer, Vector4 vector) { WriteFloat(writer, vector.x); WriteFloat(writer, vector.y); WriteFloat(writer, vector.z); WriteFloat(writer, vector.w); } /// <summary> /// Reads a chunk ID and chunk size. /// </summary> /// <returns>The chunk ID at the current location.</returns> protected short ReadFileChunk(BinaryMemoryReader reader) { // get the chunk id short id = reader.ReadInt16(); // read the length for this chunk currentChunkLength = reader.ReadInt32(); return id; } /// <summary> /// Writes a chunk ID and chunk size. This would be more accurately named /// WriteChunkHeader, but this name is the counter of ReadChunk. /// </summary> protected void WriteChunk(BinaryWriter writer, MeshChunkID id, int chunkLength) { writer.Write((short)id); writer.Write(chunkLength); } /// <summary> /// Writes a chunk ID and chunk size. This would be more accurately named /// WriteChunkHeader, but this name is the counter of ReadChunk. /// </summary> protected void WriteChunk(BinaryWriter writer, SkeletonChunkID id, int chunkLength) { writer.Write((short)id); writer.Write(chunkLength); } /// <summary> /// Reads a file header and checks the version string. /// </summary> protected void ReadFileHeader(BinaryMemoryReader reader) { short headerID = 0; // read the header ID headerID = reader.ReadInt16(); // better hope this is the header if(headerID == (short)MeshChunkID.Header) { string fileVersion = ReadString(reader); // read the version string if(version != fileVersion) { throw new AxiomException("Invalid file: version incompatible, file reports {0}, Serializer is version {1}", fileVersion, version); } } else { throw new AxiomException("Invalid file: no header found."); } } /// <summary> /// Writes a file header and version string. /// </summary> protected void WriteFileHeader(BinaryWriter writer, string fileVersion) { writer.Write((short)MeshChunkID.Header); WriteString(writer, fileVersion); } protected void Seek(BinaryMemoryReader reader, long length) { Seek(reader, length, SeekOrigin.Current); } /// <summary> /// Skips to a particular part of the binary stream. /// </summary> /// <param name="length">Number of bytes to skip.</param> protected void Seek(BinaryMemoryReader reader, long length, SeekOrigin origin) { reader.Seek(length, origin); } protected bool IsEOF(BinaryMemoryReader reader) { return reader.PeekChar() == -1; } #endregion Methods } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Commands.ServiceManagement.Model; using Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests.ConfigDataInfo; using Microsoft.WindowsAzure.Commands.Storage.Common; using System; using System.IO; using System.Linq; using System.Management.Automation; using System.Reflection; namespace Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests { [TestClass] public class FunctionalTestCommonVhd : ServiceManagementTest { private const string vhdNamePrefix = "os.vhd"; private string vhdName; protected static string vhdBlobLocation; [ClassInitialize] public static void ClassInit(TestContext context) { if (defaultAzureSubscription.Equals(null)) { Assert.Inconclusive("No Subscription is selected!"); } vhdBlobLocation = string.Format("{0}{1}/{2}", blobUrlRoot, vhdContainerName, vhdNamePrefix); if (string.IsNullOrEmpty(localFile)) { try { //CredentialHelper.CopyTestData(testDataContainer, osVhdName, vhdContainerName, vhdNamePrefix); } catch (Exception e) { Console.WriteLine(e.ToString()); Assert.Inconclusive("Upload vhd is not set!"); } } else { try { vmPowershellCmdlets.AddAzureVhd(new FileInfo(localFile), vhdBlobLocation); } catch (Exception e) { if (e.ToString().Contains("already exists")) { // Use the already uploaded vhd. Console.WriteLine("Using already uploaded blob.."); } else { throw; } } } } [TestInitialize] public void Initialize() { pass = false; testStartTime = DateTime.Now; } [TestMethod(), TestCategory(Category.Functional), TestCategory(Category.BVT), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Update,Remove)-AzureDisk)")] public void AzureDiskTest() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); vhdName = Utilities.GetUniqueShortName("os0vhd"); CopyCommonVhd(vhdContainerName, "os0.vhd", vhdName); string mediaLocation = String.Format("{0}{1}/{2}", blobUrlRoot, vhdContainerName, vhdName); try { vmPowershellCmdlets.AddAzureDisk(vhdName, mediaLocation, vhdName, null); bool found = false; foreach (DiskContext disk in vmPowershellCmdlets.GetAzureDisk(vhdName)) { Console.WriteLine("Disk: Name - {0}, Label - {1}, Size - {2},", disk.DiskName, disk.Label, disk.DiskSizeInGB); if (disk.DiskName == vhdName && disk.Label == vhdName) { found = true; Console.WriteLine("{0} is found", disk.DiskName); } } Assert.IsTrue(found, "Error: Disk is not added"); // Update only label string newLabel = "NewLabel"; vmPowershellCmdlets.UpdateAzureDisk(vhdName, newLabel); DiskContext virtualDisk = vmPowershellCmdlets.GetAzureDisk(vhdName)[0]; Console.WriteLine("Disk: Name - {0}, Label - {1}, Size - {2},", virtualDisk.DiskName, virtualDisk.Label, virtualDisk.DiskSizeInGB); Assert.AreEqual(newLabel, virtualDisk.Label); Console.WriteLine("Disk Label is successfully updated"); // Update only size int newSize = 50; vmPowershellCmdlets.UpdateAzureDisk(vhdName, null, newSize); virtualDisk = vmPowershellCmdlets.GetAzureDisk(vhdName)[0]; Console.WriteLine("Disk: Name - {0}, Label - {1}, Size - {2},", virtualDisk.DiskName, virtualDisk.Label, virtualDisk.DiskSizeInGB); Assert.AreEqual(newLabel, virtualDisk.Label); Assert.AreEqual(newSize, virtualDisk.DiskSizeInGB); Console.WriteLine("Disk size is successfully updated"); // Update both label and size newLabel = "NewLabel2"; newSize = 100; vmPowershellCmdlets.UpdateAzureDisk(vhdName, newLabel, newSize); virtualDisk = vmPowershellCmdlets.GetAzureDisk(vhdName)[0]; Console.WriteLine("Disk: Name - {0}, Label - {1}, Size - {2},", virtualDisk.DiskName, virtualDisk.Label, virtualDisk.DiskSizeInGB); Assert.AreEqual(newLabel, virtualDisk.Label); Assert.AreEqual(newSize, virtualDisk.DiskSizeInGB); Console.WriteLine("Both disk label and size are successfully updated"); vmPowershellCmdlets.RemoveAzureDisk(vhdName, true); Assert.IsTrue(Utilities.CheckRemove(vmPowershellCmdlets.GetAzureDisk, vhdName), "The disk was not removed"); pass = true; } catch (Exception e) { pass = false; if (e.ToString().Contains("ResourceNotFound")) { Console.WriteLine("Please upload {0} file to \\vhdtest\\ blob directory before running this test", vhdName); } try { vmPowershellCmdlets.RemoveAzureDisk(vhdName, true); } catch (Exception cleanupError) { Console.WriteLine("Error during cleaning up the disk.. Continue..:{0}", cleanupError); } Assert.Fail("Exception occurs: {0}", e.ToString()); } } private void CopyCommonVhd(string vhdContainerName, string vhdName, string myVhdName) { vmPowershellCmdlets.RunPSScript(string.Format("{0}-{1} -SrcContainer {2} -SrcBlob {3} -DestContainer {4} -DestBlob {5}", VerbsLifecycle.Start, StorageNouns.CopyBlob, vhdContainerName, vhdName, vhdContainerName, myVhdName)); } [TestMethod(), TestCategory(Category.Functional), TestCategory(Category.BVT), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Save,Update,Remove)-AzureVMImage)")] public void AzureVMImageTest() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); vhdName = "os1.vhd"; string newImageName = Utilities.GetUniqueShortName("vmimage"); string mediaLocation = string.Format("{0}{1}/{2}", blobUrlRoot, vhdContainerName, vhdName); string oldLabel = "old label"; string newLabel = "new label"; string vmSize = "Small"; var iconUri = "http://www.bing.com"; var smallIconUri = "http://www.bing.com"; bool showInGui = true; try { // BVT Tests for OS Images OSImageContext result = vmPowershellCmdlets.AddAzureVMImage(newImageName, mediaLocation, OS.Windows, oldLabel, vmSize, iconUri, smallIconUri, showInGui); OSImageContext resultReturned = vmPowershellCmdlets.GetAzureVMImage(newImageName)[0]; Assert.IsTrue(!string.IsNullOrEmpty(resultReturned.IOType)); Assert.IsTrue(CompareContext<OSImageContext>(result, resultReturned)); result = vmPowershellCmdlets.UpdateAzureVMImage(newImageName, newLabel); resultReturned = vmPowershellCmdlets.GetAzureVMImage(newImageName)[0]; Assert.IsTrue(!string.IsNullOrEmpty(resultReturned.IOType)); Assert.IsTrue(CompareContext<OSImageContext>(result, resultReturned)); result = vmPowershellCmdlets.UpdateAzureVMImage(newImageName, newLabel, true); resultReturned = vmPowershellCmdlets.GetAzureVMImage(newImageName)[0]; Assert.IsTrue(resultReturned.ShowInGui.HasValue && !resultReturned.ShowInGui.Value); Assert.IsTrue(CompareContext<OSImageContext>(result, resultReturned)); vmPowershellCmdlets.RemoveAzureVMImage(newImageName, false); Assert.IsTrue(Utilities.CheckRemove(vmPowershellCmdlets.GetAzureVMImage, newImageName)); // BVT Tests for VM Images // Unique Container Prefix var containerPrefix = Utilities.GetUniqueShortName("vmimg"); // Disk Blobs var srcVhdName = "os1.vhd"; var srcVhdContainer = vhdContainerName; var dstOSVhdContainer = containerPrefix.ToLower() + "os" + vhdContainerName; CredentialHelper.CopyTestData(srcVhdContainer, srcVhdName, dstOSVhdContainer); string osVhdLink = string.Format("{0}{1}/{2}", blobUrlRoot, dstOSVhdContainer, srcVhdName); var dstDataVhdContainer = containerPrefix.ToLower() + "data" + vhdContainerName; CredentialHelper.CopyTestData(srcVhdContainer, srcVhdName, dstDataVhdContainer); string dataVhdLink = string.Format("{0}{1}/{2}", blobUrlRoot, dstDataVhdContainer, srcVhdName); // VM Image OS/Data Disk Configuration var addVMImageName = containerPrefix + "Image"; var diskConfig = new VirtualMachineImageDiskConfigSet { OSDiskConfiguration = new OSDiskConfiguration { HostCaching = HostCaching.ReadWrite.ToString(), OS = OSType.Windows.ToString(), OSState = "Generalized", MediaLink = new Uri(osVhdLink) }, DataDiskConfigurations = new DataDiskConfigurationList { new DataDiskConfiguration { HostCaching = HostCaching.ReadOnly.ToString(), Lun = 0, MediaLink = new Uri(dataVhdLink) } } }; // Add-AzureVMImage string label = addVMImageName; string description = "test"; string eula = "http://www.bing.com/"; string imageFamily = "Windows"; DateTime? publishedDate = new DateTime(2015, 1, 1); string privacyUri = "http://www.bing.com/"; string recommendedVMSize = vmSize; string iconName = "iconName"; string smallIconName = "smallIconName"; vmPowershellCmdlets.AddAzureVMImage( addVMImageName, label, diskConfig, description, eula, imageFamily, publishedDate, privacyUri, recommendedVMSize, iconName, smallIconName, showInGui); // Get-AzureVMImage var vmImage = vmPowershellCmdlets.GetAzureVMImageReturningVMImages(addVMImageName).First(); Assert.IsTrue(vmImage.ImageName == addVMImageName); Assert.IsTrue(vmImage.Label == label); Assert.IsTrue(vmImage.Description == description); Assert.IsTrue(vmImage.Eula == eula); Assert.IsTrue(vmImage.ImageFamily == imageFamily); Assert.IsTrue(vmImage.PublishedDate.Value.Year == publishedDate.Value.Year); Assert.IsTrue(vmImage.PublishedDate.Value.Month == publishedDate.Value.Month); Assert.IsTrue(vmImage.PublishedDate.Value.Day == publishedDate.Value.Day); Assert.IsTrue(vmImage.PrivacyUri.AbsoluteUri.ToString() == privacyUri); Assert.IsTrue(vmImage.RecommendedVMSize == recommendedVMSize); Assert.IsTrue(vmImage.IconName == iconName); Assert.IsTrue(vmImage.IconUri == iconName); Assert.IsTrue(vmImage.SmallIconName == smallIconName); Assert.IsTrue(vmImage.SmallIconUri == smallIconName); Assert.IsTrue(vmImage.ShowInGui == showInGui); Assert.IsTrue(vmImage.OSDiskConfiguration.HostCaching == diskConfig.OSDiskConfiguration.HostCaching); Assert.IsTrue(vmImage.OSDiskConfiguration.OS == diskConfig.OSDiskConfiguration.OS); Assert.IsTrue(vmImage.OSDiskConfiguration.OSState == diskConfig.OSDiskConfiguration.OSState); Assert.IsTrue(vmImage.OSDiskConfiguration.MediaLink == diskConfig.OSDiskConfiguration.MediaLink); Assert.IsTrue(vmImage.DataDiskConfigurations.First().HostCaching == diskConfig.DataDiskConfigurations.First().HostCaching); Assert.IsTrue(vmImage.DataDiskConfigurations.First().Lun == diskConfig.DataDiskConfigurations.First().Lun); Assert.IsTrue(vmImage.DataDiskConfigurations.First().MediaLink == diskConfig.DataDiskConfigurations.First().MediaLink); // Remove-AzureVMImage vmPowershellCmdlets.RemoveAzureVMImage(addVMImageName); pass = true; } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } finally { if (!Utilities.CheckRemove(vmPowershellCmdlets.GetAzureVMImage, newImageName)) { vmPowershellCmdlets.RemoveAzureVMImage(newImageName, false); } } } /// <summary> /// /// </summary> [TestMethod(), TestCategory(Category.Functional), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (Set-AzureVMSize)")] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\overwrite_VHD.csv", "overwrite_VHD#csv", DataAccessMethod.Sequential)] public void AzureVMImageSizeTest() { string mediaLocation = UploadVhdFile(); string newImageName = Utilities.GetUniqueShortName("vmimage"); try { var instanceSizes = vmPowershellCmdlets.GetAzureRoleSize().Where(r => r.Cores <= 2 && !r.InstanceSize.StartsWith("Standard_")); const int numOfMinimumInstSize = 3; Assert.IsTrue(instanceSizes.Count() >= numOfMinimumInstSize); var instanceSizesArr = instanceSizes.Take(numOfMinimumInstSize).ToArray(); int arrayLength = instanceSizesArr.Count(); for (int i = 0; i < arrayLength; i++) { Utilities.PrintContext(instanceSizesArr[i]); // Add-AzureVMImage test for VM size OSImageContext result = vmPowershellCmdlets.AddAzureVMImage(newImageName, mediaLocation, OS.Windows, null, instanceSizesArr[i].InstanceSize); OSImageContext resultReturned = vmPowershellCmdlets.GetAzureVMImage(newImageName)[0]; Assert.IsTrue(!string.IsNullOrEmpty(resultReturned.IOType)); Assert.IsTrue(CompareContext<OSImageContext>(result, resultReturned)); // Update-AzureVMImage test for VM size System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10)); result = vmPowershellCmdlets.UpdateAzureVMImage(newImageName, resultReturned.ImageName, instanceSizesArr[Math.Max((i + 1) % arrayLength, 1)].InstanceSize); resultReturned = vmPowershellCmdlets.GetAzureVMImage(newImageName)[0]; Assert.IsTrue(!string.IsNullOrEmpty(resultReturned.IOType)); Assert.IsTrue(CompareContext<OSImageContext>(result, resultReturned)); vmPowershellCmdlets.RemoveAzureVMImage(newImageName); System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10)); pass = true; } } catch (Exception e) { pass = false; System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10)); vmPowershellCmdlets.RemoveAzureVMImage(newImageName, true); Console.WriteLine("Exception occurred: {0}", e.ToString()); throw; } finally { try { vmPowershellCmdlets.GetAzureVMImage(newImageName); vmPowershellCmdlets.RemoveAzureVMImage(newImageName); } catch (Exception e) { if (e.ToString().Contains("ResourceNotFound")) { Console.WriteLine("The vm image, {0}, is already deleted.", newImageName); } else { throw; } } } } [TestMethod(), TestCategory(Category.Functional), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (Set-AzureVMSize, Get-AzureRoleSize)")] public void HiMemVMSizeTest() { string serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); string vmName = Utilities.GetUniqueShortName(vmNamePrefix); try { // New-AzureQuickVM test for VM size 'A5' vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, vmName, serviceName, imageName, username, password, locationName, HiMemInstanceSize.A5.ToString()); PersistentVMRoleContext result = vmPowershellCmdlets.GetAzureVM(vmName, serviceName); RoleSizeContext returnedSize = vmPowershellCmdlets.GetAzureRoleSize(result.InstanceSize)[0]; Assert.AreEqual(HiMemInstanceSize.A5.ToString(), returnedSize.InstanceSize); Console.WriteLine("VM size, {0}, is verified for New-AzureQuickVM", HiMemInstanceSize.A5); vmPowershellCmdlets.RemoveAzureService(serviceName); // New-AzureQuickVM test for VM size 'A6' vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, vmName, serviceName, imageName, username, password, locationName, HiMemInstanceSize.A6.ToString()); result = vmPowershellCmdlets.GetAzureVM(vmName, serviceName); returnedSize = vmPowershellCmdlets.GetAzureRoleSize(result.InstanceSize)[0]; Assert.AreEqual(HiMemInstanceSize.A6.ToString(), returnedSize.InstanceSize); Console.WriteLine("VM size, {0}, is verified for New-AzureQuickVM", HiMemInstanceSize.A6); vmPowershellCmdlets.RemoveAzureService(serviceName); // New-AzureVMConfig test for VM size 'A7' var azureVMConfigInfo = new AzureVMConfigInfo(vmName, HiMemInstanceSize.A7.ToString(), imageName); var azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, username, password); var persistentVMConfigInfo = new PersistentVMConfigInfo(azureVMConfigInfo, azureProvisioningConfig, null, null); PersistentVM vm = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo); vmPowershellCmdlets.NewAzureVM(serviceName, new[] { vm }, locationName); result = vmPowershellCmdlets.GetAzureVM(vmName, serviceName); returnedSize = vmPowershellCmdlets.GetAzureRoleSize(result.InstanceSize)[0]; Assert.AreEqual(HiMemInstanceSize.A7.ToString(), returnedSize.InstanceSize); Console.WriteLine("VM size, {0}, is verified for New-AzureVMConfig", HiMemInstanceSize.A7); // Set-AzureVMSize test for Hi-MEM VM size (A7 to A6) vmPowershellCmdlets.SetVMSize(vmName, serviceName, new SetAzureVMSizeConfig(HiMemInstanceSize.A6.ToString())); result = vmPowershellCmdlets.GetAzureVM(vmName, serviceName); returnedSize = vmPowershellCmdlets.GetAzureRoleSize(result.InstanceSize)[0]; Assert.AreEqual(HiMemInstanceSize.A6.ToString(), returnedSize.InstanceSize); Console.WriteLine("SetVMSize is verified from A7 to A6"); // Set-AzureVMSize test for Hi-MEM VM size (A6 to A5) vmPowershellCmdlets.SetVMSize(vmName, serviceName, new SetAzureVMSizeConfig(HiMemInstanceSize.A5.ToString())); result = vmPowershellCmdlets.GetAzureVM(vmName, serviceName); returnedSize = vmPowershellCmdlets.GetAzureRoleSize(result.InstanceSize)[0]; Assert.AreEqual(HiMemInstanceSize.A5.ToString(), returnedSize.InstanceSize); Console.WriteLine("SetVMSize is verified from A6 to A5"); pass = true; } catch (Exception e) { pass = false; Console.WriteLine("Exception occurred: {0}", e.ToString()); throw; } finally { if (!Utilities.CheckRemove(vmPowershellCmdlets.GetAzureService, serviceName)) { if ((cleanupIfFailed && !pass) || (cleanupIfPassed && pass)) { vmPowershellCmdlets.RemoveAzureService(serviceName); } } } } [TestMethod(), TestCategory(Category.Functional), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (Set-AzureVMSize, Get-AzureRoleSize)")] public void RegularVMSizeTest() { string serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); string vmName = Utilities.GetUniqueShortName(vmNamePrefix); string [] regularSizes = Enum.GetNames(typeof(InstanceSize)); try { var instanceSizes = vmPowershellCmdlets.GetAzureRoleSize().Where(s => regularSizes.Contains(s.InstanceSize)).ToArray(); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, vmName, serviceName, imageName, username, password, locationName, instanceSizes[1].InstanceSize); foreach (var instanceSize in instanceSizes) { PersistentVMRoleContext result; RoleSizeContext returnedSize; var size = instanceSize.InstanceSize; // Set-AzureVMSize test for regular VM size vmPowershellCmdlets.SetVMSize(vmName, serviceName, new SetAzureVMSizeConfig(size)); result = vmPowershellCmdlets.GetAzureVM(vmName, serviceName); returnedSize = vmPowershellCmdlets.GetAzureRoleSize(result.InstanceSize)[0]; Assert.AreEqual(size, returnedSize.InstanceSize); Console.WriteLine("VM size, {0}, is verified for Set-AzureVMSize", size); if (size.Equals(InstanceSize.ExtraLarge.ToString())) { vmPowershellCmdlets.SetVMSize(vmName, serviceName, new SetAzureVMSizeConfig(InstanceSize.Small.ToString())); result = vmPowershellCmdlets.GetAzureVM(vmName, serviceName); returnedSize = vmPowershellCmdlets.GetAzureRoleSize(result.InstanceSize)[0]; Assert.AreEqual(InstanceSize.Small.ToString(), returnedSize.InstanceSize); } } pass = true; } catch (Exception e) { pass = false; Console.WriteLine("Exception occurred: {0}", e.ToString()); throw; } finally { if (!Utilities.CheckRemove(vmPowershellCmdlets.GetAzureService, serviceName)) { if ((cleanupIfFailed && !pass) || (cleanupIfPassed && pass)) { vmPowershellCmdlets.RemoveAzureService(serviceName); } } } } private bool CompareContext<T>(T obj1, T obj2) { bool result = true; Type type = typeof(T); foreach(PropertyInfo property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { string typeName = property.PropertyType.FullName; if (typeName.Equals("System.String") || typeName.Equals("System.Int32") || typeName.Equals("System.Uri") || typeName.Contains("Nullable")) { // To Hyonho: This is my temp fix for the test. // Please verify and make correct changes. if (typeName.Contains("System.DateTime")) { continue; } var obj1Value = property.GetValue(obj1, null); var obj2Value = property.GetValue(obj2, null); if (obj1Value == null) { result &= (obj2Value == null); } else { result &= (obj1Value.Equals(obj2Value)); } } else { Console.WriteLine("This type is not compared: {0}", typeName); } } return result; } [TestCleanup] public virtual void CleanUp() { Console.WriteLine("Test {0}", pass ? "passed" : "failed"); } } }
/* Copyright (c) 2010 by Genstein This file is (or was originally) part of Trizbort, the Interactive Fiction Mapper. 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.Drawing; namespace Trizbort { internal struct Vector { public Vector(float scalar) { X = scalar; Y = scalar; } public Vector(float x, float y) { X = x; Y = y; } public Vector(PointF point) { X = point.X; Y = point.Y; } public Vector(SizeF size) { X = size.Width; Y = size.Height; } public static Vector operator -(Vector a, Vector b) { return new Vector(a.X - b.X, a.Y - b.Y); } public static Vector operator -(Vector v, float scalar) { return new Vector(v.X - scalar, v.Y - scalar); } public static Vector operator +(Vector a, Vector b) { return new Vector(a.X + b.X, a.Y + b.Y); } public static Vector operator +(Vector v, float scalar) { return new Vector(v.X + scalar, v.Y + scalar); } public static Vector operator *(Vector v, float scalar) { return new Vector(v.X * scalar, v.Y * scalar); } public static Vector operator *(float scalar, Vector v) { return new Vector(v.X * scalar, v.Y * scalar); } public static Vector operator /(Vector v, float scalar) { return new Vector(v.X / scalar, v.Y / scalar); } public static bool operator ==(Vector a, Vector b) { return a.X == b.X && a.Y == b.Y; } public static bool operator !=(Vector a, Vector b) { return a.X != b.X || a.Y != b.Y; } public override bool Equals(object obj) { if (!(obj is Vector)) return false; Vector other = (Vector)obj; return this == other; } public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode(); } public PointF ToPointF() { return new PointF(X, Y); } public Point ToPoint() { return new Point((int)X, (int)Y); } public SizeF ToSizeF() { return new SizeF(X, Y); } public Size ToSize() { return new Size((int)X, (int)Y); } public float Dot(Vector other) { return Dot(this, other); } public static float Dot(Vector a, Vector b) { return a.X * b.X + a.Y * b.Y; } public float LengthSquared { get { return X * X + Y * Y; } } public float Length { get { return (float)Math.Sqrt(LengthSquared); } } public Vector Abs() { return new Vector(Math.Abs(X), Math.Abs(Y)); } public static float Distance(Vector a, Vector b) { return Math.Abs((b - a).Length); } public float Distance(Vector other) { return Distance(this, other); } public static Vector Normalize(Vector v) { Vector n = v; n.Normalize(); return n; } public void Normalize() { var length = Length; if (length == 0) { // avoid division by zero (NaN) X = 0; Y = 0; } else { X /= length; Y /= length; } } public void Negate() { X = -X; Y = -Y; } public static float DistanceFromLineSegment(LineSegment line, Vector pos) { var delta = line.End - line.Start; var direction = Vector.Normalize(delta); float distanceAlongSegment = Vector.Dot(pos, direction) - Vector.Dot(line.Start, direction); Vector nearest; if (distanceAlongSegment < 0) { nearest = line.Start; } else if (distanceAlongSegment > delta.Length) { nearest = line.End; } else { nearest = line.Start + distanceAlongSegment * direction; } return Vector.Distance(nearest, pos); } public static float DistanceFromRect(Rect rect, Vector pos) { if (rect.Contains(pos)) { return 0; } var nw = rect.GetCorner(CompassPoint.NorthWest); var ne = rect.GetCorner(CompassPoint.NorthEast); var sw = rect.GetCorner(CompassPoint.SouthWest); var se = rect.GetCorner(CompassPoint.SouthEast); var distanceFromTop = DistanceFromLineSegment(new LineSegment(nw, ne), pos); var distanceFromRight = DistanceFromLineSegment(new LineSegment(ne, se), pos); var distanceFromBottom = DistanceFromLineSegment(new LineSegment(se, sw), pos); var distanceFromLeft = DistanceFromLineSegment(new LineSegment(sw, nw), pos); return Math.Min(distanceFromTop, Math.Min(distanceFromLeft, Math.Min(distanceFromBottom, distanceFromRight))); } public float DistanceFromRect(Rect rect) { return DistanceFromRect(rect, this); } public float DistanceFromLineSegment(LineSegment line) { return DistanceFromLineSegment(line, this); } public static readonly Vector Zero = new Vector(); public float X; public float Y; } }
using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using System.Collections.Generic; namespace UIWidgets { /// <summary> /// Range slider base. /// </summary> public abstract class RangeSliderBase<T> : MonoBehaviour, IPointerClickHandler where T : struct { /// <summary> /// OnChangeEvent. /// </summary> [System.Serializable] public class OnChangeEvent : UnityEvent<T,T> { } /// <summary> /// The minimum value. /// </summary> [SerializeField] protected T valueMin; /// <summary> /// Gets or sets the minimum value. /// </summary> /// <value>The minimum value.</value> public T ValueMin { get { return valueMin; } set { if (!EqualityComparer<T>.Default.Equals(valueMin, InBoundsMin(value))) { valueMin = InBoundsMin(value); UpdateMinHandle(); UpdateFill(); OnValuesChange.Invoke(valueMin, valueMax); OnChange.Invoke(); } } } /// <summary> /// The maximum value. /// </summary> [SerializeField] protected T valueMax; /// <summary> /// Gets or sets the maximum value. /// </summary> /// <value>The maximum value.</value> public T ValueMax { get { return valueMax; } set { if (!EqualityComparer<T>.Default.Equals(valueMax, InBoundsMax(value))) { valueMax = InBoundsMax(value); UpdateMaxHandle(); UpdateFill(); OnValuesChange.Invoke(valueMin, valueMax); OnChange.Invoke(); } } } /// <summary> /// The step. /// </summary> [SerializeField] protected T step; /// <summary> /// Gets or sets the step. /// </summary> /// <value>The step.</value> public T Step { get { return step; } set { step = value; } } /// <summary> /// The minimum limit. /// </summary> [SerializeField] protected T limitMin; /// <summary> /// Gets or sets the minimum limit. /// </summary> /// <value>The minimum limit.</value> public T LimitMin { get { return limitMin; } set { limitMin = value; ValueMin = valueMin; ValueMax = valueMax; } } /// <summary> /// The maximum limit. /// </summary> [SerializeField] protected T limitMax; /// <summary> /// Gets or sets the maximum limit. /// </summary> /// <value>The maximum limit.</value> public T LimitMax { get { return limitMax; } set { limitMax = value; ValueMin = valueMin; ValueMax = valueMax; } } /// <summary> /// The handle minimum. /// </summary> [SerializeField] protected RangeSliderHandle handleMin; /// <summary> /// The handle minimum rect. /// </summary> protected RectTransform handleMinRect; /// <summary> /// Gets the handle minimum rect. /// </summary> /// <value>The handle minimum rect.</value> public RectTransform HandleMinRect { get { if (handleMin!=null && handleMinRect==null) { handleMinRect = handleMin.transform as RectTransform; } return handleMinRect; } } /// <summary> /// Gets or sets the handle minimum. /// </summary> /// <value>The handle minimum.</value> public RangeSliderHandle HandleMin { get { return handleMin; } set { handleMin = value; handleMinRect = null; handleMin.IsHorizontal = IsHorizontal; handleMin.PositionLimits = MinPositionLimits; handleMin.PositionChanged = UpdateMinValue; handleMin.OnSubmit = SelectMaxHandle; handleMin.Increase = IncreaseMin; handleMin.Decrease = DecreaseMin; HandleMinRect.anchorMin = new Vector2(0, 0); HandleMinRect.anchorMax = (IsHorizontal()) ? new Vector2(0, 1) : new Vector2(1, 0); } } /// <summary> /// The handle max. /// </summary> [SerializeField] protected RangeSliderHandle handleMax; /// <summary> /// The handle max rect. /// </summary> protected RectTransform handleMaxRect; /// <summary> /// Gets the handle maximum rect. /// </summary> /// <value>The handle maximum rect.</value> public RectTransform HandleMaxRect { get { if (handleMax!=null && handleMaxRect==null) { handleMaxRect = handleMax.transform as RectTransform; } return handleMaxRect; } } /// <summary> /// Gets or sets the handle max. /// </summary> /// <value>The handle max.</value> public RangeSliderHandle HandleMax { get { return handleMax; } set { handleMax = value; handleMaxRect = null; handleMax.IsHorizontal = IsHorizontal; handleMax.PositionLimits = MaxPositionLimits; handleMax.PositionChanged = UpdateMaxValue; handleMax.OnSubmit = SelectMinHandle; handleMax.Increase = IncreaseMax; handleMax.Decrease = DecreaseMax; HandleMaxRect.anchorMin = new Vector2(0, 0); HandleMaxRect.anchorMax = (IsHorizontal()) ? new Vector2(0, 1) : new Vector2(1, 0); } } /// <summary> /// The usable range rect. /// </summary> [SerializeField] protected RectTransform UsableRangeRect; /// <summary> /// The fill rect. /// </summary> [SerializeField] protected RectTransform FillRect; /// <summary> /// The range slider rect. /// </summary> protected RectTransform rangeSliderRect; /// <summary> /// Gets the handle maximum rect. /// </summary> /// <value>The handle maximum rect.</value> public RectTransform RangeSliderRect { get { if (rangeSliderRect==null) { rangeSliderRect = transform as RectTransform; } return rangeSliderRect; } } /// <summary> /// OnValuesChange event. /// </summary> public OnChangeEvent OnValuesChange = new OnChangeEvent(); /// <summary> /// OnChange event. /// </summary> public UnityEvent OnChange = new UnityEvent(); /// <summary> /// Whole number of steps. /// </summary> public bool WholeNumberOfSteps = false; void Awake() { } bool initCalled; void Init() { if (initCalled) { return ; } initCalled = true; HandleMin = handleMin; HandleMax = handleMax; UpdateMinHandle(); UpdateMaxHandle(); UpdateFill(); } void Start() { Init(); } /// <summary> /// Sets the values. /// </summary> /// <param name="min">Minimum.</param> /// <param name="max">Max.</param> public void SetValue(T min, T max) { var oldValueMin = valueMin; var oldValueMax = valueMax; valueMin = min; valueMax = max; valueMin = InBoundsMin(valueMin); valueMax = InBoundsMax(valueMax); var min_equals = EqualityComparer<T>.Default.Equals(oldValueMin, valueMin); var max_equals = EqualityComparer<T>.Default.Equals(oldValueMax, valueMax); if (!min_equals || !max_equals) { UpdateMinHandle(); UpdateMaxHandle(); UpdateFill(); OnValuesChange.Invoke(valueMin, valueMax); OnChange.Invoke(); } } /// <summary> /// Sets the limits. /// </summary> /// <param name="min">Minimum.</param> /// <param name="max">Max.</param> public void SetLimit(T min, T max) { var oldValueMin = valueMin; var oldValueMax = valueMax; limitMin = min; limitMax = max; valueMin = InBoundsMin(valueMin); valueMax = InBoundsMax(valueMax); var min_equals = EqualityComparer<T>.Default.Equals(oldValueMin, valueMin); var max_equals = EqualityComparer<T>.Default.Equals(oldValueMax, valueMax); if (!min_equals || !max_equals) { UpdateMinHandle(); UpdateMaxHandle(); UpdateFill(); OnValuesChange.Invoke(valueMin, valueMax); OnChange.Invoke(); } } /// <summary> /// Determines whether this instance is horizontal. /// </summary> /// <returns><c>true</c> if this instance is horizontal; otherwise, <c>false</c>.</returns> protected virtual bool IsHorizontal() { return true; } /// <summary> /// Returns size of usable rect. /// </summary> /// <returns>The size.</returns> protected float FillSize() { return (IsHorizontal()) ? UsableRangeRect.rect.width : UsableRangeRect.rect.height; } /// <summary> /// Minimum size of the handle. /// </summary> /// <returns>The handle size.</returns> protected float MinHandleSize() { if (IsHorizontal()) { return HandleMinRect.rect.width; } else { return HandleMinRect.rect.height; } } /// <summary> /// Maximum size of the handle. /// </summary> /// <returns>The handle size.</returns> protected float MaxHandleSize() { if (IsHorizontal()) { return HandleMaxRect.rect.width; } else { return HandleMaxRect.rect.height; } } /// <summary> /// Updates the minimum value. /// </summary> /// <param name="position">Position.</param> protected void UpdateMinValue(float position) { valueMin = PositionToValue(position - GetStartPoint()); UpdateMinHandle(); UpdateFill(); OnValuesChange.Invoke(valueMin, valueMax); OnChange.Invoke(); } /// <summary> /// Updates the maximum value. /// </summary> /// <param name="position">Position.</param> protected void UpdateMaxValue(float position) { valueMax = PositionToValue(position - GetStartPoint()); UpdateMaxHandle(); UpdateFill(); OnValuesChange.Invoke(valueMin, valueMax); OnChange.Invoke(); } /// <summary> /// Value to position. /// </summary> /// <returns>Position.</returns> /// <param name="value">Value.</param> protected abstract float ValueToPosition(T value); /// <summary> /// Position to value. /// </summary> /// <returns>Value.</returns> /// <param name="position">Position.</param> protected abstract T PositionToValue(float position); /// <summary> /// Gets the start point. /// </summary> /// <returns>The start point.</returns> protected float GetStartPoint() { return IsHorizontal() ? -UsableRangeRect.sizeDelta.x / 2f : -UsableRangeRect.sizeDelta.y / 2f; } /// <summary> /// Position range for minimum handle. /// </summary> /// <returns>The position limits.</returns> protected abstract Vector2 MinPositionLimits(); /// <summary> /// Position range for maximum handle. /// </summary> /// <returns>The position limits.</returns> protected abstract Vector2 MaxPositionLimits(); /// <summary> /// Fit value to bounds. /// </summary> /// <returns>Value.</returns> /// <param name="value">Value.</param> protected abstract T InBounds(T value); /// <summary> /// Fit minumum value to bounds. /// </summary> /// <returns>Value.</returns> /// <param name="value">Value.</param> protected abstract T InBoundsMin(T value); /// <summary> /// Fit maximum value to bounds. /// </summary> /// <returns>Value.</returns> /// <param name="value">Value.</param> protected abstract T InBoundsMax(T value); /// <summary> /// Increases the minimum value. /// </summary> protected abstract void IncreaseMin(); /// <summary> /// Decreases the minimum value. /// </summary> protected abstract void DecreaseMin(); /// <summary> /// Increases the maximum value. /// </summary> protected abstract void IncreaseMax(); /// <summary> /// Decreases the maximum value. /// </summary> protected abstract void DecreaseMax(); /// <summary> /// Updates the minimum handle. /// </summary> protected void UpdateMinHandle() { UpdateHandle(HandleMinRect, valueMin); } /// <summary> /// Updates the maximum handle. /// </summary> protected void UpdateMaxHandle() { UpdateHandle(HandleMaxRect, valueMax); } /// <summary> /// Updates the fill. /// </summary> void UpdateFill() { if (IsHorizontal()) { FillRect.anchoredPosition = new Vector2(HandleMinRect.anchoredPosition.x, FillRect.anchoredPosition.y); var sizeDelta = new Vector2((HandleMaxRect.anchoredPosition.x - HandleMinRect.anchoredPosition.x), FillRect.sizeDelta.y); FillRect.sizeDelta = sizeDelta; } else { FillRect.anchoredPosition = new Vector2(FillRect.anchoredPosition.x, HandleMinRect.anchoredPosition.y); var sizeDelta = new Vector2(FillRect.sizeDelta.x, (+ HandleMaxRect.anchoredPosition.y - HandleMinRect.anchoredPosition.y)); FillRect.sizeDelta = sizeDelta; } } /// <summary> /// Updates the handle. /// </summary> /// <param name="handleTransform">Handle transform.</param> /// <param name="value">Value.</param> protected void UpdateHandle(RectTransform handleTransform, T value) { var new_position = handleTransform.anchoredPosition; if (IsHorizontal()) { new_position.x = ValueToPosition(value) + handleTransform.rect.width * (handleTransform.pivot.x - 0.5f); } else { new_position.y = ValueToPosition(value) + handleTransform.rect.height * (handleTransform.pivot.y - 0.5f); } handleTransform.anchoredPosition = new_position; } /// <summary> /// Selects the minimum handle. /// </summary> void SelectMinHandle() { if ((EventSystem.current!=null) && (!EventSystem.current.alreadySelecting)) { EventSystem.current.SetSelectedGameObject(handleMin.gameObject); } } /// <summary> /// Selects the max handle. /// </summary> void SelectMaxHandle() { if ((EventSystem.current!=null) && (!EventSystem.current.alreadySelecting)) { EventSystem.current.SetSelectedGameObject(handleMax.gameObject); } } /// <summary> /// Raises the pointer click event. /// </summary> /// <param name="eventData">Event data.</param> public void OnPointerClick(PointerEventData eventData) { Vector2 curCursor; if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(UsableRangeRect, eventData.position, eventData.pressEventCamera, out curCursor)) { return ; } curCursor -= UsableRangeRect.rect.position; var new_min_position = (IsHorizontal() ? curCursor.x : curCursor.y) + GetStartPoint(); var new_max_position = new_min_position - MaxHandleSize(); var min_position = IsHorizontal() ? HandleMinRect.anchoredPosition.x : HandleMinRect.anchoredPosition.y; var max_position = IsHorizontal() ? HandleMaxRect.anchoredPosition.x : HandleMaxRect.anchoredPosition.y; var delta_min = new_min_position - min_position; var delta_max = max_position - new_max_position; if (delta_min < delta_max) { UpdateMinValue(new_min_position); } else { UpdateMaxValue(new_max_position); } } #if UNITY_EDITOR /// <summary> /// Handle values change from editor. /// </summary> public void EditorUpdate() { if (handleMin!=null && handleMax!=null && UsableRangeRect!=null && FillRect!=null) { UpdateMinHandle(); UpdateMaxHandle(); UpdateFill(); } } #endif } }
// 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.Text; using System.Reflection; using System.Diagnostics; using System.Collections.Generic; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.TypeInfos.EcmaFormat; using System.Reflection.Runtime.ParameterInfos; using System.Reflection.Runtime.ParameterInfos.EcmaFormat; using System.Reflection.Runtime.CustomAttributes; using System.Runtime.InteropServices; using Internal.Reflection.Core; using Internal.Reflection.Core.Execution; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; namespace System.Reflection.Runtime.MethodInfos.EcmaFormat { // // Implements methods and properties common to RuntimeMethodInfo and RuntimeConstructorInfo. // internal struct EcmaFormatMethodCommon : IRuntimeMethodCommon<EcmaFormatMethodCommon>, IEquatable<EcmaFormatMethodCommon> { public bool IsGenericMethodDefinition { get { return _method.GetGenericParameters().Count > 0; } } public MethodInvoker GetUncachedMethodInvoker(RuntimeTypeInfo[] methodArguments, MemberInfo exceptionPertainant) { return ReflectionCoreExecution.ExecutionEnvironment.GetMethodInvoker(DeclaringType, new QMethodDefinition(Reader, MethodHandle), methodArguments, exceptionPertainant); } public QSignatureTypeHandle[] QualifiedMethodSignature { get { return this.MethodSignature; } } public EcmaFormatMethodCommon RuntimeMethodCommonOfUninstantiatedMethod { get { EcmaFormatRuntimeNamedTypeInfo genericTypeDefinition = DeclaringType.GetGenericTypeDefinition().CastToEcmaFormatRuntimeNamedTypeInfo(); return new EcmaFormatMethodCommon(MethodHandle, genericTypeDefinition, genericTypeDefinition); } } public void FillInMetadataDescribedParameters(ref VirtualRuntimeParameterInfoArray result, QSignatureTypeHandle[] typeSignatures, MethodBase contextMethod, TypeContext typeContext) { foreach (ParameterHandle parameterHandle in _method.GetParameters()) { Parameter parameterRecord = _reader.GetParameter(parameterHandle); int index = parameterRecord.SequenceNumber; result[index] = EcmaFormatMethodParameterInfo.GetEcmaFormatMethodParameterInfo( contextMethod, _methodHandle, index - 1, parameterHandle, typeSignatures[index], typeContext); } } public RuntimeTypeInfo[] GetGenericTypeParametersWithSpecifiedOwningMethod(RuntimeNamedMethodInfo<EcmaFormatMethodCommon> owningMethod) { GenericParameterHandleCollection genericParameters = _method.GetGenericParameters(); int genericParametersCount = genericParameters.Count; if (genericParametersCount == 0) return Array.Empty<RuntimeTypeInfo>(); RuntimeTypeInfo[] genericTypeParameters = new RuntimeTypeInfo[genericParametersCount]; int i = 0; foreach (GenericParameterHandle genericParameterHandle in genericParameters) { RuntimeTypeInfo genericParameterType = EcmaFormatRuntimeGenericParameterTypeInfoForMethods.GetRuntimeGenericParameterTypeInfoForMethods(owningMethod, Reader, genericParameterHandle); genericTypeParameters[i++] = genericParameterType; } return genericTypeParameters; } // // methodHandle - the "tkMethodDef" that identifies the method. // definingType - the "tkTypeDef" that defined the method (this is where you get the metadata reader that created methodHandle.) // contextType - the type that supplies the type context (i.e. substitutions for generic parameters.) Though you // get your raw information from "definingType", you report "contextType" as your DeclaringType property. // // For example: // // typeof(Foo<>).GetTypeInfo().DeclaredMembers // // The definingType and contextType are both Foo<> // // typeof(Foo<int,String>).GetTypeInfo().DeclaredMembers // // The definingType is "Foo<,>" // The contextType is "Foo<int,String>" // // We don't report any DeclaredMembers for arrays or generic parameters so those don't apply. // public EcmaFormatMethodCommon(MethodDefinitionHandle methodHandle, EcmaFormatRuntimeNamedTypeInfo definingTypeInfo, RuntimeTypeInfo contextTypeInfo) { _definingTypeInfo = definingTypeInfo; _methodHandle = methodHandle; _contextTypeInfo = contextTypeInfo; _reader = definingTypeInfo.Reader; _method = _reader.GetMethodDefinition(methodHandle); } public MethodAttributes Attributes { get { return _method.Attributes; } } public CallingConventions CallingConvention { get { BlobReader signatureBlob = _reader.GetBlobReader(_method.Signature); CallingConventions result; SignatureHeader sigHeader = signatureBlob.ReadSignatureHeader(); if (sigHeader.CallingConvention == SignatureCallingConvention.VarArgs) result = CallingConventions.VarArgs; else result = CallingConventions.Standard; if (sigHeader.IsInstance) result |= CallingConventions.HasThis; if (sigHeader.HasExplicitThis) result |= CallingConventions.ExplicitThis; return result; } } public RuntimeTypeInfo ContextTypeInfo { get { return _contextTypeInfo; } } public IEnumerable<CustomAttributeData> CustomAttributes { get { IEnumerable<CustomAttributeData> customAttributes = RuntimeCustomAttributeData.GetCustomAttributes(_reader, _method.GetCustomAttributes()); foreach (CustomAttributeData cad in customAttributes) yield return cad; if (0 != (_method.ImplAttributes & MethodImplAttributes.PreserveSig)) yield return ReflectionCoreExecution.ExecutionDomain.GetCustomAttributeData(typeof(PreserveSigAttribute), null, null); } } public RuntimeTypeInfo DeclaringType { get { return _contextTypeInfo; } } public RuntimeNamedTypeInfo DefiningTypeInfo { get { return _definingTypeInfo; } } public MethodImplAttributes MethodImplementationFlags { get { return _method.ImplAttributes; } } public Module Module { get { return _definingTypeInfo.Module; } } public int MetadataToken { get { return MetadataTokens.GetToken(_methodHandle); } } public RuntimeMethodHandle GetRuntimeMethodHandle(Type[] genericArgHandles) { Debug.Assert(genericArgs != null); RuntimeTypeHandle[] genericArgHandles = new RuntimeTypeHandle[genericArgs.Length]; for (int i = 0; i < genericArgHandles.Length; i++) genericArgHandles[i] = genericArgs[i].TypeHandle; TypeManagerHandle typeManager = Internal.Runtime.TypeLoader.TypeLoaderEnvironment.Instance.ModuleList.GetModuleForMetadataReader(Reader); return Internal.Runtime.TypeLoader.TypeLoaderEnvironment.Instance.GetRuntimeMethodHandleForComponents( DeclaringType.TypeHandle, Name, RuntimeSignature.CreateFromMethodHandle(typeManager, MethodHandle.AsInt()), genericArgHandles); } // // Returns the ParameterInfo objects for the method parameters and return parameter. // // The ParameterInfo objects will report "contextMethod" as their Member property and use it to get type variable information from // the contextMethod's declaring type. The actual metadata, however, comes from "this." // // The methodTypeArguments provides the fill-ins for any method type variable elements in the parameter type signatures. // // Does not array-copy. // public RuntimeParameterInfo[] GetRuntimeParameters(MethodBase contextMethod, RuntimeTypeInfo[] methodTypeArguments, out RuntimeParameterInfo returnParameter) { MetadataReader reader = _reader; TypeContext typeContext = contextMethod.DeclaringType.CastToRuntimeTypeInfo().TypeContext; typeContext = new TypeContext(typeContext.GenericTypeArguments, methodTypeArguments); QSignatureTypeHandle[] typeSignatures = this.MethodSignature; int count = typeSignatures.Length; VirtualRuntimeParameterInfoArray result = new VirtualRuntimeParameterInfoArray(count); foreach (ParameterHandle parameterHandle in _method.GetParameters()) { Parameter parameterRecord = _reader.GetParameter(parameterHandle); int index = parameterRecord.SequenceNumber; result[index] = EcmaFormatMethodParameterInfo.GetEcmaFormatMethodParameterInfo( contextMethod, _methodHandle, index - 1, parameterHandle, typeSignatures[index], typeContext); } for (int i = 0; i < count; i++) { if (result[i] == null) { result[i] = RuntimeThinMethodParameterInfo.GetRuntimeThinMethodParameterInfo( contextMethod, i - 1, typeSignatures[i], typeContext); } } returnParameter = result.First; return result.Remainder; } public String Name { get { return _method.Name.GetString(_reader); } } public MetadataReader Reader { get { return _reader; } } public MethodDefinitionHandle MethodHandle { get { return _methodHandle; } } public override bool Equals(Object obj) { if (!(obj is EcmaFormatMethodCommon)) return false; return Equals((EcmaFormatMethodCommon)obj); } public bool Equals(EcmaFormatMethodCommon other) { if (!(_reader == other._reader)) return false; if (!(_methodHandle.Equals(other._methodHandle))) return false; if (!(_contextTypeInfo.Equals(other._contextTypeInfo))) return false; return true; } public override int GetHashCode() { return _methodHandle.GetHashCode() ^ _contextTypeInfo.GetHashCode(); } private QSignatureTypeHandle[] MethodSignature { get { BlobReader signatureBlob = _reader.GetBlobReader(_method.Signature); SignatureHeader header = signatureBlob.ReadSignatureHeader(); if (header.Kind != SignatureKind.Method) throw new BadImageFormatException(); int genericParameterCount = 0; if (header.IsGeneric) genericParameterCount = signatureBlob.ReadCompressedInteger(); int numParameters = signatureBlob.ReadCompressedInteger(); QSignatureTypeHandle[] signatureHandles = new QSignatureTypeHandle[checked(numParameters + 1)]; signatureHandles[0] = new QSignatureTypeHandle(_reader, signatureBlob); EcmaMetadataHelpers.SkipType(ref signatureBlob); for (int i = 0 ; i < numParameters; i++) { signatureHandles[i + 1] = new QSignatureTypeHandle(_reader, signatureBlob); } return signatureHandles; } } private readonly EcmaFormatRuntimeNamedTypeInfo _definingTypeInfo; private readonly MethodDefinitionHandle _methodHandle; private readonly RuntimeTypeInfo _contextTypeInfo; private readonly MetadataReader _reader; private readonly MethodDefinition _method; } }
// 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.Globalization; ///<summary> ///System.Globalization.CharUnicodeInfo.GetNumericValue(Char) ///</summary> public class CharUnicodeInfoGetNumericValue { public static int Main() { CharUnicodeInfoGetNumericValue testObj = new CharUnicodeInfoGetNumericValue(); TestLibrary.TestFramework.BeginTestCase("for method of System.Globalization.CharUnicodeInfo.GetNumericValue"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; return retVal; } #region Test Logic public bool PosTest1() { bool retVal = true; Char ch = '\0'; Double expectedValue = -1; Double actualValue; TestLibrary.TestFramework.BeginScenario(@"PosTest1:Test the method with '\0'"); try { actualValue = CharUnicodeInfo.GetNumericValue(ch); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("001", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; Char ch = '0'; Double expectedValue = 0; Double actualValue; TestLibrary.TestFramework.BeginScenario("PosTest1:Test the method with char '0'"); try { actualValue = CharUnicodeInfo.GetNumericValue(ch); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("003", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; Char ch = '9'; Double expectedValue = 9; Double actualValue; TestLibrary.TestFramework.BeginScenario("PosTest1:Test the method with char '9'"); try { actualValue = CharUnicodeInfo.GetNumericValue(ch); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("005", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; Char ch = '\u3289'; Double expectedValue = 10; Double actualValue; TestLibrary.TestFramework.BeginScenario("PosTest1:Test the method with char '\\u3289'"); try { actualValue = CharUnicodeInfo.GetNumericValue(ch); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("007", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; Char ch = 'a'; Double expectedValue = -1; Double actualValue; TestLibrary.TestFramework.BeginScenario("PosTest1:Test the method with char 'a'"); try { actualValue = CharUnicodeInfo.GetNumericValue(ch); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("009", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; Char ch = 'Z'; Double expectedValue = -1; Double actualValue; TestLibrary.TestFramework.BeginScenario("PosTest1:Test the method with char 'Z'"); try { actualValue = CharUnicodeInfo.GetNumericValue(ch); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("011", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unexpected exception:" + e); retVal = false; } return retVal; } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Xml; using System.Xml.Schema; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Reflection; namespace System.Xml.Xsl { /// <summary> /// Implementation of read-only IList and IList<T> interfaces. Derived classes can inherit from /// this class and implement only two methods, Count and Item, rather than the entire IList interface. /// </summary> internal abstract class ListBase<T> : IList<T>, System.Collections.IList { //----------------------------------------------- // Abstract IList methods that must be // implemented by derived classes //----------------------------------------------- public abstract int Count { get; } public abstract T this[int index] { get; set; } //----------------------------------------------- // Implemented by base class -- accessible on // ListBase //----------------------------------------------- public virtual bool Contains(T value) { return IndexOf(value) != -1; } public virtual int IndexOf(T value) { for (int i = 0; i < Count; i++) if (value.Equals(this[i])) return i; return -1; } public virtual void CopyTo(T[] array, int index) { for (int i = 0; i < Count; i++) array[index + i] = this[i]; } public virtual IListEnumerator<T> GetEnumerator() { return new IListEnumerator<T>(this); } public virtual bool IsFixedSize { get { return true; } } public virtual bool IsReadOnly { get { return true; } } public virtual void Add(T value) { Insert(Count, value); } public virtual void Insert(int index, T value) { throw new NotSupportedException(); } public virtual bool Remove(T value) { int index = IndexOf(value); if (index >= 0) { RemoveAt(index); return true; } return false; } public virtual void RemoveAt(int index) { throw new NotSupportedException(); } public virtual void Clear() { for (int index = Count - 1; index >= 0; index--) RemoveAt(index); } //----------------------------------------------- // Implemented by base class -- only accessible // after casting to IList //----------------------------------------------- IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new IListEnumerator<T>(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new IListEnumerator<T>(this); } bool System.Collections.ICollection.IsSynchronized { get { return IsReadOnly; } } object System.Collections.ICollection.SyncRoot { get { return this; } } void System.Collections.ICollection.CopyTo(Array array, int index) { for (int i = 0; i < Count; i++) array.SetValue(this[i], index); } object System.Collections.IList.this[int index] { get { return this[index]; } set { if (!IsCompatibleType(value.GetType())) throw new ArgumentException(SR.Arg_IncompatibleParamType, "value"); this[index] = (T)value; } } int System.Collections.IList.Add(object value) { if (!IsCompatibleType(value.GetType())) throw new ArgumentException(SR.Arg_IncompatibleParamType, "value"); Add((T)value); return Count - 1; } void System.Collections.IList.Clear() { Clear(); } bool System.Collections.IList.Contains(object value) { if (!IsCompatibleType(value.GetType())) return false; return Contains((T)value); } int System.Collections.IList.IndexOf(object value) { if (!IsCompatibleType(value.GetType())) return -1; return IndexOf((T)value); } void System.Collections.IList.Insert(int index, object value) { if (!IsCompatibleType(value.GetType())) throw new ArgumentException(SR.Arg_IncompatibleParamType, "value"); Insert(index, (T)value); } void System.Collections.IList.Remove(object value) { if (IsCompatibleType(value.GetType())) { Remove((T)value); } } //----------------------------------------------- // Helper methods and classes //----------------------------------------------- private static bool IsCompatibleType(object value) { if ((value == null && !typeof(T).GetTypeInfo().IsValueType) || (value is T)) return true; return false; } } /// <summary> /// Implementation of IEnumerator<T> and IEnumerator over an IList<T>. /// </summary> internal struct IListEnumerator<T> : IEnumerator<T>, System.Collections.IEnumerator { private IList<T> _sequence; private int _index; private T _current; /// <summary> /// Constructor. /// </summary> public IListEnumerator(IList<T> sequence) { _sequence = sequence; _index = 0; _current = default(T); } /// <summary> /// No-op. /// </summary> public void Dispose() { } /// <summary> /// Return current item. Return default value if before first item or after last item in the list. /// </summary> public T Current { get { return _current; } } /// <summary> /// Return current item. Throw exception if before first item or after last item in the list. /// </summary> object System.Collections.IEnumerator.Current { get { if (_index == 0) throw new InvalidOperationException(SR.Format(SR.Sch_EnumNotStarted, string.Empty)); if (_index > _sequence.Count) throw new InvalidOperationException(SR.Format(SR.Sch_EnumFinished, string.Empty)); return _current; } } /// <summary> /// Advance enumerator to next item in list. Return false if there are no more items. /// </summary> public bool MoveNext() { if (_index < _sequence.Count) { _current = _sequence[_index]; _index++; return true; } _current = default(T); return false; } /// <summary> /// Set the enumerator to its initial position, which is before the first item in the list. /// </summary> void System.Collections.IEnumerator.Reset() { _index = 0; _current = default(T); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Logic { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for WorkflowsOperations. /// </summary> public static partial class WorkflowsOperationsExtensions { /// <summary> /// Gets a list of workflows by subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> public static IPage<Workflow> ListBySubscription(this IWorkflowsOperations operations, ODataQuery<WorkflowFilter> odataQuery = default(ODataQuery<WorkflowFilter>)) { return Task.Factory.StartNew(s => ((IWorkflowsOperations)s).ListBySubscriptionAsync(odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of workflows by subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Workflow>> ListBySubscriptionAsync(this IWorkflowsOperations operations, ODataQuery<WorkflowFilter> odataQuery = default(ODataQuery<WorkflowFilter>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListBySubscriptionWithHttpMessagesAsync(odataQuery, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a list of workflows by resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> public static IPage<Workflow> ListByResourceGroup(this IWorkflowsOperations operations, string resourceGroupName, ODataQuery<WorkflowFilter> odataQuery = default(ODataQuery<WorkflowFilter>)) { return Task.Factory.StartNew(s => ((IWorkflowsOperations)s).ListByResourceGroupAsync(resourceGroupName, odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of workflows by resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Workflow>> ListByResourceGroupAsync(this IWorkflowsOperations operations, string resourceGroupName, ODataQuery<WorkflowFilter> odataQuery = default(ODataQuery<WorkflowFilter>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, odataQuery, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a workflow. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> public static Workflow Get(this IWorkflowsOperations operations, string resourceGroupName, string workflowName) { return Task.Factory.StartNew(s => ((IWorkflowsOperations)s).GetAsync(resourceGroupName, workflowName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a workflow. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Workflow> GetAsync(this IWorkflowsOperations operations, string resourceGroupName, string workflowName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, workflowName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a workflow. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='workflow'> /// The workflow. /// </param> public static Workflow CreateOrUpdate(this IWorkflowsOperations operations, string resourceGroupName, string workflowName, Workflow workflow) { return Task.Factory.StartNew(s => ((IWorkflowsOperations)s).CreateOrUpdateAsync(resourceGroupName, workflowName, workflow), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a workflow. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='workflow'> /// The workflow. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Workflow> CreateOrUpdateAsync(this IWorkflowsOperations operations, string resourceGroupName, string workflowName, Workflow workflow, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, workflowName, workflow, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates a workflow. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='workflow'> /// The workflow. /// </param> public static Workflow Update(this IWorkflowsOperations operations, string resourceGroupName, string workflowName, Workflow workflow) { return Task.Factory.StartNew(s => ((IWorkflowsOperations)s).UpdateAsync(resourceGroupName, workflowName, workflow), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates a workflow. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='workflow'> /// The workflow. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Workflow> UpdateAsync(this IWorkflowsOperations operations, string resourceGroupName, string workflowName, Workflow workflow, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, workflowName, workflow, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a workflow. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> public static void Delete(this IWorkflowsOperations operations, string resourceGroupName, string workflowName) { Task.Factory.StartNew(s => ((IWorkflowsOperations)s).DeleteAsync(resourceGroupName, workflowName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a workflow. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IWorkflowsOperations operations, string resourceGroupName, string workflowName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, workflowName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Disables a workflow. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> public static void Disable(this IWorkflowsOperations operations, string resourceGroupName, string workflowName) { Task.Factory.StartNew(s => ((IWorkflowsOperations)s).DisableAsync(resourceGroupName, workflowName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Disables a workflow. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DisableAsync(this IWorkflowsOperations operations, string resourceGroupName, string workflowName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DisableWithHttpMessagesAsync(resourceGroupName, workflowName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Enables a workflow. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> public static void Enable(this IWorkflowsOperations operations, string resourceGroupName, string workflowName) { Task.Factory.StartNew(s => ((IWorkflowsOperations)s).EnableAsync(resourceGroupName, workflowName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Enables a workflow. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task EnableAsync(this IWorkflowsOperations operations, string resourceGroupName, string workflowName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.EnableWithHttpMessagesAsync(resourceGroupName, workflowName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Generates the upgraded definition for a workflow. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='targetSchemaVersion'> /// The target schema version. /// </param> public static object GenerateUpgradedDefinition(this IWorkflowsOperations operations, string resourceGroupName, string workflowName, string targetSchemaVersion = default(string)) { return Task.Factory.StartNew(s => ((IWorkflowsOperations)s).GenerateUpgradedDefinitionAsync(resourceGroupName, workflowName, targetSchemaVersion), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Generates the upgraded definition for a workflow. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='targetSchemaVersion'> /// The target schema version. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<object> GenerateUpgradedDefinitionAsync(this IWorkflowsOperations operations, string resourceGroupName, string workflowName, string targetSchemaVersion = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GenerateUpgradedDefinitionWithHttpMessagesAsync(resourceGroupName, workflowName, targetSchemaVersion, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Validates the workflow definition. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='location'> /// The workflow location. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='workflow'> /// The workflow definition. /// </param> public static void Validate(this IWorkflowsOperations operations, string resourceGroupName, string location, string workflowName, Workflow workflow) { Task.Factory.StartNew(s => ((IWorkflowsOperations)s).ValidateAsync(resourceGroupName, location, workflowName, workflow), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Validates the workflow definition. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='location'> /// The workflow location. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='workflow'> /// The workflow definition. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task ValidateAsync(this IWorkflowsOperations operations, string resourceGroupName, string location, string workflowName, Workflow workflow, CancellationToken cancellationToken = default(CancellationToken)) { await operations.ValidateWithHttpMessagesAsync(resourceGroupName, location, workflowName, workflow, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets a list of workflows by subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Workflow> ListBySubscriptionNext(this IWorkflowsOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IWorkflowsOperations)s).ListBySubscriptionNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of workflows by subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Workflow>> ListBySubscriptionNextAsync(this IWorkflowsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListBySubscriptionNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a list of workflows by resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Workflow> ListByResourceGroupNext(this IWorkflowsOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IWorkflowsOperations)s).ListByResourceGroupNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of workflows by resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Workflow>> ListByResourceGroupNextAsync(this IWorkflowsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.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; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class libproc { // Constants from sys\param.h private const int MAXCOMLEN = 16; private const int MAXPATHLEN = 1024; // Constants from proc_info.h private const int MAXTHREADNAMESIZE = 64; private const int PROC_PIDTASKALLINFO = 2; private const int PROC_PIDTHREADINFO = 5; private const int PROC_PIDLISTTHREADS = 6; private const int PROC_PIDPATHINFO_MAXSIZE = 4 * MAXPATHLEN; private static int PROC_PIDLISTTHREADS_SIZE = (Marshal.SizeOf<uint>() * 2); // Constants from sys\resource.h private const int RUSAGE_SELF = 0; // Defines from proc_info.h internal enum ThreadRunState { TH_STATE_RUNNING = 1, TH_STATE_STOPPED = 2, TH_STATE_WAITING = 3, TH_STATE_UNINTERRUPTIBLE = 4, TH_STATE_HALTED = 5 } // Defines in proc_info.h [Flags] internal enum ThreadFlags { TH_FLAGS_SWAPPED = 0x1, TH_FLAGS_IDLE = 0x2 } // From proc_info.h [StructLayout(LayoutKind.Sequential)] internal unsafe struct proc_bsdinfo { internal uint pbi_flags; internal uint pbi_status; internal uint pbi_xstatus; internal uint pbi_pid; internal uint pbi_ppid; internal uint pbi_uid; internal uint pbi_gid; internal uint pbi_ruid; internal uint pbi_rgid; internal uint pbi_svuid; internal uint pbi_svgid; internal uint reserved; internal fixed byte pbi_comm[MAXCOMLEN]; internal fixed byte pbi_name[MAXCOMLEN * 2]; internal uint pbi_nfiles; internal uint pbi_pgid; internal uint pbi_pjobc; internal uint e_tdev; internal uint e_tpgid; internal int pbi_nice; internal ulong pbi_start_tvsec; internal ulong pbi_start_tvusec; } // From proc_info.h [StructLayout(LayoutKind.Sequential)] internal unsafe struct proc_taskinfo { internal ulong pti_virtual_size; internal ulong pti_resident_size; internal ulong pti_total_user; internal ulong pti_total_system; internal ulong pti_threads_user; internal ulong pti_threads_system; internal int pti_policy; internal int pti_faults; internal int pti_pageins; internal int pti_cow_faults; internal int pti_messages_sent; internal int pti_messages_received; internal int pti_syscalls_mach; internal int pti_syscalls_unix; internal int pti_csw; internal int pti_threadnum; internal int pti_numrunning; internal int pti_priority; }; // from sys\resource.h [StructLayout(LayoutKind.Sequential)] internal unsafe struct rusage_info_v3 { internal fixed byte ri_uuid[16]; internal ulong ri_user_time; internal ulong ri_system_time; internal ulong ri_pkg_idle_wkups; internal ulong ri_interrupt_wkups; internal ulong ri_pageins; internal ulong ri_wired_size; internal ulong ri_resident_size; internal ulong ri_phys_footprint; internal ulong ri_proc_start_abstime; internal ulong ri_proc_exit_abstime; internal ulong ri_child_user_time; internal ulong ri_child_system_time; internal ulong ri_child_pkg_idle_wkups; internal ulong ri_child_interrupt_wkups; internal ulong ri_child_pageins; internal ulong ri_child_elapsed_abstime; internal ulong ri_diskio_bytesread; internal ulong ri_diskio_byteswritten; internal ulong ri_cpu_time_qos_default; internal ulong ri_cpu_time_qos_maintenance; internal ulong ri_cpu_time_qos_background; internal ulong ri_cpu_time_qos_utility; internal ulong ri_cpu_time_qos_legacy; internal ulong ri_cpu_time_qos_user_initiated; internal ulong ri_cpu_time_qos_user_interactive; internal ulong ri_billed_system_time; internal ulong ri_serviced_system_time; } // From proc_info.h [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] internal unsafe struct proc_taskallinfo { internal proc_bsdinfo pbsd; internal proc_taskinfo ptinfo; } // From proc_info.h [StructLayout(LayoutKind.Sequential)] internal unsafe struct proc_threadinfo { internal ulong pth_user_time; internal ulong pth_system_time; internal int pth_cpu_usage; internal int pth_policy; internal int pth_run_state; internal int pth_flags; internal int pth_sleep_time; internal int pth_curpri; internal int pth_priority; internal int pth_maxpriority; internal fixed byte pth_name[MAXTHREADNAMESIZE]; } [StructLayout(LayoutKind.Sequential)] internal struct proc_fdinfo { internal int proc_fd; internal uint proc_fdtype; } /// <summary> /// Queries the OS for the PIDs for all running processes /// </summary> /// <param name="buffer">A pointer to the memory block where the PID array will start</param> /// <param name="buffersize">The length of the block of memory allocated for the PID array</param> /// <returns>Returns the number of elements (PIDs) in the buffer</returns> [DllImport(Interop.Libraries.libproc, SetLastError = true)] private static unsafe extern int proc_listallpids( int* pBuffer, int buffersize); /// <summary> /// Queries the OS for the list of all running processes and returns the PID for each /// </summary> /// <returns>Returns a list of PIDs corresponding to all running processes</returns> internal static unsafe int[] proc_listallpids() { // Get the number of processes currently running to know how much data to allocate int numProcesses = proc_listallpids(null, 0); if (numProcesses <= 0) { throw new Win32Exception(SR.CantGetAllPids); } int[] processes; do { // Create a new array for the processes (plus a 10% buffer in case new processes have spawned) // Since we don't know how many threads there could be, if result == size, that could mean two things // 1) We guessed exactly how many processes there are // 2) There are more processes that we didn't get since our buffer is too small // To make sure it isn't #2, when the result == size, increase the buffer and try again processes = new int[(int)(numProcesses * 1.10)]; fixed (int* pBuffer = processes) { numProcesses = proc_listallpids(pBuffer, processes.Length * Marshal.SizeOf<int>()); if (numProcesses <= 0) { throw new Win32Exception(SR.CantGetAllPids); } } } while (numProcesses == processes.Length); // Remove extra elements Array.Resize<int>(ref processes, numProcesses); return processes; } /// <summary> /// Gets information about a process given it's PID /// </summary> /// <param name="pid">The PID of the process</param> /// <param name="flavor">Should be PROC_PIDTASKALLINFO</param> /// <param name="arg">Flavor dependent value</param> /// <param name="buffer">A pointer to a block of memory (of size proc_taskallinfo) allocated that will contain the data</param> /// <param name="bufferSize">The size of the allocated block above</param> /// <returns> /// The amount of data actually returned. If this size matches the bufferSize parameter then /// the data is valid. If the sizes do not match then the data is invalid, most likely due /// to not having enough permissions to query for the data of that specific process /// </returns> [DllImport(Interop.Libraries.libproc, SetLastError = true)] private static unsafe extern int proc_pidinfo( int pid, int flavor, ulong arg, proc_taskallinfo* buffer, int bufferSize); /// <summary> /// Gets information about a process given it's PID /// </summary> /// <param name="pid">The PID of the process</param> /// <param name="flavor">Should be PROC_PIDTHREADINFO</param> /// <param name="arg">Flavor dependent value</param> /// <param name="buffer">A pointer to a block of memory (of size proc_threadinfo) allocated that will contain the data</param> /// <param name="bufferSize">The size of the allocated block above</param> /// <returns> /// The amount of data actually returned. If this size matches the bufferSize parameter then /// the data is valid. If the sizes do not match then the data is invalid, most likely due /// to not having enough permissions to query for the data of that specific process /// </returns> [DllImport(Interop.Libraries.libproc, SetLastError = true)] private static unsafe extern int proc_pidinfo( int pid, int flavor, ulong arg, proc_threadinfo* buffer, int bufferSize); /// <summary> /// Gets information about a process given it's PID /// </summary> /// <param name="pid">The PID of the process</param> /// <param name="flavor">Should be PROC_PIDLISTFDS</param> /// <param name="arg">Flavor dependent value</param> /// <param name="buffer">A pointer to a block of memory (of size proc_fdinfo) allocated that will contain the data</param> /// <param name="bufferSize">The size of the allocated block above</param> /// <returns> /// The amount of data actually returned. If this size matches the bufferSize parameter then /// the data is valid. If the sizes do not match then the data is invalid, most likely due /// to not having enough permissions to query for the data of that specific process /// </returns> [DllImport(Interop.Libraries.libproc, SetLastError = true)] private static unsafe extern int proc_pidinfo( int pid, int flavor, ulong arg, proc_fdinfo* buffer, int bufferSize); /// <summary> /// Gets information about a process given it's PID /// </summary> /// <param name="pid">The PID of the process</param> /// <param name="flavor">Should be PROC_PIDTASKALLINFO</param> /// <param name="arg">Flavor dependent value</param> /// <param name="buffer">A pointer to a block of memory (of size ulong[]) allocated that will contain the data</param> /// <param name="bufferSize">The size of the allocated block above</param> /// <returns> /// The amount of data actually returned. If this size matches the bufferSize parameter then /// the data is valid. If the sizes do not match then the data is invalid, most likely due /// to not having enough permissions to query for the data of that specific process /// </returns> [DllImport(Interop.Libraries.libproc, SetLastError = true)] private static unsafe extern int proc_pidinfo( int pid, int flavor, ulong arg, ulong* buffer, int bufferSize); /// <summary> /// Gets the process information for a given process /// </summary> /// <param name="pid">The PID (process ID) of the process</param> /// <returns> /// Returns a valid proc_taskallinfo struct for valid processes that the caller /// has permission to access; otherwise, returns null /// </returns> internal static unsafe proc_taskallinfo? GetProcessInfoById(int pid) { // Negative PIDs are invalid if (pid < 0) { throw new ArgumentOutOfRangeException(nameof(pid)); } // Get the process information for the specified pid int size = Marshal.SizeOf<proc_taskallinfo>(); proc_taskallinfo info = default(proc_taskallinfo); int result = proc_pidinfo(pid, PROC_PIDTASKALLINFO, 0, &info, size); return (result == size ? new proc_taskallinfo?(info) : null); } /// <summary> /// Gets the thread information for the given thread /// </summary> /// <param name="thread">The ID of the thread to query for information</param> /// <returns> /// Returns a valid proc_threadinfo struct for valid threads that the caller /// has permissions to access; otherwise, returns null /// </returns> internal static unsafe proc_threadinfo? GetThreadInfoById(int pid, ulong thread) { // Negative PIDs are invalid if (pid < 0) { throw new ArgumentOutOfRangeException(nameof(pid)); } // Negative TIDs are invalid if (thread < 0) { throw new ArgumentOutOfRangeException(nameof(thread)); } // Get the thread information for the specified thread in the specified process int size = Marshal.SizeOf<proc_threadinfo>(); proc_threadinfo info = default(proc_threadinfo); int result = proc_pidinfo(pid, PROC_PIDTHREADINFO, (ulong)thread, &info, size); return (result == size ? new proc_threadinfo?(info) : null); } internal static unsafe List<KeyValuePair<ulong, proc_threadinfo?>> GetAllThreadsInProcess(int pid) { // Negative PIDs are invalid if (pid < 0) { throw new ArgumentOutOfRangeException(nameof(pid)); } int result = 0; int size = 20; // start assuming 20 threads is enough ulong[] threadIds = null; var threads = new List<KeyValuePair<ulong, proc_threadinfo?>>(); // We have no way of knowing how many threads the process has (and therefore how big our buffer should be) // so while the return value of the function is the same as our buffer size (meaning it completely filled // our buffer), double our buffer size and try again. This ensures that we don't miss any threads do { threadIds = new ulong[size]; fixed (ulong* pBuffer = threadIds) { result = proc_pidinfo(pid, PROC_PIDLISTTHREADS, 0, pBuffer, Marshal.SizeOf<ulong>() * threadIds.Length); } if (result <= 0) { // If we were unable to access the information, just return the empty list. // This is likely to happen for privileged processes, if the process went away // by the time we tried to query it, etc. return threads; } else { checked { size *= 2; } } } while (result == Marshal.SizeOf<ulong>() * threadIds.Length); Debug.Assert((result % Marshal.SizeOf<ulong>()) == 0); // Loop over each thread and get the thread info int count = (int)(result / Marshal.SizeOf<ulong>()); threads.Capacity = count; for (int i = 0; i < count; i++) { threads.Add(new KeyValuePair<ulong, proc_threadinfo?>(threadIds[i], GetThreadInfoById(pid, threadIds[i]))); } return threads; } /// <summary> /// Gets the full path to the executable file identified by the specified PID /// </summary> /// <param name="pid">The PID of the running process</param> /// <param name="buffer">A pointer to an allocated block of memory that will be filled with the process path</param> /// <param name="bufferSize">The size of the buffer, should be PROC_PIDPATHINFO_MAXSIZE</param> /// <returns>Returns the length of the path returned on success</returns> [DllImport(Interop.Libraries.libproc, SetLastError = true)] private static unsafe extern int proc_pidpath( int pid, byte* buffer, uint bufferSize); /// <summary> /// Gets the full path to the executable file identified by the specified PID /// </summary> /// <param name="pid">The PID of the running process</param> /// <returns>Returns the full path to the process executable</returns> internal static unsafe string proc_pidpath(int pid) { // Negative PIDs are invalid if (pid < 0) { throw new ArgumentOutOfRangeException(nameof(pid), SR.NegativePidNotSupported); } // The path is a fixed buffer size, so use that and trim it after int result = 0; byte* pBuffer = stackalloc byte[PROC_PIDPATHINFO_MAXSIZE]; result = proc_pidpath(pid, pBuffer, (uint)(PROC_PIDPATHINFO_MAXSIZE * Marshal.SizeOf<byte>())); if (result <= 0) { throw new Win32Exception(); } // OS X uses UTF-8. The conversion may not strip off all trailing \0s so remove them here return System.Text.Encoding.UTF8.GetString(pBuffer, result); } /// <summary> /// Gets the rusage information for the process identified by the PID /// </summary> /// <param name="pid">The process to retrieve the rusage for</param> /// <param name="flavor">Should be RUSAGE_SELF to specify getting the info for the specified process</param> /// <param name="rusage_info_t">A buffer to be filled with rusage_info data</param> /// <returns>Returns 0 on success; on fail, -1 and errno is set with the error code</returns> /// <remarks> /// We need to use IntPtr here for the buffer since the function signature uses /// void* and not a strong type even though it returns a rusage_info struct /// </remarks> [DllImport(Interop.Libraries.libproc, SetLastError = true)] private static unsafe extern int proc_pid_rusage( int pid, int flavor, rusage_info_v3* rusage_info_t); /// <summary> /// Gets the rusage information for the process identified by the PID /// </summary> /// <param name="pid">The process to retrieve the rusage for</param> /// <returns>On success, returns a struct containing info about the process; on /// failure or when the caller doesn't have permissions to the process, throws a Win32Exception /// </returns> internal static unsafe rusage_info_v3 proc_pid_rusage(int pid) { // Negative PIDs are invalid if (pid < 0) { throw new ArgumentOutOfRangeException(nameof(pid), SR.NegativePidNotSupported); } rusage_info_v3 info = new rusage_info_v3(); // Get the PIDs rusage info int result = proc_pid_rusage(pid, RUSAGE_SELF, &info); if (result < 0) { throw new InvalidOperationException(SR.RUsageFailure); } return info; } } }
/* * * 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 Lucene.Net.Support; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using Console = Lucene.Net.Support.SystemConsole; namespace Lucene.Net { public static class SystemTypesHelpers { public static char[] toCharArray(this string str) { return str.ToCharArray(); } public static string toString(this object obj) { // LUCENENET: We compensate for the fact that // .NET doesn't have reliable results from ToString // by defaulting the behavior to return a concatenated // list of the contents of enumerables rather than the // .NET type name (similar to the way Java behaves). // Unless of course we already have a string (which // implements IEnumerable so we need skip it). if (obj is IEnumerable && !(obj is string)) { string result = obj.ToString(); // Assume that this is a default call to object.ToString() // when it starts with the same namespace as the type. if (!result.StartsWith(obj.GetType().Namespace, StringComparison.Ordinal)) { return result; } // If this is the default text, replace it with // the contents of the enumerable as Java would. IEnumerable list = obj as IEnumerable; StringBuilder sb = new StringBuilder(); bool isArray = obj.GetType().IsArray; sb.Append(isArray ? "{" : "["); foreach (object item in list) { if (sb.Length > 1) { sb.Append(", "); } sb.Append(item != null ? item.ToString() : "null"); } sb.Append(isArray ? "}" : "]"); return sb.ToString(); } return obj.ToString(); } public static bool equals(this object obj1, object obj2) { return obj1.Equals(obj2); } public static StringBuilder append(this StringBuilder sb, bool value) { sb.Append(value); return sb; } public static StringBuilder append(this StringBuilder sb, byte value) { sb.Append(value); return sb; } public static StringBuilder append(this StringBuilder sb, char value) { sb.Append(value); return sb; } public static StringBuilder append(this StringBuilder sb, char[] value) { sb.Append(value); return sb; } public static StringBuilder append(this StringBuilder sb, decimal value) { sb.Append(value); return sb; } public static StringBuilder append(this StringBuilder sb, double value) { sb.Append(value); return sb; } public static StringBuilder append(this StringBuilder sb, float value) { sb.Append(value); return sb; } public static StringBuilder append(this StringBuilder sb, int value) { sb.Append(value); return sb; } public static StringBuilder append(this StringBuilder sb, long value) { sb.Append(value); return sb; } public static StringBuilder append(this StringBuilder sb, object value) { sb.Append(value); return sb; } public static StringBuilder append(this StringBuilder sb, sbyte value) { sb.Append(value); return sb; } public static StringBuilder append(this StringBuilder sb, short value) { sb.Append(value); return sb; } public static StringBuilder append(this StringBuilder sb, string value) { sb.Append(value); return sb; } public static StringBuilder append(this StringBuilder sb, uint value) { sb.Append(value); return sb; } public static StringBuilder append(this StringBuilder sb, ulong value) { sb.Append(value); return sb; } public static StringBuilder append(this StringBuilder sb, ushort value) { sb.Append(value); return sb; } public static sbyte[] getBytes(this string str, string encoding) { return (sbyte[])(Array)Encoding.GetEncoding(encoding).GetBytes(str); } public static byte[] getBytes(this string str, Encoding encoding) { return encoding.GetBytes(str); } public static int size<T>(this ICollection<T> list) { return list.Count; } public static T[] clone<T>(this T[] e) { return (T[]) e.Clone(); } public static void add<T>(this ISet<T> s, T item) { s.Add(item); } public static void addAll<T>(this ISet<T> s, IEnumerable<T> other) { s.AddAll(other); } public static bool contains<T>(this ISet<T> s, T item) { return s.Contains(item); } public static bool containsAll<T>(this ISet<T> s, IEnumerable<T> list) { return s.IsSupersetOf(list); } public static bool remove<T>(this ISet<T> s, T item) { return s.Remove(item); } public static bool removeAll<T>(this ISet<T> s, IEnumerable<T> list) { bool modified = false; if (s.Count > list.Count()) { for (var i = list.GetEnumerator(); i.MoveNext();) modified |= s.Remove(i.Current); } else { List<T> toRemove = new List<T>(); for (var i = s.GetEnumerator(); i.MoveNext();) { if (list.Contains(i.Current)) { toRemove.Add(i.Current); } } foreach (var i in toRemove) { s.Remove(i); modified = true; } } return modified; } public static void clear<T>(this ISet<T> s) { s.Clear(); } public static void retainAll<T>(this ISet<T> s, ISet<T> other) { foreach (var e in s) { if (!other.Contains(e)) s.Remove(e); } } public static void printStackTrace(this Exception e) { Console.WriteLine(e.StackTrace); } /// <summary> /// Locates resources in the same directory as this type /// </summary> public static Stream getResourceAsStream(this Type t, string name) { return t.GetTypeInfo().Assembly.FindAndGetManifestResourceStream(t, name); } public static int read(this TextReader reader, char[] buffer) { int bytesRead = reader.Read(buffer, 0, buffer.Length); // Convert the .NET 0 based bytes to the Java -1 behavior when reading is done. return bytesRead == 0 ? -1 : bytesRead; } public static string replaceFirst(this string text, string search, string replace) { var regex = new Regex(search); return regex.Replace(text, replace, 1); } } }