context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using Lucene.Net.Index; using Lucene.Net.Support; using IndexReader = Lucene.Net.Index.IndexReader; using ToStringUtils = Lucene.Net.Util.ToStringUtils; using Query = Lucene.Net.Search.Query; namespace Lucene.Net.Search.Spans { /// <summary>Matches spans near the beginning of a field. </summary> //[Serializable] //Disabled for https://github.com/dotnet/standard/issues/300 public class SpanFirstQuery : SpanQuery, System.ICloneable { private class AnonymousClassSpans : Spans { public AnonymousClassSpans(Lucene.Net.Index.IndexReader reader, SpanFirstQuery enclosingInstance) { InitBlock(reader, enclosingInstance); } private void InitBlock(Lucene.Net.Index.IndexReader reader, SpanFirstQuery enclosingInstance) { this.reader = reader; this.enclosingInstance = enclosingInstance; spans = Enclosing_Instance.match.GetSpans(reader); } private Lucene.Net.Index.IndexReader reader; private SpanFirstQuery enclosingInstance; public SpanFirstQuery Enclosing_Instance { get { return enclosingInstance; } } private Spans spans; public override bool Next() { while (spans.Next()) { // scan to next match if (End() <= Enclosing_Instance.end) return true; } return false; } public override bool SkipTo(int target) { if (!spans.SkipTo(target)) return false; return spans.End() <= Enclosing_Instance.end || Next(); } public override int Doc() { return spans.Doc(); } public override int Start() { return spans.Start(); } public override int End() { return spans.End(); } // TODO: Remove warning after API has been finalized public override ICollection<byte[]> GetPayload() { System.Collections.Generic.ICollection<byte[]> result = null; if (spans.IsPayloadAvailable()) { result = spans.GetPayload(); } return result; //TODO: any way to avoid the new construction? } // TODO: Remove warning after API has been finalized public override bool IsPayloadAvailable() { return spans.IsPayloadAvailable(); } public override System.String ToString() { return "spans(" + Enclosing_Instance.ToString() + ")"; } } private SpanQuery match; private int end; /// <summary>Construct a SpanFirstQuery matching spans in <c>match</c> whose end /// position is less than or equal to <c>end</c>. /// </summary> public SpanFirstQuery(SpanQuery match, int end) { this.match = match; this.end = end; } /// <summary>Return the SpanQuery whose matches are filtered. </summary> public virtual SpanQuery Match { get { return match; } } /// <summary>Return the maximum end position permitted in a match. </summary> public virtual int End { get { return end; } } public override string Field { get { return match.Field; } } public override System.String ToString(System.String field) { System.Text.StringBuilder buffer = new System.Text.StringBuilder(); buffer.Append("spanFirst("); buffer.Append(match.ToString(field)); buffer.Append(", "); buffer.Append(end); buffer.Append(")"); buffer.Append(ToStringUtils.Boost(Boost)); return buffer.ToString(); } public override System.Object Clone() { SpanFirstQuery spanFirstQuery = new SpanFirstQuery((SpanQuery) match.Clone(), end); spanFirstQuery.Boost = Boost; return spanFirstQuery; } public override void ExtractTerms(System.Collections.Generic.ISet<Term> terms) { match.ExtractTerms(terms); } public override Spans GetSpans(IndexReader reader) { return new AnonymousClassSpans(reader, this); } public override Query Rewrite(IndexReader reader) { SpanFirstQuery clone = null; SpanQuery rewritten = (SpanQuery) match.Rewrite(reader); if (rewritten != match) { clone = (SpanFirstQuery) this.Clone(); clone.match = rewritten; } if (clone != null) { return clone; // some clauses rewrote } else { return this; // no clauses rewrote } } public override bool Equals(System.Object o) { if (this == o) return true; if (!(o is SpanFirstQuery)) return false; SpanFirstQuery other = (SpanFirstQuery) o; return this.end == other.end && this.match.Equals(other.match) && this.Boost == other.Boost; } public override int GetHashCode() { int h = match.GetHashCode(); h ^= ((h << 8) | (Number.URShift(h, 25))); // reversible h ^= System.Convert.ToInt32(Boost) ^ end; return h; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Collections.Tests { public class SortedListTests { [Fact] public void Ctor_Empty() { var sortList = new SortedList(); Assert.Equal(0, sortList.Count); Assert.Equal(0, sortList.Capacity); Assert.False(sortList.IsFixedSize); Assert.False(sortList.IsReadOnly); Assert.False(sortList.IsSynchronized); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public void Ctor_Int(int initialCapacity) { var sortList = new SortedList(initialCapacity); Assert.Equal(0, sortList.Count); Assert.Equal(initialCapacity, sortList.Capacity); Assert.False(sortList.IsFixedSize); Assert.False(sortList.IsReadOnly); Assert.False(sortList.IsSynchronized); } [Fact] public void Ctor_Int_NegativeInitialCapacity_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("initialCapacity", () => new SortedList(-1)); // InitialCapacity < 0 } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public void Ctor_IComparer_Int(int initialCapacity) { var sortList = new SortedList(new CustomComparer(), initialCapacity); Assert.Equal(0, sortList.Count); Assert.Equal(initialCapacity, sortList.Capacity); Assert.False(sortList.IsFixedSize); Assert.False(sortList.IsReadOnly); Assert.False(sortList.IsSynchronized); } [Fact] public void Ctor_IComparer_Int_NegativeInitialCapacity_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => new SortedList(new CustomComparer(), -1)); // InitialCapacity < 0 } [Fact] public void Ctor_IComparer() { var sortList = new SortedList(new CustomComparer()); Assert.Equal(0, sortList.Count); Assert.False(sortList.IsFixedSize); Assert.False(sortList.IsReadOnly); Assert.False(sortList.IsSynchronized); } [Fact] public void Ctor_IComparer_Null() { var sortList = new SortedList((IComparer)null); Assert.Equal(0, sortList.Count); Assert.False(sortList.IsFixedSize); Assert.False(sortList.IsReadOnly); Assert.False(sortList.IsSynchronized); } [Theory] [InlineData(0, true)] [InlineData(1, true)] [InlineData(10, true)] [InlineData(100, true)] [InlineData(0, false)] [InlineData(1, false)] [InlineData(10, false)] [InlineData(100, false)] public void Ctor_IDictionary(int count, bool sorted) { var hashtable = new Hashtable(); if (sorted) { // Create a hashtable in the correctly sorted order for (int i = 0; i < count; i++) { hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2")); } } else { // Create a hashtable in the wrong order and make sure it is sorted for (int i = count - 1; i >= 0; i--) { hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2")); } } var sortList = new SortedList(hashtable); Assert.Equal(count, sortList.Count); Assert.True(sortList.Capacity >= sortList.Count); for (int i = 0; i < count; i++) { string key = "Key_" + i.ToString("D2"); string value = "Value_" + i.ToString("D2"); Assert.Equal(sortList.GetByIndex(i), value); Assert.Equal(hashtable[key], sortList[key]); } Assert.False(sortList.IsFixedSize); Assert.False(sortList.IsReadOnly); Assert.False(sortList.IsSynchronized); } [Fact] public void Ctor_IDictionary_NullDictionary_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("d", () => new SortedList((IDictionary)null)); // Dictionary is null } [Theory] [InlineData(0, true)] [InlineData(1, true)] [InlineData(10, true)] [InlineData(100, true)] [InlineData(0, false)] [InlineData(1, false)] [InlineData(10, false)] [InlineData(100, false)] public void Ctor_IDictionary_IComparer(int count, bool sorted) { var hashtable = new Hashtable(); if (sorted) { // Create a hashtable in the correctly sorted order for (int i = count - 1; i >= 0; i--) { hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2")); } } else { // Create a hashtable in the wrong order and make sure it is sorted for (int i = 0; i < count; i++) { hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2")); } } var sortList = new SortedList(hashtable, new CustomComparer()); Assert.Equal(count, sortList.Count); Assert.True(sortList.Capacity >= sortList.Count); for (int i = 0; i < count; i++) { string key = "Key_" + i.ToString("D2"); string value = "Value_" + i.ToString("D2"); string expectedValue = "Value_" + (count - i - 1).ToString("D2"); Assert.Equal(sortList.GetByIndex(i), expectedValue); Assert.Equal(hashtable[key], sortList[key]); } Assert.False(sortList.IsFixedSize); Assert.False(sortList.IsReadOnly); Assert.False(sortList.IsSynchronized); } [Fact] public void Ctor_IDictionary_IComparer_Null() { var sortList = new SortedList(new Hashtable(), null); Assert.Equal(0, sortList.Count); Assert.False(sortList.IsFixedSize); Assert.False(sortList.IsReadOnly); Assert.False(sortList.IsSynchronized); } [Fact] public void Ctor_IDictionary_IComparer_NullDictionary_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("d", () => new SortedList(null, new CustomComparer())); // Dictionary is null } [Fact] public void DebuggerAttribute_Empty() { Assert.Equal("Count = 0", DebuggerAttributes.ValidateDebuggerDisplayReferences(new SortedList())); } [Fact] public void DebuggerAttribute_NormalList() { var list = new SortedList() { { "a", 1 }, { "b", 2 } }; DebuggerAttributeInfo debuggerAttribute = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(list); PropertyInfo infoProperty = debuggerAttribute.Properties.Single(property => property.Name == "Items"); object[] items = (object[])infoProperty.GetValue(debuggerAttribute.Instance); Assert.Equal(list.Count, items.Length); } [Fact] public void DebuggerAttribute_SynchronizedList() { var list = SortedList.Synchronized(new SortedList() { { "a", 1 }, { "b", 2 } }); DebuggerAttributeInfo debuggerAttribute = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(SortedList), list); PropertyInfo infoProperty = debuggerAttribute.Properties.Single(property => property.Name == "Items"); object[] items = (object[])infoProperty.GetValue(debuggerAttribute.Instance); Assert.Equal(list.Count, items.Length); } [Fact] public void DebuggerAttribute_NullSortedList_ThrowsArgumentNullException() { bool threwNull = false; try { DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(SortedList), null); } catch (TargetInvocationException ex) { threwNull = ex.InnerException is ArgumentNullException; } Assert.True(threwNull); } [Fact] public void EnsureCapacity_NewCapacityLessThanMin_CapsToMaxArrayLength() { // A situation like this occurs for very large lengths of SortedList. // To avoid allocating several GBs of memory and making this test run for a very // long time, we can use reflection to invoke SortedList's growth method manually. // This is relatively brittle, as it relies on accessing a private method via reflection // that isn't guaranteed to be stable. const int InitialCapacity = 10; const int MinCapacity = InitialCapacity * 2 + 1; var sortedList = new SortedList(InitialCapacity); MethodInfo ensureCapacity = sortedList.GetType().GetMethod("EnsureCapacity", BindingFlags.NonPublic | BindingFlags.Instance); ensureCapacity.Invoke(sortedList, new object[] { MinCapacity }); Assert.Equal(MinCapacity, sortedList.Capacity); } [Fact] public void Add() { var sortList1 = new SortedList(); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < 100; i++) { string key = "Key_" + i.ToString("D2"); string value = "Value_" + i; sortList2.Add(key, value); Assert.True(sortList2.ContainsKey(key)); Assert.True(sortList2.ContainsValue(value)); Assert.Equal(i, sortList2.IndexOfKey(key)); Assert.Equal(i, sortList2.IndexOfValue(value)); Assert.Equal(i + 1, sortList2.Count); } }); } [Fact] public void Add_Invalid() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.Add(null, 101)); // Key is null AssertExtensions.Throws<ArgumentException>(null, () => sortList2.Add(1, 101)); // Key already exists }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public void Clear(int count) { SortedList sortList1 = Helpers.CreateIntSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { sortList2.Clear(); Assert.Equal(0, sortList2.Count); sortList2.Clear(); Assert.Equal(0, sortList2.Count); }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public void Clone(int count) { SortedList sortList1 = Helpers.CreateIntSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { SortedList sortListClone = (SortedList)sortList2.Clone(); Assert.Equal(sortList2.Count, sortListClone.Count); Assert.False(sortListClone.IsSynchronized); // IsSynchronized is not copied Assert.Equal(sortList2.IsFixedSize, sortListClone.IsFixedSize); Assert.Equal(sortList2.IsReadOnly, sortListClone.IsReadOnly); for (int i = 0; i < sortListClone.Count; i++) { Assert.Equal(sortList2[i], sortListClone[i]); } }); } [Fact] public void Clone_IsShallowCopy() { var sortList = new SortedList(); for (int i = 0; i < 10; i++) { sortList.Add(i, new Foo()); } SortedList sortListClone = (SortedList)sortList.Clone(); string stringValue = "Hello World"; for (int i = 0; i < 10; i++) { Assert.Equal(stringValue, ((Foo)sortListClone[i]).StringValue); } // Now we remove an object from the original list, but this should still be present in the clone sortList.RemoveAt(9); Assert.Equal(stringValue, ((Foo)sortListClone[9]).StringValue); stringValue = "Good Bye"; ((Foo)sortList[0]).StringValue = stringValue; Assert.Equal(stringValue, ((Foo)sortList[0]).StringValue); Assert.Equal(stringValue, ((Foo)sortListClone[0]).StringValue); // If we change the object, of course, the previous should not happen sortListClone[0] = new Foo(); Assert.Equal(stringValue, ((Foo)sortList[0]).StringValue); stringValue = "Hello World"; Assert.Equal(stringValue, ((Foo)sortListClone[0]).StringValue); } [Fact] public void ContainsKey() { var sortList1 = new SortedList(); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < 100; i++) { string key = "Key_" + i; sortList2.Add(key, i); Assert.True(sortList2.Contains(key)); Assert.True(sortList2.ContainsKey(key)); } Assert.False(sortList2.ContainsKey("Non_Existent_Key")); for (int i = 0; i < sortList2.Count; i++) { string removedKey = "Key_" + i; sortList2.Remove(removedKey); Assert.False(sortList2.Contains(removedKey)); Assert.False(sortList2.ContainsKey(removedKey)); } }); } [Fact] public void ContainsKey_NullKey_ThrowsArgumentNullException() { var sortList1 = new SortedList(); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.Contains(null)); // Key is null AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.ContainsKey(null)); // Key is null }); } [Fact] public void ContainsValue() { var sortList1 = new SortedList(); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < 100; i++) { sortList2.Add(i, "Value_" + i); Assert.True(sortList2.ContainsValue("Value_" + i)); } Assert.False(sortList2.ContainsValue("Non_Existent_Value")); for (int i = 0; i < sortList2.Count; i++) { sortList2.Remove(i); Assert.False(sortList2.ContainsValue("Value_" + i)); } }); } [Theory] [InlineData(0, 0)] [InlineData(1, 0)] [InlineData(10, 0)] [InlineData(100, 0)] [InlineData(0, 50)] [InlineData(1, 50)] [InlineData(10, 50)] [InlineData(100, 50)] public void CopyTo(int count, int index) { SortedList sortList1 = Helpers.CreateStringSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { var array = new object[index + count]; sortList2.CopyTo(array, index); Assert.Equal(index + count, array.Length); for (int i = index; i < index + count; i++) { int actualIndex = i - index; string key = "Key_" + actualIndex.ToString("D2"); string value = "Value_" + actualIndex; DictionaryEntry entry = (DictionaryEntry)array[i]; Assert.Equal(key, entry.Key); Assert.Equal(value, entry.Value); } }); } [Fact] public void CopyTo_Invalid() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { AssertExtensions.Throws<ArgumentNullException>("array", () => sortList2.CopyTo(null, 0)); // Array is null AssertExtensions.Throws<ArgumentException>("array", null, () => sortList2.CopyTo(new object[10, 10], 0)); // Array is multidimensional AssertExtensions.Throws<ArgumentOutOfRangeException>("arrayIndex", () => sortList2.CopyTo(new object[100], -1)); // Index < 0 AssertExtensions.Throws<ArgumentException>(null, () => sortList2.CopyTo(new object[150], 51)); // Index + list.Count > array.Count }); } [Fact] public void GetByIndex() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < sortList2.Count; i++) { Assert.Equal(i, sortList2.GetByIndex(i)); int i2 = sortList2.IndexOfKey(i); Assert.Equal(i, i2); i2 = sortList2.IndexOfValue(i); Assert.Equal(i, i2); } }); } [Fact] public void GetByIndex_InvalidIndex_ThrowsArgumentOutOfRangeException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetByIndex(-1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetByIndex(sortList2.Count)); // Index >= list.Count }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public void GetEnumerator_IDictionaryEnumerator(int count) { SortedList sortList1 = Helpers.CreateIntSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { Assert.NotSame(sortList2.GetEnumerator(), sortList2.GetEnumerator()); IDictionaryEnumerator enumerator = sortList2.GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { Assert.Equal(enumerator.Current, enumerator.Entry); Assert.Equal(enumerator.Entry.Key, enumerator.Key); Assert.Equal(enumerator.Entry.Value, enumerator.Value); Assert.Equal(sortList2.GetKey(counter), enumerator.Entry.Key); Assert.Equal(sortList2.GetByIndex(counter), enumerator.Entry.Value); counter++; } Assert.Equal(count, counter); enumerator.Reset(); } }); } [Fact] public void GetEnumerator_IDictionaryEnumerator_Invalid() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { // If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current etc. doesn't IDictionaryEnumerator enumerator = sortList2.GetEnumerator(); enumerator.MoveNext(); sortList2.Add(101, 101); Assert.NotNull(enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); // Current etc. throw if index < 0 enumerator = sortList2.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); // Current etc. throw after resetting enumerator = sortList2.GetEnumerator(); enumerator.MoveNext(); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); // Current etc. throw if the current index is >= count enumerator = sortList2.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public void GetEnumerator_IEnumerator(int count) { SortedList sortList = Helpers.CreateIntSortedList(count); Assert.NotSame(sortList.GetEnumerator(), sortList.GetEnumerator()); IEnumerator enumerator = sortList.GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { DictionaryEntry dictEntry = (DictionaryEntry)enumerator.Current; Assert.Equal(sortList.GetKey(counter), dictEntry.Key); Assert.Equal(sortList.GetByIndex(counter), dictEntry.Value); counter++; } Assert.Equal(count, counter); enumerator.Reset(); } } [Fact] public void GetEnumerator_StartOfEnumeration_Clone() { SortedList sortedList = Helpers.CreateIntSortedList(10); IDictionaryEnumerator enumerator = sortedList.GetEnumerator(); ICloneable cloneableEnumerator = (ICloneable)enumerator; IDictionaryEnumerator clonedEnumerator = (IDictionaryEnumerator)cloneableEnumerator.Clone(); Assert.NotSame(enumerator, clonedEnumerator); // Cloned and original enumerators should enumerate separately. Assert.True(enumerator.MoveNext()); Assert.Equal(sortedList[0], enumerator.Value); Assert.Throws<InvalidOperationException>(() => clonedEnumerator.Value); Assert.True(clonedEnumerator.MoveNext()); Assert.Equal(sortedList[0], enumerator.Value); Assert.Equal(sortedList[0], clonedEnumerator.Value); // Cloned and original enumerators should enumerate in the same sequence. for (int i = 1; i < sortedList.Count; i++) { Assert.True(enumerator.MoveNext()); Assert.NotEqual(enumerator.Current, clonedEnumerator.Current); Assert.True(clonedEnumerator.MoveNext()); Assert.Equal(enumerator.Current, clonedEnumerator.Current); } Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Value); Assert.Equal(sortedList[sortedList.Count - 1], clonedEnumerator.Value); Assert.False(clonedEnumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Value); Assert.Throws<InvalidOperationException>(() => clonedEnumerator.Value); } [Fact] public void GetEnumerator_InMiddleOfEnumeration_Clone() { SortedList sortedList = Helpers.CreateIntSortedList(10); IEnumerator enumerator = sortedList.GetEnumerator(); enumerator.MoveNext(); ICloneable cloneableEnumerator = (ICloneable)enumerator; // Cloned and original enumerators should start at the same spot, even // if the original is in the middle of enumeration. IEnumerator clonedEnumerator = (IEnumerator)cloneableEnumerator.Clone(); Assert.Equal(enumerator.Current, clonedEnumerator.Current); for (int i = 0; i < sortedList.Count - 1; i++) { Assert.True(clonedEnumerator.MoveNext()); } Assert.False(clonedEnumerator.MoveNext()); } [Fact] public void GetEnumerator_IEnumerator_Invalid() { SortedList sortList = Helpers.CreateIntSortedList(100); // If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current doesn't IEnumerator enumerator = ((IEnumerable)sortList).GetEnumerator(); enumerator.MoveNext(); sortList.Add(101, 101); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); // Current throws if index < 0 enumerator = sortList.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Current throw after resetting enumerator = sortList.GetEnumerator(); enumerator.MoveNext(); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Current throw if the current index is >= count enumerator = sortList.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public void GetKeyList(int count) { SortedList sortList1 = Helpers.CreateStringSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys1 = sortList2.GetKeyList(); IList keys2 = sortList2.GetKeyList(); // Test we have copied the correct keys Assert.Equal(count, keys1.Count); Assert.Equal(count, keys2.Count); for (int i = 0; i < keys1.Count; i++) { string key = "Key_" + i.ToString("D2"); Assert.Equal(key, keys1[i]); Assert.Equal(key, keys2[i]); Assert.True(sortList2.ContainsKey(keys1[i])); } }); } [Fact] public void GetKeyList_IsSameAsKeysProperty() { var sortList = Helpers.CreateIntSortedList(10); Assert.Same(sortList.GetKeyList(), sortList.Keys); } [Fact] public void GetKeyList_IListProperties() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); Assert.True(keys.IsReadOnly); Assert.True(keys.IsFixedSize); Assert.False(keys.IsSynchronized); Assert.Equal(sortList2.SyncRoot, keys.SyncRoot); }); } [Fact] public void GetKeyList_Contains() { SortedList sortList1 = Helpers.CreateStringSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); for (int i = 0; i < keys.Count; i++) { string key = "Key_" + i.ToString("D2"); Assert.True(keys.Contains(key)); } Assert.False(keys.Contains("Key_101")); // No such key }); } [Fact] public void GetKeyList_Contains_InvalidValueType_ThrowsInvalidOperationException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); Assert.Throws<InvalidOperationException>(() => keys.Contains("hello")); // Value is a different object type }); } [Fact] public void GetKeyList_IndexOf() { SortedList sortList1 = Helpers.CreateStringSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); for (int i = 0; i < keys.Count; i++) { string key = "Key_" + i.ToString("D2"); Assert.Equal(i, keys.IndexOf(key)); } Assert.Equal(-1, keys.IndexOf("Key_101")); }); } [Fact] public void GetKeyList_IndexOf_Invalid() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); AssertExtensions.Throws<ArgumentNullException>("key", () => keys.IndexOf(null)); // Value is null Assert.Throws<InvalidOperationException>(() => keys.IndexOf("hello")); // Value is a different object type }); } [Theory] [InlineData(0, 0)] [InlineData(1, 0)] [InlineData(10, 0)] [InlineData(100, 0)] [InlineData(0, 50)] [InlineData(1, 50)] [InlineData(10, 50)] [InlineData(100, 50)] public void GetKeyList_CopyTo(int count, int index) { SortedList sortList1 = Helpers.CreateIntSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { object[] array = new object[index + count]; IList keys = sortList2.GetKeyList(); keys.CopyTo(array, index); Assert.Equal(index + count, array.Length); for (int i = index; i < index + count; i++) { Assert.Equal(keys[i - index], array[i]); } }); } [Fact] public void GetKeyList_CopyTo_Invalid() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); AssertExtensions.Throws<ArgumentNullException>("destinationArray", "dest", () => keys.CopyTo(null, 0)); // Array is null AssertExtensions.Throws<ArgumentException>("array", null, () => keys.CopyTo(new object[10, 10], 0)); // Array is multidimensional -- in netfx ParamName is null // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", "dstIndex", () => keys.CopyTo(new object[100], -1)); // Index + list.Count > array.Count AssertExtensions.Throws<ArgumentException>("destinationArray", string.Empty, () => keys.CopyTo(new object[150], 51)); }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public void GetKeyList_GetEnumerator(int count) { SortedList sortList1 = Helpers.CreateIntSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); Assert.NotSame(keys.GetEnumerator(), keys.GetEnumerator()); IEnumerator enumerator = sortList2.GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { object key = keys[counter]; DictionaryEntry entry = (DictionaryEntry)enumerator.Current; Assert.Equal(key, entry.Key); Assert.Equal(sortList2[key], entry.Value); counter++; } Assert.Equal(count, counter); enumerator.Reset(); } }); } [Fact] public void GetKeyList_GetEnumerator_Invalid() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); // If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current etc. doesn't IEnumerator enumerator = keys.GetEnumerator(); enumerator.MoveNext(); sortList2.Add(101, 101); Assert.NotNull(enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); // Current etc. throw if index < 0 enumerator = keys.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Current etc. throw after resetting enumerator = keys.GetEnumerator(); enumerator.MoveNext(); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Current etc. throw if the current index is >= count enumerator = keys.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); }); } [Fact] public void GetKeyList_TryingToModifyCollection_ThrowsNotSupportedException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); Assert.Throws<NotSupportedException>(() => keys.Add(101)); Assert.Throws<NotSupportedException>(() => keys.Clear()); Assert.Throws<NotSupportedException>(() => keys.Insert(0, 101)); Assert.Throws<NotSupportedException>(() => keys.Remove(1)); Assert.Throws<NotSupportedException>(() => keys.RemoveAt(0)); Assert.Throws<NotSupportedException>(() => keys[0] = 101); }); } [Theory] [InlineData(0)] [InlineData(100)] public void GetKey(int count) { SortedList sortList1 = Helpers.CreateStringSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < count; i++) { string key = "Key_" + i.ToString("D2"); Assert.Equal(key, sortList2.GetKey(sortList2.IndexOfKey(key))); } }); } [Fact] public void GetKey_InvalidIndex_ThrowsArgumentOutOfRangeException() { SortedList sortList1 = Helpers.CreateStringSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetKey(-1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetKey(sortList2.Count)); // Index >= count }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public void GetValueList(int count) { SortedList sortList1 = Helpers.CreateStringSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList values1 = sortList2.GetValueList(); IList values2 = sortList2.GetValueList(); // Test we have copied the correct values Assert.Equal(count, values1.Count); Assert.Equal(count, values2.Count); for (int i = 0; i < values1.Count; i++) { string value = "Value_" + i; Assert.Equal(value, values1[i]); Assert.Equal(value, values2[i]); Assert.True(sortList2.ContainsValue(values2[i])); } }); } [Fact] public void GetValueList_IsSameAsValuesProperty() { var sortList = Helpers.CreateIntSortedList(10); Assert.Same(sortList.GetValueList(), sortList.Values); } [Fact] public void GetValueList_IListProperties() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList values = sortList2.GetValueList(); Assert.True(values.IsReadOnly); Assert.True(values.IsFixedSize); Assert.False(values.IsSynchronized); Assert.Equal(sortList2.SyncRoot, values.SyncRoot); }); } [Fact] public void GetValueList_Contains() { SortedList sortList1 = Helpers.CreateStringSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList values = sortList2.GetValueList(); for (int i = 0; i < values.Count; i++) { string value = "Value_" + i; Assert.True(values.Contains(value)); } // No such value Assert.False(values.Contains("Value_101")); Assert.False(values.Contains(101)); Assert.False(values.Contains(null)); }); } [Fact] public void GetValueList_IndexOf() { SortedList sortList1 = Helpers.CreateStringSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList values = sortList2.GetValueList(); for (int i = 0; i < values.Count; i++) { string value = "Value_" + i; Assert.Equal(i, values.IndexOf(value)); } Assert.Equal(-1, values.IndexOf(101)); }); } [Theory] [InlineData(0, 0)] [InlineData(1, 0)] [InlineData(10, 0)] [InlineData(100, 0)] [InlineData(0, 50)] [InlineData(1, 50)] [InlineData(10, 50)] [InlineData(100, 50)] public void GetValueList_CopyTo(int count, int index) { SortedList sortList1 = Helpers.CreateIntSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { object[] array = new object[index + count]; IList values = sortList2.GetValueList(); values.CopyTo(array, index); Assert.Equal(index + count, array.Length); for (int i = index; i < index + count; i++) { Assert.Equal(values[i - index], array[i]); } }); } [Fact] public void GetValueList_CopyTo_Invalid() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList values = sortList2.GetValueList(); AssertExtensions.Throws<ArgumentNullException>("destinationArray", "dest", () => values.CopyTo(null, 0)); // Array is null AssertExtensions.Throws<ArgumentException>("array", null, () => values.CopyTo(new object[10, 10], 0)); // Array is multidimensional -- in netfx ParamName is null AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", "dstIndex", () => values.CopyTo(new object[100], -1)); // Index < 0 AssertExtensions.Throws<ArgumentException>("destinationArray", string.Empty, () => values.CopyTo(new object[150], 51)); // Index + list.Count > array.Count }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public void GetValueList_GetEnumerator(int count) { SortedList sortList1 = Helpers.CreateIntSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList values = sortList2.GetValueList(); Assert.NotSame(values.GetEnumerator(), values.GetEnumerator()); IEnumerator enumerator = sortList2.GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { object key = values[counter]; DictionaryEntry entry = (DictionaryEntry)enumerator.Current; Assert.Equal(key, entry.Key); Assert.Equal(sortList2[key], entry.Value); counter++; } Assert.Equal(count, counter); enumerator.Reset(); } }); } [Fact] public void ValueList_GetEnumerator_Invalid() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList values = sortList2.GetValueList(); // If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current etc. doesn't IEnumerator enumerator = values.GetEnumerator(); enumerator.MoveNext(); sortList2.Add(101, 101); Assert.NotNull(enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); // Current etc. throw if index < 0 enumerator = values.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Current etc. throw after resetting enumerator = values.GetEnumerator(); enumerator.MoveNext(); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Current etc. throw if the current index is >= count enumerator = values.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); }); } [Fact] public void GetValueList_TryingToModifyCollection_ThrowsNotSupportedException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList values = sortList2.GetValueList(); Assert.Throws<NotSupportedException>(() => values.Add(101)); Assert.Throws<NotSupportedException>(() => values.Clear()); Assert.Throws<NotSupportedException>(() => values.Insert(0, 101)); Assert.Throws<NotSupportedException>(() => values.Remove(1)); Assert.Throws<NotSupportedException>(() => values.RemoveAt(0)); Assert.Throws<NotSupportedException>(() => values[0] = 101); }); } [Fact] public void IndexOfKey() { SortedList sortList1 = Helpers.CreateStringSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < sortList2.Count; i++) { string key = "Key_" + i.ToString("D2"); string value = "Value_" + i; int index = sortList2.IndexOfKey(key); Assert.Equal(i, index); Assert.Equal(value, sortList2.GetByIndex(index)); } Assert.Equal(-1, sortList2.IndexOfKey("Non Existent Key")); string removedKey = "Key_01"; sortList2.Remove(removedKey); Assert.Equal(-1, sortList2.IndexOfKey(removedKey)); }); } [Fact] public void IndexOfKey_NullKey_ThrowsArgumentNullException() { SortedList sortList1 = Helpers.CreateStringSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.IndexOfKey(null)); // Key is null }); } [Fact] public void IndexOfValue() { SortedList sortList1 = Helpers.CreateStringSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < sortList2.Count; i++) { string value = "Value_" + i; int index = sortList2.IndexOfValue(value); Assert.Equal(i, index); Assert.Equal(value, sortList2.GetByIndex(index)); } Assert.Equal(-1, sortList2.IndexOfValue("Non Existent Value")); string removedKey = "Key_01"; string removedValue = "Value_1"; sortList2.Remove(removedKey); Assert.Equal(-1, sortList2.IndexOfValue(removedValue)); Assert.Equal(-1, sortList2.IndexOfValue(null)); sortList2.Add("Key_101", null); Assert.NotEqual(-1, sortList2.IndexOfValue(null)); }); } [Fact] public void IndexOfValue_SameValue() { var sortList1 = new SortedList(); sortList1.Add("Key_0", "Value_0"); sortList1.Add("Key_1", "Value_Same"); sortList1.Add("Key_2", "Value_Same"); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { Assert.Equal(1, sortList2.IndexOfValue("Value_Same")); }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(4)] [InlineData(5000)] public void Capacity_Get_Set(int capacity) { var sortList = new SortedList(); sortList.Capacity = capacity; Assert.Equal(capacity, sortList.Capacity); // Ensure nothing changes if we set capacity to the same value again sortList.Capacity = capacity; Assert.Equal(capacity, sortList.Capacity); } [Fact] public void Capacity_Set_ShrinkingCapacity_ThrowsArgumentOutOfRangeException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sortList2.Capacity = sortList2.Count - 1); // Capacity < count }); } [Fact] public void Capacity_Set_Invalid() { var sortList1 = new SortedList(); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sortList2.Capacity = -1); // Capacity < 0 }); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotIntMaxValueArrayIndexSupported))] public void Capacity_Excessive() { var sortList1 = new SortedList(); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { Assert.Throws<OutOfMemoryException>(() => sortList2.Capacity = int.MaxValue); // Capacity is too large }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] public void Item_Get(int count) { SortedList sortList1 = Helpers.CreateStringSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < count; i++) { string key = "Key_" + i.ToString("D2"); string value = "Value_" + i; Assert.Equal(value, sortList2[key]); } Assert.Null(sortList2["No Such Key"]); string removedKey = "Key_01"; sortList2.Remove(removedKey); Assert.Null(sortList2[removedKey]); }); } [Fact] public void Item_Get_DifferentCulture() { RemoteExecutor.Invoke(() => { var sortList = new SortedList(); try { var cultureNames = new string[] { "cs-CZ","da-DK","de-DE","el-GR","en-US", "es-ES","fi-FI","fr-FR","hu-HU","it-IT", "ja-JP","ko-KR","nb-NO","nl-NL","pl-PL", "pt-BR","pt-PT","ru-RU","sv-SE","tr-TR", "zh-CN","zh-HK","zh-TW" }; var installedCultures = new CultureInfo[cultureNames.Length]; var cultureDisplayNames = new string[installedCultures.Length]; int uniqueDisplayNameCount = 0; foreach (string cultureName in cultureNames) { var culture = new CultureInfo(cultureName); installedCultures[uniqueDisplayNameCount] = culture; cultureDisplayNames[uniqueDisplayNameCount] = culture.DisplayName; sortList.Add(cultureDisplayNames[uniqueDisplayNameCount], culture); uniqueDisplayNameCount++; } // In Czech ch comes after h if the comparer changes based on the current culture of the thread // we will not be able to find some items CultureInfo.CurrentCulture = new CultureInfo("cs-CZ"); for (int i = 0; i < uniqueDisplayNameCount; i++) { Assert.Equal(installedCultures[i], sortList[installedCultures[i].DisplayName]); } } catch (CultureNotFoundException) { } return RemoteExecutor.SuccessExitCode; }).Dispose(); } [Fact] public void Item_Set() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { // Change existing keys for (int i = 0; i < sortList2.Count; i++) { sortList2[i] = i + 1; Assert.Equal(i + 1, sortList2[i]); // Make sure nothing bad happens when we try to set the key to its current valeu sortList2[i] = i + 1; Assert.Equal(i + 1, sortList2[i]); } // Add new keys sortList2[101] = 2048; Assert.Equal(2048, sortList2[101]); sortList2[102] = null; Assert.Equal(null, sortList2[102]); }); } [Fact] public void Item_Set_NullKey_ThrowsArgumentNullException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2[null] = 101); // Key is null }); } [Fact] public void RemoveAt() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { // Remove from end for (int i = sortList2.Count - 1; i >= 0; i--) { sortList2.RemoveAt(i); Assert.False(sortList2.ContainsKey(i)); Assert.False(sortList2.ContainsValue(i)); Assert.Equal(i, sortList2.Count); } }); } [Fact] public void RemoveAt_InvalidIndex_ThrowsArgumentOutOfRangeException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.RemoveAt(-1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.RemoveAt(sortList2.Count)); // Index >= count }); } [Fact] public void Remove() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { // Remove from the end for (int i = sortList2.Count - 1; i >= 0; i--) { sortList2.Remove(i); Assert.False(sortList2.ContainsKey(i)); Assert.False(sortList2.ContainsValue(i)); Assert.Equal(i, sortList2.Count); } sortList2.Remove(101); // No such key }); } [Fact] public void Remove_NullKey_ThrowsArgumentNullException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.Remove(null)); // Key is null }); } [Fact] public void SetByIndex() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < sortList2.Count; i++) { sortList2.SetByIndex(i, i + 1); Assert.Equal(i + 1, sortList2.GetByIndex(i)); } }); } [Fact] public void SetByIndex_InvalidIndex_ThrowsArgumentOutOfRangeException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.SetByIndex(-1, 101)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.SetByIndex(sortList2.Count, 101)); // Index >= list.Count }); } [Fact] public void Synchronized_IsSynchronized() { SortedList sortList = SortedList.Synchronized(new SortedList()); Assert.True(sortList.IsSynchronized); } [Fact] public void Synchronized_NullList_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("list", () => SortedList.Synchronized(null)); // List is null } [Fact] public void TrimToSize() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < 10; i++) { sortList2.RemoveAt(0); } sortList2.TrimToSize(); Assert.Equal(sortList2.Count, sortList2.Capacity); sortList2.Clear(); sortList2.TrimToSize(); Assert.Equal(0, sortList2.Capacity); }); } private class Foo { public string StringValue { get; set; } = "Hello World"; } private class CustomComparer : IComparer { public int Compare(object obj1, object obj2) => -string.Compare(obj1.ToString(), obj2.ToString()); } } public class SortedList_SyncRootTests { private SortedList _sortListDaughter; private SortedList _sortListGrandDaughter; private const int NumberOfElements = 100; [Fact] [OuterLoop] public void GetSyncRootBasic() { // Testing SyncRoot is not as simple as its implementation looks like. This is the working // scenario we have in mind. // 1) Create your Down to earth mother SortedList // 2) Get a synchronized wrapper from it // 3) Get a Synchronized wrapper from 2) // 4) Get a synchronized wrapper of the mother from 1) // 5) all of these should SyncRoot to the mother earth var sortListMother = new SortedList(); for (int i = 0; i < NumberOfElements; i++) { sortListMother.Add("Key_" + i, "Value_" + i); } Assert.Equal(sortListMother.SyncRoot.GetType(), typeof(SortedList)); SortedList sortListSon = SortedList.Synchronized(sortListMother); _sortListGrandDaughter = SortedList.Synchronized(sortListSon); _sortListDaughter = SortedList.Synchronized(sortListMother); Assert.Equal(sortListSon.SyncRoot, sortListMother.SyncRoot); Assert.Equal(sortListMother.SyncRoot, sortListSon.SyncRoot); Assert.Equal(_sortListGrandDaughter.SyncRoot, sortListMother.SyncRoot); Assert.Equal(_sortListDaughter.SyncRoot, sortListMother.SyncRoot); Assert.Equal(sortListSon.SyncRoot, sortListMother.SyncRoot); //we are going to rumble with the SortedLists with some threads var workers = new Task[4]; for (int i = 0; i < workers.Length; i += 2) { var name = "Thread_worker_" + i; var action1 = new Action(() => AddMoreElements(name)); var action2 = new Action(RemoveElements); workers[i] = Task.Run(action1); workers[i + 1] = Task.Run(action2); } Task.WaitAll(workers); // Checking time // Now lets see how this is done. // Either there are some elements or none var sortListPossible = new SortedList(); for (int i = 0; i < NumberOfElements; i++) { sortListPossible.Add("Key_" + i, "Value_" + i); } for (int i = 0; i < workers.Length; i++) { sortListPossible.Add("Key_Thread_worker_" + i, "Thread_worker_" + i); } //lets check the values if IDictionaryEnumerator enumerator = sortListMother.GetEnumerator(); while (enumerator.MoveNext()) { Assert.True(sortListPossible.ContainsKey(enumerator.Key)); Assert.True(sortListPossible.ContainsValue(enumerator.Value)); } } private void AddMoreElements(string threadName) { _sortListGrandDaughter.Add("Key_" + threadName, threadName); } private void RemoveElements() { _sortListDaughter.Clear(); } } }
using System; using System.IO; using System.Collections; using System.Text; using System.Text.RegularExpressions; using System.Web; namespace HtmlHelp.ChmDecoding { /// <summary> /// The class <c>HHKParser</c> implements a parser for HHK contents files. /// </summary> internal sealed class HHKParser { /// <summary> /// regular expressions for replacing the sitemap boundary tags /// </summary> private static string RE_ULOpening = @"\<ul\>"; // will be replaced by a '(' for nested parsing private static string RE_ULClosing = @"\</ul\>"; // will be replaced by a ')' for nested parsing /// <summary> /// Matching ul-tags /// </summary> private static string RE_ULBoundaries = @"\<ul\>(?<innerText>.*)\</ul\>"; /// <summary> /// Matching the nested tree structure. /// </summary> private static string RE_NestedBoundaries = @"\( (?> [^()]+ | \( (?<DEPTH>) | \) (?<-DEPTH>) )* (?(DEPTH)(?!)) \)"; /// <summary> /// Matching object-tags /// </summary> private static string RE_ObjectBoundaries = @"\<object(?<innerText>.*?)\</object\>"; /// <summary> /// Matching param tags /// </summary> private static string RE_ParamBoundaries = @"\<param(?<innerText>.*?)\>"; /// <summary> /// Extracting tag attributes /// </summary> private const string RE_QuoteAttributes = @"( |\t)*(?<attributeName>[\-a-zA-Z0-9]*)( |\t)*=( |\t)*(?<attributeTD>[\""\'])?(?<attributeValue>.*?(?(attributeTD)\k<attributeTD>|([\s>]|.$)))"; /// <summary> /// private regular expressionobjects /// </summary> private static Regex ulRE; private static Regex NestedRE; private static Regex ObjectRE; private static Regex ParamRE; private static Regex AttributesRE; /// <summary> /// Parses a HHK file and returns an ArrayList with the index tree /// </summary> /// <param name="hhkFile">string content of the hhk file</param> /// <param name="chmFile">CHMFile instance</param> /// <returns>Returns an ArrayList with the index tree</returns> public static ArrayList ParseHHK(string hhkFile, CHMFile chmFile) { ArrayList indexList = new ArrayList(); ulRE = new Regex(RE_ULBoundaries, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline); NestedRE = new Regex(RE_NestedBoundaries, RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline); ObjectRE = new Regex(RE_ObjectBoundaries, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline); ParamRE = new Regex(RE_ParamBoundaries, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline); AttributesRE = new Regex(RE_QuoteAttributes, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline); int innerTextIdx = ulRE.GroupNumberFromName("innerText"); if( ulRE.IsMatch(hhkFile, 0) ) { Match m = ulRE.Match(hhkFile, 0); if( ObjectRE.IsMatch(hhkFile, 0) ) // first object block contains information types and categories { Match mO = ObjectRE.Match(hhkFile, 0); int iOTxt = ObjectRE.GroupNumberFromName("innerText"); string globalText = mO.Groups[iOTxt].Value; ParseGlobalSettings( globalText, chmFile ); } string innerText = m.Groups["innerText"].Value; innerText = innerText.Replace("(", "&#040;"); innerText = innerText.Replace(")", "&#041;"); innerText = Regex.Replace(innerText, RE_ULOpening, "(", RegexOptions.IgnoreCase); innerText = Regex.Replace(innerText, RE_ULClosing, ")", RegexOptions.IgnoreCase); ParseTree( innerText, null, indexList, chmFile ); } return indexList; } /// <summary> /// Recursively parses a sitemap tree /// </summary> /// <param name="text">content text</param> /// <param name="parent">Parent for all read items</param> /// <param name="arrNodes">arraylist which receives the extracted nodes</param> /// <param name="chmFile">CHMFile instance</param> private static void ParseTree( string text, IndexItem parent, ArrayList arrNodes, CHMFile chmFile ) { string strPreItems="", strPostItems=""; string innerText = ""; int nIndex = 0; while( NestedRE.IsMatch(text, nIndex) ) { Match m = NestedRE.Match(text, nIndex); innerText = m.Value.Substring( 1, m.Length-2); strPreItems = text.Substring(nIndex,m.Index-nIndex); ParseItems(strPreItems, parent, arrNodes, chmFile); if((arrNodes.Count>0) && (innerText.Length > 0) ) { IndexItem p = ((IndexItem)(arrNodes[arrNodes.Count-1])); ParseTree( innerText, p, arrNodes, chmFile ); } nIndex = m.Index+m.Length; } if( nIndex == 0) { strPostItems = text.Substring(nIndex, text.Length-nIndex); ParseItems(strPostItems, parent, arrNodes, chmFile); } else if( nIndex < text.Length-1) { strPostItems = text.Substring(nIndex, text.Length-nIndex); ParseTree(strPostItems, parent, arrNodes, chmFile); } } /// <summary> /// Parses nodes from the text /// </summary> /// <param name="itemstext">text containing the items</param> /// <param name="parentItem">parent index item</param> /// <param name="arrNodes">arraylist where the nodes should be added</param> /// <param name="chmFile">CHMFile instance</param> private static void ParseItems( string itemstext, IndexItem parentItem, ArrayList arrNodes, CHMFile chmFile) { int innerTextIdx = ObjectRE.GroupNumberFromName("innerText"); int innerPTextIdx = ParamRE.GroupNumberFromName("innerText"); // get group-name indexes int nameIndex = AttributesRE.GroupNumberFromName("attributeName"); int valueIndex = AttributesRE.GroupNumberFromName("attributeValue"); int tdIndex = AttributesRE.GroupNumberFromName("attributeTD"); int nObjStartIndex = 0; int nLastObjStartIndex = 0; string sKeyword = ""; while( ObjectRE.IsMatch(itemstext, nObjStartIndex) ) { Match m = ObjectRE.Match(itemstext, nObjStartIndex); string innerText = m.Groups[innerTextIdx].Value; IndexItem idxItem = new IndexItem(); // read parameters int nParamIndex = 0; int nNameCnt = 0; string paramTitle = ""; string paramLocal = ""; bool bAdded = false; while( ParamRE.IsMatch(innerText, nParamIndex) ) { Match mP = ParamRE.Match(innerText, nParamIndex); string innerP = mP.Groups[innerPTextIdx].Value; string paramName = ""; string paramValue = ""; int nAttrIdx = 0; //sKeyword = ""; while( AttributesRE.IsMatch( innerP, nAttrIdx ) ) { Match mA = AttributesRE.Match(innerP, nAttrIdx); string attributeName = mA.Groups[nameIndex].Value; string attributeValue = mA.Groups[valueIndex].Value; string attributeTD = mA.Groups[tdIndex].Value; if(attributeTD.Length > 0) { // delete the trailing textqualifier if( attributeValue.Length > 0) { int ltqi = attributeValue.LastIndexOf( attributeTD ); if(ltqi >= 0) { attributeValue = attributeValue.Substring(0,ltqi); } } } if( attributeName.ToLower() == "name") { paramName = HttpUtility.HtmlDecode(attributeValue); // for unicode encoded values nNameCnt++; } if( attributeName.ToLower() == "value") { paramValue = HttpUtility.HtmlDecode(attributeValue); // for unicode encoded values // delete trailing / while((paramValue.Length>0)&&(paramValue[paramValue.Length-1] == '/')) paramValue = paramValue.Substring(0,paramValue.Length-1); } nAttrIdx = mA.Index+mA.Length; } if( nNameCnt == 1) // first "Name" param = keyword { sKeyword = ""; if(parentItem != null) sKeyword = parentItem.KeyWordPath + ","; string sOldKW = sKeyword; sKeyword += paramValue; IndexItem idxFind = FindByKeyword(arrNodes, sKeyword); if(idxFind != null) { idxItem = idxFind; } else { if( sKeyword.Split(new char[] {','}).Length > 1 ) { idxItem.CharIndex = sKeyword.Length - paramValue.Length; } else { sKeyword = paramValue; sOldKW = sKeyword; idxItem.CharIndex = 0; } idxItem.KeyWordPath = sKeyword; idxItem.Indent = sKeyword.Split(new char[] {','}).Length - 1; idxItem.IsSeeAlso = false; sKeyword = sOldKW; } } else { if( (nNameCnt > 2) && (paramName.ToLower()=="name") ) { bAdded = true; IndexTopic idxTopic = new IndexTopic(paramTitle, paramLocal, chmFile.CompileFile, chmFile.ChmFilePath); idxItem.Topics.Add( idxTopic ); paramTitle = ""; paramLocal = ""; } switch(paramName.ToLower()) { case "name": //case "keyword": { paramTitle = paramValue; };break; case "local": { paramLocal = paramValue.Replace("../", "").Replace("./", ""); };break; case "type": // information type assignment for item { idxItem.InfoTypeStrings.Add( paramValue ); };break; case "see also": { idxItem.AddSeeAlso(paramValue); idxItem.IsSeeAlso = true; bAdded = true; };break; } } nParamIndex = mP.Index+mP.Length; } if(!bAdded) { bAdded=false; IndexTopic idxTopic = new IndexTopic(paramTitle, paramLocal, chmFile.CompileFile, chmFile.ChmFilePath); idxItem.Topics.Add( idxTopic ); paramTitle = ""; paramLocal = ""; } idxItem.ChmFile = chmFile; arrNodes.Add( idxItem ); nLastObjStartIndex = nObjStartIndex; nObjStartIndex = m.Index+m.Length; } } /// <summary> /// Searches an index-keyword in the index list /// </summary> /// <param name="indexList">index list to search</param> /// <param name="Keyword">keyword to find</param> /// <returns>Returns an <see cref="IndexItem">IndexItem</see> instance if found, otherwise null.</returns> private static IndexItem FindByKeyword(ArrayList indexList, string Keyword) { foreach(IndexItem curItem in indexList) { if( curItem.KeyWordPath == Keyword) return curItem; } return null; } /// <summary> /// Parses the very first &lt;OBJECT&gt; tag in the sitemap file and extracts /// information types and categories. /// </summary> /// <param name="sText">text of the object tag</param> /// <param name="chmFile">CHMFile instance</param> private static void ParseGlobalSettings(string sText, CHMFile chmFile) { int innerPTextIdx = ParamRE.GroupNumberFromName("innerText"); // get group-name indexes int nameIndex = AttributesRE.GroupNumberFromName("attributeName"); int valueIndex = AttributesRE.GroupNumberFromName("attributeValue"); int tdIndex = AttributesRE.GroupNumberFromName("attributeTD"); // read parameters int nParamIndex = 0; // 0... unknown // 1... inclusinve info type name // 2... exclusive info type name // 3... hidden info type name // 4... category name // 5... incl infotype name for category // 6... excl infotype name for category // 7... hidden infotype name for category int prevItem = 0; string sName = ""; string sDescription = ""; string curCategory = ""; while( ParamRE.IsMatch(sText, nParamIndex) ) { Match mP = ParamRE.Match(sText, nParamIndex); string innerP = mP.Groups[innerPTextIdx].Value; string paramName = ""; string paramValue = ""; int nAttrIdx = 0; while( AttributesRE.IsMatch( innerP, nAttrIdx ) ) { Match mA = AttributesRE.Match(innerP, nAttrIdx); string attributeName = mA.Groups[nameIndex].Value; string attributeValue = mA.Groups[valueIndex].Value; string attributeTD = mA.Groups[tdIndex].Value; if(attributeTD.Length > 0) { // delete the trailing textqualifier if( attributeValue.Length > 0) { int ltqi = attributeValue.LastIndexOf( attributeTD ); if(ltqi >= 0) { attributeValue = attributeValue.Substring(0,ltqi); } } } if( attributeName.ToLower() == "name") { paramName = HttpUtility.HtmlDecode(attributeValue); // for unicode encoded values } if( attributeName.ToLower() == "value") { paramValue = HttpUtility.HtmlDecode(attributeValue); // for unicode encoded values // delete trailing / while((paramValue.Length>0)&&(paramValue[paramValue.Length-1] == '/')) paramValue = paramValue.Substring(0,paramValue.Length-1); } nAttrIdx = mA.Index+mA.Length; } switch(paramName.ToLower()) { case "savetype": // inclusive information type name { prevItem = 1; sName = paramValue; };break; case "savetypedesc": // description of information type { InformationTypeMode mode = InformationTypeMode.Inclusive; sDescription = paramValue; if( prevItem == 1) mode = InformationTypeMode.Inclusive; if( prevItem == 2) mode = InformationTypeMode.Exclusive; if( prevItem == 3) mode = InformationTypeMode.Hidden; if( chmFile.GetInformationType( sName ) == null) { // check if the HtmlHelpSystem already holds such an information type if( chmFile.SystemInstance.GetInformationType( sName ) == null) { // info type not found yet InformationType newType = new InformationType(sName, sDescription, mode); chmFile.InformationTypes.Add(newType); } else { InformationType sysType = chmFile.SystemInstance.GetInformationType( sName ); chmFile.InformationTypes.Add( sysType ); } } prevItem = 0; };break; case "saveexclusive": // exclusive information type name { prevItem = 2; sName = paramValue; };break; case "savehidden": // hidden information type name { prevItem = 3; sName = paramValue; };break; case "category": // category name { prevItem = 4; sName = paramValue; curCategory = sName; };break; case "categorydesc": // category description { sDescription = paramValue; if( chmFile.GetCategory( sName ) == null) { // check if the HtmlHelpSystem already holds such a category if( chmFile.SystemInstance.GetCategory( sName ) == null) { // add category Category newCat = new Category(sName, sDescription); chmFile.Categories.Add(newCat); } else { Category sysCat = chmFile.SystemInstance.GetCategory( sName ); chmFile.Categories.Add( sysCat ); } } prevItem = 0; };break; case "type": // inclusive information type which is member of the previously read category { prevItem = 5; sName = paramValue; };break; case "typedesc": // description of type for category { sDescription = paramValue; Category cat = chmFile.GetCategory( curCategory ); if( cat != null) { // category found InformationType infoType = chmFile.GetInformationType( sName ); if( infoType != null) { if( !cat.ContainsInformationType(infoType)) { infoType.SetCategoryFlag(true); cat.AddInformationType(infoType); } } } prevItem = 0; };break; case "typeexclusive": // exclusive information type which is member of the previously read category { prevItem = 6; sName = paramValue; };break; case "typehidden": // hidden information type which is member of the previously read category { prevItem = 7; sName = paramValue; };break; default: { prevItem = 0; sName = ""; sDescription = ""; };break; } nParamIndex = mP.Index+mP.Length; } } } }
// 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.Configuration; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.Caching.Configuration; using System.Runtime.InteropServices; using System.Security; using System.Threading; namespace System.Runtime.Caching { internal sealed class MemoryCacheStatistics : IDisposable { private const int MEMORYSTATUS_INTERVAL_5_SECONDS = 5 * 1000; private const int MEMORYSTATUS_INTERVAL_30_SECONDS = 30 * 1000; private int _configCacheMemoryLimitMegabytes; private int _configPhysicalMemoryLimitPercentage; private int _configPollingInterval; private int _inCacheManagerThread; private int _disposed; private long _lastTrimCount; private long _lastTrimDurationTicks; // used only for debugging private int _lastTrimGen2Count; private int _lastTrimPercent; private DateTime _lastTrimTime; private int _pollingInterval; private GCHandleRef<Timer> _timerHandleRef; private object _timerLock; private long _totalCountBeforeTrim; private CacheMemoryMonitor _cacheMemoryMonitor; private MemoryCache _memoryCache; private PhysicalMemoryMonitor _physicalMemoryMonitor; // private private MemoryCacheStatistics() { //hide default ctor } private void AdjustTimer() { lock (_timerLock) { if (_timerHandleRef == null) return; Timer timer = _timerHandleRef.Target; // the order of these if statements is important // When above the high pressure mark, interval should be 5 seconds or less if (_physicalMemoryMonitor.IsAboveHighPressure() || _cacheMemoryMonitor.IsAboveHighPressure()) { if (_pollingInterval > MEMORYSTATUS_INTERVAL_5_SECONDS) { _pollingInterval = MEMORYSTATUS_INTERVAL_5_SECONDS; timer.Change(_pollingInterval, _pollingInterval); } return; } // When above half the low pressure mark, interval should be 30 seconds or less if ((_cacheMemoryMonitor.PressureLast > _cacheMemoryMonitor.PressureLow / 2) || (_physicalMemoryMonitor.PressureLast > _physicalMemoryMonitor.PressureLow / 2)) { // allow interval to fall back down when memory pressure goes away int newPollingInterval = Math.Min(_configPollingInterval, MEMORYSTATUS_INTERVAL_30_SECONDS); if (_pollingInterval != newPollingInterval) { _pollingInterval = newPollingInterval; timer.Change(_pollingInterval, _pollingInterval); } return; } // there is no pressure, interval should be the value from config if (_pollingInterval != _configPollingInterval) { _pollingInterval = _configPollingInterval; timer.Change(_pollingInterval, _pollingInterval); } } } // timer callback private void CacheManagerTimerCallback(object state) { CacheManagerThread(0); } internal long GetLastSize() { return _cacheMemoryMonitor.PressureLast; } private int GetPercentToTrim() { int gen2Count = GC.CollectionCount(2); // has there been a Gen 2 Collection since the last trim? if (gen2Count != _lastTrimGen2Count) { return Math.Max(_physicalMemoryMonitor.GetPercentToTrim(_lastTrimTime, _lastTrimPercent), _cacheMemoryMonitor.GetPercentToTrim(_lastTrimTime, _lastTrimPercent)); } else { return 0; } } private void InitializeConfiguration(NameValueCollection config) { MemoryCacheElement element = null; if (!_memoryCache.ConfigLess) { MemoryCacheSection section = ConfigurationManager.GetSection("system.runtime.caching/memoryCache") as MemoryCacheSection; if (section != null) { element = section.NamedCaches[_memoryCache.Name]; } } if (element != null) { _configCacheMemoryLimitMegabytes = element.CacheMemoryLimitMegabytes; _configPhysicalMemoryLimitPercentage = element.PhysicalMemoryLimitPercentage; double milliseconds = element.PollingInterval.TotalMilliseconds; _configPollingInterval = (milliseconds < (double)int.MaxValue) ? (int)milliseconds : int.MaxValue; } else { _configPollingInterval = ConfigUtil.DefaultPollingTimeMilliseconds; _configCacheMemoryLimitMegabytes = 0; _configPhysicalMemoryLimitPercentage = 0; } if (config != null) { _configPollingInterval = ConfigUtil.GetIntValueFromTimeSpan(config, ConfigUtil.PollingInterval, _configPollingInterval); _configCacheMemoryLimitMegabytes = ConfigUtil.GetIntValue(config, ConfigUtil.CacheMemoryLimitMegabytes, _configCacheMemoryLimitMegabytes, true, int.MaxValue); _configPhysicalMemoryLimitPercentage = ConfigUtil.GetIntValue(config, ConfigUtil.PhysicalMemoryLimitPercentage, _configPhysicalMemoryLimitPercentage, true, 100); } if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && _configPhysicalMemoryLimitPercentage > 0) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_PhysicalMemoryLimitPercentage); } } private void InitDisposableMembers() { bool dispose = true; try { _cacheMemoryMonitor = new CacheMemoryMonitor(_memoryCache, _configCacheMemoryLimitMegabytes); Timer timer; // Don't capture the current ExecutionContext and its AsyncLocals onto the timer causing them to live forever bool restoreFlow = false; try { if (!ExecutionContext.IsFlowSuppressed()) { ExecutionContext.SuppressFlow(); restoreFlow = true; } timer = new Timer(new TimerCallback(CacheManagerTimerCallback), null, _configPollingInterval, _configPollingInterval); } finally { // Restore the current ExecutionContext if (restoreFlow) ExecutionContext.RestoreFlow(); } _timerHandleRef = new GCHandleRef<Timer>(timer); dispose = false; } finally { if (dispose) { Dispose(); } } } private void SetTrimStats(long trimDurationTicks, long totalCountBeforeTrim, long trimCount) { _lastTrimDurationTicks = trimDurationTicks; int gen2Count = GC.CollectionCount(2); // has there been a Gen 2 Collection since the last trim? if (gen2Count != _lastTrimGen2Count) { _lastTrimTime = DateTime.UtcNow; _totalCountBeforeTrim = totalCountBeforeTrim; _lastTrimCount = trimCount; } else { // we've done multiple trims between Gen 2 collections, so only add to the trim count _lastTrimCount += trimCount; } _lastTrimGen2Count = gen2Count; _lastTrimPercent = (int)((_lastTrimCount * 100L) / _totalCountBeforeTrim); } private void Update() { _physicalMemoryMonitor.Update(); _cacheMemoryMonitor.Update(); } // public/internal internal long CacheMemoryLimit { get { return _cacheMemoryMonitor.MemoryLimit; } } internal long PhysicalMemoryLimit { get { return _physicalMemoryMonitor.MemoryLimit; } } internal TimeSpan PollingInterval { get { return TimeSpan.FromMilliseconds(_configPollingInterval); } } internal MemoryCacheStatistics(MemoryCache memoryCache, NameValueCollection config) { _memoryCache = memoryCache; _lastTrimGen2Count = -1; _lastTrimTime = DateTime.MinValue; _timerLock = new object(); InitializeConfiguration(config); _pollingInterval = _configPollingInterval; _physicalMemoryMonitor = new PhysicalMemoryMonitor(_configPhysicalMemoryLimitPercentage); InitDisposableMembers(); } internal long CacheManagerThread(int minPercent) { if (Interlocked.Exchange(ref _inCacheManagerThread, 1) != 0) return 0; try { if (_disposed == 1) { return 0; } Dbg.Trace("MemoryCacheStats", "**BEG** CacheManagerThread " + DateTime.Now.ToString("T", CultureInfo.InvariantCulture)); // The timer thread must always call Update so that the CacheManager // knows the size of the cache. Update(); AdjustTimer(); int percent = Math.Max(minPercent, GetPercentToTrim()); long beginTotalCount = _memoryCache.GetCount(); Stopwatch sw = Stopwatch.StartNew(); long trimmedOrExpired = _memoryCache.Trim(percent); sw.Stop(); // 1) don't update stats if the trim happend because MAX_COUNT was exceeded // 2) don't update stats unless we removed at least one entry if (percent > 0 && trimmedOrExpired > 0) { SetTrimStats(sw.Elapsed.Ticks, beginTotalCount, trimmedOrExpired); } Dbg.Trace("MemoryCacheStats", "**END** CacheManagerThread: " + ", percent=" + percent + ", beginTotalCount=" + beginTotalCount + ", trimmed=" + trimmedOrExpired + ", Milliseconds=" + sw.ElapsedMilliseconds); #if PERF Debug.WriteLine("CacheCommon.CacheManagerThread:" + " minPercent= " + minPercent + ", percent= " + percent + ", beginTotalCount=" + beginTotalCount + ", trimmed=" + trimmedOrExpired + ", Milliseconds=" + sw.ElapsedMilliseconds + Environment.NewLine); #endif return trimmedOrExpired; } finally { Interlocked.Exchange(ref _inCacheManagerThread, 0); } } public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) { lock (_timerLock) { GCHandleRef<Timer> timerHandleRef = _timerHandleRef; if (timerHandleRef != null && Interlocked.CompareExchange(ref _timerHandleRef, null, timerHandleRef) == timerHandleRef) { timerHandleRef.Dispose(); Dbg.Trace("MemoryCacheStats", "Stopped CacheMemoryTimers"); } } while (_inCacheManagerThread != 0) { Thread.Sleep(100); } if (_cacheMemoryMonitor != null) { _cacheMemoryMonitor.Dispose(); } // Don't need to call GC.SuppressFinalize(this) for sealed types without finalizers. } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Grandfathered suppression from original caching code checkin")] internal void UpdateConfig(NameValueCollection config) { int pollingInterval = ConfigUtil.GetIntValueFromTimeSpan(config, ConfigUtil.PollingInterval, _configPollingInterval); int cacheMemoryLimitMegabytes = ConfigUtil.GetIntValue(config, ConfigUtil.CacheMemoryLimitMegabytes, _configCacheMemoryLimitMegabytes, true, int.MaxValue); int physicalMemoryLimitPercentage = ConfigUtil.GetIntValue(config, ConfigUtil.PhysicalMemoryLimitPercentage, _configPhysicalMemoryLimitPercentage, true, 100); if (pollingInterval != _configPollingInterval) { lock (_timerLock) { _configPollingInterval = pollingInterval; } } if (cacheMemoryLimitMegabytes == _configCacheMemoryLimitMegabytes && physicalMemoryLimitPercentage == _configPhysicalMemoryLimitPercentage) { return; } try { try { } finally { // prevent ThreadAbortEx from interrupting while (Interlocked.Exchange(ref _inCacheManagerThread, 1) != 0) { Thread.Sleep(100); } } if (_disposed == 0) { if (cacheMemoryLimitMegabytes != _configCacheMemoryLimitMegabytes) { _cacheMemoryMonitor.SetLimit(cacheMemoryLimitMegabytes); _configCacheMemoryLimitMegabytes = cacheMemoryLimitMegabytes; } if (physicalMemoryLimitPercentage != _configPhysicalMemoryLimitPercentage) { _physicalMemoryMonitor.SetLimit(physicalMemoryLimitPercentage); _configPhysicalMemoryLimitPercentage = physicalMemoryLimitPercentage; } } } finally { Interlocked.Exchange(ref _inCacheManagerThread, 0); } } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using MvvmCross.Binding.Attributes; using MvvmCross.Platforms.Ios.Views; using MvvmCross.ViewModels; using MvvmCross.WeakSubscription; using UIKit; namespace MvvmCross.StackView { public class MvxStackView : UIStackView { private IEnumerable<MvxViewModel> _itemsSource; private MvxNotifyCollectionChangedEventSubscription _subscription; private IDictionary<MvxViewModel, UIView> _viewModelViewLinks; public MvxStackView() { Initialise(); } public MvxStackView(IntPtr handler) : base(handler) { Initialise(); } [MvxSetToNullAfterBinding] public virtual IEnumerable<MvxViewModel> ItemsSource { get => _itemsSource; set { if (ReferenceEquals(_itemsSource, value)) { return; } _itemsSource = value; if (_itemsSource is INotifyCollectionChanged collectionChanged) { _subscription = collectionChanged.WeakSubscribe(OnCollectionChanged); } InitialiseContainer(); } } protected override void Dispose(bool disposing) { if (disposing) { if (_subscription != null) { _subscription.Dispose(); _subscription = null; } } base.Dispose(disposing); } protected virtual UIView GetView(MvxViewModel viewModel, int index) { if (!(Mvx.Resolve<IMvxIosViewCreator>().CreateView(viewModel) is UIViewController viewController)) { return null; } return GetView(viewController, index); } protected virtual UIView GetView(UIViewController controller, int index) { return controller.View; } protected virtual void OnBeforeAdd(UIView view) { } protected virtual void OnAfterAdd(UIView view) { } protected virtual void OnBeforeRemove(UIView view) { } protected virtual void OnAfterRemove(UIView view) { } private void Initialise() { _viewModelViewLinks = new Dictionary<MvxViewModel, UIView>(); } private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs) { if (notifyCollectionChangedEventArgs.Action == NotifyCollectionChangedAction.Reset) { var viewModels = _viewModelViewLinks.Select(viewModelLink => viewModelLink.Key).ToList(); foreach (var viewModel in viewModels) { RemoveViewModel(viewModel); } return; } if (notifyCollectionChangedEventArgs.NewItems != null) { int newStartingIndex = notifyCollectionChangedEventArgs.NewStartingIndex; foreach (var newItem in notifyCollectionChangedEventArgs.NewItems) { AddViewModel(newItem as MvxViewModel, newStartingIndex); newStartingIndex++; } } if (notifyCollectionChangedEventArgs.OldItems != null) { foreach (var oldItem in notifyCollectionChangedEventArgs.OldItems) { RemoveViewModel(oldItem as MvxViewModel); } } } private void InitialiseContainer() { var index = 0; ClearSubviews(); foreach (var viewModel in ItemsSource) { AddViewModel(viewModel, index); index++; } } private void AddViewModel(MvxViewModel viewModel, int index) { InvokeOnMainThread(() => { if (index == -1) { index = 0; } var view = GetView(viewModel, index); if (view == null) { return; } _viewModelViewLinks.Add(viewModel, view); OnBeforeAdd(view); InsertArrangedSubview(view, (nuint)index); OnAfterAdd(view); }); } private void RemoveViewModel(MvxViewModel viewModel) { InvokeOnMainThread(() => { if (!_viewModelViewLinks.ContainsKey(viewModel)) { return; } var view = _viewModelViewLinks[viewModel]; OnBeforeRemove(view); RemoveArrangedSubview(view); view.RemoveFromSuperview(); _viewModelViewLinks.Remove(viewModel); OnAfterRemove(view); }); } private void ClearSubviews() { foreach (var subview in ArrangedSubviews) { RemoveArrangedSubview(subview); subview.RemoveFromSuperview(); } _viewModelViewLinks.Clear(); } } }
/* Copyright 2012 Michael Edwards Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //-CRE- using System.Collections.Specialized; using System.Reflection; using Glass.Mapper.Sc.Configuration; using NUnit.Framework; using Sitecore.Links; using Sitecore.Resources.Media; namespace Glass.Mapper.Sc.FakeDb { [TestFixture] public class UtilitiesFixture { [Test] public void GetPropertyFunc_UsingPropertyInfo_ReturnsFuction( [Values( "GetPublicSetPublic", "GetProtectedSetProtected", "GetPrivateSetPrivate", "GetPublicSetProtected", "GetPublicSetPrivate", "GetPublicNoSet" )] string propertyName ) { //Assign PropertyInfo info = typeof(StubClass).GetProperty(propertyName, Sc.Utilities.Flags); Assert.IsNotNull(info); //Act var result = Sc.Utilities.GetPropertyFunc(info); //Assert Assert.IsNotNull(result); } [Test] public void SetPropertyAction_UsingPropertyInfo_ReturnsFuction( [Values( "GetPublicSetPublic", "GetProtectedSetProtected", "GetPrivateSetPrivate", "GetPublicSetProtected", "GetPublicSetPrivate", "GetPublicNoSet" )] string propertyName ) { //Assign PropertyInfo info = typeof(StubClass).GetProperty(propertyName, Sc.Utilities.Flags); Assert.IsNotNull(info); //Act var result = Sc.Utilities.SetPropertyAction(info); //Assert Assert.IsNotNull(result); } [Test] [Sequential] public void GetPropertyFuncAndSetPropertyAction_ReadWriteUsingActionAndFunction_ReturnsString( [Values( "GetPublicSetPublic", "GetProtectedSetProtected", "GetPrivateSetPrivate", "GetPublicSetProtected", "GetPublicSetPrivate", "GetPublicNoSet" )] string propertyName, [Values( "some value", "some value", "some value", "some value", "some value", null )] string expected ) { //Assign PropertyInfo info = typeof(StubClass).GetProperty(propertyName, Sc.Utilities.Flags); var getFunc = Sc.Utilities.GetPropertyFunc(info); var setActi = Sc.Utilities.SetPropertyAction(info); var stub = new StubClass(); //Act setActi(stub, expected); var result = getFunc(stub) as string; //Assert Assert.AreEqual(expected, result); } #region CreateUrlOptions /// <summary> /// This test relates to https://github.com/mikeedwards83/Glass.Mapper/issues/97 /// </summary> [Test] [TestCase(SitecoreInfoUrlOptions.AddAspxExtension, true, false, false, false, false, false)] [TestCase(SitecoreInfoUrlOptions.AlwaysIncludeServerUrl, false, true, false, false, false, false)] [TestCase(SitecoreInfoUrlOptions.EncodeNames, false, false, true, false, false, false)] [TestCase(SitecoreInfoUrlOptions.ShortenUrls, false, false, false, true, false, false)] [TestCase(SitecoreInfoUrlOptions.SiteResolving, false, false, false, false, true, false)] [TestCase(SitecoreInfoUrlOptions.UseUseDisplayName, false, false, false, false, false, true)] public void CreateUrlOptions_SetsOptionsOnDefaultOptions( SitecoreInfoUrlOptions options, bool addAspx, bool includeServer, bool encodeNames, bool shorten, bool siteResolving, bool displayName ) { //Arrange var defaultOptions = new UrlOptions(); defaultOptions.AddAspxExtension = false; defaultOptions.AlwaysIncludeServerUrl = false; defaultOptions.EncodeNames = false; defaultOptions.ShortenUrls = false; defaultOptions.SiteResolving = false; defaultOptions.UseDisplayName = false; var urlOptionsResolver = new UrlOptionsResolver(); //Act urlOptionsResolver.CreateUrlOptions(options, defaultOptions); //Assert Assert.AreEqual(addAspx, defaultOptions.AddAspxExtension); Assert.AreEqual(includeServer, defaultOptions.AlwaysIncludeServerUrl); Assert.AreEqual(encodeNames, defaultOptions.EncodeNames); Assert.AreEqual(shorten, defaultOptions.ShortenUrls); Assert.AreEqual(siteResolving, defaultOptions.SiteResolving); Assert.AreEqual(displayName, defaultOptions.UseDisplayName); } #endregion #region GetMediaUrlOptions [Test] public void GetMediaUrlOptions_AbsolutePath() { //Arrange var option = SitecoreInfoMediaUrlOptions.AlwaysIncludeServerUrl; var urlOptionsResolver = new MediaUrlOptionsResolver(); //Act var result = urlOptionsResolver.GetMediaUrlOptions(option); //Assert Assert.AreEqual(result.AbsolutePath, MediaUrlOptions.Empty.AbsolutePath, "AlwaysIncludeServerUrl"); Assert.AreEqual(result.AllowStretch, MediaUrlOptions.Empty.AllowStretch, "AllowStretch"); Assert.IsTrue(result.AlwaysIncludeServerUrl,"AlwaysIncludeServerUrl"); Assert.AreEqual(result.DisableBrowserCache, MediaUrlOptions.Empty.DisableBrowserCache, "DisableBrowserCache"); Assert.AreEqual(result.DisableMediaCache, MediaUrlOptions.Empty.DisableMediaCache, "DisableMediaCache"); Assert.AreEqual(result.IgnoreAspectRatio, MediaUrlOptions.Empty.IgnoreAspectRatio, "IgnoreAspectRatio"); Assert.AreEqual(result.IncludeExtension, MediaUrlOptions.Empty.IncludeExtension, "IncludeExtension"); Assert.AreEqual(result.LowercaseUrls, MediaUrlOptions.Empty.LowercaseUrls, "LowercaseUrls"); Assert.AreEqual(result.Thumbnail, MediaUrlOptions.Empty.Thumbnail, "Thumbnail"); Assert.AreEqual(result.UseDefaultIcon, MediaUrlOptions.Empty.UseDefaultIcon, "UseDefaultIcon"); Assert.AreEqual(result.UseItemPath, MediaUrlOptions.Empty.UseItemPath, "UseItemPath"); } [Test] public void GetMediaUrlOptions_AllowStretch() { //Arrange var option = SitecoreInfoMediaUrlOptions.AllowStretch; var urlOptionsResolver = new MediaUrlOptionsResolver(); //Act var result = urlOptionsResolver.GetMediaUrlOptions(option); //Assert Assert.AreEqual(result.AbsolutePath, MediaUrlOptions.Empty.AbsolutePath, "AbsolutePath"); Assert.IsTrue(result.AllowStretch,"AllowStretch"); Assert.AreEqual(result.AlwaysIncludeServerUrl, MediaUrlOptions.Empty.AlwaysIncludeServerUrl, "AlwaysIncludeServerUrl"); Assert.AreEqual(result.DisableBrowserCache, MediaUrlOptions.Empty.DisableBrowserCache, "DisableBrowserCache"); Assert.AreEqual(result.DisableMediaCache, MediaUrlOptions.Empty.DisableMediaCache, "DisableMediaCache"); Assert.AreEqual(result.IgnoreAspectRatio, MediaUrlOptions.Empty.IgnoreAspectRatio, "IgnoreAspectRatio"); Assert.AreEqual(result.IncludeExtension, MediaUrlOptions.Empty.IncludeExtension, "IncludeExtension"); Assert.AreEqual(result.LowercaseUrls, MediaUrlOptions.Empty.LowercaseUrls, "LowercaseUrls"); Assert.AreEqual(result.Thumbnail, MediaUrlOptions.Empty.Thumbnail, "Thumbnail"); Assert.AreEqual(result.UseDefaultIcon, MediaUrlOptions.Empty.UseDefaultIcon, "UseDefaultIcon"); Assert.AreEqual(result.UseItemPath, MediaUrlOptions.Empty.UseItemPath, "UseItemPath"); } [Test] public void GetMediaUrlOptions_AlwaysIncludeServerUrl() { //Arrange var option = SitecoreInfoMediaUrlOptions.AlwaysIncludeServerUrl; var urlOptionsResolver = new MediaUrlOptionsResolver(); //Act var result = urlOptionsResolver.GetMediaUrlOptions(option); //Assert Assert.AreEqual(result.AbsolutePath, MediaUrlOptions.Empty.AbsolutePath, "AbsolutePath"); Assert.AreEqual(result.AllowStretch, MediaUrlOptions.Empty.AllowStretch, "AllowStretch"); Assert.IsTrue(result.AlwaysIncludeServerUrl,"AlwaysIncludeServerUrl"); Assert.AreEqual(result.DisableBrowserCache, MediaUrlOptions.Empty.DisableBrowserCache, "DisableBrowserCache"); Assert.AreEqual(result.DisableMediaCache, MediaUrlOptions.Empty.DisableMediaCache, "DisableMediaCache"); Assert.AreEqual(result.IgnoreAspectRatio, MediaUrlOptions.Empty.IgnoreAspectRatio, "IgnoreAspectRatio"); Assert.AreEqual(result.IncludeExtension, MediaUrlOptions.Empty.IncludeExtension, "IncludeExtension"); Assert.AreEqual(result.LowercaseUrls, MediaUrlOptions.Empty.LowercaseUrls, "LowercaseUrls"); Assert.AreEqual(result.Thumbnail, MediaUrlOptions.Empty.Thumbnail, "Thumbnail"); Assert.AreEqual(result.UseDefaultIcon, MediaUrlOptions.Empty.UseDefaultIcon, "UseDefaultIcon"); Assert.AreEqual(result.UseItemPath, MediaUrlOptions.Empty.UseItemPath, "UseItemPath"); } [Test] public void GetMediaUrlOptions_DisableBrowserCache() { //Arrange var option = SitecoreInfoMediaUrlOptions.DisableBrowserCache; var urlOptionsResolver = new MediaUrlOptionsResolver(); //Act var result = urlOptionsResolver.GetMediaUrlOptions(option); //Assert Assert.AreEqual(result.AbsolutePath, MediaUrlOptions.Empty.AbsolutePath, "AbsolutePath"); Assert.AreEqual(result.AllowStretch, MediaUrlOptions.Empty.AllowStretch, "AllowStretch"); Assert.AreEqual(result.AlwaysIncludeServerUrl, MediaUrlOptions.Empty.AlwaysIncludeServerUrl, "AlwaysIncludeServerUrl"); Assert.IsTrue(result.DisableBrowserCache, "DisableBrowserCache"); Assert.AreEqual(result.DisableMediaCache, MediaUrlOptions.Empty.DisableMediaCache, "DisableMediaCache"); Assert.AreEqual(result.IgnoreAspectRatio, MediaUrlOptions.Empty.IgnoreAspectRatio, "IgnoreAspectRatio"); Assert.AreEqual(result.IncludeExtension, MediaUrlOptions.Empty.IncludeExtension, "IncludeExtension"); Assert.AreEqual(result.LowercaseUrls, MediaUrlOptions.Empty.LowercaseUrls, "LowercaseUrls"); Assert.AreEqual(result.Thumbnail, MediaUrlOptions.Empty.Thumbnail, "Thumbnail"); Assert.AreEqual(result.UseDefaultIcon, MediaUrlOptions.Empty.UseDefaultIcon, "UseDefaultIcon"); Assert.AreEqual(result.UseItemPath, MediaUrlOptions.Empty.UseItemPath, "UseItemPath"); } [Test] public void GetMediaUrlOptions_DisableMediaCache() { //Arrange var option = SitecoreInfoMediaUrlOptions.DisableMediaCache; var urlOptionsResolver = new MediaUrlOptionsResolver(); //Act var result = urlOptionsResolver.GetMediaUrlOptions(option); //Assert Assert.AreEqual(result.AbsolutePath, MediaUrlOptions.Empty.AbsolutePath, "AbsolutePath"); Assert.AreEqual(result.AllowStretch, MediaUrlOptions.Empty.AllowStretch, "AllowStretch"); Assert.AreEqual(result.AlwaysIncludeServerUrl, MediaUrlOptions.Empty.AlwaysIncludeServerUrl, "AlwaysIncludeServerUrl"); Assert.AreEqual(result.DisableBrowserCache, MediaUrlOptions.Empty.DisableBrowserCache, "DisableBrowserCache"); Assert.IsTrue(result.DisableMediaCache, "DisableMediaCache"); Assert.AreEqual(result.IgnoreAspectRatio, MediaUrlOptions.Empty.IgnoreAspectRatio, "IgnoreAspectRatio"); Assert.AreEqual(result.IncludeExtension, MediaUrlOptions.Empty.IncludeExtension, "IncludeExtension"); Assert.AreEqual(result.LowercaseUrls, MediaUrlOptions.Empty.LowercaseUrls, "LowercaseUrls"); Assert.AreEqual(result.Thumbnail, MediaUrlOptions.Empty.Thumbnail, "Thumbnail"); Assert.AreEqual(result.UseDefaultIcon, MediaUrlOptions.Empty.UseDefaultIcon, "UseDefaultIcon"); Assert.AreEqual(result.UseItemPath, MediaUrlOptions.Empty.UseItemPath, "UseItemPath"); } [Test] public void GetMediaUrlOptions_IgnoreAspectRatio() { //Arrange var option = SitecoreInfoMediaUrlOptions.IgnoreAspectRatio; var urlOptionsResolver = new MediaUrlOptionsResolver(); //Act var result = urlOptionsResolver.GetMediaUrlOptions(option); //Assert Assert.AreEqual(result.AbsolutePath, MediaUrlOptions.Empty.AbsolutePath, "AbsolutePath"); Assert.AreEqual(result.AllowStretch, MediaUrlOptions.Empty.AllowStretch, "AllowStretch"); Assert.AreEqual(result.AlwaysIncludeServerUrl, MediaUrlOptions.Empty.AlwaysIncludeServerUrl, "AlwaysIncludeServerUrl"); Assert.AreEqual(result.DisableBrowserCache, MediaUrlOptions.Empty.DisableBrowserCache, "DisableBrowserCache"); Assert.AreEqual(result.DisableMediaCache, MediaUrlOptions.Empty.DisableMediaCache, "DisableMediaCache"); Assert.IsTrue(result.IgnoreAspectRatio, "IgnoreAspectRatio"); Assert.AreEqual(result.IncludeExtension, MediaUrlOptions.Empty.IncludeExtension, "IncludeExtension"); Assert.AreEqual(result.LowercaseUrls, MediaUrlOptions.Empty.LowercaseUrls, "LowercaseUrls"); Assert.AreEqual(result.Thumbnail, MediaUrlOptions.Empty.Thumbnail, "Thumbnail"); Assert.AreEqual(result.UseDefaultIcon, MediaUrlOptions.Empty.UseDefaultIcon, "UseDefaultIcon"); Assert.AreEqual(result.UseItemPath, MediaUrlOptions.Empty.UseItemPath, "UseItemPath"); } [Test] public void GetMediaUrlOptions_IncludeExtension() { //Arrange var option = SitecoreInfoMediaUrlOptions.RemoveExtension; var urlOptionsResolver = new MediaUrlOptionsResolver(); //Act var result = urlOptionsResolver.GetMediaUrlOptions(option); //Assert Assert.AreEqual(result.AbsolutePath, MediaUrlOptions.Empty.AbsolutePath, "AbsolutePath"); Assert.AreEqual(result.AllowStretch, MediaUrlOptions.Empty.AllowStretch, "AllowStretch"); Assert.AreEqual(result.AlwaysIncludeServerUrl, MediaUrlOptions.Empty.AlwaysIncludeServerUrl, "AlwaysIncludeServerUrl"); Assert.AreEqual(result.DisableBrowserCache, MediaUrlOptions.Empty.DisableBrowserCache, "DisableBrowserCache"); Assert.AreEqual(result.DisableMediaCache, MediaUrlOptions.Empty.DisableMediaCache, "DisableMediaCache"); Assert.AreEqual(result.IgnoreAspectRatio, MediaUrlOptions.Empty.IgnoreAspectRatio, "IgnoreAspectRatio"); Assert.IsFalse(result.IncludeExtension, "IncludeExtension"); Assert.AreEqual(result.LowercaseUrls, MediaUrlOptions.Empty.LowercaseUrls, "LowercaseUrls"); Assert.AreEqual(result.Thumbnail, MediaUrlOptions.Empty.Thumbnail, "Thumbnail"); Assert.AreEqual(result.UseDefaultIcon, MediaUrlOptions.Empty.UseDefaultIcon, "UseDefaultIcon"); Assert.AreEqual(result.UseItemPath, MediaUrlOptions.Empty.UseItemPath, "UseItemPath"); } [Test] public void GetMediaUrlOptions_LowercaseUrls() { //Arrange var option = SitecoreInfoMediaUrlOptions.LowercaseUrls; var urlOptionsResolver = new MediaUrlOptionsResolver(); //Act var result = urlOptionsResolver.GetMediaUrlOptions(option); //Assert Assert.AreEqual(result.AbsolutePath, MediaUrlOptions.Empty.AbsolutePath, "AbsolutePath"); Assert.AreEqual(result.AllowStretch, MediaUrlOptions.Empty.AllowStretch, "AllowStretch"); Assert.AreEqual(result.AlwaysIncludeServerUrl, MediaUrlOptions.Empty.AlwaysIncludeServerUrl, "AlwaysIncludeServerUrl"); Assert.AreEqual(result.DisableBrowserCache, MediaUrlOptions.Empty.DisableBrowserCache, "DisableBrowserCache"); Assert.AreEqual(result.DisableMediaCache, MediaUrlOptions.Empty.DisableMediaCache, "DisableMediaCache"); Assert.AreEqual(result.IgnoreAspectRatio, MediaUrlOptions.Empty.IgnoreAspectRatio, "IgnoreAspectRatio"); Assert.AreEqual(result.IncludeExtension, MediaUrlOptions.Empty.IncludeExtension, "IncludeExtension"); Assert.IsTrue(result.LowercaseUrls, "LowercaseUrls"); Assert.AreEqual(result.Thumbnail, MediaUrlOptions.Empty.Thumbnail, "Thumbnail"); Assert.AreEqual(result.UseDefaultIcon, MediaUrlOptions.Empty.UseDefaultIcon, "UseDefaultIcon"); Assert.AreEqual(result.UseItemPath, MediaUrlOptions.Empty.UseItemPath, "UseItemPath"); } [Test] public void GetMediaUrlOptions_Thumbnail() { //Arrange var option = SitecoreInfoMediaUrlOptions.Thumbnail; var urlOptionsResolver = new MediaUrlOptionsResolver(); //Act var result = urlOptionsResolver.GetMediaUrlOptions(option); //Assert Assert.AreEqual(result.AbsolutePath, MediaUrlOptions.Empty.AbsolutePath, "AbsolutePath"); Assert.AreEqual(result.AllowStretch, MediaUrlOptions.Empty.AllowStretch, "AllowStretch"); Assert.AreEqual(result.AlwaysIncludeServerUrl, MediaUrlOptions.Empty.AlwaysIncludeServerUrl, "AlwaysIncludeServerUrl"); Assert.AreEqual(result.DisableBrowserCache, MediaUrlOptions.Empty.DisableBrowserCache, "DisableBrowserCache"); Assert.AreEqual(result.DisableMediaCache, MediaUrlOptions.Empty.DisableMediaCache, "DisableMediaCache"); Assert.AreEqual(result.IgnoreAspectRatio, MediaUrlOptions.Empty.IgnoreAspectRatio, "IgnoreAspectRatio"); Assert.AreEqual(result.IncludeExtension, MediaUrlOptions.Empty.IncludeExtension, "IncludeExtension"); Assert.AreEqual(result.LowercaseUrls, MediaUrlOptions.Empty.LowercaseUrls, "LowercaseUrls"); Assert.IsTrue(result.Thumbnail, "Thumbnail"); Assert.AreEqual(result.UseDefaultIcon, MediaUrlOptions.Empty.UseDefaultIcon, "UseDefaultIcon"); Assert.AreEqual(result.UseItemPath, MediaUrlOptions.Empty.UseItemPath, "UseItemPath"); } [Test] public void GetMediaUrlOptions_UseDefaultIcon() { //Arrange var option = SitecoreInfoMediaUrlOptions.UseDefaultIcon; var urlOptionsResolver = new MediaUrlOptionsResolver(); //Act var result = urlOptionsResolver.GetMediaUrlOptions(option); //Assert Assert.AreEqual(result.AbsolutePath, MediaUrlOptions.Empty.AbsolutePath, "AbsolutePath"); Assert.AreEqual(result.AllowStretch, MediaUrlOptions.Empty.AllowStretch, "AllowStretch"); Assert.AreEqual(result.AlwaysIncludeServerUrl, MediaUrlOptions.Empty.AlwaysIncludeServerUrl, "AlwaysIncludeServerUrl"); Assert.AreEqual(result.DisableBrowserCache, MediaUrlOptions.Empty.DisableBrowserCache, "DisableBrowserCache"); Assert.AreEqual(result.DisableMediaCache, MediaUrlOptions.Empty.DisableMediaCache, "DisableMediaCache"); Assert.AreEqual(result.IgnoreAspectRatio, MediaUrlOptions.Empty.IgnoreAspectRatio, "IgnoreAspectRatio"); Assert.AreEqual(result.IncludeExtension, MediaUrlOptions.Empty.IncludeExtension, "IncludeExtension"); Assert.AreEqual(result.LowercaseUrls, MediaUrlOptions.Empty.LowercaseUrls, "LowercaseUrls"); Assert.AreEqual(result.Thumbnail, MediaUrlOptions.Empty.Thumbnail, "Thumbnail"); Assert.IsTrue(result.UseDefaultIcon, "UseDefaultIcon"); Assert.AreEqual(result.UseItemPath, MediaUrlOptions.Empty.UseItemPath, "UseItemPath"); } [Test] public void GetMediaUrlOptions_UseItemPath() { //Arrange var option = SitecoreInfoMediaUrlOptions.UseItemPath; var urlOptionsResolver = new MediaUrlOptionsResolver(); //Act var result = urlOptionsResolver.GetMediaUrlOptions(option); //Assert Assert.AreEqual(result.AbsolutePath, MediaUrlOptions.Empty.AbsolutePath, "AbsolutePath"); Assert.AreEqual(result.AllowStretch, MediaUrlOptions.Empty.AllowStretch, "AllowStretch"); Assert.AreEqual(result.AlwaysIncludeServerUrl, MediaUrlOptions.Empty.AlwaysIncludeServerUrl, "AlwaysIncludeServerUrl"); Assert.AreEqual(result.DisableBrowserCache, MediaUrlOptions.Empty.DisableBrowserCache, "DisableBrowserCache"); Assert.AreEqual(result.DisableMediaCache, MediaUrlOptions.Empty.DisableMediaCache, "DisableMediaCache"); Assert.AreEqual(result.IgnoreAspectRatio, MediaUrlOptions.Empty.IgnoreAspectRatio, "IgnoreAspectRatio"); Assert.AreEqual(result.IncludeExtension, MediaUrlOptions.Empty.IncludeExtension, "IncludeExtension"); Assert.AreEqual(result.LowercaseUrls, MediaUrlOptions.Empty.LowercaseUrls, "LowercaseUrls"); Assert.AreEqual(result.Thumbnail, MediaUrlOptions.Empty.Thumbnail, "Thumbnail"); Assert.AreEqual(result.UseDefaultIcon, MediaUrlOptions.Empty.UseDefaultIcon, "UseDefaultIcon"); Assert.IsTrue(result.UseItemPath, "UseItemPath"); } #endregion #region DoVersionCheck [Test] public void DoVersionCheck_DefaultValues_ReturnTrue() { //Arrange var config = new Config(); IItemVersionHandler versionHandler = new ItemVersionHandler(config); //Act var result = versionHandler.VersionCountEnabled(); //Assert Assert.IsTrue(result); } [Test] public void DoVersionCheck_DisableVersionCount_ReturnFalse() { //Arrange var config = new Config(); config.DisableVersionCount = true; IItemVersionHandler versionHandler = new ItemVersionHandler(config); //Act var result = versionHandler.VersionCountEnabled(); //Assert Assert.IsFalse(result); } [Test] public void DoVersionCheck_VersionCountDisabler_ReturnFalse() { //Arrange var config = new Config(); config.DisableVersionCount = true; IItemVersionHandler versionHandler = new ItemVersionHandler(config); var result = true; //Act using (new VersionCountDisabler()) { result = versionHandler.VersionCountEnabled(); } //Assert Assert.IsFalse(result); } #endregion #region ConvertAttributes [Test] public void ConvertAttributes_NameValueCollection_ReturnsString() { //Arrange var collection = new NameValueCollection(); collection["key1"] = "value1"; collection["key2"] = "value2"; collection["key3"] = "value3"; var expected = "key1='value1' key2='value2' key3='value3' "; //Act var result = Sc.Utilities.ConvertAttributes(collection); //Assert Assert.AreEqual(expected,result); } /// <summary> /// https://github.com/mikeedwards83/Glass.Mapper/issues/272 /// </summary> [Test] public void ConvertAttributes_NameValueCollection1_ReturnsString() { //Arrange var collection = new NameValueCollection(); collection["key1"] = "value1"; collection["key2"] = "{value2}"; collection["key3"] = "value3"; var expected = "key1='value1' key2='{value2}' key3='value3' "; //Act var result = Sc.Utilities.ConvertAttributes(collection); //Assert Assert.AreEqual(expected, result); } #endregion #region Stubs public class StubClass { public string GetPublicSetPublic { get; set; } protected string GetProtectedSetProtected { get; set; } private string GetPrivateSetPrivate { get; set; } public string GetPublicSetProtected { get; protected set; } public string GetPublicSetPrivate { get; private set; } private string _getPublicNoSet; public string GetPublicNoSet { get { return _getPublicNoSet; } } } #endregion } }
// // 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.WindowsAzure.Management.Automation; using Microsoft.WindowsAzure.Management.Automation.Models; namespace Microsoft.WindowsAzure.Management.Automation { public static partial class RunbookDraftOperationsExtensions { /// <summary> /// Retrieve the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the publish runbook operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResultResponse BeginPublish(this IRunbookDraftOperations operations, string automationAccount, RunbookDraftPublishParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IRunbookDraftOperations)s).BeginPublishAsync(automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the publish runbook operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResultResponse> BeginPublishAsync(this IRunbookDraftOperations operations, string automationAccount, RunbookDraftPublishParameters parameters) { return operations.BeginPublishAsync(automationAccount, parameters, CancellationToken.None); } /// <summary> /// Updates the runbook draft with runbookStream as its content. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The runbook draft update parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResultResponse BeginUpdate(this IRunbookDraftOperations operations, string automationAccount, RunbookDraftUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IRunbookDraftOperations)s).BeginUpdateAsync(automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates the runbook draft with runbookStream as its content. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The runbook draft update parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResultResponse> BeginUpdateAsync(this IRunbookDraftOperations operations, string automationAccount, RunbookDraftUpdateParameters parameters) { return operations.BeginUpdateAsync(automationAccount, parameters, CancellationToken.None); } /// <summary> /// Retrieve the content of runbook draft identified by runbook name. /// (see http://aka.ms/azureautomationsdk/runbookdraftoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <returns> /// The response model for the runbook content operation. /// </returns> public static RunbookContentResponse Content(this IRunbookDraftOperations operations, string automationAccount, string runbookName) { return Task.Factory.StartNew((object s) => { return ((IRunbookDraftOperations)s).ContentAsync(automationAccount, runbookName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the content of runbook draft identified by runbook name. /// (see http://aka.ms/azureautomationsdk/runbookdraftoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <returns> /// The response model for the runbook content operation. /// </returns> public static Task<RunbookContentResponse> ContentAsync(this IRunbookDraftOperations operations, string automationAccount, string runbookName) { return operations.ContentAsync(automationAccount, runbookName, CancellationToken.None); } /// <summary> /// Retrieve the runbook draft identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <returns> /// The response model for the get runbook draft operation. /// </returns> public static RunbookDraftGetResponse Get(this IRunbookDraftOperations operations, string automationAccount, string runbookName) { return Task.Factory.StartNew((object s) => { return ((IRunbookDraftOperations)s).GetAsync(automationAccount, runbookName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the runbook draft identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <returns> /// The response model for the get runbook draft operation. /// </returns> public static Task<RunbookDraftGetResponse> GetAsync(this IRunbookDraftOperations operations, string automationAccount, string runbookName) { return operations.GetAsync(automationAccount, runbookName, CancellationToken.None); } /// <summary> /// Retrieve the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the publish runbook operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResultResponse Publish(this IRunbookDraftOperations operations, string automationAccount, RunbookDraftPublishParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IRunbookDraftOperations)s).PublishAsync(automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the publish runbook operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResultResponse> PublishAsync(this IRunbookDraftOperations operations, string automationAccount, RunbookDraftPublishParameters parameters) { return operations.PublishAsync(automationAccount, parameters, CancellationToken.None); } /// <summary> /// Retrieve the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <returns> /// The response model for the undoedit runbook operation. /// </returns> public static RunbookDraftUndoEditResponse UndoEdit(this IRunbookDraftOperations operations, string automationAccount, string runbookName) { return Task.Factory.StartNew((object s) => { return ((IRunbookDraftOperations)s).UndoEditAsync(automationAccount, runbookName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <returns> /// The response model for the undoedit runbook operation. /// </returns> public static Task<RunbookDraftUndoEditResponse> UndoEditAsync(this IRunbookDraftOperations operations, string automationAccount, string runbookName) { return operations.UndoEditAsync(automationAccount, runbookName, CancellationToken.None); } /// <summary> /// Updates the runbook draft with runbookStream as its content. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The runbook draft update parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResultResponse Update(this IRunbookDraftOperations operations, string automationAccount, RunbookDraftUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IRunbookDraftOperations)s).UpdateAsync(automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates the runbook draft with runbookStream as its content. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The runbook draft update parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResultResponse> UpdateAsync(this IRunbookDraftOperations operations, string automationAccount, RunbookDraftUpdateParameters 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.Generic; using System.Diagnostics; using System.Linq; using System.Text; using SampleMetadata; using Xunit; namespace System.Reflection.Tests { public static class TypeInvariants { [Fact] public static void TestInvariantCode() { // These run some *runtime*-implemented Type objects through our invariant battery. // This is to ensure that the invariant testing code is actually correct. typeof(object).TestTypeDefinitionInvariants(); typeof(OuterType1.InnerType1).TestTypeDefinitionInvariants(); typeof(IList<>).TestTypeDefinitionInvariants(); typeof(IDictionary<,>).TestTypeDefinitionInvariants(); typeof(object[]).TestSzArrayInvariants(); typeof(object).MakeArrayType(1).TestMdArrayInvariants(); typeof(object[,]).TestMdArrayInvariants(); typeof(object[,,]).TestMdArrayInvariants(); typeof(object).MakeByRefType().TestByRefInvariants(); typeof(int).MakePointerType().TestPointerInvariants(); typeof(IList<int>).TestConstructedGenericTypeInvariants(); typeof(IDictionary<int, string>).TestConstructedGenericTypeInvariants(); Type theT = typeof(IList<>).GetTypeInfo().GenericTypeParameters[0]; theT.TestGenericTypeParameterInvariants(); Type theV = typeof(IDictionary<,>).GetTypeInfo().GenericTypeParameters[1]; theT.TestGenericTypeParameterInvariants(); MethodInfo genericMethod = typeof(ClassWithGenericMethods1).GetMethod("GenericMethod1", BindingFlags.Public | BindingFlags.Instance); Debug.Assert(genericMethod != null); Type theM = genericMethod.GetGenericArguments()[0]; theM.TestGenericMethodParameterInvariants(); Type theN = genericMethod.GetGenericArguments()[1]; theN.TestGenericMethodParameterInvariants(); Type openSzArray = theN.MakeArrayType(); openSzArray.TestSzArrayInvariants(); Type openMdArrayRank1 = theN.MakeArrayType(1); openMdArrayRank1.TestMdArrayInvariants(); Type openMdArrayRank2 = theN.MakeArrayType(2); openMdArrayRank2.TestMdArrayInvariants(); Type openByRef = theN.MakeByRefType(); openByRef.TestByRefInvariants(); Type openPointer = theN.MakePointerType(); openPointer.TestPointerInvariants(); Type openDictionary = typeof(IDictionary<,>).MakeGenericType(typeof(int), theN); openDictionary.TestConstructedGenericTypeInvariants(); } public static void TestTypeInvariants(this Type type) { if (type.IsTypeDefinition()) type.TestTypeDefinitionInvariants(); else if (type.HasElementType) type.TestHasElementTypeInvariants(); else if (type.IsConstructedGenericType) type.TestConstructedGenericTypeInvariants(); else if (type.IsGenericParameter) type.TestGenericParameterInvariants(); else Assert.True(false, "Type does not identify as any of the known flavors: " + type); } public static void TestTypeDefinitionInvariants(this Type type) { Assert.True(type.IsTypeDefinition()); if (type.IsGenericTypeDefinition) { type.TestGenericTypeDefinitionInvariants(); } else { type.TestTypeDefinitionCommonInvariants(); } } public static void TestGenericTypeDefinitionInvariants(this Type type) { Assert.True(type.IsGenericTypeDefinition); type.TestTypeDefinitionCommonInvariants(); Type[] gps = type.GetTypeInfo().GenericTypeParameters; Assert.NotNull(gps); Assert.NotEqual(0, gps.Length); Type[] gps2 = type.GetTypeInfo().GenericTypeParameters; Assert.NotSame(gps, gps2); Assert.Equal<Type>(gps, gps2); for (int i = 0; i < gps.Length; i++) { Type gp = gps[i]; Assert.Equal(i, gp.GenericParameterPosition); Assert.Equal(type, gp.DeclaringType); } } public static void TestHasElementTypeInvariants(this Type type) { Assert.True(type.HasElementType); if (type.IsSZArray()) type.TestSzArrayInvariants(); else if (type.IsVariableBoundArray()) type.TestMdArrayInvariants(); else if (type.IsByRef) type.TestByRefInvariants(); else if (type.IsPointer) type.TestPointerInvariants(); } public static void TestArrayInvariants(this Type type) { Assert.True(type.IsArray); if (type.IsSZArray()) type.TestSzArrayInvariants(); else if (type.IsVariableBoundArray()) type.TestMdArrayInvariants(); else Assert.True(false, "Array type does not identify as either Sz or VariableBound: " + type); BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MemberInfo[] mems; mems = type.GetEvents(bf); Assert.Equal(0, mems.Length); mems = type.GetFields(bf); Assert.Equal(0, mems.Length); mems = type.GetProperties(bf); Assert.Equal(0, mems.Length); mems = type.GetNestedTypes(bf); Assert.Equal(0, mems.Length); } public static void TestSzArrayInvariants(this Type type) { Assert.True(type.IsSZArray()); type.TestArrayCommonInvariants(); Type et = type.GetElementType(); string name = type.Name; string fullName = type.FullName; string suffix = "[]"; Assert.Equal(et.Name + suffix, name); if (fullName != null) { Assert.Equal(et.FullName + suffix, fullName); } } public static void TestMdArrayInvariants(this Type type) { Assert.True(type.IsVariableBoundArray()); type.TestArrayCommonInvariants(); string name = type.Name; string fullName = type.FullName; Type et = type.GetElementType(); int rank = type.GetArrayRank(); string suffix = (rank == 1) ? "[*]" : "[" + new string(',', rank - 1) + "]"; Assert.Equal(et.Name + suffix, name); if (fullName != null) { Assert.Equal(et.FullName + suffix, fullName); } Type systemInt32 = type.BaseType.Assembly.GetType("System.Int32", throwOnError: true); ConstructorInfo[] cis = type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly); Assert.Equal(cis.Length, 2); ConstructorInfo c1 = cis.Single(c => c.GetParameters().Length == rank); foreach (ParameterInfo p in c1.GetParameters()) Assert.Equal(p.ParameterType, systemInt32); ConstructorInfo c2 = cis.Single(c => c.GetParameters().Length == rank * 2); foreach (ParameterInfo p in c2.GetParameters()) Assert.Equal(p.ParameterType, systemInt32); } public static void TestByRefInvariants(this Type type) { Assert.True(type.IsByRef); type.TestHasElementTypeCommonInvariants(); string name = type.Name; string fullName = type.FullName; Type et = type.GetElementType(); string suffix = "&"; Assert.Equal(et.Name + suffix, name); if (fullName != null) { Assert.Equal(et.FullName + suffix, fullName); } // No base type, interfaces Assert.Null(type.BaseType); Assert.Equal(0, type.GetInterfaces().Length); // No members BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MemberInfo[] members = type.GetMembers(bf); Assert.Equal(0, members.Length); } public static void TestPointerInvariants(this Type type) { Assert.True(type.IsPointer); type.TestHasElementTypeCommonInvariants(); string name = type.Name; string fullName = type.FullName; Type et = type.GetElementType(); string suffix = "*"; Assert.Equal(et.Name + suffix, name); if (fullName != null) { Assert.Equal(et.FullName + suffix, fullName); } // No base type, interfaces Assert.Null(type.BaseType); Assert.Equal(0, type.GetInterfaces().Length); // No members BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MemberInfo[] members = type.GetMembers(bf); Assert.Equal(0, members.Length); } public static void TestConstructedGenericTypeInvariants(this Type type) { type.TestConstructedGenericTypeCommonInvariants(); } public static void TestGenericParameterInvariants(this Type type) { Assert.True(type.IsGenericParameter); type.TestTypeCommonInvariants(); // No members BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MemberInfo[] members = type.GetMembers(bf); Assert.Equal(0, members.Length); } public static void TestGenericTypeParameterInvariants(this Type type) { Assert.True(type.IsGenericTypeParameter()); type.TestGenericParameterCommonInvariants(); Assert.Null(type.DeclaringMethod); int position = type.GenericParameterPosition; Type declaringType = type.DeclaringType; Assert.NotNull(declaringType); Assert.True(declaringType.IsGenericTypeDefinition); Type[] gps = declaringType.GetTypeInfo().GenericTypeParameters; Assert.Equal(gps[position], type); } public static void TestGenericMethodParameterInvariants(this Type type) { Assert.True(type.IsGenericMethodParameter()); type.TestGenericParameterCommonInvariants(); int position = type.GenericParameterPosition; MethodInfo declaringMethod = (MethodInfo)type.DeclaringMethod; Assert.NotNull(declaringMethod); Assert.True(declaringMethod.IsGenericMethodDefinition); Type declaringType = type.DeclaringType; Assert.NotNull(declaringType); Assert.Equal(declaringMethod.DeclaringType, declaringType); Type[] gps = declaringMethod.GetGenericArguments(); Assert.Equal(gps[position], type); // There is only one generic parameter instance even if it was queried from a method from an instantiated type or // a method with an alternate ReflectedType. Assert.False(declaringType.IsConstructedGenericType); Assert.Equal(declaringType, declaringMethod.ReflectedType); } private static void TestTypeCommonInvariants(this Type type) { // Ensure that ToString() doesn't throw and that it returns some non-null value. Exact contents are considered implementation detail. string typeString = type.ToString(); Assert.NotNull(typeString); // These properties are mutually exclusive and exactly one of them must be true. int isCount = 0; isCount += type.IsTypeDefinition() ? 1 : 0; isCount += type.IsSZArray() ? 1 : 0; isCount += type.IsVariableBoundArray() ? 1 : 0; isCount += type.IsByRef ? 1 : 0; isCount += type.IsPointer ? 1 : 0; isCount += type.IsConstructedGenericType ? 1 : 0; isCount += type.IsGenericTypeParameter() ? 1 : 0; isCount += type.IsGenericMethodParameter() ? 1 : 0; Assert.Equal(1, isCount); Assert.Equal(type.IsGenericType, type.IsGenericTypeDefinition || type.IsConstructedGenericType); Assert.Equal(type.HasElementType, type.IsArray || type.IsByRef || type.IsPointer); Assert.Equal(type.IsArray, type.IsSZArray() || type.IsVariableBoundArray()); Assert.Equal(type.IsGenericParameter, type.IsGenericTypeParameter() || type.IsGenericMethodParameter()); Assert.Same(type, type.GetTypeInfo()); Assert.Same(type, type.GetTypeInfo().AsType()); Assert.Same(type, type.UnderlyingSystemType); Assert.Same(type.DeclaringType, type.ReflectedType); Assert.Equal(type.IsPublic || type.IsNotPublic ? MemberTypes.TypeInfo : MemberTypes.NestedType, type.MemberType); Assert.False(type.IsCOMObject); Module module = type.Module; Assembly assembly = type.Assembly; Assert.Equal(module.Assembly, assembly); string name = type.Name; string ns = type.Namespace; string fullName = type.FullName; string aqn = type.AssemblyQualifiedName; if (type.ContainsGenericParameters && !type.IsGenericTypeDefinition) { // Open types return null for FullName as such types cannot roundtrip through Type.GetType(string) Assert.Null(fullName); Assert.Null(aqn); } else { Assert.NotNull(fullName); Assert.NotNull(aqn); string expectedAqn = fullName + ", " + assembly.FullName; Assert.Equal(expectedAqn, aqn); } if (fullName != null) { Type roundTrip = assembly.GetType(fullName, throwOnError: true, ignoreCase: false); Assert.Same(type, roundTrip); Type roundTrip2 = module.GetType(fullName, throwOnError: true, ignoreCase: false); Assert.Same(type, roundTrip2); } Assert.Equal<Type>(type.GetInterfaces(), type.GetTypeInfo().ImplementedInterfaces); TestUtils.AssertNewObjectReturnedEachTime(() => type.GenericTypeArguments); TestUtils.AssertNewObjectReturnedEachTime(() => type.GetTypeInfo().GenericTypeParameters); TestUtils.AssertNewObjectReturnedEachTime(() => type.GetGenericArguments()); TestUtils.AssertNewObjectReturnedEachTime(() => type.GetInterfaces()); TestUtils.AssertNewObjectReturnedEachTime(() => type.GetTypeInfo().ImplementedInterfaces); CustomAttributeTests.ValidateCustomAttributesAllocatesFreshObjectsEachTime(() => type.CustomAttributes); const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy; foreach (MemberInfo mem in type.GetMember("*", MemberTypes.All, bf)) { string s = mem.ToString(); Assert.Equal(type, mem.ReflectedType); Type declaringType = mem.DeclaringType; Assert.True(type == declaringType || type.IsSubclassOf(declaringType)); if (mem is MethodBase methodBase) methodBase.TestMethodBaseInvariants(); if (type.Assembly.ReflectionOnly) { ICustomAttributeProvider icp = mem; Assert.Throws<InvalidOperationException>(() => icp.IsDefined(null, inherit: false)); Assert.Throws<InvalidOperationException>(() => icp.GetCustomAttributes(null, inherit: false)); ; Assert.Throws<InvalidOperationException>(() => icp.GetCustomAttributes(inherit: false)); if (mem is MethodBase mb) { Assert.Throws<InvalidOperationException>(() => mb.MethodHandle); Assert.Throws<InvalidOperationException>(() => mb.Invoke(null,null)); } } } TestUtils.AssertNewObjectReturnedEachTime(() => type.GetMember("*", MemberTypes.All, bf)); // Test some things that common to types that are not of a particular bucket. // (The Test*CommonInvariants() methods will cover the other half.) if (!type.IsTypeDefinition()) { Assert.False(type.IsGenericTypeDefinition); Assert.Equal(0, type.GetTypeInfo().GenericTypeParameters.Length); } if (!type.IsGenericTypeDefinition) { Assert.Throws<InvalidOperationException>(() => type.MakeGenericType(new Type[3])); } if (!type.HasElementType) { Assert.Null(type.GetElementType()); } if (!type.IsArray) { Assert.False(type.IsSZArray() || type.IsVariableBoundArray()); Assert.Throws<ArgumentException>(() => type.GetArrayRank()); } if (!type.IsByRef) { } if (!type.IsPointer) { } if (!type.IsConstructedGenericType) { Assert.Equal(0, type.GenericTypeArguments.Length); if (!type.IsGenericTypeDefinition) { Assert.Throws<InvalidOperationException>(() => type.GetGenericTypeDefinition()); } } if (!type.IsGenericParameter) { Assert.Throws<InvalidOperationException>(() => type.GenericParameterAttributes); Assert.Throws<InvalidOperationException>(() => type.GenericParameterPosition); Assert.Throws<InvalidOperationException>(() => type.GetGenericParameterConstraints()); Assert.Throws<InvalidOperationException>(() => type.DeclaringMethod); } } private static void TestTypeDefinitionCommonInvariants(this Type type) { type.TestTypeCommonInvariants(); Assert.True(type.IsTypeDefinition()); Assert.Equal(type.IsGenericTypeDefinition, type.ContainsGenericParameters); string name = type.Name; string ns = type.Namespace; string fullName = type.FullName; Assert.NotNull(name); Assert.NotNull(fullName); string expectedFullName; if (type.IsNested) { expectedFullName = type.DeclaringType.FullName + "+" + name; } else { expectedFullName = (ns == null) ? name : ns + "." + name; } Assert.Equal(expectedFullName, fullName); Type declaringType = type.DeclaringType; if (declaringType != null) { Assert.True(declaringType.IsTypeDefinition()); Type[] nestedTypes = declaringType.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic); Assert.True(nestedTypes.Any(nt => object.ReferenceEquals(nt, type))); } Assert.Equal<Type>(type.GetTypeInfo().GenericTypeParameters, type.GetGenericArguments()); int metadataToken = type.MetadataToken; Assert.Equal(0x02000000, metadataToken & 0xff000000); } private static void TestHasElementTypeCommonInvariants(this Type type) { type.TestTypeCommonInvariants(); Assert.True(type.HasElementType); Assert.True(type.IsArray || type.IsByRef || type.IsPointer); Type et = type.GetElementType(); Assert.NotNull(et); string ns = type.Namespace; Assert.Equal(et.Namespace, ns); Assert.Equal(et.Assembly, type.Assembly); Assert.Equal(et.Module, type.Module); Assert.Equal(et.ContainsGenericParameters, type.ContainsGenericParameters); Assert.Null(type.DeclaringType); Assert.False(type.IsByRefLike()); Assert.Equal(default(Guid), type.GUID); Assert.Equal(0x02000000, type.MetadataToken); Type rootElementType = type; while (rootElementType.HasElementType) { rootElementType = rootElementType.GetElementType(); } Assert.Equal<Type>(rootElementType.GetGenericArguments(), type.GetGenericArguments()); } private static void TestArrayCommonInvariants(this Type type) { type.TestHasElementTypeCommonInvariants(); Assert.True(type.IsArray); } private static void TestConstructedGenericTypeCommonInvariants(this Type type) { Assert.True(type.IsConstructedGenericType); type.TestTypeCommonInvariants(); string name = type.Name; string ns = type.Namespace; string fullName = type.FullName; Type gd = type.GetGenericTypeDefinition(); Assert.Equal(gd.Name, name); Assert.Equal(gd.Namespace, ns); if (fullName != null) { StringBuilder expectedFullName = new StringBuilder(); expectedFullName.Append(gd.FullName); expectedFullName.Append('['); Type[] genericTypeArguments = type.GenericTypeArguments; for (int i = 0; i < genericTypeArguments.Length; i++) { if (i != 0) expectedFullName.Append(','); expectedFullName.Append('['); expectedFullName.Append(genericTypeArguments[i].AssemblyQualifiedName); expectedFullName.Append(']'); } expectedFullName.Append(']'); Assert.Equal(expectedFullName.ToString(), fullName); } Assert.Equal(type.GenericTypeArguments.Any(gta => gta.ContainsGenericParameters), type.ContainsGenericParameters); Type[] gas = type.GenericTypeArguments; Assert.NotNull(gas); Assert.NotEqual(0, gas.Length); Type[] gas2 = type.GenericTypeArguments; Assert.NotSame(gas, gas2); Assert.Equal<Type>(gas, gas2); Assert.Same(type.GetGenericTypeDefinition().DeclaringType, type.DeclaringType); Assert.Equal<Type>(type.GenericTypeArguments, type.GetGenericArguments()); Assert.Equal(type.GetGenericTypeDefinition().MetadataToken, type.MetadataToken); } private static void TestGenericParameterCommonInvariants(this Type type) { type.TestTypeCommonInvariants(); Assert.True(type.IsGenericParameter); Assert.True(type.ContainsGenericParameters); string ns = type.Namespace; Assert.Equal(type.DeclaringType.Namespace, ns); Assert.Null(type.FullName); // Make sure these don't throw. int position = type.GenericParameterPosition; Assert.True(position >= 0); GenericParameterAttributes attributes = type.GenericParameterAttributes; Assert.Equal<Type>(Array.Empty<Type>(), type.GetGenericArguments()); Assert.False(type.IsByRefLike()); Assert.Equal(default(Guid), type.GUID); int metadataToken = type.MetadataToken; Assert.Equal(0x2a000000, metadataToken & 0xff000000); // No members BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MemberInfo[] members = type.GetMembers(bf); Assert.Equal(0, members.Length); } } }
namespace SPD.GUI { /// <summary> /// /// </summary> partial class OPControl { /// <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 Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.labelPatient = new System.Windows.Forms.Label(); this.labelPatientData = new System.Windows.Forms.Label(); this.labelOPDate = new System.Windows.Forms.Label(); this.labelOPTeam = new System.Windows.Forms.Label(); this.labelOPProcess = new System.Windows.Forms.Label(); this.textBoxOPDate = new System.Windows.Forms.TextBox(); this.textBoxOPTeam = new System.Windows.Forms.TextBox(); this.textBoxOPProcess = new System.Windows.Forms.TextBox(); this.textBoxOPDiagnoses = new System.Windows.Forms.TextBox(); this.labelOPDiagnoses = new System.Windows.Forms.Label(); this.labelPerformedOP = new System.Windows.Forms.Label(); this.textBoxPerformedOP = new System.Windows.Forms.TextBox(); this.labelOperationHeadline = new System.Windows.Forms.Label(); this.buttonSaveOperation = new System.Windows.Forms.Button(); this.buttonClearData = new System.Windows.Forms.Button(); this.buttonToday = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.textBoxAdditionalInformation = new System.Windows.Forms.TextBox(); this.textBoxMedication = new System.Windows.Forms.TextBox(); this.labelIntDiagnoses = new System.Windows.Forms.Label(); this.textBoxIntdiagnoses = new System.Windows.Forms.TextBox(); this.comboBoxPPPS = new System.Windows.Forms.ComboBox(); this.comboBoxResult = new System.Windows.Forms.ComboBox(); this.labelPPPS = new System.Windows.Forms.Label(); this.labelResult = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.comboBoxKathDays = new System.Windows.Forms.ComboBox(); this.label7 = new System.Windows.Forms.Label(); this.comboBoxOrgan = new System.Windows.Forms.ComboBox(); this.buttonSaveAndPrint = new System.Windows.Forms.Button(); this.listBoxDays = new System.Windows.Forms.ListBox(); this.labelDays = new System.Windows.Forms.Label(); this.labelSheets = new System.Windows.Forms.Label(); this.listBoxCopys = new System.Windows.Forms.ListBox(); this.labelOpResult = new System.Windows.Forms.Label(); this.textBoxOpResult = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // labelPatient // this.labelPatient.AutoSize = true; this.labelPatient.Location = new System.Drawing.Point(183, 14); this.labelPatient.Name = "labelPatient"; this.labelPatient.Size = new System.Drawing.Size(43, 13); this.labelPatient.TabIndex = 0; this.labelPatient.Text = "Patient:"; // // labelPatientData // this.labelPatientData.AutoSize = true; this.labelPatientData.Location = new System.Drawing.Point(229, 14); this.labelPatientData.Name = "labelPatientData"; this.labelPatientData.Size = new System.Drawing.Size(40, 13); this.labelPatientData.TabIndex = 0; this.labelPatientData.Text = "Patient"; // // labelOPDate // this.labelOPDate.AutoSize = true; this.labelOPDate.Location = new System.Drawing.Point(36, 32); this.labelOPDate.Name = "labelOPDate"; this.labelOPDate.Size = new System.Drawing.Size(51, 13); this.labelOPDate.TabIndex = 0; this.labelOPDate.Text = "OP Date:"; // // labelOPTeam // this.labelOPTeam.AutoSize = true; this.labelOPTeam.Location = new System.Drawing.Point(32, 52); this.labelOPTeam.Name = "labelOPTeam"; this.labelOPTeam.Size = new System.Drawing.Size(55, 13); this.labelOPTeam.TabIndex = 0; this.labelOPTeam.Text = "OP Team:"; // // labelOPProcess // this.labelOPProcess.AutoSize = true; this.labelOPProcess.Location = new System.Drawing.Point(21, 80); this.labelOPProcess.Name = "labelOPProcess"; this.labelOPProcess.Size = new System.Drawing.Size(66, 13); this.labelOPProcess.TabIndex = 0; this.labelOPProcess.Text = "OP Process:"; // // textBoxOPDate // this.textBoxOPDate.Location = new System.Drawing.Point(93, 29); this.textBoxOPDate.MaxLength = 255; this.textBoxOPDate.Name = "textBoxOPDate"; this.textBoxOPDate.Size = new System.Drawing.Size(224, 20); this.textBoxOPDate.TabIndex = 0; // // textBoxOPTeam // this.textBoxOPTeam.Location = new System.Drawing.Point(93, 49); this.textBoxOPTeam.MaxLength = 255; this.textBoxOPTeam.Multiline = true; this.textBoxOPTeam.Name = "textBoxOPTeam"; this.textBoxOPTeam.Size = new System.Drawing.Size(883, 28); this.textBoxOPTeam.TabIndex = 2; // // textBoxOPProcess // this.textBoxOPProcess.Location = new System.Drawing.Point(93, 77); this.textBoxOPProcess.Multiline = true; this.textBoxOPProcess.Name = "textBoxOPProcess"; this.textBoxOPProcess.Size = new System.Drawing.Size(883, 50); this.textBoxOPProcess.TabIndex = 3; // // textBoxOPDiagnoses // this.textBoxOPDiagnoses.Location = new System.Drawing.Point(93, 126); this.textBoxOPDiagnoses.MaxLength = 255; this.textBoxOPDiagnoses.Multiline = true; this.textBoxOPDiagnoses.Name = "textBoxOPDiagnoses"; this.textBoxOPDiagnoses.Size = new System.Drawing.Size(883, 34); this.textBoxOPDiagnoses.TabIndex = 4; // // labelOPDiagnoses // this.labelOPDiagnoses.AutoSize = true; this.labelOPDiagnoses.Location = new System.Drawing.Point(13, 129); this.labelOPDiagnoses.Name = "labelOPDiagnoses"; this.labelOPDiagnoses.Size = new System.Drawing.Size(74, 13); this.labelOPDiagnoses.TabIndex = 0; this.labelOPDiagnoses.Text = "OP Diagnosis:"; // // labelPerformedOP // this.labelPerformedOP.AutoSize = true; this.labelPerformedOP.Location = new System.Drawing.Point(11, 163); this.labelPerformedOP.Name = "labelPerformedOP"; this.labelPerformedOP.Size = new System.Drawing.Size(76, 13); this.labelPerformedOP.TabIndex = 0; this.labelPerformedOP.Text = "Performed OP:"; // // textBoxPerformedOP // this.textBoxPerformedOP.Location = new System.Drawing.Point(93, 160); this.textBoxPerformedOP.MaxLength = 255; this.textBoxPerformedOP.Multiline = true; this.textBoxPerformedOP.Name = "textBoxPerformedOP"; this.textBoxPerformedOP.Size = new System.Drawing.Size(372, 40); this.textBoxPerformedOP.TabIndex = 5; // // labelOperationHeadline // this.labelOperationHeadline.AutoSize = true; this.labelOperationHeadline.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelOperationHeadline.Location = new System.Drawing.Point(89, 9); this.labelOperationHeadline.Name = "labelOperationHeadline"; this.labelOperationHeadline.Size = new System.Drawing.Size(88, 20); this.labelOperationHeadline.TabIndex = 2; this.labelOperationHeadline.Text = "Operation"; // // buttonSaveOperation // this.buttonSaveOperation.Location = new System.Drawing.Point(73, 281); this.buttonSaveOperation.Name = "buttonSaveOperation"; this.buttonSaveOperation.Size = new System.Drawing.Size(98, 23); this.buttonSaveOperation.TabIndex = 12; this.buttonSaveOperation.Text = "Save and Close"; this.buttonSaveOperation.UseVisualStyleBackColor = true; this.buttonSaveOperation.Click += new System.EventHandler(this.buttonSaveOperation_Click); // // buttonClearData // this.buttonClearData.Location = new System.Drawing.Point(177, 281); this.buttonClearData.Name = "buttonClearData"; this.buttonClearData.Size = new System.Drawing.Size(70, 23); this.buttonClearData.TabIndex = 16; this.buttonClearData.Text = "Clear Data"; this.buttonClearData.UseVisualStyleBackColor = true; this.buttonClearData.Click += new System.EventHandler(this.buttonClearData_Click); // // buttonToday // this.buttonToday.Location = new System.Drawing.Point(323, 28); this.buttonToday.Name = "buttonToday"; this.buttonToday.Size = new System.Drawing.Size(76, 21); this.buttonToday.TabIndex = 1; this.buttonToday.Text = "today"; this.buttonToday.UseVisualStyleBackColor = true; this.buttonToday.Click += new System.EventHandler(this.buttonToday_Click); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(0, 202); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(87, 13); this.label1.TabIndex = 8; this.label1.Text = "Add. Information:"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(474, 163); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(62, 13); this.label2.TabIndex = 9; this.label2.Text = "Medication:"; // // textBoxAdditionalInformation // this.textBoxAdditionalInformation.Location = new System.Drawing.Point(93, 199); this.textBoxAdditionalInformation.Multiline = true; this.textBoxAdditionalInformation.Name = "textBoxAdditionalInformation"; this.textBoxAdditionalInformation.Size = new System.Drawing.Size(372, 50); this.textBoxAdditionalInformation.TabIndex = 6; // // textBoxMedication // this.textBoxMedication.Location = new System.Drawing.Point(542, 160); this.textBoxMedication.Multiline = true; this.textBoxMedication.Name = "textBoxMedication"; this.textBoxMedication.Size = new System.Drawing.Size(434, 40); this.textBoxMedication.TabIndex = 7; // // labelIntDiagnoses // this.labelIntDiagnoses.AutoSize = true; this.labelIntDiagnoses.Location = new System.Drawing.Point(357, 258); this.labelIntDiagnoses.Name = "labelIntDiagnoses"; this.labelIntDiagnoses.Size = new System.Drawing.Size(70, 13); this.labelIntDiagnoses.TabIndex = 9; this.labelIntDiagnoses.Text = "Intdiagnoses:"; // // textBoxIntdiagnoses // this.textBoxIntdiagnoses.Location = new System.Drawing.Point(433, 256); this.textBoxIntdiagnoses.Name = "textBoxIntdiagnoses"; this.textBoxIntdiagnoses.Size = new System.Drawing.Size(70, 20); this.textBoxIntdiagnoses.TabIndex = 9; // // comboBoxPPPS // this.comboBoxPPPS.FormattingEnabled = true; this.comboBoxPPPS.Location = new System.Drawing.Point(577, 255); this.comboBoxPPPS.Name = "comboBoxPPPS"; this.comboBoxPPPS.Size = new System.Drawing.Size(91, 21); this.comboBoxPPPS.TabIndex = 10; // // comboBoxResult // this.comboBoxResult.FormattingEnabled = true; this.comboBoxResult.Location = new System.Drawing.Point(711, 255); this.comboBoxResult.Name = "comboBoxResult"; this.comboBoxResult.Size = new System.Drawing.Size(106, 21); this.comboBoxResult.TabIndex = 11; // // labelPPPS // this.labelPPPS.AutoSize = true; this.labelPPPS.Location = new System.Drawing.Point(518, 258); this.labelPPPS.Name = "labelPPPS"; this.labelPPPS.Size = new System.Drawing.Size(53, 13); this.labelPPPS.TabIndex = 14; this.labelPPPS.Text = "PP or PS:"; // // labelResult // this.labelResult.AutoSize = true; this.labelResult.Location = new System.Drawing.Point(671, 258); this.labelResult.Name = "labelResult"; this.labelResult.Size = new System.Drawing.Size(40, 13); this.labelResult.TabIndex = 15; this.labelResult.Text = "Result:"; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(28, 258); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(59, 13); this.label6.TabIndex = 16; this.label6.Text = "Kath Days:"; // // comboBoxKathDays // this.comboBoxKathDays.FormattingEnabled = true; this.comboBoxKathDays.Location = new System.Drawing.Point(93, 255); this.comboBoxKathDays.Name = "comboBoxKathDays"; this.comboBoxKathDays.Size = new System.Drawing.Size(80, 21); this.comboBoxKathDays.TabIndex = 8; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(179, 258); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(39, 13); this.label7.TabIndex = 23; this.label7.Text = "Organ:"; // // comboBoxOrgan // this.comboBoxOrgan.FormattingEnabled = true; this.comboBoxOrgan.Location = new System.Drawing.Point(219, 255); this.comboBoxOrgan.Name = "comboBoxOrgan"; this.comboBoxOrgan.Size = new System.Drawing.Size(121, 21); this.comboBoxOrgan.TabIndex = 24; // // buttonSaveAndPrint // this.buttonSaveAndPrint.Location = new System.Drawing.Point(254, 281); this.buttonSaveAndPrint.Name = "buttonSaveAndPrint"; this.buttonSaveAndPrint.Size = new System.Drawing.Size(183, 23); this.buttonSaveAndPrint.TabIndex = 25; this.buttonSaveAndPrint.Text = "Save and Print Temperatur Curve"; this.buttonSaveAndPrint.UseVisualStyleBackColor = true; this.buttonSaveAndPrint.Click += new System.EventHandler(this.buttonSaveAndPrint_Click_1); // // listBoxDays // this.listBoxDays.FormattingEnabled = true; this.listBoxDays.Location = new System.Drawing.Point(483, 281); this.listBoxDays.Name = "listBoxDays"; this.listBoxDays.Size = new System.Drawing.Size(49, 30); this.listBoxDays.TabIndex = 26; // // labelDays // this.labelDays.AutoSize = true; this.labelDays.Location = new System.Drawing.Point(443, 286); this.labelDays.Name = "labelDays"; this.labelDays.Size = new System.Drawing.Size(34, 13); this.labelDays.TabIndex = 27; this.labelDays.Text = "Days:"; // // labelSheets // this.labelSheets.AutoSize = true; this.labelSheets.Location = new System.Drawing.Point(553, 286); this.labelSheets.Name = "labelSheets"; this.labelSheets.Size = new System.Drawing.Size(34, 13); this.labelSheets.TabIndex = 28; this.labelSheets.Text = "Copy:"; // // listBoxCopys // this.listBoxCopys.FormattingEnabled = true; this.listBoxCopys.Location = new System.Drawing.Point(593, 281); this.listBoxCopys.Name = "listBoxCopys"; this.listBoxCopys.Size = new System.Drawing.Size(40, 30); this.listBoxCopys.TabIndex = 29; // // labelOpResult // this.labelOpResult.AutoSize = true; this.labelOpResult.Location = new System.Drawing.Point(480, 205); this.labelOpResult.Name = "labelOpResult"; this.labelOpResult.Size = new System.Drawing.Size(58, 13); this.labelOpResult.TabIndex = 30; this.labelOpResult.Text = "OP Result:"; // // textBoxOpResult // this.textBoxOpResult.Location = new System.Drawing.Point(542, 202); this.textBoxOpResult.Multiline = true; this.textBoxOpResult.Name = "textBoxOpResult"; this.textBoxOpResult.Size = new System.Drawing.Size(434, 47); this.textBoxOpResult.TabIndex = 31; // // OPControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.textBoxOpResult); this.Controls.Add(this.labelOpResult); this.Controls.Add(this.listBoxCopys); this.Controls.Add(this.labelSheets); this.Controls.Add(this.labelDays); this.Controls.Add(this.listBoxDays); this.Controls.Add(this.buttonSaveAndPrint); this.Controls.Add(this.comboBoxOrgan); this.Controls.Add(this.label7); this.Controls.Add(this.comboBoxKathDays); this.Controls.Add(this.label6); this.Controls.Add(this.labelResult); this.Controls.Add(this.labelPPPS); this.Controls.Add(this.comboBoxResult); this.Controls.Add(this.comboBoxPPPS); this.Controls.Add(this.textBoxIntdiagnoses); this.Controls.Add(this.textBoxMedication); this.Controls.Add(this.textBoxAdditionalInformation); this.Controls.Add(this.labelIntDiagnoses); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.buttonToday); this.Controls.Add(this.buttonClearData); this.Controls.Add(this.buttonSaveOperation); this.Controls.Add(this.labelOperationHeadline); this.Controls.Add(this.textBoxPerformedOP); this.Controls.Add(this.textBoxOPDiagnoses); this.Controls.Add(this.textBoxOPTeam); this.Controls.Add(this.textBoxOPProcess); this.Controls.Add(this.labelPerformedOP); this.Controls.Add(this.textBoxOPDate); this.Controls.Add(this.labelOPDiagnoses); this.Controls.Add(this.labelOPProcess); this.Controls.Add(this.labelOPTeam); this.Controls.Add(this.labelOPDate); this.Controls.Add(this.labelPatientData); this.Controls.Add(this.labelPatient); this.Name = "OPControl"; this.Size = new System.Drawing.Size(985, 319); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label labelPatient; private System.Windows.Forms.Label labelPatientData; private System.Windows.Forms.Label labelOPDate; private System.Windows.Forms.Label labelOPTeam; private System.Windows.Forms.Label labelOPProcess; private System.Windows.Forms.TextBox textBoxOPDate; private System.Windows.Forms.TextBox textBoxOPTeam; private System.Windows.Forms.TextBox textBoxOPProcess; private System.Windows.Forms.TextBox textBoxOPDiagnoses; private System.Windows.Forms.Label labelOPDiagnoses; private System.Windows.Forms.Label labelPerformedOP; private System.Windows.Forms.TextBox textBoxPerformedOP; private System.Windows.Forms.Label labelOperationHeadline; private System.Windows.Forms.Button buttonSaveOperation; private System.Windows.Forms.Button buttonClearData; private System.Windows.Forms.Button buttonToday; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox textBoxAdditionalInformation; private System.Windows.Forms.TextBox textBoxMedication; private System.Windows.Forms.Label labelIntDiagnoses; private System.Windows.Forms.TextBox textBoxIntdiagnoses; private System.Windows.Forms.ComboBox comboBoxPPPS; private System.Windows.Forms.ComboBox comboBoxResult; private System.Windows.Forms.Label labelPPPS; private System.Windows.Forms.Label labelResult; private System.Windows.Forms.Label label6; private System.Windows.Forms.ComboBox comboBoxKathDays; private System.Windows.Forms.Label label7; private System.Windows.Forms.ComboBox comboBoxOrgan; private System.Windows.Forms.Button buttonSaveAndPrint; private System.Windows.Forms.ListBox listBoxDays; private System.Windows.Forms.Label labelDays; private System.Windows.Forms.Label labelSheets; private System.Windows.Forms.ListBox listBoxCopys; private System.Windows.Forms.Label labelOpResult; private System.Windows.Forms.TextBox textBoxOpResult; } }
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using System; using System.Collections.Generic; using TheArtOfDev.HtmlRenderer.Adapters; using TheArtOfDev.HtmlRenderer.Core.Entities; using TheArtOfDev.HtmlRenderer.Core.Parse; using TheArtOfDev.HtmlRenderer.Core.Utils; namespace TheArtOfDev.HtmlRenderer.Core { /// <summary> /// Holds parsed stylesheet css blocks arranged by media and classes.<br/> /// <seealso cref="CssBlock"/> /// </summary> /// <remarks> /// To learn more about CSS blocks visit CSS spec: http://www.w3.org/TR/CSS21/syndata.html#block /// </remarks> public sealed class CssData { #region Fields and Consts /// <summary> /// used to return empty array /// </summary> private static readonly List<CssBlock> _emptyArray = new List<CssBlock>(); /// <summary> /// dictionary of media type to dictionary of css class name to the cssBlocks collection with all the data. /// </summary> private readonly Dictionary<string, Dictionary<string, List<CssBlock>>> _mediaBlocks = new Dictionary<string, Dictionary<string, List<CssBlock>>>(StringComparer.InvariantCultureIgnoreCase); #endregion /// <summary> /// Init. /// </summary> internal CssData() { _mediaBlocks.Add("all", new Dictionary<string, List<CssBlock>>(StringComparer.InvariantCultureIgnoreCase)); } /// <summary> /// Parse the given stylesheet to <see cref="CssData"/> object.<br/> /// If <paramref name="combineWithDefault"/> is true the parsed css blocks are added to the /// default css data (as defined by W3), merged if class name already exists. If false only the data in the given stylesheet is returned. /// </summary> /// <seealso cref="http://www.w3.org/TR/CSS21/sample.html"/> /// <param name="adapter">Platform adapter</param> /// <param name="stylesheet">the stylesheet source to parse</param> /// <param name="combineWithDefault">true - combine the parsed css data with default css data, false - return only the parsed css data</param> /// <returns>the parsed css data</returns> public static CssData Parse(RAdapter adapter, string stylesheet, bool combineWithDefault = true) { CssParser parser = new CssParser(adapter); return parser.ParseStyleSheet(stylesheet, combineWithDefault); } /// <summary> /// dictionary of media type to dictionary of css class name to the cssBlocks collection with all the data /// </summary> internal IDictionary<string, Dictionary<string, List<CssBlock>>> MediaBlocks { get { return _mediaBlocks; } } /// <summary> /// Check if there are css blocks for the given class selector. /// </summary> /// <param name="className">the class selector to check for css blocks by</param> /// <param name="media">optional: the css media type (default - all)</param> /// <returns>true - has css blocks for the class, false - otherwise</returns> public bool ContainsCssBlock(string className, string media = "all") { Dictionary<string, List<CssBlock>> mid; return _mediaBlocks.TryGetValue(media, out mid) && mid.ContainsKey(className); } /// <summary> /// Get collection of css blocks for the requested class selector.<br/> /// the <paramref name="className"/> can be: class name, html element name, html element and /// class name (elm.class), hash tag with element id (#id).<br/> /// returned all the blocks that word on the requested class selector, it can contain simple /// selector or hierarchy selector. /// </summary> /// <param name="className">the class selector to get css blocks by</param> /// <param name="media">optional: the css media type (default - all)</param> /// <returns>collection of css blocks, empty collection if no blocks exists (never null)</returns> public IEnumerable<CssBlock> GetCssBlock(string className, string media = "all") { List<CssBlock> block = null; Dictionary<string, List<CssBlock>> mid; if (_mediaBlocks.TryGetValue(media, out mid)) { mid.TryGetValue(className, out block); } return block ?? _emptyArray; } /// <summary> /// Add the given css block to the css data, merging to existing block if required. /// </summary> /// <remarks> /// If there is no css blocks for the same class it will be added to data collection.<br/> /// If there is already css blocks for the same class it will check for each existing block /// if the hierarchical selectors match (or not exists). if do the two css blocks will be merged into /// one where the new block properties overwrite existing if needed. if the new block doesn't mach any /// existing it will be added either to the beginning of the list if it has no hierarchical selectors or at the end.<br/> /// Css block without hierarchical selectors must be added to the beginning of the list so more specific block /// can overwrite it when the style is applied. /// </remarks> /// <param name="media">the media type to add the CSS to</param> /// <param name="cssBlock">the css block to add</param> public void AddCssBlock(string media, CssBlock cssBlock) { Dictionary<string, List<CssBlock>> mid; if (!_mediaBlocks.TryGetValue(media, out mid)) { mid = new Dictionary<string, List<CssBlock>>(StringComparer.InvariantCultureIgnoreCase); _mediaBlocks.Add(media, mid); } if (!mid.ContainsKey(cssBlock.Class)) { var list = new List<CssBlock>(); list.Add(cssBlock); mid[cssBlock.Class] = list; } else { bool merged = false; var list = mid[cssBlock.Class]; foreach (var block in list) { if (block.EqualsSelector(cssBlock)) { merged = true; block.Merge(cssBlock); break; } } if (!merged) { // general block must be first if (cssBlock.Selectors == null) list.Insert(0, cssBlock); else list.Add(cssBlock); } } } /// <summary> /// Combine this CSS data blocks with <paramref name="other"/> CSS blocks for each media.<br/> /// Merge blocks if exists in both. /// </summary> /// <param name="other">the CSS data to combine with</param> public void Combine(CssData other) { ArgChecker.AssertArgNotNull(other, "other"); // for each media block foreach (var mediaBlock in other.MediaBlocks) { // for each css class in the media block foreach (var bla in mediaBlock.Value) { // for each css block of the css class foreach (var cssBlock in bla.Value) { // combine with this AddCssBlock(mediaBlock.Key, cssBlock); } } } } /// <summary> /// Create deep copy of the css data with cloned css blocks. /// </summary> /// <returns>cloned object</returns> public CssData Clone() { var clone = new CssData(); foreach (var mid in _mediaBlocks) { var cloneMid = new Dictionary<string, List<CssBlock>>(StringComparer.InvariantCultureIgnoreCase); foreach (var blocks in mid.Value) { var cloneList = new List<CssBlock>(); foreach (var cssBlock in blocks.Value) { cloneList.Add(cssBlock.Clone()); } cloneMid[blocks.Key] = cloneList; } clone._mediaBlocks[mid.Key] = cloneMid; } return clone; } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// FDT Financial Raw Import Table Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class FDT_IMPDataSet : EduHubDataSet<FDT_IMP> { /// <inheritdoc /> public override string Name { get { return "FDT_IMP"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal FDT_IMPDataSet(EduHubContext Context) : base(Context) { Index_FDTKEY = new Lazy<Dictionary<int, FDT_IMP>>(() => this.ToDictionary(i => i.FDTKEY)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="FDT_IMP" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="FDT_IMP" /> fields for each CSV column header</returns> internal override Action<FDT_IMP, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<FDT_IMP, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "FDTKEY": mapper[i] = (e, v) => e.FDTKEY = int.Parse(v); break; case "SOURCE": mapper[i] = (e, v) => e.SOURCE = v; break; case "SOURCE_TABLE": mapper[i] = (e, v) => e.SOURCE_TABLE = v; break; case "FIELD01": mapper[i] = (e, v) => e.FIELD01 = v; break; case "FIELD02": mapper[i] = (e, v) => e.FIELD02 = v; break; case "FIELD03": mapper[i] = (e, v) => e.FIELD03 = v; break; case "FIELD04": mapper[i] = (e, v) => e.FIELD04 = v; break; case "FIELD05": mapper[i] = (e, v) => e.FIELD05 = v; break; case "FIELD06": mapper[i] = (e, v) => e.FIELD06 = v; break; case "FIELD07": mapper[i] = (e, v) => e.FIELD07 = v; break; case "FIELD08": mapper[i] = (e, v) => e.FIELD08 = v; break; case "FIELD09": mapper[i] = (e, v) => e.FIELD09 = v; break; case "FIELD10": mapper[i] = (e, v) => e.FIELD10 = v; break; case "FIELD11": mapper[i] = (e, v) => e.FIELD11 = v; break; case "FIELD12": mapper[i] = (e, v) => e.FIELD12 = v; break; case "FIELD13": mapper[i] = (e, v) => e.FIELD13 = v; break; case "FIELD14": mapper[i] = (e, v) => e.FIELD14 = v; break; case "FIELD15": mapper[i] = (e, v) => e.FIELD15 = v; break; case "FIELD16": mapper[i] = (e, v) => e.FIELD16 = v; break; case "FIELD17": mapper[i] = (e, v) => e.FIELD17 = v; break; case "FIELD18": mapper[i] = (e, v) => e.FIELD18 = v; break; case "FIELD19": mapper[i] = (e, v) => e.FIELD19 = v; break; case "FIELD20": mapper[i] = (e, v) => e.FIELD20 = v; break; case "FIELD21": mapper[i] = (e, v) => e.FIELD21 = v; break; case "FIELD22": mapper[i] = (e, v) => e.FIELD22 = v; break; case "FIELD23": mapper[i] = (e, v) => e.FIELD23 = v; break; case "FIELD24": mapper[i] = (e, v) => e.FIELD24 = v; break; case "FIELD25": mapper[i] = (e, v) => e.FIELD25 = v; break; case "FIELD26": mapper[i] = (e, v) => e.FIELD26 = v; break; case "FIELD27": mapper[i] = (e, v) => e.FIELD27 = v; break; case "FIELD28": mapper[i] = (e, v) => e.FIELD28 = v; break; case "FIELD29": mapper[i] = (e, v) => e.FIELD29 = v; break; case "FIELD30": mapper[i] = (e, v) => e.FIELD30 = v; break; case "FIELD31": mapper[i] = (e, v) => e.FIELD31 = v; break; case "FIELD32": mapper[i] = (e, v) => e.FIELD32 = v; break; case "FIELD33": mapper[i] = (e, v) => e.FIELD33 = v; break; case "FIELD34": mapper[i] = (e, v) => e.FIELD34 = v; break; case "FIELD35": mapper[i] = (e, v) => e.FIELD35 = v; break; case "FIELD36": mapper[i] = (e, v) => e.FIELD36 = v; break; case "FIELD37": mapper[i] = (e, v) => e.FIELD37 = v; break; case "FIELD38": mapper[i] = (e, v) => e.FIELD38 = v; break; case "FIELD39": mapper[i] = (e, v) => e.FIELD39 = v; break; case "FIELD40": mapper[i] = (e, v) => e.FIELD40 = v; break; case "FIELD41": mapper[i] = (e, v) => e.FIELD41 = v; break; case "FIELD42": mapper[i] = (e, v) => e.FIELD42 = v; break; case "FIELD43": mapper[i] = (e, v) => e.FIELD43 = v; break; case "FIELD44": mapper[i] = (e, v) => e.FIELD44 = v; break; case "FIELD45": mapper[i] = (e, v) => e.FIELD45 = v; break; case "FIELD46": mapper[i] = (e, v) => e.FIELD46 = v; break; case "FIELD47": mapper[i] = (e, v) => e.FIELD47 = v; break; case "FIELD48": mapper[i] = (e, v) => e.FIELD48 = v; break; case "FIELD49": mapper[i] = (e, v) => e.FIELD49 = v; break; case "NOTES01": mapper[i] = (e, v) => e.NOTES01 = v; break; case "NOTES02": mapper[i] = (e, v) => e.NOTES02 = v; break; case "NOTES03": mapper[i] = (e, v) => e.NOTES03 = v; break; case "NOTES04": mapper[i] = (e, v) => e.NOTES04 = v; break; case "ITEM_PIC": mapper[i] = (e, v) => e.ITEM_PIC = null; // eduHub is not encoding byte arrays break; case "FDT_SOURCE": mapper[i] = (e, v) => e.FDT_SOURCE = v; break; case "FDT_DEST": mapper[i] = (e, v) => e.FDT_DEST = v; break; case "FDT_DEST_ID": mapper[i] = (e, v) => e.FDT_DEST_ID = v; break; case "FDT_EXP_DATE": mapper[i] = (e, v) => e.FDT_EXP_DATE = v; break; case "FDT_EXP_TIME": mapper[i] = (e, v) => e.FDT_EXP_TIME = v; break; case "FDT_COMMENT": mapper[i] = (e, v) => e.FDT_COMMENT = v; break; case "CURRENT_VER": mapper[i] = (e, v) => e.CURRENT_VER = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="FDT_IMP" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="FDT_IMP" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="FDT_IMP" /> entities</param> /// <returns>A merged <see cref="IEnumerable{FDT_IMP}"/> of entities</returns> internal override IEnumerable<FDT_IMP> ApplyDeltaEntities(IEnumerable<FDT_IMP> Entities, List<FDT_IMP> DeltaEntities) { HashSet<int> Index_FDTKEY = new HashSet<int>(DeltaEntities.Select(i => i.FDTKEY)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.FDTKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_FDTKEY.Remove(entity.FDTKEY); if (entity.FDTKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<int, FDT_IMP>> Index_FDTKEY; #endregion #region Index Methods /// <summary> /// Find FDT_IMP by FDTKEY field /// </summary> /// <param name="FDTKEY">FDTKEY value used to find FDT_IMP</param> /// <returns>Related FDT_IMP entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public FDT_IMP FindByFDTKEY(int FDTKEY) { return Index_FDTKEY.Value[FDTKEY]; } /// <summary> /// Attempt to find FDT_IMP by FDTKEY field /// </summary> /// <param name="FDTKEY">FDTKEY value used to find FDT_IMP</param> /// <param name="Value">Related FDT_IMP entity</param> /// <returns>True if the related FDT_IMP entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByFDTKEY(int FDTKEY, out FDT_IMP Value) { return Index_FDTKEY.Value.TryGetValue(FDTKEY, out Value); } /// <summary> /// Attempt to find FDT_IMP by FDTKEY field /// </summary> /// <param name="FDTKEY">FDTKEY value used to find FDT_IMP</param> /// <returns>Related FDT_IMP entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public FDT_IMP TryFindByFDTKEY(int FDTKEY) { FDT_IMP value; if (Index_FDTKEY.Value.TryGetValue(FDTKEY, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a FDT_IMP table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FDT_IMP]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[FDT_IMP]( [FDTKEY] int IDENTITY NOT NULL, [SOURCE] varchar(8) NULL, [SOURCE_TABLE] varchar(8) NULL, [FIELD01] varchar(60) NULL, [FIELD02] varchar(60) NULL, [FIELD03] varchar(60) NULL, [FIELD04] varchar(60) NULL, [FIELD05] varchar(60) NULL, [FIELD06] varchar(60) NULL, [FIELD07] varchar(60) NULL, [FIELD08] varchar(60) NULL, [FIELD09] varchar(60) NULL, [FIELD10] varchar(60) NULL, [FIELD11] varchar(60) NULL, [FIELD12] varchar(60) NULL, [FIELD13] varchar(60) NULL, [FIELD14] varchar(60) NULL, [FIELD15] varchar(60) NULL, [FIELD16] varchar(60) NULL, [FIELD17] varchar(60) NULL, [FIELD18] varchar(60) NULL, [FIELD19] varchar(60) NULL, [FIELD20] varchar(60) NULL, [FIELD21] varchar(60) NULL, [FIELD22] varchar(60) NULL, [FIELD23] varchar(60) NULL, [FIELD24] varchar(60) NULL, [FIELD25] varchar(60) NULL, [FIELD26] varchar(60) NULL, [FIELD27] varchar(60) NULL, [FIELD28] varchar(60) NULL, [FIELD29] varchar(60) NULL, [FIELD30] varchar(60) NULL, [FIELD31] varchar(60) NULL, [FIELD32] varchar(60) NULL, [FIELD33] varchar(60) NULL, [FIELD34] varchar(60) NULL, [FIELD35] varchar(60) NULL, [FIELD36] varchar(60) NULL, [FIELD37] varchar(60) NULL, [FIELD38] varchar(60) NULL, [FIELD39] varchar(60) NULL, [FIELD40] varchar(60) NULL, [FIELD41] varchar(60) NULL, [FIELD42] varchar(60) NULL, [FIELD43] varchar(60) NULL, [FIELD44] varchar(60) NULL, [FIELD45] varchar(60) NULL, [FIELD46] varchar(60) NULL, [FIELD47] varchar(60) NULL, [FIELD48] varchar(60) NULL, [FIELD49] varchar(60) NULL, [NOTES01] varchar(MAX) NULL, [NOTES02] varchar(MAX) NULL, [NOTES03] varchar(MAX) NULL, [NOTES04] varchar(MAX) NULL, [ITEM_PIC] varbinary(MAX) NULL, [FDT_SOURCE] varchar(8) NULL, [FDT_DEST] varchar(8) NULL, [FDT_DEST_ID] varchar(8) NULL, [FDT_EXP_DATE] varchar(20) NULL, [FDT_EXP_TIME] varchar(8) NULL, [FDT_COMMENT] varchar(MAX) NULL, [CURRENT_VER] varchar(10) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [FDT_IMP_Index_FDTKEY] PRIMARY KEY CLUSTERED ( [FDTKEY] ASC ) ); END"); } /// <summary> /// Returns null as <see cref="FDT_IMPDataSet"/> has no non-clustered indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>null</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return null; } /// <summary> /// Returns null as <see cref="FDT_IMPDataSet"/> has no non-clustered indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>null</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return null; } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="FDT_IMP"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="FDT_IMP"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<FDT_IMP> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_FDTKEY = new List<int>(); foreach (var entity in Entities) { Index_FDTKEY.Add(entity.FDTKEY); } builder.AppendLine("DELETE [dbo].[FDT_IMP] WHERE"); // Index_FDTKEY builder.Append("[FDTKEY] IN ("); for (int index = 0; index < Index_FDTKEY.Count; index++) { if (index != 0) builder.Append(", "); // FDTKEY var parameterFDTKEY = $"@p{parameterIndex++}"; builder.Append(parameterFDTKEY); command.Parameters.Add(parameterFDTKEY, SqlDbType.Int).Value = Index_FDTKEY[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the FDT_IMP data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the FDT_IMP data set</returns> public override EduHubDataSetDataReader<FDT_IMP> GetDataSetDataReader() { return new FDT_IMPDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the FDT_IMP data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the FDT_IMP data set</returns> public override EduHubDataSetDataReader<FDT_IMP> GetDataSetDataReader(List<FDT_IMP> Entities) { return new FDT_IMPDataReader(new EduHubDataSetLoadedReader<FDT_IMP>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class FDT_IMPDataReader : EduHubDataSetDataReader<FDT_IMP> { public FDT_IMPDataReader(IEduHubDataSetReader<FDT_IMP> Reader) : base (Reader) { } public override int FieldCount { get { return 67; } } public override object GetValue(int i) { switch (i) { case 0: // FDTKEY return Current.FDTKEY; case 1: // SOURCE return Current.SOURCE; case 2: // SOURCE_TABLE return Current.SOURCE_TABLE; case 3: // FIELD01 return Current.FIELD01; case 4: // FIELD02 return Current.FIELD02; case 5: // FIELD03 return Current.FIELD03; case 6: // FIELD04 return Current.FIELD04; case 7: // FIELD05 return Current.FIELD05; case 8: // FIELD06 return Current.FIELD06; case 9: // FIELD07 return Current.FIELD07; case 10: // FIELD08 return Current.FIELD08; case 11: // FIELD09 return Current.FIELD09; case 12: // FIELD10 return Current.FIELD10; case 13: // FIELD11 return Current.FIELD11; case 14: // FIELD12 return Current.FIELD12; case 15: // FIELD13 return Current.FIELD13; case 16: // FIELD14 return Current.FIELD14; case 17: // FIELD15 return Current.FIELD15; case 18: // FIELD16 return Current.FIELD16; case 19: // FIELD17 return Current.FIELD17; case 20: // FIELD18 return Current.FIELD18; case 21: // FIELD19 return Current.FIELD19; case 22: // FIELD20 return Current.FIELD20; case 23: // FIELD21 return Current.FIELD21; case 24: // FIELD22 return Current.FIELD22; case 25: // FIELD23 return Current.FIELD23; case 26: // FIELD24 return Current.FIELD24; case 27: // FIELD25 return Current.FIELD25; case 28: // FIELD26 return Current.FIELD26; case 29: // FIELD27 return Current.FIELD27; case 30: // FIELD28 return Current.FIELD28; case 31: // FIELD29 return Current.FIELD29; case 32: // FIELD30 return Current.FIELD30; case 33: // FIELD31 return Current.FIELD31; case 34: // FIELD32 return Current.FIELD32; case 35: // FIELD33 return Current.FIELD33; case 36: // FIELD34 return Current.FIELD34; case 37: // FIELD35 return Current.FIELD35; case 38: // FIELD36 return Current.FIELD36; case 39: // FIELD37 return Current.FIELD37; case 40: // FIELD38 return Current.FIELD38; case 41: // FIELD39 return Current.FIELD39; case 42: // FIELD40 return Current.FIELD40; case 43: // FIELD41 return Current.FIELD41; case 44: // FIELD42 return Current.FIELD42; case 45: // FIELD43 return Current.FIELD43; case 46: // FIELD44 return Current.FIELD44; case 47: // FIELD45 return Current.FIELD45; case 48: // FIELD46 return Current.FIELD46; case 49: // FIELD47 return Current.FIELD47; case 50: // FIELD48 return Current.FIELD48; case 51: // FIELD49 return Current.FIELD49; case 52: // NOTES01 return Current.NOTES01; case 53: // NOTES02 return Current.NOTES02; case 54: // NOTES03 return Current.NOTES03; case 55: // NOTES04 return Current.NOTES04; case 56: // ITEM_PIC return Current.ITEM_PIC; case 57: // FDT_SOURCE return Current.FDT_SOURCE; case 58: // FDT_DEST return Current.FDT_DEST; case 59: // FDT_DEST_ID return Current.FDT_DEST_ID; case 60: // FDT_EXP_DATE return Current.FDT_EXP_DATE; case 61: // FDT_EXP_TIME return Current.FDT_EXP_TIME; case 62: // FDT_COMMENT return Current.FDT_COMMENT; case 63: // CURRENT_VER return Current.CURRENT_VER; case 64: // LW_DATE return Current.LW_DATE; case 65: // LW_TIME return Current.LW_TIME; case 66: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // SOURCE return Current.SOURCE == null; case 2: // SOURCE_TABLE return Current.SOURCE_TABLE == null; case 3: // FIELD01 return Current.FIELD01 == null; case 4: // FIELD02 return Current.FIELD02 == null; case 5: // FIELD03 return Current.FIELD03 == null; case 6: // FIELD04 return Current.FIELD04 == null; case 7: // FIELD05 return Current.FIELD05 == null; case 8: // FIELD06 return Current.FIELD06 == null; case 9: // FIELD07 return Current.FIELD07 == null; case 10: // FIELD08 return Current.FIELD08 == null; case 11: // FIELD09 return Current.FIELD09 == null; case 12: // FIELD10 return Current.FIELD10 == null; case 13: // FIELD11 return Current.FIELD11 == null; case 14: // FIELD12 return Current.FIELD12 == null; case 15: // FIELD13 return Current.FIELD13 == null; case 16: // FIELD14 return Current.FIELD14 == null; case 17: // FIELD15 return Current.FIELD15 == null; case 18: // FIELD16 return Current.FIELD16 == null; case 19: // FIELD17 return Current.FIELD17 == null; case 20: // FIELD18 return Current.FIELD18 == null; case 21: // FIELD19 return Current.FIELD19 == null; case 22: // FIELD20 return Current.FIELD20 == null; case 23: // FIELD21 return Current.FIELD21 == null; case 24: // FIELD22 return Current.FIELD22 == null; case 25: // FIELD23 return Current.FIELD23 == null; case 26: // FIELD24 return Current.FIELD24 == null; case 27: // FIELD25 return Current.FIELD25 == null; case 28: // FIELD26 return Current.FIELD26 == null; case 29: // FIELD27 return Current.FIELD27 == null; case 30: // FIELD28 return Current.FIELD28 == null; case 31: // FIELD29 return Current.FIELD29 == null; case 32: // FIELD30 return Current.FIELD30 == null; case 33: // FIELD31 return Current.FIELD31 == null; case 34: // FIELD32 return Current.FIELD32 == null; case 35: // FIELD33 return Current.FIELD33 == null; case 36: // FIELD34 return Current.FIELD34 == null; case 37: // FIELD35 return Current.FIELD35 == null; case 38: // FIELD36 return Current.FIELD36 == null; case 39: // FIELD37 return Current.FIELD37 == null; case 40: // FIELD38 return Current.FIELD38 == null; case 41: // FIELD39 return Current.FIELD39 == null; case 42: // FIELD40 return Current.FIELD40 == null; case 43: // FIELD41 return Current.FIELD41 == null; case 44: // FIELD42 return Current.FIELD42 == null; case 45: // FIELD43 return Current.FIELD43 == null; case 46: // FIELD44 return Current.FIELD44 == null; case 47: // FIELD45 return Current.FIELD45 == null; case 48: // FIELD46 return Current.FIELD46 == null; case 49: // FIELD47 return Current.FIELD47 == null; case 50: // FIELD48 return Current.FIELD48 == null; case 51: // FIELD49 return Current.FIELD49 == null; case 52: // NOTES01 return Current.NOTES01 == null; case 53: // NOTES02 return Current.NOTES02 == null; case 54: // NOTES03 return Current.NOTES03 == null; case 55: // NOTES04 return Current.NOTES04 == null; case 56: // ITEM_PIC return Current.ITEM_PIC == null; case 57: // FDT_SOURCE return Current.FDT_SOURCE == null; case 58: // FDT_DEST return Current.FDT_DEST == null; case 59: // FDT_DEST_ID return Current.FDT_DEST_ID == null; case 60: // FDT_EXP_DATE return Current.FDT_EXP_DATE == null; case 61: // FDT_EXP_TIME return Current.FDT_EXP_TIME == null; case 62: // FDT_COMMENT return Current.FDT_COMMENT == null; case 63: // CURRENT_VER return Current.CURRENT_VER == null; case 64: // LW_DATE return Current.LW_DATE == null; case 65: // LW_TIME return Current.LW_TIME == null; case 66: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // FDTKEY return "FDTKEY"; case 1: // SOURCE return "SOURCE"; case 2: // SOURCE_TABLE return "SOURCE_TABLE"; case 3: // FIELD01 return "FIELD01"; case 4: // FIELD02 return "FIELD02"; case 5: // FIELD03 return "FIELD03"; case 6: // FIELD04 return "FIELD04"; case 7: // FIELD05 return "FIELD05"; case 8: // FIELD06 return "FIELD06"; case 9: // FIELD07 return "FIELD07"; case 10: // FIELD08 return "FIELD08"; case 11: // FIELD09 return "FIELD09"; case 12: // FIELD10 return "FIELD10"; case 13: // FIELD11 return "FIELD11"; case 14: // FIELD12 return "FIELD12"; case 15: // FIELD13 return "FIELD13"; case 16: // FIELD14 return "FIELD14"; case 17: // FIELD15 return "FIELD15"; case 18: // FIELD16 return "FIELD16"; case 19: // FIELD17 return "FIELD17"; case 20: // FIELD18 return "FIELD18"; case 21: // FIELD19 return "FIELD19"; case 22: // FIELD20 return "FIELD20"; case 23: // FIELD21 return "FIELD21"; case 24: // FIELD22 return "FIELD22"; case 25: // FIELD23 return "FIELD23"; case 26: // FIELD24 return "FIELD24"; case 27: // FIELD25 return "FIELD25"; case 28: // FIELD26 return "FIELD26"; case 29: // FIELD27 return "FIELD27"; case 30: // FIELD28 return "FIELD28"; case 31: // FIELD29 return "FIELD29"; case 32: // FIELD30 return "FIELD30"; case 33: // FIELD31 return "FIELD31"; case 34: // FIELD32 return "FIELD32"; case 35: // FIELD33 return "FIELD33"; case 36: // FIELD34 return "FIELD34"; case 37: // FIELD35 return "FIELD35"; case 38: // FIELD36 return "FIELD36"; case 39: // FIELD37 return "FIELD37"; case 40: // FIELD38 return "FIELD38"; case 41: // FIELD39 return "FIELD39"; case 42: // FIELD40 return "FIELD40"; case 43: // FIELD41 return "FIELD41"; case 44: // FIELD42 return "FIELD42"; case 45: // FIELD43 return "FIELD43"; case 46: // FIELD44 return "FIELD44"; case 47: // FIELD45 return "FIELD45"; case 48: // FIELD46 return "FIELD46"; case 49: // FIELD47 return "FIELD47"; case 50: // FIELD48 return "FIELD48"; case 51: // FIELD49 return "FIELD49"; case 52: // NOTES01 return "NOTES01"; case 53: // NOTES02 return "NOTES02"; case 54: // NOTES03 return "NOTES03"; case 55: // NOTES04 return "NOTES04"; case 56: // ITEM_PIC return "ITEM_PIC"; case 57: // FDT_SOURCE return "FDT_SOURCE"; case 58: // FDT_DEST return "FDT_DEST"; case 59: // FDT_DEST_ID return "FDT_DEST_ID"; case 60: // FDT_EXP_DATE return "FDT_EXP_DATE"; case 61: // FDT_EXP_TIME return "FDT_EXP_TIME"; case 62: // FDT_COMMENT return "FDT_COMMENT"; case 63: // CURRENT_VER return "CURRENT_VER"; case 64: // LW_DATE return "LW_DATE"; case 65: // LW_TIME return "LW_TIME"; case 66: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "FDTKEY": return 0; case "SOURCE": return 1; case "SOURCE_TABLE": return 2; case "FIELD01": return 3; case "FIELD02": return 4; case "FIELD03": return 5; case "FIELD04": return 6; case "FIELD05": return 7; case "FIELD06": return 8; case "FIELD07": return 9; case "FIELD08": return 10; case "FIELD09": return 11; case "FIELD10": return 12; case "FIELD11": return 13; case "FIELD12": return 14; case "FIELD13": return 15; case "FIELD14": return 16; case "FIELD15": return 17; case "FIELD16": return 18; case "FIELD17": return 19; case "FIELD18": return 20; case "FIELD19": return 21; case "FIELD20": return 22; case "FIELD21": return 23; case "FIELD22": return 24; case "FIELD23": return 25; case "FIELD24": return 26; case "FIELD25": return 27; case "FIELD26": return 28; case "FIELD27": return 29; case "FIELD28": return 30; case "FIELD29": return 31; case "FIELD30": return 32; case "FIELD31": return 33; case "FIELD32": return 34; case "FIELD33": return 35; case "FIELD34": return 36; case "FIELD35": return 37; case "FIELD36": return 38; case "FIELD37": return 39; case "FIELD38": return 40; case "FIELD39": return 41; case "FIELD40": return 42; case "FIELD41": return 43; case "FIELD42": return 44; case "FIELD43": return 45; case "FIELD44": return 46; case "FIELD45": return 47; case "FIELD46": return 48; case "FIELD47": return 49; case "FIELD48": return 50; case "FIELD49": return 51; case "NOTES01": return 52; case "NOTES02": return 53; case "NOTES03": return 54; case "NOTES04": return 55; case "ITEM_PIC": return 56; case "FDT_SOURCE": return 57; case "FDT_DEST": return 58; case "FDT_DEST_ID": return 59; case "FDT_EXP_DATE": return 60; case "FDT_EXP_TIME": return 61; case "FDT_COMMENT": return 62; case "CURRENT_VER": return 63; case "LW_DATE": return 64; case "LW_TIME": return 65; case "LW_USER": return 66; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
// // https://github.com/ServiceStack/ServiceStack.Text // ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers. // // Authors: // Demis Bellot (demis.bellot@gmail.com) // // Copyright 2012 Service Stack LLC. All Rights Reserved. // // Licensed under the same terms of ServiceStack. // using System; using System.Linq; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using System.Threading; using ServiceStack.Text.Json; namespace ServiceStack.Text.Common { public static class DeserializeListWithElements<TSerializer> where TSerializer : ITypeSerializer { internal static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>(); private static Dictionary<Type, ParseListDelegate> ParseDelegateCache = new Dictionary<Type, ParseListDelegate>(); private delegate object ParseListDelegate(string value, Type createListType, ParseStringDelegate parseFn); public static Func<string, Type, ParseStringDelegate, object> GetListTypeParseFn( Type createListType, Type elementType, ParseStringDelegate parseFn) { ParseListDelegate parseDelegate; if (ParseDelegateCache.TryGetValue(elementType, out parseDelegate)) return parseDelegate.Invoke; var genericType = typeof(DeserializeListWithElements<,>).MakeGenericType(elementType, typeof(TSerializer)); var mi = genericType.GetStaticMethod("ParseGenericList"); parseDelegate = (ParseListDelegate)mi.MakeDelegate(typeof(ParseListDelegate)); Dictionary<Type, ParseListDelegate> snapshot, newCache; do { snapshot = ParseDelegateCache; newCache = new Dictionary<Type, ParseListDelegate>(ParseDelegateCache); newCache[elementType] = parseDelegate; } while (!ReferenceEquals( Interlocked.CompareExchange(ref ParseDelegateCache, newCache, snapshot), snapshot)); return parseDelegate.Invoke; } public static string StripList(string value) { if (string.IsNullOrEmpty(value)) return null; value = value.TrimEnd(); const int startQuotePos = 1; const int endQuotePos = 2; var ret = value[0] == JsWriter.ListStartChar ? value.Substring(startQuotePos, value.Length - endQuotePos) : value; var pos = 0; Serializer.EatWhitespace(ret, ref pos); return ret.Substring(pos, ret.Length - pos); } public static List<string> ParseStringList(string value) { if ((value = StripList(value)) == null) return null; if (value == string.Empty) return new List<string>(); var to = new List<string>(); var valueLength = value.Length; var i = 0; while (i < valueLength) { var elementValue = Serializer.EatValue(value, ref i); var listValue = Serializer.UnescapeString(elementValue); to.Add(listValue); if (Serializer.EatItemSeperatorOrMapEndChar(value, ref i) && i == valueLength) { // If we ate a separator and we are at the end of the value, // it means the last element is empty => add default to.Add(null); } } return to; } public static List<int> ParseIntList(string value) { if ((value = StripList(value)) == null) return null; if (value == string.Empty) return new List<int>(); var intParts = value.Split(JsWriter.ItemSeperator); var intValues = new List<int>(intParts.Length); foreach (var intPart in intParts) { intValues.Add(int.Parse(intPart)); } return intValues; } } public static class DeserializeListWithElements<T, TSerializer> where TSerializer : ITypeSerializer { private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>(); public static ICollection<T> ParseGenericList(string value, Type createListType, ParseStringDelegate parseFn) { if ((value = DeserializeListWithElements<TSerializer>.StripList(value)) == null) return null; var isReadOnly = createListType != null && (createListType.IsGeneric() && createListType.GenericTypeDefinition() == typeof(ReadOnlyCollection<>)); var to = (createListType == null || isReadOnly) ? new List<T>() : (ICollection<T>)createListType.CreateInstance(); if (value == string.Empty) return to; var tryToParseItemsAsPrimitiveTypes = JsConfig.TryToParsePrimitiveTypeValues && typeof(T) == typeof(object); if (!string.IsNullOrEmpty(value)) { var valueLength = value.Length; var i = 0; Serializer.EatWhitespace(value, ref i); if (i < valueLength && value[i] == JsWriter.MapStartChar) { do { var itemValue = Serializer.EatTypeValue(value, ref i); to.Add((T)parseFn(itemValue)); Serializer.EatWhitespace(value, ref i); } while (++i < value.Length); } else { while (i < valueLength) { var startIndex = i; var elementValue = Serializer.EatValue(value, ref i); var listValue = elementValue; if (listValue != null) { if (tryToParseItemsAsPrimitiveTypes) { Serializer.EatWhitespace(value, ref startIndex); to.Add((T)DeserializeType<TSerializer>.ParsePrimitive(elementValue, value[startIndex])); } else { to.Add((T)parseFn(elementValue)); } } if (Serializer.EatItemSeperatorOrMapEndChar(value, ref i) && i == valueLength) { // If we ate a separator and we are at the end of the value, // it means the last element is empty => add default to.Add(default(T)); continue; } if (listValue == null) to.Add(default(T)); } } } //TODO: 8-10-2011 -- this CreateInstance call should probably be moved over to ReflectionExtensions, //but not sure how you'd like to go about caching constructors with parameters -- I would probably build a NewExpression, .Compile to a LambdaExpression and cache return isReadOnly ? (ICollection<T>)Activator.CreateInstance(createListType, to) : to; } } public static class DeserializeList<T, TSerializer> where TSerializer : ITypeSerializer { private readonly static ParseStringDelegate CacheFn; static DeserializeList() { CacheFn = GetParseFn(); } public static ParseStringDelegate Parse { get { return CacheFn; } } public static ParseStringDelegate GetParseFn() { var listInterface = typeof(T).GetTypeWithGenericInterfaceOf(typeof(IList<>)); if (listInterface == null) throw new ArgumentException(string.Format("Type {0} is not of type IList<>", typeof(T).FullName)); //optimized access for regularly used types if (typeof(T) == typeof(List<string>)) return DeserializeListWithElements<TSerializer>.ParseStringList; if (typeof(T) == typeof(List<int>)) return DeserializeListWithElements<TSerializer>.ParseIntList; var elementType = listInterface.GenericTypeArguments()[0]; var supportedTypeParseMethod = DeserializeListWithElements<TSerializer>.Serializer.GetParseFn(elementType); if (supportedTypeParseMethod != null) { var createListType = typeof(T).HasAnyTypeDefinitionsOf(typeof(List<>), typeof(IList<>)) ? null : typeof(T); var parseFn = DeserializeListWithElements<TSerializer>.GetListTypeParseFn(createListType, elementType, supportedTypeParseMethod); return value => parseFn(value, createListType, supportedTypeParseMethod); } return null; } } internal static class DeserializeEnumerable<T, TSerializer> where TSerializer : ITypeSerializer { private readonly static ParseStringDelegate CacheFn; static DeserializeEnumerable() { CacheFn = GetParseFn(); } public static ParseStringDelegate Parse { get { return CacheFn; } } public static ParseStringDelegate GetParseFn() { var enumerableInterface = typeof(T).GetTypeWithGenericInterfaceOf(typeof(IEnumerable<>)); if (enumerableInterface == null) throw new ArgumentException(string.Format("Type {0} is not of type IEnumerable<>", typeof(T).FullName)); //optimized access for regularly used types if (typeof(T) == typeof(IEnumerable<string>)) return DeserializeListWithElements<TSerializer>.ParseStringList; if (typeof(T) == typeof(IEnumerable<int>)) return DeserializeListWithElements<TSerializer>.ParseIntList; var elementType = enumerableInterface.GenericTypeArguments()[0]; var supportedTypeParseMethod = DeserializeListWithElements<TSerializer>.Serializer.GetParseFn(elementType); if (supportedTypeParseMethod != null) { const Type createListTypeWithNull = null; //Use conversions outside this class. see: Queue var parseFn = DeserializeListWithElements<TSerializer>.GetListTypeParseFn( createListTypeWithNull, elementType, supportedTypeParseMethod); return value => parseFn(value, createListTypeWithNull, supportedTypeParseMethod); } return null; } } }
// Author: // Allis Tauri <allista@gmail.com> // // Copyright (c) 2015 Allis Tauri // // This work is licensed under the Creative Commons Attribution-ShareAlike 4.0 International License. // To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/4.0/ // or send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. #if DEBUG using System; using System.IO; using System.Linq; using System.Text; using System.Collections.Generic; using System.Diagnostics; using UnityEngine; namespace AT_Utils { public static class DebugUtils { public static void CSV(string filename, params object[] args) { var row = new StringBuilder(); var len = args.Length; var last_i = len-1; for(int i = 0; i < len; i++) { var arg = args[i]; if(arg is Vector2) { var v = (Vector2)arg; row.Append(v.x); row.Append(","); row.Append(v.y); } else if(arg is Vector2d) { var v = (Vector2d)arg; row.Append(v.x); row.Append(","); row.Append(v.y); } else if(arg is Vector3) { var v = (Vector3)arg; row.Append(v.x); row.Append(","); row.Append(v.y); row.Append(","); row.Append(v.z); } else if(arg is Vector3d) { var v = (Vector3d)arg; row.Append(v.x); row.Append(","); row.Append(v.y); row.Append(","); row.Append(v.z); } else if(arg is Vector4) { var v = (Vector4)arg; row.Append(v.x); row.Append(","); row.Append(v.y); row.Append(","); row.Append(v.z); row.Append(","); row.Append(v.w); } else if(arg is Vector4d) { var v = (Vector4d)arg; row.Append(v.x); row.Append(","); row.Append(v.y); row.Append(","); row.Append(v.z); row.Append(","); row.Append(v.w); } else if(arg is string) { row.Append("\""); row.Append(arg); row.Append("\""); } else row.Append(arg); if(i < last_i) row.Append(", "); } using(var f = new StreamWriter(filename, true)) f.WriteLine(row); } public static void logVectors(string tag, bool normalize = true, params Vector3[] vecs) { var s = tag+":\n"; foreach(var v in vecs) { var vn = normalize? v.normalized : v; s += string.Format("({0}, {1}, {2}),\n", vn.x, vn.y, vn.z); } Utils.Log(s); } public static string formatSteering(Vector3 steering) { return Utils.Format("[pitch {}, roll {}, yaw {}]", steering.x, steering.y, steering.z); } public static string formatSteering(FlightCtrlState s) { return Utils.Format("[pitch {}, roll {}, yaw {}]", s.pitch, s.roll, s.yaw); } public static string FormatActions(BaseActionList actions) { return actions.Aggregate("", (s, a) => s + string.Format("{0} ({1}, active: {2}); ", a.guiName, a.actionGroup, a.active)); } public static string getStacktrace(int skip = 0) { return new StackTrace(skip+1, true).ToString(); } public static void Log(string msg, params object[] args) { Utils.Log("{}\n{}", Utils.Format(msg, args), getStacktrace(1)); } public static void logStamp(string msg = "") { Utils.Log("=== " + msg); } public static void logCrewList(List<ProtoCrewMember> crew) { string crew_str = ""; foreach(ProtoCrewMember c in crew) crew_str += string.Format("\n{0}, seat {1}, seatIdx {2}, roster {3}, ref {4}", c.name, c.seat, c.seatIdx, c.rosterStatus, c.KerbalRef); Utils.Log("Crew List:{}", crew_str); } public static Vector3d planetaryPosition(Vector3 v, CelestialBody planet) { double lng = planet.GetLongitude(v); double lat = planet.GetLatitude(v); double alt = planet.GetAltitude(v); return planet.GetWorldSurfacePosition(lat, lng, alt); } public static void logPlanetaryPosition(Vector3 v, CelestialBody planet) { Utils.Log("Planetary position: {}", planetaryPosition(v, planet)); } public static void logLongLatAlt(Vector3 v, CelestialBody planet) { double lng = planet.GetLongitude(v); double lat = planet.GetLatitude(v); double alt = planet.GetAltitude(v); Utils.Log("Long: {}, Lat: {}, Alt: {}", lng, lat, alt); } public static void logProtovesselCrew(ProtoVessel pv) { for(int i = 0; i < pv.protoPartSnapshots.Count; i++) { ProtoPartSnapshot p = pv.protoPartSnapshots[i]; Utils.Log("Part{}: {}", i, p.partName); if(p.partInfo.partPrefab != null) Utils.Log("partInfo.partPrefab.CrewCapacity {}",p.partInfo.partPrefab.CrewCapacity); Utils.Log("partInfo.internalConfig: {}", p.partInfo.internalConfig); Utils.Log("partStateValues.Count: {}", p.partStateValues.Count); foreach(string k in p.partStateValues.Keys) Utils.Log ("{} : {}", k, p.partStateValues[k]); Utils.Log("modules.Count: {}", p.modules.Count); foreach(ProtoPartModuleSnapshot pm in p.modules) Utils.Log("{} : {}", pm.moduleName, pm.moduleValues); foreach(string k in p.partStateValues.Keys) Utils.Log("{} : {}", k, p.partStateValues[k]); Utils.Log("customPartData: {}", p.customPartData); } } public static void logTransfrorm(Transform T) { Utils.Log ( "Transform: {}\n" + "Position: {}\n" + "Rotation: {}\n"+ "Local Position: {}\n" + "Local Rotation: {}", T.name, T.position, T.eulerAngles, T.localPosition, T.localEulerAngles ); } public static string formatTransformTree(Transform T, string indent = "") { var log = new List<string>(); log.Add(string.Format("{0}{1}, scl: {2}, pos: {3}, rot: {4}, active: {5}:{6}\n", indent, T, T.localScale, T.localPosition, T.localRotation.eulerAngles, T.gameObject.activeSelf, T.gameObject.activeInHierarchy)); indent += "\t"; for(int i = 0; i < T.childCount; i++) log.Add(formatTransformTree(T.GetChild(i), indent)); return string.Join("", log.ToArray()); } public static string formatPartJointsTree(Part p, string indent = "") { var count = p.children.Count; var log = new string[count+1]; log[0] = string.Format("{0}{1}: attachJoint [child {2}, parent {3}, host {4}, target {5}]\n", indent, p, p.attachJoint?.Child, p.attachJoint?.Parent, p.attachJoint?.Host, p.attachJoint?.Target); indent += "\t"; for(int i = 0; i < count; i++) log[i+1] = formatPartJointsTree(p.children[i], indent); return string.Join("", log); } public static void logShipConstruct(ShipConstruct ship) { Utils.Log("ShipConstruct: {}\n{}", ship.shipName, ship.parts.Aggregate("", (s, p) => s + p.Title() + "\n")); } //does not work with monodevelop generated .mdb files =( // public static void LogException(Action action) // { // try { action(); } // catch(Exception ex) // { // // Get stack trace for the exception with source file information // var st = new StackTrace(ex, true); // // Get the top stack frame // var frame = st.GetFrame(st.FrameCount-1); // // Log exception coordinates and stacktrace // Utils.Log("\nException in {} at line {}, column {}\n{}", // frame.GetFileName(), frame.GetFileLineNumber(), frame.GetFileColumnNumber(), // st.ToString()); // } // } public static void SetupHullMeshes(this Vessel vessel, Color color) { if(vessel == null) return; foreach(var p in vessel.Parts) { var hull_obj_T = p.partTransform.Find("__HULL_MESH"); if(hull_obj_T != null) continue; var hull_obj = new GameObject("__HULL_MESH", typeof(MeshFilter), typeof(MeshRenderer)); hull_obj.transform.SetParent(p.partTransform, false); var renderer = hull_obj.GetComponent<MeshRenderer>(); renderer.material = Utils.no_z_material; renderer.material.color = color; renderer.enabled = true; var hull_mesh = hull_obj.GetComponent<MeshFilter>(); var pM = new Metric(p, true); hull_mesh.mesh = pM.hull_mesh; hull_obj.transform.rotation = p.partTransform.rotation; hull_obj.SetActive(true); } } } class NamedStopwatch { readonly Stopwatch sw = new Stopwatch(); readonly string name; public NamedStopwatch(string name) { this.name = name; } public double ElapsedSecs { get { return sw.ElapsedTicks/(double)System.Diagnostics.Stopwatch.Frequency; } } public void Start() { Utils.Log("{}: start counting time", name); sw.Start(); } public void Stamp() { Utils.Log("{}: elapsed time: {}us", name, sw.ElapsedTicks/(Stopwatch.Frequency/(1000000L))); } public void Stop() { sw.Stop(); Stamp(); } public void Reset() { sw.Stop(); sw.Reset(); } } class AT_Profiler { class Counter { public long Total { get; protected set; } public uint Count { get; protected set; } public void Add(long val) { Total += val; Count++; } public virtual void Add(Counter c) {} public virtual double Avg { get { return (double)Total/Count; } } public override string ToString() { return string.Format("avg: {0}us", Avg); } } class SumCounter : Counter { double avg; public override double Avg { get { return avg; } } public override void Add(Counter c) { Count = (uint)Mathf.Max(Count, c.Count); avg += c.Avg; } } readonly System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); readonly Dictionary<string, Counter> counters = new Dictionary<string, Counter>(); long last = 0; public void Start() { sw.Stop(); sw.Reset(); sw.Start(); last = 0; } public void Log(string name) { var current = sw.ElapsedTicks/(Stopwatch.Frequency/(1000000L)); Counter v; if(counters.TryGetValue(name, out v)) v.Add(current-last); else { v = new Counter(); v.Add(current-last); counters[name] = v; } last = current; } static void make_report(List<KeyValuePair<string,Counter>> clist) { var report = "\nName, NumCalls, Avg.Time (us)\n"; foreach(var c in clist) report += string.Format("{0}, {1}, {2}\n", c.Key, c.Value.Count, c.Value.Avg); Utils.Log("Profiler Report:{}", report); } public void PlainReport() { var clist = counters.ToList(); clist.Sort((a, b) => b.Value.Avg.CompareTo(a.Value.Avg)); make_report(clist); } public void TreeReport() { var cum_counters = new Dictionary<string, Counter>(); foreach(var c in counters) { cum_counters[c.Key] = c.Value; var names = c.Key.Split(new []{'.'}); var cname = ""; for(int i = 0; i < names.Length-1; i++) { cname += "."+names[i]; Counter v; if(cum_counters.TryGetValue(cname, out v)) v.Add(c.Value); else { v = new SumCounter(); v.Add(c.Value); cum_counters[cname] = v; } } } var clist = cum_counters.ToList(); clist.Sort((a, b) => a.Key.CompareTo(b.Key)); make_report(clist); } } class DebugCounter { int count = 0; string name = ""; public DebugCounter(string name = "Debug", params object[] args) { this.name = string.Format(name, args); } public void Log(string msg="", params object[] args) { if(msg == "") Utils.Log("{}: {}", name, count++); else Utils.Log("{}: {} {}", name, count++, string.Format(msg, args)); } public void Reset() { count = 0; } } public class DebugModuleRCS : ModuleRCS { public override void OnStart(StartState state) { base.OnStart(state); this.Log("ThrusterTransforms:\n{}", thrusterTransforms.Aggregate("", (s, t) => s+t.name+": "+t.position+"\n")); } public new void FixedUpdate() { base.FixedUpdate(); this.Log("Part: enabled {}, shielded {}, controllable {}", enabled, part.ShieldedFromAirstream, part.isControllable); if(thrustForces.Length > 0) { this.Log("ThrustForces:\n{}", thrustForces.Aggregate("", (s, f) => s+f+", ")); this.Log("FX.Power:\n{}", thrusterFX.Aggregate("", (s, f) => s+f.Power+", "+f.Active+"; ")); } } } public class TemperatureReporter : PartModule { [KSPField(isPersistant=false, guiActiveEditor=true, guiActive=true, guiName="T", guiUnits = "C")] public float temperatureDisplay; public override void OnUpdate() { temperatureDisplay = (float)part.temperature; } } } #endif
using UnityEngine; using UnityEngine.Experimental.Rendering.HDPipeline; using UnityEngine.Rendering; namespace UnityEditor.Experimental.Rendering.HDPipeline { using CED = CoreEditorDrawer<SerializedHDRaytracingEnvironment>; [CustomEditor(typeof(HDRaytracingEnvironment))] public class HDRaytracingEnvironmentInspector : Editor { #if ENABLE_RAYTRACING protected static class Styles { // Generic public static readonly GUIContent genericSectionText = EditorGUIUtility.TrTextContent("Generic Attributes"); public static readonly GUIContent rayBiasText = EditorGUIUtility.TrTextContent("Ray Bias"); ///////////////////////////////////////////////////////////////////////////////////////////////// // Ambient Occlusion public static readonly GUIContent aoSectionText = EditorGUIUtility.TrTextContent("Ray-traced Ambient Occlusion"); public static readonly GUIContent aoEnableText = EditorGUIUtility.TrTextContent("Enable"); public static readonly GUIContent aoLayerMaskText = EditorGUIUtility.TrTextContent("AO Layer Mask"); public static readonly GUIContent aoRayLengthText = EditorGUIUtility.TrTextContent("Max AO Ray Length"); public static readonly GUIContent aoNumSamplesText = EditorGUIUtility.TrTextContent("AO Number of Samples"); public static readonly GUIContent aoFilterModeText = EditorGUIUtility.TrTextContent("AO Filter Mode"); // AO Bilateral Filter Data public static GUIContent aoBilateralRadius = new GUIContent("Fitler Radius"); // Nvidia Filter Data public static GUIContent aoNvidiaMaxFilterWidth = new GUIContent("AO Nvidia Max Filter Width"); public static GUIContent aoNvidiaFilterRadius = new GUIContent("AO Nvidia Filter Radius"); public static GUIContent aoNvidiaNormalSharpness = new GUIContent("AO Nvidia Normal Sharpness"); ///////////////////////////////////////////////////////////////////////////////////////////////// // Reflections public static GUIContent reflSectionText = new GUIContent("Ray-traced Reflections"); public static GUIContent reflEnableText = new GUIContent("Enable"); public static GUIContent reflLayerMaskText = EditorGUIUtility.TrTextContent("Reflection Layer Mask"); public static GUIContent reflRayLengthText = new GUIContent("Max Reflections Ray Length"); public static GUIContent reflBlendDistanceText = new GUIContent("Reflection Blend Distance"); public static GUIContent reflMinSmoothnessText = new GUIContent("Reflections Min Smoothness"); public static GUIContent reflClampValueText = new GUIContent("Reflections Clamp Value"); public static GUIContent reflQualityText = new GUIContent("Reflections Quality"); public static GUIContent reflFilerModeText = new GUIContent("Reflections Filter Mode"); // Reflections Quarter Res public static GUIContent reflTemporalAccumulationWeight = new GUIContent("Reflections Temporal Accumulation Weight"); // Relections Integration public static GUIContent reflNumMaxSamplesText = new GUIContent("Reflections Num Samples"); // Filter data public static GUIContent reflFilterRadius = new GUIContent("Filter Radius"); ///////////////////////////////////////////////////////////////////////////////////////////////// // Area Light Shadow public static GUIContent shadowEnableText = new GUIContent("Enable"); public static GUIContent shadowLayerMaskText = EditorGUIUtility.TrTextContent("Shadow Layer Mask"); public static GUIContent shadowSectionText = new GUIContent("Ray-traced Shadows"); public static GUIContent shadowBilateralRadius = new GUIContent("Shadows Bilateral Radius"); public static GUIContent shadowNumSamplesText = new GUIContent("Shadows Num Samples"); public static GUIContent splitIntegrationText = new GUIContent("Split Integration"); // Shadow Bilateral Filter Data public static GUIContent numAreaLightShadows = new GUIContent("Max Num Shadows"); ///////////////////////////////////////////////////////////////////////////////////////////////// // Light Cluster public static readonly GUIContent lightClusterSectionText = EditorGUIUtility.TrTextContent("Light Cluster"); public static GUIContent maxNumLightsText = new GUIContent("Cluster Cell Max Lights"); public static GUIContent cameraClusterRangeText = new GUIContent("Cluster Range"); ///////////////////////////////////////////////////////////////////////////////////////////////// // Primary visibility public static readonly GUIContent primaryRaytracingSectionText = EditorGUIUtility.TrTextContent("Primary Visiblity Raytracing"); public static readonly GUIContent raytracingEnableText = new GUIContent("Enable"); public static readonly GUIContent raytracedLayerMaskText = EditorGUIUtility.TrTextContent("Primary Visibility Layer Mask"); public static readonly GUIContent rayMaxDepth = new GUIContent("Raytracing Maximal Depth"); public static readonly GUIContent raytracingRayLength = new GUIContent("Raytracing Ray Length"); ///////////////////////////////////////////////////////////////////////////////////////////////// // Indirect Diffuse public static readonly GUIContent indirectDiffuseSectionText = EditorGUIUtility.TrTextContent("Indirect Diffuse Raytracing"); public static readonly GUIContent indirectDiffuseEnableText = new GUIContent("Enable"); public static readonly GUIContent indirectDiffuseLayerMaskText = EditorGUIUtility.TrTextContent("Indirect Diffuse Layer Mask"); public static readonly GUIContent indirectDiffuseNumSamplesText = new GUIContent("Indirect Diffuse Num Samples"); public static readonly GUIContent indirectDiffuseRayLengthText = new GUIContent("Indirect Diffuse Ray Length"); public static readonly GUIContent indirectDiffuseClampText = new GUIContent("Indirect Diffuse Clamp Value"); public static readonly GUIContent indirectDiffuseFilterModeText = new GUIContent("Indirect Diffuse Filter Mode"); public static readonly GUIContent indirectDiffuseFilterRadiusText = new GUIContent("Filter Radius"); } SerializedHDRaytracingEnvironment m_SerializedHDRaytracingEnvironment; static readonly CED.IDrawer Inspector; enum Expandable { Generic = 1 << 0, AmbientOcclusion = 1 << 1, Reflection = 1 << 2, LightCluster = 1 << 3, AreaShadow = 1 << 4, PrimaryRaytracing = 1 << 5, IndirectDiffuse = 1 << 6 } static ExpandedState<Expandable, HDRaytracingEnvironment> k_ExpandedState; static HDRaytracingEnvironmentInspector() { Inspector = CED.Group(CED.FoldoutGroup(Styles.genericSectionText, Expandable.Generic, k_ExpandedState, GenericSubMenu), CED.FoldoutGroup(Styles.aoSectionText, Expandable.AmbientOcclusion, k_ExpandedState, AmbientOcclusionSubMenu), CED.FoldoutGroup(Styles.reflSectionText, Expandable.Reflection, k_ExpandedState, ReflectionsSubMenu), CED.FoldoutGroup(Styles.shadowSectionText, Expandable.AreaShadow, k_ExpandedState, AreaShadowSubMenu), CED.FoldoutGroup(Styles.primaryRaytracingSectionText, Expandable.PrimaryRaytracing, k_ExpandedState, RaytracingSubMenu), CED.FoldoutGroup(Styles.indirectDiffuseSectionText, Expandable.IndirectDiffuse, k_ExpandedState, IndirectDiffuseSubMenu), CED.FoldoutGroup(Styles.lightClusterSectionText, Expandable.LightCluster, k_ExpandedState, LightClusterSubMenu)); } static void GenericSubMenu(SerializedHDRaytracingEnvironment rtEnv, Editor owner) { // AO Specific fields EditorGUILayout.PropertyField(rtEnv.rayBias, Styles.rayBiasText); } static void UpdateEnvironmentSubScenes(SerializedHDRaytracingEnvironment rtEnv) { rtEnv.Apply(); HDRenderPipeline hdPipeline = RenderPipelineManager.currentPipeline as HDRenderPipeline; if (hdPipeline != null) { hdPipeline.m_RayTracingManager.UpdateEnvironmentSubScenes(); } } static void AmbientOcclusionSubMenu(SerializedHDRaytracingEnvironment rtEnv, Editor owner) { // AO Specific fields EditorGUILayout.PropertyField(rtEnv.raytracedAO, Styles.aoEnableText); if(rtEnv.raytracedAO.boolValue) { EditorGUI.indentLevel++; // For the layer masks, we want to make sure the matching resources will be available during the following draw call. So we need to force a propagation to // the non serialized object and update the subscenes EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(rtEnv.aoLayerMask, Styles.aoLayerMaskText); if(EditorGUI.EndChangeCheck()) { UpdateEnvironmentSubScenes(rtEnv); } EditorGUILayout.IntSlider(rtEnv.aoNumSamples, 1, 32, Styles.aoNumSamplesText); EditorGUILayout.PropertyField(rtEnv.aoRayLength, Styles.aoRayLengthText); EditorGUILayout.PropertyField(rtEnv.aoFilterMode, Styles.aoFilterModeText); EditorGUI.indentLevel++; switch ((HDRaytracingEnvironment.AOFilterMode)rtEnv.aoFilterMode.enumValueIndex) { case HDRaytracingEnvironment.AOFilterMode.SpatioTemporal: { EditorGUILayout.PropertyField(rtEnv.aoBilateralRadius, Styles.aoBilateralRadius); } break; case HDRaytracingEnvironment.AOFilterMode.Nvidia: { EditorGUILayout.PropertyField(rtEnv.maxFilterWidthInPixels, Styles.aoNvidiaMaxFilterWidth); EditorGUILayout.PropertyField(rtEnv.filterRadiusInMeters, Styles.aoNvidiaFilterRadius); EditorGUILayout.PropertyField(rtEnv.normalSharpness, Styles.aoNvidiaNormalSharpness); } break; } EditorGUI.indentLevel--; EditorGUI.indentLevel--; } } static void ReflectionsSubMenu(SerializedHDRaytracingEnvironment rtEnv, Editor owner) { // AO Specific fields EditorGUILayout.PropertyField(rtEnv.raytracedReflections, Styles.reflEnableText); if (rtEnv.raytracedReflections.boolValue) { EditorGUI.indentLevel++; // For the layer masks, we want to make sure the matching resources will be available during the following draw call. So we need to force a propagation to // the non serialized object and update the sub-scenes EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(rtEnv.reflLayerMask, Styles.reflLayerMaskText); if(EditorGUI.EndChangeCheck()) { UpdateEnvironmentSubScenes(rtEnv); } EditorGUILayout.PropertyField(rtEnv.reflRayLength, Styles.reflRayLengthText); EditorGUILayout.PropertyField(rtEnv.reflBlendDistance, Styles.reflBlendDistanceText); EditorGUILayout.PropertyField(rtEnv.reflMinSmoothness, Styles.reflMinSmoothnessText); EditorGUILayout.PropertyField(rtEnv.reflClampValue, Styles.reflClampValueText); EditorGUILayout.PropertyField(rtEnv.reflQualityMode, Styles.reflQualityText); EditorGUI.indentLevel++; switch ((HDRaytracingEnvironment.ReflectionsQuality)rtEnv.reflQualityMode.enumValueIndex) { case HDRaytracingEnvironment.ReflectionsQuality.QuarterRes: { EditorGUILayout.PropertyField(rtEnv.reflTemporalAccumulationWeight, Styles.reflTemporalAccumulationWeight); EditorGUILayout.PropertyField(rtEnv.reflSpatialFilterRadius, Styles.reflFilterRadius); } break; case HDRaytracingEnvironment.ReflectionsQuality.Integration: { EditorGUILayout.PropertyField(rtEnv.reflNumMaxSamples, Styles.reflNumMaxSamplesText); EditorGUILayout.PropertyField(rtEnv.reflFilterMode, Styles.reflFilerModeText); switch ((HDRaytracingEnvironment.ReflectionsFilterMode)rtEnv.reflFilterMode.enumValueIndex) { case HDRaytracingEnvironment.ReflectionsFilterMode.SpatioTemporal: { EditorGUILayout.PropertyField(rtEnv.reflFilterRadius, Styles.reflFilterRadius); } break; } } break; } EditorGUI.indentLevel--; EditorGUI.indentLevel--; } } static void RaytracingSubMenu(SerializedHDRaytracingEnvironment rtEnv, Editor owner) { // Primary Visibility Specific fields EditorGUILayout.PropertyField(rtEnv.raytracedObjects, Styles.raytracingEnableText); if (rtEnv.raytracedObjects.boolValue) { // For the layer masks, we want to make sure the matching resources will be available during the following draw call. So we need to force a propagation to // the non serialized object and update the sub-scenes EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(rtEnv.raytracedLayerMask, Styles.raytracedLayerMaskText); if(EditorGUI.EndChangeCheck()) { UpdateEnvironmentSubScenes(rtEnv); } EditorGUI.indentLevel++; EditorGUILayout.PropertyField(rtEnv.rayMaxDepth, Styles.rayMaxDepth); EditorGUILayout.PropertyField(rtEnv.raytracingRayLength, Styles.raytracingRayLength); EditorGUI.indentLevel--; } } static void LightClusterSubMenu(SerializedHDRaytracingEnvironment rtEnv, Editor owner) { EditorGUILayout.PropertyField(rtEnv.maxNumLightsPercell, Styles.maxNumLightsText); EditorGUILayout.PropertyField(rtEnv.cameraClusterRange, Styles.cameraClusterRangeText); } static void AreaShadowSubMenu(SerializedHDRaytracingEnvironment rtEnv, Editor owner) { EditorGUILayout.PropertyField(rtEnv.raytracedShadows, Styles.shadowEnableText); if (rtEnv.raytracedShadows.boolValue) { // For the layer masks, we want to make sure the matching resources will be available during the following draw call. So we need to force a propagation to // the non serialized object and update the sub-scenes EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(rtEnv.shadowLayerMask, Styles.shadowLayerMaskText); if(EditorGUI.EndChangeCheck()) { UpdateEnvironmentSubScenes(rtEnv); } EditorGUILayout.PropertyField(rtEnv.shadowNumSamples, Styles.shadowNumSamplesText); EditorGUILayout.PropertyField(rtEnv.numAreaLightShadows, Styles.numAreaLightShadows); EditorGUILayout.PropertyField(rtEnv.shadowFilterRadius, Styles.shadowBilateralRadius); EditorGUILayout.PropertyField(rtEnv.splitIntegration, Styles.splitIntegrationText); } } static void IndirectDiffuseSubMenu(SerializedHDRaytracingEnvironment rtEnv, Editor owner) { EditorGUILayout.PropertyField(rtEnv.raytracedIndirectDiffuse, Styles.indirectDiffuseEnableText); if (rtEnv.raytracedIndirectDiffuse.boolValue) { // For the layer masks, we want to make sure the matching resources will be available during the following draw call. So we need to force a propagation to // the non serialized object and update the sub-scenes EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(rtEnv.indirectDiffuseLayerMask, Styles.indirectDiffuseLayerMaskText); if(EditorGUI.EndChangeCheck()) { UpdateEnvironmentSubScenes(rtEnv); } EditorGUILayout.PropertyField(rtEnv.indirectDiffuseNumSamples, Styles.indirectDiffuseNumSamplesText); EditorGUILayout.PropertyField(rtEnv.indirectDiffuseRayLength, Styles.indirectDiffuseRayLengthText); EditorGUILayout.PropertyField(rtEnv.indirectDiffuseClampValue, Styles.indirectDiffuseClampText); EditorGUILayout.PropertyField(rtEnv.indirectDiffuseFilterMode, Styles.indirectDiffuseFilterModeText); switch ((HDRaytracingEnvironment.IndirectDiffuseFilterMode)rtEnv.indirectDiffuseFilterMode.enumValueIndex) { case HDRaytracingEnvironment.IndirectDiffuseFilterMode.SpatioTemporal: { EditorGUILayout.PropertyField(rtEnv.indirectDiffuseFilterRadius, Styles.indirectDiffuseFilterRadiusText); } break; } } } protected void OnEnable() { HDRaytracingEnvironment rtEnv = (HDRaytracingEnvironment)target; // Get & automatically add additional HD data if not present m_SerializedHDRaytracingEnvironment = new SerializedHDRaytracingEnvironment(rtEnv); k_ExpandedState = new ExpandedState<Expandable, HDRaytracingEnvironment>(~(-1), "HDRP"); } public override void OnInspectorGUI() { m_SerializedHDRaytracingEnvironment.Update(); Inspector.Draw(m_SerializedHDRaytracingEnvironment, this); m_SerializedHDRaytracingEnvironment.Apply(); } #endif } }
using SharpGL.Enumerations; using System; using System.ComponentModel; namespace SharpGL.OpenGLAttributes { /// <summary> /// This class has all the settings you can edit for fog. /// </summary> [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] [Serializable()] public class PixelModeAttributes : OpenGLAttributeGroup { /// <summary> /// Initializes a new instance of the <see cref="PixelModeAttributes"/> class. /// </summary> public PixelModeAttributes() { AttributeFlags = SharpGL.Enumerations.AttributeMask.PixelMode; /* * GL_RED_BIAS and GL_RED_SCALE settings GL_GREEN_BIAS and GL_GREEN_SCALE values GL_BLUE_BIAS and GL_BLUE_SCALE GL_ALPHA_BIAS and GL_ALPHA_SCALE GL_DEPTH_BIAS and GL_DEPTH_SCALE GL_INDEX_OFFSET and GL_INDEX_SHIFT values GL_ZOOM_X and GL_ZOOM_Y factors GL_READ_BUFFER setting*/ } /// <summary> /// Sets the attributes. /// </summary> /// <param name="gl">The OpenGL instance.</param> public override void SetAttributes(OpenGL gl) { if (mapColor.HasValue) gl.PixelTransfer(PixelTransferParameterName.MapColor, mapColor.Value); if (mapStencil.HasValue) gl.PixelTransfer(PixelTransferParameterName.MapStencil, mapStencil.Value); if (indexShift.HasValue) gl.PixelTransfer(PixelTransferParameterName.IndexShift, indexShift.Value); if (indexOffset.HasValue) gl.PixelTransfer(PixelTransferParameterName.IndexOffset, indexOffset.Value); if (redScale.HasValue) gl.PixelTransfer(PixelTransferParameterName.RedScale, redScale.Value); if (greenScale.HasValue) gl.PixelTransfer(PixelTransferParameterName.GreenScale, greenScale.Value); if (blueScale.HasValue) gl.PixelTransfer(PixelTransferParameterName.BlueScale, blueScale.Value); if (alphaScale.HasValue) gl.PixelTransfer(PixelTransferParameterName.AlphaScale, alphaScale.Value); if (depthScale.HasValue) gl.PixelTransfer(PixelTransferParameterName.DepthScale, depthScale.Value); if (redBias.HasValue) gl.PixelTransfer(PixelTransferParameterName.RedBias, redBias.Value); if (greenBias.HasValue) gl.PixelTransfer(PixelTransferParameterName.GreenBias, greenBias.Value); if (blueBias.HasValue) gl.PixelTransfer(PixelTransferParameterName.BlueBias, blueBias.Value); if (alphaBias.HasValue) gl.PixelTransfer(PixelTransferParameterName.AlphaBias, alphaBias.Value); if (depthBias.HasValue) gl.PixelTransfer(PixelTransferParameterName.DepthBias, depthBias.Value); } /// <summary> /// Returns true if any attributes are set. /// </summary> /// <returns> /// True if any attributes are set /// </returns> public override bool AreAnyAttributesSet() { return mapColor.HasValue || mapStencil.HasValue; } private bool? mapColor; private bool? mapStencil; private int? indexShift; private int? indexOffset; private float? redScale; private float? greenScale; private float? blueScale; private float? alphaScale; private float? depthScale; private float? redBias; private float? greenBias; private float? blueBias; private float? alphaBias; private float? depthBias; /// <summary> /// Gets or sets the color of the map. /// </summary> /// <value> /// The color of the map. /// </value> [Description("."), Category("PixelMode")] public bool? MapColor { get { return mapColor; } set { mapColor = value; } } /// <summary> /// Gets or sets the map stencil. /// </summary> /// <value> /// The map stencil. /// </value> [Description("."), Category("PixelMode")] public bool? MapStencil { get { return mapStencil; } set { mapStencil = value; } } /// <summary> /// Gets or sets the index shift. /// </summary> /// <value> /// The index shift. /// </value> [Description("."), Category("PixelMode")] public int? IndexShift { get { return indexShift; } set { indexShift = value; } } /// <summary> /// Gets or sets the index offset. /// </summary> /// <value> /// The index offset. /// </value> [Description("."), Category("PixelMode")] public int? IndexOffset { get { return indexOffset; } set { indexOffset = value; } } /// <summary> /// Gets or sets the red scale. /// </summary> /// <value> /// The red scale. /// </value> [Description("."), Category("PixelMode")] public float? RedScale { get { return redScale; } set { redScale = value; } } /// <summary> /// Gets or sets the green scale. /// </summary> /// <value> /// The green scale. /// </value> [Description("."), Category("PixelMode")] public float? GreenScale { get { return greenScale; } set { greenScale = value; } } /// <summary> /// Gets or sets the blue scale. /// </summary> /// <value> /// The blue scale. /// </value> [Description("."), Category("PixelMode")] public float? BlueScale { get { return blueScale; } set { blueScale = value; } } /// <summary> /// Gets or sets the alpha scale. /// </summary> /// <value> /// The alpha scale. /// </value> [Description("."), Category("PixelMode")] public float? AlphaScale { get { return alphaScale; } set { alphaScale = value; } } /// <summary> /// Gets or sets the depth scale. /// </summary> /// <value> /// The depth scale. /// </value> [Description("."), Category("PixelMode")] public float? DepthScale { get { return depthScale; } set { depthScale = value; } } /// <summary> /// Gets or sets the red bias. /// </summary> /// <value> /// The red bias. /// </value> [Description("."), Category("PixelMode")] public float? RedBias { get { return redBias; } set { redBias = value; } } /// <summary> /// Gets or sets the green bias. /// </summary> /// <value> /// The green bias. /// </value> [Description("."), Category("PixelMode")] public float? GreenBias { get { return greenBias; } set { greenBias = value; } } /// <summary> /// Gets or sets the blue bias. /// </summary> /// <value> /// The blue bias. /// </value> [Description("."), Category("PixelMode")] public float? BlueBias { get { return blueBias; } set { blueBias = value; } } /// <summary> /// Gets or sets the alpha bias. /// </summary> /// <value> /// The alpha bias. /// </value> [Description("."), Category("PixelMode")] public float? AlphaBias { get { return alphaBias; } set { alphaBias = value; } } /// <summary> /// Gets or sets the depth bias. /// </summary> /// <value> /// The depth bias. /// </value> [Description("."), Category("PixelMode")] public float? DepthBias { get { return depthBias; } set { depthBias = value; } } } }
using System; using it.unifi.dsi.stlab.networkreasoner.model.gas; using it.unifi.dsi.stlab.math.algebra; using it.unifi.dsi.stlab.networkreasoner.gas.system.formulae; using System.Collections.Generic; using System.Linq; using it.unifi.dsi.stlab.utilities.object_with_substitution; using it.unifi.dsi.stlab.networkreasoner.gas.system.exactly_dimensioned_instance.computational_objects.nodes; namespace it.unifi.dsi.stlab.networkreasoner.gas.system.exactly_dimensioned_instance { public class NodeForNetwonRaphsonSystem : AbstractItemForNetwonRaphsonSystem, GasNodeVisitor, GasNodeGadgetVisitor { public class HeightPropertyMissingException : Exception { } public long Height { get; set; } public NodeRole Role{ get; set; } public AntecedentInPressureRegulation RoleInPressureRegulation{ get; set; } public List<EdgeForNetwonRaphsonSystem> IncomingEdges{ get; private set; } public List<EdgeForNetwonRaphsonSystem> OutgoingEdges{ get; private set; } public void initializeWith (GasNodeAbstract aNode) { this.IncomingEdges = new List<EdgeForNetwonRaphsonSystem> (); this.OutgoingEdges = new List<EdgeForNetwonRaphsonSystem> (); aNode.accept (this); if (this.Role == null) { this.Role = new NodeRolePassive (); } if (this.RoleInPressureRegulation == null) { this.RoleInPressureRegulation = new IsNotAntecedentInPressureRegulation (); } } #region GasNodeVisitor implementation public void forNodeWithTopologicalInfo (GasNodeTopological gasNodeTopological) { if (gasNodeTopological.Height.HasValue == false) { throw new HeightPropertyMissingException (); } this.Height = gasNodeTopological.Height.Value; this.Identifier = gasNodeTopological.Identifier; } public void forNodeWithGadget (GasNodeWithGadget gasNodeWithGadget) { gasNodeWithGadget.Gadget.accept (this); gasNodeWithGadget.Equipped.accept (this); } public void forNodeAntecedentInPressureReduction ( GasNodeAntecedentInPressureRegulator gasNodeAntecedentInPressureRegulator) { // just for debugging we do not consider this case, since the parser // doesn't create any object of this type. throw new NotSupportedException (); // this.RoleInPressureRegulation = new IsAntecedentInPressureRegulation { // Regulator = gasNodeAntecedentInPressureRegulator.RegulatorNode // }; gasNodeAntecedentInPressureRegulator.ToppedNode.accept (this); } #endregion #region GasNodeGadgetVisitor implementation public void forLoadGadget (GasNodeGadgetLoad aLoadGadget) { this.Role = new NodeRoleLoader { Load = aLoadGadget.Load }; } public void forSupplyGadget (GasNodeGadgetSupply aSupplyGadget) { this.Role = new NodeRoleSupplier { SetupPressureInMillibar = aSupplyGadget.SetupPressure }; } #endregion public virtual double invertedAlgebraicFlowSum ( Vector<EdgeForNetwonRaphsonSystem> Qvector) { // the following computation is the opposite of the one performed // by FluidDynamicSystemStateVisitorRevertComputationResultsOnOriginalDomain objects. var invertedAlgebraicSum = 0d; this.OutgoingEdges.ForEach ( edge => invertedAlgebraicSum += edge.fetchFlowFromQvector (Qvector)); this.IncomingEdges.ForEach ( edge => invertedAlgebraicSum -= edge.fetchFlowFromQvector (Qvector)); return invertedAlgebraicSum; } public void putYourCoefficientInto ( Vector<NodeForNetwonRaphsonSystem> aVector, GasFormulaVisitor aFormulaVisitor, Vector<EdgeForNetwonRaphsonSystem> Qvector) { new IfNodeIsAntecedentInPressureRegulation { IfItIs = data => aVector.atPut ( this, data.Regulator.invertedAlgebraicFlowSum (Qvector)), Otherwise = () => this.Role.putYourCoefficientIntoFor ( this, aVector, aFormulaVisitor, Qvector) }.performOn (this.RoleInPressureRegulation); } public void fixMatrixIfYouHaveSupplyGadget ( Matrix<NodeForNetwonRaphsonSystem, NodeForNetwonRaphsonSystem> aMatrix) { this.Role.fixMatrixIfYouHaveSupplyGadgetFor (this, aMatrix); } public double relativeDimensionalPressureOf ( double absolutePressure, GasFormulaVisitor aFormulaVisitor) { var formula = new RelativePressureFromAdimensionalPressureFormulaForNodes (); formula.NodeHeight = this.Height; formula.AdimensionalPressure = absolutePressure; return formula.accept (aFormulaVisitor); } public double absoluteDimensionalPressureOf ( double absolutePressure, GasFormulaVisitor aFormulaVisitor) { var formula = new AbsolutePressureFromAdimensionalPressureFormulaForNodes (); formula.AdimensionalPressure = absolutePressure; return formula.accept (aFormulaVisitor); } public GasNodeAbstract substituteNodeBecauseNegativePressureFound ( double pressure, GasNodeAbstract originalNode) { return Role.substituteNodeBecauseNegativePressureFoundFor ( this, pressure, originalNode); } public double fixPressureIfAntecedentInPressureReductionRelation ( double theCurrentNodePressure, GasFormulaVisitor aFormulaVisitor) { double antecedentNodePressure = theCurrentNodePressure; new IfNodeIsAntecedentInPressureRegulation { IfItIs = data => { if (antecedentNodePressure < 1d) { // restore atmospheric pressure antecedentNodePressure = 1d; // I don't understand if the following is the correct one // antecedentNodePressure = this.relativeDimensionalPressureOf (1d, aFormulaVisitor); } } }.performOn (this.RoleInPressureRegulation); return antecedentNodePressure; } public double fixPressureIfInPressureReductionRelation ( Vector<NodeForNetwonRaphsonSystem> unknownVectorAtCurrentStep, double theCurrentNodePressure, Func<NodeForNetwonRaphsonSystem, GasNodeAbstract> aNodeMapper, GasFormulaVisitor aFormulaVisitor) { double nodePressure = theCurrentNodePressure; new IfNodeIsConsequentInPressureRegulation { IfItIs = data => { var antecedentNodePressure = unknownVectorAtCurrentStep.valueAt (data.Antecedent); // the following assertion is assured by a precedent method // invocation that fix exactly this condition. We move that logic // in a dedicated chunck of code since here we cannot update the value // for the antecedent node, because this method should be // invoked inside a foreach loop. if (antecedentNodePressure < 1d) { throw new NotSupportedException ("Antecedent pressure cannot be less than 1d."); } // if (antecedentNodePressure < currentNodePressure) { var originalSetupPressure = new SetupPressureFinder { FormulaVisitor = aFormulaVisitor }.of (aNodeMapper.Invoke (this)); nodePressure = Math.Min (antecedentNodePressure, originalSetupPressure); var newRelativePressure = this.relativeDimensionalPressureOf ( nodePressure, aFormulaVisitor); if (newRelativePressure < -1000) { Console.WriteLine ("Relative pressure under -1000"); } this.substituteSupplyGadgetBecauseAntecedentInPressureRegulationHasLowerPressure ( newRelativePressure, aNodeMapper); //} } }.performOn (this.RoleInPressureRegulation); return nodePressure; } class SetupPressureFinder : GasNodeVisitor, GasNodeGadgetVisitor { public GasFormulaVisitor FormulaVisitor{ get; set; } public double? OriginalSetupPressure { get; set; } public long? Height{ get; set; } public Double of (GasNodeAbstract gasNodeAbstract) { gasNodeAbstract.accept (this); var coefficientFormula = new CoefficientFormulaForNodeWithSupplyGadget { GadgetSetupPressureInMillibar = this.OriginalSetupPressure.Value, NodeHeight = this.Height.Value }; return coefficientFormula.accept (this.FormulaVisitor); } #region GasNodeGadgetVisitor implementation public void forLoadGadget (GasNodeGadgetLoad aLoadGadget) { throw new NotSupportedException (); } public void forSupplyGadget (GasNodeGadgetSupply aSupplyGadget) { this.OriginalSetupPressure = aSupplyGadget.SetupPressure; } #endregion #region GasNodeVisitor implementation public void forNodeWithTopologicalInfo (GasNodeTopological gasNodeTopological) { this.Height = gasNodeTopological.Height; } public void forNodeWithGadget (GasNodeWithGadget gasNodeWithGadget) { gasNodeWithGadget.Equipped.accept (this); gasNodeWithGadget.Gadget.accept (this); } public void forNodeAntecedentInPressureReduction ( GasNodeAntecedentInPressureRegulator gasNodeAntecedentInPressureRegulator) { gasNodeAntecedentInPressureRegulator.ToppedNode.accept (this); } #endregion } void substituteSupplyGadgetBecauseAntecedentInPressureRegulationHasLowerPressure ( double newSetupPressure, Func<NodeForNetwonRaphsonSystem, GasNodeAbstract> originalNodeMapper) { this.Role = new NodeRoleSupplier { SetupPressureInMillibar = newSetupPressure }; // maybe this update on the original node can // be skipped since the user provide the // value. In subsequent computation, for instance // in negative pressure on load nodes, do we have // to use this fixed value or not? // GasNodeAbstract correspondingOriginalNode = // originalNodeMapper.Invoke (this); // // correspondingOriginalNode.accept ( // new SubstituteSupplyGadget{ SetupPressure = newSetupPressure }); } public override string ToString () { return string.Format ("[Node: id={0}]", this.Identifier); } class SubstituteSupplyGadget : GasNodeVisitor, GasNodeGadgetVisitor { public Double SetupPressure{ get; set; } #region GasNodeGadgetVisitor implementation public void forLoadGadget (GasNodeGadgetLoad aLoadGadget) { throw new NotSupportedException ("This method shouldn't be called since we're " + "substituting a node with a supply gadget."); } public void forSupplyGadget (GasNodeGadgetSupply aSupplyGadget) { aSupplyGadget.SetupPressure = SetupPressure; } #endregion #region GasNodeVisitor implementation public void forNodeWithTopologicalInfo (GasNodeTopological gasNodeTopological) { // nothing to do } public void forNodeWithGadget (GasNodeWithGadget gasNodeWithGadget) { gasNodeWithGadget.Gadget.accept (this); gasNodeWithGadget.Equipped.accept (this); } public void forNodeAntecedentInPressureReduction (GasNodeAntecedentInPressureRegulator gasNodeAntecedentInPressureRegulator) { gasNodeAntecedentInPressureRegulator.ToppedNode.accept (this); } #endregion } } }
using System.Xml; using System.Xml.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Serialization; using LegacyModuleInfo = Protobuild.Legacy.ModuleInfo; namespace Protobuild { /// <summary> /// Represents a Protobuild module. /// </summary> public class ModuleInfo { private DefinitionInfo[] _cachedDefinitions; private readonly Dictionary<string, ModuleInfo[]> _cachedSubmodules; private readonly Dictionary<string, DefinitionInfo[]> _cachedRecursivedDefinitions; /// <summary> /// Initializes a new instance of the <see cref="Protobuild.ModuleInfo"/> class. /// </summary> public ModuleInfo() { this.DefaultAction = "resync"; this.GenerateNuGetRepositories = true; _cachedSubmodules = new Dictionary<string, ModuleInfo[]>(); _cachedRecursivedDefinitions = new Dictionary<string, DefinitionInfo[]>(); } /// <summary> /// Gets or sets the name of the module. /// </summary> /// <value>The module name.</value> public string Name { get; set; } /// <summary> /// Gets or sets the authors of the module. /// </summary> /// <value>The name or names of the authors.</value> public string Authors { get; set; } /// <summary> /// Gets or sets the description of the module. /// </summary> /// <value>The description of the module.</value> public string Description { get; set; } /// <summary> /// Gets or sets the URL that specifies the license for the module. /// </summary> /// <value>The license URL for the module.</value> public string LicenseUrl { get; set; } /// <summary> /// Gets or sets the URL for the project. /// </summary> /// <value>The project URL for the module.</value> public string ProjectUrl { get; set; } /// <summary> /// Gets or sets a 64x64 icon for the module. /// </summary> /// <value>The URL to the 64x64 icon.</value> public string IconUrl { get; set; } /// <summary> /// Gets or sets the public, anonymous Git repository URL for the module. /// This URL should not require interactive authentication from the user. /// </summary> /// <value>The public, anonymous Git repository URL for the module.</value> public string GitRepositoryUrl { get; set; } /// <summary> /// Gets or sets the semantic version of the module. /// </summary> /// <value>The semantic version of the module.</value> public string SemanticVersion { get; set; } /// <summary> /// The root path of this module. /// </summary> public string Path { get; set; } /// <summary> /// Gets or sets the default action to be taken when Protobuild runs in the module. /// </summary> /// <value>The default action that Protobuild will take.</value> public string DefaultAction { get; set; } /// <summary> /// Gets or sets a comma seperated list of default platforms when the host platform is Windows. /// </summary> /// <value>The comma seperated list of default platforms when the host platform is Windows.</value> public string DefaultWindowsPlatforms { get; set; } /// <summary> /// Gets or sets a comma seperated list of default platforms when the host platform is Mac OS. /// </summary> /// <value>The comma seperated list of default platforms when the host platform is Mac OS.</value> public string DefaultMacOSPlatforms { get; set; } /// <summary> /// Gets or sets a comma seperated list of default platforms when the host platform is Linux. /// </summary> /// <value>The comma seperated list of default platforms when the host platform is Linux.</value> public string DefaultLinuxPlatforms { get; set; } /// <summary> /// Gets or sets a value indicating whether the NuGet repositories.config file is generated. /// </summary> /// <value><c>true</c> if the NuGet repositories.config file is generated; otherwise, <c>false</c>.</value> public bool GenerateNuGetRepositories { get; set; } /// <summary> /// Gets or sets a comma seperated list of supported platforms in this module. /// </summary> /// <value>The comma seperated list of supported platforms.</value> public string SupportedPlatforms { get; set; } /// <summary> /// Gets or sets a value indicating whether synchronisation is completely disabled in this module. /// </summary> /// <value><c>true</c> if synchronisation is disabled and will be skipped; otherwise, <c>false</c>.</value> public bool? DisableSynchronisation { get; set; } /// <summary> /// Gets or sets the name of the default startup project. /// </summary> /// <value>The name of the default startup project.</value> public string DefaultStartupProject { get; set; } /// <summary> /// Gets or sets a set of package references. /// </summary> /// <value>The registered packages.</value> public List<PackageRef> Packages { get; set; } /// <summary> /// Gets or sets the feature set to use when Protobuild is executing for /// this module. If this value is null, use the full feature set. /// </summary> /// <value>The feature set.</value> public List<Feature> FeatureSet { get; set; } /// <summary> /// Gets or sets the list of cached features. You shouldn't access this /// property directly, instead use the <see cref="IFeatureManager.IsFeatureEnabledInSubmodule"/> /// method. /// </summary> /// <value>The cached features.</value> public Feature[] CachedInternalFeatures { get; set; } /// <summary> /// Loads the module information from an XML stream. /// </summary> /// <param name="xmlStream">The XML stream.</param> /// <param name="modulePath">The virtual path to the module on disk.</param> /// <returns>The loaded module.</returns> public static ModuleInfo Load(Stream xmlStream, string modulePath) { return LoadInternal( XDocument.Load(xmlStream), modulePath, () => { throw new NotSupportedException("Can't fallback with stream argument."); }); } /// <summary> /// Loads the Protobuild module from the Module.xml file. /// </summary> /// <param name="xmlFile">The path to a Module.xml file.</param> /// <returns>The loaded Protobuild module.</returns> public static ModuleInfo Load(string xmlFile) { var modulePath = new FileInfo(xmlFile).Directory.Parent.FullName; return LoadInternal( XDocument.Load(xmlFile), modulePath, () => { // This is a previous module info format. var serializer = new XmlSerializer(typeof(LegacyModuleInfo)); var reader = new StreamReader(xmlFile); var legacyModule = (LegacyModuleInfo)serializer.Deserialize(reader); legacyModule.Path = new FileInfo(xmlFile).Directory.Parent.FullName; reader.Close(); // Migrate from the old format. var module = UpgradeFromOlderFormat(legacyModule, modulePath); // Re-save in the new format. if (xmlFile == System.IO.Path.Combine(Environment.CurrentDirectory, "Build", "Module.xml")) { module.Save(xmlFile); } return module; }); } private static ModuleInfo UpgradeFromOlderFormat(LegacyModuleInfo legacyModule, string modulePath) { var module = new ModuleInfo(); module.Name = legacyModule.Name; module.Path = modulePath; module.DefaultAction = legacyModule.DefaultAction; module.DefaultWindowsPlatforms = legacyModule.DefaultWindowsPlatforms; module.DefaultMacOSPlatforms = legacyModule.DefaultMacOSPlatforms; module.DefaultLinuxPlatforms = legacyModule.DefaultLinuxPlatforms; module.GenerateNuGetRepositories = legacyModule.GenerateNuGetRepositories; module.SupportedPlatforms = legacyModule.SupportedPlatforms; module.DisableSynchronisation = legacyModule.DisableSynchronisation; module.DefaultStartupProject = legacyModule.DefaultStartupProject; module.Packages = new List<PackageRef>(); if (legacyModule.Packages != null) { foreach (var oldPkg in legacyModule.Packages) { module.Packages.Add(new PackageRef { Folder = oldPkg.Folder, GitRef = oldPkg.GitRef, Uri = oldPkg.Uri }); } } return module; } private static ModuleInfo LoadInternal(XDocument doc, string modulePath, Func<ModuleInfo> fallback) { var def = new ModuleInfo(); var xsi = doc.Root == null ? null : doc.Root.Attribute(XName.Get("xsi", "http://www.w3.org/2000/xmlns/")); if (xsi != null && xsi.Value == "http://www.w3.org/2001/XMLSchema-instance") { return fallback(); } Func<string, string> getStringValue = name => { if (doc.Root == null) { return null; } var elem = doc.Root.Element(XName.Get(name)); if (elem == null) { return null; } return elem.Value; }; def.Name = getStringValue("Name"); def.Authors = getStringValue("Authors"); def.Description = getStringValue("Description"); def.ProjectUrl = getStringValue("ProjectUrl"); def.LicenseUrl = getStringValue("LicenseUrl"); def.IconUrl = getStringValue("IconUrl"); def.GitRepositoryUrl = getStringValue("GitRepositoryUrl"); def.SemanticVersion = getStringValue("SemanticVersion"); def.Path = modulePath; def.DefaultAction = getStringValue("DefaultAction"); def.DefaultLinuxPlatforms = getStringValue("DefaultLinuxPlatforms"); def.DefaultMacOSPlatforms = getStringValue("DefaultMacOSPlatforms"); def.DefaultWindowsPlatforms = getStringValue("DefaultWindowsPlatforms"); def.DefaultStartupProject = getStringValue("DefaultStartupProject"); def.SupportedPlatforms = getStringValue("SupportedPlatforms"); def.DisableSynchronisation = getStringValue("DisableSynchronisation") == "true"; def.GenerateNuGetRepositories = getStringValue("GenerateNuGetRepositories") == "true"; def.Packages = new List<PackageRef>(); if (doc.Root != null) { var packagesElem = doc.Root.Element(XName.Get("Packages")); if (packagesElem != null) { var packages = packagesElem.Elements(); foreach (var package in packages) { var folder = package.Attribute(XName.Get("Folder"))?.Value; var gitRef = package.Attribute(XName.Get("GitRef"))?.Value; var uri = package.Attribute(XName.Get("Uri"))?.Value; var repository = package.Attribute(XName.Get("Repository"))?.Value; var packageName = package.Attribute(XName.Get("Package"))?.Value; var version = package.Attribute(XName.Get("Version"))?.Value; if (!string.IsNullOrWhiteSpace(repository) && !string.IsNullOrWhiteSpace(packageName) && !string.IsNullOrWhiteSpace(version)) { // This is NuGet v3 package. Rather than writing a different interface, // we just automatically form a URI that complies with the rest of the // package resolution system. uri = repository; if (!string.IsNullOrWhiteSpace(uri)) { uri = uri.Replace("https://", "https-nuget-v3://"); uri = uri.Replace("http://", "http-nuget-v3://"); uri += $"|{packageName}"; } gitRef = version; } if (string.IsNullOrWhiteSpace(folder) && !string.IsNullOrWhiteSpace(packageName)) { folder = packageName; } if (string.IsNullOrWhiteSpace(folder) || string.IsNullOrWhiteSpace(gitRef) || string.IsNullOrWhiteSpace(uri)) { RedirectableConsole.ErrorWriteLine("WARNING: Invalid package declaration in module; skipping package."); continue; } var packageRef = new PackageRef { Folder = folder, GitRef = gitRef, Uri = uri, Platforms = null, }; var platforms = package.Attribute(XName.Get("Platforms")); var platformsArray = platforms?.Value.Split(','); if (platformsArray?.Length > 0) { packageRef.Platforms = platformsArray; } def.Packages.Add(packageRef); } } var featureSetElem = doc.Root.Element(XName.Get("FeatureSet")); if (featureSetElem != null) { def.FeatureSet = new List<Feature>(); var features = featureSetElem.Elements(); foreach (var feature in features) { try { def.FeatureSet.Add((Feature) Enum.Parse(typeof(Feature), feature.Value)); } catch { RedirectableConsole.ErrorWriteLine("Unknown feature in Module.xml; ignoring: " + feature.Value); } } } else { def.FeatureSet = null; } // Check if the feature set is present and if it does not contain // the PackageManagement feature. If that feature isn't there, we // ignore any of the data in Packages and just set the value to // an empty list. if (def.FeatureSet != null && !def.FeatureSet.Contains(Feature.PackageManagement)) { def.Packages.Clear(); } } return def; } /// <summary> /// Loads all of the project definitions present in the current module. /// </summary> /// <returns>The loaded project definitions.</returns> public DefinitionInfo[] GetDefinitions() { if (_cachedDefinitions == null) { var result = new List<DefinitionInfo>(); var path = System.IO.Path.Combine(this.Path, "Build", "Projects"); if (!Directory.Exists(path)) { return new DefinitionInfo[0]; } foreach (var file in new DirectoryInfo(path).GetFiles("*.definition")) { result.Add(DefinitionInfo.Load(file.FullName)); } _cachedDefinitions = result.ToArray(); } return _cachedDefinitions; } /// <summary> /// Loads all of the project definitions present in the current module and all submodules. /// </summary> /// <returns>The loaded project definitions.</returns> /// <param name="platform">The target platform.</param> /// <param name="relative">The current directory being scanned.</param> public IEnumerable<DefinitionInfo> GetDefinitionsRecursively(string platform = null, string relative = "") { if (!_cachedRecursivedDefinitions.ContainsKey(platform ?? "<null>") || relative != "") { var definitions = new List<DefinitionInfo>(); foreach (var definition in this.GetDefinitions()) { definition.AbsolutePath = (this.Path + '\\' + definition.RelativePath).Trim('\\'); definition.RelativePath = (relative + '\\' + definition.RelativePath).Trim('\\'); definition.ModulePath = this.Path; definitions.Add(definition); } foreach (var submodule in this.GetSubmodules(platform)) { var from = this.Path.Replace('\\', '/').TrimEnd('/') + "/"; var to = submodule.Path.Replace('\\', '/'); var subRelativePath = (new Uri(from).MakeRelativeUri(new Uri(to))) .ToString().Replace('/', '\\'); foreach (var definition in submodule.GetDefinitionsRecursively(platform, subRelativePath.Trim('\\')) ) { definitions.Add(definition); } } if (relative == "") { _cachedRecursivedDefinitions[platform ?? "<null>"] = definitions.Distinct(new DefinitionEqualityComparer()).ToArray(); } else { return definitions.Distinct(new DefinitionEqualityComparer()); } } return _cachedRecursivedDefinitions[platform ?? "<null>"]; } private class DefinitionEqualityComparer : IEqualityComparer<DefinitionInfo> { public bool Equals(DefinitionInfo a, DefinitionInfo b) { return a.ModulePath == b.ModulePath && a.Name == b.Name; } public int GetHashCode(DefinitionInfo obj) { return obj.ModulePath.GetHashCode() + obj.Name.GetHashCode() * 37; } } /// <summary> /// Loads all of the submodules present in this module. /// </summary> /// <returns>The loaded submodules.</returns> public ModuleInfo[] GetSubmodules(string platform = null) { if (!_cachedSubmodules.ContainsKey(platform ?? "<null>")) { var modules = new List<ModuleInfo>(); foreach (var directoryInit in new DirectoryInfo(this.Path).GetDirectories()) { var directory = directoryInit; if (File.Exists(System.IO.Path.Combine(directory.FullName, ".redirect"))) { // This is a redirected submodule (due to package resolution). Load the // module from it's actual path. using (var reader = new StreamReader(System.IO.Path.Combine(directory.FullName, ".redirect"))) { var targetPath = reader.ReadToEnd().Trim(); directory = new DirectoryInfo(targetPath); } } var build = directory.GetDirectories().FirstOrDefault(x => x.Name == "Build"); if (build == null) { continue; } var module = build.GetFiles().FirstOrDefault(x => x.Name == "Module.xml"); if (module == null) { continue; } modules.Add(ModuleInfo.Load(module.FullName)); } if (platform != null) { foreach (var directoryInit in new DirectoryInfo(this.Path).GetDirectories()) { var directory = directoryInit; if (File.Exists(System.IO.Path.Combine(directory.FullName, ".redirect"))) { // This is a redirected submodule (due to package resolution). Load the // module from it's actual path. using ( var reader = new StreamReader(System.IO.Path.Combine(directory.FullName, ".redirect"))) { var targetPath = reader.ReadToEnd().Trim(); directory = new DirectoryInfo(targetPath); } } var platformDirectory = new DirectoryInfo(System.IO.Path.Combine(directory.FullName, platform)); if (!platformDirectory.Exists) { continue; } var build = platformDirectory.GetDirectories().FirstOrDefault(x => x.Name == "Build"); if (build == null) { continue; } var module = build.GetFiles().FirstOrDefault(x => x.Name == "Module.xml"); if (module == null) { continue; } modules.Add(ModuleInfo.Load(module.FullName)); } } _cachedSubmodules[platform ?? "<null>"] = modules.ToArray(); } return _cachedSubmodules[platform ?? "<null>"]; } /// <summary> /// Saves the current module to a Module.xml file. /// </summary> /// <param name="xmlFile">The path to a Module.xml file.</param> public void Save(string xmlFile) { using (var writer = XmlWriter.Create(xmlFile, new XmlWriterSettings { Indent = true, IndentChars = " " })) { InternalSave().Save(writer); } } /// <summary> /// Saves the current module to a stream. /// </summary> /// <param name="xmlFile">The path to a stream.</param> public void Save(Stream stream) { using (var writer = XmlWriter.Create(stream, new XmlWriterSettings { Indent = true, IndentChars = " " })) { InternalSave().Save(writer); } } private XmlDocument InternalSave() { var doc = new XmlDocument(); var root = doc.CreateElement("Module"); doc.AppendChild(root); Action<string, string> createStringElement = (name, val) => { if (val != null) { var e = doc.CreateElement(name); e.InnerText = val; root.AppendChild(e); } }; Action<string, bool?> createBooleanElement = (name, val) => { if (val != null) { var e = doc.CreateElement(name); e.InnerText = val.Value ? "true" : "false"; root.AppendChild(e); } }; createStringElement("Name", Name); createStringElement("Authors", Authors); createStringElement("Description", Description); createStringElement("ProjectUrl", ProjectUrl); createStringElement("LicenseUrl", LicenseUrl); createStringElement("IconUrl", IconUrl); createStringElement("GitRepositoryUrl", GitRepositoryUrl); createStringElement("SemanticVersion", SemanticVersion); createStringElement("DefaultAction", DefaultAction); createStringElement("DefaultLinuxPlatforms", DefaultLinuxPlatforms); createStringElement("DefaultMacOSPlatforms", DefaultMacOSPlatforms); createStringElement("DefaultWindowsPlatforms", DefaultWindowsPlatforms); createStringElement("DefaultStartupProject", DefaultStartupProject); createStringElement("SupportedPlatforms", SupportedPlatforms); createBooleanElement("DisableSynchronisation", DisableSynchronisation); createBooleanElement("GenerateNuGetRepositories", GenerateNuGetRepositories); if (Packages != null && Packages.Count > 0) { var elem = doc.CreateElement("Packages"); root.AppendChild(elem); foreach (var package in Packages) { var packageElem = doc.CreateElement("Package"); if (package.Uri != null && (package.Uri.StartsWith("https-nuget-v3://", StringComparison.InvariantCultureIgnoreCase) || package.Uri.StartsWith("http-nuget-v3://", StringComparison.InvariantCultureIgnoreCase))) { var uriReplaced = package.Uri; uriReplaced = uriReplaced.Replace("https-nuget-v3://", "https://"); uriReplaced = uriReplaced.Replace("http-nuget-v3://", "http://"); var components = uriReplaced.Split(new[] {'|'}, 2); var repository = components[0]; var packageName = components[1]; packageElem.SetAttribute("Repository", repository); packageElem.SetAttribute("Package", packageName); packageElem.SetAttribute("Version", package.GitRef); if (packageName != package.Folder) { // We only need to specify this if it's different to the packageElem.SetAttribute("Folder", package.Folder); } } else { packageElem.SetAttribute("Uri", package.Uri); packageElem.SetAttribute("Folder", package.Folder); packageElem.SetAttribute("GitRef", package.GitRef); } if (package.Platforms != null && package.Platforms.Length > 0) { packageElem.SetAttribute("Platforms", package.Platforms.Aggregate((a, b) => a + "," + b)); } elem.AppendChild(packageElem); } } return doc; } /// <summary> /// Returns the default list of supported platforms in Protobuild. /// </summary> /// <returns>The default list of supported platforms in Protobuild.</returns> public static string GetSupportedPlatformsDefault() { return "Android,iOS,tvOS,Linux,MacOS,Ouya,PCL,PSMobile,Windows,Windows8,WindowsGL,WindowsPhone,WindowsPhone81,WindowsUniversal"; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.UserInterface; using osu.Framework.Input.Bindings; using osu.Framework.Input.Events; using osu.Framework.Testing; using osuTK; using osuTK.Input; namespace osu.Framework.Tests.Visual.Input { [HeadlessTest] public class TestSceneKeyBindingContainer : ManualInputManagerTestScene { [Test] public void TestTriggerWithNoKeyBindings() { bool pressedReceived = false; bool releasedReceived = false; TestKeyBindingContainer keyBindingContainer = null; AddStep("add container", () => { pressedReceived = false; releasedReceived = false; Child = keyBindingContainer = new TestKeyBindingContainer { Child = new TestKeyBindingReceptor { Pressed = _ => pressedReceived = true, Released = _ => releasedReceived = true } }; }); AddStep("trigger press", () => keyBindingContainer.TriggerPressed(TestAction.ActionA)); AddAssert("press received", () => pressedReceived); AddStep("trigger release", () => keyBindingContainer.TriggerReleased(TestAction.ActionA)); AddAssert("release received", () => releasedReceived); } [Test] public void TestPressKeyBeforeKeyBindingContainerAdded() { List<TestAction> pressedActions = new List<TestAction>(); List<TestAction> releasedActions = new List<TestAction>(); AddStep("press key B", () => InputManager.PressKey(Key.B)); AddStep("add container", () => { pressedActions.Clear(); releasedActions.Clear(); Child = new TestKeyBindingContainer { Child = new TestKeyBindingReceptor { Pressed = a => pressedActions.Add(a), Released = a => releasedActions.Add(a) } }; }); AddStep("press key A", () => InputManager.PressKey(Key.A)); AddAssert("only one action triggered", () => pressedActions.Count == 1); AddAssert("ActionA triggered", () => pressedActions[0] == TestAction.ActionA); AddAssert("no actions released", () => releasedActions.Count == 0); AddStep("release key A", () => InputManager.ReleaseKey(Key.A)); AddAssert("only one action triggered", () => pressedActions.Count == 1); AddAssert("only one action released", () => releasedActions.Count == 1); AddAssert("ActionA released", () => releasedActions[0] == TestAction.ActionA); } [Test] public void TestKeyHandledByOtherDrawableDoesNotTrigger() { List<TestAction> pressedActions = new List<TestAction>(); List<TestAction> releasedActions = new List<TestAction>(); TextBox textBox = null; AddStep("add children", () => { pressedActions.Clear(); releasedActions.Clear(); Child = new TestKeyBindingContainer { Children = new Drawable[] { textBox = new BasicTextBox { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(200, 30) }, new TestKeyBindingReceptor { Pressed = a => pressedActions.Add(a), Released = a => releasedActions.Add(a) } } }; }); AddStep("focus textbox and move mouse away", () => { InputManager.MoveMouseTo(textBox); InputManager.Click(MouseButton.Left); InputManager.MoveMouseTo(textBox, new Vector2(0, 100)); }); AddStep("press enter", () => InputManager.PressKey(Key.Enter)); AddStep("press mouse button", () => InputManager.PressButton(MouseButton.Left)); AddStep("release enter", () => InputManager.ReleaseKey(Key.Enter)); AddStep("release mouse button", () => InputManager.ReleaseButton(MouseButton.Left)); AddAssert("no pressed actions", () => pressedActions.Count == 0); AddAssert("no released actions", () => releasedActions.Count == 0); } [Test] public void TestReleasingSpecificModifierDoesNotReleaseCommonBindingIfOtherKeyIsActive() { bool pressedReceived = false; bool releasedReceived = false; AddStep("add container", () => { pressedReceived = false; releasedReceived = false; Child = new TestKeyBindingContainer { Child = new TestKeyBindingReceptor { Pressed = _ => pressedReceived = true, Released = _ => releasedReceived = true } }; }); AddStep("press lctrl", () => InputManager.PressKey(Key.LControl)); AddAssert("press received", () => pressedReceived); AddStep("reset variables", () => { pressedReceived = false; releasedReceived = false; }); AddStep("press rctrl", () => InputManager.PressKey(Key.RControl)); AddAssert("press not received", () => !pressedReceived); AddAssert("release not received", () => !releasedReceived); AddStep("release rctrl", () => InputManager.ReleaseKey(Key.RControl)); AddAssert("release not received", () => !releasedReceived); AddStep("release lctrl", () => InputManager.ReleaseKey(Key.LControl)); AddAssert("release received", () => releasedReceived); } [Test] public void TestSingleKeyRepeatEvents() { int pressedReceived = 0; int repeatedReceived = 0; bool releasedReceived = false; AddStep("add container", () => { pressedReceived = 0; repeatedReceived = 0; releasedReceived = false; Child = new TestKeyBindingContainer { Child = new TestKeyBindingReceptor { Pressed = a => pressedReceived += a == TestAction.ActionA ? 1 : 0, Repeated = a => repeatedReceived += a == TestAction.ActionA ? 1 : 0, Released = a => releasedReceived = a == TestAction.ActionA } }; }); AddStep("press A", () => InputManager.PressKey(Key.A)); AddAssert("press received", () => pressedReceived == 1); for (int i = 0; i < 10; i++) { int localI = i + 1; AddUntilStep($"repeat #{1 + i} received", () => repeatedReceived >= localI); } AddStep("release A", () => InputManager.ReleaseKey(Key.A)); AddAssert("release received", () => releasedReceived); AddAssert("only one press received", () => pressedReceived == 1); } [Test] public void TestKeyRepeatDoesntFireWhenNotAlive() { int pressedReceived = 0; int repeatedReceived = 0; bool releasedReceived = false; TestKeyBindingReceptor receptor = null; AddStep("add container", () => { pressedReceived = 0; repeatedReceived = 0; releasedReceived = false; Child = new TestKeyBindingContainer { Child = receptor = new TestKeyBindingReceptor { Pressed = a => pressedReceived += a == TestAction.ActionA ? 1 : 0, Repeated = a => repeatedReceived += a == TestAction.ActionA ? 1 : 0, Released = a => releasedReceived = a == TestAction.ActionA } }; }); AddStep("press A", () => InputManager.PressKey(Key.A)); AddUntilStep("wait for non-zero repeated", () => repeatedReceived > 0); AddStep("hide receptor", () => receptor.Hide()); int stopReceivingCheck = 0; AddStep("store count", () => stopReceivingCheck = repeatedReceived); AddWaitStep("wait some", 5); AddAssert("ensure not incrementing", () => stopReceivingCheck == repeatedReceived); AddStep("release A", () => InputManager.ReleaseKey(Key.A)); AddAssert("release received", () => releasedReceived); AddAssert("only one press received", () => pressedReceived == 1); } [Test] public void TestKeyCombinationRepeatEvents() { bool pressedReceived = false; bool repeatedReceived = false; bool releasedReceived = false; AddStep("add container", () => { pressedReceived = false; repeatedReceived = false; releasedReceived = false; Child = new TestKeyBindingContainer { Child = new TestKeyBindingReceptor { Pressed = a => pressedReceived = a == TestAction.ActionAB, Repeated = a => repeatedReceived = a == TestAction.ActionAB, Released = a => releasedReceived = a == TestAction.ActionAB, } }; }); AddStep("press A+B", () => { InputManager.PressKey(Key.A); InputManager.PressKey(Key.B); }); AddAssert("press received", () => pressedReceived); for (int i = 0; i < 10; i++) { AddUntilStep($"repeat #{1 + i} received", () => repeatedReceived); AddStep("reset for next repeat", () => repeatedReceived = false); } AddStep("release A", () => InputManager.ReleaseKey(Key.A)); AddAssert("release received", () => releasedReceived); AddStep("reset for potential repeat", () => repeatedReceived = false); AddWaitStep("wait", 5); AddAssert("no repeat received", () => !repeatedReceived); AddStep("release B", () => InputManager.ReleaseKey(Key.B)); } private class TestKeyBindingReceptor : Drawable, IKeyBindingHandler<TestAction> { public Action<TestAction> Pressed; public Action<TestAction> Repeated; public Action<TestAction> Released; public TestKeyBindingReceptor() { RelativeSizeAxes = Axes.Both; } public bool OnPressed(KeyBindingPressEvent<TestAction> e) { if (e.Repeat) Repeated?.Invoke(e.Action); else Pressed?.Invoke(e.Action); return true; } public void OnReleased(KeyBindingReleaseEvent<TestAction> e) { Released?.Invoke(e.Action); } } private class TestKeyBindingContainer : KeyBindingContainer<TestAction> { public override IEnumerable<IKeyBinding> DefaultKeyBindings => new IKeyBinding[] { new KeyBinding(InputKey.A, TestAction.ActionA), new KeyBinding(new KeyCombination(InputKey.A, InputKey.B), TestAction.ActionAB), new KeyBinding(InputKey.Enter, TestAction.ActionEnter), new KeyBinding(InputKey.Control, TestAction.ActionControl) }; } private enum TestAction { ActionA, ActionAB, ActionEnter, ActionControl } } }
/* * Copyright 2012-2016 The Pkcs11Interop Project * * 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. */ /* * Written for the Pkcs11Interop project by: * Jaroslav IMRICH <jimrich@jimrich.sk> */ using System; using System.Collections.Generic; using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.HighLevelAPI80; using NUnit.Framework; using LLA80 = Net.Pkcs11Interop.LowLevelAPI80; using System.Reflection; namespace Net.Pkcs11Interop.Tests.HighLevelAPI80 { /// <summary> /// Object attributes tests. /// </summary> [TestFixture()] public class _13_ObjectAttributeTest { /// <summary> /// Attribute dispose test. /// </summary> [Test()] public void _01_DisposeAttributeTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); // Unmanaged memory for attribute value stored in low level CK_ATTRIBUTE struct // is allocated by constructor of ObjectAttribute class. ObjectAttribute attr1 = new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_DATA); // Do something interesting with attribute // This unmanaged memory is freed by Dispose() method. attr1.Dispose(); // ObjectAttribute class can be used in using statement which defines a scope // at the end of which an object will be disposed (and unmanaged memory freed). using (ObjectAttribute attr2 = new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_DATA)) { // Do something interesting with attribute } #pragma warning disable 0219 // Explicit calling of Dispose() method can also be ommitted. ObjectAttribute attr3 = new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_DATA); // Do something interesting with attribute // Dispose() method will be called (and unmanaged memory freed) by GC eventually // but we cannot be sure when will this occur. #pragma warning restore 0219 } /// <summary> /// Attribute with empty value test. /// </summary> [Test()] public void _02_EmptyAttributeTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); // Create attribute without the value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_CLASS)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_CLASS); Assert.IsTrue(attr.GetValueAsByteArray() == null); } } /// <summary> /// Attribute with ulong value test. /// </summary> [Test()] public void _03_UintAttributeTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); ulong value = (ulong)CKO.CKO_DATA; // Create attribute with ulong value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_CLASS, value)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_CLASS); Assert.IsTrue(attr.GetValueAsUlong() == value); } } /// <summary> /// Attribute with bool value test. /// </summary> [Test()] public void _04_BoolAttributeTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); bool value = true; // Create attribute with bool value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_TOKEN, value)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_TOKEN); Assert.IsTrue(attr.GetValueAsBool() == value); } } /// <summary> /// Attribute with string value test. /// </summary> [Test()] public void _05_StringAttributeTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); string value = "Hello world"; // Create attribute with string value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_LABEL, value)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_LABEL); Assert.IsTrue(attr.GetValueAsString() == value); } value = null; // Create attribute with null string value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_LABEL, value)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_LABEL); Assert.IsTrue(attr.GetValueAsString() == value); } } /// <summary> /// Attribute with byte array value test. /// </summary> [Test()] public void _06_ByteArrayAttributeTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); byte[] value = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 }; // Create attribute with byte array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ID, value)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ID); Assert.IsTrue(Convert.ToBase64String(attr.GetValueAsByteArray()) == Convert.ToBase64String(value)); } value = null; // Create attribute with null byte array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ID, value)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ID); Assert.IsTrue(attr.GetValueAsByteArray() == value); } } /// <summary> /// Attribute with DateTime (CKA_DATE) value test. /// </summary> [Test()] public void _07_DateTimeAttributeTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); DateTime value = new DateTime(2012, 1, 30, 0, 0, 0, DateTimeKind.Utc); // Create attribute with DateTime value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_START_DATE, value)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_START_DATE); Assert.IsTrue(attr.GetValueAsDateTime() == value); } } /// <summary> /// Attribute with attribute array value test. /// </summary> [Test()] public void _08_AttributeArrayAttributeTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); ObjectAttribute nestedAttribute1 = new ObjectAttribute(CKA.CKA_TOKEN, true); ObjectAttribute nestedAttribute2 = new ObjectAttribute(CKA.CKA_PRIVATE, true); List<ObjectAttribute> originalValue = new List<ObjectAttribute>(); originalValue.Add(nestedAttribute1); originalValue.Add(nestedAttribute2); // Create attribute with attribute array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_WRAP_TEMPLATE, originalValue)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_WRAP_TEMPLATE); List<ObjectAttribute> recoveredValue = attr.GetValueAsObjectAttributeList(); Assert.IsTrue(recoveredValue.Count == 2); Assert.IsTrue(recoveredValue[0].Type == (ulong)CKA.CKA_TOKEN); Assert.IsTrue(recoveredValue[0].GetValueAsBool() == true); Assert.IsTrue(recoveredValue[1].Type == (ulong)CKA.CKA_PRIVATE); Assert.IsTrue(recoveredValue[1].GetValueAsBool() == true); } // There is the same pointer to unmanaged memory in both nestedAttribute1 and recoveredValue[0] instances // therefore private low level attribute structure needs to be modified to prevent double free. // This special handling is needed only in this synthetic test and should be avoided in real world application. LLA80.CK_ATTRIBUTE ckAttribute1 = (LLA80.CK_ATTRIBUTE)typeof(ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(nestedAttribute1); ckAttribute1.value = IntPtr.Zero; ckAttribute1.valueLen = 0; typeof(ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(nestedAttribute1, ckAttribute1); // There is the same pointer to unmanaged memory in both nestedAttribute2 and recoveredValue[1] instances // therefore private low level attribute structure needs to be modified to prevent double free. // This special handling is needed only in this synthetic test and should be avoided in real world application. LLA80.CK_ATTRIBUTE ckAttribute2 = (LLA80.CK_ATTRIBUTE)typeof(ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(nestedAttribute2); ckAttribute2.value = IntPtr.Zero; ckAttribute2.valueLen = 0; typeof(ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(nestedAttribute2, ckAttribute2); originalValue = null; // Create attribute with null attribute array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_WRAP_TEMPLATE, originalValue)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_WRAP_TEMPLATE); Assert.IsTrue(attr.GetValueAsObjectAttributeList() == originalValue); } originalValue = new List<ObjectAttribute>(); // Create attribute with empty attribute array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_WRAP_TEMPLATE, originalValue)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_WRAP_TEMPLATE); Assert.IsTrue(attr.GetValueAsObjectAttributeList() == null); } } /// <summary> /// Attribute with ulong array value test. /// </summary> [Test()] public void _09_UintArrayAttributeTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); List<ulong> originalValue = new List<ulong>(); originalValue.Add(333333); originalValue.Add(666666); // Create attribute with ulong array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ALLOWED_MECHANISMS); List<ulong> recoveredValue = attr.GetValueAsUlongList(); for (int i = 0; i < recoveredValue.Count; i++) Assert.IsTrue(originalValue[i] == recoveredValue[i]); } originalValue = null; // Create attribute with null ulong array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.GetValueAsUlongList() == originalValue); } originalValue = new List<ulong>(); // Create attribute with empty ulong array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.GetValueAsUlongList() == null); } } /// <summary> /// Attribute with mechanism array value test. /// </summary> [Test()] public void _10_MechanismArrayAttributeTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); List<CKM> originalValue = new List<CKM>(); originalValue.Add(CKM.CKM_RSA_PKCS); originalValue.Add(CKM.CKM_AES_CBC); // Create attribute with mechanism array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ALLOWED_MECHANISMS); List<CKM> recoveredValue = attr.GetValueAsCkmList(); for (int i = 0; i < recoveredValue.Count; i++) Assert.IsTrue(originalValue[i] == recoveredValue[i]); } originalValue = null; // Create attribute with null mechanism array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.GetValueAsCkmList() == originalValue); } originalValue = new List<CKM>(); // Create attribute with empty mechanism array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.GetValueAsCkmList() == null); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Orleans.Runtime; using Orleans.Serialization; using Orleans.TestingHost.Utils; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Memory; using Orleans.Configuration; using Microsoft.Extensions.Options; namespace Orleans.TestingHost { /// <summary> /// A host class for local testing with Orleans using in-process silos. /// Runs a Primary and optionally secondary silos in separate app domains, and client in the main app domain. /// Additional silos can also be started in-process on demand if required for particular test cases. /// </summary> /// <remarks> /// Make sure that your test project references your test grains and test grain interfaces /// projects, and has CopyLocal=True set on those references [which should be the default]. /// </remarks> public class TestCluster { private readonly List<SiloHandle> additionalSilos = new List<SiloHandle>(); private readonly TestClusterOptions options; private readonly StringBuilder log = new StringBuilder(); private int startedInstances; /// <summary> /// Primary silo handle, if applicable. /// </summary> /// <remarks>This handle is valid only when using Grain-based membership.</remarks> public SiloHandle Primary { get; private set; } /// <summary> /// List of handles to the secondary silos. /// </summary> public IReadOnlyList<SiloHandle> SecondarySilos => this.additionalSilos; /// <summary> /// Collection of all known silos. /// </summary> public ReadOnlyCollection<SiloHandle> Silos { get { var result = new List<SiloHandle>(); if (this.Primary != null) { result.Add(this.Primary); } result.AddRange(this.additionalSilos); return result.AsReadOnly(); } } /// <summary> /// Options used to configure the test cluster. /// </summary> /// <remarks>This is the options you configured your test cluster with, or the default one. /// If the cluster is being configured via ClusterConfiguration, then this object may not reflect the true settings. /// </remarks> public TestClusterOptions Options => this.options; /// <summary> /// The internal client interface. /// </summary> internal IInternalClusterClient InternalClient { get; private set; } /// <summary> /// The client. /// </summary> public IClusterClient Client => this.InternalClient; /// <summary> /// GrainFactory to use in the tests /// </summary> public IGrainFactory GrainFactory => this.Client; /// <summary> /// GrainFactory to use in the tests /// </summary> internal IInternalGrainFactory InternalGrainFactory => this.InternalClient; /// <summary> /// Client-side <see cref="IServiceProvider"/> to use in the tests. /// </summary> public IServiceProvider ServiceProvider => this.Client.ServiceProvider; /// <summary> /// SerializationManager to use in the tests /// </summary> public SerializationManager SerializationManager { get; private set; } /// <summary> /// Delegate used to create and start an individual silo. /// </summary> public Func<string, IList<IConfigurationSource>, SiloHandle> CreateSilo { private get; set; } = InProcessSiloHandle.Create; /// <summary> /// Configures the test cluster plus client in-process. /// </summary> public TestCluster(TestClusterOptions options, IReadOnlyList<IConfigurationSource> configurationSources) { this.options = options; this.ConfigurationSources = configurationSources.ToArray(); } /// <summary> /// Deploys the cluster using the specified configuration and starts the client in-process. /// It will start the number of silos defined in <see cref="TestClusterOptions.InitialSilosCount"/>. /// </summary> public void Deploy() { this.DeployAsync().GetAwaiter().GetResult(); } /// <summary> /// Deploys the cluster using the specified configuration and starts the client in-process. /// </summary> public async Task DeployAsync() { if (this.Primary != null || this.additionalSilos.Count > 0) throw new InvalidOperationException("Cluster host already deployed."); AppDomain.CurrentDomain.UnhandledException += ReportUnobservedException; try { string startMsg = "----------------------------- STARTING NEW UNIT TEST SILO HOST: " + GetType().FullName + " -------------------------------------"; WriteLog(startMsg); await InitializeAsync(); } catch (TimeoutException te) { FlushLogToConsole(); throw new TimeoutException("Timeout during test initialization", te); } catch (Exception ex) { StopAllSilos(); Exception baseExc = ex.GetBaseException(); FlushLogToConsole(); if (baseExc is TimeoutException) { throw new TimeoutException("Timeout during test initialization", ex); } // IMPORTANT: // Do NOT re-throw the original exception here, also not as an internal exception inside AggregateException // Due to the way MS tests works, if the original exception is an Orleans exception, // it's assembly might not be loaded yet in this phase of the test. // As a result, we will get "MSTest: Unit Test Adapter threw exception: Type is not resolved for member XXX" // and will loose the original exception. This makes debugging tests super hard! // The root cause has to do with us initializing our tests from Test constructor and not from TestInitialize method. // More details: http://dobrzanski.net/2010/09/20/mstest-unit-test-adapter-threw-exception-type-is-not-resolved-for-member/ //throw new Exception( // string.Format("Exception during test initialization: {0}", // LogFormatter.PrintException(baseExc))); throw; } } /// <summary> /// Get the list of current active silos. /// </summary> /// <returns>List of current silos.</returns> public IEnumerable<SiloHandle> GetActiveSilos() { WriteLog("GetActiveSilos: Primary={0} + {1} Additional={2}", Primary, additionalSilos.Count, Runtime.Utils.EnumerableToString(additionalSilos)); if (Primary?.IsActive == true) yield return Primary; if (additionalSilos.Count > 0) foreach (var s in additionalSilos) if (s?.IsActive == true) yield return s; } /// <summary> /// Find the silo handle for the specified silo address. /// </summary> /// <param name="siloAddress">Silo address to be found.</param> /// <returns>SiloHandle of the appropriate silo, or <c>null</c> if not found.</returns> public SiloHandle GetSiloForAddress(SiloAddress siloAddress) { var activeSilos = GetActiveSilos().ToList(); var ret = activeSilos.FirstOrDefault(s => s.SiloAddress.Equals(siloAddress)); return ret; } /// <summary> /// Wait for the silo liveness sub-system to detect and act on any recent cluster membership changes. /// </summary> /// <param name="didKill">Whether recent membership changes we done by graceful Stop.</param> public async Task WaitForLivenessToStabilizeAsync(bool didKill = false) { var clusterMembershipOptions = this.ServiceProvider.GetService<IOptions<ClusterMembershipOptions>>().Value; TimeSpan stabilizationTime = GetLivenessStabilizationTime(clusterMembershipOptions, didKill); WriteLog(Environment.NewLine + Environment.NewLine + "WaitForLivenessToStabilize is about to sleep for {0}", stabilizationTime); await Task.Delay(stabilizationTime); WriteLog("WaitForLivenessToStabilize is done sleeping"); } /// <summary> /// Get the timeout value to use to wait for the silo liveness sub-system to detect and act on any recent cluster membership changes. /// <seealso cref="WaitForLivenessToStabilizeAsync"/> /// </summary> public static TimeSpan GetLivenessStabilizationTime(ClusterMembershipOptions clusterMembershipOptions, bool didKill = false) { TimeSpan stabilizationTime = TimeSpan.Zero; if (didKill) { // in case of hard kill (kill and not Stop), we should give silos time to detect failures first. stabilizationTime = TestingUtils.Multiply(clusterMembershipOptions.ProbeTimeout, clusterMembershipOptions.NumMissedProbesLimit); } if (clusterMembershipOptions.UseLivenessGossip) { stabilizationTime += TimeSpan.FromSeconds(5); } else { stabilizationTime += TestingUtils.Multiply(clusterMembershipOptions.TableRefreshTimeout, 2); } return stabilizationTime; } /// <summary> /// Start an additional silo, so that it joins the existing cluster. /// </summary> /// <returns>SiloHandle for the newly started silo.</returns> public SiloHandle StartAdditionalSilo(bool startAdditionalSiloOnNewPort = false) { return this.StartAdditionalSilos(1, startAdditionalSiloOnNewPort).GetAwaiter().GetResult().Single(); } /// <summary> /// Start a number of additional silo, so that they join the existing cluster. /// </summary> /// <param name="silosToStart">Number of silos to start.</param> /// <param name="startAdditionalSiloOnNewPort"></param> /// <returns>List of SiloHandles for the newly started silos.</returns> public async Task<List<SiloHandle>> StartAdditionalSilos(int silosToStart, bool startAdditionalSiloOnNewPort = false) { var instances = new List<SiloHandle>(); if (silosToStart > 0) { var siloStartTasks = Enumerable.Range(this.startedInstances, silosToStart) .Select(instanceNumber => Task.Run(() => StartOrleansSilo((short)instanceNumber, this.options, startSiloOnNewPort: startAdditionalSiloOnNewPort))).ToArray(); try { await Task.WhenAll(siloStartTasks); } catch (Exception) { this.additionalSilos.AddRange(siloStartTasks.Where(t => t.Exception == null).Select(t => t.Result)); throw; } instances.AddRange(siloStartTasks.Select(t => t.Result)); this.additionalSilos.AddRange(instances); } return instances; } /// <summary> /// Stop any additional silos, not including the default Primary silo. /// </summary> public void StopSecondarySilos() { foreach (var instance in this.additionalSilos.ToList()) { StopSilo(instance); } } /// <summary> /// Stops the default Primary silo. /// </summary> public void StopPrimarySilo() { if (Primary == null) throw new InvalidOperationException("There is no primary silo"); StopClusterClient(); StopSilo(Primary); } private void StopClusterClient() { try { this.InternalClient?.Close().GetAwaiter().GetResult(); } catch (Exception exc) { WriteLog("Exception Uninitializing grain client: {0}", exc); } finally { this.InternalClient?.Dispose(); this.InternalClient = null; } } /// <summary> /// Stop all current silos. /// </summary> public void StopAllSilos() { StopClusterClient(); StopSecondarySilos(); if (Primary != null) { StopPrimarySilo(); } AppDomain.CurrentDomain.UnhandledException -= ReportUnobservedException; } /// <summary> /// Do a semi-graceful Stop of the specified silo. /// </summary> /// <param name="instance">Silo to be stopped.</param> public void StopSilo(SiloHandle instance) { if (instance != null) { StopOrleansSilo(instance, true); if (Primary == instance) { Primary = null; } else { additionalSilos.Remove(instance); } } } /// <summary> /// Do an immediate Kill of the specified silo. /// </summary> /// <param name="instance">Silo to be killed.</param> public void KillSilo(SiloHandle instance) { if (instance != null) { // do NOT stop, just kill directly, to simulate crash. StopOrleansSilo(instance, false); } } /// <summary> /// Performs a hard kill on client. Client will not cleanup resources. /// </summary> public void KillClient() { this.InternalClient?.Abort(); this.InternalClient = null; } /// <summary> /// Do a Stop or Kill of the specified silo, followed by a restart. /// </summary> /// <param name="instance">Silo to be restarted.</param> public SiloHandle RestartSilo(SiloHandle instance) { if (instance != null) { var instanceNumber = instance.InstanceNumber; var siloName = instance.Name; StopSilo(instance); var newInstance = StartOrleansSilo(instanceNumber, this.options); if (siloName == Silo.PrimarySiloName) { Primary = newInstance; } else { additionalSilos.Add(newInstance); } return newInstance; } return null; } /// <summary> /// Restart a previously stopped. /// </summary> /// <param name="siloName">Silo to be restarted.</param> public SiloHandle RestartStoppedSecondarySilo(string siloName) { if (siloName == null) throw new ArgumentNullException(nameof(siloName)); var siloHandle = this.Silos.Single(s => s.Name.Equals(siloName, StringComparison.Ordinal)); var newInstance = this.StartOrleansSilo(this.Silos.IndexOf(siloHandle), this.options); additionalSilos.Add(newInstance); return newInstance; } #region Private methods /// <summary> /// Initialize the grain client. This should be already done by <see cref="Deploy()"/> or <see cref="DeployAsync"/> /// </summary> public void InitializeClient() { WriteLog("Initializing Cluster Client"); this.InternalClient = (IInternalClusterClient)TestClusterHostFactory.CreateClusterClient("MainClient", this.ConfigurationSources); this.InternalClient.Connect().GetAwaiter().GetResult(); this.SerializationManager = this.ServiceProvider.GetRequiredService<SerializationManager>(); } public IReadOnlyList<IConfigurationSource> ConfigurationSources { get; } private async Task InitializeAsync() { short silosToStart = this.options.InitialSilosCount; if (this.options.UseTestClusterMembership) { this.Primary = StartOrleansSilo(this.startedInstances, this.options); silosToStart--; } if (silosToStart > 0) { await this.StartAdditionalSilos(silosToStart); } WriteLog("Done initializing cluster"); if (this.options.InitializeClientOnDeploy) { InitializeClient(); } } /// <summary> /// Start a new silo in the target cluster /// </summary> /// <param name="cluster">The TestCluster in which the silo should be deployed</param> /// <param name="instanceNumber">The instance number to deploy</param> /// <param name="clusterOptions">The options to use.</param> /// <param name="configurationOverrides">Configuration overrides.</param> /// <param name="startSiloOnNewPort">Whether we start this silo on a new port, instead of the default one</param> /// <returns>A handle to the silo deployed</returns> public static SiloHandle StartOrleansSilo(TestCluster cluster, int instanceNumber, TestClusterOptions clusterOptions, IReadOnlyList<IConfigurationSource> configurationOverrides = null, bool startSiloOnNewPort = false) { if (cluster == null) throw new ArgumentNullException(nameof(cluster)); return cluster.StartOrleansSilo(instanceNumber, clusterOptions, configurationOverrides, startSiloOnNewPort); } /// <summary> /// Starts a new silo. /// </summary> /// <param name="instanceNumber">The instance number to deploy</param> /// <param name="clusterOptions">The options to use.</param> /// <param name="configurationOverrides">Configuration overrides.</param> /// <param name="startSiloOnNewPort">Whether we start this silo on a new port, instead of the default one</param> /// <returns>A handle to the deployed silo.</returns> public SiloHandle StartOrleansSilo(int instanceNumber, TestClusterOptions clusterOptions, IReadOnlyList<IConfigurationSource> configurationOverrides = null, bool startSiloOnNewPort = false) { var configurationSources = this.ConfigurationSources.ToList(); // Add overrides. if (configurationOverrides != null) configurationSources.AddRange(configurationOverrides); var siloSpecificOptions = TestSiloSpecificOptions.Create(clusterOptions, instanceNumber, startSiloOnNewPort); configurationSources.Add(new MemoryConfigurationSource { InitialData = siloSpecificOptions.ToDictionary() }); var handle = this.CreateSilo(siloSpecificOptions.SiloName,configurationSources); handle.InstanceNumber = (short)instanceNumber; Interlocked.Increment(ref this.startedInstances); return handle; } private void StopOrleansSilo(SiloHandle instance, bool stopGracefully) { try { instance.StopSilo(stopGracefully); instance.Dispose(); } finally { Interlocked.Decrement(ref this.startedInstances); } } #endregion #region Tracing helper functions public string GetLog() { return this.log.ToString(); } private void ReportUnobservedException(object sender, UnhandledExceptionEventArgs eventArgs) { Exception exception = (Exception)eventArgs.ExceptionObject; this.WriteLog("Unobserved exception: {0}", exception); } private void WriteLog(string format, params object[] args) { log.AppendFormat(format + Environment.NewLine, args); } private void FlushLogToConsole() { Console.WriteLine(GetLog()); } #endregion } }
namespace ArcGISCompare { partial class frmMaster { /// <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.components = new System.ComponentModel.Container(); System.Windows.Forms.ToolStripStatusLabel comment; System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmMaster)); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.mnuApplication = new System.Windows.Forms.ToolStripMenuItem(); this.mnuSource = new System.Windows.Forms.ToolStripMenuItem(); this.mnuDestination = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.mnuSaveMappings = new System.Windows.Forms.ToolStripMenuItem(); this.mnuSep = new System.Windows.Forms.ToolStripSeparator(); this.mnuExit = new System.Windows.Forms.ToolStripMenuItem(); this.mnuAnalyze = new System.Windows.Forms.ToolStripMenuItem(); this.mnuAnalyzeAll = new System.Windows.Forms.ToolStripMenuItem(); this.mnuAnalyzeSource = new System.Windows.Forms.ToolStripMenuItem(); this.mnuAnalyzeDestination = new System.Windows.Forms.ToolStripMenuItem(); this.mnuAnalyzeInstructions = new System.Windows.Forms.ToolStripMenuItem(); this.mnuRun = new System.Windows.Forms.ToolStripMenuItem(); this.mnuMappings = new System.Windows.Forms.ToolStripMenuItem(); this.mnuShowMappings = new System.Windows.Forms.ToolStripMenuItem(); this.mnuSaveMap = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.mnuInitializeMap = new System.Windows.Forms.ToolStripMenuItem(); this.mnuUpdateMap = new System.Windows.Forms.ToolStripMenuItem(); this.sOne = new System.Windows.Forms.SplitContainer(); this.tcTop = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.lbSource = new System.Windows.Forms.ListBox(); this.label1 = new System.Windows.Forms.Label(); this.splitContainer2 = new System.Windows.Forms.SplitContainer(); this.TV = new System.Windows.Forms.TreeView(); this.imgNodes = new System.Windows.Forms.ImageList(this.components); this.label3 = new System.Windows.Forms.Label(); this.lbDestination = new System.Windows.Forms.ListBox(); this.label2 = new System.Windows.Forms.Label(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.splitContainer3 = new System.Windows.Forms.SplitContainer(); this.lbSrcAttributes = new System.Windows.Forms.ListBox(); this.label10 = new System.Windows.Forms.Label(); this.lblSourceFeature = new System.Windows.Forms.Label(); this.splitContainer4 = new System.Windows.Forms.SplitContainer(); this.lstAttMappings = new System.Windows.Forms.ListBox(); this.label6 = new System.Windows.Forms.Label(); this.lbDestAttributes = new System.Windows.Forms.ListBox(); this.label4 = new System.Windows.Forms.Label(); this.lblDestinationFeature = new System.Windows.Forms.Label(); this.tabPage3 = new System.Windows.Forms.TabPage(); this.splitContainer7 = new System.Windows.Forms.SplitContainer(); this.lbSourceValues = new System.Windows.Forms.ListBox(); this.label8 = new System.Windows.Forms.Label(); this.splitContainer8 = new System.Windows.Forms.SplitContainer(); this.lstValueMappings = new System.Windows.Forms.ListBox(); this.label5 = new System.Windows.Forms.Label(); this.lbDestinationValues = new System.Windows.Forms.ListBox(); this.label9 = new System.Windows.Forms.Label(); this.helpBox = new System.Windows.Forms.RichTextBox(); this.lblHelp = new System.Windows.Forms.Label(); this.statusStrip2 = new System.Windows.Forms.StatusStrip(); this.GPB = new System.Windows.Forms.ProgressBar(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.srcWorkspaceLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.destWorkspaceLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.instDLG = new System.Windows.Forms.OpenFileDialog(); this.saveDLG = new System.Windows.Forms.SaveFileDialog(); this.conMenu = new System.Windows.Forms.ContextMenuStrip(this.components); this.mnuInsertConstant = new System.Windows.Forms.ToolStripMenuItem(); this.mapMenu = new System.Windows.Forms.ContextMenuStrip(this.components); this.mnuMapConstant = new System.Windows.Forms.ToolStripMenuItem(); comment = new System.Windows.Forms.ToolStripStatusLabel(); this.menuStrip1.SuspendLayout(); this.sOne.Panel1.SuspendLayout(); this.sOne.Panel2.SuspendLayout(); this.sOne.SuspendLayout(); this.tcTop.SuspendLayout(); this.tabPage1.SuspendLayout(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.splitContainer2.Panel1.SuspendLayout(); this.splitContainer2.Panel2.SuspendLayout(); this.splitContainer2.SuspendLayout(); this.tabPage2.SuspendLayout(); this.splitContainer3.Panel1.SuspendLayout(); this.splitContainer3.Panel2.SuspendLayout(); this.splitContainer3.SuspendLayout(); this.splitContainer4.Panel1.SuspendLayout(); this.splitContainer4.Panel2.SuspendLayout(); this.splitContainer4.SuspendLayout(); this.tabPage3.SuspendLayout(); this.splitContainer7.Panel1.SuspendLayout(); this.splitContainer7.Panel2.SuspendLayout(); this.splitContainer7.SuspendLayout(); this.splitContainer8.Panel1.SuspendLayout(); this.splitContainer8.Panel2.SuspendLayout(); this.splitContainer8.SuspendLayout(); this.statusStrip2.SuspendLayout(); this.statusStrip1.SuspendLayout(); this.conMenu.SuspendLayout(); this.mapMenu.SuspendLayout(); this.SuspendLayout(); // // comment // comment.Name = "comment"; comment.Size = new System.Drawing.Size(118, 17); comment.Text = "toolStripStatusLabel1"; comment.Visible = false; // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mnuApplication, this.mnuAnalyze, this.mnuRun, this.mnuMappings}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(859, 24); this.menuStrip1.TabIndex = 0; this.menuStrip1.Text = "Mapping Selected"; // // mnuApplication // this.mnuApplication.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mnuSource, this.mnuDestination, this.toolStripSeparator1, this.mnuSaveMappings, this.mnuSep, this.mnuExit}); this.mnuApplication.Name = "mnuApplication"; this.mnuApplication.Size = new System.Drawing.Size(80, 20); this.mnuApplication.Text = "Application"; // // mnuSource // this.mnuSource.Name = "mnuSource"; this.mnuSource.Size = new System.Drawing.Size(264, 22); this.mnuSource.Text = "Select Template Geodatabase"; this.mnuSource.Click += new System.EventHandler(this.mnuSourceG_Click); // // mnuDestination // this.mnuDestination.Name = "mnuDestination"; this.mnuDestination.Size = new System.Drawing.Size(264, 22); this.mnuDestination.Text = "Select Implementation Geodatabase"; this.mnuDestination.Click += new System.EventHandler(this.mnuDestination_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(261, 6); // // mnuSaveMappings // this.mnuSaveMappings.Name = "mnuSaveMappings"; this.mnuSaveMappings.Size = new System.Drawing.Size(264, 22); this.mnuSaveMappings.Text = "Save Results"; this.mnuSaveMappings.Visible = false; this.mnuSaveMappings.Click += new System.EventHandler(this.mnuSaveMappings_Click); // // mnuSep // this.mnuSep.Name = "mnuSep"; this.mnuSep.Size = new System.Drawing.Size(261, 6); // // mnuExit // this.mnuExit.Name = "mnuExit"; this.mnuExit.Size = new System.Drawing.Size(264, 22); this.mnuExit.Text = "Exit"; this.mnuExit.Click += new System.EventHandler(this.mnuExit_Click); // // mnuAnalyze // this.mnuAnalyze.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mnuAnalyzeAll, this.mnuAnalyzeSource, this.mnuAnalyzeDestination, this.mnuAnalyzeInstructions}); this.mnuAnalyze.Name = "mnuAnalyze"; this.mnuAnalyze.Size = new System.Drawing.Size(60, 20); this.mnuAnalyze.Text = "Analyze"; this.mnuAnalyze.Visible = false; // // mnuAnalyzeAll // this.mnuAnalyzeAll.Name = "mnuAnalyzeAll"; this.mnuAnalyzeAll.Size = new System.Drawing.Size(159, 22); this.mnuAnalyzeAll.Text = "All"; this.mnuAnalyzeAll.Visible = false; // // mnuAnalyzeSource // this.mnuAnalyzeSource.Name = "mnuAnalyzeSource"; this.mnuAnalyzeSource.Size = new System.Drawing.Size(159, 22); this.mnuAnalyzeSource.Text = "Template"; this.mnuAnalyzeSource.Visible = false; this.mnuAnalyzeSource.Click += new System.EventHandler(this.mnuAnalyzeSource_Click); // // mnuAnalyzeDestination // this.mnuAnalyzeDestination.Name = "mnuAnalyzeDestination"; this.mnuAnalyzeDestination.Size = new System.Drawing.Size(159, 22); this.mnuAnalyzeDestination.Text = "Implementation"; this.mnuAnalyzeDestination.Visible = false; // // mnuAnalyzeInstructions // this.mnuAnalyzeInstructions.Name = "mnuAnalyzeInstructions"; this.mnuAnalyzeInstructions.Size = new System.Drawing.Size(159, 22); this.mnuAnalyzeInstructions.Text = "Instructions"; this.mnuAnalyzeInstructions.Visible = false; // // mnuRun // this.mnuRun.Name = "mnuRun"; this.mnuRun.Size = new System.Drawing.Size(40, 20); this.mnuRun.Text = "Run"; this.mnuRun.Visible = false; this.mnuRun.Click += new System.EventHandler(this.mnuRun_Click); // // mnuMappings // this.mnuMappings.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mnuShowMappings, this.mnuSaveMap, this.toolStripSeparator2, this.mnuInitializeMap, this.mnuUpdateMap}); this.mnuMappings.Name = "mnuMappings"; this.mnuMappings.Size = new System.Drawing.Size(56, 20); this.mnuMappings.Text = "Results"; this.mnuMappings.Visible = false; // // mnuShowMappings // this.mnuShowMappings.Name = "mnuShowMappings"; this.mnuShowMappings.Size = new System.Drawing.Size(117, 22); this.mnuShowMappings.Text = "Show"; this.mnuShowMappings.Click += new System.EventHandler(this.mnuShowMappings_Click); // // mnuSaveMap // this.mnuSaveMap.Name = "mnuSaveMap"; this.mnuSaveMap.Size = new System.Drawing.Size(117, 22); this.mnuSaveMap.Text = "Save"; this.mnuSaveMap.Click += new System.EventHandler(this.mnuSaveMappings_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(114, 6); // // mnuInitializeMap // this.mnuInitializeMap.Name = "mnuInitializeMap"; this.mnuInitializeMap.Size = new System.Drawing.Size(117, 22); this.mnuInitializeMap.Text = "Initialize"; // // mnuUpdateMap // this.mnuUpdateMap.Name = "mnuUpdateMap"; this.mnuUpdateMap.Size = new System.Drawing.Size(117, 22); this.mnuUpdateMap.Text = "Update"; // // sOne // this.sOne.Dock = System.Windows.Forms.DockStyle.Fill; this.sOne.Location = new System.Drawing.Point(0, 24); this.sOne.Name = "sOne"; this.sOne.Orientation = System.Windows.Forms.Orientation.Horizontal; // // sOne.Panel1 // this.sOne.Panel1.Controls.Add(this.tcTop); this.sOne.Panel1MinSize = 350; // // sOne.Panel2 // this.sOne.Panel2.Controls.Add(this.helpBox); this.sOne.Panel2.Controls.Add(this.lblHelp); this.sOne.Panel2.Controls.Add(this.statusStrip2); this.sOne.Panel2.Controls.Add(this.GPB); this.sOne.Panel2.Controls.Add(this.statusStrip1); this.sOne.Panel2MinSize = 100; this.sOne.Size = new System.Drawing.Size(859, 460); this.sOne.SplitterDistance = 350; this.sOne.TabIndex = 1; // // tcTop // this.tcTop.Controls.Add(this.tabPage1); this.tcTop.Controls.Add(this.tabPage2); this.tcTop.Controls.Add(this.tabPage3); this.tcTop.Dock = System.Windows.Forms.DockStyle.Fill; this.tcTop.ItemSize = new System.Drawing.Size(275, 18); this.tcTop.Location = new System.Drawing.Point(0, 0); this.tcTop.Name = "tcTop"; this.tcTop.SelectedIndex = 0; this.tcTop.Size = new System.Drawing.Size(859, 350); this.tcTop.SizeMode = System.Windows.Forms.TabSizeMode.Fixed; this.tcTop.TabIndex = 0; // // tabPage1 // this.tabPage1.Controls.Add(this.splitContainer1); this.tabPage1.Location = new System.Drawing.Point(4, 22); this.tabPage1.Name = "tabPage1"; this.tabPage1.Padding = new System.Windows.Forms.Padding(3); this.tabPage1.Size = new System.Drawing.Size(851, 324); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "Comparing Features"; this.tabPage1.UseVisualStyleBackColor = true; // // splitContainer1 // this.splitContainer1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.Location = new System.Drawing.Point(3, 3); this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.BackColor = System.Drawing.Color.WhiteSmoke; this.splitContainer1.Panel1.Controls.Add(this.lbSource); this.splitContainer1.Panel1.Controls.Add(this.label1); this.splitContainer1.Panel1MinSize = 200; // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.splitContainer2); this.splitContainer1.Size = new System.Drawing.Size(845, 318); this.splitContainer1.SplitterDistance = 250; this.splitContainer1.TabIndex = 0; // // lbSource // this.lbSource.BackColor = System.Drawing.Color.WhiteSmoke; this.lbSource.Dock = System.Windows.Forms.DockStyle.Fill; this.lbSource.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.lbSource.FormattingEnabled = true; this.lbSource.Location = new System.Drawing.Point(0, 18); this.lbSource.Name = "lbSource"; this.lbSource.Size = new System.Drawing.Size(246, 296); this.lbSource.Sorted = true; this.lbSource.TabIndex = 1; // // label1 // this.label1.BackColor = System.Drawing.Color.Gainsboro; this.label1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.label1.Dock = System.Windows.Forms.DockStyle.Top; this.label1.Location = new System.Drawing.Point(0, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(246, 18); this.label1.TabIndex = 0; this.label1.Text = "Template Data Feature Classes"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // splitContainer2 // this.splitContainer2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer2.Location = new System.Drawing.Point(0, 0); this.splitContainer2.Name = "splitContainer2"; // // splitContainer2.Panel1 // this.splitContainer2.Panel1.Controls.Add(this.TV); this.splitContainer2.Panel1.Controls.Add(this.label3); // // splitContainer2.Panel2 // this.splitContainer2.Panel2.BackColor = System.Drawing.Color.WhiteSmoke; this.splitContainer2.Panel2.Controls.Add(this.lbDestination); this.splitContainer2.Panel2.Controls.Add(this.label2); this.splitContainer2.Panel2MinSize = 100; this.splitContainer2.Size = new System.Drawing.Size(591, 318); this.splitContainer2.SplitterDistance = 337; this.splitContainer2.TabIndex = 0; // // TV // this.TV.Dock = System.Windows.Forms.DockStyle.Fill; this.TV.ImageIndex = 0; this.TV.ImageList = this.imgNodes; this.TV.Location = new System.Drawing.Point(0, 18); this.TV.Name = "TV"; this.TV.SelectedImageIndex = 0; this.TV.Size = new System.Drawing.Size(333, 296); this.TV.TabIndex = 1; // // imgNodes // this.imgNodes.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imgNodes.ImageStream"))); this.imgNodes.TransparentColor = System.Drawing.Color.Transparent; this.imgNodes.Images.SetKeyName(0, "Check-32.png"); this.imgNodes.Images.SetKeyName(1, "Error-32.png"); // // label3 // this.label3.BackColor = System.Drawing.Color.Silver; this.label3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.label3.Dock = System.Windows.Forms.DockStyle.Top; this.label3.Location = new System.Drawing.Point(0, 0); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(333, 18); this.label3.TabIndex = 0; this.label3.Text = "Comparison Results"; this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // lbDestination // this.lbDestination.AllowDrop = true; this.lbDestination.BackColor = System.Drawing.Color.WhiteSmoke; this.lbDestination.Dock = System.Windows.Forms.DockStyle.Fill; this.lbDestination.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.lbDestination.FormattingEnabled = true; this.lbDestination.Location = new System.Drawing.Point(0, 18); this.lbDestination.Name = "lbDestination"; this.lbDestination.Size = new System.Drawing.Size(246, 296); this.lbDestination.Sorted = true; this.lbDestination.TabIndex = 2; // // label2 // this.label2.BackColor = System.Drawing.Color.Gainsboro; this.label2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.label2.Dock = System.Windows.Forms.DockStyle.Top; this.label2.Location = new System.Drawing.Point(0, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(246, 18); this.label2.TabIndex = 1; this.label2.Text = "Implementation Data Feature Classes"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // tabPage2 // this.tabPage2.Controls.Add(this.splitContainer3); this.tabPage2.Location = new System.Drawing.Point(4, 22); this.tabPage2.Name = "tabPage2"; this.tabPage2.Padding = new System.Windows.Forms.Padding(3); this.tabPage2.Size = new System.Drawing.Size(851, 324); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "Comparing Attributes"; this.tabPage2.UseVisualStyleBackColor = true; // // splitContainer3 // this.splitContainer3.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.splitContainer3.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer3.Location = new System.Drawing.Point(3, 3); this.splitContainer3.Name = "splitContainer3"; // // splitContainer3.Panel1 // this.splitContainer3.Panel1.Controls.Add(this.lbSrcAttributes); this.splitContainer3.Panel1.Controls.Add(this.label10); this.splitContainer3.Panel1.Controls.Add(this.lblSourceFeature); this.splitContainer3.Panel1MinSize = 250; // // splitContainer3.Panel2 // this.splitContainer3.Panel2.Controls.Add(this.splitContainer4); this.splitContainer3.Size = new System.Drawing.Size(845, 318); this.splitContainer3.SplitterDistance = 250; this.splitContainer3.TabIndex = 0; // // lbSrcAttributes // this.lbSrcAttributes.BackColor = System.Drawing.Color.WhiteSmoke; this.lbSrcAttributes.Dock = System.Windows.Forms.DockStyle.Fill; this.lbSrcAttributes.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.lbSrcAttributes.FormattingEnabled = true; this.lbSrcAttributes.Location = new System.Drawing.Point(0, 36); this.lbSrcAttributes.Name = "lbSrcAttributes"; this.lbSrcAttributes.Size = new System.Drawing.Size(246, 278); this.lbSrcAttributes.Sorted = true; this.lbSrcAttributes.TabIndex = 3; // // label10 // this.label10.BackColor = System.Drawing.Color.Gainsboro; this.label10.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.label10.Dock = System.Windows.Forms.DockStyle.Top; this.label10.Location = new System.Drawing.Point(0, 18); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(246, 18); this.label10.TabIndex = 4; this.label10.Text = "Template Attributes"; this.label10.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // lblSourceFeature // this.lblSourceFeature.BackColor = System.Drawing.Color.Gainsboro; this.lblSourceFeature.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.lblSourceFeature.Dock = System.Windows.Forms.DockStyle.Top; this.lblSourceFeature.Location = new System.Drawing.Point(0, 0); this.lblSourceFeature.Name = "lblSourceFeature"; this.lblSourceFeature.Size = new System.Drawing.Size(246, 18); this.lblSourceFeature.TabIndex = 2; this.lblSourceFeature.Text = "Template Attributes"; this.lblSourceFeature.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // splitContainer4 // this.splitContainer4.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.splitContainer4.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer4.Location = new System.Drawing.Point(0, 0); this.splitContainer4.Name = "splitContainer4"; // // splitContainer4.Panel1 // this.splitContainer4.Panel1.Controls.Add(this.lstAttMappings); this.splitContainer4.Panel1.Controls.Add(this.label6); // // splitContainer4.Panel2 // this.splitContainer4.Panel2.Controls.Add(this.lbDestAttributes); this.splitContainer4.Panel2.Controls.Add(this.label4); this.splitContainer4.Panel2.Controls.Add(this.lblDestinationFeature); this.splitContainer4.Size = new System.Drawing.Size(591, 318); this.splitContainer4.SplitterDistance = 328; this.splitContainer4.TabIndex = 0; // // lstAttMappings // this.lstAttMappings.BackColor = System.Drawing.Color.Gainsboro; this.lstAttMappings.Dock = System.Windows.Forms.DockStyle.Fill; this.lstAttMappings.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.lstAttMappings.FormattingEnabled = true; this.lstAttMappings.Location = new System.Drawing.Point(0, 18); this.lstAttMappings.Name = "lstAttMappings"; this.lstAttMappings.Size = new System.Drawing.Size(324, 296); this.lstAttMappings.TabIndex = 3; this.lstAttMappings.SelectedIndexChanged += new System.EventHandler(this.lstAttMappings_SelectedIndexChanged); // // label6 // this.label6.BackColor = System.Drawing.Color.Silver; this.label6.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.label6.Dock = System.Windows.Forms.DockStyle.Top; this.label6.Location = new System.Drawing.Point(0, 0); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(324, 18); this.label6.TabIndex = 2; this.label6.Text = "Currently Defined Attribute Comparisons"; this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // lbDestAttributes // this.lbDestAttributes.AllowDrop = true; this.lbDestAttributes.BackColor = System.Drawing.Color.WhiteSmoke; this.lbDestAttributes.Dock = System.Windows.Forms.DockStyle.Fill; this.lbDestAttributes.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.lbDestAttributes.FormattingEnabled = true; this.lbDestAttributes.Location = new System.Drawing.Point(0, 36); this.lbDestAttributes.Name = "lbDestAttributes"; this.lbDestAttributes.Size = new System.Drawing.Size(255, 278); this.lbDestAttributes.Sorted = true; this.lbDestAttributes.TabIndex = 4; // // label4 // this.label4.BackColor = System.Drawing.Color.Gainsboro; this.label4.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.label4.Dock = System.Windows.Forms.DockStyle.Top; this.label4.Location = new System.Drawing.Point(0, 18); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(255, 18); this.label4.TabIndex = 5; this.label4.Text = "Implementation Attributes"; this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // lblDestinationFeature // this.lblDestinationFeature.BackColor = System.Drawing.Color.Gainsboro; this.lblDestinationFeature.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.lblDestinationFeature.Dock = System.Windows.Forms.DockStyle.Top; this.lblDestinationFeature.Location = new System.Drawing.Point(0, 0); this.lblDestinationFeature.Name = "lblDestinationFeature"; this.lblDestinationFeature.Size = new System.Drawing.Size(255, 18); this.lblDestinationFeature.TabIndex = 3; this.lblDestinationFeature.Text = "Implementation Attributes"; this.lblDestinationFeature.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // tabPage3 // this.tabPage3.Controls.Add(this.splitContainer7); this.tabPage3.Location = new System.Drawing.Point(4, 22); this.tabPage3.Name = "tabPage3"; this.tabPage3.Size = new System.Drawing.Size(851, 324); this.tabPage3.TabIndex = 2; this.tabPage3.Text = "Comparing Values"; this.tabPage3.UseVisualStyleBackColor = true; // // splitContainer7 // this.splitContainer7.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.splitContainer7.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer7.Location = new System.Drawing.Point(0, 0); this.splitContainer7.Name = "splitContainer7"; // // splitContainer7.Panel1 // this.splitContainer7.Panel1.Controls.Add(this.lbSourceValues); this.splitContainer7.Panel1.Controls.Add(this.label8); this.splitContainer7.Panel1MinSize = 250; // // splitContainer7.Panel2 // this.splitContainer7.Panel2.Controls.Add(this.splitContainer8); this.splitContainer7.Size = new System.Drawing.Size(851, 324); this.splitContainer7.SplitterDistance = 250; this.splitContainer7.TabIndex = 0; // // lbSourceValues // this.lbSourceValues.BackColor = System.Drawing.Color.WhiteSmoke; this.lbSourceValues.Dock = System.Windows.Forms.DockStyle.Fill; this.lbSourceValues.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.lbSourceValues.FormattingEnabled = true; this.lbSourceValues.Location = new System.Drawing.Point(0, 18); this.lbSourceValues.Name = "lbSourceValues"; this.lbSourceValues.Size = new System.Drawing.Size(246, 302); this.lbSourceValues.Sorted = true; this.lbSourceValues.TabIndex = 2; // // label8 // this.label8.BackColor = System.Drawing.Color.Gainsboro; this.label8.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.label8.Dock = System.Windows.Forms.DockStyle.Top; this.label8.Location = new System.Drawing.Point(0, 0); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(246, 18); this.label8.TabIndex = 1; this.label8.Text = "Template Data Values"; this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // splitContainer8 // this.splitContainer8.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.splitContainer8.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer8.Location = new System.Drawing.Point(0, 0); this.splitContainer8.Name = "splitContainer8"; // // splitContainer8.Panel1 // this.splitContainer8.Panel1.Controls.Add(this.lstValueMappings); this.splitContainer8.Panel1.Controls.Add(this.label5); // // splitContainer8.Panel2 // this.splitContainer8.Panel2.Controls.Add(this.lbDestinationValues); this.splitContainer8.Panel2.Controls.Add(this.label9); this.splitContainer8.Size = new System.Drawing.Size(597, 324); this.splitContainer8.SplitterDistance = 325; this.splitContainer8.TabIndex = 0; // // lstValueMappings // this.lstValueMappings.BackColor = System.Drawing.Color.Gainsboro; this.lstValueMappings.Dock = System.Windows.Forms.DockStyle.Fill; this.lstValueMappings.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.lstValueMappings.FormattingEnabled = true; this.lstValueMappings.Location = new System.Drawing.Point(0, 18); this.lstValueMappings.Name = "lstValueMappings"; this.lstValueMappings.Size = new System.Drawing.Size(321, 302); this.lstValueMappings.TabIndex = 3; // // label5 // this.label5.BackColor = System.Drawing.Color.Silver; this.label5.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.label5.Dock = System.Windows.Forms.DockStyle.Top; this.label5.Location = new System.Drawing.Point(0, 0); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(321, 18); this.label5.TabIndex = 2; this.label5.Text = "Currently Defined Value Comparisons"; this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // lbDestinationValues // this.lbDestinationValues.AllowDrop = true; this.lbDestinationValues.BackColor = System.Drawing.Color.WhiteSmoke; this.lbDestinationValues.Dock = System.Windows.Forms.DockStyle.Fill; this.lbDestinationValues.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.lbDestinationValues.FormattingEnabled = true; this.lbDestinationValues.Location = new System.Drawing.Point(0, 18); this.lbDestinationValues.Name = "lbDestinationValues"; this.lbDestinationValues.Size = new System.Drawing.Size(264, 302); this.lbDestinationValues.Sorted = true; this.lbDestinationValues.TabIndex = 3; // // label9 // this.label9.BackColor = System.Drawing.Color.Gainsboro; this.label9.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.label9.Dock = System.Windows.Forms.DockStyle.Top; this.label9.Location = new System.Drawing.Point(0, 0); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(264, 18); this.label9.TabIndex = 2; this.label9.Text = "Implementation Data Values"; this.label9.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // helpBox // this.helpBox.Dock = System.Windows.Forms.DockStyle.Fill; this.helpBox.Location = new System.Drawing.Point(0, 27); this.helpBox.Name = "helpBox"; this.helpBox.Size = new System.Drawing.Size(859, 57); this.helpBox.TabIndex = 5; this.helpBox.Text = ""; this.helpBox.Visible = false; // // lblHelp // this.lblHelp.Dock = System.Windows.Forms.DockStyle.Top; this.lblHelp.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblHelp.Location = new System.Drawing.Point(0, 8); this.lblHelp.Name = "lblHelp"; this.lblHelp.Size = new System.Drawing.Size(859, 19); this.lblHelp.TabIndex = 4; this.lblHelp.Text = "Help/Information"; this.lblHelp.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.lblHelp.Visible = false; // // statusStrip2 // this.statusStrip2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { comment}); this.statusStrip2.Location = new System.Drawing.Point(0, 149); this.statusStrip2.Name = "statusStrip2"; this.statusStrip2.Size = new System.Drawing.Size(859, 22); this.statusStrip2.TabIndex = 3; this.statusStrip2.Text = "statusStrip2"; this.statusStrip2.Visible = false; // // GPB // this.GPB.Dock = System.Windows.Forms.DockStyle.Top; this.GPB.Location = new System.Drawing.Point(0, 0); this.GPB.Name = "GPB"; this.GPB.Size = new System.Drawing.Size(859, 8); this.GPB.TabIndex = 1; // // statusStrip1 // this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.srcWorkspaceLabel, this.destWorkspaceLabel}); this.statusStrip1.Location = new System.Drawing.Point(0, 84); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Size = new System.Drawing.Size(859, 22); this.statusStrip1.TabIndex = 0; this.statusStrip1.Text = "statusStrip1"; // // srcWorkspaceLabel // this.srcWorkspaceLabel.AutoSize = false; this.srcWorkspaceLabel.Name = "srcWorkspaceLabel"; this.srcWorkspaceLabel.Size = new System.Drawing.Size(422, 17); this.srcWorkspaceLabel.Spring = true; this.srcWorkspaceLabel.Text = "Select the Template Workspace"; this.srcWorkspaceLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // destWorkspaceLabel // this.destWorkspaceLabel.AutoSize = false; this.destWorkspaceLabel.Name = "destWorkspaceLabel"; this.destWorkspaceLabel.Size = new System.Drawing.Size(422, 17); this.destWorkspaceLabel.Spring = true; this.destWorkspaceLabel.Text = "Select the Implementation Workspace"; this.destWorkspaceLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // saveDLG // this.saveDLG.DefaultExt = "mdb"; this.saveDLG.Filter = "Mappings Database (*.mdb)|*.mdb"; // // conMenu // this.conMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mnuInsertConstant}); this.conMenu.Name = "conMenu"; this.conMenu.Size = new System.Drawing.Size(155, 26); this.conMenu.Text = "Insert Constant"; // // mnuInsertConstant // this.mnuInsertConstant.Name = "mnuInsertConstant"; this.mnuInsertConstant.Size = new System.Drawing.Size(154, 22); this.mnuInsertConstant.Text = "Insert Constant"; // // mapMenu // this.mapMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mnuMapConstant}); this.mapMenu.Name = "mapMenu"; this.mapMenu.Size = new System.Drawing.Size(155, 26); // // mnuMapConstant // this.mnuMapConstant.Name = "mnuMapConstant"; this.mnuMapConstant.Size = new System.Drawing.Size(154, 22); this.mnuMapConstant.Text = "Insert Constant"; // // frmMaster // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(859, 484); this.Controls.Add(this.sOne); this.Controls.Add(this.menuStrip1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.HelpButton = true; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MainMenuStrip = this.menuStrip1; this.Name = "frmMaster"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Geodatabase Schema Comparison Tool"; this.Load += new System.EventHandler(this.frmMaster_Load); this.ResizeEnd += new System.EventHandler(this.frmMaster_ResizeEnd); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.sOne.Panel1.ResumeLayout(false); this.sOne.Panel2.ResumeLayout(false); this.sOne.Panel2.PerformLayout(); this.sOne.ResumeLayout(false); this.tcTop.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); this.splitContainer1.ResumeLayout(false); this.splitContainer2.Panel1.ResumeLayout(false); this.splitContainer2.Panel2.ResumeLayout(false); this.splitContainer2.ResumeLayout(false); this.tabPage2.ResumeLayout(false); this.splitContainer3.Panel1.ResumeLayout(false); this.splitContainer3.Panel2.ResumeLayout(false); this.splitContainer3.ResumeLayout(false); this.splitContainer4.Panel1.ResumeLayout(false); this.splitContainer4.Panel2.ResumeLayout(false); this.splitContainer4.ResumeLayout(false); this.tabPage3.ResumeLayout(false); this.splitContainer7.Panel1.ResumeLayout(false); this.splitContainer7.Panel2.ResumeLayout(false); this.splitContainer7.ResumeLayout(false); this.splitContainer8.Panel1.ResumeLayout(false); this.splitContainer8.Panel2.ResumeLayout(false); this.splitContainer8.ResumeLayout(false); this.statusStrip2.ResumeLayout(false); this.statusStrip2.PerformLayout(); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); this.conMenu.ResumeLayout(false); this.mapMenu.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem mnuApplication; private System.Windows.Forms.ToolStripMenuItem mnuSource; private System.Windows.Forms.ToolStripMenuItem mnuDestination; private System.Windows.Forms.ToolStripSeparator mnuSep; private System.Windows.Forms.ToolStripMenuItem mnuExit; private System.Windows.Forms.SplitContainer sOne; private System.Windows.Forms.TabControl tcTop; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.TabPage tabPage2; private System.Windows.Forms.SplitContainer splitContainer1; private System.Windows.Forms.SplitContainer splitContainer2; private System.Windows.Forms.Label label1; private System.Windows.Forms.ListBox lbSource; private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.ToolStripStatusLabel srcWorkspaceLabel; private System.Windows.Forms.ToolStripStatusLabel destWorkspaceLabel; private System.Windows.Forms.ListBox lbDestination; private System.Windows.Forms.Label label2; private System.Windows.Forms.ToolStripMenuItem mnuAnalyze; private System.Windows.Forms.ToolStripMenuItem mnuAnalyzeAll; private System.Windows.Forms.ToolStripMenuItem mnuAnalyzeSource; private System.Windows.Forms.ToolStripMenuItem mnuAnalyzeDestination; private System.Windows.Forms.ToolStripMenuItem mnuAnalyzeInstructions; private System.Windows.Forms.ProgressBar GPB; private System.Windows.Forms.Label label3; private System.Windows.Forms.SplitContainer splitContainer3; private System.Windows.Forms.SplitContainer splitContainer4; private System.Windows.Forms.ListBox lbSrcAttributes; private System.Windows.Forms.Label lblSourceFeature; private System.Windows.Forms.ListBox lbDestAttributes; private System.Windows.Forms.Label lblDestinationFeature; private System.Windows.Forms.ListBox lstAttMappings; private System.Windows.Forms.Label label6; private System.Windows.Forms.OpenFileDialog instDLG; private System.Windows.Forms.ToolStripMenuItem mnuSaveMappings; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripMenuItem mnuRun; private System.Windows.Forms.SaveFileDialog saveDLG; private System.Windows.Forms.TabPage tabPage3; private System.Windows.Forms.SplitContainer splitContainer7; private System.Windows.Forms.ListBox lbSourceValues; private System.Windows.Forms.Label label8; private System.Windows.Forms.SplitContainer splitContainer8; private System.Windows.Forms.ListBox lbDestinationValues; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label4; private System.Windows.Forms.ListBox lstValueMappings; private System.Windows.Forms.Label label5; private System.Windows.Forms.ContextMenuStrip conMenu; private System.Windows.Forms.ToolStripMenuItem mnuInsertConstant; private System.Windows.Forms.ContextMenuStrip mapMenu; private System.Windows.Forms.ToolStripMenuItem mnuMapConstant; private System.Windows.Forms.StatusStrip statusStrip2; private System.Windows.Forms.ToolStripMenuItem mnuSourceG; private System.Windows.Forms.ToolStripMenuItem mnuSourceD; private System.Windows.Forms.ToolStripMenuItem mnuMappings; private System.Windows.Forms.ToolStripMenuItem mnuShowMappings; private System.Windows.Forms.ToolStripMenuItem mnuSaveMap; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripMenuItem mnuInitializeMap; private System.Windows.Forms.ToolStripMenuItem mnuUpdateMap; private System.Windows.Forms.RichTextBox helpBox; private System.Windows.Forms.Label lblHelp; private System.Windows.Forms.TreeView TV; private System.Windows.Forms.ImageList imgNodes; } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A web page element, like a table or an image /// </summary> public class WebPageElement_Core : TypeCore, ICreativeWork { public WebPageElement_Core() { this._TypeId = 294; this._Id = "WebPageElement"; this._Schema_Org_Url = "http://schema.org/WebPageElement"; string label = ""; GetLabel(out label, "WebPageElement", typeof(WebPageElement_Core)); this._Label = label; this._Ancestors = new int[]{266,78}; this._SubTypes = new int[]{242,259,288,289,290,291}; this._SuperTypes = new int[]{78}; this._Properties = new int[]{67,108,143,229,0,2,10,12,18,20,24,26,21,50,51,54,57,58,59,61,62,64,70,72,81,97,100,110,115,116,126,138,151,178,179,180,199,211,219,230,231}; } /// <summary> /// The subject matter of the content. /// </summary> private About_Core about; public About_Core About { get { return about; } set { about = value; SetPropertyInstance(about); } } /// <summary> /// Specifies the Person that is legally accountable for the CreativeWork. /// </summary> private AccountablePerson_Core accountablePerson; public AccountablePerson_Core AccountablePerson { get { return accountablePerson; } set { accountablePerson = value; SetPropertyInstance(accountablePerson); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// A secondary title of the CreativeWork. /// </summary> private AlternativeHeadline_Core alternativeHeadline; public AlternativeHeadline_Core AlternativeHeadline { get { return alternativeHeadline; } set { alternativeHeadline = value; SetPropertyInstance(alternativeHeadline); } } /// <summary> /// The media objects that encode this creative work. This property is a synonym for encodings. /// </summary> private AssociatedMedia_Core associatedMedia; public AssociatedMedia_Core AssociatedMedia { get { return associatedMedia; } set { associatedMedia = value; SetPropertyInstance(associatedMedia); } } /// <summary> /// An embedded audio object. /// </summary> private Audio_Core audio; public Audio_Core Audio { get { return audio; } set { audio = value; SetPropertyInstance(audio); } } /// <summary> /// The author of this content. Please note that author is special in that HTML 5 provides a special mechanism for indicating authorship via the rel tag. That is equivalent to this and may be used interchangabely. /// </summary> private Author_Core author; public Author_Core Author { get { return author; } set { author = value; SetPropertyInstance(author); } } /// <summary> /// Awards won by this person or for this creative work. /// </summary> private Awards_Core awards; public Awards_Core Awards { get { return awards; } set { awards = value; SetPropertyInstance(awards); } } /// <summary> /// Comments, typically from users, on this CreativeWork. /// </summary> private Comment_Core comment; public Comment_Core Comment { get { return comment; } set { comment = value; SetPropertyInstance(comment); } } /// <summary> /// The location of the content. /// </summary> private ContentLocation_Core contentLocation; public ContentLocation_Core ContentLocation { get { return contentLocation; } set { contentLocation = value; SetPropertyInstance(contentLocation); } } /// <summary> /// Official rating of a piece of content\u2014for example,'MPAA PG-13'. /// </summary> private ContentRating_Core contentRating; public ContentRating_Core ContentRating { get { return contentRating; } set { contentRating = value; SetPropertyInstance(contentRating); } } /// <summary> /// A secondary contributor to the CreativeWork. /// </summary> private Contributor_Core contributor; public Contributor_Core Contributor { get { return contributor; } set { contributor = value; SetPropertyInstance(contributor); } } /// <summary> /// The party holding the legal copyright to the CreativeWork. /// </summary> private CopyrightHolder_Core copyrightHolder; public CopyrightHolder_Core CopyrightHolder { get { return copyrightHolder; } set { copyrightHolder = value; SetPropertyInstance(copyrightHolder); } } /// <summary> /// The year during which the claimed copyright for the CreativeWork was first asserted. /// </summary> private CopyrightYear_Core copyrightYear; public CopyrightYear_Core CopyrightYear { get { return copyrightYear; } set { copyrightYear = value; SetPropertyInstance(copyrightYear); } } /// <summary> /// The creator/author of this CreativeWork or UserComments. This is the same as the Author property for CreativeWork. /// </summary> private Creator_Core creator; public Creator_Core Creator { get { return creator; } set { creator = value; SetPropertyInstance(creator); } } /// <summary> /// The date on which the CreativeWork was created. /// </summary> private DateCreated_Core dateCreated; public DateCreated_Core DateCreated { get { return dateCreated; } set { dateCreated = value; SetPropertyInstance(dateCreated); } } /// <summary> /// The date on which the CreativeWork was most recently modified. /// </summary> private DateModified_Core dateModified; public DateModified_Core DateModified { get { return dateModified; } set { dateModified = value; SetPropertyInstance(dateModified); } } /// <summary> /// Date of first broadcast/publication. /// </summary> private DatePublished_Core datePublished; public DatePublished_Core DatePublished { get { return datePublished; } set { datePublished = value; SetPropertyInstance(datePublished); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// A link to the page containing the comments of the CreativeWork. /// </summary> private DiscussionURL_Core discussionURL; public DiscussionURL_Core DiscussionURL { get { return discussionURL; } set { discussionURL = value; SetPropertyInstance(discussionURL); } } /// <summary> /// Specifies the Person who edited the CreativeWork. /// </summary> private Editor_Core editor; public Editor_Core Editor { get { return editor; } set { editor = value; SetPropertyInstance(editor); } } /// <summary> /// The media objects that encode this creative work /// </summary> private Encodings_Core encodings; public Encodings_Core Encodings { get { return encodings; } set { encodings = value; SetPropertyInstance(encodings); } } /// <summary> /// Genre of the creative work /// </summary> private Genre_Core genre; public Genre_Core Genre { get { return genre; } set { genre = value; SetPropertyInstance(genre); } } /// <summary> /// Headline of the article /// </summary> private Headline_Core headline; public Headline_Core Headline { get { return headline; } set { headline = value; SetPropertyInstance(headline); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// The language of the content. please use one of the language codes from the <a href=\http://tools.ietf.org/html/bcp47\>IETF BCP 47 standard.</a> /// </summary> private InLanguage_Core inLanguage; public InLanguage_Core InLanguage { get { return inLanguage; } set { inLanguage = value; SetPropertyInstance(inLanguage); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// Indicates whether this content is family friendly. /// </summary> private IsFamilyFriendly_Core isFamilyFriendly; public IsFamilyFriendly_Core IsFamilyFriendly { get { return isFamilyFriendly; } set { isFamilyFriendly = value; SetPropertyInstance(isFamilyFriendly); } } /// <summary> /// The keywords/tags used to describe this content. /// </summary> private Keywords_Core keywords; public Keywords_Core Keywords { get { return keywords; } set { keywords = value; SetPropertyInstance(keywords); } } /// <summary> /// Indicates that the CreativeWork contains a reference to, but is not necessarily about a concept. /// </summary> private Mentions_Core mentions; public Mentions_Core Mentions { get { return mentions; } set { mentions = value; SetPropertyInstance(mentions); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event. /// </summary> private Offers_Core offers; public Offers_Core Offers { get { return offers; } set { offers = value; SetPropertyInstance(offers); } } /// <summary> /// Specifies the Person or Organization that distributed the CreativeWork. /// </summary> private Provider_Core provider; public Provider_Core Provider { get { return provider; } set { provider = value; SetPropertyInstance(provider); } } /// <summary> /// The publisher of the creative work. /// </summary> private Publisher_Core publisher; public Publisher_Core Publisher { get { return publisher; } set { publisher = value; SetPropertyInstance(publisher); } } /// <summary> /// Link to page describing the editorial principles of the organization primarily responsible for the creation of the CreativeWork. /// </summary> private PublishingPrinciples_Core publishingPrinciples; public PublishingPrinciples_Core PublishingPrinciples { get { return publishingPrinciples; } set { publishingPrinciples = value; SetPropertyInstance(publishingPrinciples); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The Organization on whose behalf the creator was working. /// </summary> private SourceOrganization_Core sourceOrganization; public SourceOrganization_Core SourceOrganization { get { return sourceOrganization; } set { sourceOrganization = value; SetPropertyInstance(sourceOrganization); } } /// <summary> /// A thumbnail image relevant to the Thing. /// </summary> private ThumbnailURL_Core thumbnailURL; public ThumbnailURL_Core ThumbnailURL { get { return thumbnailURL; } set { thumbnailURL = value; SetPropertyInstance(thumbnailURL); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } /// <summary> /// The version of the CreativeWork embodied by a specified resource. /// </summary> private Version_Core version; public Version_Core Version { get { return version; } set { version = value; SetPropertyInstance(version); } } /// <summary> /// An embedded video object. /// </summary> private Video_Core video; public Video_Core Video { get { return video; } set { video = value; SetPropertyInstance(video); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Threading; using RLToolkit.Logger; namespace RLToolkit.Basic { /// <summary> /// Timer manager. /// </summary> public static class TimerManager { #region Local Variables // states private static bool isRunning = false; private static bool isVerbose = false; // ticking-related private static Thread tickThread; private static int tickCount = 0; // list related private static List<TimerManagerEventset> timerEvents = new List<TimerManagerEventset>(); private static List<TimerManagerEventset> deferredAddList = new List<TimerManagerEventset>(); private static List<string> deferredRemList = new List<string>(); private static List<string> deferredPauseList = new List<string>(); private static List<string> deferredUnpauseList = new List<string>(); private static bool deferredCleanFlag = false; #endregion #region initialization /// <summary> /// Trigger the timer start when it's first used /// </summary> static TimerManager() { LogManager.Instance.Log().Info("TimerManager started ticking."); tickThread = new Thread(tick); tickThread.Start(); tickCount = 0; } #endregion #region EventSetManagement /// <summary> /// Method to Add EventSets /// </summary> /// <returns><c>true</c>, if EventSet was added, <c>false</c> otherwise.</returns> /// <param name="ID">the Identifier to associate this EventSet to</param> /// <param name="ms">the number of milliseconds inbetween ticks</param> /// <param name="handler">The event handler to call when ticking</param> /// <param name="tickNow">If set to <c>true</c> tick as soon as possible</param> public static bool AddEventSet (string ID, int ms, TimerManagerEventHandler handler, bool tickNow) { LogManager.Instance.Log().Debug(string.Format("Adding EventSet with parameters: ID: {0}, ms: {1}, handler: {2}, tickNow: {3}", ID, ms.ToString(), handler.Method, tickNow.ToString())); if (IsIdentExist (ID)) { LogManager.Instance.Log().Debug("ID already existed. abort."); return false; } TimerManagerEventset e = new TimerManagerEventset(); e.eHandler += handler; e.timeInbetweenTick = ms; e.Id = ID; if (tickNow) { // fire at the next timer itteration e.nextTick = DateTime.UtcNow; } else { // fire after X seconds e.nextTick = DateTime.UtcNow.AddMilliseconds(ms); } LogManager.Instance.Log().Debug(string.Format("Next Tick at: {0}", e.nextTick.ToLongTimeString())); deferredAddList.Add(e); // automatically restart the timer since we added something isRunning = true; return true; } /// <summary> /// Method to remove a known EventSet /// </summary> /// <returns><c>true</c>, if the eventset was removed, <c>false</c> otherwise.</returns> /// <param name="ID">The Identifier of the EventSet to remove</param> public static bool RemoveEventSet (string ID) { LogManager.Instance.Log().Debug(string.Format("Removing EventSet with parameters: ID: {0}", ID)); if (ID.Trim() == "") { LogManager.Instance.Log().Warn("using an empty ident. Abort"); return false; } if (ID == null) { LogManager.Instance.Log().Warn("using an null ident. Abort"); return false; } deferredRemList.Add(ID); return true; } /// <summary> /// Method to fetch the number of EventSet registered. Mostly for internal use only. /// </summary> /// <returns>The EventSet count.</returns> internal static int GetEventSetsCount() { LogManager.Instance.Log().Debug(string.Format("Getting the EventSet count: {0}", timerEvents.Count)); return timerEvents.Count; } /// <summary> /// Method that Clears all the EventSet in the timer manager /// </summary> public static void ClearAllEventSets () { // schedule to wipe it LogManager.Instance.Log().Debug("Setting the flag to clear the event list."); deferredCleanFlag = true; } #endregion #region Ticking /// <summary> /// Method to start the timer /// </summary> /// <returns>always true</returns> /// <obsolete>Replaced by an automatic management of the timer</obsolete> [Obsolete("No need to call this anymore. should be handled automatically.")] public static bool StartTicking () { LogManager.Instance.Log().Debug(string.Format("Trying to activate the ticking. Current state: {0}", isRunning.ToString())); isRunning = true; return true; } /// <summary> /// Method to stop the timer /// </summary> /// <returns>always false</returns> /// <obsolete>Replaced by an automatic management of the timer</obsolete> [Obsolete("No need to call this anymore. should be handled automatically.")] public static bool StopTicking () { LogManager.Instance.Log().Debug(string.Format("Trying to deactivate the ticking. Current state: {0}", isRunning.ToString())); isRunning = false; return false; } /// <summary> /// Forces the start of the timer thread. (internal use only) /// </summary> internal static void ForceStartThread() { // force the start of the thread for unit tests if (isVerbose) { LogManager.Instance.Log().Debug("Thread status: " + tickThread.IsAlive); } if (!tickThread.IsAlive) { if (isVerbose) { LogManager.Instance.Log().Debug("Force Starting thread."); } tickThread = new Thread(tick); tickThread.Start(); tickCount = 0; } } /// <summary> /// Method that does the ticking /// </summary> private static void tick () {// tick! bool skip = false; while (true) { skip = false; if (isVerbose) { LogManager.Instance.Log().Debug("Ticking!"); } // if we're not running, don't tick if (!isRunning) { if (isVerbose) { LogManager.Instance.Log().Debug("Timer not running while ticking. Abort."); } skip = true; } if (!skip) { // increment our counter tickCount++; if (deferredCleanFlag) { LogManager.Instance.Log().Info("timer Event Cleared"); timerEvents = new List<TimerManagerEventset>(); deferredCleanFlag = false; //continue; } // make a new list that will replace the one once we're done with our tick List<TimerManagerEventset> newList = new List<TimerManagerEventset>(); // copy the lists and wipe the old one List<TimerManagerEventset> defAddListCopy = new List<TimerManagerEventset>(deferredAddList); List<string> defRemListCopy = new List<string>(deferredRemList); List<string> defPauListCopy = new List<string>(deferredPauseList); List<string> defUnpListCopy = new List<string>(deferredUnpauseList); deferredAddList = new List<TimerManagerEventset>(); deferredRemList = new List<string>(); deferredPauseList = new List<string>(); deferredUnpauseList = new List<string>(); List<TimerManagerEventset> currentList = new List<TimerManagerEventset>(timerEvents); // add the new stuff requested if (defAddListCopy.Count > 0) { LogManager.Instance.Log().Debug("Adding " + defAddListCopy.Count.ToString() + " items"); currentList.AddRange(defAddListCopy); } // check each events foreach (TimerManagerEventset t in currentList) { TimerManagerEventset newT = new TimerManagerEventset(t); if (defRemListCopy.Contains(t.Id)) { // we need to wipe that one. don't even bother readding it to the new list LogManager.Instance.Log().Debug("Removing " + t.Id); continue; } if (defPauListCopy.Contains(t.Id)) { LogManager.Instance.Log().Debug("Pausing " + t.Id); newT.isPaused = true; // we're not gonna fire since we just paused it newList.Add(newT); continue; } if (defUnpListCopy.Contains(t.Id)) { // wake that one up! LogManager.Instance.Log().Debug("Unpausing " + t.Id); newT.isPaused = false; } if (DateTime.UtcNow >= newT.nextTick) {// we're ready to tick // if we're paused, don't even bother. next! if (t.isPaused) { if (isVerbose) { LogManager.Instance.Log().Debug(string.Format("EventSet ID \"{0}\" is ready to tick but is paused.", newT.Id)); } continue; } LogManager.Instance.Log().Debug(string.Format("EventSet ID \"{0}\" is ready to tick", newT.Id)); newT.nextTick = DateTime.UtcNow.AddMilliseconds(newT.timeInbetweenTick); newList.Add(newT); LogManager.Instance.Log().Debug(string.Format("Setting new tick time for EventSet ID \"{0}\" to {1}", newT.Id, newT.nextTick.ToLongTimeString())); // fire TimerManagerEventArg param = new TimerManagerEventArg(); param.tickTime = DateTime.UtcNow; LogManager.Instance.Log().Debug("Firing event"); newT.executeEvent(new object(), param); } else { // nothing to do, just put back the data in the list newList.Add(newT); } } // swap the old list with the new updated one timerEvents = newList; } // sleep if (isVerbose) { LogManager.Instance.Log().Debug("Timer Sleeping."); } skip = false; // check if we need to tick next time isRunning = IsEventListFilled(); Thread.Sleep (1000); } } #endregion #region Helper functions /// <summary> /// Method that querry if an Identifier already exists with a provided name /// </summary> /// <returns><c>true</c> if the ident exist; otherwise, <c>false</c>.</returns> /// <param name="Ident">The identifier to look for</param> internal static bool IsIdentExist (string Ident) { return IsIdentExist(Ident, timerEvents); } /// <summary> /// Method that querry if an Identifier already exists with a provided name, in a specified list /// </summary> /// <returns><c>true</c> if the ident exist; otherwise, <c>false</c>.</returns> /// <param name="Ident">The identifier to look for</param> /// <param name="inputList">what List&lt;TimerManagerEventset&gt; to use for the search</param> internal static bool IsIdentExist (string Ident, List<TimerManagerEventset> inputList) { LogManager.Instance.Log().Debug(string.Format("Trying to find if Id \"{0}\" exists", Ident)); List<TimerManagerEventset> currentList = new List<TimerManagerEventset>(inputList); foreach (TimerManagerEventset t in currentList) { if (t.Id.ToLower() == Ident.ToLower()) { LogManager.Instance.Log().Debug("Ident found."); return true; } } LogManager.Instance.Log().Debug("Ident not found."); return false; } /// <summary> /// Method to set the pause status of an event set. /// </summary> /// <returns>Returns if the eventset was found</returns> /// <param name="Ident">the identifier to look for</param> /// <param name="isPausing">if we pause or not</param> public static bool PauseIdent(string Ident, bool isPausing) { LogManager.Instance.Log().Debug(string.Format("Trying to set pause status to {0} for the Id \"{1}\"", isPausing, Ident)); if (Ident.Trim() == "") { LogManager.Instance.Log().Warn("using an empty ident. Abort"); return false; } if (Ident == null) { LogManager.Instance.Log().Warn("using an null ident. Abort"); return false; } if (!IsIdentExist(Ident, timerEvents)) { if (!IsIdentExist(Ident, deferredAddList)) { LogManager.Instance.Log().Warn("using an ident that is not found. aborting."); return false; } } if (isPausing) { deferredPauseList.Add(Ident); } else { deferredUnpauseList.Add(Ident); } LogManager.Instance.Log().Debug("Added the ident to be paused/unpaused."); return true; } /// <summary> /// Method that verify if there's any event registered and not paused /// </summary> /// <returns>True if it does contain something not paused, else false</returns> internal static bool IsEventListFilled() { return IsEventListFilled(true); } /// <summary> /// Method that verify if there's any event registered, with the possiblity to check paused items too /// </summary> /// <param name="includePaused">If we include or not the paused events in the search</param> /// <returns>True if it does contain something, else false</returns> internal static bool IsEventListFilled(bool includePaused) { if (includePaused) { if (timerEvents.Count > 0) { // we have stuff. but... anything worth checking? List<TimerManagerEventset> currentList = new List<TimerManagerEventset>(timerEvents); foreach (TimerManagerEventset t in currentList) { if (isVerbose) { LogManager.Instance.Log().Debug("Event name: " + t.Id + " -> " + t.isPaused); } if (!t.isPaused) { // we have at least one not paused. return true; } } } // we're empty or all paused, move along. return false; } else { return (timerEvents.Count > 0); } } /// <summary> /// Forces more verbose debug info /// </summary> /// <param name="input">If set to true, will make debug info more verbose</param> public static void SetDebugVerbose(bool input) { isVerbose = input; } /// <summary> /// Resets the tick counter. /// </summary> internal static void ResetTickCounter() { LogManager.Instance.Log().Debug("reseting the tick counter."); tickCount = 0; } /// <summary> /// Gets the tick counter value /// </summary> /// <returns>The tick counter value</returns> internal static int GetTickCounter() { if (isVerbose) { LogManager.Instance.Log().Debug("Fetching the tick counter (" + tickCount + ")."); } return tickCount; } /// <summary> /// Method that will try to fetch the eventSet associated with an ID /// </summary> /// <returns>The event set if the ID is known, null if not found</returns> /// <param name="input">the ID to match</param> internal static TimerManagerEventset GetEventSetByID(string input) { if (isVerbose) { LogManager.Instance.Log().Debug("Looking for event: " + input); } List<TimerManagerEventset> currentList = new List<TimerManagerEventset>(timerEvents); foreach (TimerManagerEventset t in currentList) { if (t.Id.ToLower() == input.ToLower().Trim()) { // that's our man! return t; } } // null if we didn't found anything that matches return null; } #endregion } }
// Copyright 2020, 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. using System; using System.Collections.Generic; using System.Text; using Xunit; namespace FirebaseAdmin.Auth.Hash.Tests { public class UserImportHashTest { private static readonly byte[] SignerKey = Encoding.UTF8.GetBytes("key%20"); private static readonly byte[] SaltSeperator = Encoding.UTF8.GetBytes("separator"); [Fact] public void Base() { var hash = new MockHash(); var props = hash.GetProperties(); var expectedResult = new Dictionary<string, object> { { "key", "value" }, { "hashAlgorithm", "MockHash" }, }; Assert.Equal(expectedResult, hash.GetProperties()); } [Fact] public void ScryptHash() { var scryptHash = new Scrypt() { Rounds = 8, Key = SignerKey, SaltSeparator = SaltSeperator, MemoryCost = 13, }; var props = scryptHash.GetProperties(); var expectedResult = new Dictionary<string, object> { { "hashAlgorithm", "SCRYPT" }, { "rounds", 8 }, { "signerKey", SignerKey }, { "saltSeparator", SaltSeperator }, { "memoryCost", 13 }, }; Assert.Equal(expectedResult, scryptHash.GetProperties()); } [Fact] public void StandardScryptHash() { UserImportHash hash = new StandardScrypt() { DerivedKeyLength = 8, BlockSize = 4, Parallelization = 2, MemoryCost = 13, }; var props = hash.GetProperties(); var expectedResult = new Dictionary<string, object> { { "hashAlgorithm", "STANDARD_SCRYPT" }, { "dkLen", 8 }, { "blockSize", 4 }, { "parallization", 2 }, { "memoryCost", 13 }, }; Assert.Equal(expectedResult, hash.GetProperties()); } [Fact] public void RepeatableHashes() { var repeatableHashes = new Dictionary<string, RepeatableHash>() { { "MD5", new Md5 { Rounds = 5 } }, { "SHA1", new Sha1 { Rounds = 5 } }, { "SHA256", new Sha256 { Rounds = 5 } }, { "SHA512", new Sha512 { Rounds = 5 } }, { "PBKDF_SHA1", new PbkdfSha1 { Rounds = 5 } }, { "PBKDF2_SHA256", new Pbkdf2Sha256 { Rounds = 5 } }, }; foreach (var entry in repeatableHashes) { var expected = new Dictionary<string, object>() { { "hashAlgorithm", entry.Key }, { "rounds", 5 }, }; Assert.Equal(expected, entry.Value.GetProperties()); } } [Fact] public void RepeatableHashesNoRounds() { var repeatableHashes = new Dictionary<string, RepeatableHash>() { { "MD5", new Md5 { } }, { "SHA1", new Sha1 { } }, { "SHA256", new Sha256 { } }, { "SHA512", new Sha512 { } }, { "PBKDF_SHA1", new PbkdfSha1 { } }, { "PBKDF2_SHA256", new Pbkdf2Sha256 { } }, }; foreach (var entry in repeatableHashes) { Assert.Throws<ArgumentNullException>(() => entry.Value.GetProperties()); } } [Fact] public void HmacHashes() { var hmacHashes = new Dictionary<string, Hmac>() { { "HMAC_MD5", new HmacMd5 { Key = SignerKey } }, { "HMAC_SHA1", new HmacSha1 { Key = SignerKey } }, { "HMAC_SHA256", new HmacSha256 { Key = SignerKey } }, { "HMAC_SHA512", new HmacSha512 { Key = SignerKey } }, }; foreach (var entry in hmacHashes) { var expected = new Dictionary<string, object>() { { "hashAlgorithm", entry.Key }, { "signerKey", SignerKey }, }; Assert.Equal(expected, entry.Value.GetProperties()); } } [Fact] public void HmacHashesNoKey() { var hmacHashes = new Dictionary<string, Hmac>() { { "HMAC_MD5", new HmacMd5 { } }, { "HMAC_SHA1", new HmacSha1 { } }, { "HMAC_SHA256", new HmacSha256 { } }, { "HMAC_SHA512", new HmacSha512 { } }, }; foreach (var entry in hmacHashes) { Assert.Throws<ArgumentException>(() => entry.Value.GetProperties()); } } [Fact] public void RepeatableHashRoundsTooLow() { Assert.Throws<ArgumentException>(() => new Md5 { Rounds = -1 }.GetProperties()); Assert.Throws<ArgumentException>(() => new Sha1 { Rounds = 0 }.GetProperties()); Assert.Throws<ArgumentException>(() => new Sha256 { Rounds = 0 }.GetProperties()); Assert.Throws<ArgumentException>(() => new Sha512 { Rounds = 0 }.GetProperties()); Assert.Throws<ArgumentException>(() => new PbkdfSha1 { Rounds = -1 }.GetProperties()); Assert.Throws<ArgumentException>( () => new Pbkdf2Sha256 { Rounds = -1 }.GetProperties()); } [Fact] public void RepeatableHashRoundsTooHigh() { Assert.Throws<ArgumentException>(() => new Md5 { Rounds = 8193 }.GetProperties()); Assert.Throws<ArgumentException>(() => new Sha1 { Rounds = 8193 }.GetProperties()); Assert.Throws<ArgumentException>(() => new Sha256 { Rounds = 8193 }.GetProperties()); Assert.Throws<ArgumentException>(() => new Sha512 { Rounds = 8193 }.GetProperties()); Assert.Throws<ArgumentException>( () => new PbkdfSha1 { Rounds = 120001 }.GetProperties()); Assert.Throws<ArgumentException>( () => new Pbkdf2Sha256 { Rounds = 120001 }.GetProperties()); } [Fact] public void ScryptHashConstraintsTooLow() { var scryptHash = new Scrypt() { Rounds = -1, Key = SignerKey, SaltSeparator = SaltSeperator, MemoryCost = 3, }; Assert.Throws<ArgumentException>(() => scryptHash.GetProperties()); scryptHash = new Scrypt() { Rounds = 3, Key = SignerKey, SaltSeparator = SaltSeperator, MemoryCost = 0, }; Assert.Throws<ArgumentException>(() => scryptHash.GetProperties()); } [Fact] public void ScryptHashConstraintsTooHigh() { var scryptHash = new Scrypt() { Rounds = 9, Key = SignerKey, SaltSeparator = SaltSeperator, MemoryCost = 3, }; Assert.Throws<ArgumentException>(() => scryptHash.GetProperties()); scryptHash = new Scrypt() { Rounds = 3, Key = SignerKey, SaltSeparator = SaltSeperator, MemoryCost = 15, }; Assert.Throws<ArgumentException>(() => scryptHash.GetProperties()); } [Fact] public void StandardScryptHashConstraintsTooLow() { var standardScryptHash = new StandardScrypt() { DerivedKeyLength = -1, BlockSize = 4, Parallelization = 2, MemoryCost = 13, }; Assert.Throws<ArgumentException>(() => standardScryptHash.GetProperties()); standardScryptHash = new StandardScrypt() { DerivedKeyLength = 2, BlockSize = -1, Parallelization = 2, MemoryCost = 13, }; Assert.Throws<ArgumentException>(() => standardScryptHash.GetProperties()); standardScryptHash = new StandardScrypt() { DerivedKeyLength = 2, BlockSize = 4, Parallelization = -2, MemoryCost = 13, }; Assert.Throws<ArgumentException>(() => standardScryptHash.GetProperties()); standardScryptHash = new StandardScrypt() { DerivedKeyLength = 2, BlockSize = 4, Parallelization = 2, MemoryCost = -1, }; Assert.Throws<ArgumentException>(() => standardScryptHash.GetProperties()); } [Fact] public void InstantiateInvalidHashType() { Assert.Throws<ArgumentException>(() => new InvalidHashType(null)); Assert.Throws<ArgumentException>(() => new InvalidHashType(string.Empty)); } private class MockHash : UserImportHash { public MockHash() : base("MockHash") { } protected override IReadOnlyDictionary<string, object> GetHashConfiguration() { return new Dictionary<string, object> { { "key", "value" }, }; } } private class InvalidHashType : UserImportHash { public InvalidHashType(string hashName) : base(hashName) { } protected override IReadOnlyDictionary<string, object> GetHashConfiguration() { return new Dictionary<string, object> { { "key", "value" }, }; } } } }
using System; using Autofac; using FluentAssertions; using ScopedUnitOfWork.Interfaces; using ScopedUnitOfWork.Interfaces.Exceptions; using ScopedUnitOfWork.Tests.AcceptanceTests.SampleApplication.SimpleDomain; using Xunit; namespace ScopedUnitOfWork.Tests.AcceptanceTests { [Collection("SequentialTests")] public class UnitOfWorkUsageTestsBase : AcceptanceTestBase { public UnitOfWorkUsageTestsBase() { TestsConfiguration.CreateApplication(); } protected override IContainer Container => TestsConfiguration.Container; [Fact] public void MultipleCommitCallsShouldFail() { using (var uow = GetFactory().Create()) { uow.Commit(); Action action = () => uow.Commit(); action.Should().Throw<InvalidOperationException>("*already committed*"); } } [Fact] public void MultipleDisposeCallsShouldWork() { var uow = GetFactory().Create(); Action action = () => { uow.Dispose(); uow.Dispose(); uow.Dispose(); }; action.Should().NotThrow(); } [Fact] public void UsingUnitsOfWorkWithoutUsingStatementShouldFail() { // using "using" statements guarantees stack-like nature of units of work, which is // how it is internally implemented. This means disposing outside uow before inner is disposed // is not allowed! // case 1 using (var uow = GetFactory().Create()) { using (GetFactory().Create()) { Action action1 = () => uow.Dispose(); action1.Should().Throw<IncorrectUnitOfWorkUsageException>(); } } // case 2 var uowA = GetFactory().Create(); var uowB = GetFactory().Create(); Action action2 = () => uowA.Dispose(); action2.Should().Throw<IncorrectUnitOfWorkUsageException>(); // should be fine uowB.Dispose(); uowA.Dispose(); } [Fact] public void Create_ShouldThrow_WhenRequestingTransactionalButTransactionsNotSupported() { var uow = GetFactory().Create(); Action action = () => { uow.Dispose(); uow.Dispose(); uow.Dispose(); }; action.Should().NotThrow(); } [Fact] public void Commit_ShouldThrow_WhenInnerTransactionalUnitOfWorkRolledBack() { using (var uow = GetFactory().Create(ScopeType.Transactional)) { using (GetFactory().Create(ScopeType.Transactional)) { // not commit called here, means will rollback (dispose) } Action action = () => uow.Commit(); action.Should().Throw<TransactionFailedException>(); } } [Fact] public void Commit_ShouldThrow_WhenUnitOfWorkAlreadyDisposed() { var uow = GetFactory().Create(); uow.Dispose(); Action action = () => uow.Commit(); action.Should().Throw<InvalidOperationException>("*disposed*"); } [Fact] public void Commit_ShouldNotThrow_WhenInnerTransactionalUnitOfWorkRolledBack_ButItselfIsNotTransactional() { // note here: not transactional! using (var uow = GetFactory().Create()) { using (GetFactory().Create(ScopeType.Transactional)) { // not commit called here, means will rollback (dispose) } Action action = () => uow.Commit(); action.Should().NotThrow(); } } [Fact] public void ShouldRollbackCorrectlyWhenExplodesDueToExceptions() { var shouldNotBeThereCustomer = CustomerGenerator.Generate(); using (IUnitOfWork uowOuter = GetFactory().Create(ScopeType.Transactional)) { uowOuter.GetRepository<ICustomerRepository>() .Add(shouldNotBeThereCustomer); using (IUnitOfWork uowInner = GetFactory().Create()) { try { uowInner.GetRepository<ICustomerRepository>() .Add(new Customer()); // well this should fail uowInner.Commit(); } catch (Exception) { // ignored completely. Although suppressing all // it is the only way to support all implementations // since they differ in exceptions thrown } } try { uowOuter.Commit(); } catch (Exception) { // ignored completely. } } using (IUnitOfWork uow = GetFactory().Create()) { uow.GetRepository<ICustomerRepository>() .FindByName(shouldNotBeThereCustomer.Name) .Should().BeNull(); } } [Fact] public void ComplexUsageScenario() { var firstCustomer = CustomerGenerator.Generate(); var secondCustomer = CustomerGenerator.Generate(); var thirdCustomer = CustomerGenerator.Generate(); // Arrange using (var uow = GetFactory().Create()) { uow.GetRepository<ICustomerRepository>().Add(firstCustomer); uow.Commit(); } // Act // our controller or some other top level service (maybe on application services layer) // opens a spanning context using (var spanningUnitOfWork = GetFactory().Create()) { var repository = spanningUnitOfWork.GetRepository<ICustomerRepository>(); Customer customer = repository.FindByName(firstCustomer.Name); // let's say this was a authorization check or something customer.Name.Should().Be(firstCustomer.Name); // now we want to call a business service which would have its own transactional unit of work in there using (var businessUnitOfWork = GetFactory().Create(ScopeType.Transactional)) { using (var firstDomainService = GetFactory().Create()) { firstDomainService.GetRepository<ICustomerRepository>() .Add(secondCustomer); firstDomainService.Commit(); } using (var secondDomainService = GetFactory().Create()) { secondDomainService.GetRepository<ICustomerRepository>() .Add(thirdCustomer); secondDomainService.Commit(); } // this should commit the transaction as its the top most transactional uow businessUnitOfWork.Commit(); } } // Assert using (var verificationUoW = GetFactory().Create()) { verificationUoW.GetRepository<ICustomerRepository>() .FindByName(secondCustomer.Name).Should().NotBeNull(); verificationUoW.GetRepository<ICustomerRepository>() .FindByName(thirdCustomer.Name).Should().NotBeNull(); } } } }
/* * 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 cloudfront-2015-07-27.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.CloudFront.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.CloudFront.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for UpdateDistribution operation /// </summary> public class UpdateDistributionResponseUnmarshaller : XmlResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { UpdateDistributionResponse response = new UpdateDistributionResponse(); UnmarshallResult(context,response); if (context.ResponseData.IsHeaderPresent("ETag")) response.ETag = context.ResponseData.GetHeaderValue("ETag"); return response; } private static void UnmarshallResult(XmlUnmarshallerContext context, UpdateDistributionResponse response) { int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; while (context.Read()) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("Distribution", targetDepth)) { var unmarshaller = DistributionUnmarshaller.Instance; response.Distribution = unmarshaller.Unmarshall(context); continue; } } else if (context.IsEndElement && context.CurrentDepth < originalDepth) { return; } } return; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context); if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDenied")) { return new AccessDeniedException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("CNAMEAlreadyExists")) { return new CNAMEAlreadyExistsException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("IllegalUpdate")) { return new IllegalUpdateException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InconsistentQuantities")) { return new InconsistentQuantitiesException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidArgument")) { return new InvalidArgumentException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidDefaultRootObject")) { return new InvalidDefaultRootObjectException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidErrorCode")) { return new InvalidErrorCodeException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidForwardCookies")) { return new InvalidForwardCookiesException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidGeoRestrictionParameter")) { return new InvalidGeoRestrictionParameterException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidHeadersForS3Origin")) { return new InvalidHeadersForS3OriginException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidIfMatchVersion")) { return new InvalidIfMatchVersionException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidLocationCode")) { return new InvalidLocationCodeException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidMinimumProtocolVersion")) { return new InvalidMinimumProtocolVersionException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidOriginAccessIdentity")) { return new InvalidOriginAccessIdentityException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidRelativePath")) { return new InvalidRelativePathException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidRequiredProtocol")) { return new InvalidRequiredProtocolException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidResponseCode")) { return new InvalidResponseCodeException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidTTLOrder")) { return new InvalidTTLOrderException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidViewerCertificate")) { return new InvalidViewerCertificateException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidWebACLId")) { return new InvalidWebACLIdException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("MissingBody")) { return new MissingBodyException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("NoSuchDistribution")) { return new NoSuchDistributionException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("NoSuchOrigin")) { return new NoSuchOriginException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("PreconditionFailed")) { return new PreconditionFailedException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyCacheBehaviors")) { return new TooManyCacheBehaviorsException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyCertificates")) { return new TooManyCertificatesException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyCookieNamesInWhiteList")) { return new TooManyCookieNamesInWhiteListException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyDistributionCNAMEs")) { return new TooManyDistributionCNAMEsException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyHeadersInForwardedValues")) { return new TooManyHeadersInForwardedValuesException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyOrigins")) { return new TooManyOriginsException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyTrustedSigners")) { return new TooManyTrustedSignersException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("TrustedSignerDoesNotExist")) { return new TrustedSignerDoesNotExistException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } return new AmazonCloudFrontException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static UpdateDistributionResponseUnmarshaller _instance = new UpdateDistributionResponseUnmarshaller(); internal static UpdateDistributionResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static UpdateDistributionResponseUnmarshaller Instance { get { return _instance; } } } }
/* * REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application * * The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists. * * OpenAPI spec version: v1 * * */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Swashbuckle.SwaggerGen.Annotations; using HETSAPI.Models; using HETSAPI.ViewModels; using HETSAPI.Services; using HETSAPI.Authorization; namespace HETSAPI.Controllers { /// <summary> /// /// </summary> public partial class OwnerController : Controller { private readonly IOwnerService _service; /// <summary> /// Create a controller and set the service /// </summary> public OwnerController(IOwnerService service) { _service = service; } /// <summary> /// /// </summary> /// <param name="items"></param> /// <response code="201">Owner created</response> [HttpPost] [Route("/api/owners/bulk")] [SwaggerOperation("OwnersBulkPost")] [RequiresPermission(Permission.ADMIN)] public virtual IActionResult OwnersBulkPost([FromBody]Owner[] items) { return this._service.OwnersBulkPostAsync(items); } /// <summary> /// /// </summary> /// <response code="200">OK</response> [HttpGet] [Route("/api/owners")] [SwaggerOperation("OwnersGet")] [SwaggerResponse(200, type: typeof(List<Owner>))] public virtual IActionResult OwnersGet() { return this._service.OwnersGetAsync(); } /// <summary> /// /// </summary> /// <remarks>Returns attachments for a particular Owner</remarks> /// <param name="id">id of Owner to fetch attachments for</param> /// <response code="200">OK</response> /// <response code="404">Owner not found</response> [HttpGet] [Route("/api/owners/{id}/attachments")] [SwaggerOperation("OwnersIdAttachmentsGet")] [SwaggerResponse(200, type: typeof(List<AttachmentViewModel>))] public virtual IActionResult OwnersIdAttachmentsGet([FromRoute]int id) { return this._service.OwnersIdAttachmentsGetAsync(id); } /// <summary> /// /// </summary> /// <remarks>Gets an Owner&#39;s Contacts</remarks> /// <param name="id">id of Owner to fetch Contacts for</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/owners/{id}/contacts")] [SwaggerOperation("OwnersIdContactsGet")] [SwaggerResponse(200, type: typeof(List<Contact>))] public virtual IActionResult OwnersIdContactsGet([FromRoute]int id) { return this._service.OwnersIdContactsGetAsync(id); } /// <summary> /// /// </summary> /// <remarks>Adds Owner Contact</remarks> /// <param name="id">id of Owner to add a contact for</param> /// <param name="item">Adds to Owner Contact</param> /// <response code="200">OK</response> [HttpPost] [Route("/api/owners/{id}/contacts")] [SwaggerOperation("OwnersIdContactsPost")] [SwaggerResponse(200, type: typeof(Contact))] public virtual IActionResult OwnersIdContactsPost([FromRoute]int id, [FromBody]Contact item) { return this._service.OwnersIdContactsPostAsync(id, item); } /// <summary> /// /// </summary> /// <remarks>Replaces an Owner&#39;s Contacts</remarks> /// <param name="id">id of Owner to replace Contacts for</param> /// <param name="item">Replacement Owner contacts.</param> /// <response code="200">OK</response> [HttpPut] [Route("/api/owners/{id}/contacts")] [SwaggerOperation("OwnersIdContactsPut")] [SwaggerResponse(200, type: typeof(List<Contact>))] public virtual IActionResult OwnersIdContactsPut([FromRoute]int id, [FromBody]Contact[] item) { return this._service.OwnersIdContactsPutAsync(id, item); } /// <summary> /// /// </summary> /// <param name="id">id of Owner to delete</param> /// <response code="200">OK</response> /// <response code="404">Owner not found</response> [HttpPost] [Route("/api/owners/{id}/delete")] [SwaggerOperation("OwnersIdDeletePost")] public virtual IActionResult OwnersIdDeletePost([FromRoute]int id) { return this._service.OwnersIdDeletePostAsync(id); } /// <summary> /// /// </summary> /// <remarks>Gets an Owner&#39;s Equipment</remarks> /// <param name="id">id of Owner to fetch Equipment for</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/owners/{id}/equipment")] [SwaggerOperation("OwnersIdEquipmentGet")] [SwaggerResponse(200, type: typeof(List<Equipment>))] public virtual IActionResult OwnersIdEquipmentGet([FromRoute]int id) { return this._service.OwnersIdEquipmentGetAsync(id); } /// <summary> /// /// </summary> /// <remarks>Replaces an Owner&#39;s Equipment</remarks> /// <param name="id">id of Owner to replace Equipment for</param> /// <param name="item">Replacement Owner Equipment.</param> /// <response code="200">OK</response> [HttpPut] [Route("/api/owners/{id}/equipment")] [SwaggerOperation("OwnersIdEquipmentPut")] [SwaggerResponse(200, type: typeof(List<Equipment>))] public virtual IActionResult OwnersIdEquipmentPut([FromRoute]int id, [FromBody]Equipment[] item) { return this._service.OwnersIdEquipmentPutAsync(id, item); } /// <summary> /// /// </summary> /// <param name="id">id of Owner to fetch</param> /// <response code="200">OK</response> /// <response code="404">Owner not found</response> [HttpGet] [Route("/api/owners/{id}")] [SwaggerOperation("OwnersIdGet")] [SwaggerResponse(200, type: typeof(Owner))] public virtual IActionResult OwnersIdGet([FromRoute]int id) { return this._service.OwnersIdGetAsync(id); } /// <summary> /// /// </summary> /// <remarks>Returns History for a particular Owner</remarks> /// <param name="id">id of Owner to fetch History for</param> /// <param name="offset">offset for records that are returned</param> /// <param name="limit">limits the number of records returned.</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/owners/{id}/history")] [SwaggerOperation("OwnersIdHistoryGet")] [SwaggerResponse(200, type: typeof(List<HistoryViewModel>))] public virtual IActionResult OwnersIdHistoryGet([FromRoute]int id, [FromQuery]int? offset, [FromQuery]int? limit) { return this._service.OwnersIdHistoryGetAsync(id, offset, limit); } /// <summary> /// /// </summary> /// <remarks>Add a History record to the Owner</remarks> /// <param name="id">id of Owner to add History for</param> /// <param name="item"></param> /// <response code="200">OK</response> /// <response code="201">History created</response> [HttpPost] [Route("/api/owners/{id}/history")] [SwaggerOperation("OwnersIdHistoryPost")] public virtual IActionResult OwnersIdHistoryPost([FromRoute]int id, [FromBody]History item) { return this._service.OwnersIdHistoryPostAsync(id, item); } /// <summary> /// /// </summary> /// <param name="id">id of Owner to fetch</param> /// <param name="item"></param> /// <response code="200">OK</response> /// <response code="404">Owner not found</response> [HttpPut] [Route("/api/owners/{id}")] [SwaggerOperation("OwnersIdPut")] [SwaggerResponse(200, type: typeof(Owner))] public virtual IActionResult OwnersIdPut([FromRoute]int id, [FromBody]Owner item) { return this._service.OwnersIdPutAsync(id, item); } /// <summary> /// /// </summary> /// <param name="item"></param> /// <response code="201">Owner created</response> [HttpPost] [Route("/api/owners")] [SwaggerOperation("OwnersPost")] [SwaggerResponse(200, type: typeof(Owner))] public virtual IActionResult OwnersPost([FromBody]Owner item) { return this._service.OwnersPostAsync(item); } /// <summary> /// Searches Owners /// </summary> /// <remarks>Used for the owner search page.</remarks> /// <param name="localareas">Local Areas (comma seperated list of id numbers)</param> /// <param name="equipmenttypes">Equipment Types (comma seperated list of id numbers)</param> /// <param name="owner">Id for a specific Owner</param> /// <param name="status">Status</param> /// <param name="hired">Hired</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/owners/search")] [SwaggerOperation("OwnersSearchGet")] [SwaggerResponse(200, type: typeof(List<Owner>))] public virtual IActionResult OwnersSearchGet([FromQuery]string localareas, [FromQuery]string equipmenttypes, [FromQuery]int? owner, [FromQuery]string status, [FromQuery]bool? hired) { return this._service.OwnersSearchGetAsync(localareas, equipmenttypes, owner, status, hired); } } }
namespace Loon.Core.Graphics.Opengl { using System; using Loon.Core.Graphics.Opengl; using Loon.Core.Graphics; public class GLUtils { private static int currentHardwareTextureID = -1; private static int currentSourceBlendMode = -1; private static int currentDestinationBlendMode = -1; private static bool enableDither = true; private static bool enableLightning = true; private static bool enableDepthTest = true; private static bool enablecissorTest = false; private static bool enableBlend = false; private static bool enableCulling = false; private static bool enableTextures = false; private static bool enableTexCoordArray = false; private static bool enableTexColorArray = false; private static bool enableVertexArray = false; private static float red = -1; private static float green = -1; private static float blue = -1; private static float alpha = -1; public static void Reset(GL gl) { GLUtils.currentHardwareTextureID = -1; GLUtils.currentSourceBlendMode = -1; GLUtils.currentDestinationBlendMode = -1; GLUtils.DisableBlend(gl); GLUtils.DisableCulling(gl); GLUtils.DisableTextures(gl); GLUtils.DisableTexCoordArray(gl); GLUtils.DisableTexColorArray(gl); GLUtils.DisableVertexArray(gl); GLUtils.red = -1; GLUtils.green = -1; GLUtils.blue = -1; GLUtils.alpha = -1; } public static void SetClearColor(GL gl10, LColor c) { GLUtils.SetColor(gl10, c.r, c.g, c.b, c.a); } public static void SetColor(GL gl10, float r, float g, float b, float a) { if (a != GLUtils.alpha || r != GLUtils.red || g != GLUtils.green || b != GLUtils.blue) { GLUtils.alpha = a; GLUtils.red = r; GLUtils.green = g; GLUtils.blue = b; gl10.GLColor4f(r, g, b, a); } } public static void EnableVertexArray(GL gl10) { if (!GLUtils.enableVertexArray) { GLUtils.enableVertexArray = true; gl10.GLEnableClientState(GL.GL_VERTEX_ARRAY); } } public static void DisableVertexArray(GL gl10) { if (GLUtils.enableVertexArray) { GLUtils.enableVertexArray = false; gl10.GLDisableClientState(GL.GL_VERTEX_ARRAY); } } public static void Reload() { GLUtils.currentHardwareTextureID = -1; GLUtils.currentSourceBlendMode = -1; GLUtils.currentDestinationBlendMode = -1; GLUtils.red = -1; GLUtils.green = -1; GLUtils.blue = -1; GLUtils.alpha = -1; GLUtils.enableDither = true; GLUtils.enableLightning = true; GLUtils.enableDepthTest = true; GLUtils.enablecissorTest = false; GLUtils.enableBlend = false; GLUtils.enableCulling = false; GLUtils.enableTextures = false; GLUtils.enableTexCoordArray = false; GLUtils.enableTexColorArray = false; GLUtils.enableVertexArray = false; } public static void EnableTexCoordArray(GL gl10) { if (!GLUtils.enableTexCoordArray) { GLUtils.enableTexCoordArray = true; gl10.GLEnableClientState(GL.GL_TEXTURE_COORD_ARRAY); } } public static void DisableTexCoordArray(GL gl10) { if (GLUtils.enableTexCoordArray) { GLUtils.enableTexCoordArray = false; gl10.GLDisableClientState(GL.GL_TEXTURE_COORD_ARRAY); } } public static void EnableTexColorArray(GL gl10) { if (!GLUtils.enableTexColorArray) { GLUtils.enableTexColorArray = true; gl10.GLEnableClientState(GL.GL_COLOR_ARRAY); } } public static void DisableTexColorArray(GL gl10) { if (GLUtils.enableTexColorArray) { GLUtils.enableTexColorArray = false; gl10.GLDisableClientState(GL.GL_COLOR_ARRAY); } } public static void EnablecissorTest(GL gl10) { if (!GLUtils.enablecissorTest) { GLUtils.enablecissorTest = true; gl10.GLEnable(GL.GL_SCISSOR_TEST); } } public static void DisablecissorTest(GL gl10) { if (GLUtils.enablecissorTest) { GLUtils.enablecissorTest = false; gl10.GLDisable(GL.GL_SCISSOR_TEST); } } public static void EnableBlend(GL gl10) { if (!GLUtils.enableBlend) { gl10.GLEnable(GL.GL_BLEND); GLUtils.enableBlend = true; } } public static void DisableBlend(GL gl10) { if (GLUtils.enableBlend) { gl10.GLDisable(GL.GL_BLEND); GLUtils.enableBlend = false; } } public static void DisableCulling(GL gl10) { if (GLUtils.enableCulling) { GLUtils.enableCulling = false; gl10.GLDisable(GL.GL_CULL_FACE); } } public static void EnableTextures(GL gl10) { if (!GLUtils.enableTextures) { GLUtils.enableTextures = true; gl10.GLEnable(GL.GL_TEXTURE_2D); } } public static void DisableTextures(GL gl10) { if (GLUtils.enableTextures) { GLUtils.enableTextures = false; gl10.GLDisable(GL.GL_TEXTURE_2D); } } public static void EnableLightning(GL gl10) { if (!GLUtils.enableLightning) { GLUtils.enableLightning = true; gl10.GLEnable(GL.GL_LIGHTING); } } public static void DisableLightning(GL gl10) { if (GLUtils.enableLightning) { GLUtils.enableLightning = false; gl10.GLDisable(GL.GL_LIGHTING); } } public static void EnableDither(GL gl10) { if (!GLUtils.enableDither) { GLUtils.enableDither = true; gl10.GLEnable(GL.GL_DITHER); } } public static void DisableDither(GL gl10) { if (GLUtils.enableDither) { GLUtils.enableDither = false; gl10.GLDisable(GL.GL_DITHER); } } public static void EnableDepthTest(GL gl10) { if (!GLUtils.enableDepthTest) { GLUtils.enableDepthTest = true; gl10.GLEnable(GL.GL_DEPTH_TEST); gl10.GLDepthMask(true); } } public static void DisableDepthTest(GL gl10) { if (GLUtils.enableDepthTest) { GLUtils.enableDepthTest = false; gl10.GLDisable(GL.GL_DEPTH_TEST); gl10.GLDepthMask(false); } } public static void BindTexture(GL gl10, int hardwareTextureID) { if (GLUtils.currentHardwareTextureID != hardwareTextureID) { GLUtils.currentHardwareTextureID = hardwareTextureID; gl10.GLBindTexture(GL.GL_TEXTURE_2D, hardwareTextureID); } } public static void BlendFunction(GL gl10, int pSourceBlendMode, int pDestinationBlendMode) { if (GLUtils.currentSourceBlendMode != pSourceBlendMode || GLUtils.currentDestinationBlendMode != pDestinationBlendMode) { GLUtils.currentSourceBlendMode = pSourceBlendMode; GLUtils.currentDestinationBlendMode = pDestinationBlendMode; gl10.GLBlendFunc(pSourceBlendMode, pDestinationBlendMode); } } public static void SetShadeModelSmooth(GL gl10) { gl10.GLShadeModel(GL.GL_SMOOTH); } public static void SetShadeModelFlat(GL gl10) { gl10.GLShadeModel(GL.GL_FLAT); } public static void SetHintFastest(GL gl10) { gl10.GLHint(GL.GL_PERSPECTIVE_CORRECTION_HINT, GL.GL_FASTEST); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NUnit.Framework; using CorruptIndexException = Lucene.Net.Index.CorruptIndexException; using IndexReader = Lucene.Net.Index.IndexReader; using IndexSearcher = Lucene.Net.Search.IndexSearcher; using Query = Lucene.Net.Search.Query; using QueryUtils = Lucene.Net.Search.QueryUtils; using ScoreDoc = Lucene.Net.Search.ScoreDoc; using TopDocs = Lucene.Net.Search.TopDocs; namespace Lucene.Net.Search.Function { /// <summary> Test FieldScoreQuery search. /// <p/> /// Tests here create an index with a few documents, each having /// an int value indexed field and a float value indexed field. /// The values of these fields are later used for scoring. /// <p/> /// The rank tests use Hits to verify that docs are ordered (by score) as expected. /// <p/> /// The exact score tests use TopDocs top to verify the exact score. /// </summary> [TestFixture] public class TestFieldScoreQuery:FunctionTestSetup { /* @override constructor */ public TestFieldScoreQuery(System.String name):base(name, true) { } public TestFieldScoreQuery() : base() { } /// <summary>Test that FieldScoreQuery of Type.BYTE returns docs in expected order. </summary> [Test] public virtual void TestRankByte() { // INT field values are small enough to be parsed as byte DoTestRank(INT_FIELD, FieldScoreQuery.Type.BYTE); } /// <summary>Test that FieldScoreQuery of Type.SHORT returns docs in expected order. </summary> [Test] public virtual void TestRankShort() { // INT field values are small enough to be parsed as short DoTestRank(INT_FIELD, FieldScoreQuery.Type.SHORT); } /// <summary>Test that FieldScoreQuery of Type.INT returns docs in expected order. </summary> [Test] public virtual void TestRankInt() { DoTestRank(INT_FIELD, FieldScoreQuery.Type.INT); } /// <summary>Test that FieldScoreQuery of Type.FLOAT returns docs in expected order. </summary> [Test] public virtual void TestRankFloat() { // INT field can be parsed as float DoTestRank(INT_FIELD, FieldScoreQuery.Type.FLOAT); // same values, but in flot format DoTestRank(FLOAT_FIELD, FieldScoreQuery.Type.FLOAT); } // Test that FieldScoreQuery returns docs in expected order. private void DoTestRank(System.String field, FieldScoreQuery.Type tp) { IndexSearcher s = new IndexSearcher(dir, true); Query q = new FieldScoreQuery(field, tp); Log("test: " + q); QueryUtils.Check(q, s); ScoreDoc[] h = s.Search(q, null, 1000).ScoreDocs; Assert.AreEqual(N_DOCS, h.Length, "All docs should be matched!"); System.String prevID = "ID" + (N_DOCS + 1); // greater than all ids of docs in this test for (int i = 0; i < h.Length; i++) { System.String resID = s.Doc(h[i].Doc).Get(ID_FIELD); Log(i + ". score=" + h[i].Score + " - " + resID); Log(s.Explain(q, h[i].Doc)); Assert.IsTrue(String.CompareOrdinal(resID, prevID) < 0, "res id " + resID + " should be < prev res id " + prevID); prevID = resID; } } /// <summary>Test that FieldScoreQuery of Type.BYTE returns the expected scores. </summary> [Test] public virtual void TestExactScoreByte() { // INT field values are small enough to be parsed as byte DoTestExactScore(INT_FIELD, FieldScoreQuery.Type.BYTE); } /// <summary>Test that FieldScoreQuery of Type.SHORT returns the expected scores. </summary> [Test] public virtual void TestExactScoreShort() { // INT field values are small enough to be parsed as short DoTestExactScore(INT_FIELD, FieldScoreQuery.Type.SHORT); } /// <summary>Test that FieldScoreQuery of Type.INT returns the expected scores. </summary> [Test] public virtual void TestExactScoreInt() { DoTestExactScore(INT_FIELD, FieldScoreQuery.Type.INT); } /// <summary>Test that FieldScoreQuery of Type.FLOAT returns the expected scores. </summary> [Test] public virtual void TestExactScoreFloat() { // INT field can be parsed as float DoTestExactScore(INT_FIELD, FieldScoreQuery.Type.FLOAT); // same values, but in flot format DoTestExactScore(FLOAT_FIELD, FieldScoreQuery.Type.FLOAT); } // Test that FieldScoreQuery returns docs with expected score. private void DoTestExactScore(System.String field, FieldScoreQuery.Type tp) { IndexSearcher s = new IndexSearcher(dir, true); Query q = new FieldScoreQuery(field, tp); TopDocs td = s.Search(q, null, 1000); Assert.AreEqual(N_DOCS, td.TotalHits, "All docs should be matched!"); ScoreDoc[] sd = td.ScoreDocs; for (int i = 0; i < sd.Length; i++) { float score = sd[i].Score; Log(s.Explain(q, sd[i].Doc)); System.String id = s.IndexReader.Document(sd[i].Doc).Get(ID_FIELD); float expectedScore = ExpectedFieldScore(id); // "ID7" --> 7.0 Assert.AreEqual(expectedScore, score, TEST_SCORE_TOLERANCE_DELTA, "score of " + id + " shuould be " + expectedScore + " != " + score); } } /// <summary>Test that FieldScoreQuery of Type.BYTE caches/reuses loaded values and consumes the proper RAM resources. </summary> [Test] public virtual void TestCachingByte() { // INT field values are small enough to be parsed as byte DoTestCaching(INT_FIELD, FieldScoreQuery.Type.BYTE); } /// <summary>Test that FieldScoreQuery of Type.SHORT caches/reuses loaded values and consumes the proper RAM resources. </summary> [Test] public virtual void TestCachingShort() { // INT field values are small enough to be parsed as short DoTestCaching(INT_FIELD, FieldScoreQuery.Type.SHORT); } /// <summary>Test that FieldScoreQuery of Type.INT caches/reuses loaded values and consumes the proper RAM resources. </summary> [Test] public virtual void TestCachingInt() { DoTestCaching(INT_FIELD, FieldScoreQuery.Type.INT); } /// <summary>Test that FieldScoreQuery of Type.FLOAT caches/reuses loaded values and consumes the proper RAM resources. </summary> [Test] public virtual void TestCachingFloat() { // INT field values can be parsed as float DoTestCaching(INT_FIELD, FieldScoreQuery.Type.FLOAT); // same values, but in flot format DoTestCaching(FLOAT_FIELD, FieldScoreQuery.Type.FLOAT); } // Test that values loaded for FieldScoreQuery are cached properly and consumes the proper RAM resources. private void DoTestCaching(System.String field, FieldScoreQuery.Type tp) { // prepare expected array types for comparison System.Collections.Hashtable expectedArrayTypes = new System.Collections.Hashtable(); expectedArrayTypes[FieldScoreQuery.Type.BYTE] = new sbyte[0]; expectedArrayTypes[FieldScoreQuery.Type.SHORT] = new short[0]; expectedArrayTypes[FieldScoreQuery.Type.INT] = new int[0]; expectedArrayTypes[FieldScoreQuery.Type.FLOAT] = new float[0]; IndexSearcher s = new IndexSearcher(dir, true); System.Object[] innerArray = new Object[s.IndexReader.GetSequentialSubReaders().Length]; bool warned = false; // print warning once. for (int i = 0; i < 10; i++) { FieldScoreQuery q = new FieldScoreQuery(field, tp); ScoreDoc[] h = s.Search(q, null, 1000).ScoreDocs; Assert.AreEqual(N_DOCS, h.Length, "All docs should be matched!"); IndexReader[] readers = s.IndexReader.GetSequentialSubReaders(); for (int j = 0; j < readers.Length; j++) { IndexReader reader = readers[j]; try { if (i == 0) { innerArray[j] = q.valSrc.GetValues(reader).InnerArray; Log(i + ". compare: " + innerArray[j].GetType() + " to " + expectedArrayTypes[tp].GetType()); Assert.AreEqual(innerArray[j].GetType(), expectedArrayTypes[tp].GetType(), "field values should be cached in the correct array type!"); } else { Log(i + ". compare: " + innerArray[j] + " to " + q.valSrc.GetValues(reader).InnerArray); Assert.AreSame(innerArray[j], q.valSrc.GetValues(reader).InnerArray, "field values should be cached and reused!"); } } catch (System.NotSupportedException) { if (!warned) { System.Console.Error.WriteLine("WARNING: " + TestName() + " cannot fully test values of " + q); warned = true; } } } } // verify new values are reloaded (not reused) for a new reader s = new IndexSearcher(dir, true); FieldScoreQuery q2 = new FieldScoreQuery(field, tp); ScoreDoc[] h2 = s.Search(q2, null, 1000).ScoreDocs; Assert.AreEqual(N_DOCS, h2.Length, "All docs should be matched!"); IndexReader[] readers2 = s.IndexReader.GetSequentialSubReaders(); for (int j = 0; j < readers2.Length; j++) { IndexReader reader = readers2[j]; try { Log("compare: " + innerArray + " to " + q2.valSrc.GetValues(reader).InnerArray); Assert.AreNotSame(innerArray, q2.valSrc.GetValues(reader).InnerArray, "cached field values should not be reused if reader as changed!"); } catch (System.NotSupportedException) { if (!warned) { System.Console.Error.WriteLine("WARNING: " + TestName() + " cannot fully test values of " + q2); warned = true; } } } } private System.String TestName() { return Lucene.Net.TestCase.GetFullName(); } } }
// 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.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net; using System.Text; using Microsoft.Rest.Generator.ClientModel; using Microsoft.Rest.Generator.Logging; using Microsoft.Rest.Generator.Properties; using Microsoft.Rest.Generator.Utilities; namespace Microsoft.Rest.Generator { public abstract class CodeNamer { private static readonly IDictionary<char, string> basicLaticCharacters; protected CodeNamer() { ReservedWords = new HashSet<string>(); } /// <summary> /// Gets collection of reserved words. /// </summary> public HashSet<string> ReservedWords { get; private set; } /// <summary> /// Formats segments of a string split by underscores or hyphens into "Camel" case strings. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public static string CamelCase(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return name.Split('_', '-', ' ') .Where(s => !string.IsNullOrEmpty(s)) .Select((s, i) => FormatCase(s, i == 0)) // Pass true/toLower for just the first element. .DefaultIfEmpty("") .Aggregate(string.Concat); } /// <summary> /// Formats segments of a string split by underscores or hyphens into "Pascal" case. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public static string PascalCase(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return name.Split('_', '-', ' ') .Where(s => !string.IsNullOrEmpty(s)) .Select(s => FormatCase(s, false)) .DefaultIfEmpty("") .Aggregate(string.Concat); } /// <summary> /// Recursively normalizes names in the client model /// </summary> /// <param name="client"></param> public virtual void NormalizeClientModel(ServiceClient client) { if (client == null) { throw new ArgumentNullException("client"); } client.Name = GetTypeName(client.Name); client.Namespace = GetNamespaceName(client.Namespace); foreach (var property in client.Properties) { property.Name = GetPropertyName(property.Name); property.Type = NormalizeTypeReference(property.Type); } var normalizedModels = new List<CompositeType>(); foreach (var modelType in client.ModelTypes) { normalizedModels.Add(NormalizeTypeDeclaration(modelType) as CompositeType); } client.ModelTypes.Clear(); normalizedModels.ForEach( (item) => client.ModelTypes.Add(item)); var normalizedErrors = new List<CompositeType>(); foreach (var modelType in client.ErrorTypes) { normalizedErrors.Add(NormalizeTypeDeclaration(modelType) as CompositeType); } client.ErrorTypes.Clear(); normalizedErrors.ForEach((item) => client.ErrorTypes.Add(item)); var normalizedHeaders = new List<CompositeType>(); foreach (var modelType in client.HeaderTypes) { normalizedHeaders.Add(NormalizeTypeDeclaration(modelType) as CompositeType); } client.HeaderTypes.Clear(); normalizedHeaders.ForEach((item) => client.HeaderTypes.Add(item)); var normalizedEnums = new List<EnumType>(); foreach (var enumType in client.EnumTypes) { var normalizedType = NormalizeTypeDeclaration(enumType) as EnumType; if (normalizedType != null) { normalizedEnums.Add(NormalizeTypeDeclaration(enumType) as EnumType); } } client.EnumTypes.Clear(); normalizedEnums.ForEach((item) => client.EnumTypes.Add(item)); foreach (var method in client.Methods) { NormalizeMethod(method); } } /// <summary> /// Normalizes names in the method /// </summary> /// <param name="method"></param> public virtual void NormalizeMethod(Method method) { if (method == null) { throw new ArgumentNullException("method"); } method.Name = GetMethodName(method.Name); method.Group = GetMethodGroupName(method.Group); method.ReturnType = NormalizeTypeReference(method.ReturnType); method.DefaultResponse = NormalizeTypeReference(method.DefaultResponse); var normalizedResponses = new Dictionary<HttpStatusCode, Response>(); foreach (var statusCode in method.Responses.Keys) { normalizedResponses[statusCode] = NormalizeTypeReference(method.Responses[statusCode]); } method.Responses.Clear(); foreach (var statusCode in normalizedResponses.Keys) { method.Responses[statusCode] = normalizedResponses[statusCode]; } foreach (var parameter in method.Parameters) { parameter.Name = GetParameterName(parameter.Name); parameter.Type = NormalizeTypeReference(parameter.Type); } foreach (var parameterTransformation in method.InputParameterTransformation) { parameterTransformation.OutputParameter.Name = GetParameterName(parameterTransformation.OutputParameter.Name); parameterTransformation.OutputParameter.Type = NormalizeTypeReference(parameterTransformation.OutputParameter.Type); foreach (var parameterMapping in parameterTransformation.ParameterMappings) { if (parameterMapping.InputParameterProperty != null) { parameterMapping.InputParameterProperty = string.Join(".", parameterMapping.InputParameterProperty.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries) .Select(p => GetPropertyName(p))); } if (parameterMapping.OutputParameterProperty != null) { parameterMapping.OutputParameterProperty = string.Join(".", parameterMapping.OutputParameterProperty.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries) .Select(p => GetPropertyName(p))); } } } } /// <summary> /// Formats a string for naming members of an enum using Pascal case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetEnumMemberName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return PascalCase(RemoveInvalidCharacters(name)); } /// <summary> /// Formats a string for naming fields using a prefix '_' and VariableName Camel case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetFieldName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return '_' + GetVariableName(name); } /// <summary> /// Formats a string for naming interfaces using a prefix 'I' and Pascal case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetInterfaceName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return "I" + PascalCase(RemoveInvalidCharacters(name)); } /// <summary> /// Formats a string for naming a method using Pascal case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetMethodName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Operation"))); } /// <summary> /// Formats a string for identifying a namespace using Pascal case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetNamespaceName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return PascalCase(RemoveInvalidCharactersNamespace(name)); } /// <summary> /// Formats a string for naming method parameters using GetVariableName Camel case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetParameterName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return GetVariableName(GetEscapedReservedName(name, "Parameter")); } /// <summary> /// Formats a string for naming properties using Pascal case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetPropertyName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Property"))); } /// <summary> /// Formats a string for naming a Type or Object using Pascal case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetTypeName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Model"))); } /// <summary> /// Formats a string for naming a Method Group using Pascal case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetMethodGroupName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Model"))); } /// <summary> /// Formats a string for naming a local variable using Camel case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetVariableName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return CamelCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Variable"))); } /// <summary> /// Returns language specific type reference name. /// </summary> /// <param name="typePair"></param> /// <returns></returns> public virtual Response NormalizeTypeReference(Response typePair) { return new Response(NormalizeTypeReference(typePair.Body), NormalizeTypeReference(typePair.Headers)); } /// <summary> /// Returns language specific type reference name. /// </summary> /// <param name="type"></param> /// <returns></returns> public abstract IType NormalizeTypeReference(IType type); /// <summary> /// Returns language specific type declaration name. /// </summary> /// <param name="type"></param> /// <returns></returns> public abstract IType NormalizeTypeDeclaration(IType type); /// <summary> /// Formats a string as upper or lower case. Two-letter inputs that are all upper case are both lowered. /// Example: ID = > id, Ex => ex /// </summary> /// <param name="name"></param> /// <param name="toLower"></param> /// <returns>The formatted string.</returns> private static string FormatCase(string name, bool toLower) { if (!string.IsNullOrEmpty(name)) { if (name.Length < 2 || (name.Length == 2 && char.IsUpper(name[0]) && char.IsUpper(name[1]))) { name = toLower ? name.ToLowerInvariant() : name.ToUpperInvariant(); } else { name = (toLower ? char.ToLowerInvariant(name[0]) : char.ToUpperInvariant(name[0])) + name.Substring(1, name.Length - 1); } } return name; } /// <summary> /// Removes invalid characters from the name. Everything but alpha-numeral, underscore, /// and dash. /// </summary> /// <param name="name">String to parse.</param> /// <returns>Name with invalid characters removed.</returns> public static string RemoveInvalidCharacters(string name) { return GetValidName(name, '_', '-'); } /// <summary> /// Removes invalid characters from the namespace. Everything but alpha-numeral, underscore, /// period, and dash. /// </summary> /// <param name="name">String to parse.</param> /// <returns>Namespace with invalid characters removed.</returns> protected virtual string RemoveInvalidCharactersNamespace(string name) { return GetValidName(name, '_', '-', '.'); } /// <summary> /// Gets valid name for the identifier. /// </summary> /// <param name="name">String to parse.</param> /// <param name="allowerCharacters">Allowed characters.</param> /// <returns>Name with invalid characters removed.</returns> private static string GetValidName(string name, params char[] allowerCharacters) { var correctName = RemoveInvalidCharacters(name, allowerCharacters); // here we have only letters and digits or an empty string if (string.IsNullOrEmpty(correctName) || basicLaticCharacters.ContainsKey(correctName[0])) { var sb = new StringBuilder(); foreach (char symbol in name) { if (basicLaticCharacters.ContainsKey(symbol)) { sb.Append(basicLaticCharacters[symbol]); } else { sb.Append(symbol); } } correctName = RemoveInvalidCharacters(sb.ToString(), allowerCharacters); } // if it is still empty string, throw if (correctName.IsNullOrEmpty()) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.InvalidIdentifierName, name)); } return correctName; } /// <summary> /// Removes invalid characters from the name. /// </summary> /// <param name="name">String to parse.</param> /// <param name="allowerCharacters">Allowed characters.</param> /// <returns>Name with invalid characters removed.</returns> private static string RemoveInvalidCharacters(string name, params char[] allowerCharacters) { return new string(name.Replace("[]", "Sequence") .Where(c => char.IsLetterOrDigit(c) || allowerCharacters.Contains(c)) .ToArray()); } /// <summary> /// If the provided name is a reserved word in a programming language then the method converts the /// name by appending the provided appendValue /// </summary> /// <param name="name">Name.</param> /// <param name="appendValue">String to append.</param> /// <returns>The transformed reserved name</returns> protected virtual string GetEscapedReservedName(string name, string appendValue) { if (name == null) { throw new ArgumentNullException("name"); } if (appendValue == null) { throw new ArgumentNullException("appendValue"); } if (ReservedWords.Contains(name, StringComparer.OrdinalIgnoreCase)) { name += appendValue; } return name; } /// <summary> /// Resolves name collisions in the client model by iterating over namespaces (if provided, /// model names, client name, and client method groups. /// </summary> /// <param name="serviceClient">Service client to process.</param> /// <param name="clientNamespace">Client namespace or null.</param> /// <param name="modelNamespace">Client model namespace or null.</param> public virtual void ResolveNameCollisions(ServiceClient serviceClient, string clientNamespace, string modelNamespace) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } // take all namespaces of Models var exclusionListQuery = SplitNamespaceAndIgnoreLast(modelNamespace) .Union(SplitNamespaceAndIgnoreLast(clientNamespace)); var exclusionDictionary = new Dictionary<string, string>(exclusionListQuery .Where(s => !string.IsNullOrWhiteSpace(s)) .ToDictionary(s => s, v => "namespace"), StringComparer.OrdinalIgnoreCase); var models = new List<CompositeType>(serviceClient.ModelTypes); serviceClient.ModelTypes.Clear(); foreach (var model in models) { model.Name = ResolveNameConflict( exclusionDictionary, model.Name, "Schema definition", "Model"); serviceClient.ModelTypes.Add(model); } models = new List<CompositeType>(serviceClient.HeaderTypes); serviceClient.HeaderTypes.Clear(); foreach (var model in models) { model.Name = ResolveNameConflict( exclusionDictionary, model.Name, "Schema definition", "Model"); serviceClient.HeaderTypes.Add(model); } foreach (var model in serviceClient.ModelTypes .Concat(serviceClient.HeaderTypes) .Concat(serviceClient.ErrorTypes)) { foreach (var property in model.Properties) { if (property.Name.Equals(model.Name, StringComparison.OrdinalIgnoreCase)) { property.Name += "Property"; } } } var enumTypes = new List<EnumType>(serviceClient.EnumTypes); serviceClient.EnumTypes.Clear(); foreach (var enumType in enumTypes) { enumType.Name = ResolveNameConflict( exclusionDictionary, enumType.Name, "Enum name", "Enum"); serviceClient.EnumTypes.Add(enumType); } serviceClient.Name = ResolveNameConflict( exclusionDictionary, serviceClient.Name, "Client", "Client"); ResolveMethodGroupNameCollision(serviceClient, exclusionDictionary); } /// <summary> /// Resolves name collisions in the client model for method groups (operations). /// </summary> /// <param name="serviceClient"></param> /// <param name="exclusionDictionary"></param> protected virtual void ResolveMethodGroupNameCollision(ServiceClient serviceClient, Dictionary<string, string> exclusionDictionary) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } if (exclusionDictionary == null) { throw new ArgumentNullException("exclusionDictionary"); } var methodGroups = serviceClient.MethodGroups.ToList(); foreach (var methodGroup in methodGroups) { var resolvedName = ResolveNameConflict( exclusionDictionary, methodGroup, "Client operation", "Operations"); foreach (var method in serviceClient.Methods) { if (method.Group == methodGroup) { method.Group = resolvedName; } } } } private static string ResolveNameConflict( Dictionary<string, string> exclusionDictionary, string typeName, string type, string suffix) { string resolvedName = typeName; var sb = new StringBuilder(); sb.AppendLine(); while (exclusionDictionary.ContainsKey(resolvedName)) { sb.AppendLine(string.Format(CultureInfo.InvariantCulture, Resources.NamespaceConflictReasonMessage, resolvedName, exclusionDictionary[resolvedName])); resolvedName += suffix; } if (!string.Equals(resolvedName, typeName, StringComparison.OrdinalIgnoreCase)) { sb.AppendLine(Resources.NamingConflictsSuggestion); Logger.LogWarning( string.Format( CultureInfo.InvariantCulture, Resources.EntityConflictTitleMessage, type, typeName, resolvedName, sb)); } exclusionDictionary.Add(resolvedName, type); return resolvedName; } private static IEnumerable<string> SplitNamespaceAndIgnoreLast(string nameSpace) { if (string.IsNullOrEmpty(nameSpace)) { return Enumerable.Empty<string>(); } var namespaceWords = nameSpace.Split(new[] {'.'}, StringSplitOptions.RemoveEmptyEntries); if (namespaceWords.Length < 1) { return Enumerable.Empty<string>(); } // else we do not need the last part of the namespace return namespaceWords.Take(namespaceWords.Length - 1); } [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")] static CodeNamer() { basicLaticCharacters = new Dictionary<char, string>(); basicLaticCharacters[(char)32] = "Space"; basicLaticCharacters[(char)33] = "ExclamationMark"; basicLaticCharacters[(char)34] = "QuotationMark"; basicLaticCharacters[(char)35] = "NumberSign"; basicLaticCharacters[(char)36] = "DollarSign"; basicLaticCharacters[(char)37] = "PercentSign"; basicLaticCharacters[(char)38] = "Ampersand"; basicLaticCharacters[(char)39] = "Apostrophe"; basicLaticCharacters[(char)40] = "LeftParenthesis"; basicLaticCharacters[(char)41] = "RightParenthesis"; basicLaticCharacters[(char)42] = "Asterisk"; basicLaticCharacters[(char)43] = "PlusSign"; basicLaticCharacters[(char)44] = "Comma"; basicLaticCharacters[(char)45] = "HyphenMinus"; basicLaticCharacters[(char)46] = "FullStop"; basicLaticCharacters[(char)47] = "Slash"; basicLaticCharacters[(char)48] = "Zero"; basicLaticCharacters[(char)49] = "One"; basicLaticCharacters[(char)50] = "Two"; basicLaticCharacters[(char)51] = "Three"; basicLaticCharacters[(char)52] = "Four"; basicLaticCharacters[(char)53] = "Five"; basicLaticCharacters[(char)54] = "Six"; basicLaticCharacters[(char)55] = "Seven"; basicLaticCharacters[(char)56] = "Eight"; basicLaticCharacters[(char)57] = "Nine"; basicLaticCharacters[(char)58] = "Colon"; basicLaticCharacters[(char)59] = "Semicolon"; basicLaticCharacters[(char)60] = "LessThanSign"; basicLaticCharacters[(char)61] = "EqualSign"; basicLaticCharacters[(char)62] = "GreaterThanSign"; basicLaticCharacters[(char)63] = "QuestionMark"; basicLaticCharacters[(char)64] = "AtSign"; basicLaticCharacters[(char)91] = "LeftSquareBracket"; basicLaticCharacters[(char)92] = "Backslash"; basicLaticCharacters[(char)93] = "RightSquareBracket"; basicLaticCharacters[(char)94] = "CircumflexAccent"; basicLaticCharacters[(char)95] = "LowLine"; basicLaticCharacters[(char)96] = "GraveAccent"; basicLaticCharacters[(char)123] = "LeftCurlyBracket"; basicLaticCharacters[(char)124] = "VerticalBar"; basicLaticCharacters[(char)125] = "RightCurlyBracket"; basicLaticCharacters[(char)126] = "Tilde"; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Graphics.Containers; using osu.Framework.Testing; using osu.Game.Beatmaps.Drawables.Cards; using osu.Game.Graphics.Containers; using osu.Game.Graphics.UserInterface; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Online.API.Requests.Responses; using osu.Game.Overlays; using osu.Game.Overlays.BeatmapListing; using osu.Game.Scoring; using osuTK.Input; using APIUser = osu.Game.Online.API.Requests.Responses.APIUser; namespace osu.Game.Tests.Visual.Online { public class TestSceneBeatmapListingOverlay : OsuManualInputManagerTestScene { private readonly List<APIBeatmapSet> setsForResponse = new List<APIBeatmapSet>(); private BeatmapListingOverlay overlay; private BeatmapListingSearchControl searchControl => overlay.ChildrenOfType<BeatmapListingSearchControl>().Single(); [SetUpSteps] public void SetUpSteps() { AddStep("setup overlay", () => { Child = overlay = new BeatmapListingOverlay { State = { Value = Visibility.Visible } }; setsForResponse.Clear(); }); AddStep("initialize dummy", () => { var api = (DummyAPIAccess)API; api.HandleRequest = req => { if (!(req is SearchBeatmapSetsRequest searchBeatmapSetsRequest)) return false; searchBeatmapSetsRequest.TriggerSuccess(new SearchBeatmapSetsResponse { BeatmapSets = setsForResponse, }); return true; }; // non-supporter user api.LocalUser.Value = new APIUser { Username = "TestBot", Id = API.LocalUser.Value.Id + 1, }; }); } [Test] public void TestHideViaBack() { AddAssert("is visible", () => overlay.State.Value == Visibility.Visible); AddStep("hide", () => InputManager.Key(Key.Escape)); AddUntilStep("is hidden", () => overlay.State.Value == Visibility.Hidden); } [Test] public void TestHideViaBackWithSearch() { AddAssert("is visible", () => overlay.State.Value == Visibility.Visible); AddStep("search something", () => overlay.ChildrenOfType<SearchTextBox>().First().Text = "search"); AddStep("kill search", () => InputManager.Key(Key.Escape)); AddAssert("search textbox empty", () => string.IsNullOrEmpty(overlay.ChildrenOfType<SearchTextBox>().First().Text)); AddAssert("is visible", () => overlay.State.Value == Visibility.Visible); AddStep("hide", () => InputManager.Key(Key.Escape)); AddUntilStep("is hidden", () => overlay.State.Value == Visibility.Hidden); } [Test] public void TestHideViaBackWithScrolledSearch() { AddAssert("is visible", () => overlay.State.Value == Visibility.Visible); AddStep("show many results", () => fetchFor(Enumerable.Repeat(CreateAPIBeatmapSet(Ruleset.Value), 100).ToArray())); AddUntilStep("placeholder hidden", () => !overlay.ChildrenOfType<BeatmapListingOverlay.NotFoundDrawable>().Any(d => d.IsPresent)); AddStep("scroll to bottom", () => overlay.ChildrenOfType<OverlayScrollContainer>().First().ScrollToEnd()); AddStep("kill search", () => InputManager.Key(Key.Escape)); AddUntilStep("search textbox empty", () => string.IsNullOrEmpty(overlay.ChildrenOfType<SearchTextBox>().First().Text)); AddUntilStep("is scrolled to top", () => overlay.ChildrenOfType<OverlayScrollContainer>().First().Current == 0); AddAssert("is visible", () => overlay.State.Value == Visibility.Visible); AddStep("hide", () => InputManager.Key(Key.Escape)); AddUntilStep("is hidden", () => overlay.State.Value == Visibility.Hidden); } [Test] public void TestCorrectOldContentExpiration() { AddAssert("is visible", () => overlay.State.Value == Visibility.Visible); AddStep("show many results", () => fetchFor(Enumerable.Repeat(CreateAPIBeatmapSet(Ruleset.Value), 100).ToArray())); assertAllCardsOfType<BeatmapCardNormal>(100); AddStep("show more results", () => fetchFor(Enumerable.Repeat(CreateAPIBeatmapSet(Ruleset.Value), 30).ToArray())); assertAllCardsOfType<BeatmapCardNormal>(30); } [Test] public void TestCardSizeSwitching() { AddAssert("is visible", () => overlay.State.Value == Visibility.Visible); AddStep("show many results", () => fetchFor(Enumerable.Repeat(CreateAPIBeatmapSet(Ruleset.Value), 100).ToArray())); assertAllCardsOfType<BeatmapCardNormal>(100); setCardSize(BeatmapCardSize.Extra); assertAllCardsOfType<BeatmapCardExtra>(100); setCardSize(BeatmapCardSize.Normal); assertAllCardsOfType<BeatmapCardNormal>(100); AddStep("fetch for 0 beatmaps", () => fetchFor()); AddUntilStep("placeholder shown", () => overlay.ChildrenOfType<BeatmapListingOverlay.NotFoundDrawable>().SingleOrDefault()?.IsPresent == true); setCardSize(BeatmapCardSize.Extra); AddAssert("placeholder shown", () => overlay.ChildrenOfType<BeatmapListingOverlay.NotFoundDrawable>().SingleOrDefault()?.IsPresent == true); } [Test] public void TestNoBeatmapsPlaceholder() { AddStep("fetch for 0 beatmaps", () => fetchFor()); placeholderShown(); AddStep("show many results", () => fetchFor(Enumerable.Repeat(CreateAPIBeatmapSet(Ruleset.Value), 100).ToArray())); AddUntilStep("wait for loaded", () => this.ChildrenOfType<BeatmapCard>().Count() == 100); AddUntilStep("placeholder hidden", () => !overlay.ChildrenOfType<BeatmapListingOverlay.NotFoundDrawable>().Any(d => d.IsPresent)); AddStep("fetch for 0 beatmaps", () => fetchFor()); placeholderShown(); // fetch once more to ensure nothing happens in displaying placeholder again when it already is present. AddStep("fetch for 0 beatmaps again", () => fetchFor()); placeholderShown(); void placeholderShown() => AddUntilStep("placeholder shown", () => { var notFoundDrawable = overlay.ChildrenOfType<BeatmapListingOverlay.NotFoundDrawable>().SingleOrDefault(); return notFoundDrawable != null && notFoundDrawable.IsPresent && notFoundDrawable.Parent.DrawHeight > 0; }); } [Test] public void TestUserWithoutSupporterUsesSupporterOnlyFiltersWithoutResults() { AddStep("fetch for 0 beatmaps", () => fetchFor()); AddStep("set dummy as non-supporter", () => ((DummyAPIAccess)API).LocalUser.Value.IsSupporter = false); // only Rank Achieved filter setRankAchievedFilter(new[] { ScoreRank.XH }); supporterRequiredPlaceholderShown(); setRankAchievedFilter(Array.Empty<ScoreRank>()); notFoundPlaceholderShown(); // only Played filter setPlayedFilter(SearchPlayed.Played); supporterRequiredPlaceholderShown(); setPlayedFilter(SearchPlayed.Any); notFoundPlaceholderShown(); // both RankAchieved and Played filters setRankAchievedFilter(new[] { ScoreRank.XH }); setPlayedFilter(SearchPlayed.Played); supporterRequiredPlaceholderShown(); setRankAchievedFilter(Array.Empty<ScoreRank>()); setPlayedFilter(SearchPlayed.Any); notFoundPlaceholderShown(); } [Test] public void TestUserWithSupporterUsesSupporterOnlyFiltersWithoutResults() { AddStep("fetch for 0 beatmaps", () => fetchFor()); AddStep("set dummy as supporter", () => ((DummyAPIAccess)API).LocalUser.Value.IsSupporter = true); // only Rank Achieved filter setRankAchievedFilter(new[] { ScoreRank.XH }); notFoundPlaceholderShown(); setRankAchievedFilter(Array.Empty<ScoreRank>()); notFoundPlaceholderShown(); // only Played filter setPlayedFilter(SearchPlayed.Played); notFoundPlaceholderShown(); setPlayedFilter(SearchPlayed.Any); notFoundPlaceholderShown(); // both Rank Achieved and Played filters setRankAchievedFilter(new[] { ScoreRank.XH }); setPlayedFilter(SearchPlayed.Played); notFoundPlaceholderShown(); setRankAchievedFilter(Array.Empty<ScoreRank>()); setPlayedFilter(SearchPlayed.Any); notFoundPlaceholderShown(); } [Test] public void TestUserWithoutSupporterUsesSupporterOnlyFiltersWithResults() { AddStep("fetch for 1 beatmap", () => fetchFor(CreateAPIBeatmapSet(Ruleset.Value))); noPlaceholderShown(); AddStep("set dummy as non-supporter", () => ((DummyAPIAccess)API).LocalUser.Value.IsSupporter = false); // only Rank Achieved filter setRankAchievedFilter(new[] { ScoreRank.XH }); supporterRequiredPlaceholderShown(); setRankAchievedFilter(Array.Empty<ScoreRank>()); noPlaceholderShown(); // only Played filter setPlayedFilter(SearchPlayed.Played); supporterRequiredPlaceholderShown(); setPlayedFilter(SearchPlayed.Any); noPlaceholderShown(); // both Rank Achieved and Played filters setRankAchievedFilter(new[] { ScoreRank.XH }); setPlayedFilter(SearchPlayed.Played); supporterRequiredPlaceholderShown(); setRankAchievedFilter(Array.Empty<ScoreRank>()); setPlayedFilter(SearchPlayed.Any); noPlaceholderShown(); } [Test] public void TestUserWithSupporterUsesSupporterOnlyFiltersWithResults() { AddStep("fetch for 1 beatmap", () => fetchFor(CreateAPIBeatmapSet(Ruleset.Value))); noPlaceholderShown(); AddStep("set dummy as supporter", () => ((DummyAPIAccess)API).LocalUser.Value.IsSupporter = true); // only Rank Achieved filter setRankAchievedFilter(new[] { ScoreRank.XH }); noPlaceholderShown(); setRankAchievedFilter(Array.Empty<ScoreRank>()); noPlaceholderShown(); // only Played filter setPlayedFilter(SearchPlayed.Played); noPlaceholderShown(); setPlayedFilter(SearchPlayed.Any); noPlaceholderShown(); // both Rank Achieved and Played filters setRankAchievedFilter(new[] { ScoreRank.XH }); setPlayedFilter(SearchPlayed.Played); noPlaceholderShown(); setRankAchievedFilter(Array.Empty<ScoreRank>()); setPlayedFilter(SearchPlayed.Any); noPlaceholderShown(); } [Test] public void TestExpandedCardContentNotClipped() { AddAssert("is visible", () => overlay.State.Value == Visibility.Visible); AddStep("show result with many difficulties", () => { var beatmapSet = CreateAPIBeatmapSet(Ruleset.Value); beatmapSet.Beatmaps = Enumerable.Repeat(beatmapSet.Beatmaps.First(), 100).ToArray(); fetchFor(beatmapSet); }); assertAllCardsOfType<BeatmapCardNormal>(1); AddStep("hover extra info row", () => { var difficultyArea = this.ChildrenOfType<BeatmapCardExtraInfoRow>().Single(); InputManager.MoveMouseTo(difficultyArea); }); AddUntilStep("wait for expanded", () => this.ChildrenOfType<BeatmapCardNormal>().Single().Expanded.Value); AddAssert("expanded content not clipped", () => { var cardContainer = this.ChildrenOfType<ReverseChildIDFillFlowContainer<BeatmapCard>>().Single().Parent; var expandedContent = this.ChildrenOfType<ExpandedContentScrollContainer>().Single(); return expandedContent.ScreenSpaceDrawQuad.GetVertices().ToArray().All(v => cardContainer.ScreenSpaceDrawQuad.Contains(v)); }); } private static int searchCount; private void fetchFor(params APIBeatmapSet[] beatmaps) { setsForResponse.Clear(); setsForResponse.AddRange(beatmaps); // trigger arbitrary change for fetching. searchControl.Query.Value = $"search {searchCount++}"; } private void setRankAchievedFilter(ScoreRank[] ranks) { AddStep($"set Rank Achieved filter to [{string.Join(',', ranks)}]", () => { searchControl.Ranks.Clear(); searchControl.Ranks.AddRange(ranks); }); } private void setPlayedFilter(SearchPlayed played) { AddStep($"set Played filter to {played}", () => searchControl.Played.Value = played); } private void supporterRequiredPlaceholderShown() { AddUntilStep("\"supporter required\" placeholder shown", () => overlay.ChildrenOfType<BeatmapListingOverlay.SupporterRequiredDrawable>().SingleOrDefault()?.IsPresent == true); } private void notFoundPlaceholderShown() { AddUntilStep("\"no maps found\" placeholder shown", () => overlay.ChildrenOfType<BeatmapListingOverlay.NotFoundDrawable>().SingleOrDefault()?.IsPresent == true); } private void noPlaceholderShown() { AddUntilStep("\"supporter required\" placeholder not shown", () => !overlay.ChildrenOfType<BeatmapListingOverlay.SupporterRequiredDrawable>().Any(d => d.IsPresent)); AddUntilStep("\"no maps found\" placeholder not shown", () => !overlay.ChildrenOfType<BeatmapListingOverlay.NotFoundDrawable>().Any(d => d.IsPresent)); } private void setCardSize(BeatmapCardSize cardSize) => AddStep($"set card size to {cardSize}", () => overlay.ChildrenOfType<BeatmapListingCardSizeTabControl>().Single().Current.Value = cardSize); private void assertAllCardsOfType<T>(int expectedCount) where T : BeatmapCard => AddUntilStep($"all loaded beatmap cards are {typeof(T)}", () => { int loadedCorrectCount = this.ChildrenOfType<BeatmapCard>().Count(card => card.IsLoaded && card.GetType() == typeof(T)); return loadedCorrectCount > 0 && loadedCorrectCount == expectedCount; }); } }
// Adaptive Quality|Utilities|90050 // Adapted from The Lab Renderer's ValveCamera.cs, available at // https://github.com/ValveSoftware/the_lab_renderer/blob/ae64c48a8ccbe5406aba1e39b160d4f2f7156c2c/Assets/TheLabRenderer/Scripts/ValveCamera.cs // For The Lab Renderer's license see THIRD_PARTY_NOTICES. // **Only Compatible With Unity 5.4 and above** #if (UNITY_5_4_OR_NEWER) namespace VRTK { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using UnityEngine; using UnityEngine.VR; /// <summary> /// Adaptive Quality dynamically changes rendering settings to maintain VR framerate while maximizing GPU utilization. /// </summary> /// <remarks> /// > **Only Compatible With Unity 5.4 and above** /// /// There are two goals: /// <list type="bullet"> /// <item> <description>Reduce the chances of dropping frames and reprojecting</description> </item> /// <item> <description>Increase quality when there are idle GPU cycles</description> </item> /// </list> /// <para /> /// This script currently changes the following to reach these goals: /// <list type="bullet"> /// <item> <description>Rendering resolution and viewport size (aka Dynamic Resolution)</description> </item> /// </list> /// <para /> /// In the future it could be changed to also change the following: /// <list type="bullet"> /// <item> <description>MSAA level</description> </item> /// <item> <description>Fixed Foveated Rendering</description> </item> /// <item> <description>Radial Density Masking</description> </item> /// <item> <description>(Non-fixed) Foveated Rendering (once HMDs support eye tracking)</description> </item> /// </list> /// <para /> /// Some shaders, especially Image Effects, need to be modified to work with the changed render scale. To fix them /// pass `1.0f / VRSettings.renderViewportScale` into the shader and scale all incoming UV values with it in the vertex /// program. Do this by using `Material.SetFloat` to set the value in the script that configures the shader. /// <para /> /// In more detail: /// <list type="bullet"> /// <item> <description>In the `.shader` file: Add a new runtime-set property value `float _InverseOfRenderViewportScale` /// and add `vertexInput.texcoord *= _InverseOfRenderViewportScale` to the start of the vertex program</description> </item> /// <item> <description>In the `.cs` file: Before using the material (eg. `Graphics.Blit`) add /// `material.SetFloat("_InverseOfRenderViewportScale", 1.0f / VRSettings.renderViewportScale)`</description> </item> /// </list> /// </remarks> /// <example> /// `VRTK/Examples/039_CameraRig_AdaptiveQuality` displays the frames per second in the centre of the headset view. /// The debug visualization of this script is displayed near the top edge of the headset view. /// Pressing the trigger generates a new sphere and pressing the touchpad generates ten new spheres. /// Eventually when lots of spheres are present the FPS will drop and demonstrate the script. /// </example> [AddComponentMenu("VRTK/Scripts/Utilities/VRTK_AdaptiveQuality")] public sealed class VRTK_AdaptiveQuality : MonoBehaviour { #region Public fields [Tooltip("Toggles whether to show the debug overlay.\n\n" + "Each square represents a different level on the quality scale. Levels increase from left to right," + " the first green box that is lit above represents the recommended render target resolution provided by the" + " current `VRDevice`, the box that is lit below in cyan represents the current resolution and the filled box" + " represents the current viewport scale. The yellow boxes represent resolutions below the recommended render target resolution.\n" + "The currently lit box becomes red whenever the user is likely seeing reprojection in the HMD since the" + " application isn't maintaining VR framerate. If lit, the box all the way on the left is almost always lit" + " red because it represents the lowest render scale with reprojection on.")] public bool drawDebugVisualization; [Tooltip("Toggles whether to allow keyboard shortcuts to control this script.\n\n" + "* The supported shortcuts are:\n" + " * `Shift+F1`: Toggle debug visualization on/off\n" + " * `Shift+F2`: Toggle usage of override render scale on/off\n" + " * `Shift+F3`: Decrease override render scale level\n" + " * `Shift+F4`: Increase override render scale level")] public bool allowKeyboardShortcuts = true; [Tooltip("Toggles whether to allow command line arguments to control this script at startup of the standalone build.\n\n" + "* The supported command line arguments all begin with '-' and are:\n" + " * `-noaq`: Disable adaptive quality\n" + " * `-aqminscale X`: Set minimum render scale to X\n" + " * `-aqmaxscale X`: Set maximum render scale to X\n" + " * `-aqmaxres X`: Set maximum render target dimension to X\n" + " * `-aqfillratestep X`: Set render scale fill rate step size in percent to X (X from 1 to 100)\n" + " * `-aqoverride X`: Set override render scale level to X\n" + " * `-vrdebug`: Enable debug visualization\n" + " * `-msaa X`: Set MSAA level to X")] public bool allowCommandLineArguments = true; [Tooltip("The MSAA level to use.")] [Header("Quality")] [Range(0, 8)] public int msaaLevel = 4; [Tooltip("Toggles whether the render viewport scale is dynamically adjusted to maintain VR framerate.\n\n" + "If unchecked, the renderer will render at the recommended resolution provided by the current `VRDevice`.")] public bool scaleRenderViewport = true; [Tooltip("The minimum allowed render scale.")] [Range(0.01f, 5)] public float minimumRenderScale = 0.8f; [Tooltip("The maximum allowed render scale.")] public float maximumRenderScale = 1.4f; [Tooltip("The maximum allowed render target dimension.\n\n" + "This puts an upper limit on the size of the render target regardless of the maximum render scale.")] public int maximumRenderTargetDimension = 4096; [Tooltip("The fill rate step size in percent by which the render scale levels will be calculated.")] [Range(1, 100)] public int renderScaleFillRateStepSizeInPercent = 15; [Tooltip("Toggles whether the render target resolution is dynamically adjusted to maintain VR framerate.\n\n" + "If unchecked, the renderer will use the maximum target resolution specified by `maximumRenderScale`.")] public bool scaleRenderTargetResolution = false; [Tooltip("Toggles whether to override the used render viewport scale level.")] [Header("Override")] [NonSerialized] public bool overrideRenderViewportScale; [Tooltip("The render viewport scale level to override the current one with.")] [NonSerialized] public int overrideRenderViewportScaleLevel; #endregion #region Public readonly fields & properties /// <summary> /// All the calculated render scales. /// </summary> /// <remarks> /// The elements of this collection are to be interpreted as modifiers to the recommended render target /// resolution provided by the current `VRDevice`. /// </remarks> public readonly ReadOnlyCollection<float> renderScales; /// <summary> /// The current render scale. /// </summary> /// <remarks> /// A render scale of `1.0` represents the recommended render target resolution provided by the current `VRDevice`. /// </remarks> public static float CurrentRenderScale { get { return VRSettings.renderScale * VRSettings.renderViewportScale; } } /// <summary> /// The recommended render target resolution provided by the current `VRDevice`. /// </summary> public Vector2 defaultRenderTargetResolution { get { return RenderTargetResolutionForRenderScale(allRenderScales[defaultRenderViewportScaleLevel]); } } /// <summary> /// The current render target resolution. /// </summary> public Vector2 currentRenderTargetResolution { get { return RenderTargetResolutionForRenderScale(CurrentRenderScale); } } #endregion #region Private fields /// <summary> /// The frame duration in milliseconds to fallback to if the current `VRDevice` specifies no refresh rate. /// </summary> private const float DefaultFrameDurationInMilliseconds = 1000f / 90f; private readonly AdaptiveSetting<int> renderViewportScaleSetting = new AdaptiveSetting<int>(0, 30, 10); private readonly AdaptiveSetting<int> renderScaleSetting = new AdaptiveSetting<int>(0, 180, 90); private readonly List<float> allRenderScales = new List<float>(); private int defaultRenderViewportScaleLevel; private float previousMinimumRenderScale; private float previousMaximumRenderScale; private float previousRenderScaleFillRateStepSizeInPercent; private readonly Timing timing = new Timing(); private int lastRenderViewportScaleLevelBelowRenderScaleLevelFrameCount; private bool interleavedReprojectionEnabled; private bool hmdDisplayIsOnDesktop; private float singleFrameDurationInMilliseconds; private GameObject debugVisualizationQuad; private Material debugVisualizationQuadMaterial; #endregion public VRTK_AdaptiveQuality() { renderScales = allRenderScales.AsReadOnly(); } /// <summary> /// Calculates and returns the render target resolution for a given render scale. /// </summary> /// <param name="renderScale"> /// The render scale to calculate the render target resolution with. /// </param> /// <returns> /// The render target resolution for `renderScale`. /// </returns> public static Vector2 RenderTargetResolutionForRenderScale(float renderScale) { return new Vector2((int)(VRSettings.eyeTextureWidth / VRSettings.renderScale * renderScale), (int)(VRSettings.eyeTextureHeight / VRSettings.renderScale * renderScale)); } /// <summary> /// Calculates and returns the biggest allowed maximum render scale to be used for `maximumRenderScale` /// given the current `maximumRenderTargetDimension`. /// </summary> /// <returns> /// The biggest allowed maximum render scale. /// </returns> public float BiggestAllowedMaximumRenderScale() { if (VRSettings.eyeTextureWidth == 0 || VRSettings.eyeTextureHeight == 0) { return maximumRenderScale; } float maximumHorizontalRenderScale = maximumRenderTargetDimension * VRSettings.renderScale / VRSettings.eyeTextureWidth; float maximumVerticalRenderScale = maximumRenderTargetDimension * VRSettings.renderScale / VRSettings.eyeTextureHeight; return Mathf.Min(maximumHorizontalRenderScale, maximumVerticalRenderScale); } /// <summary> /// A summary of this script by listing all the calculated render scales with their /// corresponding render target resolution. /// </summary> /// <returns> /// The summary. /// </returns> public override string ToString() { var stringBuilder = new StringBuilder("Adaptive Quality\n"); stringBuilder.AppendLine("Render Scale:"); stringBuilder.AppendLine("Level - Resolution - Multiplier"); for (int index = 0; index < allRenderScales.Count; index++) { float renderScale = allRenderScales[index]; var renderTargetResolution = RenderTargetResolutionForRenderScale(renderScale); stringBuilder.AppendFormat( "{0, 3} {1, 5}x{2, -5} {3, -8}", index, (int)renderTargetResolution.x, (int)renderTargetResolution.y, renderScale); if (index == 0) { stringBuilder.Append(" (Interleaved reprojection hint)"); } else if (index == defaultRenderViewportScaleLevel) { stringBuilder.Append(" (Default)"); } if (index == renderViewportScaleSetting.currentValue) { stringBuilder.Append(" (Current Viewport)"); } if (index == renderScaleSetting.currentValue) { stringBuilder.Append(" (Current Target Resolution)"); } if (index != allRenderScales.Count - 1) { stringBuilder.AppendLine(); } } return stringBuilder.ToString(); } #region MonoBehaviour methods private void Awake() { VRTK_SDKManager.instance.AddBehaviourToToggleOnLoadedSetupChange(this); } private void OnEnable() { Camera.onPreCull += OnCameraPreCull; hmdDisplayIsOnDesktop = VRTK_SDK_Bridge.IsDisplayOnDesktop(); singleFrameDurationInMilliseconds = VRDevice.refreshRate > 0.0f ? 1000.0f / VRDevice.refreshRate : DefaultFrameDurationInMilliseconds; HandleCommandLineArguments(); if (!Application.isEditor) { OnValidate(); } } private void OnDisable() { Camera.onPreCull -= OnCameraPreCull; SetRenderScale(1.0f, 1.0f); } private void OnDestroy() { VRTK_SDKManager.instance.RemoveBehaviourToToggleOnLoadedSetupChange(this); } private void OnValidate() { minimumRenderScale = Mathf.Max(0.01f, minimumRenderScale); maximumRenderScale = Mathf.Max(minimumRenderScale, maximumRenderScale); maximumRenderTargetDimension = Mathf.Max(2, maximumRenderTargetDimension); renderScaleFillRateStepSizeInPercent = Mathf.Max(1, renderScaleFillRateStepSizeInPercent); msaaLevel = msaaLevel == 1 ? 0 : Mathf.Clamp(Mathf.ClosestPowerOfTwo(msaaLevel), 0, 8); } private void Update() { HandleKeyPresses(); UpdateRenderScaleLevels(); CreateOrDestroyDebugVisualization(); UpdateDebugVisualization(); timing.SaveCurrentFrameTiming(); } #if UNITY_5_4_1 || UNITY_5_4_2 || UNITY_5_4_3 || UNITY_5_5_OR_NEWER private void LateUpdate() { UpdateRenderScale(); } #endif private void OnCameraPreCull(Camera camera) { if (camera.transform != VRTK_SDK_Bridge.GetHeadsetCamera()) { return; } #if !(UNITY_5_4_1 || UNITY_5_4_2 || UNITY_5_4_3 || UNITY_5_5_OR_NEWER) UpdateRenderScale(); #endif UpdateMSAALevel(); } #endregion private void HandleCommandLineArguments() { if (!allowCommandLineArguments) { return; } var commandLineArguments = Environment.GetCommandLineArgs(); for (int index = 0; index < commandLineArguments.Length; index++) { string argument = commandLineArguments[index]; string nextArgument = index + 1 < commandLineArguments.Length ? commandLineArguments[index + 1] : ""; switch (argument) { case CommandLineArguments.Disable: scaleRenderViewport = false; break; case CommandLineArguments.MinimumRenderScale: minimumRenderScale = float.Parse(nextArgument); break; case CommandLineArguments.MaximumRenderScale: maximumRenderScale = float.Parse(nextArgument); break; case CommandLineArguments.MaximumRenderTargetDimension: maximumRenderTargetDimension = int.Parse(nextArgument); break; case CommandLineArguments.RenderScaleFillRateStepSizeInPercent: renderScaleFillRateStepSizeInPercent = int.Parse(nextArgument); break; case CommandLineArguments.OverrideRenderScaleLevel: overrideRenderViewportScale = true; overrideRenderViewportScaleLevel = int.Parse(nextArgument); break; case CommandLineArguments.DrawDebugVisualization: drawDebugVisualization = true; break; case CommandLineArguments.MSAALevel: msaaLevel = int.Parse(nextArgument); break; } } } private void HandleKeyPresses() { if (!allowKeyboardShortcuts || !KeyboardShortcuts.Modifiers.Any(Input.GetKey)) { return; } if (Input.GetKeyDown(KeyboardShortcuts.ToggleDrawDebugVisualization)) { drawDebugVisualization = !drawDebugVisualization; } else if (Input.GetKeyDown(KeyboardShortcuts.ToggleOverrideRenderScale)) { overrideRenderViewportScale = !overrideRenderViewportScale; } else if (Input.GetKeyDown(KeyboardShortcuts.DecreaseOverrideRenderScaleLevel)) { overrideRenderViewportScaleLevel = ClampRenderScaleLevel(overrideRenderViewportScaleLevel - 1); } else if (Input.GetKeyDown(KeyboardShortcuts.IncreaseOverrideRenderScaleLevel)) { overrideRenderViewportScaleLevel = ClampRenderScaleLevel(overrideRenderViewportScaleLevel + 1); } } private void UpdateMSAALevel() { if (QualitySettings.antiAliasing != msaaLevel) { QualitySettings.antiAliasing = msaaLevel; } } #region Render scale methods private void UpdateRenderScaleLevels() { if (Mathf.Abs(previousMinimumRenderScale - minimumRenderScale) <= float.Epsilon && Mathf.Abs(previousMaximumRenderScale - maximumRenderScale) <= float.Epsilon && Mathf.Abs(previousRenderScaleFillRateStepSizeInPercent - renderScaleFillRateStepSizeInPercent) <= float.Epsilon) { return; } previousMinimumRenderScale = minimumRenderScale; previousMaximumRenderScale = maximumRenderScale; previousRenderScaleFillRateStepSizeInPercent = renderScaleFillRateStepSizeInPercent; allRenderScales.Clear(); // Respect maximumRenderTargetDimension float allowedMaximumRenderScale = BiggestAllowedMaximumRenderScale(); float renderScaleToAdd = Mathf.Min(minimumRenderScale, allowedMaximumRenderScale); // Add min scale as the reprojection scale allRenderScales.Add(renderScaleToAdd); // Add all entries while (renderScaleToAdd <= maximumRenderScale) { allRenderScales.Add(renderScaleToAdd); renderScaleToAdd = Mathf.Sqrt((renderScaleFillRateStepSizeInPercent + 100) / 100.0f * renderScaleToAdd * renderScaleToAdd); if (renderScaleToAdd > allowedMaximumRenderScale) { // Too large break; } } // Figure out default render viewport scale level for debug visualization defaultRenderViewportScaleLevel = Mathf.Clamp( allRenderScales.FindIndex(renderScale => renderScale >= 1.0f), 1, allRenderScales.Count - 1); renderViewportScaleSetting.currentValue = defaultRenderViewportScaleLevel; renderScaleSetting.currentValue = defaultRenderViewportScaleLevel; overrideRenderViewportScaleLevel = ClampRenderScaleLevel(overrideRenderViewportScaleLevel); } private void UpdateRenderScale() { if (allRenderScales.Count == 0) { return; } if (!scaleRenderViewport) { renderViewportScaleSetting.currentValue = defaultRenderViewportScaleLevel; renderScaleSetting.currentValue = defaultRenderViewportScaleLevel; SetRenderScale(1.0f, 1.0f); return; } // Rendering in low resolution means adaptive quality needs to scale back the render scale target to free up gpu cycles bool renderInLowResolution = VRTK_SDK_Bridge.ShouldAppRenderWithLowResources(); // Thresholds float allowedSingleFrameDurationInMilliseconds = renderInLowResolution ? singleFrameDurationInMilliseconds * 0.75f : singleFrameDurationInMilliseconds; float lowThresholdInMilliseconds = 0.7f * allowedSingleFrameDurationInMilliseconds; float extrapolationThresholdInMilliseconds = 0.85f * allowedSingleFrameDurationInMilliseconds; float highThresholdInMilliseconds = 0.9f * allowedSingleFrameDurationInMilliseconds; int newRenderViewportScaleLevel = renderViewportScaleSetting.currentValue; // Rapidly reduce render viewport scale level if cost of last 1 or 3 frames, or the predicted next frame's cost are expensive if (timing.WasFrameTimingBad( 1, highThresholdInMilliseconds, renderViewportScaleSetting.lastChangeFrameCount, renderViewportScaleSetting.decreaseFrameCost) || timing.WasFrameTimingBad( 3, highThresholdInMilliseconds, renderViewportScaleSetting.lastChangeFrameCount, renderViewportScaleSetting.decreaseFrameCost) || timing.WillFrameTimingBeBad( extrapolationThresholdInMilliseconds, highThresholdInMilliseconds, renderViewportScaleSetting.lastChangeFrameCount, renderViewportScaleSetting.decreaseFrameCost)) { // Always drop 2 levels except when dropping from level 2 (level 0 is for reprojection) newRenderViewportScaleLevel = ClampRenderScaleLevel(renderViewportScaleSetting.currentValue == 2 ? 1 : renderViewportScaleSetting.currentValue - 2); } // Rapidly increase render viewport scale level if last 12 frames are cheap else if (timing.WasFrameTimingGood( 12, lowThresholdInMilliseconds, renderViewportScaleSetting.lastChangeFrameCount - renderViewportScaleSetting.increaseFrameCost, renderViewportScaleSetting.increaseFrameCost)) { newRenderViewportScaleLevel = ClampRenderScaleLevel(renderViewportScaleSetting.currentValue + 2); } // Slowly increase render viewport scale level if last 6 frames are cheap else if (timing.WasFrameTimingGood( 6, lowThresholdInMilliseconds, renderViewportScaleSetting.lastChangeFrameCount, renderViewportScaleSetting.increaseFrameCost)) { // Only increase by 1 level to prevent frame drops caused by adjusting newRenderViewportScaleLevel = ClampRenderScaleLevel(renderViewportScaleSetting.currentValue + 1); } // Apply and remember when render viewport scale level changed if (newRenderViewportScaleLevel != renderViewportScaleSetting.currentValue) { if (renderViewportScaleSetting.currentValue >= renderScaleSetting.currentValue && newRenderViewportScaleLevel < renderScaleSetting.currentValue) { lastRenderViewportScaleLevelBelowRenderScaleLevelFrameCount = Time.frameCount; } renderViewportScaleSetting.currentValue = newRenderViewportScaleLevel; } // Ignore frame timings if overriding if (overrideRenderViewportScale) { renderViewportScaleSetting.currentValue = overrideRenderViewportScaleLevel; } // Force on interleaved reprojection for level 0 which is just a replica of level 1 with reprojection enabled float additionalViewportScale = 1.0f; if (!hmdDisplayIsOnDesktop) { if (renderViewportScaleSetting.currentValue == 0) { if (interleavedReprojectionEnabled && timing.GetFrameTiming(0) < singleFrameDurationInMilliseconds * 0.85f) { interleavedReprojectionEnabled = false; } else if (timing.GetFrameTiming(0) > singleFrameDurationInMilliseconds * 0.925f) { interleavedReprojectionEnabled = true; } } else { interleavedReprojectionEnabled = false; } VRTK_SDK_Bridge.ForceInterleavedReprojectionOn(interleavedReprojectionEnabled); } // Not running in direct mode! Interleaved reprojection not supported, so scale down the viewport some more else if (renderViewportScaleSetting.currentValue == 0) { additionalViewportScale = 0.8f; } int newRenderScaleLevel = renderScaleSetting.currentValue; int levelInBetween = (renderViewportScaleSetting.currentValue - renderScaleSetting.currentValue) / 2; // Increase render scale level to the level in between if (renderScaleSetting.currentValue < renderViewportScaleSetting.currentValue && Time.frameCount >= renderScaleSetting.lastChangeFrameCount + renderScaleSetting.increaseFrameCost) { newRenderScaleLevel = ClampRenderScaleLevel(renderScaleSetting.currentValue + Mathf.Max(1, levelInBetween)); } // Decrease render scale level else if (renderScaleSetting.currentValue > renderViewportScaleSetting.currentValue && Time.frameCount >= renderScaleSetting.lastChangeFrameCount + renderScaleSetting.decreaseFrameCost && Time.frameCount >= lastRenderViewportScaleLevelBelowRenderScaleLevelFrameCount + renderViewportScaleSetting.increaseFrameCost) { // Slowly decrease render scale level to level in between if last 6 frames are cheap, otherwise rapidly newRenderScaleLevel = timing.WasFrameTimingGood(6, lowThresholdInMilliseconds, 0, 0) ? ClampRenderScaleLevel(renderScaleSetting.currentValue + Mathf.Min(-1, levelInBetween)) : renderViewportScaleSetting.currentValue; } // Apply and remember when render scale level changed renderScaleSetting.currentValue = newRenderScaleLevel; if (!scaleRenderTargetResolution) { renderScaleSetting.currentValue = allRenderScales.Count - 1; } float newRenderScale = allRenderScales[renderScaleSetting.currentValue]; float newRenderViewportScale = allRenderScales[Mathf.Min(renderViewportScaleSetting.currentValue, renderScaleSetting.currentValue)] / newRenderScale * additionalViewportScale; SetRenderScale(newRenderScale, newRenderViewportScale); } private static void SetRenderScale(float renderScale, float renderViewportScale) { if (Mathf.Abs(VRSettings.renderScale - renderScale) > float.Epsilon) { VRSettings.renderScale = renderScale; } if (Mathf.Abs(VRSettings.renderViewportScale - renderViewportScale) > float.Epsilon) { VRSettings.renderViewportScale = renderViewportScale; } } private int ClampRenderScaleLevel(int renderScaleLevel) { return Mathf.Clamp(renderScaleLevel, 0, allRenderScales.Count - 1); } #endregion #region Debug visualization methods private void CreateOrDestroyDebugVisualization() { if (!Application.isPlaying) { return; } if (enabled && drawDebugVisualization && debugVisualizationQuad == null) { var mesh = new Mesh { vertices = new[] { new Vector3(-0.5f, 0.9f, 1.0f), new Vector3(-0.5f, 1.0f, 1.0f), new Vector3(0.5f, 1.0f, 1.0f), new Vector3(0.5f, 0.9f, 1.0f) }, uv = new[] { new Vector2(0.0f, 0.0f), new Vector2(0.0f, 1.0f), new Vector2(1.0f, 1.0f), new Vector2(1.0f, 0.0f) }, triangles = new[] { 0, 1, 2, 0, 2, 3 } }; #if !UNITY_5_5_OR_NEWER mesh.Optimize(); #endif mesh.UploadMeshData(true); debugVisualizationQuad = new GameObject(VRTK_SharedMethods.GenerateVRTKObjectName(true, "AdaptiveQualityDebugVisualizationQuad")); debugVisualizationQuad.transform.parent = VRTK_DeviceFinder.HeadsetTransform(); debugVisualizationQuad.transform.localPosition = Vector3.forward; debugVisualizationQuad.transform.localRotation = Quaternion.identity; debugVisualizationQuad.AddComponent<MeshFilter>().mesh = mesh; debugVisualizationQuadMaterial = Resources.Load<Material>("AdaptiveQualityDebugVisualization"); debugVisualizationQuad.AddComponent<MeshRenderer>().material = debugVisualizationQuadMaterial; } else if ((!enabled || !drawDebugVisualization) && debugVisualizationQuad != null) { Destroy(debugVisualizationQuad); debugVisualizationQuad = null; debugVisualizationQuadMaterial = null; } } private void UpdateDebugVisualization() { if (!drawDebugVisualization || debugVisualizationQuadMaterial == null) { return; } int lastFrameIsInBudget = (interleavedReprojectionEnabled || VRTK_SharedMethods.GetGPUTimeLastFrame() > singleFrameDurationInMilliseconds ? 0 : 1); debugVisualizationQuadMaterial.SetInt(ShaderPropertyIDs.RenderScaleLevelsCount, allRenderScales.Count); debugVisualizationQuadMaterial.SetInt(ShaderPropertyIDs.DefaultRenderViewportScaleLevel, defaultRenderViewportScaleLevel); debugVisualizationQuadMaterial.SetInt(ShaderPropertyIDs.CurrentRenderViewportScaleLevel, renderViewportScaleSetting.currentValue); debugVisualizationQuadMaterial.SetInt(ShaderPropertyIDs.CurrentRenderScaleLevel, renderScaleSetting.currentValue); debugVisualizationQuadMaterial.SetInt(ShaderPropertyIDs.LastFrameIsInBudget, lastFrameIsInBudget); } #endregion #region Private helper classes private sealed class AdaptiveSetting<T> { public T currentValue { get { return _currentValue; } set { if (!EqualityComparer<T>.Default.Equals(value, _currentValue)) { lastChangeFrameCount = Time.frameCount; } previousValue = _currentValue; _currentValue = value; } } public T previousValue { get; private set; } public int lastChangeFrameCount { get; private set; } public readonly int increaseFrameCost; public readonly int decreaseFrameCost; private T _currentValue; public AdaptiveSetting(T currentValue, int increaseFrameCost, int decreaseFrameCost) { previousValue = currentValue; this.currentValue = currentValue; this.increaseFrameCost = increaseFrameCost; this.decreaseFrameCost = decreaseFrameCost; } } private static class CommandLineArguments { public const string Disable = "-noaq"; public const string MinimumRenderScale = "-aqminscale"; public const string MaximumRenderScale = "-aqmaxscale"; public const string MaximumRenderTargetDimension = "-aqmaxres"; public const string RenderScaleFillRateStepSizeInPercent = "-aqfillratestep"; public const string OverrideRenderScaleLevel = "-aqoverride"; public const string DrawDebugVisualization = "-vrdebug"; public const string MSAALevel = "-msaa"; } private static class KeyboardShortcuts { public static readonly KeyCode[] Modifiers = { KeyCode.LeftShift, KeyCode.RightShift }; public const KeyCode ToggleDrawDebugVisualization = KeyCode.F1; public const KeyCode ToggleOverrideRenderScale = KeyCode.F2; public const KeyCode DecreaseOverrideRenderScaleLevel = KeyCode.F3; public const KeyCode IncreaseOverrideRenderScaleLevel = KeyCode.F4; } private static class ShaderPropertyIDs { public static readonly int RenderScaleLevelsCount = Shader.PropertyToID("_RenderScaleLevelsCount"); public static readonly int DefaultRenderViewportScaleLevel = Shader.PropertyToID("_DefaultRenderViewportScaleLevel"); public static readonly int CurrentRenderViewportScaleLevel = Shader.PropertyToID("_CurrentRenderViewportScaleLevel"); public static readonly int CurrentRenderScaleLevel = Shader.PropertyToID("_CurrentRenderScaleLevel"); public static readonly int LastFrameIsInBudget = Shader.PropertyToID("_LastFrameIsInBudget"); } private sealed class Timing { private readonly float[] buffer = new float[12]; private int bufferIndex; public void SaveCurrentFrameTiming() { bufferIndex = (bufferIndex + 1) % buffer.Length; buffer[bufferIndex] = VRTK_SharedMethods.GetGPUTimeLastFrame(); } public float GetFrameTiming(int framesAgo) { return buffer[(bufferIndex - framesAgo + buffer.Length) % buffer.Length]; } public bool WasFrameTimingBad(int framesAgo, float thresholdInMilliseconds, int lastChangeFrameCount, int changeFrameCost) { if (!AreFramesAvailable(framesAgo, lastChangeFrameCount, changeFrameCost)) { // Too early to know return false; } for (int frame = 0; frame < framesAgo; frame++) { if (GetFrameTiming(frame) <= thresholdInMilliseconds) { return false; } } return true; } public bool WasFrameTimingGood(int framesAgo, float thresholdInMilliseconds, int lastChangeFrameCount, int changeFrameCost) { if (!AreFramesAvailable(framesAgo, lastChangeFrameCount, changeFrameCost)) { // Too early to know return false; } for (int frame = 0; frame < framesAgo; frame++) { if (GetFrameTiming(frame) > thresholdInMilliseconds) { return false; } } return true; } public bool WillFrameTimingBeBad(float extrapolationThresholdInMilliseconds, float thresholdInMilliseconds, int lastChangeFrameCount, int changeFrameCost) { if (!AreFramesAvailable(2, lastChangeFrameCount, changeFrameCost)) { // Too early to know return false; } // Predict next frame's cost using linear extrapolation: max(frame-1 to frame+1, frame-2 to frame+1) float frameMinus0Timing = GetFrameTiming(0); if (frameMinus0Timing <= extrapolationThresholdInMilliseconds) { return false; } float delta = frameMinus0Timing - GetFrameTiming(1); if (!AreFramesAvailable(3, lastChangeFrameCount, changeFrameCost)) { delta = Mathf.Max(delta, (frameMinus0Timing - GetFrameTiming(2)) / 2f); } return frameMinus0Timing + delta > thresholdInMilliseconds; } private static bool AreFramesAvailable(int framesAgo, int lastChangeFrameCount, int changeFrameCost) { return Time.frameCount >= framesAgo + lastChangeFrameCount + changeFrameCost; } } #endregion } } #endif
// *********************************************************************** // Copyright (c) 2014-2015 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.Reflection; using NUnit.Framework.Compatibility; using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal.Builders { /// <summary> /// NUnitTestFixtureBuilder is able to build a fixture given /// a class marked with a TestFixtureAttribute or an unmarked /// class containing test methods. In the first case, it is /// called by the attribute and in the second directly by /// NUnitSuiteBuilder. /// </summary> public class NUnitTestFixtureBuilder { #region Static Fields static readonly string NO_TYPE_ARGS_MSG = "Fixture type contains generic parameters. You must either provide " + "Type arguments or specify constructor arguments that allow NUnit " + "to deduce the Type arguments."; #endregion #region Instance Fields private ITestCaseBuilder _testBuilder = new DefaultTestCaseBuilder(); #endregion #region Public Methods /// <summary> /// Build a TestFixture from type provided. A non-null TestSuite /// must always be returned, since the method is generally called /// because the user has marked the target class as a fixture. /// If something prevents the fixture from being used, it should /// be returned nonetheless, labelled as non-runnable. /// </summary> /// <param name="typeInfo">An ITypeInfo for the fixture to be used.</param> /// <returns>A TestSuite object or one derived from TestSuite.</returns> // TODO: This should really return a TestFixture, but that requires changes to the Test hierarchy. public TestSuite BuildFrom(ITypeInfo typeInfo) { var fixture = new TestFixture(typeInfo); if (fixture.RunState != RunState.NotRunnable) CheckTestFixtureIsValid(fixture); fixture.ApplyAttributesToTest(typeInfo.Type.GetTypeInfo()); AddTestCasesToFixture(fixture); return fixture; } /// <summary> /// Overload of BuildFrom called by tests that have arguments. /// Builds a fixture using the provided type and information /// in the ITestFixtureData object. /// </summary> /// <param name="typeInfo">The TypeInfo for which to construct a fixture.</param> /// <param name="testFixtureData">An object implementing ITestFixtureData or null.</param> /// <returns></returns> public TestSuite BuildFrom(ITypeInfo typeInfo, ITestFixtureData testFixtureData) { Guard.ArgumentNotNull(testFixtureData, "testFixtureData"); object[] arguments = testFixtureData.Arguments; if (typeInfo.ContainsGenericParameters) { Type[] typeArgs = testFixtureData.TypeArgs; if (typeArgs.Length == 0) { int cnt = 0; foreach (object o in arguments) if (o is Type) cnt++; else break; typeArgs = new Type[cnt]; for (int i = 0; i < cnt; i++) typeArgs[i] = (Type)arguments[i]; if (cnt > 0) { object[] args = new object[arguments.Length - cnt]; for (int i = 0; i < args.Length; i++) args[i] = arguments[cnt + i]; arguments = args; } } if (typeArgs.Length > 0 || TypeHelper.CanDeduceTypeArgsFromArgs(typeInfo.Type, arguments, ref typeArgs)) { typeInfo = typeInfo.MakeGenericType(typeArgs); } } var fixture = new TestFixture(typeInfo); if (arguments != null && arguments.Length > 0) { string name = fixture.Name = typeInfo.GetDisplayName(arguments); string nspace = typeInfo.Namespace; fixture.FullName = nspace != null && nspace != "" ? nspace + "." + name : name; fixture.Arguments = arguments; } if (fixture.RunState != RunState.NotRunnable) fixture.RunState = testFixtureData.RunState; foreach (string key in testFixtureData.Properties.Keys) foreach (object val in testFixtureData.Properties[key]) fixture.Properties.Add(key, val); if (fixture.RunState != RunState.NotRunnable) CheckTestFixtureIsValid(fixture); fixture.ApplyAttributesToTest(typeInfo.Type.GetTypeInfo()); AddTestCasesToFixture(fixture); return fixture; } #endregion #region Helper Methods /// <summary> /// Method to add test cases to the newly constructed fixture. /// </summary> /// <param name="fixture">The fixture to which cases should be added</param> private void AddTestCasesToFixture(TestFixture fixture) { // TODO: Check this logic added from Neil's build. if (fixture.TypeInfo.ContainsGenericParameters) { fixture.RunState = RunState.NotRunnable; fixture.Properties.Set(PropertyNames.SkipReason, NO_TYPE_ARGS_MSG); return; } var methods = fixture.TypeInfo.GetMethods( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); foreach (IMethodInfo method in methods) { Test test = BuildTestCase(method, fixture); if (test != null) { fixture.Add(test); } } } /// <summary> /// Method to create a test case from a MethodInfo and add /// it to the fixture being built. It first checks to see if /// any global TestCaseBuilder addin wants to build the /// test case. If not, it uses the internal builder /// collection maintained by this fixture builder. /// /// The default implementation has no test case builders. /// Derived classes should add builders to the collection /// in their constructor. /// </summary> /// <param name="method">The method for which a test is to be created</param> /// <param name="suite">The test suite being built.</param> /// <returns>A newly constructed Test</returns> private Test BuildTestCase(IMethodInfo method, TestSuite suite) { return _testBuilder.CanBuildFrom(method, suite) ? _testBuilder.BuildFrom(method, suite) : null; } private static void CheckTestFixtureIsValid(TestFixture fixture) { if (fixture.TypeInfo.ContainsGenericParameters) { fixture.RunState = RunState.NotRunnable; fixture.Properties.Set(PropertyNames.SkipReason, NO_TYPE_ARGS_MSG); } else if (!fixture.TypeInfo.IsStaticClass) { object[] args = fixture.Arguments; Type[] argTypes; // Note: This could be done more simply using // Type.EmptyTypes and Type.GetTypeArray() but // they don't exist in all runtimes we support. argTypes = new Type[args.Length]; int index = 0; foreach (object arg in args) argTypes[index++] = arg.GetType(); if (!fixture.TypeInfo.HasConstructor(argTypes)) { fixture.RunState = RunState.NotRunnable; fixture.Properties.Set(PropertyNames.SkipReason, "No suitable constructor was found"); } } } private static bool IsStaticClass(Type type) { return type.GetTypeInfo().IsAbstract && type.GetTypeInfo().IsSealed; } #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.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Net; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Threading; using Xunit; using Xunit.NetCore.Extensions; namespace System.Diagnostics.Tests { public partial class ProcessTests : ProcessTestBase { private class FinalizingProcess : Process { public static volatile bool WasFinalized; public static void CreateAndRelease() { new FinalizingProcess(); } protected override void Dispose(bool disposing) { if (!disposing) { WasFinalized = true; } base.Dispose(disposing); } } private void SetAndCheckBasePriority(ProcessPriorityClass exPriorityClass, int priority) { _process.PriorityClass = exPriorityClass; _process.Refresh(); Assert.Equal(priority, _process.BasePriority); } private void AssertNonZeroWindowsZeroUnix(long value) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.NotEqual(0, value); } else { Assert.Equal(0, value); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] [PlatformSpecific(TestPlatforms.Windows)] // Expected behavior varies on Windows and Unix public void TestBasePriorityOnWindows() { CreateDefaultProcess(); ProcessPriorityClass originalPriority = _process.PriorityClass; var expected = PlatformDetection.IsWindowsNanoServer ? ProcessPriorityClass.BelowNormal : ProcessPriorityClass.Normal; // For some reason we're BelowNormal initially on Nano Assert.Equal(expected, originalPriority); try { // We are not checking for RealTime case here, as RealTime priority process can // preempt the threads of all other processes, including operating system processes // performing important tasks, which may cause the machine to be unresponsive. //SetAndCheckBasePriority(ProcessPriorityClass.RealTime, 24); SetAndCheckBasePriority(ProcessPriorityClass.High, 13); SetAndCheckBasePriority(ProcessPriorityClass.Idle, 4); SetAndCheckBasePriority(ProcessPriorityClass.Normal, 8); } finally { _process.PriorityClass = originalPriority; } } [Theory] [InlineData(true)] [InlineData(false)] [InlineData(null)] public void TestEnableRaiseEvents(bool? enable) { bool exitedInvoked = false; Process p = CreateProcessLong(); if (enable.HasValue) { p.EnableRaisingEvents = enable.Value; } p.Exited += delegate { exitedInvoked = true; }; StartSleepKillWait(p); if (enable.GetValueOrDefault()) { // There's no guarantee that the Exited callback will be invoked by // the time Process.WaitForExit completes, though it's extremely likely. // There could be a race condition where WaitForExit is returning from // its wait and sees that the callback is already running asynchronously, // at which point it returns to the caller even if the callback hasn't // entirely completed. As such, we spin until the value is set. Assert.True(SpinWait.SpinUntil(() => exitedInvoked, WaitInMS)); } else { Assert.False(exitedInvoked); } } [Fact] public void TestExitCode() { { Process p = CreateProcessPortable(RemotelyInvokable.Dummy); p.Start(); Assert.True(p.WaitForExit(WaitInMS)); Assert.Equal(SuccessExitCode, p.ExitCode); } { Process p = CreateProcessLong(); StartSleepKillWait(p); Assert.NotEqual(0, p.ExitCode); } } [Fact] public void TestExitTime() { // Try twice, since it's possible that the system clock could be adjusted backwards between when we snapshot it // and when the process ends, but vanishingly unlikely that would happen twice. DateTime timeBeforeProcessStart = DateTime.MaxValue; Process p = null; for (int i = 0; i <= 1; i++) { // ExitTime resolution on some platforms is less accurate than our DateTime.UtcNow resolution, so // we subtract ms from the begin time to account for it. timeBeforeProcessStart = DateTime.UtcNow.AddMilliseconds(-25); p = CreateProcessLong(); p.Start(); Assert.Throws<InvalidOperationException>(() => p.ExitTime); p.Kill(); Assert.True(p.WaitForExit(WaitInMS)); if (p.ExitTime.ToUniversalTime() >= timeBeforeProcessStart) break; } Assert.True(p.ExitTime.ToUniversalTime() >= timeBeforeProcessStart, $@"TestExitTime is incorrect. " + $@"TimeBeforeStart {timeBeforeProcessStart} Ticks={timeBeforeProcessStart.Ticks}, " + $@"ExitTime={p.ExitTime}, Ticks={p.ExitTime.Ticks}, " + $@"ExitTimeUniversal {p.ExitTime.ToUniversalTime()} Ticks={p.ExitTime.ToUniversalTime().Ticks}, " + $@"NowUniversal {DateTime.Now.ToUniversalTime()} Ticks={DateTime.Now.Ticks}"); } [Fact] public void StartTime_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.StartTime); } [Fact] public void TestId() { CreateDefaultProcess(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Equal(_process.Id, Interop.GetProcessId(_process.SafeHandle)); } else { IEnumerable<int> testProcessIds = Process.GetProcessesByName(HostRunnerName).Select(p => p.Id); Assert.Contains(_process.Id, testProcessIds); } } [Fact] public void TestHasExited() { { Process p = CreateProcessPortable(RemotelyInvokable.Dummy); p.Start(); Assert.True(p.WaitForExit(WaitInMS)); Assert.True(p.HasExited, "TestHasExited001 failed"); } { Process p = CreateProcessLong(); p.Start(); try { Assert.False(p.HasExited, "TestHasExited002 failed"); } finally { p.Kill(); Assert.True(p.WaitForExit(WaitInMS)); } Assert.True(p.HasExited, "TestHasExited003 failed"); } } [Fact] public void HasExited_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.HasExited); } [Fact] public void Kill_NotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.Kill()); } [Fact] public void TestMachineName() { CreateDefaultProcess(); // Checking that the MachineName returns some value. Assert.NotNull(_process.MachineName); } [Fact] public void MachineName_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.MachineName); } [Fact] [ActiveIssue("https://github.com/dotnet/corefx/issues/22264", TargetFrameworkMonikers.UapNotUapAot)] public void TestMainModuleOnNonOSX() { Process p = Process.GetCurrentProcess(); Assert.True(p.Modules.Count > 0); Assert.Equal(HostRunnerName.ToLowerInvariant(), p.MainModule.ModuleName.ToLowerInvariant()); Assert.EndsWith(HostRunnerName, p.MainModule.FileName); Assert.Equal(string.Format("System.Diagnostics.ProcessModule ({0})", HostRunnerName), p.MainModule.ToString()); } [Fact] public void TestMaxWorkingSet() { CreateDefaultProcess(); using (Process p = Process.GetCurrentProcess()) { Assert.True((long)p.MaxWorkingSet > 0); Assert.True((long)p.MinWorkingSet >= 0); } if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) return; // doesn't support getting/setting working set for other processes long curValue = (long)_process.MaxWorkingSet; Assert.True(curValue >= 0); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { try { _process.MaxWorkingSet = (IntPtr)((int)curValue + 1024); IntPtr min, max; uint flags; Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags); curValue = (int)max; _process.Refresh(); Assert.Equal(curValue, (int)_process.MaxWorkingSet); } finally { _process.MaxWorkingSet = (IntPtr)curValue; } } } [Fact] [PlatformSpecific(~TestPlatforms.OSX)] // Getting MaxWorkingSet is not supported on OSX. public void MaxWorkingSet_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.MaxWorkingSet); } [Fact] [PlatformSpecific(TestPlatforms.OSX)] public void MaxValueWorkingSet_GetSetMacos_ThrowsPlatformSupportedException() { var process = new Process(); Assert.Throws<PlatformNotSupportedException>(() => process.MaxWorkingSet); Assert.Throws<PlatformNotSupportedException>(() => process.MaxWorkingSet = (IntPtr)1); } [Fact] public void TestMinWorkingSet() { CreateDefaultProcess(); using (Process p = Process.GetCurrentProcess()) { Assert.True((long)p.MaxWorkingSet > 0); Assert.True((long)p.MinWorkingSet >= 0); } if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) return; // doesn't support getting/setting working set for other processes long curValue = (long)_process.MinWorkingSet; Assert.True(curValue >= 0); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { try { _process.MinWorkingSet = (IntPtr)((int)curValue - 1024); IntPtr min, max; uint flags; Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags); curValue = (int)min; _process.Refresh(); Assert.Equal(curValue, (int)_process.MinWorkingSet); } finally { _process.MinWorkingSet = (IntPtr)curValue; } } } [Fact] [PlatformSpecific(~TestPlatforms.OSX)] // Getting MinWorkingSet is not supported on OSX. public void MinWorkingSet_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.MinWorkingSet); } [Fact] [PlatformSpecific(TestPlatforms.OSX)] public void MinWorkingSet_GetMacos_ThrowsPlatformSupportedException() { var process = new Process(); Assert.Throws<PlatformNotSupportedException>(() => process.MinWorkingSet); } [Fact] public void TestModules() { ProcessModuleCollection moduleCollection = Process.GetCurrentProcess().Modules; foreach (ProcessModule pModule in moduleCollection) { // Validated that we can get a value for each of the following. Assert.NotNull(pModule); Assert.NotNull(pModule.FileName); Assert.NotNull(pModule.ModuleName); // Just make sure these don't throw IntPtr baseAddr = pModule.BaseAddress; IntPtr entryAddr = pModule.EntryPointAddress; int memSize = pModule.ModuleMemorySize; } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestNonpagedSystemMemorySize64() { CreateDefaultProcess(); AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize64); } [Fact] public void NonpagedSystemMemorySize64_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.NonpagedSystemMemorySize64); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestPagedMemorySize64() { CreateDefaultProcess(); AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize64); } [Fact] public void PagedMemorySize64_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.PagedMemorySize64); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestPagedSystemMemorySize64() { CreateDefaultProcess(); AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize64); } [Fact] public void PagedSystemMemorySize64_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.PagedSystemMemorySize64); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestPeakPagedMemorySize64() { CreateDefaultProcess(); AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize64); } [Fact] public void PeakPagedMemorySize64_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.PeakPagedMemorySize64); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestPeakVirtualMemorySize64() { CreateDefaultProcess(); AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize64); } [Fact] public void PeakVirtualMemorySize64_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.PeakVirtualMemorySize64); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestPeakWorkingSet64() { CreateDefaultProcess(); AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet64); } [Fact] public void PeakWorkingSet64_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.PeakWorkingSet64); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestPrivateMemorySize64() { CreateDefaultProcess(); AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize64); } [Fact] public void PrivateMemorySize64_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.PrivateMemorySize64); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestVirtualMemorySize64() { CreateDefaultProcess(); Assert.True(_process.VirtualMemorySize64 > 0); } [Fact] public void VirtualMemorySize64_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.VirtualMemorySize64); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestWorkingSet64() { CreateDefaultProcess(); if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { // resident memory can be 0 on OSX. Assert.True(_process.WorkingSet64 >= 0); return; } Assert.True(_process.WorkingSet64 > 0); } [Fact] public void WorkingSet64_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.WorkingSet64); } [Fact] public void TestProcessorTime() { CreateDefaultProcess(); Assert.True(_process.UserProcessorTime.TotalSeconds >= 0); Assert.True(_process.PrivilegedProcessorTime.TotalSeconds >= 0); double processorTimeBeforeSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds; double processorTimeAtHalfSpin = 0; // Perform loop to occupy cpu, takes less than a second. int i = int.MaxValue / 16; while (i > 0) { i--; if (i == int.MaxValue / 32) processorTimeAtHalfSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds; } Assert.InRange(processorTimeAtHalfSpin, processorTimeBeforeSpin, Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds); } [Fact] public void UserProcessorTime_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.UserProcessorTime); } [Fact] public void PriviledgedProcessorTime_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.PrivilegedProcessorTime); } [Fact] public void TotalProcessorTime_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.TotalProcessorTime); } [Fact] [ActiveIssue("https://github.com/dotnet/corefx/issues/22266", TargetFrameworkMonikers.UapNotUapAot)] public void TestProcessStartTime() { TimeSpan allowedWindow = TimeSpan.FromSeconds(3); DateTime testStartTime = DateTime.UtcNow; using (var remote = RemoteInvoke(() => { Console.Write(Process.GetCurrentProcess().StartTime.ToUniversalTime()); return SuccessExitCode; }, new RemoteInvokeOptions { StartInfo = new ProcessStartInfo { RedirectStandardOutput = true } })) { Assert.Equal(remote.Process.StartTime, remote.Process.StartTime); DateTime remoteStartTime = DateTime.Parse(remote.Process.StandardOutput.ReadToEnd()); DateTime curTime = DateTime.UtcNow; Assert.InRange(remoteStartTime, testStartTime - allowedWindow, curTime + allowedWindow); } } [Fact] public void ExitTime_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.ExitTime); } [Fact] [PlatformSpecific(~TestPlatforms.OSX)] // getting/setting affinity not supported on OSX public void TestProcessorAffinity() { CreateDefaultProcess(); IntPtr curProcessorAffinity = _process.ProcessorAffinity; try { _process.ProcessorAffinity = new IntPtr(0x1); Assert.Equal(new IntPtr(0x1), _process.ProcessorAffinity); } finally { _process.ProcessorAffinity = curProcessorAffinity; Assert.Equal(curProcessorAffinity, _process.ProcessorAffinity); } } [Fact] public void TestPriorityBoostEnabled() { CreateDefaultProcess(); bool isPriorityBoostEnabled = _process.PriorityBoostEnabled; try { _process.PriorityBoostEnabled = true; Assert.True(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled001 failed"); _process.PriorityBoostEnabled = false; Assert.False(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled002 failed"); } finally { _process.PriorityBoostEnabled = isPriorityBoostEnabled; } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // PriorityBoostEnabled is a no-op on Unix. public void PriorityBoostEnabled_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.PriorityBoostEnabled); Assert.Throws<InvalidOperationException>(() => process.PriorityBoostEnabled = true); } [Fact, PlatformSpecific(TestPlatforms.Windows)] // Expected behavior varies on Windows and Unix public void TestPriorityClassWindows() { CreateDefaultProcess(); ProcessPriorityClass priorityClass = _process.PriorityClass; try { _process.PriorityClass = ProcessPriorityClass.High; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High); _process.PriorityClass = ProcessPriorityClass.Normal; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal); } finally { _process.PriorityClass = priorityClass; } } [Theory] [InlineData((ProcessPriorityClass)0)] [InlineData(ProcessPriorityClass.Normal | ProcessPriorityClass.Idle)] public void TestInvalidPriorityClass(ProcessPriorityClass priorityClass) { var process = new Process(); Assert.Throws<InvalidEnumArgumentException>(() => process.PriorityClass = priorityClass); } [Fact] public void PriorityClass_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.PriorityClass); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestProcessName() { CreateDefaultProcess(); string expected = PlatformDetection.IsFullFramework || PlatformDetection.IsNetNative ? TestConsoleApp : HostRunner; Assert.Equal(Path.GetFileNameWithoutExtension(expected), Path.GetFileNameWithoutExtension(_process.ProcessName), StringComparer.OrdinalIgnoreCase); } [Fact] public void ProcessName_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.ProcessName); } [Fact] public void TestSafeHandle() { CreateDefaultProcess(); Assert.False(_process.SafeHandle.IsInvalid); } [Fact] public void SafeHandle_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.SafeHandle); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestSessionId() { CreateDefaultProcess(); uint sessionId; #if TargetsWindows Interop.ProcessIdToSessionId((uint)_process.Id, out sessionId); #else sessionId = (uint)Interop.getsid(_process.Id); #endif Assert.Equal(sessionId, (uint)_process.SessionId); } [Fact] public void SessionId_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.SessionId); } [Fact] public void TestGetCurrentProcess() { Process current = Process.GetCurrentProcess(); Assert.NotNull(current); int currentProcessId = #if TargetsWindows Interop.GetCurrentProcessId(); #else Interop.getpid(); #endif Assert.Equal(currentProcessId, current.Id); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestGetProcessById() { CreateDefaultProcess(); Process p = Process.GetProcessById(_process.Id); Assert.Equal(_process.Id, p.Id); Assert.Equal(_process.ProcessName, p.ProcessName); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestGetProcesses() { Process currentProcess = Process.GetCurrentProcess(); // Get all the processes running on the machine, and check if the current process is one of them. var foundCurrentProcess = (from p in Process.GetProcesses() where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName)) select p).Any(); Assert.True(foundCurrentProcess, "TestGetProcesses001 failed"); foundCurrentProcess = (from p in Process.GetProcesses(currentProcess.MachineName) where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName)) select p).Any(); Assert.True(foundCurrentProcess, "TestGetProcesses002 failed"); } [Fact] public void GetProcesseses_NullMachineName_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("machineName", () => Process.GetProcesses(null)); } [Fact] public void GetProcesses_EmptyMachineName_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>(null, () => Process.GetProcesses("")); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void GetProcessesByName_ProcessName_ReturnsExpected() { // Get the current process using its name Process currentProcess = Process.GetCurrentProcess(); Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName); Assert.NotEmpty(processes); Assert.All(processes, process => Assert.Equal(".", process.MachineName)); } public static IEnumerable<object[]> MachineName_TestData() { string currentProcessName = Process.GetCurrentProcess().MachineName; yield return new object[] { currentProcessName }; yield return new object[] { "." }; yield return new object[] { Dns.GetHostName() }; } public static IEnumerable<object[]> MachineName_Remote_TestData() { yield return new object[] { Guid.NewGuid().ToString("N") }; yield return new object[] { "\\" + Guid.NewGuid().ToString("N") }; } [Theory] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] [MemberData(nameof(MachineName_TestData))] public void GetProcessesByName_ProcessNameMachineName_ReturnsExpected(string machineName) { Process currentProcess = Process.GetCurrentProcess(); Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName, machineName); Assert.NotEmpty(processes); Assert.All(processes, process => Assert.Equal(machineName, process.MachineName)); } [MemberData(nameof(MachineName_Remote_TestData))] [PlatformSpecific(TestPlatforms.Windows)] // Accessing processes on remote machines is only supported on Windows. public void GetProcessesByName_RemoteMachineNameWindows_ReturnsExpected(string machineName) { try { GetProcessesByName_ProcessNameMachineName_ReturnsExpected(machineName); } catch (InvalidOperationException) { // As we can't detect reliably if performance counters are enabled // we let possible InvalidOperationExceptions pass silently. } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void GetProcessesByName_NoSuchProcess_ReturnsEmpty() { string processName = Guid.NewGuid().ToString("N"); Assert.Empty(Process.GetProcessesByName(processName)); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void GetProcessesByName_NullMachineName_ThrowsArgumentNullException() { Process currentProcess = Process.GetCurrentProcess(); AssertExtensions.Throws<ArgumentNullException>("machineName", () => Process.GetProcessesByName(currentProcess.ProcessName, null)); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void GetProcessesByName_EmptyMachineName_ThrowsArgumentException() { Process currentProcess = Process.GetCurrentProcess(); AssertExtensions.Throws<ArgumentException>(null, () => Process.GetProcessesByName(currentProcess.ProcessName, "")); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Behavior differs on Windows and Unix [ActiveIssue("https://github.com/dotnet/corefx/issues/18212", TargetFrameworkMonikers.UapAot)] [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "Retrieving information about local processes is not supported on uap")] public void TestProcessOnRemoteMachineWindows() { Process currentProccess = Process.GetCurrentProcess(); void TestRemoteProccess(Process remoteProcess) { Assert.Equal(currentProccess.Id, remoteProcess.Id); Assert.Equal(currentProccess.BasePriority, remoteProcess.BasePriority); Assert.Equal(currentProccess.EnableRaisingEvents, remoteProcess.EnableRaisingEvents); Assert.Equal("127.0.0.1", remoteProcess.MachineName); // This property throws exception only on remote processes. Assert.Throws<NotSupportedException>(() => remoteProcess.MainModule); } try { TestRemoteProccess(Process.GetProcessById(currentProccess.Id, "127.0.0.1")); TestRemoteProccess(Process.GetProcessesByName(currentProccess.ProcessName, "127.0.0.1").Where(p => p.Id == currentProccess.Id).Single()); } catch (InvalidOperationException) { // As we can't detect reliably if performance counters are enabled // we let possible InvalidOperationExceptions pass silently. } } [Fact] public void StartInfo_GetFileName_ReturnsExpected() { Process process = CreateProcessLong(); process.Start(); // Processes are not hosted by dotnet in the full .NET Framework. string expectedFileName = PlatformDetection.IsFullFramework || PlatformDetection.IsNetNative ? TestConsoleApp : RunnerName; Assert.Equal(expectedFileName, process.StartInfo.FileName); process.Kill(); Assert.True(process.WaitForExit(WaitInMS)); } [Fact] public void StartInfo_SetOnRunningProcess_ThrowsInvalidOperationException() { Process process = CreateProcessLong(); process.Start(); // .NET Core fixes a bug where Process.StartInfo for a unrelated process would // return information about the current process, not the unrelated process. // See https://github.com/dotnet/corefx/issues/1100. if (PlatformDetection.IsFullFramework) { var startInfo = new ProcessStartInfo(); process.StartInfo = startInfo; Assert.Equal(startInfo, process.StartInfo); } else { Assert.Throws<InvalidOperationException>(() => process.StartInfo = new ProcessStartInfo()); } process.Kill(); Assert.True(process.WaitForExit(WaitInMS)); } [Fact] public void StartInfo_SetGet_ReturnsExpected() { var process = new Process() { StartInfo = new ProcessStartInfo(TestConsoleApp) }; Assert.Equal(TestConsoleApp, process.StartInfo.FileName); } [Fact] public void StartInfo_SetNull_ThrowsArgumentNullException() { var process = new Process(); Assert.Throws<ArgumentNullException>(() => process.StartInfo = null); } [Fact] public void StartInfo_GetOnRunningProcess_ThrowsInvalidOperationException() { Process process = Process.GetCurrentProcess(); // .NET Core fixes a bug where Process.StartInfo for an unrelated process would // return information about the current process, not the unrelated process. // See https://github.com/dotnet/corefx/issues/1100. if (PlatformDetection.IsFullFramework) { Assert.NotNull(process.StartInfo); } else { Assert.Throws<InvalidOperationException>(() => process.StartInfo); } } [Theory] [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "Non applicable for uap - RemoteInvoke works differently")] [InlineData(@"""abc"" d e", @"abc,d,e")] [InlineData(@"""abc"" d e", @"abc,d,e")] [InlineData("\"abc\"\t\td\te", @"abc,d,e")] [InlineData(@"a\\b d""e f""g h", @"a\\b,de fg,h")] [InlineData(@"\ \\ \\\", @"\,\\,\\\")] [InlineData(@"a\\\""b c d", @"a\""b,c,d")] [InlineData(@"a\\\\""b c"" d e", @"a\\b c,d,e")] [InlineData(@"a""b c""d e""f g""h i""j k""l", @"ab cd,ef gh,ij kl")] [InlineData(@"a b c""def", @"a,b,cdef")] [InlineData(@"""\a\"" \\""\\\ b c", @"\a"" \\\\,b,c")] [InlineData("\"\" b \"\"", ",b,")] [InlineData("\"\"\"\" b c", "\",b,c")] [InlineData("c\"\"\"\" b \"\"\\", "c\",b,\\")] [InlineData("\"\"c \"\"b\"\" d\"\\", "c,b,d\\")] [InlineData("\"\"a\"\" b d", "a,b,d")] [InlineData("b d \"\"a\"\" ", "b,d,a")] [InlineData("\\\"\\\"a\\\"\\\" b d", "\"\"a\"\",b,d")] [InlineData("b d \\\"\\\"a\\\"\\\"", "b,d,\"\"a\"\"")] public void TestArgumentParsing(string inputArguments, string expectedArgv) { var options = new RemoteInvokeOptions { Start = true, StartInfo = new ProcessStartInfo { RedirectStandardOutput = true } }; using (RemoteInvokeHandle handle = RemoteInvokeRaw((Func<string, string, string, int>)RemotelyInvokable.ConcatThreeArguments, inputArguments, options)) { Assert.Equal(expectedArgv, handle.Process.StandardOutput.ReadToEnd()); } } [Fact] public void StandardInput_GetNotRedirected_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.StandardInput); } // [Fact] // uncomment for diagnostic purposes to list processes to console public void TestDiagnosticsWithConsoleWriteLine() { foreach (var p in Process.GetProcesses().OrderBy(p => p.Id)) { Console.WriteLine("{0} : \"{1}\" (Threads: {2})", p.Id, p.ProcessName, p.Threads.Count); p.Dispose(); } } [Fact] public void CanBeFinalized() { FinalizingProcess.CreateAndRelease(); GC.Collect(); GC.WaitForPendingFinalizers(); Assert.True(FinalizingProcess.WasFinalized); } [Theory] [InlineData(false)] [InlineData(true)] public void TestStartWithMissingFile(bool fullPath) { string path = Guid.NewGuid().ToString("N"); if (fullPath) { path = Path.GetFullPath(path); Assert.True(Path.IsPathRooted(path)); } else { Assert.False(Path.IsPathRooted(path)); } Assert.False(File.Exists(path)); Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(path)); Assert.NotEqual(0, e.NativeErrorCode); } [Fact] public void Start_NullStartInfo_ThrowsArgumentNullExceptionException() { AssertExtensions.Throws<ArgumentNullException>("startInfo", () => Process.Start((ProcessStartInfo)null)); } [Fact] public void Start_EmptyFileName_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.Start()); } [Fact] public void Start_HasStandardOutputEncodingNonRedirected_ThrowsInvalidOperationException() { var process = new Process { StartInfo = new ProcessStartInfo { FileName = "FileName", RedirectStandardOutput = false, StandardOutputEncoding = Encoding.UTF8 } }; Assert.Throws<InvalidOperationException>(() => process.Start()); } [Fact] public void Start_HasStandardErrorEncodingNonRedirected_ThrowsInvalidOperationException() { var process = new Process { StartInfo = new ProcessStartInfo { FileName = "FileName", RedirectStandardError = false, StandardErrorEncoding = Encoding.UTF8 } }; Assert.Throws<InvalidOperationException>(() => process.Start()); } [Fact] public void Start_Disposed_ThrowsObjectDisposedException() { var process = new Process(); process.StartInfo.FileName = "Nothing"; process.Dispose(); Assert.Throws<ObjectDisposedException>(() => process.Start()); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] [PlatformSpecific(TestPlatforms.Linux | TestPlatforms.Windows)] // Expected process HandleCounts differs on OSX public void TestHandleCount() { using (Process p = Process.GetCurrentProcess()) { Assert.True(p.HandleCount > 0); } } [Fact] [PlatformSpecific(TestPlatforms.OSX)] // Expected process HandleCounts differs on OSX public void TestHandleCount_OSX() { using (Process p = Process.GetCurrentProcess()) { Assert.Equal(0, p.HandleCount); } } [Fact] [PlatformSpecific(TestPlatforms.Linux | TestPlatforms.Windows)] // Expected process HandleCounts differs on OSX [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Handle count change is not reliable, but seems less robust on NETFX")] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void HandleCountChanges() { RemoteInvoke(() => { Process p = Process.GetCurrentProcess(); int handleCount = p.HandleCount; using (var fs1 = File.Open(GetTestFilePath(), FileMode.OpenOrCreate)) using (var fs2 = File.Open(GetTestFilePath(), FileMode.OpenOrCreate)) using (var fs3 = File.Open(GetTestFilePath(), FileMode.OpenOrCreate)) { p.Refresh(); int secondHandleCount = p.HandleCount; Assert.True(handleCount < secondHandleCount); handleCount = secondHandleCount; } p.Refresh(); int thirdHandleCount = p.HandleCount; Assert.True(thirdHandleCount < handleCount); return SuccessExitCode; }).Dispose(); } [Fact] public void HandleCount_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.HandleCount); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // MainWindowHandle is not supported on Unix. public void MainWindowHandle_NoWindow_ReturnsEmptyHandle() { CreateDefaultProcess(); Assert.Equal(IntPtr.Zero, _process.MainWindowHandle); Assert.Equal(_process.MainWindowHandle, _process.MainWindowHandle); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "HWND not available")] public void MainWindowHandle_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.MainWindowHandle); } [Fact] public void MainWindowTitle_NoWindow_ReturnsEmpty() { CreateDefaultProcess(); Assert.Empty(_process.MainWindowTitle); Assert.Same(_process.MainWindowTitle, _process.MainWindowTitle); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // MainWindowTitle is a no-op and always returns string.Empty on Unix. [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "HWND not available")] public void MainWindowTitle_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.MainWindowTitle); } [Fact] public void CloseMainWindow_NoWindow_ReturnsFalse() { CreateDefaultProcess(); Assert.False(_process.CloseMainWindow()); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // CloseMainWindow is a no-op and always returns false on Unix. [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "MainWindow handle is not available on UAP")] public void CloseMainWindow_NotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.CloseMainWindow()); } [PlatformSpecific(TestPlatforms.Windows)] // Needs to get the process Id from OS [Fact] public void TestRespondingWindows() { using (Process p = Process.GetCurrentProcess()) { Assert.True(p.Responding); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Responding always returns true on Unix. [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "HWND not available")] public void Responding_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.Responding); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestNonpagedSystemMemorySize() { CreateDefaultProcess(); #pragma warning disable 0618 AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize); #pragma warning restore 0618 } [Fact] public void NonpagedSystemMemorySize_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); #pragma warning disable 0618 Assert.Throws<InvalidOperationException>(() => process.NonpagedSystemMemorySize); #pragma warning restore 0618 } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestPagedMemorySize() { CreateDefaultProcess(); #pragma warning disable 0618 AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize); #pragma warning restore 0618 } [Fact] public void PagedMemorySize_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); #pragma warning disable 0618 Assert.Throws<InvalidOperationException>(() => process.PagedMemorySize); #pragma warning restore 0618 } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestPagedSystemMemorySize() { CreateDefaultProcess(); #pragma warning disable 0618 AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize); #pragma warning restore 0618 } [Fact] public void PagedSystemMemorySize_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); #pragma warning disable 0618 Assert.Throws<InvalidOperationException>(() => process.PagedSystemMemorySize); #pragma warning restore 0618 } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestPeakPagedMemorySize() { CreateDefaultProcess(); #pragma warning disable 0618 AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize); #pragma warning restore 0618 } [Fact] public void PeakPagedMemorySize_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); #pragma warning disable 0618 Assert.Throws<InvalidOperationException>(() => process.PeakPagedMemorySize); #pragma warning restore 0618 } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestPeakVirtualMemorySize() { CreateDefaultProcess(); #pragma warning disable 0618 AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize); #pragma warning restore 0618 } [Fact] public void PeakVirtualMemorySize_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); #pragma warning disable 0618 Assert.Throws<InvalidOperationException>(() => process.PeakVirtualMemorySize); #pragma warning restore 0618 } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestPeakWorkingSet() { CreateDefaultProcess(); #pragma warning disable 0618 AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet); #pragma warning restore 0618 } [Fact] public void PeakWorkingSet_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); #pragma warning disable 0618 Assert.Throws<InvalidOperationException>(() => process.PeakWorkingSet); #pragma warning restore 0618 } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestPrivateMemorySize() { CreateDefaultProcess(); #pragma warning disable 0618 AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize); #pragma warning restore 0618 } [Fact] public void PrivateMemorySize_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); #pragma warning disable 0618 Assert.Throws<InvalidOperationException>(() => process.PrivateMemorySize); #pragma warning restore 0618 } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestVirtualMemorySize() { CreateDefaultProcess(); #pragma warning disable 0618 Assert.Equal(unchecked((int)_process.VirtualMemorySize64), _process.VirtualMemorySize); #pragma warning restore 0618 } [Fact] public void VirtualMemorySize_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); #pragma warning disable 0618 Assert.Throws<InvalidOperationException>(() => process.VirtualMemorySize); #pragma warning restore 0618 } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestWorkingSet() { CreateDefaultProcess(); if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { // resident memory can be 0 on OSX. #pragma warning disable 0618 Assert.True(_process.WorkingSet >= 0); #pragma warning restore 0618 return; } #pragma warning disable 0618 Assert.True(_process.WorkingSet > 0); #pragma warning restore 0618 } [Fact] public void WorkingSet_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); #pragma warning disable 0618 Assert.Throws<InvalidOperationException>(() => process.WorkingSet); #pragma warning restore 0618 } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix public void Process_StartInvalidNamesTest() { Assert.Throws<InvalidOperationException>(() => Process.Start(null, "userName", new SecureString(), "thisDomain")); Assert.Throws<InvalidOperationException>(() => Process.Start(string.Empty, "userName", new SecureString(), "thisDomain")); Assert.Throws<Win32Exception>(() => Process.Start("exe", string.Empty, new SecureString(), "thisDomain")); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void Process_StartWithInvalidUserNamePassword() { SecureString password = AsSecureString("Value"); Assert.Throws<Win32Exception>(() => Process.Start(GetCurrentProcessName(), "userName", password, "thisDomain")); Assert.Throws<Win32Exception>(() => Process.Start(GetCurrentProcessName(), Environment.UserName, password, Environment.UserDomainName)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void Process_StartTest() { string currentProcessName = GetCurrentProcessName(); string userName = string.Empty; string domain = "thisDomain"; SecureString password = AsSecureString("Value"); Process p = Process.Start(currentProcessName, userName, password, domain); // This writes junk to the Console but with this overload, we can't prevent that. Assert.NotNull(p); Assert.Equal(currentProcessName, p.StartInfo.FileName); Assert.Equal(userName, p.StartInfo.UserName); Assert.Same(password, p.StartInfo.Password); Assert.Equal(domain, p.StartInfo.Domain); Assert.True(p.WaitForExit(WaitInMS)); password.Dispose(); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void Process_StartWithArgumentsTest() { string currentProcessName = GetCurrentProcessName(); string userName = string.Empty; string domain = Environment.UserDomainName; string arguments = "-xml testResults.xml"; SecureString password = AsSecureString("Value"); Process p = Process.Start(currentProcessName, arguments, userName, password, domain); Assert.NotNull(p); Assert.Equal(currentProcessName, p.StartInfo.FileName); Assert.Equal(arguments, p.StartInfo.Arguments); Assert.Equal(userName, p.StartInfo.UserName); Assert.Same(password, p.StartInfo.Password); Assert.Equal(domain, p.StartInfo.Domain); p.Kill(); password.Dispose(); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix public void Process_StartWithDuplicatePassword() { var startInfo = new ProcessStartInfo() { FileName = "exe", UserName = "dummyUser", PasswordInClearText = "Value", Password = AsSecureString("Value"), UseShellExecute = false }; var process = new Process() { StartInfo = startInfo }; AssertExtensions.Throws<ArgumentException>(null, () => process.Start()); } [Fact] public void TestLongProcessIsWorking() { // Sanity check for CreateProcessLong Process p = CreateProcessLong(); p.Start(); Thread.Sleep(500); Assert.False(p.HasExited); p.Kill(); p.WaitForExit(); Assert.True(p.HasExited); } private string GetCurrentProcessName() { return $"{Process.GetCurrentProcess().ProcessName}.exe"; } private SecureString AsSecureString(string str) { SecureString secureString = new SecureString(); foreach (var ch in str) { secureString.AppendChar(ch); } return secureString; } } }
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 DebuggerApi; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Debugger.Interop; using NSubstitute; using NUnit.Framework; using YetiCommon.CastleAspects; using YetiVSI.DebugEngine; namespace YetiVSI.Test.DebugEngine { [TestFixture] class DebugCodeContextTests { const ulong _testPc = 0x123456789abcdef0; const string _testPcStr = "0x123456789abcdef0"; const string _testName = "frame name"; DebugCodeContext.Factory _codeContextfactory = new DebugCodeContext.Factory(); RemoteTarget _target; IDebugDocumentContext2 _mockDocumentContext; IDebugCodeContext2 _codeContext; [SetUp] public void SetUp() { _target = Substitute.For<RemoteTarget>(); _mockDocumentContext = Substitute.For<IDebugDocumentContext2>(); _codeContext = _codeContextfactory.Create( _target, _testPc, _testName, _mockDocumentContext, Guid.Empty); } [Test] public void GetName() { Assert.AreEqual(VSConstants.S_OK, _codeContext.GetName(out string name)); Assert.AreEqual(_testName, name); } [Test] public void GetNameNull() { _codeContext = _codeContextfactory.Create( _target, _testPc, null, _mockDocumentContext); Assert.AreEqual(VSConstants.S_OK, _codeContext.GetName(out string name)); Assert.AreEqual(_testPcStr, name); } [Test] public void GetNameResolvedFromAddress() { var address = Substitute.For<SbAddress>(); address.GetFunction().GetName().Returns("dummy_func()"); _target.ResolveLoadAddress(_testPc).Returns(address); _codeContext = _codeContextfactory.Create( _target, _testPc, functionName: null, documentContext: null); Assert.AreEqual(VSConstants.S_OK, _codeContext.GetName(out string name)); Assert.AreEqual("dummy_func()", name); } [Test] public void GetInfoAddress() { var contextInfo = new CONTEXT_INFO[1]; Assert.AreEqual(VSConstants.S_OK, _codeContext.GetInfo(enum_CONTEXT_INFO_FIELDS.CIF_ADDRESS, contextInfo)); Assert.AreEqual(enum_CONTEXT_INFO_FIELDS.CIF_ADDRESS, contextInfo[0].dwFields); Assert.AreEqual(_testPcStr, contextInfo[0].bstrAddress); } [Test] public void GetInfoName() { var contextInfo = new CONTEXT_INFO[1]; Assert.AreEqual(VSConstants.S_OK, _codeContext.GetInfo(enum_CONTEXT_INFO_FIELDS.CIF_FUNCTION, contextInfo)); Assert.AreEqual(enum_CONTEXT_INFO_FIELDS.CIF_FUNCTION, contextInfo[0].dwFields); Assert.AreEqual(_testName, contextInfo[0].bstrFunction); } [Test] public void GetInfo() { var contextInfo = new CONTEXT_INFO[1]; Assert.AreEqual(VSConstants.S_OK, _codeContext.GetInfo( enum_CONTEXT_INFO_FIELDS.CIF_ADDRESS | enum_CONTEXT_INFO_FIELDS.CIF_FUNCTION, contextInfo)); Assert.AreEqual( enum_CONTEXT_INFO_FIELDS.CIF_ADDRESS | enum_CONTEXT_INFO_FIELDS.CIF_FUNCTION, contextInfo[0].dwFields); Assert.AreEqual(_testPcStr, contextInfo[0].bstrAddress); Assert.AreEqual(_testName, contextInfo[0].bstrFunction); } [Test] public void GetInfoNone() { var contextInfo = new CONTEXT_INFO[1]; Assert.AreEqual(VSConstants.S_OK, _codeContext.GetInfo(0, contextInfo)); Assert.AreEqual(0, (uint)contextInfo[0].dwFields); } [Test] public void CompareNone() { Assert.AreEqual(VSConstants.S_FALSE, _codeContext.Compare( enum_CONTEXT_COMPARE.CONTEXT_EQUAL, null, 0, out _)); } [Test] public void CompareEqual() { uint matchIndex; Assert.AreEqual(VSConstants.S_OK, _codeContext.Compare( enum_CONTEXT_COMPARE.CONTEXT_EQUAL, new IDebugMemoryContext2[1] { _codeContext}, 1, out matchIndex)); Assert.AreEqual(0, matchIndex); } [Test] public void CompareGreaterThan() { Assert.AreEqual(VSConstants.S_OK, _codeContext.Compare( enum_CONTEXT_COMPARE.CONTEXT_GREATER_THAN, new IDebugMemoryContext2[1] { _codeContextfactory.Create( _target, _testPc - 1, _testName, _mockDocumentContext, Guid.Empty) }, 1, out uint matchIndex)); Assert.AreEqual(0, matchIndex); } [Test] public void CompareGreaterThanOrEqual() { Assert.AreEqual(VSConstants.S_OK, _codeContext.Compare( enum_CONTEXT_COMPARE.CONTEXT_GREATER_THAN_OR_EQUAL, new IDebugMemoryContext2[1] { _codeContext }, 1, out uint matchIndex)); Assert.AreEqual(0, matchIndex); } [Test] public void CompareLessThan() { Assert.AreEqual(VSConstants.S_OK, _codeContext.Compare( enum_CONTEXT_COMPARE.CONTEXT_LESS_THAN, new IDebugMemoryContext2[1] { _codeContextfactory.Create( _target, _testPc + 1, _testName, _mockDocumentContext, Guid.Empty) }, 1, out uint matchIndex)); Assert.AreEqual(0, matchIndex); } [Test] public void CompareLessThanOrEqual() { Assert.AreEqual(VSConstants.S_OK, _codeContext.Compare( enum_CONTEXT_COMPARE.CONTEXT_LESS_THAN_OR_EQUAL, new IDebugMemoryContext2[1] { _codeContext }, 1, out uint matchIndex)); Assert.AreEqual(0, matchIndex); } [Test] public void CompareSameFunction() { Assert.AreEqual(VSConstants.S_OK, _codeContext.Compare( enum_CONTEXT_COMPARE.CONTEXT_SAME_FUNCTION, new IDebugMemoryContext2[1] { _codeContext }, 1, out uint matchIndex)); Assert.AreEqual(0, matchIndex); } [Test] public void CompareMultiple() { IDebugMemoryContext2[] others = new IDebugMemoryContext2[] { _codeContextfactory.Create( _target, _testPc - 1, _testName, _mockDocumentContext, Guid.Empty), _codeContextfactory.Create( _target, _testPc, _testName, _mockDocumentContext, Guid.Empty), _codeContextfactory.Create( _target, _testPc + 1, _testName, _mockDocumentContext, Guid.Empty) }; uint matchIndex; Assert.AreEqual(VSConstants.S_OK, _codeContext.Compare( enum_CONTEXT_COMPARE.CONTEXT_EQUAL, others, 3, out matchIndex)); Assert.AreEqual(1, matchIndex); } [Test] public void CompareEqualWithProxy() { var proxyGenerator = new Castle.DynamicProxy.ProxyGenerator(); var decoratorUtil = new DecoratorUtil(); // Create the factory. var factory = new DebugCodeContext.Factory(); // Decorate the factory with a dummy aspect. var aspect = new YetiCommon.Tests.CastleAspects.TestSupport.CallCountAspect(); var factoryDecorator = decoratorUtil.CreateFactoryDecorator(proxyGenerator, aspect); var factoryWithProxy = factoryDecorator.Decorate(factory); var memoryContextWithProxy = factoryWithProxy.Create( _target, _testPc, _testName, _mockDocumentContext, Guid.Empty); // Check all the combinations of comparing proxied and non-proxied memory context. uint matchIndex; Assert.AreEqual(VSConstants.S_OK, memoryContextWithProxy.Compare( enum_CONTEXT_COMPARE.CONTEXT_EQUAL, new IDebugMemoryContext2[1] { memoryContextWithProxy }, 1, out matchIndex)); Assert.AreEqual(0, matchIndex); Assert.AreEqual(VSConstants.S_OK, _codeContext.Compare( enum_CONTEXT_COMPARE.CONTEXT_EQUAL, new IDebugMemoryContext2[1] { memoryContextWithProxy }, 1, out matchIndex)); Assert.AreEqual(0, matchIndex); Assert.AreEqual(VSConstants.S_OK, memoryContextWithProxy.Compare( enum_CONTEXT_COMPARE.CONTEXT_EQUAL, new IDebugMemoryContext2[1] { _codeContext}, 1, out matchIndex)); Assert.AreEqual(0, matchIndex); } [Test] public void GetAddress() { Assert.AreEqual(_testPc, ((IGgpDebugCodeContext)_codeContext).Address); } [Test] public void GetDocumentContext() { Assert.AreEqual(VSConstants.S_OK, _codeContext.GetDocumentContext( out IDebugDocumentContext2 documentContext)); Assert.AreEqual(_mockDocumentContext, documentContext); } [Test] public void GetDocumentContext_Null() { _codeContext = _codeContextfactory.Create( _target, _testPc, _testName, null, Guid.Empty); Assert.AreEqual(VSConstants.S_FALSE, _codeContext.GetDocumentContext( out IDebugDocumentContext2 documentContext)); Assert.AreEqual(null, documentContext); } [Test] public void GetLanguageInfo() { string language = null; var guid = new Guid(); Assert.AreEqual(VSConstants.S_OK, _codeContext.GetLanguageInfo(ref language, ref guid)); Assert.That(guid, Is.EqualTo(Guid.Empty)); } [TestCase(AD7Constants.CLanguage, "C")] [TestCase(AD7Constants.CppLanguage, "C++")] [TestCase(AD7Constants.CSharpLanguage, "C#")] [TestCase("63A08714-FC37-11D2-904C-00C04FA302A2", "")] [TestCase("00000000-0000-0000-0000-000000000000", "")] public void GetLanguageInfoWhenProvided(string guidAsString, string correspondingLanguage) { var guid = new Guid(guidAsString); IDebugCodeContext2 context = _codeContextfactory.Create( _target, _testPc, _testName, _mockDocumentContext, guid); var outputGuid = Guid.Empty; var outputLanguage = string.Empty; int result = context.GetLanguageInfo(ref outputLanguage, ref outputGuid); Assert.That(result, Is.EqualTo(VSConstants.S_OK)); Assert.That(outputGuid, Is.EqualTo(outputGuid)); Assert.That(outputLanguage, Is.EqualTo(correspondingLanguage)); } } }
using Bridge.Test.NUnit; using System; using System.Globalization; namespace Bridge.ClientTest.Batch3.BridgeIssues { /// <summary> /// The tests here ensures decimal separator character obeys current /// culture between string conversions. /// </summary> [TestFixture(TestNameFormat = "#3934 - {0}")] public class Bridge3934 { /// <summary> /// Calls individual batches for each type to be tested. /// </summary> [Test] public static void TestConvert() { TestFloat(); TestDouble(); TestDecimal(); } /// <summary> /// Tests single precision floating-point conversion with culture set as parameter or as current culture. /// Will trigger a failed assertion if an exception is thrown during either conversion test. /// </summary> public static void TestFloat() { var oldCulture = CultureInfo.CurrentCulture; float back; float input = 7.5f; string str; var convtype = "float"; // WARNING: GetCultures() here is a stub and corresponds to // .NET's GetCultures(CultureTypes.AllCultures) foreach (var culture in CultureInfo.GetCultures()) { var cultureDesc = "\"" + culture.EnglishName + "\" (" + culture.Name + ")"; try { str = input.ToString(culture); back = Convert.ToSingle(str, culture); Assert.AreEqual(input, back, "Decimal separator retained between " + convtype + "-string conversion in specified " + cultureDesc + "."); } catch (Exception exc) { Assert.Fail("Exception thrown while converting between " + convtype + "-string if specified culture is " + cultureDesc + " in conversion calls: " + exc.Message); } try { CultureInfo.CurrentCulture = culture; str = input.ToString(); back = Convert.ToSingle(str); Assert.AreEqual(input, back, "Decimal separator retained between " + convtype + "-string conversion in " + cultureDesc + " when set as current culture."); } catch (Exception exc) { Assert.Fail("Exception thrown while converting between " + convtype + "-string when in conversion call if current culture set to " + cultureDesc + ": " + exc.Message); } finally { CultureInfo.CurrentCulture = oldCulture; } } } /// <summary> /// Tests double precision float-point conversion with culture set as parameter or as current culture. /// Will trigger a failed assertion if an exception is thrown during either conversion test. /// </summary> public static void TestDouble() { var oldCulture = CultureInfo.CurrentCulture; double back; double input = 7.5; string str; var convtype = "double"; // WARNING: GetCultures() here is a stub and corresponds to // .NET's GetCultures(CultureTypes.AllCultures) foreach (var culture in CultureInfo.GetCultures()) { var cultureDesc = "\"" + culture.EnglishName + "\" (" + culture.Name + ")"; try { str = input.ToString(culture); back = Convert.ToDouble(str, culture); Assert.AreEqual(input, back, "Decimal separator retained between " + convtype + "-string conversion in specified " + cultureDesc + "."); } catch (Exception exc) { Assert.Fail("Exception thrown while converting between " + convtype + "-string if specified culture is " + cultureDesc + " in conversion calls: " + exc.Message); } try { CultureInfo.CurrentCulture = culture; str = input.ToString(); back = Convert.ToDouble(str); Assert.AreEqual(input, back, "Decimal separator retained between " + convtype + "-string conversion in " + cultureDesc + " when set as current culture."); } catch (Exception exc) { Assert.Fail("Exception thrown while converting between " + convtype + "-string when in conversion call if current culture set to " + cultureDesc + ": " + exc.Message); } finally { CultureInfo.CurrentCulture = oldCulture; } } } /// <summary> /// Tests decimal conversion with culture set as parameter or as current culture. /// Will trigger a failed assertion if an exception is thrown during either conversion test. /// </summary> public static void TestDecimal() { var oldCulture = CultureInfo.CurrentCulture; decimal back; decimal input = 7.5m; string str; var convtype = "decimal"; // WARNING: GetCultures() here is a stub and corresponds to // .NET's GetCultures(CultureTypes.AllCultures) foreach (var culture in CultureInfo.GetCultures()) { var cultureDesc = "\"" + culture.EnglishName + "\" (" + culture.Name + ")"; try { str = input.ToString(culture); back = Convert.ToDecimal(str, culture); Assert.AreEqual(input, back, "Decimal separator retained between " + convtype + "-string conversion in specified " + cultureDesc + "."); } catch (Exception exc) { Assert.Fail("Exception thrown while converting between " + convtype + "-string if specified culture is " + cultureDesc + " in conversion calls: " + exc.Message); } try { CultureInfo.CurrentCulture = culture; str = input.ToString(); back = Convert.ToDecimal(str); Assert.AreEqual(input, back, "Decimal separator retained between " + convtype + "-string conversion in " + cultureDesc + " when set as current culture."); } catch (Exception exc) { Assert.Fail("Exception thrown while converting between " + convtype + "-string when in conversion call if current culture set to " + cultureDesc + ": " + exc.Message); } finally { CultureInfo.CurrentCulture = oldCulture; } } } } }
/* * 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 IndexReader = Lucene.Net.Index.IndexReader; using Query = Lucene.Net.Search.Query; using ToStringUtils = Lucene.Net.Util.ToStringUtils; using System.Collections.Generic; namespace Lucene.Net.Search.Spans { /// <summary>Matches spans near the beginning of a field. </summary> [System.Serializable] public class SpanFirstQuery : SpanQuery { private SpanQuery match; private int end; /// <summary>Construct a SpanFirstQuery matching spans in <code>match</code> whose end /// position is less than or equal to <code>end</code>. /// </summary> public SpanFirstQuery(SpanQuery match, int end) { this.match = match; this.end = end; } /// <summary>Return the SpanQuery whose matches are filtered. </summary> public virtual SpanQuery GetMatch() { return match; } /// <summary>Return the maximum end position permitted in a match. </summary> public virtual int GetEnd() { return end; } public override System.String GetField() { return match.GetField(); } /// <summary>Returns a collection of all terms matched by this query.</summary> /// <deprecated> use extractTerms instead /// </deprecated> /// <seealso cref="#ExtractTerms(Set)"> /// </seealso> public override System.Collections.ICollection GetTerms() { return match.GetTerms(); } public override System.String ToString(System.String field) { System.Text.StringBuilder buffer = new System.Text.StringBuilder(); buffer.Append("spanFirst("); buffer.Append(match.ToString(field)); buffer.Append(", "); buffer.Append(end); buffer.Append(")"); buffer.Append(ToStringUtils.Boost(GetBoost())); return buffer.ToString(); } public override void ExtractTerms(System.Collections.Hashtable terms) { match.ExtractTerms(terms); } public override PayloadSpans GetPayloadSpans(IndexReader reader) { return (PayloadSpans)GetSpans(reader); } public override Spans GetSpans(IndexReader reader) { return new AnonymousClassPayloadSpans(reader, this); } private class AnonymousClassPayloadSpans : PayloadSpans { private PayloadSpans spans; private Lucene.Net.Index.IndexReader reader; private SpanFirstQuery enclosingInstance; private void InitBlock(Lucene.Net.Index.IndexReader reader, SpanFirstQuery enclosingInstance) { this.reader = reader; this.enclosingInstance = enclosingInstance; spans = Enclosing_Instance.match.GetPayloadSpans(reader); } public AnonymousClassPayloadSpans(Lucene.Net.Index.IndexReader reader, SpanFirstQuery enclosingInstance) { InitBlock(reader, enclosingInstance); } public SpanFirstQuery Enclosing_Instance { get { return enclosingInstance; } } public virtual bool Next() { while (spans.Next()) { // scan to next match if (End() <= Enclosing_Instance.end) return true; } return false; } public virtual bool SkipTo(int target) { if (!spans.SkipTo(target)) return false; return (spans.End() <= Enclosing_Instance.end) || Next(); } public virtual int Doc() { return spans.Doc(); } public virtual int Start() { return spans.Start(); } public virtual int End() { return spans.End(); } public ICollection<byte[]> GetPayload() { List<byte[]> result = null; if (spans.IsPayloadAvailable()) result = new List<byte[]>(spans.GetPayload()); return result; } public bool IsPayloadAvailable() { return spans.IsPayloadAvailable(); } public override System.String ToString() { return "spans(" + Enclosing_Instance.ToString() + ")"; } } public override Query Rewrite(IndexReader reader) { SpanFirstQuery clone = null; SpanQuery rewritten = (SpanQuery) match.Rewrite(reader); if (rewritten != match) { clone = (SpanFirstQuery) this.Clone(); clone.match = rewritten; } if (clone != null) { return clone; // some clauses rewrote } else { return this; // no clauses rewrote } } public override bool Equals(object o) { if (this == o) return true; if (!(o is SpanFirstQuery)) return false; SpanFirstQuery other = (SpanFirstQuery) o; return this.end == other.end && this.match.Equals(other.match) && this.GetBoost() == other.GetBoost(); } public override int GetHashCode() { int h = match.GetHashCode(); h ^= ((h << 8) | ((int) (((uint) h) >> 25))); // reversible h ^= System.Convert.ToInt32(GetBoost()) ^ end; return h; } } }
// // 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.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure; using Microsoft.Azure.Management.Sql; using Microsoft.Azure.Management.Sql.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Sql { /// <summary> /// Represents all the operations for Azure SQL Database Server Upgrade /// </summary> internal partial class ServerUpgradeOperations : IServiceOperations<SqlManagementClient>, IServerUpgradeOperations { /// <summary> /// Initializes a new instance of the ServerUpgradeOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ServerUpgradeOperations(SqlManagementClient client) { this._client = client; } private SqlManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Sql.SqlManagementClient. /// </summary> public SqlManagementClient Client { get { return this._client; } } /// <summary> /// Cancel a pending upgrade for the Azure SQL Database server. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server to cancel /// upgrade. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> CancelAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); TracingAdapter.Enter(invocationId, this, "CancelAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/operationResults/versionUpgrade"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } 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.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Returns information about Upgrade status of an Azure SQL Database /// Server. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server to upgrade. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a Get request for Upgrade status of an /// Azure SQL Database Server. /// </returns> public async Task<ServerUpgradeGetResponse> GetAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/operationResults/versionUpgrade"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } 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.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServerUpgradeGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServerUpgradeGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken statusValue = responseDoc["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); result.Status = statusInstance; } JToken scheduleUpgradeAfterTimeValue = responseDoc["scheduleUpgradeAfterTime"]; if (scheduleUpgradeAfterTimeValue != null && scheduleUpgradeAfterTimeValue.Type != JTokenType.Null) { DateTime scheduleUpgradeAfterTimeInstance = ((DateTime)scheduleUpgradeAfterTimeValue); result.ScheduleUpgradeAfterTime = scheduleUpgradeAfterTimeInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Start an Azure SQL Database Server Upgrade. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server to upgrade. /// </param> /// <param name='parameters'> /// Required. The required parameters for the Azure SQL Database Server /// Upgrade. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> StartAsync(string resourceGroupName, string serverName, ServerUpgradeStartParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } if (parameters.Properties.Version == null) { throw new ArgumentNullException("parameters.Properties.Version"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "StartAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/upgrade"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } 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 // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject serverUpgradeStartParametersValue = new JObject(); requestDoc = serverUpgradeStartParametersValue; JObject serverUpgradePropertiesValue = new JObject(); serverUpgradeStartParametersValue["serverUpgradeProperties"] = serverUpgradePropertiesValue; serverUpgradePropertiesValue["Version"] = parameters.Properties.Version; if (parameters.Properties.ScheduleUpgradeAfterUtcDateTime != null) { serverUpgradePropertiesValue["ScheduleUpgradeAfterUtcDateTime"] = parameters.Properties.ScheduleUpgradeAfterUtcDateTime.Value; } if (parameters.Properties.DatabaseCollection != null) { if (parameters.Properties.DatabaseCollection is ILazyCollection == false || ((ILazyCollection)parameters.Properties.DatabaseCollection).IsInitialized) { JArray databaseCollectionArray = new JArray(); foreach (RecommendedDatabaseProperties databaseCollectionItem in parameters.Properties.DatabaseCollection) { JObject recommendedDatabasePropertiesValue = new JObject(); databaseCollectionArray.Add(recommendedDatabasePropertiesValue); if (databaseCollectionItem.Name != null) { recommendedDatabasePropertiesValue["Name"] = databaseCollectionItem.Name; } if (databaseCollectionItem.TargetEdition != null) { recommendedDatabasePropertiesValue["TargetEdition"] = databaseCollectionItem.TargetEdition; } if (databaseCollectionItem.TargetServiceLevelObjective != null) { recommendedDatabasePropertiesValue["TargetServiceLevelObjective"] = databaseCollectionItem.TargetServiceLevelObjective; } } serverUpgradePropertiesValue["DatabaseCollection"] = databaseCollectionArray; } } if (parameters.Properties.ElasticPoolCollection != null) { if (parameters.Properties.ElasticPoolCollection is ILazyCollection == false || ((ILazyCollection)parameters.Properties.ElasticPoolCollection).IsInitialized) { JArray elasticPoolCollectionArray = new JArray(); foreach (UpgradeRecommendedElasticPoolProperties elasticPoolCollectionItem in parameters.Properties.ElasticPoolCollection) { JObject upgradeRecommendedElasticPoolPropertiesValue = new JObject(); elasticPoolCollectionArray.Add(upgradeRecommendedElasticPoolPropertiesValue); if (elasticPoolCollectionItem.Name != null) { upgradeRecommendedElasticPoolPropertiesValue["Name"] = elasticPoolCollectionItem.Name; } if (elasticPoolCollectionItem.Edition != null) { upgradeRecommendedElasticPoolPropertiesValue["Edition"] = elasticPoolCollectionItem.Edition; } upgradeRecommendedElasticPoolPropertiesValue["Dtu"] = elasticPoolCollectionItem.Dtu; upgradeRecommendedElasticPoolPropertiesValue["StorageMb"] = elasticPoolCollectionItem.StorageMb; upgradeRecommendedElasticPoolPropertiesValue["DatabaseDtuMin"] = elasticPoolCollectionItem.DatabaseDtuMin; upgradeRecommendedElasticPoolPropertiesValue["DatabaseDtuMax"] = elasticPoolCollectionItem.DatabaseDtuMax; if (elasticPoolCollectionItem.DatabaseCollection != null) { if (elasticPoolCollectionItem.DatabaseCollection is ILazyCollection == false || ((ILazyCollection)elasticPoolCollectionItem.DatabaseCollection).IsInitialized) { JArray databaseCollectionArray2 = new JArray(); foreach (string databaseCollectionItem2 in elasticPoolCollectionItem.DatabaseCollection) { databaseCollectionArray2.Add(databaseCollectionItem2); } upgradeRecommendedElasticPoolPropertiesValue["DatabaseCollection"] = databaseCollectionArray2; } } if (elasticPoolCollectionItem.IncludeAllDatabases != null) { upgradeRecommendedElasticPoolPropertiesValue["IncludeAllDatabases"] = elasticPoolCollectionItem.IncludeAllDatabases.Value; } } serverUpgradePropertiesValue["ElasticPoolCollection"] = elasticPoolCollectionArray; } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
/****************************************************************************** * The MIT License * Copyright (c) 2007 Novell Inc., www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // Authors: // Thomas Wiest (twiest@novell.com) // Rusty Howell (rhowell@novell.com) // // (C) Novell Inc. using System; using System.Collections.Generic; using System.Text; namespace System.Management.Internal { /// <summary> /// The KeyBinding defines a single key property value binding. /// </summary> internal class CimKeyBinding : IComparable { /* <!ELEMENT KEYBINDING (KEYVALUE|VALUE.REFERENCE)> * <!ATTLIST KEYBINDING * %CIMName;> * * <KEYBINDING NAME="CreationClassName"> * <KEYVALUE VALUETYPE="string">OMC_UnitaryComputerSystem</KEYVALUE> * </KEYBINDING> * */ #region Members public enum RefType { KeyValue, ValueReference }; private CimName _name = null; private object _value = null; RefType _type; #endregion #region Constructors public CimKeyBinding(CimName name) { Name = name; } public CimKeyBinding(CimName name, CimKeyValue keyValue) : this(name) { Value = keyValue; } public CimKeyBinding(CimName name, CimValueReference reference) : this(name) { Value = reference; } #endregion #region Properties and Indexers /// <summary> /// Gets or sets the name of the KeyBinding /// </summary> public CimName Name { get { if (_name == null) _name = new CimName(null); return _name; } set { _name = value; } } /// <summary> /// Gets or sets the KeyValue /// </summary> public object Value { get { return _value; } set { _value = value; if (_value is CimKeyValue) { _type = RefType.KeyValue; } else if (_value is CimValueReference) { _type = RefType.ValueReference; } else { throw new Exception("Invalid type for KeyBinding"); } } } /// <summary> /// Gets the Type of the value /// </summary> public RefType Type { get { return _type; } } public bool IsSet { get { return (Value == null); } } #endregion #region Methods and Operators public bool ShallowCompare(CimKeyBinding keybinding) { return (this.Name == keybinding.Name); } #region Equals, operator== , operator!= /// <summary> /// Compares two CimKeyBinding objects /// </summary> /// <param name="obj"></param> /// <returns>Returns true if equals</returns> public override bool Equals(object obj) { if ((obj == null) || !(obj is CimKeyBinding)) { return false; } return (this == (CimKeyBinding)obj); } /// <summary> /// Compares two CimKeyBinding objects /// </summary> /// <param name="val1"></param> /// <param name="val2"></param> /// <returns>Returns true if they are equal</returns> public static bool operator ==(CimKeyBinding val1, CimKeyBinding val2) { //Add code here if (((object)val1 == null) || ((object)val2 == null)) { if (((object)val1 == null) && ((object)val2 == null)) { return true; } return false; } if (val1.Type != val2.Type) { return false; } if (val1.Type == RefType.KeyValue) { return ((CimKeyValue)val1.Value).Equals(val2.Value); // this should call the overriden method in the class } else { return ((CimValueReference)val1.Value).Equals(val2.Value); } } public static bool operator !=(CimKeyBinding val1, CimKeyBinding val2) { return !(val1 == val2); } public override string ToString() { string str = string.Empty; switch (Type) { case RefType.KeyValue: str = ((CimKeyValue)Value).Value; break; case RefType.ValueReference: str = ((CimValueReference)Value).ToString(); break; default: throw new Exception("Invalid type for KeyBinding"); } return str; } #endregion #endregion #region IComparable Members /// <summary> /// Sortable by CimName Name member /// </summary> /// <param name="obj"></param> /// <returns></returns> public int CompareTo(object obj) { return this.Name.CompareTo(((CimKeyBinding)obj).Name); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests.LegacyTests { public class ToLookupTests { // Class which is passed as an argument for EqualityComparer public class AnagramEqualityComparer : IEqualityComparer<string> { public bool Equals(string x, string y) { if ((x == null) && (y == null)) return true; if ((x == null) || (y == null)) return false; return getCanonicalString(x) == getCanonicalString(y); } public int GetHashCode(string obj) { return getCanonicalString(obj).GetHashCode(); } private string getCanonicalString(string word) { char[] wordChars = word.ToCharArray(); Array.Sort<char>(wordChars); return new string(wordChars); } } private struct Record { public string Name; public int Score; } public class Helper { // The following helper verification function will be used when the PLINQ team runs these tests // This is a non-order preserving verification function #if PLINQ public static int MatchAll<K, T>(IEnumerable<K> key, IEnumerable<T> element, System.Linq.ILookup<K, T> lookup) { int num = 0; if ((lookup == null) &&(key == null) &&(element == null)) return 0; if ((lookup == null) || (key == null && element == null)) { Console.WriteLine("expected key : {0}", key == null ? "null" : key.Count().ToString()); Console.WriteLine("expected element : {0}", element == null ? "null" : element.Count().ToString()); Console.WriteLine("actual lookup: {0}", lookup == null ? "null" : lookup.Count().ToString()); return 1; } try { List<T> expectedResults = new List<T>(element); using (IEnumerator<K> k1 = key.GetEnumerator()) using (IEnumerator<T> e1 = element.GetEnumerator()) { while (k1.MoveNext()) { if (!lookup.Contains(k1.Current)) return 1; foreach (T e in lookup[k1.Current]) { if (!expectedResults.Contains(e)) return 1; expectedResults.Remove(e); } num = num + 1; } } if (expectedResults.Count != 0) return 1; if (lookup.Count != num) return 1; return 0; } catch(AggregateException ae) { var innerExceptions = ae.Flatten().InnerExceptions; if (innerExceptions.Where(ex => ex != null).Select(ex => ex.GetType()).Distinct().Count() == 1) { throw innerExceptions.First(); } else { Console.WriteLine(ae); } return 1; } } #else // Helper function to verify that all elements in dictionary are matched (Order Preserving) public static int MatchAll<K, T>(IEnumerable<K> key, IEnumerable<T> element, System.Linq.ILookup<K, T> lookup) { int num = 0; if ((lookup == null) && (key == null) && (element == null)) return 0; using (IEnumerator<K> k1 = key.GetEnumerator()) using (IEnumerator<T> e1 = element.GetEnumerator()) { while (k1.MoveNext()) { if (!lookup.Contains(k1.Current)) return 1; foreach (T e in lookup[k1.Current]) { e1.MoveNext(); if (!Equals(e, e1.Current)) return 1; } num = num + 1; } } if (lookup.Count != num) return 1; return 0; } #endif } public class ToLookup006 { private static int ToLookup001() { var q1 = from x1 in new string[] { "Alen", "Felix", null, null, "X", "Have Space", "Clinton", "" } select x1; ; var q2 = from x2 in new int[] { 55, 49, 9, -100, 24, 25, -1, 0 } select x2; var q = from x3 in q1 from x4 in q2 select new { a1 = x3, a2 = x4 }; var rst1 = q.ToLookup((e) => e.a1); var rst2 = q.ToLookup((e) => e.a1); return ((null == rst2) ? 1 : 0); // return Helper.MatchAll(q1, q2, q); // return Verification.Allequal(rst1, rst2); } public static int Main() { int ret = RunTest(ToLookup001); if (0 != ret) Console.Write(s_errorMessage); return ret; } private static string s_errorMessage = String.Empty; private delegate int D(); private static int RunTest(D m) { int n = m(); if (0 != n) s_errorMessage += m.ToString() + " - FAILED!\r\n"; return n; } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class ToLookup1 { // Overload-1: keySelector returns null. public static int Test1() { string[] key = { "Chris", "Bob", null, "Tim" }; int[] element = { 50, 95, 55, 90 }; Record[] source = new Record[4]; source[0].Name = key[0]; source[0].Score = element[0]; source[1].Name = key[1]; source[1].Score = element[1]; source[2].Name = key[2]; source[2].Score = element[2]; source[3].Name = key[3]; source[3].Score = element[3]; var result = source.ToLookup((e) => e.Name); return Helper.MatchAll(key, source, result); } public static int Main() { return Test1(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class ToLookup2 { // Overload-2: Only one element is present and given Comparer is used. public static int Test2() { string[] key = { "Chris" }; int[] element = { 50 }; Record[] source = new Record[1]; // key is an anagram of Chris source[0].Name = "risCh"; source[0].Score = element[0]; var result = source.ToLookup((e) => e.Name, new AnagramEqualityComparer()); return Helper.MatchAll(key, source, result); } public static int Main() { return Test2(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class ToLookup3 { // Overload-3: All elements are unique and elementSelector function is called. public static int Test3() { string[] key = { "Chris", "Prakash", "Tim", "Robert", "Brian" }; int[] element = { 50, 100, 95, 60, 80 }; Record[] source = new Record[5]; source[0].Name = key[0]; source[0].Score = element[0]; source[1].Name = key[1]; source[1].Score = element[1]; source[2].Name = key[2]; source[2].Score = element[2]; source[3].Name = key[3]; source[3].Score = element[3]; source[4].Name = key[4]; source[4].Score = element[4]; var result = source.ToLookup((e) => e.Name, (e) => e.Score); return Helper.MatchAll(key, element, result); } public static int Main() { return Test3(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class ToLookup4 { // Overload-4: keySelector has duplicate values public static int Test4() { string[] key = { "Chris", "Prakash", "Robert" }; int[] element = { 50, 80, 100, 95, 99, 56 }; Record[] source = new Record[6]; source[0].Name = key[0]; source[0].Score = element[0]; source[1].Name = key[1]; source[1].Score = element[2]; source[2].Name = key[2]; source[2].Score = element[5]; source[3].Name = key[1]; source[3].Score = element[3]; source[4].Name = key[0]; source[4].Score = element[1]; source[5].Name = key[1]; source[5].Score = element[4]; System.Linq.ILookup<string, int> result = source.ToLookup((e) => e.Name, (e) => e.Score, new AnagramEqualityComparer()); return Helper.MatchAll(key, element, result); } public static int Main() { return Test4(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class ToLookup5 { //Overload-4: source is empty public static int Test5() { string[] key = { }; int[] element = { }; Record[] source = new Record[] { }; System.Linq.ILookup<string, int> result = source.ToLookup((e) => e.Name, (e) => e.Score, new AnagramEqualityComparer()); return Helper.MatchAll(key, element, result); } public static int Main() { return Test5(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class ToLookup7 { // DDB:171937 public static int Test7() { string[] key = { null }; string[] element = { null }; string[] source = new string[] { null }; System.Linq.ILookup<string, string> result = source.ToLookup((e) => e, (e) => e, EqualityComparer<string>.Default); return Helper.MatchAll(key, element, result); } public static int Main() { return Test7(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } } }
// // 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; using Microsoft.Azure.Management.DataLake.Store; using Microsoft.Azure.Management.DataLake.Store.Models; namespace Microsoft.Azure.Management.DataLake.Store { /// <summary> /// Creates a Data Lake Store account management client. /// </summary> public static partial class DataLakeStoreAccountOperationsExtensions { /// <summary> /// Creates the specified Data Lake Store account. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group the account will be /// associated with. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create Data Lake Store account /// operation. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public static AzureAsyncOperationResponse BeginCreate(this IDataLakeStoreAccountOperations operations, string resourceGroupName, DataLakeStoreAccountCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IDataLakeStoreAccountOperations)s).BeginCreateAsync(resourceGroupName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates the specified Data Lake Store account. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group the account will be /// associated with. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create Data Lake Store account /// operation. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public static Task<AzureAsyncOperationResponse> BeginCreateAsync(this IDataLakeStoreAccountOperations operations, string resourceGroupName, DataLakeStoreAccountCreateOrUpdateParameters parameters) { return operations.BeginCreateAsync(resourceGroupName, parameters, CancellationToken.None); } /// <summary> /// Deletes the Data Lake Store account object specified by the account /// name. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='accountName'> /// Required. The name of the account to delete /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public static AzureAsyncOperationResponse BeginDelete(this IDataLakeStoreAccountOperations operations, string resourceGroupName, string accountName) { return Task.Factory.StartNew((object s) => { return ((IDataLakeStoreAccountOperations)s).BeginDeleteAsync(resourceGroupName, accountName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes the Data Lake Store account object specified by the account /// name. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='accountName'> /// Required. The name of the account to delete /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public static Task<AzureAsyncOperationResponse> BeginDeleteAsync(this IDataLakeStoreAccountOperations operations, string resourceGroupName, string accountName) { return operations.BeginDeleteAsync(resourceGroupName, accountName, CancellationToken.None); } /// <summary> /// Updates the Data Lake Store account object specified by the account /// name with the contents of the account object. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the update Data Lake Store account /// operation. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public static AzureAsyncOperationResponse BeginUpdate(this IDataLakeStoreAccountOperations operations, string resourceGroupName, DataLakeStoreAccountCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IDataLakeStoreAccountOperations)s).BeginUpdateAsync(resourceGroupName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates the Data Lake Store account object specified by the account /// name with the contents of the account object. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the update Data Lake Store account /// operation. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public static Task<AzureAsyncOperationResponse> BeginUpdateAsync(this IDataLakeStoreAccountOperations operations, string resourceGroupName, DataLakeStoreAccountCreateOrUpdateParameters parameters) { return operations.BeginUpdateAsync(resourceGroupName, parameters, CancellationToken.None); } /// <summary> /// Creates the specified Data Lake Store account. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create Data Lake Store account /// operation. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public static AzureAsyncOperationResponse Create(this IDataLakeStoreAccountOperations operations, string resourceGroupName, DataLakeStoreAccountCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IDataLakeStoreAccountOperations)s).CreateAsync(resourceGroupName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates the specified Data Lake Store account. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create Data Lake Store account /// operation. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public static Task<AzureAsyncOperationResponse> CreateAsync(this IDataLakeStoreAccountOperations operations, string resourceGroupName, DataLakeStoreAccountCreateOrUpdateParameters parameters) { return operations.CreateAsync(resourceGroupName, parameters, CancellationToken.None); } /// <summary> /// Creates or updates the specified Data Lake Store account with the /// specified firewall rules. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group the account is in. /// </param> /// <param name='accountName'> /// Required. The name of the account to add the firewall rule to /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create firewall rule operation. /// </param> /// <returns> /// Data Lake Store account Firewall rule information response. /// </returns> public static DataLakeStoreFirewallRuleCreateUpdateOrGetResponse CreateOrUpdateFirewallRule(this IDataLakeStoreAccountOperations operations, string resourceGroupName, string accountName, DataLakeStoreFirewallRuleCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IDataLakeStoreAccountOperations)s).CreateOrUpdateFirewallRuleAsync(resourceGroupName, accountName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates or updates the specified Data Lake Store account with the /// specified firewall rules. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group the account is in. /// </param> /// <param name='accountName'> /// Required. The name of the account to add the firewall rule to /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create firewall rule operation. /// </param> /// <returns> /// Data Lake Store account Firewall rule information response. /// </returns> public static Task<DataLakeStoreFirewallRuleCreateUpdateOrGetResponse> CreateOrUpdateFirewallRuleAsync(this IDataLakeStoreAccountOperations operations, string resourceGroupName, string accountName, DataLakeStoreFirewallRuleCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateFirewallRuleAsync(resourceGroupName, accountName, parameters, CancellationToken.None); } /// <summary> /// Deletes the Data Lake Store account object specified by the account /// name. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='accountName'> /// Required. The name of the account to delete /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public static AzureAsyncOperationResponse Delete(this IDataLakeStoreAccountOperations operations, string resourceGroupName, string accountName) { return Task.Factory.StartNew((object s) => { return ((IDataLakeStoreAccountOperations)s).DeleteAsync(resourceGroupName, accountName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes the Data Lake Store account object specified by the account /// name. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='accountName'> /// Required. The name of the account to delete /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public static Task<AzureAsyncOperationResponse> DeleteAsync(this IDataLakeStoreAccountOperations operations, string resourceGroupName, string accountName) { return operations.DeleteAsync(resourceGroupName, accountName, CancellationToken.None); } /// <summary> /// Deletes the specified firewall rule from the specified Data Lake /// Store account /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='accountName'> /// Required. The name of the account to delete the firewall rule from /// </param> /// <param name='firewallRuleName'> /// Required. The name of the firewall rule to delete /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse DeleteFirewallRule(this IDataLakeStoreAccountOperations operations, string resourceGroupName, string accountName, string firewallRuleName) { return Task.Factory.StartNew((object s) => { return ((IDataLakeStoreAccountOperations)s).DeleteFirewallRuleAsync(resourceGroupName, accountName, firewallRuleName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified firewall rule from the specified Data Lake /// Store account /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='accountName'> /// Required. The name of the account to delete the firewall rule from /// </param> /// <param name='firewallRuleName'> /// Required. The name of the firewall rule to delete /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteFirewallRuleAsync(this IDataLakeStoreAccountOperations operations, string resourceGroupName, string accountName, string firewallRuleName) { return operations.DeleteFirewallRuleAsync(resourceGroupName, accountName, firewallRuleName, CancellationToken.None); } /// <summary> /// Gets the next page of the Data Lake firewall rule objects within /// the specified account, if any. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='nextLink'> /// Required. The url to the next firewall rule page. /// </param> /// <returns> /// Data Lake firewall rule list information. /// </returns> public static DataLakeStoreFirewallRuleListResponse FirewallRulesListNext(this IDataLakeStoreAccountOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IDataLakeStoreAccountOperations)s).FirewallRulesListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the next page of the Data Lake firewall rule objects within /// the specified account, if any. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='nextLink'> /// Required. The url to the next firewall rule page. /// </param> /// <returns> /// Data Lake firewall rule list information. /// </returns> public static Task<DataLakeStoreFirewallRuleListResponse> FirewallRulesListNextAsync(this IDataLakeStoreAccountOperations operations, string nextLink) { return operations.FirewallRulesListNextAsync(nextLink, CancellationToken.None); } /// <summary> /// Gets the Data Lake Store account object specified by the account /// name. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='accountName'> /// Required. The name of the account to retrieve /// </param> /// <returns> /// Data Lake Store account information response. /// </returns> public static DataLakeStoreAccountGetResponse Get(this IDataLakeStoreAccountOperations operations, string resourceGroupName, string accountName) { return Task.Factory.StartNew((object s) => { return ((IDataLakeStoreAccountOperations)s).GetAsync(resourceGroupName, accountName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the Data Lake Store account object specified by the account /// name. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='accountName'> /// Required. The name of the account to retrieve /// </param> /// <returns> /// Data Lake Store account information response. /// </returns> public static Task<DataLakeStoreAccountGetResponse> GetAsync(this IDataLakeStoreAccountOperations operations, string resourceGroupName, string accountName) { return operations.GetAsync(resourceGroupName, accountName, CancellationToken.None); } /// <summary> /// Gets the specified Data Lake firewall rules. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group the account is in. /// </param> /// <param name='accountName'> /// Required. The name of the account to get the firewall rules from /// </param> /// <param name='firewallRuleName'> /// Required. the name of the firewall rule to retrieve. /// </param> /// <returns> /// Data Lake Store account Firewall rule information response. /// </returns> public static DataLakeStoreFirewallRuleCreateUpdateOrGetResponse GetFirewallRule(this IDataLakeStoreAccountOperations operations, string resourceGroupName, string accountName, string firewallRuleName) { return Task.Factory.StartNew((object s) => { return ((IDataLakeStoreAccountOperations)s).GetFirewallRuleAsync(resourceGroupName, accountName, firewallRuleName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the specified Data Lake firewall rules. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group the account is in. /// </param> /// <param name='accountName'> /// Required. The name of the account to get the firewall rules from /// </param> /// <param name='firewallRuleName'> /// Required. the name of the firewall rule to retrieve. /// </param> /// <returns> /// Data Lake Store account Firewall rule information response. /// </returns> public static Task<DataLakeStoreFirewallRuleCreateUpdateOrGetResponse> GetFirewallRuleAsync(this IDataLakeStoreAccountOperations operations, string resourceGroupName, string accountName, string firewallRuleName) { return operations.GetFirewallRuleAsync(resourceGroupName, accountName, firewallRuleName, CancellationToken.None); } /// <summary> /// Lists the Data Lake Store account objects within the subscription /// or within a specific resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Optional. The name of the resource group. /// </param> /// <param name='parameters'> /// Optional. Query parameters. If null is passed returns all Data Lake /// Store account items. /// </param> /// <returns> /// Data Lake Store account list information response. /// </returns> public static DataLakeStoreAccountListResponse List(this IDataLakeStoreAccountOperations operations, string resourceGroupName, DataLakeStoreAccountListParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IDataLakeStoreAccountOperations)s).ListAsync(resourceGroupName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists the Data Lake Store account objects within the subscription /// or within a specific resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Optional. The name of the resource group. /// </param> /// <param name='parameters'> /// Optional. Query parameters. If null is passed returns all Data Lake /// Store account items. /// </param> /// <returns> /// Data Lake Store account list information response. /// </returns> public static Task<DataLakeStoreAccountListResponse> ListAsync(this IDataLakeStoreAccountOperations operations, string resourceGroupName, DataLakeStoreAccountListParameters parameters) { return operations.ListAsync(resourceGroupName, parameters, CancellationToken.None); } /// <summary> /// Lists the Data Lake firewall rules objects within the specified /// Data Lake Store account. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Optional. The name of the resource group. /// </param> /// <param name='accountName'> /// Required. The name of the account to get the firewall rules from /// </param> /// <returns> /// Data Lake firewall rule list information. /// </returns> public static DataLakeStoreFirewallRuleListResponse ListFirewallRules(this IDataLakeStoreAccountOperations operations, string resourceGroupName, string accountName) { return Task.Factory.StartNew((object s) => { return ((IDataLakeStoreAccountOperations)s).ListFirewallRulesAsync(resourceGroupName, accountName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists the Data Lake firewall rules objects within the specified /// Data Lake Store account. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Optional. The name of the resource group. /// </param> /// <param name='accountName'> /// Required. The name of the account to get the firewall rules from /// </param> /// <returns> /// Data Lake firewall rule list information. /// </returns> public static Task<DataLakeStoreFirewallRuleListResponse> ListFirewallRulesAsync(this IDataLakeStoreAccountOperations operations, string resourceGroupName, string accountName) { return operations.ListFirewallRulesAsync(resourceGroupName, accountName, CancellationToken.None); } /// <summary> /// Gets the next page of the Data Lake Store account objects within /// the subscription or within a specific resource group with the link /// to the next page, if any. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='nextLink'> /// Required. The url to the next Data Lake Store account page. /// </param> /// <returns> /// Data Lake Store account list information response. /// </returns> public static DataLakeStoreAccountListResponse ListNext(this IDataLakeStoreAccountOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IDataLakeStoreAccountOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the next page of the Data Lake Store account objects within /// the subscription or within a specific resource group with the link /// to the next page, if any. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='nextLink'> /// Required. The url to the next Data Lake Store account page. /// </param> /// <returns> /// Data Lake Store account list information response. /// </returns> public static Task<DataLakeStoreAccountListResponse> ListNextAsync(this IDataLakeStoreAccountOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } /// <summary> /// Updates the Data Lake Store account object specified by the account /// name with the contents of the account object. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the update Data Lake Store account /// operation. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public static AzureAsyncOperationResponse Update(this IDataLakeStoreAccountOperations operations, string resourceGroupName, DataLakeStoreAccountCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IDataLakeStoreAccountOperations)s).UpdateAsync(resourceGroupName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates the Data Lake Store account object specified by the account /// name with the contents of the account object. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.Store.IDataLakeStoreAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the update Data Lake Store account /// operation. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public static Task<AzureAsyncOperationResponse> UpdateAsync(this IDataLakeStoreAccountOperations operations, string resourceGroupName, DataLakeStoreAccountCreateOrUpdateParameters parameters) { return operations.UpdateAsync(resourceGroupName, 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.Data.Common; using System.Diagnostics; namespace System.Data.SqlClient { internal sealed class SqlConnectionString : DbConnectionOptions { // instances of this class are intended to be immutable, i.e readonly // used by pooling classes so it is much easier to verify correctness // when not worried about the class being modified during execution internal static class DEFAULT { internal const ApplicationIntent ApplicationIntent = DbConnectionStringDefaults.ApplicationIntent; internal const string Application_Name = TdsEnums.SQL_PROVIDER_NAME; internal const string AttachDBFilename = ""; internal const int Connect_Timeout = ADP.DefaultConnectionTimeout; internal const string Current_Language = ""; internal const string Data_Source = ""; internal const bool Encrypt = false; internal const string FailoverPartner = ""; internal const string Initial_Catalog = ""; internal const bool Integrated_Security = false; internal const int Load_Balance_Timeout = 0; // default of 0 means don't use internal const bool MARS = false; internal const int Max_Pool_Size = 100; internal const int Min_Pool_Size = 0; internal const bool MultiSubnetFailover = DbConnectionStringDefaults.MultiSubnetFailover; internal const int Packet_Size = 8000; internal const string Password = ""; internal const bool Persist_Security_Info = false; internal const bool Pooling = true; internal const bool TrustServerCertificate = false; internal const string Type_System_Version = ""; internal const string User_ID = ""; internal const bool User_Instance = false; internal const bool Replication = false; internal const int Connect_Retry_Count = 1; internal const int Connect_Retry_Interval = 10; } // SqlConnection ConnectionString Options // keys must be lowercase! internal static class KEY { internal const string ApplicationIntent = "applicationintent"; internal const string Application_Name = "application name"; internal const string AsynchronousProcessing = "asynchronous processing"; internal const string AttachDBFilename = "attachdbfilename"; internal const string Connect_Timeout = "connect timeout"; internal const string Connection_Reset = "connection reset"; internal const string Context_Connection = "context connection"; internal const string Current_Language = "current language"; internal const string Data_Source = "data source"; internal const string Encrypt = "encrypt"; internal const string Enlist = "enlist"; internal const string FailoverPartner = "failover partner"; internal const string Initial_Catalog = "initial catalog"; internal const string Integrated_Security = "integrated security"; internal const string Load_Balance_Timeout = "load balance timeout"; internal const string MARS = "multipleactiveresultsets"; internal const string Max_Pool_Size = "max pool size"; internal const string Min_Pool_Size = "min pool size"; internal const string MultiSubnetFailover = "multisubnetfailover"; internal const string Network_Library = "network library"; internal const string Packet_Size = "packet size"; internal const string Password = "password"; internal const string Persist_Security_Info = "persist security info"; internal const string Pooling = "pooling"; internal const string TransactionBinding = "transaction binding"; internal const string TrustServerCertificate = "trustservercertificate"; internal const string Type_System_Version = "type system version"; internal const string User_ID = "user id"; internal const string User_Instance = "user instance"; internal const string Workstation_Id = "workstation id"; internal const string Replication = "replication"; internal const string Connect_Retry_Count = "connectretrycount"; internal const string Connect_Retry_Interval = "connectretryinterval"; } // Constant for the number of duplicate options in the connection string private static class SYNONYM { // application name internal const string APP = "app"; internal const string Async = "async"; // attachDBFilename internal const string EXTENDED_PROPERTIES = "extended properties"; internal const string INITIAL_FILE_NAME = "initial file name"; // connect timeout internal const string CONNECTION_TIMEOUT = "connection timeout"; internal const string TIMEOUT = "timeout"; // current language internal const string LANGUAGE = "language"; // data source internal const string ADDR = "addr"; internal const string ADDRESS = "address"; internal const string SERVER = "server"; internal const string NETWORK_ADDRESS = "network address"; // initial catalog internal const string DATABASE = "database"; // integrated security internal const string TRUSTED_CONNECTION = "trusted_connection"; // load balance timeout internal const string Connection_Lifetime = "connection lifetime"; // network library internal const string NET = "net"; internal const string NETWORK = "network"; // password internal const string Pwd = "pwd"; // persist security info internal const string PERSISTSECURITYINFO = "persistsecurityinfo"; // user id internal const string UID = "uid"; internal const string User = "user"; // workstation id internal const string WSID = "wsid"; // make sure to update SynonymCount value below when adding or removing synonyms } internal const int SynonymCount = 18; internal const int DeprecatedSynonymCount = 3; internal enum TypeSystem { Latest = 2008, SQLServer2000 = 2000, SQLServer2005 = 2005, SQLServer2008 = 2008, SQLServer2012 = 2012, } internal static class TYPESYSTEMVERSION { internal const string Latest = "Latest"; internal const string SQL_Server_2000 = "SQL Server 2000"; internal const string SQL_Server_2005 = "SQL Server 2005"; internal const string SQL_Server_2008 = "SQL Server 2008"; internal const string SQL_Server_2012 = "SQL Server 2012"; } static private Hashtable s_sqlClientSynonyms; private readonly bool _integratedSecurity; private readonly bool _encrypt; private readonly bool _trustServerCertificate; private readonly bool _mars; private readonly bool _persistSecurityInfo; private readonly bool _pooling; private readonly bool _replication; private readonly bool _userInstance; private readonly bool _multiSubnetFailover; private readonly int _connectTimeout; private readonly int _loadBalanceTimeout; private readonly int _maxPoolSize; private readonly int _minPoolSize; private readonly int _packetSize; private readonly int _connectRetryCount; private readonly int _connectRetryInterval; private readonly ApplicationIntent _applicationIntent; private readonly string _applicationName; private readonly string _attachDBFileName; private readonly string _currentLanguage; private readonly string _dataSource; private readonly string _localDBInstance; // created based on datasource, set to NULL if datasource is not LocalDB private readonly string _failoverPartner; private readonly string _initialCatalog; private readonly string _password; private readonly string _userID; private readonly string _workstationId; private readonly TypeSystem _typeSystemVersion; internal SqlConnectionString(string connectionString) : base(connectionString, GetParseSynonyms()) { ThrowUnsupportedIfKeywordSet(KEY.AsynchronousProcessing); ThrowUnsupportedIfKeywordSet(KEY.Connection_Reset); ThrowUnsupportedIfKeywordSet(KEY.Context_Connection); ThrowUnsupportedIfKeywordSet(KEY.Enlist); ThrowUnsupportedIfKeywordSet(KEY.TransactionBinding); // Network Library has its own special error message if (ContainsKey(KEY.Network_Library)) { throw SQL.NetworkLibraryKeywordNotSupported(); } _integratedSecurity = ConvertValueToIntegratedSecurity(); #if MANAGED_SNI if(_integratedSecurity) { throw SQL.UnsupportedKeyword(KEY.Integrated_Security); } #endif _encrypt = ConvertValueToBoolean(KEY.Encrypt, DEFAULT.Encrypt); _mars = ConvertValueToBoolean(KEY.MARS, DEFAULT.MARS); _persistSecurityInfo = ConvertValueToBoolean(KEY.Persist_Security_Info, DEFAULT.Persist_Security_Info); _pooling = ConvertValueToBoolean(KEY.Pooling, DEFAULT.Pooling); _replication = ConvertValueToBoolean(KEY.Replication, DEFAULT.Replication); _userInstance = ConvertValueToBoolean(KEY.User_Instance, DEFAULT.User_Instance); _multiSubnetFailover = ConvertValueToBoolean(KEY.MultiSubnetFailover, DEFAULT.MultiSubnetFailover); _connectTimeout = ConvertValueToInt32(KEY.Connect_Timeout, DEFAULT.Connect_Timeout); _loadBalanceTimeout = ConvertValueToInt32(KEY.Load_Balance_Timeout, DEFAULT.Load_Balance_Timeout); _maxPoolSize = ConvertValueToInt32(KEY.Max_Pool_Size, DEFAULT.Max_Pool_Size); _minPoolSize = ConvertValueToInt32(KEY.Min_Pool_Size, DEFAULT.Min_Pool_Size); _packetSize = ConvertValueToInt32(KEY.Packet_Size, DEFAULT.Packet_Size); _connectRetryCount = ConvertValueToInt32(KEY.Connect_Retry_Count, DEFAULT.Connect_Retry_Count); _connectRetryInterval = ConvertValueToInt32(KEY.Connect_Retry_Interval, DEFAULT.Connect_Retry_Interval); _applicationIntent = ConvertValueToApplicationIntent(); _applicationName = ConvertValueToString(KEY.Application_Name, DEFAULT.Application_Name); _attachDBFileName = ConvertValueToString(KEY.AttachDBFilename, DEFAULT.AttachDBFilename); _currentLanguage = ConvertValueToString(KEY.Current_Language, DEFAULT.Current_Language); _dataSource = ConvertValueToString(KEY.Data_Source, DEFAULT.Data_Source); _localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource); _failoverPartner = ConvertValueToString(KEY.FailoverPartner, DEFAULT.FailoverPartner); _initialCatalog = ConvertValueToString(KEY.Initial_Catalog, DEFAULT.Initial_Catalog); _password = ConvertValueToString(KEY.Password, DEFAULT.Password); _trustServerCertificate = ConvertValueToBoolean(KEY.TrustServerCertificate, DEFAULT.TrustServerCertificate); // Temporary string - this value is stored internally as an enum. string typeSystemVersionString = ConvertValueToString(KEY.Type_System_Version, null); _userID = ConvertValueToString(KEY.User_ID, DEFAULT.User_ID); _workstationId = ConvertValueToString(KEY.Workstation_Id, null); if (_loadBalanceTimeout < 0) { throw ADP.InvalidConnectionOptionValue(KEY.Load_Balance_Timeout); } if (_connectTimeout < 0) { throw ADP.InvalidConnectionOptionValue(KEY.Connect_Timeout); } if (_maxPoolSize < 1) { throw ADP.InvalidConnectionOptionValue(KEY.Max_Pool_Size); } if (_minPoolSize < 0) { throw ADP.InvalidConnectionOptionValue(KEY.Min_Pool_Size); } if (_maxPoolSize < _minPoolSize) { throw ADP.InvalidMinMaxPoolSizeValues(); } if ((_packetSize < TdsEnums.MIN_PACKET_SIZE) || (TdsEnums.MAX_PACKET_SIZE < _packetSize)) { throw SQL.InvalidPacketSizeValue(); } ValidateValueLength(_applicationName, TdsEnums.MAXLEN_APPNAME, KEY.Application_Name); ValidateValueLength(_currentLanguage, TdsEnums.MAXLEN_LANGUAGE, KEY.Current_Language); ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source); ValidateValueLength(_failoverPartner, TdsEnums.MAXLEN_SERVERNAME, KEY.FailoverPartner); ValidateValueLength(_initialCatalog, TdsEnums.MAXLEN_DATABASE, KEY.Initial_Catalog); ValidateValueLength(_password, TdsEnums.MAXLEN_PASSWORD, KEY.Password); ValidateValueLength(_userID, TdsEnums.MAXLEN_USERNAME, KEY.User_ID); if (null != _workstationId) { ValidateValueLength(_workstationId, TdsEnums.MAXLEN_HOSTNAME, KEY.Workstation_Id); } if (!String.Equals(DEFAULT.FailoverPartner, _failoverPartner, StringComparison.OrdinalIgnoreCase)) { // fail-over partner is set if (_multiSubnetFailover) { throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner: false, internalConnection: null); } if (String.Equals(DEFAULT.Initial_Catalog, _initialCatalog, StringComparison.OrdinalIgnoreCase)) { throw ADP.MissingConnectionOptionValue(KEY.FailoverPartner, KEY.Initial_Catalog); } } if (0 <= _attachDBFileName.IndexOf('|')) { throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename); } else { ValidateValueLength(_attachDBFileName, TdsEnums.MAXLEN_ATTACHDBFILE, KEY.AttachDBFilename); } if (true == _userInstance && !string.IsNullOrEmpty(_failoverPartner)) { throw SQL.UserInstanceFailoverNotCompatible(); } if (string.IsNullOrEmpty(typeSystemVersionString)) { typeSystemVersionString = DbConnectionStringDefaults.TypeSystemVersion; } if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.Latest, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.Latest; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2000, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2000; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2005, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2005; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2008, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2008; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2012, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2012; } else { throw ADP.InvalidConnectionOptionValue(KEY.Type_System_Version); } if (_applicationIntent == ApplicationIntent.ReadOnly && !String.IsNullOrEmpty(_failoverPartner)) throw SQL.ROR_FailoverNotSupportedConnString(); if ((_connectRetryCount < 0) || (_connectRetryCount > 255)) { throw ADP.InvalidConnectRetryCountValue(); } if ((_connectRetryInterval < 1) || (_connectRetryInterval > 60)) { throw ADP.InvalidConnectRetryIntervalValue(); } } // This c-tor is used to create SSE and user instance connection strings when user instance is set to true // BUG (VSTFDevDiv) 479687: Using TransactionScope with Linq2SQL against user instances fails with "connection has been broken" message internal SqlConnectionString(SqlConnectionString connectionOptions, string dataSource, bool userInstance) : base(connectionOptions) { _integratedSecurity = connectionOptions._integratedSecurity; _encrypt = connectionOptions._encrypt; _mars = connectionOptions._mars; _persistSecurityInfo = connectionOptions._persistSecurityInfo; _pooling = connectionOptions._pooling; _replication = connectionOptions._replication; _userInstance = userInstance; _connectTimeout = connectionOptions._connectTimeout; _loadBalanceTimeout = connectionOptions._loadBalanceTimeout; _maxPoolSize = connectionOptions._maxPoolSize; _minPoolSize = connectionOptions._minPoolSize; _multiSubnetFailover = connectionOptions._multiSubnetFailover; _packetSize = connectionOptions._packetSize; _applicationName = connectionOptions._applicationName; _attachDBFileName = connectionOptions._attachDBFileName; _currentLanguage = connectionOptions._currentLanguage; _dataSource = dataSource; _localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource); _failoverPartner = connectionOptions._failoverPartner; _initialCatalog = connectionOptions._initialCatalog; _password = connectionOptions._password; _userID = connectionOptions._userID; _workstationId = connectionOptions._workstationId; _typeSystemVersion = connectionOptions._typeSystemVersion; _applicationIntent = connectionOptions._applicationIntent; _connectRetryCount = connectionOptions._connectRetryCount; _connectRetryInterval = connectionOptions._connectRetryInterval; ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source); } internal bool IntegratedSecurity { get { return _integratedSecurity; } } // We always initialize in Async mode so that both synchronous and asynchronous methods // will work. In the future we can deprecate the keyword entirely. internal bool Asynchronous { get { return true; } } // SQLPT 41700: Ignore ResetConnection=False, always reset the connection for security internal bool ConnectionReset { get { return true; } } // internal bool EnableUdtDownload { get { return _enableUdtDownload;} } internal bool Encrypt { get { return _encrypt; } } internal bool TrustServerCertificate { get { return _trustServerCertificate; } } internal bool MARS { get { return _mars; } } internal bool MultiSubnetFailover { get { return _multiSubnetFailover; } } internal bool PersistSecurityInfo { get { return _persistSecurityInfo; } } internal bool Pooling { get { return _pooling; } } internal bool Replication { get { return _replication; } } internal bool UserInstance { get { return _userInstance; } } internal int ConnectTimeout { get { return _connectTimeout; } } internal int LoadBalanceTimeout { get { return _loadBalanceTimeout; } } internal int MaxPoolSize { get { return _maxPoolSize; } } internal int MinPoolSize { get { return _minPoolSize; } } internal int PacketSize { get { return _packetSize; } } internal int ConnectRetryCount { get { return _connectRetryCount; } } internal int ConnectRetryInterval { get { return _connectRetryInterval; } } internal ApplicationIntent ApplicationIntent { get { return _applicationIntent; } } internal string ApplicationName { get { return _applicationName; } } internal string AttachDBFilename { get { return _attachDBFileName; } } internal string CurrentLanguage { get { return _currentLanguage; } } internal string DataSource { get { return _dataSource; } } internal string LocalDBInstance { get { return _localDBInstance; } } internal string FailoverPartner { get { return _failoverPartner; } } internal string InitialCatalog { get { return _initialCatalog; } } internal string Password { get { return _password; } } internal string UserID { get { return _userID; } } internal string WorkstationId { get { return _workstationId; } } internal TypeSystem TypeSystemVersion { get { return _typeSystemVersion; } } // this hashtable is meant to be read-only translation of parsed string // keywords/synonyms to a known keyword string internal static Hashtable GetParseSynonyms() { Hashtable hash = s_sqlClientSynonyms; if (null == hash) { hash = new Hashtable(SqlConnectionStringBuilder.KeywordsCount + SqlConnectionStringBuilder.DeprecatedKeywordsCount + SynonymCount + DeprecatedSynonymCount); hash.Add(KEY.ApplicationIntent, KEY.ApplicationIntent); hash.Add(KEY.Application_Name, KEY.Application_Name); hash.Add(KEY.AsynchronousProcessing, KEY.AsynchronousProcessing); hash.Add(KEY.AttachDBFilename, KEY.AttachDBFilename); hash.Add(KEY.Connect_Timeout, KEY.Connect_Timeout); hash.Add(KEY.Connection_Reset, KEY.Connection_Reset); hash.Add(KEY.Context_Connection, KEY.Context_Connection); hash.Add(KEY.Current_Language, KEY.Current_Language); hash.Add(KEY.Data_Source, KEY.Data_Source); hash.Add(KEY.Encrypt, KEY.Encrypt); hash.Add(KEY.Enlist, KEY.Enlist); hash.Add(KEY.FailoverPartner, KEY.FailoverPartner); hash.Add(KEY.Initial_Catalog, KEY.Initial_Catalog); hash.Add(KEY.Integrated_Security, KEY.Integrated_Security); hash.Add(KEY.Load_Balance_Timeout, KEY.Load_Balance_Timeout); hash.Add(KEY.MARS, KEY.MARS); hash.Add(KEY.Max_Pool_Size, KEY.Max_Pool_Size); hash.Add(KEY.Min_Pool_Size, KEY.Min_Pool_Size); hash.Add(KEY.MultiSubnetFailover, KEY.MultiSubnetFailover); hash.Add(KEY.Network_Library, KEY.Network_Library); hash.Add(KEY.Packet_Size, KEY.Packet_Size); hash.Add(KEY.Password, KEY.Password); hash.Add(KEY.Persist_Security_Info, KEY.Persist_Security_Info); hash.Add(KEY.Pooling, KEY.Pooling); hash.Add(KEY.Replication, KEY.Replication); hash.Add(KEY.TrustServerCertificate, KEY.TrustServerCertificate); hash.Add(KEY.TransactionBinding, KEY.TransactionBinding); hash.Add(KEY.Type_System_Version, KEY.Type_System_Version); hash.Add(KEY.User_ID, KEY.User_ID); hash.Add(KEY.User_Instance, KEY.User_Instance); hash.Add(KEY.Workstation_Id, KEY.Workstation_Id); hash.Add(KEY.Connect_Retry_Count, KEY.Connect_Retry_Count); hash.Add(KEY.Connect_Retry_Interval, KEY.Connect_Retry_Interval); hash.Add(SYNONYM.APP, KEY.Application_Name); hash.Add(SYNONYM.Async, KEY.AsynchronousProcessing); hash.Add(SYNONYM.EXTENDED_PROPERTIES, KEY.AttachDBFilename); hash.Add(SYNONYM.INITIAL_FILE_NAME, KEY.AttachDBFilename); hash.Add(SYNONYM.CONNECTION_TIMEOUT, KEY.Connect_Timeout); hash.Add(SYNONYM.TIMEOUT, KEY.Connect_Timeout); hash.Add(SYNONYM.LANGUAGE, KEY.Current_Language); hash.Add(SYNONYM.ADDR, KEY.Data_Source); hash.Add(SYNONYM.ADDRESS, KEY.Data_Source); hash.Add(SYNONYM.NETWORK_ADDRESS, KEY.Data_Source); hash.Add(SYNONYM.SERVER, KEY.Data_Source); hash.Add(SYNONYM.DATABASE, KEY.Initial_Catalog); hash.Add(SYNONYM.TRUSTED_CONNECTION, KEY.Integrated_Security); hash.Add(SYNONYM.Connection_Lifetime, KEY.Load_Balance_Timeout); hash.Add(SYNONYM.NET, KEY.Network_Library); hash.Add(SYNONYM.NETWORK, KEY.Network_Library); hash.Add(SYNONYM.Pwd, KEY.Password); hash.Add(SYNONYM.PERSISTSECURITYINFO, KEY.Persist_Security_Info); hash.Add(SYNONYM.UID, KEY.User_ID); hash.Add(SYNONYM.User, KEY.User_ID); hash.Add(SYNONYM.WSID, KEY.Workstation_Id); Debug.Assert(SqlConnectionStringBuilder.KeywordsCount + SqlConnectionStringBuilder.DeprecatedKeywordsCount + SynonymCount + DeprecatedSynonymCount == hash.Count, "incorrect initial ParseSynonyms size"); s_sqlClientSynonyms = hash; } return hash; } internal string ObtainWorkstationId() { // If not supplied by the user, the default value is the MachineName // Note: In Longhorn you'll be able to rename a machine without // rebooting. Therefore, don't cache this machine name. string result = WorkstationId; if (null == result) { // permission to obtain Environment.MachineName is Asserted // since permission to open the connection has been granted // the information is shared with the server, but not directly with the user result = string.Empty; } return result; } private void ValidateValueLength(string value, int limit, string key) { if (limit < value.Length) { throw ADP.InvalidConnectionOptionValueLength(key, limit); } } internal System.Data.SqlClient.ApplicationIntent ConvertValueToApplicationIntent() { object value = base.Parsetable[KEY.ApplicationIntent]; if (value == null) { return DEFAULT.ApplicationIntent; } // when wrong value is used in the connection string provided to SqlConnection.ConnectionString or c-tor, // wrap Format and Overflow exceptions with Argument one, to be consistent with rest of the keyword types (like int and bool) try { return DbConnectionStringBuilderUtil.ConvertToApplicationIntent(KEY.ApplicationIntent, value); } catch (FormatException e) { throw ADP.InvalidConnectionOptionValue(KEY.ApplicationIntent, e); } catch (OverflowException e) { throw ADP.InvalidConnectionOptionValue(KEY.ApplicationIntent, e); } // ArgumentException and other types are raised as is (no wrapping) } internal void ThrowUnsupportedIfKeywordSet(string keyword) { if (ContainsKey(keyword)) { throw SQL.UnsupportedKeyword(keyword); } } } }
using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.IO; using FileHelpers.Dynamic; using FileHelpers.Options; namespace FileHelpers { /// <summary>A class to read generic CSV files delimited for any char.</summary> [DebuggerDisplay("CsvEngine. ErrorMode: {ErrorManager.ErrorMode.ToString()}. Encoding: {Encoding.EncodingName}")] public sealed class CsvEngine : FileHelperEngine { #region " Static Methods " /// <summary>Reads a CSV File and return their contents as DataTable (The file must have the field names in the first row)</summary> /// <param name="delimiter">The delimiter for each field</param> /// <param name="filename">The file to read.</param> /// <returns>The contents of the file as a DataTable</returns> public static DataTable CsvToDataTable(string filename, char delimiter) { return CsvToDataTable(filename, "RecorMappingClass", delimiter, true); } /// <summary> /// Reads a CSV File and return their contents as DataTable /// (The file must have the field names in the first /// row) /// </summary> /// <param name="classname">The name of the record class</param> /// <param name="delimiter">The delimiter for each field</param> /// <param name="filename">The file to read.</param> /// <returns>The contents of the file as a DataTable</returns> public static DataTable CsvToDataTable(string filename, string classname, char delimiter) { return CsvToDataTable(filename, classname, delimiter, true); } /// <summary> /// Reads a CSV File and return their contents as DataTable /// </summary> /// <param name="classname">The name of the record class</param> /// <param name="delimiter">The delimiter for each field</param> /// <param name="filename">The file to read.</param> /// <param name="hasHeader">Indicates if the file contains a header with the field names.</param> /// <returns>The contents of the file as a DataTable</returns> public static DataTable CsvToDataTable(string filename, string classname, char delimiter, bool hasHeader) { var options = new CsvOptions(classname, delimiter, filename); if (hasHeader == false) options.HeaderLines = 0; return CsvToDataTable(filename, options); } /// <summary> /// Reads a CSV File and return their contents as DataTable /// </summary> /// <param name="classname">The name of the record class</param> /// <param name="delimiter">The delimiter for each field</param> /// <param name="filename">The file to read.</param> /// <param name="hasHeader">Indicates if the file contains a header with the field names.</param> /// <param name="ignoreEmptyLines">Indicates if blank lines in the file should not be included in the returned DataTable</param> /// <returns>The contents of the file as a DataTable</returns> public static DataTable CsvToDataTable(string filename, string classname, char delimiter, bool hasHeader, bool ignoreEmptyLines) { var options = new CsvOptions(classname, delimiter, filename); if (hasHeader == false) options.HeaderLines = 0; options.IgnoreEmptyLines = ignoreEmptyLines; return CsvToDataTable(filename, options); } /// <summary> /// Reads a CSV File and return their contents as /// DataTable /// </summary> /// <param name="filename">The file to read.</param> /// <param name="options">The options used to create the record mapping class.</param> /// <returns>The contents of the file as a DataTable</returns> public static DataTable CsvToDataTable(string filename, CsvOptions options) { var engine = new CsvEngine(options); #pragma warning disable 618 return engine.ReadFileAsDT(filename); #pragma warning restore 618 } /// <summary> /// Simply dumps the DataTable contents to a delimited file /// using a ',' as delimiter. /// </summary> /// <param name="dt">The source Data Table</param> /// <param name="filename">The destination file.</param> public static void DataTableToCsv(DataTable dt, string filename) { DataTableToCsv(dt, filename, new CsvOptions("Tempo1", ',', dt.Columns.Count)); } /// <summary> /// Simply dumps the DataTable contents to a delimited file using /// <paramref name="delimiter"/> as delimiter. /// </summary> /// <param name="dt">The source Data Table</param> /// <param name="filename">The destination file.</param> /// <param name="delimiter">The delimiter to be used on the file</param> public static void DataTableToCsv(DataTable dt, string filename, char delimiter) { DataTableToCsv(dt, filename, new CsvOptions("Tempo1", delimiter, dt.Columns.Count)); } /// <summary> /// Simply dumps the DataTable contents to a delimited file. Only /// allows to set the delimiter. /// </summary> /// <param name="dt">The source Data Table</param> /// <param name="filename">The destination file.</param> /// <param name="options">The options used to write the file</param> public static void DataTableToCsv(DataTable dt, string filename, CsvOptions options) { using (var fs = new StreamWriter(filename, false, options.Encoding, DefaultWriteBufferSize)) { // output header if (options.IncludeHeaderNames) { var columnNames = new List<object>(); foreach (DataColumn dataColumn in dt.Columns) { columnNames.Add(dataColumn.ColumnName); } Append(fs, options, columnNames); } foreach (DataRow dr in dt.Rows) { object[] fields = dr.ItemArray; Append(fs, options, fields); } fs.Close(); } } #endregion #region " Constructor " /// <summary> /// <para>Create a CsvEngine using the specified sample file with their headers.</para> /// <para>With this constructor will ignore the first line of the file. Use CsvOptions overload.</para> /// </summary> /// <param name="className">The name of the record class</param> /// <param name="delimiter">The delimiter for each field</param> /// <param name="sampleFile">A sample file with a header that contains the names of the fields.</param> public CsvEngine(string className, char delimiter, string sampleFile) : this(new CsvOptions(className, delimiter, sampleFile)) {} /// <summary> /// <para>Create a CsvEngine using the specified number of fields.</para> /// <para>With this constructor will ignore the first line of the file. Use CsvOptions overload.</para> /// </summary> /// <param name="className">The name of the record class</param> /// <param name="delimiter">The delimiter for each field</param> /// <param name="numberOfFields">The number of fields of each record</param> public CsvEngine(string className, char delimiter, int numberOfFields) : this(new CsvOptions(className, delimiter, numberOfFields)) {} /// <summary> /// Create a CsvEngine using the specified sample file with /// their headers. /// </summary> /// <param name="options">The options used to create the record mapping class.</param> public CsvEngine(CsvOptions options) : base(GetMappingClass(options)) {} #endregion private static Type GetMappingClass(CsvOptions options) { var cb = new CsvClassBuilder(options); return cb.CreateRecordClass(); } private static void Append(TextWriter fs, CsvOptions options, IList<object> fields) { for (int i = 0; i < fields.Count; i++) { if (i > 0) { fs.Write(options.Delimiter); } fs.Write(options.ValueToString(fields[i])); } fs.Write(Environment.NewLine); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework.Net; namespace Pool { /// <summary> /// This is the main type for your game /// </summary> public class Pool : Microsoft.Xna.Framework.Game { public GraphicsDeviceManager graphics; public SpriteBatch spriteBatch; public bool ended = false; public Color background = Color.Black; // Ball holder public List<Ball> balls; // This is used for displaying which balls have been potted public List<Ball> pottedBalls; const int refugeX = 705; // State Variables public GameState _gameState; public MenuState _menuState; public GameMode _gameMode; public PlayerIndex _currentPlayer; Color _playerOneColour; Color _playerTwoColour; Color _firstColourHit; TurnState _turnState; bool _cueVisible; bool _freezeInput; bool _freezeInputPrevious; PlayerIndex _winningPlayer; int _winningTimer; int _cueBallTimer; // Multiplayer only public Networking _connection; public IPAddress _connectionAddress; public PlayerIndex _myPlayer; string _ipInput = "127.0.0.1"; long _startTime = 0; long _lastInput = 0; // Resources Texture2D _fourpx; Texture2D _cue; Texture2D _cueball; Texture2D _table; Texture2D _darkenOverlay; Texture2D _logo; Texture2D _barUnderlay; Texture2D _barOverlay; // Menu buttons and text Texture2D[] _menuPlay = new Texture2D[3]; Texture2D[] _menuPractice = new Texture2D[3]; Texture2D[] _menuOffline = new Texture2D[3]; Texture2D[] _menuHost = new Texture2D[3]; Texture2D[] _menuConnect = new Texture2D[3]; Texture2D[] _menuOk = new Texture2D[3]; Texture2D[] _menuBack = new Texture2D[3]; Texture2D _menuWaitingStatic; Texture2D _menuEnterIpStatic; Texture2D _explanation; // Fonts SpriteFont _spriteFont; // SoundEffect public SoundEffect _cueStrike; public SoundEffect _ballStrike; public SoundEffect _railBounce; public SoundEffect _pocketBounce; public SoundEffect _portal; // A semi-transparent colour for our ball predictors Color _semiTransparent; // Position and size Rectangle _tablePosition; Rectangle _playableArea; // Cue information public Vector2 _cuePosition; public double _cueRotation; public double _cueDistance; // Constants const int MAX_POWER = 150; // Ball Predictor BallPredictor _ballPredictor; // Stuff for showing some big text stuff Color _bigTextColour = Color.HotPink; string _bigtextString = ""; SpriteFont _bigTextFont; int _bigTextTimer = 0; // Previous mouse and keyboard states Vector2 _mousePosition; MouseState _mouseStatePrevious; KeyboardState _keyboardStatePrevious; // The mouse position when the cue last started to be dragged Vector2 _lastMousePosition; public Pool() { _currentPlayer = PlayerIndex.One; _turnState = TurnState.SHOOTING; _gameState = GameState.MENU; _menuState = MenuState.HOME; graphics = new GraphicsDeviceManager(this); graphics.PreferredBackBufferWidth = 1280; graphics.PreferredBackBufferHeight = 720; IsFixedTimeStep = true; TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 10); IsMouseVisible = true; Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here _mousePosition = new Vector2(Mouse.GetState().X, Mouse.GetState().Y); _lastMousePosition = new Vector2(Mouse.GetState().X, Mouse.GetState().Y); _keyboardStatePrevious = Keyboard.GetState(); _mouseStatePrevious = Mouse.GetState(); _playableArea = new Rectangle(85, 85, 1105, 555); _cueVisible = true; base.Initialize(); } protected void PostLoadInitialize() { double scaleFactor = (double)graphics.PreferredBackBufferWidth / (double)_table.Width; _tablePosition = new Rectangle(0, 0, graphics.PreferredBackBufferWidth, (int)Math.Round(scaleFactor * _table.Height)); _ballPredictor = new BallPredictor(this, _cueball, _playableArea, _semiTransparent); InitializeGame(false); } public void InitializeGame(bool multiPlayer) { if (!multiPlayer) { GenerateBalls(); pottedBalls = new List<Ball>(); _winningPlayer = PlayerIndex.Three; _playerOneColour = Color.Transparent; _playerTwoColour = Color.Transparent; } } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // Load the required resources _fourpx = Content.Load<Texture2D>("4px"); _cue = Content.Load<Texture2D>("cue"); _cueball = Content.Load<Texture2D>("cueball"); _table = Content.Load<Texture2D>("pooltable"); _logo = Content.Load<Texture2D>("logo"); _barUnderlay = Content.Load<Texture2D>("barunderlay"); _barOverlay = Content.Load<Texture2D>("baroverlay"); _darkenOverlay = Content.Load<Texture2D>("darken"); // Menu buttons _menuPlay[0] = Content.Load<Texture2D>("menu_play_up"); _menuPlay[1] = Content.Load<Texture2D>("menu_play_over"); _menuPlay[2] = Content.Load<Texture2D>("menu_play_down"); _menuPractice[0] = Content.Load<Texture2D>("menu_practice_up"); _menuPractice[1] = Content.Load<Texture2D>("menu_practice_over"); _menuPractice[2] = Content.Load<Texture2D>("menu_practice_down"); _menuOffline[0] = Content.Load<Texture2D>("menu_offline_up"); _menuOffline[1] = Content.Load<Texture2D>("menu_offline_over"); _menuOffline[2] = Content.Load<Texture2D>("menu_offline_down"); _menuHost[0] = Content.Load<Texture2D>("menu_host_up"); _menuHost[1] = Content.Load<Texture2D>("menu_host_over"); _menuHost[2] = Content.Load<Texture2D>("menu_host_down"); _menuConnect[0] = Content.Load<Texture2D>("menu_connect_up"); _menuConnect[1] = Content.Load<Texture2D>("menu_connect_over"); _menuConnect[2] = Content.Load<Texture2D>("menu_connect_down"); _menuOk[0] = Content.Load<Texture2D>("menu_ok_up"); _menuOk[1] = Content.Load<Texture2D>("menu_ok_over"); _menuOk[2] = Content.Load<Texture2D>("menu_ok_down"); _menuBack[0] = Content.Load<Texture2D>("menu_back_up"); _menuBack[1] = Content.Load<Texture2D>("menu_back_over"); _menuBack[2] = Content.Load<Texture2D>("menu_back_down"); // Menu text _menuWaitingStatic = Content.Load<Texture2D>("menu_awaiting_connection_static"); _menuEnterIpStatic = Content.Load<Texture2D>("menu_enter_ip_static"); _explanation = Content.Load<Texture2D>("explanation"); // Make a transparent colour _semiTransparent = new Color(255, 255, 255, 100); // Load some sounds _cueStrike = Content.Load<SoundEffect>("cuestrike"); _ballStrike = Content.Load<SoundEffect>("ballstrike"); _railBounce = Content.Load<SoundEffect>("railbounce"); _pocketBounce = Content.Load<SoundEffect>("pocketbounce"); _portal = Content.Load<SoundEffect>("portal"); // Load some fonts _spriteFont = Content.Load<SpriteFont>("SpriteFont1"); _bigTextFont = Content.Load<SpriteFont>("BigFont"); PostLoadInitialize(); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { _mousePosition.X = Mouse.GetState().X; _mousePosition.Y = Mouse.GetState().Y; switch (GameState) { case GameState.MENU: if ((GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || (!Keyboard.GetState().IsKeyDown(Keys.Escape) && _keyboardStatePrevious.IsKeyDown(Keys.Escape))) && _menuState != MenuState.AWAITCONNECTION) EndGame(); UpdateMenu(gameTime); break; case GameState.GAMEPLAY: UpdateGame(gameTime); if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || (!Keyboard.GetState().IsKeyDown(Keys.Escape) && _keyboardStatePrevious.IsKeyDown(Keys.Escape))) _gameState = GameState.MENU; break; default: break; } _mouseStatePrevious = Mouse.GetState(); _keyboardStatePrevious = Keyboard.GetState(); base.Update(gameTime); } protected void UpdateMenu(GameTime gameTime) { if (Mouse.GetState().LeftButton == ButtonState.Released && Mouse.GetState().LeftButton != _mouseStatePrevious.LeftButton) { switch (_menuState) { case MenuState.HOME: if (Mouse.GetState().Y >= 350 && Mouse.GetState().Y < 400) { _menuState = MenuState.MODE; } if (Mouse.GetState().Y >= 400 && Mouse.GetState().Y < 450) { _gameMode = GameMode.PRACTICE; pottedBalls.Clear(); GenerateBalls(); _startTime = (long)gameTime.TotalGameTime.TotalSeconds; _menuState = MenuState.HOME; _gameState = GameState.GAMEPLAY; } break; case MenuState.MODE: if (Mouse.GetState().Y >= 350 && Mouse.GetState().Y < 400) { _gameMode = GameMode.OFFLINE; GenerateBalls(); pottedBalls.Clear(); _menuState = MenuState.HOME; _gameState = GameState.GAMEPLAY; } if (Mouse.GetState().Y >= 400 && Mouse.GetState().Y < 450) { _menuState = MenuState.AWAITCONNECTION; } if (Mouse.GetState().Y >= 450 && Mouse.GetState().Y < 500) { _menuState = MenuState.ENTERIP; } if (Mouse.GetState().Y >= 500 && Mouse.GetState().Y < 550) { _menuState = MenuState.HOME; } break; case MenuState.AWAITCONNECTION: if (Mouse.GetState().Y >= 450 && Mouse.GetState().Y < 500) { _menuState = MenuState.MODE; } break; case MenuState.ENTERIP: if (Mouse.GetState().Y >= 500 && Mouse.GetState().Y < 550) { if (IPAddress.TryParse(_ipInput, out _connectionAddress)) _menuState = MenuState.CONNECTING; } if (Mouse.GetState().Y >= 550 && Mouse.GetState().Y < 600) { _menuState = MenuState.MODE; } break; default: break; } } if (_menuState == MenuState.ENTERIP) { if (gameTime.TotalGameTime.TotalMilliseconds >= _lastInput + 150) { if (Keyboard.GetState().IsKeyDown(Keys.D0) || Keyboard.GetState().IsKeyDown(Keys.NumPad0)) { _ipInput += "0"; _lastInput = (long)gameTime.TotalGameTime.TotalMilliseconds; } if (Keyboard.GetState().IsKeyDown(Keys.D1) || Keyboard.GetState().IsKeyDown(Keys.NumPad1)) { _ipInput += "1"; _lastInput = (long)gameTime.TotalGameTime.TotalMilliseconds; } if (Keyboard.GetState().IsKeyDown(Keys.D2) || Keyboard.GetState().IsKeyDown(Keys.NumPad2)) { _ipInput += "2"; _lastInput = (long)gameTime.TotalGameTime.TotalMilliseconds; } if (Keyboard.GetState().IsKeyDown(Keys.D3) || Keyboard.GetState().IsKeyDown(Keys.NumPad3)) { _ipInput += "3"; _lastInput = (long)gameTime.TotalGameTime.TotalMilliseconds; } if (Keyboard.GetState().IsKeyDown(Keys.D4) || Keyboard.GetState().IsKeyDown(Keys.NumPad4)) { _ipInput += "4"; _lastInput = (long)gameTime.TotalGameTime.TotalMilliseconds; } if (Keyboard.GetState().IsKeyDown(Keys.D5) || Keyboard.GetState().IsKeyDown(Keys.NumPad5)) { _ipInput += "5"; _lastInput = (long)gameTime.TotalGameTime.TotalMilliseconds; } if (Keyboard.GetState().IsKeyDown(Keys.D6) || Keyboard.GetState().IsKeyDown(Keys.NumPad6)) { _ipInput += "6"; _lastInput = (long)gameTime.TotalGameTime.TotalMilliseconds; } if (Keyboard.GetState().IsKeyDown(Keys.D7) || Keyboard.GetState().IsKeyDown(Keys.NumPad7)) { _ipInput += "7"; _lastInput = (long)gameTime.TotalGameTime.TotalMilliseconds; } if (Keyboard.GetState().IsKeyDown(Keys.D8) || Keyboard.GetState().IsKeyDown(Keys.NumPad8)) { _ipInput += "8"; _lastInput = (long)gameTime.TotalGameTime.TotalMilliseconds; } if (Keyboard.GetState().IsKeyDown(Keys.D9) || Keyboard.GetState().IsKeyDown(Keys.NumPad9)) { _ipInput += "9"; _lastInput = (long)gameTime.TotalGameTime.TotalMilliseconds; } if (Keyboard.GetState().IsKeyDown(Keys.OemPeriod)) { _ipInput += "."; _lastInput = (long)gameTime.TotalGameTime.TotalMilliseconds; } if (Keyboard.GetState().IsKeyDown(Keys.OemSemicolon)) { _ipInput += ":"; _lastInput = (long)gameTime.TotalGameTime.TotalMilliseconds; } if (Keyboard.GetState().IsKeyDown(Keys.Back) && _ipInput.Length > 0) { _ipInput = _ipInput.Substring(0, _ipInput.Length - 1); _lastInput = (long)gameTime.TotalGameTime.TotalMilliseconds; } if (!Keyboard.GetState().IsKeyDown(Keys.Enter) && _keyboardStatePrevious.IsKeyDown(Keys.Enter)) { if (IPAddress.TryParse(_ipInput, out _connectionAddress)) { _menuState = MenuState.CONNECTING; } } } } else if (_menuState == MenuState.CONNECTING) { if (_connection == null) { ConnectionExitedDelegate ced = new ConnectionExitedDelegate(ConnectionExited); _connection = new Networking(this, ced, _connectionAddress, 7167, false); } else if (_connection.Connected) { _gameState = GameState.GAMEPLAY; pottedBalls.Clear(); _gameMode = GameMode.ONLINE; _myPlayer = PlayerIndex.Two; GenerateBalls(); _menuState = MenuState.HOME; } } else if (_menuState == MenuState.AWAITCONNECTION) { if (_connection == null) { ConnectionExitedDelegate ced = new ConnectionExitedDelegate(ConnectionExited); _connection = new Networking(this, ced, IPAddress.Any, 7167, true); } else if (_connection.Connected) { _gameState = GameState.GAMEPLAY; _gameMode = GameMode.ONLINE; _myPlayer = PlayerIndex.One; GenerateBalls(); _menuState = MenuState.HOME; } } } protected void UpdateGame(GameTime gameTime) { #region TEST //if (Mouse.GetState().LeftButton == ButtonState.Pressed && Mouse.GetState().LeftButton != _mouseStatePrevious.LeftButton) //{ // testRectangle.X = Mouse.GetState().X; // testRectangle.Y = Mouse.GetState().Y; //} //else if (Mouse.GetState().LeftButton == ButtonState.Pressed) //{ // testRectangle.Width = Mouse.GetState().X - testRectangle.X; // testRectangle.Height = Mouse.GetState().Y - testRectangle.Y; //} //if (Keyboard.GetState().IsKeyDown(Keys.Left) && Keyboard.GetState().IsKeyDown(Keys.Left) != _keyboardStatePrevious.IsKeyDown(Keys.Left)) //{ // spherePosition.X--; //} //if (Keyboard.GetState().IsKeyDown(Keys.Right) && Keyboard.GetState().IsKeyDown(Keys.Right) != _keyboardStatePrevious.IsKeyDown(Keys.Right)) //{ // spherePosition.X++; //} //if (Keyboard.GetState().IsKeyDown(Keys.Down) && Keyboard.GetState().IsKeyDown(Keys.Down) != _keyboardStatePrevious.IsKeyDown(Keys.Down)) //{ // spherePosition.Y++; //} //if (Keyboard.GetState().IsKeyDown(Keys.Up) && Keyboard.GetState().IsKeyDown(Keys.Up) != _keyboardStatePrevious.IsKeyDown(Keys.Up)) //{ // spherePosition.Y--; //} #endregion if (_bigTextTimer > 0) { _bigTextTimer -= gameTime.ElapsedGameTime.Milliseconds; } if (_cueBallTimer > 0) { _cueBallTimer -= gameTime.ElapsedGameTime.Milliseconds; _freezeInput = true; } else { /// TODO LOL if (_cueBallTimer < 0) _cueBallTimer = 0; } if (_gameMode == GameMode.ONLINE && _currentPlayer != _myPlayer) { _freezeInput = true; _cueVisible = false; } else { _cueVisible = true; } if (!_freezeInput) { _cuePosition = balls[0].Position; if (Mouse.GetState().LeftButton == ButtonState.Released) { _lastMousePosition = new Vector2(Mouse.GetState().X, Mouse.GetState().Y); if (_mouseStatePrevious.LeftButton == ButtonState.Pressed && _cueDistance > 0) { // do shot MakeShot(_cueDistance, _cueRotation, false); if (_gameMode == GameMode.ONLINE && _connection != null) { _connection.SendSync(balls); _connection.SendVelocity(_cueDistance, _cueRotation); } _cueDistance = 0; } else { _cueRotation = Math.Atan2(Mouse.GetState().X - balls[0].X, Mouse.GetState().Y - balls[0].Y); } } else if (Mouse.GetState().LeftButton == ButtonState.Pressed && _mouseStatePrevious.LeftButton == ButtonState.Released) { _lastMousePosition = new Vector2(Mouse.GetState().X, Mouse.GetState().Y); } else { double mouseDistanceFromCue = (_mousePosition - balls[0].Position).Length(); // let the user pull the cue back to decide power // (let me overcomplicate everything for you!) // Angles between the polar axes centred around the ball and various lines double lastMousePosAngle = _cueRotation; double currentMousePosAngle = Math.Atan2(Mouse.GetState().X - balls[0].X, Mouse.GetState().Y - balls[0].Y); // A triangle constructed of: // - The line between the ball and where the mouse currently is // - The line between the ball and where the mouse was when lmb was first held // - The third line connecting these two lines, creating a right angle between this line and the line to where lmb was first held // The angle is gotten by subtracting the angles above double theta = currentMousePosAngle - lastMousePosAngle; // The length of the first line segment double firstLineSegment = (_mousePosition - balls[0].Position).Length(); // Then use trigonometry to calculate the length of the third line double trigThirdLine = firstLineSegment * Math.Cos(theta); double fullLine = (balls[0].Position - _lastMousePosition).Length(); // And subtract this length from line segment 2 to get the distance of the mouse from that point _cueDistance = (int)Math.Floor(fullLine - trigThirdLine); if (_cueDistance < 0) _cueDistance = 0; if (_cueDistance > MAX_POWER) _cueDistance = MAX_POWER; } if (_cueDistance > 0 && Mouse.GetState().LeftButton == ButtonState.Released) _cueDistance = 0; _cuePosition.X = balls[0].Position.X - (float)(Math.Sin(_cueRotation) * _cueDistance); _cuePosition.Y = balls[0].Position.Y - (float)(Math.Cos(_cueRotation) * _cueDistance); } _ballPredictor.Update(gameTime, balls, _cueRotation); foreach (Ball ball in balls) { foreach (Ball other in balls) { if (ball != other) { if (ball.Velocity.LengthSquared() > 0) { if (ball.BoundingSphere.Intersects(other.BoundingSphere)) { Vector2 impact = other.Velocity - ball.Velocity; Vector2 impulse = Vector2.Normalize(other.Position - ball.Position); float impactSpeed = Vector2.Dot(impact, impulse); if (impactSpeed < -2000) impactSpeed = -2000; if (impactSpeed < 0) { _ballStrike.Play(impactSpeed / -2000.0f, 0.0f, 0.0f); if (ball.Colour != Color.White && other.Colour != Color.White) { Color tempColour = ball.Colour; ball.Colour = other.Colour; other.Colour = tempColour; } else if (ball.Colour == Color.White) { if (_firstColourHit == Color.Transparent) { _firstColourHit = other.Colour; //string colourHit; //if (other.Colour == Color.Black) // colourHit = "black"; //else if (other.Colour == Color.Orange) // colourHit = "orange"; //else if (other.Colour == Color.Red) // colourHit = "red"; //else // colourHit = "BAD"; //ShowBigText(Color.White, "Hit " + colourHit, 1500); } } else if (other.Colour == Color.White) { if (_firstColourHit == Color.Transparent) { _firstColourHit = ball.Colour; //string colourHit; //if (ball.Colour == Color.Black) // colourHit = "black"; //else if (ball.Colour == Color.Orange) // colourHit = "orange"; //else if (ball.Colour == Color.Red) // colourHit = "red"; //else // colourHit = "BAD"; } } impulse *= impactSpeed * 0.95f; other.Velocity -= impulse; ball.Velocity += impulse; } } } } } ball.Update(gameTime); } for (int i = 0; i < pottedBalls.Count; i++) { if (pottedBalls[i].X > refugeX + (i * 30)) { pottedBalls[i].X -= (float)(0.5 * gameTime.ElapsedGameTime.Milliseconds); } if (pottedBalls[i].X < refugeX + (i * 30)) { pottedBalls[i].X = refugeX + (i * 30); } } _freezeInput = false; for (int i = 0; i < balls.Count; i++) { if (balls[i]._potted) { // If it aint the cue ball.. damnit if (balls[i].Colour != Color.White) { _pocketBounce.Play(1.0f, 0.0f, 0.0f); // If it aint the black.. double damnit if (balls[i].Colour != Color.Black) { // If players are not yet assigned colours if (_playerOneColour == Color.Transparent) { // Assign 'em I guess Color otherColour; if (balls[i].Colour == Color.Red) otherColour = Color.Orange; else otherColour = Color.Red; switch (_currentPlayer) { case PlayerIndex.One: _playerOneColour = balls[i].Colour; _playerTwoColour = otherColour; break; case PlayerIndex.Two: _playerOneColour = otherColour; _playerTwoColour = balls[i].Colour; break; } ShowBigText(Color.White, "SCORE", 1500); _turnState = TurnState.SCORED; } else { // Otherwise check if they potted their own ball Color currentPlayersColour; if (_currentPlayer == PlayerIndex.One) { currentPlayersColour = _playerOneColour; } else { currentPlayersColour = _playerTwoColour; } if (balls[i].Colour == currentPlayersColour) { // BAM _turnState = TurnState.SCORED; ShowBigText(Color.White, "SCORE", 1500); } } } else { // If they pot the black Color currentPlayerColour; if (_currentPlayer == PlayerIndex.One) currentPlayerColour = _playerOneColour; else currentPlayerColour = _playerTwoColour; int currentPlayerBallsLeft = 0; foreach (Ball ball in balls) { if (ball.Colour == currentPlayerColour) currentPlayerBallsLeft++; } // If they have more than one ball of their colour left, fuck if (currentPlayerBallsLeft > 0 || currentPlayerColour == Color.Transparent || (_firstColourHit != currentPlayerColour && _firstColourHit != Color.Black)) { PlayerIndex otherPlayer; if (_currentPlayer == PlayerIndex.One) otherPlayer = PlayerIndex.Two; else otherPlayer = PlayerIndex.One; _winningPlayer = otherPlayer; _winningTimer = 14000; _freezeInput = true; } else { _winningPlayer = _currentPlayer; _winningTimer = 14000; _freezeInput = true; } } pottedBalls.Add(balls[i]); balls[i].X = 2000; balls[i].Y = 676; balls.Remove(balls[i]); i--; } else { // If white, _portal.Play(1.0f, 1.0f, 1.0f); balls[i]._potted = false; _freezeInput = true; _cueBallTimer = 1000; balls[i].Position = Ball._reversedPocketSpheres[balls[i]._pocketCollided]; } } else if (balls[i].Velocity.LengthSquared() > 0) { _freezeInput = true; } } if (_winningTimer > 0) { _freezeInput = true; _winningTimer -= gameTime.ElapsedGameTime.Milliseconds; } else if (_winningPlayer != PlayerIndex.Three) { // Restart game when timer gets to 0 _winningTimer = 0; GenerateBalls(); _playerOneColour = Color.Transparent; _playerTwoColour = Color.Transparent; _startTime = gameTime.TotalGameTime.Seconds; InitializeGame(false); } if (_freezeInput == false && _freezeInputPrevious == true && _gameMode != GameMode.PRACTICE) { // Play just resumed, then Color currentPlayerColour; if (_currentPlayer == PlayerIndex.One) currentPlayerColour = _playerOneColour; else currentPlayerColour = _playerTwoColour; // Check how many balls the current player has int currentPlayerBallsLeft = 0; foreach (Ball ball in balls) { if (ball.Colour == currentPlayerColour) currentPlayerBallsLeft++; } if ((currentPlayerColour == Color.Transparent && (_firstColourHit == Color.Red || _firstColourHit == Color.Orange)) || (currentPlayerColour != Color.Transparent && _firstColourHit == currentPlayerColour) || ((currentPlayerBallsLeft == 0 && currentPlayerColour != Color.Transparent) && _firstColourHit == Color.Black)) { } else if (_winningTimer == 0) { ShowBigText(Color.White, "Foul", 1500); } else if (_winningTimer != 0) { _firstColourHit = Color.Transparent; } _firstColourHit = Color.Transparent; // Switch players if (_turnState != TurnState.SCORED) { if (_currentPlayer == PlayerIndex.One) _currentPlayer = PlayerIndex.Two; else _currentPlayer = PlayerIndex.One; } _turnState = TurnState.SHOOTING; } _freezeInputPrevious = _freezeInput; } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(background); spriteBatch.Begin(); switch (GameState) { case GameState.MENU: DrawMenu(gameTime); break; case GameState.GAMEPLAY: DrawGame(gameTime); break; default: break; } //spriteBatch.DrawString(_spriteFont, _mousePosition.X.ToString() + "," + _mousePosition.Y.ToString(), new Vector2(_mousePosition.X + 50, _mousePosition.Y + 50), Color.Black); // Big text! if (_bigTextTimer > 0) { spriteBatch.DrawString(_bigTextFont, _bigtextString, new Vector2(640 - (10 * _bigtextString.Length), 300), _bigTextColour); } spriteBatch.End(); base.Draw(gameTime); } protected void DrawMenu(GameTime gameTime) { spriteBatch.Draw(_table, new Rectangle(0, 0, 1280, 720), Color.White); spriteBatch.Draw(_darkenOverlay, new Rectangle(0, 0, 1280, 720), Color.White); spriteBatch.Draw(_logo, new Vector2(150, 80), Color.White); spriteBatch.Draw(_explanation, new Vector2(830, 355), Color.White); switch (_menuState) { case MenuState.HOME: if (Mouse.GetState().Y >= 350 && Mouse.GetState().Y < 400) { if (Mouse.GetState().LeftButton == ButtonState.Pressed) spriteBatch.Draw(_menuPlay[1], new Vector2(150, 350), Color.White); else spriteBatch.Draw(_menuPlay[2], new Vector2(150, 350), Color.White); } else { spriteBatch.Draw(_menuPlay[0], new Vector2(150, 350), Color.White); } if (Mouse.GetState().Y >= 400 && Mouse.GetState().Y < 450) { if (Mouse.GetState().LeftButton == ButtonState.Pressed) spriteBatch.Draw(_menuPractice[1], new Vector2(150, 400), Color.White); else spriteBatch.Draw(_menuPractice[2], new Vector2(150, 400), Color.White); } else { spriteBatch.Draw(_menuPractice[0], new Vector2(150, 400), Color.White); } break; case MenuState.MODE: if (Mouse.GetState().Y >= 350 && Mouse.GetState().Y < 400) { if (Mouse.GetState().LeftButton == ButtonState.Pressed) spriteBatch.Draw(_menuOffline[1], new Vector2(150, 350), Color.White); else spriteBatch.Draw(_menuOffline[2], new Vector2(150, 350), Color.White); } else { spriteBatch.Draw(_menuOffline[0], new Vector2(150, 350), Color.White); } if (Mouse.GetState().Y >= 400 && Mouse.GetState().Y < 450) { if (Mouse.GetState().LeftButton == ButtonState.Pressed) spriteBatch.Draw(_menuHost[1], new Vector2(150, 400), Color.White); else spriteBatch.Draw(_menuHost[2], new Vector2(150, 400), Color.White); } else { spriteBatch.Draw(_menuHost[0], new Vector2(150, 400), Color.White); } if (Mouse.GetState().Y >= 450 && Mouse.GetState().Y < 500) { if (Mouse.GetState().LeftButton == ButtonState.Pressed) spriteBatch.Draw(_menuConnect[1], new Vector2(150, 450), Color.White); else spriteBatch.Draw(_menuConnect[2], new Vector2(150, 450), Color.White); } else { spriteBatch.Draw(_menuConnect[0], new Vector2(150, 450), Color.White); } if (Mouse.GetState().Y >= 500 && Mouse.GetState().Y < 550) { if (Mouse.GetState().LeftButton == ButtonState.Pressed) spriteBatch.Draw(_menuBack[1], new Vector2(150, 500), Color.White); else spriteBatch.Draw(_menuBack[2], new Vector2(150, 500), Color.White); } else { spriteBatch.Draw(_menuBack[0], new Vector2(150, 500), Color.White); } break; case MenuState.AWAITCONNECTION: spriteBatch.Draw(_menuWaitingStatic, new Vector2(150, 350), Color.White); if (Mouse.GetState().Y >= 450 && Mouse.GetState().Y < 500) { if (Mouse.GetState().LeftButton == ButtonState.Pressed) spriteBatch.Draw(_menuBack[1], new Vector2(150, 450), Color.White); else spriteBatch.Draw(_menuBack[2], new Vector2(150, 450), Color.White); } else { spriteBatch.Draw(_menuBack[0], new Vector2(150, 450), Color.White); } break; case MenuState.ENTERIP: spriteBatch.Draw(_menuEnterIpStatic, new Vector2(150, 350), Color.White); if (Mouse.GetState().Y >= 500 && Mouse.GetState().Y < 550) { if (Mouse.GetState().LeftButton == ButtonState.Pressed) spriteBatch.Draw(_menuOk[1], new Vector2(150, 500), Color.White); else spriteBatch.Draw(_menuOk[2], new Vector2(150, 500), Color.White); } else { spriteBatch.Draw(_menuOk[0], new Vector2(150, 500), Color.White); } if (Mouse.GetState().Y >= 550 && Mouse.GetState().Y < 600) { if (Mouse.GetState().LeftButton == ButtonState.Pressed) spriteBatch.Draw(_menuBack[1], new Vector2(150, 550), Color.White); else spriteBatch.Draw(_menuBack[2], new Vector2(150, 550), Color.White); } else { spriteBatch.Draw(_menuBack[0], new Vector2(150, 550), Color.White); } spriteBatch.DrawString(_bigTextFont, _ipInput, new Vector2(295, 400), Color.White); break; default: break; } } protected void DrawGame(GameTime gameTime) { spriteBatch.Draw(_table, _tablePosition, Color.White); //spriteBatch.Draw(_fourpx, testRectangle, Color.White); //spriteBatch.DrawString(_spriteFont, testRectangle.X.ToString() + ", " + testRectangle.Y.ToString() + ", " + testRectangle.Width.ToString() + ", " + testRectangle.Height.ToString(), new Vector2(testRectangle.X - 25, testRectangle.Y - 25), Color.White); if (!InputFrozen) { _ballPredictor.Draw(gameTime); } // Draw balls foreach (Ball ball in balls) { ball.Draw(gameTime); } // Draw potted balls spriteBatch.Draw(_barUnderlay, new Vector2(0, 0), Color.White); for (int i = 0; i < pottedBalls.Count; i++) { if (pottedBalls[i].X <= 1125) spriteBatch.Draw(_cueball, pottedBalls[i].Position, pottedBalls[i].Colour); } spriteBatch.Draw(_barOverlay, new Vector2(0, 0), Color.White); // Draw cue if (_cueVisible) spriteBatch.Draw(_cue, _cuePosition, null, Color.White, (float)-_cueRotation, new Vector2(8, 870 + (_cueball.Width / 2)), 1.0f, SpriteEffects.None, 1.0f); if (_gameMode != GameMode.PRACTICE) { string currentPlayer = "Current player: "; switch (_currentPlayer) { case PlayerIndex.One: currentPlayer += "One"; break; case PlayerIndex.Two: currentPlayer += "Two"; break; default: currentPlayer += "ERROR"; break; } spriteBatch.DrawString(_spriteFont, currentPlayer, new Vector2(25, 25), Color.White); string currentPlayerColour; if (_playerOneColour == Color.Transparent) { currentPlayerColour = "None"; } else if (_currentPlayer == PlayerIndex.One) { currentPlayerColour = ColourToString(_playerOneColour); } else { currentPlayerColour = ColourToString(_playerTwoColour); } spriteBatch.DrawString(_spriteFont, "Player's colour: " + currentPlayerColour, new Vector2(25, 50), Color.White); } else { long totalSeconds = (long)gameTime.TotalGameTime.TotalSeconds - _startTime; long seconds = (totalSeconds % 3600) % 60; long minutes = (totalSeconds / 60) % 60; long hours = (totalSeconds / 3600); string time = (hours < 10 ? "0" : "") + hours.ToString() + ":" + (minutes < 10 ? "0" : "") + minutes.ToString() + ":" + (seconds < 10 ? "0" : "") + seconds.ToString(); spriteBatch.DrawString(_spriteFont, "Time: " + time, new Vector2(25, 25), Color.White); } if (_winningPlayer != PlayerIndex.Three) { string winningPlayerString; if (_winningPlayer == PlayerIndex.One) winningPlayerString = "One"; else winningPlayerString = "Two"; string winningString = (_gameMode != GameMode.PRACTICE ? "Player " + winningPlayerString + " wins!" : "Game over!") + " The Game restarts in " + ((_winningTimer + 1) / 1000) + " seconds."; spriteBatch.DrawString(_bigTextFont, winningString, new Vector2(600 - (10 * winningString.Length), 300), Color.White); } #if (DEBUG) //foreach (Rectangle rect in Ball._pocketRectangles) //{ // spriteBatch.Draw(_fourpx, rect, Color.White); //} //spriteBatch.Draw(_circle, spherePosition, Color.AliceBlue); #endif } public bool InputFrozen { get { return _freezeInput; } set { _freezeInput = value; } } public virtual GameState GameState { get { return _gameState; } set { _gameState = value; } } public virtual TurnState TurnState { get { return _turnState; } set { _turnState = value; } } string ColourToString(Color ballColour) { if (ballColour == Color.Red) return "Red"; if (ballColour == Color.Orange) return "Orange"; if (ballColour == Color.Black) return "Black"; else return "White"; } void ShowBigText(Color bigTextColour, string bigTextString, int bigTextTime) { _bigTextColour = bigTextColour; _bigtextString = bigTextString; _bigTextTimer = bigTextTime; } public void GenerateBalls() { balls = BallConfigurations.Triangle(this, _cueball, _playableArea, 16, new Vector2(360, 360), new Vector2(800, 360), _cueball.Width / 2); } public void ConnectionExited(ConnectionError e) { Console.WriteLine(e.ToString()); if (_connection != null) { _connection.Close(); _connection = null; } switch (e) { case ConnectionError.LISTENING_SOCKET_IN_USE: this._gameState = GameState.MENU; break; case ConnectionError.REJECTED_BY_HOST: this._gameState = GameState.MENU; break; case ConnectionError.CONNECTION_EXITED: this._gameState = GameState.MENU; break; default: this._gameState = GameState.MENU; break; } GenerateBalls(); } public void MakeShot(double cueDistance, double cueRotation, bool remote) { balls[0].SetVelocity(cueDistance * 15, cueRotation); float volume = (float)(cueDistance / MAX_POWER); _cueStrike.Play(volume, 0.0f, 0.0f); _freezeInput = true; } public void EndGame() { if (_connection != null) { _connection.Close(); _connection = null; } ended = true; this.Exit(); } } public delegate void ConnectionExitedDelegate(ConnectionError e); public enum GameState { MENU, GAMEPLAY } public enum TurnState { SHOOTING, MADESHOT, SCORED } public enum MenuState { HOME, MODE, AWAITCONNECTION, ENTERIP, CONNECTING, PAUSE } public enum GameMode { PRACTICE, OFFLINE, ONLINE } }
// Python Tools for Visual Studio // 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.RegularExpressions; using Microsoft.PythonTools.Django.Analysis; using Microsoft.PythonTools.Interpreter; using Microsoft.VisualStudio.Language.Intellisense; namespace Microsoft.PythonTools.Django.TemplateParsing { /// <summary> /// Captures information about a Django template variable including the filter(s) and any arguments. /// /// For example for a variable such as {{ fob!oar }} we'll have a DjangoVariable() with an Expression /// which is of kind Variable for "fob" and a DjangoFilter with a filter name of oar. /// /// For {{ fob!oar:42 }} we will have the same thing but the filter will have an Arg of kind Number and /// the Value "42". Likewise for {{ fob!oar:'abc' }} the filter will have an Arg of kind Constant and /// a value 'abc'. /// </summary> class DjangoVariable { public readonly DjangoVariableValue Expression; public readonly int ExpressionStart; public readonly DjangoFilter[] Filters; const string _doubleQuotedString = @"""[^""\\]*(?:\\.[^""\\]*)*"""; const string _singleQuotedString = @"'[^'\\]*(?:\\.[^'\\]*)*'"; const string _numFormat = @"[-+\.]?\d[\d\.e]*"; const string _constStr = @" (?:_\(" + _doubleQuotedString + @"\)| _\(" + _singleQuotedString + @"\)| " + _doubleQuotedString + @"| " + _singleQuotedString + @")"; private static Regex _filterRegex = new Regex(@" ^(?<constant>" + _constStr + @")| ^(?<num>" + _numFormat + @")| ^(?<var>[\w\.]+)| (?:\| (?<filter_name>\w*) (?:\: (?: (?<constant_arg>" + _constStr + @")| (?<num_arg>" + _numFormat + @")| (?<var_arg>[\w\.]+) ) )? )", RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace); public DjangoVariable(DjangoVariableValue expression, int expressionStart, params DjangoFilter[] filters) { Expression = expression; ExpressionStart = expressionStart; Filters = filters; } public static DjangoVariable Variable(string expression, int expressionStart, params DjangoFilter[] filters) { return new DjangoVariable(new DjangoVariableValue(expression, DjangoVariableKind.Variable), expressionStart, filters); } public static DjangoVariable Constant(string expression, int expressionStart, params DjangoFilter[] filters) { return new DjangoVariable(new DjangoVariableValue(expression, DjangoVariableKind.Constant), expressionStart, filters); } public static DjangoVariable Number(string expression, int expressionStart, params DjangoFilter[] filters) { return new DjangoVariable(new DjangoVariableValue(expression, DjangoVariableKind.Number), expressionStart, filters); } public static DjangoVariable Parse(string filterText, int start = 0) { if (filterText.StartsWith("{{")) { filterText = GetTrimmedFilterText(filterText, ref start); if (filterText == null) { return null; } } else { int i = 0; while (i < filterText.Length && char.IsWhiteSpace(filterText[i])) { ++i; ++start; } if (i < filterText.Length) { filterText = filterText.Substring(i).TrimEnd(); } } int varStart = start; DjangoVariableValue variable = null; List<DjangoFilter> filters = new List<DjangoFilter>(); foreach (Match match in _filterRegex.Matches(filterText)) { if (variable == null) { var constantGroup = match.Groups["constant"]; if (constantGroup.Success) { varStart = constantGroup.Index; variable = new DjangoVariableValue(constantGroup.Value, DjangoVariableKind.Constant); } else { var varGroup = match.Groups["var"]; if (!varGroup.Success) { var numGroup = match.Groups["num"]; if (!numGroup.Success) { return null; } varStart = numGroup.Index; variable = new DjangoVariableValue(numGroup.Value, DjangoVariableKind.Number); } else { varStart = varGroup.Index; variable = new DjangoVariableValue(varGroup.Value, DjangoVariableKind.Variable); } } } else { filters.Add(GetFilterFromMatch(match, start)); } } return new DjangoVariable(variable, varStart + start, filters.ToArray()); } /// <summary> /// Gets the trimmed filter text and passes back the position in the buffer where the first /// character of the filter actually starts. /// </summary> internal static string GetTrimmedFilterText(string text, ref int start) { start = 0; string filterText = null; int? tmpStart = null; for (int i = 2; i < text.Length; i++) { if (!Char.IsWhiteSpace(text[i])) { tmpStart = start = i; break; } } if (tmpStart != null) { if (text.EndsWith("%}") || text.EndsWith("}}")) { for (int i = text.Length - 3; i >= tmpStart.Value; i--) { if (!Char.IsWhiteSpace(text[i])) { filterText = text.Substring(tmpStart.Value, i + 1 - tmpStart.Value); break; } } } else { // unterminated tag, see if we terminate at a new line for (int i = tmpStart.Value; i < text.Length; i++) { if (text[i] == '\r' || text[i] == '\n') { filterText = text.Substring(tmpStart.Value, i + 1 - tmpStart.Value); break; } } if (filterText == null) { filterText = text.Substring(tmpStart.Value); } } } return filterText; } private static DjangoFilter GetFilterFromMatch(Match match, int start) { var filterName = match.Groups["filter_name"]; if (!filterName.Success) { // TODO: Report error } var filterStart = filterName.Index; DjangoVariableValue arg = null; int argStart = 0; var constantGroup = match.Groups["constant_arg"]; if (constantGroup.Success) { arg = new DjangoVariableValue(constantGroup.Value, DjangoVariableKind.Constant); argStart = constantGroup.Index; } else { var varGroup = match.Groups["var_arg"]; if (varGroup.Success) { arg = new DjangoVariableValue(varGroup.Value, DjangoVariableKind.Variable); argStart = varGroup.Index; } else { var numGroup = match.Groups["num_arg"]; if (numGroup.Success) { arg = new DjangoVariableValue(numGroup.Value, DjangoVariableKind.Number); argStart = numGroup.Index; } } } return new DjangoFilter(filterName.Value, filterStart + start, arg, argStart + start); } public IEnumerable<CompletionInfo> GetCompletions(IDjangoCompletionContext context, int position) { if (Expression == null) { return CompletionInfo.ToCompletionInfo(context.Variables, StandardGlyphGroup.GlyphGroupField); } else if (position <= Expression.Value.Length + ExpressionStart) { if (position - ExpressionStart - 1 >= 0 && Expression.Value[position - ExpressionStart - 1] == '.') { // TODO: Handle multiple dots string varName = Expression.Value.Substring(0, Expression.Value.IndexOf('.')); // get the members of this variable return CompletionInfo.ToCompletionInfo(context.GetMembers(varName)); } else { return CompletionInfo.ToCompletionInfo(context.Variables, StandardGlyphGroup.GlyphGroupField); } } else if (Filters.Length > 0) { // we are triggering in the filter or arg area foreach (var curFilter in Filters) { if (position >= curFilter.FilterStart && position <= curFilter.FilterStart + curFilter.Filter.Length) { // it's in this filter area return CompletionInfo.ToCompletionInfo(context.Filters, StandardGlyphGroup.GlyphKeyword); } else if (curFilter.Arg != null && position >= curFilter.ArgStart && position < curFilter.ArgStart + curFilter.Arg.Value.Length) { // it's in this argument return CompletionInfo.ToCompletionInfo(context.Variables, StandardGlyphGroup.GlyphGroupField); } } if (String.IsNullOrWhiteSpace(Filters.Last().Filter)) { // last filter was blank, so provide filters return CompletionInfo.ToCompletionInfo(context.Filters, StandardGlyphGroup.GlyphKeyword); } else { // ... else, provide variables return CompletionInfo.ToCompletionInfo(context.Variables, StandardGlyphGroup.GlyphGroupField); } } return Enumerable.Empty<CompletionInfo>(); } public IEnumerable<BlockClassification> GetSpans() { if (Expression != null) { foreach (var span in Expression.GetSpans(ExpressionStart)) { yield return span; } } foreach (var filter in Filters) { foreach (var span in filter.GetSpans()) { yield return span; } } } } class CompletionInfo { public readonly string DisplayText; public readonly StandardGlyphGroup Glyph; public readonly string InsertionText; public readonly string Documentation; public CompletionInfo(string displayText, StandardGlyphGroup glyph, string insertionText = null, string documentation = null) { DisplayText = displayText; Glyph = glyph; InsertionText = insertionText ?? displayText; Documentation = documentation ?? ""; } internal static IEnumerable<CompletionInfo> ToCompletionInfo(IEnumerable<string> keys, StandardGlyphGroup glyph) { return keys.Select(key => new CompletionInfo(key, glyph, key)); } internal static IEnumerable<CompletionInfo> ToCompletionInfo(Dictionary<string, PythonMemberType> keys) { return keys.Select(kv => new CompletionInfo(kv.Key, kv.Value.ToGlyphGroup(), kv.Key)); } internal static IEnumerable<CompletionInfo> ToCompletionInfo(Dictionary<string, TagInfo> dictionary, StandardGlyphGroup glyph) { if (dictionary == null) { return Enumerable.Empty<CompletionInfo>(); } return dictionary.Select(key => new CompletionInfo( key.Key, glyph, key.Key, key.Value.Documentation )); } internal static IEnumerable<CompletionInfo> ToCompletionInfo<T>(Dictionary<string, T> dictionary, StandardGlyphGroup glyph) { if (dictionary == null) { return Enumerable.Empty<CompletionInfo>(); } return ToCompletionInfo(dictionary.Keys, glyph); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using DSharpPlus.Net; namespace DSharpPlus.Entities { /// <summary> /// Constructs embeds. /// </summary> public sealed class DiscordEmbedBuilder { /// <summary> /// Gets or sets the embed's title. /// </summary> public string Title { get => this._title; set { if (value != null && value.Length > 256) throw new ArgumentException("Title length cannot exceed 256 characters.", nameof(value)); this._title = value; } } private string _title; /// <summary> /// Gets or sets the embed's description. /// </summary> public string Description { get => this._description; set { if (value != null && value.Length > 2048) throw new ArgumentException("Description length cannot exceed 2048 characters.", nameof(value)); this._description = value; } } private string _description; /// <summary> /// Gets or sets the url for the embed's title. /// </summary> public string Url { get => this._url?.ToString(); set => this._url = string.IsNullOrEmpty(value) ? null : new Uri(value); } private Uri _url; /// <summary> /// Gets or sets the embed's color. /// </summary> public Optional<DiscordColor> Color { get; set; } /// <summary> /// Gets or sets the embed's timestamp. /// </summary> public DateTimeOffset? Timestamp { get; set; } /// <summary> /// Gets or sets the embed's image url. /// </summary> public string ImageUrl { get => this._imageUri?.ToString(); set => this._imageUri = string.IsNullOrEmpty(value) ? null : new DiscordUri(value); } private DiscordUri _imageUri; /// <summary> /// Gets or sets the thumbnail's image url. /// </summary> public string ThumbnailUrl { get => this._thumbnailUri?.ToString(); set => this._thumbnailUri = string.IsNullOrEmpty(value) ? null : new DiscordUri(value); } private DiscordUri _thumbnailUri; /// <summary> /// Gets the embed's author. /// </summary> public EmbedAuthor Author { get; set; } /// <summary> /// Gets the embed's footer. /// </summary> public EmbedFooter Footer { get; set; } /// <summary> /// Gets the embed's fields. /// </summary> public IReadOnlyList<DiscordEmbedField> Fields { get; } private readonly List<DiscordEmbedField> _fields = new List<DiscordEmbedField>(); /// <summary> /// Constructs a new empty embed builder. /// </summary> public DiscordEmbedBuilder() { this.Fields = new ReadOnlyCollection<DiscordEmbedField>(this._fields); } /// <summary> /// Constructs a new embed builder using another embed as prototype. /// </summary> /// <param name="original">Embed to use as prototype.</param> public DiscordEmbedBuilder(DiscordEmbed original) : this() { this.Title = original.Title; this.Description = original.Description; this.Url = original.Url?.ToString(); this.Color = original.Color; this.Timestamp = original.Timestamp; this.ThumbnailUrl = original.Thumbnail?.Url?.ToString(); if (original.Author != null) this.Author = new EmbedAuthor { IconUrl = original.Author.IconUrl?.ToString(), Name = original.Author.Name, Url = original.Author.Url?.ToString() }; if (original.Footer != null) this.Footer = new EmbedFooter { IconUrl = original.Footer.IconUrl?.ToString(), Text = original.Footer.Text }; if (original.Fields?.Any() == true) this._fields.AddRange(original.Fields); while (this._fields.Count > 25) this._fields.RemoveAt(this._fields.Count - 1); } /// <summary> /// Sets the embed's title. /// </summary> /// <param name="title">Title to set.</param> /// <returns>This embed builder.</returns> public DiscordEmbedBuilder WithTitle(string title) { this.Title = title; return this; } /// <summary> /// Sets the embed's description. /// </summary> /// <param name="description">Description to set.</param> /// <returns>This embed builder.</returns> public DiscordEmbedBuilder WithDescription(string description) { this.Description = description; return this; } /// <summary> /// Sets the embed's title url. /// </summary> /// <param name="url">Title url to set.</param> /// <returns>This embed builder.</returns> public DiscordEmbedBuilder WithUrl(string url) { this.Url = url; return this; } /// <summary> /// Sets the embed's title url. /// </summary> /// <param name="url">Title url to set.</param> /// <returns>This embed builder.</returns> public DiscordEmbedBuilder WithUrl(Uri url) { this._url = url; return this; } /// <summary> /// Sets the embed's color. /// </summary> /// <param name="color">Embed color to set.</param> /// <returns>This embed builder.</returns> public DiscordEmbedBuilder WithColor(DiscordColor color) { this.Color = color; return this; } /// <summary> /// Sets the embed's timestamp. /// </summary> /// <param name="timestamp">Timestamp to set.</param> /// <returns>This embed builder.</returns> public DiscordEmbedBuilder WithTimestamp(DateTimeOffset? timestamp) { this.Timestamp = timestamp; return this; } /// <summary> /// Sets the embed's timestamp. /// </summary> /// <param name="timestamp">Timestamp to set.</param> /// <returns>This embed builder.</returns> public DiscordEmbedBuilder WithTimestamp(DateTime? timestamp) { if (timestamp == null) this.Timestamp = null; else this.Timestamp = new DateTimeOffset(timestamp.Value); return this; } /// <summary> /// Sets the embed's timestamp based on a snowflake. /// </summary> /// <param name="snowflake">Snowflake to calculate timestamp from.</param> /// <returns>This embed builder.</returns> public DiscordEmbedBuilder WithTimestamp(ulong snowflake) { this.Timestamp = new DateTimeOffset(2015, 1, 1, 0, 0, 0, TimeSpan.Zero).AddMilliseconds(snowflake >> 22); return this; } /// <summary> /// Sets the embed's image url. /// </summary> /// <param name="url">Image url to set.</param> /// <returns>This embed builder.</returns> public DiscordEmbedBuilder WithImageUrl(string url) { this.ImageUrl = url; return this; } /// <summary> /// Sets the embed's image url. /// </summary> /// <param name="url">Image url to set.</param> /// <returns>This embed builder.</returns> public DiscordEmbedBuilder WithImageUrl(Uri url) { this._imageUri = new DiscordUri(url); return this; } /// <summary> /// Sets the embed's thumbnail url. /// </summary> /// <param name="url">Thumbnail url to set.</param> /// <returns>This embed builder.</returns> public DiscordEmbedBuilder WithThumbnailUrl(string url) { this.ThumbnailUrl = url; return this; } /// <summary> /// Sets the embed's thumbnail url. /// </summary> /// <param name="url">Thumbnail url to set.</param> /// <returns>This embed builder.</returns> public DiscordEmbedBuilder WithThumbnailUrl(Uri url) { this._thumbnailUri = new DiscordUri(url); return this; } /// <summary> /// Sets the embed's author. /// </summary> /// <param name="name">Author's name.</param> /// <param name="url">Author's url.</param> /// <param name="iconUrl">Author icon's url.</param> /// <returns>This embed builder.</returns> public DiscordEmbedBuilder WithAuthor(string name = null, string url = null, string iconUrl = null) { if (string.IsNullOrEmpty(name) && string.IsNullOrEmpty(url) && string.IsNullOrEmpty(iconUrl)) this.Author = null; else this.Author = new EmbedAuthor { Name = name, Url = url, IconUrl = iconUrl }; return this; } /// <summary> /// Sets the embed's footer. /// </summary> /// <param name="text">Footer's text.</param> /// <param name="iconUrl">Footer icon's url.</param> /// <returns>This embed builder.</returns> public DiscordEmbedBuilder WithFooter(string text = null, string iconUrl = null) { if (text != null && text.Length > 2048) throw new ArgumentException("Footer text length cannot exceed 2048 characters.", nameof(text)); if (string.IsNullOrEmpty(text) && string.IsNullOrEmpty(iconUrl)) this.Footer = null; else this.Footer = new EmbedFooter { Text = text, IconUrl = iconUrl }; return this; } /// <summary> /// Adds a field to this embed. /// </summary> /// <param name="name">Name of the field to add.</param> /// <param name="value">Value of the field to add.</param> /// <param name="inline">Whether the field is to be inline or not.</param> /// <returns>This embed builder.</returns> public DiscordEmbedBuilder AddField(string name, string value, bool inline = false) { if (string.IsNullOrWhiteSpace(name)) { if (name == null) throw new ArgumentNullException(nameof(name)); throw new ArgumentException("Name cannot be empty or whitespace.", nameof(name)); } if (string.IsNullOrWhiteSpace(value)) { if (value == null) throw new ArgumentNullException(nameof(value)); throw new ArgumentException("Value cannot be empty or whitespace.", nameof(value)); } if (name.Length > 256) throw new ArgumentException("Embed field name length cannot exceed 256 characters."); if (value.Length > 1024) throw new ArgumentException("Embed field value length cannot exceed 1024 characters."); if (this._fields.Count >= 25) throw new InvalidOperationException("Cannot add more than 25 fields."); this._fields.Add(new DiscordEmbedField { Inline = inline, Name = name, Value = value }); return this; } /// <summary> /// Removes all fields from this embed. /// </summary> /// <returns>This embed builder.</returns> public DiscordEmbedBuilder ClearFields() { this._fields.Clear(); return this; } /// <summary> /// Constructs a new embed from data supplied to this builder. /// </summary> /// <returns>New discord embed.</returns> public DiscordEmbed Build() { var embed = new DiscordEmbed { Title = this._title, Description = this._description, Url = this._url, _color = this.Color.IfPresent(e => e.Value), Timestamp = this.Timestamp }; if (this.Footer != null) embed.Footer = new DiscordEmbedFooter { Text = this.Footer.Text, IconUrl = this.Footer.IconUrl != null ? new DiscordUri(this.Footer.IconUrl) : null }; if (this.Author != null) embed.Author = new DiscordEmbedAuthor { Name = this.Author.Name, Url = this.Author.Url != null ? new Uri(this.Author.Url) : null, IconUrl = this.Author.IconUrl != null ? new DiscordUri(this.Author.IconUrl) : null }; if (this._imageUri != null) embed.Image = new DiscordEmbedImage { Url = this._imageUri }; if (this._thumbnailUri != null) embed.Thumbnail = new DiscordEmbedThumbnail { Url = this._thumbnailUri }; embed.Fields = new ReadOnlyCollection<DiscordEmbedField>(new List<DiscordEmbedField>(this._fields)); // copy the list, don't wrap it, prevents mutation return embed; } /// <summary> /// Implicitly converts this builder to an embed. /// </summary> /// <param name="builder">Builder to convert.</param> public static implicit operator DiscordEmbed(DiscordEmbedBuilder builder) => builder?.Build(); public class EmbedAuthor { /// <summary> /// Gets or sets the name of the author. /// </summary> public string Name { get => this._name; set { if (value != null && value.Length > 256) throw new ArgumentException("Author name length cannot exceed 256 characters.", nameof(value)); this._name = value; } } private string _name; /// <summary> /// Gets or sets the Url to which the author's link leads. /// </summary> public string Url { get => this._uri?.ToString(); set => this._uri = string.IsNullOrEmpty(value) ? null : new Uri(value); } private Uri _uri; /// <summary> /// Gets or sets the Author's icon url. /// </summary> public string IconUrl { get => this._iconUri?.ToString(); set => this._iconUri = string.IsNullOrEmpty(value) ? null : new DiscordUri(value); } private DiscordUri _iconUri; } public class EmbedFooter { /// <summary> /// Gets or sets the text of the footer. /// </summary> public string Text { get => this._text; set { if (value != null && value.Length > 2048) throw new ArgumentException("Footer text length cannot exceed 2048 characters.", nameof(value)); this._text = value; } } private string _text; /// <summary> /// Gets or sets the Url /// </summary> public string IconUrl { get => this._iconUri?.ToString(); set => this._iconUri = string.IsNullOrEmpty(value) ? null : new DiscordUri(value); } private DiscordUri _iconUri; } } }
/* * Qa full api * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: all * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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 NUnit.Framework; using System; using System.Linq; using System.IO; using System.Collections.Generic; using HostMe.Sdk.Api; using HostMe.Sdk.Model; using HostMe.Sdk.Client; using System.Reflection; namespace HostMe.Sdk.Test { /// <summary> /// Class for testing Booking /// </summary> /// <remarks> /// This file is automatically generated by Swagger Codegen. /// Please update the test case below to test the model. /// </remarks> [TestFixture] public class BookingTests { // TODO uncomment below to declare an instance variable for Booking //private Booking instance; /// <summary> /// Setup before each test /// </summary> [SetUp] public void Init() { // TODO uncomment below to create an instance of Booking //instance = new Booking(); } /// <summary> /// Clean up after each test /// </summary> [TearDown] public void Cleanup() { } /// <summary> /// Test an instance of Booking /// </summary> [Test] public void BookingInstanceTest() { // TODO uncomment below to test "IsInstanceOfType" Booking //Assert.IsInstanceOfType<Booking> (instance, "variable 'instance' is a Booking"); } /// <summary> /// Test the property 'Id' /// </summary> [Test] public void IdTest() { // TODO unit test for the property 'Id' } /// <summary> /// Test the property 'CustomerName' /// </summary> [Test] public void CustomerNameTest() { // TODO unit test for the property 'CustomerName' } /// <summary> /// Test the property 'Phone' /// </summary> [Test] public void PhoneTest() { // TODO unit test for the property 'Phone' } /// <summary> /// Test the property 'Status' /// </summary> [Test] public void StatusTest() { // TODO unit test for the property 'Status' } /// <summary> /// Test the property 'Areas' /// </summary> [Test] public void AreasTest() { // TODO unit test for the property 'Areas' } /// <summary> /// Test the property 'InternalNotes' /// </summary> [Test] public void InternalNotesTest() { // TODO unit test for the property 'InternalNotes' } /// <summary> /// Test the property 'SpecialRequests' /// </summary> [Test] public void SpecialRequestsTest() { // TODO unit test for the property 'SpecialRequests' } /// <summary> /// Test the property 'AboutGuestNotes' /// </summary> [Test] public void AboutGuestNotesTest() { // TODO unit test for the property 'AboutGuestNotes' } /// <summary> /// Test the property 'DepositStatus' /// </summary> [Test] public void DepositStatusTest() { // TODO unit test for the property 'DepositStatus' } /// <summary> /// Test the property 'TableNumber' /// </summary> [Test] public void TableNumberTest() { // TODO unit test for the property 'TableNumber' } /// <summary> /// Test the property 'Email' /// </summary> [Test] public void EmailTest() { // TODO unit test for the property 'Email' } /// <summary> /// Test the property 'Source' /// </summary> [Test] public void SourceTest() { // TODO unit test for the property 'Source' } /// <summary> /// Test the property 'Type' /// </summary> [Test] public void TypeTest() { // TODO unit test for the property 'Type' } /// <summary> /// Test the property 'Created' /// </summary> [Test] public void CreatedTest() { // TODO unit test for the property 'Created' } /// <summary> /// Test the property 'Closed' /// </summary> [Test] public void ClosedTest() { // TODO unit test for the property 'Closed' } /// <summary> /// Test the property 'ReservationTime' /// </summary> [Test] public void ReservationTimeTest() { // TODO unit test for the property 'ReservationTime' } /// <summary> /// Test the property 'ExpectedTime' /// </summary> [Test] public void ExpectedTimeTest() { // TODO unit test for the property 'ExpectedTime' } /// <summary> /// Test the property 'StatusTime' /// </summary> [Test] public void StatusTimeTest() { // TODO unit test for the property 'StatusTime' } /// <summary> /// Test the property 'EstimatedReleaseTime' /// </summary> [Test] public void EstimatedReleaseTimeTest() { // TODO unit test for the property 'EstimatedReleaseTime' } /// <summary> /// Test the property 'RegistrationTime' /// </summary> [Test] public void RegistrationTimeTest() { // TODO unit test for the property 'RegistrationTime' } /// <summary> /// Test the property 'GroupSize' /// </summary> [Test] public void GroupSizeTest() { // TODO unit test for the property 'GroupSize' } /// <summary> /// Test the property 'UnreadMessageCount' /// </summary> [Test] public void UnreadMessageCountTest() { // TODO unit test for the property 'UnreadMessageCount' } /// <summary> /// Test the property 'Amount' /// </summary> [Test] public void AmountTest() { // TODO unit test for the property 'Amount' } /// <summary> /// Test the property 'CardAttached' /// </summary> [Test] public void CardAttachedTest() { // TODO unit test for the property 'CardAttached' } /// <summary> /// Test the property 'Membership' /// </summary> [Test] public void MembershipTest() { // TODO unit test for the property 'Membership' } /// <summary> /// Test the property 'HighChair' /// </summary> [Test] public void HighChairTest() { // TODO unit test for the property 'HighChair' } /// <summary> /// Test the property 'Stroller' /// </summary> [Test] public void StrollerTest() { // TODO unit test for the property 'Stroller' } /// <summary> /// Test the property 'Booth' /// </summary> [Test] public void BoothTest() { // TODO unit test for the property 'Booth' } /// <summary> /// Test the property 'HighTop' /// </summary> [Test] public void HighTopTest() { // TODO unit test for the property 'HighTop' } /// <summary> /// Test the property 'Table' /// </summary> [Test] public void TableTest() { // TODO unit test for the property 'Table' } /// <summary> /// Test the property 'Party' /// </summary> [Test] public void PartyTest() { // TODO unit test for the property 'Party' } /// <summary> /// Test the property 'PartyTypes' /// </summary> [Test] public void PartyTypesTest() { // TODO unit test for the property 'PartyTypes' } /// <summary> /// Test the property 'CustomerProfile' /// </summary> [Test] public void CustomerProfileTest() { // TODO unit test for the property 'CustomerProfile' } /// <summary> /// Test the property 'EstimatedTurnOverTime' /// </summary> [Test] public void EstimatedTurnOverTimeTest() { // TODO unit test for the property 'EstimatedTurnOverTime' } } }
using System; using UnityEngine; namespace UnityStandardAssets.CinematicEffects { [ExecuteInEditMode] [RequireComponent(typeof(Camera))] [AddComponentMenu("Image Effects/Rendering/Screen Space Reflection")] public class ScreenSpaceReflection : MonoBehaviour { public enum SSRDebugMode { None = 0, IncomingRadiance = 1, SSRResult = 2, FinalGlossyTerm = 3, SSRMask = 4, Roughness = 5, BaseColor = 6, SpecColor = 7, Reflectivity = 8, ReflectionProbeOnly = 9, ReflectionProbeMinusSSR = 10, SSRMinusReflectionProbe = 11, NoGlossy = 12, NegativeNoGlossy = 13, MipLevel = 14, } public enum SSRResolution { FullResolution = 0, HalfTraceFullResolve = 1, HalfResolution = 2, } [Serializable] public struct SSRSettings { [AttributeUsage(AttributeTargets.Field)] public class LayoutAttribute : PropertyAttribute {} [Layout] public BasicSettings basicSettings; [Layout] public ReflectionSettings reflectionSettings; [Layout] public AdvancedSettings advancedSettings; [Layout] public DebugSettings debugSettings; private static readonly SSRSettings s_Performance = new SSRSettings { basicSettings = new BasicSettings { screenEdgeFading = 0, maxDistance = 10.0f, fadeDistance = 10.0f, reflectionMultiplier = 1.0f, enableHDR = false, additiveReflection = false }, reflectionSettings = new ReflectionSettings { maxSteps = 64, rayStepSize = 4, widthModifier = 0.5f, smoothFallbackThreshold = 0.4f, distanceBlur = 1.0f, fresnelFade = 0.2f, fresnelFadePower = 2.0f, smoothFallbackDistance = 0.05f, }, advancedSettings = new AdvancedSettings { useTemporalConfidence = false, temporalFilterStrength = 0.0f, treatBackfaceHitAsMiss = false, allowBackwardsRays = false, traceBehindObjects = true, highQualitySharpReflections = false, traceEverywhere = false, resolution = SSRResolution.HalfResolution, bilateralUpsample = false, improveCorners = false, reduceBanding = false, highlightSuppression = false }, debugSettings = new DebugSettings { debugMode = SSRDebugMode.None } }; private static readonly SSRSettings s_Default = new SSRSettings { basicSettings = new BasicSettings { screenEdgeFading = 0.03f, maxDistance = 100.0f, fadeDistance = 100.0f, reflectionMultiplier = 1.0f, enableHDR = true, additiveReflection = false, }, reflectionSettings = new ReflectionSettings { maxSteps = 128, rayStepSize = 3, widthModifier = 0.5f, smoothFallbackThreshold = 0.2f, distanceBlur = 1.0f, fresnelFade = 0.2f, fresnelFadePower = 2.0f, smoothFallbackDistance = 0.05f, }, advancedSettings = new AdvancedSettings { useTemporalConfidence = true, temporalFilterStrength = 0.7f, treatBackfaceHitAsMiss = false, allowBackwardsRays = false, traceBehindObjects = true, highQualitySharpReflections = true, traceEverywhere = true, resolution = SSRResolution.HalfTraceFullResolve, bilateralUpsample = true, improveCorners = true, reduceBanding = true, highlightSuppression = false }, debugSettings = new DebugSettings { debugMode = SSRDebugMode.None } }; private static readonly SSRSettings s_HighQuality = new SSRSettings { basicSettings = new BasicSettings { screenEdgeFading = 0.03f, maxDistance = 100.0f, fadeDistance = 100.0f, reflectionMultiplier = 1.0f, enableHDR = true, additiveReflection = false, }, reflectionSettings = new ReflectionSettings { maxSteps = 512, rayStepSize = 1, widthModifier = 0.5f, smoothFallbackThreshold = 0.2f, distanceBlur = 1.0f, fresnelFade = 0.2f, fresnelFadePower = 2.0f, smoothFallbackDistance = 0.05f, }, advancedSettings = new AdvancedSettings { useTemporalConfidence = true, temporalFilterStrength = 0.7f, treatBackfaceHitAsMiss = false, allowBackwardsRays = false, traceBehindObjects = true, highQualitySharpReflections = true, traceEverywhere = true, resolution = SSRResolution.HalfTraceFullResolve, bilateralUpsample = true, improveCorners = true, reduceBanding = true, highlightSuppression = false }, debugSettings = new DebugSettings { debugMode = SSRDebugMode.None } }; public static SSRSettings performanceSettings { get { return s_Performance; } } public static SSRSettings defaultSettings { get { return s_Default; } } public static SSRSettings highQualitySettings { get { return s_HighQuality; } } } [Serializable] public struct BasicSettings { /// BASIC SETTINGS [Tooltip("Nonphysical multiplier for the SSR reflections. 1.0 is physically based.")] [Range(0.0f, 2.0f)] public float reflectionMultiplier; [Tooltip("Maximum reflection distance in world units.")] [Range(0.5f, 1000.0f)] public float maxDistance; [Tooltip("How far away from the maxDistance to begin fading SSR.")] [Range(0.0f, 1000.0f)] public float fadeDistance; [Tooltip("Higher = fade out SSRR near the edge of the screen so that reflections don't pop under camera motion.")] [Range(0.0f, 1.0f)] public float screenEdgeFading; [Tooltip("Enable for better reflections of very bright objects at a performance cost")] public bool enableHDR; // When enabled, we just add our reflections on top of the existing ones. This is physically incorrect, but several // popular demos and games have taken this approach, and it does hide some artifacts. [Tooltip("Add reflections on top of existing ones. Not physically correct.")] public bool additiveReflection; } [Serializable] public struct ReflectionSettings { /// REFLECTIONS [Tooltip("Max raytracing length.")] [Range(16, 2048)] public int maxSteps; [Tooltip("Log base 2 of ray tracing coarse step size. Higher traces farther, lower gives better quality silhouettes.")] [Range(0, 4)] public int rayStepSize; [Tooltip("Typical thickness of columns, walls, furniture, and other objects that reflection rays might pass behind.")] [Range(0.01f, 10.0f)] public float widthModifier; [Tooltip("Increase if reflections flicker on very rough surfaces.")] [Range(0.0f, 1.0f)] public float smoothFallbackThreshold; [Tooltip("Start falling back to non-SSR value solution at smoothFallbackThreshold - smoothFallbackDistance, with full fallback occuring at smoothFallbackThreshold.")] [Range(0.0f, 0.2f)] public float smoothFallbackDistance; [Tooltip("Amplify Fresnel fade out. Increase if floor reflections look good close to the surface and bad farther 'under' the floor.")] [Range(0.0f, 1.0f)] public float fresnelFade; [Tooltip("Higher values correspond to a faster Fresnel fade as the reflection changes from the grazing angle.")] [Range(0.1f, 10.0f)] public float fresnelFadePower; [Tooltip("Controls how blurry reflections get as objects are further from the camera. 0 is constant blur no matter trace distance or distance from camera. 1 fully takes into account both factors.")] [Range(0.0f, 1.0f)] public float distanceBlur; } [Serializable] public struct AdvancedSettings { /// ADVANCED [Range(0.0f, 0.99f)] [Tooltip("Increase to decrease flicker in scenes; decrease to prevent ghosting (especially in dynamic scenes). 0 gives maximum performance.")] public float temporalFilterStrength; [Tooltip("Enable to limit ghosting from applying the temporal filter.")] public bool useTemporalConfidence; [Tooltip("Enable to allow rays to pass behind objects. This can lead to more screen-space reflections, but the reflections are more likely to be wrong.")] public bool traceBehindObjects; [Tooltip("Enable to increase quality of the sharpest reflections (through filtering), at a performance cost.")] public bool highQualitySharpReflections; [Tooltip("Improves quality in scenes with varying smoothness, at a potential performance cost.")] public bool traceEverywhere; [Tooltip("Enable to force more surfaces to use reflection probes if you see streaks on the sides of objects or bad reflections of their backs.")] public bool treatBackfaceHitAsMiss; [Tooltip("Enable for a performance gain in scenes where most glossy objects are horizontal, like floors, water, and tables. Leave on for scenes with glossy vertical objects.")] public bool allowBackwardsRays; [Tooltip("Improve visual fidelity of reflections on rough surfaces near corners in the scene, at the cost of a small amount of performance.")] public bool improveCorners; [Tooltip("Half resolution SSRR is much faster, but less accurate. Quality can be reclaimed for some performance by doing the resolve at full resolution.")] public SSRResolution resolution; [Tooltip("Drastically improves reflection reconstruction quality at the expense of some performance.")] public bool bilateralUpsample; [Tooltip("Improve visual fidelity of mirror reflections at the cost of a small amount of performance.")] public bool reduceBanding; [Tooltip("Enable to limit the effect a few bright pixels can have on rougher surfaces")] public bool highlightSuppression; } [Serializable] public struct DebugSettings { /// DEBUG [Tooltip("Various Debug Visualizations")] public SSRDebugMode debugMode; } [SerializeField] public SSRSettings settings = SSRSettings.defaultSettings; ///////////// Unexposed Variables ////////////////// // Perf optimization we still need to test across platforms [Tooltip("Enable to try and bypass expensive bilateral upsampling away from edges. There is a slight performance hit for generating the edge buffers, but a potentially high performance savings from bypassing bilateral upsampling where it is unneeded. Test on your target platforms to see if performance improves.")] private bool useEdgeDetector = false; // Debug variable, useful for forcing all surfaces in a scene to reflection with arbitrary sharpness/roughness [Range(-4.0f, 4.0f)] private float mipBias = 0.0f; // Flag for whether to knock down the reflection term by occlusion stored in the gbuffer. Currently consistently gives // better results when true, so this flag is private for now. private bool useOcclusion = true; // When enabled, all filtering is performed at the highest resolution. This is extraordinarily slow, and should only be used during development. private bool fullResolutionFiltering = false; // Crude sky fallback, feature-gated until next revision private bool fallbackToSky = false; // For next release; will improve quality at the expense of performance private bool computeAverageRayDistance = false; // Internal values for temporal filtering private bool m_HasInformationFromPreviousFrame; private Matrix4x4 m_PreviousWorldToCameraMatrix; private RenderTexture m_PreviousDepthBuffer; private RenderTexture m_PreviousHitBuffer; private RenderTexture m_PreviousReflectionBuffer; public Shader ssrShader; private Material m_SSRMaterial; [NonSerialized] private RenderTexureUtility m_RTU = new RenderTexureUtility(); public Material ssrMaterial { get { if (m_SSRMaterial == null) m_SSRMaterial = ImageEffectHelper.CheckShaderAndCreateMaterial(ssrShader); return m_SSRMaterial; } } // Shader pass indices used by the effect private enum PassIndex { RayTraceStep1 = 0, RayTraceStep2 = 1, RayTraceStep4 = 2, RayTraceStep8 = 3, RayTraceStep16 = 4, CompositeFinal = 5, Blur = 6, CompositeSSR = 7, Blit = 8, EdgeGeneration = 9, MinMipGeneration = 10, HitPointToReflections = 11, BilateralKeyPack = 12, BlitDepthAsCSZ = 13, TemporalFilter = 14, AverageRayDistanceGeneration = 15, PoissonBlur = 16, } protected void OnEnable() { if (ssrShader == null) ssrShader = Shader.Find("Hidden/ScreenSpaceReflection"); if (!ImageEffectHelper.IsSupported(ssrShader, true, true, this)) { enabled = false; Debug.LogWarning("The image effect " + ToString() + " has been disabled as it's not supported on the current platform."); return; } GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth; } void OnDisable() { if (m_SSRMaterial) DestroyImmediate(m_SSRMaterial); if (m_PreviousDepthBuffer) DestroyImmediate(m_PreviousDepthBuffer); if (m_PreviousHitBuffer) DestroyImmediate(m_PreviousHitBuffer); if (m_PreviousReflectionBuffer) DestroyImmediate(m_PreviousReflectionBuffer); m_SSRMaterial = null; m_PreviousDepthBuffer = null; m_PreviousHitBuffer = null; m_PreviousReflectionBuffer = null; } private void PreparePreviousBuffers(int w, int h) { if (m_PreviousDepthBuffer != null) { if ((m_PreviousDepthBuffer.width != w) || (m_PreviousDepthBuffer.height != h)) { DestroyImmediate(m_PreviousDepthBuffer); DestroyImmediate(m_PreviousHitBuffer); DestroyImmediate(m_PreviousReflectionBuffer); m_PreviousDepthBuffer = null; m_PreviousHitBuffer = null; m_PreviousReflectionBuffer = null; } } if (m_PreviousDepthBuffer == null) { m_PreviousDepthBuffer = new RenderTexture(w, h, 0, RenderTextureFormat.RFloat); m_PreviousHitBuffer = new RenderTexture(w, h, 0, RenderTextureFormat.ARGBHalf); m_PreviousReflectionBuffer = new RenderTexture(w, h, 0, RenderTextureFormat.ARGBHalf); } } [ImageEffectOpaque] public void OnRenderImage(RenderTexture source, RenderTexture destination) { if (ssrMaterial == null) { Graphics.Blit(source, destination); return; } if (m_HasInformationFromPreviousFrame) { m_HasInformationFromPreviousFrame = (m_PreviousDepthBuffer != null) && (source.width == m_PreviousDepthBuffer.width) && (source.height == m_PreviousDepthBuffer.height); } bool doTemporalFilterThisFrame = m_HasInformationFromPreviousFrame && settings.advancedSettings.temporalFilterStrength > 0.0; m_HasInformationFromPreviousFrame = false; // Not using deferred shading? Just blit source to destination. if (Camera.current.actualRenderingPath != RenderingPath.DeferredShading) { Graphics.Blit(source, destination); return; } var rtW = source.width; var rtH = source.height; // RGB: Normals, A: Roughness. // Has the nice benefit of allowing us to control the filtering mode as well. RenderTexture bilateralKeyTexture = m_RTU.GetTemporaryRenderTexture(rtW, rtH, 0, RenderTextureFormat.ARGB32); bilateralKeyTexture.filterMode = FilterMode.Point; Graphics.Blit(source, bilateralKeyTexture, ssrMaterial, (int)PassIndex.BilateralKeyPack); ssrMaterial.SetTexture("_NormalAndRoughnessTexture", bilateralKeyTexture); float sWidth = source.width; float sHeight = source.height; Vector2 sourceToTempUV = new Vector2(sWidth / rtW, sHeight / rtH); int downsampleAmount = (settings.advancedSettings.resolution == SSRResolution.FullResolution) ? 1 : 2; rtW = rtW / downsampleAmount; rtH = rtH / downsampleAmount; ssrMaterial.SetVector("_SourceToTempUV", new Vector4(sourceToTempUV.x, sourceToTempUV.y, 1.0f / sourceToTempUV.x, 1.0f / sourceToTempUV.y)); Matrix4x4 P = GetComponent<Camera>().projectionMatrix; Vector4 projInfo = new Vector4 ((-2.0f / (sWidth * P[0])), (-2.0f / (sHeight * P[5])), ((1.0f - P[2]) / P[0]), ((1.0f + P[6]) / P[5])); /** The height in pixels of a 1m object if viewed from 1m away. */ float pixelsPerMeterAtOneMeter = sWidth / (-2.0f * (float)(Math.Tan(GetComponent<Camera>().fieldOfView / 180.0 * Math.PI * 0.5))); ssrMaterial.SetFloat("_PixelsPerMeterAtOneMeter", pixelsPerMeterAtOneMeter); float sx = sWidth / 2.0f; float sy = sHeight / 2.0f; Matrix4x4 warpToScreenSpaceMatrix = new Matrix4x4(); warpToScreenSpaceMatrix.SetRow(0, new Vector4(sx, 0.0f, 0.0f, sx)); warpToScreenSpaceMatrix.SetRow(1, new Vector4(0.0f, sy, 0.0f, sy)); warpToScreenSpaceMatrix.SetRow(2, new Vector4(0.0f, 0.0f, 1.0f, 0.0f)); warpToScreenSpaceMatrix.SetRow(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); Matrix4x4 projectToPixelMatrix = warpToScreenSpaceMatrix * P; ssrMaterial.SetVector("_ScreenSize", new Vector2(sWidth, sHeight)); ssrMaterial.SetVector("_ReflectionBufferSize", new Vector2(rtW, rtH)); Vector2 invScreenSize = new Vector2((float)(1.0 / sWidth), (float)(1.0 / sHeight)); Matrix4x4 worldToCameraMatrix = GetComponent<Camera>().worldToCameraMatrix; Matrix4x4 cameraToWorldMatrix = GetComponent<Camera>().worldToCameraMatrix.inverse; ssrMaterial.SetVector("_InvScreenSize", invScreenSize); ssrMaterial.SetVector("_ProjInfo", projInfo); // used for unprojection ssrMaterial.SetMatrix("_ProjectToPixelMatrix", projectToPixelMatrix); ssrMaterial.SetMatrix("_WorldToCameraMatrix", worldToCameraMatrix); ssrMaterial.SetMatrix("_CameraToWorldMatrix", cameraToWorldMatrix); ssrMaterial.SetInt("_EnableRefine", settings.advancedSettings.reduceBanding ? 1 : 0); ssrMaterial.SetInt("_AdditiveReflection", settings.basicSettings.additiveReflection ? 1 : 0); ssrMaterial.SetInt("_ImproveCorners", settings.advancedSettings.improveCorners ? 1 : 0); ssrMaterial.SetFloat("_ScreenEdgeFading", settings.basicSettings.screenEdgeFading); ssrMaterial.SetFloat("_MipBias", mipBias); ssrMaterial.SetInt("_UseOcclusion", useOcclusion ? 1 : 0); ssrMaterial.SetInt("_BilateralUpsampling", settings.advancedSettings.bilateralUpsample ? 1 : 0); ssrMaterial.SetInt("_FallbackToSky", fallbackToSky ? 1 : 0); ssrMaterial.SetInt("_TreatBackfaceHitAsMiss", settings.advancedSettings.treatBackfaceHitAsMiss ? 1 : 0); ssrMaterial.SetInt("_AllowBackwardsRays", settings.advancedSettings.allowBackwardsRays ? 1 : 0); ssrMaterial.SetInt("_TraceEverywhere", settings.advancedSettings.traceEverywhere ? 1 : 0); float z_f = GetComponent<Camera>().farClipPlane; float z_n = GetComponent<Camera>().nearClipPlane; Vector3 cameraClipInfo = (float.IsPositiveInfinity(z_f)) ? new Vector3(z_n, -1.0f, 1.0f) : new Vector3(z_n * z_f, z_n - z_f, z_f); ssrMaterial.SetVector("_CameraClipInfo", cameraClipInfo); ssrMaterial.SetFloat("_MaxRayTraceDistance", settings.basicSettings.maxDistance); ssrMaterial.SetFloat("_FadeDistance", settings.basicSettings.fadeDistance); ssrMaterial.SetFloat("_LayerThickness", settings.reflectionSettings.widthModifier); const int maxMip = 5; RenderTexture[] reflectionBuffers; RenderTextureFormat intermediateFormat = settings.basicSettings.enableHDR ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32; reflectionBuffers = new RenderTexture[maxMip]; for (int i = 0; i < maxMip; ++i) { if (fullResolutionFiltering) reflectionBuffers[i] = m_RTU.GetTemporaryRenderTexture(rtW, rtH, 0, intermediateFormat); else reflectionBuffers[i] = m_RTU.GetTemporaryRenderTexture(rtW >> i, rtH >> i, 0, intermediateFormat); // We explicitly interpolate during bilateral upsampling. reflectionBuffers[i].filterMode = settings.advancedSettings.bilateralUpsample ? FilterMode.Point : FilterMode.Bilinear; } ssrMaterial.SetInt("_EnableSSR", 1); ssrMaterial.SetInt("_DebugMode", (int)settings.debugSettings.debugMode); ssrMaterial.SetInt("_TraceBehindObjects", settings.advancedSettings.traceBehindObjects ? 1 : 0); ssrMaterial.SetInt("_MaxSteps", settings.reflectionSettings.maxSteps); RenderTexture rayHitTexture = m_RTU.GetTemporaryRenderTexture(rtW, rtH); // We have 5 passes for different step sizes int tracePass = Mathf.Clamp(settings.reflectionSettings.rayStepSize, 0, 4); Graphics.Blit(source, rayHitTexture, ssrMaterial, tracePass); ssrMaterial.SetTexture("_HitPointTexture", rayHitTexture); // Resolve the hitpoints into the mirror reflection buffer Graphics.Blit(source, reflectionBuffers[0], ssrMaterial, (int)PassIndex.HitPointToReflections); ssrMaterial.SetTexture("_ReflectionTexture0", reflectionBuffers[0]); ssrMaterial.SetInt("_FullResolutionFiltering", fullResolutionFiltering ? 1 : 0); ssrMaterial.SetFloat("_MaxRoughness", 1.0f - settings.reflectionSettings.smoothFallbackThreshold); ssrMaterial.SetFloat("_RoughnessFalloffRange", settings.reflectionSettings.smoothFallbackDistance); ssrMaterial.SetFloat("_SSRMultiplier", settings.basicSettings.reflectionMultiplier); RenderTexture[] edgeTextures = new RenderTexture[maxMip]; if (settings.advancedSettings.bilateralUpsample && useEdgeDetector) { edgeTextures[0] = m_RTU.GetTemporaryRenderTexture(rtW, rtH); Graphics.Blit(source, edgeTextures[0], ssrMaterial, (int)PassIndex.EdgeGeneration); for (int i = 1; i < maxMip; ++i) { edgeTextures[i] = m_RTU.GetTemporaryRenderTexture(rtW >> i, rtH >> i); ssrMaterial.SetInt("_LastMip", i - 1); Graphics.Blit(edgeTextures[i - 1], edgeTextures[i], ssrMaterial, (int)PassIndex.MinMipGeneration); } } if (settings.advancedSettings.highQualitySharpReflections) { RenderTexture filteredReflections = m_RTU.GetTemporaryRenderTexture(reflectionBuffers[0].width, reflectionBuffers[0].height, 0, reflectionBuffers[0].format); filteredReflections.filterMode = reflectionBuffers[0].filterMode; reflectionBuffers[0].filterMode = FilterMode.Bilinear; Graphics.Blit(reflectionBuffers[0], filteredReflections, ssrMaterial, (int)PassIndex.PoissonBlur); // Replace the unfiltered buffer with the newly filtered one. m_RTU.ReleaseTemporaryRenderTexture(reflectionBuffers[0]); reflectionBuffers[0] = filteredReflections; ssrMaterial.SetTexture("_ReflectionTexture0", reflectionBuffers[0]); } // Generate the blurred low-resolution buffers for (int i = 1; i < maxMip; ++i) { RenderTexture inputTex = reflectionBuffers[i - 1]; RenderTexture hBlur; if (fullResolutionFiltering) hBlur = m_RTU.GetTemporaryRenderTexture(rtW, rtH, 0, intermediateFormat); else { int lowMip = i; hBlur = m_RTU.GetTemporaryRenderTexture(rtW >> lowMip, rtH >> (i - 1), 0, intermediateFormat); } for (int j = 0; j < (fullResolutionFiltering ? (i * i) : 1); ++j) { // Currently we blur at the resolution of the previous mip level, we could save bandwidth by blurring directly to the lower resolution. ssrMaterial.SetVector("_Axis", new Vector4(1.0f, 0.0f, 0.0f, 0.0f)); ssrMaterial.SetFloat("_CurrentMipLevel", i - 1.0f); Graphics.Blit(inputTex, hBlur, ssrMaterial, (int)PassIndex.Blur); ssrMaterial.SetVector("_Axis", new Vector4(0.0f, 1.0f, 0.0f, 0.0f)); inputTex = reflectionBuffers[i]; Graphics.Blit(hBlur, inputTex, ssrMaterial, (int)PassIndex.Blur); } ssrMaterial.SetTexture("_ReflectionTexture" + i, reflectionBuffers[i]); m_RTU.ReleaseTemporaryRenderTexture(hBlur); } if (settings.advancedSettings.bilateralUpsample && useEdgeDetector) { for (int i = 0; i < maxMip; ++i) ssrMaterial.SetTexture("_EdgeTexture" + i, edgeTextures[i]); } ssrMaterial.SetInt("_UseEdgeDetector", useEdgeDetector ? 1 : 0); RenderTexture averageRayDistanceBuffer = m_RTU.GetTemporaryRenderTexture(source.width, source.height, 0, RenderTextureFormat.RHalf); if (computeAverageRayDistance) { Graphics.Blit(source, averageRayDistanceBuffer, ssrMaterial, (int)PassIndex.AverageRayDistanceGeneration); } ssrMaterial.SetInt("_UseAverageRayDistance", computeAverageRayDistance ? 1 : 0); ssrMaterial.SetTexture("_AverageRayDistanceBuffer", averageRayDistanceBuffer); bool resolveDiffersFromTraceRes = (settings.advancedSettings.resolution == SSRResolution.HalfTraceFullResolve); RenderTexture finalReflectionBuffer = m_RTU.GetTemporaryRenderTexture(resolveDiffersFromTraceRes ? source.width : rtW, resolveDiffersFromTraceRes ? source.height : rtH, 0, intermediateFormat); ssrMaterial.SetFloat("_FresnelFade", settings.reflectionSettings.fresnelFade); ssrMaterial.SetFloat("_FresnelFadePower", settings.reflectionSettings.fresnelFadePower); ssrMaterial.SetFloat("_DistanceBlur", settings.reflectionSettings.distanceBlur); ssrMaterial.SetInt("_HalfResolution", (settings.advancedSettings.resolution != SSRResolution.FullResolution) ? 1 : 0); ssrMaterial.SetInt("_HighlightSuppression", settings.advancedSettings.highlightSuppression ? 1 : 0); Graphics.Blit(reflectionBuffers[0], finalReflectionBuffer, ssrMaterial, (int)PassIndex.CompositeSSR); ssrMaterial.SetTexture("_FinalReflectionTexture", finalReflectionBuffer); RenderTexture temporallyFilteredBuffer = m_RTU.GetTemporaryRenderTexture(resolveDiffersFromTraceRes ? source.width : rtW, resolveDiffersFromTraceRes ? source.height : rtH, 0, intermediateFormat); if (doTemporalFilterThisFrame) { ssrMaterial.SetInt("_UseTemporalConfidence", settings.advancedSettings.useTemporalConfidence ? 1 : 0); ssrMaterial.SetFloat("_TemporalAlpha", settings.advancedSettings.temporalFilterStrength); ssrMaterial.SetMatrix("_CurrentCameraToPreviousCamera", m_PreviousWorldToCameraMatrix * cameraToWorldMatrix); ssrMaterial.SetTexture("_PreviousReflectionTexture", m_PreviousReflectionBuffer); ssrMaterial.SetTexture("_PreviousCSZBuffer", m_PreviousDepthBuffer); Graphics.Blit(source, temporallyFilteredBuffer, ssrMaterial, (int)PassIndex.TemporalFilter); ssrMaterial.SetTexture("_FinalReflectionTexture", temporallyFilteredBuffer); } if (settings.advancedSettings.temporalFilterStrength > 0.0) { m_PreviousWorldToCameraMatrix = worldToCameraMatrix; PreparePreviousBuffers(source.width, source.height); Graphics.Blit(source, m_PreviousDepthBuffer, ssrMaterial, (int)PassIndex.BlitDepthAsCSZ); Graphics.Blit(rayHitTexture, m_PreviousHitBuffer); Graphics.Blit(doTemporalFilterThisFrame ? temporallyFilteredBuffer : finalReflectionBuffer, m_PreviousReflectionBuffer); m_HasInformationFromPreviousFrame = true; } Graphics.Blit(source, destination, ssrMaterial, (int)PassIndex.CompositeFinal); m_RTU.ReleaseAllTemporyRenderTexutres(); } } }
// 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.Diagnostics; using System.Net; using Microsoft.Protocols.TestTools.StackSdk.Security.KerberosLib.Types; using Microsoft.Protocols.TestTools.StackSdk.Transport; namespace Microsoft.Protocols.TestTools.StackSdk.Security.KerberosLib { public class KpasswdClient : KerberosRole { #region members private TransportStack kdcTransport; private Type expectedPduType; protected string kdcAddress; protected int kdcPort; protected TransportType transportType; #endregion members /// <summary> /// Contains all the important state variables in the context. /// </summary> public override KerberosContext Context { get; set; } /// <summary> /// A boolean value indicating whether KDC Proxy is used. /// </summary> public bool UseProxy { get; set; } /// <summary> /// KDC Proxy client used to send and receive proxy messages. /// It is used when UseProxy is TRUE. /// </summary> public KKDCPClient ProxyClient { get; set; } /// <summary> /// Create a Kpassword client instance /// </summary> /// <param name="kdcAddress">The IP address of the KDC.</param> /// <param name="kdcPort">The port of the KDC.</param> /// <param name="transportType">Whether the transport is TCP or UDP transport.</param> public KpasswdClient(string kdcAddress, int kdcPort, TransportType transportType) { this.Context = new KerberosContext(); this.kdcAddress = kdcAddress; this.kdcPort = kdcPort; this.transportType = transportType; } #region Connection with KDC /// <summary> /// Set up the TCP/UDP transport connection with KDC. /// </summary> /// <exception cref="System.ArgumentException">Thrown when the connection type is neither TCP nor UDP</exception> public virtual void Connect() { SocketTransportConfig transportConfig = new SocketTransportConfig(); transportConfig.Role = Role.Client; transportConfig.MaxConnections = 1; transportConfig.BufferSize = KerberosConstValue.TRANSPORT_BUFFER_SIZE; transportConfig.RemoteIpPort = kdcPort; transportConfig.RemoteIpAddress = IPAddress.Parse(kdcAddress); // For UDP bind if (transportConfig.RemoteIpAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { transportConfig.LocalIpAddress = IPAddress.Any; } else if (transportConfig.RemoteIpAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) { transportConfig.LocalIpAddress = IPAddress.IPv6Any; } if (transportType == TransportType.TCP) { transportConfig.Type = StackTransportType.Tcp; } else if (transportType == TransportType.UDP) { transportConfig.Type = StackTransportType.Udp; } else { throw new ArgumentException("ConnectionType can only be TCP or UDP."); } kdcTransport = new TransportStack(transportConfig, DecodePacketCallback); if (transportType == TransportType.TCP) { kdcTransport.Connect(); } else { kdcTransport.Start(); } } public virtual void DisConnect() { if (this.transportType == TransportType.TCP) kdcTransport.Disconnect(); } #endregion #region Transport methods /// <summary> /// Encode a PDU to a binary stream. Then send the stream. /// </summary> /// <param name="pdu">A specified type of a PDU. This argument cannot be null. /// If it is null, ArgumentNullException will be thrown.</param> /// <exception cref="System.ArgumentNullException">Thrown when the input parameter is null.</exception> public void SendPdu(KerberosPdu pdu) { if (pdu == null) { throw new ArgumentNullException("pdu"); } if (UseProxy) { Debug.Assert(ProxyClient != null, "Proxy Client should be set when using proxy."); //temporarily change the tranpsort type to TCP, since all proxy messages are TCP format. var oriTransportType = Context.TransportType; Context.TransportType = TransportType.TCP; KDCProxyMessage message = ProxyClient.MakeProxyMessage(pdu); //send proxy message ProxyClient.SendProxyRequest(message); //restore the original transport type Context.TransportType = oriTransportType; } else { this.Connect(); kdcTransport.SendPacket(pdu); } } /// <summary> /// Expect to receive a PDU of any type from the remote host. /// </summary> /// <param name="timeout">Timeout of receiving PDU.</param> /// <returns>The expected PDU.</returns> /// <exception cref="System.TimeoutException">Thrown when the timeout parameter is negative.</exception> public KerberosPdu ExpectPdu(TimeSpan timeout, Type pduType = null) { this.expectedPduType = pduType; KerberosPdu pdu = null; if (UseProxy) { Debug.Assert(ProxyClient != null, "Proxy Client should be set when using proxy."); int consumedLength = 0; int expectedLength = 0; if (ProxyClient.Error == KKDCPError.STATUS_SUCCESS) { KDCProxyMessage message = ProxyClient.GetProxyResponse(); //temporarily change the tranpsort type to TCP, since all proxy messages are TCP format. var oriTransportType = Context.TransportType; Context.TransportType = TransportType.TCP; //get proxy message pdu = getExpectedPduFromBytes(message.Message.kerb_message.ByteArrayValue, out consumedLength, out expectedLength); //restore the original transport type Context.TransportType = oriTransportType; } } else { if (timeout.TotalMilliseconds < 0) { throw new TimeoutException(KerberosConstValue.TIMEOUT_EXCEPTION); } this.expectedPduType = pduType; TransportEvent eventPacket = kdcTransport.ExpectTransportEvent(timeout); pdu = (KerberosPdu)eventPacket.EventObject; this.DisConnect(); } return pdu; } #endregion /// <summary> /// Decode Kpassword PDUs from received message bytes /// </summary> /// <param name="endPoint">An endpoint from which the message bytes are received</param> /// <param name="receivedBytes">The received bytes to be decoded</param> /// <param name="consumedLength">Length of message bytes consumed by decoder</param> /// <param name="expectedLength">Length of message bytes the decoder expects to receive</param> /// <returns>The decoded Kpassword PDUs</returns> /// <exception cref="System.FormatException">thrown when a kpassword message type is unsupported</exception> public override KerberosPdu[] DecodePacketCallback(object endPoint, byte[] receivedBytes, out int consumedLength, out int expectedLength) { KerberosPdu pdu = getExpectedPduFromBytes(receivedBytes, out consumedLength, out expectedLength); // insufficient data, need to receive more if (pdu == null) { return null; } return new KerberosPdu[] { pdu }; } //Get the expected Kerberos PDU from byte array private KerberosPdu getExpectedPduFromBytes( byte[] receivedBytes, out int consumedLength, out int expectedLength) { // initialize lengths consumedLength = 0; expectedLength = 0; if (null == receivedBytes || 0 == receivedBytes.Length) { return null; } // TCP has a 4 bytes length header, while UDP has not byte[] pduBytes = receivedBytes; if ((this.Context.TransportType == TransportType.TCP)) { // insufficient data, needs to receive more if (receivedBytes.Length < sizeof(int)) { return null; } // get pdu data length byte[] lengthBytes = ArrayUtility.SubArray(receivedBytes, 0, sizeof(int)); Array.Reverse(lengthBytes); int pduLength = BitConverter.ToInt32(lengthBytes, 0); // insufficient data, needs to receive more expectedLength = sizeof(int) + pduLength; if (receivedBytes.Length < expectedLength) { return null; } // remove length header from pdu bytes pduBytes = ArrayUtility.SubArray<byte>(receivedBytes, sizeof(int), pduLength); } else { // UDP has no length header expectedLength = pduBytes.Length; } consumedLength = expectedLength; KerberosPdu pdu = null; //Get AP data in message to judge the kpassword type byte[] apLengthBytes = ArrayUtility.SubArray<byte>(pduBytes, 2 * sizeof(ushort), sizeof(ushort)); Array.Reverse(apLengthBytes); ushort apLength = BitConverter.ToUInt16(apLengthBytes, 0); //If the length is zero, then the last field contains a KRB-ERROR message instead of a KRB-PRIV message. if (apLength == 0) { pdu = new KerberosKrbError(); pdu.FromBytes(ArrayUtility.SubArray<byte>(pduBytes, 3 * sizeof(ushort))); return pdu; } // get message type // (the lower 5 bits indicates its message type) byte[] apBytes = ArrayUtility.SubArray<byte>(pduBytes, 3 * sizeof(ushort), apLength); MsgType kpassMsgType = (MsgType)(apBytes[0] & 0x1f); if (kpassMsgType == MsgType.KRB_AP_REQ) { pdu = new KpasswordRequest(); } else { pdu = new KpasswordResponse(); pdu.FromBytes(pduBytes); } return pdu; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using osu.Framework; using osu.Framework.Caching; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osuTK; using osuTK.Graphics; using osu.Framework.Graphics.Shapes; using osu.Framework.Allocation; using osu.Framework.Threading; namespace osu.Game.Screens.Play { public class SquareGraph : Container { private BufferedContainer<Column> columns; public int ColumnCount => columns?.Children.Count ?? 0; private int progress; public int Progress { get => progress; set { if (value == progress) return; progress = value; redrawProgress(); } } private float[] calculatedValues = { }; // values but adjusted to fit the amount of columns private int[] values; public int[] Values { get => values; set { if (value == values) return; values = value; layout.Invalidate(); } } private Color4 fillColour; public Color4 FillColour { get => fillColour; set { if (value == fillColour) return; fillColour = value; redrawFilled(); } } public override bool Invalidate(Invalidation invalidation = Invalidation.All, Drawable source = null, bool shallPropagate = true) { if ((invalidation & Invalidation.DrawSize) > 0) layout.Invalidate(); return base.Invalidate(invalidation, source, shallPropagate); } private readonly Cached layout = new Cached(); private ScheduledDelegate scheduledCreate; protected override void Update() { base.Update(); if (values != null && !layout.IsValid) { columns?.FadeOut(500, Easing.OutQuint).Expire(); scheduledCreate?.Cancel(); scheduledCreate = Scheduler.AddDelayed(RecreateGraph, 500); layout.Validate(); } } private CancellationTokenSource cts; /// <summary> /// Recreates the entire graph. /// </summary> protected virtual void RecreateGraph() { var newColumns = new BufferedContainer<Column> { CacheDrawnFrameBuffer = true, RedrawOnScale = false, RelativeSizeAxes = Axes.Both, }; for (float x = 0; x < DrawWidth; x += Column.WIDTH) { newColumns.Add(new Column(DrawHeight) { LitColour = fillColour, Anchor = Anchor.BottomLeft, Origin = Anchor.BottomLeft, Position = new Vector2(x, 0), State = ColumnState.Dimmed, }); } cts?.Cancel(); LoadComponentAsync(newColumns, c => { Child = columns = c; columns.FadeInFromZero(500, Easing.OutQuint); recalculateValues(); redrawFilled(); redrawProgress(); }, (cts = new CancellationTokenSource()).Token); } /// <summary> /// Redraws all the columns to match their lit/dimmed state. /// </summary> private void redrawProgress() { for (int i = 0; i < ColumnCount; i++) columns[i].State = i <= progress ? ColumnState.Lit : ColumnState.Dimmed; columns?.ForceRedraw(); } /// <summary> /// Redraws the filled amount of all the columns. /// </summary> private void redrawFilled() { for (int i = 0; i < ColumnCount; i++) columns[i].Filled = calculatedValues.ElementAtOrDefault(i); columns?.ForceRedraw(); } /// <summary> /// Takes <see cref="Values"/> and adjusts it to fit the amount of columns. /// </summary> private void recalculateValues() { var newValues = new List<float>(); if (values == null) { for (float i = 0; i < ColumnCount; i++) newValues.Add(0); return; } var max = values.Max(); float step = values.Length / (float)ColumnCount; for (float i = 0; i < values.Length; i += step) { newValues.Add((float)values[(int)i] / max); } calculatedValues = newValues.ToArray(); } public class Column : Container, IStateful<ColumnState> { protected readonly Color4 EmptyColour = Color4.White.Opacity(20); public Color4 LitColour = Color4.LightBlue; protected readonly Color4 DimmedColour = Color4.White.Opacity(140); private float cubeCount => DrawHeight / WIDTH; private const float cube_size = 4; private const float padding = 2; public const float WIDTH = cube_size + padding; public event Action<ColumnState> StateChanged; private readonly List<Box> drawableRows = new List<Box>(); private float filled; public float Filled { get => filled; set { if (value == filled) return; filled = value; fillActive(); } } private ColumnState state; public ColumnState State { get => state; set { if (value == state) return; state = value; if (IsLoaded) fillActive(); StateChanged?.Invoke(State); } } public Column(float height) { Width = WIDTH; Height = height; } [BackgroundDependencyLoader] private void load() { drawableRows.AddRange(Enumerable.Range(0, (int)cubeCount).Select(r => new Box { Size = new Vector2(cube_size), Position = new Vector2(0, r * WIDTH + padding), })); Children = drawableRows; // Reverse drawableRows so when iterating through them they start at the bottom drawableRows.Reverse(); } protected override void LoadComplete() { base.LoadComplete(); fillActive(); } private void fillActive() { Color4 colour = State == ColumnState.Lit ? LitColour : DimmedColour; int countFilled = (int)MathHelper.Clamp(filled * drawableRows.Count, 0, drawableRows.Count); for (int i = 0; i < drawableRows.Count; i++) drawableRows[i].Colour = i < countFilled ? colour : EmptyColour; } } public enum ColumnState { Lit, Dimmed } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Security.Cryptography.Apple; using System.Security.Cryptography.Asn1; using Internal.Cryptography; namespace System.Security.Cryptography { #if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS public partial class DSA : AsymmetricAlgorithm { public static new DSA Create() { return new DSAImplementation.DSASecurityTransforms(); } #endif internal static partial class DSAImplementation { public sealed partial class DSASecurityTransforms : DSA { private SecKeyPair _keys; private bool _disposed; public DSASecurityTransforms() : this(1024) { } public DSASecurityTransforms(int keySize) { base.KeySize = keySize; } internal DSASecurityTransforms(SafeSecKeyRefHandle publicKey) { SetKey(SecKeyPair.PublicOnly(publicKey)); } internal DSASecurityTransforms(SafeSecKeyRefHandle publicKey, SafeSecKeyRefHandle privateKey) { SetKey(SecKeyPair.PublicPrivatePair(publicKey, privateKey)); } public override KeySizes[] LegalKeySizes { get { return new[] { new KeySizes(minSize: 512, maxSize: 1024, skipSize: 64) }; } } public override int KeySize { get { return base.KeySize; } set { if (KeySize == value) return; // Set the KeySize before freeing the key so that an invalid value doesn't throw away the key base.KeySize = value; ThrowIfDisposed(); if (_keys != null) { _keys.Dispose(); _keys = null; } } } public override DSAParameters ExportParameters(bool includePrivateParameters) { // Apple requires all private keys to be exported encrypted, but since we're trying to export // as parsed structures we will need to decrypt it for the user. const string ExportPassword = "DotnetExportPassphrase"; SecKeyPair keys = GetKeys(); if (includePrivateParameters && keys.PrivateKey == null) { throw new CryptographicException(SR.Cryptography_OpenInvalidHandle); } byte[] keyBlob = Interop.AppleCrypto.SecKeyExport( includePrivateParameters ? keys.PrivateKey : keys.PublicKey, exportPrivate: includePrivateParameters, password: ExportPassword); try { if (!includePrivateParameters) { DSAKeyFormatHelper.ReadSubjectPublicKeyInfo( keyBlob, out int localRead, out DSAParameters key); Debug.Assert(localRead == keyBlob.Length); return key; } else { DSAKeyFormatHelper.ReadEncryptedPkcs8( keyBlob, ExportPassword, out int localRead, out DSAParameters key); Debug.Assert(localRead == keyBlob.Length); return key; } } finally { CryptographicOperations.ZeroMemory(keyBlob); } } public override void ImportParameters(DSAParameters parameters) { if (parameters.P == null || parameters.Q == null || parameters.G == null || parameters.Y == null) throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MissingFields); // J is not required and is not even used on CNG blobs. // It should, however, be less than P (J == (P-1) / Q). // This validation check is just to maintain parity with DSACng and DSACryptoServiceProvider, // which also perform this check. if (parameters.J != null && parameters.J.Length >= parameters.P.Length) throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedPJ); int keySize = parameters.P.Length; bool hasPrivateKey = parameters.X != null; if (parameters.G.Length != keySize || parameters.Y.Length != keySize) throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedPGY); if (hasPrivateKey && parameters.X.Length != parameters.Q.Length) throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedQX); if (!(8 * parameters.P.Length).IsLegalSize(LegalKeySizes)) throw new CryptographicException(SR.Cryptography_InvalidKeySize); if (parameters.Q.Length != 20) throw new CryptographicException(SR.Cryptography_InvalidDsaParameters_QRestriction_ShortKey); ThrowIfDisposed(); if (hasPrivateKey) { SafeSecKeyRefHandle privateKey = ImportKey(parameters); DSAParameters publicOnly = parameters; publicOnly.X = null; SafeSecKeyRefHandle publicKey; try { publicKey = ImportKey(publicOnly); } catch { privateKey.Dispose(); throw; } SetKey(SecKeyPair.PublicPrivatePair(publicKey, privateKey)); } else { SafeSecKeyRefHandle publicKey = ImportKey(parameters); SetKey(SecKeyPair.PublicOnly(publicKey)); } } public override void ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, ReadOnlySpan<byte> source, out int bytesRead) { ThrowIfDisposed(); base.ImportEncryptedPkcs8PrivateKey(passwordBytes, source, out bytesRead); } public override void ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, ReadOnlySpan<byte> source, out int bytesRead) { ThrowIfDisposed(); base.ImportEncryptedPkcs8PrivateKey(password, source, out bytesRead); } private static SafeSecKeyRefHandle ImportKey(DSAParameters parameters) { if (parameters.X != null) { // DSAPrivateKey ::= SEQUENCE( // version INTEGER, // p INTEGER, // q INTEGER, // g INTEGER, // y INTEGER, // x INTEGER, // ) using (AsnWriter privateKeyWriter = new AsnWriter(AsnEncodingRules.DER)) { privateKeyWriter.PushSequence(); privateKeyWriter.WriteInteger(0); privateKeyWriter.WriteKeyParameterInteger(parameters.P); privateKeyWriter.WriteKeyParameterInteger(parameters.Q); privateKeyWriter.WriteKeyParameterInteger(parameters.G); privateKeyWriter.WriteKeyParameterInteger(parameters.Y); privateKeyWriter.WriteKeyParameterInteger(parameters.X); privateKeyWriter.PopSequence(); return Interop.AppleCrypto.ImportEphemeralKey(privateKeyWriter.EncodeAsSpan(), true); } } else { using (AsnWriter writer = DSAKeyFormatHelper.WriteSubjectPublicKeyInfo(parameters)) { return Interop.AppleCrypto.ImportEphemeralKey(writer.EncodeAsSpan(), false); } } } public override unsafe void ImportSubjectPublicKeyInfo( ReadOnlySpan<byte> source, out int bytesRead) { ThrowIfDisposed(); fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length)) { // Validate the DER value and get the number of bytes. DSAKeyFormatHelper.ReadSubjectPublicKeyInfo( manager.Memory, out int localRead); SafeSecKeyRefHandle publicKey = Interop.AppleCrypto.ImportEphemeralKey(source.Slice(0, localRead), false); SetKey(SecKeyPair.PublicOnly(publicKey)); bytesRead = localRead; } } } public override byte[] CreateSignature(byte[] rgbHash) { if (rgbHash == null) throw new ArgumentNullException(nameof(rgbHash)); SecKeyPair keys = GetKeys(); if (keys.PrivateKey == null) { throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); } byte[] derFormatSignature = Interop.AppleCrypto.GenerateSignature(keys.PrivateKey, rgbHash); // Since the AppleCrypto implementation is limited to FIPS 186-2, signature field sizes // are always 160 bits / 20 bytes (the size of SHA-1, and the only legal length for Q). byte[] ieeeFormatSignature = AsymmetricAlgorithmHelpers.ConvertDerToIeee1363( derFormatSignature, 0, derFormatSignature.Length, fieldSizeBits: 160); return ieeeFormatSignature; } public override bool VerifySignature(byte[] hash, byte[] signature) { if (hash == null) throw new ArgumentNullException(nameof(hash)); if (signature == null) throw new ArgumentNullException(nameof(signature)); return VerifySignature((ReadOnlySpan<byte>)hash, (ReadOnlySpan<byte>)signature); } public override bool VerifySignature(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature) { byte[] derFormatSignature = AsymmetricAlgorithmHelpers.ConvertIeee1363ToDer(signature); return Interop.AppleCrypto.VerifySignature( GetKeys().PublicKey, hash, derFormatSignature); } protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { if (hashAlgorithm != HashAlgorithmName.SHA1) { // Matching DSACryptoServiceProvider's "I only understand SHA-1/FIPS 186-2" exception throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name); } return AsymmetricAlgorithmHelpers.HashData(data, offset, count, hashAlgorithm); } protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) => AsymmetricAlgorithmHelpers.HashData(data, hashAlgorithm); protected override bool TryHashData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) => AsymmetricAlgorithmHelpers.TryHashData(data, destination, hashAlgorithm, out bytesWritten); protected override void Dispose(bool disposing) { if (disposing) { if (_keys != null) { _keys.Dispose(); _keys = null; } _disposed = true; } base.Dispose(disposing); } private void ThrowIfDisposed() { // The other SecurityTransforms types use _keys.PublicKey == null, // but since Apple doesn't provide DSA key generation we can't easily tell // if a failed attempt to generate a key happened, or we're in a pristine state. // // So this type uses an explicit field, rather than inferred state. if (_disposed) { throw new ObjectDisposedException(nameof(DSA)); } } internal SecKeyPair GetKeys() { ThrowIfDisposed(); SecKeyPair current = _keys; if (current != null) { return current; } // macOS 10.11 and macOS 10.12 declare DSA invalid for key generation. // Rather than write code which might or might not work, returning // (OSStatus)-4 (errSecUnimplemented), just make the exception occur here. // // When the native code can be verified, then it can be added. throw new PlatformNotSupportedException(SR.Cryptography_DSA_KeyGenNotSupported); } private void SetKey(SecKeyPair newKeyPair) { ThrowIfDisposed(); SecKeyPair current = _keys; _keys = newKeyPair; current?.Dispose(); if (newKeyPair != null) { int size = Interop.AppleCrypto.GetSimpleKeySizeInBits(newKeyPair.PublicKey); KeySizeValue = size; } } } } #if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS } #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.Collections.Generic; using System.Runtime.InteropServices; using System.Threading; using Xunit; namespace System.Text.RegularExpressions.Tests { public class RegexConstructorTests { public static IEnumerable<object[]> Ctor_TestData() { yield return new object[] { "foo", RegexOptions.None, Timeout.InfiniteTimeSpan }; yield return new object[] { "foo", RegexOptions.RightToLeft, Timeout.InfiniteTimeSpan }; yield return new object[] { "foo", RegexOptions.Compiled, Timeout.InfiniteTimeSpan }; yield return new object[] { "foo", RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant, Timeout.InfiniteTimeSpan }; yield return new object[] { "foo", RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.Compiled, Timeout.InfiniteTimeSpan }; yield return new object[] { "foo", RegexOptions.None, new TimeSpan(1) }; yield return new object[] { "foo", RegexOptions.None, TimeSpan.FromMilliseconds(int.MaxValue - 1) }; } [Theory] [MemberData(nameof(Ctor_TestData))] public static void Ctor(string pattern, RegexOptions options, TimeSpan matchTimeout) { if (matchTimeout == Timeout.InfiniteTimeSpan) { if (options == RegexOptions.None) { Regex regex1 = new Regex(pattern); Assert.Equal(pattern, regex1.ToString()); Assert.Equal(options, regex1.Options); Assert.False(regex1.RightToLeft); Assert.Equal(matchTimeout, regex1.MatchTimeout); } Regex regex2 = new Regex(pattern, options); Assert.Equal(pattern, regex2.ToString()); Assert.Equal(options, regex2.Options); Assert.Equal((options & RegexOptions.RightToLeft) != 0, regex2.RightToLeft); Assert.Equal(matchTimeout, regex2.MatchTimeout); } Regex regex3 = new Regex(pattern, options, matchTimeout); Assert.Equal(pattern, regex3.ToString()); Assert.Equal(options, regex3.Options); Assert.Equal((options & RegexOptions.RightToLeft) != 0, regex3.RightToLeft); Assert.Equal(matchTimeout, regex3.MatchTimeout); } [Fact] public static void Ctor_Invalid() { // Pattern is null AssertExtensions.Throws<ArgumentNullException>("pattern", () => new Regex(null)); AssertExtensions.Throws<ArgumentNullException>("pattern", () => new Regex(null, RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("pattern", () => new Regex(null, RegexOptions.None, new TimeSpan())); // Options are invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", (RegexOptions)(-1))); AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", (RegexOptions)(-1), new TimeSpan())); AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", (RegexOptions)0x400)); AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", (RegexOptions)0x400, new TimeSpan())); AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.RightToLeft)); AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture)); AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.Singleline)); AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace)); // MatchTimeout is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("matchTimeout", () => new Regex("foo", RegexOptions.None, new TimeSpan(-1))); AssertExtensions.Throws<ArgumentOutOfRangeException>("matchTimeout", () => new Regex("foo", RegexOptions.None, TimeSpan.Zero)); AssertExtensions.Throws<ArgumentOutOfRangeException>("matchTimeout", () => new Regex("foo", RegexOptions.None, TimeSpan.FromMilliseconds(int.MaxValue))); } [Fact] public void CacheSize_Get() { Assert.Equal(15, Regex.CacheSize); } [Theory] [InlineData(0)] [InlineData(12)] public void CacheSize_Set(int newCacheSize) { int originalCacheSize = Regex.CacheSize; Regex.CacheSize = newCacheSize; Assert.Equal(newCacheSize, Regex.CacheSize); Regex.CacheSize = originalCacheSize; } [Fact] public void CacheSize_Set_NegativeValue_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => Regex.CacheSize = -1); } [Theory] // \d, \D, \s, \S, \w, \W, \P, \p inside character range [InlineData(@"cat([a-\d]*)dog", RegexOptions.None)] [InlineData(@"([5-\D]*)dog", RegexOptions.None)] [InlineData(@"cat([6-\s]*)dog", RegexOptions.None)] [InlineData(@"cat([c-\S]*)", RegexOptions.None)] [InlineData(@"cat([7-\w]*)", RegexOptions.None)] [InlineData(@"cat([a-\W]*)dog", RegexOptions.None)] [InlineData(@"([f-\p{Lu}]\w*)\s([\p{Lu}]\w*)", RegexOptions.None)] [InlineData(@"([1-\P{Ll}][\p{Ll}]*)\s([\P{Ll}][\p{Ll}]*)", RegexOptions.None)] [InlineData(@"[\p]", RegexOptions.None)] [InlineData(@"[\P]", RegexOptions.None)] [InlineData(@"([\pcat])", RegexOptions.None)] [InlineData(@"([\Pcat])", RegexOptions.None)] [InlineData(@"(\p{", RegexOptions.None)] [InlineData(@"(\p{Ll", RegexOptions.None)] // \x, \u, \a, \b, \e, \f, \n, \r, \t, \v, \c, inside character range [InlineData(@"(cat)([\o]*)(dog)", RegexOptions.None)] // Use < in a group [InlineData(@"cat(?<0>dog)", RegexOptions.None)] [InlineData(@"cat(?<1dog>dog)", RegexOptions.None)] [InlineData(@"cat(?<dog)_*>dog)", RegexOptions.None)] [InlineData(@"cat(?<dog!>)_*>dog)", RegexOptions.None)] [InlineData(@"cat(?<dog >)_*>dog)", RegexOptions.None)] [InlineData(@"cat(?<dog<>)_*>dog)", RegexOptions.None)] [InlineData(@"cat(?<>dog)", RegexOptions.None)] [InlineData(@"cat(?<->dog)", RegexOptions.None)] [InlineData(@"(?<cat>cat)\w+(?<dog-16>dog)", RegexOptions.None)] [InlineData(@"(?<cat>cat)\w+(?<dog-1uosn>dog)", RegexOptions.None)] [InlineData(@"(?<cat>cat)\w+(?<dog-catdog>dog)", RegexOptions.None)] [InlineData(@"(?<cat>cat)\w+(?<dog-()*!@>dog)", RegexOptions.None)] // Use (? in a group [InlineData("cat(?(?#COMMENT)cat)", RegexOptions.None)] [InlineData("cat(?(?'cat'cat)dog)", RegexOptions.None)] [InlineData("cat(?(?<cat>cat)dog)", RegexOptions.None)] [InlineData("cat(?(?afdcat)dog)", RegexOptions.None)] // Pattern whitespace [InlineData(@"(cat) (?#cat) \s+ (?#followed by 1 or more whitespace", RegexOptions.IgnorePatternWhitespace)] [InlineData(@"(cat) (?#cat) \s+ (?#followed by 1 or more whitespace", RegexOptions.None)] // Back reference [InlineData(@"(?<cat>cat)\s+(?<dog>dog)\kcat", RegexOptions.None)] [InlineData(@"(?<cat>cat)\s+(?<dog>dog)\k<cat2>", RegexOptions.None)] [InlineData(@"(?<cat>cat)\s+(?<dog>dog)\k<8>cat", RegexOptions.None)] [InlineData(@"(?<cat>cat)\s+(?<dog>dog)\k<8>cat", RegexOptions.ECMAScript)] [InlineData(@"(?<cat>cat)\s+(?<dog>dog)\k8", RegexOptions.None)] [InlineData(@"(?<cat>cat)\s+(?<dog>dog)\k8", RegexOptions.ECMAScript)] // Octal, decimal [InlineData(@"(cat)(\7)", RegexOptions.None)] [InlineData(@"(cat)\s+(?<2147483648>dog)", RegexOptions.None)] [InlineData(@"(cat)\s+(?<21474836481097>dog)", RegexOptions.None)] // Scan control [InlineData(@"(cat)(\c*)(dog)", RegexOptions.None)] [InlineData(@"(cat)\c", RegexOptions.None)] [InlineData(@"(cat)(\c *)(dog)", RegexOptions.None)] [InlineData(@"(cat)(\c?*)(dog)", RegexOptions.None)] [InlineData("(cat)(\\c\0*)(dog)", RegexOptions.None)] [InlineData(@"(cat)(\c`*)(dog)", RegexOptions.None)] [InlineData(@"(cat)(\c\|*)(dog)", RegexOptions.None)] [InlineData(@"(cat)(\c\[*)(dog)", RegexOptions.None)] // Nested quantifiers [InlineData("^[abcd]{0,16}*$", RegexOptions.None)] [InlineData("^[abcd]{1,}*$", RegexOptions.None)] [InlineData("^[abcd]{1}*$", RegexOptions.None)] [InlineData("^[abcd]{0,16}?*$", RegexOptions.None)] [InlineData("^[abcd]{1,}?*$", RegexOptions.None)] [InlineData("^[abcd]{1}?*$", RegexOptions.None)] [InlineData("^[abcd]*+$", RegexOptions.None)] [InlineData("^[abcd]+*$", RegexOptions.None)] [InlineData("^[abcd]?*$", RegexOptions.None)] [InlineData("^[abcd]*?+$", RegexOptions.None)] [InlineData("^[abcd]+?*$", RegexOptions.None)] [InlineData("^[abcd]??*$", RegexOptions.None)] [InlineData("^[abcd]*{0,5}$", RegexOptions.None)] [InlineData("^[abcd]+{0,5}$", RegexOptions.None)] [InlineData("^[abcd]?{0,5}$", RegexOptions.None)] // Invalid character escapes [InlineData(@"\u", RegexOptions.None)] [InlineData(@"\ua", RegexOptions.None)] [InlineData(@"\u0", RegexOptions.None)] [InlineData(@"\x", RegexOptions.None)] [InlineData(@"\x2", RegexOptions.None)] // Invalid character class [InlineData("[", RegexOptions.None)] [InlineData("[]", RegexOptions.None)] [InlineData("[a", RegexOptions.None)] [InlineData("[^", RegexOptions.None)] [InlineData("[cat", RegexOptions.None)] [InlineData("[^cat", RegexOptions.None)] [InlineData("[a-", RegexOptions.None)] [InlineData(@"\p{", RegexOptions.None)] [InlineData(@"\p{cat", RegexOptions.None)] [InlineData(@"\p{cat}", RegexOptions.None)] [InlineData(@"\P{", RegexOptions.None)] [InlineData(@"\P{cat", RegexOptions.None)] [InlineData(@"\P{cat}", RegexOptions.None)] // Invalid grouping constructs [InlineData("(", RegexOptions.None)] [InlineData("(?", RegexOptions.None)] [InlineData("(?<", RegexOptions.None)] [InlineData("(?<cat>", RegexOptions.None)] [InlineData("(?'", RegexOptions.None)] [InlineData("(?'cat'", RegexOptions.None)] [InlineData("(?:", RegexOptions.None)] [InlineData("(?imn", RegexOptions.None)] [InlineData("(?imn )", RegexOptions.None)] [InlineData("(?=", RegexOptions.None)] [InlineData("(?!", RegexOptions.None)] [InlineData("(?<=", RegexOptions.None)] [InlineData("(?<!", RegexOptions.None)] [InlineData("(?>", RegexOptions.None)] [InlineData("(?)", RegexOptions.None)] [InlineData("(?<)", RegexOptions.None)] [InlineData("(?')", RegexOptions.None)] [InlineData(@"\1", RegexOptions.None)] [InlineData(@"\1", RegexOptions.None)] [InlineData(@"\k", RegexOptions.None)] [InlineData(@"\k<", RegexOptions.None)] [InlineData(@"\k<1", RegexOptions.None)] [InlineData(@"\k<cat", RegexOptions.None)] [InlineData(@"\k<>", RegexOptions.None)] // Invalid alternation constructs [InlineData("(?(", RegexOptions.None)] [InlineData("(?()|", RegexOptions.None)] [InlineData("(?(cat", RegexOptions.None)] [InlineData("(?(cat)|", RegexOptions.None)] // Regex with 0 numeric names [InlineData("foo(?<0>bar)", RegexOptions.None)] [InlineData("foo(?'0'bar)", RegexOptions.None)] // Regex without closing > [InlineData("foo(?<1bar)", RegexOptions.None)] [InlineData("foo(?'1bar)", RegexOptions.None)] // Misc [InlineData(@"\p{klsak", RegexOptions.None)] [InlineData("(?r:cat)", RegexOptions.None)] [InlineData("(?c:cat)", RegexOptions.None)] [InlineData("(??e:cat)", RegexOptions.None)] // Character class subtraction [InlineData("[a-f-[]]+", RegexOptions.None)] // Not character class substraction [InlineData("[A-[]+", RegexOptions.None)] // Invalid testgroup [InlineData("(?(?e))", RegexOptions.None)] [InlineData("(?(?a)", RegexOptions.None)] [InlineData("(?(?", RegexOptions.None)] [InlineData("(?(", RegexOptions.None)] [InlineData("?(a:b)", RegexOptions.None)] [InlineData("?(a)", RegexOptions.None)] [InlineData("?(a|b)", RegexOptions.None)] [InlineData("?((a)", RegexOptions.None)] [InlineData("?((a)a", RegexOptions.None)] [InlineData("?((a)a|", RegexOptions.None)] [InlineData("?((a)a|b", RegexOptions.None)] public void Ctor_InvalidPattern(string pattern, RegexOptions options) { AssertExtensions.Throws<ArgumentException>(null, () => new Regex(pattern, options)); } [Theory] // Testgroup with options [InlineData("(?(?i))", RegexOptions.None, typeof(NullReferenceException))] [InlineData("(?(?I))", RegexOptions.None, typeof(NullReferenceException))] [InlineData("(?(?m))", RegexOptions.None, typeof(NullReferenceException))] [InlineData("(?(?M))", RegexOptions.None, typeof(NullReferenceException))] [InlineData("(?(?s))", RegexOptions.None, typeof(NullReferenceException))] [InlineData("(?(?S))", RegexOptions.None, typeof(NullReferenceException))] [InlineData("(?(?x))", RegexOptions.None, typeof(NullReferenceException))] [InlineData("(?(?X))", RegexOptions.None, typeof(NullReferenceException))] [InlineData("(?(?n))", RegexOptions.None, typeof(NullReferenceException))] [InlineData("(?(?N))", RegexOptions.None, typeof(NullReferenceException))] [InlineData(" (?(?n))", RegexOptions.None, typeof(OutOfMemoryException))] public void Ctor_InvalidPattern(string pattern, RegexOptions options, Type exceptionType) { if (PlatformDetection.IsFullFramework) { Assert.Throws(exceptionType, () => new Regex(pattern, options)); } else { Ctor_InvalidPattern(pattern, options); } } } }
/************************************************************************* Copyright (c) 1992-2007 The University of Tennessee. All rights reserved. Contributors: * Sergey Bochkanov (ALGLIB project). Translation from FORTRAN to pseudocode. See subroutines comments for additional copyrights. >>> SOURCE LICENSE >>> 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 (www.fsf.org); 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. A copy of the GNU General Public License is available at http://www.fsf.org/licensing/licenses >>> END OF LICENSE >>> *************************************************************************/ using System; namespace FuncLib.Mathematics.LinearAlgebra.AlgLib { internal class rotations { /************************************************************************* Application of a sequence of elementary rotations to a matrix The algorithm pre-multiplies the matrix by a sequence of rotation transformations which is given by arrays C and S. Depending on the value of the IsForward parameter either 1 and 2, 3 and 4 and so on (if IsForward=true) rows are rotated, or the rows N and N-1, N-2 and N-3 and so on, are rotated. Not the whole matrix but only a part of it is transformed (rows from M1 to M2, columns from N1 to N2). Only the elements of this submatrix are changed. Input parameters: IsForward - the sequence of the rotation application. M1,M2 - the range of rows to be transformed. N1, N2 - the range of columns to be transformed. C,S - transformation coefficients. Array whose index ranges within [1..M2-M1]. A - processed matrix. WORK - working array whose index ranges within [N1..N2]. Output parameters: A - transformed matrix. Utility subroutine. *************************************************************************/ public static void applyrotationsfromtheleft(bool isforward, int m1, int m2, int n1, int n2, ref double[] c, ref double[] s, ref double[,] a, ref double[] work) { int j = 0; int jp1 = 0; double ctemp = 0; double stemp = 0; double temp = 0; int i_ = 0; if (m1 > m2 | n1 > n2) { return; } // // Form P * A // if (isforward) { if (n1 != n2) { // // Common case: N1<>N2 // for (j = m1; j <= m2 - 1; j++) { ctemp = c[j - m1 + 1]; stemp = s[j - m1 + 1]; if ((double)(ctemp) != (double)(1) | (double)(stemp) != (double)(0)) { jp1 = j + 1; for (i_ = n1; i_ <= n2; i_++) { work[i_] = ctemp * a[jp1, i_]; } for (i_ = n1; i_ <= n2; i_++) { work[i_] = work[i_] - stemp * a[j, i_]; } for (i_ = n1; i_ <= n2; i_++) { a[j, i_] = ctemp * a[j, i_]; } for (i_ = n1; i_ <= n2; i_++) { a[j, i_] = a[j, i_] + stemp * a[jp1, i_]; } for (i_ = n1; i_ <= n2; i_++) { a[jp1, i_] = work[i_]; } } } } else { // // Special case: N1=N2 // for (j = m1; j <= m2 - 1; j++) { ctemp = c[j - m1 + 1]; stemp = s[j - m1 + 1]; if ((double)(ctemp) != (double)(1) | (double)(stemp) != (double)(0)) { temp = a[j + 1, n1]; a[j + 1, n1] = ctemp * temp - stemp * a[j, n1]; a[j, n1] = stemp * temp + ctemp * a[j, n1]; } } } } else { if (n1 != n2) { // // Common case: N1<>N2 // for (j = m2 - 1; j >= m1; j--) { ctemp = c[j - m1 + 1]; stemp = s[j - m1 + 1]; if ((double)(ctemp) != (double)(1) | (double)(stemp) != (double)(0)) { jp1 = j + 1; for (i_ = n1; i_ <= n2; i_++) { work[i_] = ctemp * a[jp1, i_]; } for (i_ = n1; i_ <= n2; i_++) { work[i_] = work[i_] - stemp * a[j, i_]; } for (i_ = n1; i_ <= n2; i_++) { a[j, i_] = ctemp * a[j, i_]; } for (i_ = n1; i_ <= n2; i_++) { a[j, i_] = a[j, i_] + stemp * a[jp1, i_]; } for (i_ = n1; i_ <= n2; i_++) { a[jp1, i_] = work[i_]; } } } } else { // // Special case: N1=N2 // for (j = m2 - 1; j >= m1; j--) { ctemp = c[j - m1 + 1]; stemp = s[j - m1 + 1]; if ((double)(ctemp) != (double)(1) | (double)(stemp) != (double)(0)) { temp = a[j + 1, n1]; a[j + 1, n1] = ctemp * temp - stemp * a[j, n1]; a[j, n1] = stemp * temp + ctemp * a[j, n1]; } } } } } /************************************************************************* Application of a sequence of elementary rotations to a matrix The algorithm post-multiplies the matrix by a sequence of rotation transformations which is given by arrays C and S. Depending on the value of the IsForward parameter either 1 and 2, 3 and 4 and so on (if IsForward=true) rows are rotated, or the rows N and N-1, N-2 and N-3 and so on are rotated. Not the whole matrix but only a part of it is transformed (rows from M1 to M2, columns from N1 to N2). Only the elements of this submatrix are changed. Input parameters: IsForward - the sequence of the rotation application. M1,M2 - the range of rows to be transformed. N1, N2 - the range of columns to be transformed. C,S - transformation coefficients. Array whose index ranges within [1..N2-N1]. A - processed matrix. WORK - working array whose index ranges within [M1..M2]. Output parameters: A - transformed matrix. Utility subroutine. *************************************************************************/ public static void applyrotationsfromtheright(bool isforward, int m1, int m2, int n1, int n2, ref double[] c, ref double[] s, ref double[,] a, ref double[] work) { int j = 0; int jp1 = 0; double ctemp = 0; double stemp = 0; double temp = 0; int i_ = 0; // // Form A * P' // if (isforward) { if (m1 != m2) { // // Common case: M1<>M2 // for (j = n1; j <= n2 - 1; j++) { ctemp = c[j - n1 + 1]; stemp = s[j - n1 + 1]; if ((double)(ctemp) != (double)(1) | (double)(stemp) != (double)(0)) { jp1 = j + 1; for (i_ = m1; i_ <= m2; i_++) { work[i_] = ctemp * a[i_, jp1]; } for (i_ = m1; i_ <= m2; i_++) { work[i_] = work[i_] - stemp * a[i_, j]; } for (i_ = m1; i_ <= m2; i_++) { a[i_, j] = ctemp * a[i_, j]; } for (i_ = m1; i_ <= m2; i_++) { a[i_, j] = a[i_, j] + stemp * a[i_, jp1]; } for (i_ = m1; i_ <= m2; i_++) { a[i_, jp1] = work[i_]; } } } } else { // // Special case: M1=M2 // for (j = n1; j <= n2 - 1; j++) { ctemp = c[j - n1 + 1]; stemp = s[j - n1 + 1]; if ((double)(ctemp) != (double)(1) | (double)(stemp) != (double)(0)) { temp = a[m1, j + 1]; a[m1, j + 1] = ctemp * temp - stemp * a[m1, j]; a[m1, j] = stemp * temp + ctemp * a[m1, j]; } } } } else { if (m1 != m2) { // // Common case: M1<>M2 // for (j = n2 - 1; j >= n1; j--) { ctemp = c[j - n1 + 1]; stemp = s[j - n1 + 1]; if ((double)(ctemp) != (double)(1) | (double)(stemp) != (double)(0)) { jp1 = j + 1; for (i_ = m1; i_ <= m2; i_++) { work[i_] = ctemp * a[i_, jp1]; } for (i_ = m1; i_ <= m2; i_++) { work[i_] = work[i_] - stemp * a[i_, j]; } for (i_ = m1; i_ <= m2; i_++) { a[i_, j] = ctemp * a[i_, j]; } for (i_ = m1; i_ <= m2; i_++) { a[i_, j] = a[i_, j] + stemp * a[i_, jp1]; } for (i_ = m1; i_ <= m2; i_++) { a[i_, jp1] = work[i_]; } } } } else { // // Special case: M1=M2 // for (j = n2 - 1; j >= n1; j--) { ctemp = c[j - n1 + 1]; stemp = s[j - n1 + 1]; if ((double)(ctemp) != (double)(1) | (double)(stemp) != (double)(0)) { temp = a[m1, j + 1]; a[m1, j + 1] = ctemp * temp - stemp * a[m1, j]; a[m1, j] = stemp * temp + ctemp * a[m1, j]; } } } } } /************************************************************************* The subroutine generates the elementary rotation, so that: [ CS SN ] . [ F ] = [ R ] [ -SN CS ] [ G ] [ 0 ] CS**2 + SN**2 = 1 *************************************************************************/ public static void generaterotation(double f, double g, ref double cs, ref double sn, ref double r) { double f1 = 0; double g1 = 0; if ((double)(g) == (double)(0)) { cs = 1; sn = 0; r = f; } else { if ((double)(f) == (double)(0)) { cs = 0; sn = 1; r = g; } else { f1 = f; g1 = g; if ((double)(Math.Abs(f1)) > (double)(Math.Abs(g1))) { r = Math.Abs(f1) * Math.Sqrt(1 + AP.Math.Sqr(g1 / f1)); } else { r = Math.Abs(g1) * Math.Sqrt(1 + AP.Math.Sqr(f1 / g1)); } cs = f1 / r; sn = g1 / r; if ((double)(Math.Abs(f)) > (double)(Math.Abs(g)) & (double)(cs) < (double)(0)) { cs = -cs; sn = -sn; r = -r; } } } } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using NetTopologySuite.IO; namespace DotSpatial.Data { /// <summary> /// A reader that reads features from WKB text. /// </summary> public static class WkbFeatureReader { #region Fields private static ByteOrder endian; #endregion #region Methods /// <summary> /// Given the array of bytes, this reverses the bytes based on size. So if size if 4, the /// reversal will flip uints of 4 bytes at a time. /// </summary> /// <param name="data">Data that gets reversed.</param> /// <param name="size">Number of bytes that will be flipped together.</param> public static void CheckEndian(byte[] data, int size) { if ((endian == ByteOrder.LittleEndian) == BitConverter.IsLittleEndian) return; int count = data.Length / size; for (int i = 0; i < count; i++) { byte[] temp = new byte[size]; Array.Copy(data, i * size, temp, 0, size); Array.Reverse(temp); Array.Copy(temp, 0, data, i * size, size); } } /// <summary> /// Since WKB can in fact store different kinds of shapes, this will split out /// each type of shape into a different featureset. If all the shapes are /// the same kind of feature, thre will only be one list of feature types. /// </summary> /// <param name="data">Data to get the feature sets from.</param> /// <returns>The feature sets gotten from the data.</returns> public static FeatureSetPack GetFeatureSets(byte[] data) { MemoryStream ms = new MemoryStream(data); return GetFeatureSets(ms); } /// <summary> /// Gets a FeatureSetPack from the WKB. /// </summary> /// <param name="data">Data to get the feature sets from.</param> /// <returns>The feature sets gotten from the data.</returns> public static FeatureSetPack GetFeatureSets(Stream data) { FeatureSetPack result = new FeatureSetPack(); while (data.Position < data.Length) { ReadFeature(data, result); } result.StopEditing(); return result; } /// <summary> /// Reads the specified number of doubles. /// </summary> /// <param name="data">Data to read the double from.</param> /// <param name="count">Number of doubles that should be read.</param> /// <returns>The doubles that were read.</returns> public static double[] ReadDouble(Stream data, int count) { byte[] vals = new byte[8 * count]; data.Read(vals, 0, count * 8); CheckEndian(vals, 8); double[] result = new double[count]; Buffer.BlockCopy(vals, 0, result, 0, count * 8); return result; } /// <summary> /// Reads only a single geometry into a feature. This may be a multi-part geometry. /// </summary> /// <param name="data">The data to read the features from.</param> /// <param name="results">FeatureSetPack the read features get added to.</param> public static void ReadFeature(Stream data, FeatureSetPack results) { endian = (ByteOrder)data.ReadByte(); WKBGeometryTypes type = (WKBGeometryTypes)ReadInt32(data); switch (type) { case WKBGeometryTypes.WKBPoint: ReadPoint(data, results); return; case WKBGeometryTypes.WKBLineString: ReadLineString(data, results); return; case WKBGeometryTypes.WKBPolygon: ReadPolygon(data, results); break; case WKBGeometryTypes.WKBMultiPoint: ReadMultiPoint(data, results); break; case WKBGeometryTypes.WKBMultiLineString: ReadMultiLineString(data, results); break; case WKBGeometryTypes.WKBMultiPolygon: ReadMultiPolygon(data, results); break; case WKBGeometryTypes.WKBGeometryCollection: ReadGeometryCollection(data, results); break; } } /// <summary> /// Reads an int from the stream. /// </summary> /// <param name="data">The raw byte data.</param> /// <returns>The int that was read.</returns> public static int ReadInt32(Stream data) { byte[] vals = new byte[4]; data.Read(vals, 0, 4); CheckEndian(vals, 4); return BitConverter.ToInt32(vals, 0); } /// <summary> /// Reads ints from the stream. /// </summary> /// <param name="data">The raw byte data.</param> /// <param name="count">The count of integers, not bytes.</param> /// <returns>The ints that were read.</returns> public static int[] ReadInt32(Stream data, int count) { byte[] vals = new byte[4 * count]; data.Read(vals, 0, 4 * count); CheckEndian(vals, 4); int[] result = new int[count]; Buffer.BlockCopy(vals, 0, result, 0, count * 4); return result; } /// <summary> /// Reads a point from the data. This assumes that the byte order and shapetype have already been read. /// </summary> /// <param name="data">Data to read the point from.</param> /// <returns>The read point as shape.</returns> public static Shape ReadPoint(Stream data) { Shape result = new Shape { Range = new ShapeRange(FeatureType.Point) }; PartRange prt = new PartRange(FeatureType.Point) { NumVertices = 1 }; result.Range.Parts.Add(prt); result.Vertices = ReadDouble(data, 2); return result; } /// <summary> /// Reads only a single geometry into a feature. This may be a multi-part geometry, /// but cannot be a mixed part geometry. Anything that registers as "geometryCollection" /// will trigger an exception. /// </summary> /// <param name="data">The data to read from.</param> /// <returns>The shape that was read.</returns> public static Shape ReadShape(Stream data) { return ReadShape(data, FeatureType.Unspecified); } /// <summary> /// Attempts to read in an entry to the specified feature type. If the feature type does not match /// the geometry type, this will return null. (A Point geometry will be accepted by MultiPoint /// feature type, but not the other way arround. Either way, this will advance the reader /// through the shape feature. Using the Unspecified will always return the shape it reads, /// or null in the case of mixed feature collections which are not supported. /// </summary> /// <param name="data">Data that contains the WKB feature.</param> /// <param name="featureType">The feature type.</param> /// <returns>The resulting shape.</returns> public static Shape ReadShape(Stream data, FeatureType featureType) { endian = (ByteOrder)data.ReadByte(); WKBGeometryTypes type = (WKBGeometryTypes)ReadInt32(data); Shape result; switch (type) { case WKBGeometryTypes.WKBPoint: result = ReadPoint(data); if (featureType == FeatureType.Point || featureType == FeatureType.MultiPoint || featureType == FeatureType.Unspecified) { return result; } return null; case WKBGeometryTypes.WKBLineString: result = ReadLineString(data); if (featureType == FeatureType.Line || featureType == FeatureType.Unspecified) { return result; } return null; case WKBGeometryTypes.WKBPolygon: result = ReadPolygon(data); if (featureType == FeatureType.Polygon || featureType == FeatureType.Unspecified) { return result; } return null; case WKBGeometryTypes.WKBMultiPoint: result = ReadMultiPoint(data); if (featureType == FeatureType.MultiPoint || featureType == FeatureType.Unspecified) { return result; } return null; case WKBGeometryTypes.WKBMultiLineString: result = ReadMultiLineString(data); if (featureType == FeatureType.Line || featureType == FeatureType.Unspecified) { return result; } return null; case WKBGeometryTypes.WKBMultiPolygon: result = ReadMultiPolygon(data); if (featureType == FeatureType.Polygon || featureType == FeatureType.Unspecified) { return result; } return null; case WKBGeometryTypes.WKBGeometryCollection: throw new ArgumentException("Mixed shape type collections are not supported by this method."); } return null; } /// <summary> /// Calculates the area and if the area is negative, this is considered a hole. /// </summary> /// <param name="coords">Coordinates whose direction gets checked.</param> /// <returns>Boolean, true if this has a negative area and should be thought of as a hole.</returns> private static bool IsCounterClockwise(double[] coords) { double area = 0; for (int i = 0; i < coords.Length / 2; i++) { double x1 = coords[i * 2]; double y1 = coords[(i * 2) + 1]; double x2, y2; if (i == (coords.Length / 2) - 1) { x2 = coords[0]; y2 = coords[1]; } else { x2 = coords[(i + 1) * 2]; y2 = coords[((i + 1) * 2) + 1]; } double trapArea = (x1 * y2) - (x2 * y1); area += trapArea; } return area >= 0; } private static void ReadGeometryCollection(Stream data, FeatureSetPack results) { int numGeometries = ReadInt32(data); // Don't worry about "multi-parting" these. Simply create a separate shape // entry for every single geometry here since we have to split out the features // based on feature type. (currently we don't have a mixed feature type for drawing.) for (int i = 0; i < numGeometries; i++) { endian = (ByteOrder)data.ReadByte(); WKBGeometryTypes type = (WKBGeometryTypes)ReadInt32(data); switch (type) { case WKBGeometryTypes.WKBPoint: ReadPoint(data, results); return; case WKBGeometryTypes.WKBLineString: ReadLineString(data, results); return; case WKBGeometryTypes.WKBPolygon: ReadPolygon(data, results); break; case WKBGeometryTypes.WKBMultiPoint: ReadMultiPoint(data, results); break; case WKBGeometryTypes.WKBMultiLineString: ReadMultiLineString(data, results); break; case WKBGeometryTypes.WKBMultiPolygon: ReadMultiPolygon(data, results); break; case WKBGeometryTypes.WKBGeometryCollection: ReadGeometryCollection(data, results); break; } } } private static Shape ReadLineString(Stream data) { Shape result = new Shape(FeatureType.Line); int count = ReadInt32(data); double[] coords = ReadDouble(data, 2 * count); PartRange lPrt = new PartRange(FeatureType.Line) { NumVertices = count }; result.Range.Parts.Add(lPrt); result.Vertices = coords; return result; } private static void ReadLineString(Stream data, FeatureSetPack results) { int count = ReadInt32(data); double[] coords = ReadDouble(data, 2 * count); ShapeRange lShp = new ShapeRange(FeatureType.Line); PartRange lPrt = new PartRange(FeatureType.Line) { NumVertices = count }; lShp.Parts.Add(lPrt); results.Add(coords, lShp); } private static Shape ReadMultiLineString(Stream data) { Shape result = new Shape(FeatureType.Line); int numLineStrings = ReadInt32(data); List<double[]> strings = new List<double[]>(); int partOffset = 0; for (int iString = 0; iString < numLineStrings; iString++) { // Each of these needs to read a full WKBLineString data.Seek(5, SeekOrigin.Current); // ignore header int numPoints = ReadInt32(data); double[] coords = ReadDouble(data, 2 * numPoints); PartRange lPrt = new PartRange(FeatureType.Line) { PartOffset = partOffset, NumVertices = numPoints }; result.Range.Parts.Add(lPrt); partOffset += coords.Length / 2; strings.Add(coords); } double[] allVertices = new double[partOffset * 2]; int offset = 0; foreach (double[] ring in strings) { Array.Copy(ring, 0, allVertices, offset, ring.Length); offset += ring.Length; } result.Vertices = allVertices; return result; } private static void ReadMultiLineString(Stream data, FeatureSetPack results) { int numLineStrings = ReadInt32(data); ShapeRange shp = new ShapeRange(FeatureType.Line); List<double[]> strings = new List<double[]>(); int partOffset = 0; for (int iString = 0; iString < numLineStrings; iString++) { // Each of these needs to read a full WKBLineString data.Seek(5, SeekOrigin.Current); // ignore header int numPoints = ReadInt32(data); double[] coords = ReadDouble(data, 2 * numPoints); PartRange lPrt = new PartRange(FeatureType.Line) { PartOffset = partOffset, NumVertices = numPoints }; shp.Parts.Add(lPrt); partOffset += coords.Length / 2; strings.Add(coords); } double[] allVertices = new double[partOffset * 2]; int offset = 0; foreach (double[] ring in strings) { Array.Copy(ring, 0, allVertices, offset, ring.Length); offset += ring.Length; } results.Add(allVertices, shp); } /// <summary> /// Reads one multipoint shape from a data stream. /// (this assumes that the two bytes (endian and type) have already been read. /// </summary> /// <param name="data">The data to read from.</param> /// <returns>The multipoint that was read as shape.</returns> private static Shape ReadMultiPoint(Stream data) { Shape result = new Shape(FeatureType.MultiPoint); int count = ReadInt32(data); PartRange prt = new PartRange(FeatureType.MultiPoint) { NumVertices = count }; result.Range.Parts.Add(prt); double[] vertices = new double[count * 2]; for (int iPoint = 0; iPoint < count; iPoint++) { data.ReadByte(); // ignore endian ReadInt32(data); // ignore geometry type double[] coord = ReadDouble(data, 2); Array.Copy(coord, 0, vertices, iPoint * 2, 2); } result.Vertices = vertices; return result; } private static void ReadMultiPoint(Stream data, FeatureSetPack results) { int count = ReadInt32(data); ShapeRange sr = new ShapeRange(FeatureType.MultiPoint); PartRange prt = new PartRange(FeatureType.MultiPoint) { NumVertices = count }; sr.Parts.Add(prt); double[] vertices = new double[count * 2]; for (int iPoint = 0; iPoint < count; iPoint++) { data.ReadByte(); // ignore endian ReadInt32(data); // ignore geometry type double[] coord = ReadDouble(data, 2); Array.Copy(coord, 0, vertices, iPoint * 2, 2); } results.Add(vertices, sr); } private static Shape ReadMultiPolygon(Stream data) { Shape result = new Shape(FeatureType.Polygon); int numPolygons = ReadInt32(data); List<double[]> rings = new List<double[]>(); int partOffset = 0; for (int iPoly = 0; iPoly < numPolygons; iPoly++) { data.Seek(5, SeekOrigin.Current); // endian and geometry type int numRings = ReadInt32(data); for (int iRing = 0; iRing < numRings; iRing++) { int numPoints = ReadInt32(data); // ring structures are like a linestring without the final point. double[] coords = ReadDouble(data, 2 * numPoints); if (iRing == 0) { // By shapefile standard, the shell should be clockwise if (IsCounterClockwise(coords)) coords = ReverseCoords(coords); } else { // By shapefile standard, the holes should be counter clockwise. if (!IsCounterClockwise(coords)) coords = ReverseCoords(coords); } PartRange lPrt = new PartRange(FeatureType.Polygon) { PartOffset = partOffset, NumVertices = numPoints }; result.Range.Parts.Add(lPrt); partOffset += coords.Length / 2; rings.Add(coords); } } double[] allVertices = new double[partOffset * 2]; int offset = 0; foreach (double[] ring in rings) { Array.Copy(ring, 0, allVertices, offset, ring.Length); offset += ring.Length; } result.Vertices = allVertices; return result; } private static void ReadMultiPolygon(Stream data, FeatureSetPack results) { int numPolygons = ReadInt32(data); ShapeRange lShp = new ShapeRange(FeatureType.Polygon); List<double[]> rings = new List<double[]>(); int partOffset = 0; for (int iPoly = 0; iPoly < numPolygons; iPoly++) { data.Seek(5, SeekOrigin.Current); // endian and geometry type int numRings = ReadInt32(data); for (int iRing = 0; iRing < numRings; iRing++) { int numPoints = ReadInt32(data); // ring structures are like a linestring without the final point. double[] coords = ReadDouble(data, 2 * numPoints); if (iRing == 0) { // By shapefile standard, the shell should be clockwise if (IsCounterClockwise(coords)) coords = ReverseCoords(coords); } else { // By shapefile standard, the holes should be counter clockwise. if (!IsCounterClockwise(coords)) coords = ReverseCoords(coords); } PartRange lPrt = new PartRange(FeatureType.Polygon) { PartOffset = partOffset, NumVertices = numPoints }; lShp.Parts.Add(lPrt); partOffset += coords.Length / 2; rings.Add(coords); } } double[] allVertices = new double[partOffset * 2]; int offset = 0; foreach (double[] ring in rings) { Array.Copy(ring, 0, allVertices, offset, ring.Length); offset += ring.Length; } results.Add(allVertices, lShp); } /// <summary> /// This assumes that the byte order and shapetype have already been read. /// </summary> /// <param name="data">The data to read from.</param> /// <param name="results">The featureSetPack the read point gets added to.</param> private static void ReadPoint(Stream data, FeatureSetPack results) { ShapeRange sr = new ShapeRange(FeatureType.MultiPoint); PartRange prt = new PartRange(FeatureType.MultiPoint) { NumVertices = 1 }; sr.Parts.Add(prt); double[] coord = ReadDouble(data, 2); results.Add(coord, sr); } private static Shape ReadPolygon(Stream data) { Shape result = new Shape(FeatureType.Polygon); int numRings = ReadInt32(data); List<double[]> rings = new List<double[]>(); int partOffset = 0; for (int iRing = 0; iRing < numRings; iRing++) { int numPoints = ReadInt32(data); // ring structures are like a linestring without the final point. double[] coords = ReadDouble(data, 2 * numPoints); if (iRing == 0) { // By shapefile standard, the shell should be clockwise if (IsCounterClockwise(coords)) coords = ReverseCoords(coords); } else { // By shapefile standard, the holes should be counter clockwise. if (!IsCounterClockwise(coords)) coords = ReverseCoords(coords); } PartRange lPrt = new PartRange(FeatureType.Polygon) { PartOffset = partOffset, NumVertices = numPoints }; result.Range.Parts.Add(lPrt); partOffset += coords.Length / 2; rings.Add(coords); } double[] allVertices = new double[partOffset * 2]; int offset = 0; foreach (double[] ring in rings) { Array.Copy(ring, 0, allVertices, offset, ring.Length); offset += ring.Length; } result.Vertices = allVertices; return result; } private static void ReadPolygon(Stream data, FeatureSetPack results) { int numRings = ReadInt32(data); ShapeRange lShp = new ShapeRange(FeatureType.Polygon); List<double[]> rings = new List<double[]>(); int partOffset = 0; for (int iRing = 0; iRing < numRings; iRing++) { int numPoints = ReadInt32(data); // ring structures are like a linestring without the final point. double[] coords = ReadDouble(data, 2 * numPoints); if (iRing == 0) { // By shapefile standard, the shell should be clockwise if (IsCounterClockwise(coords)) coords = ReverseCoords(coords); } else { // By shapefile standard, the holes should be counter clockwise. if (!IsCounterClockwise(coords)) coords = ReverseCoords(coords); } PartRange lPrt = new PartRange(FeatureType.Polygon) { PartOffset = partOffset, NumVertices = numPoints }; lShp.Parts.Add(lPrt); partOffset += coords.Length / 2; rings.Add(coords); } double[] allVertices = new double[partOffset * 2]; int offset = 0; foreach (double[] ring in rings) { Array.Copy(ring, 0, allVertices, offset, ring.Length); offset += ring.Length; } results.Add(allVertices, lShp); } /// <summary> /// Fix introduced by JamesP@esdm.co.uk. 3/11/2010 /// Using Array.Reverse does not work because it has the unwanted effect of flipping /// the X and Y values. /// </summary> /// <param name="coords">The double precision XY coordinate array of vertices.</param> /// <returns>The double array in reverse order.</returns> private static double[] ReverseCoords(double[] coords) { int numCoords = coords.Length; double[] newCoords = new double[numCoords]; for (int i = numCoords - 1; i >= 0; i -= 2) { newCoords[i - 1] = coords[numCoords - i - 1]; // X newCoords[i] = coords[numCoords - i]; // Y } return newCoords; } #endregion } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Security; using System.Text; using System.Threading; using System.Web; using System.Web.Compilation; using NUnit.Framework; using SqlCE4Umbraco; using Umbraco.Core; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Tests; using Umbraco.Tests.TestHelpers; using Umbraco.Web.BaseRest; using umbraco; using umbraco.DataLayer; using umbraco.MacroEngines; using umbraco.businesslogic; using umbraco.cms.businesslogic; using umbraco.editorControls.tags; using umbraco.interfaces; using umbraco.uicontrols; namespace Umbraco.Tests { /// <summary> /// Tests for typefinder /// </summary> [TestFixture] public class TypeFinderTests { /// <summary> /// List of assemblies to scan /// </summary> private Assembly[] _assemblies; [SetUp] public void Initialize() { TestHelper.SetupLog4NetForTests(); _assemblies = new[] { this.GetType().Assembly, typeof(ApplicationStartupHandler).Assembly, typeof(SqlCEHelper).Assembly, typeof(CMSNode).Assembly, typeof(System.Guid).Assembly, typeof(NUnit.Framework.Assert).Assembly, typeof(Microsoft.CSharp.CSharpCodeProvider).Assembly, typeof(System.Xml.NameTable).Assembly, typeof(System.Configuration.GenericEnumConverter).Assembly, typeof(System.Web.SiteMap).Assembly, typeof(TabPage).Assembly, typeof(System.Web.Mvc.ActionResult).Assembly, typeof(TypeFinder).Assembly, typeof(ISqlHelper).Assembly, typeof(ICultureDictionary).Assembly, typeof(Tag).Assembly, typeof(global::UmbracoExamine.BaseUmbracoIndexer).Assembly }; } [Test] public void Find_Class_Of_Type_With_Attribute() { var typesFound = TypeFinder.FindClassesOfTypeWithAttribute<TestEditor, MyTestAttribute>(_assemblies); Assert.AreEqual(2, typesFound.Count()); } [Test] public void Find_Classes_Of_Type() { var typesFound = TypeFinder.FindClassesOfType<IApplicationStartupHandler>(_assemblies); var originalTypesFound = TypeFinderOriginal.FindClassesOfType<IApplicationStartupHandler>(_assemblies); Assert.AreEqual(originalTypesFound.Count(), typesFound.Count()); Assert.AreEqual(6, typesFound.Count()); Assert.AreEqual(6, originalTypesFound.Count()); } [Test] public void Find_Classes_With_Attribute() { var typesFound = TypeFinder.FindClassesWithAttribute<RestExtensionAttribute>(_assemblies); Assert.AreEqual(1, typesFound.Count()); } [Ignore] [Test] public void Benchmark_Original_Finder() { using (DisposableTimer.TraceDuration<TypeFinderTests>("Starting test", "Finished test")) { using (DisposableTimer.TraceDuration<TypeFinderTests>("Starting FindClassesOfType", "Finished FindClassesOfType")) { for (var i = 0; i < 1000; i++) { Assert.Greater(TypeFinderOriginal.FindClassesOfType<DisposableObject>(_assemblies).Count(), 0); } } using (DisposableTimer.TraceDuration<TypeFinderTests>("Starting FindClassesOfTypeWithAttribute", "Finished FindClassesOfTypeWithAttribute")) { for (var i = 0; i < 1000; i++) { Assert.Greater(TypeFinderOriginal.FindClassesOfTypeWithAttribute<TestEditor, MyTestAttribute>(_assemblies).Count(), 0); } } using (DisposableTimer.TraceDuration<TypeFinderTests>("Starting FindClassesWithAttribute", "Finished FindClassesWithAttribute")) { for (var i = 0; i < 1000; i++) { Assert.Greater(TypeFinderOriginal.FindClassesWithAttribute<XsltExtensionAttribute>(_assemblies).Count(), 0); } } } } [Ignore] [Test] public void Benchmark_New_Finder() { using (DisposableTimer.TraceDuration<TypeFinderTests>("Starting test", "Finished test")) { using (DisposableTimer.TraceDuration<TypeFinderTests>("Starting FindClassesOfType", "Finished FindClassesOfType")) { for (var i = 0; i < 1000; i++) { Assert.Greater(TypeFinder.FindClassesOfType<DisposableObject>(_assemblies).Count(), 0); } } using (DisposableTimer.TraceDuration<TypeFinderTests>("Starting FindClassesOfTypeWithAttribute", "Finished FindClassesOfTypeWithAttribute")) { for (var i = 0; i < 1000; i++) { Assert.Greater(TypeFinder.FindClassesOfTypeWithAttribute<TestEditor, MyTestAttribute>(_assemblies).Count(), 0); } } using (DisposableTimer.TraceDuration<TypeFinderTests>("Starting FindClassesWithAttribute", "Finished FindClassesWithAttribute")) { for (var i = 0; i < 1000; i++) { Assert.Greater(TypeFinder.FindClassesWithAttribute<XsltExtensionAttribute>(_assemblies).Count(), 0); } } } } public class MyTag : ITag { public int Id { get; private set; } public string TagCaption { get; private set; } public string Group { get; private set; } } public class MySuperTag : MyTag { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class MyTestAttribute : Attribute { } public abstract class TestEditor { } [MyTestAttribute] public class BenchmarkTestEditor : TestEditor { } [MyTestAttribute] public class MyOtherTestEditor : TestEditor { } //USED FOR THE ABOVE TESTS // see this issue for details: http://issues.umbraco.org/issue/U4-1187 internal static class TypeFinderOriginal { private static readonly ConcurrentBag<Assembly> LocalFilteredAssemblyCache = new ConcurrentBag<Assembly>(); private static readonly ReaderWriterLockSlim LocalFilteredAssemblyCacheLocker = new ReaderWriterLockSlim(); private static ReadOnlyCollection<Assembly> _allAssemblies = null; private static ReadOnlyCollection<Assembly> _binFolderAssemblies = null; private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim(); /// <summary> /// lazily load a reference to all assemblies and only local assemblies. /// This is a modified version of: http://www.dominicpettifer.co.uk/Blog/44/how-to-get-a-reference-to-all-assemblies-in-the--bin-folder /// </summary> /// <remarks> /// We do this because we cannot use AppDomain.Current.GetAssemblies() as this will return only assemblies that have been /// loaded in the CLR, not all assemblies. /// See these threads: /// http://issues.umbraco.org/issue/U5-198 /// http://stackoverflow.com/questions/3552223/asp-net-appdomain-currentdomain-getassemblies-assemblies-missing-after-app /// http://stackoverflow.com/questions/2477787/difference-between-appdomain-getassemblies-and-buildmanager-getreferencedassembl /// </remarks> internal static IEnumerable<Assembly> GetAllAssemblies() { if (_allAssemblies == null) { using (new WriteLock(Locker)) { List<Assembly> assemblies = null; try { var isHosted = HttpContext.Current != null; try { if (isHosted) { assemblies = new List<Assembly>(BuildManager.GetReferencedAssemblies().Cast<Assembly>()); } } catch (InvalidOperationException e) { if (!(e.InnerException is SecurityException)) throw; } if (assemblies == null) { //NOTE: we cannot use AppDomain.CurrentDomain.GetAssemblies() because this only returns assemblies that have // already been loaded in to the app domain, instead we will look directly into the bin folder and load each one. var binFolder = Assembly.GetExecutingAssembly().GetAssemblyFile().Directory; var binAssemblyFiles = Directory.GetFiles(binFolder.FullName, "*.dll", SearchOption.TopDirectoryOnly).ToList(); assemblies = new List<Assembly>(); foreach (var a in binAssemblyFiles) { try { var assName = AssemblyName.GetAssemblyName(a); var ass = Assembly.Load(assName); assemblies.Add(ass); } catch (Exception e) { if (e is SecurityException || e is BadImageFormatException) { //swallow these exceptions } else { throw; } } } } //if for some reason they are still no assemblies, then use the AppDomain to load in already loaded assemblies. if (!assemblies.Any()) { assemblies.AddRange(AppDomain.CurrentDomain.GetAssemblies().ToList()); } //here we are trying to get the App_Code assembly var fileExtensions = new[] { ".cs", ".vb" }; //only vb and cs files are supported var appCodeFolder = new DirectoryInfo(IOHelper.MapPath(IOHelper.ResolveUrl("~/App_code"))); //check if the folder exists and if there are any files in it with the supported file extensions if (appCodeFolder.Exists && (fileExtensions.Any(x => appCodeFolder.GetFiles("*" + x).Any()))) { var appCodeAssembly = Assembly.Load("App_Code"); if (!assemblies.Contains(appCodeAssembly)) // BuildManager will find App_Code already assemblies.Add(appCodeAssembly); } //now set the _allAssemblies _allAssemblies = new ReadOnlyCollection<Assembly>(assemblies); } catch (InvalidOperationException e) { if (!(e.InnerException is SecurityException)) throw; _binFolderAssemblies = _allAssemblies; } } } return _allAssemblies; } /// <summary> /// Returns only assemblies found in the bin folder that have been loaded into the app domain. /// </summary> /// <returns></returns> /// <remarks> /// This will be used if we implement App_Plugins from Umbraco v5 but currently it is not used. /// </remarks> internal static IEnumerable<Assembly> GetBinAssemblies() { if (_binFolderAssemblies == null) { using (new WriteLock(Locker)) { var assemblies = GetAssembliesWithKnownExclusions().ToArray(); var binFolder = Assembly.GetExecutingAssembly().GetAssemblyFile().Directory; var binAssemblyFiles = Directory.GetFiles(binFolder.FullName, "*.dll", SearchOption.TopDirectoryOnly).ToList(); var domainAssemblyNames = binAssemblyFiles.Select(AssemblyName.GetAssemblyName); var safeDomainAssemblies = new List<Assembly>(); var binFolderAssemblies = new List<Assembly>(); foreach (var a in assemblies) { try { //do a test to see if its queryable in med trust var assemblyFile = a.GetAssemblyFile(); safeDomainAssemblies.Add(a); } catch (SecurityException) { //we will just ignore this because this will fail //in medium trust for system assemblies, we get an exception but we just want to continue until we get to //an assembly that is ok. } } foreach (var assemblyName in domainAssemblyNames) { try { var foundAssembly = safeDomainAssemblies.FirstOrDefault(a => a.GetAssemblyFile() == assemblyName.GetAssemblyFile()); if (foundAssembly != null) { binFolderAssemblies.Add(foundAssembly); } } catch (SecurityException) { //we will just ignore this because if we are trying to do a call to: // AssemblyName.ReferenceMatchesDefinition(a.GetName(), assemblyName))) //in medium trust for system assemblies, we get an exception but we just want to continue until we get to //an assembly that is ok. } } _binFolderAssemblies = new ReadOnlyCollection<Assembly>(binFolderAssemblies); } } return _binFolderAssemblies; } /// <summary> /// Return a list of found local Assemblies excluding the known assemblies we don't want to scan /// and exluding the ones passed in and excluding the exclusion list filter, the results of this are /// cached for perforance reasons. /// </summary> /// <param name="excludeFromResults"></param> /// <returns></returns> internal static IEnumerable<Assembly> GetAssembliesWithKnownExclusions( IEnumerable<Assembly> excludeFromResults = null) { if (LocalFilteredAssemblyCache.Any()) return LocalFilteredAssemblyCache; using (new WriteLock(LocalFilteredAssemblyCacheLocker)) { var assemblies = GetFilteredAssemblies(excludeFromResults, KnownAssemblyExclusionFilter); assemblies.ForEach(LocalFilteredAssemblyCache.Add); } return LocalFilteredAssemblyCache; } /// <summary> /// Return a list of found local Assemblies and exluding the ones passed in and excluding the exclusion list filter /// </summary> /// <param name="excludeFromResults"></param> /// <param name="exclusionFilter"></param> /// <returns></returns> private static IEnumerable<Assembly> GetFilteredAssemblies( IEnumerable<Assembly> excludeFromResults = null, string[] exclusionFilter = null) { if (excludeFromResults == null) excludeFromResults = new List<Assembly>(); if (exclusionFilter == null) exclusionFilter = new string[] { }; return GetAllAssemblies() .Where(x => !excludeFromResults.Contains(x) && !x.GlobalAssemblyCache && !exclusionFilter.Any(f => x.FullName.StartsWith(f))); } /// <summary> /// this is our assembly filter to filter out known types that def dont contain types we'd like to find or plugins /// </summary> /// <remarks> /// NOTE the comma vs period... comma delimits the name in an Assembly FullName property so if it ends with comma then its an exact name match /// </remarks> internal static readonly string[] KnownAssemblyExclusionFilter = new[] { "mscorlib,", "System.", "Antlr3.", "Autofac.", "Autofac,", "Castle.", "ClientDependency.", "DataAnnotationsExtensions.", "DataAnnotationsExtensions,", "Dynamic,", "HtmlDiff,", "Iesi.Collections,", "log4net,", "Microsoft.", "Newtonsoft.", "NHibernate.", "NHibernate,", "NuGet.", "RouteDebugger,", "SqlCE4Umbraco,", "umbraco.datalayer,", "umbraco.interfaces,", "umbraco.providers,", "Umbraco.Web.UI,", "umbraco.webservices", "Lucene.", "Examine,", "Examine.", "ServiceStack.", "MySql.", "HtmlAgilityPack.", "TidyNet.", "ICSharpCode.", "CookComputing.", /* Mono */ "MonoDevelop.NUnit" }; public static IEnumerable<Type> FindClassesOfTypeWithAttribute<T, TAttribute>() where TAttribute : Attribute { return FindClassesOfTypeWithAttribute<T, TAttribute>(GetAssembliesWithKnownExclusions(), true); } public static IEnumerable<Type> FindClassesOfTypeWithAttribute<T, TAttribute>(IEnumerable<Assembly> assemblies) where TAttribute : Attribute { return FindClassesOfTypeWithAttribute<T, TAttribute>(assemblies, true); } public static IEnumerable<Type> FindClassesOfTypeWithAttribute<T, TAttribute>(IEnumerable<Assembly> assemblies, bool onlyConcreteClasses) where TAttribute : Attribute { if (assemblies == null) throw new ArgumentNullException("assemblies"); var l = new List<Type>(); foreach (var a in assemblies) { var types = from t in GetTypesWithFormattedException(a) where !t.IsInterface && typeof(T).IsAssignableFrom(t) && t.GetCustomAttributes<TAttribute>(false).Any() && (!onlyConcreteClasses || (t.IsClass && !t.IsAbstract)) select t; l.AddRange(types); } return l; } /// <summary> /// Searches all filtered local assemblies specified for classes of the type passed in. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static IEnumerable<Type> FindClassesOfType<T>() { return FindClassesOfType<T>(GetAssembliesWithKnownExclusions(), true); } /// <summary> /// Returns all types found of in the assemblies specified of type T /// </summary> /// <typeparam name="T"></typeparam> /// <param name="assemblies"></param> /// <param name="onlyConcreteClasses"></param> /// <returns></returns> public static IEnumerable<Type> FindClassesOfType<T>(IEnumerable<Assembly> assemblies, bool onlyConcreteClasses) { if (assemblies == null) throw new ArgumentNullException("assemblies"); return GetAssignablesFromType<T>(assemblies, onlyConcreteClasses); } /// <summary> /// Returns all types found of in the assemblies specified of type T /// </summary> /// <typeparam name="T"></typeparam> /// <param name="assemblies"></param> /// <returns></returns> public static IEnumerable<Type> FindClassesOfType<T>(IEnumerable<Assembly> assemblies) { return FindClassesOfType<T>(assemblies, true); } /// <summary> /// Finds the classes with attribute. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="assemblies">The assemblies.</param> /// <param name="onlyConcreteClasses">if set to <c>true</c> only concrete classes.</param> /// <returns></returns> public static IEnumerable<Type> FindClassesWithAttribute<T>(IEnumerable<Assembly> assemblies, bool onlyConcreteClasses) where T : Attribute { return FindClassesWithAttribute(typeof(T), assemblies, onlyConcreteClasses); } /// <summary> /// Finds the classes with attribute. /// </summary> /// <param name="type">The attribute type </param> /// <param name="assemblies">The assemblies.</param> /// <param name="onlyConcreteClasses">if set to <c>true</c> only concrete classes.</param> /// <returns></returns> public static IEnumerable<Type> FindClassesWithAttribute(Type type, IEnumerable<Assembly> assemblies, bool onlyConcreteClasses) { if (assemblies == null) throw new ArgumentNullException("assemblies"); if (!TypeHelper.IsTypeAssignableFrom<Attribute>(type)) throw new ArgumentException("The type specified: " + type + " is not an Attribute type"); var l = new List<Type>(); foreach (var a in assemblies) { var types = from t in GetTypesWithFormattedException(a) where !t.IsInterface && t.GetCustomAttributes(type, false).Any() && (!onlyConcreteClasses || (t.IsClass && !t.IsAbstract)) select t; l.AddRange(types); } return l; } /// <summary> /// Finds the classes with attribute. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="assemblies">The assemblies.</param> /// <returns></returns> public static IEnumerable<Type> FindClassesWithAttribute<T>(IEnumerable<Assembly> assemblies) where T : Attribute { return FindClassesWithAttribute<T>(assemblies, true); } /// <summary> /// Finds the classes with attribute in filtered local assemblies /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static IEnumerable<Type> FindClassesWithAttribute<T>() where T : Attribute { return FindClassesWithAttribute<T>(GetAssembliesWithKnownExclusions()); } #region Private methods /// <summary> /// Gets a collection of assignables of type T from a collection of assemblies /// </summary> /// <typeparam name="T"></typeparam> /// <param name="assemblies"></param> /// <param name="onlyConcreteClasses"></param> /// <returns></returns> private static IEnumerable<Type> GetAssignablesFromType<T>(IEnumerable<Assembly> assemblies, bool onlyConcreteClasses) { return GetTypes(typeof(T), assemblies, onlyConcreteClasses); } private static IEnumerable<Type> GetTypes(Type assignTypeFrom, IEnumerable<Assembly> assemblies, bool onlyConcreteClasses) { var l = new List<Type>(); foreach (var a in assemblies) { var types = from t in GetTypesWithFormattedException(a) where !t.IsInterface && assignTypeFrom.IsAssignableFrom(t) && (!onlyConcreteClasses || (t.IsClass && !t.IsAbstract)) select t; l.AddRange(types); } return l; } private static IEnumerable<Type> GetTypesWithFormattedException(Assembly a) { //if the assembly is dynamic, do not try to scan it if (a.IsDynamic) return Enumerable.Empty<Type>(); try { return a.GetExportedTypes(); } catch (ReflectionTypeLoadException ex) { var sb = new StringBuilder(); sb.AppendLine("Could not load types from assembly " + a.FullName + ", errors:"); foreach (var loaderException in ex.LoaderExceptions.WhereNotNull()) { sb.AppendLine("Exception: " + loaderException.ToString()); } throw new ReflectionTypeLoadException(ex.Types, ex.LoaderExceptions, sb.ToString()); } } #endregion } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace SampleWebApi.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 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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.Text; using Gallio.Framework.Assertions; using MbUnit.Framework; namespace MbUnit.Tests.Framework { [TestsOn(typeof(Assert))] public class AssertTest_Exceptions : BaseAssertTest { [Test] public void Throws_throws_if_arguments_invalid() { Assert.Throws<ArgumentNullException>(() => Assert.Throws<Exception>(null)); Assert.Throws<ArgumentNullException>(() => Assert.Throws<Exception>(null, "")); Assert.Throws<ArgumentNullException>(() => Assert.Throws(null, () => { })); Assert.Throws<ArgumentNullException>(() => Assert.Throws(null, () => { }, "")); Assert.Throws<ArgumentNullException>(() => Assert.Throws(typeof(Exception), null)); Assert.Throws<ArgumentNullException>(() => Assert.Throws(typeof(Exception), null, "")); } [Test] public void Throws_passes_and_returns_exception_when_expected_exception_occurs() { InvalidOperationException ex = Assert.Throws<InvalidOperationException>(() => { throw new InvalidOperationException("Exception"); }); Assert.IsNotNull(ex); Assert.AreEqual("Exception", ex.Message); } [Test] public void Throws_with_message_passes_and_returns_exception_when_expected_exception_occurs() { InvalidOperationException ex = Assert.Throws<InvalidOperationException>(() => { throw new InvalidOperationException("Exception"); }, "Foo"); Assert.IsNotNull(ex); Assert.AreEqual("Exception", ex.Message); } [Test] public void Throws_passes_and_returns_exception_when_subtype_of_expected_exception_occurs() { Exception ex = Assert.Throws<Exception>(() => { throw new InvalidOperationException("Exception"); }); Assert.IsNotNull(ex); Assert.AreEqual("Exception", ex.Message); } [Test] public void Throws_with_message_passes_and_returns_exception_when_subtype_of_expected_exception_occurs() { Exception ex = Assert.Throws<Exception>(() => { throw new InvalidOperationException("Exception"); }, "Foo"); Assert.IsNotNull(ex); Assert.AreEqual("Exception", ex.Message); } [Test] public void Throws_with_type_passes_and_returns_exception_when_expected_exception_occurs() { Exception ex = Assert.Throws(typeof(InvalidOperationException), () => { throw new InvalidOperationException("Exception"); }); Assert.IsNotNull(ex); Assert.AreEqual("Exception", ex.Message); } [Test] public void Throws_with_type_with_message_passes_and_returns_exception_when_expected_exception_occurs() { Exception ex = Assert.Throws(typeof(InvalidOperationException), () => { throw new InvalidOperationException("Exception"); }, "Foo"); Assert.IsNotNull(ex); Assert.AreEqual("Exception", ex.Message); } [Test] public void Throws_with_type_passes_and_returns_exception_when_subtype_of_expected_exception_occurs() { Exception ex = Assert.Throws(typeof(Exception), () => { throw new InvalidOperationException("Exception"); }); Assert.IsNotNull(ex); Assert.AreEqual("Exception", ex.Message); } [Test] public void Throws_with_type_with_message_passes_and_returns_exception_when_subtype_of_expected_exception_occurs() { Exception ex = Assert.Throws(typeof(Exception), () => { throw new InvalidOperationException("Exception"); }, "Foo"); Assert.IsNotNull(ex); Assert.AreEqual("Exception", ex.Message); } [Test] public void Throws_fails_if_no_exception_was_thrown() { AssertionFailure[] failures = Capture(() => Assert.Throws<InvalidOperationException>(() => { })); Assert.Count(1, failures); Assert.IsNull(failures[0].Message); Assert.AreEqual("Expected the block to throw an exception.", failures[0].Description); Assert.Count(0, failures[0].Exceptions); } [Test] public void Throws_with_message_fails_if_no_exception_was_thrown() { AssertionFailure[] failures = Capture(() => Assert.Throws<InvalidOperationException>(() => { }, "Hello {0}", "World")); Assert.Count(1, failures); Assert.AreEqual("Hello World", failures[0].Message); Assert.AreEqual("Expected the block to throw an exception.", failures[0].Description); Assert.Count(0, failures[0].Exceptions); } [Test] public void Throws_with_type_fails_if_no_exception_was_thrown() { AssertionFailure[] failures = Capture(() => Assert.Throws(typeof(InvalidOperationException), () => { })); Assert.Count(1, failures); Assert.IsNull(failures[0].Message); Assert.AreEqual("Expected the block to throw an exception.", failures[0].Description); Assert.Count(0, failures[0].Exceptions); } [Test] public void Throws_with_type_with_message_fails_if_no_exception_was_thrown() { AssertionFailure[] failures = Capture(() => Assert.Throws(typeof(InvalidOperationException), () => { }, "Hello {0}", "World")); Assert.Count(1, failures); Assert.AreEqual("Hello World", failures[0].Message); Assert.AreEqual("Expected the block to throw an exception.", failures[0].Description); Assert.Count(0, failures[0].Exceptions); } [Test] public void Throws_fails_if_supertype_of_expected_exception_was_thrown() { AssertionFailure[] failures = Capture(() => Assert.Throws<InvalidOperationException>(() => { throw new Exception("Wrong exception type."); })); Assert.Count(1, failures); Assert.IsNull(failures[0].Message); Assert.AreEqual("The block threw an exception of a different type than was expected.", failures[0].Description); Assert.Count(1, failures[0].Exceptions); Assert.AreEqual("Wrong exception type.", failures[0].Exceptions[0].Message); } [Test] public void Throws_fails_if_unrelated_expected_exception_was_thrown() { AssertionFailure[] failures = Capture(() => Assert.Throws<InvalidOperationException>(() => { throw new NotSupportedException("Wrong exception type."); })); Assert.Count(1, failures); Assert.IsNull(failures[0].Message); Assert.AreEqual("The block threw an exception of a different type than was expected.", failures[0].Description); Assert.Count(1, failures[0].Exceptions); Assert.AreEqual("Wrong exception type.", failures[0].Exceptions[0].Message); } [Test] public void DoesNotThrow_throws_if_arguments_invalid() { Assert.Throws<ArgumentNullException>(() => Assert.DoesNotThrow(null)); Assert.Throws<ArgumentNullException>(() => Assert.DoesNotThrow(null, "")); } [Test] public void DoesNotThrow_passes_if_no_exception_thrown() { Assert.DoesNotThrow(() => { }); } [Test] public void DoesNotThrow_with_message_passes_if_no_exception_thrown() { Assert.DoesNotThrow(() => { }, "Foo"); } [Test] public void DoesNotThrow_fails_if_exception_thrown() { AssertionFailure[] failures = Capture(() => Assert.DoesNotThrow(() => { throw new NotSupportedException("Boom."); })); Assert.Count(1, failures); Assert.IsNull(failures[0].Message); Assert.AreEqual("The block threw an exception but none was expected.", failures[0].Description); Assert.Count(1, failures[0].Exceptions); Assert.AreEqual("Boom.", failures[0].Exceptions[0].Message); } [Test] public void DoesNotThrow_with_message_fails_if_exception_thrown() { AssertionFailure[] failures = Capture(() => Assert.DoesNotThrow(() => { throw new NotSupportedException("Boom."); }, "Hello {0}", "World")); Assert.Count(1, failures); Assert.AreEqual("Hello World", failures[0].Message); Assert.AreEqual("The block threw an exception but none was expected.", failures[0].Description); Assert.AreEqual("Boom.", failures[0].Exceptions[0].Message); } [Test] public void Throws_passes_and_returns_exception_when_expected_exception_and_inner_exception_occur() { InvalidOperationException ex = Assert.Throws<InvalidOperationException, ArgumentException>(() => { throw new InvalidOperationException("Exception", new ArgumentException()); }); Assert.IsNotNull(ex); Assert.AreEqual("Exception", ex.Message); } [Test] public void Throws_passes_and_returns_exception_when_expected_exception_and_derived_inner_exception_occur() { InvalidOperationException ex = Assert.Throws<InvalidOperationException, ArgumentException>(() => { throw new InvalidOperationException("Exception", new ArgumentOutOfRangeException()); }); Assert.IsNotNull(ex); Assert.AreEqual("Exception", ex.Message); } [Test] public void Throws_fails_if_no_inner_exception() { AssertionFailure[] failures = Capture(() => Assert.Throws<InvalidOperationException, ArgumentException>(() => { throw new InvalidOperationException("Exception"); })); Assert.Count(1, failures); Assert.IsNull(failures[0].Message); Assert.AreEqual("The block threw an exception of the expected type, but having no inner expection.", failures[0].Description); } [Test] public void Throws_fails_if_inner_exception_does_not_match() { AssertionFailure[] failures = Capture(() => Assert.Throws<InvalidOperationException, ArgumentException>(() => { throw new InvalidOperationException("Exception", new NotSupportedException()); })); Assert.Count(1, failures); Assert.IsNull(failures[0].Message); Assert.AreEqual("The block threw an exception of the expected type, but having an unexpected inner expection.", failures[0].Description); } [Test] // Issue 769 (http://code.google.com/p/mb-unit/issues/detail?id=769) public void DoesNotThrow_should_not_fail_because_of_an_inner_assertion_failure() { AssertionFailure[] failures = Capture(() => Assert.DoesNotThrow(() => Assert.Fail())); Assert.Count(1, failures); // Only Assert.Fail should cause a failure. Assert.IsNull(failures[0].Message); Assert.AreEqual("An assertion failed.", failures[0].Description); } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.IO; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using Aurora.Framework; using Aurora.Framework.Capabilities; using Aurora.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; namespace Aurora.Modules.Auction { public class AuctionModule : IAuctionModule, INonSharedRegionModule { private IScene m_scene; #region INonSharedRegionModule Members public void Initialise(IConfigSource pSource) { } public void AddRegion(IScene scene) { m_scene = scene; m_scene.EventManager.OnRegisterCaps += RegisterCaps; m_scene.EventManager.OnNewClient += OnNewClient; m_scene.EventManager.OnClosingClient += OnClosingClient; } public void RemoveRegion(IScene scene) { m_scene.EventManager.OnRegisterCaps -= RegisterCaps; m_scene.EventManager.OnNewClient -= OnNewClient; m_scene.EventManager.OnClosingClient -= OnClosingClient; } public void RegionLoaded(IScene scene) { } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "AuctionModule"; } } public void Close() { } #endregion #region Client members public void OnNewClient(IClientAPI client) { client.OnViewerStartAuction += StartAuction; } private void OnClosingClient(IClientAPI client) { client.OnViewerStartAuction -= StartAuction; } public void StartAuction(IClientAPI client, int LocalID, UUID SnapshotID) { if (!m_scene.Permissions.IsGod(client.AgentId)) return; StartAuction(LocalID, SnapshotID); } #endregion #region CAPS public OSDMap RegisterCaps(UUID agentID, IHttpServer server) { OSDMap retVal = new OSDMap(); retVal["ViewerStartAuction"] = CapsUtil.CreateCAPS("ViewerStartAuction", ""); server.AddStreamHandler(new GenericStreamHandler("POST", retVal["ViewerStartAuction"], ViewerStartAuction)); return retVal; } private byte[] ViewerStartAuction(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { //OSDMap rm = (OSDMap)OSDParser.DeserializeLLSDXml(request); return MainServer.NoResponse; } #endregion #region IAuctionModule members public void StartAuction(int LocalID, UUID SnapshotID) { IParcelManagementModule parcelManagement = m_scene.RequestModuleInterface<IParcelManagementModule>(); if (parcelManagement != null) { ILandObject landObject = parcelManagement.GetLandObject(LocalID); if (landObject == null) return; landObject.LandData.SnapshotID = SnapshotID; landObject.LandData.AuctionID = (uint)Util.RandomClass.Next(0, int.MaxValue); landObject.LandData.Status = ParcelStatus.Abandoned; landObject.SendLandUpdateToAvatarsOverMe(); } } public void SetAuctionInfo(int LocalID, AuctionInfo info) { SaveAuctionInfo(LocalID, info); } public void AddAuctionBid(int LocalID, UUID userID, int bid) { AuctionInfo info = GetAuctionInfo(LocalID); info.AuctionBids.Add(new AuctionBid() { Amount = bid, AuctionBidder = userID, TimeBid = DateTime.Now }); SaveAuctionInfo(LocalID, info); } public void AuctionEnd(int LocalID) { IParcelManagementModule parcelManagement = m_scene.RequestModuleInterface<IParcelManagementModule>(); if (parcelManagement != null) { ILandObject landObject = parcelManagement.GetLandObject(LocalID); if (landObject == null) return; AuctionInfo info = GetAuctionInfo(LocalID); AuctionBid highestBid = new AuctionBid() { Amount = 0 }; foreach (AuctionBid bid in info.AuctionBids) if (highestBid.Amount < bid.Amount) highestBid = bid; IOfflineMessagesConnector offlineMessages = Aurora.DataManager.DataManager.RequestPlugin<IOfflineMessagesConnector>(); if (offlineMessages != null) offlineMessages.AddOfflineMessage(new GridInstantMessage() { binaryBucket = new byte[0], dialog = (byte)InstantMessageDialog.MessageBox, fromAgentID = UUID.Zero, fromAgentName = "System", fromGroup = false, imSessionID = UUID.Random(), message = "You won the auction for the parcel " + landObject.LandData.Name + ", paying " + highestBid.Amount + " for it", offline = 0, ParentEstateID = 0, Position = Vector3.Zero, RegionID = m_scene.RegionInfo.RegionID, timestamp = (uint)Util.UnixTimeSinceEpoch(), toAgentID = highestBid.AuctionBidder }); landObject.UpdateLandSold(highestBid.AuctionBidder, UUID.Zero, false, landObject.LandData.AuctionID, highestBid.Amount, landObject.LandData.Area); } } private void SaveAuctionInfo(int LocalID, AuctionInfo info) { IParcelManagementModule parcelManagement = m_scene.RequestModuleInterface<IParcelManagementModule>(); if (parcelManagement != null) { ILandObject landObject = parcelManagement.GetLandObject(LocalID); if (landObject == null) return; landObject.LandData.GenericData["AuctionInfo"] = info.ToOSD(); } } private AuctionInfo GetAuctionInfo(int LocalID) { IParcelManagementModule parcelManagement = m_scene.RequestModuleInterface<IParcelManagementModule>(); if (parcelManagement != null) { ILandObject landObject = parcelManagement.GetLandObject(LocalID); if (landObject == null) return null; OSDMap map = (OSDMap)landObject.LandData.GenericData["AuctionInfo"]; AuctionInfo info = new AuctionInfo(); info.FromOSD(map); return info; } return null; } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using Avalonia.Collections; using Avalonia.Controls; #nullable enable namespace Avalonia.Styling { /// <summary> /// A style that consists of a number of child styles. /// </summary> public class Styles : AvaloniaObject, IAvaloniaList<IStyle>, IStyle, IResourceProvider { private readonly AvaloniaList<IStyle> _styles = new AvaloniaList<IStyle>(); private IResourceHost? _owner; private IResourceDictionary? _resources; private Dictionary<Type, List<IStyle>?>? _cache; public Styles() { _styles.ResetBehavior = ResetBehavior.Remove; _styles.CollectionChanged += OnCollectionChanged; } public Styles(IResourceHost owner) : this() { Owner = owner; } public event NotifyCollectionChangedEventHandler? CollectionChanged; public event EventHandler? OwnerChanged; public int Count => _styles.Count; public IResourceHost? Owner { get => _owner; private set { if (_owner != value) { _owner = value; OwnerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Gets or sets a dictionary of style resources. /// </summary> public IResourceDictionary Resources { get => _resources ?? (Resources = new ResourceDictionary()); set { value = value ?? throw new ArgumentNullException(nameof(Resources)); if (Owner is object) { _resources?.RemoveOwner(Owner); } _resources = value; if (Owner is object) { _resources.AddOwner(Owner); } } } bool ICollection<IStyle>.IsReadOnly => false; bool IResourceNode.HasResources { get { if (_resources?.Count > 0) { return true; } foreach (var i in this) { if (i is IResourceProvider p && p.HasResources) { return true; } } return false; } } IStyle IReadOnlyList<IStyle>.this[int index] => _styles[index]; IReadOnlyList<IStyle> IStyle.Children => this; public IStyle this[int index] { get => _styles[index]; set => _styles[index] = value; } public SelectorMatchResult TryAttach(IStyleable target, IStyleHost? host) { _cache ??= new Dictionary<Type, List<IStyle>?>(); if (_cache.TryGetValue(target.StyleKey, out var cached)) { if (cached is object) { foreach (var style in cached) { style.TryAttach(target, host); } return SelectorMatchResult.AlwaysThisType; } else { return SelectorMatchResult.NeverThisType; } } else { List<IStyle>? matches = null; foreach (var child in this) { if (child.TryAttach(target, host) != SelectorMatchResult.NeverThisType) { matches ??= new List<IStyle>(); matches.Add(child); } } _cache.Add(target.StyleKey, matches); return matches is null ? SelectorMatchResult.NeverThisType : SelectorMatchResult.AlwaysThisType; } } /// <inheritdoc/> public bool TryGetResource(object key, out object? value) { if (_resources != null && _resources.TryGetResource(key, out value)) { return true; } for (var i = Count - 1; i >= 0; --i) { if (this[i] is IResourceProvider p && p.TryGetResource(key, out value)) { return true; } } value = null; return false; } /// <inheritdoc/> public void AddRange(IEnumerable<IStyle> items) => _styles.AddRange(items); /// <inheritdoc/> public void InsertRange(int index, IEnumerable<IStyle> items) => _styles.InsertRange(index, items); /// <inheritdoc/> public void Move(int oldIndex, int newIndex) => _styles.Move(oldIndex, newIndex); /// <inheritdoc/> public void MoveRange(int oldIndex, int count, int newIndex) => _styles.MoveRange(oldIndex, count, newIndex); /// <inheritdoc/> public void RemoveAll(IEnumerable<IStyle> items) => _styles.RemoveAll(items); /// <inheritdoc/> public void RemoveRange(int index, int count) => _styles.RemoveRange(index, count); /// <inheritdoc/> public int IndexOf(IStyle item) => _styles.IndexOf(item); /// <inheritdoc/> public void Insert(int index, IStyle item) => _styles.Insert(index, item); /// <inheritdoc/> public void RemoveAt(int index) => _styles.RemoveAt(index); /// <inheritdoc/> public void Add(IStyle item) => _styles.Add(item); /// <inheritdoc/> public void Clear() => _styles.Clear(); /// <inheritdoc/> public bool Contains(IStyle item) => _styles.Contains(item); /// <inheritdoc/> public void CopyTo(IStyle[] array, int arrayIndex) => _styles.CopyTo(array, arrayIndex); /// <inheritdoc/> public bool Remove(IStyle item) => _styles.Remove(item); public AvaloniaList<IStyle>.Enumerator GetEnumerator() => _styles.GetEnumerator(); /// <inheritdoc/> IEnumerator<IStyle> IEnumerable<IStyle>.GetEnumerator() => _styles.GetEnumerator(); /// <inheritdoc/> IEnumerator IEnumerable.GetEnumerator() => _styles.GetEnumerator(); /// <inheritdoc/> void IResourceProvider.AddOwner(IResourceHost owner) { owner = owner ?? throw new ArgumentNullException(nameof(owner)); if (Owner != null) { throw new InvalidOperationException("The Styles already has a owner."); } Owner = owner; _resources?.AddOwner(owner); foreach (var child in this) { if (child is IResourceProvider r) { r.AddOwner(owner); } } } /// <inheritdoc/> void IResourceProvider.RemoveOwner(IResourceHost owner) { owner = owner ?? throw new ArgumentNullException(nameof(owner)); if (Owner == owner) { Owner = null; _resources?.RemoveOwner(owner); foreach (var child in this) { if (child is IResourceProvider r) { r.RemoveOwner(owner); } } } } private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { static IReadOnlyList<T> ToReadOnlyList<T>(IList list) { if (list is IReadOnlyList<T>) { return (IReadOnlyList<T>)list; } else { var result = new T[list.Count]; list.CopyTo(result, 0); return result; } } void Add(IList items) { for (var i = 0; i < items.Count; ++i) { var style = (IStyle)items[i]; if (Owner is object && style is IResourceProvider resourceProvider) { resourceProvider.AddOwner(Owner); } _cache = null; } (Owner as IStyleHost)?.StylesAdded(ToReadOnlyList<IStyle>(items)); } void Remove(IList items) { for (var i = 0; i < items.Count; ++i) { var style = (IStyle)items[i]; if (Owner is object && style is IResourceProvider resourceProvider) { resourceProvider.RemoveOwner(Owner); } _cache = null; } (Owner as IStyleHost)?.StylesRemoved(ToReadOnlyList<IStyle>(items)); } switch (e.Action) { case NotifyCollectionChangedAction.Add: Add(e.NewItems); break; case NotifyCollectionChangedAction.Remove: Remove(e.OldItems); break; case NotifyCollectionChangedAction.Replace: Remove(e.OldItems); Add(e.NewItems); break; case NotifyCollectionChangedAction.Reset: throw new InvalidOperationException("Reset should not be called on Styles."); } CollectionChanged?.Invoke(this, e); } } }
// Transport Security Layer (TLS) // Copyright (c) 2003-2004 Carlos Guzman Alvarez // Copyright (C) 2004, 2006-2010 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Net; using System.Collections; using System.Globalization; using System.Text.RegularExpressions; using System.Security.Cryptography; using X509Cert = System.Security.Cryptography.X509Certificates; using Mono.Security.X509; using Mono.Security.X509.Extensions; using Mono.Security.Interface; namespace Mono.Security.Protocol.Tls.Handshake.Client { internal class TlsServerCertificate : HandshakeMessage { #region Fields private X509CertificateCollection certificates; #endregion #region Constructors public TlsServerCertificate(Context context, byte[] buffer) : base(context, HandshakeType.Certificate, buffer) { } #endregion #region Methods public override void Update() { base.Update(); this.Context.ServerSettings.Certificates = this.certificates; this.Context.ServerSettings.UpdateCertificateRSA(); } #endregion #region Protected Methods protected override void ProcessAsSsl3() { this.ProcessAsTls1(); } protected override void ProcessAsTls1() { this.certificates = new X509CertificateCollection(); int readed = 0; int length = this.ReadInt24(); while (readed < length) { // Read certificate length int certLength = ReadInt24(); // Increment readed readed += 3; if (certLength > 0) { // Read certificate data byte[] buffer = this.ReadBytes(certLength); // Create a new X509 Certificate X509Certificate certificate = new X509Certificate(buffer); certificates.Add(certificate); readed += certLength; DebugHelper.WriteLine( String.Format("Server Certificate {0}", certificates.Count), buffer); } } this.validateCertificates(certificates); } #endregion #region Private Methods // Note: this method only works for RSA certificates // DH certificates requires some changes - does anyone use one ? private bool checkCertificateUsage (X509Certificate cert) { ClientContext context = (ClientContext)this.Context; // certificate extensions are required for this // we "must" accept older certificates without proofs if (cert.Version < 3) return true; KeyUsages ku = KeyUsages.none; switch (context.Negotiating.Cipher.ExchangeAlgorithmType) { case ExchangeAlgorithmType.RsaSign: ku = KeyUsages.digitalSignature; break; case ExchangeAlgorithmType.RsaKeyX: ku = KeyUsages.keyEncipherment; break; case ExchangeAlgorithmType.DiffieHellman: ku = KeyUsages.keyAgreement; break; case ExchangeAlgorithmType.Fortezza: return false; // unsupported certificate type } KeyUsageExtension kux = null; ExtendedKeyUsageExtension eku = null; X509Extension xtn = cert.Extensions ["2.5.29.15"]; if (xtn != null) kux = new KeyUsageExtension (xtn); xtn = cert.Extensions ["2.5.29.37"]; if (xtn != null) eku = new ExtendedKeyUsageExtension (xtn); if ((kux != null) && (eku != null)) { // RFC3280 states that when both KeyUsageExtension and // ExtendedKeyUsageExtension are present then BOTH should // be valid if (!kux.Support (ku)) return false; return (eku.KeyPurpose.Contains ("1.3.6.1.5.5.7.3.1") || eku.KeyPurpose.Contains ("2.16.840.1.113730.4.1")); } else if (kux != null) { return kux.Support (ku); } else if (eku != null) { // Server Authentication (1.3.6.1.5.5.7.3.1) or // Netscape Server Gated Crypto (2.16.840.1.113730.4) return (eku.KeyPurpose.Contains ("1.3.6.1.5.5.7.3.1") || eku.KeyPurpose.Contains ("2.16.840.1.113730.4.1")); } // last chance - try with older (deprecated) Netscape extensions xtn = cert.Extensions ["2.16.840.1.113730.1.1"]; if (xtn != null) { NetscapeCertTypeExtension ct = new NetscapeCertTypeExtension (xtn); return ct.Support (NetscapeCertTypeExtension.CertTypes.SslServer); } // if the CN=host (checked later) then we assume this is meant for SSL/TLS // e.g. the new smtp.gmail.com certificate return true; } private void validateCertificates(X509CertificateCollection certificates) { ClientContext context = (ClientContext)this.Context; AlertDescription description = AlertDescription.BadCertificate; #if INSIDE_SYSTEM // This helps the linker to remove a lot of validation code that will never be used since // System.dll will, for OSX and iOS, uses the operating system X.509 certificate validations RemoteValidation (context, description); #else if (context.SslStream.HaveRemoteValidation2Callback) RemoteValidation (context, description); else LocalValidation (context, description); #endif } void RemoteValidation (ClientContext context, AlertDescription description) { ValidationResult res = context.SslStream.RaiseServerCertificateValidation2 (certificates); if (res.Trusted) return; long error = res.ErrorCode; switch (error) { case 0x800B0101: description = AlertDescription.CertificateExpired; break; case 0x800B010A: description = AlertDescription.UnknownCA; break; case 0x800B0109: description = AlertDescription.UnknownCA; break; default: description = AlertDescription.CertificateUnknown; break; } string err = String.Format ("Invalid certificate received from server. Error code: 0x{0:x}", error); throw new TlsException (description, err); } void LocalValidation (ClientContext context, AlertDescription description) { // the leaf is the web server certificate X509Certificate leaf = certificates [0]; X509Cert.X509Certificate cert = new X509Cert.X509Certificate (leaf.RawData); ArrayList errors = new ArrayList(); // SSL specific check - not all certificates can be // used to server-side SSL some rules applies after // all ;-) if (!checkCertificateUsage (leaf)) { // WinError.h CERT_E_PURPOSE 0x800B0106 errors.Add ((int)-2146762490); } // SSL specific check - does the certificate match // the host ? if (!checkServerIdentity (leaf)) { // WinError.h CERT_E_CN_NO_MATCH 0x800B010F errors.Add ((int)-2146762481); } // Note: building and verifying a chain can take much time // so we do it last (letting simple things fails first) // Note: In TLS the certificates MUST be in order (and // optionally include the root certificate) so we're not // building the chain using LoadCertificate (it's faster) // Note: IIS doesn't seem to send the whole certificate chain // but only the server certificate :-( it's assuming that you // already have this chain installed on your computer. duh! // http://groups.google.ca/groups?q=IIS+server+certificate+chain&hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=85058s%24avd%241%40nnrp1.deja.com&rnum=3 // we must remove the leaf certificate from the chain X509CertificateCollection chain = new X509CertificateCollection (certificates); chain.Remove (leaf); X509Chain verify = new X509Chain (chain); bool result = false; try { result = verify.Build (leaf); } catch (Exception) { result = false; } if (!result) { switch (verify.Status) { case X509ChainStatusFlags.InvalidBasicConstraints: // WinError.h TRUST_E_BASIC_CONSTRAINTS 0x80096019 errors.Add ((int)-2146869223); break; case X509ChainStatusFlags.NotSignatureValid: // WinError.h TRUST_E_BAD_DIGEST 0x80096010 errors.Add ((int)-2146869232); break; case X509ChainStatusFlags.NotTimeNested: // WinError.h CERT_E_VALIDITYPERIODNESTING 0x800B0102 errors.Add ((int)-2146762494); break; case X509ChainStatusFlags.NotTimeValid: // WinError.h CERT_E_EXPIRED 0x800B0101 description = AlertDescription.CertificateExpired; errors.Add ((int)-2146762495); break; case X509ChainStatusFlags.PartialChain: // WinError.h CERT_E_CHAINING 0x800B010A description = AlertDescription.UnknownCA; errors.Add ((int)-2146762486); break; case X509ChainStatusFlags.UntrustedRoot: // WinError.h CERT_E_UNTRUSTEDROOT 0x800B0109 description = AlertDescription.UnknownCA; errors.Add ((int)-2146762487); break; default: // unknown error description = AlertDescription.CertificateUnknown; errors.Add ((int)verify.Status); break; } } int[] certificateErrors = (int[])errors.ToArray(typeof(int)); if (!context.SslStream.RaiseServerCertificateValidation( cert, certificateErrors)) { throw new TlsException( description, "Invalid certificate received from server."); } } // RFC2818 - HTTP Over TLS, Section 3.1 // http://www.ietf.org/rfc/rfc2818.txt // // 1. if present MUST use subjectAltName dNSName as identity // 1.1. if multiples entries a match of any one is acceptable // 1.2. wildcard * is acceptable // 2. URI may be an IP address -> subjectAltName.iPAddress // 2.1. exact match is required // 3. Use of the most specific Common Name (CN=) in the Subject // 3.1 Existing practice but DEPRECATED private bool checkServerIdentity (X509Certificate cert) { ClientContext context = (ClientContext)this.Context; string targetHost = context.ClientSettings.TargetHost; X509Extension ext = cert.Extensions ["2.5.29.17"]; // 1. subjectAltName if (ext != null) { SubjectAltNameExtension subjectAltName = new SubjectAltNameExtension (ext); // 1.1 - multiple dNSName foreach (string dns in subjectAltName.DNSNames) { // 1.2 TODO - wildcard support if (Match (targetHost, dns)) return true; } // 2. ipAddress foreach (string ip in subjectAltName.IPAddresses) { // 2.1. Exact match required if (ip == targetHost) return true; } } // 3. Common Name (CN=) return checkDomainName (cert.SubjectName); } private bool checkDomainName(string subjectName) { ClientContext context = (ClientContext)this.Context; string domainName = String.Empty; Regex search = new Regex(@"CN\s*=\s*([^,]*)"); MatchCollection elements = search.Matches(subjectName); if (elements.Count == 1) { if (elements[0].Success) { domainName = elements[0].Groups[1].Value.ToString(); } } return Match (context.ClientSettings.TargetHost, domainName); } // ensure the pattern is valid wrt to RFC2595 and RFC2818 // http://www.ietf.org/rfc/rfc2595.txt // http://www.ietf.org/rfc/rfc2818.txt static bool Match (string hostname, string pattern) { // check if this is a pattern int index = pattern.IndexOf ('*'); if (index == -1) { // not a pattern, do a direct case-insensitive comparison return (String.Compare (hostname, pattern, true, CultureInfo.InvariantCulture) == 0); } // check pattern validity // A "*" wildcard character MAY be used as the left-most name component in the certificate. // unless this is the last char (valid) if (index != pattern.Length - 1) { // then the next char must be a dot .'. if (pattern [index + 1] != '.') return false; } // only one (A) wildcard is supported int i2 = pattern.IndexOf ('*', index + 1); if (i2 != -1) return false; // match the end of the pattern string end = pattern.Substring (index + 1); int length = hostname.Length - end.Length; // no point to check a pattern that is longer than the hostname if (length <= 0) return false; if (String.Compare (hostname, length, end, 0, end.Length, true, CultureInfo.InvariantCulture) != 0) return false; // special case, we start with the wildcard if (index == 0) { // ensure we hostname non-matched part (start) doesn't contain a dot int i3 = hostname.IndexOf ('.'); return ((i3 == -1) || (i3 >= (hostname.Length - end.Length))); } // match the start of the pattern string start = pattern.Substring (0, index); return (String.Compare (hostname, 0, start, 0, start.Length, true, CultureInfo.InvariantCulture) == 0); } #endregion } }
//--------------------------------------------------------------------------- // // <copyright file="ProxyManager.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: Manages Win32 proxies // // History: // 06/02/2003 : BrendanM Ported to WCP // //--------------------------------------------------------------------------- // PRESHARP: In order to avoid generating warnings about unkown message numbers and unknown pragmas. #pragma warning disable 1634, 1691 using System; using System.Windows; using System.Windows.Automation; using System.Windows.Automation.Provider; using System.Text; using System.Globalization; using System.Collections; using System.Runtime.InteropServices; using System.Reflection; using System.Diagnostics; using System.Runtime.Serialization; using System.Security.Permissions; using System.ComponentModel; using MS.Win32; namespace MS.Internal.Automation { internal sealed class ProxyManager { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors // Static class - Private constructor to prevent creation private ProxyManager() { } #endregion Constructors //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods #region Proxy registration and table management // load proxies from specified assembly internal static void RegisterProxyAssembly ( AssemblyName assemblyName ) { Assembly a = null; try { a = Assembly.Load( assemblyName ); } catch(System.IO.FileNotFoundException) { throw new ProxyAssemblyNotLoadedException(SR.Get(SRID.Assembly0NotFound,assemblyName)); } string typeName = assemblyName.Name + ".UIAutomationClientSideProviders"; Type t = a.GetType( typeName ); if( t == null ) { throw new ProxyAssemblyNotLoadedException(SR.Get(SRID.CouldNotFindType0InAssembly1, typeName, assemblyName)); } FieldInfo fi = t.GetField("ClientSideProviderDescriptionTable", BindingFlags.Static | BindingFlags.Public); if (fi == null || fi.FieldType != typeof(ClientSideProviderDescription[])) { throw new ProxyAssemblyNotLoadedException(SR.Get(SRID.CouldNotFindRegisterMethodOnType0InAssembly1, typeName, assemblyName)); } ClientSideProviderDescription[] table = fi.GetValue(null) as ClientSideProviderDescription[]; if (table != null) { ClientSettings.RegisterClientSideProviders(table); } } // register specified proxies internal static void RegisterWindowHandlers(ClientSideProviderDescription[] proxyInfo) { // If a client registers a proxy before the defaults proxies are loaded because of use, // we should load the defaults first. LoadDefaultProxies(); lock (_lockObj) { AddToProxyDescriptionTable( proxyInfo ); } } // set proxy table to specified array, clearing any previously registered proxies internal static void SetProxyDescriptionTable(ClientSideProviderDescription[] proxyInfo) { lock (_lockObj) { // This method replaces the entire table. So clear all the collections for( int i = 0 ; i < _pseudoProxies.Length ; i++ ) { _pseudoProxies[ i ] = null; } _classHandlers.Clear(); _partialClassHandlers.Clear(); _imageOnlyHandlers.Clear(); _fallbackHandlers.Clear(); AddToProxyDescriptionTable( proxyInfo ); // if someone calls this method before the default proxies are // loaded assume they don't want us to add the defaults on top // of the ones they just put into affect here _defaultProxiesNeeded = false; } } // return an array representing the currently registered proxies internal static ClientSideProviderDescription[] GetProxyDescriptionTable() { // the ClientSideProviderDescription table is split into four different collections. Bundle them all back // together to let them be manipulated // If a client gets the table before the defaults proxies are loaded because of use, it should return the default proxies LoadDefaultProxies(); lock (_lockObj) { int count = 0; IEnumerable [ ] sourceProxyDescription = {_classHandlers, _partialClassHandlers, _imageOnlyHandlers, _fallbackHandlers}; // figure out how many there are foreach ( IEnumerable e in sourceProxyDescription ) { foreach ( Object item in e ) { Object o = item; if( o is DictionaryEntry ) o = ((DictionaryEntry)o).Value; if (o is ClientSideProviderDescription) { count++; } else if (o is ClientSideProviderFactoryCallback) { count++; } else { count += ((ArrayList)o).Count; } } } ClientSideProviderDescription[] proxyDescriptions = new ClientSideProviderDescription[count]; count = 0; // Because the four collections have a simular stucture in common we can treat like they are the same // and build the array in the correct order from each one. foreach ( IEnumerable e in sourceProxyDescription ) { foreach ( Object item in e ) { Object o = item; if( o is DictionaryEntry ) o = ((DictionaryEntry)o).Value; if (o is ClientSideProviderDescription) { proxyDescriptions[count++] = (ClientSideProviderDescription)o; } else if (o is ClientSideProviderFactoryCallback) { ClientSideProviderFactoryCallback pfc = (ClientSideProviderFactoryCallback)o; proxyDescriptions[count++] = new ClientSideProviderDescription(pfc, null); } else { foreach( Object o1 in (ArrayList) o ) { proxyDescriptions[count++] = (ClientSideProviderDescription)o1; } } } } return proxyDescriptions; } } #endregion Proxy registration and table management #region Methods that return a proxy or native object // helper to return the non-client area provider internal static IRawElementProviderSimple GetNonClientProvider( IntPtr hwnd ) { ClientSideProviderFactoryCallback nonClientFactory = ProxyManager.NonClientProxyFactory; if( nonClientFactory == null ) return null; return nonClientFactory( hwnd, 0, UnsafeNativeMethods.OBJID_CLIENT ); } // helper to return the User32FocusedMenu provider internal static IRawElementProviderSimple GetUser32FocusedMenuProvider( IntPtr hwnd ) { ClientSideProviderFactoryCallback menuFactory = ProxyManager.User32FocusedMenuProxyFactory; if( menuFactory == null ) return null; return menuFactory( hwnd, 0, UnsafeNativeMethods.OBJID_CLIENT ); } #endregion Methods that return a proxy or native object #region miscellaneous HWND rountines internal static string GetClassName( NativeMethods.HWND hwnd ) { StringBuilder str = new StringBuilder( NativeMethods.MAX_PATH ); int result = SafeNativeMethods.GetClassName(hwnd, str, NativeMethods.MAX_PATH); int lastWin32Error = Marshal.GetLastWin32Error(); if (result == 0) { Misc.ThrowWin32ExceptionsIfError(lastWin32Error); } return str.ToString(); } internal static string RealGetWindowClass( NativeMethods.HWND hwnd ) { StringBuilder str = new StringBuilder( NativeMethods.MAX_PATH ); int result = SafeNativeMethods.RealGetWindowClass(hwnd, str, NativeMethods.MAX_PATH); int lastWin32Error = Marshal.GetLastWin32Error(); if (result == 0) { Misc.ThrowWin32ExceptionsIfError(lastWin32Error); } return str.ToString(); } private static string [] BadImplClassnames = new string [] { // The following classes are known to not check the lParam to WM_GETOBJECT, so avoid them: // Keep list in [....] with UiaNodeFactory.cpp "TrayClockWClass", "REListBox20W", "REComboBox20W", "WMP Skin Host", "CWmpControlCntr", "WMP Plugin UI Host", }; internal static bool IsKnownBadWindow( NativeMethods.HWND hwnd ) { string className = GetClassName( hwnd ); foreach (string str in BadImplClassnames) { if (String.Compare(className, str, StringComparison.OrdinalIgnoreCase) == 0) return true; } // Check for problem minimized WMP window: this class is only used // when WMP10 is minimized into the task bar. It's an ATL:... class, // so have to check via parent. Structure looks like: // ... // ReBarWindow32 - taskbar rebar window // WMP9DeskBand // WMP9ActiveXHost122294984 // ATL::0754F282 <- this is the bad one NativeMethods.HWND hwndParent = SafeNativeMethods.GetAncestor(hwnd, SafeNativeMethods.GA_PARENT); if (hwndParent != NativeMethods.HWND.NULL) { string parentClassName = GetClassName(hwndParent); if (parentClassName.StartsWith("WMP9ActiveXHost", StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } // find the name of the image for this HWND. If this fails for any reason just return null. // Review: Getting the image name is expessive if the image name starts to be used a lot // we could cache it in a static hash using the PID as the key. internal static string GetImageName( NativeMethods.HWND hwnd ) { int instance = Misc.GetWindowLong(hwnd, SafeNativeMethods.GWL_HINSTANCE); if ( instance == 0 ) { return null; } StringBuilder sb = new StringBuilder(NativeMethods.MAX_PATH); using (SafeProcessHandle processHandle = new SafeProcessHandle(hwnd)) { if (processHandle.IsInvalid) { return null; } if (Misc.GetModuleFileNameEx(processHandle, (IntPtr)instance, sb, NativeMethods.MAX_PATH) == 0) { return null; } } return System.IO.Path.GetFileName(sb.ToString().ToLower(CultureInfo.InvariantCulture)); } #endregion miscellaneous HWND rountines internal static void LoadDefaultProxies( ) { //No need to load the default providers if they are already loaded if (!_defaultProxiesNeeded) return; // set this bool before we even know that the default proxies were loaded because if there was // a problem we don't want to go thru the following overhead for every hwnd. We just try this // once per process. _defaultProxiesNeeded = false; #if (INTERNAL_COMPILE || INTERNALTESTUIAUTOMATION) ClientSettings.RegisterClientSideProviders(UIAutomationClientsideProviders.UIAutomationClientSideProviders.ClientSideProviderDescriptionTable); #else Assembly callingAssembly = null; Assembly currentAssembly = Assembly.GetExecutingAssembly(); // Walk up the stack looking for the first assembly that is different than the ExecutingAssembly // This would be the assembly that called us. StackTrace st = new StackTrace(); for ( int i=0; i < st.FrameCount; i++ ) { StackFrame sf = st.GetFrame(i); MethodBase mb = sf.GetMethod(); Type t = mb.ReflectedType; Assembly a = t.Assembly; if ( a.GetName().Name != currentAssembly.GetName().Name ) { callingAssembly = a; break; } } AssemblyName ourAssembly = Assembly.GetAssembly(typeof(ProxyManager)).GetName(); // Attempt to discover the version of UIA that the caller is linked against, // and then use the correpsonding proxy dll version. If we can't do that, // we'll use the default version. AssemblyName proxyAssemblyName = new AssemblyName(); proxyAssemblyName.Name = _defaultProxyAssembly; proxyAssemblyName.Version = ourAssembly.Version; proxyAssemblyName.CultureInfo = ourAssembly.CultureInfo; proxyAssemblyName.SetPublicKeyToken( ourAssembly.GetPublicKeyToken() ); if ( callingAssembly != null ) { // find the name of the UIAutomation dll referenced by this assembly because it my be different // from the one that acually got loaded. We want to load the proxy dll that matches this one. // This simulates behave simular to fusion side-by-side. AssemblyName assemblyName = new AssemblyName(); foreach ( AssemblyName name in callingAssembly.GetReferencedAssemblies() ) { if ( name.Name == ourAssembly.Name ) { assemblyName = name; break; } } if ( assemblyName.Name != null ) { proxyAssemblyName.Version = assemblyName.Version; proxyAssemblyName.CultureInfo = assemblyName.CultureInfo; proxyAssemblyName.SetPublicKeyToken( assemblyName.GetPublicKeyToken() ); } } RegisterProxyAssembly( proxyAssemblyName ); #endif } #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties // Disable use of default proxies. // This is used to stop the proxies frrom being loaded on the server. internal static void DisableDefaultProxies() { _defaultProxiesNeeded = false; } internal static ClientSideProviderFactoryCallback NonClientProxyFactory { get { return _pseudoProxies[ (int)PseudoProxy.NonClient ]; } } internal static ClientSideProviderFactoryCallback NonClientMenuBarProxyFactory { get { return _pseudoProxies[ (int)PseudoProxy.NonClientMenuBar ]; } } internal static ClientSideProviderFactoryCallback NonClientSysMenuProxyFactory { get { return _pseudoProxies[ (int)PseudoProxy.NonClientSysMenu ]; } } internal static ClientSideProviderFactoryCallback User32FocusedMenuProxyFactory { get { return _pseudoProxies[ (int)PseudoProxy.User32FocusedMenu ]; } } #endregion Internal Properties //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods // Get a proxy for a given hwnd // (Also used as an entry by RESW to get proxy for a parent to check if it supports overrides) internal static IRawElementProviderSimple ProxyProviderFromHwnd(NativeMethods.HWND hwnd, int idChild, int idObject) { // The precedence that proxies are chosen is as follows: // // All entries in the table passed into RegisterWindowHandlers that do not specify AllowSubstringMatch // are tried first. If the class name of the current hwnd matches the ClassName in the entery then // the image name is checked for a match if it was specified. // // If no match is found then the real class name is checked for a match unless NoBaseMatching flag is on. // this allows class name ThunderRT6CommandButton to match Button becuse it subclasses button. // If more than one entry has the same ClassName the first one in the table is tried first. // // If no exact match if found, all the entries that specified AllowSubstringMatch are tried in the order // they occur in the table. If a match is found and the ImageName was specified that is checked to see // if it matches the current image. // // If no substring matches are found entries that have specifed only the ImageName are tried. // // If there still is no match entries that have no ClassName and no ImageName are tried. // // If this fails the default hwnd proxy is used. // // If RegisterWindowHandlers is called again those entries occur before the earlier ones in the table. if (hwnd == NativeMethods.HWND.NULL) { return null; } LoadDefaultProxies (); string className = GetClassName (hwnd).ToLower (CultureInfo.InvariantCulture); object proxyDescOrArrayList = null; lock (_lockObj) { proxyDescOrArrayList = _classHandlers[className]; } string imageName = null; IRawElementProviderSimple proxy = FindProxyInEntryOrArrayList(ProxyScoping.ExactMatchApparentClassName, proxyDescOrArrayList, ref imageName, hwnd, idChild, idObject, null); // If we don't have a proxy for the class try to match the real class string baseClassName = null; if (proxy == null) { baseClassName = GetBaseClassName(hwnd); if (baseClassName == className) baseClassName = null; if (!String.IsNullOrEmpty(baseClassName)) { lock (_lockObj) { proxyDescOrArrayList = _classHandlers[baseClassName]; } proxy = FindProxyInEntryOrArrayList(ProxyScoping.ExactMatchRealClassName, proxyDescOrArrayList, ref imageName, hwnd, idChild, idObject, null); } } // If we don't have a proxy yet look for a partial match if there are any if (proxy == null && _partialClassHandlers.Count > 0) { proxy = FindProxyInEntryOrArrayList(ProxyScoping.PartialMatchApparentClassName, _partialClassHandlers, ref imageName, hwnd, idChild, idObject, className); if (proxy == null && !String.IsNullOrEmpty(baseClassName)) { proxy = FindProxyInEntryOrArrayList(ProxyScoping.PartialMatchRealClassName, _partialClassHandlers, ref imageName, hwnd, idChild, idObject, baseClassName); } } // There is no match yet look for entry that just specified an image name // this is like a fallback proxy for a particular image if( proxy == null ) { proxy = FindProxyFromImageFallback(ref imageName, hwnd, idChild, idObject); } // use the fallback proxy if there is one if (proxy == null) { proxy = FindProxyInEntryOrArrayList(ProxyScoping.FallbackHandlers, _fallbackHandlers, ref imageName, hwnd, idChild, idObject, null); } // may be null if no proxy found return proxy; } static private IRawElementProviderSimple FindProxyFromImageFallback(ref string imageName, NativeMethods.HWND hwnd, int idChild, int idObject) { int count; lock (_lockObj) { count = _imageOnlyHandlers.Count; } // if there is no _imageOnlyHandlers registered there is no need to look if (count > 0) { // Null and Empty string mean different things here. #pragma warning suppress 6507 if (imageName == null) imageName = GetImageName(hwnd); // Null and Empty string mean different things here. #pragma warning suppress 6507 if (imageName != null) { object entryOrArrayList; lock (_lockObj) { entryOrArrayList = _imageOnlyHandlers[imageName]; } return FindProxyInEntryOrArrayList(ProxyScoping.ImageOnlyHandlers, entryOrArrayList, ref imageName, hwnd, idChild, idObject, null); } } return null; } // Given a single entry or arraylist, check if it or each object in it matches. // This just handles the arraylist iteration, and calls through to GetProxyFromEntry to do the actual entry checking. static private IRawElementProviderSimple FindProxyInEntryOrArrayList(ProxyScoping findType, object entryOrArrayList, ref string imageName, NativeMethods.HWND hwnd, int idChild, int idObject, string classNameForPartialMatch) { if (entryOrArrayList == null) return null; ArrayList array = entryOrArrayList as ArrayList; if (array == null) { return GetProxyFromEntry(findType, entryOrArrayList, ref imageName, hwnd, idChild, idObject, classNameForPartialMatch); } // This the array will only grow in size, it will not shrink. That is the reason why it is // safe to capture the count outside the loop. The reference we have to the Arraylist is // kind of like a snapshot. int count; lock (_lockObj) { count = array.Count; } IRawElementProviderSimple proxy = null; // this is a for loop because we need this to be thread safe and ClientSideProviderFactoryCallback calls out // so there would have been a lock in force when the call out was made which causes // deadlock. We need to make our locks as narrow as possible. for( int i = 0; i < count; i++ ) { object entry; lock (_lockObj) { entry = array[i]; } proxy = GetProxyFromEntry(findType, entry, ref imageName, hwnd, idChild, idObject, classNameForPartialMatch); if( proxy != null ) break; } return proxy; } // Given an entry from one of the hash-tables or lists, check if it matches the image/classname, and if so, call the // factory method to create the proxy. // (Because full classname matching is done via hash-table lookup, this only needs to do string comparisons // for partial classname matches.) static private IRawElementProviderSimple GetProxyFromEntry(ProxyScoping findType, object entry, ref string imageName, NativeMethods.HWND hwnd, int idChild, int idObject, string classNameForPartialMatch) { // First, determine if the entry matches, and if so, extract the factory callback... ClientSideProviderFactoryCallback factoryCallback = null; // The entry may be a ClientSideProviderFactoryCallback or ClientSideProviderDescription... if (findType == ProxyScoping.ImageOnlyHandlers || findType == ProxyScoping.FallbackHandlers) { // Handle the fallback and image cases specially. The array for these is an array // of ClientSideProviderFactoryCallbacks, not ClientSideProviderDescription. factoryCallback = (ClientSideProviderFactoryCallback)entry; } else { // Other cases use ClientSideProviderDescription... ClientSideProviderDescription pi = (ClientSideProviderDescription)entry; // Get the image name if necessary... #pragma warning suppress 6507 // Null and Empty string mean different things here. if (imageName == null && pi.ImageName != null) { imageName = GetImageName(hwnd); } if (pi.ImageName == null || pi.ImageName == imageName) { // Check if we have a match for this entry... switch (findType) { case ProxyScoping.ExactMatchApparentClassName: factoryCallback = pi.ClientSideProviderFactoryCallback; break; case ProxyScoping.ExactMatchRealClassName: if ((pi.Flags & ClientSideProviderMatchIndicator.DisallowBaseClassNameMatch) == 0) { factoryCallback = pi.ClientSideProviderFactoryCallback; } break; case ProxyScoping.PartialMatchApparentClassName: if (classNameForPartialMatch.IndexOf(pi.ClassName, StringComparison.Ordinal) >= 0) { factoryCallback = pi.ClientSideProviderFactoryCallback; } break; case ProxyScoping.PartialMatchRealClassName: if (classNameForPartialMatch.IndexOf(pi.ClassName, StringComparison.Ordinal) >= 0 && ((pi.Flags & ClientSideProviderMatchIndicator.DisallowBaseClassNameMatch) == 0)) { factoryCallback = pi.ClientSideProviderFactoryCallback; } break; default: Debug.Assert(false, "unexpected switch() case:"); break; } } } // Second part: did we get a match? If so, use the factory callback to obtain an instance... if (factoryCallback == null) return null; // if we get an exception creating a proxy just don't create the proxy and let the UIAutomation default proxy be used // This will still allow the tree to be navigated and some properties to be made availible. // try { return factoryCallback(hwnd, idChild, idObject); } catch( Exception e ) { if( Misc.IsCriticalException( e ) ) throw; return null; } } private static void AddToProxyDescriptionTable(ClientSideProviderDescription[] proxyInfo) { ClientSideProviderDescription pi; // the array that is passed in may have the same className occuring more than once in the table. // The way this works it the first occurence in the array is giver the first chance to return a valid // proxy. In order to make that work we go through the array backwards so the the entries first // in the table get inserted in front of the ones that came later. This also works if // RegisterWindowHandlers is called more than once. for( int i = proxyInfo.Length - 1; i >= 0; i-- ) { pi = proxyInfo[i]; // Check for pseudo-proxy names... if( pi.ClassName != null && pi.ClassName.Length > 0 && pi.ClassName[ 0 ] == '#' ) { for( int j = 0 ; j < _pseudoProxyClassNames.Length ; j++ ) { if( pi.ClassName.Equals( _pseudoProxyClassNames[ j ] ) ) { if( pi.ImageName != null || pi.Flags != 0 ) { throw new ArgumentException(SR.Get(SRID.NonclientClassnameCannotBeUsedWithFlagsOrImagename)); } _pseudoProxies[j] = pi.ClientSideProviderFactoryCallback; break; } } // fall through to add to table as usual, that ensures that it appears in a 'get' operation. } if( pi.ClassName == null && pi.ImageName == null ) { _fallbackHandlers.Insert(0, pi.ClientSideProviderFactoryCallback); } else if ( pi.ClassName == null ) { AddToHashTable(_imageOnlyHandlers, pi.ImageName, pi.ClientSideProviderFactoryCallback); } else if ((pi.Flags & ClientSideProviderMatchIndicator.AllowSubstringMatch) != 0) { _partialClassHandlers.Insert( 0, pi ); } else { AddToHashTable( _classHandlers, pi.ClassName, pi ); } } } private static void AddToHashTable( Hashtable table, string key, object data ) { object o = table[ key ]; if( o == null ) { table.Add( key, data ); } else { ArrayList l = o as ArrayList; if( l == null ) { l = new ArrayList(); l.Insert( 0, o ); } l.Insert( 0, data ); table[ key ] = l; } } // find the name of the base class for this HWND. If this fails for any reason just return null. private static string GetBaseClassName( NativeMethods.HWND hwnd ) { const int OBJID_QUERYCLASSNAMEIDX = unchecked(unchecked((int)0xFFFFFFF4)); const int QUERYCLASSNAME_BASE = 65536; if( IsKnownBadWindow( hwnd ) ) { return RealGetWindowClass( hwnd ).ToLower( CultureInfo.InvariantCulture ); } IntPtr result = Misc.SendMessageTimeout(hwnd, UnsafeNativeMethods.WM_GETOBJECT, IntPtr.Zero, (IntPtr)OBJID_QUERYCLASSNAMEIDX); int index = (int)result; if ( index >= QUERYCLASSNAME_BASE && index - QUERYCLASSNAME_BASE < _classNames.Length ) { return _classNames[index - QUERYCLASSNAME_BASE].ToLower( CultureInfo.InvariantCulture ); } else { return RealGetWindowClass( hwnd ).ToLower( CultureInfo.InvariantCulture ); } } #endregion Private Methods //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields private enum ProxyScoping { ExactMatchApparentClassName, ExactMatchRealClassName, PartialMatchApparentClassName, PartialMatchRealClassName, ImageOnlyHandlers, FallbackHandlers, } private static object _lockObj = new object(); // contains ClientSideProviderDescription structs or an Arraylist of ClientSideProviderDescription structs private static Hashtable _classHandlers = new Hashtable(22, 1.0f); private static ArrayList _partialClassHandlers = new ArrayList(12); // contains a ClientSideProviderFactoryCallback delagate or an Arraylist of delagates private static Hashtable _imageOnlyHandlers = new Hashtable(0,1.0f); // contains ClientSideProviderFactoryCallback delagates private static ArrayList _fallbackHandlers = new ArrayList(1); private static bool _defaultProxiesNeeded = true; // The name of the default proxy assembly this will probably change before we ship private const string _defaultProxyAssembly = "UIAutomationClientsideProviders"; // used to plug in the non-client area and user32 focused menu proxy private static ClientSideProviderFactoryCallback[] _pseudoProxies = new ClientSideProviderFactoryCallback[(int)PseudoProxy.LAST]; private enum PseudoProxy { NonClient = 0, NonClientMenuBar, NonClientSysMenu, User32FocusedMenu, LAST } // Pseudo-proxy names - must be all lowercase, since we convert // to lowercase in proxyinfo ctor private static string [ ] _pseudoProxyClassNames = { "#nonclient", "#nonclientmenubar", "#nonclientsysmenu", "#user32focusedmenu" }; private static string [ ] _classNames = { "ListBox", "#32768", "Button", "Static", "Edit", "ComboBox", "#32770", "#32771", "MDIClient", "#32769", "ScrollBar", "msctls_statusbar32", "ToolbarWindow32", "msctls_progress32", "SysAnimate32", "SysTabControl32", "msctls_hotkey32", "SysHeader32", "msctls_trackbar32", "SysListView32", "OpenListView", "msctls_updown", "msctls_updown32", "tooltips_class", "tooltips_class32", "SysTreeView32", "SysMonthCal32", "SysDateTimePick32", "RICHEDIT", "RichEdit20A", "RichEdit20W", "SysIPAddress32" }; #endregion Private Fields } }
using System; using NUnit.Framework; using SimpleContainer.Infection; using SimpleContainer.Interface; using SimpleContainer.Tests.Helpers; namespace SimpleContainer.Tests.Factories { public abstract class FactoriesArgumentsHandlingTest : SimpleContainerTestBase { public class UnusedArguments : FactoriesArgumentsHandlingTest { public class Wrap { public readonly Func<object, Service> createService; public Wrap(Func<object, Service> createService) { this.createService = createService; } } public class Service { } [Test] public void Test() { var container = Container(); var wrap = container.Get<Wrap>(); var error = Assert.Throws<SimpleContainerException>(() => wrap.createService(new { argument = "qq" })); Assert.That(error.Message, Is.EqualTo(TestHelpers.FormatMessage(@" arguments [argument] are not used !Service <---------------"))); } } public class PassArgumentsFromInterfaceToImplmementation : FactoriesArgumentsHandlingTest { public interface IInterface { } public class Impl : IInterface { public readonly string argument; public Impl(string argument) { this.argument = argument; } } public class Wrap { public readonly Func<object, IInterface> createInterface; public Wrap(Func<object, IInterface> createInterface) { this.createInterface = createInterface; } } [Test] public void Test() { var container = Container(); var impl = container.Get<Wrap>().createInterface(new { argument = "666" }); Assert.That(impl, Is.InstanceOf<Impl>()); Assert.That(((Impl)impl).argument, Is.EqualTo("666")); } } public class ArgumentsAreNotUsedForDependencies : FactoriesArgumentsHandlingTest { public class Wrap { public readonly Func<object, Service> createService; public Wrap(Func<object, Service> createService) { this.createService = createService; } } public class Service { public readonly Dependency dependency; public Service(Dependency dependency) { this.dependency = dependency; } } public class Dependency { public readonly string argument; public Dependency(string argument) { this.argument = argument; } } [Test] public void Test() { var container = Container(); var wrap = container.Get<Wrap>(); var error = Assert.Throws<SimpleContainerException>(() => wrap.createService(new { argument = "qq" })); Assert.That(error.Message, Is.EqualTo(TestHelpers.FormatMessage(@" parameter [argument] of service [Dependency] is not configured !Service !Dependency !argument <---------------"))); } } public class CanInjectFuncWithArgumentsUsingBuildUp : FactoriesArgumentsHandlingTest { public class A { } [Inject] private Func<object, A> createA; [Test] public void Test() { Container().BuildUp(this, new string[0]); Assert.DoesNotThrow(() => createA(new object())); } } public class CreateWithArgumentThatOverridesConfiguredDependency : FactoriesArgumentsHandlingTest { public class A { public readonly string dependency; public A(string dependency) { this.dependency = dependency; } } [Test] public void Test() { var container = Container(builder => builder.BindDependencies<A>(new { dependency = "configured" })); var service = container.Create<A>(arguments: new { dependency = "argument" }); Assert.That(service.dependency, Is.EqualTo("argument")); } } public class GracefullErrorForNotSupportedDelegateTypes : FactoriesArgumentsHandlingTest { public class A { } [Test] public void Test() { var container = Container(); var exception = Assert.Throws<SimpleContainerException>(() => container.Get<Func<int, int, A>>()); Assert.That(exception.Message, Is.EqualTo(TestHelpers.FormatMessage(@" can't create delegate [Func<int,int,A>] !Func<int,int,A> <---------------"))); } } public class CanInjectFuncWithTypeWithArgumentsUsingBuildUp : FactoriesArgumentsHandlingTest { public interface IA { string GetDescription(); } public class A<T> : IA { private readonly int parameter; public A(int parameter) { this.parameter = parameter; } public string GetDescription() { return typeof(T).Name + "_" + parameter; } } [Inject] private Func<object, Type, IA> createA; [Test] public void Test() { var container = Container(); container.BuildUp(this, new string[0]); Assert.That(createA(new { parameter = 42 }, typeof(A<int>)).GetDescription(), Is.EqualTo("Int32_42")); } } } }
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Net; using System.Web; using ServiceStack.Common; using ServiceStack.Common.Utils; using ServiceStack.MiniProfiler.UI; using ServiceStack.ServiceHost; using ServiceStack.Text; using ServiceStack.WebHost.Endpoints.Extensions; using ServiceStack.WebHost.Endpoints.Metadata; using ServiceStack.WebHost.Endpoints.Support; namespace ServiceStack.WebHost.Endpoints { public class ServiceStackHttpHandlerFactory : IHttpHandlerFactory { static readonly List<string> WebHostRootFileNames = new List<string>(); static private readonly string WebHostPhysicalPath = null; static private readonly string DefaultRootFileName = null; static private string ApplicationBaseUrl = null; static private readonly IHttpHandler DefaultHttpHandler = null; static private readonly RedirectHttpHandler NonRootModeDefaultHttpHandler = null; static private readonly IHttpHandler ForbiddenHttpHandler = null; static private readonly IHttpHandler NotFoundHttpHandler = null; static private readonly IHttpHandler StaticFileHandler = new StaticFileHandler(); private static readonly bool IsIntegratedPipeline = false; private static readonly bool ServeDefaultHandler = false; private static Func<IHttpRequest, IHttpHandler>[] RawHttpHandlers; [ThreadStatic] public static string DebugLastHandlerArgs; static ServiceStackHttpHandlerFactory() { //MONO doesn't implement this property var pi = typeof(HttpRuntime).GetProperty("UsingIntegratedPipeline"); if (pi != null) { IsIntegratedPipeline = (bool)pi.GetGetMethod().Invoke(null, new object[0]); } if (EndpointHost.Config == null) { throw new ConfigurationErrorsException( "ServiceStack: AppHost does not exist or has not been initialized. " + "Make sure you have created an AppHost and started it with 'new AppHost().Init();' in your Global.asax Application_Start()", new ArgumentNullException("EndpointHost.Config")); } var isAspNetHost = HttpListenerBase.Instance == null || HttpContext.Current != null; WebHostPhysicalPath = EndpointHost.Config.WebHostPhysicalPath; //Apache+mod_mono treats path="servicestack*" as path="*" so takes over root path, so we need to serve matching resources var hostedAtRootPath = EndpointHost.Config.ServiceStackHandlerFactoryPath == null; //DefaultHttpHandler not supported in IntegratedPipeline mode if (!IsIntegratedPipeline && isAspNetHost && !hostedAtRootPath && !Env.IsMono) DefaultHttpHandler = new DefaultHttpHandler(); ServeDefaultHandler = hostedAtRootPath || Env.IsMono; if (ServeDefaultHandler) { foreach (var filePath in Directory.GetFiles(WebHostPhysicalPath)) { var fileNameLower = Path.GetFileName(filePath).ToLower(); if (DefaultRootFileName == null && EndpointHost.Config.DefaultDocuments.Contains(fileNameLower)) { //Can't serve Default.aspx pages when hostedAtRootPath so ignore and allow for next default document if (!(hostedAtRootPath && fileNameLower.EndsWith(".aspx"))) { DefaultRootFileName = fileNameLower; ((StaticFileHandler)StaticFileHandler).SetDefaultFile(filePath); if (DefaultHttpHandler == null) DefaultHttpHandler = new RedirectHttpHandler { RelativeUrl = DefaultRootFileName }; } } WebHostRootFileNames.Add(Path.GetFileName(fileNameLower)); } foreach (var dirName in Directory.GetDirectories(WebHostPhysicalPath)) { var dirNameLower = Path.GetFileName(dirName).ToLower(); WebHostRootFileNames.Add(Path.GetFileName(dirNameLower)); } } if (!string.IsNullOrEmpty(EndpointHost.Config.DefaultRedirectPath)) DefaultHttpHandler = new RedirectHttpHandler { RelativeUrl = EndpointHost.Config.DefaultRedirectPath }; if (DefaultHttpHandler == null && !string.IsNullOrEmpty(EndpointHost.Config.MetadataRedirectPath)) DefaultHttpHandler = new RedirectHttpHandler { RelativeUrl = EndpointHost.Config.MetadataRedirectPath }; if (!string.IsNullOrEmpty(EndpointHost.Config.MetadataRedirectPath)) NonRootModeDefaultHttpHandler = new RedirectHttpHandler { RelativeUrl = EndpointHost.Config.MetadataRedirectPath }; if (DefaultHttpHandler == null) DefaultHttpHandler = NotFoundHttpHandler; var defaultRedirectHanlder = DefaultHttpHandler as RedirectHttpHandler; var debugDefaultHandler = defaultRedirectHanlder != null ? defaultRedirectHanlder.RelativeUrl : typeof(DefaultHttpHandler).Name; SetApplicationBaseUrl(EndpointHost.Config.WebHostUrl); var httpHandlers = EndpointHost.Config.CustomHttpHandlers; httpHandlers.TryGetValue(HttpStatusCode.Forbidden, out ForbiddenHttpHandler); if (ForbiddenHttpHandler == null) { ForbiddenHttpHandler = new ForbiddenHttpHandler { IsIntegratedPipeline = IsIntegratedPipeline, WebHostPhysicalPath = WebHostPhysicalPath, WebHostRootFileNames = WebHostRootFileNames, ApplicationBaseUrl = ApplicationBaseUrl, DefaultRootFileName = DefaultRootFileName, DefaultHandler = debugDefaultHandler, }; } httpHandlers.TryGetValue(HttpStatusCode.NotFound, out NotFoundHttpHandler); if (NotFoundHttpHandler == null) { NotFoundHttpHandler = new NotFoundHttpHandler { IsIntegratedPipeline = IsIntegratedPipeline, WebHostPhysicalPath = WebHostPhysicalPath, WebHostRootFileNames = WebHostRootFileNames, ApplicationBaseUrl = ApplicationBaseUrl, DefaultRootFileName = DefaultRootFileName, DefaultHandler = debugDefaultHandler, }; } var rawHandlers = EndpointHost.Config.RawHttpHandlers; rawHandlers.Add(ReturnRequestInfo); rawHandlers.Add(MiniProfilerHandler.MatchesRequest); RawHttpHandlers = rawHandlers.ToArray(); } // Entry point for ASP.NET public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated) { DebugLastHandlerArgs = requestType + "|" + url + "|" + pathTranslated; var httpReq = new HttpRequestWrapper(pathTranslated, context.Request); foreach (var rawHttpHandler in RawHttpHandlers) { var reqInfo = rawHttpHandler(httpReq); if (reqInfo != null) return reqInfo; } var mode = EndpointHost.Config.ServiceStackHandlerFactoryPath; var pathInfo = context.Request.GetPathInfo(); //WebDev Server auto requests '/default.aspx' so recorrect path to different default document if (mode == null && (url == "/default.aspx" || url == "/Default.aspx")) pathInfo = "/"; if (string.IsNullOrEmpty(pathInfo) || pathInfo == "/") { //Exception calling context.Request.Url on Apache+mod_mono var absoluteUrl = Env.IsMono ? url.ToParentPath() : context.Request.GetApplicationUrl(); if (ApplicationBaseUrl == null) SetApplicationBaseUrl(absoluteUrl); return ServeDefaultHandler ? DefaultHttpHandler : NonRootModeDefaultHttpHandler; } if (mode != null && pathInfo.EndsWith(mode)) { var requestPath = context.Request.Path.ToLower(); if (requestPath == "/" + mode || requestPath == mode || requestPath == mode + "/") { if (context.Request.PhysicalPath != WebHostPhysicalPath || !File.Exists(Path.Combine(context.Request.PhysicalPath, DefaultRootFileName ?? ""))) { return new IndexPageHttpHandler(); } } var okToServe = ShouldAllow(context.Request.FilePath); return okToServe ? DefaultHttpHandler : ForbiddenHttpHandler; } return GetHandlerForPathInfo( context.Request.HttpMethod, pathInfo, context.Request.FilePath, pathTranslated) ?? NotFoundHttpHandler; } private static void SetApplicationBaseUrl(string absoluteUrl) { if (absoluteUrl == null) return; ApplicationBaseUrl = absoluteUrl; var defaultRedirectUrl = DefaultHttpHandler as RedirectHttpHandler; if (defaultRedirectUrl != null && defaultRedirectUrl.AbsoluteUrl == null) defaultRedirectUrl.AbsoluteUrl = ApplicationBaseUrl.CombineWith( defaultRedirectUrl.RelativeUrl); if (NonRootModeDefaultHttpHandler != null && NonRootModeDefaultHttpHandler.AbsoluteUrl == null) NonRootModeDefaultHttpHandler.AbsoluteUrl = ApplicationBaseUrl.CombineWith( NonRootModeDefaultHttpHandler.RelativeUrl); } // Entry point for HttpListener public static IHttpHandler GetHandler(IHttpRequest httpReq) { foreach (var rawHttpHandler in RawHttpHandlers) { var reqInfo = rawHttpHandler(httpReq); if (reqInfo != null) return reqInfo; } var mode = EndpointHost.Config.ServiceStackHandlerFactoryPath; var pathInfo = httpReq.PathInfo; if (string.IsNullOrEmpty(pathInfo) || pathInfo == "/") { if (ApplicationBaseUrl == null) SetApplicationBaseUrl(httpReq.GetPathUrl()); return ServeDefaultHandler ? DefaultHttpHandler : NonRootModeDefaultHttpHandler; } if (mode != null && pathInfo.EndsWith(mode)) { var requestPath = pathInfo; if (requestPath == "/" + mode || requestPath == mode || requestPath == mode + "/") { //TODO: write test for this if (httpReq.GetPhysicalPath() != WebHostPhysicalPath || !File.Exists(Path.Combine(httpReq.ApplicationFilePath, DefaultRootFileName ?? ""))) { return new IndexPageHttpHandler(); } } var okToServe = ShouldAllow(httpReq.GetPhysicalPath()); return okToServe ? DefaultHttpHandler : ForbiddenHttpHandler; } return GetHandlerForPathInfo(httpReq.HttpMethod, pathInfo, pathInfo, httpReq.GetPhysicalPath()) ?? NotFoundHttpHandler; } /// <summary> /// If enabled, just returns the Request Info as it understands /// </summary> /// <param name="context"></param> /// <returns></returns> private static IHttpHandler ReturnRequestInfo(HttpRequest request) { if (EndpointHost.Config.DebugOnlyReturnRequestInfo) { var reqInfo = RequestInfoHandler.GetRequestInfo( new HttpRequestWrapper(typeof(RequestInfo).Name, request)); reqInfo.Host = EndpointHost.Config.DebugAspNetHostEnvironment + "_v" + Env.ServiceStackVersion + "_" + EndpointHost.Config.ServiceName; //reqInfo.FactoryUrl = url; //Just RawUrl without QueryString //reqInfo.FactoryPathTranslated = pathTranslated; //Local path on filesystem reqInfo.PathInfo = request.PathInfo; reqInfo.Path = request.Path; reqInfo.ApplicationPath = request.ApplicationPath; return new RequestInfoHandler { RequestInfo = reqInfo }; } return null; } private static IHttpHandler ReturnRequestInfo(IHttpRequest httpReq) { if (EndpointHost.Config.DebugOnlyReturnRequestInfo) { var reqInfo = RequestInfoHandler.GetRequestInfo(httpReq); reqInfo.Host = EndpointHost.Config.DebugHttpListenerHostEnvironment + "_v" + Env.ServiceStackVersion + "_" + EndpointHost.Config.ServiceName; reqInfo.PathInfo = httpReq.PathInfo; reqInfo.Path = httpReq.GetPathUrl(); return new RequestInfoHandler { RequestInfo = reqInfo }; } return null; } // no handler registered // serve the file from the filesystem, restricting to a safelist of extensions private static bool ShouldAllow(string filePath) { var fileExt = Path.GetExtension(filePath); if (string.IsNullOrEmpty(fileExt)) return false; return EndpointHost.Config.AllowFileExtensions.Contains(fileExt.Substring(1)); } public static IHttpHandler GetHandlerForPathInfo(string httpMethod, string pathInfo, string requestPath, string filePath) { var pathParts = pathInfo.TrimStart('/').Split('/'); if (pathParts.Length == 0) return NotFoundHttpHandler; var handler = GetHandlerForPathParts(pathParts); if (handler != null) return handler; var existingFile = pathParts[0].ToLower(); if (WebHostRootFileNames.Contains(existingFile)) { //e.g. CatchAllHandler to Process Markdown files var catchAllHandler = GetCatchAllHandlerIfAny(httpMethod, pathInfo, filePath); if (catchAllHandler != null) return catchAllHandler; return ShouldAllow(requestPath) ? StaticFileHandler : ForbiddenHttpHandler; } var restPath = RestHandler.FindMatchingRestPath(httpMethod, pathInfo); if (restPath != null) return new RestHandler { RestPath = restPath, RequestName = restPath.RequestType.Name }; return GetCatchAllHandlerIfAny(httpMethod, pathInfo, filePath); } private static IHttpHandler GetCatchAllHandlerIfAny(string httpMethod, string pathInfo, string filePath) { if (EndpointHost.CatchAllHandlers != null) { foreach (var httpHandlerResolver in EndpointHost.CatchAllHandlers) { var httpHandler = httpHandlerResolver(httpMethod, pathInfo, filePath); if (httpHandler != null) return httpHandler; } } return null; } private static IHttpHandler GetHandlerForPathParts(string[] pathParts) { var pathController = string.Intern(pathParts[0].ToLower()); if (pathParts.Length == 1) { if (pathController == "metadata") return new IndexMetadataHandler(); if (pathController == "soap11") return new Soap11MessageSyncReplyHttpHandler(); if (pathController == "soap12") return new Soap12MessageSyncReplyHttpHandler(); if (pathController == RequestInfoHandler.RestPath) return new RequestInfoHandler(); return null; } var pathAction = string.Intern(pathParts[1].ToLower()); var requestName = pathParts.Length > 2 ? pathParts[2] : null; switch (pathController) { case "json": if (pathAction == "syncreply") return new JsonSyncReplyHandler { RequestName = requestName }; if (pathAction == "asynconeway") return new JsonAsyncOneWayHandler { RequestName = requestName }; if (pathAction == "metadata") return new JsonMetadataHandler(); break; case "xml": if (pathAction == "syncreply") return new XmlSyncReplyHandler { RequestName = requestName }; if (pathAction == "asynconeway") return new XmlAsyncOneWayHandler { RequestName = requestName }; if (pathAction == "metadata") return new XmlMetadataHandler(); break; case "jsv": if (pathAction == "syncreply") return new JsvSyncReplyHandler { RequestName = requestName }; if (pathAction == "asynconeway") return new JsvAsyncOneWayHandler { RequestName = requestName }; if (pathAction == "metadata") return new JsvMetadataHandler(); break; case "soap11": if (pathAction == "wsdl") return new Soap11WsdlMetadataHandler(); if (pathAction == "metadata") return new Soap11MetadataHandler(); break; case "soap12": if (pathAction == "wsdl") return new Soap12WsdlMetadataHandler(); if (pathAction == "metadata") return new Soap12MetadataHandler(); break; case RequestInfoHandler.RestPath: return new RequestInfoHandler(); default: string contentType; if (EndpointHost.ContentTypeFilter .ContentTypeFormats.TryGetValue(pathController, out contentType)) { var feature = Common.Web.ContentType.GetFeature(contentType); if (feature == Feature.None) feature = Feature.CustomFormat; var format = Common.Web.ContentType.GetContentFormat(contentType); if (pathAction == "syncreply") return new GenericHandler(contentType, EndpointAttributes.SyncReply, feature) { RequestName = requestName }; if (pathAction == "asynconeway") return new GenericHandler(contentType, EndpointAttributes.AsyncOneWay, feature) { RequestName = requestName }; if (pathAction == "metadata") return new CustomMetadataHandler(contentType, format); } break; } return null; } public void ReleaseHandler(IHttpHandler handler) { } } }
//------------------------------------------------------------------------------ // <copyright file="PageParser.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* * Implements the ASP.NET template parser * * Copyright (c) 1998 Microsoft Corporation */ namespace System.Web.UI { using System.Runtime.Serialization.Formatters; using System.Text; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System; using System.IO; using System.Collections; using System.Collections.Specialized; using System.Reflection; using System.Globalization; using System.CodeDom.Compiler; using System.ComponentModel; using System.Web.Hosting; using System.Web.Caching; using System.Web.Util; using System.Web.Compilation; using System.Web.Configuration; using System.Web.Management; using System.EnterpriseServices; using HttpException = System.Web.HttpException; using System.Text.RegularExpressions; using System.Security.Permissions; /* * Parser for .aspx files */ /// <internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public sealed class PageParser : TemplateControlParser { private int _transactionMode = 0 /*TransactionOption.Disabled*/; internal int TransactionMode { get { return _transactionMode; } } private TraceMode _traceMode = System.Web.TraceMode.Default; internal TraceMode TraceMode { get { return _traceMode; } } private TraceEnable _traceEnabled = TraceEnable.Default; internal TraceEnable TraceEnabled { get { return _traceEnabled; } } private int _codePage; private string _responseEncoding; private int _lcid; private string _culture; private int _mainDirectiveLineNumber = 1; private bool _mainDirectiveMasterPageSet; private OutputCacheLocation _outputCacheLocation; internal bool FRequiresSessionState { get { return flags[requiresSessionState]; } } internal bool FReadOnlySessionState { get { return flags[readOnlySessionState]; } } private string _errorPage; private string _styleSheetTheme; internal String StyleSheetTheme { get { return _styleSheetTheme; } } internal bool AspCompatMode { get { return flags[aspCompatMode]; } } internal bool AsyncMode { get { return flags[asyncMode]; } } internal bool ValidateRequest { get { return flags[validateRequest]; } } private Type _previousPageType; internal Type PreviousPageType { get { return _previousPageType; } } private Type _masterPageType; internal Type MasterPageType { get { return _masterPageType; } } private string _configMasterPageFile; public PageParser() { flags[buffer] = Page.BufferDefault; flags[requiresSessionState] = true; flags[validateRequest] = true; } /* * Compile an .aspx file into a Page object */ /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> private static object s_lock = new object(); // Only allowed in full trust (ASURT 123086) [SecurityPermission(SecurityAction.Demand, Unrestricted=true)] public static IHttpHandler GetCompiledPageInstance(string virtualPath, string inputFile, HttpContext context) { // Canonicalize the path to avoid failure caused by the CheckSuspiciousPhysicalPath // security check, which was not meant to apply to this scenario (plus this API requires // full trust). VSWhidbey 541640. if (!String.IsNullOrEmpty(inputFile)) { inputFile = Path.GetFullPath(inputFile); } return GetCompiledPageInstance(VirtualPath.Create(virtualPath), inputFile, context); } private static IHttpHandler GetCompiledPageInstance(VirtualPath virtualPath, string inputFile, HttpContext context) { // This is a hacky API that only exists to support web service's // DefaultWsdlHelpGenerator.aspx, which doesn't live under the app root. // To make this work, we add an explicit mapping from the virtual path // to the stream of the passed in file // Make it relative to the current request if necessary if (context != null) virtualPath = context.Request.FilePathObject.Combine(virtualPath); object virtualPathToFileMappingState = null; try { try { // If there is a physical path, we need to connect the virtual path to it, so that // the build system will use the right input file for the virtual path. if (inputFile != null) { virtualPathToFileMappingState = HostingEnvironment.AddVirtualPathToFileMapping( virtualPath, inputFile); } BuildResultCompiledType result = (BuildResultCompiledType)BuildManager.GetVPathBuildResult( context, virtualPath, false /*noBuild*/, true /*allowCrossApp*/, true /*allowBuildInPrecompile*/); return (IHttpHandler)HttpRuntime.CreatePublicInstance(result.ResultType); } finally { if (virtualPathToFileMappingState != null) HostingEnvironment.ClearVirtualPathToFileMapping(virtualPathToFileMappingState); } } catch { throw; } } internal override Type DefaultBaseType { get { return typeof(System.Web.UI.Page); } } internal override Type DefaultFileLevelBuilderType { get { return typeof(FileLevelPageControlBuilder); } } internal override RootBuilder CreateDefaultFileLevelBuilder() { return new FileLevelPageControlBuilder(); } private void EnsureMasterPageFileFromConfigApplied() { // Skip if it's already applied. if (_mainDirectiveMasterPageSet) { return; } // If the masterPageFile is defined in the config if (_configMasterPageFile != null) { // Readjust the lineNumber to the location of maindirective int prevLineNumber = _lineNumber; _lineNumber = _mainDirectiveLineNumber; try { if (_configMasterPageFile.Length > 0) { Type type = GetReferencedType(_configMasterPageFile); // Make sure it has the correct base type if (!typeof(MasterPage).IsAssignableFrom(type)) { ProcessError(SR.GetString(SR.Invalid_master_base, _configMasterPageFile)); } } if (((FileLevelPageControlBuilder)RootBuilder).ContentBuilderEntries != null) { RootBuilder.SetControlType(BaseType); RootBuilder.PreprocessAttribute(String.Empty /*filter*/, "MasterPageFile", _configMasterPageFile, true /*mainDirectiveMode*/); } } finally { _lineNumber = prevLineNumber; } } _mainDirectiveMasterPageSet = true; } internal override void HandlePostParse() { base.HandlePostParse(); EnsureMasterPageFileFromConfigApplied(); } // Get default settings from config internal override void ProcessConfigSettings() { base.ProcessConfigSettings(); if (PagesConfig != null) { // Check config for various attributes, and if they have non-default values, // set them in _mainDirectiveConfigSettings. if (PagesConfig.Buffer != Page.BufferDefault) _mainDirectiveConfigSettings["buffer"] = Util.GetStringFromBool(PagesConfig.Buffer); if (PagesConfig.EnableViewStateMac != Page.EnableViewStateMacDefault) _mainDirectiveConfigSettings["enableviewstatemac"] = Util.GetStringFromBool(PagesConfig.EnableViewStateMac); if (PagesConfig.EnableEventValidation != Page.EnableEventValidationDefault) _mainDirectiveConfigSettings["enableEventValidation"] = Util.GetStringFromBool(PagesConfig.EnableEventValidation); if (PagesConfig.SmartNavigation != Page.SmartNavigationDefault) _mainDirectiveConfigSettings["smartnavigation"] = Util.GetStringFromBool(PagesConfig.SmartNavigation); if (PagesConfig.ThemeInternal != null && PagesConfig.Theme.Length != 0) _mainDirectiveConfigSettings["theme"] = PagesConfig.Theme; if (PagesConfig.StyleSheetThemeInternal != null && PagesConfig.StyleSheetThemeInternal.Length != 0) _mainDirectiveConfigSettings["stylesheettheme"] = PagesConfig.StyleSheetThemeInternal; if (PagesConfig.MasterPageFileInternal != null && PagesConfig.MasterPageFileInternal.Length != 0) { _configMasterPageFile = PagesConfig.MasterPageFileInternal; } if (PagesConfig.ViewStateEncryptionMode != Page.EncryptionModeDefault) { _mainDirectiveConfigSettings["viewStateEncryptionMode"] = Enum.Format(typeof(ViewStateEncryptionMode), PagesConfig.ViewStateEncryptionMode, "G"); } if (PagesConfig.MaintainScrollPositionOnPostBack != Page.MaintainScrollPositionOnPostBackDefault) { _mainDirectiveConfigSettings["maintainScrollPositionOnPostBack"] = Util.GetStringFromBool(PagesConfig.MaintainScrollPositionOnPostBack); } if (PagesConfig.MaxPageStateFieldLength != Page.DefaultMaxPageStateFieldLength) { _mainDirectiveConfigSettings["maxPageStateFieldLength"] = PagesConfig.MaxPageStateFieldLength; } flags[requiresSessionState] = ((PagesConfig.EnableSessionState == PagesEnableSessionState.True) || (PagesConfig.EnableSessionState == PagesEnableSessionState.ReadOnly)); flags[readOnlySessionState] = (PagesConfig.EnableSessionState == PagesEnableSessionState.ReadOnly); flags[validateRequest] = PagesConfig.ValidateRequest; flags[aspCompatMode] = HttpRuntime.ApartmentThreading; } ApplyBaseType(); } private void ApplyBaseType() { if (DefaultPageBaseType != null) { BaseType = DefaultPageBaseType; } else if (PagesConfig != null && PagesConfig.PageBaseTypeInternal != null) { BaseType = PagesConfig.PageBaseTypeInternal; } } internal override void ProcessDirective(string directiveName, IDictionary directive) { if (StringUtil.EqualsIgnoreCase(directiveName, "previousPageType")) { if (_previousPageType != null) { ProcessError(SR.GetString(SR.Only_one_directive_allowed, directiveName)); return; } _previousPageType = GetDirectiveType(directive, directiveName); Util.CheckAssignableType(typeof(Page), _previousPageType); } else if (StringUtil.EqualsIgnoreCase(directiveName, "masterType")) { if (_masterPageType != null) { ProcessError(SR.GetString(SR.Only_one_directive_allowed, directiveName)); return; } _masterPageType = GetDirectiveType(directive, directiveName); Util.CheckAssignableType(typeof(MasterPage), _masterPageType); } else { base.ProcessDirective(directiveName, directive); } } // Override to get the location of maindirective. internal override void ProcessMainDirective(IDictionary mainDirective) { // Remember the location of the main directive. _mainDirectiveLineNumber = _lineNumber; base.ProcessMainDirective(mainDirective); } internal override bool ProcessMainDirectiveAttribute(string deviceName, string name, string value, IDictionary parseData) { switch (name) { case "errorpage": _errorPage = Util.GetNonEmptyAttribute(name, value); // Return false to let the generic attribute processing continue return false; case "contenttype": // Check validity Util.GetNonEmptyAttribute(name, value); // Return false to let the generic attribute processing continue return false; case "theme": if (IsExpressionBuilderValue(value)) { return false; } // Check validity Util.CheckThemeAttribute(value); // Return false to let the generic attribute processing continue return false; case "stylesheettheme": // Make sure no device filter or expression builder was specified ValidateBuiltInAttribute(deviceName, name, value); // Check validity Util.CheckThemeAttribute(value); _styleSheetTheme = value; return true; case "enablesessionstate": flags[requiresSessionState] = true; flags[readOnlySessionState] = false; if (Util.IsFalseString(value)) { flags[requiresSessionState] = false; } else if (StringUtil.EqualsIgnoreCase(value, "readonly")) { flags[readOnlySessionState] = true; } else if (!Util.IsTrueString(value)) { ProcessError(SR.GetString(SR.Enablesessionstate_must_be_true_false_or_readonly)); } if (flags[requiresSessionState]) { // Session state is only available for compiled pages OnFoundAttributeRequiringCompilation(name); } break; case "culture": _culture = Util.GetNonEmptyAttribute(name, value); // Setting culture requires medium permission if (!HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Medium)) { throw new HttpException(SR.GetString(SR.Insufficient_trust_for_attribute, "culture")); } //do not verify at parse time if potentially using browser AutoDetect if(StringUtil.EqualsIgnoreCase(value, HttpApplication.AutoCulture)) { return false; } // Create a CultureInfo just to verify validity CultureInfo cultureInfo; try { if(StringUtil.StringStartsWithIgnoreCase(value, HttpApplication.AutoCulture)) { //safe to trim leading "auto:", string used elsewhere for null check _culture = _culture.Substring(5); } cultureInfo = HttpServerUtility.CreateReadOnlyCultureInfo(_culture); } catch { ProcessError(SR.GetString(SR.Invalid_attribute_value, _culture, "culture")); return false; } // Don't allow neutral cultures (ASURT 77930) if (cultureInfo.IsNeutralCulture) { ProcessError(SR.GetString(SR.Invalid_culture_attribute, Util.GetSpecificCulturesFormattedList(cultureInfo))); } // Return false to let the generic attribute processing continue return false; case "lcid": // Skip validity check for expression builder (e.g. <%$ ... %>) if (IsExpressionBuilderValue(value)) return false; _lcid = Util.GetNonNegativeIntegerAttribute(name, value); // Create a CultureInfo just to verify validity try { HttpServerUtility.CreateReadOnlyCultureInfo(_lcid); } catch { ProcessError(SR.GetString(SR.Invalid_attribute_value, _lcid.ToString(CultureInfo.InvariantCulture), "lcid")); } // Return false to let the generic attribute processing continue return false; case "uiculture": // Check validity Util.GetNonEmptyAttribute(name, value); // Return false to let the generic attribute processing continue return false; case "responseencoding": // Skip validity check for expression builder (e.g. <%$ ... %>) if (IsExpressionBuilderValue(value)) return false; _responseEncoding = Util.GetNonEmptyAttribute(name, value); // Call Encoding.GetEncoding just to verify validity Encoding.GetEncoding(_responseEncoding); // Return false to let the generic attribute processing continue return false; case "codepage": // Skip validity check for expression builder (e.g. <%$ ... %>) if (IsExpressionBuilderValue(value)) return false; _codePage = Util.GetNonNegativeIntegerAttribute(name, value); // Call Encoding.GetEncoding just to verify validity Encoding.GetEncoding(_codePage); // Return false to let the generic attribute processing continue return false; case "transaction": // This only makes sense for compiled pages OnFoundAttributeRequiringCompilation(name); ParseTransactionAttribute(name, value); break; case "aspcompat": // This only makes sense for compiled pages OnFoundAttributeRequiringCompilation(name); flags[aspCompatMode] = Util.GetBooleanAttribute(name, value); // Only allow the use of aspcompat when we have UnmanagedCode access (ASURT 76694) if (flags[aspCompatMode] && !HttpRuntime.HasUnmanagedPermission()) { throw new HttpException(SR.GetString(SR.Insufficient_trust_for_attribute, "AspCompat")); } break; case "async": // This only makes sense for compiled pages OnFoundAttributeRequiringCompilation(name); flags[asyncMode] = Util.GetBooleanAttribute(name, value); // Async requires Medium trust if (!HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Medium)) { throw new HttpException(SR.GetString(SR.Insufficient_trust_for_attribute, "async")); } break; case "tracemode": // We use TraceModeInternal instead of TraceMode to disallow the 'default' value (ASURT 75783) object tmpObj = Util.GetEnumAttribute(name, value, typeof(TraceModeInternal)); _traceMode = (TraceMode) tmpObj; break; case "trace": bool traceEnabled = Util.GetBooleanAttribute(name, value); if (traceEnabled) _traceEnabled = TraceEnable.Enable; else _traceEnabled = TraceEnable.Disable; break; case "smartnavigation": // Make sure no device filter or expression builder was specified, since it doesn't make much // sense for smartnav (which only works on IE5.5+) (VSWhidbey 85876) ValidateBuiltInAttribute(deviceName, name, value); // Ignore it if it has default value. Otherwise, let the generic // attribute processing continue bool smartNavigation = Util.GetBooleanAttribute(name, value); return (smartNavigation == Page.SmartNavigationDefault); case "maintainscrollpositiononpostback": bool maintainScrollPosition = Util.GetBooleanAttribute(name, value); return (maintainScrollPosition == Page.MaintainScrollPositionOnPostBackDefault); case "validaterequest": flags[validateRequest] = Util.GetBooleanAttribute(name, value); break; case "clienttarget": // Skip validity check for expression builder (e.g. <%$ ... %>) if (IsExpressionBuilderValue(value)) return false; // Check validity HttpCapabilitiesDefaultProvider.GetUserAgentFromClientTarget(CurrentVirtualPath, value); // Return false to let the generic attribute processing continue return false; case "masterpagefile": // Skip validity check for expression builder (e.g. <%$ ... %>) if (IsExpressionBuilderValue(value)) return false; if (value.Length > 0) { // Add dependency on the Type by calling this method Type type = GetReferencedType(value); // Make sure it has the correct base type if (!typeof(MasterPage).IsAssignableFrom(type)) { ProcessError(SR.GetString(SR.Invalid_master_base, value)); } if (deviceName.Length > 0) { // Make sure the masterPageFile definition from config // is applied before filtered masterPageFile attributes. EnsureMasterPageFileFromConfigApplied(); } } //VSWhidbey 479064 Remember the masterPageFile had been set even if it's empty string _mainDirectiveMasterPageSet = true; // Return false to let the generic attribute processing continue return false; default: // We didn't handle the attribute. Try the base class return base.ProcessMainDirectiveAttribute(deviceName, name, value, parseData); } // The attribute was handled // Make sure no device filter or resource expression was specified ValidateBuiltInAttribute(deviceName, name, value); return true; } internal override void ProcessUnknownMainDirectiveAttribute(string filter, string attribName, string value) { // asynctimeout is in seconds while the corresponding public page property is a timespan // this requires a patch-up if (attribName == "asynctimeout") { int timeoutInSeconds = Util.GetNonNegativeIntegerAttribute(attribName, value); value = (new TimeSpan(0, 0, timeoutInSeconds)).ToString(); } base.ProcessUnknownMainDirectiveAttribute(filter, attribName, value); } internal override void PostProcessMainDirectiveAttributes(IDictionary parseData) { // Can't have an error page if buffering is off if (!flags[buffer] && _errorPage != null) { ProcessError(SR.GetString(SR.Error_page_not_supported_when_buffering_off)); return; } if (_culture != null && _lcid > 0) { ProcessError(SR.GetString(SR.Attributes_mutually_exclusive, "Culture", "LCID")); return; } if (_responseEncoding != null && _codePage > 0) { ProcessError(SR.GetString(SR.Attributes_mutually_exclusive, "ResponseEncoding", "CodePage")); return; } // async can't be combined with aspcompat if (AsyncMode && AspCompatMode) { ProcessError(SR.GetString(SR.Async_and_aspcompat)); return; } // async can't be combined with transactions if (AsyncMode && _transactionMode != 0) { ProcessError(SR.GetString(SR.Async_and_transaction)); return; } // Let the base class do its post processing base.PostProcessMainDirectiveAttributes(parseData); } private enum TraceModeInternal { SortByTime = 0, SortByCategory = 1 } // This must be in its own method to avoid jitting System.EnterpriseServices.dll // when it is not needed (ASURT 71868) private void ParseTransactionAttribute(string name, string value) { object tmpObj = Util.GetEnumAttribute(name, value, typeof(TransactionOption)); if (tmpObj != null) { _transactionMode = (int) tmpObj; // Add a reference to the transaction assembly only if needed if (_transactionMode != 0 /*TransactionOption.Disabled*/) { if (!HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Medium)) { throw new HttpException(SR.GetString(SR.Insufficient_trust_for_attribute, "transaction")); } AddAssemblyDependency(typeof(TransactionOption).Assembly); } } } internal const string defaultDirectiveName = "page"; internal override string DefaultDirectiveName { get { return defaultDirectiveName; } } /* * Process the contents of the <%@ OutputCache ... %> directive */ internal override void ProcessOutputCacheDirective(string directiveName, IDictionary directive) { string varyByContentEncoding; string varyByHeader; string sqlDependency; bool noStoreValue = false; varyByContentEncoding = Util.GetAndRemoveNonEmptyAttribute(directive, "varybycontentencoding"); if (varyByContentEncoding != null) { OutputCacheParameters.VaryByContentEncoding = varyByContentEncoding; } varyByHeader = Util.GetAndRemoveNonEmptyAttribute(directive, "varybyheader"); if (varyByHeader != null) { OutputCacheParameters.VaryByHeader = varyByHeader; } object tmpObj = Util.GetAndRemoveEnumAttribute(directive, typeof(OutputCacheLocation), "location"); if (tmpObj != null) { _outputCacheLocation = (OutputCacheLocation) tmpObj; OutputCacheParameters.Location = _outputCacheLocation; } sqlDependency = Util.GetAndRemoveNonEmptyAttribute(directive, "sqldependency"); if (sqlDependency != null) { OutputCacheParameters.SqlDependency = sqlDependency; // Validate the sqldependency attribute SqlCacheDependency.ValidateOutputCacheDependencyString(sqlDependency, true); } // Get the "no store" bool value if (Util.GetAndRemoveBooleanAttribute(directive, "nostore", ref noStoreValue)) { OutputCacheParameters.NoStore = noStoreValue; } base.ProcessOutputCacheDirective(directiveName, directive); } private static Type s_defaultPageBaseType; public static Type DefaultPageBaseType { get { return s_defaultPageBaseType; } set { if (value != null && !typeof(Page).IsAssignableFrom(value)) { throw ExceptionUtil.PropertyInvalid("DefaultPageBaseType"); } BuildManager.ThrowIfPreAppStartNotRunning(); s_defaultPageBaseType = value; } } private static Type s_defaultUserContorlBaseType; public static Type DefaultUserControlBaseType { get { return s_defaultUserContorlBaseType; } set { if (value != null && !typeof(UserControl).IsAssignableFrom(value)) { throw ExceptionUtil.PropertyInvalid("DefaultUserControlBaseType"); } BuildManager.ThrowIfPreAppStartNotRunning(); s_defaultUserContorlBaseType = value; } } private static Type s_defaultApplicationBaseType; public static Type DefaultApplicationBaseType { get { return s_defaultApplicationBaseType; } set { if (value != null && !typeof(HttpApplication).IsAssignableFrom(value)) { throw ExceptionUtil.PropertyInvalid("DefaultApplicationBaseType"); } BuildManager.ThrowIfPreAppStartNotRunning(); s_defaultApplicationBaseType = value; } } private static Type s_defaultPageParserFilterType; public static Type DefaultPageParserFilterType { get { return s_defaultPageParserFilterType; } set { if (value != null && !typeof(PageParserFilter).IsAssignableFrom(value)) { throw ExceptionUtil.PropertyInvalid("DefaultPageParserFilterType"); } BuildManager.ThrowIfPreAppStartNotRunning(); s_defaultPageParserFilterType = value; } } private static bool s_enableLongStringsAsResources = true; public static bool EnableLongStringsAsResources { get { return s_enableLongStringsAsResources; } set { BuildManager.ThrowIfPreAppStartNotRunning(); s_enableLongStringsAsResources = value; } } internal override bool FDurationRequiredOnOutputCache { get { return _outputCacheLocation != OutputCacheLocation.None; } } internal override bool FVaryByParamsRequiredOnOutputCache { get { return _outputCacheLocation != OutputCacheLocation.None; } } internal override string UnknownOutputCacheAttributeError { get { return SR.Attr_not_supported_in_pagedirective; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace System.Data.SqlClient.SNI { /// <summary> /// MARS handle /// </summary> internal class SNIMarsHandle : SNIHandle { private const uint ACK_THRESHOLD = 2; private readonly SNIMarsConnection _connection; private readonly Queue<SNIPacket> _receivedPacketQueue = new Queue<SNIPacket>(); private readonly Queue<SNIMarsQueuedPacket> _sendPacketQueue = new Queue<SNIMarsQueuedPacket>(); private readonly TdsParserStateObject _callbackObject; private readonly Guid _connectionId = Guid.NewGuid(); private readonly ushort _sessionId; private readonly ManualResetEventSlim _packetEvent = new ManualResetEventSlim(false); private readonly ManualResetEventSlim _ackEvent = new ManualResetEventSlim(false); private readonly SNISMUXHeader _currentHeader = new SNISMUXHeader(); private uint _sendHighwater = 4; private int _asyncReceives = 0; private uint _receiveHighwater = 4; private uint _receiveHighwaterLastAck = 4; private uint _sequenceNumber; private SNIError _connectionError; /// <summary> /// Connection ID /// </summary> public override Guid ConnectionId { get { return _connectionId; } } /// <summary> /// Dispose object /// </summary> public override void Dispose() { SendControlPacket(SNISMUXFlags.SMUX_FIN, false); } /// <summary> /// Constructor /// </summary> /// <param name="connection">MARS connection</param> /// <param name="sessionId">MARS session ID</param> /// <param name="callbackObject">Callback object</param> /// <param name="async">true if connection is asynchronous</param> public SNIMarsHandle(SNIMarsConnection connection, ushort sessionId, TdsParserStateObject callbackObject, out SNIError sniError) { _sessionId = sessionId; _connection = connection; _callbackObject = callbackObject; sniError = SendControlPacket(SNISMUXFlags.SMUX_SYN, true); } /// <summary> /// Send control packet /// </summary> /// <param name="flags">SMUX header flags</param> /// <param name="async">true if packet should be sent asynchronously</param> /// <returns>True if completed successfully, otherwise false</returns> private SNIError SendControlPacket(SNISMUXFlags flags, bool async) { byte[] headerBytes = null; lock (this) { GetSMUXHeaderBytes(0, (byte)flags, ref headerBytes); } SNIPacket packet = new SNIPacket(headerBytes, SNISMUXHeader.HEADER_LENGTH); if (async) { SNIError sniError; _connection.SendAsync(packet, NullCallback, false, out sniError); return sniError; } else { return _connection.Send(packet); } } private static void NullCallback(SNIPacket packet, SNIError error) { } /// <summary> /// Generate SMUX header /// </summary> /// <param name="length">Packet length</param> /// <param name="flags">Packet flags</param> /// <param name="headerBytes">Header in bytes</param> private void GetSMUXHeaderBytes(int length, byte flags, ref byte[] headerBytes) { headerBytes = new byte[SNISMUXHeader.HEADER_LENGTH]; _currentHeader.SMID = 83; _currentHeader.flags = flags; _currentHeader.sessionId = _sessionId; _currentHeader.length = (uint)SNISMUXHeader.HEADER_LENGTH + (uint)length; _currentHeader.sequenceNumber = ((flags == (byte)SNISMUXFlags.SMUX_FIN) || (flags == (byte)SNISMUXFlags.SMUX_ACK)) ? _sequenceNumber - 1 : _sequenceNumber++; _currentHeader.highwater = _receiveHighwater; _receiveHighwaterLastAck = _currentHeader.highwater; BitConverter.GetBytes(_currentHeader.SMID).CopyTo(headerBytes, 0); BitConverter.GetBytes(_currentHeader.flags).CopyTo(headerBytes, 1); BitConverter.GetBytes(_currentHeader.sessionId).CopyTo(headerBytes, 2); BitConverter.GetBytes(_currentHeader.length).CopyTo(headerBytes, 4); BitConverter.GetBytes(_currentHeader.sequenceNumber).CopyTo(headerBytes, 8); BitConverter.GetBytes(_currentHeader.highwater).CopyTo(headerBytes, 12); } /// <summary> /// Generate a packet with SMUX header /// </summary> /// <param name="packet">SNI packet</param> /// <returns>Encapsulated SNI packet</returns> private SNIPacket GetSMUXEncapsulatedPacket(SNIPacket packet) { uint xSequenceNumber = _sequenceNumber; byte[] headerBytes = null; GetSMUXHeaderBytes(packet.Length, (byte)SNISMUXFlags.SMUX_DATA, ref headerBytes); SNIPacket smuxPacket = new SNIPacket(); #if DEBUG smuxPacket.Description = string.Format("({0}) SMUX packet {1}", packet.Description == null ? "" : packet.Description, xSequenceNumber); #endif smuxPacket.Allocate(16 + packet.Length); smuxPacket.AppendData(headerBytes, 16); smuxPacket.AppendPacket(packet); return smuxPacket; } /// Send a packet synchronously /// </summary> /// <param name="packet">SNI packet</param> /// <returns>SNI error code</returns> public override SNIError Send(SNIPacket packet) { while (true) { lock (this) { if (_sequenceNumber < _sendHighwater) { break; } } _ackEvent.Wait(); lock (this) { _ackEvent.Reset(); } } return _connection.Send(GetSMUXEncapsulatedPacket(packet)); } /// <summary> /// Send packet asynchronously /// </summary> /// <param name="packet">SNI packet</param> /// <param name="callback">Completion callback</param> /// <returns>True if completed successfully, otherwise false</returns> private bool InternalSendAsync(SNIPacket packet, SNIAsyncCallback callback) { SNIPacket encapsulatedPacket = null; lock (this) { if (_sequenceNumber >= _sendHighwater) { return false; } encapsulatedPacket = GetSMUXEncapsulatedPacket(packet); if (callback != null) { encapsulatedPacket.SetCompletionCallback(callback); } else { encapsulatedPacket.SetCompletionCallback(HandleSendComplete); } SNIError sniError; bool completedSync = _connection.SendAsync(encapsulatedPacket, callback, true, out sniError); Debug.Assert(!completedSync && (sniError == null), "Should not have completed synchronously"); return true; } } /// <summary> /// Send pending packets /// </summary> /// <returns>True if all packets finished sending sync or an error occurred, otherwise false</returns> private void SendPendingPackets() { while (true) { lock (this) { if (_sequenceNumber < _sendHighwater) { if (_sendPacketQueue.Count != 0) { SNIMarsQueuedPacket packet = _sendPacketQueue.Peek(); if (!InternalSendAsync(packet.Packet, packet.Callback)) { return; } _sendPacketQueue.Dequeue(); continue; } else { _ackEvent.Set(); } } break; } } } /// <summary> /// Send a packet asynchronously /// </summary> /// <param name="packet">SNI packet</param> /// <param name="callback">Completion callback</param> /// <returns>SNI error code</returns> public override bool SendAsync(SNIPacket packet, SNIAsyncCallback callback, bool forceCallback, out SNIError sniError) { lock (this) { _sendPacketQueue.Enqueue(new SNIMarsQueuedPacket(packet, callback != null ? callback : HandleSendComplete)); } SendPendingPackets(); sniError = null; return false; } /// <summary> /// Receive a packet asynchronously /// </summary> /// <returns>True if completed synchronously, otherwise false</returns> public override bool ReceiveAsync(bool forceCallback, ref SNIPacket packet, out SNIError sniError) { Debug.Assert(!forceCallback, "SNIMarsHandles should never be forced to use a callback"); lock (_receivedPacketQueue) { int queueCount = _receivedPacketQueue.Count; if (_connectionError != null) { sniError = _connectionError; return true; } if (queueCount == 0) { _asyncReceives++; sniError = null; return false; } packet = _receivedPacketQueue.Dequeue(); if (queueCount == 1) { _packetEvent.Reset(); } } lock (this) { _receiveHighwater++; } sniError = SendAckIfNecessary(); return true; } /// <summary> /// Handle receive error /// </summary> public void HandleReceiveError(SNIPacket packet, SNIError sniError) { int callbacksPending; lock (_receivedPacketQueue) { Debug.Assert(_connectionError == null, "Already have a stored connection error"); _connectionError = sniError; // Wake any pending sync receives _packetEvent.Set(); callbacksPending = _asyncReceives; _asyncReceives = 0; } // Callback to any pending async receives for (int i = 0; i < _asyncReceives; i++) { _callbackObject.ReadAsyncCallback(packet, _connectionError); } } /// <summary> /// Handle send completion /// </summary> public void HandleSendComplete(SNIPacket packet, SNIError sniError) { Debug.Assert(_callbackObject != null); _callbackObject.WriteAsyncCallback(packet, sniError); } /// <summary> /// Handle SMUX acknowledgement /// </summary> /// <param name="highwater">Send highwater mark</param> public void HandleAck(uint highwater) { lock (this) { if (_sendHighwater != highwater) { _sendHighwater = highwater; SendPendingPackets(); } } } /// <summary> /// Handle receive completion /// </summary> /// <param name="packet">SNI packet</param> /// <param name="header">SMUX header</param> public void HandleReceiveComplete(SNIPacket packet, SNISMUXHeader header) { lock (this) { if (_sendHighwater != header.highwater) { HandleAck(header.highwater); } lock (_receivedPacketQueue) { // The error callback takes care of completing all pending receives if (_connectionError == null) { if (_asyncReceives == 0) { _receivedPacketQueue.Enqueue(packet); _packetEvent.Set(); return; } _asyncReceives--; } } } _callbackObject.ReadAsyncCallback(packet, null); lock (this) { _receiveHighwater++; } SendAckIfNecessary(); } /// <summary> /// Send ACK if we've hit highwater threshold /// </summary> private SNIError SendAckIfNecessary() { uint receiveHighwater; uint receiveHighwaterLastAck; lock (this) { receiveHighwater = _receiveHighwater; receiveHighwaterLastAck = _receiveHighwaterLastAck; } if (receiveHighwater - receiveHighwaterLastAck > ACK_THRESHOLD) { return SendControlPacket(SNISMUXFlags.SMUX_ACK, true); } return null; } /// <summary> /// Receive a packet synchronously /// </summary> /// <param name="packet">SNI packet</param> /// <param name="timeoutInMilliseconds">Timeout in Milliseconds</param> /// <returns>SNI error code</returns> public override SNIError Receive(ref SNIPacket packet, int timeout) { int queueCount; uint result = TdsEnums.SNI_SUCCESS_IO_PENDING; while (true) { lock (_receivedPacketQueue) { if (_connectionError != null) { return _connectionError; } queueCount = _receivedPacketQueue.Count; if (queueCount > 0) { packet = _receivedPacketQueue.Dequeue(); if (queueCount == 1) { _packetEvent.Reset(); } result = TdsEnums.SNI_SUCCESS; } } if (result == TdsEnums.SNI_SUCCESS) { lock (this) { _receiveHighwater++; } return SendAckIfNecessary(); } if (!_packetEvent.Wait(timeout)) { return new SNIError(SNIProviders.SMUX_PROV, 0, SNIErrorCode.ConnTimeoutError, string.Empty); } } } /// <summary> /// Check SNI handle connection /// </summary> /// <param name="handle"></param> /// <returns>SNI error status</returns> public override bool CheckConnection() { return _connection.CheckConnection(); } /// <summary> /// Set async callbacks /// </summary> /// <param name="receiveCallback">Receive callback</param> /// <param name="sendCallback">Send callback</param> public override void SetAsyncCallbacks(SNIAsyncCallback receiveCallback, SNIAsyncCallback sendCallback) { Debug.Assert(false, "Should never be called for a SNIMarsHandle"); } /// <summary> /// Set buffer size /// </summary> /// <param name="bufferSize">Buffer size</param> public override void SetBufferSize(int bufferSize) { } /// <summary> /// Enable SSL /// </summary> public override SNIError EnableSsl(uint options) { return _connection.EnableSsl(options); } /// <summary> /// Disable SSL /// </summary> public override void DisableSsl() { _connection.DisableSsl(); } /// <summary> /// Test handle for killing underlying connection /// </summary> public override void KillConnection() { _connection.KillConnection(); } /// <summary> /// Creates a new MARS session. /// </summary> public override SNIHandle CreateSession(TdsParserStateObject callbackObject, out SNIError sniError) { return _connection.CreateSession(callbackObject, out sniError); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using NHibernate.Mapping; namespace Themis.NHibernate.Impl { /// <summary> /// The expression visitor, which for a specified pair: entity type and role type, /// provides the compounded sql condition. /// </summary> internal class FilteringExpressionToSqlVisitor : ExpressionVisitor { private readonly Type _entityType; private readonly PersistentClass _model; private readonly Func<MemberExpression, string> _roleParameterNameGetter; private readonly Type _roleType; private List<string> _partialConditions; public FilteringExpressionToSqlVisitor(Type roleType, Type entityType, PersistentClass model, Func<MemberExpression, string> roleParameterNameGetter) { _roleType = roleType; _entityType = entityType; _model = model; _roleParameterNameGetter = roleParameterNameGetter; } /// <summary> /// Gets the compounded, or-connected condition for the expressions passed as a paramter. /// </summary> /// <param name="expressions">The bool returning expressions having an entity type and role type as parameters.</param> /// <returns></returns> public string GetCondition(IEnumerable<LambdaExpression> expressions) { _partialConditions = new List<string>(); foreach (var e in expressions) { _partialConditions.Add(Visit(e).ToString()); } if (_partialConditions.Count == 1) return _partialConditions[0]; var conditions = _partialConditions.Select(WrapWithBrackets).ToArray(); var result = string.Join(" OR ", conditions); return WrapWithBrackets(result); } private static string WrapWithBrackets(string result) { return "(" + result + ")"; } protected override Expression VisitUnary(UnaryExpression u) { if (u.NodeType != ExpressionType.Not) { throw new ArgumentException("Currently only NOT unary operator is handled", "u"); } return Expression.Constant(new ConstantExpressionValue("NOT (" + Visit(u.Operand) + ")")); } protected override Expression VisitBinary(BinaryExpression b) { switch (b.NodeType) { case ExpressionType.LessThan: return VisitBinary(b, "<"); case ExpressionType.LessThanOrEqual: return VisitBinary(b, "<="); case ExpressionType.GreaterThan: return VisitBinary(b, ">"); case ExpressionType.GreaterThanOrEqual: return VisitBinary(b, ">="); case ExpressionType.Equal: return VisitBinary(b, "="); case ExpressionType.NotEqual: return VisitBinary(b, "<>"); default: throw new ArgumentException("Currently only comperator expressions are handled", "b"); } } protected override Expression VisitLambda<T>(Expression<T> lambda) { return Visit(lambda.Body); } protected override Expression VisitInvocation(InvocationExpression iv) { throw new ArgumentException("Visiting InvocationExpression is not handled"); } protected override Expression VisitListInit(ListInitExpression init) { throw new ArgumentException("Visiting ListInitExpression is not handled"); } protected override MemberAssignment VisitMemberAssignment(MemberAssignment assignment) { throw new ArgumentException("Visiting MemberAssignment is not handled"); } protected override Expression VisitMemberInit(MemberInitExpression init) { throw new ArgumentException("Visiting MemberInitExpression is not handled"); } protected override MemberListBinding VisitMemberListBinding(MemberListBinding binding) { throw new ArgumentException("Visiting MemberListBinding is not handled"); } protected override MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding) { throw new ArgumentException("Visiting MemberMemberBinding is not handled"); } protected override Expression VisitMethodCall(MethodCallExpression m) { throw new ArgumentException("Visiting MethodCallExpression is not handled"); } protected override Expression VisitNew(NewExpression node) { throw new ArgumentException("Visiting NewExpression is not handled"); } protected override Expression VisitNewArray(NewArrayExpression na) { throw new ArgumentException("Visiting NewArrayExpression is not handled"); } protected override Expression VisitParameter(ParameterExpression p) { throw new ArgumentException( "Visiting ParameterExpression is not handled. There should be no situation where Themis process a parameter expression."); } protected override Expression VisitMember(MemberExpression m) { var temp = m.Expression; while (temp is MemberExpression) { temp = ((MemberExpression)temp).Expression; } var param = temp as ParameterExpression; if (param == null) { throw new ArgumentException("Themis cannot establish for which paramter the passed expression was used"); } if (param.Type == _entityType) { return ProcessEntityExpression(m); } if (param.Type == _roleType) { return ProcessRoleExpression(m); } throw new ArgumentException("The passed member expression is neither entity or role expression", "m"); } private Expression ProcessEntityExpression(MemberExpression m) { var isSimpleProperty = m.Expression is ParameterExpression; if (isSimpleProperty) { var property = _model.GetProperty(m.Member.Name); return ProcessEntitySimpleProperty(property); } var mayBeToOne = m.Expression is MemberExpression; if (mayBeToOne) { var member = (MemberExpression)m.Expression; var property = _model.GetProperty(member.Member.Name); var entityPropInfo = string.Format("Entity type: {0}, property name: {1}", _entityType.FullName, property.Name); if (!(property.Value is ToOne)) { throw new InvalidOperationException("Only to one mappings are considered. " + entityPropInfo); } var dbField = property.Value.ColumnIterator.First().Text; return Expression.Constant(new ConstantExpressionValue(dbField)); } throw new ArgumentException("The member expression " + m + " cannot be processed by Themis."); } private Expression ProcessEntitySimpleProperty(Property property) { var entityPropInfo = string.Format("Entity type: {0}, property name: {1}", _entityType.FullName, property.Name); if (property.IsComposite) { throw new InvalidOperationException("Composite columns are not handled by Themis. " + entityPropInfo); } if (property.Value.GetType() == typeof(SimpleValue)) { var dbField = property.Value.ColumnIterator.First().Text; return Expression.Constant(new ConstantExpressionValue(dbField)); } throw new InvalidOperationException("The equality can be done only on the SimpleValue property. " + entityPropInfo); } private Expression ProcessRoleExpression(MemberExpression memberExpression) { return Expression.Constant( new ConstantExpressionValue(":" + _roleParameterNameGetter(memberExpression))); } private ConstantExpression VisitBinary(BinaryExpression b, string op) { return Expression.Constant(new ConstantExpressionValue("(" + Visit(b.Left) + op + Visit(b.Right) + ")")); } #region Nested type: ConstantExpressionValue private class ConstantExpressionValue { private readonly string _value; public ConstantExpressionValue(string value) { _value = value; } public override string ToString() { return _value; } } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace FileBrowser.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>(); } /// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and 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)) { 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="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <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, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System.Threading.Tasks; using System.Diagnostics; namespace System.IO { // This class implements a TextWriter for writing characters to a Stream. // This is designed for character output in a particular Encoding, // whereas the Stream class is designed for byte input and output. [Serializable] public class StreamWriter : TextWriter { // For UTF-8, the values of 1K for the default buffer size and 4K for the // file stream buffer size are reasonable & give very reasonable // performance for in terms of construction time for the StreamWriter and // write perf. Note that for UTF-8, we end up allocating a 4K byte buffer, // which means we take advantage of adaptive buffering code. // The performance using UnicodeEncoding is acceptable. private const int DefaultBufferSize = 1024; // char[] private const int DefaultFileStreamBufferSize = 4096; private const int MinBufferSize = 128; private const int DontCopyOnWriteLineThreshold = 512; // Bit bucket - Null has no backing store. Non closable. public new static readonly StreamWriter Null = new StreamWriter(Stream.Null, UTF8NoBOM, MinBufferSize, true); private Stream _stream; private Encoding _encoding; private Encoder _encoder; private byte[] _byteBuffer; private char[] _charBuffer; private int _charPos; private int _charLen; private bool _autoFlush; private bool _haveWrittenPreamble; private bool _closable; // We don't guarantee thread safety on StreamWriter, but we should at // least prevent users from trying to write anything while an Async // write from the same thread is in progress. [NonSerialized] private volatile Task _asyncWriteTask; private void CheckAsyncTaskInProgress() { // We are not locking the access to _asyncWriteTask because this is not meant to guarantee thread safety. // We are simply trying to deter calling any Write APIs while an async Write from the same thread is in progress. Task t = _asyncWriteTask; if (t != null && !t.IsCompleted) throw new InvalidOperationException(SR.InvalidOperation_AsyncIOInProgress); } // The high level goal is to be tolerant of encoding errors when we read and very strict // when we write. Hence, default StreamWriter encoding will throw on encoding error. // Note: when StreamWriter throws on invalid encoding chars (for ex, high surrogate character // D800-DBFF without a following low surrogate character DC00-DFFF), it will cause the // internal StreamWriter's state to be irrecoverable as it would have buffered the // illegal chars and any subsequent call to Flush() would hit the encoding error again. // Even Close() will hit the exception as it would try to flush the unwritten data. // Maybe we can add a DiscardBufferedData() method to get out of such situation (like // StreamReader though for different reason). Either way, the buffered data will be lost! private static Encoding UTF8NoBOM => EncodingCache.UTF8NoBOM; internal StreamWriter() : base(null) { // Ask for CurrentCulture all the time } public StreamWriter(Stream stream) : this(stream, UTF8NoBOM, DefaultBufferSize, false) { } public StreamWriter(Stream stream, Encoding encoding) : this(stream, encoding, DefaultBufferSize, false) { } // Creates a new StreamWriter for the given stream. The // character encoding is set by encoding and the buffer size, // in number of 16-bit characters, is set by bufferSize. // public StreamWriter(Stream stream, Encoding encoding, int bufferSize) : this(stream, encoding, bufferSize, false) { } public StreamWriter(Stream stream, Encoding encoding, int bufferSize, bool leaveOpen) : base(null) // Ask for CurrentCulture all the time { if (stream == null || encoding == null) { throw new ArgumentNullException(stream == null ? nameof(stream) : nameof(encoding)); } if (!stream.CanWrite) { throw new ArgumentException(SR.Argument_StreamNotWritable); } if (bufferSize <= 0) { throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); } Init(stream, encoding, bufferSize, leaveOpen); } public StreamWriter(string path) : this(path, false, UTF8NoBOM, DefaultBufferSize) { } public StreamWriter(string path, bool append) : this(path, append, UTF8NoBOM, DefaultBufferSize) { } public StreamWriter(string path, bool append, Encoding encoding) : this(path, append, encoding, DefaultBufferSize) { } public StreamWriter(string path, bool append, Encoding encoding, int bufferSize) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath); if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); Stream stream = new FileStream(path, append ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.Read, DefaultFileStreamBufferSize, FileOptions.SequentialScan); Init(stream, encoding, bufferSize, shouldLeaveOpen: false); } private void Init(Stream streamArg, Encoding encodingArg, int bufferSize, bool shouldLeaveOpen) { _stream = streamArg; _encoding = encodingArg; _encoder = _encoding.GetEncoder(); if (bufferSize < MinBufferSize) { bufferSize = MinBufferSize; } _charBuffer = new char[bufferSize]; _byteBuffer = new byte[_encoding.GetMaxByteCount(bufferSize)]; _charLen = bufferSize; // If we're appending to a Stream that already has data, don't write // the preamble. if (_stream.CanSeek && _stream.Position > 0) { _haveWrittenPreamble = true; } _closable = !shouldLeaveOpen; } public override void Close() { Dispose(true); GC.SuppressFinalize(this); } protected override void Dispose(bool disposing) { try { // We need to flush any buffered data if we are being closed/disposed. // Also, we never close the handles for stdout & friends. So we can safely // write any buffered data to those streams even during finalization, which // is generally the right thing to do. if (_stream != null) { // Note: flush on the underlying stream can throw (ex., low disk space) if (disposing /* || (LeaveOpen && stream is __ConsoleStream) */) { CheckAsyncTaskInProgress(); Flush(true, true); } } } finally { // Dispose of our resources if this StreamWriter is closable. // Note: Console.Out and other such non closable streamwriters should be left alone if (!LeaveOpen && _stream != null) { try { // Attempt to close the stream even if there was an IO error from Flushing. // Note that Stream.Close() can potentially throw here (may or may not be // due to the same Flush error). In this case, we still need to ensure // cleaning up internal resources, hence the finally block. if (disposing) { _stream.Close(); } } finally { _stream = null; _byteBuffer = null; _charBuffer = null; _encoding = null; _encoder = null; _charLen = 0; base.Dispose(disposing); } } } } public override void Flush() { CheckAsyncTaskInProgress(); Flush(true, true); } private void Flush(bool flushStream, bool flushEncoder) { // flushEncoder should be true at the end of the file and if // the user explicitly calls Flush (though not if AutoFlush is true). // This is required to flush any dangling characters from our UTF-7 // and UTF-8 encoders. if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } // Perf boost for Flush on non-dirty writers. if (_charPos == 0 && !flushStream && !flushEncoder) { return; } if (!_haveWrittenPreamble) { _haveWrittenPreamble = true; byte[] preamble = _encoding.GetPreamble(); if (preamble.Length > 0) { _stream.Write(preamble, 0, preamble.Length); } } int count = _encoder.GetBytes(_charBuffer, 0, _charPos, _byteBuffer, 0, flushEncoder); _charPos = 0; if (count > 0) { _stream.Write(_byteBuffer, 0, count); } // By definition, calling Flush should flush the stream, but this is // only necessary if we passed in true for flushStream. The Web // Services guys have some perf tests where flushing needlessly hurts. if (flushStream) { _stream.Flush(); } } public virtual bool AutoFlush { get { return _autoFlush; } set { CheckAsyncTaskInProgress(); _autoFlush = value; if (value) { Flush(true, false); } } } public virtual Stream BaseStream { get { return _stream; } } internal bool LeaveOpen { get { return !_closable; } } internal bool HaveWrittenPreamble { set { _haveWrittenPreamble = value; } } public override Encoding Encoding { get { return _encoding; } } public override void Write(char value) { CheckAsyncTaskInProgress(); if (_charPos == _charLen) { Flush(false, false); } _charBuffer[_charPos] = value; _charPos++; if (_autoFlush) { Flush(true, false); } } public override void Write(char[] buffer) { // This may be faster than the one with the index & count since it // has to do less argument checking. if (buffer == null) { return; } CheckAsyncTaskInProgress(); int index = 0; int count = buffer.Length; while (count > 0) { if (_charPos == _charLen) { Flush(false, false); } int n = _charLen - _charPos; if (n > count) { n = count; } Debug.Assert(n > 0, "StreamWriter::Write(char[]) isn't making progress! This is most likely a race in user code."); Buffer.BlockCopy(buffer, index * sizeof(char), _charBuffer, _charPos * sizeof(char), n * sizeof(char)); _charPos += n; index += n; count -= n; } if (_autoFlush) { Flush(true, false); } } public override void Write(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } CheckAsyncTaskInProgress(); while (count > 0) { if (_charPos == _charLen) { Flush(false, false); } int n = _charLen - _charPos; if (n > count) { n = count; } Debug.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code."); Buffer.BlockCopy(buffer, index * sizeof(char), _charBuffer, _charPos * sizeof(char), n * sizeof(char)); _charPos += n; index += n; count -= n; } if (_autoFlush) { Flush(true, false); } } public override void Write(string value) { if (value == null) { return; } CheckAsyncTaskInProgress(); int count = value.Length; int index = 0; while (count > 0) { if (_charPos == _charLen) { Flush(false, false); } int n = _charLen - _charPos; if (n > count) { n = count; } Debug.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code."); value.CopyTo(index, _charBuffer, _charPos, n); _charPos += n; index += n; count -= n; } if (_autoFlush) { Flush(true, false); } } // // Optimize the most commonly used WriteLine overload. This optimization is important for System.Console in particular // because of it will make one WriteLine equal to one call to the OS instead of two in the common case. // public override void WriteLine(string value) { if (value == null) { value = String.Empty; } CheckAsyncTaskInProgress(); int count = value.Length; int index = 0; while (count > 0) { if (_charPos == _charLen) { Flush(false, false); } int n = _charLen - _charPos; if (n > count) { n = count; } Debug.Assert(n > 0, "StreamWriter::WriteLine(String) isn't making progress! This is most likely a race condition in user code."); value.CopyTo(index, _charBuffer, _charPos, n); _charPos += n; index += n; count -= n; } char[] coreNewLine = CoreNewLine; for (int i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (_charPos == _charLen) { Flush(false, false); } _charBuffer[_charPos] = coreNewLine[i]; _charPos++; } if (_autoFlush) { Flush(true, false); } } #region Task based Async APIs public override Task WriteAsync(char value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteAsync(value); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: false); _asyncWriteTask = task; return task; } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. // Fields that are written to must be assigned at the end of the method *and* before instance invocations. private static async Task WriteAsyncInternal(StreamWriter _this, char value, char[] charBuffer, int charPos, int charLen, char[] coreNewLine, bool autoFlush, bool appendNewLine) { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } charBuffer[charPos] = value; charPos++; if (appendNewLine) { for (int i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } charBuffer[charPos] = coreNewLine[i]; charPos++; } } if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } _this.CharPos_Prop = charPos; } public override Task WriteAsync(string value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteAsync(value); } if (value != null) { if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: false); _asyncWriteTask = task; return task; } else { return Task.CompletedTask; } } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. // Fields that are written to must be assigned at the end of the method *and* before instance invocations. private static async Task WriteAsyncInternal(StreamWriter _this, string value, char[] charBuffer, int charPos, int charLen, char[] coreNewLine, bool autoFlush, bool appendNewLine) { Debug.Assert(value != null); int count = value.Length; int index = 0; while (count > 0) { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } int n = charLen - charPos; if (n > count) { n = count; } Debug.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code."); value.CopyTo(index, charBuffer, charPos, n); charPos += n; index += n; count -= n; } if (appendNewLine) { for (int i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } charBuffer[charPos] = coreNewLine[i]; charPos++; } } if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } _this.CharPos_Prop = charPos; } public override Task WriteAsync(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteAsync(buffer, index, count); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, buffer, index, count, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: false); _asyncWriteTask = task; return task; } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. // Fields that are written to must be assigned at the end of the method *and* before instance invocations. private static async Task WriteAsyncInternal(StreamWriter _this, char[] buffer, int index, int count, char[] charBuffer, int charPos, int charLen, char[] coreNewLine, bool autoFlush, bool appendNewLine) { Debug.Assert(count == 0 || (count > 0 && buffer != null)); Debug.Assert(index >= 0); Debug.Assert(count >= 0); Debug.Assert(buffer == null || (buffer != null && buffer.Length - index >= count)); while (count > 0) { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } int n = charLen - charPos; if (n > count) { n = count; } Debug.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code."); Buffer.BlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char)); charPos += n; index += n; count -= n; } if (appendNewLine) { for (int i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } charBuffer[charPos] = coreNewLine[i]; charPos++; } } if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } _this.CharPos_Prop = charPos; } public override Task WriteLineAsync() { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteLineAsync(); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, null, 0, 0, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } public override Task WriteLineAsync(char value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteLineAsync(value); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } public override Task WriteLineAsync(string value) { if (value == null) { return WriteLineAsync(); } // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteLineAsync(value); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } public override Task WriteLineAsync(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteLineAsync(buffer, index, count); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, buffer, index, count, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } public override Task FlushAsync() { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Flush() which a subclass might have overridden. To be safe // we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Flush) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.FlushAsync(); } // flushEncoder should be true at the end of the file and if // the user explicitly calls Flush (though not if AutoFlush is true). // This is required to flush any dangling characters from our UTF-7 // and UTF-8 encoders. if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = FlushAsyncInternal(true, true, _charBuffer, _charPos); _asyncWriteTask = task; return task; } private int CharPos_Prop { set { _charPos = value; } } private bool HaveWrittenPreamble_Prop { set { _haveWrittenPreamble = value; } } private Task FlushAsyncInternal(bool flushStream, bool flushEncoder, char[] sCharBuffer, int sCharPos) { // Perf boost for Flush on non-dirty writers. if (sCharPos == 0 && !flushStream && !flushEncoder) { return Task.CompletedTask; } Task flushTask = FlushAsyncInternal(this, flushStream, flushEncoder, sCharBuffer, sCharPos, _haveWrittenPreamble, _encoding, _encoder, _byteBuffer, _stream); _charPos = 0; return flushTask; } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. private static async Task FlushAsyncInternal(StreamWriter _this, bool flushStream, bool flushEncoder, char[] charBuffer, int charPos, bool haveWrittenPreamble, Encoding encoding, Encoder encoder, Byte[] byteBuffer, Stream stream) { if (!haveWrittenPreamble) { _this.HaveWrittenPreamble_Prop = true; byte[] preamble = encoding.GetPreamble(); if (preamble.Length > 0) { await stream.WriteAsync(preamble, 0, preamble.Length).ConfigureAwait(false); } } int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder); if (count > 0) { await stream.WriteAsync(byteBuffer, 0, count).ConfigureAwait(false); } // By definition, calling Flush should flush the stream, but this is // only necessary if we passed in true for flushStream. The Web // Services guys have some perf tests where flushing needlessly hurts. if (flushStream) { await stream.FlushAsync().ConfigureAwait(false); } } #endregion } // class StreamWriter } // namespace
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Timers; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using DirFindFlags = OpenMetaverse.DirectoryManager.DirFindFlags; namespace OpenSim.Groups { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "GroupsModule")] public class GroupsModule : ISharedRegionModule, IGroupsModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private List<Scene> m_sceneList = new List<Scene>(); private IMessageTransferModule m_msgTransferModule = null; private IGroupsServicesConnector m_groupData = null; private IUserManagement m_UserManagement; // Configuration settings private bool m_groupsEnabled = false; private bool m_groupNoticesEnabled = true; private bool m_debugEnabled = false; private int m_levelGroupCreate = 0; #region Region Module interfaceBase Members public void Initialise(IConfigSource config) { IConfig groupsConfig = config.Configs["Groups"]; if (groupsConfig == null) { // Do not run this module by default. return; } else { m_groupsEnabled = groupsConfig.GetBoolean("Enabled", false); if (!m_groupsEnabled) { return; } if (groupsConfig.GetString("Module", "Default") != Name) { m_groupsEnabled = false; return; } m_log.InfoFormat("[Groups]: Initializing {0}", this.Name); m_groupNoticesEnabled = groupsConfig.GetBoolean("NoticesEnabled", true); m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", false); m_levelGroupCreate = groupsConfig.GetInt("LevelGroupCreate", 0); } } public void AddRegion(Scene scene) { if (m_groupsEnabled) { scene.RegisterModuleInterface<IGroupsModule>(this); scene.AddCommand( "Debug", this, "debug groups verbose", "debug groups verbose <true|false>", "This setting turns on very verbose groups debugging", HandleDebugGroupsVerbose); } } private void HandleDebugGroupsVerbose(object modules, string[] args) { if (args.Length < 4) { MainConsole.Instance.Output("Usage: debug groups verbose <true|false>"); return; } bool verbose = false; if (!bool.TryParse(args[3], out verbose)) { MainConsole.Instance.Output("Usage: debug groups verbose <true|false>"); return; } m_debugEnabled = verbose; MainConsole.Instance.OutputFormat("{0} verbose logging set to {1}", Name, m_debugEnabled); } public void RegionLoaded(Scene scene) { if (!m_groupsEnabled) return; if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); if (m_groupData == null) { m_groupData = scene.RequestModuleInterface<IGroupsServicesConnector>(); // No Groups Service Connector, then nothing works... if (m_groupData == null) { m_groupsEnabled = false; m_log.Error("[Groups]: Could not get IGroupsServicesConnector"); RemoveRegion(scene); return; } } if (m_msgTransferModule == null) { m_msgTransferModule = scene.RequestModuleInterface<IMessageTransferModule>(); // No message transfer module, no notices, group invites, rejects, ejects, etc if (m_msgTransferModule == null) { m_log.Warn("[Groups]: Could not get MessageTransferModule"); } } if (m_UserManagement == null) { m_UserManagement = scene.RequestModuleInterface<IUserManagement>(); if (m_UserManagement == null) m_log.Warn("[Groups]: Could not get UserManagementModule"); } lock (m_sceneList) { m_sceneList.Add(scene); } scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnMakeRootAgent += OnMakeRoot; scene.EventManager.OnMakeChildAgent += OnMakeChild; scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; scene.EventManager.OnClientClosed += OnClientClosed; } public void RemoveRegion(Scene scene) { if (!m_groupsEnabled) return; if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); scene.EventManager.OnNewClient -= OnNewClient; scene.EventManager.OnMakeRootAgent -= OnMakeRoot; scene.EventManager.OnMakeChildAgent -= OnMakeChild; scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage; scene.EventManager.OnClientClosed -= OnClientClosed; lock (m_sceneList) { m_sceneList.Remove(scene); } } public void Close() { if (!m_groupsEnabled) return; if (m_debugEnabled) m_log.Debug("[Groups]: Shutting down Groups module."); } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "Groups Module V2"; } } public void PostInitialise() { // NoOp } #endregion #region EventHandlers private void OnNewClient(IClientAPI client) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); client.OnAgentDataUpdateRequest += OnAgentDataUpdateRequest; client.OnRequestAvatarProperties += OnRequestAvatarProperties; } private void OnMakeRoot(ScenePresence sp) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); sp.ControllingClient.OnUUIDGroupNameRequest += HandleUUIDGroupNameRequest; // Used for Notices and Group Invites/Accept/Reject sp.ControllingClient.OnInstantMessage += OnInstantMessage; // Send out group data update for compatibility. // There might be some problem with the thread we're generating this on but not // doing the update at this time causes problems (Mantis #7920 and #7915) // TODO: move sending this update to a later time in the rootification of the client. if(!sp.haveGroupInformation) SendAgentGroupDataUpdate(sp.ControllingClient, false); } private void OnMakeChild(ScenePresence sp) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); sp.ControllingClient.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest; // Used for Notices and Group Invites/Accept/Reject sp.ControllingClient.OnInstantMessage -= OnInstantMessage; } private void OnRequestAvatarProperties(IClientAPI remoteClient, UUID avatarID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupMembershipData[] avatarGroups = GetProfileListedGroupMemberships(remoteClient, avatarID); remoteClient.SendAvatarGroupsReply(avatarID, avatarGroups); } private void OnClientClosed(UUID AgentId, Scene scene) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); if (scene == null) return; ScenePresence sp = scene.GetScenePresence(AgentId); IClientAPI client = sp.ControllingClient; if (client != null) { client.OnAgentDataUpdateRequest -= OnAgentDataUpdateRequest; client.OnRequestAvatarProperties -= OnRequestAvatarProperties; // make child possible not called? client.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest; client.OnInstantMessage -= OnInstantMessage; } /* lock (m_ActiveClients) { if (m_ActiveClients.ContainsKey(AgentId)) { IClientAPI client = m_ActiveClients[AgentId]; client.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest; client.OnAgentDataUpdateRequest -= OnAgentDataUpdateRequest; client.OnDirFindQuery -= OnDirFindQuery; client.OnInstantMessage -= OnInstantMessage; m_ActiveClients.Remove(AgentId); } else { if (m_debugEnabled) m_log.WarnFormat("[Groups]: Client closed that wasn't registered here."); } } */ } private void OnAgentDataUpdateRequest(IClientAPI remoteClient, UUID dataForAgentID, UUID sessionID) { // this a private message for own agent only if (dataForAgentID != GetRequestingAgentID(remoteClient)) return; SendAgentGroupDataUpdate(remoteClient, false); // also current viewers do ignore it and ask later on a much nicer thread // its a info request not a change, so nothing is sent to others // they do get the group title with the avatar object update on arrivel to a region } private void HandleUUIDGroupNameRequest(UUID GroupID, IClientAPI remoteClient) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); string GroupName; GroupRecord group = m_groupData.GetGroupRecord(GetRequestingAgentIDStr(remoteClient), GroupID, null); if (group != null) { GroupName = group.GroupName; } else { GroupName = "Unknown"; } remoteClient.SendGroupNameReply(GroupID, GroupName); } private void OnInstantMessage(IClientAPI remoteClient, GridInstantMessage im) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); //m_log.DebugFormat("[Groups]: IM From {0} to {1} msg {2} type {3}", im.fromAgentID, im.toAgentID, im.message, (InstantMessageDialog)im.dialog); // Group invitations if ((im.dialog == (byte)InstantMessageDialog.GroupInvitationAccept) || (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline)) { UUID inviteID = new UUID(im.imSessionID); GroupInviteInfo inviteInfo = m_groupData.GetAgentToGroupInvite(GetRequestingAgentIDStr(remoteClient), inviteID); if (inviteInfo == null) { if (m_debugEnabled) m_log.WarnFormat("[Groups]: Received an Invite IM for an invite that does not exist {0}.", inviteID); return; } //m_log.DebugFormat("[XXX]: Invite is for Agent {0} to Group {1}.", inviteInfo.AgentID, inviteInfo.GroupID); UUID fromAgentID = new UUID(im.fromAgentID); UUID invitee = UUID.Zero; string tmp = string.Empty; Util.ParseUniversalUserIdentifier(inviteInfo.AgentID, out invitee, out tmp, out tmp, out tmp, out tmp); if ((inviteInfo != null) && (fromAgentID == invitee)) { // Accept if (im.dialog == (byte)InstantMessageDialog.GroupInvitationAccept) { //m_log.DebugFormat("[XXX]: Received an accept invite notice."); // and the sessionid is the role string reason = string.Empty; if (!m_groupData.AddAgentToGroup(GetRequestingAgentIDStr(remoteClient), invitee.ToString(), inviteInfo.GroupID, inviteInfo.RoleID, string.Empty, out reason)) remoteClient.SendAgentAlertMessage("Unable to add you to the group: " + reason, false); else { GridInstantMessage msg = new GridInstantMessage(); msg.imSessionID = UUID.Zero.Guid; msg.fromAgentID = UUID.Zero.Guid; msg.toAgentID = invitee.Guid; msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); msg.fromAgentName = "Groups"; msg.message = string.Format("You have been added to the group."); msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.MessageBox; msg.fromGroup = false; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = UUID.Zero.Guid; msg.binaryBucket = new byte[0]; OutgoingInstantMessage(msg, invitee); IClientAPI inviteeClient = GetActiveRootClient(invitee); if(inviteeClient !=null) { SendAgentGroupDataUpdate(inviteeClient,true); } } m_groupData.RemoveAgentToGroupInvite(GetRequestingAgentIDStr(remoteClient), inviteID); } // Reject if (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: Received a reject invite notice."); m_groupData.RemoveAgentToGroupInvite(GetRequestingAgentIDStr(remoteClient), inviteID); m_groupData.RemoveAgentFromGroup(GetRequestingAgentIDStr(remoteClient), inviteInfo.AgentID, inviteInfo.GroupID); } } } // Group notices if ((im.dialog == (byte)InstantMessageDialog.GroupNotice)) { if (!m_groupNoticesEnabled) { return; } UUID GroupID = new UUID(im.toAgentID); if (m_groupData.GetGroupRecord(GetRequestingAgentIDStr(remoteClient), GroupID, null) != null) { UUID NoticeID = UUID.Random(); string Subject = im.message.Substring(0, im.message.IndexOf('|')); string Message = im.message.Substring(Subject.Length + 1); InventoryItemBase item = null; bool hasAttachment = false; if (im.binaryBucket.Length >= 1 && im.binaryBucket[0] > 0) { hasAttachment = true; string binBucket = OpenMetaverse.Utils.BytesToString(im.binaryBucket); binBucket = binBucket.Remove(0, 14).Trim(); OSD binBucketOSD = OSDParser.DeserializeLLSDXml(binBucket); if (binBucketOSD is OSDMap) { OSDMap binBucketMap = (OSDMap)binBucketOSD; UUID itemID = binBucketMap["item_id"].AsUUID(); UUID ownerID = binBucketMap["owner_id"].AsUUID(); item = m_sceneList[0].InventoryService.GetItem(ownerID, itemID); } else m_log.DebugFormat("[Groups]: Received OSD with unexpected type: {0}", binBucketOSD.GetType()); } if (m_groupData.AddGroupNotice(GetRequestingAgentIDStr(remoteClient), GroupID, NoticeID, im.fromAgentName, Subject, Message, hasAttachment, (byte)(item == null ? 0 : item.AssetType), item == null ? null : item.Name, item == null ? UUID.Zero : item.ID, item == null ? UUID.Zero.ToString() : item.Owner.ToString())) { if (OnNewGroupNotice != null) { OnNewGroupNotice(GroupID, NoticeID); } // Send notice out to everyone that wants notices foreach (GroupMembersData member in m_groupData.GetGroupMembers(GetRequestingAgentIDStr(remoteClient), GroupID)) { if (member.AcceptNotices) { // Build notice IIM, one of reach, because the sending may be async GridInstantMessage msg = CreateGroupNoticeIM(UUID.Zero, NoticeID, (byte)OpenMetaverse.InstantMessageDialog.GroupNotice); msg.toAgentID = member.AgentID.Guid; OutgoingInstantMessage(msg, member.AgentID); } } } } } if (im.dialog == (byte)InstantMessageDialog.GroupNoticeInventoryAccepted) { if (im.binaryBucket.Length < 16) // Invalid return; //// 16 bytes are the UUID. Maybe. // UUID folderID = new UUID(im.binaryBucket, 0); UUID noticeID = new UUID(im.imSessionID); GroupNoticeInfo notice = m_groupData.GetGroupNotice(remoteClient.AgentId.ToString(), noticeID); if (notice != null) { UUID giver = new UUID(im.toAgentID); string tmp = string.Empty; Util.ParseUniversalUserIdentifier(notice.noticeData.AttachmentOwnerID, out giver, out tmp, out tmp, out tmp, out tmp); m_log.DebugFormat("[Groups]: Giving inventory from {0} to {1}", giver, remoteClient.AgentId); string message; InventoryItemBase itemCopy = ((Scene)(remoteClient.Scene)).GiveInventoryItem(remoteClient.AgentId, giver, notice.noticeData.AttachmentItemID, out message); if (itemCopy == null) { remoteClient.SendAgentAlertMessage(message, false); return; } remoteClient.SendInventoryItemCreateUpdate(itemCopy, 0); } } // Interop, received special 210 code for ejecting a group member // this only works within the comms servers domain, and won't work hypergrid // TODO:FIXME: Use a presense server of some kind to find out where the // client actually is, and try contacting that region directly to notify them, // or provide the notification via xmlrpc update queue if ((im.dialog == 210)) { // This is sent from the region that the ejectee was ejected from // if it's being delivered here, then the ejectee is here // so we need to send local updates to the agent. UUID ejecteeID = new UUID(im.toAgentID); im.imSessionID = UUID.Zero.Guid; im.dialog = (byte)InstantMessageDialog.MessageFromAgent; OutgoingInstantMessage(im, ejecteeID); IClientAPI ejectee = GetActiveRootClient(ejecteeID); if (ejectee != null) { UUID groupID = new UUID(im.imSessionID); ejectee.SendAgentDropGroup(groupID); SendAgentGroupDataUpdate(ejectee,true); } } } private void OnGridInstantMessage(GridInstantMessage msg) { if (m_debugEnabled) m_log.InfoFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Trigger the above event handler OnInstantMessage(null, msg); // If a message from a group arrives here, it may need to be forwarded to a local client if (msg.fromGroup == true) { switch (msg.dialog) { case (byte)InstantMessageDialog.GroupInvitation: case (byte)InstantMessageDialog.GroupNotice: UUID toAgentID = new UUID(msg.toAgentID); IClientAPI localClient = GetActiveRootClient(toAgentID); if (localClient != null) { localClient.SendInstantMessage(msg); } break; } } } #endregion #region IGroupsModule Members public event NewGroupNotice OnNewGroupNotice; public GroupRecord GetGroupRecord(UUID GroupID) { return m_groupData.GetGroupRecord(UUID.Zero.ToString(), GroupID, null); } public GroupRecord GetGroupRecord(string name) { return m_groupData.GetGroupRecord(UUID.Zero.ToString(), UUID.Zero, name); } public void ActivateGroup(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupData.SetAgentActiveGroup(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID); // Changing active group changes title, active powers, all kinds of things // anyone who is in any region that can see this client, should probably be // updated with new group info. At a minimum, they should get ScenePresence // updated with new title. SendAgentGroupDataUpdate(remoteClient, true); } /// <summary> /// Get the Role Titles for an Agent, for a specific group /// </summary> public List<GroupTitlesData> GroupTitlesRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupRolesData> agentRoles = m_groupData.GetAgentGroupRoles(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID); GroupMembershipData agentMembership = m_groupData.GetAgentGroupMembership(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID); List<GroupTitlesData> titles = new List<GroupTitlesData>(); foreach (GroupRolesData role in agentRoles) { GroupTitlesData title = new GroupTitlesData(); title.Name = role.Name; if (agentMembership != null) { title.Selected = agentMembership.ActiveRole == role.RoleID; } title.UUID = role.RoleID; titles.Add(title); } return titles; } public List<GroupMembersData> GroupMembersRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat( "[Groups]: GroupMembersRequest called for {0} from client {1}", groupID, remoteClient.Name); List<GroupMembersData> data = m_groupData.GetGroupMembers(GetRequestingAgentIDStr(remoteClient), groupID); if (m_debugEnabled) { foreach (GroupMembersData member in data) { m_log.DebugFormat("[Groups]: Member({0}) - IsOwner({1})", member.AgentID, member.IsOwner); } } return data; } public List<GroupRolesData> GroupRoleDataRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupRolesData> data = m_groupData.GetGroupRoles(GetRequestingAgentIDStr(remoteClient), groupID); return data; } public List<GroupRoleMembersData> GroupRoleMembersRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupRoleMembersData> data = m_groupData.GetGroupRoleMembers(GetRequestingAgentIDStr(remoteClient), groupID); if (m_debugEnabled) { foreach (GroupRoleMembersData member in data) { m_log.DebugFormat("[Groups]: Member({0}) - Role({1})", member.MemberID, member.RoleID); } } return data; } public GroupProfileData GroupProfileRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupProfileData profile = new GroupProfileData(); // just to get the OwnerRole... ExtendedGroupRecord groupInfo = m_groupData.GetGroupRecord(GetRequestingAgentIDStr(remoteClient), groupID, string.Empty); GroupMembershipData memberInfo = m_groupData.GetAgentGroupMembership(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID); if (groupInfo != null) { profile.AllowPublish = groupInfo.AllowPublish; profile.Charter = groupInfo.Charter; profile.FounderID = groupInfo.FounderID; profile.GroupID = groupID; profile.GroupMembershipCount = groupInfo.MemberCount; profile.GroupRolesCount = groupInfo.RoleCount; profile.InsigniaID = groupInfo.GroupPicture; profile.MaturePublish = groupInfo.MaturePublish; profile.MembershipFee = groupInfo.MembershipFee; profile.Money = 0; profile.Name = groupInfo.GroupName; profile.OpenEnrollment = groupInfo.OpenEnrollment; profile.OwnerRole = groupInfo.OwnerRoleID; profile.ShowInList = groupInfo.ShowInList; } if (memberInfo != null) { profile.MemberTitle = memberInfo.GroupTitle; profile.PowersMask = memberInfo.GroupPowers; } return profile; } public GroupMembershipData[] GetMembershipData(UUID agentID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); return m_groupData.GetAgentGroupMemberships(UUID.Zero.ToString(), agentID.ToString()).ToArray(); } public GroupMembershipData GetMembershipData(UUID groupID, UUID agentID) { if (m_debugEnabled) m_log.DebugFormat( "[Groups]: {0} called with groupID={1}, agentID={2}", System.Reflection.MethodBase.GetCurrentMethod().Name, groupID, agentID); return m_groupData.GetAgentGroupMembership(UUID.Zero.ToString(), agentID.ToString(), groupID); } public GroupMembershipData GetActiveMembershipData(UUID agentID) { string agentIDstr = agentID.ToString(); return m_groupData.GetAgentActiveMembership(agentIDstr, agentIDstr); } public void UpdateGroupInfo(IClientAPI remoteClient, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Note: Permissions checking for modification rights is handled by the Groups Server/Service string reason = string.Empty; if (!m_groupData.UpdateGroup(GetRequestingAgentIDStr(remoteClient), groupID, charter, showInList, insigniaID, membershipFee, openEnrollment, allowPublish, maturePublish, out reason)) remoteClient.SendAgentAlertMessage(reason, false); } public void SetGroupAcceptNotices(IClientAPI remoteClient, UUID groupID, bool acceptNotices, bool listInProfile) { // Note: Permissions checking for modification rights is handled by the Groups Server/Service if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupData.UpdateMembership(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID, acceptNotices, listInProfile); } public UUID CreateGroup(IClientAPI remoteClient, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called in {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, remoteClient.Scene.RegionInfo.RegionName); if (m_groupData.GetGroupRecord(GetRequestingAgentIDStr(remoteClient), UUID.Zero, name) != null) { remoteClient.SendCreateGroupReply(UUID.Zero, false, "A group with the same name already exists."); return UUID.Zero; } // check user level ScenePresence avatar = null; Scene scene = (Scene)remoteClient.Scene; scene.TryGetScenePresence(remoteClient.AgentId, out avatar); if (avatar != null) { if (avatar.GodController.UserLevel < m_levelGroupCreate) { remoteClient.SendCreateGroupReply(UUID.Zero, false, String.Format("Insufficient permissions to create a group. Requires level {0}", m_levelGroupCreate)); return UUID.Zero; } } // check funds // is there a money module present ? IMoneyModule money = scene.RequestModuleInterface<IMoneyModule>(); if (money != null) { // do the transaction, that is if the agent has got sufficient funds if (!money.AmountCovered(remoteClient.AgentId, money.GroupCreationCharge)) { remoteClient.SendCreateGroupReply(UUID.Zero, false, "Insufficient funds to create a group."); return UUID.Zero; } } string reason = string.Empty; UUID groupID = m_groupData.CreateGroup(remoteClient.AgentId, name, charter, showInList, insigniaID, membershipFee, openEnrollment, allowPublish, maturePublish, remoteClient.AgentId, out reason); if (groupID != UUID.Zero) { if (money != null && money.GroupCreationCharge > 0) money.ApplyCharge(remoteClient.AgentId, money.GroupCreationCharge, MoneyTransactionType.GroupCreate, name); remoteClient.SendCreateGroupReply(groupID, true, "Group created successfully"); // Update the founder with new group information. SendAgentGroupDataUpdate(remoteClient, false); } else remoteClient.SendCreateGroupReply(groupID, false, reason); return groupID; } public GroupNoticeData[] GroupNoticesListRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // ToDo: check if agent is a member of group and is allowed to see notices? List<ExtendedGroupNoticeData> notices = m_groupData.GetGroupNotices(GetRequestingAgentIDStr(remoteClient), groupID); List<GroupNoticeData> os_notices = new List<GroupNoticeData>(); foreach (ExtendedGroupNoticeData n in notices) { GroupNoticeData osn = n.ToGroupNoticeData(); os_notices.Add(osn); } return os_notices.ToArray(); } /// <summary> /// Get the title of the agent's current role. /// </summary> public string GetGroupTitle(UUID avatarID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupMembershipData membership = m_groupData.GetAgentActiveMembership(UUID.Zero.ToString(), avatarID.ToString()); if (membership != null) { return membership.GroupTitle; } return string.Empty; } /// <summary> /// Change the current Active Group Role for Agent /// </summary> public void GroupTitleUpdate(IClientAPI remoteClient, UUID groupID, UUID titleRoleID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupData.SetAgentActiveGroupRole(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID, titleRoleID); // TODO: Not sure what all is needed here, but if the active group role change is for the group // the client currently has set active, then we need to do a scene presence update too // if (m_groupData.GetAgentActiveMembership(GetRequestingAgentID(remoteClient)).GroupID == GroupID) SendDataUpdate(remoteClient, true); } public void GroupRoleUpdate(IClientAPI remoteClient, UUID groupID, UUID roleID, string name, string description, string title, ulong powers, byte updateType) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Security Checks are handled in the Groups Service. switch ((OpenMetaverse.GroupRoleUpdate)updateType) { case OpenMetaverse.GroupRoleUpdate.Create: string reason = string.Empty; if (!m_groupData.AddGroupRole(GetRequestingAgentIDStr(remoteClient), groupID, UUID.Random(), name, description, title, powers, out reason)) remoteClient.SendAgentAlertMessage("Unable to create role: " + reason, false); break; case OpenMetaverse.GroupRoleUpdate.Delete: m_groupData.RemoveGroupRole(GetRequestingAgentIDStr(remoteClient), groupID, roleID); break; case OpenMetaverse.GroupRoleUpdate.UpdateAll: case OpenMetaverse.GroupRoleUpdate.UpdateData: case OpenMetaverse.GroupRoleUpdate.UpdatePowers: if (m_debugEnabled) { GroupPowers gp = (GroupPowers)powers; m_log.DebugFormat("[Groups]: Role ({0}) updated with Powers ({1}) ({2})", name, powers.ToString(), gp.ToString()); } m_groupData.UpdateGroupRole(GetRequestingAgentIDStr(remoteClient), groupID, roleID, name, description, title, powers); break; case OpenMetaverse.GroupRoleUpdate.NoUpdate: default: // No Op break; } // TODO: This update really should send out updates for everyone in the role that just got changed. SendDataUpdate(remoteClient, true); } public void GroupRoleChanges(IClientAPI remoteClient, UUID groupID, UUID roleID, UUID memberID, uint changes) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Todo: Security check switch (changes) { case 0: // Add m_groupData.AddAgentToGroupRole(GetRequestingAgentIDStr(remoteClient), memberID.ToString(), groupID, roleID); break; case 1: // Remove m_groupData.RemoveAgentFromGroupRole(GetRequestingAgentIDStr(remoteClient), memberID.ToString(), groupID, roleID); break; default: m_log.ErrorFormat("[Groups]: {0} does not understand changes == {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, changes); break; } // TODO: This update really should send out updates for everyone in the role that just got changed. SendDataUpdate(remoteClient, true); } public void GroupNoticeRequest(IClientAPI remoteClient, UUID groupNoticeID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called for notice {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, groupNoticeID); GridInstantMessage msg = CreateGroupNoticeIM(remoteClient.AgentId, groupNoticeID, (byte)InstantMessageDialog.GroupNoticeRequested); OutgoingInstantMessage(msg, GetRequestingAgentID(remoteClient)); } public GridInstantMessage CreateGroupNoticeIM(UUID agentID, UUID groupNoticeID, byte dialog) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GridInstantMessage msg = new GridInstantMessage(); byte[] bucket; msg.imSessionID = groupNoticeID.Guid; msg.toAgentID = agentID.Guid; msg.dialog = dialog; // msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.GroupNotice; msg.fromGroup = true; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = UUID.Zero.Guid; GroupNoticeInfo info = m_groupData.GetGroupNotice(agentID.ToString(), groupNoticeID); if (info != null) { msg.fromAgentID = info.GroupID.Guid; msg.timestamp = info.noticeData.Timestamp; msg.fromAgentName = info.noticeData.FromName; msg.message = info.noticeData.Subject + "|" + info.Message; if (info.noticeData.HasAttachment) { byte[] name = System.Text.Encoding.UTF8.GetBytes(info.noticeData.AttachmentName); bucket = new byte[19 + name.Length]; bucket[0] = 1; // has attachment? bucket[1] = info.noticeData.AttachmentType; // attachment type name.CopyTo(bucket, 18); } else { bucket = new byte[19]; bucket[0] = 0; // Has att? bucket[1] = 0; // type bucket[18] = 0; // null terminated } info.GroupID.ToBytes(bucket, 2); msg.binaryBucket = bucket; } else { m_log.DebugFormat("[Groups]: Group Notice {0} not found, composing empty message.", groupNoticeID); msg.fromAgentID = UUID.Zero.Guid; msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); ; msg.fromAgentName = string.Empty; msg.message = string.Empty; msg.binaryBucket = new byte[0]; } return msg; } public void JoinGroupRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupRecord groupRecord = GetGroupRecord(groupID); IMoneyModule money = remoteClient.Scene.RequestModuleInterface<IMoneyModule>(); // Should check to see if there's an outstanding invitation if (money != null && groupRecord.MembershipFee > 0) { // Does the agent have the funds to cover the group join fee? if (!money.AmountCovered(remoteClient.AgentId, groupRecord.MembershipFee)) { remoteClient.SendAlertMessage("Insufficient funds to join the group."); remoteClient.SendJoinGroupReply(groupID, false); return; } } string reason = string.Empty; if (m_groupData.AddAgentToGroup(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID, UUID.Zero, string.Empty, out reason)) { if (money != null && groupRecord.MembershipFee > 0) money.ApplyCharge(remoteClient.AgentId, groupRecord.MembershipFee, MoneyTransactionType.GroupJoin, groupRecord.GroupName); remoteClient.SendJoinGroupReply(groupID, true); // Should this send updates to everyone in the group? SendAgentGroupDataUpdate(remoteClient, true); if (reason != string.Empty) // A warning remoteClient.SendAlertMessage("Warning: " + reason); } else remoteClient.SendJoinGroupReply(groupID, false); } public void LeaveGroupRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupData.RemoveAgentFromGroup(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID); remoteClient.SendLeaveGroupReply(groupID, true); remoteClient.SendAgentDropGroup(groupID); // SL sends out notifcations to the group messaging session that the person has left // Should this also update everyone who is in the group? SendAgentGroupDataUpdate(remoteClient, true); } public void EjectGroupMemberRequest(IClientAPI remoteClient, UUID groupID, UUID ejecteeID) { EjectGroupMember(remoteClient, GetRequestingAgentID(remoteClient), groupID, ejecteeID); } public void EjectGroupMember(IClientAPI remoteClient, UUID agentID, UUID groupID, UUID ejecteeID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Todo: Security check? m_groupData.RemoveAgentFromGroup(agentID.ToString(), ejecteeID.ToString(), groupID); string agentName; RegionInfo regionInfo; // remoteClient provided or just agentID? if (remoteClient != null) { agentName = remoteClient.Name; regionInfo = remoteClient.Scene.RegionInfo; remoteClient.SendEjectGroupMemberReply(agentID, groupID, true); } else { IClientAPI client = GetActiveClient(agentID); if (client != null) { agentName = client.Name; regionInfo = client.Scene.RegionInfo; client.SendEjectGroupMemberReply(agentID, groupID, true); } else { regionInfo = m_sceneList[0].RegionInfo; UserAccount acc = m_sceneList[0].UserAccountService.GetUserAccount(regionInfo.ScopeID, agentID); if (acc != null) { agentName = acc.FirstName + " " + acc.LastName; } else { agentName = "Unknown member"; } } } GroupRecord groupInfo = m_groupData.GetGroupRecord(agentID.ToString(), groupID, null); UserAccount account = m_sceneList[0].UserAccountService.GetUserAccount(regionInfo.ScopeID, ejecteeID); if ((groupInfo == null) || (account == null)) { return; } IClientAPI ejecteeClient = GetActiveRootClient(ejecteeID); // Send Message to Ejectee GridInstantMessage msg = new GridInstantMessage(); // if local send a normal message if(ejecteeClient != null) { msg.imSessionID = UUID.Zero.Guid; msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.MessageFromAgent; // also execute and send update ejecteeClient.SendAgentDropGroup(groupID); SendAgentGroupDataUpdate(ejecteeClient,true); } else // send { // Interop, received special 210 code for ejecting a group member // this only works within the comms servers domain, and won't work hypergrid // TODO:FIXME: Use a presence server of some kind to find out where the // client actually is, and try contacting that region directly to notify them, // or provide the notification via xmlrpc update queue msg.imSessionID = groupInfo.GroupID.Guid; msg.dialog = (byte)210; //interop } msg.fromAgentID = agentID.Guid; // msg.fromAgentID = info.GroupID; msg.toAgentID = ejecteeID.Guid; //msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); msg.timestamp = 0; msg.fromAgentName = agentName; msg.message = string.Format("You have been ejected from '{1}' by {0}.", agentName, groupInfo.GroupName); msg.fromGroup = false; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = regionInfo.RegionID.Guid; msg.binaryBucket = new byte[0]; OutgoingInstantMessage(msg, ejecteeID); // Message to ejector msg = new GridInstantMessage(); msg.imSessionID = UUID.Zero.Guid; msg.fromAgentID = agentID.Guid; msg.toAgentID = agentID.Guid; msg.timestamp = 0; msg.fromAgentName = agentName; if (account != null) { msg.message = string.Format("{2} has been ejected from '{1}' by {0}.", agentName, groupInfo.GroupName, account.FirstName + " " + account.LastName); } else { msg.message = string.Format("{2} has been ejected from '{1}' by {0}.", agentName, groupInfo.GroupName, "Unknown member"); } msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.MessageFromAgent; msg.fromGroup = false; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = regionInfo.RegionID.Guid; msg.binaryBucket = new byte[0]; OutgoingInstantMessage(msg, agentID); } public void InviteGroupRequest(IClientAPI remoteClient, UUID groupID, UUID invitedAgentID, UUID roleID) { InviteGroup(remoteClient, GetRequestingAgentID(remoteClient), groupID, invitedAgentID, roleID); } public void InviteGroup(IClientAPI remoteClient, UUID agentID, UUID groupID, UUID invitedAgentID, UUID roleID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); string agentName = m_UserManagement.GetUserName(agentID); RegionInfo regionInfo = m_sceneList[0].RegionInfo; GroupRecord group = m_groupData.GetGroupRecord(agentID.ToString(), groupID, null); if (group == null) { m_log.DebugFormat("[Groups]: No such group {0}", groupID); return; } // Todo: Security check, probably also want to send some kind of notification UUID InviteID = UUID.Random(); if (m_groupData.AddAgentToGroupInvite(agentID.ToString(), InviteID, groupID, roleID, invitedAgentID.ToString())) { if (m_msgTransferModule != null) { Guid inviteUUID = InviteID.Guid; GridInstantMessage msg = new GridInstantMessage(); msg.imSessionID = inviteUUID; // msg.fromAgentID = agentID.Guid; msg.fromAgentID = groupID.Guid; msg.toAgentID = invitedAgentID.Guid; //msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); msg.timestamp = 0; msg.fromAgentName = agentName; msg.message = string.Format("{0} has invited you to join a group called {1}. There is no cost to join this group.", agentName, group.GroupName); msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.GroupInvitation; msg.fromGroup = true; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = regionInfo.RegionID.Guid; msg.binaryBucket = new byte[20]; OutgoingInstantMessage(msg, invitedAgentID); } } } public List<DirGroupsReplyData> FindGroups(IClientAPI remoteClient, string query) { return m_groupData.FindGroups(GetRequestingAgentIDStr(remoteClient), query); } #endregion #region Client/Update Tools private IClientAPI GetActiveRootClient(UUID agentID) { foreach (Scene scene in m_sceneList) { ScenePresence sp = scene.GetScenePresence(agentID); if (sp != null && !sp.IsChildAgent && !sp.IsDeleted) { return sp.ControllingClient; } } return null; } /// <summary> /// Try to find an active IClientAPI reference for agentID giving preference to root connections /// </summary> private IClientAPI GetActiveClient(UUID agentID) { IClientAPI child = null; // Try root avatar first foreach (Scene scene in m_sceneList) { ScenePresence sp = scene.GetScenePresence(agentID); if (sp != null&& !sp.IsDeleted) { if (!sp.IsChildAgent) { return sp.ControllingClient; } else { child = sp.ControllingClient; } } } // If we didn't find a root, then just return whichever child we found, or null if none return child; } private void SendScenePresenceUpdate(UUID AgentID, string Title) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: Updating scene title for {0} with title: {1}", AgentID, Title); ScenePresence presence = null; foreach (Scene scene in m_sceneList) { presence = scene.GetScenePresence(AgentID); if (presence != null) { if (presence.Grouptitle != Title) { presence.Grouptitle = Title; if (! presence.IsChildAgent) presence.SendAvatarDataToAllAgents(); } } } } public void SendAgentGroupDataUpdate(IClientAPI remoteClient) { SendAgentGroupDataUpdate(remoteClient, true); } /// <summary> /// Tell remoteClient about its agent groups, and optionally send title to others /// </summary> private void SendAgentGroupDataUpdate(IClientAPI remoteClient, bool tellOthers) { if (m_debugEnabled) m_log.InfoFormat("[Groups]: {0} called for {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, remoteClient.Name); // NPCs currently don't have a CAPs structure or event queues. There is a strong argument for conveying this information // to them anyway since it makes writing server-side bots a lot easier, but for now we don't do anything. if (remoteClient.SceneAgent.PresenceType == PresenceType.Npc) return; // TODO: All the client update functions need to be reexamined because most do too much and send too much stuff UUID agentID = GetRequestingAgentID(remoteClient); SendDataUpdate(remoteClient, tellOthers); GroupMembershipData[] membershipArray = GetProfileListedGroupMemberships(remoteClient, agentID); remoteClient.UpdateGroupMembership(membershipArray); remoteClient.SendAgentGroupDataUpdate(agentID, membershipArray); } /// <summary> /// Get a list of groups memberships for the agent that are marked "ListInProfile" /// (unless that agent has a godLike aspect, in which case get all groups) /// </summary> /// <param name="dataForAgentID"></param> /// <returns></returns> private GroupMembershipData[] GetProfileListedGroupMemberships(IClientAPI requestingClient, UUID dataForAgentID) { List<GroupMembershipData> membershipData = m_groupData.GetAgentGroupMemberships(requestingClient.AgentId.ToString(), dataForAgentID.ToString()); GroupMembershipData[] membershipArray; // cScene and property accessor 'isGod' are in support of the opertions to bypass 'hidden' group attributes for // those with a GodLike aspect. Scene cScene = (Scene)requestingClient.Scene; bool isGod = cScene.Permissions.IsGod(requestingClient.AgentId); if (isGod) { membershipArray = membershipData.ToArray(); } else { if (requestingClient.AgentId != dataForAgentID) { Predicate<GroupMembershipData> showInProfile = delegate(GroupMembershipData membership) { return membership.ListInProfile; }; membershipArray = membershipData.FindAll(showInProfile).ToArray(); } else { membershipArray = membershipData.ToArray(); } } if (m_debugEnabled) { m_log.InfoFormat("[Groups]: Get group membership information for {0} requested by {1}", dataForAgentID, requestingClient.AgentId); foreach (GroupMembershipData membership in membershipArray) { m_log.InfoFormat("[Groups]: {0} :: {1} - {2} - {3}", dataForAgentID, membership.GroupName, membership.GroupTitle, membership.GroupPowers); } } return membershipArray; } //tell remoteClient about its agent group info, and optionally send title to others private void SendDataUpdate(IClientAPI remoteClient, bool tellOthers) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); UUID activeGroupID = UUID.Zero; string activeGroupTitle = string.Empty; string activeGroupName = string.Empty; ulong activeGroupPowers = (ulong)GroupPowers.None; UUID agentID = GetRequestingAgentID(remoteClient); GroupMembershipData membership = m_groupData.GetAgentActiveMembership(agentID.ToString(), agentID.ToString()); if (membership != null) { activeGroupID = membership.GroupID; activeGroupTitle = membership.GroupTitle; activeGroupPowers = membership.GroupPowers; activeGroupName = membership.GroupName; } UserAccount account = m_sceneList[0].UserAccountService.GetUserAccount(remoteClient.Scene.RegionInfo.ScopeID, agentID); string firstname, lastname; if (account != null) { firstname = account.FirstName; lastname = account.LastName; } else { firstname = "Unknown"; lastname = "Unknown"; } remoteClient.SendAgentDataUpdate(agentID, activeGroupID, firstname, lastname, activeGroupPowers, activeGroupName, activeGroupTitle); if (tellOthers) SendScenePresenceUpdate(agentID, activeGroupTitle); ScenePresence sp = (ScenePresence)remoteClient.SceneAgent; if (sp != null) sp.Grouptitle = activeGroupTitle; } #endregion #region IM Backed Processes private void OutgoingInstantMessage(GridInstantMessage msg, UUID msgTo) { if (m_debugEnabled) m_log.InfoFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); IClientAPI localClient = GetActiveRootClient(msgTo); if (localClient != null) { if (m_debugEnabled) m_log.InfoFormat("[Groups]: MsgTo ({0}) is local, delivering directly", localClient.Name); localClient.SendInstantMessage(msg); } else if (m_msgTransferModule != null) { if (m_debugEnabled) m_log.InfoFormat("[Groups]: MsgTo ({0}) is not local, delivering via TransferModule", msgTo); m_msgTransferModule.SendInstantMessage(msg, delegate(bool success) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: Message Sent: {0}", success?"Succeeded":"Failed"); }); } } public void NotifyChange(UUID groupID) { // Notify all group members of a chnge in group roles and/or // permissions // } #endregion private string GetRequestingAgentIDStr(IClientAPI client) { return GetRequestingAgentID(client).ToString(); } private UUID GetRequestingAgentID(IClientAPI client) { UUID requestingAgentID = UUID.Zero; if (client != null) { requestingAgentID = client.AgentId; } return requestingAgentID; } } }
// -- FILE ------------------------------------------------------------------ // name : TimeToolTest.cs // project : Itenso Time Period // created : Jani Giannoudis - 2011.02.18 // language : C# 4.0 // environment: .NET 2.0 // copyright : (c) 2011-2012 by Itenso GmbH, Switzerland // -------------------------------------------------------------------------- using System; using System.Globalization; using Itenso.TimePeriod; using Xunit; namespace Itenso.TimePeriodTests { // ------------------------------------------------------------------------ public sealed class TimeToolTest : TestUnitBase { #region Date and Time // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void GetDateTest() { Assert.Equal( TimeTool.GetDate( testDate ).Year, testDate.Year ); Assert.Equal( TimeTool.GetDate( testDate ).Month, testDate.Month ); Assert.Equal( TimeTool.GetDate( testDate ).Day, testDate.Day ); Assert.Equal(0, TimeTool.GetDate( testDate ).Hour); Assert.Equal(0, TimeTool.GetDate( testDate ).Minute); Assert.Equal(0, TimeTool.GetDate( testDate ).Second); Assert.Equal(0, TimeTool.GetDate( testDate ).Millisecond); } // GetDateTest // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void SetDateTest() { Assert.Equal( TimeTool.SetDate( testDate, testDiffDate ).Year, testDiffDate.Year ); Assert.Equal( TimeTool.SetDate( testDate, testDiffDate ).Month, testDiffDate.Month ); Assert.Equal( TimeTool.SetDate( testDate, testDiffDate ).Day, testDiffDate.Day ); Assert.Equal( TimeTool.SetDate( testDate, testDiffDate ).Hour, testDate.Hour ); Assert.Equal( TimeTool.SetDate( testDate, testDiffDate ).Minute, testDate.Minute ); Assert.Equal( TimeTool.SetDate( testDate, testDiffDate ).Second, testDate.Second ); Assert.Equal( TimeTool.SetDate( testDate, testDiffDate ).Millisecond, testDate.Millisecond ); Assert.Equal( TimeTool.SetDate( testDate, testDiffDate.Year, testDiffDate.Month, testDiffDate.Day ).Year, testDiffDate.Year ); Assert.Equal( TimeTool.SetDate( testDate, testDiffDate.Year, testDiffDate.Month, testDiffDate.Day ).Month, testDiffDate.Month ); Assert.Equal( TimeTool.SetDate( testDate, testDiffDate.Year, testDiffDate.Month, testDiffDate.Day ).Day, testDiffDate.Day ); Assert.Equal( TimeTool.SetDate( testDate, testDiffDate.Year, testDiffDate.Month, testDiffDate.Day ).Hour, testDate.Hour ); Assert.Equal( TimeTool.SetDate( testDate, testDiffDate.Year, testDiffDate.Month, testDiffDate.Day ).Minute, testDate.Minute ); Assert.Equal( TimeTool.SetDate( testDate, testDiffDate.Year, testDiffDate.Month, testDiffDate.Day ).Second, testDate.Second ); Assert.Equal( TimeTool.SetDate( testDate, testDiffDate.Year, testDiffDate.Month, testDiffDate.Day ).Millisecond, testDate.Millisecond ); } // SetDateTest // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void HasTimeOfDayTest() { DateTime now = ClockProxy.Clock.Now; Assert.False( TimeTool.HasTimeOfDay( new DateTime( now.Year, now.Month, now.Day, 0, 0, 0, 0 ) ) ); Assert.True( TimeTool.HasTimeOfDay( new DateTime( now.Year, now.Month, now.Day, 1, 0, 0, 0 ) ) ); Assert.True( TimeTool.HasTimeOfDay( new DateTime( now.Year, now.Month, now.Day, 0, 1, 0, 0 ) ) ); Assert.True( TimeTool.HasTimeOfDay( new DateTime( now.Year, now.Month, now.Day, 0, 0, 1, 0 ) ) ); Assert.True( TimeTool.HasTimeOfDay( new DateTime( now.Year, now.Month, now.Day, 0, 0, 0, 1 ) ) ); } // HasTimeOfDayTest // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void SetTimeOfDayTest() { Assert.Equal( TimeTool.SetTimeOfDay( testDate, testDiffDate ).Year, testDate.Year ); Assert.Equal( TimeTool.SetTimeOfDay( testDate, testDiffDate ).Month, testDate.Month ); Assert.Equal( TimeTool.SetTimeOfDay( testDate, testDiffDate ).Day, testDate.Day ); Assert.Equal( TimeTool.SetTimeOfDay( testDate, testDiffDate ).Hour, testDiffDate.Hour ); Assert.Equal( TimeTool.SetTimeOfDay( testDate, testDiffDate ).Minute, testDiffDate.Minute ); Assert.Equal( TimeTool.SetTimeOfDay( testDate, testDiffDate ).Second, testDiffDate.Second ); Assert.Equal( TimeTool.SetTimeOfDay( testDate, testDiffDate ).Millisecond, testDiffDate.Millisecond ); Assert.Equal( TimeTool.SetTimeOfDay( testDate, testDiffDate.Hour, testDiffDate.Minute, testDiffDate.Second, testDiffDate.Millisecond ).Year, testDate.Year ); Assert.Equal( TimeTool.SetTimeOfDay( testDate, testDiffDate.Hour, testDiffDate.Minute, testDiffDate.Second, testDiffDate.Millisecond ).Month, testDate.Month ); Assert.Equal( TimeTool.SetTimeOfDay( testDate, testDiffDate.Hour, testDiffDate.Minute, testDiffDate.Second, testDiffDate.Millisecond ).Day, testDate.Day ); Assert.Equal( TimeTool.SetTimeOfDay( testDate, testDiffDate.Hour, testDiffDate.Minute, testDiffDate.Second, testDiffDate.Millisecond ).Hour, testDiffDate.Hour ); Assert.Equal( TimeTool.SetTimeOfDay( testDate, testDiffDate.Hour, testDiffDate.Minute, testDiffDate.Second, testDiffDate.Millisecond ).Minute, testDiffDate.Minute ); Assert.Equal( TimeTool.SetTimeOfDay( testDate, testDiffDate.Hour, testDiffDate.Minute, testDiffDate.Second, testDiffDate.Millisecond ).Second, testDiffDate.Second ); Assert.Equal( TimeTool.SetTimeOfDay( testDate, testDiffDate.Hour, testDiffDate.Minute, testDiffDate.Second, testDiffDate.Millisecond ).Millisecond, testDiffDate.Millisecond ); } // SetTimeOfDayTest #endregion #region Year // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void GetYearOfTest() { Assert.Equal(2000, TimeTool.GetYearOf( YearMonth.January, new DateTime( 2000, 1, 1 ) )); Assert.Equal(2000, TimeTool.GetYearOf( YearMonth.April, new DateTime( 2000, 4, 1 ) )); Assert.Equal(2000, TimeTool.GetYearOf( YearMonth.April, new DateTime( 2001, 3, 31 ) )); Assert.Equal(1999, TimeTool.GetYearOf( YearMonth.April, new DateTime( 2000, 3, 31 ) )); } // GetYearOfTest #endregion #region Halfyear // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void NextHalfyearTest() { int year; YearHalfyear halfyear; TimeTool.NextHalfyear( YearHalfyear.First, out year, out halfyear ); Assert.Equal(YearHalfyear.Second, halfyear); TimeTool.NextHalfyear( YearHalfyear.Second, out year, out halfyear ); Assert.Equal(YearHalfyear.First, halfyear); } // NextHalfyearTest // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void PreviousHalfyearTest() { int year; YearHalfyear halfyear; TimeTool.PreviousHalfyear( YearHalfyear.First, out year, out halfyear ); Assert.Equal(YearHalfyear.Second, halfyear); TimeTool.PreviousHalfyear( YearHalfyear.Second, out year, out halfyear ); Assert.Equal(YearHalfyear.First, halfyear); } // PreviousHalfyearTest // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void AddHalfyearTest() { int year; YearHalfyear halfyear; TimeTool.AddHalfyear( YearHalfyear.First, 1, out year, out halfyear ); Assert.Equal(YearHalfyear.Second, halfyear); TimeTool.AddHalfyear( YearHalfyear.First, -1, out year, out halfyear ); Assert.Equal(YearHalfyear.Second, halfyear); TimeTool.AddHalfyear( YearHalfyear.Second, 1, out year, out halfyear ); Assert.Equal(YearHalfyear.First, halfyear); TimeTool.AddHalfyear( YearHalfyear.Second, -1, out year, out halfyear ); Assert.Equal(YearHalfyear.First, halfyear); TimeTool.AddHalfyear( YearHalfyear.First, 2, out year, out halfyear ); Assert.Equal(YearHalfyear.First, halfyear); TimeTool.AddHalfyear( YearHalfyear.First, -2, out year, out halfyear ); Assert.Equal(YearHalfyear.First, halfyear); TimeTool.AddHalfyear( YearHalfyear.Second, 2, out year, out halfyear ); Assert.Equal(YearHalfyear.Second, halfyear); TimeTool.AddHalfyear( YearHalfyear.Second, -2, out year, out halfyear ); Assert.Equal(YearHalfyear.Second, halfyear); TimeTool.AddHalfyear( YearHalfyear.First, 5, out year, out halfyear ); Assert.Equal(YearHalfyear.Second, halfyear); TimeTool.AddHalfyear( YearHalfyear.First, -5, out year, out halfyear ); Assert.Equal(YearHalfyear.Second, halfyear); TimeTool.AddHalfyear( YearHalfyear.Second, 5, out year, out halfyear ); Assert.Equal(YearHalfyear.First, halfyear); TimeTool.AddHalfyear( YearHalfyear.Second, -5, out year, out halfyear ); Assert.Equal(YearHalfyear.First, halfyear); TimeTool.AddHalfyear( 2008, YearHalfyear.First, 1, out year, out halfyear ); Assert.Equal(2008, year); Assert.Equal(YearHalfyear.Second, halfyear); TimeTool.AddHalfyear( 2008, YearHalfyear.Second, 1, out year, out halfyear ); Assert.Equal(2009, year); Assert.Equal(YearHalfyear.First, halfyear); TimeTool.AddHalfyear( 2008, YearHalfyear.First, 2, out year, out halfyear ); Assert.Equal(2009, year); Assert.Equal(YearHalfyear.First, halfyear); TimeTool.AddHalfyear( 2008, YearHalfyear.Second, 2, out year, out halfyear ); Assert.Equal(2009, year); Assert.Equal(YearHalfyear.Second, halfyear); TimeTool.AddHalfyear( 2008, YearHalfyear.First, 3, out year, out halfyear ); Assert.Equal(2009, year); Assert.Equal(YearHalfyear.Second, halfyear); TimeTool.AddHalfyear( 2008, YearHalfyear.Second, 3, out year, out halfyear ); Assert.Equal(2010, year); Assert.Equal(YearHalfyear.First, halfyear); } // AddHalfyearTest // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void GetCalendarHalfyearOfMonthTest() { Assert.Equal(YearHalfyear.First, TimeTool.GetHalfyearOfMonth( YearMonth.January )); Assert.Equal(YearHalfyear.First, TimeTool.GetHalfyearOfMonth( YearMonth.February )); Assert.Equal(YearHalfyear.First, TimeTool.GetHalfyearOfMonth( YearMonth.March )); Assert.Equal(YearHalfyear.First, TimeTool.GetHalfyearOfMonth( YearMonth.April )); Assert.Equal(YearHalfyear.First, TimeTool.GetHalfyearOfMonth( YearMonth.May )); Assert.Equal(YearHalfyear.First, TimeTool.GetHalfyearOfMonth( YearMonth.June )); Assert.Equal(YearHalfyear.Second, TimeTool.GetHalfyearOfMonth( YearMonth.July )); Assert.Equal(YearHalfyear.Second, TimeTool.GetHalfyearOfMonth( YearMonth.August )); Assert.Equal(YearHalfyear.Second, TimeTool.GetHalfyearOfMonth( YearMonth.September )); Assert.Equal(YearHalfyear.Second, TimeTool.GetHalfyearOfMonth( YearMonth.October )); Assert.Equal(YearHalfyear.Second, TimeTool.GetHalfyearOfMonth( YearMonth.November )); Assert.Equal(YearHalfyear.Second, TimeTool.GetHalfyearOfMonth( YearMonth.December )); } // GetCalendarHalfyearOfMonthTest // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void GetHalfyearOfMonthTest() { Assert.Equal(YearHalfyear.First, TimeTool.GetHalfyearOfMonth( YearMonth.October, YearMonth.October )); Assert.Equal(YearHalfyear.First, TimeTool.GetHalfyearOfMonth( YearMonth.October, YearMonth.November )); Assert.Equal(YearHalfyear.First, TimeTool.GetHalfyearOfMonth( YearMonth.October, YearMonth.December )); Assert.Equal(YearHalfyear.First, TimeTool.GetHalfyearOfMonth( YearMonth.October, YearMonth.January )); Assert.Equal(YearHalfyear.First, TimeTool.GetHalfyearOfMonth( YearMonth.October, YearMonth.February )); Assert.Equal(YearHalfyear.First, TimeTool.GetHalfyearOfMonth( YearMonth.October, YearMonth.March )); Assert.Equal(YearHalfyear.Second, TimeTool.GetHalfyearOfMonth( YearMonth.October, YearMonth.April )); Assert.Equal(YearHalfyear.Second, TimeTool.GetHalfyearOfMonth( YearMonth.October, YearMonth.May )); Assert.Equal(YearHalfyear.Second, TimeTool.GetHalfyearOfMonth( YearMonth.October, YearMonth.June )); Assert.Equal(YearHalfyear.Second, TimeTool.GetHalfyearOfMonth( YearMonth.October, YearMonth.July )); Assert.Equal(YearHalfyear.Second, TimeTool.GetHalfyearOfMonth( YearMonth.October, YearMonth.August )); Assert.Equal(YearHalfyear.Second, TimeTool.GetHalfyearOfMonth( YearMonth.October, YearMonth.September )); } // GetHalfyearOfMonthTest // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void GetMonthsOfHalfyearTest() { Assert.Equal( TimeTool.GetMonthsOfHalfyear( YearHalfyear.First ), TimeSpec.FirstHalfyearMonths ); Assert.Equal( TimeTool.GetMonthsOfHalfyear( YearHalfyear.Second ), TimeSpec.SecondHalfyearMonths ); } // GetMonthsOfQuarterTest #endregion #region Quarter // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void NextQarterTest() { int year; YearQuarter quarter; TimeTool.NextQuarter( YearQuarter.First, out year, out quarter ); Assert.Equal(YearQuarter.Second, quarter); TimeTool.NextQuarter( YearQuarter.Second, out year, out quarter ); Assert.Equal(YearQuarter.Third, quarter); TimeTool.NextQuarter( YearQuarter.Third, out year, out quarter ); Assert.Equal(YearQuarter.Fourth, quarter); TimeTool.NextQuarter( YearQuarter.Fourth, out year, out quarter ); Assert.Equal(YearQuarter.First, quarter); } // NextQarterTest // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void PreviousQuarterTest() { int year; YearQuarter quarter; TimeTool.PreviousQuarter( YearQuarter.First, out year, out quarter ); Assert.Equal(YearQuarter.Fourth, quarter); TimeTool.PreviousQuarter( YearQuarter.Second, out year, out quarter ); Assert.Equal(YearQuarter.First, quarter); TimeTool.PreviousQuarter( YearQuarter.Third, out year, out quarter ); Assert.Equal(YearQuarter.Second, quarter); TimeTool.PreviousQuarter( YearQuarter.Fourth, out year, out quarter ); Assert.Equal(YearQuarter.Third, quarter); } // PreviousQuarterTest // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void AddQuarterTest() { int year; YearQuarter quarter; TimeTool.AddQuarter( YearQuarter.First, 1, out year, out quarter ); Assert.Equal(YearQuarter.Second, quarter); TimeTool.AddQuarter( YearQuarter.Second, 1, out year, out quarter ); Assert.Equal(YearQuarter.Third, quarter); TimeTool.AddQuarter( YearQuarter.Third, 1, out year, out quarter ); Assert.Equal(YearQuarter.Fourth, quarter); TimeTool.AddQuarter( YearQuarter.Fourth, 1, out year, out quarter ); Assert.Equal(YearQuarter.First, quarter); TimeTool.AddQuarter( YearQuarter.First, -1, out year, out quarter ); Assert.Equal(YearQuarter.Fourth, quarter); TimeTool.AddQuarter( YearQuarter.Second, -1, out year, out quarter ); Assert.Equal(YearQuarter.First, quarter); TimeTool.AddQuarter( YearQuarter.Third, -1, out year, out quarter ); Assert.Equal(YearQuarter.Second, quarter); TimeTool.AddQuarter( YearQuarter.Fourth, -1, out year, out quarter ); Assert.Equal(YearQuarter.Third, quarter); TimeTool.AddQuarter( YearQuarter.First, 2, out year, out quarter ); Assert.Equal(YearQuarter.Third, quarter); TimeTool.AddQuarter( YearQuarter.Second, 2, out year, out quarter ); Assert.Equal(YearQuarter.Fourth, quarter); TimeTool.AddQuarter( YearQuarter.Third, 2, out year, out quarter ); Assert.Equal(YearQuarter.First, quarter); TimeTool.AddQuarter( YearQuarter.Fourth, 2, out year, out quarter ); Assert.Equal(YearQuarter.Second, quarter); TimeTool.AddQuarter( YearQuarter.First, -2, out year, out quarter ); Assert.Equal(YearQuarter.Third, quarter); TimeTool.AddQuarter( YearQuarter.Second, -2, out year, out quarter ); Assert.Equal(YearQuarter.Fourth, quarter); TimeTool.AddQuarter( YearQuarter.Third, -2, out year, out quarter ); Assert.Equal(YearQuarter.First, quarter); TimeTool.AddQuarter( YearQuarter.Fourth, -2, out year, out quarter ); Assert.Equal(YearQuarter.Second, quarter); TimeTool.AddQuarter( YearQuarter.First, 3, out year, out quarter ); Assert.Equal(YearQuarter.Fourth, quarter); TimeTool.AddQuarter( YearQuarter.Second, 3, out year, out quarter ); Assert.Equal(YearQuarter.First, quarter); TimeTool.AddQuarter( YearQuarter.Third, 3, out year, out quarter ); Assert.Equal(YearQuarter.Second, quarter); TimeTool.AddQuarter( YearQuarter.Fourth, 3, out year, out quarter ); Assert.Equal(YearQuarter.Third, quarter); TimeTool.AddQuarter( YearQuarter.First, -3, out year, out quarter ); Assert.Equal(YearQuarter.Second, quarter); TimeTool.AddQuarter( YearQuarter.Second, -3, out year, out quarter ); Assert.Equal(YearQuarter.Third, quarter); TimeTool.AddQuarter( YearQuarter.Third, -3, out year, out quarter ); Assert.Equal(YearQuarter.Fourth, quarter); TimeTool.AddQuarter( YearQuarter.Fourth, -3, out year, out quarter ); Assert.Equal(YearQuarter.First, quarter); TimeTool.AddQuarter( YearQuarter.First, 4, out year, out quarter ); Assert.Equal(YearQuarter.First, quarter); TimeTool.AddQuarter( YearQuarter.Second, 4, out year, out quarter ); Assert.Equal(YearQuarter.Second, quarter); TimeTool.AddQuarter( YearQuarter.Third, 4, out year, out quarter ); Assert.Equal(YearQuarter.Third, quarter); TimeTool.AddQuarter( YearQuarter.Fourth, 4, out year, out quarter ); Assert.Equal(YearQuarter.Fourth, quarter); TimeTool.AddQuarter( YearQuarter.First, -4, out year, out quarter ); Assert.Equal(YearQuarter.First, quarter); TimeTool.AddQuarter( YearQuarter.Second, -4, out year, out quarter ); Assert.Equal(YearQuarter.Second, quarter); TimeTool.AddQuarter( YearQuarter.Third, -4, out year, out quarter ); Assert.Equal(YearQuarter.Third, quarter); TimeTool.AddQuarter( YearQuarter.Fourth, -4, out year, out quarter ); Assert.Equal(YearQuarter.Fourth, quarter); TimeTool.AddQuarter( 2008, YearQuarter.First, 1, out year, out quarter ); Assert.Equal(2008, year); Assert.Equal(YearQuarter.Second, quarter); TimeTool.AddQuarter( 2008, YearQuarter.Second, 1, out year, out quarter ); Assert.Equal(2008, year); Assert.Equal(YearQuarter.Third, quarter); TimeTool.AddQuarter( 2008, YearQuarter.Third, 1, out year, out quarter ); Assert.Equal(2008, year); Assert.Equal(YearQuarter.Fourth, quarter); TimeTool.AddQuarter( 2008, YearQuarter.Fourth, 1, out year, out quarter ); Assert.Equal(2009, year); Assert.Equal(YearQuarter.First, quarter); TimeTool.AddQuarter( 2008, YearQuarter.First, 2, out year, out quarter ); Assert.Equal(2008, year); Assert.Equal(YearQuarter.Third, quarter); TimeTool.AddQuarter( 2008, YearQuarter.Second, 2, out year, out quarter ); Assert.Equal(2008, year); Assert.Equal(YearQuarter.Fourth, quarter); TimeTool.AddQuarter( 2008, YearQuarter.Third, 2, out year, out quarter ); Assert.Equal(2009, year); Assert.Equal(YearQuarter.First, quarter); TimeTool.AddQuarter( 2008, YearQuarter.Fourth, 2, out year, out quarter ); Assert.Equal(2009, year); Assert.Equal(YearQuarter.Second, quarter); TimeTool.AddQuarter( 2008, YearQuarter.First, 5, out year, out quarter ); Assert.Equal(2009, year); Assert.Equal(YearQuarter.Second, quarter); TimeTool.AddQuarter( 2008, YearQuarter.Second, 5, out year, out quarter ); Assert.Equal(2009, year); Assert.Equal(YearQuarter.Third, quarter); TimeTool.AddQuarter( 2008, YearQuarter.Third, 5, out year, out quarter ); Assert.Equal(2009, year); Assert.Equal(YearQuarter.Fourth, quarter); TimeTool.AddQuarter( 2008, YearQuarter.Fourth, 5, out year, out quarter ); Assert.Equal(2010, year); Assert.Equal(YearQuarter.First, quarter); } // AddQuarterTest // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void GetCalendarQuarterOfMonthTest() { Assert.Equal(YearQuarter.First, TimeTool.GetQuarterOfMonth( YearMonth.January )); Assert.Equal(YearQuarter.First, TimeTool.GetQuarterOfMonth( YearMonth.February )); Assert.Equal(YearQuarter.First, TimeTool.GetQuarterOfMonth( YearMonth.March )); Assert.Equal(YearQuarter.Second, TimeTool.GetQuarterOfMonth( YearMonth.April )); Assert.Equal(YearQuarter.Second, TimeTool.GetQuarterOfMonth( YearMonth.May )); Assert.Equal(YearQuarter.Second, TimeTool.GetQuarterOfMonth( YearMonth.June )); Assert.Equal(YearQuarter.Third, TimeTool.GetQuarterOfMonth( YearMonth.July )); Assert.Equal(YearQuarter.Third, TimeTool.GetQuarterOfMonth( YearMonth.August )); Assert.Equal(YearQuarter.Third, TimeTool.GetQuarterOfMonth( YearMonth.September )); Assert.Equal(YearQuarter.Fourth, TimeTool.GetQuarterOfMonth( YearMonth.October )); Assert.Equal(YearQuarter.Fourth, TimeTool.GetQuarterOfMonth( YearMonth.November )); Assert.Equal(YearQuarter.Fourth, TimeTool.GetQuarterOfMonth( YearMonth.December )); } // GetCalendarQuarterOfMonthTest // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void GetQuarterOfMonthTest() { Assert.Equal(YearQuarter.First, TimeTool.GetQuarterOfMonth( YearMonth.October, YearMonth.October )); Assert.Equal(YearQuarter.First, TimeTool.GetQuarterOfMonth( YearMonth.October, YearMonth.November )); Assert.Equal(YearQuarter.First, TimeTool.GetQuarterOfMonth( YearMonth.October, YearMonth.December )); Assert.Equal(YearQuarter.Second, TimeTool.GetQuarterOfMonth( YearMonth.October, YearMonth.January )); Assert.Equal(YearQuarter.Second, TimeTool.GetQuarterOfMonth( YearMonth.October, YearMonth.February )); Assert.Equal(YearQuarter.Second, TimeTool.GetQuarterOfMonth( YearMonth.October, YearMonth.March )); Assert.Equal(YearQuarter.Third, TimeTool.GetQuarterOfMonth( YearMonth.October, YearMonth.April )); Assert.Equal(YearQuarter.Third, TimeTool.GetQuarterOfMonth( YearMonth.October, YearMonth.May )); Assert.Equal(YearQuarter.Third, TimeTool.GetQuarterOfMonth( YearMonth.October, YearMonth.June )); Assert.Equal(YearQuarter.Fourth, TimeTool.GetQuarterOfMonth( YearMonth.October, YearMonth.July )); Assert.Equal(YearQuarter.Fourth, TimeTool.GetQuarterOfMonth( YearMonth.October, YearMonth.August )); Assert.Equal(YearQuarter.Fourth, TimeTool.GetQuarterOfMonth( YearMonth.October, YearMonth.September )); } // GetQuarterOfMonthTest // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void GetMonthsOfQuarterTest() { Assert.Equal( TimeTool.GetMonthsOfQuarter( YearQuarter.First ), TimeSpec.FirstQuarterMonths ); Assert.Equal( TimeTool.GetMonthsOfQuarter( YearQuarter.Second ), TimeSpec.SecondQuarterMonths ); Assert.Equal( TimeTool.GetMonthsOfQuarter( YearQuarter.Third ), TimeSpec.ThirdQuarterMonths ); Assert.Equal( TimeTool.GetMonthsOfQuarter( YearQuarter.Fourth ), TimeSpec.FourthQuarterMonths ); } // GetMonthsOfQuarterTest #endregion #region Month // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void NextMonthTest() { int year; YearMonth month; TimeTool.NextMonth( YearMonth.January, out year, out month ); Assert.Equal(YearMonth.February, month); TimeTool.NextMonth( YearMonth.February, out year, out month ); Assert.Equal(YearMonth.March, month); TimeTool.NextMonth( YearMonth.March, out year, out month ); Assert.Equal(YearMonth.April, month); TimeTool.NextMonth( YearMonth.April, out year, out month ); Assert.Equal(YearMonth.May, month); TimeTool.NextMonth( YearMonth.May, out year, out month ); Assert.Equal(YearMonth.June, month); TimeTool.NextMonth( YearMonth.June, out year, out month ); Assert.Equal(YearMonth.July, month); TimeTool.NextMonth( YearMonth.July, out year, out month ); Assert.Equal(YearMonth.August, month); TimeTool.NextMonth( YearMonth.August, out year, out month ); Assert.Equal(YearMonth.September, month); TimeTool.NextMonth( YearMonth.September, out year, out month ); Assert.Equal(YearMonth.October, month); TimeTool.NextMonth( YearMonth.October, out year, out month ); Assert.Equal(YearMonth.November, month); TimeTool.NextMonth( YearMonth.November, out year, out month ); Assert.Equal(YearMonth.December, month); TimeTool.NextMonth( YearMonth.December, out year, out month ); Assert.Equal(YearMonth.January, month); } // NextMonthTest // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void PreviousMonthTest() { int year; YearMonth month; TimeTool.PreviousMonth( YearMonth.January, out year, out month ); Assert.Equal(YearMonth.December, month); TimeTool.PreviousMonth( YearMonth.February, out year, out month ); Assert.Equal(YearMonth.January, month); TimeTool.PreviousMonth( YearMonth.March, out year, out month ); Assert.Equal(YearMonth.February, month); TimeTool.PreviousMonth( YearMonth.April, out year, out month ); Assert.Equal(YearMonth.March, month); TimeTool.PreviousMonth( YearMonth.May, out year, out month ); Assert.Equal(YearMonth.April, month); TimeTool.PreviousMonth( YearMonth.June, out year, out month ); Assert.Equal(YearMonth.May, month); TimeTool.PreviousMonth( YearMonth.July, out year, out month ); Assert.Equal(YearMonth.June, month); TimeTool.PreviousMonth( YearMonth.August, out year, out month ); Assert.Equal(YearMonth.July, month); TimeTool.PreviousMonth( YearMonth.September, out year, out month ); Assert.Equal(YearMonth.August, month); TimeTool.PreviousMonth( YearMonth.October, out year, out month ); Assert.Equal(YearMonth.September, month); TimeTool.PreviousMonth( YearMonth.November, out year, out month ); Assert.Equal(YearMonth.October, month); TimeTool.PreviousMonth( YearMonth.December, out year, out month ); Assert.Equal(YearMonth.November, month); } // PreviousMonthTest // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void AddMonthsTest() { int year; YearMonth month; TimeTool.AddMonth( YearMonth.January, 1, out year, out month ); Assert.Equal(YearMonth.February, month); TimeTool.AddMonth( YearMonth.February, 1, out year, out month ); Assert.Equal(YearMonth.March, month); TimeTool.AddMonth( YearMonth.March, 1, out year, out month ); Assert.Equal(YearMonth.April, month); TimeTool.AddMonth( YearMonth.April, 1, out year, out month ); Assert.Equal(YearMonth.May, month); TimeTool.AddMonth( YearMonth.May, 1, out year, out month ); Assert.Equal(YearMonth.June, month); TimeTool.AddMonth( YearMonth.June, 1, out year, out month ); Assert.Equal(YearMonth.July, month); TimeTool.AddMonth( YearMonth.July, 1, out year, out month ); Assert.Equal(YearMonth.August, month); TimeTool.AddMonth( YearMonth.August, 1, out year, out month ); Assert.Equal(YearMonth.September, month); TimeTool.AddMonth( YearMonth.September, 1, out year, out month ); Assert.Equal(YearMonth.October, month); TimeTool.AddMonth( YearMonth.October, 1, out year, out month ); Assert.Equal(YearMonth.November, month); TimeTool.AddMonth( YearMonth.November, 1, out year, out month ); Assert.Equal(YearMonth.December, month); TimeTool.AddMonth( YearMonth.December, 1, out year, out month ); Assert.Equal(YearMonth.January, month); TimeTool.AddMonth( YearMonth.January, -1, out year, out month ); Assert.Equal(YearMonth.December, month); TimeTool.AddMonth( YearMonth.February, -1, out year, out month ); Assert.Equal(YearMonth.January, month); TimeTool.AddMonth( YearMonth.March, -1, out year, out month ); Assert.Equal(YearMonth.February, month); TimeTool.AddMonth( YearMonth.April, -1, out year, out month ); Assert.Equal(YearMonth.March, month); TimeTool.AddMonth( YearMonth.May, -1, out year, out month ); Assert.Equal(YearMonth.April, month); TimeTool.AddMonth( YearMonth.June, -1, out year, out month ); Assert.Equal(YearMonth.May, month); TimeTool.AddMonth( YearMonth.July, -1, out year, out month ); Assert.Equal(YearMonth.June, month); TimeTool.AddMonth( YearMonth.August, -1, out year, out month ); Assert.Equal(YearMonth.July, month); TimeTool.AddMonth( YearMonth.September, -1, out year, out month ); Assert.Equal(YearMonth.August, month); TimeTool.AddMonth( YearMonth.October, -1, out year, out month ); Assert.Equal(YearMonth.September, month); TimeTool.AddMonth( YearMonth.November, -1, out year, out month ); Assert.Equal(YearMonth.October, month); TimeTool.AddMonth( YearMonth.December, -1, out year, out month ); Assert.Equal(YearMonth.November, month); for ( int i = -36; i <= 36; i += 36 ) { TimeTool.AddMonth( YearMonth.January, i, out year, out month ); Assert.Equal(YearMonth.January, month); TimeTool.AddMonth( YearMonth.February, i, out year, out month ); Assert.Equal(YearMonth.February, month); TimeTool.AddMonth( YearMonth.March, i, out year, out month ); Assert.Equal(YearMonth.March, month); TimeTool.AddMonth( YearMonth.April, i, out year, out month ); Assert.Equal(YearMonth.April, month); TimeTool.AddMonth( YearMonth.May, i, out year, out month ); Assert.Equal(YearMonth.May, month); TimeTool.AddMonth( YearMonth.June, i, out year, out month ); Assert.Equal(YearMonth.June, month); TimeTool.AddMonth( YearMonth.July, i, out year, out month ); Assert.Equal(YearMonth.July, month); TimeTool.AddMonth( YearMonth.August, i, out year, out month ); Assert.Equal(YearMonth.August, month); TimeTool.AddMonth( YearMonth.September, i, out year, out month ); Assert.Equal(YearMonth.September, month); TimeTool.AddMonth( YearMonth.October, i, out year, out month ); Assert.Equal(YearMonth.October, month); TimeTool.AddMonth( YearMonth.November, i, out year, out month ); Assert.Equal(YearMonth.November, month); TimeTool.AddMonth( YearMonth.December, i, out year, out month ); Assert.Equal(YearMonth.December, month); } for ( int i = 1; i < ( 3 * TimeSpec.MonthsPerYear ); i++ ) { TimeTool.AddMonth( 2008, (YearMonth)i, 1, out year, out month ); Assert.Equal( year, 2008 + ( i / 12 ) ); Assert.Equal( month, (YearMonth)( ( i % TimeSpec.MonthsPerYear ) + 1 ) ); } } // AddMonthsTest #endregion #region Week // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void WeeekOfYearCalendarTest() { DateTime moment = new DateTime( 2007, 12, 31 ); CultureTestData cultures = new CultureTestData(); foreach ( CultureInfo culture in cultures ) { int calendarWeekOfYear = culture.Calendar.GetWeekOfYear( moment, culture.DateTimeFormat.CalendarWeekRule, culture.DateTimeFormat.FirstDayOfWeek ); int year; int weekOfYear; TimeTool.GetWeekOfYear( moment, culture, YearWeekType.Calendar, out year, out weekOfYear ); Assert.Equal( weekOfYear, calendarWeekOfYear ); } } // WeeekOfYearCalendarTest // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void WeeekOfYearIsoTest() { DateTime moment = new DateTime( 2007, 12, 31 ); CultureTestData cultures = new CultureTestData(); foreach ( CultureInfo culture in cultures ) { if ( culture.DateTimeFormat.CalendarWeekRule != CalendarWeekRule.FirstFourDayWeek || culture.DateTimeFormat.FirstDayOfWeek != DayOfWeek.Monday ) { continue; } int year; int weekOfYear; TimeTool.GetWeekOfYear( moment, culture, YearWeekType.Iso8601, out year, out weekOfYear ); Assert.Equal(1, weekOfYear); } } // WeeekOfYearIsoTest #endregion #region Day // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void DayStartTest() { Assert.Equal( TimeTool.DayStart( testDate ).Year, testDate.Year ); Assert.Equal( TimeTool.DayStart( testDate ).Month, testDate.Month ); Assert.Equal( TimeTool.DayStart( testDate ).Day, testDate.Day ); Assert.Equal(0, TimeTool.DayStart( testDate ).Hour); Assert.Equal(0, TimeTool.DayStart( testDate ).Minute); Assert.Equal(0, TimeTool.DayStart( testDate ).Second); Assert.Equal(0, TimeTool.DayStart( testDate ).Millisecond); } // DayStartTest // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void NextDayTest() { Assert.Equal(DayOfWeek.Tuesday, TimeTool.NextDay( DayOfWeek.Monday )); Assert.Equal(DayOfWeek.Wednesday, TimeTool.NextDay( DayOfWeek.Tuesday )); Assert.Equal(DayOfWeek.Thursday, TimeTool.NextDay( DayOfWeek.Wednesday )); Assert.Equal(DayOfWeek.Friday, TimeTool.NextDay( DayOfWeek.Thursday )); Assert.Equal(DayOfWeek.Saturday, TimeTool.NextDay( DayOfWeek.Friday )); Assert.Equal(DayOfWeek.Sunday, TimeTool.NextDay( DayOfWeek.Saturday )); Assert.Equal(DayOfWeek.Monday, TimeTool.NextDay( DayOfWeek.Sunday )); } // NextDayTest // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void PreviousDayTest() { Assert.Equal(DayOfWeek.Sunday, TimeTool.PreviousDay( DayOfWeek.Monday )); Assert.Equal(DayOfWeek.Monday, TimeTool.PreviousDay( DayOfWeek.Tuesday )); Assert.Equal(DayOfWeek.Tuesday, TimeTool.PreviousDay( DayOfWeek.Wednesday )); Assert.Equal(DayOfWeek.Wednesday, TimeTool.PreviousDay( DayOfWeek.Thursday )); Assert.Equal(DayOfWeek.Thursday, TimeTool.PreviousDay( DayOfWeek.Friday )); Assert.Equal(DayOfWeek.Friday, TimeTool.PreviousDay( DayOfWeek.Saturday )); Assert.Equal(DayOfWeek.Saturday, TimeTool.PreviousDay( DayOfWeek.Sunday )); } // PreviousDayTest // ---------------------------------------------------------------------- [Trait("Category", "TimeTool")] [Fact] public void AddDaysTest() { Assert.Equal(DayOfWeek.Monday, TimeTool.AddDays( DayOfWeek.Sunday, 1 )); Assert.Equal(DayOfWeek.Tuesday, TimeTool.AddDays( DayOfWeek.Monday, 1 )); Assert.Equal(DayOfWeek.Wednesday, TimeTool.AddDays( DayOfWeek.Tuesday, 1 )); Assert.Equal(DayOfWeek.Thursday, TimeTool.AddDays( DayOfWeek.Wednesday, 1 )); Assert.Equal(DayOfWeek.Friday, TimeTool.AddDays( DayOfWeek.Thursday, 1 )); Assert.Equal(DayOfWeek.Saturday, TimeTool.AddDays( DayOfWeek.Friday, 1 )); Assert.Equal(DayOfWeek.Sunday, TimeTool.AddDays( DayOfWeek.Saturday, 1 )); Assert.Equal(DayOfWeek.Sunday, TimeTool.AddDays( DayOfWeek.Monday, -1 )); Assert.Equal(DayOfWeek.Monday, TimeTool.AddDays( DayOfWeek.Tuesday, -1 )); Assert.Equal(DayOfWeek.Tuesday, TimeTool.AddDays( DayOfWeek.Wednesday, -1 )); Assert.Equal(DayOfWeek.Wednesday, TimeTool.AddDays( DayOfWeek.Thursday, -1 )); Assert.Equal(DayOfWeek.Thursday, TimeTool.AddDays( DayOfWeek.Friday, -1 )); Assert.Equal(DayOfWeek.Friday, TimeTool.AddDays( DayOfWeek.Saturday, -1 )); Assert.Equal(DayOfWeek.Saturday, TimeTool.AddDays( DayOfWeek.Sunday, -1 )); Assert.Equal(DayOfWeek.Sunday, TimeTool.AddDays( DayOfWeek.Sunday, 14 )); Assert.Equal(DayOfWeek.Monday, TimeTool.AddDays( DayOfWeek.Monday, 14 )); Assert.Equal(DayOfWeek.Tuesday, TimeTool.AddDays( DayOfWeek.Tuesday, 14 )); Assert.Equal(DayOfWeek.Wednesday, TimeTool.AddDays( DayOfWeek.Wednesday, 14 )); Assert.Equal(DayOfWeek.Thursday, TimeTool.AddDays( DayOfWeek.Thursday, 14 )); Assert.Equal(DayOfWeek.Friday, TimeTool.AddDays( DayOfWeek.Friday, 14 )); Assert.Equal(DayOfWeek.Saturday, TimeTool.AddDays( DayOfWeek.Saturday, 14 )); Assert.Equal(DayOfWeek.Sunday, TimeTool.AddDays( DayOfWeek.Sunday, -14 )); Assert.Equal(DayOfWeek.Monday, TimeTool.AddDays( DayOfWeek.Monday, -14 )); Assert.Equal(DayOfWeek.Tuesday, TimeTool.AddDays( DayOfWeek.Tuesday, -14 )); Assert.Equal(DayOfWeek.Wednesday, TimeTool.AddDays( DayOfWeek.Wednesday, -14 )); Assert.Equal(DayOfWeek.Thursday, TimeTool.AddDays( DayOfWeek.Thursday, -14 )); Assert.Equal(DayOfWeek.Friday, TimeTool.AddDays( DayOfWeek.Friday, -14 )); Assert.Equal(DayOfWeek.Saturday, TimeTool.AddDays( DayOfWeek.Saturday, -14 )); } // AddDaysTest #endregion // ---------------------------------------------------------------------- // members private DateTime testDate = new DateTime( 2000, 10, 2, 13, 45, 53, 673 ); private DateTime testDiffDate = new DateTime( 2002, 9, 3, 7, 14, 22, 234 ); } // class TimeToolTest } // namespace Itenso.TimePeriodTests // -- EOF -------------------------------------------------------------------
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Extensions { // Credit: Unknown public static class Holidays { public static DateTime Easter(int year) { //This algorithm is a C# conversion of the one described at //http://www.assa.org.au/edm.html#Computer int firstDigit; int remain19; int temp; int tableA; int tableB; int tableC; int tableD; int tableE; int d; //day of easter int m; //month of easter firstDigit = year / 100; remain19 = year % 19; temp = (firstDigit - 15) / 2 + 202 - 11 * remain19; int[] substract1 = { 21, 24, 25, 27, 28, 29, 30, 31, 32, 34, 35, 38 }; var subtract1List = new List<int>(substract1); if (subtract1List.Contains(firstDigit)) { temp = temp - 1; } int[] substract2 = { 33, 36, 37, 39, 40 }; var subtract2List = new List<int>(substract2); if (subtract2List.Contains(firstDigit)) { temp = temp - 2; } temp = temp % 30; tableA = temp + 21; if (temp == 29) { tableA = tableA - 1; } if (temp == 28 && remain19 > 10) { tableA = tableA - 1; } //find the next Sunday tableB = (tableA - 19) % 7; tableC = (40 - firstDigit) % 4; if (tableC == 3) { tableC++; } if (tableC > 1) { tableC++; } temp = year % 100; tableD = (temp + temp / 4) % 7; tableE = ((20 - tableB - tableC - tableD) % 7) + 1; d = tableA + tableE; if (d > 31) { d = d - 31; m = 4; } else { m = 3; } return new DateTime(year, m, d); } public static DateTime GetFirstNonHolidayWeekday(DateTime date, string weekday) { var newDate = date; newDate = newDate.AddDays(1); while ((newDate.DayOfWeek.ToString() != weekday) || (IsHoliday(newDate))) { newDate = newDate.AddDays(1); } return newDate; } public static DateTime GetShortestSpanToNonHolidayWeekday(DateTime date, string weekday) { DateTime returnValue; var originalDate = date; // Setup Past Date var pastDate = date; pastDate = pastDate.AddDays(-1); while ((pastDate.DayOfWeek.ToString() != weekday) || (IsHoliday(pastDate))) { pastDate = pastDate.AddDays(-1); } // Setup Future Date var futureDate = date; futureDate = futureDate.AddDays(1); while ((futureDate.DayOfWeek.ToString() != weekday) || (IsHoliday(futureDate))) { futureDate = futureDate.AddDays(1); } // Check to see which span is shortest and return that date var pastSpan = originalDate - pastDate; var futureSpan = futureDate - originalDate; if (pastSpan < futureSpan) { returnValue = pastDate; } else { returnValue = futureDate; } return returnValue; } public static DateTime GetShortestSpanToWeekday(DateTime date, string weekday) { DateTime returnValue; var originalDate = date; // Setup Past Date var pastDate = date; pastDate = pastDate.AddDays(-1); while (pastDate.DayOfWeek.ToString() != weekday) { pastDate = pastDate.AddDays(-1); } // Setup Future Date var futureDate = date; futureDate = futureDate.AddDays(1); while (futureDate.DayOfWeek.ToString() != weekday) { futureDate = futureDate.AddDays(1); } // Check to see which span is shortest and return that date var pastSpan = originalDate - pastDate; var futureSpan = futureDate - originalDate; if (pastSpan < futureSpan) { returnValue = pastDate; } else { returnValue = futureDate; } return returnValue; } public static bool IsHoliday(this DateTime currentDate) { int year = currentDate.Year; var holidays = new List<DateTime>(); //New Years holidays.Add(new DateTime(year, 1, 1)); //Martin Luther King Day holidays.Add(MlkDay(year)); holidays.Add(PresidentsDay(year)); //holidays.Add(Easter(year)); holidays.Add(MemorialDay(year)); //Independence Day holidays.Add(new DateTime(year, 7, 4)); holidays.Add(LaborDay(year)); holidays.Add(Thanksgiving(year)); holidays.Add(Thanksgiving2(year)); //X-mas holidays.Add(new DateTime(year, 12, 25)); foreach (var d in (from h in holidays where h.Month == currentDate.Month && h.Day == currentDate.Day select h)) return true; return false; } public static DateTime LaborDay(int year) { var laborDay = DateTime.MinValue; var sept = new List<DateTime>(); for (int count = 1; count < 31; count++) { sept.Add(new DateTime(year, 9, count)); } var monday = DayOfWeek.Monday; //use LINQ query to find all Mondays and return in ascending order to get the first Monday of the month //use First extension to get one Monday, the first one laborDay = (from d in sept where d.DayOfWeek == monday orderby d.Day ascending select d).First(); return laborDay; } public static DateTime MemorialDay(int year) { var memorialDay = DateTime.MinValue; var may = new List<DateTime>(); for (int count = 1; count < 32; count++) { may.Add(new DateTime(year, 5, count)); } var monday = DayOfWeek.Monday; //use LINQ query to find all Mondays and return in descending order to get the last Monday of the month //use First extension to get 1 Monday; the last one because of descending sort memorialDay = (from d in may where d.DayOfWeek == monday orderby d.Day descending select d).First(); return memorialDay; } public static DateTime MlkDay(int year) { var mlkDay = DateTime.MinValue; var jan = new List<DateTime>(); for (int count = 1; count < 32; count++) { jan.Add(new DateTime(year, 1, count)); } var monday = DayOfWeek.Monday; //Martin Luther King Day is the 3rd Monday of the month //use LINQ query to find all Mondays and return in ascending order //Use a combination of Take and Last to get the 3rd Monday mlkDay = (from d in jan where d.DayOfWeek == monday orderby d.Day ascending select d).Take(3).Last(); return mlkDay; } public static DateTime PresidentsDay(int year) { var leapYear = new DateTime(year, 2, 1); var presidentsDay = DateTime.MinValue; var feb = new List<DateTime>(); for (int count = 1; count < 28; count++) { feb.Add(new DateTime(year, 2, count)); } var monday = DayOfWeek.Monday; //use LINQ query to find all Mondays and return in ascending order //Presidents Day is the 3rd Monday of the month //Use a combination of Take and Last to get the 3rd Monday presidentsDay = (from d in feb where d.DayOfWeek == monday orderby d.Day ascending select d).Take(3).Last(); return presidentsDay; } public static DateTime Thanksgiving(int year) { var thanksgiving = DateTime.MinValue; var november = new List<DateTime>(); for (int count = 1; count < 31; count++) { november.Add(new DateTime(year, 11, count)); } var thursdays = DayOfWeek.Thursday; //Use LINQ query to find all the thursdays of the month of November. //Thanksgiving is on the 4th thursday //Use the combination of Take and Last to get the 4th thursday of the month thanksgiving = (from d in november where d.DayOfWeek == thursdays orderby d.Day ascending select d).Take(4).Last(); return thanksgiving; } public static DateTime Thanksgiving2(int year) { var thanksgiving = DateTime.MinValue; var november = new List<DateTime>(); for (int count = 1; count < 31; count++) { november.Add(new DateTime(year, 11, count)); } var thursdays = DayOfWeek.Thursday; //Use LINQ query to find all the thursdays of the month of November. //Thanksgiving is on the 4th thursday //Use the combination of Take and Last to get the 4th thursday of the month thanksgiving = (from d in november where d.DayOfWeek == thursdays orderby d.Day ascending select d).Take(4).Last().AddDays(1); return thanksgiving; } } }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Runtime.CompilerServices; using Encog.App.Analyst.Analyze; using Encog.App.Analyst.Commands; using Encog.App.Analyst.Script; using Encog.App.Analyst.Script.Normalize; using Encog.App.Analyst.Script.Prop; using Encog.App.Analyst.Script.Task; using Encog.App.Analyst.Wizard; using Encog.App.Quant; using Encog.Bot; using Encog.ML; using Encog.ML.Bayesian; using Encog.ML.Train; using Encog.Util; using Encog.Util.File; using Encog.Util.Logging; namespace Encog.App.Analyst { /// <summary> /// The Encog Analyst runs Encog Analyst Script files (EGA) to perform many /// common machine learning tasks. It is very much like Maven or ANT for Encog. /// Encog analyst files are made up of configuration information and tasks. Tasks /// are series of commands that make use of the configuration information to /// process CSV files. /// </summary> public class EncogAnalyst { /// <summary> /// The name of the task that SHOULD everything. /// </summary> public const String TaskFull = "task-full"; /// <summary> /// The update time for a download. /// </summary> public const int UpdateTime = 10; /// <summary> /// The commands. /// </summary> private readonly IDictionary<String, Cmd> _commands; /// <summary> /// The listeners. /// </summary> private readonly IList<IAnalystListener> _listeners; /// <summary> /// The analyst script. /// </summary> private readonly AnalystScript _script; /// <summary> /// The current task. /// </summary> private QuantTask _currentQuantTask; /// <summary> /// Holds a copy of the original property data, used to revert. /// </summary> private IDictionary<String, String> _revertData; /// <summary> /// Construct the Encog analyst. /// </summary> public EncogAnalyst() { _script = new AnalystScript(); _listeners = new List<IAnalystListener>(); _currentQuantTask = null; _commands = new Dictionary<String, Cmd>(); MaxIteration = -1; AddCommand(new CmdCreate(this)); AddCommand(new CmdEvaluate(this)); AddCommand(new CmdEvaluateRaw(this)); AddCommand(new CmdGenerate(this)); AddCommand(new CmdNormalize(this)); AddCommand(new CmdRandomize(this)); AddCommand(new CmdSegregate(this)); AddCommand(new CmdTrain(this)); AddCommand(new CmdBalance(this)); AddCommand(new CmdSet(this)); AddCommand(new CmdReset(this)); AddCommand(new CmdCluster(this)); AddCommand(new CmdCode(this)); AddCommand(new CmdProcess(this)); } /// <summary> /// </summary> public IMLMethod Method { get; set; } /// <value>The lag depth.</value> public int LagDepth { get { return _script.Normalize.NormalizedFields.Where(field => field.TimeSlice < 0) .Aggregate(0, (current, field) => Math.Max(current, Math.Abs(field.TimeSlice))); } } /// <value>The lead depth.</value> public int LeadDepth { get { return _script.Normalize.NormalizedFields.Where(field => field.TimeSlice > 0) .Aggregate(0, (current, field) => Math.Max(current, field.TimeSlice)); } } /// <value>the listeners</value> public IList<IAnalystListener> Listeners { get { return _listeners; } } /// <summary> /// Set the max iterations. /// </summary> public int MaxIteration { get; set; } /// <value>The reverted data.</value> public IDictionary<String, String> RevertData { get { return _revertData; } } /// <value>the script</value> public AnalystScript Script { get { return _script; } } /// <summary> /// Set the current task. /// </summary> public QuantTask CurrentQuantTask { set { _currentQuantTask = value; } } /// <value>True, if any field has a time slice.</value> public bool TimeSeries { get { return _script.Normalize.NormalizedFields.Any(field => field.TimeSlice != 0); } } /// <summary> /// Add a listener. /// </summary> /// <param name="listener">The listener to add.</param> public void AddAnalystListener(IAnalystListener listener) { _listeners.Add(listener); } /// <summary> /// Add a command. /// </summary> /// <param name="cmd">The command to add.</param> public void AddCommand(Cmd cmd) { _commands[cmd.Name] = cmd; } /// <summary> /// Analyze the specified file. Used by the wizard. /// </summary> /// <param name="file">The file to analyze.</param> /// <param name="headers">True if headers are present.</param> /// <param name="format">The format of the file.</param> public void Analyze(FileInfo file, bool headers, AnalystFileFormat format) { _script.Properties.SetFilename(AnalystWizard.FileRaw, file.ToString()); _script.Properties.SetProperty( ScriptProperties.SetupConfigInputHeaders, headers); var a = new PerformAnalysis(_script, file.ToString(), headers, format); a.Process(this); } /// <summary> /// Determine the input count. This is the actual number of columns. /// </summary> /// <returns>The input count.</returns> public int DetermineInputCount() { int result = 0; foreach (AnalystField field in _script.Normalize.NormalizedFields) { if (field.Input && !field.Ignored) { result += field.ColumnsNeeded; } } return result; } /// <summary> /// Determine the input field count, the fields are higher-level /// than columns. /// </summary> /// <returns>The input field count.</returns> public int DetermineInputFieldCount() { int result = 0; foreach (AnalystField field in _script.Normalize.NormalizedFields) { if (field.Input && !field.Ignored) { result++; } } return result; } /// <summary> /// Determine the output count, this is the number of output /// columns needed. /// </summary> /// <returns>The output count.</returns> public int DetermineOutputCount() { int result = 0; foreach (AnalystField field in _script.Normalize.NormalizedFields) { if (field.Output && !field.Ignored) { result += field.ColumnsNeeded; } } return result; } /// <summary> /// Determine the number of output fields. Fields are higher /// level than columns. /// </summary> /// <returns>The output field count.</returns> public int DetermineOutputFieldCount() { int result = 0; foreach (AnalystField field in _script.Normalize.NormalizedFields) { if (field.Output && !field.Ignored) { result++; } } if (Method is BayesianNetwork) { result++; } return result; } /// <summary> /// Determine how many unique columns there are. Timeslices are not /// counted multiple times. /// </summary> /// <returns>The number of columns.</returns> public int DetermineUniqueColumns() { IDictionary<String, Object> used = new Dictionary<String, Object>(); int result = 0; foreach (AnalystField field in _script.Normalize.NormalizedFields) { if (!field.Ignored) { String name = field.Name; if (!used.ContainsKey(name)) { result += field.ColumnsNeeded; used[name] = null; } } } return result; } /// <summary> /// Determine the unique input field count. Timeslices are not /// counted multiple times. /// </summary> /// <returns>The number of unique input fields.</returns> public int DetermineUniqueInputFieldCount() { IDictionary<String, Object> map = new Dictionary<String, Object>(); int result = 0; foreach (AnalystField field in _script.Normalize.NormalizedFields) { if (!map.ContainsKey(field.Name)) { if (field.Input && !field.Ignored) { result++; map[field.Name] = null; } } } return result; } /// <summary> /// Determine the unique output field count. Do not count timeslices /// multiple times. /// </summary> /// <returns>The unique output field count.</returns> public int DetermineUniqueOutputFieldCount() { IDictionary<String, Object> map = new Dictionary<String, Object>(); int result = 0; foreach (AnalystField field in _script.Normalize.NormalizedFields) { if (!map.ContainsKey(field.Name)) { if (field.Output && !field.Ignored) { result++; } map[field.Name] = null; } } return result; } /// <summary> /// Download a raw file from the Internet. /// </summary> public void Download() { Uri sourceURL = _script.Properties.GetPropertyURL( ScriptProperties.HeaderDatasourceSourceFile); String rawFile = _script.Properties.GetPropertyFile( ScriptProperties.HeaderDatasourceRawFile); FileInfo rawFilename = Script.ResolveFilename(rawFile); if (!rawFilename.Exists) { DownloadPage(sourceURL, rawFilename); } } /// <summary> /// Down load a file from the specified URL, uncompress if needed. /// </summary> /// <param name="url">THe URL.</param> /// <param name="file">The file to down load into.</param> private void DownloadPage(Uri url, FileInfo file) { try { // download the URL file.Delete(); FileInfo tempFile = FileUtil.CombinePath( new FileInfo(file.DirectoryName), "temp.tmp"); tempFile.Delete(); FileStream fos = tempFile.OpenWrite(); int lastUpdate = 0; int length = 0; int size = 0; var buffer = new byte[BotUtil.BufferSize]; WebRequest http = WebRequest.Create(url); var response = (HttpWebResponse) http.GetResponse(); Stream istream = response.GetResponseStream(); do { length = istream.Read(buffer, 0, buffer.Length); if (length > 0) { if (length >= 0) { fos.Write(buffer, 0, length); size += length; } if (lastUpdate > UpdateTime) { Report(0, (int) (size/Format.MemoryMeg), "Downloading... " + Format.FormatMemory(size)); lastUpdate = 0; } lastUpdate++; } } while (length > 0); fos.Close(); // unzip if needed if (url.ToString().ToLower().EndsWith(".gz")) { // Get the stream of the source file. using (FileStream inFile = tempFile.OpenRead()) { //Create the decompressed file. using (FileStream outFile = file.Create()) { using (var Decompress = new GZipStream(inFile, CompressionMode.Decompress)) { size = 0; lastUpdate = 0; do { length = Decompress.Read(buffer, 0, buffer.Length); if (length >= 0) { outFile.Write(buffer, 0, length); size += length; } if (lastUpdate > UpdateTime) { Report(0, (int) (size/Format.MemoryMeg), "Uncompressing... " + Format.FormatMemory(size)); lastUpdate = 0; } lastUpdate++; } while (length > 0); } } tempFile.Delete(); } } else { // rename the temp file to the actual file file.Delete(); tempFile.MoveTo(file.ToString()); } } catch (IOException e) { throw new AnalystError(e); } } /// <summary> /// Execute a task. /// </summary> /// <param name="task">The task to execute.</param> public void ExecuteTask(AnalystTask task) { int total = task.Lines.Count; int current = 1; foreach (String line in task.Lines) { EncogLogging.Log(EncogLogging.LevelDebug, "Execute analyst line: " + line); ReportCommandBegin(total, current, line); bool canceled = false; String command; String args; String line2 = line.Trim(); int index = line2.IndexOf(' '); if (index != -1) { command = line2.Substring(0, (index) - (0)).ToUpper(); args = line2.Substring(index + 1); } else { command = line2.ToUpper(); args = ""; } Cmd cmd = _commands[command]; if (cmd != null) { canceled = cmd.ExecuteCommand(args); } else { throw new AnalystError("Unknown Command: " + line); } ReportCommandEnd(canceled); CurrentQuantTask = null; current++; if (ShouldStopAll()) { break; } } } /// <summary> /// Execute a task. /// </summary> /// <param name="name">The name of the task to execute.</param> public void ExecuteTask(String name) { EncogLogging.Log(EncogLogging.LevelInfo, "Analyst execute task:" + name); AnalystTask task = _script.GetTask(name); if (task == null) { throw new AnalystError("Can't find task: " + name); } ExecuteTask(task); } /// <summary> /// Load the specified script file. /// </summary> /// <param name="file">The file to load.</param> public void Load(FileInfo file) { Stream fis = null; _script.BasePath = file.DirectoryName; try { fis = file.OpenRead(); Load(fis); } catch (IOException ex) { throw new AnalystError(ex); } finally { if (fis != null) { try { fis.Close(); } catch (IOException e) { throw new AnalystError(e); } } } } /// <summary> /// Load from an input stream. /// </summary> /// <param name="stream">The stream to load from.</param> public void Load(Stream stream) { _script.Load(stream); _revertData = _script.Properties.PrepareRevert(); } /// <summary> /// Load from the specified filename. /// </summary> /// <param name="filename">The filename to load from.</param> public void Load(String filename) { Load(new FileInfo(filename)); } /// <summary> /// Remove a listener. /// </summary> /// <param name="listener">The listener to remove.</param> public void RemoveAnalystListener(IAnalystListener listener) { _listeners.Remove(listener); } /// <summary> /// Report progress. /// </summary> /// <param name="total">The total units.</param> /// <param name="current">The current unit.</param> /// <param name="message">The message.</param> private void Report(int total, int current, String message) { foreach (IAnalystListener listener in _listeners) { listener.Report(total, current, message); } } /// <summary> /// Report a command has begin. /// </summary> /// <param name="total">The total units.</param> /// <param name="current">The current unit.</param> /// <param name="name">The command name.</param> private void ReportCommandBegin(int total, int current, String name) { foreach (IAnalystListener listener in _listeners) { listener.ReportCommandBegin(total, current, name); } } /// <summary> /// Report a command has ended. /// </summary> /// <param name="canceled">Was the command canceled.</param> private void ReportCommandEnd(bool canceled) { foreach (IAnalystListener listener in _listeners) { listener.ReportCommandEnd(canceled); } } /// <summary> /// Report training. /// </summary> /// <param name="train">The trainer.</param> public void ReportTraining(IMLTrain train) { foreach (IAnalystListener listener in _listeners) { listener.ReportTraining(train); } } /// <summary> /// Report that training has begun. /// </summary> public void ReportTrainingBegin() { foreach (IAnalystListener listener in _listeners) { listener.ReportTrainingBegin(); } } /// <summary> /// Report that training has ended. /// </summary> public void ReportTrainingEnd() { foreach (IAnalystListener listener in _listeners) { listener.ReportTrainingEnd(); } } /// <summary> /// Save the script to a file. /// </summary> /// <param name="file">The file to save to.</param> public void Save(FileInfo file) { Stream fos = null; try { _script.BasePath = file.DirectoryName; fos = file.OpenWrite(); Save(fos); } catch (IOException ex) { throw new AnalystError(ex); } finally { if (fos != null) { try { fos.Close(); } catch (IOException e) { throw new AnalystError(e); } } } } /// <summary> /// Save the script to a stream. /// </summary> /// <param name="stream">The stream to save to.</param> public void Save(Stream stream) { _script.Save(stream); } /// <summary> /// Save the script to a filename. /// </summary> /// <param name="filename">The filename to save to.</param> public void Save(String filename) { Save(new FileInfo(filename)); } /// <summary> /// Should all commands be stopped. /// </summary> /// <returns>True, if all commands should be stopped.</returns> private bool ShouldStopAll() { foreach (IAnalystListener listener in _listeners) { if (listener.ShouldShutDown()) { return true; } } return false; } /// <summary> /// Should the current command be stopped. /// </summary> /// <returns>True if the current command should be stopped.</returns> public bool ShouldStopCommand() { foreach (IAnalystListener listener in _listeners) { if (listener.ShouldStopCommand()) { return true; } } return false; } /// <summary> /// Stop the current task. /// </summary> [MethodImpl(MethodImplOptions.Synchronized)] public void StopCurrentTask() { if (_currentQuantTask != null) { _currentQuantTask.RequestStop(); } } /// <summary> /// Determine the total number of columns. /// </summary> /// <returns>The number of tes</returns> public int DetermineTotalColumns() { int result = 0; foreach (AnalystField field in _script.Normalize.NormalizedFields) { if (!field.Ignored) { result += field.ColumnsNeeded; } } return result; } /// <summary> /// Determine the total input field count, minus ignored fields. /// </summary> /// <returns>The number of unique input fields.</returns> public int DetermineTotalInputFieldCount() { int result = 0; foreach (AnalystField field in _script.Normalize.NormalizedFields) { if (field.Input && !field.Ignored) { result += field.ColumnsNeeded; } } return result; } public int DetermineMaxTimeSlice() { int result = int.MinValue; foreach (AnalystField field in Script.Normalize.NormalizedFields) { result = Math.Max(result, field.TimeSlice); } return result; } public int DetermineMinTimeSlice() { int result = int.MaxValue; foreach (AnalystField field in Script.Normalize.NormalizedFields) { result = Math.Min(result, field.TimeSlice); } return result; } } }
using Lucene.Net.Analysis.Tokenattributes; using System; using System.Diagnostics; using Lucene.Net.Documents; namespace Lucene.Net.Index { using Lucene.Net.Randomized.Generators; using NUnit.Framework; using System.IO; /* * 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 Analyzer = Lucene.Net.Analysis.Analyzer; using BytesRef = Lucene.Net.Util.BytesRef; using Directory = Lucene.Net.Store.Directory; using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; using Document = Documents.Document; using Field = Field; using FieldType = FieldType; using FixedBitSet = Lucene.Net.Util.FixedBitSet; using IOUtils = Lucene.Net.Util.IOUtils; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using TestUtil = Lucene.Net.Util.TestUtil; using TextField = TextField; using TokenStream = Lucene.Net.Analysis.TokenStream; [TestFixture] public class TestLongPostings : LuceneTestCase { // Produces a realistic unicode random string that // survives MockAnalyzer unchanged: private string GetRandomTerm(string other) { Analyzer a = new MockAnalyzer(Random()); while (true) { string s = TestUtil.RandomRealisticUnicodeString(Random()); if (other != null && s.Equals(other)) { continue; } IOException priorException = null; TokenStream ts = a.TokenStream("foo", new StringReader(s)); try { ITermToBytesRefAttribute termAtt = ts.GetAttribute<ITermToBytesRefAttribute>(); BytesRef termBytes = termAtt.BytesRef; ts.Reset(); int count = 0; bool changed = false; while (ts.IncrementToken()) { termAtt.FillBytesRef(); if (count == 0 && !termBytes.Utf8ToString().Equals(s)) { // The value was changed during analysis. Keep iterating so the // tokenStream is exhausted. changed = true; } count++; } ts.End(); // Did we iterate just once and the value was unchanged? if (!changed && count == 1) { return s; } } catch (IOException e) { priorException = e; } finally { IOUtils.CloseWhileHandlingException(priorException, ts); } } } [Test] public virtual void TestLongPostings_Mem() { // Don't use TestUtil.getTempDir so that we own the // randomness (ie same seed will point to same dir): Directory dir = NewFSDirectory(CreateTempDir("longpostings" + "." + Random().NextLong())); int NUM_DOCS = AtLeast(2000); if (VERBOSE) { Console.WriteLine("TEST: NUM_DOCS=" + NUM_DOCS); } string s1 = GetRandomTerm(null); string s2 = GetRandomTerm(s1); if (VERBOSE) { Console.WriteLine("\nTEST: s1=" + s1 + " s2=" + s2); /* for(int idx=0;idx<s1.Length();idx++) { System.out.println(" s1 ch=0x" + Integer.toHexString(s1.charAt(idx))); } for(int idx=0;idx<s2.Length();idx++) { System.out.println(" s2 ch=0x" + Integer.toHexString(s2.charAt(idx))); } */ } FixedBitSet isS1 = new FixedBitSet(NUM_DOCS); for (int idx = 0; idx < NUM_DOCS; idx++) { if (Random().NextBoolean()) { isS1.Set(idx); } } IndexReader r; IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(IndexWriterConfig.OpenMode_e.CREATE).SetMergePolicy(NewLogMergePolicy()); iwc.SetRAMBufferSizeMB(16.0 + 16.0 * Random().NextDouble()); iwc.SetMaxBufferedDocs(-1); RandomIndexWriter riw = new RandomIndexWriter(Random(), dir, iwc); for (int idx = 0; idx < NUM_DOCS; idx++) { Document doc = new Document(); string s = isS1.Get(idx) ? s1 : s2; Field f = NewTextField("field", s, Field.Store.NO); int count = TestUtil.NextInt(Random(), 1, 4); for (int ct = 0; ct < count; ct++) { doc.Add(f); } riw.AddDocument(doc); } r = riw.Reader; riw.Dispose(); /* if (VERBOSE) { System.out.println("TEST: terms"); TermEnum termEnum = r.Terms(); while(termEnum.Next()) { System.out.println(" term=" + termEnum.Term() + " len=" + termEnum.Term().Text().Length()); Assert.IsTrue(termEnum.DocFreq() > 0); System.out.println(" s1?=" + (termEnum.Term().Text().equals(s1)) + " s1len=" + s1.Length()); System.out.println(" s2?=" + (termEnum.Term().Text().equals(s2)) + " s2len=" + s2.Length()); final String s = termEnum.Term().Text(); for(int idx=0;idx<s.Length();idx++) { System.out.println(" ch=0x" + Integer.toHexString(s.charAt(idx))); } } } */ Assert.AreEqual(NUM_DOCS, r.NumDocs); Assert.IsTrue(r.DocFreq(new Term("field", s1)) > 0); Assert.IsTrue(r.DocFreq(new Term("field", s2)) > 0); int num = AtLeast(1000); for (int iter = 0; iter < num; iter++) { string term; bool doS1; if (Random().NextBoolean()) { term = s1; doS1 = true; } else { term = s2; doS1 = false; } if (VERBOSE) { Console.WriteLine("\nTEST: iter=" + iter + " doS1=" + doS1); } DocsAndPositionsEnum postings = MultiFields.GetTermPositionsEnum(r, null, "field", new BytesRef(term)); int docID = -1; while (docID < DocIdSetIterator.NO_MORE_DOCS) { int what = Random().Next(3); if (what == 0) { if (VERBOSE) { Console.WriteLine("TEST: docID=" + docID + "; do next()"); } // nextDoc int expected = docID + 1; while (true) { if (expected == NUM_DOCS) { expected = int.MaxValue; break; } else if (isS1.Get(expected) == doS1) { break; } else { expected++; } } docID = postings.NextDoc(); if (VERBOSE) { Console.WriteLine(" got docID=" + docID); } Assert.AreEqual(expected, docID); if (docID == DocIdSetIterator.NO_MORE_DOCS) { break; } if (Random().Next(6) == 3) { int freq = postings.Freq(); Assert.IsTrue(freq >= 1 && freq <= 4); for (int pos = 0; pos < freq; pos++) { Assert.AreEqual(pos, postings.NextPosition()); if (Random().NextBoolean()) { var dummy = postings.Payload; if (Random().NextBoolean()) { dummy = postings.Payload; // get it again } } } } } else { // advance int targetDocID; if (docID == -1) { targetDocID = Random().Next(NUM_DOCS + 1); } else { targetDocID = docID + TestUtil.NextInt(Random(), 1, NUM_DOCS - docID); } if (VERBOSE) { Console.WriteLine("TEST: docID=" + docID + "; do advance(" + targetDocID + ")"); } int expected = targetDocID; while (true) { if (expected == NUM_DOCS) { expected = int.MaxValue; break; } else if (isS1.Get(expected) == doS1) { break; } else { expected++; } } docID = postings.Advance(targetDocID); if (VERBOSE) { Console.WriteLine(" got docID=" + docID); } Assert.AreEqual(expected, docID); if (docID == DocIdSetIterator.NO_MORE_DOCS) { break; } if (Random().Next(6) == 3) { int freq = postings.Freq(); Assert.IsTrue(freq >= 1 && freq <= 4); for (int pos = 0; pos < freq; pos++) { Assert.AreEqual(pos, postings.NextPosition()); if (Random().NextBoolean()) { var dummy = postings.Payload; if (Random().NextBoolean()) { dummy = postings.Payload; // get it again } } } } } } } r.Dispose(); dir.Dispose(); } // a weaker form of testLongPostings, that doesnt check positions [Test] public virtual void TestLongPostingsNoPositions() { DoTestLongPostingsNoPositions(FieldInfo.IndexOptions.DOCS_ONLY); DoTestLongPostingsNoPositions(FieldInfo.IndexOptions.DOCS_AND_FREQS); } public virtual void DoTestLongPostingsNoPositions(FieldInfo.IndexOptions options) { // Don't use TestUtil.getTempDir so that we own the // randomness (ie same seed will point to same dir): Directory dir = NewFSDirectory(CreateTempDir("longpostings" + "." + Random().NextLong())); int NUM_DOCS = AtLeast(2000); if (VERBOSE) { Console.WriteLine("TEST: NUM_DOCS=" + NUM_DOCS); } string s1 = GetRandomTerm(null); string s2 = GetRandomTerm(s1); if (VERBOSE) { Console.WriteLine("\nTEST: s1=" + s1 + " s2=" + s2); /* for(int idx=0;idx<s1.Length();idx++) { System.out.println(" s1 ch=0x" + Integer.toHexString(s1.charAt(idx))); } for(int idx=0;idx<s2.Length();idx++) { System.out.println(" s2 ch=0x" + Integer.toHexString(s2.charAt(idx))); } */ } FixedBitSet isS1 = new FixedBitSet(NUM_DOCS); for (int idx = 0; idx < NUM_DOCS; idx++) { if (Random().NextBoolean()) { isS1.Set(idx); } } IndexReader r; if (true) { IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(IndexWriterConfig.OpenMode_e.CREATE).SetMergePolicy(NewLogMergePolicy()); iwc.SetRAMBufferSizeMB(16.0 + 16.0 * Random().NextDouble()); iwc.SetMaxBufferedDocs(-1); RandomIndexWriter riw = new RandomIndexWriter(Random(), dir, iwc); FieldType ft = new FieldType(TextField.TYPE_NOT_STORED); ft.IndexOptions = options; for (int idx = 0; idx < NUM_DOCS; idx++) { Document doc = new Document(); string s = isS1.Get(idx) ? s1 : s2; Field f = NewField("field", s, ft); int count = TestUtil.NextInt(Random(), 1, 4); for (int ct = 0; ct < count; ct++) { doc.Add(f); } riw.AddDocument(doc); } r = riw.Reader; riw.Dispose(); } else { r = DirectoryReader.Open(dir); } /* if (VERBOSE) { System.out.println("TEST: terms"); TermEnum termEnum = r.Terms(); while(termEnum.Next()) { System.out.println(" term=" + termEnum.Term() + " len=" + termEnum.Term().Text().Length()); Assert.IsTrue(termEnum.DocFreq() > 0); System.out.println(" s1?=" + (termEnum.Term().Text().equals(s1)) + " s1len=" + s1.Length()); System.out.println(" s2?=" + (termEnum.Term().Text().equals(s2)) + " s2len=" + s2.Length()); final String s = termEnum.Term().Text(); for(int idx=0;idx<s.Length();idx++) { System.out.println(" ch=0x" + Integer.toHexString(s.charAt(idx))); } } } */ Assert.AreEqual(NUM_DOCS, r.NumDocs); Assert.IsTrue(r.DocFreq(new Term("field", s1)) > 0); Assert.IsTrue(r.DocFreq(new Term("field", s2)) > 0); int num = AtLeast(1000); for (int iter = 0; iter < num; iter++) { string term; bool doS1; if (Random().NextBoolean()) { term = s1; doS1 = true; } else { term = s2; doS1 = false; } if (VERBOSE) { Console.WriteLine("\nTEST: iter=" + iter + " doS1=" + doS1 + " term=" + term); } DocsEnum docs; DocsEnum postings; if (options == FieldInfo.IndexOptions.DOCS_ONLY) { docs = TestUtil.Docs(Random(), r, "field", new BytesRef(term), null, null, DocsEnum.FLAG_NONE); postings = null; } else { docs = postings = TestUtil.Docs(Random(), r, "field", new BytesRef(term), null, null, DocsEnum.FLAG_FREQS); Debug.Assert(postings != null); } Debug.Assert(docs != null); int docID = -1; while (docID < DocIdSetIterator.NO_MORE_DOCS) { int what = Random().Next(3); if (what == 0) { if (VERBOSE) { Console.WriteLine("TEST: docID=" + docID + "; do next()"); } // nextDoc int expected = docID + 1; while (true) { if (expected == NUM_DOCS) { expected = int.MaxValue; break; } else if (isS1.Get(expected) == doS1) { break; } else { expected++; } } docID = docs.NextDoc(); if (VERBOSE) { Console.WriteLine(" got docID=" + docID); } Assert.AreEqual(expected, docID); if (docID == DocIdSetIterator.NO_MORE_DOCS) { break; } if (Random().Next(6) == 3 && postings != null) { int freq = postings.Freq(); Assert.IsTrue(freq >= 1 && freq <= 4); } } else { // advance int targetDocID; if (docID == -1) { targetDocID = Random().Next(NUM_DOCS + 1); } else { targetDocID = docID + TestUtil.NextInt(Random(), 1, NUM_DOCS - docID); } if (VERBOSE) { Console.WriteLine("TEST: docID=" + docID + "; do advance(" + targetDocID + ")"); } int expected = targetDocID; while (true) { if (expected == NUM_DOCS) { expected = int.MaxValue; break; } else if (isS1.Get(expected) == doS1) { break; } else { expected++; } } docID = docs.Advance(targetDocID); if (VERBOSE) { Console.WriteLine(" got docID=" + docID); } Assert.AreEqual(expected, docID); if (docID == DocIdSetIterator.NO_MORE_DOCS) { break; } if (Random().Next(6) == 3 && postings != null) { int freq = postings.Freq(); Assert.IsTrue(freq >= 1 && freq <= 4, "got invalid freq=" + freq); } } } } r.Dispose(); dir.Dispose(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ClosedXML.Excel { internal class XLConditionalFormat : IXLConditionalFormat, IXLStylized { public XLConditionalFormat(XLRange range, Boolean copyDefaultModify = false) { Id = Guid.NewGuid(); Range = range; Style = new XLStyle(this, range.Worksheet.Style); Values = new XLDictionary<XLFormula>(); Colors = new XLDictionary<XLColor>(); ContentTypes = new XLDictionary<XLCFContentType>(); IconSetOperators = new XLDictionary<XLCFIconSetOperator>(); CopyDefaultModify = copyDefaultModify; } public XLConditionalFormat(XLConditionalFormat conditionalFormat) { Id = Guid.NewGuid(); Range = conditionalFormat.Range; Style = new XLStyle(this, conditionalFormat.Style); Values = new XLDictionary<XLFormula>(conditionalFormat.Values); Colors = new XLDictionary<XLColor>(conditionalFormat.Colors); ContentTypes = new XLDictionary<XLCFContentType>(conditionalFormat.ContentTypes); IconSetOperators = new XLDictionary<XLCFIconSetOperator>(conditionalFormat.IconSetOperators); ConditionalFormatType = conditionalFormat.ConditionalFormatType; TimePeriod = conditionalFormat.TimePeriod; IconSetStyle = conditionalFormat.IconSetStyle; Operator = conditionalFormat.Operator; Bottom = conditionalFormat.Bottom; Percent = conditionalFormat.Percent; ReverseIconOrder = conditionalFormat.ReverseIconOrder; ShowIconOnly = conditionalFormat.ShowIconOnly; ShowBarOnly = conditionalFormat.ShowBarOnly; } public Guid Id { get; internal set; } public Boolean CopyDefaultModify { get; set; } private IXLStyle _style; private Int32 _styleCacheId; public IXLStyle Style { get { return GetStyle(); } set { SetStyle(value); } } private IXLStyle GetStyle() { //return _style; if (_style != null) return _style; return _style = new XLStyle(this, Range.Worksheet.Workbook.GetStyleById(_styleCacheId), CopyDefaultModify); } private void SetStyle(IXLStyle styleToUse) { //_style = new XLStyle(this, styleToUse); _styleCacheId = Range.Worksheet.Workbook.GetStyleId(styleToUse); _style = null; StyleChanged = false; } public IEnumerable<IXLStyle> Styles { get { UpdatingStyle = true; yield return Style; UpdatingStyle = false; } } public bool UpdatingStyle { get; set; } public IXLStyle InnerStyle { get; set; } public IXLRanges RangesUsed { get { return new XLRanges(); } } public bool StyleChanged { get; set; } public XLDictionary<XLFormula> Values { get; private set; } public XLDictionary<XLColor> Colors { get; private set; } public XLDictionary<XLCFContentType> ContentTypes { get; private set; } public XLDictionary<XLCFIconSetOperator> IconSetOperators { get; private set; } public IXLRange Range { get; set; } public XLConditionalFormatType ConditionalFormatType { get; set; } public XLTimePeriod TimePeriod { get; set; } public XLIconSetStyle IconSetStyle { get; set; } public XLCFOperator Operator { get; set; } public Boolean Bottom { get; set; } public Boolean Percent { get; set; } public Boolean ReverseIconOrder { get; set; } public Boolean ShowIconOnly { get; set; } public Boolean ShowBarOnly { get; set; } public void CopyFrom(IXLConditionalFormat other) { Style = other.Style; ConditionalFormatType = other.ConditionalFormatType; TimePeriod = other.TimePeriod; IconSetStyle = other.IconSetStyle; Operator = other.Operator; Bottom = other.Bottom; Percent = other.Percent; ReverseIconOrder = other.ReverseIconOrder; ShowIconOnly = other.ShowIconOnly; ShowBarOnly = other.ShowBarOnly; Values.Clear(); other.Values.ForEach(kp => Values.Add(kp.Key, new XLFormula(kp.Value))); //CopyDictionary(Values, other.Values); CopyDictionary(Colors, other.Colors); CopyDictionary(ContentTypes, other.ContentTypes); CopyDictionary(IconSetOperators, other.IconSetOperators); } private void CopyDictionary<T>(XLDictionary<T> target, XLDictionary<T> source) { target.Clear(); source.ForEach(kp => target.Add(kp.Key, kp.Value)); } public IXLStyle WhenIsBlank() { ConditionalFormatType = XLConditionalFormatType.IsBlank; return Style; } public IXLStyle WhenNotBlank() { ConditionalFormatType = XLConditionalFormatType.NotBlank; return Style; } public IXLStyle WhenIsError() { ConditionalFormatType = XLConditionalFormatType.IsError; return Style; } public IXLStyle WhenNotError() { ConditionalFormatType = XLConditionalFormatType.NotError; return Style; } public IXLStyle WhenDateIs(XLTimePeriod timePeriod) { TimePeriod = timePeriod; ConditionalFormatType = XLConditionalFormatType.TimePeriod; return Style; } public IXLStyle WhenContains(String value) { Values.Initialize(new XLFormula { Value = value }); ConditionalFormatType = XLConditionalFormatType.ContainsText; Operator = XLCFOperator.Contains; return Style; } public IXLStyle WhenNotContains(String value) { Values.Initialize(new XLFormula { Value = value }); ConditionalFormatType = XLConditionalFormatType.NotContainsText; Operator = XLCFOperator.NotContains; return Style; } public IXLStyle WhenStartsWith(String value) { Values.Initialize(new XLFormula { Value = value }); ConditionalFormatType = XLConditionalFormatType.StartsWith; Operator = XLCFOperator.StartsWith; return Style; } public IXLStyle WhenEndsWith(String value) { Values.Initialize(new XLFormula { Value = value }); ConditionalFormatType = XLConditionalFormatType.EndsWith; Operator = XLCFOperator.EndsWith; return Style; } public IXLStyle WhenEquals(String value) { Values.Initialize(new XLFormula { Value = value }); Operator = XLCFOperator.Equal; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenNotEquals(String value) { Values.Initialize(new XLFormula { Value = value }); Operator = XLCFOperator.NotEqual; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenGreaterThan(String value) { Values.Initialize(new XLFormula { Value = value }); Operator = XLCFOperator.GreaterThan; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenLessThan(String value) { Values.Initialize(new XLFormula { Value = value }); Operator = XLCFOperator.LessThan; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenEqualOrGreaterThan(String value) { Values.Initialize(new XLFormula { Value = value }); Operator = XLCFOperator.EqualOrGreaterThan; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenEqualOrLessThan(String value) { Values.Initialize(new XLFormula { Value = value }); Operator = XLCFOperator.EqualOrLessThan; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenBetween(String minValue, String maxValue) { Values.Initialize(new XLFormula { Value = minValue }); Values.Add(new XLFormula { Value = maxValue }); Operator = XLCFOperator.Between; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenNotBetween(String minValue, String maxValue) { Values.Initialize(new XLFormula { Value = minValue }); Values.Add(new XLFormula { Value = maxValue }); Operator = XLCFOperator.NotBetween; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenEquals(Double value) { Values.Initialize(new XLFormula(value)); Operator = XLCFOperator.Equal; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenNotEquals(Double value) { Values.Initialize(new XLFormula(value)); Operator = XLCFOperator.NotEqual; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenGreaterThan(Double value) { Values.Initialize(new XLFormula(value)); Operator = XLCFOperator.GreaterThan; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenLessThan(Double value) { Values.Initialize(new XLFormula(value)); Operator = XLCFOperator.LessThan; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenEqualOrGreaterThan(Double value) { Values.Initialize(new XLFormula(value)); Operator = XLCFOperator.EqualOrGreaterThan; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenEqualOrLessThan(Double value) { Values.Initialize(new XLFormula(value)); Operator = XLCFOperator.EqualOrLessThan; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenBetween(Double minValue, Double maxValue) { Values.Initialize(new XLFormula(minValue)); Values.Add(new XLFormula(maxValue)); Operator = XLCFOperator.Between; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenNotBetween(Double minValue, Double maxValue) { Values.Initialize(new XLFormula(minValue)); Values.Add(new XLFormula(maxValue)); Operator = XLCFOperator.NotBetween; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenIsDuplicate() { ConditionalFormatType = XLConditionalFormatType.IsDuplicate; return Style; } public IXLStyle WhenIsUnique() { ConditionalFormatType = XLConditionalFormatType.IsUnique; return Style; } public IXLStyle WhenIsTrue(String formula) { String f = formula.TrimStart()[0] == '=' ? formula : "=" + formula; Values.Initialize(new XLFormula { Value = f }); ConditionalFormatType = XLConditionalFormatType.Expression; return Style; } public IXLStyle WhenIsTop(Int32 value, XLTopBottomType topBottomType = XLTopBottomType.Items) { Values.Initialize(new XLFormula(value)); Percent = topBottomType == XLTopBottomType.Percent; ConditionalFormatType = XLConditionalFormatType.Top10; Bottom = false; return Style; } public IXLStyle WhenIsBottom(Int32 value, XLTopBottomType topBottomType = XLTopBottomType.Items) { Values.Initialize(new XLFormula(value)); Percent = topBottomType == XLTopBottomType.Percent; ConditionalFormatType = XLConditionalFormatType.Top10; Bottom = true; return Style; } public IXLCFColorScaleMin ColorScale() { ConditionalFormatType = XLConditionalFormatType.ColorScale; return new XLCFColorScaleMin(this); } public IXLCFDataBarMin DataBar(XLColor color, Boolean showBarOnly = false) { Colors.Initialize(color); ShowBarOnly = showBarOnly; ConditionalFormatType = XLConditionalFormatType.DataBar; return new XLCFDataBarMin(this); } public IXLCFDataBarMin DataBar(XLColor positiveColor, XLColor negativeColor, Boolean showBarOnly = false) { Colors.Initialize(positiveColor); Colors.Add(negativeColor); ShowBarOnly = showBarOnly; ConditionalFormatType = XLConditionalFormatType.DataBar; return new XLCFDataBarMin(this); } public IXLCFIconSet IconSet(XLIconSetStyle iconSetStyle, Boolean reverseIconOrder = false, Boolean showIconOnly = false) { IconSetOperators.Clear(); Values.Clear(); ContentTypes.Clear(); ConditionalFormatType = XLConditionalFormatType.IconSet; IconSetStyle = iconSetStyle; ReverseIconOrder = reverseIconOrder; ShowIconOnly = showIconOnly; return new XLCFIconSet(this); } } }
//----------------------------------------------------------------------- // <copyright file="PinchGesture.cs" company="Google LLC"> // // Copyright 2018 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCore.Examples.ObjectManipulation { using GoogleARCore.Examples.ObjectManipulationInternal; using UnityEngine; /// <summary> /// Gesture for when the user performs a two-finger pinch motion on the touch screen. /// </summary> public class PinchGesture : Gesture<PinchGesture> { /// <summary> /// Constructs a PinchGesture gesture. /// </summary> /// <param name="recognizer">The gesture recognizer.</param> /// <param name="touch1">The first touch that started this gesture.</param> /// <param name="touch2">The second touch that started this gesture.</param> public PinchGesture(PinchGestureRecognizer recognizer, Touch touch1, Touch touch2) : base(recognizer) { FingerId1 = touch1.fingerId; FingerId2 = touch2.fingerId; StartPosition1 = touch1.position; StartPosition2 = touch2.position; } /// <summary> /// Gets the id of the first finger used in this gesture. /// </summary> public int FingerId1 { get; private set; } /// <summary> /// Gets the id of the second finger used in this gesture. /// </summary> public int FingerId2 { get; private set; } /// <summary> /// Gets the screen position of the first finger where the gesture started. /// </summary> public Vector2 StartPosition1 { get; private set; } /// <summary> /// Gets the screen position of the second finger where the gesture started. /// </summary> public Vector2 StartPosition2 { get; private set; } /// <summary> /// Gets the gap between then position of the first and second fingers. /// </summary> public float Gap { get; private set; } /// <summary> /// Gets the gap delta between then position of the first and second fingers. /// </summary> public float GapDelta { get; private set; } /// <summary> /// Returns true if this gesture can start. /// </summary> /// <returns>True if the gesture can start.</returns> protected internal override bool CanStart() { if (GestureTouchesUtility.IsFingerIdRetained(FingerId1) || GestureTouchesUtility.IsFingerIdRetained(FingerId2)) { Cancel(); return false; } Touch touch1, touch2; bool foundTouches = GestureTouchesUtility.TryFindTouch(FingerId1, out touch1); foundTouches = GestureTouchesUtility.TryFindTouch(FingerId2, out touch2) && foundTouches; if (!foundTouches) { Cancel(); return false; } // Check that at least one finger is moving. if (touch1.deltaPosition == Vector2.zero && touch2.deltaPosition == Vector2.zero) { return false; } PinchGestureRecognizer pinchRecognizer = Recognizer as PinchGestureRecognizer; Vector3 firstToSecondDirection = (StartPosition1 - StartPosition2).normalized; float dot1 = Vector3.Dot(touch1.deltaPosition.normalized, -firstToSecondDirection); float dot2 = Vector3.Dot(touch2.deltaPosition.normalized, firstToSecondDirection); float dotThreshold = Mathf.Cos(pinchRecognizer.SlopMotionDirectionDegrees * Mathf.Deg2Rad); // Check angle of motion for the first touch. if (touch1.deltaPosition != Vector2.zero && Mathf.Abs(dot1) < dotThreshold) { return false; } // Check angle of motion for the second touch. if (touch2.deltaPosition != Vector2.zero && Mathf.Abs(dot2) < dotThreshold) { return false; } float startgap = (StartPosition1 - StartPosition2).magnitude; Gap = (touch1.position - touch2.position).magnitude; float separation = GestureTouchesUtility.PixelsToInches(Mathf.Abs(Gap - startgap)); if (separation < pinchRecognizer.SlopInches) { return false; } return true; } /// <summary> /// Action to be performed when this gesture is started. /// </summary> protected internal override void OnStart() { GestureTouchesUtility.LockFingerId(FingerId1); GestureTouchesUtility.LockFingerId(FingerId2); } /// <summary> /// Updates this gesture. /// </summary> /// <returns>True if the update was successful.</returns> protected internal override bool UpdateGesture() { Touch touch1, touch2; bool foundTouches = GestureTouchesUtility.TryFindTouch(FingerId1, out touch1); foundTouches = GestureTouchesUtility.TryFindTouch(FingerId2, out touch2) && foundTouches; if (!foundTouches) { Cancel(); return false; } if (touch1.phase == TouchPhase.Canceled || touch2.phase == TouchPhase.Canceled) { Cancel(); return false; } if (touch1.phase == TouchPhase.Ended || touch2.phase == TouchPhase.Ended) { Complete(); return false; } if (touch1.phase == TouchPhase.Moved || touch2.phase == TouchPhase.Moved) { float newgap = (touch1.position - touch2.position).magnitude; GapDelta = newgap - Gap; Gap = newgap; return true; } return false; } /// <summary> /// Action to be performed when this gesture is cancelled. /// </summary> protected internal override void OnCancel() { } /// <summary> /// Action to be performed when this gesture is finished. /// </summary> protected internal override void OnFinish() { GestureTouchesUtility.ReleaseFingerId(FingerId1); GestureTouchesUtility.ReleaseFingerId(FingerId2); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime.InteropServices; namespace System.Numerics.Matrices { /// <summary> /// Represents a matrix of double precision floating-point values defined by its number of columns and rows /// </summary> [StructLayout(LayoutKind.Sequential)] public struct Matrix1x3: IEquatable<Matrix1x3>, IMatrix { public const int ColumnCount = 1; public const int RowCount = 3; static Matrix1x3() { Zero = new Matrix1x3(0); } /// <summary> /// Gets the smallest value used to determine equality /// </summary> public double Epsilon { get { return MatrixHelper.Epsilon; } } /// <summary> /// Constant Matrix1x3 with all values initialized to zero /// </summary> public static readonly Matrix1x3 Zero; /// <summary> /// Initializes a Matrix1x3 with all of it values specifically set /// </summary> /// <param name="m11">The column 1, row 1 value</param> /// <param name="m12">The column 1, row 2 value</param> /// <param name="m13">The column 1, row 3 value</param> public Matrix1x3(double m11, double m12, double m13) { M11 = m11; M12 = m12; M13 = m13; } /// <summary> /// Initialized a Matrix1x3 with all values set to the same value /// </summary> /// <param name="value">The value to set all values to</param> public Matrix1x3(double value) { M11 = M12 = M13 = value; } public double M11; public double M12; public double M13; public unsafe double this[int col, int row] { get { if (col < 0 || col >= ColumnCount) throw new ArgumentOutOfRangeException("col", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", ColumnCount, col)); if (row < 0 || row >= RowCount) throw new ArgumentOutOfRangeException("row", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", RowCount, row)); fixed (Matrix1x3* p = &this) { double* d = (double*)p; return d[row * ColumnCount + col]; } } set { if (col < 0 || col >= ColumnCount) throw new ArgumentOutOfRangeException("col", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", ColumnCount, col)); if (row < 0 || row >= RowCount) throw new ArgumentOutOfRangeException("row", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", RowCount, row)); fixed (Matrix1x3* p = &this) { double* d = (double*)p; d[row * ColumnCount + col] = value; } } } /// <summary> /// Gets the number of columns in the matrix /// </summary> public int Columns { get { return ColumnCount; } } /// <summary> /// Get the number of rows in the matrix /// </summary> public int Rows { get { return RowCount; } } public override bool Equals(object obj) { if (obj is Matrix1x3) return this == (Matrix1x3)obj; return false; } public bool Equals(Matrix1x3 other) { return this == other; } public unsafe override int GetHashCode() { fixed (Matrix1x3* p = &this) { int* x = (int*)p; unchecked { return 0xFFE1 + 7 * ((((x[00] ^ x[01]) << 0)) << 0) + 7 * ((((x[01] ^ x[02]) << 0)) << 1) + 7 * ((((x[02] ^ x[03]) << 0)) << 2); } } } public override string ToString() { return "Matrix1x3: " + String.Format("{{|{0:00}|}}", M11) + String.Format("{{|{0:00}|}}", M12) + String.Format("{{|{0:00}|}}", M13); } /// <summary> /// Creates and returns a transposed matrix /// </summary> /// <returns>Matrix with transposed values</returns> public Matrix3x1 Transpose() { return new Matrix3x1(M11, M12, M13); } public static bool operator ==(Matrix1x3 matrix1, Matrix1x3 matrix2) { return MatrixHelper.AreEqual(matrix1.M11, matrix2.M11) && MatrixHelper.AreEqual(matrix1.M12, matrix2.M12) && MatrixHelper.AreEqual(matrix1.M13, matrix2.M13); } public static bool operator !=(Matrix1x3 matrix1, Matrix1x3 matrix2) { return MatrixHelper.NotEqual(matrix1.M11, matrix2.M11) || MatrixHelper.NotEqual(matrix1.M12, matrix2.M12) || MatrixHelper.NotEqual(matrix1.M13, matrix2.M13); } public static Matrix1x3 operator +(Matrix1x3 matrix1, Matrix1x3 matrix2) { double m11 = matrix1.M11 + matrix2.M11; double m12 = matrix1.M12 + matrix2.M12; double m13 = matrix1.M13 + matrix2.M13; return new Matrix1x3(m11, m12, m13); } public static Matrix1x3 operator -(Matrix1x3 matrix1, Matrix1x3 matrix2) { double m11 = matrix1.M11 - matrix2.M11; double m12 = matrix1.M12 - matrix2.M12; double m13 = matrix1.M13 - matrix2.M13; return new Matrix1x3(m11, m12, m13); } public static Matrix1x3 operator *(Matrix1x3 matrix, double scalar) { double m11 = matrix.M11 * scalar; double m12 = matrix.M12 * scalar; double m13 = matrix.M13 * scalar; return new Matrix1x3(m11, m12, m13); } public static Matrix1x3 operator *(double scalar, Matrix1x3 matrix) { double m11 = scalar * matrix.M11; double m12 = scalar * matrix.M12; double m13 = scalar * matrix.M13; return new Matrix1x3(m11, m12, m13); } public static Matrix2x3 operator *(Matrix1x3 matrix1, Matrix2x1 matrix2) { double m11 = matrix1.M11 * matrix2.M11; double m21 = matrix1.M11 * matrix2.M21; double m12 = matrix1.M12 * matrix2.M11; double m22 = matrix1.M12 * matrix2.M21; double m13 = matrix1.M13 * matrix2.M11; double m23 = matrix1.M13 * matrix2.M21; return new Matrix2x3(m11, m21, m12, m22, m13, m23); } public static Matrix3x3 operator *(Matrix1x3 matrix1, Matrix3x1 matrix2) { double m11 = matrix1.M11 * matrix2.M11; double m21 = matrix1.M11 * matrix2.M21; double m31 = matrix1.M11 * matrix2.M31; double m12 = matrix1.M12 * matrix2.M11; double m22 = matrix1.M12 * matrix2.M21; double m32 = matrix1.M12 * matrix2.M31; double m13 = matrix1.M13 * matrix2.M11; double m23 = matrix1.M13 * matrix2.M21; double m33 = matrix1.M13 * matrix2.M31; return new Matrix3x3(m11, m21, m31, m12, m22, m32, m13, m23, m33); } public static Matrix4x3 operator *(Matrix1x3 matrix1, Matrix4x1 matrix2) { double m11 = matrix1.M11 * matrix2.M11; double m21 = matrix1.M11 * matrix2.M21; double m31 = matrix1.M11 * matrix2.M31; double m41 = matrix1.M11 * matrix2.M41; double m12 = matrix1.M12 * matrix2.M11; double m22 = matrix1.M12 * matrix2.M21; double m32 = matrix1.M12 * matrix2.M31; double m42 = matrix1.M12 * matrix2.M41; double m13 = matrix1.M13 * matrix2.M11; double m23 = matrix1.M13 * matrix2.M21; double m33 = matrix1.M13 * matrix2.M31; double m43 = matrix1.M13 * matrix2.M41; return new Matrix4x3(m11, m21, m31, m41, m12, m22, m32, m42, m13, m23, m33, m43); } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// STVDO Transfer Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class STVDO_TRDataSet : EduHubDataSet<STVDO_TR> { /// <inheritdoc /> public override string Name { get { return "STVDO_TR"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal STVDO_TRDataSet(EduHubContext Context) : base(Context) { Index_ORIG_SCHOOL = new Lazy<Dictionary<string, IReadOnlyList<STVDO_TR>>>(() => this.ToGroupedDictionary(i => i.ORIG_SCHOOL)); Index_STVDO_TRANS_ID = new Lazy<NullDictionary<string, STVDO_TR>>(() => this.ToNullDictionary(i => i.STVDO_TRANS_ID)); Index_TID = new Lazy<Dictionary<int, STVDO_TR>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="STVDO_TR" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="STVDO_TR" /> fields for each CSV column header</returns> internal override Action<STVDO_TR, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<STVDO_TR, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "ORIG_SCHOOL": mapper[i] = (e, v) => e.ORIG_SCHOOL = v; break; case "STVDO_TRANS_ID": mapper[i] = (e, v) => e.STVDO_TRANS_ID = v; break; case "SKEY": mapper[i] = (e, v) => e.SKEY = v; break; case "SKEY_NEW": mapper[i] = (e, v) => e.SKEY_NEW = v; break; case "SCHOOL_YEAR": mapper[i] = (e, v) => e.SCHOOL_YEAR = v; break; case "CAMPUS": mapper[i] = (e, v) => e.CAMPUS = v == null ? (int?)null : int.Parse(v); break; case "YEAR_SEMESTER": mapper[i] = (e, v) => e.YEAR_SEMESTER = v; break; case "VDOMAIN": mapper[i] = (e, v) => e.VDOMAIN = v; break; case "VDIMENSION": mapper[i] = (e, v) => e.VDIMENSION = v; break; case "SCORE": mapper[i] = (e, v) => e.SCORE = v; break; case "ORIGINAL_SCHOOL": mapper[i] = (e, v) => e.ORIGINAL_SCHOOL = v; break; case "ST_TRANS_ID": mapper[i] = (e, v) => e.ST_TRANS_ID = v; break; case "IMP_STATUS": mapper[i] = (e, v) => e.IMP_STATUS = v; break; case "IMP_DATE": mapper[i] = (e, v) => e.IMP_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="STVDO_TR" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="STVDO_TR" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="STVDO_TR" /> entities</param> /// <returns>A merged <see cref="IEnumerable{STVDO_TR}"/> of entities</returns> internal override IEnumerable<STVDO_TR> ApplyDeltaEntities(IEnumerable<STVDO_TR> Entities, List<STVDO_TR> DeltaEntities) { HashSet<string> Index_STVDO_TRANS_ID = new HashSet<string>(DeltaEntities.Select(i => i.STVDO_TRANS_ID)); HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.ORIG_SCHOOL; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = false; overwritten = overwritten || Index_STVDO_TRANS_ID.Remove(entity.STVDO_TRANS_ID); overwritten = overwritten || Index_TID.Remove(entity.TID); if (entity.ORIG_SCHOOL.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<string, IReadOnlyList<STVDO_TR>>> Index_ORIG_SCHOOL; private Lazy<NullDictionary<string, STVDO_TR>> Index_STVDO_TRANS_ID; private Lazy<Dictionary<int, STVDO_TR>> Index_TID; #endregion #region Index Methods /// <summary> /// Find STVDO_TR by ORIG_SCHOOL field /// </summary> /// <param name="ORIG_SCHOOL">ORIG_SCHOOL value used to find STVDO_TR</param> /// <returns>List of related STVDO_TR entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STVDO_TR> FindByORIG_SCHOOL(string ORIG_SCHOOL) { return Index_ORIG_SCHOOL.Value[ORIG_SCHOOL]; } /// <summary> /// Attempt to find STVDO_TR by ORIG_SCHOOL field /// </summary> /// <param name="ORIG_SCHOOL">ORIG_SCHOOL value used to find STVDO_TR</param> /// <param name="Value">List of related STVDO_TR entities</param> /// <returns>True if the list of related STVDO_TR entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByORIG_SCHOOL(string ORIG_SCHOOL, out IReadOnlyList<STVDO_TR> Value) { return Index_ORIG_SCHOOL.Value.TryGetValue(ORIG_SCHOOL, out Value); } /// <summary> /// Attempt to find STVDO_TR by ORIG_SCHOOL field /// </summary> /// <param name="ORIG_SCHOOL">ORIG_SCHOOL value used to find STVDO_TR</param> /// <returns>List of related STVDO_TR entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STVDO_TR> TryFindByORIG_SCHOOL(string ORIG_SCHOOL) { IReadOnlyList<STVDO_TR> value; if (Index_ORIG_SCHOOL.Value.TryGetValue(ORIG_SCHOOL, out value)) { return value; } else { return null; } } /// <summary> /// Find STVDO_TR by STVDO_TRANS_ID field /// </summary> /// <param name="STVDO_TRANS_ID">STVDO_TRANS_ID value used to find STVDO_TR</param> /// <returns>Related STVDO_TR entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public STVDO_TR FindBySTVDO_TRANS_ID(string STVDO_TRANS_ID) { return Index_STVDO_TRANS_ID.Value[STVDO_TRANS_ID]; } /// <summary> /// Attempt to find STVDO_TR by STVDO_TRANS_ID field /// </summary> /// <param name="STVDO_TRANS_ID">STVDO_TRANS_ID value used to find STVDO_TR</param> /// <param name="Value">Related STVDO_TR entity</param> /// <returns>True if the related STVDO_TR entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySTVDO_TRANS_ID(string STVDO_TRANS_ID, out STVDO_TR Value) { return Index_STVDO_TRANS_ID.Value.TryGetValue(STVDO_TRANS_ID, out Value); } /// <summary> /// Attempt to find STVDO_TR by STVDO_TRANS_ID field /// </summary> /// <param name="STVDO_TRANS_ID">STVDO_TRANS_ID value used to find STVDO_TR</param> /// <returns>Related STVDO_TR entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public STVDO_TR TryFindBySTVDO_TRANS_ID(string STVDO_TRANS_ID) { STVDO_TR value; if (Index_STVDO_TRANS_ID.Value.TryGetValue(STVDO_TRANS_ID, out value)) { return value; } else { return null; } } /// <summary> /// Find STVDO_TR by TID field /// </summary> /// <param name="TID">TID value used to find STVDO_TR</param> /// <returns>Related STVDO_TR entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public STVDO_TR FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find STVDO_TR by TID field /// </summary> /// <param name="TID">TID value used to find STVDO_TR</param> /// <param name="Value">Related STVDO_TR entity</param> /// <returns>True if the related STVDO_TR entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out STVDO_TR Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find STVDO_TR by TID field /// </summary> /// <param name="TID">TID value used to find STVDO_TR</param> /// <returns>Related STVDO_TR entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public STVDO_TR TryFindByTID(int TID) { STVDO_TR value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a STVDO_TR table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[STVDO_TR]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[STVDO_TR]( [TID] int IDENTITY NOT NULL, [ORIG_SCHOOL] varchar(8) NOT NULL, [STVDO_TRANS_ID] varchar(30) NULL, [SKEY] varchar(10) NULL, [SKEY_NEW] varchar(10) NULL, [SCHOOL_YEAR] varchar(4) NULL, [CAMPUS] int NULL, [YEAR_SEMESTER] varchar(6) NULL, [VDOMAIN] varchar(10) NULL, [VDIMENSION] varchar(10) NULL, [SCORE] varchar(6) NULL, [ORIGINAL_SCHOOL] varchar(8) NULL, [ST_TRANS_ID] varchar(30) NULL, [IMP_STATUS] varchar(15) NULL, [IMP_DATE] datetime NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [STVDO_TR_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE CLUSTERED INDEX [STVDO_TR_Index_ORIG_SCHOOL] ON [dbo].[STVDO_TR] ( [ORIG_SCHOOL] ASC ); CREATE NONCLUSTERED INDEX [STVDO_TR_Index_STVDO_TRANS_ID] ON [dbo].[STVDO_TR] ( [STVDO_TRANS_ID] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STVDO_TR]') AND name = N'STVDO_TR_Index_STVDO_TRANS_ID') ALTER INDEX [STVDO_TR_Index_STVDO_TRANS_ID] ON [dbo].[STVDO_TR] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STVDO_TR]') AND name = N'STVDO_TR_Index_TID') ALTER INDEX [STVDO_TR_Index_TID] ON [dbo].[STVDO_TR] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STVDO_TR]') AND name = N'STVDO_TR_Index_STVDO_TRANS_ID') ALTER INDEX [STVDO_TR_Index_STVDO_TRANS_ID] ON [dbo].[STVDO_TR] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STVDO_TR]') AND name = N'STVDO_TR_Index_TID') ALTER INDEX [STVDO_TR_Index_TID] ON [dbo].[STVDO_TR] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="STVDO_TR"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="STVDO_TR"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<STVDO_TR> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<string> Index_STVDO_TRANS_ID = new List<string>(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_STVDO_TRANS_ID.Add(entity.STVDO_TRANS_ID); Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[STVDO_TR] WHERE"); // Index_STVDO_TRANS_ID builder.Append("[STVDO_TRANS_ID] IN ("); for (int index = 0; index < Index_STVDO_TRANS_ID.Count; index++) { if (index != 0) builder.Append(", "); // STVDO_TRANS_ID var parameterSTVDO_TRANS_ID = $"@p{parameterIndex++}"; builder.Append(parameterSTVDO_TRANS_ID); command.Parameters.Add(parameterSTVDO_TRANS_ID, SqlDbType.VarChar, 30).Value = (object)Index_STVDO_TRANS_ID[index] ?? DBNull.Value; } builder.AppendLine(") OR"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the STVDO_TR data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the STVDO_TR data set</returns> public override EduHubDataSetDataReader<STVDO_TR> GetDataSetDataReader() { return new STVDO_TRDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the STVDO_TR data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the STVDO_TR data set</returns> public override EduHubDataSetDataReader<STVDO_TR> GetDataSetDataReader(List<STVDO_TR> Entities) { return new STVDO_TRDataReader(new EduHubDataSetLoadedReader<STVDO_TR>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class STVDO_TRDataReader : EduHubDataSetDataReader<STVDO_TR> { public STVDO_TRDataReader(IEduHubDataSetReader<STVDO_TR> Reader) : base (Reader) { } public override int FieldCount { get { return 18; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // ORIG_SCHOOL return Current.ORIG_SCHOOL; case 2: // STVDO_TRANS_ID return Current.STVDO_TRANS_ID; case 3: // SKEY return Current.SKEY; case 4: // SKEY_NEW return Current.SKEY_NEW; case 5: // SCHOOL_YEAR return Current.SCHOOL_YEAR; case 6: // CAMPUS return Current.CAMPUS; case 7: // YEAR_SEMESTER return Current.YEAR_SEMESTER; case 8: // VDOMAIN return Current.VDOMAIN; case 9: // VDIMENSION return Current.VDIMENSION; case 10: // SCORE return Current.SCORE; case 11: // ORIGINAL_SCHOOL return Current.ORIGINAL_SCHOOL; case 12: // ST_TRANS_ID return Current.ST_TRANS_ID; case 13: // IMP_STATUS return Current.IMP_STATUS; case 14: // IMP_DATE return Current.IMP_DATE; case 15: // LW_DATE return Current.LW_DATE; case 16: // LW_TIME return Current.LW_TIME; case 17: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // STVDO_TRANS_ID return Current.STVDO_TRANS_ID == null; case 3: // SKEY return Current.SKEY == null; case 4: // SKEY_NEW return Current.SKEY_NEW == null; case 5: // SCHOOL_YEAR return Current.SCHOOL_YEAR == null; case 6: // CAMPUS return Current.CAMPUS == null; case 7: // YEAR_SEMESTER return Current.YEAR_SEMESTER == null; case 8: // VDOMAIN return Current.VDOMAIN == null; case 9: // VDIMENSION return Current.VDIMENSION == null; case 10: // SCORE return Current.SCORE == null; case 11: // ORIGINAL_SCHOOL return Current.ORIGINAL_SCHOOL == null; case 12: // ST_TRANS_ID return Current.ST_TRANS_ID == null; case 13: // IMP_STATUS return Current.IMP_STATUS == null; case 14: // IMP_DATE return Current.IMP_DATE == null; case 15: // LW_DATE return Current.LW_DATE == null; case 16: // LW_TIME return Current.LW_TIME == null; case 17: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // ORIG_SCHOOL return "ORIG_SCHOOL"; case 2: // STVDO_TRANS_ID return "STVDO_TRANS_ID"; case 3: // SKEY return "SKEY"; case 4: // SKEY_NEW return "SKEY_NEW"; case 5: // SCHOOL_YEAR return "SCHOOL_YEAR"; case 6: // CAMPUS return "CAMPUS"; case 7: // YEAR_SEMESTER return "YEAR_SEMESTER"; case 8: // VDOMAIN return "VDOMAIN"; case 9: // VDIMENSION return "VDIMENSION"; case 10: // SCORE return "SCORE"; case 11: // ORIGINAL_SCHOOL return "ORIGINAL_SCHOOL"; case 12: // ST_TRANS_ID return "ST_TRANS_ID"; case 13: // IMP_STATUS return "IMP_STATUS"; case 14: // IMP_DATE return "IMP_DATE"; case 15: // LW_DATE return "LW_DATE"; case 16: // LW_TIME return "LW_TIME"; case 17: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "ORIG_SCHOOL": return 1; case "STVDO_TRANS_ID": return 2; case "SKEY": return 3; case "SKEY_NEW": return 4; case "SCHOOL_YEAR": return 5; case "CAMPUS": return 6; case "YEAR_SEMESTER": return 7; case "VDOMAIN": return 8; case "VDIMENSION": return 9; case "SCORE": return 10; case "ORIGINAL_SCHOOL": return 11; case "ST_TRANS_ID": return 12; case "IMP_STATUS": return 13; case "IMP_DATE": return 14; case "LW_DATE": return 15; case "LW_TIME": return 16; case "LW_USER": return 17; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
using System; using System.Collections.Generic; using System.Drawing; using System.Text; using System.Windows.Forms; namespace DeOps.Interface.Views { public class OpusColorTable : ProfessionalColorTable { // button public override Color ButtonSelectedHighlight { get { return Color.FromArgb(255, 218, 223, 232); } } public override Color ButtonSelectedHighlightBorder { get { return Color.FromArgb(255, 130, 148, 180); } } public override Color ButtonPressedHighlight { get { return Color.FromArgb(255, 191, 200, 216); } } public override Color ButtonPressedHighlightBorder { get { return Color.FromArgb(255, 130, 148, 180); } } public override Color ButtonCheckedHighlight { get { return Color.FromArgb(255, 218, 223, 232); } } public override Color ButtonCheckedHighlightBorder { get { return Color.FromArgb(255, 130, 148, 180); } } public override Color ButtonPressedBorder { get { return Color.FromArgb(255, 130, 148, 180); } } public override Color ButtonSelectedBorder { get { return Color.FromArgb(255, 130, 148, 180); } } public override Color ButtonCheckedGradientBegin { get { return Color.FromArgb(0, 0, 0, 0); } } public override Color ButtonCheckedGradientMiddle { get { return Color.FromArgb(0, 0, 0, 0); } } public override Color ButtonCheckedGradientEnd { get { return Color.FromArgb(0, 0, 0, 0); } } public override Color ButtonSelectedGradientBegin { get { return Color.FromArgb(255, 218, 223, 233); } } public override Color ButtonSelectedGradientMiddle { get { return Color.FromArgb(255, 218, 223, 233); } } public override Color ButtonSelectedGradientEnd { get { return Color.FromArgb(255, 218, 223, 233); } } public override Color ButtonPressedGradientBegin { get { return Color.FromArgb(255, 193, 202, 218); } } public override Color ButtonPressedGradientMiddle { get { return Color.FromArgb(255, 193, 202, 218); } } public override Color ButtonPressedGradientEnd { get { return Color.FromArgb(255, 193, 202, 218); } } // check public override Color CheckBackground { get { return Color.FromArgb(255, 130, 148, 180); } } public override Color CheckSelectedBackground { get { return Color.FromArgb(255, 193, 202, 218); } } public override Color CheckPressedBackground { get { return Color.FromArgb(255, 193, 202, 218); } } // grip public override Color GripDark { get { return Color.FromArgb(255, 224, 224, 218); } } public override Color GripLight { get { return Color.FromArgb(255, 255, 255, 255); } } // image public override Color ImageMarginGradientBegin { get { return Color.FromArgb(255, 249, 248, 247); } } public override Color ImageMarginGradientMiddle { get { return Color.FromArgb(255, 241, 241, 238); } } public override Color ImageMarginGradientEnd { get { return Color.FromArgb(255, 227, 226, 221); } } public override Color ImageMarginRevealedGradientBegin { get { return Color.FromArgb(255, 244, 243, 241); } } public override Color ImageMarginRevealedGradientMiddle { get { return Color.FromArgb(255, 235, 235, 231); } } public override Color ImageMarginRevealedGradientEnd { get { return Color.FromArgb(255, 230, 229, 224); } } // menu public override Color MenuStripGradientBegin { get { return Color.FromArgb(255, 227, 226, 221); } } public override Color MenuStripGradientEnd { get { return Color.FromArgb(255, 249, 249, 248); } } public override Color MenuItemSelected { get { return Color.FromArgb(255, 255, 255, 255); } } public override Color MenuItemBorder { get { return Color.FromArgb(255, 130, 148, 180); } } public override Color MenuBorder { get { return Color.FromArgb(255, 171, 170, 164); } } public override Color MenuItemSelectedGradientBegin { get { return Color.FromArgb(255, 218, 223, 233); } } public override Color MenuItemSelectedGradientEnd { get { return Color.FromArgb(255, 218, 223, 233); } } public override Color MenuItemPressedGradientBegin { get { return Color.FromArgb(255, 249, 248, 247); } } public override Color MenuItemPressedGradientMiddle { get { return Color.FromArgb(255, 235, 235, 231); } } public override Color MenuItemPressedGradientEnd { get { return Color.FromArgb(255, 241, 241, 238); } } // rafting public override Color RaftingContainerGradientBegin { get { return Color.FromArgb(255, 227, 226, 221); } } public override Color RaftingContainerGradientEnd { get { return Color.FromArgb(255, 249, 249, 248); } } // separator public override Color SeparatorDark { get { return Color.FromArgb(255, 226, 226, 220); } } public override Color SeparatorLight { get { return Color.FromArgb(255, 244, 244, 242); } } // status public override Color StatusStripGradientBegin { get { return Color.FromArgb(255, 227, 226, 221); } } public override Color StatusStripGradientEnd { get { return Color.FromArgb(255, 249, 249, 248); } } // toolstrip public override Color ToolStripBorder { get { return Color.FromArgb(255, 232, 231, 227); } } public override Color ToolStripDropDownBackground { get { return Color.FromArgb(255, 251, 251, 250); } } public override Color ToolStripGradientBegin { get { return Color.FromArgb(255, 249, 248, 247); } } public override Color ToolStripGradientMiddle { get { return Color.FromArgb(255, 241, 241, 238); } } public override Color ToolStripGradientEnd { get { return Color.FromArgb(255, 227, 226, 221); } } // panel public override Color ToolStripContentPanelGradientBegin { get { return Color.FromArgb(255, 227, 226, 221); } } public override Color ToolStripContentPanelGradientEnd { get { return Color.FromArgb(255, 249, 249, 248); } } public override Color ToolStripPanelGradientBegin { get { return Color.FromArgb(255, 227, 226, 221); } } public override Color ToolStripPanelGradientEnd { get { return Color.FromArgb(255, 249, 249, 248); } } public override Color OverflowButtonGradientBegin { get { return Color.FromArgb(255, 235, 235, 231); } } public override Color OverflowButtonGradientMiddle { get { return Color.FromArgb(255, 230, 229, 224); } } public override Color OverflowButtonGradientEnd { get { return Color.FromArgb(255, 214, 213, 205); } } } class NavColorTable : OpusColorTable { // cornflower 100,149,237 // 120,169,255 // 80,129,217 // panel public override Color ToolStripGradientBegin { get { return Color.FromArgb(255, 100, 149, 237); } } public override Color ToolStripGradientMiddle { get { return Color.FromArgb(255, 100, 149, 237); } } public override Color ToolStripGradientEnd { get { return Color.FromArgb(255, 100, 149, 237); } } // mouse over lighter public override Color ButtonSelectedGradientBegin { get { return Color.FromArgb(255, 120, 169, 255); } } public override Color ButtonSelectedGradientEnd { get { return Color.FromArgb(255, 120, 169, 255); } } // mouse down darker public override Color MenuItemPressedGradientBegin { get { return Color.FromArgb(255, 80, 129, 217); } } public override Color MenuItemPressedGradientEnd { get { return Color.FromArgb(255, 80, 129, 217); } } public override Color ButtonPressedGradientBegin { get { return Color.FromArgb(255, 80, 129, 217); } } public override Color ButtonPressedGradientMiddle { get { return Color.FromArgb(255, 80, 129, 217); } } public override Color ButtonPressedGradientEnd { get { return Color.FromArgb(255, 80, 129, 217); } } // black border public override Color MenuBorder { get { return Color.FromArgb(255, 150, 150, 150); } } public override Color ButtonSelectedBorder { get { return Color.FromArgb(255, 80, 129, 217); } } } }
// Copyright 2009 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System.Collections.Generic; using System.IO; using System.Text; using NodaTime.Utility; namespace NodaTime.TimeZones.IO { /// <summary> /// Implementation of <see cref="IDateTimeZoneReader"/> for the most recent version /// of the "blob" format of time zone data. If the format changes, this class will be /// renamed (e.g. to DateTimeZoneReaderV0) and the new implementation will replace it. /// </summary> internal sealed class DateTimeZoneReader : IDateTimeZoneReader { /// <summary> /// Raw stream to read from. Be careful before reading from this - you need to take /// account of bufferedByte as well. /// </summary> private readonly Stream input; private readonly IList<string> stringPool; /// <summary> /// Sometimes we need to buffer a byte in memory, e.g. to check if there is any /// more data. Anything reading directly from the stream should check here first. /// </summary> private byte? bufferedByte; internal DateTimeZoneReader(Stream input, IList<string> stringPool) { this.input = input; this.stringPool = stringPool; } public bool HasMoreData { get { if (bufferedByte != null) { return true; } int nextByte = input.ReadByte(); if (nextByte == -1) { return false; } // Okay, we got a byte - remember it for the next call to ReadByte. bufferedByte = (byte) nextByte; return true; } } /// <summary> /// Reads a non-negative integer value from the stream. /// </summary> /// <remarks> /// The value must have been written by <see cref="DateTimeZoneWriter.WriteCount" />. /// </remarks> /// <returns>The integer value from the stream.</returns> public int ReadCount() { uint unsigned = ReadVarint(); if (unsigned > int.MaxValue) { throw new InvalidNodaDataException("Count value greater than Int32.MaxValue"); } return (int) unsigned; } /// <summary> /// Reads a (possibly-negative) integer value from the stream. /// </summary> /// <remarks> /// The value must have been written by <see cref="DateTimeZoneWriter.WriteSignedCount" />. /// </remarks> /// <returns>The integer value from the stream.</returns> public int ReadSignedCount() { uint value = ReadVarint(); return (int) (value >> 1) ^ -(int) (value & 1); // zigzag encoding } /// <summary> /// Reads a base-128 varint value from the stream. /// </summary> /// <remarks> /// The value must have been written by DateTimeZoneWriter.WriteVarint, which /// documents the format. /// </remarks> /// <returns>The integer value from the stream.</returns> private uint ReadVarint() { unchecked { uint ret = 0; int shift = 0; while (true) { byte nextByte = ReadByte(); ret += (uint) (nextByte & 0x7f) << shift; shift += 7; if (nextByte < 0x80) { return ret; } } } } /// <summary> /// Reads a number of milliseconds from the stream. /// </summary> /// <remarks> /// The value must have been written by <see cref="DateTimeZoneWriter.WriteMilliseconds" />. /// </remarks> /// <returns>The offset value from the stream.</returns> public int ReadMilliseconds() { unchecked { byte firstByte = ReadByte(); int millis; if ((firstByte & 0x80) == 0) { millis = firstByte * (30 * NodaConstants.MillisecondsPerMinute); } else { int flag = firstByte & 0xe0; // The flag parts of the first byte int firstData = firstByte & 0x1f; // The data parts of the first byte switch (flag) { case 0x80: // Minutes int minutes = (firstData << 8) + ReadByte(); millis = minutes * NodaConstants.MillisecondsPerMinute; break; case 0xa0: // Seconds int seconds = (firstData << 16) + (ReadInt16() & 0xffff); millis = seconds * NodaConstants.MillisecondsPerSecond; break; case 0xc0: // Milliseconds millis = (firstData << 24) + (ReadByte() << 16) + (ReadInt16() & 0xffff); break; default: throw new InvalidNodaDataException("Invalid flag in offset: " + flag.ToString("x2")); } } millis -= NodaConstants.MillisecondsPerDay; return millis; } } /// <summary> /// Reads an offset value from the stream. /// </summary> /// <remarks> /// The value must have been written by <see cref="DateTimeZoneWriter.WriteOffset" />. /// </remarks> /// <returns>The offset value from the stream.</returns> public Offset ReadOffset() { int millis = ReadMilliseconds(); return Offset.FromMilliseconds(millis); } /// <summary> /// Reads a string to string dictionary value from the stream. /// </summary> /// <remarks> /// The value must have been written by <see cref="DateTimeZoneWriter.WriteDictionary" />. /// </remarks> /// <returns>The <see cref="IDictionary{TKey,TValue}" /> value from the stream.</returns> public IDictionary<string, string> ReadDictionary() { IDictionary<string, string> results = new Dictionary<string, string>(); int count = ReadCount(); for (int i = 0; i < count; i++) { string key = ReadString(); string value = ReadString(); results.Add(key, value); } return results; } /// <summary> /// Reads an instant representing a zone interval transition from the stream. /// </summary> /// <remarks> /// The value must have been written by <see cref="DateTimeZoneWriter.WriteZoneIntervalTransition" />. /// </remarks> /// <param name="previous">The previous transition written (usually for a given timezone), or null if there is /// no previous transition.</param> /// <returns>The instant read from the stream</returns> public Instant ReadZoneIntervalTransition(Instant? previous) { unchecked { int value = ReadCount(); if (value < DateTimeZoneWriter.ZoneIntervalConstants.MinValueForHoursSincePrevious) { switch (value) { case DateTimeZoneWriter.ZoneIntervalConstants.MarkerMinValue: return Instant.BeforeMinValue; case DateTimeZoneWriter.ZoneIntervalConstants.MarkerMaxValue: return Instant.AfterMaxValue; case DateTimeZoneWriter.ZoneIntervalConstants.MarkerRaw: return Instant.FromTicksSinceUnixEpoch(ReadInt64()); default: throw new InvalidNodaDataException("Unrecognised marker value: " + value); } } if (value < DateTimeZoneWriter.ZoneIntervalConstants.MinValueForMinutesSinceEpoch) { if (previous == null) { throw new InvalidNodaDataException( "No previous value, so can't interpret value encoded as delta-since-previous: " + value); } return (Instant) previous + Duration.FromHours(value); } return DateTimeZoneWriter.ZoneIntervalConstants.EpochForMinutesSinceEpoch + Duration.FromMinutes(value); } } /// <summary> /// Reads a string value from the stream. /// </summary> /// <remarks> /// The value must have been written by <see cref="DateTimeZoneWriter.WriteString" />. /// </remarks> /// <returns>The string value from the stream.</returns> public string ReadString() { if (stringPool == null) { // This will flush the buffered byte if there is one, so we don't need to worry about that // when reading the actual data. int length = ReadCount(); var data = new byte[length]; int offset = 0; while (offset < length) { int bytesRead = input.Read(data, offset, length - offset); if (bytesRead <= 0) { throw new InvalidNodaDataException("Unexpectedly reached end of data with " + (length - offset) + " bytes still to read"); } offset += bytesRead; } return Encoding.UTF8.GetString(data, 0, length); } else { int index = ReadCount(); return stringPool[index]; } } /// <summary> /// Reads a signed 16 bit integer value from the stream and returns it as an int. /// </summary> /// <returns>The 16 bit int value.</returns> private int ReadInt16() { unchecked { int high = ReadByte(); int low = ReadByte(); return (high << 8) | low; } } /// <summary> /// Reads a signed 32 bit integer value from the stream and returns it as an int. /// </summary> /// <returns>The 32 bit int value.</returns> private int ReadInt32() { unchecked { int high = ReadInt16() & 0xffff; int low = ReadInt16() & 0xffff; return (high << 16) | low; } } /// <summary> /// Reads a signed 64 bit integer value from the stream and returns it as an long. /// </summary> /// <returns>The 64 bit long value.</returns> private long ReadInt64() { unchecked { long high = ReadInt32() & 0xffffffffL; long low = ReadInt32() & 0xffffffffL; return (high << 32) | low; } } /// <summary> /// Reads a signed 8 bit integer value from the stream and returns it as an int. /// </summary> /// <returns>The 8 bit int value.</returns> /// <exception cref="InvalidNodaDataException">The data in the stream has been exhausted.</exception> /// <inheritdoc /> public byte ReadByte() { if (bufferedByte != null) { byte ret = bufferedByte.Value; bufferedByte = null; return ret; } int value = input.ReadByte(); if (value == -1) { throw new InvalidNodaDataException("Unexpected end of data stream"); } return (byte)value; } } }
// 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.Internal.Resources { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; using Azure.Internal.Subscriptions.Models; /// <summary> /// PolicyDefinitionsOperations operations. /// </summary> internal partial class PolicyDefinitionsOperations : IServiceOperations<PolicyClient>, IPolicyDefinitionsOperations { /// <summary> /// Initializes a new instance of the PolicyDefinitionsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal PolicyDefinitionsOperations(PolicyClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the PolicyClient /// </summary> public PolicyClient Client { get; private set; } /// <summary> /// Creates or updates a policy definition. /// </summary> /// <param name='policyDefinitionName'> /// The name of the policy definition to create. /// </param> /// <param name='parameters'> /// The policy definition properties. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<PolicyDefinition>> CreateOrUpdateWithHttpMessagesAsync(string policyDefinitionName, PolicyDefinition parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (policyDefinitionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "policyDefinitionName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("policyDefinitionName", policyDefinitionName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}").ToString(); _url = _url.Replace("{policyDefinitionName}", Uri.EscapeDataString(policyDefinitionName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<PolicyDefinition>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<PolicyDefinition>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes a policy definition. /// </summary> /// <param name='policyDefinitionName'> /// The name of the policy definition to delete. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string policyDefinitionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (policyDefinitionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "policyDefinitionName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("policyDefinitionName", policyDefinitionName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}").ToString(); _url = _url.Replace("{policyDefinitionName}", Uri.EscapeDataString(policyDefinitionName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the policy definition. /// </summary> /// <param name='policyDefinitionName'> /// The name of the policy definition to get. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<PolicyDefinition>> GetWithHttpMessagesAsync(string policyDefinitionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (policyDefinitionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "policyDefinitionName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("policyDefinitionName", policyDefinitionName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}").ToString(); _url = _url.Replace("{policyDefinitionName}", Uri.EscapeDataString(policyDefinitionName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<PolicyDefinition>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<PolicyDefinition>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the policy definitions for a subscription. /// </summary> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<PolicyDefinition>>> ListWithHttpMessagesAsync(ODataQuery<PolicyDefinition> odataQuery = default(ODataQuery<PolicyDefinition>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<PolicyDefinition>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<PolicyDefinition>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the policy definitions for a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<PolicyDefinition>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<PolicyDefinition>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<PolicyDefinition>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// // AudioCdRipper.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Threading; using System.Runtime.InteropServices; using Mono.Unix; using Hyena; using Banshee.Base; using Banshee.Collection; using Banshee.ServiceStack; using Banshee.MediaEngine; using Banshee.MediaProfiles; using Banshee.Configuration.Schema; namespace Banshee.GStreamer { public class AudioCdRipper : IAudioCdRipper { private HandleRef handle; private string encoder_pipeline; private string output_extension; private string output_path; private TrackInfo current_track; private RipperProgressHandler progress_handler; private RipperMimeTypeHandler mimetype_handler; private RipperFinishedHandler finished_handler; private RipperErrorHandler error_handler; public event AudioCdRipperProgressHandler Progress; public event AudioCdRipperTrackFinishedHandler TrackFinished; public event AudioCdRipperErrorHandler Error; public void Begin (string device, bool enableErrorCorrection) { try { Profile profile = null; ProfileConfiguration config = ServiceManager.MediaProfileManager.GetActiveProfileConfiguration ("cd-importing"); if (config != null) { profile = config.Profile; } else { profile = ServiceManager.MediaProfileManager.GetProfileForMimeType ("audio/vorbis") ?? ServiceManager.MediaProfileManager.GetProfileForMimeType ("audio/flac"); if (profile != null) { Log.InformationFormat ("Using default/fallback encoding profile: {0}", profile.Name); ProfileConfiguration.SaveActiveProfile (profile, "cd-importing"); } } if (profile != null) { encoder_pipeline = profile.Pipeline.GetProcessById ("gstreamer"); output_extension = profile.OutputFileExtension; } if (String.IsNullOrEmpty (encoder_pipeline)) { throw new ApplicationException (); } Hyena.Log.InformationFormat ("Ripping using encoder profile `{0}' with pipeline: {1}", profile.Name, encoder_pipeline); } catch (Exception e) { throw new ApplicationException (Catalog.GetString ("Could not find an encoder for ripping."), e); } try { int paranoia_mode = enableErrorCorrection ? 255 : 0; handle = new HandleRef (this, br_new (device, paranoia_mode, encoder_pipeline)); progress_handler = new RipperProgressHandler (OnNativeProgress); br_set_progress_callback (handle, progress_handler); mimetype_handler = new RipperMimeTypeHandler (OnNativeMimeType); br_set_mimetype_callback (handle, mimetype_handler); finished_handler = new RipperFinishedHandler (OnNativeFinished); br_set_finished_callback (handle, finished_handler); error_handler = new RipperErrorHandler (OnNativeError); br_set_error_callback (handle, error_handler); } catch (Exception e) { throw new ApplicationException (Catalog.GetString ("Could not create CD ripping driver."), e); } } public void Finish () { if (output_path != null) { System.IO.File.Delete (output_path); } TrackReset (); encoder_pipeline = null; output_extension = null; br_destroy (handle); handle = new HandleRef (this, IntPtr.Zero); } public void Cancel () { Finish (); } private void TrackReset () { current_track = null; output_path = null; } public void RipTrack (int trackIndex, TrackInfo track, SafeUri outputUri, out bool taggingSupported) { TrackReset (); current_track = track; using (TagList tags = new TagList (track)) { output_path = String.Format ("{0}.{1}", outputUri.LocalPath, output_extension); Log.DebugFormat ("GStreamer ripping track {0} to {1}", trackIndex, output_path); br_rip_track (handle, trackIndex + 1, output_path, tags.Handle, out taggingSupported); } } protected virtual void OnProgress (TrackInfo track, TimeSpan ellapsedTime) { AudioCdRipperProgressHandler handler = Progress; if (handler != null) { handler (this, new AudioCdRipperProgressArgs (track, ellapsedTime, track.Duration)); } } protected virtual void OnTrackFinished (TrackInfo track, SafeUri outputUri) { AudioCdRipperTrackFinishedHandler handler = TrackFinished; if (handler != null) { handler (this, new AudioCdRipperTrackFinishedArgs (track, outputUri)); } } protected virtual void OnError (TrackInfo track, string message) { AudioCdRipperErrorHandler handler = Error; if (handler != null) { handler (this, new AudioCdRipperErrorArgs (track, message)); } } private void OnNativeProgress (IntPtr ripper, int mseconds) { OnProgress (current_track, TimeSpan.FromMilliseconds (mseconds)); } private void OnNativeMimeType (IntPtr ripper, IntPtr mimetype) { if (mimetype != IntPtr.Zero && current_track != null) { string type = GLib.Marshaller.Utf8PtrToString (mimetype); if (type != null) { string [] split = type.Split (';', '.', ' ', '\t'); if (split != null && split.Length > 0) { current_track.MimeType = split[0].Trim (); } else { current_track.MimeType = type.Trim (); } } } } private void OnNativeFinished (IntPtr ripper) { SafeUri uri = new SafeUri (output_path); TrackInfo track = current_track; TrackReset (); OnTrackFinished (track, uri); } private void OnNativeError (IntPtr ripper, IntPtr error, IntPtr debug) { string error_message = GLib.Marshaller.Utf8PtrToString (error); if (debug != IntPtr.Zero) { string debug_string = GLib.Marshaller.Utf8PtrToString (debug); if (!String.IsNullOrEmpty (debug_string)) { error_message = String.Format ("{0}: {1}", error_message, debug_string); } } OnError (current_track, error_message); } private delegate void RipperProgressHandler (IntPtr ripper, int mseconds); private delegate void RipperMimeTypeHandler (IntPtr ripper, IntPtr mimetype); private delegate void RipperFinishedHandler (IntPtr ripper); private delegate void RipperErrorHandler (IntPtr ripper, IntPtr error, IntPtr debug); [DllImport ("libbanshee.dll")] private static extern IntPtr br_new (string device, int paranoia_mode, string encoder_pipeline); [DllImport ("libbanshee.dll")] private static extern void br_destroy (HandleRef handle); [DllImport ("libbanshee.dll")] private static extern void br_rip_track (HandleRef handle, int track_number, string output_path, HandleRef tag_list, out bool tagging_supported); [DllImport ("libbanshee.dll")] private static extern void br_set_progress_callback (HandleRef handle, RipperProgressHandler callback); [DllImport ("libbanshee.dll")] private static extern void br_set_mimetype_callback (HandleRef handle, RipperMimeTypeHandler callback); [DllImport ("libbanshee.dll")] private static extern void br_set_finished_callback (HandleRef handle, RipperFinishedHandler callback); [DllImport ("libbanshee.dll")] private static extern void br_set_error_callback (HandleRef handle, RipperErrorHandler callback); } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Linq; using System.Windows.Markup; using Prism.Properties; namespace Prism.Modularity { /// <summary> /// The <see cref="ModuleCatalog"/> holds information about the modules that can be used by the /// application. Each module is described in a <see cref="ModuleInfo"/> class, that records the /// name, type and location of the module. /// /// It also verifies that the <see cref="ModuleCatalog"/> is internally valid. That means that /// it does not have: /// <list> /// <item>Circular dependencies</item> /// <item>Missing dependencies</item> /// <item> /// Invalid dependencies, such as a Module that's loaded at startup that depends on a module /// that might need to be retrieved. /// </item> /// </list> /// The <see cref="ModuleCatalog"/> also serves as a baseclass for more specialized Catalogs . /// </summary> [ContentProperty("Items")] public class ModuleCatalog : IModuleCatalog { private readonly ModuleCatalogItemCollection items; private bool isLoaded; /// <summary> /// Initializes a new instance of the <see cref="ModuleCatalog"/> class. /// </summary> public ModuleCatalog() { this.items = new ModuleCatalogItemCollection(); this.items.CollectionChanged += this.ItemsCollectionChanged; } /// <summary> /// Initializes a new instance of the <see cref="ModuleCatalog"/> class while providing an /// initial list of <see cref="ModuleInfo"/>s. /// </summary> /// <param name="modules">The initial list of modules.</param> public ModuleCatalog(IEnumerable<ModuleInfo> modules) : this() { if (modules == null) throw new System.ArgumentNullException("modules"); foreach (ModuleInfo moduleInfo in modules) { this.Items.Add(moduleInfo); } } /// <summary> /// Gets the items in the <see cref="ModuleCatalog"/>. This property is mainly used to add <see cref="ModuleInfoGroup"/>s or /// <see cref="ModuleInfo"/>s through XAML. /// </summary> /// <value>The items in the catalog.</value> public Collection<IModuleCatalogItem> Items { get { return this.items; } } /// <summary> /// Gets all the <see cref="ModuleInfo"/> classes that are in the <see cref="ModuleCatalog"/>, regardless /// if they are within a <see cref="ModuleInfoGroup"/> or not. /// </summary> /// <value>The modules.</value> public virtual IEnumerable<ModuleInfo> Modules { get { return this.GrouplessModules.Union(this.Groups.SelectMany(g => g)); } } /// <summary> /// Gets the <see cref="ModuleInfoGroup"/>s that have been added to the <see cref="ModuleCatalog"/>. /// </summary> /// <value>The groups.</value> public IEnumerable<ModuleInfoGroup> Groups { get { return this.Items.OfType<ModuleInfoGroup>(); } } /// <summary> /// Gets or sets a value that remembers whether the <see cref="ModuleCatalog"/> has been validated already. /// </summary> protected bool Validated { get; set; } /// <summary> /// Returns the list of <see cref="ModuleInfo"/>s that are not contained within any <see cref="ModuleInfoGroup"/>. /// </summary> /// <value>The groupless modules.</value> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Groupless")] protected IEnumerable<ModuleInfo> GrouplessModules { get { return this.Items.OfType<ModuleInfo>(); } } /// <summary> /// Creates a <see cref="ModuleCatalog"/> from XAML. /// </summary> /// <param name="xamlStream"><see cref="Stream"/> that contains the XAML declaration of the catalog.</param> /// <returns>An instance of <see cref="ModuleCatalog"/> built from the XAML.</returns> public static ModuleCatalog CreateFromXaml(Stream xamlStream) { if (xamlStream == null) { throw new ArgumentNullException("xamlStream"); } return XamlReader.Load(xamlStream) as ModuleCatalog; } /// <summary> /// Creates a <see cref="ModuleCatalog"/> from a XAML included as an Application Resource. /// </summary> /// <param name="builderResourceUri">Relative <see cref="Uri"/> that identifies the XAML included as an Application Resource.</param> /// <returns>An instance of <see cref="ModuleCatalog"/> build from the XAML.</returns> public static ModuleCatalog CreateFromXaml(Uri builderResourceUri) { var streamInfo = System.Windows.Application.GetResourceStream(builderResourceUri); if ((streamInfo != null) && (streamInfo.Stream != null)) { return CreateFromXaml(streamInfo.Stream); } return null; } /// <summary> /// Loads the catalog if necessary. /// </summary> public void Load() { this.isLoaded = true; this.InnerLoad(); } /// <summary> /// Return the list of <see cref="ModuleInfo"/>s that <paramref name="moduleInfo"/> depends on. /// </summary> /// <remarks> /// If the <see cref="ModuleCatalog"/> was not yet validated, this method will call <see cref="Validate"/>. /// </remarks> /// <param name="moduleInfo">The <see cref="ModuleInfo"/> to get the </param> /// <returns>An enumeration of <see cref="ModuleInfo"/> that <paramref name="moduleInfo"/> depends on.</returns> public virtual IEnumerable<ModuleInfo> GetDependentModules(ModuleInfo moduleInfo) { this.EnsureCatalogValidated(); return this.GetDependentModulesInner(moduleInfo); } /// <summary> /// Returns a list of <see cref="ModuleInfo"/>s that contain both the <see cref="ModuleInfo"/>s in /// <paramref name="modules"/>, but also all the modules they depend on. /// </summary> /// <param name="modules">The modules to get the dependencies for.</param> /// <returns> /// A list of <see cref="ModuleInfo"/> that contains both all <see cref="ModuleInfo"/>s in <paramref name="modules"/> /// but also all the <see cref="ModuleInfo"/> they depend on. /// </returns> public virtual IEnumerable<ModuleInfo> CompleteListWithDependencies(IEnumerable<ModuleInfo> modules) { if (modules == null) { throw new ArgumentNullException("modules"); } this.EnsureCatalogValidated(); List<ModuleInfo> completeList = new List<ModuleInfo>(); List<ModuleInfo> pendingList = modules.ToList(); while (pendingList.Count > 0) { ModuleInfo moduleInfo = pendingList[0]; foreach (ModuleInfo dependency in this.GetDependentModules(moduleInfo)) { if (!completeList.Contains(dependency) && !pendingList.Contains(dependency)) { pendingList.Add(dependency); } } pendingList.RemoveAt(0); completeList.Add(moduleInfo); } IEnumerable<ModuleInfo> sortedList = this.Sort(completeList); return sortedList; } /// <summary> /// Validates the <see cref="ModuleCatalog"/>. /// </summary> /// <exception cref="ModularityException">When validation of the <see cref="ModuleCatalog"/> fails.</exception> public virtual void Validate() { this.ValidateUniqueModules(); this.ValidateDependencyGraph(); this.ValidateCrossGroupDependencies(); this.ValidateDependenciesInitializationMode(); this.Validated = true; } /// <summary> /// Adds a <see cref="ModuleInfo"/> to the <see cref="ModuleCatalog"/>. /// </summary> /// <param name="moduleInfo">The <see cref="ModuleInfo"/> to add.</param> /// <returns>The <see cref="ModuleCatalog"/> for easily adding multiple modules.</returns> public virtual void AddModule(ModuleInfo moduleInfo) { this.Items.Add(moduleInfo); } /// <summary> /// Adds a groupless <see cref="ModuleInfo"/> to the catalog. /// </summary> /// <param name="moduleType"><see cref="Type"/> of the module to be added.</param> /// <param name="dependsOn">Collection of module names (<see cref="ModuleInfo.ModuleName"/>) of the modules on which the module to be added logically depends on.</param> /// <returns>The same <see cref="ModuleCatalog"/> instance with the added module.</returns> public ModuleCatalog AddModule(Type moduleType, params string[] dependsOn) { return this.AddModule(moduleType, InitializationMode.WhenAvailable, dependsOn); } /// <summary> /// Adds a groupless <see cref="ModuleInfo"/> to the catalog. /// </summary> /// <param name="moduleType"><see cref="Type"/> of the module to be added.</param> /// <param name="initializationMode">Stage on which the module to be added will be initialized.</param> /// <param name="dependsOn">Collection of module names (<see cref="ModuleInfo.ModuleName"/>) of the modules on which the module to be added logically depends on.</param> /// <returns>The same <see cref="ModuleCatalog"/> instance with the added module.</returns> public ModuleCatalog AddModule(Type moduleType, InitializationMode initializationMode, params string[] dependsOn) { if (moduleType == null) throw new System.ArgumentNullException("moduleType"); return this.AddModule(moduleType.Name, moduleType.AssemblyQualifiedName, initializationMode, dependsOn); } /// <summary> /// Adds a groupless <see cref="ModuleInfo"/> to the catalog. /// </summary> /// <param name="moduleName">Name of the module to be added.</param> /// <param name="moduleType"><see cref="Type"/> of the module to be added.</param> /// <param name="dependsOn">Collection of module names (<see cref="ModuleInfo.ModuleName"/>) of the modules on which the module to be added logically depends on.</param> /// <returns>The same <see cref="ModuleCatalog"/> instance with the added module.</returns> public ModuleCatalog AddModule(string moduleName, string moduleType, params string[] dependsOn) { return this.AddModule(moduleName, moduleType, InitializationMode.WhenAvailable, dependsOn); } /// <summary> /// Adds a groupless <see cref="ModuleInfo"/> to the catalog. /// </summary> /// <param name="moduleName">Name of the module to be added.</param> /// <param name="moduleType"><see cref="Type"/> of the module to be added.</param> /// <param name="initializationMode">Stage on which the module to be added will be initialized.</param> /// <param name="dependsOn">Collection of module names (<see cref="ModuleInfo.ModuleName"/>) of the modules on which the module to be added logically depends on.</param> /// <returns>The same <see cref="ModuleCatalog"/> instance with the added module.</returns> public ModuleCatalog AddModule(string moduleName, string moduleType, InitializationMode initializationMode, params string[] dependsOn) { return this.AddModule(moduleName, moduleType, null, initializationMode, dependsOn); } /// <summary> /// Adds a groupless <see cref="ModuleInfo"/> to the catalog. /// </summary> /// <param name="moduleName">Name of the module to be added.</param> /// <param name="moduleType"><see cref="Type"/> of the module to be added.</param> /// <param name="refValue">Reference to the location of the module to be added assembly.</param> /// <param name="initializationMode">Stage on which the module to be added will be initialized.</param> /// <param name="dependsOn">Collection of module names (<see cref="ModuleInfo.ModuleName"/>) of the modules on which the module to be added logically depends on.</param> /// <returns>The same <see cref="ModuleCatalog"/> instance with the added module.</returns> public ModuleCatalog AddModule(string moduleName, string moduleType, string refValue, InitializationMode initializationMode, params string[] dependsOn) { if (moduleName == null) { throw new ArgumentNullException("moduleName"); } if (moduleType == null) { throw new ArgumentNullException("moduleType"); } ModuleInfo moduleInfo = new ModuleInfo(moduleName, moduleType); moduleInfo.DependsOn.AddRange(dependsOn); moduleInfo.InitializationMode = initializationMode; moduleInfo.Ref = refValue; this.Items.Add(moduleInfo); return this; } /// <summary> /// Initializes the catalog, which may load and validate the modules. /// </summary> /// <exception cref="ModularityException">When validation of the <see cref="ModuleCatalog"/> fails, because this method calls <see cref="Validate"/>.</exception> public virtual void Initialize() { if (!this.isLoaded) { this.Load(); } this.Validate(); } /// <summary> /// Creates and adds a <see cref="ModuleInfoGroup"/> to the catalog. /// </summary> /// <param name="initializationMode">Stage on which the module group to be added will be initialized.</param> /// <param name="refValue">Reference to the location of the module group to be added.</param> /// <param name="moduleInfos">Collection of <see cref="ModuleInfo"/> included in the group.</param> /// <returns><see cref="ModuleCatalog"/> with the added module group.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] public virtual ModuleCatalog AddGroup(InitializationMode initializationMode, string refValue, params ModuleInfo[] moduleInfos) { if (moduleInfos == null) throw new System.ArgumentNullException("moduleInfos"); ModuleInfoGroup newGroup = new ModuleInfoGroup(); newGroup.InitializationMode = initializationMode; newGroup.Ref = refValue; foreach (ModuleInfo info in moduleInfos) { newGroup.Add(info); } this.items.Add(newGroup); return this; } /// <summary> /// Checks for cyclic dependencies, by calling the dependencysolver. /// </summary> /// <param name="modules">the.</param> /// <returns></returns> protected static string[] SolveDependencies(IEnumerable<ModuleInfo> modules) { if (modules == null) throw new System.ArgumentNullException("modules"); ModuleDependencySolver solver = new ModuleDependencySolver(); foreach (ModuleInfo data in modules) { solver.AddModule(data.ModuleName); if (data.DependsOn != null) { foreach (string dependency in data.DependsOn) { solver.AddDependency(data.ModuleName, dependency); } } } if (solver.ModuleCount > 0) { return solver.Solve(); } return new string[0]; } /// <summary> /// Ensures that all the dependencies within <paramref name="modules"/> refer to <see cref="ModuleInfo"/>s /// within that list. /// </summary> /// <param name="modules">The modules to validate modules for.</param> /// <exception cref="ModularityException"> /// Throws if a <see cref="ModuleInfo"/> in <paramref name="modules"/> depends on a module that's /// not in <paramref name="modules"/>. /// </exception> /// <exception cref="System.ArgumentNullException">Throws if <paramref name="modules"/> is <see langword="null"/>.</exception> protected static void ValidateDependencies(IEnumerable<ModuleInfo> modules) { if (modules == null) throw new System.ArgumentNullException("modules"); var moduleNames = modules.Select(m => m.ModuleName).ToList(); foreach (ModuleInfo moduleInfo in modules) { if (moduleInfo.DependsOn != null && moduleInfo.DependsOn.Except(moduleNames).Any()) { throw new ModularityException( moduleInfo.ModuleName, String.Format(CultureInfo.CurrentCulture, Resources.ModuleDependenciesNotMetInGroup, moduleInfo.ModuleName)); } } } /// <summary> /// Does the actual work of loading the catalog. The base implementation does nothing. /// </summary> protected virtual void InnerLoad() { } /// <summary> /// Sorts a list of <see cref="ModuleInfo"/>s. This method is called by <see cref="CompleteListWithDependencies"/> /// to return a sorted list. /// </summary> /// <param name="modules">The <see cref="ModuleInfo"/>s to sort.</param> /// <returns>Sorted list of <see cref="ModuleInfo"/>s</returns> protected virtual IEnumerable<ModuleInfo> Sort(IEnumerable<ModuleInfo> modules) { foreach (string moduleName in SolveDependencies(modules)) { yield return modules.First(m => m.ModuleName == moduleName); } } /// <summary> /// Makes sure all modules have an Unique name. /// </summary> /// <exception cref="DuplicateModuleException"> /// Thrown if the names of one or more modules are not unique. /// </exception> protected virtual void ValidateUniqueModules() { List<string> moduleNames = this.Modules.Select(m => m.ModuleName).ToList(); string duplicateModule = moduleNames.FirstOrDefault( m => moduleNames.Count(m2 => m2 == m) > 1); if (duplicateModule != null) { throw new DuplicateModuleException(duplicateModule, String.Format(CultureInfo.CurrentCulture, Resources.DuplicatedModule, duplicateModule)); } } /// <summary> /// Ensures that there are no cyclic dependencies. /// </summary> protected virtual void ValidateDependencyGraph() { SolveDependencies(this.Modules); } /// <summary> /// Ensures that there are no dependencies between modules on different groups. /// </summary> /// <remarks> /// A groupless module can only depend on other groupless modules. /// A module within a group can depend on other modules within the same group and/or on groupless modules. /// </remarks> protected virtual void ValidateCrossGroupDependencies() { ValidateDependencies(this.GrouplessModules); foreach (ModuleInfoGroup group in this.Groups) { ValidateDependencies(this.GrouplessModules.Union(group)); } } /// <summary> /// Ensures that there are no modules marked to be loaded <see cref="InitializationMode.WhenAvailable"/> /// depending on modules loaded <see cref="InitializationMode.OnDemand"/> /// </summary> protected virtual void ValidateDependenciesInitializationMode() { ModuleInfo moduleInfo = this.Modules.FirstOrDefault( m => m.InitializationMode == InitializationMode.WhenAvailable && this.GetDependentModulesInner(m) .Any(dependency => dependency.InitializationMode == InitializationMode.OnDemand)); if (moduleInfo != null) { throw new ModularityException( moduleInfo.ModuleName, String.Format(CultureInfo.CurrentCulture, Resources.StartupModuleDependsOnAnOnDemandModule, moduleInfo.ModuleName)); } } /// <summary> /// Returns the <see cref="ModuleInfo"/> on which the received module dependens on. /// </summary> /// <param name="moduleInfo">Module whose dependant modules are requested.</param> /// <returns>Collection of <see cref="ModuleInfo"/> dependants of <paramref name="moduleInfo"/>.</returns> protected virtual IEnumerable<ModuleInfo> GetDependentModulesInner(ModuleInfo moduleInfo) { return this.Modules.Where(dependantModule => moduleInfo.DependsOn.Contains(dependantModule.ModuleName)); } /// <summary> /// Ensures that the catalog is validated. /// </summary> protected virtual void EnsureCatalogValidated() { if (!this.Validated) { this.Validate(); } } private void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (this.Validated) { this.EnsureCatalogValidated(); } } private class ModuleCatalogItemCollection : Collection<IModuleCatalogItem>, INotifyCollectionChanged { public event NotifyCollectionChangedEventHandler CollectionChanged; protected override void InsertItem(int index, IModuleCatalogItem item) { base.InsertItem(index, item); this.OnNotifyCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index)); } protected void OnNotifyCollectionChanged(NotifyCollectionChangedEventArgs eventArgs) { if (this.CollectionChanged != null) { this.CollectionChanged(this, eventArgs); } } } } }
#region License /* * ResponseStream.cs * * This code is derived from ResponseStream.cs (System.Net) of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2005 Novell, Inc. (http://www.novell.com) * Copyright (c) 2012-2020 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Authors /* * Authors: * - Gonzalo Paniagua Javier <gonzalo@novell.com> */ #endregion using System; using System.IO; using System.Text; namespace WebSocketSharp.Net { internal class ResponseStream : Stream { #region Private Fields private MemoryStream _bodyBuffer; private static readonly byte[] _crlf; private bool _disposed; private Stream _innerStream; private static readonly byte[] _lastChunk; private static readonly int _maxHeadersLength; private HttpListenerResponse _response; private bool _sendChunked; private Action<byte[], int, int> _write; private Action<byte[], int, int> _writeBody; private Action<byte[], int, int> _writeChunked; #endregion #region Static Constructor static ResponseStream () { _crlf = new byte[] { 13, 10 }; // "\r\n" _lastChunk = new byte[] { 48, 13, 10, 13, 10 }; // "0\r\n\r\n" _maxHeadersLength = 32768; } #endregion #region Internal Constructors internal ResponseStream ( Stream innerStream, HttpListenerResponse response, bool ignoreWriteExceptions ) { _innerStream = innerStream; _response = response; if (ignoreWriteExceptions) { _write = writeWithoutThrowingException; _writeChunked = writeChunkedWithoutThrowingException; } else { _write = innerStream.Write; _writeChunked = writeChunked; } _bodyBuffer = new MemoryStream (); } #endregion #region Public Properties public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return !_disposed; } } public override long Length { get { throw new NotSupportedException (); } } public override long Position { get { throw new NotSupportedException (); } set { throw new NotSupportedException (); } } #endregion #region Private Methods private bool flush (bool closing) { if (!_response.HeadersSent) { if (!flushHeaders ()) return false; _response.HeadersSent = true; _sendChunked = _response.SendChunked; _writeBody = _sendChunked ? _writeChunked : _write; } flushBody (closing); return true; } private void flushBody (bool closing) { using (_bodyBuffer) { var len = _bodyBuffer.Length; if (len > Int32.MaxValue) { _bodyBuffer.Position = 0; var buffLen = 1024; var buff = new byte[buffLen]; var nread = 0; while (true) { nread = _bodyBuffer.Read (buff, 0, buffLen); if (nread <= 0) break; _writeBody (buff, 0, nread); } } else if (len > 0) { _writeBody (_bodyBuffer.GetBuffer (), 0, (int) len); } } if (!closing) { _bodyBuffer = new MemoryStream (); return; } if (_sendChunked) _write (_lastChunk, 0, 5); _bodyBuffer = null; } private bool flushHeaders () { if (!_response.SendChunked) { if (_response.ContentLength64 != _bodyBuffer.Length) return false; } var statusLine = _response.StatusLine; var headers = _response.FullHeaders; var buff = new MemoryStream (); var enc = Encoding.UTF8; using (var writer = new StreamWriter (buff, enc, 256)) { writer.Write (statusLine); writer.Write (headers.ToStringMultiValue (true)); writer.Flush (); var start = enc.GetPreamble ().Length; var len = buff.Length - start; if (len > _maxHeadersLength) return false; _write (buff.GetBuffer (), start, (int) len); } _response.CloseConnection = headers["Connection"] == "close"; return true; } private static byte[] getChunkSizeBytes (int size) { var chunkSize = String.Format ("{0:x}\r\n", size); return Encoding.ASCII.GetBytes (chunkSize); } private void writeChunked (byte[] buffer, int offset, int count) { var size = getChunkSizeBytes (count); _innerStream.Write (size, 0, size.Length); _innerStream.Write (buffer, offset, count); _innerStream.Write (_crlf, 0, 2); } private void writeChunkedWithoutThrowingException ( byte[] buffer, int offset, int count ) { try { writeChunked (buffer, offset, count); } catch { } } private void writeWithoutThrowingException ( byte[] buffer, int offset, int count ) { try { _innerStream.Write (buffer, offset, count); } catch { } } #endregion #region Internal Methods internal void Close (bool force) { if (_disposed) return; _disposed = true; if (!force) { if (flush (true)) { _response.Close (); _response = null; _innerStream = null; return; } _response.CloseConnection = true; } if (_sendChunked) _write (_lastChunk, 0, 5); _bodyBuffer.Dispose (); _response.Abort (); _bodyBuffer = null; _response = null; _innerStream = null; } internal void InternalWrite (byte[] buffer, int offset, int count) { _write (buffer, offset, count); } #endregion #region Public Methods public override IAsyncResult BeginRead ( byte[] buffer, int offset, int count, AsyncCallback callback, object state ) { throw new NotSupportedException (); } public override IAsyncResult BeginWrite ( byte[] buffer, int offset, int count, AsyncCallback callback, object state ) { if (_disposed) { var name = GetType ().ToString (); throw new ObjectDisposedException (name); } return _bodyBuffer.BeginWrite (buffer, offset, count, callback, state); } public override void Close () { Close (false); } protected override void Dispose (bool disposing) { Close (!disposing); } public override int EndRead (IAsyncResult asyncResult) { throw new NotSupportedException (); } public override void EndWrite (IAsyncResult asyncResult) { if (_disposed) { var name = GetType ().ToString (); throw new ObjectDisposedException (name); } _bodyBuffer.EndWrite (asyncResult); } public override void Flush () { if (_disposed) return; var sendChunked = _sendChunked || _response.SendChunked; if (!sendChunked) return; flush (false); } public override int Read (byte[] buffer, int offset, int count) { throw new NotSupportedException (); } public override long Seek (long offset, SeekOrigin origin) { throw new NotSupportedException (); } public override void SetLength (long value) { throw new NotSupportedException (); } public override void Write (byte[] buffer, int offset, int count) { if (_disposed) { var name = GetType ().ToString (); throw new ObjectDisposedException (name); } _bodyBuffer.Write (buffer, offset, count); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class OVRSceneLoader : MonoBehaviour { public const string externalStoragePath = "/sdcard/Android/data"; public const string sceneLoadDataName = "SceneLoadData.txt"; public const string resourceBundleName = "asset_resources"; public float sceneCheckIntervalSeconds = 1f; public float logCloseTime = 5.0f; public Canvas mainCanvas; public Text logTextBox; private AsyncOperation loadSceneOperation; private string formattedLogText; private float closeLogTimer; private bool closeLogDialogue; private bool canvasPosUpdated; private struct SceneInfo { public List<string> scenes; public long version; public SceneInfo(List<string> sceneList, long currentSceneEpochVersion) { scenes = sceneList; version = currentSceneEpochVersion; } } private string scenePath = ""; private string sceneLoadDataPath = ""; private List<AssetBundle> loadedAssetBundles = new List<AssetBundle>(); private SceneInfo currentSceneInfo; private void Awake() { // Make it presist across scene to continue checking for changes DontDestroyOnLoad(this.gameObject); } void Start() { string applicationPath = Path.Combine(externalStoragePath, Application.identifier); scenePath = Path.Combine(applicationPath, "cache/scenes"); sceneLoadDataPath = Path.Combine(scenePath, sceneLoadDataName); closeLogDialogue = false; StartCoroutine(DelayCanvasPosUpdate()); currentSceneInfo = GetSceneInfo(); // Check valid scene info has been fetched, and load the scenes if (currentSceneInfo.version != 0 && !string.IsNullOrEmpty(currentSceneInfo.scenes[0])) { LoadScene(currentSceneInfo); } } private void LoadScene(SceneInfo sceneInfo) { AssetBundle mainSceneBundle = null; Debug.Log("[OVRSceneLoader] Loading main scene: " + sceneInfo.scenes[0] + " with version " + sceneInfo.version.ToString()); logTextBox.text += "Target Scene: " + sceneInfo.scenes[0] + "\n"; logTextBox.text += "Version: " + sceneInfo.version.ToString() + "\n"; // Load main scene and dependent additive scenes (if any) Debug.Log("[OVRSceneLoader] Loading scene bundle files."); // Fetch all files under scene cache path, excluding unnecessary files such as scene metadata file string[] bundles = Directory.GetFiles(scenePath, "*_*"); logTextBox.text += "Loading " + bundles.Length + " bundle(s) . . . "; string mainSceneBundleFileName = "scene_" + sceneInfo.scenes[0].ToLower(); try { foreach (string b in bundles) { var assetBundle = AssetBundle.LoadFromFile(b); if (assetBundle != null) { Debug.Log("[OVRSceneLoader] Loading file bundle: " + assetBundle.name == null ? "null" : assetBundle.name); loadedAssetBundles.Add(assetBundle); } else { Debug.LogError("[OVRSceneLoader] Loading file bundle failed"); } if (assetBundle.name == mainSceneBundleFileName) { mainSceneBundle = assetBundle; } if (assetBundle.name == resourceBundleName) { OVRResources.SetResourceBundle(assetBundle); } } } catch(Exception e) { logTextBox.text += "<color=red>" + e.Message + "</color>"; return; } logTextBox.text += "<color=green>DONE\n</color>"; if (mainSceneBundle != null) { logTextBox.text += "Loading Scene: {0:P0}\n"; formattedLogText = logTextBox.text; string[] scenePaths = mainSceneBundle.GetAllScenePaths(); string sceneName = Path.GetFileNameWithoutExtension(scenePaths[0]); loadSceneOperation = SceneManager.LoadSceneAsync(sceneName); loadSceneOperation.completed += LoadSceneOperation_completed; } else { logTextBox.text += "<color=red>Failed to get main scene bundle.\n</color>"; } } private void LoadSceneOperation_completed(AsyncOperation obj) { StartCoroutine(onCheckSceneCoroutine()); StartCoroutine(DelayCanvasPosUpdate()); closeLogTimer = 0; closeLogDialogue = true; logTextBox.text += "Log closing in {0} seconds.\n"; formattedLogText = logTextBox.text; } public void Update() { // Display scene load percentage if (loadSceneOperation != null) { if (!loadSceneOperation.isDone) { logTextBox.text = string.Format(formattedLogText, loadSceneOperation.progress + 0.1f); if (loadSceneOperation.progress >= 0.9f) { logTextBox.text = formattedLogText.Replace("{0:P0}", "<color=green>DONE</color>"); logTextBox.text += "Transitioning to new scene.\nLoad times will vary depending on scene complexity.\n"; } } } UpdateCanvasPosition(); // Wait a certain time before closing the log dialogue after the scene has transitioned if (closeLogDialogue) { if (closeLogTimer < logCloseTime) { closeLogTimer += Time.deltaTime; logTextBox.text = string.Format(formattedLogText, (int)(logCloseTime - closeLogTimer)); } else { mainCanvas.gameObject.SetActive(false); closeLogDialogue = false; } } } private void UpdateCanvasPosition() { // Update canvas camera reference and position if the main camera has changed if (mainCanvas.worldCamera != Camera.main) { mainCanvas.worldCamera = Camera.main; if (Camera.main != null) { Vector3 newPosition = Camera.main.transform.position + Camera.main.transform.forward * 0.3f; gameObject.transform.position = newPosition; gameObject.transform.rotation = Camera.main.transform.rotation; } } } private SceneInfo GetSceneInfo() { SceneInfo sceneInfo = new SceneInfo(); try { StreamReader reader = new StreamReader(sceneLoadDataPath); sceneInfo.version = System.Convert.ToInt64(reader.ReadLine()); List<string> sceneList = new List<string>(); while (!reader.EndOfStream) { sceneList.Add(reader.ReadLine()); } sceneInfo.scenes = sceneList; } catch { logTextBox.text += "<color=red>Failed to get scene info data.\n</color>"; } return sceneInfo; } // Update canvas position after a slight delay to get accurate headset position after scene transitions IEnumerator DelayCanvasPosUpdate() { yield return new WaitForSeconds(0.1f); UpdateCanvasPosition(); } IEnumerator onCheckSceneCoroutine() { SceneInfo newSceneInfo; while (true) { newSceneInfo = GetSceneInfo(); if (newSceneInfo.version != currentSceneInfo.version) { Debug.Log("[OVRSceneLoader] Scene change detected."); // Unload all asset bundles foreach (var b in loadedAssetBundles) { if (b != null) { b.Unload(true); } } loadedAssetBundles.Clear(); // Unload all scenes in the hierarchy including main scene and // its dependent additive scenes. int activeScenes = SceneManager.sceneCount; for (int i = 0; i < activeScenes; i++) { SceneManager.UnloadSceneAsync(SceneManager.GetSceneAt(i)); } DestroyAllGameObjects(); SceneManager.LoadSceneAsync("OVRTransitionScene"); break; } yield return new WaitForSeconds(sceneCheckIntervalSeconds); } } void DestroyAllGameObjects() { foreach (GameObject go in Resources.FindObjectsOfTypeAll(typeof(GameObject)) as GameObject[]) { Destroy(go); } } }
using AutoMapper; using Microsoft.Azure.Commands.Compute.Common; using Microsoft.Azure.Commands.Compute.Models; using Microsoft.Azure.Commands.Common.Authentication.Models; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Management.Automation; using System.Text.RegularExpressions; using Microsoft.Azure.Commands.Common.Authentication.Abstractions; using Newtonsoft.Json; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; namespace Microsoft.Azure.Commands.Compute.Extension.DSC { [Cmdlet( VerbsCommon.Set, ProfileNouns.VirtualMachineDscExtension, SupportsShouldProcess = true, DefaultParameterSetName = AzureBlobDscExtensionParamSet)] [OutputType(typeof(PSAzureOperationResponse))] public class SetAzureVMDscExtensionCommand : VirtualMachineExtensionBaseCmdlet { protected const string AzureBlobDscExtensionParamSet = "AzureBlobDscExtension"; [Parameter( Mandatory = true, Position = 2, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the resource group that contains the virtual machine.")] [ResourceGroupCompleter()] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } [Parameter( Mandatory = true, Position = 3, ValueFromPipelineByPropertyName = true, HelpMessage = "Name of the virtual machine where dsc extension handler would be installed.")] [ValidateNotNullOrEmpty] public string VMName { get; set; } [Parameter( ValueFromPipelineByPropertyName = true, HelpMessage = "Name of the ARM resource that represents the extension. This is defaulted to 'Microsoft.Powershell.DSC'")] [ValidateNotNullOrEmpty] public string Name { get; set; } /// <summary> /// The name of the configuration archive that was previously uploaded by /// Publish-AzureRmVMDSCConfiguration. This parameter must specify only the name /// of the file, without any path. /// A null value or empty string indicate that the VM extension should install DSC, /// but not start any configuration /// </summary> [Alias("ConfigurationArchiveBlob")] [Parameter( Mandatory = true, Position = 5, ValueFromPipelineByPropertyName = true, ParameterSetName = AzureBlobDscExtensionParamSet, HelpMessage = "The name of the configuration file that was previously uploaded by Publish-AzureRmVMDSCConfiguration")] [AllowEmptyString] [AllowNull] public string ArchiveBlobName { get; set; } /// <summary> /// The Azure Storage Account name used to upload the configuration script to the container specified by ArchiveContainerName. /// </summary> [Alias("StorageAccountName")] [Parameter( Mandatory = true, Position = 4, ValueFromPipelineByPropertyName = true, ParameterSetName = AzureBlobDscExtensionParamSet, HelpMessage = "The Azure Storage Account name used to download the ArchiveBlobName")] [ValidateNotNullOrEmpty] public String ArchiveStorageAccountName { get; set; } [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = AzureBlobDscExtensionParamSet, HelpMessage = "The name of the resource group that contains the storage account containing the configuration archive. " + "This param is optional if storage account and virtual machine both exists in the same resource group name, " + "specified by ResourceGroupName param.")] [ValidateNotNullOrEmpty] public string ArchiveResourceGroupName { get; set; } /// <summary> /// The DNS endpoint suffix for all storage services, e.g. "core.windows.net". /// </summary> [Alias("StorageEndpointSuffix")] [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = AzureBlobDscExtensionParamSet, HelpMessage = "The Storage Endpoint Suffix.")] [ValidateNotNullOrEmpty] public string ArchiveStorageEndpointSuffix { get; set; } /// <summary> /// Name of the Azure Storage Container where the configuration script is located. /// </summary> [Alias("ContainerName")] [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = AzureBlobDscExtensionParamSet, HelpMessage = "Name of the Azure Storage Container where the configuration archive is located")] [ValidateNotNullOrEmpty] public string ArchiveContainerName { get; set; } /// <summary> /// Name of the configuration that will be invoked by the DSC Extension. The value of this parameter should be the name of one of the configurations /// contained within the file specified by ArchiveBlobName. /// /// If omitted, this parameter will default to the name of the file given by the ArchiveBlobName parameter, excluding any extension, for example if /// ArchiveBlobName is "SalesWebSite.ps1", the default value for ConfigurationName will be "SalesWebSite". /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, HelpMessage = "Name of the configuration that will be invoked by the DSC Extension")] [ValidateNotNullOrEmpty] public string ConfigurationName { get; set; } /// <summary> /// A hashtable specifying the arguments to the ConfigurationFunction. The keys /// correspond to the parameter names and the values to the parameter values. /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, HelpMessage = "A hashtable specifying the arguments to the ConfigurationFunction")] [ValidateNotNullOrEmpty] public Hashtable ConfigurationArgument { get; set; } /// <summary> /// Path to a .psd1 file that specifies the data for the Configuration. This /// file must contain a hashtable with the items described in /// http://technet.microsoft.com/en-us/library/dn249925.aspx. /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, HelpMessage = "Path to a .psd1 file that specifies the data for the Configuration")] [ValidateNotNullOrEmpty] public string ConfigurationData { get; set; } /// <summary> /// The specific version of the DSC extension that Set-AzureRmVMDSCExtension will /// apply the settings to. /// </summary> [Alias("HandlerVersion")] [Parameter( Mandatory = true, Position = 1, ValueFromPipelineByPropertyName = true, HelpMessage = "The version of the DSC extension that Set-AzureRmVMDSCExtension will apply the settings to. " + "Allowed format N.N")] [ValidateNotNullOrEmpty] public string Version { get; set; } /// <summary> /// By default Set-AzureRmVMDscExtension will not overwrite any existing blobs. Use -Force to overwrite them. /// </summary> [Parameter( HelpMessage = "Use this parameter to overwrite any existing blobs")] public SwitchParameter Force { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Location of the resource.")] [ValidateNotNullOrEmpty] public string Location { get; set; } /// <summary> /// We install the extension handler version specified by the version param. By default extension handler is not autoupdated. /// Use -AutoUpdate to enable auto update of extension handler to the latest version as and when it is available. /// </summary> [Parameter( HelpMessage = "Extension handler gets auto updated to the latest version if this switch is present.")] public SwitchParameter AutoUpdate { get; set; } /// <summary> /// Specifies the version of the Windows Management Framework (WMF) to install /// on the VM. /// /// The DSC Azure Extension depends on DSC features that are only available in /// the WMF updates. This parameter specifies which version of the update to /// install on the VM. The possible values are "4.0","latest" and "5.0PP". /// /// A value of "4.0" will install KB3000850 /// (http://support.microsoft.com/kb/3000850) on Windows 8.1 or Windows Server /// 2012 R2, or WMF 4.0 /// (http://www.microsoft.com/en-us/download/details.aspx?id=40855) on other /// versions of Windows if a newer version isnt already installed. /// /// A value of "5.0PP" will install the latest release of WMF 5.0PP /// (http://go.microsoft.com/fwlink/?LinkId=398175). /// /// A value of "latest" will install the latest WMF, currently WMF 5.0PP /// /// The default value is "latest" /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] [ValidateSetAttribute(new[] { "4.0", "latest", "5.0PP" })] public string WmfVersion { get; set; } /// <summary> /// The Extension Data Collection state /// </summary> [Parameter(ValueFromPipelineByPropertyName = true, HelpMessage = "Enables or Disables Data Collection in the extension. It is enabled if it is not specified. " + "The value is persisted in the extension between calls.") ] [ValidateSet("Enable", "Disable")] [AllowNull] public string DataCollection { get; set; } //Private Variables private const string VersionRegexExpr = @"^(([0-9])\.)\d+$"; /// <summary> /// Credentials used to access Azure Storage /// </summary> private StorageCredentials _storageCredentials; public override void ExecuteCmdlet() { base.ExecuteCmdlet(); ValidateParameters(); CreateConfiguration(); } //Private Methods private void ValidateParameters() { if (string.IsNullOrEmpty(ArchiveBlobName)) { if (ConfigurationName != null || ConfigurationArgument != null || ConfigurationData != null) { this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscNullArchiveNoConfiguragionParameters); } if (ArchiveContainerName != null || ArchiveStorageEndpointSuffix != null) { this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscNullArchiveNoStorageParameters); } } else { if (string.Compare( Path.GetFileName(ArchiveBlobName), ArchiveBlobName, StringComparison.InvariantCultureIgnoreCase) != 0) { this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscConfigurationDataFileShouldNotIncludePath); } if (ConfigurationData != null) { ConfigurationData = GetUnresolvedProviderPathFromPSPath(ConfigurationData); if (!File.Exists(ConfigurationData)) { this.ThrowInvalidArgumentError( Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscCannotFindConfigurationDataFile, ConfigurationData); } if (string.Compare( Path.GetExtension(ConfigurationData), ".psd1", StringComparison.InvariantCultureIgnoreCase) != 0) { this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscInvalidConfigurationDataFile); } } if (ArchiveResourceGroupName == null) { ArchiveResourceGroupName = ResourceGroupName; } _storageCredentials = this.GetStorageCredentials(ArchiveResourceGroupName, ArchiveStorageAccountName); if (ConfigurationName == null) { ConfigurationName = Path.GetFileNameWithoutExtension(ArchiveBlobName); } if (ArchiveContainerName == null) { ArchiveContainerName = DscExtensionCmdletConstants.DefaultContainerName; } if (ArchiveStorageEndpointSuffix == null) { ArchiveStorageEndpointSuffix = DefaultProfile.DefaultContext.Environment.GetEndpoint(AzureEnvironment.Endpoint.StorageEndpointSuffix); } if (!(Regex.Match(Version, VersionRegexExpr).Success)) { this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscExtensionInvalidVersion); } } } private void CreateConfiguration() { var publicSettings = new DscExtensionPublicSettings(); var privateSettings = new DscExtensionPrivateSettings(); if (!string.IsNullOrEmpty(ArchiveBlobName)) { ConfigurationUris configurationUris = UploadConfigurationDataToBlob(); publicSettings.SasToken = configurationUris.SasToken; publicSettings.ModulesUrl = configurationUris.ModulesUrl; Hashtable privacySetting = new Hashtable(); privacySetting.Add("DataCollection", DataCollection); publicSettings.Privacy = privacySetting; publicSettings.ConfigurationFunction = string.Format( CultureInfo.InvariantCulture, "{0}\\{1}", Path.GetFileNameWithoutExtension(ArchiveBlobName), ConfigurationName); Tuple<DscExtensionPublicSettings.Property[], Hashtable> settings = DscExtensionSettingsSerializer.SeparatePrivateItems(ConfigurationArgument); publicSettings.Properties = settings.Item1; privateSettings.Items = settings.Item2; privateSettings.DataBlobUri = configurationUris.DataBlobUri; if (!string.IsNullOrEmpty(WmfVersion)) { publicSettings.WmfVersion = WmfVersion; } } if (string.IsNullOrEmpty(this.Location)) { this.Location = GetLocationFromVm(this.ResourceGroupName, this.VMName); } var parameters = new VirtualMachineExtension { Location = this.Location, Publisher = DscExtensionCmdletConstants.ExtensionPublishedNamespace, VirtualMachineExtensionType = DscExtensionCmdletConstants.ExtensionPublishedName, TypeHandlerVersion = Version, // Define the public and private property bags that will be passed to the extension. Settings = publicSettings, //PrivateConfuguration contains sensitive data in a plain text ProtectedSettings = privateSettings, AutoUpgradeMinorVersion = AutoUpdate.IsPresent }; //Add retry logic due to CRP service restart known issue CRP bug: 3564713 var count = 1; Rest.Azure.AzureOperationResponse<VirtualMachineExtension> op = null; while (count <= 2) { try { op = VirtualMachineExtensionClient.CreateOrUpdateWithHttpMessagesAsync( ResourceGroupName, VMName, Name ?? DscExtensionCmdletConstants.ExtensionPublishedNamespace + "." + DscExtensionCmdletConstants.ExtensionPublishedName, parameters).GetAwaiter().GetResult(); } catch (Rest.Azure.CloudException ex) { var errorReturned = JsonConvert.DeserializeObject<ComputeLongRunningOperationError>(ex.Response.Content); if ("Failed".Equals(errorReturned.Status) && errorReturned.Error != null && "InternalExecutionError".Equals(errorReturned.Error.Code)) { count++; } else { break; } } } var result = Mapper.Map<PSAzureOperationResponse>(op); WriteObject(result); } /// <summary> /// Uploading configuration data to blob storage. /// </summary> /// <returns>ConfigurationUris collection that represent artifacts of uploading</returns> private ConfigurationUris UploadConfigurationDataToBlob() { // // Get a reference to the container in blob storage // var storageAccount = new CloudStorageAccount(_storageCredentials, ArchiveStorageEndpointSuffix, true); var blobClient = storageAccount.CreateCloudBlobClient(); var containerReference = blobClient.GetContainerReference(ArchiveContainerName); // // Get a reference to the configuration blob and create a SAS token to access it // var blobAccessPolicy = new SharedAccessBlobPolicy { SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1), Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Delete }; var configurationBlobName = ArchiveBlobName; var configurationBlobReference = containerReference.GetBlockBlobReference(configurationBlobName); var configurationBlobSasToken = configurationBlobReference.GetSharedAccessSignature(blobAccessPolicy); // // Upload the configuration data to blob storage and get a SAS token // string configurationDataBlobUri = null; if (ConfigurationData != null) { var guid = Guid.NewGuid(); // there may be multiple VMs using the same configuration var configurationDataBlobName = string.Format( CultureInfo.InvariantCulture, "{0}-{1}.psd1", ConfigurationName, guid); var configurationDataBlobReference = containerReference.GetBlockBlobReference(configurationDataBlobName); ConfirmAction( true, string.Empty, string.Format( CultureInfo.CurrentUICulture, Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscUploadToBlobStorageAction, ConfigurationData), configurationDataBlobReference.Uri.AbsoluteUri, () => { if (!Force && configurationDataBlobReference.Exists()) { ThrowTerminatingError( new ErrorRecord( new UnauthorizedAccessException( string.Format( CultureInfo.CurrentUICulture, Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscStorageBlobAlreadyExists, configurationDataBlobName)), "StorageBlobAlreadyExists", ErrorCategory.PermissionDenied, null)); } //HACK //configurationDataBlobReference.UploadFromFile(ConfigurationData, FileMode.Open); var configurationDataBlobSasToken = configurationDataBlobReference.GetSharedAccessSignature(blobAccessPolicy); configurationDataBlobUri = configurationDataBlobReference.StorageUri.PrimaryUri.AbsoluteUri + configurationDataBlobSasToken; }); } return new ConfigurationUris { ModulesUrl = configurationBlobReference.StorageUri.PrimaryUri.AbsoluteUri, SasToken = configurationBlobSasToken, DataBlobUri = configurationDataBlobUri }; } /// <summary> /// Class represent info about uploaded Configuration. /// </summary> private class ConfigurationUris { public string SasToken { get; set; } public string DataBlobUri { get; set; } public string ModulesUrl { get; set; } } } }
using System; using SharpBox2D.Collision.Shapes; using SharpBox2D.Common; using SharpBox2D.Dynamics; using SharpBox2D.Dynamics.Joints; namespace SharpBox2D.TestBed.Profile.Worlds { public class PistonWorld : PerformanceTestWorld { public float timeStep = 1f / 60; public int velIters = 8; public int posIters = 3; public RevoluteJoint m_joint1; public PrismaticJoint m_joint2; public World world; public PistonWorld() {} public void setupWorld(World world) { this.world = world; Body ground = null; { BodyDef bd = new BodyDef(); ground = world.createBody(bd); PolygonShape shape = new PolygonShape(); shape.setAsBox(5.0f, 100.0f); bd = new BodyDef(); bd.type = BodyType.STATIC; FixtureDef sides = new FixtureDef(); sides.shape = shape; sides.density = 0; sides.friction = 0; sides.restitution = .8f; sides.filter.categoryBits = 4; sides.filter.maskBits = 2; bd.position.set(-10.01f, 50.0f); Body bod = world.createBody(bd); bod.createFixture(sides); bd.position.set(10.01f, 50.0f); bod = world.createBody(bd); bod.createFixture(sides); } // turney { CircleShape cd; FixtureDef fd = new FixtureDef(); BodyDef bd = new BodyDef(); bd.type = BodyType.DYNAMIC; int numPieces = 5; float radius = 4f; bd.position = new Vec2(0.0f, 25.0f); Body body = world.createBody(bd); for (int i = 0; i < numPieces; i++) { cd = new CircleShape(); cd.m_radius = .5f; fd.shape = cd; fd.density = 25; fd.friction = .1f; fd.restitution = .9f; float xPos = radius * (float) System.Math.Cos(2f * System.Math.PI * (i / (float) (numPieces))); float yPos = radius * (float) System.Math.Sin(2f * System.Math.PI * (i / (float) (numPieces))); cd.m_p.set(xPos, yPos); body.createFixture(fd); } RevoluteJointDef rjd = new RevoluteJointDef(); rjd.initialize(body, ground, body.getPosition()); rjd.motorSpeed = MathUtils.PI; rjd.maxMotorTorque = 1000000.0f; rjd.enableMotor = true; world.createJoint(rjd); } { Body prevBody = ground; // Define crank. { PolygonShape shape = new PolygonShape(); shape.setAsBox(0.5f, 2.0f); BodyDef bd = new BodyDef(); bd.type = BodyType.DYNAMIC; bd.position.set(0.0f, 7.0f); Body body = world.createBody(bd); body.createFixture(shape, 2.0f); RevoluteJointDef rjd = new RevoluteJointDef(); rjd.initialize(prevBody, body, new Vec2(0.0f, 5.0f)); rjd.motorSpeed = 1.0f * MathUtils.PI; rjd.maxMotorTorque = 20000; rjd.enableMotor = true; m_joint1 = (RevoluteJoint) world.createJoint(rjd); prevBody = body; } // Define follower. { PolygonShape shape = new PolygonShape(); shape.setAsBox(0.5f, 4.0f); BodyDef bd = new BodyDef(); bd.type = BodyType.DYNAMIC; bd.position.set(0.0f, 13.0f); Body body = world.createBody(bd); body.createFixture(shape, 2.0f); RevoluteJointDef rjd = new RevoluteJointDef(); rjd.initialize(prevBody, body, new Vec2(0.0f, 9.0f)); rjd.enableMotor = false; world.createJoint(rjd); prevBody = body; } // Define piston { PolygonShape shape = new PolygonShape(); shape.setAsBox(7f, 2f); BodyDef bd = new BodyDef(); bd.type = BodyType.DYNAMIC; bd.position.set(0.0f, 17.0f); Body body = world.createBody(bd); FixtureDef piston = new FixtureDef(); piston.shape = shape; piston.density = 2; piston.filter.categoryBits = 1; piston.filter.maskBits = 2; body.createFixture(piston); RevoluteJointDef rjd = new RevoluteJointDef(); rjd.initialize(prevBody, body, new Vec2(0.0f, 17.0f)); world.createJoint(rjd); PrismaticJointDef pjd = new PrismaticJointDef(); pjd.initialize(ground, body, new Vec2(0.0f, 17.0f), new Vec2(0.0f, 1.0f)); pjd.maxMotorForce = 1000.0f; pjd.enableMotor = true; m_joint2 = (PrismaticJoint) world.createJoint(pjd); } // Create a payload { PolygonShape sd = new PolygonShape(); BodyDef bd = new BodyDef(); bd.type = BodyType.DYNAMIC; FixtureDef fixture = new FixtureDef(); Body body; for (int i = 0; i < 100; ++i) { sd.setAsBox(0.4f, 0.3f); bd.position.set(-1.0f, 23.0f + i); bd.bullet = false; body = world.createBody(bd); fixture.shape = sd; fixture.density = .1f; fixture.filter.categoryBits = 2; fixture.filter.maskBits = 1 | 4 | 2; body.createFixture(fixture); } CircleShape cd = new CircleShape(); cd.m_radius = 0.36f; for (int i = 0; i < 100; ++i) { bd.position.set(1.0f, 23.0f + i); bd.bullet = false; fixture.shape = cd; fixture.density = 2f; fixture.filter.categoryBits = 2; fixture.filter.maskBits = 1 | 4 | 2; body = world.createBody(bd); body.createFixture(fixture); } float angle = 0.0f; float delta = MathUtils.PI / 3.0f; Vec2[] vertices = new Vec2[6]; for (int i = 0; i < 6; ++i) { vertices[i] = new Vec2(0.3f * MathUtils.cos(angle), 0.3f * MathUtils.sin(angle)); angle += delta; } PolygonShape shape = new PolygonShape(); shape.set(vertices, 6); for (int i = 0; i < 100; ++i) { bd.position.set(0f, 23.0f + i); bd.type = BodyType.DYNAMIC; bd.fixedRotation = true; bd.bullet = false; fixture.shape = shape; fixture.density = 1f; fixture.filter.categoryBits = 2; fixture.filter.maskBits = 1 | 4 | 2; body = world.createBody(bd); body.createFixture(fixture); } } } } public void step() { world.step(timeStep, posIters, velIters); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System { using System; using System.Globalization; using System.Text; using Microsoft.Win32; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Diagnostics.Contracts; // Represents a Globally Unique Identifier. [StructLayout(LayoutKind.Sequential)] [Serializable] [System.Runtime.InteropServices.ComVisible(true)] [System.Runtime.Versioning.NonVersionable] // This only applies to field layout public struct Guid : IFormattable, IComparable , IComparable<Guid>, IEquatable<Guid> { public static readonly Guid Empty = new Guid(); //////////////////////////////////////////////////////////////////////////////// // Member variables //////////////////////////////////////////////////////////////////////////////// private int _a; private short _b; private short _c; private byte _d; private byte _e; private byte _f; private byte _g; private byte _h; private byte _i; private byte _j; private byte _k; //////////////////////////////////////////////////////////////////////////////// // Constructors //////////////////////////////////////////////////////////////////////////////// // Creates a new guid from an array of bytes. // public Guid(byte[] b) { if (b==null) throw new ArgumentNullException("b"); if (b.Length != 16) throw new ArgumentException(Environment.GetResourceString("Arg_GuidArrayCtor", "16")); Contract.EndContractBlock(); _a = ((int)b[3] << 24) | ((int)b[2] << 16) | ((int)b[1] << 8) | b[0]; _b = (short)(((int)b[5] << 8) | b[4]); _c = (short)(((int)b[7] << 8) | b[6]); _d = b[8]; _e = b[9]; _f = b[10]; _g = b[11]; _h = b[12]; _i = b[13]; _j = b[14]; _k = b[15]; } [CLSCompliant(false)] public Guid (uint a, ushort b, ushort c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { _a = (int)a; _b = (short)b; _c = (short)c; _d = d; _e = e; _f = f; _g = g; _h = h; _i = i; _j = j; _k = k; } // Creates a new GUID initialized to the value represented by the arguments. // public Guid(int a, short b, short c, byte[] d) { if (d==null) throw new ArgumentNullException("d"); // Check that array is not too big if(d.Length != 8) throw new ArgumentException(Environment.GetResourceString("Arg_GuidArrayCtor", "8")); Contract.EndContractBlock(); _a = a; _b = b; _c = c; _d = d[0]; _e = d[1]; _f = d[2]; _g = d[3]; _h = d[4]; _i = d[5]; _j = d[6]; _k = d[7]; } // Creates a new GUID initialized to the value represented by the // arguments. The bytes are specified like this to avoid endianness issues. // public Guid(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { _a = a; _b = b; _c = c; _d = d; _e = e; _f = f; _g = g; _h = h; _i = i; _j = j; _k = k; } [Flags] private enum GuidStyles { None = 0x00000000, AllowParenthesis = 0x00000001, //Allow the guid to be enclosed in parens AllowBraces = 0x00000002, //Allow the guid to be enclosed in braces AllowDashes = 0x00000004, //Allow the guid to contain dash group separators AllowHexPrefix = 0x00000008, //Allow the guid to contain {0xdd,0xdd} RequireParenthesis = 0x00000010, //Require the guid to be enclosed in parens RequireBraces = 0x00000020, //Require the guid to be enclosed in braces RequireDashes = 0x00000040, //Require the guid to contain dash group separators RequireHexPrefix = 0x00000080, //Require the guid to contain {0xdd,0xdd} HexFormat = RequireBraces | RequireHexPrefix, /* X */ NumberFormat = None, /* N */ DigitFormat = RequireDashes, /* D */ BraceFormat = RequireBraces | RequireDashes, /* B */ ParenthesisFormat = RequireParenthesis | RequireDashes, /* P */ Any = AllowParenthesis | AllowBraces | AllowDashes | AllowHexPrefix, } private enum GuidParseThrowStyle { None = 0, All = 1, AllButOverflow = 2 } private enum ParseFailureKind { None = 0, ArgumentNull = 1, Format = 2, FormatWithParameter = 3, NativeException = 4, FormatWithInnerException = 5 } // This will store the result of the parsing. And it will eventually be used to construct a Guid instance. private struct GuidResult { internal Guid parsedGuid; internal GuidParseThrowStyle throwStyle; internal ParseFailureKind m_failure; internal string m_failureMessageID; internal object m_failureMessageFormatArgument; internal string m_failureArgumentName; internal Exception m_innerException; internal void Init(GuidParseThrowStyle canThrow) { parsedGuid = Guid.Empty; throwStyle = canThrow; } internal void SetFailure(Exception nativeException) { m_failure = ParseFailureKind.NativeException; m_innerException = nativeException; } internal void SetFailure(ParseFailureKind failure, string failureMessageID) { SetFailure(failure, failureMessageID, null, null, null); } internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument) { SetFailure(failure, failureMessageID, failureMessageFormatArgument, null, null); } internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument, string failureArgumentName, Exception innerException) { Contract.Assert(failure != ParseFailureKind.NativeException, "ParseFailureKind.NativeException should not be used with this overload"); m_failure = failure; m_failureMessageID = failureMessageID; m_failureMessageFormatArgument = failureMessageFormatArgument; m_failureArgumentName = failureArgumentName; m_innerException = innerException; if (throwStyle != GuidParseThrowStyle.None) { throw GetGuidParseException(); } } internal Exception GetGuidParseException() { switch (m_failure) { case ParseFailureKind.ArgumentNull: return new ArgumentNullException(m_failureArgumentName, Environment.GetResourceString(m_failureMessageID)); case ParseFailureKind.FormatWithInnerException: return new FormatException(Environment.GetResourceString(m_failureMessageID), m_innerException); case ParseFailureKind.FormatWithParameter: return new FormatException(Environment.GetResourceString(m_failureMessageID, m_failureMessageFormatArgument)); case ParseFailureKind.Format: return new FormatException(Environment.GetResourceString(m_failureMessageID)); case ParseFailureKind.NativeException: return m_innerException; default: Contract.Assert(false, "Unknown GuidParseFailure: " + m_failure); return new FormatException(Environment.GetResourceString("Format_GuidUnrecognized")); } } } // Creates a new guid based on the value in the string. The value is made up // of hex digits speared by the dash ("-"). The string may begin and end with // brackets ("{", "}"). // // The string must be of the form dddddddd-dddd-dddd-dddd-dddddddddddd. where // d is a hex digit. (That is 8 hex digits, followed by 4, then 4, then 4, // then 12) such as: "CA761232-ED42-11CE-BACD-00AA0057B223" // public Guid(String g) { if (g==null) { throw new ArgumentNullException("g"); } Contract.EndContractBlock(); this = Guid.Empty; GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.All); if (TryParseGuid(g, GuidStyles.Any, ref result)) { this = result.parsedGuid; } else { throw result.GetGuidParseException(); } } public static Guid Parse(String input) { if (input == null) { throw new ArgumentNullException("input"); } Contract.EndContractBlock(); GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.AllButOverflow); if (TryParseGuid(input, GuidStyles.Any, ref result)) { return result.parsedGuid; } else { throw result.GetGuidParseException(); } } public static bool TryParse(String input, out Guid result) { GuidResult parseResult = new GuidResult(); parseResult.Init(GuidParseThrowStyle.None); if (TryParseGuid(input, GuidStyles.Any, ref parseResult)) { result = parseResult.parsedGuid; return true; } else { result = Guid.Empty; return false; } } public static Guid ParseExact(String input, String format) { if (input == null) throw new ArgumentNullException("input"); if (format == null) throw new ArgumentNullException("format"); if( format.Length != 1) { // all acceptable format strings are of length 1 throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification")); } GuidStyles style; char formatCh = format[0]; if (formatCh == 'D' || formatCh == 'd') { style = GuidStyles.DigitFormat; } else if (formatCh == 'N' || formatCh == 'n') { style = GuidStyles.NumberFormat; } else if (formatCh == 'B' || formatCh == 'b') { style = GuidStyles.BraceFormat; } else if (formatCh == 'P' || formatCh == 'p') { style = GuidStyles.ParenthesisFormat; } else if (formatCh == 'X' || formatCh == 'x') { style = GuidStyles.HexFormat; } else { throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification")); } GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.AllButOverflow); if (TryParseGuid(input, style, ref result)) { return result.parsedGuid; } else { throw result.GetGuidParseException(); } } public static bool TryParseExact(String input, String format, out Guid result) { if (format == null || format.Length != 1) { result = Guid.Empty; return false; } GuidStyles style; char formatCh = format[0]; if (formatCh == 'D' || formatCh == 'd') { style = GuidStyles.DigitFormat; } else if (formatCh == 'N' || formatCh == 'n') { style = GuidStyles.NumberFormat; } else if (formatCh == 'B' || formatCh == 'b') { style = GuidStyles.BraceFormat; } else if (formatCh == 'P' || formatCh == 'p') { style = GuidStyles.ParenthesisFormat; } else if (formatCh == 'X' || formatCh == 'x') { style = GuidStyles.HexFormat; } else { // invalid guid format specification result = Guid.Empty; return false; } GuidResult parseResult = new GuidResult(); parseResult.Init(GuidParseThrowStyle.None); if (TryParseGuid(input, style, ref parseResult)) { result = parseResult.parsedGuid; return true; } else { result = Guid.Empty; return false; } } private static bool TryParseGuid(String g, GuidStyles flags, ref GuidResult result) { if (g == null) { result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } String guidString = g.Trim(); //Remove Whitespace if (guidString.Length == 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } // Check for dashes bool dashesExistInString = (guidString.IndexOf('-', 0) >= 0); if (dashesExistInString) { if ((flags & (GuidStyles.AllowDashes | GuidStyles.RequireDashes)) == 0) { // dashes are not allowed result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } else { if ((flags & GuidStyles.RequireDashes) != 0) { // dashes are required result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } // Check for braces bool bracesExistInString = (guidString.IndexOf('{', 0) >= 0); if (bracesExistInString) { if ((flags & (GuidStyles.AllowBraces | GuidStyles.RequireBraces)) == 0) { // braces are not allowed result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } else { if ((flags & GuidStyles.RequireBraces) != 0) { // braces are required result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } // Check for parenthesis bool parenthesisExistInString = (guidString.IndexOf('(', 0) >= 0); if (parenthesisExistInString) { if ((flags & (GuidStyles.AllowParenthesis | GuidStyles.RequireParenthesis)) == 0) { // parenthesis are not allowed result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } else { if ((flags & GuidStyles.RequireParenthesis) != 0) { // parenthesis are required result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } try { // let's get on with the parsing if (dashesExistInString) { // Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)] return TryParseGuidWithDashes(guidString, ref result); } else if (bracesExistInString) { // Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} return TryParseGuidWithHexPrefix(guidString, ref result); } else { // Check if it's of the form dddddddddddddddddddddddddddddddd return TryParseGuidWithNoStyle(guidString, ref result); } } catch(IndexOutOfRangeException ex) { result.SetFailure(ParseFailureKind.FormatWithInnerException, "Format_GuidUnrecognized", null, null, ex); return false; } catch (ArgumentException ex) { result.SetFailure(ParseFailureKind.FormatWithInnerException, "Format_GuidUnrecognized", null, null, ex); return false; } } // Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} private static bool TryParseGuidWithHexPrefix(String guidString, ref GuidResult result) { int numStart = 0; int numLen = 0; // Eat all of the whitespace guidString = EatAllWhitespace(guidString); // Check for leading '{' if(String.IsNullOrEmpty(guidString) || guidString[0] != '{') { result.SetFailure(ParseFailureKind.Format, "Format_GuidBrace"); return false; } // Check for '0x' if(!IsHexPrefix(guidString, 1)) { result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, etc}"); return false; } // Find the end of this hex number (since it is not fixed length) numStart = 3; numLen = guidString.IndexOf(',', numStart) - numStart; if(numLen <= 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidComma"); return false; } if (!StringToInt(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._a, ref result)) return false; // Check for '0x' if(!IsHexPrefix(guidString, numStart+numLen+1)) { result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, 0xdddd, etc}"); return false; } // +3 to get by ',0x' numStart = numStart + numLen + 3; numLen = guidString.IndexOf(',', numStart) - numStart; if(numLen <= 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidComma"); return false; } // Read in the number if (!StringToShort(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._b, ref result)) return false; // Check for '0x' if(!IsHexPrefix(guidString, numStart+numLen+1)) { result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, 0xdddd, 0xdddd, etc}"); return false; } // +3 to get by ',0x' numStart = numStart + numLen + 3; numLen = guidString.IndexOf(',', numStart) - numStart; if(numLen <= 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidComma"); return false; } // Read in the number if (!StringToShort(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._c, ref result)) return false; // Check for '{' if(guidString.Length <= numStart+numLen+1 || guidString[numStart+numLen+1] != '{') { result.SetFailure(ParseFailureKind.Format, "Format_GuidBrace"); return false; } // Prepare for loop numLen++; byte[] bytes = new byte[8]; for(int i = 0; i < 8; i++) { // Check for '0x' if(!IsHexPrefix(guidString, numStart+numLen+1)) { result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{... { ... 0xdd, ...}}"); return false; } // +3 to get by ',0x' or '{0x' for first case numStart = numStart + numLen + 3; // Calculate number length if(i < 7) // first 7 cases { numLen = guidString.IndexOf(',', numStart) - numStart; if(numLen <= 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidComma"); return false; } } else // last case ends with '}', not ',' { numLen = guidString.IndexOf('}', numStart) - numStart; if(numLen <= 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidBraceAfterLastNumber"); return false; } } // Read in the number uint number = (uint)Convert.ToInt32(guidString.Substring(numStart, numLen),16); // check for overflow if(number > 255) { result.SetFailure(ParseFailureKind.Format, "Overflow_Byte"); return false; } bytes[i] = (byte)number; } result.parsedGuid._d = bytes[0]; result.parsedGuid._e = bytes[1]; result.parsedGuid._f = bytes[2]; result.parsedGuid._g = bytes[3]; result.parsedGuid._h = bytes[4]; result.parsedGuid._i = bytes[5]; result.parsedGuid._j = bytes[6]; result.parsedGuid._k = bytes[7]; // Check for last '}' if(numStart+numLen+1 >= guidString.Length || guidString[numStart+numLen+1] != '}') { result.SetFailure(ParseFailureKind.Format, "Format_GuidEndBrace"); return false; } // Check if we have extra characters at the end if( numStart+numLen+1 != guidString.Length -1) { result.SetFailure(ParseFailureKind.Format, "Format_ExtraJunkAtEnd"); return false; } return true; } // Check if it's of the form dddddddddddddddddddddddddddddddd private static bool TryParseGuidWithNoStyle(String guidString, ref GuidResult result) { int startPos=0; int temp; long templ; int currentPos = 0; if(guidString.Length != 32) { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } for(int i= 0; i< guidString.Length; i++) { char ch = guidString[i]; if(ch >= '0' && ch <= '9') { continue; } else { char upperCaseCh = Char.ToUpper(ch, CultureInfo.InvariantCulture); if(upperCaseCh >= 'A' && upperCaseCh <= 'F') { continue; } } result.SetFailure(ParseFailureKind.Format, "Format_GuidInvalidChar"); return false; } if (!StringToInt(guidString.Substring(startPos, 8) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._a, ref result)) return false; startPos += 8; if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result.parsedGuid._b, ref result)) return false; startPos += 4; if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result.parsedGuid._c, ref result)) return false; startPos += 4; if (!StringToInt(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out temp, ref result)) return false; startPos += 4; currentPos = startPos; if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result)) return false; if (currentPos - startPos!=12) { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } result.parsedGuid._d = (byte)(temp>>8); result.parsedGuid._e = (byte)(temp); temp = (int)(templ >> 32); result.parsedGuid._f = (byte)(temp>>8); result.parsedGuid._g = (byte)(temp); temp = (int)(templ); result.parsedGuid._h = (byte)(temp>>24); result.parsedGuid._i = (byte)(temp>>16); result.parsedGuid._j = (byte)(temp>>8); result.parsedGuid._k = (byte)(temp); return true; } // Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)] private static bool TryParseGuidWithDashes(String guidString, ref GuidResult result) { int startPos=0; int temp; long templ; int currentPos = 0; // check to see that it's the proper length if (guidString[0]=='{') { if (guidString.Length!=38 || guidString[37]!='}') { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } startPos=1; } else if (guidString[0]=='(') { if (guidString.Length!=38 || guidString[37]!=')') { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } startPos=1; } else if(guidString.Length != 36) { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } if (guidString[8+startPos] != '-' || guidString[13+startPos] != '-' || guidString[18+startPos] != '-' || guidString[23+startPos] != '-') { result.SetFailure(ParseFailureKind.Format, "Format_GuidDashes"); return false; } currentPos = startPos; if (!StringToInt(guidString, ref currentPos, 8, ParseNumbers.NoSpace, out temp, ref result)) return false; result.parsedGuid._a = temp; ++currentPos; //Increment past the '-'; if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result)) return false; result.parsedGuid._b = (short)temp; ++currentPos; //Increment past the '-'; if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result)) return false; result.parsedGuid._c = (short)temp; ++currentPos; //Increment past the '-'; if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result)) return false; ++currentPos; //Increment past the '-'; startPos=currentPos; if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result)) return false; if (currentPos - startPos != 12) { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } result.parsedGuid._d = (byte)(temp>>8); result.parsedGuid._e = (byte)(temp); temp = (int)(templ >> 32); result.parsedGuid._f = (byte)(temp>>8); result.parsedGuid._g = (byte)(temp); temp = (int)(templ); result.parsedGuid._h = (byte)(temp>>24); result.parsedGuid._i = (byte)(temp>>16); result.parsedGuid._j = (byte)(temp>>8); result.parsedGuid._k = (byte)(temp); return true; } // // StringToShort, StringToInt, and StringToLong are wrappers around COMUtilNative integer parsing routines; [System.Security.SecuritySafeCritical] private static unsafe bool StringToShort(String str, int requiredLength, int flags, out short result, ref GuidResult parseResult) { return StringToShort(str, null, requiredLength, flags, out result, ref parseResult); } [System.Security.SecuritySafeCritical] private static unsafe bool StringToShort(String str, ref int parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult) { fixed(int * ppos = &parsePos) { return StringToShort(str, ppos, requiredLength, flags, out result, ref parseResult); } } [System.Security.SecurityCritical] private static unsafe bool StringToShort(String str, int* parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult) { result = 0; int x; bool retValue = StringToInt(str, parsePos, requiredLength, flags, out x, ref parseResult); result = (short)x; return retValue; } [System.Security.SecuritySafeCritical] private static unsafe bool StringToInt(String str, int requiredLength, int flags, out int result, ref GuidResult parseResult) { return StringToInt(str, null, requiredLength, flags, out result, ref parseResult); } [System.Security.SecuritySafeCritical] private static unsafe bool StringToInt(String str, ref int parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult) { fixed(int * ppos = &parsePos) { return StringToInt(str, ppos, requiredLength, flags, out result, ref parseResult); } } [System.Security.SecurityCritical] private static unsafe bool StringToInt(String str, int* parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult) { result = 0; int currStart = (parsePos == null) ? 0 : (*parsePos); try { result = ParseNumbers.StringToInt(str, 16, flags, parsePos); } catch (OverflowException ex) { if (parseResult.throwStyle == GuidParseThrowStyle.All) { throw; } else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow) { throw new FormatException(Environment.GetResourceString("Format_GuidUnrecognized"), ex); } else { parseResult.SetFailure(ex); return false; } } catch (Exception ex) { if (parseResult.throwStyle == GuidParseThrowStyle.None) { parseResult.SetFailure(ex); return false; } else { throw; } } //If we didn't parse enough characters, there's clearly an error. if (requiredLength != -1 && parsePos != null && (*parsePos) - currStart != requiredLength) { parseResult.SetFailure(ParseFailureKind.Format, "Format_GuidInvalidChar"); return false; } return true; } [System.Security.SecuritySafeCritical] private static unsafe bool StringToLong(String str, int flags, out long result, ref GuidResult parseResult) { return StringToLong(str, null, flags, out result, ref parseResult); } [System.Security.SecuritySafeCritical] private static unsafe bool StringToLong(String str, ref int parsePos, int flags, out long result, ref GuidResult parseResult) { fixed(int * ppos = &parsePos) { return StringToLong(str, ppos, flags, out result, ref parseResult); } } [System.Security.SecuritySafeCritical] private static unsafe bool StringToLong(String str, int* parsePos, int flags, out long result, ref GuidResult parseResult) { result = 0; try { result = ParseNumbers.StringToLong(str, 16, flags, parsePos); } catch (OverflowException ex) { if (parseResult.throwStyle == GuidParseThrowStyle.All) { throw; } else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow) { throw new FormatException(Environment.GetResourceString("Format_GuidUnrecognized"), ex); } else { parseResult.SetFailure(ex); return false; } } catch (Exception ex) { if (parseResult.throwStyle == GuidParseThrowStyle.None) { parseResult.SetFailure(ex); return false; } else { throw; } } return true; } private static String EatAllWhitespace(String str) { int newLength = 0; char[] chArr = new char[str.Length]; char curChar; // Now get each char from str and if it is not whitespace add it to chArr for(int i = 0; i < str.Length; i++) { curChar = str[i]; if(!Char.IsWhiteSpace(curChar)) { chArr[newLength++] = curChar; } } // Return a new string based on chArr return new String(chArr, 0, newLength); } private static bool IsHexPrefix(String str, int i) { if(str.Length > i+1 && str[i] == '0' && (Char.ToLower(str[i+1], CultureInfo.InvariantCulture) == 'x')) return true; else return false; } // Returns an unsigned byte array containing the GUID. public byte[] ToByteArray() { byte[] g = new byte[16]; g[0] = (byte)(_a); g[1] = (byte)(_a >> 8); g[2] = (byte)(_a >> 16); g[3] = (byte)(_a >> 24); g[4] = (byte)(_b); g[5] = (byte)(_b >> 8); g[6] = (byte)(_c); g[7] = (byte)(_c >> 8); g[8] = _d; g[9] = _e; g[10] = _f; g[11] = _g; g[12] = _h; g[13] = _i; g[14] = _j; g[15] = _k; return g; } // Returns the guid in "registry" format. public override String ToString() { return ToString("D",null); } public override int GetHashCode() { return _a ^ (((int)_b << 16) | (int)(ushort)_c) ^ (((int)_f << 24) | _k); } // Returns true if and only if the guid represented // by o is the same as this instance. public override bool Equals(Object o) { Guid g; // Check that o is a Guid first if(o == null || !(o is Guid)) return false; else g = (Guid) o; // Now compare each of the elements if(g._a != _a) return false; if(g._b != _b) return false; if(g._c != _c) return false; if (g._d != _d) return false; if (g._e != _e) return false; if (g._f != _f) return false; if (g._g != _g) return false; if (g._h != _h) return false; if (g._i != _i) return false; if (g._j != _j) return false; if (g._k != _k) return false; return true; } public bool Equals(Guid g) { // Now compare each of the elements if(g._a != _a) return false; if(g._b != _b) return false; if(g._c != _c) return false; if (g._d != _d) return false; if (g._e != _e) return false; if (g._f != _f) return false; if (g._g != _g) return false; if (g._h != _h) return false; if (g._i != _i) return false; if (g._j != _j) return false; if (g._k != _k) return false; return true; } private int GetResult(uint me, uint them) { if (me<them) { return -1; } return 1; } public int CompareTo(Object value) { if (value == null) { return 1; } if (!(value is Guid)) { throw new ArgumentException(Environment.GetResourceString("Arg_MustBeGuid")); } Guid g = (Guid)value; if (g._a!=this._a) { return GetResult((uint)this._a, (uint)g._a); } if (g._b!=this._b) { return GetResult((uint)this._b, (uint)g._b); } if (g._c!=this._c) { return GetResult((uint)this._c, (uint)g._c); } if (g._d!=this._d) { return GetResult((uint)this._d, (uint)g._d); } if (g._e!=this._e) { return GetResult((uint)this._e, (uint)g._e); } if (g._f!=this._f) { return GetResult((uint)this._f, (uint)g._f); } if (g._g!=this._g) { return GetResult((uint)this._g, (uint)g._g); } if (g._h!=this._h) { return GetResult((uint)this._h, (uint)g._h); } if (g._i!=this._i) { return GetResult((uint)this._i, (uint)g._i); } if (g._j!=this._j) { return GetResult((uint)this._j, (uint)g._j); } if (g._k!=this._k) { return GetResult((uint)this._k, (uint)g._k); } return 0; } public int CompareTo(Guid value) { if (value._a!=this._a) { return GetResult((uint)this._a, (uint)value._a); } if (value._b!=this._b) { return GetResult((uint)this._b, (uint)value._b); } if (value._c!=this._c) { return GetResult((uint)this._c, (uint)value._c); } if (value._d!=this._d) { return GetResult((uint)this._d, (uint)value._d); } if (value._e!=this._e) { return GetResult((uint)this._e, (uint)value._e); } if (value._f!=this._f) { return GetResult((uint)this._f, (uint)value._f); } if (value._g!=this._g) { return GetResult((uint)this._g, (uint)value._g); } if (value._h!=this._h) { return GetResult((uint)this._h, (uint)value._h); } if (value._i!=this._i) { return GetResult((uint)this._i, (uint)value._i); } if (value._j!=this._j) { return GetResult((uint)this._j, (uint)value._j); } if (value._k!=this._k) { return GetResult((uint)this._k, (uint)value._k); } return 0; } public static bool operator ==(Guid a, Guid b) { // Now compare each of the elements if(a._a != b._a) return false; if(a._b != b._b) return false; if(a._c != b._c) return false; if(a._d != b._d) return false; if(a._e != b._e) return false; if(a._f != b._f) return false; if(a._g != b._g) return false; if(a._h != b._h) return false; if(a._i != b._i) return false; if(a._j != b._j) return false; if(a._k != b._k) return false; return true; } public static bool operator !=(Guid a, Guid b) { return !(a == b); } // This will create a new guid. Since we've now decided that constructors should 0-init, // we need a method that allows users to create a guid. [System.Security.SecuritySafeCritical] // auto-generated public static Guid NewGuid() { // CoCreateGuid should never return Guid.Empty, since it attempts to maintain some // uniqueness guarantees. It should also never return a known GUID, but it's unclear // how extensively it checks for known values. Contract.Ensures(Contract.Result<Guid>() != Guid.Empty); Guid guid; Marshal.ThrowExceptionForHR(Win32Native.CoCreateGuid(out guid), new IntPtr(-1)); return guid; } public String ToString(String format) { return ToString(format, null); } private static char HexToChar(int a) { a = a & 0xf; return (char) ((a > 9) ? a - 10 + 0x61 : a + 0x30); } [System.Security.SecurityCritical] unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b) { return HexsToChars(guidChars, offset, a, b, false); } [System.Security.SecurityCritical] unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b, bool hex) { if (hex) { guidChars[offset++] = '0'; guidChars[offset++] = 'x'; } guidChars[offset++] = HexToChar(a>>4); guidChars[offset++] = HexToChar(a); if (hex) { guidChars[offset++] = ','; guidChars[offset++] = '0'; guidChars[offset++] = 'x'; } guidChars[offset++] = HexToChar(b>>4); guidChars[offset++] = HexToChar(b); return offset; } // IFormattable interface // We currently ignore provider [System.Security.SecuritySafeCritical] public String ToString(String format, IFormatProvider provider) { if (format == null || format.Length == 0) format = "D"; string guidString; int offset = 0; bool dash = true; bool hex = false; if( format.Length != 1) { // all acceptable format strings are of length 1 throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification")); } char formatCh = format[0]; if (formatCh == 'D' || formatCh == 'd') { guidString = string.FastAllocateString(36); } else if (formatCh == 'N' || formatCh == 'n') { guidString = string.FastAllocateString(32); dash = false; } else if (formatCh == 'B' || formatCh == 'b') { guidString = string.FastAllocateString(38); unsafe { fixed (char* guidChars = guidString) { guidChars[offset++] = '{'; guidChars[37] = '}'; } } } else if (formatCh == 'P' || formatCh == 'p') { guidString = string.FastAllocateString(38); unsafe { fixed (char* guidChars = guidString) { guidChars[offset++] = '('; guidChars[37] = ')'; } } } else if (formatCh == 'X' || formatCh == 'x') { guidString = string.FastAllocateString(68); unsafe { fixed (char* guidChars = guidString) { guidChars[offset++] = '{'; guidChars[67] = '}'; } } dash = false; hex = true; } else { throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification")); } unsafe { fixed (char* guidChars = guidString) { if (hex) { // {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} guidChars[offset++] = '0'; guidChars[offset++] = 'x'; offset = HexsToChars(guidChars, offset, _a >> 24, _a >> 16); offset = HexsToChars(guidChars, offset, _a >> 8, _a); guidChars[offset++] = ','; guidChars[offset++] = '0'; guidChars[offset++] = 'x'; offset = HexsToChars(guidChars, offset, _b >> 8, _b); guidChars[offset++] = ','; guidChars[offset++] = '0'; guidChars[offset++] = 'x'; offset = HexsToChars(guidChars, offset, _c >> 8, _c); guidChars[offset++] = ','; guidChars[offset++] = '{'; offset = HexsToChars(guidChars, offset, _d, _e, true); guidChars[offset++] = ','; offset = HexsToChars(guidChars, offset, _f, _g, true); guidChars[offset++] = ','; offset = HexsToChars(guidChars, offset, _h, _i, true); guidChars[offset++] = ','; offset = HexsToChars(guidChars, offset, _j, _k, true); guidChars[offset++] = '}'; } else { // [{|(]dddddddd[-]dddd[-]dddd[-]dddd[-]dddddddddddd[}|)] offset = HexsToChars(guidChars, offset, _a >> 24, _a >> 16); offset = HexsToChars(guidChars, offset, _a >> 8, _a); if (dash) guidChars[offset++] = '-'; offset = HexsToChars(guidChars, offset, _b >> 8, _b); if (dash) guidChars[offset++] = '-'; offset = HexsToChars(guidChars, offset, _c >> 8, _c); if (dash) guidChars[offset++] = '-'; offset = HexsToChars(guidChars, offset, _d, _e); if (dash) guidChars[offset++] = '-'; offset = HexsToChars(guidChars, offset, _f, _g); offset = HexsToChars(guidChars, offset, _h, _i); offset = HexsToChars(guidChars, offset, _j, _k); } } } return guidString; } } }
#region License, Terms and Conditions // // Jayrock - JSON and JSON-RPC for Microsoft .NET Framework and Mono // Written by Atif Aziz (atif.aziz@skybow.com) // Copyright (c) 2005 Atif Aziz. All rights reserved. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License as published by the Free // Software Foundation; either version 2.1 of the License, or (at your option) // any later version. // // This library is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more // details. // // You should have received a copy of the GNU Lesser General Public License // along with this library; if not, write to the Free Software Foundation, Inc., // 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #endregion namespace Jayrock.Json { #region Imports using System; #endregion /// <summary> /// Represents a reader that provides fast, non-cached, forward-only /// access to JSON data. /// </summary> public abstract class JsonReader : IDisposable { /// <summary> /// Reads the next token and returns true if one was found. /// </summary> public abstract bool Read(); /// <summary> /// Gets the current token. /// </summary> public abstract JsonToken Token { get; } /// <summary> /// Gets the class of the current token. /// </summary> public JsonTokenClass TokenClass { get { return Token.Class; } } /// <summary> /// Gets the text of the current token. /// </summary> public string Text { get { return Token.Text; } } /// <summary> /// Return the current level of nesting as the reader encounters /// nested objects and arrays. /// </summary> public abstract int Depth { get; } /// <summary> /// Closes the reader and releases any underlying resources /// associated with the reader. /// </summary> public virtual void Close() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Returns a <see cref="String"/> that represents the state of the /// instance. /// </summary> public override string ToString() { return Token.ToString(); } /// <summary> /// Indicates whether the reader has reached the end of input source. /// </summary> public bool EOF { get { return TokenClass == JsonTokenClass.EOF; } } /// <summary> /// Reads the next token ensuring that it matches the specified /// token. If not, an exception is thrown. /// </summary> public string ReadToken(JsonTokenClass token) { int depth = Depth; if (!token.IsTerminator) MoveToContent(); // // We allow an exception to the simple case of validating // the token and returning its value. If the reader is still at // the start (depth is zero) and we're being asked to check // for the null token or a scalar-type token then we allow that // to be appear within a one-length array. This is done because // valid JSON text must begin with an array or object. Our // JsonWriterBase automatically wraps a scalar value in an // array if not done explicitly. This exception here allow // that case to pass as being logically valid, as if the // token appeared entirely on its own between BOF and EOF. // string text; if (depth == 0 && TokenClass == JsonTokenClass.Array && (token.IsScalar || token == JsonTokenClass.Null)) { Read(/* array */); text = ReadToken(token); ReadToken(JsonTokenClass.EndArray); } else { if (TokenClass != token) throw new JsonException(string.Format("Found {0} where {1} was expected.", TokenClass, token)); text = Text; Read(); } return text; } /// <summary> /// Reads the next token, ensures it is a String and returns its /// text. If the next token is not a String, then an exception /// is thrown instead. /// </summary> public string ReadString() { return ReadToken(JsonTokenClass.String); } /// <summary> /// Reads the next token, ensures it is a Boolean and returns its /// value. If the next token is not a Boolean, then an exception /// is thrown instead. /// </summary> public bool ReadBoolean() { return ReadToken(JsonTokenClass.Boolean) == JsonBoolean.TrueText; } /// <summary> /// Reads the next token, ensures it is a Number and returns its /// text representation. If the next token is not a Number, then /// an exception is thrown instead. /// </summary> public JsonNumber ReadNumber() { return new JsonNumber(ReadToken(JsonTokenClass.Number)); } /// <summary> /// Reads the next token, ensures it is a Null. If the next token /// is not a Null, then an exception is thrown instead. /// </summary> public void ReadNull() { ReadToken(JsonTokenClass.Null); } /// <summary> /// Reads the next token, ensures it is Member (of an object) and /// returns its text. If the next token is not a Member, then an /// exception is thrown instead. /// </summary> public string ReadMember() { return ReadToken(JsonTokenClass.Member); } /// <summary> /// Steps out of the current depth to the level immediately above. /// Usually this skips the current Object or Array being read, /// including all nested structures. /// </summary> public void StepOut() { int depth = Depth; if (depth == 0) throw new InvalidOperationException(); while (Depth > depth || (TokenClass != JsonTokenClass.EndObject && TokenClass != JsonTokenClass.EndArray)) Read(); Read(/* past tail */); } /// <summary> /// Skips through the next item. If it is an Object or Array, then /// the entire object or array is skipped. If it is a scalar value /// then just that value is skipped. If the reader is on an object /// member then the member and its value is skipped. /// </summary> public void Skip() { if (!MoveToContent()) return; if (TokenClass == JsonTokenClass.Object || TokenClass == JsonTokenClass.Array) { StepOut(); } else if (TokenClass == JsonTokenClass.Member) { Read(/* member */); Skip(/* value */); } else { Read(/* scalar */); } } /// <summary> /// Ensures that the reader is positioned on content (a JSON value) /// ready to be read. If the reader is already aligned on the start /// of a value then no further action is taken. /// </summary> /// <returns>Return true if content was found. Otherwise false to /// indicate EOF.</returns> public bool MoveToContent() { if (!EOF) { if (TokenClass.IsTerminator) return Read(); return true; } else { return false; } } /// <summary> /// Represents the method that handles the Disposed event of a reader. /// </summary> public virtual event EventHandler Disposed; void IDisposable.Dispose() { Close(); } protected virtual void Dispose(bool disposing) { if (disposing) OnDisposed(EventArgs.Empty); } private void OnDisposed(EventArgs e) { EventHandler handler = Disposed; if (handler != null) handler(this, e); } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using MbUnit.Core; using MbUnit.Core.Reports.Serialization; using MbUnit.Core.Remoting; using System.Reflection; namespace MbUnit.Forms { /// <summary> /// Summary description for ExceptionBrowser. /// </summary> public sealed class ExceptionBrowser : System.Windows.Forms.UserControl { private ReflectorTreeView tree = null; private System.Windows.Forms.TreeView exceptionTreeView; private System.Windows.Forms.Splitter splitter1; private System.Windows.Forms.RichTextBox textBox1; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public ExceptionBrowser() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // TODO: Add any initialization after the InitializeComponent call } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.exceptionTreeView = new System.Windows.Forms.TreeView(); this.splitter1 = new System.Windows.Forms.Splitter(); this.textBox1 = new System.Windows.Forms.RichTextBox(); this.SuspendLayout(); // // exceptionTreeView // this.exceptionTreeView.Dock = System.Windows.Forms.DockStyle.Top; this.exceptionTreeView.Location = new System.Drawing.Point(0, 0); this.exceptionTreeView.Name = "exceptionTreeView"; this.exceptionTreeView.Size = new System.Drawing.Size(500, 56); this.exceptionTreeView.TabIndex = 0; this.exceptionTreeView.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.exceptionTreeView_AfterSelect); // // splitter1 // this.splitter1.Dock = System.Windows.Forms.DockStyle.Top; this.splitter1.Location = new System.Drawing.Point(0, 56); this.splitter1.Name = "splitter1"; this.splitter1.Size = new System.Drawing.Size(500, 3); this.splitter1.TabIndex = 1; this.splitter1.TabStop = false; // // textBox1 // this.textBox1.AcceptsTab = true; this.textBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.textBox1.Location = new System.Drawing.Point(0, 59); this.textBox1.Name = "textBox1"; this.textBox1.ReadOnly = true; this.textBox1.Size = new System.Drawing.Size(500, 229); this.textBox1.TabIndex = 2; this.textBox1.Text = ""; this.textBox1.WordWrap = false; // // ExceptionBrowser // this.Controls.Add(this.textBox1); this.Controls.Add(this.splitter1); this.Controls.Add(this.exceptionTreeView); this.Name = "ExceptionBrowser"; this.Size = new System.Drawing.Size(500, 288); this.ResumeLayout(false); } #endregion public ReflectorTreeView Tree { get { return this.tree; } set { if (this.tree != null && value != this.tree) { this.tree.AfterSelect -= new TreeViewEventHandler(treeView_AfterSelect); this.tree.FinishTests -= new EventHandler(treeView_FinishTests); } this.tree = value; if (this.tree != null) { this.tree.AfterSelect += new TreeViewEventHandler(treeView_AfterSelect); this.tree.FinishTests += new EventHandler(treeView_FinishTests); } } } public void AddException(ReportException ex) { this.exceptionTreeView.Nodes.Clear(); // adding recursively the exceptions ReportException current = ex; TreeNode parent = null; while(current!=null) { TreeNode node =new TreeNode(current.Type); node.Tag = current; if (parent==null) { this.exceptionTreeView.Nodes.Add(node); this.exceptionTreeView.SelectedNode = node; parent = node; } else { parent.Nodes.Add(node); parent = node; } current = current.Exception; } this.exceptionTreeView.ExpandAll(); this.RefreshException(); this.Refresh(); } public void RefreshException() { this.textBox1.Text=""; if (this.exceptionTreeView.SelectedNode==null) { this.textBox1.Text=""; return; } ReportException ex = (ReportException)this.exceptionTreeView.SelectedNode.Tag; Font boldFont = new Font(this.Font.FontFamily,this.Font.SizeInPoints,FontStyle.Bold); Font font = new Font(this.Font.FontFamily,this.Font.SizeInPoints); // adding name this.textBox1.SelectionFont = boldFont; this.textBox1.SelectedText = String.Format("Message: {0}\n\n", ex.Message); this.textBox1.SelectionFont = font; this.textBox1.SelectedText = String.Format("Type: {0}\n", ex.Type); this.textBox1.SelectedText = String.Format("Source: {0}\n",ex.Source); foreach(ReportProperty property in ex.Properties) this.textBox1.SelectedText = String.Format("{0}: {1}\n", property.Name, property.Value); this.textBox1.SelectedText = String.Format("Stack:"); this.textBox1.SelectedText = String.Format("{0}",ex.StackTrace); } private void treeView_AfterSelect( object sender, System.Windows.Forms.TreeViewEventArgs e ) { SafelyDisplaySelectedNodeResult(); } private void treeView_FinishTests( object sender, EventArgs e ) { SafelyDisplaySelectedNodeResult(); } private void SafelyDisplaySelectedNodeResult() { try { if (this.InvokeRequired) { this.Invoke(new MethodInvoker(this.DisplaySelectedNodeResult)); } else { DisplaySelectedNodeResult(); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } private void DisplaySelectedNodeResult() { // retreive current exceptoin this.exceptionTreeView.Nodes.Clear(); this.textBox1.Text = ""; UnitTreeNode node = this.tree.TypeTree.SelectedNode as UnitTreeNode; if (node == null) return; ReportRun result = this.Tree.TestDomains.GetResult(node); if (result != null && result.Result == ReportRunResult.Failure) { AddException(result.Exception); } } private void exceptionTreeView_AfterSelect( object sender, System.Windows.Forms.TreeViewEventArgs e ) { RefreshException(); } public void Clear() { if (InvokeRequired) Invoke(new MethodInvoker(Clear)); else { exceptionTreeView.Nodes.Clear(); textBox1.Clear(); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using DG.Tweening; using UnityEngine; using UnityEngine.Advertisements; using UnityEngine.Events; using UnityEngine.UI; using UnityStandardAssets.ImageEffects; public class TitleManager : MonoBehaviour { //References //Public public bool AdsVersion; public Transform ColorGrid; public Color ChosenColor; public Color DefaultColor; public Material WallMaterial; public Text txtStoreName; public YesNoDialogWindow YesNoWindow; //Game save public Transform SaveSlot1; public Transform SaveSlot2; public Transform SaveSlot3; //public Text txtLoadStoreName; //public Text txtLoadMoney; //public Text txtLoadDate; //public Text txtDebug; //quality public Toggle ToggleQualityFast; public Toggle ToggleQualityGood; public Toggle ToggleQualityBeautiful; public Toggle ToggleQualityFantastic; //public Transform SaveGameGrid; //public GameObject SaveGameEntryPrefab; public GameObject Overlay; public GameObject TxtAdVersion; public AudioSource MusicSource; //Private //List<GameSaveData> _saveGameSaves = new List<GameSaveData>(); //List<string> _savePaths = new List<string>(); private GameSaveData _data1; private GameSaveData _data2; private GameSaveData _data3; private int _saveFileToDelete; void Awake() { DOTween.Init(false, true, LogBehaviour.ErrorsOnly).SetCapacity(512, 32); DOTween.defaultEaseType = Ease.Linear; QualitySettings.SetQualityLevel(PlayerPrefs.GetInt(SaveGameManager.SettingsQuality, 0)); //Load quelity settings AdjustQualitySettings(); if (AdsVersion) { Advertisement.Initialize("131625348"); } else { TxtAdVersion.SetActive(false); } } private void AdjustQualitySettings() { #if UNITY_ANDROID //Application.targetFrameRate = 30; QualitySettings.vSyncCount = 1; QualitySettings.antiAliasing = 0; Screen.sleepTimeout = SleepTimeout.NeverSleep; if (QualitySettings.GetQualityLevel() == 0) { Camera.main.GetComponent<Antialiasing>().enabled = false; } else { Camera.main.GetComponent<Antialiasing>().enabled = true; } #endif } void Start() { SetQualityToggle(); //Get saved games //LoadSavedGames(); LoadGameDataToSlots(); //GetChosenColor(); WallMaterial.color = DefaultColor; ChosenColor = DefaultColor; //Debug.Log(_saveGameSaves.Count); } private void LoadFromIndex(string i) { int index = Int32.Parse(i); LoadGame(index); } public void DeleteSaveAtIndex(int i) { _saveFileToDelete = i; //File.Delete(_savePaths[index]); ShowYesNoWindow("Are you sure?", "Are you sure you want to delete your save file?", ActuallyDeleteSave, null); //Reload saves //LoadSavedGames(); //LoadSavedGamesInGrid(); } private void ActuallyDeleteSave() { File.Delete(SaveGameManager.Singleton.GetSaveSlotPath(_saveFileToDelete)); LoadGameDataToSlots(); } public void OnColorChanged() { ChosenColor = GetChosenColor(); WallMaterial.color = ChosenColor; } private Color GetChosenColor() { foreach (var ch in ColorGrid.GetAllChildren()) { if (ch.GetComponent<Toggle>().isOn) { Color col = ch.GetComponent<Image>().color; return col; } } return Color.white; } public void StartGame() { ShowOverlay(); StoreManager.StoreColor = ChosenColor; StoreManager.StoreName = txtStoreName.text; StoreManager.AdsVersion = AdsVersion; Application.LoadLevelAsync("Store"); } public void LoadGame(int index) { switch (index) { case 1: if (_data1 == null) { return; } break; case 2: if (_data2 == null) { return; } break; case 3: if (_data3 == null) { return; } break; } ShowOverlay(); StoreManager.AdsVersion = AdsVersion; SaveGameManager.AdsVersion = AdsVersion; SaveGameManager.ShouldLoadGameOnStart = true; //SaveGameManager.SaveGameFilepathToLoad = _savePaths[index]; SaveGameManager.SaveGameFilepathToLoad = SaveGameManager.Singleton.GetSaveSlotPath(index); Application.LoadLevelAsync("Store"); } public void QuitGame() { ShowYesNoWindow("Are you sure?", "Are you sure you want to quit?", QuitRoutine, null); } public void QuitRoutine() { //Makes sure editor doesn't get killed by accident #if !UNITY_EDITOR System.Diagnostics.Process.GetCurrentProcess().Kill(); #endif } public void SetSound(bool on) { SoundManager.Singleton.PlaySounds = on; SaveGameManager.SoundEnabled = on; SaveGameManager.Singleton.SavePreferences(); } public void SetMusic(bool on) { SaveGameManager.MusicEnabled = on; SaveGameManager.Singleton.SavePreferences(); if (on) { MusicSource.Play(); } else { MusicSource.Stop(); } } public void SetQualityLevel(int level) { QualitySettings.SetQualityLevel(level, true); AdjustQualitySettings(); SaveGameManager.Singleton.SavePreferences(); } private void SetQualityToggle() { switch (QualitySettings.GetQualityLevel()) { case 0: ToggleQualityFast.isOn = true; break; case 1: ToggleQualityGood.isOn = true; break; case 2: ToggleQualityBeautiful.isOn = true; break; case 3: ToggleQualityFantastic.isOn = true; break; } } public void ShowOverlay() { Overlay.SetActive(true); } public void LoadGameDataToSlots() { _data1 = SaveGameManager.Singleton.GetGameSaveDataFromSlot(1); _data2 = SaveGameManager.Singleton.GetGameSaveDataFromSlot(2); _data3 = SaveGameManager.Singleton.GetGameSaveDataFromSlot(3); SetSaveData(SaveSlot1, _data1); SetSaveData(SaveSlot2, _data2); SetSaveData(SaveSlot3, _data3); } private void SetSaveData(Transform slotTransform, GameSaveData data) { if (data == null) { slotTransform.FindChild("txtStoreName").GetComponent<Text>().text = ""; slotTransform.FindChild("txtDate").GetComponent<Text>().text = ""; slotTransform.FindChild("txtMoney").GetComponent<Text>().text = ""; slotTransform.FindChild("txtSlotEmpty").GetComponent<Text>().text = "- Empty -"; slotTransform.FindChild("btnDeleteSave").gameObject.SetActive(false); slotTransform.GetComponent<Image>().color = DefaultColor; } else { slotTransform.FindChild("txtStoreName").GetComponent<Text>().text = data.StoreName; slotTransform.FindChild("txtDate").GetComponent<Text>().text = "Y" + data.Year + " D" + data.Day + " " + data.Season; slotTransform.FindChild("txtMoney").GetComponent<Text>().text = data.Money.ToString("C"); slotTransform.FindChild("txtSlotEmpty").GetComponent<Text>().text = ""; slotTransform.FindChild("btnDeleteSave").gameObject.SetActive(true); slotTransform.GetComponent<Image>().color = data.StoreColor.GetColor(); } } public void ShowYesNoWindow(string title, string question, Action onYes, Action onNo) { YesNoWindow.SetYesNoActions(onYes, onNo); YesNoWindow.Show(title, question); YesNoWindow.transform.DOScale(new Vector3(.5f, .5f, .5f), .2f).From(); } public void ShareOnTwitter() { string address = "http://twitter.com/intent/tweet"; Application.OpenURL(address + "?text=" + WWW.EscapeURL("Check out Store Story for Android!") + "&amp;url=" + WWW.EscapeURL("https://play.google.com/store/apps/details?id=storestory.be.blackdragon") + "&amp;related=" + WWW.EscapeURL("") + "&amp;lang=" + WWW.EscapeURL("en")); } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace Northwind{ /// <summary> /// Strongly-typed collection for the Invoice class. /// </summary> [Serializable] public partial class InvoiceCollection : ReadOnlyList<Invoice, InvoiceCollection> { public InvoiceCollection() {} } /// <summary> /// This is Read-only wrapper class for the Invoices view. /// </summary> [Serializable] public partial class Invoice : ReadOnlyRecord<Invoice>, IReadOnlyRecord { #region Default Settings protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema Accessor public static TableSchema.Table Schema { get { if (BaseSchema == null) { SetSQLProps(); } return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Invoices", TableType.View, DataService.GetInstance("Northwind")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarShipName = new TableSchema.TableColumn(schema); colvarShipName.ColumnName = "ShipName"; colvarShipName.DataType = DbType.String; colvarShipName.MaxLength = 40; colvarShipName.AutoIncrement = false; colvarShipName.IsNullable = true; colvarShipName.IsPrimaryKey = false; colvarShipName.IsForeignKey = false; colvarShipName.IsReadOnly = false; schema.Columns.Add(colvarShipName); TableSchema.TableColumn colvarShipAddress = new TableSchema.TableColumn(schema); colvarShipAddress.ColumnName = "ShipAddress"; colvarShipAddress.DataType = DbType.String; colvarShipAddress.MaxLength = 60; colvarShipAddress.AutoIncrement = false; colvarShipAddress.IsNullable = true; colvarShipAddress.IsPrimaryKey = false; colvarShipAddress.IsForeignKey = false; colvarShipAddress.IsReadOnly = false; schema.Columns.Add(colvarShipAddress); TableSchema.TableColumn colvarShipCity = new TableSchema.TableColumn(schema); colvarShipCity.ColumnName = "ShipCity"; colvarShipCity.DataType = DbType.String; colvarShipCity.MaxLength = 15; colvarShipCity.AutoIncrement = false; colvarShipCity.IsNullable = true; colvarShipCity.IsPrimaryKey = false; colvarShipCity.IsForeignKey = false; colvarShipCity.IsReadOnly = false; schema.Columns.Add(colvarShipCity); TableSchema.TableColumn colvarShipRegion = new TableSchema.TableColumn(schema); colvarShipRegion.ColumnName = "ShipRegion"; colvarShipRegion.DataType = DbType.String; colvarShipRegion.MaxLength = 15; colvarShipRegion.AutoIncrement = false; colvarShipRegion.IsNullable = true; colvarShipRegion.IsPrimaryKey = false; colvarShipRegion.IsForeignKey = false; colvarShipRegion.IsReadOnly = false; schema.Columns.Add(colvarShipRegion); TableSchema.TableColumn colvarShipPostalCode = new TableSchema.TableColumn(schema); colvarShipPostalCode.ColumnName = "ShipPostalCode"; colvarShipPostalCode.DataType = DbType.String; colvarShipPostalCode.MaxLength = 10; colvarShipPostalCode.AutoIncrement = false; colvarShipPostalCode.IsNullable = true; colvarShipPostalCode.IsPrimaryKey = false; colvarShipPostalCode.IsForeignKey = false; colvarShipPostalCode.IsReadOnly = false; schema.Columns.Add(colvarShipPostalCode); TableSchema.TableColumn colvarShipCountry = new TableSchema.TableColumn(schema); colvarShipCountry.ColumnName = "ShipCountry"; colvarShipCountry.DataType = DbType.String; colvarShipCountry.MaxLength = 15; colvarShipCountry.AutoIncrement = false; colvarShipCountry.IsNullable = true; colvarShipCountry.IsPrimaryKey = false; colvarShipCountry.IsForeignKey = false; colvarShipCountry.IsReadOnly = false; schema.Columns.Add(colvarShipCountry); TableSchema.TableColumn colvarCustomerID = new TableSchema.TableColumn(schema); colvarCustomerID.ColumnName = "CustomerID"; colvarCustomerID.DataType = DbType.String; colvarCustomerID.MaxLength = 5; colvarCustomerID.AutoIncrement = false; colvarCustomerID.IsNullable = true; colvarCustomerID.IsPrimaryKey = false; colvarCustomerID.IsForeignKey = false; colvarCustomerID.IsReadOnly = false; schema.Columns.Add(colvarCustomerID); TableSchema.TableColumn colvarCustomerName = new TableSchema.TableColumn(schema); colvarCustomerName.ColumnName = "CustomerName"; colvarCustomerName.DataType = DbType.String; colvarCustomerName.MaxLength = 40; colvarCustomerName.AutoIncrement = false; colvarCustomerName.IsNullable = false; colvarCustomerName.IsPrimaryKey = false; colvarCustomerName.IsForeignKey = false; colvarCustomerName.IsReadOnly = false; schema.Columns.Add(colvarCustomerName); TableSchema.TableColumn colvarAddress = new TableSchema.TableColumn(schema); colvarAddress.ColumnName = "Address"; colvarAddress.DataType = DbType.String; colvarAddress.MaxLength = 60; colvarAddress.AutoIncrement = false; colvarAddress.IsNullable = true; colvarAddress.IsPrimaryKey = false; colvarAddress.IsForeignKey = false; colvarAddress.IsReadOnly = false; schema.Columns.Add(colvarAddress); TableSchema.TableColumn colvarCity = new TableSchema.TableColumn(schema); colvarCity.ColumnName = "City"; colvarCity.DataType = DbType.String; colvarCity.MaxLength = 15; colvarCity.AutoIncrement = false; colvarCity.IsNullable = true; colvarCity.IsPrimaryKey = false; colvarCity.IsForeignKey = false; colvarCity.IsReadOnly = false; schema.Columns.Add(colvarCity); TableSchema.TableColumn colvarRegion = new TableSchema.TableColumn(schema); colvarRegion.ColumnName = "Region"; colvarRegion.DataType = DbType.String; colvarRegion.MaxLength = 15; colvarRegion.AutoIncrement = false; colvarRegion.IsNullable = true; colvarRegion.IsPrimaryKey = false; colvarRegion.IsForeignKey = false; colvarRegion.IsReadOnly = false; schema.Columns.Add(colvarRegion); TableSchema.TableColumn colvarPostalCode = new TableSchema.TableColumn(schema); colvarPostalCode.ColumnName = "PostalCode"; colvarPostalCode.DataType = DbType.String; colvarPostalCode.MaxLength = 10; colvarPostalCode.AutoIncrement = false; colvarPostalCode.IsNullable = true; colvarPostalCode.IsPrimaryKey = false; colvarPostalCode.IsForeignKey = false; colvarPostalCode.IsReadOnly = false; schema.Columns.Add(colvarPostalCode); TableSchema.TableColumn colvarCountry = new TableSchema.TableColumn(schema); colvarCountry.ColumnName = "Country"; colvarCountry.DataType = DbType.String; colvarCountry.MaxLength = 15; colvarCountry.AutoIncrement = false; colvarCountry.IsNullable = true; colvarCountry.IsPrimaryKey = false; colvarCountry.IsForeignKey = false; colvarCountry.IsReadOnly = false; schema.Columns.Add(colvarCountry); TableSchema.TableColumn colvarSalesperson = new TableSchema.TableColumn(schema); colvarSalesperson.ColumnName = "Salesperson"; colvarSalesperson.DataType = DbType.String; colvarSalesperson.MaxLength = 31; colvarSalesperson.AutoIncrement = false; colvarSalesperson.IsNullable = false; colvarSalesperson.IsPrimaryKey = false; colvarSalesperson.IsForeignKey = false; colvarSalesperson.IsReadOnly = false; schema.Columns.Add(colvarSalesperson); TableSchema.TableColumn colvarOrderID = new TableSchema.TableColumn(schema); colvarOrderID.ColumnName = "OrderID"; colvarOrderID.DataType = DbType.Int32; colvarOrderID.MaxLength = 0; colvarOrderID.AutoIncrement = false; colvarOrderID.IsNullable = false; colvarOrderID.IsPrimaryKey = false; colvarOrderID.IsForeignKey = false; colvarOrderID.IsReadOnly = false; schema.Columns.Add(colvarOrderID); TableSchema.TableColumn colvarOrderDate = new TableSchema.TableColumn(schema); colvarOrderDate.ColumnName = "OrderDate"; colvarOrderDate.DataType = DbType.DateTime; colvarOrderDate.MaxLength = 0; colvarOrderDate.AutoIncrement = false; colvarOrderDate.IsNullable = true; colvarOrderDate.IsPrimaryKey = false; colvarOrderDate.IsForeignKey = false; colvarOrderDate.IsReadOnly = false; schema.Columns.Add(colvarOrderDate); TableSchema.TableColumn colvarRequiredDate = new TableSchema.TableColumn(schema); colvarRequiredDate.ColumnName = "RequiredDate"; colvarRequiredDate.DataType = DbType.DateTime; colvarRequiredDate.MaxLength = 0; colvarRequiredDate.AutoIncrement = false; colvarRequiredDate.IsNullable = true; colvarRequiredDate.IsPrimaryKey = false; colvarRequiredDate.IsForeignKey = false; colvarRequiredDate.IsReadOnly = false; schema.Columns.Add(colvarRequiredDate); TableSchema.TableColumn colvarShippedDate = new TableSchema.TableColumn(schema); colvarShippedDate.ColumnName = "ShippedDate"; colvarShippedDate.DataType = DbType.DateTime; colvarShippedDate.MaxLength = 0; colvarShippedDate.AutoIncrement = false; colvarShippedDate.IsNullable = true; colvarShippedDate.IsPrimaryKey = false; colvarShippedDate.IsForeignKey = false; colvarShippedDate.IsReadOnly = false; schema.Columns.Add(colvarShippedDate); TableSchema.TableColumn colvarShipperName = new TableSchema.TableColumn(schema); colvarShipperName.ColumnName = "ShipperName"; colvarShipperName.DataType = DbType.String; colvarShipperName.MaxLength = 40; colvarShipperName.AutoIncrement = false; colvarShipperName.IsNullable = false; colvarShipperName.IsPrimaryKey = false; colvarShipperName.IsForeignKey = false; colvarShipperName.IsReadOnly = false; schema.Columns.Add(colvarShipperName); TableSchema.TableColumn colvarProductID = new TableSchema.TableColumn(schema); colvarProductID.ColumnName = "ProductID"; colvarProductID.DataType = DbType.Int32; colvarProductID.MaxLength = 0; colvarProductID.AutoIncrement = false; colvarProductID.IsNullable = false; colvarProductID.IsPrimaryKey = false; colvarProductID.IsForeignKey = false; colvarProductID.IsReadOnly = false; schema.Columns.Add(colvarProductID); TableSchema.TableColumn colvarProductName = new TableSchema.TableColumn(schema); colvarProductName.ColumnName = "ProductName"; colvarProductName.DataType = DbType.String; colvarProductName.MaxLength = 40; colvarProductName.AutoIncrement = false; colvarProductName.IsNullable = false; colvarProductName.IsPrimaryKey = false; colvarProductName.IsForeignKey = false; colvarProductName.IsReadOnly = false; schema.Columns.Add(colvarProductName); TableSchema.TableColumn colvarUnitPrice = new TableSchema.TableColumn(schema); colvarUnitPrice.ColumnName = "UnitPrice"; colvarUnitPrice.DataType = DbType.Currency; colvarUnitPrice.MaxLength = 0; colvarUnitPrice.AutoIncrement = false; colvarUnitPrice.IsNullable = false; colvarUnitPrice.IsPrimaryKey = false; colvarUnitPrice.IsForeignKey = false; colvarUnitPrice.IsReadOnly = false; schema.Columns.Add(colvarUnitPrice); TableSchema.TableColumn colvarQuantity = new TableSchema.TableColumn(schema); colvarQuantity.ColumnName = "Quantity"; colvarQuantity.DataType = DbType.Int16; colvarQuantity.MaxLength = 0; colvarQuantity.AutoIncrement = false; colvarQuantity.IsNullable = false; colvarQuantity.IsPrimaryKey = false; colvarQuantity.IsForeignKey = false; colvarQuantity.IsReadOnly = false; schema.Columns.Add(colvarQuantity); TableSchema.TableColumn colvarDiscount = new TableSchema.TableColumn(schema); colvarDiscount.ColumnName = "Discount"; colvarDiscount.DataType = DbType.Single; colvarDiscount.MaxLength = 0; colvarDiscount.AutoIncrement = false; colvarDiscount.IsNullable = false; colvarDiscount.IsPrimaryKey = false; colvarDiscount.IsForeignKey = false; colvarDiscount.IsReadOnly = false; schema.Columns.Add(colvarDiscount); TableSchema.TableColumn colvarExtendedPrice = new TableSchema.TableColumn(schema); colvarExtendedPrice.ColumnName = "ExtendedPrice"; colvarExtendedPrice.DataType = DbType.Currency; colvarExtendedPrice.MaxLength = 0; colvarExtendedPrice.AutoIncrement = false; colvarExtendedPrice.IsNullable = true; colvarExtendedPrice.IsPrimaryKey = false; colvarExtendedPrice.IsForeignKey = false; colvarExtendedPrice.IsReadOnly = false; schema.Columns.Add(colvarExtendedPrice); TableSchema.TableColumn colvarFreight = new TableSchema.TableColumn(schema); colvarFreight.ColumnName = "Freight"; colvarFreight.DataType = DbType.Currency; colvarFreight.MaxLength = 0; colvarFreight.AutoIncrement = false; colvarFreight.IsNullable = true; colvarFreight.IsPrimaryKey = false; colvarFreight.IsForeignKey = false; colvarFreight.IsReadOnly = false; schema.Columns.Add(colvarFreight); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["Northwind"].AddSchema("Invoices",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public Invoice() { SetSQLProps(); SetDefaults(); MarkNew(); } public Invoice(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public Invoice(object keyID) { SetSQLProps(); LoadByKey(keyID); } public Invoice(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("ShipName")] [Bindable(true)] public string ShipName { get { return GetColumnValue<string>("ShipName"); } set { SetColumnValue("ShipName", value); } } [XmlAttribute("ShipAddress")] [Bindable(true)] public string ShipAddress { get { return GetColumnValue<string>("ShipAddress"); } set { SetColumnValue("ShipAddress", value); } } [XmlAttribute("ShipCity")] [Bindable(true)] public string ShipCity { get { return GetColumnValue<string>("ShipCity"); } set { SetColumnValue("ShipCity", value); } } [XmlAttribute("ShipRegion")] [Bindable(true)] public string ShipRegion { get { return GetColumnValue<string>("ShipRegion"); } set { SetColumnValue("ShipRegion", value); } } [XmlAttribute("ShipPostalCode")] [Bindable(true)] public string ShipPostalCode { get { return GetColumnValue<string>("ShipPostalCode"); } set { SetColumnValue("ShipPostalCode", value); } } [XmlAttribute("ShipCountry")] [Bindable(true)] public string ShipCountry { get { return GetColumnValue<string>("ShipCountry"); } set { SetColumnValue("ShipCountry", value); } } [XmlAttribute("CustomerID")] [Bindable(true)] public string CustomerID { get { return GetColumnValue<string>("CustomerID"); } set { SetColumnValue("CustomerID", value); } } [XmlAttribute("CustomerName")] [Bindable(true)] public string CustomerName { get { return GetColumnValue<string>("CustomerName"); } set { SetColumnValue("CustomerName", value); } } [XmlAttribute("Address")] [Bindable(true)] public string Address { get { return GetColumnValue<string>("Address"); } set { SetColumnValue("Address", value); } } [XmlAttribute("City")] [Bindable(true)] public string City { get { return GetColumnValue<string>("City"); } set { SetColumnValue("City", value); } } [XmlAttribute("Region")] [Bindable(true)] public string Region { get { return GetColumnValue<string>("Region"); } set { SetColumnValue("Region", value); } } [XmlAttribute("PostalCode")] [Bindable(true)] public string PostalCode { get { return GetColumnValue<string>("PostalCode"); } set { SetColumnValue("PostalCode", value); } } [XmlAttribute("Country")] [Bindable(true)] public string Country { get { return GetColumnValue<string>("Country"); } set { SetColumnValue("Country", value); } } [XmlAttribute("Salesperson")] [Bindable(true)] public string Salesperson { get { return GetColumnValue<string>("Salesperson"); } set { SetColumnValue("Salesperson", value); } } [XmlAttribute("OrderID")] [Bindable(true)] public int OrderID { get { return GetColumnValue<int>("OrderID"); } set { SetColumnValue("OrderID", value); } } [XmlAttribute("OrderDate")] [Bindable(true)] public DateTime? OrderDate { get { return GetColumnValue<DateTime?>("OrderDate"); } set { SetColumnValue("OrderDate", value); } } [XmlAttribute("RequiredDate")] [Bindable(true)] public DateTime? RequiredDate { get { return GetColumnValue<DateTime?>("RequiredDate"); } set { SetColumnValue("RequiredDate", value); } } [XmlAttribute("ShippedDate")] [Bindable(true)] public DateTime? ShippedDate { get { return GetColumnValue<DateTime?>("ShippedDate"); } set { SetColumnValue("ShippedDate", value); } } [XmlAttribute("ShipperName")] [Bindable(true)] public string ShipperName { get { return GetColumnValue<string>("ShipperName"); } set { SetColumnValue("ShipperName", value); } } [XmlAttribute("ProductID")] [Bindable(true)] public int ProductID { get { return GetColumnValue<int>("ProductID"); } set { SetColumnValue("ProductID", value); } } [XmlAttribute("ProductName")] [Bindable(true)] public string ProductName { get { return GetColumnValue<string>("ProductName"); } set { SetColumnValue("ProductName", value); } } [XmlAttribute("UnitPrice")] [Bindable(true)] public decimal UnitPrice { get { return GetColumnValue<decimal>("UnitPrice"); } set { SetColumnValue("UnitPrice", value); } } [XmlAttribute("Quantity")] [Bindable(true)] public short Quantity { get { return GetColumnValue<short>("Quantity"); } set { SetColumnValue("Quantity", value); } } [XmlAttribute("Discount")] [Bindable(true)] public float Discount { get { return GetColumnValue<float>("Discount"); } set { SetColumnValue("Discount", value); } } [XmlAttribute("ExtendedPrice")] [Bindable(true)] public decimal? ExtendedPrice { get { return GetColumnValue<decimal?>("ExtendedPrice"); } set { SetColumnValue("ExtendedPrice", value); } } [XmlAttribute("Freight")] [Bindable(true)] public decimal? Freight { get { return GetColumnValue<decimal?>("Freight"); } set { SetColumnValue("Freight", value); } } #endregion #region Columns Struct public struct Columns { public static string ShipName = @"ShipName"; public static string ShipAddress = @"ShipAddress"; public static string ShipCity = @"ShipCity"; public static string ShipRegion = @"ShipRegion"; public static string ShipPostalCode = @"ShipPostalCode"; public static string ShipCountry = @"ShipCountry"; public static string CustomerID = @"CustomerID"; public static string CustomerName = @"CustomerName"; public static string Address = @"Address"; public static string City = @"City"; public static string Region = @"Region"; public static string PostalCode = @"PostalCode"; public static string Country = @"Country"; public static string Salesperson = @"Salesperson"; public static string OrderID = @"OrderID"; public static string OrderDate = @"OrderDate"; public static string RequiredDate = @"RequiredDate"; public static string ShippedDate = @"ShippedDate"; public static string ShipperName = @"ShipperName"; public static string ProductID = @"ProductID"; public static string ProductName = @"ProductName"; public static string UnitPrice = @"UnitPrice"; public static string Quantity = @"Quantity"; public static string Discount = @"Discount"; public static string ExtendedPrice = @"ExtendedPrice"; public static string Freight = @"Freight"; } #endregion #region IAbstractRecord Members public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } public object GetColumnValue(string columnName) { return base.GetColumnValue<object>(columnName); } #endregion } }
public static class GlobalMembersGdimagepolygon1 { #if __cplusplus #endif #define GD_H #define GD_MAJOR_VERSION #define GD_MINOR_VERSION #define GD_RELEASE_VERSION #define GD_EXTRA_VERSION //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdXXX_VERSION_STR(mjr, mnr, rev, ext) mjr "." mnr "." rev ext #define GDXXX_VERSION_STR //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdXXX_STR(s) gd.gdXXX_SSTR(s) #define GDXXX_STR //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdXXX_SSTR(s) #s #define GDXXX_SSTR //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define GD_VERSION_STRING "GD_MAJOR_VERSION" "." "GD_MINOR_VERSION" "." "GD_RELEASE_VERSION" GD_EXTRA_VERSION #define GD_VERSION_STRING #if _WIN32 || CYGWIN || _WIN32_WCE #if BGDWIN32 #if NONDLL #define BGD_EXPORT_DATA_PROT #else #if __GNUC__ #define BGD_EXPORT_DATA_PROT #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_EXPORT_DATA_PROT __declspec(dllexport) #define BGD_EXPORT_DATA_PROT #endif #endif #else #if __GNUC__ #define BGD_EXPORT_DATA_PROT #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_EXPORT_DATA_PROT __declspec(dllimport) #define BGD_EXPORT_DATA_PROT #endif #endif //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_STDCALL __stdcall #define BGD_STDCALL #define BGD_EXPORT_DATA_IMPL #else #if HAVE_VISIBILITY #define BGD_EXPORT_DATA_PROT #define BGD_EXPORT_DATA_IMPL #else #define BGD_EXPORT_DATA_PROT #define BGD_EXPORT_DATA_IMPL #endif #define BGD_STDCALL #endif #if BGD_EXPORT_DATA_PROT_ConditionalDefinition1 #if BGD_STDCALL_ConditionalDefinition1 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) rt __stdcall #define BGD_DECLARE #elif BGD_STDCALL_ConditionalDefinition2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) rt #define BGD_DECLARE #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) rt BGD_STDCALLTangibleTempImmunity #define BGD_DECLARE #endif #elif BGD_EXPORT_DATA_PROT_ConditionalDefinition2 #if BGD_STDCALL_ConditionalDefinition1 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) rt __stdcall #define BGD_DECLARE #elif BGD_STDCALL_ConditionalDefinition2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) rt #define BGD_DECLARE #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) rt BGD_STDCALLTangibleTempImmunity #define BGD_DECLARE #endif #elif BGD_EXPORT_DATA_PROT_ConditionalDefinition3 #if BGD_STDCALL_ConditionalDefinition1 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt __stdcall #define BGD_DECLARE #elif BGD_STDCALL_ConditionalDefinition2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt #define BGD_DECLARE #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt BGD_STDCALLTangibleTempImmunity #define BGD_DECLARE #endif #elif BGD_EXPORT_DATA_PROT_ConditionalDefinition4 #if BGD_STDCALL_ConditionalDefinition1 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt __stdcall #define BGD_DECLARE #elif BGD_STDCALL_ConditionalDefinition2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt #define BGD_DECLARE #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt BGD_STDCALLTangibleTempImmunity #define BGD_DECLARE #endif #else #if BGD_STDCALL_ConditionalDefinition1 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt __stdcall #define BGD_DECLARE #elif BGD_STDCALL_ConditionalDefinition2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt #define BGD_DECLARE #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define Bgd.gd_DECLARE(rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt BGD_STDCALLTangibleTempImmunity #define BGD_DECLARE #endif #endif #if __cplusplus #endif #if __cplusplus #endif #define GD_IO_H #if VMS #endif #if __cplusplus #endif #define gdMaxColors #define gdAlphaMax #define gdAlphaOpaque #define gdAlphaTransparent #define gdRedMax #define gdGreenMax #define gdBlueMax //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTrueColorGetAlpha(c) (((c) & 0x7F000000) >> 24) #define gdTrueColorGetAlpha //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTrueColorGetRed(c) (((c) & 0xFF0000) >> 16) #define gdTrueColorGetRed //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTrueColorGetGreen(c) (((c) & 0x00FF00) >> 8) #define gdTrueColorGetGreen //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTrueColorGetBlue(c) ((c) & 0x0000FF) #define gdTrueColorGetBlue #define gdEffectReplace #define gdEffectAlphaBlend #define gdEffectNormal #define gdEffectOverlay #define GD_TRUE #define GD_FALSE #define GD_EPSILON #define M_PI #define gdDashSize #define gdStyled #define gdBrushed #define gdStyledBrushed #define gdTiled #define gdTransparent #define gdAntiAliased //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gdImageCreatePalette gdImageCreate #define gdImageCreatePalette #define gdFTEX_LINESPACE #define gdFTEX_CHARMAP #define gdFTEX_RESOLUTION #define gdFTEX_DISABLE_KERNING #define gdFTEX_XSHOW #define gdFTEX_FONTPATHNAME #define gdFTEX_FONTCONFIG #define gdFTEX_RETURNFONTPATHNAME #define gdFTEX_Unicode #define gdFTEX_Shift_JIS #define gdFTEX_Big5 #define gdFTEX_Adobe_Custom //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTrueColor(r, g, b) (((r) << 16) + ((g) << 8) + (b)) #define gdTrueColor //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTrueColorAlpha(r, g, b, a) (((a) << 24) + ((r) << 16) + ((g) << 8) + (b)) #define gdTrueColorAlpha #define gdArc //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gdPie gdArc #define gdPie #define gdChord #define gdNoFill #define gdEdged //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageTrueColor(im) ((im)->trueColor) #define gdImageTrueColor //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageSX(im) ((im)->sx) #define gdImageSX //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageSY(im) ((im)->sy) #define gdImageSY //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageColorsTotal(im) ((im)->colorsTotal) #define gdImageColorsTotal //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageRed(im, c) ((im)->trueColor ? (((c) & 0xFF0000) >> 16) : (im)->red[(c)]) #define gdImageRed //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageGreen(im, c) ((im)->trueColor ? (((c) & 0x00FF00) >> 8) : (im)->green[(c)]) #define gdImageGreen //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageBlue(im, c) ((im)->trueColor ? ((c) & 0x0000FF) : (im)->blue[(c)]) #define gdImageBlue //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageAlpha(im, c) ((im)->trueColor ? (((c) & 0x7F000000) >> 24) : (im)->alpha[(c)]) #define gdImageAlpha //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageGetTransparent(im) ((im)->transparent) #define gdImageGetTransparent //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageGetInterlaced(im) ((im)->interlace) #define gdImageGetInterlaced //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImagePalettePixel(im, x, y) (im)->pixels[(y)][(x)] #define gdImagePalettePixel //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageTrueColorPixel(im, x, y) (im)->tpixels[(y)][(x)] #define gdImageTrueColorPixel //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageResolutionX(im) (im)->res_x #define gdImageResolutionX //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageResolutionY(im) (im)->res_y #define gdImageResolutionY #define GD2_CHUNKSIZE #define GD2_CHUNKSIZE_MIN #define GD2_CHUNKSIZE_MAX #define GD2_VERS #define GD2_ID #define GD2_FMT_RAW #define GD2_FMT_COMPRESSED #define GD_FLIP_HORINZONTAL #define GD_FLIP_VERTICAL #define GD_FLIP_BOTH #define GD_CMP_IMAGE #define GD_CMP_NUM_COLORS #define GD_CMP_COLOR #define GD_CMP_SIZE_X #define GD_CMP_SIZE_Y #define GD_CMP_TRANSPARENT #define GD_CMP_BACKGROUND #define GD_CMP_INTERLACE #define GD_CMP_TRUECOLOR #define GD_RESOLUTION #if __cplusplus #endif #if __cplusplus #endif #define GDFX_H #if __cplusplus #endif #if __cplusplus #endif #if __cplusplus #endif #define GDHELPERS_H #if ! _WIN32_WCE #else #endif #if _WIN32 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexDeclare(x) CRITICAL_SECTION x #define gdMutexDeclare //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexSetup(x) InitializeCriticalSection(&x) #define gdMutexSetup //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexShutdown(x) DeleteCriticalSection(&x) #define gdMutexShutdown //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexLock(x) EnterCriticalSection(&x) #define gdMutexLock //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexUnlock(x) LeaveCriticalSection(&x) #define gdMutexUnlock #elif HAVE_PTHREAD //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexDeclare(x) pthread_mutex_t x #define gdMutexDeclare //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexSetup(x) pthread_mutex_init(&x, 0) #define gdMutexSetup //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexShutdown(x) pthread_mutex_destroy(&x) #define gdMutexShutdown //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexLock(x) pthread_mutex_lock(&x) #define gdMutexLock //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexUnlock(x) pthread_mutex_unlock(&x) #define gdMutexUnlock #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexDeclare(x) #define gdMutexDeclare //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexSetup(x) #define gdMutexSetup //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexShutdown(x) #define gdMutexShutdown //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexLock(x) #define gdMutexLock //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexUnlock(x) #define gdMutexUnlock #endif //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define DPCM2DPI(dpcm) (unsigned int)((dpcm)*2.54 + 0.5) #define DPCM2DPI //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define DPM2DPI(dpm) (unsigned int)((dpm)*0.0254 + 0.5) #define DPM2DPI //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define DPI2DPCM(dpi) (unsigned int)((dpi)/2.54 + 0.5) #define DPI2DPCM //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define DPI2DPM(dpi) (unsigned int)((dpi)/0.0254 + 0.5) #define DPI2DPM #if __cplusplus #endif #define GDTEST_TOP_DIR #define GDTEST_STRING_MAX //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdAssertImageEqualsToFile(ex,ac) gd.gdTestImageCompareToFile(__FILE__,__LINE__,NULL,(ex),(ac)) #define gdAssertImageEqualsToFile //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdAssertImageFileEqualsMsg(ex,ac) gd.gdTestImageCompareFiles(__FILE__,__LINE__,(ms),(ex),(ac)) #define gdAssertImageFileEqualsMsg //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdAssertImageEquals(tc,ex,ac) CuAssertImageEquals_LineMsg((tc),__FILE__,__LINE__,NULL,(ex),(ac)) #define gdAssertImageEquals //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdAssertImageEqualsMsg(tc,ex,ac) CuAssertImageEquals_LineMsg((tc),__FILE__,__LINE__,(ms),(ex),(ac)) #define gdAssertImageEqualsMsg //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTestAssert(cond) _gd.gdTestAssert(__FILE__, __LINE__, "assert failed in <%s:%i>\n", (cond)) #define gdTestAssert //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTestErrorMsg(...) _gd.gdTestErrorMsg(__FILE__, __LINE__, __VA_ARGS__) #define gdTestErrorMsg static int Main() { gdImageStruct im; int white; int black; int r; gdPoint points; im = gd.gdImageCreate(100, 100); if (im == null) Environment.Exit(1); white = gd.gdImageColorAllocate(im, 0xff, 0xff, 0xff); black = gd.gdImageColorAllocate(im, 0, 0, 0); gd.gdImageFilledRectangle(im, 0, 0, 99, 99, white); //C++ TO C# CONVERTER TODO TASK: The memory management function 'calloc' has no equivalent in C#: points = (gdPoint)calloc(3, sizeof(gdPoint)); if (points == null) { gd.gdImageDestroy(im); Environment.Exit(1); } points[0].x = 10; points[0].y = 10; gd.gdImagePolygon(im, points, 1, black); //C++ TO C# CONVERTER TODO TASK: There is no direct equivalent in C# to the following C++ macro: r = GlobalMembersGdtest.gd.gdTestImageCompareToFile(__FILE__, __LINE__, null, (DefineConstants.GDTEST_TOP_DIR "/gdimagepolygon/gdimagepolygon1.png"), (im)); //C++ TO C# CONVERTER TODO TASK: The memory management function 'free' has no equivalent in C#: free(points); gd.gdImageDestroy(im); if (r == 0) Environment.Exit(1); return EXIT_SUCCESS; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.IO; using System.Linq; using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.DataAnnotations; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Mvc.ViewEngines; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Mvc.ViewFeatures.Buffers; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Options; using Microsoft.Extensions.WebEncoders.Testing; using Moq; namespace Microsoft.AspNetCore.Mvc.Rendering { public class DefaultTemplatesUtilities { public class ObjectTemplateModel { public ObjectTemplateModel() { ComplexInnerModel = new object(); } public string Property1 { get; set; } [Display(Name = "Prop2")] public string Property2 { get; set; } public object ComplexInnerModel { get; set; } } public class ObjectWithScaffoldColumn { public string Property1 { get; set; } [ScaffoldColumn(false)] public string Property2 { get; set; } [ScaffoldColumn(true)] public string Property3 { get; set; } } public static HtmlHelper<ObjectTemplateModel> GetHtmlHelper() { return GetHtmlHelper<ObjectTemplateModel>(model: null); } public static HtmlHelper<IEnumerable<ObjectTemplateModel>> GetHtmlHelperForEnumerable() { return GetHtmlHelper<IEnumerable<ObjectTemplateModel>>(model: null); } public static HtmlHelper<ObjectTemplateModel> GetHtmlHelper(IUrlHelper urlHelper) { return GetHtmlHelper<ObjectTemplateModel>( model: null, urlHelper: urlHelper, viewEngine: CreateViewEngine(), provider: TestModelMetadataProvider.CreateDefaultProvider()); } public static HtmlHelper<ObjectTemplateModel> GetHtmlHelper(IHtmlGenerator htmlGenerator) { var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider(); return GetHtmlHelper<ObjectTemplateModel>( new ViewDataDictionary<ObjectTemplateModel>(metadataProvider), CreateUrlHelper(), CreateViewEngine(), metadataProvider, localizerFactory: null, innerHelperWrapper: null, htmlGenerator: htmlGenerator, idAttributeDotReplacement: null); } public static HtmlHelper<TModel> GetHtmlHelper<TModel>(ViewDataDictionary<TModel> viewData) { return GetHtmlHelper( viewData, CreateUrlHelper(), CreateViewEngine(), TestModelMetadataProvider.CreateDefaultProvider(), localizerFactory: null, innerHelperWrapper: null, htmlGenerator: null, idAttributeDotReplacement: null); } public static HtmlHelper<TModel> GetHtmlHelper<TModel>( ViewDataDictionary<TModel> viewData, string idAttributeDotReplacement) { return GetHtmlHelper( viewData, CreateUrlHelper(), CreateViewEngine(), TestModelMetadataProvider.CreateDefaultProvider(), localizerFactory: null, innerHelperWrapper: null, htmlGenerator: null, idAttributeDotReplacement: idAttributeDotReplacement); } public static HtmlHelper<TModel> GetHtmlHelper<TModel>(TModel model) { return GetHtmlHelper(model, CreateViewEngine()); } public static HtmlHelper<TModel> GetHtmlHelper<TModel>(TModel model, string idAttributeDotReplacement) { var provider = TestModelMetadataProvider.CreateDefaultProvider(); var viewData = new ViewDataDictionary<TModel>(provider); viewData.Model = model; return GetHtmlHelper( viewData, CreateUrlHelper(), CreateViewEngine(), provider, localizerFactory: null, innerHelperWrapper: null, htmlGenerator: null, idAttributeDotReplacement: idAttributeDotReplacement); } public static HtmlHelper<IEnumerable<TModel>> GetHtmlHelperForEnumerable<TModel>(TModel model) { return GetHtmlHelper<IEnumerable<TModel>>(new TModel[] { model }); } public static HtmlHelper<TModel> GetHtmlHelper<TModel>(IModelMetadataProvider provider) { return GetHtmlHelper<TModel>(model: default(TModel), provider: provider); } public static HtmlHelper<ObjectTemplateModel> GetHtmlHelper(IModelMetadataProvider provider) { return GetHtmlHelper<ObjectTemplateModel>(model: null, provider: provider); } public static HtmlHelper<IEnumerable<ObjectTemplateModel>> GetHtmlHelperForEnumerable( IModelMetadataProvider provider) { return GetHtmlHelper<IEnumerable<ObjectTemplateModel>>(model: null, provider: provider); } public static HtmlHelper<TModel> GetHtmlHelper<TModel>(TModel model, IModelMetadataProvider provider) { return GetHtmlHelper(model, CreateUrlHelper(), CreateViewEngine(), provider); } public static HtmlHelper<TModel> GetHtmlHelper<TModel>( TModel model, ICompositeViewEngine viewEngine, IStringLocalizerFactory stringLocalizerFactory = null) { return GetHtmlHelper( model, CreateUrlHelper(), viewEngine, TestModelMetadataProvider.CreateDefaultProvider(stringLocalizerFactory), stringLocalizerFactory); } public static HtmlHelper<TModel> GetHtmlHelper<TModel>( TModel model, ICompositeViewEngine viewEngine, Func<IHtmlHelper, IHtmlHelper> innerHelperWrapper) { return GetHtmlHelper( model, CreateUrlHelper(), viewEngine, TestModelMetadataProvider.CreateDefaultProvider(), localizerFactory: null, innerHelperWrapper); } public static HtmlHelper<TModel> GetHtmlHelper<TModel>( TModel model, IUrlHelper urlHelper, ICompositeViewEngine viewEngine, IModelMetadataProvider provider, IStringLocalizerFactory localizerFactory = null) { return GetHtmlHelper(model, urlHelper, viewEngine, provider, localizerFactory, innerHelperWrapper: null); } public static HtmlHelper<TModel> GetHtmlHelper<TModel>( TModel model, IUrlHelper urlHelper, ICompositeViewEngine viewEngine, IModelMetadataProvider provider, IStringLocalizerFactory localizerFactory, Func<IHtmlHelper, IHtmlHelper> innerHelperWrapper) { var viewData = new ViewDataDictionary<TModel>(provider); viewData.Model = model; return GetHtmlHelper( viewData, urlHelper, viewEngine, provider, localizerFactory, innerHelperWrapper, htmlGenerator: null, idAttributeDotReplacement: null); } private static HtmlHelper<TModel> GetHtmlHelper<TModel>( ViewDataDictionary<TModel> viewData, IUrlHelper urlHelper, ICompositeViewEngine viewEngine, IModelMetadataProvider provider, IStringLocalizerFactory localizerFactory, Func<IHtmlHelper, IHtmlHelper> innerHelperWrapper, IHtmlGenerator htmlGenerator, string idAttributeDotReplacement) { var httpContext = new DefaultHttpContext(); var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); var options = new MvcViewOptions(); if (!string.IsNullOrEmpty(idAttributeDotReplacement)) { options.HtmlHelperOptions.IdAttributeDotReplacement = idAttributeDotReplacement; } var localizationOptions = new MvcDataAnnotationsLocalizationOptions(); var localizationOptionsAccesor = Options.Create(localizationOptions); options.ClientModelValidatorProviders.Add(new DataAnnotationsClientModelValidatorProvider( new ValidationAttributeAdapterProvider(), localizationOptionsAccesor, localizerFactory)); var urlHelperFactory = new Mock<IUrlHelperFactory>(); urlHelperFactory .Setup(f => f.GetUrlHelper(It.IsAny<ActionContext>())) .Returns(urlHelper); if (htmlGenerator == null) { htmlGenerator = HtmlGeneratorUtilities.GetHtmlGenerator(provider, urlHelperFactory.Object, options); } // TemplateRenderer will Contextualize this transient service. var innerHelper = (IHtmlHelper)new HtmlHelper( htmlGenerator, viewEngine, provider, new TestViewBufferScope(), new HtmlTestEncoder(), UrlEncoder.Default); if (innerHelperWrapper != null) { innerHelper = innerHelperWrapper(innerHelper); } var serviceProvider = new ServiceCollection() .AddSingleton(viewEngine) .AddSingleton(urlHelperFactory.Object) .AddSingleton(Mock.Of<IViewComponentHelper>()) .AddSingleton(innerHelper) .AddSingleton<IViewBufferScope, TestViewBufferScope>() .BuildServiceProvider(); httpContext.RequestServices = serviceProvider; var htmlHelper = new HtmlHelper<TModel>( htmlGenerator, viewEngine, provider, new TestViewBufferScope(), new HtmlTestEncoder(), UrlEncoder.Default, new ModelExpressionProvider(provider)); var viewContext = new ViewContext( actionContext, Mock.Of<IView>(), viewData, new TempDataDictionary( httpContext, Mock.Of<ITempDataProvider>()), new StringWriter(), options.HtmlHelperOptions); htmlHelper.Contextualize(viewContext); return htmlHelper; } private static ICompositeViewEngine CreateViewEngine() { var view = new Mock<IView>(); view .Setup(v => v.RenderAsync(It.IsAny<ViewContext>())) .Callback(async (ViewContext v) => { view.ToString(); await v.Writer.WriteAsync(FormatOutput(v.ViewData.ModelExplorer)); }) .Returns(Task.FromResult(0)); var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict); viewEngine .Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false)) .Returns(ViewEngineResult.NotFound("MyView", Enumerable.Empty<string>())) .Verifiable(); viewEngine .Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false)) .Returns(ViewEngineResult.Found("MyView", view.Object)) .Verifiable(); return viewEngine.Object; } public static string FormatOutput(IHtmlHelper helper, object model) { var modelExplorer = helper.MetadataProvider.GetModelExplorerForType(model.GetType(), model); return FormatOutput(modelExplorer); } private static string FormatOutput(ModelExplorer modelExplorer) { var metadata = modelExplorer.Metadata; return string.Format( CultureInfo.InvariantCulture, "Model = {0}, ModelType = {1}, PropertyName = {2}, SimpleDisplayText = {3}", modelExplorer.Model ?? "(null)", metadata.ModelType == null ? "(null)" : metadata.ModelType.FullName, metadata.PropertyName ?? "(null)", modelExplorer.GetSimpleDisplayText() ?? "(null)"); } private static IUrlHelper CreateUrlHelper() { return Mock.Of<IUrlHelper>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Orleans.Runtime.Configuration; using Orleans.Runtime.Scheduler; namespace Orleans.Runtime.GrainDirectory { /// <summary> /// Most methods of this class are synchronized since they might be called both /// from LocalGrainDirectory on CacheValidator.SchedulingContext and from RemoteGrainDirectory. /// </summary> internal class GrainDirectoryHandoffManager { private const int HANDOFF_CHUNK_SIZE = 500; private readonly LocalGrainDirectory localDirectory; private readonly Dictionary<SiloAddress, GrainDirectoryPartition> directoryPartitionsMap; private readonly List<SiloAddress> silosHoldingMyPartition; private readonly Dictionary<SiloAddress, Task> lastPromise; private readonly Logger logger; internal GrainDirectoryHandoffManager(LocalGrainDirectory localDirectory, GlobalConfiguration config) { logger = LogManager.GetLogger(this.GetType().FullName); this.localDirectory = localDirectory; directoryPartitionsMap = new Dictionary<SiloAddress, GrainDirectoryPartition>(); silosHoldingMyPartition = new List<SiloAddress>(); lastPromise = new Dictionary<SiloAddress, Task>(); } internal List<ActivationAddress> GetHandedOffInfo(GrainId grain) { lock (this) { foreach (var partition in directoryPartitionsMap.Values) { var result = partition.LookUpActivations(grain); if (result.Addresses != null) return result.Addresses; } } return null; } private async Task HandoffMyPartitionUponStop(Dictionary<GrainId, IGrainInfo> batchUpdate, bool isFullCopy) { if (batchUpdate.Count == 0 || silosHoldingMyPartition.Count == 0) { if (logger.IsVerbose) logger.Verbose((isFullCopy ? "FULL" : "DELTA") + " handoff finished with empty delta (nothing to send)"); return; } if (logger.IsVerbose) logger.Verbose("Sending {0} items to my {1}: (ring status is {2})", batchUpdate.Count, silosHoldingMyPartition.ToStrings(), localDirectory.RingStatusToString()); var tasks = new List<Task>(); var n = 0; var chunk = new Dictionary<GrainId, IGrainInfo>(); // Note that batchUpdate will not change while this method is executing foreach (var pair in batchUpdate) { chunk[pair.Key] = pair.Value; n++; if ((n % HANDOFF_CHUNK_SIZE != 0) && (n != batchUpdate.Count)) { // If we haven't filled in a chunk yet, keep looping. continue; } foreach (SiloAddress silo in silosHoldingMyPartition) { SiloAddress captureSilo = silo; Dictionary<GrainId, IGrainInfo> captureChunk = chunk; bool captureIsFullCopy = isFullCopy; if (logger.IsVerbose) logger.Verbose("Sending handed off partition to " + captureSilo); Task pendingRequest; if (lastPromise.TryGetValue(captureSilo, out pendingRequest)) { try { await pendingRequest; } catch (Exception) { } } Task task = localDirectory.Scheduler.RunOrQueueTask( () => localDirectory.GetDirectoryReference(captureSilo).AcceptHandoffPartition( localDirectory.MyAddress, captureChunk, captureIsFullCopy), localDirectory.RemoteGrainDirectory.SchedulingContext); lastPromise[captureSilo] = task; tasks.Add(task); } // We need to use a new Dictionary because the call to AcceptHandoffPartition, which reads the current Dictionary, // happens asynchronously (and typically after some delay). chunk = new Dictionary<GrainId, IGrainInfo>(); // This is a quick temporary solution. We send a full copy by sending one chunk as a full copy and follow-on chunks as deltas. // Obviously, this will really mess up if there's a failure after the first chunk but before the others are sent, since on a // full copy receive the follower dumps all old data and replaces it with the new full copy. // On the other hand, over time things should correct themselves, and of course, losing directory data isn't necessarily catastrophic. isFullCopy = false; } await Task.WhenAll(tasks); } internal void ProcessSiloRemoveEvent(SiloAddress removedSilo) { lock (this) { if (logger.IsVerbose) logger.Verbose("Processing silo remove event for " + removedSilo); // Reset our follower list to take the changes into account ResetFollowers(); // check if this is one of our successors (i.e., if I hold this silo's copy) // (if yes, adjust local and/or handoffed directory partitions) if (!directoryPartitionsMap.ContainsKey(removedSilo)) return; // at least one predcessor should exist, which is me SiloAddress predecessor = localDirectory.FindPredecessors(removedSilo, 1)[0]; if (localDirectory.MyAddress.Equals(predecessor)) { if (logger.IsVerbose) logger.Verbose("Merging my partition with the copy of silo " + removedSilo); // now I am responsible for this directory part localDirectory.DirectoryPartition.Merge(directoryPartitionsMap[removedSilo]); // no need to send our new partition to all others, as they // will realize the change and combine their copies without any additional communication (see below) } else { if (logger.IsVerbose) logger.Verbose("Merging partition of " + predecessor + " with the copy of silo " + removedSilo); // adjust copy for the predecessor of the failed silo directoryPartitionsMap[predecessor].Merge(directoryPartitionsMap[removedSilo]); } localDirectory.GsiActivationMaintainer.TrackDoubtfulGrains(directoryPartitionsMap[removedSilo].GetItems()); if (logger.IsVerbose) logger.Verbose("Removed copied partition of silo " + removedSilo); directoryPartitionsMap.Remove(removedSilo); } } internal void ProcessSiloStoppingEvent() { lock (this) { ProcessSiloStoppingEvent_Impl(); } } private async void ProcessSiloStoppingEvent_Impl() { if (logger.IsVerbose) logger.Verbose("Processing silo stopping event"); // Select our nearest predecessor to receive our hand-off, since that's the silo that will wind up owning our partition (assuming // that it doesn't also fail and that no other silo joins during the transition period). if (silosHoldingMyPartition.Count == 0) { silosHoldingMyPartition.AddRange(localDirectory.FindPredecessors(localDirectory.MyAddress, 1)); } // take a copy of the current directory partition Dictionary<GrainId, IGrainInfo> batchUpdate = localDirectory.DirectoryPartition.GetItems(); try { await HandoffMyPartitionUponStop(batchUpdate, true); localDirectory.MarkStopPreparationCompleted(); } catch (Exception exc) { localDirectory.MarkStopPreparationFailed(exc); } } internal void ProcessSiloAddEvent(SiloAddress addedSilo) { lock (this) { if (logger.IsVerbose) logger.Verbose("Processing silo add event for " + addedSilo); // Reset our follower list to take the changes into account ResetFollowers(); // check if this is one of our successors (i.e., if I should hold this silo's copy) // (if yes, adjust local and/or copied directory partitions by splitting them between old successors and the new one) // NOTE: We need to move part of our local directory to the new silo if it is an immediate successor. List<SiloAddress> successors = localDirectory.FindSuccessors(localDirectory.MyAddress, 1); if (!successors.Contains(addedSilo)) return; // check if this is an immediate successor if (successors[0].Equals(addedSilo)) { // split my local directory and send to my new immediate successor his share if (logger.IsVerbose) logger.Verbose("Splitting my partition between me and " + addedSilo); GrainDirectoryPartition splitPart = localDirectory.DirectoryPartition.Split( grain => { var s = localDirectory.CalculateTargetSilo(grain); return (s != null) && !localDirectory.MyAddress.Equals(s); }, false); List<ActivationAddress> splitPartListSingle = splitPart.ToListOfActivations(true); List<ActivationAddress> splitPartListMulti = splitPart.ToListOfActivations(false); if (splitPartListSingle.Count > 0) { if (logger.IsVerbose) logger.Verbose("Sending " + splitPartListSingle.Count + " single activation entries to " + addedSilo); localDirectory.Scheduler.QueueTask(async () => { await localDirectory.GetDirectoryReference(successors[0]).RegisterMany(splitPartListSingle, singleActivation:true); splitPartListSingle.ForEach( activationAddress => localDirectory.DirectoryPartition.RemoveGrain(activationAddress.Grain)); }, localDirectory.RemoteGrainDirectory.SchedulingContext).Ignore(); } if (splitPartListMulti.Count > 0) { if (logger.IsVerbose) logger.Verbose("Sending " + splitPartListMulti.Count + " entries to " + addedSilo); localDirectory.Scheduler.QueueTask(async () => { await localDirectory.GetDirectoryReference(successors[0]).RegisterMany(splitPartListMulti, singleActivation:false); splitPartListMulti.ForEach( activationAddress => localDirectory.DirectoryPartition.RemoveGrain(activationAddress.Grain)); }, localDirectory.RemoteGrainDirectory.SchedulingContext).Ignore(); } } else { // adjust partitions by splitting them accordingly between new and old silos SiloAddress predecessorOfNewSilo = localDirectory.FindPredecessors(addedSilo, 1)[0]; if (!directoryPartitionsMap.ContainsKey(predecessorOfNewSilo)) { // we should have the partition of the predcessor of our new successor logger.Warn(ErrorCode.DirectoryPartitionPredecessorExpected, "This silo is expected to hold directory partition of " + predecessorOfNewSilo); } else { if (logger.IsVerbose) logger.Verbose("Splitting partition of " + predecessorOfNewSilo + " and creating a copy for " + addedSilo); GrainDirectoryPartition splitPart = directoryPartitionsMap[predecessorOfNewSilo].Split( grain => { // Need to review the 2nd line condition. var s = localDirectory.CalculateTargetSilo(grain); return (s != null) && !predecessorOfNewSilo.Equals(s); }, true); directoryPartitionsMap[addedSilo] = splitPart; } } // remove partition of one of the old successors that we do not need to now SiloAddress oldSuccessor = directoryPartitionsMap.FirstOrDefault(pair => !successors.Contains(pair.Key)).Key; if (oldSuccessor == null) return; if (logger.IsVerbose) logger.Verbose("Removing copy of the directory partition of silo " + oldSuccessor + " (holding copy of " + addedSilo + " instead)"); directoryPartitionsMap.Remove(oldSuccessor); } } internal void AcceptHandoffPartition(SiloAddress source, Dictionary<GrainId, IGrainInfo> partition, bool isFullCopy) { if (logger.IsVerbose) logger.Verbose("Got request to register " + (isFullCopy ? "FULL" : "DELTA") + " directory partition with " + partition.Count + " elements from " + source); if (!directoryPartitionsMap.ContainsKey(source)) { if (!isFullCopy) { logger.Warn(ErrorCode.DirectoryUnexpectedDelta, String.Format("Got delta of the directory partition from silo {0} (Membership status {1}) while not holding a full copy. Membership active cluster size is {2}", source, localDirectory.Membership.GetApproximateSiloStatus(source), localDirectory.Membership.GetApproximateSiloStatuses(true).Count)); } directoryPartitionsMap[source] = new GrainDirectoryPartition(); } if (isFullCopy) { directoryPartitionsMap[source].Set(partition); } else { directoryPartitionsMap[source].Update(partition); } localDirectory.GsiActivationMaintainer.TrackDoubtfulGrains(partition); } internal void RemoveHandoffPartition(SiloAddress source) { if (logger.IsVerbose) logger.Verbose("Got request to unregister directory partition copy from " + source); directoryPartitionsMap.Remove(source); } private void ResetFollowers() { var copyList = silosHoldingMyPartition.ToList(); foreach (var follower in copyList) { RemoveOldFollower(follower); } } private void RemoveOldFollower(SiloAddress silo) { if (logger.IsVerbose) logger.Verbose("Removing my copy from silo " + silo); // release this old copy, as we have got a new one silosHoldingMyPartition.Remove(silo); localDirectory.Scheduler.QueueTask(() => localDirectory.GetDirectoryReference(silo).RemoveHandoffPartition(localDirectory.MyAddress), localDirectory.RemoteGrainDirectory.SchedulingContext).Ignore(); } } }
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using Moq; using NUnit.Framework; using XenAdmin.Alerts; using XenAdmin.Core; using XenAdmin.Network; using XenAdminTests.UnitTests.UnitTestHelper; using XenAPI; namespace XenAdminTests.UnitTests.AlertTests { [TestFixture, Category(TestCategories.Unit), Category(TestCategories.SmokeTest)] public class XenServerPatchAlertTests { private Mock<IXenConnection> connA; private Mock<IXenConnection> connB; private Mock<Host> hostA; private Mock<Host> hostB; protected Cache cacheA; protected Cache cacheB; [Test] public void TestAlertWithConnectionAndHosts() { XenServerPatch p = new XenServerPatch("uuid", "name", "My description", "guidance", string.Empty, "6.0.1", "http://url", "http://patchUrl", new DateTime(2011, 4, 1).ToString(), "", ""); XenServerPatchAlert alert = new XenServerPatchAlert(p); alert.IncludeConnection(connA.Object); alert.IncludeConnection(connB.Object); alert.IncludeHosts(new List<Host> { hostA.Object, hostB.Object }); IUnitTestVerifier validator = new VerifyGetters(alert); validator.Verify(new AlertClassUnitTestData { AppliesTo = "HostAName, HostBName, ConnAName, ConnBName", FixLinkText = "Go to Web Page", HelpID = "XenServerPatchAlert", Description = "My description", HelpLinkText = "Help", Title = "New Update Available - name", Priority = "Priority2" }); Assert.IsFalse(alert.CanIgnore); VerifyConnExpectations(Times.Once); VerifyHostsExpectations(Times.Once); } [Test] public void TestAlertWithHostsAndNoConnection() { XenServerPatch p = new XenServerPatch("uuid", "name", "My description", "guidance", string.Empty, "6.0.1", "http://url", "http://patchUrl", new DateTime(2011, 4, 1).ToString(), "1", ""); XenServerPatchAlert alert = new XenServerPatchAlert(p); alert.IncludeHosts(new List<Host>() { hostA.Object, hostB.Object }); IUnitTestVerifier validator = new VerifyGetters(alert); validator.Verify(new AlertClassUnitTestData { AppliesTo = "HostAName, HostBName", FixLinkText = "Go to Web Page", HelpID = "XenServerPatchAlert", Description = "My description", HelpLinkText = "Help", Title = "New Update Available - name", Priority = "Priority1" }); Assert.IsFalse(alert.CanIgnore); VerifyConnExpectations(Times.Never); VerifyHostsExpectations(Times.Once); } [Test] public void TestAlertWithConnectionAndNoHosts() { XenServerPatch p = new XenServerPatch("uuid", "name", "My description", "guidance", string.Empty, "6.0.1", "http://url", "http://patchUrl", new DateTime(2011, 4, 1).ToString(), "0", ""); XenServerPatchAlert alert = new XenServerPatchAlert(p); alert.IncludeConnection(connA.Object); alert.IncludeConnection(connB.Object); IUnitTestVerifier validator = new VerifyGetters(alert); validator.Verify(new AlertClassUnitTestData { AppliesTo = "ConnAName, ConnBName", FixLinkText = "Go to Web Page", HelpID = "XenServerPatchAlert", Description = "My description", HelpLinkText = "Help", Title = "New Update Available - name", Priority = "Unknown" }); Assert.IsFalse(alert.CanIgnore); VerifyConnExpectations(Times.Once); VerifyHostsExpectations(Times.Never); } [Test] public void TestAlertWithNoConnectionAndNoHosts() { XenServerPatch p = new XenServerPatch("uuid", "name", "My description", "guidance", string.Empty, "6.0.1", "http://url", "http://patchUrl", new DateTime(2011, 4, 1).ToString(), "5", ""); XenServerPatchAlert alert = new XenServerPatchAlert(p); IUnitTestVerifier validator = new VerifyGetters(alert); validator.Verify(new AlertClassUnitTestData { AppliesTo = string.Empty, FixLinkText = "Go to Web Page", HelpID = "XenServerPatchAlert", Description = "My description", HelpLinkText = "Help", Title = "New Update Available - name", Priority = "Priority5" }); Assert.IsTrue(alert.CanIgnore); VerifyConnExpectations(Times.Never); VerifyHostsExpectations(Times.Never); } [Test, ExpectedException(typeof(NullReferenceException))] public void TestAlertWithNullPatch() { XenServerPatchAlert alert = new XenServerPatchAlert(null); } private void VerifyConnExpectations(Func<Times> times) { connA.Verify(n => n.Name, times()); connB.Verify(n => n.Name, times()); } private void VerifyHostsExpectations(Func<Times> times) { hostA.Verify(n => n.Name(), times()); hostB.Verify(n => n.Name(), times()); } [SetUp] public void TestSetUp() { connA = new Mock<IXenConnection>(MockBehavior.Strict); connA.Setup(n => n.Name).Returns("ConnAName"); cacheA = new Cache(); connA.Setup(x => x.Cache).Returns(cacheA); connB = new Mock<IXenConnection>(MockBehavior.Strict); connB.Setup(n => n.Name).Returns("ConnBName"); cacheB = new Cache(); connB.Setup(x => x.Cache).Returns(cacheB); hostA = new Mock<Host>(MockBehavior.Strict); hostA.Setup(n => n.Name()).Returns("HostAName"); hostA.Setup(n => n.Equals(It.IsAny<object>())).Returns((object o) => ReferenceEquals(o, hostA.Object)); hostB = new Mock<Host>(MockBehavior.Strict); hostB.Setup(n => n.Name()).Returns("HostBName"); hostB.Setup(n => n.Equals(It.IsAny<object>())).Returns((object o) => ReferenceEquals(o, hostB.Object)); } [TearDown] public void TestTearDown() { cacheA = null; cacheB = null; connA = null; connB = null; hostA = null; hostB = null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Xml.Linq; using HBus.Nodes.Common; using HBus.Nodes.Devices; using HBus.Nodes.Exceptions; using HBus.Nodes.Hardware; using HBus.Nodes.Pins; using HBus.Nodes.Sensors; using HBus.Nodes.Wires; using HBus.Ports; using HBus.Utilities; using log4net; namespace HBus.Nodes.Configuration { public class XmlConfigurator : INodeConfigurator { private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly string _xmlFile; #region public properties public IHardwareAbstractionLayer Hal { get; private set; } public BusController Bus { get; private set; } public Scheduler Scheduler { get; private set; } public Node Node { get; private set; } #endregion public XmlConfigurator(string filename) { _xmlFile = filename; } public void Configure(bool defaultConfig) { try { #region initial check var xdoc = XDocument.Load(_xmlFile); if (xdoc.Root == null) throw new NodeConfigurationException("xml root not found"); var xnode = xdoc.Root.Elements() .FirstOrDefault( x => x.Name.LocalName == "node" && Convert.ToBoolean(x.Attribute("default").Value) == defaultConfig); if (xnode == null) throw new NodeConfigurationException("node configuration not found"); #endregion ConfigureHal(xnode.Element("hal")); //configure bus settings ConfigureBus(xnode.Element("bus"), xnode.Element("info")); if (Bus == null) throw new NodeConfigurationException("HBus controller not configured"); //configure bus settings ConfigureScheduler(xnode.Element("scheduler")); if (Scheduler == null) throw new NodeConfigurationException("Scheduler not configured"); //configure bus settings ConfigureNode(xnode); if (Node == null) throw new NodeConfigurationException("Node not configured"); } catch (Exception ex) { throw new NodeConfigurationException("Node configuration failed", ex); } } public bool LoadConfiguration(bool defaultConfig, Node node) { try { #region Open xml file var xdoc = XDocument.Load(_xmlFile); if (xdoc.Root == null) throw new NodeConfigurationException("xml root not found"); var xnode = xdoc.Root.Elements() .FirstOrDefault( x => x.Name.LocalName == "node" && Convert.ToBoolean(x.Attribute("default").Value) == defaultConfig); if (xnode == null) throw new NodeConfigurationException("node configuration not found"); #endregion //Configure node GetNodeInfo(xnode.Element("info"), ref node); node.Pins = GetPins(xnode.Element("pins").Elements()); node.Devices = GetDevices(xnode.Element("devices").Elements()); foreach (var device in node.Devices) device.Address = node.Address; node.Wires = GetWires(xnode.Element("wires").Elements(), node, Bus); node.Sensors = GetSensors(xnode.Element("sensors").Elements()); foreach (var sensor in node.Sensors) sensor.Address = node.Address; node.Subnodes = GetSubnodes(xnode.Element("subnodes").Elements()); //Update info node.DigitalInputs = (byte)node.Pins.Count(p => p.Type == PinTypes.Input); node.DigitalOutputs = (byte)node.Pins.Count(p => p.Type == PinTypes.Output); node.AnalogInputs = (byte)node.Pins.Count(p => p.Type == PinTypes.Analog); node.CounterInputs = (byte)node.Pins.Count(p => p.Type == PinTypes.Counter); node.PwmOutputs = (byte)node.Pins.Count(p => p.Type == PinTypes.Pwm); node.WiresCount = (byte)node.Wires.Count(); node.DevicesCount = (byte)node.Devices.Count(); node.SensorsCount = (byte)node.Sensors.Count(); Log.Debug(string.Format("Configuration loaded for node {0}", node)); return true; } catch (Exception ex) { Log.Error(new NodeConfigurationException("load configuration failed", ex)); } return false; } public bool SaveConfiguration(bool defaultConfig) { try { #region Open xml file var xdoc = XDocument.Load(_xmlFile); if (xdoc.Root == null) throw new NodeConfigurationException("xml root not found"); var xnode = xdoc.Root.Elements() .FirstOrDefault( x => x.Name.LocalName == "node" && Convert.ToBoolean(x.Attribute("default").Value) == defaultConfig); if (xnode == null) throw new NodeConfigurationException("node configuration not found"); #endregion SaveNodeInfo(Node, xnode); SavePins(Node.Pins, xnode.Element("pins")); SaveDevices(Node.Devices, xnode.Element("devices")); SaveWires(Node.Wires, xnode.Element("wires")); SaveSensors(Node.Sensors, xnode.Element("sensors")); SaveSubnodes(Node.Subnodes, xnode.Element("subnodes")); xdoc.Save(_xmlFile); return true; } catch (Exception ex) { Log.Error(new NodeConfigurationException("save configuration failed", ex)); } return false; } //------------------------------------------------------------ //Singleton readonly objects //------------------------------------------------------------ //Hal configuration private void ConfigureHal(XElement element) { if (element == null) throw new NodeConfigurationException("hal section not found"); Hal = (IHardwareAbstractionLayer)GetConfiguredObject(element); if (Hal != null) Log.Debug(string.Format("Configured hal of type {0}", Hal.GetType().Name)); else Log.Warn("No Hal found (maybe is embededd ?)"); } private void ConfigureBus(XElement busElement, XElement nodeElement) { if (busElement == null) throw new NodeConfigurationException("bus section not found"); var ports = new List<Port>(); foreach (var xport in busElement.Element("ports").Elements()) { var port = (Port)GetConfiguredObject(xport); if (port != null) ports.Add(port); else { Log.Warn(string.Format("port {0} failed configuration", xport)); } } var address = nodeElement != null && nodeElement.Element("address") != null ? Address.Parse(Convert.ToUInt32(nodeElement.Element("address").Value)) : Address.Empty; Bus = new BusController(address, ports.ToArray()); Log.Debug(string.Format("Configured bus of type {0}", Bus.GetType().Name)); } private void ConfigureScheduler(XElement element) { Scheduler = Scheduler.GetScheduler(); } private void ConfigureNode(XElement element) { if (element == null) throw new NodeConfigurationException("node section not found"); Node = (Node)GetConfiguredObject(element); LoadConfiguration(false, Node); } #region read functions private void GetNodeInfo(XElement element, ref Node node) { try { if (element == null || node == null) return; node.Id = element.Element("id") != null ? Convert.ToUInt32(element.Element("id").Value) : 0; node.Name = element.Element("name") != null ? element.Element("name").Value : string.Empty; node.Address = element.Element("address") != null ? Address.Parse(Convert.ToUInt32(element.Element("address").Value)) : Address.Empty; node.Description = element.Element("description") != null ? element.Element("description").Value : string.Empty; node.Type = element.Element("type") != null ? element.Element("type").Value : string.Empty; node.Hardware = element.Element("hardware") != null ? element.Element("hardware").Value : string.Empty; node.Version = element.Element("version") != null ? element.Element("version").Value : string.Empty; node.Location = element.Element("location") != null ? element.Element("location").Value : string.Empty; Log.Debug("Configured node info"); } catch (Exception ex) { Log.Error(string.Format("{0} failed", MethodBase.GetCurrentMethod().Name), ex); } } private IList<Pin> GetPins(IEnumerable<XElement> elements) { var pins = new List<Pin>(); foreach (var xpin in elements) { if (xpin == null) continue; var pin = new Pin(Hal, Scheduler) { //Id = Convert.ToUInt32(xpin.Attribute("id").Value); //NodeId = xpin.Parent != null && xpin.Parent.Parent != null ? Convert.ToUInt32(xpin.Parent.Parent.Attribute("id").Value) : 0 Index = xpin.Attribute("index") != null ? Convert.ToByte(xpin.Attribute("index").Value) : (byte)0, Name = xpin.Attribute("name") != null ? xpin.Attribute("name").Value : string.Empty, Description = xpin.Attribute("description") != null ? xpin.Attribute("description").Value : string.Empty, Location = xpin.Attribute("location") != null ? xpin.Attribute("location").Value : string.Empty, Type = xpin.Attribute("type") != null && Enum.IsDefined(typeof(PinTypes), xpin.Attribute("type").Value) ? (PinTypes)Enum.Parse(typeof(PinTypes), xpin.Attribute("type").Value) : PinTypes.None, SubType = xpin.Attribute("subtype") != null && Enum.IsDefined(typeof(PinSubTypes), xpin.Attribute("subtype").Value) ? (PinSubTypes)Enum.Parse(typeof(PinSubTypes), xpin.Attribute("subtype").Value) : PinSubTypes.None, Source = xpin.Attribute("source") != null ? xpin.Attribute("source").Value : string.Empty, Parameters = xpin.Attribute("parameters") != null ? Csv.CsvToList<byte>(xpin.Attribute("parameters").Value).ToArray() : null }; pins.Add(pin); } Log.Debug(string.Format("Configured {0} pins", pins.Count)); return pins; } private IList<Wire> GetWires(IEnumerable<XElement> elements, Node node, BusController bus) { var wires = new List<Wire>(); foreach (var xwire in elements) { var input = xwire.Attribute("input").Value; var pin = node.Pins.FirstOrDefault(p => p.Name == input); if (pin == null) throw new WireException("Input pin not found"); var index = Convert.ToByte(xwire.Attribute("index").Value); var address = xwire.Attribute("address") != null && !string.IsNullOrEmpty(xwire.Attribute("address").Value) ? Address.Parse(Convert.ToUInt32(xwire.Attribute("address").Value)) : Address.Empty; var useInputData = xwire.Attribute("useInputData") != null && !string.IsNullOrEmpty(xwire.Attribute("useInputData").Value) && Convert.ToBoolean(xwire.Attribute("useInputData").Value); var cmdText = xwire.Attribute("command").Value.ToUpperInvariant(); byte cmd = 0; #region parse command name switch (cmdText) { case "PING": cmd = NodeCommands.CMD_PING; break; case "RESET": cmd = NodeCommands.CMD_RESET; break; case "READ_CONFIG": cmd = NodeCommands.CMD_READ_CONFIG; break; case "START": cmd = NodeCommands.CMD_START; break; case "STOP": cmd = NodeCommands.CMD_STOP; break; //Pins case "CHANGE_DIGITAL": cmd = NodeCommands.CMD_CHANGE_DIGITAL; break; case "TOGGLE_DIGITAL": cmd = NodeCommands.CMD_TOGGLE_DIGITAL; break; case "TIMED_DIGITAL": cmd = NodeCommands.CMD_TIMED_DIGITAL; break; case "DELAY_DIGITAL": cmd = NodeCommands.CMD_DELAY_DIGITAL; break; case "PULSE_DIGITAL": cmd = NodeCommands.CMD_PULSE_DIGITAL; break; case "CYCLE_DIGITAL": cmd = NodeCommands.CMD_CYCLE_DIGITAL; break; case "CHANGE_ALL_DIGITAL": cmd = NodeCommands.CMD_CHANGE_ALL_DIGITAL; break; case "CHANGE_PWM": cmd = NodeCommands.CMD_CHANGE_PWM; break; case "CHANGE_PIN": cmd = NodeCommands.CMD_CHANGE_PIN; break; case "DELAY_TOGGLE_DIGITAL": cmd = NodeCommands.CMD_DELAY_TOGGLE_DIGITAL; break; case "DELTA_PWM": cmd = NodeCommands.CMD_DELTA_PWM; break; case "FADE_PWM": cmd = NodeCommands.CMD_FADE_PWM; break; case "ACTIVATE": cmd = NodeCommands.CMD_ACTIVATE; break; case "DEACTIVATE": cmd = NodeCommands.CMD_DEACTIVATE; break; case "EXECUTE_DEVICE_ACTION": cmd = NodeCommands.CMD_EXECUTE_DEVICE_ACTION; break; case "PUSH_SENSOR_READ": cmd = NodeCommands.CMD_READ_SENSOR; break; } #endregion var dataText = xwire.Attribute("data") != null ? xwire.Attribute("data").Value : string.Empty; var data = Csv.CsvToList<byte>(dataText).ToArray(); //var trgText = xwire.Attribute("trigger") != null ? xwire.Attribute("trigger").Value : string.Empty; //var trgs = Csv.CsvToList<string>(trgText).ToArray(); //var trigger = WireTriggers.None; //foreach (var trg in trgs) //{ // trigger |= trg != null && Enum.IsDefined(typeof (WireTriggers), trg) // ? (WireTriggers) Enum.Parse(typeof (WireTriggers), trg) // : WireTriggers.None; //} var wire = new Wire(pin) { Index = index, Command = cmd, Address = address, UseInputData = useInputData, Parameters = data }; //Add wire trigger event //TODO configurable on Activate/deactivate/change wire.OnWireTriggered += (sender, args) => { var w = (Wire)sender; var stack = new SimpleStack(w.Parameters); if (w.UseInputData) { stack.Push(args.Source.Value); } if (w.Address == Address.Empty || w.Address == bus.Address) node.Execute(w.Address, w.Command, stack.Data); else bus.SendImmediate(w.Command, w.Address, stack.Data); }; wires.Add(wire); } Log.Debug(string.Format("Configured {0} wires", wires.Count)); return wires; } private IList<Device> GetDevices(IEnumerable<XElement> elements) { var devices = new List<Device>(); foreach (var xdevice in elements) { if (xdevice == null) continue; var device = (Device)GetConfiguredObject(xdevice); var xinfo = xdevice.Element("info"); device.Name = xinfo.Element("name") != null ? xinfo.Element("name").Value : string.Empty; device.Index = xinfo.Element("index") != null ? Convert.ToByte(xinfo.Element("index").Value) : (byte)0; device.Class = xinfo.Element("hardware") != null ? xinfo.Element("hardware").Value : string.Empty; //Address = // xinfo.Element("address") != null // ? Address.Parse(Convert.ToUInt32(xinfo.Element("address").Value)) // : Address.Empty, device.Description = xinfo.Element("description") != null ? xinfo.Element("description").Value : string.Empty; device.Location = xinfo.Element("location") != null ? xinfo.Element("location").Value : string.Empty; device.Actions = device.Actions.ToArray(); devices.Add(device); } Log.Debug(string.Format("Configured {0} devices", devices.Count)); return devices; } private IList<Sensor> GetSensors(IEnumerable<XElement> elements) { var sensors = new List<Sensor>(); foreach (var xsensor in elements) { if (xsensor == null) continue; var sensor = (Sensor)GetConfiguredObject(xsensor); var xinfo = xsensor.Element("info"); if (xinfo != null) { sensor.Name = xinfo.Element("name") != null ? xinfo.Element("name").Value : string.Empty; sensor.Index = xinfo.Element("index") != null ? Convert.ToByte(xinfo.Element("index").Value) : (byte)0; sensor.Description = xinfo.Element("description") != null ? xinfo.Element("description").Value : string.Empty; sensor.Location = xinfo.Element("location") != null ? xinfo.Element("location").Value : string.Empty; sensor.Interval = xinfo.Element("interval") != null ? Convert.ToUInt16(xinfo.Element("interval").Value) : (ushort)0; sensor.Class = xinfo.Element("class").Value; sensor.Unit = xinfo.Element("unit").Value; sensor.MinRange = Convert.ToSingle(xinfo.Element("minRange").Value); sensor.MaxRange = Convert.ToSingle(xinfo.Element("maxRange").Value); sensor.Scale = Convert.ToSingle(xinfo.Element("scale").Value); sensor.Function = xinfo.Element("function") != null && Enum.IsDefined(typeof(FunctionType), xinfo.Element("function").Value) ? (FunctionType)Enum.Parse(typeof(FunctionType), xinfo.Element("function").Value) : FunctionType.None; sensor.Hardware = xinfo.Element("hardware").Value; } if (sensor != null) sensors.Add(sensor); } Log.Debug(string.Format("Configured {0} sensors", sensors.Count)); return sensors; } private IList<NodeInfo> GetSubnodes(IEnumerable<XElement> elements) { var nodes = new List<NodeInfo>(); foreach (var xnode in elements) { if (xnode == null) continue; var node = new NodeInfo { Name = xnode.Attribute("name") != null ? xnode.Attribute("name").Value : string.Empty, Description = xnode.Attribute("description") != null ? xnode.Attribute("description").Value : string.Empty, Location = xnode.Attribute("location") != null ? xnode.Attribute("location").Value : string.Empty, Type = xnode.Attribute("type") != null ? xnode.Attribute("type").Value : string.Empty, Hardware = xnode.Attribute("hardware") != null ? xnode.Attribute("hardware").Value : string.Empty, Version = xnode.Attribute("version") != null ? xnode.Attribute("version").Value : string.Empty, DigitalInputs = xnode.Attribute("inputs") != null ? Convert.ToByte(xnode.Attribute("inputs").Value) : (byte)0, AnalogInputs = xnode.Attribute("analogs") != null ? Convert.ToByte(xnode.Attribute("analogs").Value) : (byte)0, CounterInputs = xnode.Attribute("counters") != null ? Convert.ToByte(xnode.Attribute("counters").Value) : (byte)0, DigitalOutputs = xnode.Attribute("outputs") != null ? Convert.ToByte(xnode.Attribute("outputs").Value) : (byte)0, PwmOutputs = xnode.Attribute("pwms") != null ? Convert.ToByte(xnode.Attribute("pwms").Value) : (byte)0, DevicesCount = xnode.Attribute("devices") != null ? Convert.ToByte(xnode.Attribute("devices").Value) : (byte)0, SensorsCount = xnode.Attribute("sensors") != null ? Convert.ToByte(xnode.Attribute("sensors").Value) : (byte)0, }; nodes.Add(node); } Log.Debug(string.Format("Configured {0} subnodes", nodes.Count)); return nodes; } #endregion #region write functions private void SaveNodeInfo(Node node, XElement xnode) { try { if (xnode == null) throw new NodeConfigurationException("node xelement not found"); var xinfo = xnode.Element("info"); xinfo.Element("name").SetValue(node.Name); xinfo.Element("address").SetValue(node.Address.Value); xinfo.Element("description").SetValue(node.Description); xinfo.Element("type").SetValue(node.Type); xinfo.Element("hardware").SetValue(node.Hardware); xinfo.Element("version").SetValue(node.Version); xinfo.Element("location").SetValue(node.Location); Log.Debug("Saved node info configuration {node.Name}"); } catch (Exception ex) { Log.Error(string.Format("{0} failed", MethodBase.GetCurrentMethod().Name), ex); } } private void SavePins(IList<Pin> pins, XElement xpins) { try { foreach (var pin in pins) { var xpin = xpins.Elements().FirstOrDefault(p => p.Attribute("index") != null && Convert.ToUInt16(p.Attribute("index").Value) == pin.Index && p.Attribute("type") != null && p.Attribute("type").Value == pin.Type.ToString()); if (xpin == null) { Log.Warn(string.Format("pin {0} not found", pin)); continue; } xpin.Attribute("name").SetValue(pin.Name); xpin.Attribute("description").SetValue(pin.Description); xpin.Attribute("location").SetValue(pin.Location); xpin.Attribute("type").SetValue(pin.Type); xpin.Attribute("subtype").SetValue(pin.SubType); xpin.Attribute("source").SetValue(pin.Source); } } catch (Exception ex) { Log.Error(string.Format("{0} failed", MethodBase.GetCurrentMethod().Name), ex); } } private void SaveDevices(IList<Device> devices, XElement xdevices) { try { foreach (var device in devices) { var xdev = xdevices.Elements().FirstOrDefault(p => p.Element("info") != null && p.Element("info").Element("index") != null && Convert.ToUInt16(p.Element("info").Element("index").Value) == device.Index); if (xdev == null) { Log.Warn(string.Format("device {0} not found", device)); continue; } var xinfo = xdev.Element("info"); xinfo.Element("name").SetValue(device.Name); xinfo.Element("description").SetValue(device.Description); xinfo.Element("location").SetValue(device.Location); xinfo.Element("class").SetValue(device.Class); } } catch (Exception ex) { Log.Error(string.Format("{0} failed", MethodBase.GetCurrentMethod().Name), ex); } } private void SaveWires(IList<Wire> wires, XElement xwires) { try { string outname = string.Empty, outtype = string.Empty, outaction = string.Empty, outvalues = string.Empty; foreach (var wire in wires) { var xwire = xwires.Elements().FirstOrDefault(p => p.Attribute("index") != null && Convert.ToUInt16(p.Attribute("index").Value) == wire.Index); if (xwire == null) { Log.Warn(string.Format("wire {0} not found", wire)); continue; } } } catch (Exception ex) { Log.Error(string.Format("{0} failed", MethodBase.GetCurrentMethod().Name), ex); } } private void SaveSensors(IList<Sensor> sensors, XElement xsensors) { try { foreach (var sensor in sensors) { var xsen = xsensors.Elements().FirstOrDefault(p => p.Element("info").Element("index") != null && Convert.ToUInt16(p.Element("info").Element("index").Value) == sensor.Index); if (xsen == null) { Log.Warn(string.Format("sensor {0} not found", sensor)); continue; } var xinfo = xsen.Element("info"); xinfo.Element("name").SetValue(sensor.Name); xinfo.Element("description").SetValue(sensor.Description ?? string.Empty); xinfo.Element("location").SetValue(sensor.Location ?? string.Empty); xinfo.Element("class").SetValue(sensor.Class ?? string.Empty); xinfo.Element("interval").SetValue(sensor.Interval); if (xinfo.Element("type") != null) { var xtype = xinfo.Element("type"); //xtype.Element("type").SetValue(sensor.Type.Type ?? string.Empty); xtype.Element("unit").SetValue(sensor.Unit ?? string.Empty); xtype.Element("minRange").SetValue(sensor.MinRange); xtype.Element("maxRange").SetValue(sensor.MaxRange); xtype.Element("scale").SetValue(sensor.Scale); xtype.Element("function").SetValue(sensor.Function); xtype.Element("hardware").SetValue(sensor.Hardware ?? string.Empty); //xtype.Element("version").SetValue(sensor.Type.Version ?? string.Empty); } } } catch (Exception ex) { Log.Error(string.Format("{0} failed", MethodBase.GetCurrentMethod().Name), ex); } } private void SaveSubnodes(IList<NodeInfo> subnodes, XElement xsubnodes) { try { for (var i = 0; i < subnodes.Count; i++) { var subnode = subnodes[i]; var xsub = xsubnodes.Elements().FirstOrDefault(p => p.Attribute("index") != null && Convert.ToUInt16(p.Attribute("index").Value) == i); if (xsub == null) { Log.Warn(string.Format("subnode {0} not found", subnode)); continue; } xsub.Attribute("name").SetValue(subnode.Name); xsub.Attribute("description").SetValue(subnode.Description); xsub.Attribute("location").SetValue(subnode.Location); xsub.Attribute("type").SetValue(subnode.Type); xsub.Attribute("hardware").SetValue(subnode.Hardware); xsub.Attribute("version").SetValue(subnode.Version); xsub.Attribute("inputs").SetValue(subnode.DigitalInputs); xsub.Attribute("analogs").SetValue(subnode.AnalogInputs); xsub.Attribute("counters").SetValue(subnode.CounterInputs); xsub.Attribute("outputs").SetValue(subnode.DigitalOutputs); xsub.Attribute("pwms").SetValue(subnode.PwmOutputs); xsub.Attribute("devices").SetValue(subnode.DevicesCount); xsub.Attribute("sensors").SetValue(subnode.SensorsCount); } } catch (Exception ex) { Log.Error(string.Format("{0} failed", MethodBase.GetCurrentMethod().Name), ex); } } #endregion /// <summary> /// Return configured object read from xml /// </summary> /// <param name="xobject">XML node with object constructor parameters</param> /// <returns>Configured object</returns> private object GetConfiguredObject(XElement xobject) { try { // ReSharper disable PossibleNullReferenceException if (xobject == null) return null; if (xobject.Attribute("type") == null) return null; var objectType = xobject.Attribute("type").Value; var type = Type.GetType(objectType); if (type == null) return null; var parameters = GetConstructorParameters(type, xobject.Element("parameters")); return Activator.CreateInstance(type, parameters); } catch (Exception ex) { Log.Error(string.Format("{0} failed", MethodBase.GetCurrentMethod().Name), ex); } return null; } /// <summary> /// Return configured object read from xml /// </summary> private object[] GetConstructorParameters(Type type, XElement xParameters) { // ReSharper disable PossibleNullReferenceException if (type == null) return null; //Search constructor with same parameters var parameters = (from c in type.GetConstructors() where xParameters.Elements().Count() == c.GetParameters().Length select c.GetParameters()).FirstOrDefault(); if (parameters == null) { //Constructor without parameters or not found return null; } //Copy xml parameters var pars = new List<object>(); foreach (var parameter in parameters) { //Read parameters from xml file foreach (var xpar in xParameters.Elements()) { //Check parameter mandatory attributes if (xpar.Attribute("name") == null) continue; if (xpar.Attribute("type") == null) continue; //if (xpar.Attribute("value") == null) continue; var parType = Type.GetType(xpar.Attribute("type").Value); if ((parameter.ParameterType == parType || parType == null) && parameter.Name == xpar.Attribute("name").Value) { var value = xpar.Attribute("value") != null ? xpar.Attribute("value").Value : null; if (value != null) { if (value.StartsWith("@")) { switch (value) { case "@hal": pars.Add(Hal); break; case "@bus": pars.Add(Bus); break; case "@scheduler": pars.Add((object)Scheduler); break; case "@node": pars.Add(Node); break; case "@configurator": pars.Add(this); break; } } else { object val = parameter.ParameterType.IsEnum ? Enum.Parse(parameter.ParameterType, value) : Convert.ChangeType(value, parameter.ParameterType); if (val != null) { pars.Add(val); } else { if (parameter.IsOptional) pars.Add(parameter.DefaultValue); } } } else { if (parameter.IsOptional) pars.Add(parameter.DefaultValue); else return null; } break; } } } //return object with parameters return pars.ToArray(); } } }
using System; using System.Threading; using Microsoft.SPOT; using Microsoft.SPOT.Presentation.Media; using Skewworks.NETMF.Modal; namespace Skewworks.NETMF.Controls { /// <summary> /// Provides a compact list of items which can be navigated via drop-down or pop-out /// </summary> [Serializable] public class Combobox : Control { #region Variables private ListboxItem[] _items; private int _selIndex = -1; private Font _font; private int _lineHeight; // Pixels needed for each line private readonly Bitmap _down; private bool _expand; private bool _forcePopup; private bool _bZebra; //private Color _fore; private Color _zebra; //private Color _sel; //private Color _selText; //private IControl _removing; #endregion #region Constructors /// <summary> /// Creates a new combo box /// </summary> /// <param name="name">Name of the check box</param> /// <param name="font">Font to render the content text</param> /// <param name="x">X position relative to it's parent</param> /// <param name="y">Y position relative to it's parent</param> /// <param name="width">Width in pixel</param> /// <param name="forcePopup">true if the combo box should always display a pop-up even if it has room for a drop-down</param> /// <remarks> /// The <see cref="Control.Height"/> is calculated automatically to fit the font. /// </remarks> public Combobox(string name, Font font, int x, int y, int width, bool forcePopup = false) : base(name, x, y, width, font.Height + 7) { _font = font; _forcePopup = forcePopup; DefaultColors(); _down = Resources.GetBitmap(Resources.BitmapResources.down); UpdateValues(); } /// <summary> /// Creates a new combo box /// </summary> /// <param name="name">Name of the check box</param> /// <param name="font">Font to render the content text</param> /// <param name="x">X position relative to it's parent</param> /// <param name="y">Y position relative to it's parent</param> /// <param name="width">Width in pixel</param> /// <param name="height">Height in pixel</param> /// <param name="forcePopup">true if the combo box should always display a pop-up even if it has room for a drop-down</param> public Combobox(string name, Font font, int x, int y, int width, int height, bool forcePopup = false) : base(name, x, y, width, height) { _font = font; _forcePopup = forcePopup; DefaultColors(); _down = Resources.GetBitmap(Resources.BitmapResources.down); UpdateValues(); } /// <summary> /// Creates a new combo box /// </summary> /// <param name="name">Name of the check box</param> /// <param name="font">Font to render the content text</param> /// <param name="x">X position relative to it's parent</param> /// <param name="y">Y position relative to it's parent</param> /// <param name="width">Width in pixel</param> /// <param name="items">Items to initially add to the combo box</param> /// <param name="forcePopup">true if the combo box should always display a pop-up even if it has room for a drop-down</param> /// <remarks> /// The <see cref="Control.Height"/> is calculated automatically to fit the font. /// </remarks> public Combobox(string name, Font font, int x, int y, int width, ListboxItem[] items, bool forcePopup = false) : base(name, x, y, width, font.Height + 7) { _font = font; _forcePopup = forcePopup; _items = items; DefaultColors(); _down = Resources.GetBitmap(Resources.BitmapResources.down); if (_items != null && _items.Length != 0) { _selIndex = 0; } UpdateValues(); } /// <summary> /// Creates a new combo box /// </summary> /// <param name="name">Name of the check box</param> /// <param name="font">Font to render the content text</param> /// <param name="x">X position relative to it's parent</param> /// <param name="y">Y position relative to it's parent</param> /// <param name="width">Width in pixel</param> /// <param name="height">Height in pixel</param> /// <param name="items">Items to initially add to the combo box</param> /// <param name="forcePopup">true if the combo box should always display a pop-up even if it has room for a drop-down</param> public Combobox(string name, Font font, int x, int y, int width, int height, ListboxItem[] items, bool forcePopup = false) : base(name, x, y, width, height) { _font = font; _forcePopup = forcePopup; _items = items; DefaultColors(); _down = Resources.GetBitmap(Resources.BitmapResources.down); if (_items != null && _items.Length != 0) { _selIndex = 0; } UpdateValues(); } #endregion #region Events /// <summary> /// Adds or removes callback methods for SelectedIndexChanged events /// </summary> /// <remarks> /// Applications can subscribe to this event to be notified when a button release occurs /// </remarks> public event OnSelectedIndexChanged SelectedIndexChanged; /// <summary> /// Fires the <see cref="SelectedIndexChanged"/> event /// </summary> /// <param name="sender">Object sending the event</param> /// <param name="index">New item index</param> protected virtual void OnSelectedIndexChanged(object sender, int index) { if (SelectedIndexChanged != null) { SelectedIndexChanged(sender, index); } } #endregion #region Properties /// <summary> /// Gets/Sets if the combo box should always display a pop-up even if it has room for a drop-down /// </summary> public bool AlwaysPopup { get { return _forcePopup; } set { _forcePopup = value; } } /// <summary> /// Gets/Sets the font to use for the text and item /// </summary> public Font Font { get { return _font; } set { if (value == null || _font == value) { return; } _font = value; UpdateValues(); Invalidate(); } } /// <summary> /// Gets/Sets the combo box items /// </summary> public ListboxItem[] Items { get { return _items; } set { _items = value; UpdateValues(); Invalidate(); } } /// <summary> /// Gets/Sets the index of the selected item. /// </summary> public int SelectedIndex { get { return _selIndex; } set { if (_items == null) { return; } if (_selIndex == value) { return; } if (value < -1) { value = -1; } else if (value > _items.Length - 1) { value = _items.Length - 1; } _selIndex = value; Invalidate(); OnSelectedIndexChanged(this, _selIndex); } } /// <summary> /// Gets/Sets the string value of the selected item /// </summary> public string SelectedValue { get { if (_items == null || _selIndex < 0 || _selIndex > _items.Length - 1) { return string.Empty; } return _items[_selIndex].Text; } set { if (_items == null || _selIndex < 0 || _selIndex > _items.Length - 1 || _items[_selIndex].Text == value) { return; } _items[_selIndex].Text = value; Invalidate(); } } /// <summary> /// Gets/Sets whether or not to enable Zebra Striping /// </summary> /// <see cref="ZebraStripeColor"/> public bool ZebraStripe { get { return _bZebra; } set { if (_bZebra == value) { return; } _bZebra = value; Invalidate(); } } /// <summary> /// Gets/Sets color to use with Zebra Stripes /// </summary> /// <see cref="ZebraStripe"/> public Color ZebraStripeColor { get { return _zebra; } set { if (_zebra == value) { return; } _zebra = value; if (_bZebra) { Invalidate(); } } } #endregion #region Buttons /// <summary> /// Override this message to handle button pressed events internally. /// </summary> /// <param name="buttonId">Integer ID corresponding to the affected button</param> /// <param name="handled">true if the event is handled. Set to true if handled.</param> /// <remarks> /// Expands the combo box on <see cref="ButtonIDs.Select"/> /// </remarks> protected override void ButtonPressedMessage(int buttonId, ref bool handled) { if (buttonId == (int) ButtonIDs.Select) { _expand = true; } base.ButtonPressedMessage(buttonId, ref handled); } /// <summary> /// Override this message to handle button released events internally. /// </summary> /// <param name="buttonId">Integer ID corresponding to the affected button</param> /// <param name="handled">true if the event is handled. Set to true if handled.</param> /// <remarks> /// Shows the pop up or item list on <see cref="ButtonIDs.Select"/> if _expand is true /// </remarks> protected override void ButtonReleasedMessage(int buttonId, ref bool handled) { if (_items != null && buttonId == (int)ButtonIDs.Select && _expand) { ShowPopupOrList(); } _expand = false; base.ButtonReleasedMessage(buttonId, ref handled); } #endregion #region Touch /// <summary> /// Override this message to handle touch events internally. /// </summary> /// <param name="sender">Object sending the event</param> /// <param name="point">Point on screen touch event is occurring</param> /// <param name="handled">true if the event is handled. Set to true if handled.</param> /// <remarks> /// Expands the combo box on <see cref="ButtonIDs.Select"/> /// </remarks> protected override void TouchDownMessage(object sender, point point, ref bool handled) { if (point.X > Width - 31) { _expand = true; } base.TouchDownMessage(sender, point,ref handled); } /// <summary> /// Override this message to handle touch events internally. /// </summary> /// <param name="sender">Object sending the event</param> /// <param name="point">Point on screen touch event is occurring</param> /// <param name="handled">true if the event is handled. Set to true if handled.</param> /// <remarks> /// Shows the pop up or item list on <see cref="ButtonIDs.Select"/> if _expand is true /// </remarks> protected override void TouchUpMessage(object sender, point point, ref bool handled) { if (_items != null && point.X > Width - 31 && _expand) { ShowPopupOrList(); } _expand = false; base.TouchUpMessage(sender, point, ref handled); } #endregion #region Public Methods /// <summary> /// Adds a item to the combo box /// </summary> /// <param name="item">Item to add</param> public void AddItem(ListboxItem item) { // Update Array Size if (_items == null) { _items = new[] { item }; } else { var tmp = new ListboxItem[_items.Length + 1]; Array.Copy(_items, tmp, _items.Length); tmp[tmp.Length - 1] = item; _items = tmp; } if (_selIndex == -1) { _selIndex = 0; Invalidate(); } //item.Parent = this; } /// <summary> /// Adds a number of items to the combo box /// </summary> /// <param name="items">Items to add</param> public void AddItems(ListboxItem[] items) { if (items == null) { return; } Suspended = true; try { //for (int i = 0; i < items.Length; i++) // items[i].Parent = this; if (_items == null) { _items = items; } else { var tmp = new ListboxItem[_items.Length + items.Length]; Array.Copy(_items, tmp, _items.Length); Array.Copy(items, 0, tmp, _items.Length, items.Length); _items = tmp; } if (_selIndex == -1) { _selIndex = 0; } } finally { Suspended = false; } } /// <summary> /// Removes all items from the combo box /// </summary> public void ClearItems() { if (_items == null) { return; } _items = null; Invalidate(); } /// <summary> /// Removes a single item from the combo box /// </summary> /// <param name="item">Item to remove</param> public void RemoveItem(ListboxItem item) { if (_items == null) // || item == _removing) { return; } for (int i = 0; i < _items.Length; i++) { if (_items[i] == item) { RemoveItemAt(i); return; } } } /// <summary> /// Removes a item by its index /// </summary> /// <param name="index">Index of the item to remove</param> public void RemoveItemAt(int index) { if (_items == null || index < 0 || index >= _items.Length) { return; } if (_items.Length == 1) { ClearItems(); return; } //if (_items[index] == _removing) // return; Suspended = true; try { _items[index].Parent = null; var tmp = new ListboxItem[_items.Length - 1]; int c = 0; for (int i = 0; i < _items.Length; i++) { if (i != index) { tmp[c++] = _items[i]; } } } finally { Suspended = false; } } #endregion #region GUI protected override void OnRender(int x, int y, int width, int height) { //x = Left; //y = Top; // Draw Shadow Core.Screen.DrawRectangle(Colors.White, 1, Left + 1, Top + 1, Width - 1, Height - 1, 1, 1, Colors.White, 0, 0, Colors.White, 0, 0, 256); // Draw Outline Core.Screen.DrawRectangle((Focused) ? Core.SystemColors.SelectionColor : Core.SystemColors.BorderColor, 1, Left, Top, Width - 1, Height - 1, 1, 1, 0, 0, 0, 0, 0, 0, 256); // Draw Fill Core.Screen.DrawRectangle( 0, 0, Left + 1, Top + 1, Width - 3, Height - 3, 0, 0, Core.SystemColors.ControlTop, Left, Top, Enabled ? Core.SystemColors.ControlBottom : Core.SystemColors.ControlTop, Left, Top + (Height/2), 256); // Draw Button Core.Screen.DrawLine(Core.SystemColors.BorderColor, 1, Left + Width - 31, Top + 1, Left + Width - 31, Top + Height - 3); Core.Screen.DrawImage(Left + Width - 16 - (_down.Width / 2), y + (Height / 2) - (_down.Height / 2), _down, 0, 0, _down.Width, _down.Height); // Draw Text y = y + (Height / 2 - _font.Height / 2); if (_items != null && _selIndex != -1) { Core.Screen.DrawTextInRect(_items[_selIndex].Text, Left + 6, y, Width - 39, _font.Height, Bitmap.DT_TrimmingCharacterEllipsis, (Enabled) ? Core.SystemColors.FontColor : Colors.DarkGray, _font); } // no need to cal base.OnRender } #endregion #region Private Methods private void ShowPopupOrList() { int iMin = (_items.Length > 5) ? _lineHeight * 5 : _lineHeight * _items.Length; int h = Parent.Height - Y - Height; if (_forcePopup || h < iMin) { new Thread(Modal).Start(); } else { if (h > Core.ScreenHeight / 2) { h = Core.ScreenHeight / 2; } if (h > (_items.Length * _lineHeight) + 3) { h = (_items.Length * _lineHeight) + 3; } var lstDynamic = new Listbox(Name + "_lst", _font, X, Y + Height - 1, Width - 31, h, _items) { ZebraStripe = _bZebra, ZebraStripeColor = _zebra, SelectedIndex = _selIndex }; lstDynamic.DoubleTap += (sender2, e2) => CleanUp(lstDynamic); lstDynamic.LostFocus += sender3 => CleanUp(lstDynamic, false); Parent.AddChild(lstDynamic); Parent.ActiveChild = lstDynamic; } } private void CleanUp(Listbox lst, bool updateSelection = true) { if (updateSelection || Focused) { SelectedIndex = lst.SelectedIndex; } Parent.RemoveChild(lst); } private void DefaultColors() { //_fore = Core.SystemColors.FontColor; //_sel = Core.SystemColors.SelectionColor; //_selText = Core.SystemColors.SelectedFontColor; _zebra = Colors.Ghost; } private void Modal() { SelectedIndex = SelectionDialog.Show(_items, _font, _selIndex, _bZebra); } private void UpdateValues() { _lineHeight = _font.Height + 4; } #endregion } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using System.Threading; using System.Web; using ASC.Common.Logging; using ASC.Core; using ASC.Core.Tenants; using ASC.Core.Users; using ASC.Notify; using ASC.Notify.Model; using ASC.Notify.Patterns; using ASC.Notify.Recipients; using ASC.Web.Core; using ASC.Web.Core.Users; using ASC.Web.Core.WhiteLabel; using ASC.Web.Studio.Utility; namespace ASC.Web.Studio.Core.Notify { public class StudioNotifyService { private readonly INotifyClient client; private static string EMailSenderName { get { return ASC.Core.Configuration.Constants.NotifyEMailSenderSysName; } } public static StudioNotifyService Instance { get; private set; } static StudioNotifyService() { Instance = new StudioNotifyService(); } private StudioNotifyService() { client = WorkContext.NotifyContext.NotifyService.RegisterClient(StudioNotifyHelper.NotifySource); } #region Periodic Notify public void RegisterSendMethod() { var cron = ConfigurationManagerExtension.AppSettings["core.notify.cron"] ?? "0 0 5 ? * *"; // 5am every day if (ConfigurationManagerExtension.AppSettings["core.notify.tariff"] != "false") { if (TenantExtra.Enterprise) { client.RegisterSendMethod(SendEnterpriseTariffLetters, cron); } else if (TenantExtra.Opensource) { client.RegisterSendMethod(SendOpensourceTariffLetters, cron); } else if (TenantExtra.Saas) { if (CoreContext.Configuration.Personal) { if (!CoreContext.Configuration.CustomMode) { client.RegisterSendMethod(SendLettersPersonal, cron); } } else { client.RegisterSendMethod(SendSaasTariffLetters, cron); } } } if (!CoreContext.Configuration.Personal) { client.RegisterSendMethod(SendMsgWhatsNew, "0 0 * ? * *"); // every hour } } public void SendSaasTariffLetters(DateTime scheduleDate) { StudioPeriodicNotify.SendSaasLetters(client, EMailSenderName, scheduleDate); } public void SendEnterpriseTariffLetters(DateTime scheduleDate) { StudioPeriodicNotify.SendEnterpriseLetters(client, EMailSenderName, scheduleDate); } public void SendOpensourceTariffLetters(DateTime scheduleDate) { StudioPeriodicNotify.SendOpensourceLetters(client, EMailSenderName, scheduleDate); } public void SendLettersPersonal(DateTime scheduleDate) { StudioPeriodicNotify.SendPersonalLetters(client, EMailSenderName, scheduleDate); } public void SendMsgWhatsNew(DateTime scheduleDate) { StudioWhatsNewNotify.SendMsgWhatsNew(scheduleDate, client); } #endregion public void SendMsgToAdminAboutProfileUpdated() { client.SendNoticeAsync(Actions.SelfProfileUpdated, null, null); } public void SendMsgToAdminFromNotAuthUser(string email, string message) { client.SendNoticeAsync(Actions.UserMessageToAdmin, null, null, new TagValue(Tags.Body, message), new TagValue(Tags.UserEmail, email)); } public void SendRequestTariff(bool license, string fname, string lname, string title, string email, string phone, string ctitle, string csize, string site, string message) { fname = (fname ?? "").Trim(); if (string.IsNullOrEmpty(fname)) throw new ArgumentNullException("fname"); lname = (lname ?? "").Trim(); if (string.IsNullOrEmpty(lname)) throw new ArgumentNullException("lname"); title = (title ?? "").Trim(); email = (email ?? "").Trim(); if (string.IsNullOrEmpty(email)) throw new ArgumentNullException("email"); phone = (phone ?? "").Trim(); if (string.IsNullOrEmpty(phone)) throw new ArgumentNullException("phone"); ctitle = (ctitle ?? "").Trim(); if (string.IsNullOrEmpty(ctitle)) throw new ArgumentNullException("ctitle"); csize = (csize ?? "").Trim(); if (string.IsNullOrEmpty(csize)) throw new ArgumentNullException("csize"); site = (site ?? "").Trim(); if (string.IsNullOrEmpty(site) && !CoreContext.Configuration.CustomMode) throw new ArgumentNullException("site"); message = (message ?? "").Trim(); if (string.IsNullOrEmpty(message) && !CoreContext.Configuration.CustomMode) throw new ArgumentNullException("message"); var salesEmail = AdditionalWhiteLabelSettings.Instance.SalesEmail ?? SetupInfo.SalesEmail; var recipient = (IRecipient)(new DirectRecipient(SecurityContext.CurrentAccount.ID.ToString(), String.Empty, new[] { salesEmail }, false)); client.SendNoticeToAsync(license ? Actions.RequestLicense : Actions.RequestTariff, null, new[] { recipient }, new[] { "email.sender" }, null, new TagValue(Tags.UserName, fname), new TagValue(Tags.UserLastName, lname), new TagValue(Tags.UserPosition, title), new TagValue(Tags.UserEmail, email), new TagValue(Tags.Phone, phone), new TagValue(Tags.Website, site), new TagValue(Tags.CompanyTitle, ctitle), new TagValue(Tags.CompanySize, csize), new TagValue(Tags.Body, message)); } #region Voip public void SendToAdminVoipWarning(double balance) { client.SendNoticeAsync(Actions.VoipWarning, null, null, new TagValue(Tags.Body, balance)); } public void SendToAdminVoipBlocked() { client.SendNoticeAsync(Actions.VoipBlocked, null, null); } #endregion #region User Password public void UserPasswordChange(UserInfo userInfo) { var hash = CoreContext.Authentication.GetUserPasswordStamp(userInfo.ID).ToString("s"); var confirmationUrl = CommonLinkUtility.GetConfirmationUrl(userInfo.Email, ConfirmType.PasswordChange, hash); Func<string> greenButtonText = () => WebstudioNotifyPatternResource.ButtonChangePassword; var action = CoreContext.Configuration.Personal ? (CoreContext.Configuration.CustomMode ? Actions.PersonalCustomModePasswordChange : Actions.PersonalPasswordChange) : Actions.PasswordChange; client.SendNoticeToAsync( action, null, StudioNotifyHelper.RecipientFromEmail(userInfo.Email, false), new[] { EMailSenderName }, null, TagValues.GreenButton(greenButtonText, confirmationUrl)); } #endregion #region User Email public void SendEmailChangeInstructions(UserInfo user, string email) { var confirmationUrl = CommonLinkUtility.GetConfirmationUrl(email, ConfirmType.EmailChange, SecurityContext.CurrentAccount.ID); Func<string> greenButtonText = () => WebstudioNotifyPatternResource.ButtonChangeEmail; var action = CoreContext.Configuration.Personal ? (CoreContext.Configuration.CustomMode ? Actions.PersonalCustomModeEmailChangeV115 : Actions.PersonalEmailChangeV115) : Actions.EmailChangeV115; client.SendNoticeToAsync( action, null, StudioNotifyHelper.RecipientFromEmail(email, false), new[] { EMailSenderName }, null, TagValues.GreenButton(greenButtonText, confirmationUrl), new TagValue(CommonTags.Culture, user.GetCulture().Name)); } public void SendEmailActivationInstructions(UserInfo user, string email) { var confirmationUrl = CommonLinkUtility.GetConfirmationUrl(email, ConfirmType.EmailActivation); Func<string> greenButtonText = () => WebstudioNotifyPatternResource.ButtonActivateEmail; client.SendNoticeToAsync( Actions.ActivateEmail, null, StudioNotifyHelper.RecipientFromEmail(email, false), new[] { EMailSenderName }, null, new TagValue(Tags.InviteLink, confirmationUrl), TagValues.GreenButton(greenButtonText, confirmationUrl), new TagValue(Tags.UserDisplayName, (user.DisplayUserName() ?? string.Empty).Trim())); } #endregion #region MailServer public void SendMailboxCreated(List<string> toEmails, string username, string address) { SendMailboxCreated(toEmails, username, address, null, null, -1, -1, null); } public void SendMailboxCreated(List<string> toEmails, string username, string address, string server, string encyption, int portImap, int portSmtp, string login, bool skipSettings = false) { var tags = new List<ITagValue> { new TagValue(Tags.UserName, username ?? string.Empty), new TagValue(Tags.Address, address ?? string.Empty) }; if (!skipSettings) { var link = string.Format("{0}/addons/mail/#accounts/changepwd={1}", CommonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/'), address); tags.Add(new TagValue(Tags.MyStaffLink, link)); tags.Add(new TagValue(Tags.Server, server)); tags.Add(new TagValue(Tags.Encryption, encyption ?? string.Empty)); tags.Add(new TagValue(Tags.ImapPort, portImap.ToString(CultureInfo.InvariantCulture))); tags.Add(new TagValue(Tags.SmtpPort, portSmtp.ToString(CultureInfo.InvariantCulture))); tags.Add(new TagValue(Tags.Login, login)); } client.SendNoticeToAsync( skipSettings ? Actions.MailboxWithoutSettingsCreated : Actions.MailboxCreated, null, StudioNotifyHelper.RecipientFromEmail(toEmails, false), new[] { EMailSenderName }, null, tags.ToArray()); } public void SendMailboxPasswordChanged(List<string> toEmails, string username, string address) { client.SendNoticeToAsync( Actions.MailboxPasswordChanged, null, StudioNotifyHelper.RecipientFromEmail(toEmails, false), new[] { EMailSenderName }, null, new TagValue(Tags.UserName, username ?? string.Empty), new TagValue(Tags.Address, address ?? string.Empty)); } #endregion public void SendMsgMobilePhoneChange(UserInfo userInfo) { var confirmationUrl = CommonLinkUtility.GetConfirmationUrl(userInfo.Email.ToLower(), ConfirmType.PhoneActivation); Func<string> greenButtonText = () => WebstudioNotifyPatternResource.ButtonChangePhone; client.SendNoticeToAsync( Actions.PhoneChange, null, StudioNotifyHelper.RecipientFromEmail(userInfo.Email, false), new[] { EMailSenderName }, null, TagValues.GreenButton(greenButtonText, confirmationUrl)); } public void SendMsgTfaReset(UserInfo userInfo) { var confirmationUrl = CommonLinkUtility.GetConfirmationUrl(userInfo.Email.ToLower(), ConfirmType.TfaActivation); Func<string> greenButtonText = () => WebstudioNotifyPatternResource.ButtonChangeTfa; client.SendNoticeToAsync( Actions.TfaChange, null, StudioNotifyHelper.RecipientFromEmail(userInfo.Email, false), new[] { EMailSenderName }, null, TagValues.GreenButton(greenButtonText, confirmationUrl)); } public void UserHasJoin() { if (!CoreContext.Configuration.Personal) { client.SendNoticeAsync(Actions.UserHasJoin, null, null); } } public void SendJoinMsg(string email, EmployeeType emplType) { var inviteUrl = CommonLinkUtility.GetConfirmationUrl(email, ConfirmType.EmpInvite, (int)emplType) + String.Format("&emplType={0}", (int)emplType); Func<string> greenButtonText = () => WebstudioNotifyPatternResource.ButtonJoin; client.SendNoticeToAsync( Actions.JoinUsers, null, StudioNotifyHelper.RecipientFromEmail(email, true), new[] { EMailSenderName }, null, new TagValue(Tags.InviteLink, inviteUrl), TagValues.GreenButton(greenButtonText, inviteUrl)); } public void UserInfoAddedAfterInvite(UserInfo newUserInfo) { if (!CoreContext.UserManager.UserExists(newUserInfo.ID)) return; INotifyAction notifyAction; var footer = "social"; if (CoreContext.Configuration.Personal) { if (CoreContext.Configuration.CustomMode) { notifyAction = Actions.PersonalCustomModeAfterRegistration1; footer = "personalCustomMode"; } else { notifyAction = Actions.PersonalAfterRegistration1; footer = "personal"; } } else if (TenantExtra.Enterprise) { var defaultRebranding = MailWhiteLabelSettings.Instance.IsDefault; notifyAction = defaultRebranding ? Actions.EnterpriseUserWelcomeV10 : CoreContext.Configuration.CustomMode ? Actions.EnterpriseWhitelabelUserWelcomeCustomMode : Actions.EnterpriseWhitelabelUserWelcomeV10; footer = null; } else if (TenantExtra.Opensource) { notifyAction = Actions.OpensourceUserWelcomeV11; footer = "opensource"; } else { notifyAction = Actions.SaasUserWelcomeV115; } Func<string> greenButtonText = () => TenantExtra.Enterprise ? WebstudioNotifyPatternResource.ButtonAccessYourPortal : WebstudioNotifyPatternResource.ButtonAccessYouWebOffice; client.SendNoticeToAsync( notifyAction, null, StudioNotifyHelper.RecipientFromEmail(newUserInfo.Email, false), new[] { EMailSenderName }, null, new TagValue(Tags.UserName, newUserInfo.FirstName.HtmlEncode()), new TagValue(Tags.MyStaffLink, GetMyStaffLink()), TagValues.GreenButton(greenButtonText, CommonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/')), new TagValue(CommonTags.Footer, footer), new TagValue(CommonTags.MasterTemplate, CoreContext.Configuration.Personal ? "HtmlMasterPersonal" : "HtmlMaster")); } public void GuestInfoAddedAfterInvite(UserInfo newUserInfo) { if (!CoreContext.UserManager.UserExists(newUserInfo.ID)) return; INotifyAction notifyAction; var footer = "social"; if (TenantExtra.Enterprise) { var defaultRebranding = MailWhiteLabelSettings.Instance.IsDefault; notifyAction = defaultRebranding ? Actions.EnterpriseGuestWelcomeV10 : Actions.EnterpriseWhitelabelGuestWelcomeV10; footer = null; } else if (TenantExtra.Opensource) { notifyAction = Actions.OpensourceGuestWelcomeV11; footer = "opensource"; } else { notifyAction = Actions.SaasGuestWelcomeV115; } Func<string> greenButtonText = () => TenantExtra.Enterprise ? WebstudioNotifyPatternResource.ButtonAccessYourPortal : WebstudioNotifyPatternResource.ButtonAccessYouWebOffice; client.SendNoticeToAsync( notifyAction, null, StudioNotifyHelper.RecipientFromEmail(newUserInfo.Email, false), new[] { EMailSenderName }, null, new TagValue(Tags.UserName, newUserInfo.FirstName.HtmlEncode()), new TagValue(Tags.MyStaffLink, GetMyStaffLink()), TagValues.GreenButton(greenButtonText, CommonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/')), new TagValue(CommonTags.Footer, footer)); } public void UserInfoActivation(UserInfo newUserInfo) { if (newUserInfo.IsActive) throw new ArgumentException("User is already activated!"); INotifyAction notifyAction; var footer = "social"; if (TenantExtra.Enterprise) { var defaultRebranding = MailWhiteLabelSettings.Instance.IsDefault; notifyAction = defaultRebranding ? Actions.EnterpriseUserActivationV10 : Actions.EnterpriseWhitelabelUserActivationV10; footer = null; } else if (TenantExtra.Opensource) { notifyAction = Actions.OpensourceUserActivationV11; footer = "opensource"; } else { notifyAction = Actions.SaasUserActivationV115; } var confirmationUrl = GenerateActivationConfirmUrl(newUserInfo); Func<string> greenButtonText = () => WebstudioNotifyPatternResource.ButtonAccept; client.SendNoticeToAsync( notifyAction, null, StudioNotifyHelper.RecipientFromEmail(newUserInfo.Email, false), new[] { EMailSenderName }, null, new TagValue(Tags.ActivateUrl, confirmationUrl), TagValues.GreenButton(greenButtonText, confirmationUrl), new TagValue(Tags.UserName, newUserInfo.FirstName.HtmlEncode()), new TagValue(CommonTags.Footer, footer)); } public void GuestInfoActivation(UserInfo newUserInfo) { if (newUserInfo.IsActive) throw new ArgumentException("User is already activated!"); INotifyAction notifyAction; var footer = "social"; if (TenantExtra.Enterprise) { var defaultRebranding = MailWhiteLabelSettings.Instance.IsDefault; notifyAction = defaultRebranding ? Actions.EnterpriseGuestActivationV10 : Actions.EnterpriseWhitelabelGuestActivationV10; footer = null; } else if (TenantExtra.Opensource) { notifyAction = Actions.OpensourceGuestActivationV11; footer = "opensource"; } else { notifyAction = Actions.SaasGuestActivationV115; } var confirmationUrl = GenerateActivationConfirmUrl(newUserInfo); Func<string> greenButtonText = () => WebstudioNotifyPatternResource.ButtonAccept; client.SendNoticeToAsync( notifyAction, null, StudioNotifyHelper.RecipientFromEmail(newUserInfo.Email, false), new[] { EMailSenderName }, null, new TagValue(Tags.ActivateUrl, confirmationUrl), TagValues.GreenButton(greenButtonText, confirmationUrl), new TagValue(Tags.UserName, newUserInfo.FirstName.HtmlEncode()), new TagValue(CommonTags.Footer, footer)); } public void SendMsgProfileDeletion(UserInfo user) { var confirmationUrl = CommonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.ProfileRemove); Func<string> greenButtonText = () => CoreContext.Configuration.Personal ? WebstudioNotifyPatternResource.ButtonConfirmTermination : WebstudioNotifyPatternResource.ButtonRemoveProfile; var action = CoreContext.Configuration.Personal ? (CoreContext.Configuration.CustomMode ? Actions.PersonalCustomModeProfileDelete : Actions.PersonalProfileDelete) : Actions.ProfileDelete; client.SendNoticeToAsync( action, null, StudioNotifyHelper.RecipientFromEmail(user.Email, false), new[] { EMailSenderName }, null, TagValues.GreenButton(greenButtonText, confirmationUrl), new TagValue(CommonTags.Culture, user.GetCulture().Name)); } public void SendMsgProfileHasDeletedItself(UserInfo user) { var tenant = CoreContext.TenantManager.GetCurrentTenant(); var admins = CoreContext.UserManager.GetUsers() .Where(u => WebItemSecurity.IsProductAdministrator(WebItemManager.PeopleProductID, u.ID)); ThreadPool.QueueUserWorkItem(_ => { try { CoreContext.TenantManager.SetCurrentTenant(tenant); foreach (var admin in admins) { var culture = string.IsNullOrEmpty(admin.CultureName) ? tenant.GetCulture() : admin.GetCulture(); Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; client.SendNoticeToAsync( Actions.ProfileHasDeletedItself, null, new IRecipient[] { admin }, new[] { EMailSenderName }, null, new TagValue(Tags.FromUserName, user.DisplayUserName()), new TagValue(Tags.FromUserLink, GetUserProfileLink(user.ID))); } } catch (Exception ex) { LogManager.GetLogger("ASC.Notify").Error(ex); } }); } public void SendMsgReassignsCompleted(Guid recipientId, UserInfo fromUser, UserInfo toUser) { client.SendNoticeToAsync( Actions.ReassignsCompleted, null, new[] { StudioNotifyHelper.ToRecipient(recipientId) }, new[] { EMailSenderName }, null, new TagValue(Tags.UserName, DisplayUserSettings.GetFullUserName(recipientId)), new TagValue(Tags.FromUserName, fromUser.DisplayUserName()), new TagValue(Tags.FromUserLink, GetUserProfileLink(fromUser.ID)), new TagValue(Tags.ToUserName, toUser.DisplayUserName()), new TagValue(Tags.ToUserLink, GetUserProfileLink(toUser.ID))); } public void SendMsgReassignsFailed(Guid recipientId, UserInfo fromUser, UserInfo toUser, string message) { client.SendNoticeToAsync( Actions.ReassignsFailed, null, new[] { StudioNotifyHelper.ToRecipient(recipientId) }, new[] { EMailSenderName }, null, new TagValue(Tags.UserName, DisplayUserSettings.GetFullUserName(recipientId)), new TagValue(Tags.FromUserName, fromUser.DisplayUserName()), new TagValue(Tags.FromUserLink, GetUserProfileLink(fromUser.ID)), new TagValue(Tags.ToUserName, toUser.DisplayUserName()), new TagValue(Tags.ToUserLink, GetUserProfileLink(toUser.ID)), new TagValue(Tags.Message, message)); } public void SendMsgRemoveUserDataCompleted(Guid recipientId, Guid fromUserId, string fromUserName, long docsSpace, long crmSpace, long mailSpace, long talkSpace) { client.SendNoticeToAsync( CoreContext.Configuration.CustomMode ? Actions.RemoveUserDataCompletedCustomMode : Actions.RemoveUserDataCompleted, null, new[] { StudioNotifyHelper.ToRecipient(recipientId) }, new[] { EMailSenderName }, null, new TagValue(Tags.UserName, DisplayUserSettings.GetFullUserName(recipientId)), new TagValue(Tags.FromUserName, fromUserName.HtmlEncode()), new TagValue(Tags.FromUserLink, GetUserProfileLink(fromUserId)), new TagValue("DocsSpace", FileSizeComment.FilesSizeToString(docsSpace)), new TagValue("CrmSpace", FileSizeComment.FilesSizeToString(crmSpace)), new TagValue("MailSpace", FileSizeComment.FilesSizeToString(mailSpace)), new TagValue("TalkSpace", FileSizeComment.FilesSizeToString(talkSpace))); } public void SendMsgRemoveUserDataFailed(Guid recipientId, Guid fromUserId, string fromUserName, string message) { client.SendNoticeToAsync( Actions.RemoveUserDataFailed, null, new[] { StudioNotifyHelper.ToRecipient(recipientId) }, new[] { EMailSenderName }, null, new TagValue(Tags.UserName, DisplayUserSettings.GetFullUserName(recipientId)), new TagValue(Tags.FromUserName, fromUserName.HtmlEncode()), new TagValue(Tags.FromUserLink, GetUserProfileLink(fromUserId)), new TagValue(Tags.Message, message)); } public void SendAdminWelcome(UserInfo newUserInfo) { if (!CoreContext.UserManager.UserExists(newUserInfo.ID)) return; if (!newUserInfo.IsActive) throw new ArgumentException("User is not activated yet!"); INotifyAction notifyAction; var tagValues = new List<ITagValue>(); if (TenantExtra.Enterprise) { var defaultRebranding = MailWhiteLabelSettings.Instance.IsDefault; notifyAction = defaultRebranding ? Actions.EnterpriseAdminWelcomeV10 : Actions.EnterpriseWhitelabelAdminWelcomeV10; tagValues.Add(TagValues.GreenButton(() => WebstudioNotifyPatternResource.ButtonAccessControlPanel, CommonLinkUtility.GetFullAbsolutePath(SetupInfo.ControlPanelUrl))); } else if (TenantExtra.Opensource) { notifyAction = Actions.OpensourceAdminWelcomeV11; tagValues.Add(new TagValue(CommonTags.Footer, "opensource")); tagValues.Add(new TagValue(Tags.ControlPanelUrl, CommonLinkUtility.GetFullAbsolutePath(SetupInfo.ControlPanelUrl).TrimEnd('/'))); } else { notifyAction = Actions.SaasAdminWelcomeV115; //tagValues.Add(TagValues.GreenButton(() => WebstudioNotifyPatternResource.ButtonConfigureRightNow, CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.GetAdministration(ManagementType.General)))); tagValues.Add(new TagValue(CommonTags.Footer, "common")); } tagValues.Add(new TagValue(Tags.UserName, newUserInfo.FirstName.HtmlEncode())); client.SendNoticeToAsync( notifyAction, null, StudioNotifyHelper.RecipientFromEmail(newUserInfo.Email, false), new[] { EMailSenderName }, null, tagValues.ToArray()); } #region Backup & Restore public void SendMsgBackupCompleted(Guid userId, string link) { client.SendNoticeToAsync( Actions.BackupCreated, null, new[] { StudioNotifyHelper.ToRecipient(userId) }, new[] { EMailSenderName }, null, new TagValue(Tags.OwnerName, CoreContext.UserManager.GetUsers(userId).DisplayUserName())); } public void SendMsgRestoreStarted(bool notifyAllUsers) { var owner = CoreContext.UserManager.GetUsers(CoreContext.TenantManager.GetCurrentTenant().OwnerId); var users = notifyAllUsers ? StudioNotifyHelper.RecipientFromEmail(CoreContext.UserManager.GetUsers(EmployeeStatus.Active).Where(r => r.ActivationStatus == EmployeeActivationStatus.Activated).Select(u => u.Email).ToList(), false) : owner.ActivationStatus == EmployeeActivationStatus.Activated ? StudioNotifyHelper.RecipientFromEmail(owner.Email, false) : new IDirectRecipient[0]; client.SendNoticeToAsync( Actions.RestoreStarted, null, users, new[] { EMailSenderName }, null); } public void SendMsgRestoreCompleted(bool notifyAllUsers) { var users = notifyAllUsers ? CoreContext.UserManager.GetUsers(EmployeeStatus.Active) : new[] { CoreContext.UserManager.GetUsers(CoreContext.TenantManager.GetCurrentTenant().OwnerId) }; foreach (var user in users) { var hash = CoreContext.Authentication.GetUserPasswordStamp(user.ID).ToString("s"); var confirmationUrl = CommonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.PasswordChange, hash); Func<string> greenButtonText = () => WebstudioNotifyPatternResource.ButtonSetPassword; client.SendNoticeToAsync( Actions.RestoreCompletedV115, null, new IRecipient[] { user }, new[] { EMailSenderName }, null, TagValues.GreenButton(greenButtonText, confirmationUrl)); } } #endregion #region Portal Deactivation & Deletion public void SendMsgPortalDeactivation(Tenant t, string deactivateUrl, string activateUrl) { var u = CoreContext.UserManager.GetUsers(t.OwnerId); Func<string> greenButtonText = () => WebstudioNotifyPatternResource.ButtonDeactivatePortal; client.SendNoticeToAsync( Actions.PortalDeactivate, null, new IRecipient[] { u }, new[] { EMailSenderName }, null, new TagValue(Tags.ActivateUrl, activateUrl), TagValues.GreenButton(greenButtonText, deactivateUrl), new TagValue(Tags.OwnerName, u.DisplayUserName())); } public void SendMsgPortalDeletion(Tenant t, string url, bool showAutoRenewText) { var u = CoreContext.UserManager.GetUsers(t.OwnerId); Func<string> greenButtonText = () => WebstudioNotifyPatternResource.ButtonDeletePortal; client.SendNoticeToAsync( Actions.PortalDelete, null, new IRecipient[] { u }, new[] { EMailSenderName }, null, TagValues.GreenButton(greenButtonText, url), new TagValue(Tags.AutoRenew, showAutoRenewText.ToString()), new TagValue(Tags.OwnerName, u.DisplayUserName())); } public void SendMsgPortalDeletionSuccess(UserInfo owner, string url) { Func<string> greenButtonText = () => WebstudioNotifyPatternResource.ButtonLeaveFeedback; client.SendNoticeToAsync( Actions.PortalDeleteSuccessV115, null, new IRecipient[] { owner }, new[] { EMailSenderName }, null, TagValues.GreenButton(greenButtonText, url), new TagValue(Tags.OwnerName, owner.DisplayUserName())); } #endregion public void SendMsgDnsChange(Tenant t, string confirmDnsUpdateUrl, string portalAddress, string portalDns) { var u = CoreContext.UserManager.GetUsers(t.OwnerId); Func<string> greenButtonText = () => WebstudioNotifyPatternResource.ButtonConfirmPortalAddressChange; client.SendNoticeToAsync( Actions.DnsChange, null, new IRecipient[] { u }, new[] { EMailSenderName }, null, new TagValue("ConfirmDnsUpdate", confirmDnsUpdateUrl),//TODO: Tag is deprecated and replaced by TagGreenButton TagValues.GreenButton(greenButtonText, confirmDnsUpdateUrl), new TagValue("PortalAddress", AddHttpToUrl(portalAddress)), new TagValue("PortalDns", AddHttpToUrl(portalDns ?? string.Empty)), new TagValue(Tags.OwnerName, u.DisplayUserName())); } public void SendMsgConfirmChangeOwner(UserInfo owner, UserInfo newOwner, string confirmOwnerUpdateUrl) { Func<string> greenButtonText = () => WebstudioNotifyPatternResource.ButtonConfirmPortalOwnerUpdate; client.SendNoticeToAsync( Actions.ConfirmOwnerChange, null, new IRecipient[] { owner }, new[] { EMailSenderName }, null, TagValues.GreenButton(greenButtonText, confirmOwnerUpdateUrl), new TagValue(Tags.UserName, newOwner.DisplayUserName()), new TagValue(Tags.OwnerName, owner.DisplayUserName())); } public void SendCongratulations(UserInfo u) { try { INotifyAction notifyAction; var footer = "common"; if (TenantExtra.Enterprise) { var defaultRebranding = MailWhiteLabelSettings.Instance.IsDefault; notifyAction = defaultRebranding ? Actions.EnterpriseAdminActivationV10 : Actions.EnterpriseWhitelabelAdminActivationV10; footer = null; } else if (TenantExtra.Opensource) { notifyAction = Actions.OpensourceAdminActivationV11; footer = "opensource"; } else { notifyAction = Actions.SaasAdminActivationV115; } var confirmationUrl = CommonLinkUtility.GetConfirmationUrl(u.Email, ConfirmType.EmailActivation); confirmationUrl += "&first=true"; Func<string> greenButtonText = () => WebstudioNotifyPatternResource.ButtonConfirm; client.SendNoticeToAsync( notifyAction, null, StudioNotifyHelper.RecipientFromEmail(u.Email, false), new[] { EMailSenderName }, null, new TagValue(Tags.UserName, u.FirstName.HtmlEncode()), new TagValue(Tags.MyStaffLink, GetMyStaffLink()), new TagValue(Tags.ActivateUrl, confirmationUrl), TagValues.GreenButton(greenButtonText, confirmationUrl), new TagValue(CommonTags.Footer, footer)); } catch (Exception error) { LogManager.GetLogger("ASC.Notify").Error(error); } } #region Personal public void SendInvitePersonal(string email, string additionalMember = "") { var newUserInfo = CoreContext.UserManager.GetUserByEmail(email); if (CoreContext.UserManager.UserExists(newUserInfo.ID)) return; var lang = CoreContext.Configuration.CustomMode ? "ru-RU" : Thread.CurrentThread.CurrentUICulture.Name; var culture = SetupInfo.GetPersonalCulture(lang); var confirmUrl = CommonLinkUtility.GetConfirmationUrl(email, ConfirmType.EmpInvite, (int)EmployeeType.User) + "&emplType=" + (int)EmployeeType.User + "&lang=" + culture.Key + additionalMember; client.SendNoticeToAsync( CoreContext.Configuration.CustomMode ? Actions.PersonalCustomModeConfirmation : Actions.PersonalConfirmation, null, StudioNotifyHelper.RecipientFromEmail(email, false), new[] { EMailSenderName }, null, new TagValue(Tags.InviteLink, confirmUrl), new TagValue(CommonTags.Footer, CoreContext.Configuration.CustomMode ? "personalCustomMode" : "personal"), new TagValue(CommonTags.Culture, Thread.CurrentThread.CurrentUICulture.Name)); } public void SendUserWelcomePersonal(UserInfo newUserInfo) { client.SendNoticeToAsync( CoreContext.Configuration.CustomMode ? Actions.PersonalCustomModeAfterRegistration1 : Actions.PersonalAfterRegistration1, null, StudioNotifyHelper.RecipientFromEmail(newUserInfo.Email, true), new[] { EMailSenderName }, null, new TagValue(CommonTags.Footer, CoreContext.Configuration.CustomMode ? "personalCustomMode" : "personal"), new TagValue(CommonTags.MasterTemplate, "HtmlMasterPersonal")); } #endregion #region Migration Portal public void MigrationPortalStart(string region, bool notify) { MigrationNotify(Actions.MigrationPortalStart, region, string.Empty, notify); } public void MigrationPortalSuccess(string region, string url, bool notify, int toTenantId) { MigrationNotify(Actions.MigrationPortalSuccessV115, region, url, notify, toTenantId); } public void MigrationPortalError(string region, string url, bool notify) { MigrationNotify(!string.IsNullOrEmpty(region) ? Actions.MigrationPortalError : Actions.MigrationPortalServerFailure, region, url, notify); } private void MigrationNotify(INotifyAction action, string region, string url, bool notify, int? toTenantId = null) { var users = CoreContext.UserManager.GetUsers() .Where(u => notify ? u.ActivationStatus.HasFlag(EmployeeActivationStatus.Activated) : u.IsOwner()); if (users.Any()) { var args = CreateArgs(region, url); if (action == Actions.MigrationPortalSuccessV115) { foreach (var user in users) { var currentArgs = new List<ITagValue>(args); var newTenantId = toTenantId.HasValue ? toTenantId.Value : CoreContext.TenantManager.GetCurrentTenant().TenantId; var hash = CoreContext.Authentication.GetUserPasswordStamp(user.ID).ToString("s"); var confirmationUrl = url + "/" + CommonLinkUtility.GetConfirmationUrlRelative(newTenantId, user.Email, ConfirmType.PasswordChange, hash); Func<string> greenButtonText = () => WebstudioNotifyPatternResource.ButtonSetPassword; currentArgs.Add(TagValues.GreenButton(greenButtonText, confirmationUrl)); client.SendNoticeToAsync( action, null, new IRecipient[] { user }, new[] { EMailSenderName }, null, currentArgs.ToArray()); } } else { client.SendNoticeToAsync( action, null, users.Select(u => StudioNotifyHelper.ToRecipient(u.ID)).ToArray(), new[] { EMailSenderName }, null, args.ToArray()); } } } private List<ITagValue> CreateArgs(string region, string url) { var args = new List<ITagValue>() { new TagValue(Tags.RegionName, TransferResourceHelper.GetRegionDescription(region)), new TagValue(Tags.PortalUrl, url) }; if (!string.IsNullOrEmpty(url)) { args.Add(new TagValue(CommonTags.VirtualRootPath, url)); args.Add(new TagValue(CommonTags.ProfileUrl, url + CommonLinkUtility.GetMyStaff())); args.Add(new TagValue(CommonTags.LetterLogo, TenantLogoManager.GetLogoDark(true))); } return args; } public void PortalRenameNotify(String oldVirtualRootPath) { var tenant = CoreContext.TenantManager.GetCurrentTenant(); var users = CoreContext.UserManager.GetUsers() .Where(u => u.ActivationStatus.HasFlag(EmployeeActivationStatus.Activated)); ThreadPool.QueueUserWorkItem(_ => { try { CoreContext.TenantManager.SetCurrentTenant(tenant); foreach (var u in users) { var culture = string.IsNullOrEmpty(u.CultureName) ? tenant.GetCulture() : u.GetCulture(); Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; client.SendNoticeToAsync( Actions.PortalRename, null, new[] { StudioNotifyHelper.ToRecipient(u.ID) }, new[] { EMailSenderName }, null, new TagValue(Tags.PortalUrl, oldVirtualRootPath), new TagValue(Tags.UserDisplayName, u.DisplayUserName())); } } catch (Exception ex) { LogManager.GetLogger("ASC.Notify").Error(ex); } }); } #endregion #region Helpers private static string GetMyStaffLink() { return CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.GetMyStaff()); } private static string GetUserProfileLink(Guid userId) { return CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.GetUserProfile(userId)); } private static string AddHttpToUrl(string url) { var httpPrefix = Uri.UriSchemeHttp + Uri.SchemeDelimiter; return !string.IsNullOrEmpty(url) && !url.StartsWith(httpPrefix) ? httpPrefix + url : url; } private static string GenerateActivationConfirmUrl(UserInfo user) { var confirmUrl = CommonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.Activation); return confirmUrl + String.Format("&uid={0}&firstname={1}&lastname={2}", SecurityContext.CurrentAccount.ID, HttpUtility.UrlEncode(user.FirstName), HttpUtility.UrlEncode(user.LastName)); } #endregion public void SendRegData(UserInfo u) { try { if (!TenantExtra.Saas || !CoreContext.Configuration.CustomMode) return; var salesEmail = AdditionalWhiteLabelSettings.Instance.SalesEmail ?? SetupInfo.SalesEmail; if (string.IsNullOrEmpty(salesEmail)) return; var recipient = new DirectRecipient(salesEmail, null, new[] { salesEmail }, false); client.SendNoticeToAsync( Actions.SaasCustomModeRegData, null, new IRecipient[] { recipient }, new[] { EMailSenderName }, null, new TagValue(Tags.UserName, u.FirstName.HtmlEncode()), new TagValue(Tags.UserLastName, u.LastName.HtmlEncode()), new TagValue(Tags.UserEmail, u.Email.HtmlEncode()), new TagValue(Tags.Phone, u.MobilePhone != null ? u.MobilePhone.HtmlEncode() : "-"), new TagValue(Tags.Date, u.CreateDate.ToShortDateString() + " " + u.CreateDate.ToShortTimeString()), new TagValue(CommonTags.Footer, null), TagValues.WithoutUnsubscribe()); } catch (Exception error) { LogManager.GetLogger("ASC.Notify").Error(error); } } #region Storage encryption public void SendStorageEncryptionStart(string serverRootPath) { SendStorageEncryptionNotify(Actions.StorageEncryptionStart, false, serverRootPath); } public void SendStorageEncryptionSuccess(string serverRootPath) { SendStorageEncryptionNotify(Actions.StorageEncryptionSuccess, false, serverRootPath); } public void SendStorageEncryptionError(string serverRootPath) { SendStorageEncryptionNotify(Actions.StorageEncryptionError, true, serverRootPath); } public void SendStorageDecryptionStart(string serverRootPath) { SendStorageEncryptionNotify(Actions.StorageDecryptionStart, false, serverRootPath); } public void SendStorageDecryptionSuccess(string serverRootPath) { SendStorageEncryptionNotify(Actions.StorageDecryptionSuccess, false, serverRootPath); } public void SendStorageDecryptionError(string serverRootPath) { SendStorageEncryptionNotify(Actions.StorageDecryptionError, true, serverRootPath); } private void SendStorageEncryptionNotify(INotifyAction action, bool notifyAdminsOnly, string serverRootPath) { var users = notifyAdminsOnly ? CoreContext.UserManager.GetUsersByGroup(Constants.GroupAdmin.ID) : CoreContext.UserManager.GetUsers().Where(u => u.ActivationStatus.HasFlag(EmployeeActivationStatus.Activated)); foreach (var u in users) { client.SendNoticeToAsync( action, null, new[] { StudioNotifyHelper.ToRecipient(u.ID) }, new[] { EMailSenderName }, null, new TagValue(Tags.UserName, u.FirstName.HtmlEncode()), new TagValue(Tags.PortalUrl, serverRootPath), new TagValue(Tags.ControlPanelUrl, GetControlPanelUrl(serverRootPath))); } } private string GetControlPanelUrl(string serverRootPath) { var controlPanelUrl = SetupInfo.ControlPanelUrl; if (string.IsNullOrEmpty(controlPanelUrl)) return string.Empty; if (controlPanelUrl.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase) || controlPanelUrl.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase)) return controlPanelUrl; return serverRootPath + "/" + controlPanelUrl.TrimStart('~', '/').TrimEnd('/'); } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Xunit; using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier< Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; using VerifyVB = Test.Utilities.VisualBasicSecurityCodeFixVerifier< Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.NetFramework.Analyzers.UnitTests { public partial class DoNotUseInsecureDtdProcessingAnalyzerTests { private static DiagnosticResult GetCA3075DataTableReadXmlCSharpResultAt(int line, int column) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleDoNotUseDtdProcessingOverloads).WithLocation(line, column).WithArguments("ReadXml"); #pragma warning restore RS0030 // Do not used banned APIs private static DiagnosticResult GetCA3075DataTableReadXmlBasicResultAt(int line, int column) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleDoNotUseDtdProcessingOverloads).WithLocation(line, column).WithArguments("ReadXml"); #pragma warning restore RS0030 // Do not used banned APIs [Fact] public async Task UseDataTableReadXmlShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.IO; using System.Xml; using System.Data; namespace TestNamespace { public class UseXmlReaderForDataTableReadXml { public void TestMethod(Stream stream) { DataTable table = new DataTable(); table.ReadXml(stream); } } } ", GetCA3075DataTableReadXmlCSharpResultAt(13, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.IO Imports System.Xml Imports System.Data Namespace TestNamespace Public Class UseXmlReaderForDataTableReadXml Public Sub TestMethod(stream As Stream) Dim table As New DataTable() table.ReadXml(stream) End Sub End Class End Namespace", GetCA3075DataTableReadXmlBasicResultAt(10, 13) ); } [Fact] public async Task UseDataTableReadXmlInGetShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Data; class TestClass { public DataTable Test { get { var src = """"; DataTable dt = new DataTable(); dt.ReadXml(src); return dt; } } }", GetCA3075DataTableReadXmlCSharpResultAt(11, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Data Class TestClass Public ReadOnly Property Test() As DataTable Get Dim src = """" Dim dt As New DataTable() dt.ReadXml(src) Return dt End Get End Property End Class", GetCA3075DataTableReadXmlBasicResultAt(9, 13) ); } [Fact] public async Task UseDataTableReadXmlInSetShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Data; class TestClass { DataTable privateDoc; public DataTable GetDoc { set { if (value == null) { var src = """"; DataTable dt = new DataTable(); dt.ReadXml(src); privateDoc = dt; } else privateDoc = value; } } }", GetCA3075DataTableReadXmlCSharpResultAt(15, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Data Class TestClass Private privateDoc As DataTable Public WriteOnly Property GetDoc() As DataTable Set If value Is Nothing Then Dim src = """" Dim dt As New DataTable() dt.ReadXml(src) privateDoc = dt Else privateDoc = value End If End Set End Property End Class", GetCA3075DataTableReadXmlBasicResultAt(11, 17) ); } [Fact] public async Task UseDataTableReadXmlInTryBlockShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Data; class TestClass { private void TestMethod() { try { var src = """"; DataTable dt = new DataTable(); dt.ReadXml(src); } catch (Exception) { throw; } finally { } } }", GetCA3075DataTableReadXmlCSharpResultAt(13, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System Imports System.Data Class TestClass Private Sub TestMethod() Try Dim src = """" Dim dt As New DataTable() dt.ReadXml(src) Catch generatedExceptionName As Exception Throw Finally End Try End Sub End Class", GetCA3075DataTableReadXmlBasicResultAt(10, 13) ); } [Fact] public async Task UseDataTableReadXmlInCatchBlockShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Data; class TestClass { private void TestMethod() { try { } catch (Exception) { var src = """"; DataTable dt = new DataTable(); dt.ReadXml(src); } finally { } } }", GetCA3075DataTableReadXmlCSharpResultAt(14, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System Imports System.Data Class TestClass Private Sub TestMethod() Try Catch generatedExceptionName As Exception Dim src = """" Dim dt As New DataTable() dt.ReadXml(src) Finally End Try End Sub End Class", GetCA3075DataTableReadXmlBasicResultAt(11, 13) ); } [Fact] public async Task UseDataTableReadXmlInFinallyBlockShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Data; class TestClass { private void TestMethod() { try { } catch (Exception) { throw; } finally { var src = """"; DataTable dt = new DataTable(); dt.ReadXml(src); } } }", GetCA3075DataTableReadXmlCSharpResultAt(15, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System Imports System.Data Class TestClass Private Sub TestMethod() Try Catch generatedExceptionName As Exception Throw Finally Dim src = """" Dim dt As New DataTable() dt.ReadXml(src) End Try End Sub End Class", GetCA3075DataTableReadXmlBasicResultAt(13, 13) ); } [Fact] public async Task UseDataTableReadXmlInAsyncAwaitShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Threading.Tasks; using System.Data; class TestClass { private async Task TestMethod() { await Task.Run(() => { var src = """"; DataTable dt = new DataTable(); dt.ReadXml(src); }); } private async void TestMethod2() { await TestMethod(); } }", GetCA3075DataTableReadXmlCSharpResultAt(12, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Threading.Tasks Imports System.Data Class TestClass Private Async Function TestMethod() As Task Await Task.Run(Function() Dim src = """" Dim dt As New DataTable() dt.ReadXml(src) End Function) End Function Private Async Sub TestMethod2() Await TestMethod() End Sub End Class", GetCA3075DataTableReadXmlBasicResultAt(10, 13) ); } [Fact] public async Task UseDataTableReadXmlInDelegateShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Data; class TestClass { delegate void Del(); Del d = delegate () { var src = """"; DataTable dt = new DataTable(); dt.ReadXml(src); }; }", GetCA3075DataTableReadXmlCSharpResultAt(11, 9) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Data Class TestClass Private Delegate Sub Del() Private d As Del = Sub() Dim src = """" Dim dt As New DataTable() dt.ReadXml(src) End Sub End Class", GetCA3075DataTableReadXmlBasicResultAt(10, 5) ); } [Fact] public async Task UseDataTableReadXmlWithXmlReaderShouldNotGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; using System.Data; namespace TestNamespace { public class UseXmlReaderForDataTableReadXml { public void TestMethod(XmlReader reader) { DataTable table = new DataTable(); table.ReadXml(reader); } } } " ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Imports System.Data Namespace TestNamespace Public Class UseXmlReaderForDataTableReadXml Public Sub TestMethod(reader As XmlReader) Dim table As New DataTable() table.ReadXml(reader) End Sub End Class End Namespace"); } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // MONO 1.0 Beta mcs does not like #if !A && !B && !C syntax // .NET Compact Framework 1.0 has no support for Win32 Console API's #if !NETCF // .Mono 1.0 has no support for Win32 Console API's #if !MONO // SSCLI 1.0 has no support for Win32 Console API's #if !SSCLI // We don't want framework or platform specific code in the CLI version of log4net #if !CLI_1_0 using System; using System.Globalization; using System.Runtime.InteropServices; using log4net.Layout; using log4net.Util; namespace log4net.Appender { /// <summary> /// Appends logging events to the console. /// </summary> /// <remarks> /// <para> /// ColoredConsoleAppender appends log events to the standard output stream /// or the error output stream using a layout specified by the /// user. It also allows the color of a specific type of message to be set. /// </para> /// <para> /// By default, all output is written to the console's standard output stream. /// The <see cref="Target"/> property can be set to direct the output to the /// error stream. /// </para> /// <para> /// NOTE: This appender writes directly to the application's attached console /// not to the <c>System.Console.Out</c> or <c>System.Console.Error</c> <c>TextWriter</c>. /// The <c>System.Console.Out</c> and <c>System.Console.Error</c> streams can be /// programmatically redirected (for example NUnit does this to capture program output). /// This appender will ignore these redirections because it needs to use Win32 /// API calls to colorize the output. To respect these redirections the <see cref="ConsoleAppender"/> /// must be used. /// </para> /// <para> /// When configuring the colored console appender, mapping should be /// specified to map a logging level to a color. For example: /// </para> /// <code lang="XML" escaped="true"> /// <mapping> /// <level value="ERROR" /> /// <foreColor value="White" /> /// <backColor value="Red, HighIntensity" /> /// </mapping> /// <mapping> /// <level value="DEBUG" /> /// <backColor value="Green" /> /// </mapping> /// </code> /// <para> /// The Level is the standard log4net logging level and ForeColor and BackColor can be any /// combination of the following values: /// <list type="bullet"> /// <item><term>Blue</term><description></description></item> /// <item><term>Green</term><description></description></item> /// <item><term>Red</term><description></description></item> /// <item><term>White</term><description></description></item> /// <item><term>Yellow</term><description></description></item> /// <item><term>Purple</term><description></description></item> /// <item><term>Cyan</term><description></description></item> /// <item><term>HighIntensity</term><description></description></item> /// </list> /// </para> /// </remarks> /// <author>Rick Hobbs</author> /// <author>Nicko Cadell</author> public class ColoredConsoleAppender : AppenderSkeleton { #region Colors Enum /// <summary> /// The enum of possible color values for use with the color mapping method /// </summary> /// <remarks> /// <para> /// The following flags can be combined together to /// form the colors. /// </para> /// </remarks> /// <seealso cref="ColoredConsoleAppender" /> [Flags] public enum Colors : int { /// <summary> /// color is blue /// </summary> Blue = 0x0001, /// <summary> /// color is green /// </summary> Green = 0x0002, /// <summary> /// color is red /// </summary> Red = 0x0004, /// <summary> /// color is white /// </summary> White = Blue | Green | Red, /// <summary> /// color is yellow /// </summary> Yellow = Red | Green, /// <summary> /// color is purple /// </summary> Purple = Red | Blue, /// <summary> /// color is cyan /// </summary> Cyan = Green | Blue, /// <summary> /// color is intensified /// </summary> HighIntensity = 0x0008, } #endregion // Colors Enum #region Public Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class. /// </summary> /// <remarks> /// The instance of the <see cref="ColoredConsoleAppender" /> class is set up to write /// to the standard output stream. /// </remarks> public ColoredConsoleAppender() { } /// <summary> /// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class /// with the specified layout. /// </summary> /// <param name="layout">the layout to use for this appender</param> /// <remarks> /// The instance of the <see cref="ColoredConsoleAppender" /> class is set up to write /// to the standard output stream. /// </remarks> [Obsolete("Instead use the default constructor and set the Layout property")] public ColoredConsoleAppender(ILayout layout) : this(layout, false) { } /// <summary> /// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class /// with the specified layout. /// </summary> /// <param name="layout">the layout to use for this appender</param> /// <param name="writeToErrorStream">flag set to <c>true</c> to write to the console error stream</param> /// <remarks> /// When <paramref name="writeToErrorStream" /> is set to <c>true</c>, output is written to /// the standard error output stream. Otherwise, output is written to the standard /// output stream. /// </remarks> [Obsolete("Instead use the default constructor and set the Layout & Target properties")] public ColoredConsoleAppender(ILayout layout, bool writeToErrorStream) { Layout = layout; m_writeToErrorStream = writeToErrorStream; } #endregion // Public Instance Constructors #region Public Instance Properties /// <summary> /// Target is the value of the console output stream. /// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>. /// </summary> /// <value> /// Target is the value of the console output stream. /// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>. /// </value> /// <remarks> /// <para> /// Target is the value of the console output stream. /// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>. /// </para> /// </remarks> virtual public string Target { get { return m_writeToErrorStream ? ConsoleError : ConsoleOut; } set { string v = value.Trim(); if (string.Compare(ConsoleError, v, true, CultureInfo.InvariantCulture) == 0) { m_writeToErrorStream = true; } else { m_writeToErrorStream = false; } } } /// <summary> /// Add a mapping of level to color - done by the config file /// </summary> /// <param name="mapping">The mapping to add</param> /// <remarks> /// <para> /// Add a <see cref="LevelColors"/> mapping to this appender. /// Each mapping defines the foreground and background colors /// for a level. /// </para> /// </remarks> public void AddMapping(LevelColors mapping) { m_levelMapping.Add(mapping); } #endregion // Public Instance Properties #region Override implementation of AppenderSkeleton /// <summary> /// This method is called by the <see cref="AppenderSkeleton.DoAppend(log4net.Core.LoggingEvent)"/> method. /// </summary> /// <param name="loggingEvent">The event to log.</param> /// <remarks> /// <para> /// Writes the event to the console. /// </para> /// <para> /// The format of the output will depend on the appender's layout. /// </para> /// </remarks> #if NET_4_0 [System.Security.SecuritySafeCritical] #endif [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] override protected void Append(log4net.Core.LoggingEvent loggingEvent) { if (m_consoleOutputWriter != null) { IntPtr consoleHandle = IntPtr.Zero; if (m_writeToErrorStream) { // Write to the error stream consoleHandle = GetStdHandle(STD_ERROR_HANDLE); } else { // Write to the output stream consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE); } // Default to white on black ushort colorInfo = (ushort)Colors.White; // see if there is a specified lookup LevelColors levelColors = m_levelMapping.Lookup(loggingEvent.Level) as LevelColors; if (levelColors != null) { colorInfo = levelColors.CombinedColor; } // Render the event to a string string strLoggingMessage = RenderLoggingEvent(loggingEvent); // get the current console color - to restore later CONSOLE_SCREEN_BUFFER_INFO bufferInfo; GetConsoleScreenBufferInfo(consoleHandle, out bufferInfo); // set the console colors SetConsoleTextAttribute(consoleHandle, colorInfo); // Using WriteConsoleW seems to be unreliable. // If a large buffer is written, say 15,000 chars // Followed by a larger buffer, say 20,000 chars // then WriteConsoleW will fail, last error 8 // 'Not enough storage is available to process this command.' // // Although the documentation states that the buffer must // be less that 64KB (i.e. 32,000 WCHARs) the longest string // that I can write out a the first call to WriteConsoleW // is only 30,704 chars. // // Unlike the WriteFile API the WriteConsoleW method does not // seem to be able to partially write out from the input buffer. // It does have a lpNumberOfCharsWritten parameter, but this is // either the length of the input buffer if any output was written, // or 0 when an error occurs. // // All results above were observed on Windows XP SP1 running // .NET runtime 1.1 SP1. // // Old call to WriteConsoleW: // // WriteConsoleW( // consoleHandle, // strLoggingMessage, // (UInt32)strLoggingMessage.Length, // out (UInt32)ignoreWrittenCount, // IntPtr.Zero); // // Instead of calling WriteConsoleW we use WriteFile which // handles large buffers correctly. Because WriteFile does not // handle the codepage conversion as WriteConsoleW does we // need to use a System.IO.StreamWriter with the appropriate // Encoding. The WriteFile calls are wrapped up in the // System.IO.__ConsoleStream internal class obtained through // the System.Console.OpenStandardOutput method. // // See the ActivateOptions method below for the code that // retrieves and wraps the stream. // The windows console uses ScrollConsoleScreenBuffer internally to // scroll the console buffer when the display buffer of the console // has been used up. ScrollConsoleScreenBuffer fills the area uncovered // by moving the current content with the background color // currently specified on the console. This means that it fills the // whole line in front of the cursor position with the current // background color. // This causes an issue when writing out text with a non default // background color. For example; We write a message with a Blue // background color and the scrollable area of the console is full. // When we write the newline at the end of the message the console // needs to scroll the buffer to make space available for the new line. // The ScrollConsoleScreenBuffer internals will fill the newly created // space with the current background color: Blue. // We then change the console color back to default (White text on a // Black background). We write some text to the console, the text is // written correctly in White with a Black background, however the // remainder of the line still has a Blue background. // // This causes a disjointed appearance to the output where the background // colors change. // // This can be remedied by restoring the console colors before causing // the buffer to scroll, i.e. before writing the last newline. This does // assume that the rendered message will end with a newline. // // Therefore we identify a trailing newline in the message and don't // write this to the output, then we restore the console color and write // a newline. Note that we must AutoFlush before we restore the console // color otherwise we will have no effect. // // There will still be a slight artefact for the last line of the message // will have the background extended to the end of the line, however this // is unlikely to cause any user issues. // // Note that none of the above is visible while the console buffer is scrollable // within the console window viewport, the effects only arise when the actual // buffer is full and needs to be scrolled. char[] messageCharArray = strLoggingMessage.ToCharArray(); int arrayLength = messageCharArray.Length; bool appendNewline = false; // Trim off last newline, if it exists if (arrayLength > 1 && messageCharArray[arrayLength-2] == '\r' && messageCharArray[arrayLength-1] == '\n') { arrayLength -= 2; appendNewline = true; } // Write to the output stream m_consoleOutputWriter.Write(messageCharArray, 0, arrayLength); // Restore the console back to its previous color scheme SetConsoleTextAttribute(consoleHandle, bufferInfo.wAttributes); if (appendNewline) { // Write the newline, after changing the color scheme m_consoleOutputWriter.Write(s_windowsNewline, 0, 2); } } } private static readonly char[] s_windowsNewline = {'\r', '\n'}; /// <summary> /// This appender requires a <see cref="Layout"/> to be set. /// </summary> /// <value><c>true</c></value> /// <remarks> /// <para> /// This appender requires a <see cref="Layout"/> to be set. /// </para> /// </remarks> override protected bool RequiresLayout { get { return true; } } /// <summary> /// Initialize the options for this appender /// </summary> /// <remarks> /// <para> /// Initialize the level to color mappings set on this appender. /// </para> /// </remarks> #if NET_4_0 [System.Security.SecuritySafeCritical] #endif [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode=true)] public override void ActivateOptions() { base.ActivateOptions(); m_levelMapping.ActivateOptions(); System.IO.Stream consoleOutputStream = null; // Use the Console methods to open a Stream over the console std handle if (m_writeToErrorStream) { // Write to the error stream consoleOutputStream = Console.OpenStandardError(); } else { // Write to the output stream consoleOutputStream = Console.OpenStandardOutput(); } // Lookup the codepage encoding for the console System.Text.Encoding consoleEncoding = System.Text.Encoding.GetEncoding(GetConsoleOutputCP()); // Create a writer around the console stream m_consoleOutputWriter = new System.IO.StreamWriter(consoleOutputStream, consoleEncoding, 0x100); m_consoleOutputWriter.AutoFlush = true; // SuppressFinalize on m_consoleOutputWriter because all it will do is flush // and close the file handle. Because we have set AutoFlush the additional flush // is not required. The console file handle should not be closed, so we don't call // Dispose, Close or the finalizer. GC.SuppressFinalize(m_consoleOutputWriter); } #endregion // Override implementation of AppenderSkeleton #region Public Static Fields /// <summary> /// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console /// standard output stream. /// </summary> /// <remarks> /// <para> /// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console /// standard output stream. /// </para> /// </remarks> public const string ConsoleOut = "Console.Out"; /// <summary> /// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console /// standard error output stream. /// </summary> /// <remarks> /// <para> /// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console /// standard error output stream. /// </para> /// </remarks> public const string ConsoleError = "Console.Error"; #endregion // Public Static Fields #region Private Instances Fields /// <summary> /// Flag to write output to the error stream rather than the standard output stream /// </summary> private bool m_writeToErrorStream = false; /// <summary> /// Mapping from level object to color value /// </summary> private LevelMapping m_levelMapping = new LevelMapping(); /// <summary> /// The console output stream writer to write to /// </summary> /// <remarks> /// <para> /// This writer is not thread safe. /// </para> /// </remarks> private System.IO.StreamWriter m_consoleOutputWriter = null; #endregion // Private Instances Fields #region Win32 Methods [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] private static extern int GetConsoleOutputCP(); [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] private static extern bool SetConsoleTextAttribute( IntPtr consoleHandle, ushort attributes); [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] private static extern bool GetConsoleScreenBufferInfo( IntPtr consoleHandle, out CONSOLE_SCREEN_BUFFER_INFO bufferInfo); // [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] // private static extern bool WriteConsoleW( // IntPtr hConsoleHandle, // [MarshalAs(UnmanagedType.LPWStr)] string strBuffer, // UInt32 bufferLen, // out UInt32 written, // IntPtr reserved); //private const UInt32 STD_INPUT_HANDLE = unchecked((UInt32)(-10)); private const UInt32 STD_OUTPUT_HANDLE = unchecked((UInt32)(-11)); private const UInt32 STD_ERROR_HANDLE = unchecked((UInt32)(-12)); [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] private static extern IntPtr GetStdHandle( UInt32 type); [StructLayout(LayoutKind.Sequential)] private struct COORD { public UInt16 x; public UInt16 y; } [StructLayout(LayoutKind.Sequential)] private struct SMALL_RECT { public UInt16 Left; public UInt16 Top; public UInt16 Right; public UInt16 Bottom; } [StructLayout(LayoutKind.Sequential)] private struct CONSOLE_SCREEN_BUFFER_INFO { public COORD dwSize; public COORD dwCursorPosition; public ushort wAttributes; public SMALL_RECT srWindow; public COORD dwMaximumWindowSize; } #endregion // Win32 Methods #region LevelColors LevelMapping Entry /// <summary> /// A class to act as a mapping between the level that a logging call is made at and /// the color it should be displayed as. /// </summary> /// <remarks> /// <para> /// Defines the mapping between a level and the color it should be displayed in. /// </para> /// </remarks> public class LevelColors : LevelMappingEntry { private Colors m_foreColor; private Colors m_backColor; private ushort m_combinedColor = 0; /// <summary> /// The mapped foreground color for the specified level /// </summary> /// <remarks> /// <para> /// Required property. /// The mapped foreground color for the specified level. /// </para> /// </remarks> public Colors ForeColor { get { return m_foreColor; } set { m_foreColor = value; } } /// <summary> /// The mapped background color for the specified level /// </summary> /// <remarks> /// <para> /// Required property. /// The mapped background color for the specified level. /// </para> /// </remarks> public Colors BackColor { get { return m_backColor; } set { m_backColor = value; } } /// <summary> /// Initialize the options for the object /// </summary> /// <remarks> /// <para> /// Combine the <see cref="ForeColor"/> and <see cref="BackColor"/> together. /// </para> /// </remarks> public override void ActivateOptions() { base.ActivateOptions(); m_combinedColor = (ushort)( (int)m_foreColor + (((int)m_backColor) << 4) ); } /// <summary> /// The combined <see cref="ForeColor"/> and <see cref="BackColor"/> suitable for /// setting the console color. /// </summary> internal ushort CombinedColor { get { return m_combinedColor; } } } #endregion // LevelColors LevelMapping Entry } } #endif // !CLI_1_0 #endif // !SSCLI #endif // !MONO #endif // !NETCF