context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// 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.Reflection;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Tests
{
public static class SortedListTests
{
[Fact]
public static void TestCtor_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 static void TestCtor_Capacity(int capacity)
{
var sortList = new SortedList(capacity);
Assert.Equal(0, sortList.Count);
Assert.Equal(capacity, sortList.Capacity);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public static void TestCtor_Capcaity_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new SortedList(-1)); // Capacity < 0
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void TestCtor_IComparer_Capacity(int capacity)
{
var sortList = new SortedList(new CustomComparer(), capacity);
Assert.Equal(0, sortList.Count);
Assert.Equal(capacity, sortList.Capacity);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public static void TestCtor_IComparer_Capacity_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new SortedList(new CustomComparer(), -1)); // Capacity < 0
}
[Fact]
public static void TestCtor_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 static void Test_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 static void TestCtor_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 static void TestCtor_IDictionary_Invalid()
{
Assert.Throws<ArgumentNullException>(() => 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 static void TestCtor_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 static void TestCtor_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 static void TestCtor_IDictionary_IComparer_Invalid()
{
Assert.Throws<ArgumentNullException>(() => new SortedList(null, new CustomComparer())); // Dictionary is null
}
[Fact]
public static void TestDebuggerAttribute()
{
var list = new SortedList() { { "a", 1 }, { "b", 2 } };
DebuggerAttributes.ValidateDebuggerDisplayReferences(new SortedList());
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(list);
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(SortedList), SortedList.Synchronized(list));
bool threwNull = false;
try
{
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(SortedList), null);
}
catch (TargetInvocationException ex)
{
ArgumentNullException nullException = ex.InnerException as ArgumentNullException;
threwNull = nullException != null;
}
Assert.True(threwNull);
}
[Fact]
public static void TestAdd()
{
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 static void TestAdd_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<ArgumentNullException>(() => sortList2.Add(null, 101)); // Key is null
Assert.Throws<ArgumentException>(() => sortList2.Add(1, 101)); // Key already exists
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void TestClear(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 static void TestClone(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 static void TestClone_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 static void TestContainsKey()
{
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 static void TestContainsKey_Invalid()
{
var sortList1 = new SortedList();
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<ArgumentNullException>(() => sortList2.Contains(null)); // Key is null
Assert.Throws<ArgumentNullException>(() => sortList2.ContainsKey(null)); // Key is null
});
}
[Fact]
public static void TestContainsValue()
{
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 static void TestCopyTo(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 static void TestCopyTo_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<ArgumentNullException>(() => sortList2.CopyTo(null, 0)); // Array is null
Assert.Throws<ArgumentException>(() => sortList2.CopyTo(new object[10, 10], 0)); // Array is multidimensional
Assert.Throws<ArgumentOutOfRangeException>(() => sortList2.CopyTo(new object[100], -1)); // Index < 0
Assert.Throws<ArgumentException>(() => sortList2.CopyTo(new object[150], 51)); // Index + list.Count > array.Count
});
}
[Fact]
public static void TestGetByIndex()
{
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 static void TestGetByIndex_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<ArgumentOutOfRangeException>(() => sortList2.GetByIndex(-1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>(() => sortList2.GetByIndex(sortList2.Count)); // Index >= list.Count
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void TestGetEnumerator_IDictionaryEnumerator(int count)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IDictionaryEnumerator enumerator1 = sortList2.GetEnumerator();
IDictionaryEnumerator enumerator2 = sortList2.GetEnumerator();
IDictionaryEnumerator[] enumerators = { enumerator1, enumerator2 };
foreach (IDictionaryEnumerator enumerator in enumerators)
{
Assert.NotNull(enumerator);
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 static void TestGetEnumerator_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 static void TestGetEnumerator_IEnumerator(int count)
{
SortedList sortList = Helpers.CreateIntSortedList(count);
IEnumerator enumerator1 = ((IEnumerable)sortList).GetEnumerator();
IEnumerator enumerator2 = ((IEnumerable)sortList).GetEnumerator();
IEnumerator[] enumerators = { enumerator1, enumerator2 };
foreach (IEnumerator enumerator in enumerators)
{
Assert.NotNull(enumerator);
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 static void TestGetEnumerator_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 static void TestGetKeyList(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 static void TestGetKeyList_IsSameAsKeysProperty()
{
var sortList = Helpers.CreateIntSortedList(10);
Assert.Same(sortList.GetKeyList(), sortList.Keys);
}
[Fact]
public static void TestGetKeyList_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 static void TestGetKeyList_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 static void TestGetKeyList_Contains_Invalid()
{
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 static void TestGetKeyList_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 static void TestGetKeyList_IndexOf_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
Assert.Throws<ArgumentNullException>(() => 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 static void TestGetKeyList_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 static void TestGetKeyList_CopyTo_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
Assert.Throws<ArgumentNullException>(() => keys.CopyTo(null, 0)); // Array is null
Assert.Throws<ArgumentException>(() => keys.CopyTo(new object[10, 10], 0)); // Array is multidimensional
Assert.Throws<ArgumentOutOfRangeException>(() => keys.CopyTo(new object[100], -1)); // Index < 0
Assert.Throws<ArgumentException>(() => keys.CopyTo(new object[150], 51)); // Index + list.Count > array.Count
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void TestGetKeyList_GetEnumerator(int count)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
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 static void TestGetKeyList_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 static void TestGetKeyList_TryingToModifyCollection_Throws()
{
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 static void TestGetKey(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 static void TestGetKey_Invalid()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<ArgumentOutOfRangeException>(() => sortList2.GetKey(-1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>(() => sortList2.GetKey(sortList2.Count)); // Index >= count
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void TestGetValueList(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 static void TestGetValueList_IsSameAsValuesProperty()
{
var sortList = Helpers.CreateIntSortedList(10);
Assert.Same(sortList.GetValueList(), sortList.Values);
}
[Fact]
public static void TestGetValueList_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 static void TestGetValueList_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 static void TestGetValueList_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 static void TestGetValueList_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 static void TestGetValueList_CopyTo_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
Assert.Throws<ArgumentNullException>(() => values.CopyTo(null, 0)); // Array is null
Assert.Throws<ArgumentException>(() => values.CopyTo(new object[10, 10], 0)); // Array is multidimensional
Assert.Throws<ArgumentOutOfRangeException>(() => values.CopyTo(new object[100], -1)); // Index < 0
Assert.Throws<ArgumentException>(() => values.CopyTo(new object[150], 51)); // Index + list.Count > array.Count
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void TestGetValueList_GetEnumerator(int count)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
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 static void TestValueList_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 static void TestGetValueList_TryingToModifyCollection_Throws()
{
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 static void TestIndexOfKey()
{
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 static void TestIndexOfKey_Invalid()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<ArgumentNullException>(() => sortList2.IndexOfKey(null)); // Key is null
});
}
[Fact]
public static void TestIndexOfValue()
{
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 static void TestIndexOfValue_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 static void TestGetSetCapacity(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 static void TestSetCapacity_Shrink()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<ArgumentOutOfRangeException>(() => sortList2.Capacity = sortList2.Count - 1); // Capacity < count
});
}
[Fact]
public static void TestSetCapacity_Invalid()
{
var sortList1 = new SortedList();
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<ArgumentOutOfRangeException>(() => sortList2.Capacity = -1); // Capacity < 0
Assert.Throws<OutOfMemoryException>(() => sortList2.Capacity = int.MaxValue); // Capacity is too large
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
public static void TestGetObject(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 static void TestGetObject_DifferentCulture()
{
var sortList = new SortedList();
CultureInfo currentCulture = CultureInfo.DefaultThreadCurrentCulture;
try
{
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US");
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.DefaultThreadCurrentCulture = new CultureInfo("cs-CZ");
for (int i = 0; i < uniqueDisplayNameCount; i++)
{
Assert.Equal(installedCultures[i], sortList[installedCultures[i].DisplayName]);
}
}
catch (CultureNotFoundException)
{
}
finally
{
CultureInfo.DefaultThreadCurrentCulture = currentCulture;
}
}
[Fact]
public static void TestSetObject()
{
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 static void TestSetObject_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<ArgumentNullException>(() => sortList2[null] = 101); // Key is null
});
}
[Fact]
public static void TestRemoveAt()
{
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 static void TestRemoveAt_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<ArgumentOutOfRangeException>(() => sortList2.RemoveAt(-1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>(() => sortList2.RemoveAt(sortList2.Count)); // Index >= count
});
}
[Fact]
public static void TestRemove()
{
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 static void TestRemove_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<ArgumentNullException>(() => sortList2.Remove(null)); // Key is null
});
}
[Fact]
public static void TestSetByIndex()
{
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 static void TestSetByIndex_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<ArgumentOutOfRangeException>(() => sortList2.SetByIndex(-1, 101)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>(() => sortList2.SetByIndex(sortList2.Count, 101)); // Index >= list.Count
});
}
[Fact]
public static void TestSynchronized_IsSynchronized()
{
SortedList sortList = SortedList.Synchronized(new SortedList());
Assert.True(sortList.IsSynchronized);
}
[Fact]
public static void TestSynchronized_Invalid()
{
Assert.Throws<ArgumentNullException>(() => SortedList.Synchronized(null)); // List is null
}
[Fact]
public static void TestTrimToSize()
{
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
{
private string _stringValue = "Hello World";
public string StringValue
{
get { return _stringValue; }
set { _stringValue = value; }
}
}
private class CustomComparer : IComparer
{
public int Compare(object obj1, object obj2)
{
return -string.Compare(obj1.ToString(), obj2.ToString());
}
}
}
public class SortedList_SyncRootTests
{
private SortedList _sortListDaughter;
private SortedList _sortListGrandDaughter;
private int _numElements = 100;
[Fact]
[OuterLoop]
public void TestGetSyncRootBasic()
{
// Testing SyncRoot is not as simple as its implementation looks like. This is the working
// scenrio 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 < _numElements; i++)
{
sortListMother.Add("Key_" + i, "Value_" + i);
}
Assert.Equal(sortListMother.SyncRoot.GetType(), typeof(object));
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 < _numElements; 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 DevExpress.Mvvm.Native;
using DevExpress.Mvvm.UI.Interactivity;
using DevExpress.Mvvm.UI.Native;
using System;
using System.Collections.Specialized;
using System.Reflection;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Markup;
using System.Linq;
namespace DevExpress.Mvvm.UI {
[ContentProperty("Commands")]
public class CompositeCommandBehavior : Behavior<DependencyObject> {
#region Inner classes
class CompositeCommandCanExecuteConverter : IMultiValueConverter {
readonly CompositeCommandExecuteCondition canExecuteCondition;
public CompositeCommandCanExecuteConverter(CompositeCommandExecuteCondition canExecuteCondition) {
this.canExecuteCondition = canExecuteCondition;
}
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
if(values == null || values.Length == 0)
return false;
if(canExecuteCondition == CompositeCommandExecuteCondition.AllCommandsCanBeExecuted)
return values.Cast<bool>().All(x => x);
if(canExecuteCondition == CompositeCommandExecuteCondition.AnyCommandCanBeExecuted)
return values.Cast<bool>().Any(x => x);
throw new InvalidOperationException();
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) {
throw new NotImplementedException();
}
}
#endregion
#region Static
public static readonly DependencyProperty CommandPropertyNameProperty;
public static readonly DependencyProperty CanExecuteConditionProperty;
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Code Defects", "DXCA001")]
[IgnoreDependencyPropertiesConsistencyChecker]
static readonly DependencyProperty CanExecuteProperty;
[IgnoreDependencyPropertiesConsistencyChecker]
static readonly DependencyProperty InternalItemsProperty;
static CompositeCommandBehavior() {
Type owner = typeof(CompositeCommandBehavior);
CommandPropertyNameProperty = DependencyProperty.Register("CommandPropertyName", typeof(string), owner,
new PropertyMetadata("Command", (d, e) => ((CompositeCommandBehavior)d).OnCommandPropertyNameChanged(e)));
CanExecuteProperty = DependencyProperty.Register("CanExecute", typeof(bool), owner,
new PropertyMetadata(false, (d, e) => ((CompositeCommandBehavior)d).OnCanExecuteChanged(e)));
InternalItemsProperty = DependencyProperty.RegisterAttached("InternalItems", typeof(CommandsCollection), owner,
new PropertyMetadata(null));
CanExecuteConditionProperty = DependencyProperty.Register("CanExecuteCondition", typeof(CompositeCommandExecuteCondition), owner,
new PropertyMetadata(CompositeCommandExecuteCondition.AllCommandsCanBeExecuted, (d, e) => ((CompositeCommandBehavior)d).UpdateCanExecuteBinding()));
}
#endregion
#region Dependency Properties
public string CommandPropertyName {
get { return (string)GetValue(CommandPropertyNameProperty); }
set { SetValue(CommandPropertyNameProperty, value); }
}
bool CanExecute {
get { return (bool)GetValue(CanExecuteProperty); }
set { SetValue(CanExecuteProperty, value); }
}
public CompositeCommandExecuteCondition CanExecuteCondition {
get { return (CompositeCommandExecuteCondition)GetValue(CanExecuteConditionProperty); }
set { SetValue(CanExecuteConditionProperty, value); }
}
#endregion
#region Props
public DelegateCommand<object> CompositeCommand { get; private set; }
public CommandsCollection Commands { get; private set; }
#endregion
public CompositeCommandBehavior() {
CompositeCommand = new DelegateCommand<object>(CompositeCommandExecute, CompositeCommandCanExecute, false);
Commands = new CommandsCollection();
((INotifyCollectionChanged)Commands).CollectionChanged += OnCommandsChanged;
}
#region Commands
void OnCommandsChanged(object sender, NotifyCollectionChangedEventArgs e) {
UpdateCanExecuteBinding();
}
void UpdateCanExecuteBinding() {
MultiBinding multiBinding = new MultiBinding() {
Converter = new CompositeCommandCanExecuteConverter(CanExecuteCondition)
};
for(int i = 0; i < Commands.Count; i++) {
multiBinding.Bindings.Add(new Binding("CanExecute") {
Mode = BindingMode.OneWay,
Source = Commands[i]
});
}
BindingOperations.SetBinding(this, CanExecuteProperty, multiBinding);
}
void CompositeCommandExecute(object parameter) {
if(!CanExecute)
return;
foreach(CommandItem item in Commands)
item.ExecuteCommand();
}
bool CompositeCommandCanExecute(object parameter) {
return CanExecute;
}
void RaiseCompositeCommandCanExecuteChanged() {
CompositeCommand.RaiseCanExecuteChanged();
}
void OnCanExecuteChanged(DependencyPropertyChangedEventArgs e) {
RaiseCompositeCommandCanExecuteChanged();
}
#endregion
#region Attach|Detach command
protected override void OnAttached() {
base.OnAttached();
SetAssociatedObjectCommandProperty(CommandPropertyName);
AssociatedObject.SetValue(InternalItemsProperty, Commands);
}
protected override void OnDetaching() {
ReleaseAssociatedObjectCommandProperty(CommandPropertyName);
AssociatedObject.SetValue(InternalItemsProperty, null);
base.OnDetaching();
}
void OnCommandPropertyNameChanged(DependencyPropertyChangedEventArgs e) {
if(!IsAttached)
return;
ReleaseAssociatedObjectCommandProperty(e.OldValue as string);
SetAssociatedObjectCommandProperty(e.NewValue as string);
}
PropertyInfo GetCommandProperty(string propName) {
return ObjectPropertyHelper.GetPropertyInfoSetter(AssociatedObject, propName);
}
DependencyProperty GetCommandDependencyProperty(string propName) {
return ObjectPropertyHelper.GetDependencyProperty(AssociatedObject, propName);
}
void SetAssociatedObjectCommandProperty(string propName) {
var pi = GetCommandProperty(propName);
if(pi != null)
pi.SetValue(AssociatedObject, CompositeCommand, null);
else
GetCommandDependencyProperty(propName).Do(x => AssociatedObject.SetValue(x, CompositeCommand));
}
void ReleaseAssociatedObjectCommandProperty(string propName) {
var pi = GetCommandProperty(propName);
if(pi != null) {
if(pi.GetValue(AssociatedObject, null) == CompositeCommand)
pi.SetValue(AssociatedObject, null, null);
} else {
DependencyProperty commandProperty = GetCommandDependencyProperty(propName);
if(commandProperty != null && AssociatedObject.GetValue(commandProperty) == CompositeCommand)
AssociatedObject.SetValue(commandProperty, null);
}
}
#endregion
}
public class CommandsCollection : FreezableCollection<CommandItem> { }
public class CommandItem : DependencyObjectExt {
#region Static
public static readonly DependencyProperty CommandProperty;
public static readonly DependencyProperty CommandParameterProperty;
public static readonly DependencyProperty CheckCanExecuteProperty;
public static readonly DependencyProperty CanExecuteProperty;
static readonly DependencyPropertyKey CanExecutePropertyKey;
static CommandItem() {
Type owner = typeof(CommandItem);
CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), owner,
new PropertyMetadata(null, (d, e) => ((CommandItem)d).OnCommandChanged(e)));
CommandParameterProperty = DependencyProperty.Register("CommandParameter", typeof(object), owner,
new PropertyMetadata(null, (d, e) => ((CommandItem)d).UpdateCanExecute()));
CheckCanExecuteProperty = DependencyProperty.Register("CheckCanExecute", typeof(bool), owner,
new PropertyMetadata(true, (d, e) => ((CommandItem)d).UpdateCanExecute()));
CanExecutePropertyKey = DependencyProperty.RegisterReadOnly("CanExecute", typeof(bool), owner,
new PropertyMetadata(false));
CanExecuteProperty = CanExecutePropertyKey.DependencyProperty;
}
#endregion
#region Dependency Properties
public ICommand Command {
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
public object CommandParameter {
get { return GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
public bool CheckCanExecute {
get { return (bool)GetValue(CheckCanExecuteProperty); }
set { SetValue(CheckCanExecuteProperty, value); }
}
public bool CanExecute {
get { return (bool)GetValue(CanExecuteProperty); }
private set { SetValue(CanExecutePropertyKey, value); }
}
#endregion
CanExecuteChangedEventHandler<CommandItem> commandCanExecuteChangedHandler;
public bool ExecuteCommand() {
if(!CanExecute)
return false;
Command.Execute(CommandParameter);
return true;
}
void OnCommandChanged(DependencyPropertyChangedEventArgs e) {
var oldValue = e.OldValue as ICommand;
var newValue = e.NewValue as ICommand;
if(oldValue != null && commandCanExecuteChangedHandler != null) {
oldValue.CanExecuteChanged -= commandCanExecuteChangedHandler.Handler;
commandCanExecuteChangedHandler = null;
}
if(newValue != null) {
commandCanExecuteChangedHandler = new CanExecuteChangedEventHandler<CommandItem>(this, (owner, o, ee) => owner.OnCommandCanExecuteChanged(o, ee));
newValue.CanExecuteChanged += commandCanExecuteChangedHandler.Handler;
}
UpdateCanExecute();
}
void OnCommandCanExecuteChanged(object sender, EventArgs e) {
UpdateCanExecute();
}
void UpdateCanExecute() {
CanExecute = Command != null && (!CheckCanExecute || Command.CanExecute(CommandParameter));
}
}
public enum CompositeCommandExecuteCondition { AllCommandsCanBeExecuted, AnyCommandCanBeExecuted }
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
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
#if CLR4
using System;
using System.Linq;
using System.Abstract;
using System.Collections.Generic;
using SystemCaching = System.Runtime.Caching;
using System.Collections.ObjectModel;
namespace Contoso.Abstract
{
/// <summary>
/// ISystemServiceCache
/// </summary>
public interface ISystemServiceCache : IServiceCache
{
/// <summary>
/// Gets the cache.
/// </summary>
SystemCaching.ObjectCache Cache { get; }
/// <summary>
/// Gets the specified tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="regionName">Name of the region.</param>
/// <param name="names">The names.</param>
/// <returns></returns>
object Get(object tag, string regionName, IEnumerable<string> names);
}
/// <summary>
/// SystemServiceCache
/// </summary>
public class SystemServiceCache : ISystemServiceCache, ServiceCacheManager.ISetupRegistration
{
static SystemServiceCache() { ServiceCacheManager.EnsureRegistration(); }
/// <summary>
/// Initializes a new instance of the <see cref="SystemServiceCache"/> class.
/// </summary>
public SystemServiceCache()
: this(SystemCaching.MemoryCache.Default) { }
/// <summary>
/// Initializes a new instance of the <see cref="SystemServiceCache"/> class.
/// </summary>
/// <param name="name">The name.</param>
public SystemServiceCache(string name)
: this(new SystemCaching.MemoryCache(name)) { }
/// <summary>
/// Initializes a new instance of the <see cref="SystemServiceCache"/> class.
/// </summary>
/// <param name="cache">The cache.</param>
public SystemServiceCache(SystemCaching.ObjectCache cache)
{
Cache = cache;
Settings = new ServiceCacheSettings(new DefaultFileTouchableCacheItem(this, new DefaultTouchableCacheItem(this, null)));
}
Action<IServiceLocator, string> ServiceCacheManager.ISetupRegistration.DefaultServiceRegistrar
{
get { return (locator, name) => ServiceCacheManager.RegisterInstance<ISystemServiceCache>(this, locator, name); }
}
/// <summary>
/// Gets the service object of the specified type.
/// </summary>
/// <param name="serviceType">An object that specifies the type of service object to get.</param>
/// <returns>
/// A service object of type <paramref name="serviceType"/>.-or- null if there is no service object of type <paramref name="serviceType"/>.
/// </returns>
public object GetService(Type serviceType) { throw new NotImplementedException(); }
/// <summary>
/// Gets or sets the <see cref="System.Object"/> with the specified name.
/// </summary>
public object this[string name]
{
get { return Get(null, name); }
set { Set(null, name, CacheItemPolicy.Default, value, ServiceCacheByDispatcher.Empty); }
}
/// <summary>
/// Adds the specified tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="itemPolicy">The item policy.</param>
/// <param name="value">The value.</param>
/// <param name="dispatch">The dispatch.</param>
/// <returns></returns>
public object Add(object tag, string name, CacheItemPolicy itemPolicy, object value, ServiceCacheByDispatcher dispatch)
{
if (itemPolicy == null)
throw new ArgumentNullException("itemPolicy");
var updateCallback = itemPolicy.UpdateCallback;
if (updateCallback != null)
updateCallback(name, value);
string regionName;
Settings.TryGetRegion(ref name, out regionName);
//
value = Cache.Add(name, value, GetCacheDependency(tag, itemPolicy, dispatch), regionName);
var registration = dispatch.Registration;
if (registration != null && registration.UseHeaders)
{
var headerPolicy = new SystemCaching.CacheItemPolicy();
headerPolicy.ChangeMonitors.Add(Cache.CreateCacheEntryChangeMonitor(new[] { name }, regionName));
var header = dispatch.Header;
header.Item = name;
Cache.Add(name + "#", header, headerPolicy, regionName);
}
return value;
}
/// <summary>
/// Gets the item from cache associated with the key provided.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <returns>
/// The cached item.
/// </returns>
public object Get(object tag, string name)
{
string regionName;
Settings.TryGetRegion(ref name, out regionName);
return Cache.Get(name, regionName);
}
/// <summary>
/// Gets the specified tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="registration">The registration.</param>
/// <param name="header">The header.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException"></exception>
public object Get(object tag, string name, IServiceCacheRegistration registration, out CacheItemHeader header)
{
if (registration == null)
throw new ArgumentNullException("registration");
string regionName;
Settings.TryGetRegion(ref name, out regionName);
header = (registration.UseHeaders ? (CacheItemHeader)Cache.Get(name + "#", regionName) : null);
return Cache.Get(name, regionName);
}
/// <summary>
/// Gets the specified tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="names">The names.</param>
/// <returns></returns>
public object Get(object tag, IEnumerable<string> names) { return Cache.GetValues(null, names.ToArray()); }
/// <summary>
/// Gets the specified tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="regionName">Name of the region.</param>
/// <param name="names">The names.</param>
/// <returns></returns>
public object Get(object tag, string regionName, IEnumerable<string> names) { return Cache.GetValues(regionName, names.ToArray()); }
/// <summary>
/// Gets the specified registration.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="registration">The registration.</param>
/// <returns></returns>
/// <exception cref="System.NotImplementedException"></exception>
public IEnumerable<CacheItemHeader> Get(object tag, IServiceCacheRegistration registration)
{
if (registration == null)
throw new ArgumentNullException("registration");
throw new NotImplementedException();
}
/// <summary>
/// Tries the get.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public bool TryGet(object tag, string name, out object value)
{
string regionName;
Settings.TryGetRegion(ref name, out regionName);
var cacheItem = Cache.GetCacheItem(name, regionName);
if (cacheItem != null)
{
value = cacheItem.Value;
return true;
}
value = null;
return false;
}
/// <summary>
/// Adds an object into cache based on the parameters provided.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="itemPolicy">The itemPolicy object.</param>
/// <param name="value">The value to store in cache.</param>
/// <param name="dispatch">The dispatch.</param>
/// <returns></returns>
public object Set(object tag, string name, CacheItemPolicy itemPolicy, object value, ServiceCacheByDispatcher dispatch)
{
if (itemPolicy == null)
throw new ArgumentNullException("itemPolicy");
var updateCallback = itemPolicy.UpdateCallback;
if (updateCallback != null)
updateCallback(name, value);
string regionName;
Settings.TryGetRegion(ref name, out regionName);
//
Cache.Set(name, value, GetCacheDependency(tag, itemPolicy, dispatch), regionName);
var registration = dispatch.Registration;
if (registration != null && registration.UseHeaders)
{
var headerPolicy = new SystemCaching.CacheItemPolicy();
headerPolicy.ChangeMonitors.Add(Cache.CreateCacheEntryChangeMonitor(new[] { name }, regionName));
var header = dispatch.Header;
header.Item = name;
Cache.Set(name + "#", header, headerPolicy, regionName);
}
return value;
}
/// <summary>
/// Removes from cache the item associated with the key provided.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="registration">The registration.</param>
/// <returns>
/// The item removed from the Cache. If the value in the key parameter is not found, returns null.
/// </returns>
public object Remove(object tag, string name, IServiceCacheRegistration registration)
{
string regionName;
Settings.TryGetRegion(ref name, out regionName);
if (registration != null && registration.UseHeaders)
Cache.Remove(name + "#", regionName);
return Cache.Remove(name, regionName);
}
/// <summary>
/// Settings
/// </summary>
public ServiceCacheSettings Settings { get; private set; }
#region TouchableCacheItem
/// <summary>
/// DefaultTouchableCacheItem
/// </summary>
public class DefaultTouchableCacheItem : ITouchableCacheItem
{
private SystemServiceCache _parent;
private ITouchableCacheItem _base;
/// <summary>
/// Initializes a new instance of the <see cref="DefaultTouchableCacheItem"/> class.
/// </summary>
/// <param name="parent">The parent.</param>
/// <param name="base">The @base.</param>
public DefaultTouchableCacheItem(SystemServiceCache parent, ITouchableCacheItem @base) { _parent = parent; _base = @base; }
/// <summary>
/// Touches the specified tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="names">The names.</param>
public void Touch(object tag, string[] names)
{
if (names == null || names.Length == 0)
return;
var settings = _parent.Settings;
var cache = _parent.Cache;
foreach (var name in names)
{
var touchName = name;
string regionName;
settings.TryGetRegion(ref touchName, out regionName);
cache.Set(touchName, string.Empty, ServiceCache.InfiniteAbsoluteExpiration, regionName);
}
if (_base != null)
_base.Touch(tag, names);
}
/// <summary>
/// Makes the dependency.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="names">The names.</param>
/// <returns></returns>
public object MakeDependency(object tag, string[] names)
{
if (names == null || names.Length == 0)
return null;
var changeMonitors = new[] { _parent.Cache.CreateCacheEntryChangeMonitor(names) };
return (_base == null ? changeMonitors : changeMonitors.Union(_base.MakeDependency(tag, names) as IEnumerable<SystemCaching.ChangeMonitor>));
}
}
/// <summary>
/// DefaultFileTouchableCacheItem
/// </summary>
public class DefaultFileTouchableCacheItem : ServiceCache.FileTouchableCacheItemBase
{
/// <summary>
/// Initializes a new instance of the <see cref="DefaultFileTouchableCacheItem"/> class.
/// </summary>
/// <param name="parent">The parent.</param>
/// <param name="base">The @base.</param>
public DefaultFileTouchableCacheItem(SystemServiceCache parent, ITouchableCacheItem @base)
: base(parent, @base) { }
/// <summary>
/// Makes the dependency internal.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="names">The names.</param>
/// <param name="baseDependency">The base dependency.</param>
/// <returns></returns>
protected override object MakeDependencyInternal(object tag, string[] names, object baseDependency) { return new SystemCaching.HostFileChangeMonitor(names.Select(x => GetFilePathForName(x)).ToArray()); }
}
#endregion
#region Domain-specific
/// <summary>
/// Gets the cache.
/// </summary>
public SystemCaching.ObjectCache Cache { get; private set; }
#endregion
private SystemCaching.CacheItemPolicy GetCacheDependency(object tag, CacheItemPolicy itemPolicy, ServiceCacheByDispatcher dispatch)
{
// item priority
SystemCaching.CacheItemPriority itemPriority;
switch (itemPolicy.Priority)
{
case CacheItemPriority.NotRemovable:
itemPriority = SystemCaching.CacheItemPriority.NotRemovable;
break;
default:
itemPriority = SystemCaching.CacheItemPriority.Default;
break;
}
var removedCallback = (itemPolicy.RemovedCallback != null ? new SystemCaching.CacheEntryRemovedCallback(x => { itemPolicy.RemovedCallback(x.CacheItem.Key, x.CacheItem.Value); }) : null);
var updateCallback = (itemPolicy.UpdateCallback != null ? new SystemCaching.CacheEntryUpdateCallback(x => { itemPolicy.UpdateCallback(x.UpdatedCacheItem.Key, x.UpdatedCacheItem.Value); }) : null);
var newItemPolicy = new SystemCaching.CacheItemPolicy
{
AbsoluteExpiration = itemPolicy.AbsoluteExpiration,
Priority = itemPriority,
RemovedCallback = removedCallback,
SlidingExpiration = itemPolicy.SlidingExpiration,
UpdateCallback = updateCallback,
};
var changeMonitors = GetCacheDependency(tag, itemPolicy.Dependency, dispatch);
if (changeMonitors != null)
{
var list = newItemPolicy.ChangeMonitors;
foreach (var changeMonitor in changeMonitors)
list.Add(changeMonitor);
}
return newItemPolicy;
}
private IEnumerable<SystemCaching.ChangeMonitor> GetCacheDependency(object tag, CacheItemDependency dependency, ServiceCacheByDispatcher dispatch)
{
object value;
if (dependency == null || (value = dependency(this, dispatch.Registration, tag, dispatch.Values)) == null)
return null;
//
var names = (value as string[]);
var touchable = Settings.Touchable;
return ((touchable != null && names != null ? touchable.MakeDependency(tag, names) : value) as IEnumerable<SystemCaching.ChangeMonitor>);
}
}
}
#endif
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: support@ultracart.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// ScreenRecordingSettings
/// </summary>
[DataContract]
public partial class ScreenRecordingSettings : IEquatable<ScreenRecordingSettings>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="ScreenRecordingSettings" /> class.
/// </summary>
/// <param name="costPerThousand">Cost per one thousand sessions.</param>
/// <param name="enabled">enabled.</param>
/// <param name="retentionInterval">How long screen recording data is retained.</param>
/// <param name="sessionsCurrentBillingPeriod">sessionsCurrentBillingPeriod.</param>
/// <param name="sessionsLastBillingPeriod">sessionsLastBillingPeriod.</param>
/// <param name="sessionsTrialBillingPeriod">sessionsTrialBillingPeriod.</param>
/// <param name="trialExpiration">trialExpiration.</param>
/// <param name="trialExpired">trialExpired.</param>
public ScreenRecordingSettings(decimal? costPerThousand = default(decimal?), bool? enabled = default(bool?), string retentionInterval = default(string), int? sessionsCurrentBillingPeriod = default(int?), int? sessionsLastBillingPeriod = default(int?), int? sessionsTrialBillingPeriod = default(int?), string trialExpiration = default(string), bool? trialExpired = default(bool?))
{
this.CostPerThousand = costPerThousand;
this.Enabled = enabled;
this.RetentionInterval = retentionInterval;
this.SessionsCurrentBillingPeriod = sessionsCurrentBillingPeriod;
this.SessionsLastBillingPeriod = sessionsLastBillingPeriod;
this.SessionsTrialBillingPeriod = sessionsTrialBillingPeriod;
this.TrialExpiration = trialExpiration;
this.TrialExpired = trialExpired;
}
/// <summary>
/// Cost per one thousand sessions
/// </summary>
/// <value>Cost per one thousand sessions</value>
[DataMember(Name="cost_per_thousand", EmitDefaultValue=false)]
public decimal? CostPerThousand { get; set; }
/// <summary>
/// Gets or Sets Enabled
/// </summary>
[DataMember(Name="enabled", EmitDefaultValue=false)]
public bool? Enabled { get; set; }
/// <summary>
/// How long screen recording data is retained
/// </summary>
/// <value>How long screen recording data is retained</value>
[DataMember(Name="retention_interval", EmitDefaultValue=false)]
public string RetentionInterval { get; set; }
/// <summary>
/// Gets or Sets SessionsCurrentBillingPeriod
/// </summary>
[DataMember(Name="sessions_current_billing_period", EmitDefaultValue=false)]
public int? SessionsCurrentBillingPeriod { get; set; }
/// <summary>
/// Gets or Sets SessionsLastBillingPeriod
/// </summary>
[DataMember(Name="sessions_last_billing_period", EmitDefaultValue=false)]
public int? SessionsLastBillingPeriod { get; set; }
/// <summary>
/// Gets or Sets SessionsTrialBillingPeriod
/// </summary>
[DataMember(Name="sessions_trial_billing_period", EmitDefaultValue=false)]
public int? SessionsTrialBillingPeriod { get; set; }
/// <summary>
/// Gets or Sets TrialExpiration
/// </summary>
[DataMember(Name="trial_expiration", EmitDefaultValue=false)]
public string TrialExpiration { get; set; }
/// <summary>
/// Gets or Sets TrialExpired
/// </summary>
[DataMember(Name="trial_expired", EmitDefaultValue=false)]
public bool? TrialExpired { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ScreenRecordingSettings {\n");
sb.Append(" CostPerThousand: ").Append(CostPerThousand).Append("\n");
sb.Append(" Enabled: ").Append(Enabled).Append("\n");
sb.Append(" RetentionInterval: ").Append(RetentionInterval).Append("\n");
sb.Append(" SessionsCurrentBillingPeriod: ").Append(SessionsCurrentBillingPeriod).Append("\n");
sb.Append(" SessionsLastBillingPeriod: ").Append(SessionsLastBillingPeriod).Append("\n");
sb.Append(" SessionsTrialBillingPeriod: ").Append(SessionsTrialBillingPeriod).Append("\n");
sb.Append(" TrialExpiration: ").Append(TrialExpiration).Append("\n");
sb.Append(" TrialExpired: ").Append(TrialExpired).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as ScreenRecordingSettings);
}
/// <summary>
/// Returns true if ScreenRecordingSettings instances are equal
/// </summary>
/// <param name="input">Instance of ScreenRecordingSettings to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ScreenRecordingSettings input)
{
if (input == null)
return false;
return
(
this.CostPerThousand == input.CostPerThousand ||
(this.CostPerThousand != null &&
this.CostPerThousand.Equals(input.CostPerThousand))
) &&
(
this.Enabled == input.Enabled ||
(this.Enabled != null &&
this.Enabled.Equals(input.Enabled))
) &&
(
this.RetentionInterval == input.RetentionInterval ||
(this.RetentionInterval != null &&
this.RetentionInterval.Equals(input.RetentionInterval))
) &&
(
this.SessionsCurrentBillingPeriod == input.SessionsCurrentBillingPeriod ||
(this.SessionsCurrentBillingPeriod != null &&
this.SessionsCurrentBillingPeriod.Equals(input.SessionsCurrentBillingPeriod))
) &&
(
this.SessionsLastBillingPeriod == input.SessionsLastBillingPeriod ||
(this.SessionsLastBillingPeriod != null &&
this.SessionsLastBillingPeriod.Equals(input.SessionsLastBillingPeriod))
) &&
(
this.SessionsTrialBillingPeriod == input.SessionsTrialBillingPeriod ||
(this.SessionsTrialBillingPeriod != null &&
this.SessionsTrialBillingPeriod.Equals(input.SessionsTrialBillingPeriod))
) &&
(
this.TrialExpiration == input.TrialExpiration ||
(this.TrialExpiration != null &&
this.TrialExpiration.Equals(input.TrialExpiration))
) &&
(
this.TrialExpired == input.TrialExpired ||
(this.TrialExpired != null &&
this.TrialExpired.Equals(input.TrialExpired))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.CostPerThousand != null)
hashCode = hashCode * 59 + this.CostPerThousand.GetHashCode();
if (this.Enabled != null)
hashCode = hashCode * 59 + this.Enabled.GetHashCode();
if (this.RetentionInterval != null)
hashCode = hashCode * 59 + this.RetentionInterval.GetHashCode();
if (this.SessionsCurrentBillingPeriod != null)
hashCode = hashCode * 59 + this.SessionsCurrentBillingPeriod.GetHashCode();
if (this.SessionsLastBillingPeriod != null)
hashCode = hashCode * 59 + this.SessionsLastBillingPeriod.GetHashCode();
if (this.SessionsTrialBillingPeriod != null)
hashCode = hashCode * 59 + this.SessionsTrialBillingPeriod.GetHashCode();
if (this.TrialExpiration != null)
hashCode = hashCode * 59 + this.TrialExpiration.GetHashCode();
if (this.TrialExpired != null)
hashCode = hashCode * 59 + this.TrialExpired.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
/*
* Farseer Physics Engine:
* Copyright (c) 2012 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System.Diagnostics;
using FarseerPhysics.Common;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Dynamics.Joints
{
// p = attached point, m = mouse point
// C = p - m
// Cdot = v
// = v + cross(w, r)
// J = [I r_skew]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
/// <summary>
/// A mouse joint is used to make a point on a body track a
/// specified world point. This is a soft constraint with a maximum
/// force. This allows the constraint to stretch without
/// applying huge forces.
/// NOTE: this joint is not documented in the manual because it was
/// developed to be used in the testbed. If you want to learn how to
/// use the mouse joint, look at the testbed.
/// </summary>
public class FixedMouseJoint : Joint
{
#region Properties/Fields
/// <summary>
/// The local anchor point on BodyA
/// </summary>
public Vector2 LocalAnchorA;
public override Vector2 WorldAnchorA
{
get => BodyA.GetWorldPoint(LocalAnchorA);
set => LocalAnchorA = BodyA.GetLocalPoint(value);
}
public override Vector2 WorldAnchorB
{
get => _worldAnchor;
set
{
WakeBodies();
_worldAnchor = value;
}
}
/// <summary>
/// The maximum constraint force that can be exerted to move the candidate body. Usually you will express
/// as some multiple of the weight (multiplier * mass * gravity).
/// </summary>
public float MaxForce
{
get => _maxForce;
set
{
Debug.Assert(MathUtils.IsValid(value) && value >= 0.0f);
_maxForce = value;
}
}
/// <summary>
/// The response speed.
/// </summary>
public float Frequency
{
get => _frequency;
set
{
Debug.Assert(MathUtils.IsValid(value) && value >= 0.0f);
_frequency = value;
}
}
/// <summary>
/// The damping ratio. 0 = no damping, 1 = critical damping.
/// </summary>
public float DampingRatio
{
get => _dampingRatio;
set
{
Debug.Assert(MathUtils.IsValid(value) && value >= 0.0f);
_dampingRatio = value;
}
}
Vector2 _worldAnchor;
float _frequency;
float _dampingRatio;
float _beta;
// Solver shared
Vector2 _impulse;
float _maxForce;
float _gamma;
// Solver temp
int _indexA;
Vector2 _rA;
Vector2 _localCenterA;
float _invMassA;
float _invIA;
Mat22 _mass;
Vector2 _C;
#endregion
/// <summary>
/// This requires a world target point,
/// tuning parameters, and the time step.
/// </summary>
/// <param name="body">The body.</param>
/// <param name="worldAnchor">The target.</param>
public FixedMouseJoint(Body body, Vector2 worldAnchor) : base(body)
{
JointType = JointType.FixedMouse;
Frequency = 5.0f;
DampingRatio = 0.7f;
MaxForce = 1000 * body.Mass;
Debug.Assert(worldAnchor.IsValid());
_worldAnchor = worldAnchor;
LocalAnchorA = MathUtils.MulT(BodyA._xf, worldAnchor);
}
public override Vector2 GetReactionForce(float invDt)
{
return invDt * _impulse;
}
public override float GetReactionTorque(float invDt)
{
return invDt * 0.0f;
}
internal override void InitVelocityConstraints(ref SolverData data)
{
_indexA = BodyA.IslandIndex;
_localCenterA = BodyA._sweep.LocalCenter;
_invMassA = BodyA._invMass;
_invIA = BodyA._invI;
var cA = data.Positions[_indexA].C;
var aA = data.Positions[_indexA].A;
var vA = data.Velocities[_indexA].V;
var wA = data.Velocities[_indexA].W;
var qA = new Rot(aA);
float mass = BodyA.Mass;
// Frequency
float omega = 2.0f * Settings.Pi * Frequency;
// Damping coefficient
float d = 2.0f * mass * DampingRatio * omega;
// Spring stiffness
float k = mass * (omega * omega);
// magic formulas
// gamma has units of inverse mass.
// beta has units of inverse time.
float h = data.Step.Dt;
Debug.Assert(d + h * k > Settings.Epsilon, "damping is less than Epsilon. Does the body have mass?");
_gamma = h * (d + h * k);
if (_gamma != 0.0f)
_gamma = 1.0f / _gamma;
_beta = h * k * _gamma;
// Compute the effective mass matrix.
_rA = MathUtils.Mul(qA, LocalAnchorA - _localCenterA);
// K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)]
// = [1/m1+1/m2 0 ] + invI1 * [r1.Y*r1.Y -r1.X*r1.Y] + invI2 * [r1.Y*r1.Y -r1.X*r1.Y]
// [ 0 1/m1+1/m2] [-r1.X*r1.Y r1.X*r1.X] [-r1.X*r1.Y r1.X*r1.X]
var K = new Mat22();
K.Ex.X = _invMassA + _invIA * _rA.Y * _rA.Y + _gamma;
K.Ex.Y = -_invIA * _rA.X * _rA.Y;
K.Ey.X = K.Ex.Y;
K.Ey.Y = _invMassA + _invIA * _rA.X * _rA.X + _gamma;
_mass = K.Inverse;
_C = cA + _rA - _worldAnchor;
_C *= _beta;
// Cheat with some damping
wA *= 0.98f;
if (Settings.EnableWarmstarting)
{
_impulse *= data.Step.DtRatio;
vA += _invMassA * _impulse;
wA += _invIA * MathUtils.Cross(_rA, _impulse);
}
else
{
_impulse = Vector2.Zero;
}
data.Velocities[_indexA].V = vA;
data.Velocities[_indexA].W = wA;
}
internal override void SolveVelocityConstraints(ref SolverData data)
{
var vA = data.Velocities[_indexA].V;
var wA = data.Velocities[_indexA].W;
// Cdot = v + cross(w, r)
var Cdot = vA + MathUtils.Cross(wA, _rA);
var impulse = MathUtils.Mul(ref _mass, -(Cdot + _C + _gamma * _impulse));
var oldImpulse = _impulse;
_impulse += impulse;
float maxImpulse = data.Step.Dt * MaxForce;
if (_impulse.LengthSquared() > maxImpulse * maxImpulse)
{
_impulse *= maxImpulse / _impulse.Length();
}
impulse = _impulse - oldImpulse;
vA += _invMassA * impulse;
wA += _invIA * MathUtils.Cross(_rA, impulse);
data.Velocities[_indexA].V = vA;
data.Velocities[_indexA].W = wA;
}
internal override bool SolvePositionConstraints(ref SolverData data)
{
return true;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// See CompactBinary.cs for a description of the CompactBinary protocol.
namespace Bond.Protocols
{
using System;
using System.Runtime.CompilerServices;
using System.Text;
using System.Collections.Generic;
using Bond.IO;
/// <summary>
/// Length-calculator for Bond CompactBinary protocol V2
/// </summary>
[Reader(typeof(CompactBinaryReader<>))]
public struct CompactBinaryCounter : IProtocolWriter
{
private class CounterStackFrame
{
public readonly LinkedListNode<UInt32> lengthSlot;
public int currentLength;
public CounterStackFrame(LinkedListNode<UInt32> slot)
{
lengthSlot = slot;
}
}
readonly LinkedList<UInt32> lengths;
readonly Stack<CounterStackFrame> counterStack;
/// <summary>
/// Create an instance of CompactBinaryCounter
/// </summary>
public CompactBinaryCounter(LinkedList<UInt32> lengthsOut)
{
lengths = lengthsOut;
counterStack = new Stack<CounterStackFrame>();
}
private CounterStackFrame GetCurrentStackFrame()
{
return counterStack.Peek();
}
private void AddBytes(int count)
{
var stackFrame = GetCurrentStackFrame();
var length = checked(stackFrame.currentLength + count);
stackFrame.currentLength = length;
}
private void AddVarUInt16(ushort value)
{
AddBytes(IntegerHelper.GetVarUInt16Length(value));
}
private void AddVarUInt32(uint value)
{
AddBytes(IntegerHelper.GetVarUInt32Length(value));
}
private void AddVarUInt64(ulong value)
{
AddBytes(IntegerHelper.GetVarUInt64Length(value));
}
/// <summary>
/// Write protocol magic number and version
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteVersion()
{
}
#region Complex types
/// <summary>
/// Start writing a struct
/// </summary>
/// <param name="metadata">Schema metadata</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteStructBegin(Metadata metadata)
{
LinkedListNode<UInt32> frameNode = lengths.AddLast(0);
counterStack.Push(new CounterStackFrame(frameNode));
}
/// <summary>
/// End writing a struct
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteStructEnd()
{
CounterStackFrame frame = counterStack.Peek();
uint structLength = (uint)frame.currentLength + 1; // +1 for the BT_STOP byte
frame.lengthSlot.Value = structLength;
counterStack.Pop();
if (counterStack.Count > 0)
{
AddVarUInt32(structLength);
AddBytes(checked((int)structLength));
}
}
/// <summary>
/// Start writing a base struct
/// </summary>
/// <param name="metadata">Base schema metadata</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteBaseBegin(Metadata metadata)
{ }
/// <summary>
/// End writing a base struct
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteBaseEnd()
{
AddBytes(1);
}
/// <summary>
/// Start writing a field
/// </summary>
/// <param name="type">Type of the field</param>
/// <param name="id">Identifier of the field</param>
/// <param name="metadata">Metadata of the field</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteFieldBegin(BondDataType type, ushort id, Metadata metadata)
{
if (id <= 5)
{
AddBytes(1);
}
else if (id <= 0xFF)
{
AddBytes(2);
}
else
{
AddBytes(3);
}
}
/// <summary>
/// Indicate that field was omitted because it was set to its default value
/// </summary>
/// <param name="dataType">Type of the field</param>
/// <param name="id">Identifier of the field</param>
/// <param name="metadata">Metadata of the field</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteFieldOmitted(BondDataType dataType, ushort id, Metadata metadata)
{ }
/// <summary>
/// End writing a field
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteFieldEnd()
{ }
/// <summary>
/// Start writing a list or set container
/// </summary>
/// <param name="count">Number of elements in the container</param>
/// <param name="elementType">Type of the elements</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteContainerBegin(int count, BondDataType elementType)
{
if (count < 7)
{
AddBytes(1);
}
else
{
AddBytes(1);
AddVarUInt32((uint)count);
}
}
/// <summary>
/// Start writing a map container
/// </summary>
/// <param name="count">Number of elements in the container</param>
/// <param name="keyType">Type of the keys</param>
/// <param name="valueType">Type of the values</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteContainerBegin(int count, BondDataType keyType, BondDataType valueType)
{
AddBytes(2);
AddVarUInt32((uint)count);
}
/// <summary>
/// End writing a container
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteContainerEnd()
{ }
/// <summary>
/// Write array of bytes verbatim
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteBytes(ArraySegment<byte> data)
{
AddBytes(data.Count);
}
#endregion
#region Primitive types
/// <summary>
/// Write an UInt8
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUInt8(byte value)
{
AddBytes(1);
}
/// <summary>
/// Write an UInt16
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUInt16(UInt16 value)
{
AddVarUInt16(value);
}
/// <summary>
/// Write an UInt16
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUInt32(UInt32 value)
{
AddVarUInt32(value);
}
/// <summary>
/// Write an UInt64
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUInt64(UInt64 value)
{
AddVarUInt64(value);
}
/// <summary>
/// Write an Int8
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteInt8(SByte value)
{
AddBytes(1);
}
/// <summary>
/// Write an Int16
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteInt16(Int16 value)
{
AddVarUInt16(IntegerHelper.EncodeZigzag16(value));
}
/// <summary>
/// Write an Int32
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteInt32(Int32 value)
{
AddVarUInt32(IntegerHelper.EncodeZigzag32(value));
}
/// <summary>
/// Write an Int64
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteInt64(Int64 value)
{
AddVarUInt64(IntegerHelper.EncodeZigzag64(value));
}
/// <summary>
/// Write a float
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteFloat(float value)
{
AddBytes(4);
}
/// <summary>
/// Write a double
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteDouble(double value)
{
AddBytes(8);
}
/// <summary>
/// Write a bool
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteBool(bool value)
{
AddBytes(1);
}
/// <summary>
/// Write a UTF-8 string
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteString(string value)
{
int size = Encoding.UTF8.GetByteCount(value);
AddVarUInt32((uint)size);
AddBytes(size);
}
/// <summary>
/// Write a UTF-16 string
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteWString(string value)
{
AddVarUInt32((uint)value.Length);
AddBytes(value.Length * 2);
}
#endregion
}
}
| |
using System;
namespace Com.CodeGame.CodeHockey2014.DevKit.CSharpCgdk.Model {
public class Game {
private readonly long randomSeed;
private readonly int tickCount;
private readonly double worldWidth;
private readonly double worldHeight;
private readonly double goalNetTop;
private readonly double goalNetWidth;
private readonly double goalNetHeight;
private readonly double rinkTop;
private readonly double rinkLeft;
private readonly double rinkBottom;
private readonly double rinkRight;
private readonly int afterGoalStateTickCount;
private readonly int overtimeTickCount;
private readonly int defaultActionCooldownTicks;
private readonly int swingActionCooldownTicks;
private readonly int cancelStrikeActionCooldownTicks;
private readonly int actionCooldownTicksAfterLosingPuck;
private readonly double stickLength;
private readonly double stickSector;
private readonly double passSector;
private readonly int hockeyistAttributeBaseValue;
private readonly double minActionChance;
private readonly double maxActionChance;
private readonly double strikeAngleDeviation;
private readonly double passAngleDeviation;
private readonly double pickUpPuckBaseChance;
private readonly double takePuckAwayBaseChance;
private readonly int maxEffectiveSwingTicks;
private readonly double strikePowerBaseFactor;
private readonly double strikePowerGrowthFactor;
private readonly double strikePuckBaseChance;
private readonly double knockdownChanceFactor;
private readonly double knockdownTicksFactor;
private readonly double maxSpeedToAllowSubstitute;
private readonly double substitutionAreaHeight;
private readonly double passPowerFactor;
private readonly double hockeyistMaxStamina;
private readonly double activeHockeyistStaminaGrowthPerTick;
private readonly double restingHockeyistStaminaGrowthPerTick;
private readonly double zeroStaminaHockeyistEffectivenessFactor;
private readonly double speedUpStaminaCostFactor;
private readonly double turnStaminaCostFactor;
private readonly double takePuckStaminaCost;
private readonly double swingStaminaCost;
private readonly double strikeStaminaBaseCost;
private readonly double strikeStaminaCostGrowthFactor;
private readonly double cancelStrikeStaminaCost;
private readonly double passStaminaCost;
private readonly double goalieMaxSpeed;
private readonly double hockeyistMaxSpeed;
private readonly double struckHockeyistInitialSpeedFactor;
private readonly double hockeyistSpeedUpFactor;
private readonly double hockeyistSpeedDownFactor;
private readonly double hockeyistTurnAngleFactor;
private readonly int versatileHockeyistStrength;
private readonly int versatileHockeyistEndurance;
private readonly int versatileHockeyistDexterity;
private readonly int versatileHockeyistAgility;
private readonly int forwardHockeyistStrength;
private readonly int forwardHockeyistEndurance;
private readonly int forwardHockeyistDexterity;
private readonly int forwardHockeyistAgility;
private readonly int defencemanHockeyistStrength;
private readonly int defencemanHockeyistEndurance;
private readonly int defencemanHockeyistDexterity;
private readonly int defencemanHockeyistAgility;
private readonly int minRandomHockeyistParameter;
private readonly int maxRandomHockeyistParameter;
private readonly double struckPuckInitialSpeedFactor;
private readonly double puckBindingRange;
public Game(long randomSeed, int tickCount, double worldWidth, double worldHeight, double goalNetTop,
double goalNetWidth, double goalNetHeight, double rinkTop, double rinkLeft, double rinkBottom,
double rinkRight, int afterGoalStateTickCount, int overtimeTickCount, int defaultActionCooldownTicks,
int swingActionCooldownTicks, int cancelStrikeActionCooldownTicks,
int actionCooldownTicksAfterLosingPuck, double stickLength, double stickSector, double passSector,
int hockeyistAttributeBaseValue, double minActionChance, double maxActionChance,
double strikeAngleDeviation, double passAngleDeviation, double pickUpPuckBaseChance,
double takePuckAwayBaseChance, int maxEffectiveSwingTicks, double strikePowerBaseFactor,
double strikePowerGrowthFactor, double strikePuckBaseChance, double knockdownChanceFactor,
double knockdownTicksFactor, double maxSpeedToAllowSubstitute, double substitutionAreaHeight,
double passPowerFactor, double hockeyistMaxStamina, double activeHockeyistStaminaGrowthPerTick,
double restingHockeyistStaminaGrowthPerTick, double zeroStaminaHockeyistEffectivenessFactor,
double speedUpStaminaCostFactor, double turnStaminaCostFactor, double takePuckStaminaCost,
double swingStaminaCost, double strikeStaminaBaseCost, double strikeStaminaCostGrowthFactor,
double cancelStrikeStaminaCost, double passStaminaCost, double goalieMaxSpeed, double hockeyistMaxSpeed,
double struckHockeyistInitialSpeedFactor, double hockeyistSpeedUpFactor,
double hockeyistSpeedDownFactor, double hockeyistTurnAngleFactor, int versatileHockeyistStrength,
int versatileHockeyistEndurance, int versatileHockeyistDexterity, int versatileHockeyistAgility,
int forwardHockeyistStrength, int forwardHockeyistEndurance, int forwardHockeyistDexterity,
int forwardHockeyistAgility, int defencemanHockeyistStrength, int defencemanHockeyistEndurance,
int defencemanHockeyistDexterity, int defencemanHockeyistAgility, int minRandomHockeyistParameter,
int maxRandomHockeyistParameter, double struckPuckInitialSpeedFactor, double puckBindingRange) {
this.randomSeed = randomSeed;
this.tickCount = tickCount;
this.worldWidth = worldWidth;
this.worldHeight = worldHeight;
this.goalNetTop = goalNetTop;
this.goalNetWidth = goalNetWidth;
this.goalNetHeight = goalNetHeight;
this.rinkTop = rinkTop;
this.rinkLeft = rinkLeft;
this.rinkBottom = rinkBottom;
this.rinkRight = rinkRight;
this.afterGoalStateTickCount = afterGoalStateTickCount;
this.overtimeTickCount = overtimeTickCount;
this.defaultActionCooldownTicks = defaultActionCooldownTicks;
this.swingActionCooldownTicks = swingActionCooldownTicks;
this.cancelStrikeActionCooldownTicks = cancelStrikeActionCooldownTicks;
this.actionCooldownTicksAfterLosingPuck = actionCooldownTicksAfterLosingPuck;
this.stickLength = stickLength;
this.stickSector = stickSector;
this.passSector = passSector;
this.hockeyistAttributeBaseValue = hockeyistAttributeBaseValue;
this.minActionChance = minActionChance;
this.maxActionChance = maxActionChance;
this.strikeAngleDeviation = strikeAngleDeviation;
this.passAngleDeviation = passAngleDeviation;
this.pickUpPuckBaseChance = pickUpPuckBaseChance;
this.takePuckAwayBaseChance = takePuckAwayBaseChance;
this.maxEffectiveSwingTicks = maxEffectiveSwingTicks;
this.strikePowerBaseFactor = strikePowerBaseFactor;
this.strikePowerGrowthFactor = strikePowerGrowthFactor;
this.strikePuckBaseChance = strikePuckBaseChance;
this.knockdownChanceFactor = knockdownChanceFactor;
this.knockdownTicksFactor = knockdownTicksFactor;
this.maxSpeedToAllowSubstitute = maxSpeedToAllowSubstitute;
this.substitutionAreaHeight = substitutionAreaHeight;
this.passPowerFactor = passPowerFactor;
this.hockeyistMaxStamina = hockeyistMaxStamina;
this.activeHockeyistStaminaGrowthPerTick = activeHockeyistStaminaGrowthPerTick;
this.restingHockeyistStaminaGrowthPerTick = restingHockeyistStaminaGrowthPerTick;
this.zeroStaminaHockeyistEffectivenessFactor = zeroStaminaHockeyistEffectivenessFactor;
this.speedUpStaminaCostFactor = speedUpStaminaCostFactor;
this.turnStaminaCostFactor = turnStaminaCostFactor;
this.takePuckStaminaCost = takePuckStaminaCost;
this.swingStaminaCost = swingStaminaCost;
this.strikeStaminaBaseCost = strikeStaminaBaseCost;
this.strikeStaminaCostGrowthFactor = strikeStaminaCostGrowthFactor;
this.cancelStrikeStaminaCost = cancelStrikeStaminaCost;
this.passStaminaCost = passStaminaCost;
this.goalieMaxSpeed = goalieMaxSpeed;
this.hockeyistMaxSpeed = hockeyistMaxSpeed;
this.struckHockeyistInitialSpeedFactor = struckHockeyistInitialSpeedFactor;
this.hockeyistSpeedUpFactor = hockeyistSpeedUpFactor;
this.hockeyistSpeedDownFactor = hockeyistSpeedDownFactor;
this.hockeyistTurnAngleFactor = hockeyistTurnAngleFactor;
this.versatileHockeyistStrength = versatileHockeyistStrength;
this.versatileHockeyistEndurance = versatileHockeyistEndurance;
this.versatileHockeyistDexterity = versatileHockeyistDexterity;
this.versatileHockeyistAgility = versatileHockeyistAgility;
this.forwardHockeyistStrength = forwardHockeyistStrength;
this.forwardHockeyistEndurance = forwardHockeyistEndurance;
this.forwardHockeyistDexterity = forwardHockeyistDexterity;
this.forwardHockeyistAgility = forwardHockeyistAgility;
this.defencemanHockeyistStrength = defencemanHockeyistStrength;
this.defencemanHockeyistEndurance = defencemanHockeyistEndurance;
this.defencemanHockeyistDexterity = defencemanHockeyistDexterity;
this.defencemanHockeyistAgility = defencemanHockeyistAgility;
this.minRandomHockeyistParameter = minRandomHockeyistParameter;
this.maxRandomHockeyistParameter = maxRandomHockeyistParameter;
this.struckPuckInitialSpeedFactor = struckPuckInitialSpeedFactor;
this.puckBindingRange = puckBindingRange;
}
public long RandomSeed {
get { return randomSeed; }
}
public int TickCount {
get { return tickCount; }
}
public double WorldWidth {
get { return worldWidth; }
}
public double WorldHeight {
get { return worldHeight; }
}
public double GoalNetTop {
get { return goalNetTop; }
}
public double GoalNetWidth {
get { return goalNetWidth; }
}
public double GoalNetHeight {
get { return goalNetHeight; }
}
public double RinkTop {
get { return rinkTop; }
}
public double RinkLeft {
get { return rinkLeft; }
}
public double RinkBottom {
get { return rinkBottom; }
}
public double RinkRight {
get { return rinkRight; }
}
public int AfterGoalStateTickCount {
get { return afterGoalStateTickCount; }
}
public int OvertimeTickCount {
get { return overtimeTickCount; }
}
public int DefaultActionCooldownTicks {
get { return defaultActionCooldownTicks; }
}
public int SwingActionCooldownTicks {
get { return swingActionCooldownTicks; }
}
public int CancelStrikeActionCooldownTicks {
get { return cancelStrikeActionCooldownTicks; }
}
public int ActionCooldownTicksAfterLosingPuck {
get { return actionCooldownTicksAfterLosingPuck; }
}
public double StickLength {
get { return stickLength; }
}
public double StickSector {
get { return stickSector; }
}
public double PassSector {
get { return passSector; }
}
public int HockeyistAttributeBaseValue {
get { return hockeyistAttributeBaseValue; }
}
public double MinActionChance {
get { return minActionChance; }
}
public double MaxActionChance {
get { return maxActionChance; }
}
public double StrikeAngleDeviation {
get { return strikeAngleDeviation; }
}
public double PassAngleDeviation {
get { return passAngleDeviation; }
}
public double PickUpPuckBaseChance {
get { return pickUpPuckBaseChance; }
}
public double TakePuckAwayBaseChance {
get { return takePuckAwayBaseChance; }
}
public int MaxEffectiveSwingTicks {
get { return maxEffectiveSwingTicks; }
}
public double StrikePowerBaseFactor {
get { return strikePowerBaseFactor; }
}
public double StrikePowerGrowthFactor {
get { return strikePowerGrowthFactor; }
}
public double StrikePuckBaseChance {
get { return strikePuckBaseChance; }
}
public double KnockdownChanceFactor {
get { return knockdownChanceFactor; }
}
public double KnockdownTicksFactor {
get { return knockdownTicksFactor; }
}
public double MaxSpeedToAllowSubstitute {
get { return maxSpeedToAllowSubstitute; }
}
public double SubstitutionAreaHeight {
get { return substitutionAreaHeight; }
}
public double PassPowerFactor {
get { return passPowerFactor; }
}
public double HockeyistMaxStamina {
get { return hockeyistMaxStamina; }
}
public double ActiveHockeyistStaminaGrowthPerTick {
get { return activeHockeyistStaminaGrowthPerTick; }
}
public double RestingHockeyistStaminaGrowthPerTick {
get { return restingHockeyistStaminaGrowthPerTick; }
}
public double ZeroStaminaHockeyistEffectivenessFactor {
get { return zeroStaminaHockeyistEffectivenessFactor; }
}
public double SpeedUpStaminaCostFactor {
get { return speedUpStaminaCostFactor; }
}
public double TurnStaminaCostFactor {
get { return turnStaminaCostFactor; }
}
public double TakePuckStaminaCost {
get { return takePuckStaminaCost; }
}
public double SwingStaminaCost {
get { return swingStaminaCost; }
}
public double StrikeStaminaBaseCost {
get { return strikeStaminaBaseCost; }
}
public double StrikeStaminaCostGrowthFactor {
get { return strikeStaminaCostGrowthFactor; }
}
public double CancelStrikeStaminaCost {
get { return cancelStrikeStaminaCost; }
}
public double PassStaminaCost {
get { return passStaminaCost; }
}
public double GoalieMaxSpeed {
get { return goalieMaxSpeed; }
}
public double HockeyistMaxSpeed {
get { return hockeyistMaxSpeed; }
}
public double StruckHockeyistInitialSpeedFactor {
get { return struckHockeyistInitialSpeedFactor; }
}
public double HockeyistSpeedUpFactor {
get { return hockeyistSpeedUpFactor; }
}
public double HockeyistSpeedDownFactor {
get { return hockeyistSpeedDownFactor; }
}
public double HockeyistTurnAngleFactor {
get { return hockeyistTurnAngleFactor; }
}
public int VersatileHockeyistStrength {
get { return versatileHockeyistStrength; }
}
public int VersatileHockeyistEndurance {
get { return versatileHockeyistEndurance; }
}
public int VersatileHockeyistDexterity {
get { return versatileHockeyistDexterity; }
}
public int VersatileHockeyistAgility {
get { return versatileHockeyistAgility; }
}
public int ForwardHockeyistStrength {
get { return forwardHockeyistStrength; }
}
public int ForwardHockeyistEndurance {
get { return forwardHockeyistEndurance; }
}
public int ForwardHockeyistDexterity {
get { return forwardHockeyistDexterity; }
}
public int ForwardHockeyistAgility {
get { return forwardHockeyistAgility; }
}
public int DefencemanHockeyistStrength {
get { return defencemanHockeyistStrength; }
}
public int DefencemanHockeyistEndurance {
get { return defencemanHockeyistEndurance; }
}
public int DefencemanHockeyistDexterity {
get { return defencemanHockeyistDexterity; }
}
public int DefencemanHockeyistAgility {
get { return defencemanHockeyistAgility; }
}
public int MinRandomHockeyistParameter {
get { return minRandomHockeyistParameter; }
}
public int MaxRandomHockeyistParameter {
get { return maxRandomHockeyistParameter; }
}
public double StruckPuckInitialSpeedFactor {
get { return struckPuckInitialSpeedFactor; }
}
public double PuckBindingRange {
get { return puckBindingRange; }
}
}
}
| |
using System;
using UIKit;
using CoreGraphics;
using CoreAnimation;
using WFS210;
using WFS210.Util;
using System.Collections.Generic;
using Foundation;
using WFS210.Services;
namespace WFS210.UI
{
public partial class ScopeView : UIView
{
public Padding Padding { get; set; }
private int TotalSamples;
public int GrappleDistance { get; set; }
public int ScrollPosition { get; set; }
CGPath[] path;
CGPoint initialPoint;
Oscilloscope wfs210;
CGPoint[] scopePoints;
public float SampleToPointRatio;
public int SelectedChannel{ get; set; }
public bool MarkersAreVisible { get; set; }
public XMarker[] XMarkers = new XMarker[2];
public YMarker[] YMarkers = new YMarker[2];
ZeroLine[] zeroLines = new ZeroLine[2];
TriggerMarker trigMarker;
CALayer gridLayer;
public List<Marker> Markers = new List<Marker> ();
CAShapeLayer[] signals;
CAShapeLayer maskLayer;
public VoltTimeIndicator VoltTimeIndicator;
CalibrationIndicator CalibrationIndicator;
CALayer scroll;
CAShapeLayer scrollBar;
UIPinchGestureRecognizer pinchGesture;
UILongPressGestureRecognizer longPressGesture;
UIPanGestureRecognizer panGesture;
ServiceManager _ServiceManager;
public ServiceManager ServiceManager {
get{ return this._ServiceManager; }
set {
this._ServiceManager = value;
wfs210 = _ServiceManager.ActiveService.Oscilloscope;
SampleToPointRatio = (float)ScopeBounds.Height / (wfs210.DeviceContext.UnitsPerDivision * wfs210.DeviceContext.Divisions);
TotalSamples = wfs210.DeviceContext.SamplesPerTimeBase * 15;
}
}
public event EventHandler<NewDataEventArgs> NewData;
/// <summary>
/// Initializes a new instance of the <see cref="iWFS210.ScopeView"/> class.
/// </summary>
/// <param name="handle">Handle.</param>
public ScopeView (IntPtr handle) : base (handle)
{
this.GrappleDistance = 60;
Padding = new Padding (17, 0, 18, 0);
MarkersAreVisible = true;
LoadGrid ();
RegisterPanGestureRecognizer ();
RegisterLongPressRecognizer ();
LoadVoltTimeIndicator ();
LoadCalibrationIndicator ();
RegisterPinchRecognizer ();
LoadScrollIndicator ();
}
/// <summary>
/// Initialize's scopeview.
/// </summary>
public void Initialize ()
{
LoadZeroLines ();
LoadTriggerMarker ();
LoadXMarkers ();
LoadYMarkers ();
path = new CGPath[wfs210.Channels.Count];
signals = new CAShapeLayer[wfs210.Channels.Count];
LoadSignals ();
signals [0].StrokeColor = new CGColor (0, 255, 0);
signals [1].StrokeColor = new CGColor (255, 255, 0);
FillMarkersList ();
LoadMarkers ();
}
/// <summary>
/// Gets the scope bounds.
/// </summary>
/// <value>The scope bounds.</value>
public CGRect ScopeBounds {
get {
return new CGRect (
this.Bounds.X + Padding.Left,
this.Bounds.Y + Padding.Top,
this.Bounds.Width - Padding.Horizontal,
this.Bounds.Height - Padding.Vertical
);
}
}
/// <summary>
/// Raises the new data event.
/// </summary>
/// <param name="e">E.</param>
protected virtual void OnNewData (NewDataEventArgs e)
{
if (NewData != null)
NewData (this, e);
}
/// <summary>
/// Gets or sets the service.
/// </summary>
/// <value>The service.</value>
Service Service {
get {
return ServiceManager.ActiveService;
}
}
int Latestpoint =0;
/// <summary>
/// Updates the scope view.
/// </summary>
public void Update ()
{
for (int i = 0; i < wfs210.Channels.Count; i++) {
path [i] = new CGPath ();
SampleBuffer buffer = wfs210.Channels [i].Samples;
if (buffer.LatestPoint > TotalSamples)
Latestpoint = TotalSamples;
else
Latestpoint = buffer.LatestPoint;
scopePoints = new CGPoint[Latestpoint];
var offset = ScrollPosition;
if (wfs210.Channels [i].VoltsPerDivision != VoltsPerDivision.VdivNone) {
for (int j = offset; j < offset + scopePoints.Length; j++) {
scopePoints [j - offset] = new CGPoint (MapXPosToScreen (j - offset) + ScopeBounds.Left, MapSampleDataToScreen (buffer [j]));
}
} else {
for (int j = offset; j < offset + scopePoints.Length; j++) {
scopePoints [j - offset] = new CGPoint (MapXPosToScreen (j - offset) + ScopeBounds.Left,0);
}
}
path [i].AddLines (scopePoints);
signals [i].Path = path [i];
}
if (MarkersAreVisible) {
foreach (Marker m in Markers) {
m.Layer.Hidden = false;
}
} else {
foreach (Marker m in Markers) {
m.Layer.Hidden = true;
}
}
CalibrationIndicator.Hidden = !wfs210.Calibrating;
}
/// <summary>
/// Maps the sample data to screen.
/// </summary>
/// <returns>The sample data to screen.</returns>
/// <param name="sample">Sample.</param>
private int MapSampleDataToScreen (int sample)
{
var result = (int)((sample * SampleToPointRatio) + ScopeBounds.Top);
return result;
}
/// <summary>
/// Maps the screen data to scope data.
/// </summary>
/// <returns>The screen data to scope data.</returns>
/// <param name="value">Value.</param>
private int MapScreenDataToScopeData (int value)
{
return (int)((value - ScopeBounds.Top) / SampleToPointRatio);
}
/// <summary>
/// Maps the screen data to scope data inverted.
/// </summary>
/// <returns>The screen data to scope data inverted.</returns>
/// <param name="value">Value.</param>
private int MapScreenDataToScopeDataInverted (int value)
{
return 255 - (int)(value / SampleToPointRatio);
}
/// <summary>
/// Maps the X position to screen.
/// </summary>
/// <returns>The X position to screen.</returns>
/// <param name="pos">Position.</param>
private int MapXPosToScreen (int pos)
{
var totalSamples = TotalSamples;
var ratio = ScopeBounds.Width / totalSamples;
return (int)(pos * ratio);
}
/// <summary>
/// Loads the grid.
/// </summary>
void LoadGrid ()
{
gridLayer = new CALayer ();
gridLayer.Position = new CGPoint ((ScopeBounds.Width / 2) + ScopeBounds.Left, ScopeBounds.Height / 2 + ScopeBounds.Top);
var image = UIImage.FromBundle ("VIEWPORT/VIEWPORT-130x78");
gridLayer.Contents = image.CGImage;
gridLayer.Bounds = new CGRect (0, 0, image.CGImage.Width / image.CurrentScale, image.CGImage.Height / image.CurrentScale);
Layer.AddSublayer (gridLayer);
}
/// <summary>
/// Gets the signal mask.
/// </summary>
/// <returns>The signal mask.</returns>
CAShapeLayer GetSignalMask ()
{
CGRect clippingRect = new CGRect (ScopeBounds.Left, ScopeBounds.Top + 3, ScopeBounds.Width, ScopeBounds.Height - 7);
// Set clippingRect to the rectangle you wish to clip to
var maskPath = UIBezierPath.FromRect (clippingRect);
// Create a shape layer
maskLayer = new CAShapeLayer ();
maskLayer.Position = new CGPoint (ScopeBounds.Width / 2 + ScopeBounds.Left, ScopeBounds.Height / 2 + ScopeBounds.Top);
maskLayer.Bounds = new CGRect (ScopeBounds.X, ScopeBounds.Y, ScopeBounds.Width, ScopeBounds.Height);
//maskLayer.BorderColor = new CGColor (255, 0, 0 , 1f);
// Set the path of the mask layer to be the Bezier path we calculated earlier
maskLayer.Path = maskPath.CGPath;
//maskLayer.BorderWidth = 1f;
//Layer.AddSublayer (maskLayer);
return maskLayer;
}
/// <summary>
/// Loads the signals.
/// </summary>
void LoadSignals ()
{
for (int i = 0; i < wfs210.Channels.Count; i++) {
signals [i] = new CAShapeLayer ();
signals [i].Path = path [i];
signals [i].LineWidth = 1f;
signals [i].StrokeColor = new CGColor (0, 255, 0);
signals [i].FillColor = new CGColor (0, 0, 0, 0);
signals [i].Mask = GetSignalMask ();
Layer.AddSublayer (signals [i]);
}
}
/// <summary>
/// Loads the markers.
/// </summary>
void LoadMarkers ()
{
if (MarkersAreVisible) {
foreach (Marker marker in Markers) {
var rect = GetMarkerRect (marker);
marker.Position = new CGPoint (rect.X, rect.Y);
Layer.AddSublayer (marker.Layer);
}
}
}
/// <summary>
/// Gets the marker rectangle.
/// </summary>
/// <returns>The marker rectangle.</returns>
/// <param name="marker">Marker.</param>
CGRect GetMarkerRect (Marker marker)
{
if (marker.Layout == MarkerLayout.Vertical) {
return new CGRect (marker.Value,
ScopeBounds.Height / 2 + marker.Inlay,
marker.Image.CGImage.Width,
ScopeBounds.Height + marker.Inlay);
} else {
return new CGRect (ScopeBounds.Width / 2 - marker.Inlay,
marker.Value,
ScopeBounds.Width + marker.Inlay,
marker.Image.CGImage.Height);
}
}
/// <summary>
/// Loads the X markers.
/// </summary>
public void LoadXMarkers ()
{
//Makeing XMarkers and adding it to the layers
XMarkers [0] = new XMarker ("MARKERS/MARKER 1 SLIDER-__x60", Convert.ToInt32 (ScopeBounds.Width / 4), "XMARKER1", 9);
XMarkers [1] = new XMarker ("MARKERS/MARKER 2 SLIDER-__x60", Convert.ToInt32 (ScopeBounds.Width / 4) * 3, "XMARKER2", 9);
}
/// <summary>
/// Loads the Y markers.
/// </summary>
public void LoadYMarkers ()
{
//Makeing YMarkers and adding it to the layers
YMarkers [0] = new YMarker ("MARKERS/MARKER A SLIDER-112x__", Convert.ToInt32 (ScopeBounds.Height / 4), "YMARKER1", -9);
YMarkers [1] = new YMarker ("MARKERS/MARKER B SLIDER-112x__", Convert.ToInt32 (ScopeBounds.Height / 4) * 3, "YMARKER2", -9);
}
/// <summary>
/// Loads the zero lines.
/// </summary>
public void LoadZeroLines ()
{
//Makeing ZeroLines and adding it to the layers
zeroLines [0] = new ZeroLine ("ZEROLINE/ZERO-CHAN1-131x__", MapSampleDataToScreen (wfs210.Channels [0].YPosition), "ZEROLINE1", -17);
zeroLines [1] = new ZeroLine ("ZEROLINE/ZERO-CHAN2-131x__", MapSampleDataToScreen (wfs210.Channels [0].YPosition), "ZEROLINE2", -17);
}
/// <summary>
/// Loads the trigger marker.
/// </summary>
public void LoadTriggerMarker ()
{
//Makeing TriggerMarkers and adding it to the layers
trigMarker = new TriggerMarker ("TRIGGER LEVEL/TRIG SLIDER-SLOPE UP-112x__", MapSampleDataToScreen (wfs210.Trigger.Level), "TRIGGERMARKER", -9);
}
/// <summary>
/// Loads the volt time indicator.
/// </summary>
public void LoadVoltTimeIndicator ()
{
VoltTimeIndicator = new VoltTimeIndicator ();
VoltTimeIndicator.Hidden = true;
VoltTimeIndicator.Layer.ZPosition = 100;
Layer.AddSublayer (VoltTimeIndicator.Layer);
}
/// <summary>
/// Loads the calibration indicator.
/// </summary>
public void LoadCalibrationIndicator ()
{
CalibrationIndicator = new CalibrationIndicator ();
CalibrationIndicator.Hidden = true;
CalibrationIndicator.Layer.ZPosition = 100;
Layer.AddSublayer (CalibrationIndicator.Layer);
}
/// <summary>
/// Loads the scroll indicator.
/// </summary>
void LoadScrollIndicator ()
{
scroll = new CALayer ();
var image = UIImage.FromBundle ("VIEWPORT/SCROLL BAR-130x688");
scroll.Bounds = new CGRect (0, 0, image.CGImage.Width / image.CurrentScale, image.CGImage.Height / image.CurrentScale);
scroll.Position = new CGPoint (ScopeBounds.Width / 2 + ScopeBounds.Left, ScopeBounds.Height + ScopeBounds.Top);
scroll.Contents = image.CGImage;
Layer.AddSublayer (scroll);
scrollBar = new CAShapeLayer ();
var path = new CGPath ();
var data = new CGPoint[2];
data [0].X = 0 + ScopeBounds.Left + 2;
data [1].X = 100;
data [0].Y = ScopeBounds.Height + ScopeBounds.Top;
data [1].Y = ScopeBounds.Height + ScopeBounds.Top;
path.AddLines (data);
scrollBar.LineWidth = 2f;
scrollBar.StrokeColor = new CGColor (72f / 255f, 72f / 255f, 72f / 255f);
scrollBar.FillColor = new CGColor (0, 0, 0, 0);
scrollBar.Path = path;
Layer.AddSublayer (scrollBar);
}
/// <summary>
/// Updates the scroll indicator.
/// </summary>
void UpdateScrollIndicator ()
{
var path = new CGPath ();
var data = new CGPoint[2];
float ratio = (float)(ScrollPosition / (4096f - (TotalSamples / 2)));
float scrollRatio = (float)(TotalSamples * ratio);
data [0].X = (MapXPosToScreen ((int)scrollRatio)) + ScopeBounds.Left + 2;
data [1].X = data [0].X + 87;
data [0].Y = ScopeBounds.Height + ScopeBounds.Top;
data [1].Y = ScopeBounds.Height + ScopeBounds.Top;
path.AddLines (data);
scrollBar.Path = path;
}
/// <summary>
/// Fills the markerslist.
/// </summary>
public void FillMarkersList ()
{
Markers.Add (XMarkers [0]);
Markers.Add (XMarkers [1]);
Markers.Add (YMarkers [0]);
Markers.Add (YMarkers [1]);
Markers.Add (trigMarker);
Markers.Add (zeroLines [0]);
Markers.Add (zeroLines [1]);
}
/// <summary>
/// Registers the pinch recognizer.
/// </summary>
private void RegisterPinchRecognizer ()
{
float startDistance;
startDistance = 0.0f;
pinchGesture = new UIPinchGestureRecognizer ((pg) => {
if (pg.State == UIGestureRecognizerState.Began) {
if (pg.NumberOfTouches == 2) {
CGPoint firstPoint = pg.LocationOfTouch (0, this);
CGPoint secondPoint = pg.LocationOfTouch (1, this);
startDistance = CalculateDistance (firstPoint, secondPoint);
}
VoltTimeIndicator.Hidden = false;
} else if (pg.State == UIGestureRecognizerState.Changed) {
float distance;
if (pg.NumberOfTouches == 2) {
CGPoint firstPoint = pg.LocationOfTouch (0, this);
CGPoint secondPoint = pg.LocationOfTouch (1, this);
distance = CalculateDistance (firstPoint, secondPoint);
if (PointsAreHorizontal (firstPoint, secondPoint)) {
if (distance > startDistance + 50) {
startDistance = distance;
wfs210.TimeBase = wfs210.TimeBase.Cycle (-1);
} else if (distance < startDistance - 50) {
startDistance = distance;
wfs210.TimeBase = wfs210.TimeBase.Cycle (1);
}
VoltTimeIndicator.Text = TimeBaseConverter.ToString (wfs210.TimeBase);
} else {
if (distance > startDistance + 50) {
startDistance = distance;
Service.Execute (new NextVoltsPerDivisionCommand (SelectedChannel));
} else if (distance < startDistance - 50) {
startDistance = distance;
Service.Execute (new PreviousVoltsPerDivisionCommand (SelectedChannel));
}
VoltTimeIndicator.Text = VoltsPerDivisionConverter.ToString (wfs210.Channels [SelectedChannel].VoltsPerDivision, wfs210.Channels [SelectedChannel].AttenuationFactor);
}
}
} else if (pg.State == UIGestureRecognizerState.Ended) {
VoltTimeIndicator.Hidden = true;
ApplyMarkerValuesToScope ();
OnNewData (null);
Update ();
}
});
this.AddGestureRecognizer (pinchGesture);
}
/// <summary>
/// Applies the marker values to scope object.
/// </summary>
private void ApplyMarkerValuesToScope ()
{
Service.Execute (new YPositionCommand (0, MapScreenDataToScopeData (zeroLines [0].Value)));
Service.Execute (new YPositionCommand (1, MapScreenDataToScopeData (zeroLines [1].Value)));
var triggerLevel = MapScreenDataToScopeData (trigMarker.Value);
Service.Execute (new TriggerLevelCommand (triggerLevel));
}
/// <summary>
/// Registers the pan gesture recognizer.
/// </summary>
void RegisterPanGestureRecognizer ()
{
float previousX = 0;
panGesture = new UIPanGestureRecognizer (() => {
switch (panGesture.State) {
case UIGestureRecognizerState.Began:
previousX = (float)panGesture.LocationOfTouch (0, this).X;
break;
case UIGestureRecognizerState.Changed:
var touch = panGesture.LocationOfTouch (0, this);
var copy = ScrollPosition;
var delta = touch.X - previousX;
copy -= (int)delta;
copy = (int)Math.Min (Math.Max (copy, 0), 4096 - TotalSamples);
previousX = (float)touch.X;
ScrollPosition = copy;
UpdateScrollIndicator ();
Update ();
break;
case UIGestureRecognizerState.Ended:
break;
}
});
panGesture.MaximumNumberOfTouches = 2;
panGesture.MinimumNumberOfTouches = 2;
this.AddGestureRecognizer (panGesture);
}
/// <summary>
/// Checks if the Points making a horizontal line.
/// </summary>
/// <returns><c>true</c>, if horizontal, <c>false</c> otherwise.</returns>
/// <param name="firstPoint">First point.</param>
/// <param name="secondPoint">Second point.</param>
private static bool PointsAreHorizontal (CGPoint firstPoint, CGPoint secondPoint)
{
bool horizontal;
double angle = Math.Atan2 (secondPoint.Y - firstPoint.Y, secondPoint.X - firstPoint.X);
double sin = Math.Abs (Math.Sin (angle));
if (sin < Math.Sin (Math.PI / 4))
horizontal = true;
else
horizontal = false;
return horizontal;
}
/// <summary>
/// Calculates the distance between 2 points.
/// </summary>
/// <returns>The distance.</returns>
/// <param name="firstPoint">First point.</param>
/// <param name="secondPoint">Second point.</param>
private float CalculateDistance (CGPoint firstPoint, CGPoint secondPoint)
{
float distance = (float)Math.Sqrt ((firstPoint.X - secondPoint.X) * (firstPoint.X - secondPoint.X) +
(firstPoint.Y - secondPoint.Y) * (firstPoint.Y - secondPoint.Y));
return distance;
}
/// <summary>
/// Registers the long press recognizer.
/// </summary>
private void RegisterLongPressRecognizer ()
{
Marker closestMarker;
closestMarker = null;
longPressGesture = new UILongPressGestureRecognizer ((lp) => {
if (lp.State == UIGestureRecognizerState.Began) {
initialPoint = lp.LocationInView (this);
closestMarker = GetMarkerAt (initialPoint);
} else if (lp.State == UIGestureRecognizerState.Changed) {
if (closestMarker != null) {
if (closestMarker is XMarker) {
var position = closestMarker.Value;
var touchPos = lp.LocationInView (this).X;
if (touchPos > ScopeBounds.Left) {
if (touchPos < this.Bounds.Width)
position = (int)lp.LocationInView (this).X;
}
closestMarker.Value = position;
} else {
var position = closestMarker.Value;
var touchPos = lp.LocationInView (this).Y;
if (touchPos > ScopeBounds.Top) {
if (touchPos < this.Bounds.Height)
position = (int)lp.LocationInView (this).Y;
}
closestMarker.Value = position;
}
}
} else if (lp.State == UIGestureRecognizerState.Ended) {
closestMarker = null;
ApplyMarkerValuesToScope ();
OnNewData (null);
}
});
longPressGesture.MinimumPressDuration = 0.1d;
longPressGesture.AllowableMovement = 100f;
this.AddGestureRecognizer (longPressGesture);
}
/// <summary>
/// Returns the distance from the point to the marker. This value can
/// be used to check if the marker has been hit.
/// </summary>
/// <returns>The distance from the point to the marker.</returns>
/// <param name="pt">Point.</param>
/// <param name="marker">Marker.</param>
public int HitTest (CGPoint pt, Marker marker)
{
int distance;
// Note: If the line is vertical, then we need to return the horizontal distance, and vice versa.
if (marker.Layout == MarkerLayout.Horizontal) {
distance = (int)Math.Abs (marker.Value - pt.Y); // vertical distance
} else {
distance = (int)Math.Abs (marker.Value - pt.X); // horizontal distance
}
return distance;
}
/// <summary>
/// Gets the marker at the specified touch position that is
/// within grapple distance.
/// </summary>
/// <returns>The closest <see cref="WFS210.UI.Marker"/>, null if no marker is within
/// grapple distance.</returns>
/// <param name="pt">Touch position.</param>
public Marker GetMarkerAt (CGPoint pt)
{
Marker closestMarker = null;
float distance, lastDistance = GrappleDistance;
// Here we will loop over all markers in an attempt
// to find the marker closest to the touch position.
for (int i = 0; i < Markers.Count; i++) {
// First, we calculate the distance between the marker
// line and the touch position. If this distance is within
// grapple distance, then we have a hit.
distance = HitTest (pt, Markers [i]);
if (distance < GrappleDistance) {
// Check if this new hit is closer than the previous
// hit. If it is, the current marker will be the
// new closest marker.
if ((i == 0) || (distance < lastDistance)) {
closestMarker = Markers [i];
lastDistance = distance; // save
}
}
}
return closestMarker;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Server;
namespace Server.Commands.Generic
{
[Flags]
public enum CommandSupport
{
Single = 0x0001,
Global = 0x0002,
Online = 0x0004,
Multi = 0x0008,
Area = 0x0010,
Self = 0x0020,
Region = 0x0040,
Contained = 0x0080,
IPAddress = 0x0100,
All = Single | Global | Online | Multi | Area | Self | Region | Contained | IPAddress,
AllMobiles = All & ~Contained,
AllNPCs = All & ~(IPAddress | Online | Self | Contained),
AllItems = All & ~(IPAddress | Online | Self | Region),
Simple = Single | Multi,
Complex = Global | Online | Area | Region | Contained | IPAddress
}
public abstract class BaseCommandImplementor
{
public static void RegisterImplementors()
{
Register(new RegionCommandImplementor());
Register(new GlobalCommandImplementor());
Register(new OnlineCommandImplementor());
Register(new SingleCommandImplementor());
Register(new SerialCommandImplementor());
Register(new MultiCommandImplementor());
Register(new AreaCommandImplementor());
Register(new SelfCommandImplementor());
Register(new ContainedCommandImplementor());
Register(new IPAddressCommandImplementor());
Register(new RangeCommandImplementor());
Register(new ScreenCommandImplementor());
Register(new FacetCommandImplementor());
}
private string[] m_Accessors;
private AccessLevel m_AccessLevel;
private CommandSupport m_SupportRequirement;
private Dictionary<string, BaseCommand> m_Commands;
private string m_Usage;
private string m_Description;
private bool m_SupportsConditionals;
public bool SupportsConditionals
{
get { return m_SupportsConditionals; }
set { m_SupportsConditionals = value; }
}
public string[] Accessors
{
get { return m_Accessors; }
set { m_Accessors = value; }
}
public string Usage
{
get { return m_Usage; }
set { m_Usage = value; }
}
public string Description
{
get { return m_Description; }
set { m_Description = value; }
}
public AccessLevel AccessLevel
{
get { return m_AccessLevel; }
set { m_AccessLevel = value; }
}
public CommandSupport SupportRequirement
{
get { return m_SupportRequirement; }
set { m_SupportRequirement = value; }
}
public Dictionary<string, BaseCommand> Commands
{
get { return m_Commands; }
}
public BaseCommandImplementor()
{
m_Commands = new Dictionary<string, BaseCommand>(StringComparer.OrdinalIgnoreCase);
}
public virtual void Compile(Mobile from, BaseCommand command, ref string[] args, ref object obj)
{
obj = null;
}
public virtual void Register(BaseCommand command)
{
for (int i = 0; i < command.Commands.Length; ++i)
m_Commands[command.Commands[i]] = command;
}
public bool CheckObjectTypes(Mobile from, BaseCommand command, Extensions ext, out bool items, out bool mobiles)
{
items = mobiles = false;
ObjectConditional cond = ObjectConditional.Empty;
foreach (BaseExtension check in ext)
{
if (check is WhereExtension)
{
cond = (check as WhereExtension).Conditional;
break;
}
}
bool condIsItem = cond.IsItem;
bool condIsMobile = cond.IsMobile;
switch (command.ObjectTypes)
{
case ObjectTypes.All:
case ObjectTypes.Both:
{
if (condIsItem)
items = true;
if (condIsMobile)
mobiles = true;
break;
}
case ObjectTypes.Items:
{
if (condIsItem)
{
items = true;
}
else if (condIsMobile)
{
from.SendMessage("You may not use a mobile type condition for this command.");
return false;
}
break;
}
case ObjectTypes.Mobiles:
{
if (condIsMobile)
{
mobiles = true;
}
else if (condIsItem)
{
from.SendMessage("You may not use an item type condition for this command.");
return false;
}
break;
}
}
return true;
}
public void RunCommand(Mobile from, BaseCommand command, string[] args)
{
try
{
object obj = null;
Compile(from, command, ref args, ref obj);
RunCommand(from, obj, command, args);
}
catch (Exception ex)
{
from.SendMessage(ex.Message);
}
}
public string GenerateArgString(string[] args)
{
if (args.Length == 0)
return "";
// NOTE: this does not preserve the case where quotation marks are used on a single word
StringBuilder sb = new StringBuilder();
for (int i = 0; i < args.Length; ++i)
{
if (i > 0)
sb.Append(' ');
if (args[i].IndexOf(' ') >= 0)
{
sb.Append('"');
sb.Append(args[i]);
sb.Append('"');
}
else
{
sb.Append(args[i]);
}
}
return sb.ToString();
}
public void RunCommand(Mobile from, object obj, BaseCommand command, string[] args)
{
// try
// {
CommandEventArgs e = new CommandEventArgs(from, command.Commands[0], GenerateArgString(args), args);
if (!command.ValidateArgs(this, e))
return;
bool flushToLog = false;
if (obj is ArrayList)
{
ArrayList list = (ArrayList)obj;
if (list.Count > 20)
CommandLogging.Enabled = false;
else if (list.Count == 0)
command.LogFailure("Nothing was found to use this command on.");
command.ExecuteList(e, list);
if (list.Count > 20)
{
flushToLog = true;
CommandLogging.Enabled = true;
}
}
else if (obj != null)
{
if (command.ListOptimized)
{
ArrayList list = new ArrayList();
list.Add(obj);
command.ExecuteList(e, list);
}
else
{
command.Execute(e, obj);
}
}
command.Flush(from, flushToLog);
// }
// catch ( Exception ex )
// {
// from.SendMessage( ex.Message );
// }
}
public virtual void Process(Mobile from, BaseCommand command, string[] args)
{
RunCommand(from, command, args);
}
public virtual void Execute(CommandEventArgs e)
{
if (e.Length >= 1)
{
BaseCommand command = null;
m_Commands.TryGetValue(e.GetString(0), out command);
if (command == null)
{
e.Mobile.SendMessage("That is either an invalid command name or one that does not support this modifier.");
}
else if (e.Mobile.AccessLevel < command.AccessLevel)
{
e.Mobile.SendMessage("You do not have access to that command.");
}
else
{
string[] oldArgs = e.Arguments;
string[] args = new string[oldArgs.Length - 1];
for (int i = 0; i < args.Length; ++i)
args[i] = oldArgs[i + 1];
Process(e.Mobile, command, args);
}
}
else
{
e.Mobile.SendMessage("You must supply a command name.");
}
}
public void Register()
{
if (m_Accessors == null)
return;
for (int i = 0; i < m_Accessors.Length; ++i)
CommandSystem.Register(m_Accessors[i], m_AccessLevel, new CommandEventHandler(Execute));
}
public static void Register(BaseCommandImplementor impl)
{
m_Implementors.Add(impl);
impl.Register();
}
private static List<BaseCommandImplementor> m_Implementors;
public static List<BaseCommandImplementor> Implementors
{
get
{
if (m_Implementors == null)
{
m_Implementors = new List<BaseCommandImplementor>();
RegisterImplementors();
}
return m_Implementors;
}
}
}
}
| |
//
// 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 AutoMapper;
using Microsoft.Azure.Commands.Compute.Automation.Models;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Automation
{
public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet
{
protected object CreateContainerServiceGetDynamicParameters()
{
dynamicParameters = new RuntimeDefinedParameterDictionary();
var pResourceGroupName = new RuntimeDefinedParameter();
pResourceGroupName.Name = "ResourceGroupName";
pResourceGroupName.ParameterType = typeof(string);
pResourceGroupName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 1,
Mandatory = true
});
pResourceGroupName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ResourceGroupName", pResourceGroupName);
var pContainerServiceName = new RuntimeDefinedParameter();
pContainerServiceName.Name = "Name";
pContainerServiceName.ParameterType = typeof(string);
pContainerServiceName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 2,
Mandatory = true
});
pContainerServiceName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("Name", pContainerServiceName);
var pArgumentList = new RuntimeDefinedParameter();
pArgumentList.Name = "ArgumentList";
pArgumentList.ParameterType = typeof(object[]);
pArgumentList.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByStaticParameters",
Position = 3,
Mandatory = true
});
pArgumentList.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ArgumentList", pArgumentList);
return dynamicParameters;
}
protected void ExecuteContainerServiceGetMethod(object[] invokeMethodInputParameters)
{
string resourceGroupName = (string)ParseParameter(invokeMethodInputParameters[0]);
string containerServiceName = (string)ParseParameter(invokeMethodInputParameters[1]);
if (!string.IsNullOrEmpty(resourceGroupName) && !string.IsNullOrEmpty(containerServiceName))
{
var result = ContainerServicesClient.Get(resourceGroupName, containerServiceName);
WriteObject(result);
}
else if (!string.IsNullOrEmpty(resourceGroupName))
{
var result = ContainerServicesClient.ListByResourceGroup(resourceGroupName);
var resultList = result.ToList();
var nextPageLink = result.NextPageLink;
while (!string.IsNullOrEmpty(nextPageLink))
{
var pageResult = ContainerServicesClient.ListByResourceGroupNext(nextPageLink);
foreach (var pageItem in pageResult)
{
resultList.Add(pageItem);
}
nextPageLink = pageResult.NextPageLink;
}
WriteObject(resultList, true);
}
else
{
var result = ContainerServicesClient.List();
var resultList = result.ToList();
var nextPageLink = result.NextPageLink;
while (!string.IsNullOrEmpty(nextPageLink))
{
var pageResult = ContainerServicesClient.ListNext(nextPageLink);
foreach (var pageItem in pageResult)
{
resultList.Add(pageItem);
}
nextPageLink = pageResult.NextPageLink;
}
WriteObject(resultList, true);
}
}
}
public partial class NewAzureComputeArgumentListCmdlet : ComputeAutomationBaseCmdlet
{
protected PSArgument[] CreateContainerServiceGetParameters()
{
string resourceGroupName = string.Empty;
string containerServiceName = string.Empty;
return ConvertFromObjectsToArguments(
new string[] { "ResourceGroupName", "ContainerServiceName" },
new object[] { resourceGroupName, containerServiceName });
}
}
[Cmdlet(VerbsCommon.Get, "AzureRmContainerService", DefaultParameterSetName = "DefaultParameter")]
[OutputType(typeof(PSContainerService))]
public partial class GetAzureRmContainerService : ComputeAutomationBaseCmdlet
{
protected override void ProcessRecord()
{
AutoMapper.Mapper.AddProfile<ComputeAutomationAutoMapperProfile>();
ExecuteClientAction(() =>
{
string resourceGroupName = this.ResourceGroupName;
string containerServiceName = this.Name;
if (!string.IsNullOrEmpty(resourceGroupName) && !string.IsNullOrEmpty(containerServiceName))
{
var result = ContainerServicesClient.Get(resourceGroupName, containerServiceName);
var psObject = new PSContainerService();
Mapper.Map<ContainerService, PSContainerService>(result, psObject);
WriteObject(psObject);
}
else if (!string.IsNullOrEmpty(resourceGroupName))
{
var result = ContainerServicesClient.ListByResourceGroup(resourceGroupName);
var resultList = result.ToList();
var nextPageLink = result.NextPageLink;
while (!string.IsNullOrEmpty(nextPageLink))
{
var pageResult = ContainerServicesClient.ListByResourceGroupNext(nextPageLink);
foreach (var pageItem in pageResult)
{
resultList.Add(pageItem);
}
nextPageLink = pageResult.NextPageLink;
}
var psObject = new List<PSContainerServiceList>();
foreach (var r in resultList)
{
psObject.Add(Mapper.Map<ContainerService, PSContainerServiceList>(r));
}
WriteObject(psObject, true);
}
else
{
var result = ContainerServicesClient.List();
var resultList = result.ToList();
var nextPageLink = result.NextPageLink;
while (!string.IsNullOrEmpty(nextPageLink))
{
var pageResult = ContainerServicesClient.ListNext(nextPageLink);
foreach (var pageItem in pageResult)
{
resultList.Add(pageItem);
}
nextPageLink = pageResult.NextPageLink;
}
var psObject = new List<PSContainerServiceList>();
foreach (var r in resultList)
{
psObject.Add(Mapper.Map<ContainerService, PSContainerServiceList>(r));
}
WriteObject(psObject, true);
}
});
}
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 1,
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = false)]
[AllowNull]
public string ResourceGroupName { get; set; }
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 2,
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = false)]
[AllowNull]
public string Name { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Vulkan
{
internal static class ExternalFunction
{
internal static T getInstanceFunction<T>(VK.Instance instance, string name)
{
IntPtr funcPtr = VK.GetInstanceProcAddr(instance, name);
if(funcPtr == IntPtr.Zero)
{
throw new Exception(String.Format("Instance function {0} not found, extension may not be present", name));
}
return Marshal.GetDelegateForFunctionPointer<T>(funcPtr);
}
internal static T getDeviceFunction<T>(VK.Device device, string name)
{
IntPtr funcPtr = VK.GetDeviceProcAddr(device, name);
if(funcPtr == IntPtr.Zero)
{
throw new Exception(String.Format("Device function {0} not found, extension may not be present", name));
}
return Marshal.GetDelegateForFunctionPointer<T>(funcPtr);
}
}
internal static class Alloc
{
internal static IntPtr alloc<T>(T data)
{
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(data.GetType()));
Marshal.StructureToPtr(data, ptr, false);
return ptr;
}
internal unsafe static IntPtr* alloc(List<string> data)
{
IntPtr* ptr = (IntPtr*)Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)) * data.Count);
for(int i = 0; i < data.Count; i++)
{
ptr[i] = Marshal.StringToHGlobalAnsi(data[i]);
}
return ptr;
}
internal static IntPtr alloc<T>(List<T> data) where T : struct
{
if(data == null)
{
return IntPtr.Zero;
}
bool isEnum = typeof(T).IsEnum;
Type outputType = isEnum ? Enum.GetUnderlyingType(typeof(T)) : typeof(T);
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(outputType) * data.Count);
Int64 addr = ptr.ToInt64();
for(int i = 0; i < data.Count; i++)
{
IntPtr anItem = new IntPtr(addr);
if(isEnum)
{
int val = Convert.ToInt32(data[i]);
Marshal.StructureToPtr(val, anItem, false);
}
else
{
Marshal.StructureToPtr(data[i], anItem, false);
}
addr += Marshal.SizeOf(outputType);
}
return ptr;
}
internal static IntPtr alloc<T>(T[] data) where T : struct
{
if(data == null)
{
return IntPtr.Zero;
}
bool isEnum = typeof(T).IsEnum;
Type outputType = isEnum ? Enum.GetUnderlyingType(typeof(T)) : typeof(T);
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(outputType) * data.Length);
Int64 addr = ptr.ToInt64();
for(int i = 0; i < data.Length; i++)
{
IntPtr anItem = new IntPtr(addr);
if(isEnum)
{
int val = Convert.ToInt32(data[i]);
Marshal.StructureToPtr(val, anItem, false);
}
else
{
Marshal.StructureToPtr(data[i], anItem, false);
}
addr += Marshal.SizeOf(outputType);
}
return ptr;
}
internal static void free(IntPtr data)
{
if(data != IntPtr.Zero)
{
Marshal.FreeHGlobal(data);
}
}
internal unsafe static void free(IntPtr* data, int count)
{
for(int i = 0; i < count; i++)
{
Marshal.FreeHGlobal(data[i]);
}
Marshal.FreeHGlobal(new IntPtr(data));
}
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct _InstanceCreateInfo
{
public VK.StructureType sType;
public IntPtr next;
public UInt32 flags;
public IntPtr applicationInfo;
public UInt32 enabledLayerCount;
public IntPtr* enabledLayerNames;
public UInt32 enabledExtensionCount;
public IntPtr* enabledExtensionNames;
public _InstanceCreateInfo(VK.InstanceCreateInfo info)
{
sType = info.type;
next = info.next;
flags = info.flags;
applicationInfo = Alloc.alloc(info.applicationInfo);
enabledLayerCount = (UInt32)info.enabledLayerNames.Count;
enabledExtensionCount = (UInt32)info.enabledExtensionNames.Count;
enabledLayerNames = Alloc.alloc(info.enabledLayerNames);
enabledExtensionNames = Alloc.alloc(info.enabledExtensionNames);
}
public void destroy()
{
Alloc.free(applicationInfo);
Alloc.free(enabledLayerNames, (int)enabledLayerCount);
Alloc.free(enabledExtensionNames, (int)enabledExtensionCount);
}
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct _DeviceCreateInfo
{
public VK.StructureType SType;
public IntPtr Next;
public UInt32 Flags;
public UInt32 QueueCreateInfoCount;
public IntPtr* QueueCreateInfos;
public UInt32 enabledLayerCount;
public IntPtr* enabledLayerNames;
public UInt32 enabledExtensionCount;
public IntPtr* enabledExtensionNames;
public IntPtr EnabledFeatures;
public _DeviceCreateInfo(VK.DeviceCreateInfo info)
{
SType = info.type;
Next = info.next;
Flags = info.flags;
QueueCreateInfoCount = (UInt32)info.queueCreateInfos.Count;
List<_DeviceQueueCreateInfo> qArray = new List<_DeviceQueueCreateInfo>();
for(int i = 0; i < info.queueCreateInfos.Count; i++)
{
qArray.Add(new _DeviceQueueCreateInfo(info.queueCreateInfos[i]));
}
QueueCreateInfos = (IntPtr*)Alloc.alloc(qArray);
enabledLayerCount = (UInt32)info.enabledLayerNames.Count;
enabledExtensionCount = (UInt32)info.enabledExtensionNames.Count;
enabledLayerNames = Alloc.alloc(info.enabledLayerNames);
enabledExtensionNames = Alloc.alloc(info.enabledExtensionNames);
EnabledFeatures = Alloc.alloc(info.enabledFeatures);
}
public void destroy()
{
Alloc.free(enabledLayerNames, (int)enabledLayerCount);
Alloc.free(enabledExtensionNames, (int)enabledExtensionCount);
Alloc.free(new IntPtr(QueueCreateInfos)); //since this is allocated as a large blob and should be freed as one
Alloc.free(EnabledFeatures);
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct _DeviceQueueCreateInfo
{
public VK.StructureType SType;
public IntPtr Next;
public UInt32 Flags;
public UInt32 QueueFamilyIndex;
public UInt32 QueueCount;
public IntPtr QueuePriorities;
public _DeviceQueueCreateInfo(VK.DeviceQueueCreateInfo info)
{
SType = info.type;
Next = info.next;
Flags = info.flags;
QueueFamilyIndex = info.queueFamilyIndex;
QueueCount = info.queueCount;
QueuePriorities = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(float)) * info.queuePriorities.Length);
Marshal.Copy(info.queuePriorities, 0, QueuePriorities, info.queuePriorities.Length);
}
public void destroy()
{
Alloc.free(QueuePriorities);
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct _BindSparseInfo
{
VK.StructureType sType;
IntPtr pNext;
UInt32 waitSemaphoreCount;
IntPtr pWaitSemaphores;
UInt32 bufferBindCount;
IntPtr pBufferBinds;
UInt32 imageOpaqueBindCount;
IntPtr pImageOpaqueBinds;
UInt32 imageBindCount;
IntPtr pImageBinds;
UInt32 signalSemaphoreCount;
IntPtr pSignalSemaphores;
public _BindSparseInfo(VK.BindSparseInfo info)
{
sType = info.type;
pNext = info.pNext;
waitSemaphoreCount = (UInt32)info.pWaitSemaphores.Count;
bufferBindCount = (UInt32)info.pBufferBinds.Count;
imageOpaqueBindCount = (UInt32)info.pImageOpaqueBinds.Count;
imageBindCount = (UInt32)info.pImageBinds.Count;
signalSemaphoreCount = (UInt32)info.pSignalSemaphores.Count;
pWaitSemaphores = Alloc.alloc(info.pWaitSemaphores);
pBufferBinds = Alloc.alloc(info.pBufferBinds);
pImageOpaqueBinds = Alloc.alloc(info.pImageOpaqueBinds);
pImageBinds = Alloc.alloc(info.pImageBinds);
pSignalSemaphores = Alloc.alloc(info.pSignalSemaphores);
}
public void destroy()
{
Alloc.free(pWaitSemaphores);
Alloc.free(pBufferBinds);
Alloc.free(pImageOpaqueBinds);
Alloc.free(pImageBinds);
Alloc.free(pSignalSemaphores);
}
}
[StructLayout(LayoutKind.Sequential)]
public struct _SparseBufferMemoryBindInfo
{
public VK.Buffer buffer;
public UInt32 bindCount;
public IntPtr binds;
public _SparseBufferMemoryBindInfo(VK.SparseBufferMemoryBindInfo info)
{
buffer = info.buffer;
bindCount = (UInt32)info.binds.Count;
binds = Alloc.alloc(info.binds);
}
public void destory()
{
Alloc.free(binds);
}
};
[StructLayout(LayoutKind.Sequential)]
public struct _SparseImageOpaqueMemoryBindInfo
{
public VK.Image image;
public UInt32 bindCount;
public IntPtr binds;
public _SparseImageOpaqueMemoryBindInfo(VK.SparseImageOpaqueMemoryBindInfo info)
{
image = info.image;
bindCount = (UInt32)info.binds.Count;
binds = Alloc.alloc(info.binds);
}
public void destory()
{
Alloc.free(binds);
}
};
[StructLayout(LayoutKind.Sequential)]
public struct _SparseImageMemoryBindInfo
{
public VK.Image image;
public UInt32 bindCount;
public IntPtr binds;
public _SparseImageMemoryBindInfo(VK.SparseImageMemoryBindInfo info)
{
image = info.image;
bindCount = (UInt32)info.binds.Count;
binds = Alloc.alloc(info.binds);
}
public void destory()
{
Alloc.free(binds);
}
};
[StructLayout(LayoutKind.Sequential)]
public struct _BufferCreateInfo
{
public VK.StructureType type;
public IntPtr next;
public VK.BufferCreateFlags flags; //Buffer creation flags
public DeviceSize size; //Specified in bytes
public VK.BufferUsageFlags usage; //Buffer usage flags
public VK.SharingMode sharingMode;
public UInt32 queueFamilyIndexCount;
public IntPtr queueFamilyIndices;
public _BufferCreateInfo(VK.BufferCreateInfo info)
{
type = info.type;
next = info.next;
flags = info.flags;
size = info.size;
usage = info.usage;
sharingMode = info.sharingMode;
queueFamilyIndexCount = (UInt32)(info.queueFamilyIndices?.Count ?? 0);
queueFamilyIndices = Alloc.alloc(info.queueFamilyIndices);
}
public void destroy()
{
Alloc.free(queueFamilyIndices);
}
};
[StructLayout(LayoutKind.Sequential)]
public struct _ImageCreateInfo
{
public VK.StructureType type;
public IntPtr next;
public VK.ImageCreateFlags flags; //Image creation flags
public VK.ImageType imageType;
public VK.Format format;
public VK.Extent3D extent;
public UInt32 mipLevels;
public UInt32 arrayLayers;
public VK.SampleCountFlags samples;
public VK.ImageTiling tiling;
public VK.ImageUsageFlags usage; //Image usage flags
public VK.SharingMode sharingMode; //Cross-queue-family sharing mode
public UInt32 queueFamilyIndexCount; //Number of queue families to share across
public IntPtr queueFamilyIndices; //Array of queue family indices to share across
public VK.ImageLayout initialLayout; //Initial image layout for all subresources
public _ImageCreateInfo(VK.ImageCreateInfo info)
{
type = info.type;
next = info.next;
flags = info.flags;
imageType = info.imageType;
format = info.format;
extent = info.extent;
mipLevels = info.mipLevels;
arrayLayers = info.arrayLayers;
samples = info.samples;
tiling = info.tiling;
usage = info.usage;
sharingMode = info.sharingMode;
queueFamilyIndexCount = (UInt32)info.queueFamilyIndices.Count;
queueFamilyIndices = Alloc.alloc(info.queueFamilyIndices);
initialLayout = info.initialLayout;
}
public void destroy()
{
Alloc.free(queueFamilyIndices);
}
};
[StructLayout(LayoutKind.Sequential)]
internal struct _SubmitInfo
{
public VK.StructureType SType;
public IntPtr Next;
public UInt32 WaitSemaphoreCount;
public IntPtr WaitSemaphores;
public IntPtr WaitDstStageMask;
public UInt32 CommandBufferCount;
public IntPtr CommandBuffers;
public UInt32 SignalSemaphoreCount;
public IntPtr SignalSemaphores;
public _SubmitInfo(VK.SubmitInfo info)
{
SType = info.type;
Next = info.next;
WaitSemaphoreCount = (UInt32)(info.waitSemaphores?.Count ?? 0);
CommandBufferCount = (UInt32)(info.commandBuffers?.Count ?? 0);
SignalSemaphoreCount = (UInt32)(info.signalSemaphores?.Count ?? 0);
WaitDstStageMask = Alloc.alloc(info.waitDstStageMask);
WaitSemaphores = Alloc.alloc(info.waitSemaphores);
CommandBuffers = Alloc.alloc(info.commandBuffers);
SignalSemaphores = Alloc.alloc(info.signalSemaphores);
}
public void destroy()
{
Alloc.free(WaitDstStageMask);
Alloc.free(WaitSemaphores);
Alloc.free(CommandBuffers);
Alloc.free(SignalSemaphores);
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
internal struct _RenderPassCreateInfo
{
public VK.StructureType type;
public IntPtr next;
public VK.RenderPassCreateFlags flags;
public UInt32 attachmentCount;
public IntPtr attachments;
public UInt32 subpassCount;
public IntPtr subpasses;
public UInt32 dependencyCount;
public IntPtr dependencies;
public _RenderPassCreateInfo(VK.RenderPassCreateInfo info)
{
type = info.type;
next = info.next;
flags = info.flags;
attachmentCount = (UInt32)(info.attachments?.Count ?? 0);
subpassCount = (UInt32)(info.subpasses?.Count ?? 0);
dependencyCount = (UInt32)(info.dependencies?.Count ?? 0);
attachments = Alloc.alloc(info.attachments);
dependencies = Alloc.alloc(info.dependencies);
List<_SubpassDescription> subpassArray = new List<_SubpassDescription>();
for(int i = 0; i < info.subpasses.Count; i++)
{
subpassArray.Add(new _SubpassDescription(info.subpasses[i]));
}
subpasses = Alloc.alloc(subpassArray);
for(int i = 0; i < subpassArray.Count; i++)
{
subpassArray[i].destroy();
}
}
public void destroy()
{
Alloc.free(attachments);
Alloc.free(subpasses);
Alloc.free(dependencies);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
internal struct _SubpassDescription
{
public VK.SubpassDescriptionFlags flags;
public VK.PipelineBindPoint pipelineBindPoint; //Must be VK_PIPELINE_BIND_POINT_GRAPHICS for now
public UInt32 inputAttachmentCount;
public IntPtr inputAttachments;
public UInt32 colorAttachmentCount;
public IntPtr colorAttachments;
public IntPtr resolveAttachments;
public IntPtr depthStencilAttachment;
public UInt32 preserveAttachmentCount;
public IntPtr preserveAttachments;
public _SubpassDescription(VK.SubpassDescription info)
{
flags = info.flags;
pipelineBindPoint = info.pipelineBindPoint;
inputAttachmentCount = (UInt32)(info.inputAttachments?.Count ?? 0);
colorAttachmentCount = (UInt32)(info.colorAttachments?.Count ?? 0);
preserveAttachmentCount = (UInt32)(info.preserveAttachments?.Count ?? 0);
inputAttachments = Alloc.alloc(info.inputAttachments);
colorAttachments = Alloc.alloc(info.colorAttachments);
resolveAttachments = Alloc.alloc(info.resolveAttachments);
depthStencilAttachment = Alloc.alloc(info.depthStencilAttachment);
preserveAttachments = Alloc.alloc(info.preserveAttachments);
}
public void destroy()
{
Alloc.free(inputAttachments);
Alloc.free(colorAttachments);
Alloc.free(resolveAttachments);
Alloc.free(depthStencilAttachment);
Alloc.free(preserveAttachments);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
internal struct _FramebufferCreateInfo
{
public VK.StructureType type;
public IntPtr next;
public VK.FramebufferCreateFlags flags;
public VK.RenderPass renderPass;
public UInt32 attachmentCount;
public IntPtr attachments;
public UInt32 width;
public UInt32 height;
public UInt32 layers;
public _FramebufferCreateInfo(VK.FramebufferCreateInfo info)
{
type = info.type;
next = info.next;
flags = info.flags;
renderPass = info.renderPass;
attachmentCount = (UInt32)(info.attachments?.Count ?? 0);
width = info.width;
height = info.height;
layers = info.layers;
attachments = Alloc.alloc(info.attachments);
}
public void destroy()
{
Alloc.free(attachments);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
internal struct _CommandBufferBeginInfo
{
public VK.StructureType type;
public IntPtr next;
public VK.CommandBufferUsageFlags flags; //Command buffer usage flags
public IntPtr inheritanceInfo; //Pointer to inheritance info for secondary command buffers
public _CommandBufferBeginInfo(VK.CommandBufferBeginInfo info)
{
type = info.type;
next = info.next;
flags = info.flags;
inheritanceInfo = info.inheritanceInfo == null ? IntPtr.Zero : Alloc.alloc(info.inheritanceInfo);
}
public void destroy()
{
Alloc.free(inheritanceInfo);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _PipelineVertexInputStateCreateInfo
{
public VK.StructureType type;
public IntPtr next;
public VK.PipelineVertexInputStateCreateFlags flags;
public UInt32 vertexBindingDescriptionCount; //number of bindings
public IntPtr vertexBindingDescriptions;
public UInt32 vertexAttributeDescriptionCount; //number of attributes
public IntPtr vertexAttributeDescriptions;
public _PipelineVertexInputStateCreateInfo(VK.PipelineVertexInputStateCreateInfo info)
{
type = info.type;
next = info.next;
flags = info.flags;
vertexBindingDescriptionCount = (UInt32)(info.vertexBindingDescriptions?.Length ?? 0);
vertexBindingDescriptions = info.vertexBindingDescriptions != null ? Alloc.alloc(info.vertexBindingDescriptions) : IntPtr.Zero;
vertexAttributeDescriptionCount = (UInt32)(info.vertexAttributeDescriptions?.Length ?? 0);
vertexAttributeDescriptions = info.vertexAttributeDescriptions != null ? Alloc.alloc(info.vertexAttributeDescriptions) : IntPtr.Zero;
}
public void destroy()
{
Alloc.free(vertexBindingDescriptions);
Alloc.free(vertexAttributeDescriptions);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _GraphicsPipelineCreateInfo
{
public VK.StructureType type;
public IntPtr next;
public VK.PipelineCreateFlags flags; //Pipeline creation flags
public UInt32 stageCount;
public IntPtr pStages; //One entry for each active shader stage
public IntPtr pVertexInputState;
public IntPtr pInputAssemblyState;
public IntPtr pTessellationState;
public IntPtr pViewportState;
public IntPtr pRasterizationState;
public IntPtr pMultisampleState;
public IntPtr pDepthStencilState;
public IntPtr pColorBlendState;
public IntPtr pDynamicState;
public VK.PipelineLayout layout; //Interface layout of the pipeline
public VK.RenderPass renderPass;
public UInt32 subpass;
public VK.Pipeline basePipelineHandle; //If VK_PIPELINE_CREATE_DERIVATIVE_BIT is set and this value is nonzero, it specifies the handle of the base pipeline this is a derivative of
public Int32 basePipelineIndex; //If VK_PIPELINE_CREATE_DERIVATIVE_BIT is set and this value is not -1, it specifies an index into pCreateInfos of the base pipeline this is a derivative of
public _GraphicsPipelineCreateInfo(VK.GraphicsPipelineCreateInfo info)
{
type = info.type;
next = info.next;
flags = info.flags;
stageCount = (UInt32)info.stages.Count;
List<_PipelineShaderStageCreateInfo> stages = new List<_PipelineShaderStageCreateInfo>();
for(int i=0; i< info.stages.Count; i++)
{
stages.Add(new _PipelineShaderStageCreateInfo(info.stages[i]));
}
pStages = Alloc.alloc(stages);
pVertexInputState = info.vertexInputState == null ? IntPtr.Zero : Alloc.alloc(new _PipelineVertexInputStateCreateInfo(info.vertexInputState));
pInputAssemblyState = info.inputAssemblyState == null ? IntPtr.Zero : Alloc.alloc(info.inputAssemblyState);
pTessellationState = info.tessellationState == null ? IntPtr.Zero : Alloc.alloc(info.tessellationState);
pViewportState = info.viewportState == null ? IntPtr.Zero : Alloc.alloc(new _PipelineViewportStateCreateInfo(info.viewportState));
pRasterizationState = info.rasterizationState == null ? IntPtr.Zero : Alloc.alloc(info.rasterizationState);
pMultisampleState = info.multisampleState == null ? IntPtr.Zero : Alloc.alloc(new _PipelineMultisampleStateCreateInfo(info.multisampleState));
pDepthStencilState = info.depthStencilState == null ? IntPtr.Zero : Alloc.alloc(info.depthStencilState);
pColorBlendState = info.colorBlendState == null ? IntPtr.Zero : Alloc.alloc(new _PipelineColorBlendStateCreateInfo(info.colorBlendState));
pDynamicState = info.dynamicState == null ? IntPtr.Zero : Alloc.alloc(new _PipelineDynamicStateCreateInfo(info.dynamicState));
layout = info.layout;
renderPass = info.renderPass;
subpass = info.subpass;
basePipelineHandle = info.basePipelineHandle;
basePipelineIndex = info.basePipelineIndex;
}
public void destroy()
{
Alloc.free(pStages);
Alloc.free(pVertexInputState);
Alloc.free(pInputAssemblyState);
Alloc.free(pTessellationState);
Alloc.free(pViewportState);
Alloc.free(pRasterizationState);
Alloc.free(pMultisampleState);
Alloc.free(pDepthStencilState);
Alloc.free(pColorBlendState);
Alloc.free(pDynamicState);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _ComputePipelineCreateInfo
{
public VK.StructureType type;
public IntPtr next;
public VK.PipelineCreateFlags flags; //Pipeline creation flags
public _PipelineShaderStageCreateInfo stage;
public VK.PipelineLayout layout; //Interface layout of the pipeline
public VK.Pipeline basePipelineHandle; //If VK_PIPELINE_CREATE_DERIVATIVE_BIT is set and this value is nonzero, it specifies the handle of the base pipeline this is a derivative of
public Int32 basePipelineIndex; //If VK_PIPELINE_CREATE_DERIVATIVE_BIT is set and this value is not -1, it specifies an index into pCreateInfos of the base pipeline this is a derivative of
public _ComputePipelineCreateInfo(VK.ComputePipelineCreateInfo info)
{
type = info.type;
next = info.next;
flags = info.flags;
stage = new _PipelineShaderStageCreateInfo(info.stage);
layout = info.layout;
basePipelineHandle = info.basePipelineHandle;
basePipelineIndex = info.basePipelineIndex;
}
public void destroy()
{
stage.destroy();
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _PipelineShaderStageCreateInfo
{
public VK.StructureType type;
public IntPtr next;
public VK.PipelineShaderStageCreateFlags flags;
public VK.ShaderStageFlags stage; //Shader stage
public VK.ShaderModule module; //Module containing entry point
public IntPtr name; //Null-terminated entry point name
public IntPtr specializationInfo;
public _PipelineShaderStageCreateInfo(VK.PipelineShaderStageCreateInfo info)
{
type = info.type;
next = info.next;
flags = info.flags;
stage = info.stage;
module = info.module;
name = Marshal.StringToHGlobalAnsi(info.name);
if(info.specializationInfo != null)
{
specializationInfo = Alloc.alloc(new _SpecializationInfo(info.specializationInfo));
}
else
{
specializationInfo = IntPtr.Zero;
}
}
public void destroy()
{
Marshal.FreeHGlobal(name);
Alloc.free(specializationInfo);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _PipelineViewportStateCreateInfo
{
public VK.StructureType type;
public IntPtr next;
public VK.PipelineViewportStateCreateFlags flags;
public UInt32 viewportCount;
public IntPtr viewports;
public UInt32 scissorCount;
public IntPtr scissors;
public _PipelineViewportStateCreateInfo(VK.PipelineViewportStateCreateInfo info)
{
type = info.type;
next = info.next;
flags = info.flags;
viewportCount = (UInt32)info.viewports.Count;
viewports = Alloc.alloc(info.viewports);
scissorCount = (UInt32)info.scissors.Count;
scissors = Alloc.alloc(info.scissors);
}
public void destroy()
{
Alloc.free(viewports);
Alloc.free(scissors);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _PipelineMultisampleStateCreateInfo
{
public VK.StructureType type;
public IntPtr next;
public VK.PipelineMultisampleStateCreateFlags flags;
public VK.SampleCountFlags rasterizationSamples; //Number of samples used for rasterization
public Bool32 sampleShadingEnable; //optional (GL45)
public float minSampleShading; //optional (GL45)
public IntPtr sampleMask; //Array of sampleMask words
public Bool32 alphaToCoverageEnable;
public Bool32 alphaToOneEnable;
public _PipelineMultisampleStateCreateInfo(VK.PipelineMultisampleStateCreateInfo info)
{
type = info.type;
next = info.next;
flags = info.flags;
rasterizationSamples = info.rasterizationSamples;
sampleShadingEnable = info.sampleShadingEnable;
minSampleShading = info.minSampleShading;
sampleMask = Alloc.alloc(info.sampleMask);
alphaToCoverageEnable = info.alphaToCoverageEnable;
alphaToOneEnable = info.alphaToOneEnable;
}
public void destroy()
{
Alloc.free(sampleMask);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public unsafe struct _PipelineColorBlendStateCreateInfo
{
public VK.StructureType type;
public IntPtr next;
public VK.PipelineColorBlendStateCreateFlags flags;
public Bool32 logicOpEnable;
public VK.LogicOp logicOp;
public UInt32 attachmentCount; //# of pAttachments
public IntPtr pAttachments;
public fixed float blendConstants[4];
public _PipelineColorBlendStateCreateInfo(VK.PipelineColorBlendStateCreateInfo info)
{
type = info.type;
next = info.next;
flags = info.flags;
logicOpEnable = info.logicOpEnable;
logicOp = info.logicOp;
attachmentCount = (UInt32)info.attachments.Count;
pAttachments = Alloc.alloc(info.attachments);
for(int i = 0; i < 4; i++)
{
blendConstants[i] = info.blendConstants[i];
}
}
public void destroy()
{
Alloc.free(pAttachments);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _PipelineDynamicStateCreateInfo
{
public VK.StructureType type;
public IntPtr next;
public VK.PipelineDynamicStateCreateFlags flags;
public UInt32 dynamicStateCount;
public IntPtr dynamicStates;
public _PipelineDynamicStateCreateInfo(VK.PipelineDynamicStateCreateInfo info)
{
type = info.type;
next = info.next;
flags = info.flags;
dynamicStateCount = (UInt32)info.dynamicStates.Count;
dynamicStates = Alloc.alloc(info.dynamicStates);
}
public void destroy()
{
Alloc.free(dynamicStates);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _PipelineLayoutCreateInfo
{
public VK.StructureType type;
public IntPtr next;
public VK.PipelineLayoutCreateFlags flags;
public UInt32 setLayoutCount; //Number of descriptor sets interfaced by the pipeline
public IntPtr setLayouts; //Array of setCount number of descriptor set layout objects defining the layout of the
public UInt32 pushConstantRangeCount; //Number of push-constant ranges used by the pipeline
public IntPtr pushConstantRanges; //Array of pushConstantRangeCount number of ranges used by various shader stages
public _PipelineLayoutCreateInfo(VK.PipelineLayoutCreateInfo info)
{
type = info.type;
next = info.next;
flags = info.flags;
setLayoutCount = (UInt32)(info.setLayouts?.Count ?? 0);
setLayouts = Alloc.alloc(info.setLayouts);
pushConstantRangeCount = (UInt32)(info.pushConstantRanges?.Count ?? 0);
pushConstantRanges = Alloc.alloc(info.pushConstantRanges);
}
public void destroy()
{
Alloc.free(setLayouts);
Alloc.free(pushConstantRanges);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _SpecializationInfo
{
public UInt32 mapEntryCount; //Number of entries in the map
public IntPtr pMapEntries; //Array of map entries
public UInt64 dataSize; //Size in bytes of pData
public IntPtr pData; //Pointer to SpecConstant data
public _SpecializationInfo(VK.SpecializationInfo info)
{
mapEntryCount = (UInt32)info.mapEntries.Count;
pMapEntries = Alloc.alloc(info.mapEntries);
dataSize = info.dataSize;
pData = info.pData;
}
public void destroy()
{
Alloc.free(pMapEntries);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _DescriptorSetLayoutCreateInfo
{
public VK.StructureType type;
public IntPtr next;
public VK.DescriptorSetLayoutCreateFlags flags;
public UInt32 bindingCount; //Number of bindings in the descriptor set layout
public IntPtr pBindings; //Array of descriptor set layout bindings
public _DescriptorSetLayoutCreateInfo(VK.DescriptorSetLayoutCreateInfo info)
{
type = info.type;
next = info.next;
flags = info.flags;
bindingCount = (UInt32)info.bindings.Count;
List<_DescriptorSetLayoutBinding> bindings = new List<_DescriptorSetLayoutBinding>();
for(int i=0; i < info.bindings.Count; i++)
{
bindings.Add(new _DescriptorSetLayoutBinding(info.bindings[i]));
}
pBindings = Alloc.alloc(bindings);
}
public void destroy()
{
Alloc.free(pBindings);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _DescriptorSetLayoutBinding
{
public UInt32 binding; //Binding number for this entry
public VK.DescriptorType descriptorType; //Type of the descriptors in this binding
public UInt32 descriptorCount; //Number of descriptors in this binding
public VK.ShaderStageFlags stageFlags; //Shader stages this binding is visible to
public IntPtr pImmutableSamplers; //Immutable samplers (used if descriptor type is SAMPLER or COMBINED_IMAGE_SAMPLER, is either NULL or contains count number of elements)
public _DescriptorSetLayoutBinding(VK.DescriptorSetLayoutBinding info)
{
binding = info.binding;
descriptorType = info.descriptorType;
descriptorCount = info.descriptorCount;
stageFlags = info.stageFlags;
pImmutableSamplers = Alloc.alloc(info.immutableSamplers);
}
public void destroy()
{
Alloc.free(pImmutableSamplers);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _DescriptorPoolCreateInfo
{
public VK.StructureType type;
public IntPtr next;
public VK.DescriptorPoolCreateFlags flags;
public UInt32 maxSets;
public UInt32 poolSizeCount;
public IntPtr pPoolSizes;
public _DescriptorPoolCreateInfo(VK.DescriptorPoolCreateInfo info)
{
type = info.type;
next = info.next;
flags = info.flags;
maxSets = info.maxSets;
poolSizeCount = (UInt32)info.poolSizes.Count;
pPoolSizes = Alloc.alloc(info.poolSizes);
}
public void destroy()
{
Alloc.free(pPoolSizes);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _DescriptorSetAllocateInfo
{
public VK.StructureType type;
public IntPtr next;
public VK.DescriptorPool descriptorPool;
public UInt32 descriptorSetCount;
public IntPtr pSetLayouts;
public _DescriptorSetAllocateInfo(VK.DescriptorSetAllocateInfo info)
{
type = info.type;
next = info.next;
descriptorPool = info.descriptorPool;
descriptorSetCount = (UInt32)info.setLayouts.Count;
pSetLayouts = Alloc.alloc(info.setLayouts);
}
public void destroy()
{
Alloc.free(pSetLayouts);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _DeviceGroupRenderPassBeginInfo
{
public VK.StructureType type;
public IntPtr next;
public UInt32 deviceMask;
public UInt32 deviceRenderAreaCount;
public IntPtr deviceRenderAreas;
public _DeviceGroupRenderPassBeginInfo(VK.DeviceGroupRenderPassBeginInfo info)
{
type = info.type;
next = info.next;
deviceMask = info.deviceMask;
deviceRenderAreaCount = (UInt32)(info.deviceRenderAreas?.Count ?? 0);
deviceRenderAreas = Alloc.alloc(info.deviceRenderAreas);
}
public void destroy()
{
Alloc.free(deviceRenderAreas);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _DeviceGroupSubmitInfo
{
public VK.StructureType type;
public IntPtr next;
public UInt32 waitSemaphoreCount;
public IntPtr pWaitSemaphoreDeviceIndices;
public UInt32 commandBufferCount;
public IntPtr pCommandBufferDeviceMasks;
public UInt32 signalSemaphoreCount;
public IntPtr pSignalSemaphoreDeviceIndices;
public _DeviceGroupSubmitInfo(VK.DeviceGroupSubmitInfo info)
{
type = info.type;
next = info.next;
waitSemaphoreCount = (UInt32)(info.waitSemaphoreDeviceIndices?.Count ?? 0);
commandBufferCount = (UInt32)(info.commandBufferDeviceMasks?.Count ?? 0);
signalSemaphoreCount = (UInt32)(info.signalSemaphoreDeviceIndices?.Count ?? 0);
pWaitSemaphoreDeviceIndices = Alloc.alloc(info.waitSemaphoreDeviceIndices);
pCommandBufferDeviceMasks = Alloc.alloc(info.commandBufferDeviceMasks);
pSignalSemaphoreDeviceIndices = Alloc.alloc(info.signalSemaphoreDeviceIndices);
}
public void destroy()
{
Alloc.free(pWaitSemaphoreDeviceIndices);
Alloc.free(pCommandBufferDeviceMasks);
Alloc.free(pSignalSemaphoreDeviceIndices);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _RenderPassBeginInfo
{
public VK.StructureType type;
public IntPtr next;
public VK.RenderPass renderPass;
public VK.Framebuffer framebuffer;
public VK.Rect2D renderArea;
public UInt32 clearValueCount;
public IntPtr pClearValues;
public _RenderPassBeginInfo(VK.RenderPassBeginInfo info)
{
type = info.type;
next = info.next;
renderPass = info.renderPass;
framebuffer = info.framebuffer;
renderArea = info.renderArea;
clearValueCount = (UInt32)(info.clearValues.Count);
pClearValues = Alloc.alloc(info.clearValues);
}
public void destroy()
{
Alloc.free(pClearValues);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _BindBufferMemoryDeviceGroupInfo
{
public VK.StructureType type;
public IntPtr next;
public UInt32 deviceIndexCount;
public IntPtr deviceIndices;
public _BindBufferMemoryDeviceGroupInfo(VK.BindBufferMemoryDeviceGroupInfo info)
{
type = info.type;
next = info.next;
deviceIndexCount = (UInt32)info.deviceIndices.Count;
deviceIndices = Alloc.alloc(info.deviceIndices);
}
public void destroy()
{
Alloc.free(deviceIndices);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _BindImageMemoryDeviceGroupInfo
{
public VK.StructureType type;
public IntPtr next;
public UInt32 deviceIndexCount;
public IntPtr deviceIndices;
public UInt32 splitInstanceBindRegionCount;
public IntPtr splitInstanceBindRegions;
public _BindImageMemoryDeviceGroupInfo(VK.BindImageMemoryDeviceGroupInfo info)
{
type = info.type;
next = info.next;
deviceIndexCount = (UInt32)info.deviceIndices.Count;
deviceIndices = Alloc.alloc(info.deviceIndices);
splitInstanceBindRegionCount = (UInt32)info.splitInstanceBindRegions.Count;
splitInstanceBindRegions = Alloc.alloc(info.splitInstanceBindRegions);
}
public void destroy()
{
Alloc.free(deviceIndices);
Alloc.free(splitInstanceBindRegions);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _PhysicalDeviceGroupProperties
{
public VK.StructureType type;
public IntPtr next;
public UInt32 physicalDeviceCount;
public IntPtr physicalDevices;
public Bool32 subsetAllocation;
public _PhysicalDeviceGroupProperties(VK.PhysicalDeviceGroupProperties info)
{
type = info.type;
next = info.next;
physicalDeviceCount = (UInt32)info.physicalDevices.Count;
physicalDevices = Alloc.alloc(info.physicalDevices);
subsetAllocation = info.subsetAllocation;
}
public void destroy()
{
Alloc.free(physicalDevices);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _DeviceGroupDeviceCreateInfo
{
public VK.StructureType type;
public IntPtr next;
public UInt32 physicalDeviceCount;
public IntPtr physicalDevices;
public _DeviceGroupDeviceCreateInfo(VK.DeviceGroupDeviceCreateInfo info)
{
type = info.type;
next = info.next;
physicalDeviceCount = (UInt32)info.physicalDevices.Count;
physicalDevices = Alloc.alloc(info.physicalDevices);
}
public void destroy()
{
Alloc.free(physicalDevices);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _RenderPassInputAttachmentAspectCreateInfo
{
public VK.StructureType type;
public IntPtr next;
public UInt32 aspectReferenceCount;
public IntPtr aspectReferences;
public _RenderPassInputAttachmentAspectCreateInfo(VK.RenderPassInputAttachmentAspectCreateInfo info)
{
type = info.type;
next = info.next;
aspectReferenceCount = (UInt32)info.aspectReferences.Count;
aspectReferences = Alloc.alloc(info.aspectReferences);
}
public void destroy()
{
Alloc.free(aspectReferences);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _RenderPassMultiviewCreateInfo
{
public VK.StructureType type;
public IntPtr next;
public UInt32 subpassCount;
public IntPtr viewMasks;
public UInt32 dependencyCount;
public IntPtr viewOffsets;
public UInt32 correlationMaskCount;
public IntPtr pCorrelationMasks;
public _RenderPassMultiviewCreateInfo(VK.RenderPassMultiviewCreateInfo info)
{
type = info.type;
next = info.next;
subpassCount = info.subpassCount;
viewMasks = Alloc.alloc(info.viewMasks);
dependencyCount = info.dependencyCount;
viewOffsets = Alloc.alloc(info.viewOffsets);
correlationMaskCount = info.correlationMaskCount;
pCorrelationMasks = Alloc.alloc(info.pCorrelationMasks);
}
public void destroy()
{
Alloc.free(viewMasks);
Alloc.free(viewOffsets);
Alloc.free(pCorrelationMasks);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _DescriptorUpdateTemplateCreateInfo
{
public VK.StructureType type;
public IntPtr next;
public VK.DescriptorUpdateTemplateCreateFlags flags;
public UInt32 descriptorUpdateEntryCount; //Number of descriptor update entries to use for the update template
public IntPtr descriptorUpdateEntries; //Descriptor update entries for the template
public VK.DescriptorUpdateTemplateType templateType;
public VK.DescriptorSetLayout descriptorSetLayout;
public VK.PipelineBindPoint pipelineBindPoint;
public VK.PipelineLayout pipelineLayout; //If used for push descriptors, this is the only allowed layout
public UInt32 set;
public _DescriptorUpdateTemplateCreateInfo(VK.DescriptorUpdateTemplateCreateInfo info)
{
type = info.type;
next = info.next;
flags = info.flags;
descriptorUpdateEntryCount = (UInt32)info.descriptorUpdateEntries.Count;
descriptorUpdateEntries = Alloc.alloc(info.descriptorUpdateEntries);
templateType = info.templateType;
descriptorSetLayout = info.descriptorSetLayout;
pipelineBindPoint = info.pipelineBindPoint;
pipelineLayout = info.pipelineLayout;
set = info.set;
}
public void destroy()
{
Alloc.free(descriptorUpdateEntries);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _ShaderModuleCreateInfo
{
public VK.StructureType type;
public IntPtr next;
public VK.ShaderModuleCreateFlags flags;
public UInt64 codeSize;
public IntPtr code; //Binary code of size codeSize
public _ShaderModuleCreateInfo(VK.ShaderModuleCreateInfo info)
{
type = info.type;
next = info.next;
flags = info.flags;
codeSize = (UInt32)info.code.Length;
code = Marshal.AllocHGlobal(info.code.Length);
Marshal.Copy(info.code, 0, code, info.code.Length);
}
public void destroy()
{
Marshal.FreeHGlobal(code);
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _WriteDescriptorSet
{
public VK.StructureType type;
public IntPtr next;
public VK.DescriptorSet dstSet; //Destination descriptor set
public UInt32 dstBinding; //Binding within the destination descriptor set to write
public UInt32 dstArrayElement; //Array element within the destination binding to write
public UInt32 descriptorCount; //Number of descriptors to write (determines the size of the array pointed by pDescriptors)
public VK.DescriptorType descriptorType; //Descriptor type to write (determines which members of the array pointed by pDescriptors are going to be used)
public IntPtr pImageInfo; //Sampler, image view, and layout for SAMPLER, COMBINED_IMAGE_SAMPLER, {SAMPLED,STORAGE}_IMAGE, and INPUT_ATTACHMENT descriptor types.
public IntPtr pBufferInfo; //Raw buffer, size, and offset for {UNIFORM,STORAGE}_BUFFER[_DYNAMIC] descriptor types.
public IntPtr pTexelBufferView; //Buffer view to write to the descriptor for {UNIFORM,STORAGE}_TEXEL_BUFFER descriptor types.
public _WriteDescriptorSet(VK.WriteDescriptorSet set)
{
type = set.type;
next = set.next;
dstSet = set.dstSet;
dstBinding = set.dstBinding;
dstArrayElement = set.dstArrayElement;
descriptorCount = set.descriptorCount;
descriptorType = set.descriptorType;
pImageInfo = IntPtr.Zero;
pBufferInfo = IntPtr.Zero;
pTexelBufferView = IntPtr.Zero;
switch(descriptorType)
{
case VK.DescriptorType.AccelerationStructureNv:
throw new Exception("Not Supported yet");
break;
case VK.DescriptorType.CombinedImageSampler:
pImageInfo = Alloc.alloc(set.imageInfo);
break;
case VK.DescriptorType.InlineUniformBlockExt:
pBufferInfo = Alloc.alloc(set.bufferInfo);
break;
case VK.DescriptorType.InputAttachment:
pImageInfo = Alloc.alloc(set.imageInfo);
break;
case VK.DescriptorType.SampledImage:
pImageInfo = Alloc.alloc(set.imageInfo);
break;
case VK.DescriptorType.Sampler:
pImageInfo = Alloc.alloc(set.imageInfo);
break;
case VK.DescriptorType.StorageBuffer:
pBufferInfo = Alloc.alloc(set.bufferInfo);
break;
case VK.DescriptorType.StorageBufferDynamic:
pBufferInfo = Alloc.alloc(set.bufferInfo);
break;
case VK.DescriptorType.StorageImage:
pImageInfo = Alloc.alloc(set.imageInfo);
break;
case VK.DescriptorType.StorageTexelBuffer:
pTexelBufferView = Alloc.alloc(set.texelBufferView);
break;
case VK.DescriptorType.UniformBuffer:
pBufferInfo = Alloc.alloc(set.bufferInfo);
break;
case VK.DescriptorType.UniformBufferDynamic:
pBufferInfo = Alloc.alloc(set.bufferInfo);
break;
case VK.DescriptorType.UniformTexelBuffer:
pTexelBufferView = Alloc.alloc(set.texelBufferView);
break;
}
}
public void destory()
{
Alloc.free(pImageInfo);
Alloc.free(pBufferInfo);
Alloc.free(pTexelBufferView);
}
};
}
| |
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using DemoGame.Server.Queries;
using log4net;
using NetGore;
using NetGore.Db;
namespace DemoGame.Server
{
/// <summary>
/// Base class for an inventory for a <see cref="Character"/>.
/// </summary>
public abstract class CharacterInventory : InventoryBase<ItemEntity>
{
static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
readonly Character _character;
bool _isLoading;
/// <summary>
/// Initializes a new instance of the <see cref="CharacterInventory"/> class.
/// </summary>
/// <param name="character">The <see cref="Character"/> the inventory belongs to.</param>
/// <exception cref="ArgumentNullException"><paramref name="character" /> is <c>null</c>.</exception>
protected CharacterInventory(Character character) : base(GameData.MaxInventorySize)
{
if (character == null)
throw new ArgumentNullException("character");
_character = character;
}
/// <summary>
/// Gets the Character that this Inventory belongs to.
/// </summary>
public Character Character
{
get { return _character; }
}
/// <summary>
/// Gets the <see cref="IDbController"/> used by this CharacterInventory.
/// </summary>
public IDbController DbController
{
get { return Character.DbController; }
}
/// <summary>
/// Gets if the state of this <see cref="CharacterInventory"/> is persistent.
/// </summary>
public bool IsPersistent
{
get { return Character.IsPersistent; }
}
/// <summary>
/// Decrements the amount of the item at the given <paramref name="slot"/>.
/// </summary>
/// <param name="slot">The slot of the inventory item who's amount is to be decremented.</param>
public void DecreaseItemAmount(InventorySlot slot)
{
// Get the ItemEntity
var item = this[slot];
if (item == null)
{
const string errmsg = "Tried to decrease amount of inventory slot `{0}`, but it contains no item.";
Debug.Fail(string.Format(errmsg, slot));
if (log.IsWarnEnabled)
log.WarnFormat(errmsg, slot);
return;
}
// Check for a valid amount
if (item.Amount == 0)
{
// If amount is already 0, we will show a warning but still remove the item
const string errmsg = "Item in slot `{0}` already contains an amount of 0.";
Debug.Fail(string.Format(errmsg, slot));
if (log.IsWarnEnabled)
log.WarnFormat(errmsg, slot);
// Remove the item
ClearSlot(slot, true);
}
else
{
// Decrease the amount
item.Amount--;
// Remove the item if it ran out
if (item.Amount <= 0)
ClearSlot(slot, true);
}
}
/// <summary>
/// When overridden in the derived class, handles when this object is disposed.
/// </summary>
/// <param name="disposeManaged">True if dispose was called directly; false if this object was garbage collected.</param>
protected override void Dispose(bool disposeManaged)
{
base.Dispose(disposeManaged);
// If not persistent, destroy every item in the collection
if (!IsPersistent)
RemoveAll(true);
}
/// <summary>
/// Makes the Character drop an item from their Inventory.
/// </summary>
/// <param name="slot">Slot of the item to drop.</param>
/// <returns>True if the item was successfully dropped, else false.</returns>
public bool Drop(InventorySlot slot)
{
// Get the item to drop
var dropItem = this[slot];
// Check for an invalid item
if (dropItem == null)
{
const string errmsg = "Could not drop item since no item exists at slot `{0}`.";
if (log.IsWarnEnabled)
log.WarnFormat(errmsg, slot);
return false;
}
// Remove the item from the inventory
RemoveAt(slot, false);
// Drop the item
Character.DropItem(dropItem);
return true;
}
/// <summary>
/// Makes the Character drop an item from their Inventory.
/// </summary>
/// <param name="slot">Slot of the item to drop.</param>
/// <param name="amount">The maximum amount of the item to drop.</param>
/// <returns>True if the item was successfully dropped, else false.</returns>
public bool Drop(InventorySlot slot, byte amount)
{
// Get the item to drop
var dropItem = this[slot];
// Check for an invalid item
if (dropItem == null)
{
const string errmsg = "Could not drop item since no item exists at slot `{0}`.";
if (log.IsWarnEnabled)
log.WarnFormat(errmsg, slot);
return false;
}
// If the amount to drop is greater than or equal to the amount available, drop it all
if (dropItem.Amount <= amount)
{
// Remove the item from the inventory
RemoveAt(slot, false);
// Drop the item
Character.DropItem(dropItem);
}
else
{
// Only drop some of the item
var dropPart = dropItem.Split(amount);
// Drop the portion of the item
Character.DropItem(dropPart);
}
return true;
}
/// <summary>
/// When overridden in the derived class, performs additional processing to handle an inventory slot
/// changing. This is only called when the object references changes, not when any part of the object
/// (such as the Item's amount) changes. It is guarenteed that if <paramref name="newItem"/> is null,
/// <paramref name="oldItem"/> will not be, and vise versa. Both will never be null or non-null.
/// </summary>
/// <param name="slot">Slot that the change took place in.</param>
/// <param name="newItem">The ItemEntity that was added to the <paramref name="slot"/>.</param>
/// <param name="oldItem">The ItemEntity that used to be in the <paramref name="slot"/>,
/// or null if the slot used to be empty.</param>
protected override void HandleSlotChanged(InventorySlot slot, ItemEntity newItem, ItemEntity oldItem)
{
Debug.Assert(oldItem != newItem);
if (newItem != null)
newItem.IsPersistent = IsPersistent;
// Slot change logic is only needed for when persistent
if (!IsPersistent)
return;
// Stop listening for changes on the item that was removed
if (oldItem != null)
{
oldItem.GraphicOrAmountChanged -= ItemGraphicOrAmountChangeHandler;
}
// Listen to the item for changes on the item that was added
if (newItem != null)
{
newItem.GraphicOrAmountChanged -= ItemGraphicOrAmountChangeHandler;
newItem.GraphicOrAmountChanged += ItemGraphicOrAmountChangeHandler;
}
// Do not update the database when we are loading the collection
if (!_isLoading)
{
// Update the inventory slot in the database
if (newItem == null)
DbController.GetQuery<DeleteCharacterInventoryItemQuery>().Execute(Character.ID, slot);
else
DbController.GetQuery<InsertCharacterInventoryItemQuery>().Execute(Character.ID, newItem.ID, slot);
}
// Prepare the slot for updating
SendSlotUpdate(slot);
}
/// <summary>
/// Handles when an item in the UserInventory has changed the amount or graphic, and notifies the
/// InventoryUpdater to handle the change.
/// </summary>
/// <param name="sender">Item that has changed.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
void ItemGraphicOrAmountChangeHandler(ItemEntity sender, EventArgs e)
{
Debug.Assert(IsPersistent, "This should NEVER be called when IsPersistent == false!");
InventorySlot slot;
// Try to get the slot
try
{
slot = GetSlot(sender);
}
catch (ArgumentException ex)
{
log.Warn(string.Format("Failed to get the inventory slot of item `{0}`", sender), ex);
return;
}
// Set the slot as changed
SendSlotUpdate(slot);
}
/// <summary>
/// Loads the Character's inventory items from the database.
/// </summary>
public void Load()
{
_isLoading = true;
var queryResults = DbController.GetQuery<SelectCharacterInventoryItemsQuery>().Execute(Character.ID);
foreach (var values in queryResults)
{
// Make sure no item is already in the slot... just in case
if (this[values.Key] != null)
{
const string errmsg =
"Character `{0}` already had an item in slot `{1}` ({2})." +
" It is going to have to be disposed to make room for the newest loaded item `{3}`." +
" If this ever happens, its likely a problem.";
var item = this[values.Key];
if (log.IsErrorEnabled)
log.ErrorFormat(errmsg, Character, values.Key, item, values.Value);
Debug.Fail(string.Format(errmsg, Character, values.Key, item, values.Value));
item.Dispose();
}
// Set the item into the slot
this[values.Key] = new ItemEntity(values.Value);
}
_isLoading = false;
}
/// <summary>
/// When overridden in the derived class, notifies the Client that a slot in the Inventory has changed.
/// </summary>
/// <param name="slot">The slot that changed.</param>
protected virtual void SendSlotUpdate(InventorySlot slot)
{
}
}
}
| |
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using sqlite3_int64 = System.Int64;
using u32 = System.UInt32;
using System.Text;
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/*
*************************************************************************
**
** This file contains low-level memory & pool allocation drivers
**
** This file contains implementations of the low-level memory allocation
** routines specified in the sqlite3_mem_methods object.
**
*************************************************************************
*/
/*
** Like malloc(), but remember the size of the allocation
** so that we can find it later using sqlite3MemSize().
**
** For this low-level routine, we are guaranteed that nByte>0 because
** cases of nByte<=0 will be intercepted and dealt with by higher level
** routines.
*/
#if SQLITE_POOL_MEM
#if !NO_TRUE
static byte[] sqlite3MemMalloc( u32 nByte )
{
return new byte[nByte];
}
static byte[] sqlite3MemMalloc( int nByte )
{
return new byte[nByte];
}
static int[] sqlite3MemMallocInt( int nInt )
{
return new int[nInt];
}
#else
static byte[] sqlite3MemMalloc(int nByte)
{
byte[] pByte = null;
int savej = -1;
int BestSize = int.MaxValue;
if (nByte > mem0.aByteSize[0])
{
int i;
for (i = 0; i < mem0.aByteSize.Length - 1; i++) if (nByte <= mem0.aByteSize[i]) break;
mem0.mr_Byte++;
for (int j = 0; j <= mem0.aByte_used[i]; j++)
if (mem0.aByte[i][j] != null)
{
if (mem0.aByte[i][j].Length == nByte)
{
pByte = mem0.aByte[i][j]; mem0.aByte[i][j] = null; mem0.cf_Byte++;
if (j == mem0.aByte_used[i]) mem0.aByte_used[i]--;
break;
}
if (mem0.aByte[i][j].Length > nByte)
{
if (mem0.aByte[i][j].Length < BestSize)
{
BestSize = mem0.aByte[i][j].Length;
savej = j;
}
}
}
if (pByte == null && savej >= 0)
{
pByte = mem0.aByte[i][savej]; mem0.aByte[i][savej] = null; mem0.cf_Byte++;
Array.Resize(ref pByte, nByte);
}
if (mem0.aByte_used[i] >=0 && mem0.aByte[i][mem0.aByte_used[i]] == null) mem0.aByte_used[i]--;
}
if (pByte == null) pByte = new byte[nByte];
return pByte;
}
static int[] sqlite3MemMallocInt(int nInt)
{
int[] pInt = null;
int savei = -1;
int BestSize = int.MaxValue;
if (nInt >=10)
{
mem0.mr_Int++;
int i;
for (i = 0; i < mem0.hw_Int; i++)
if (mem0.aInt[i] != null)
{
if (mem0.aInt[i].Length == nInt)
{
pInt = mem0.aInt[i]; mem0.aInt[i] = null; mem0.cf_Int++; break;
}
if (mem0.aInt[i].Length > nInt)
{
if (mem0.aInt[i].Length < BestSize)
{
BestSize = mem0.aInt[i].Length;
savei = i;
}
}
}
if (pInt == null && savei >= 0)
{
pInt = mem0.aInt[savei]; mem0.aInt[savei] = null; mem0.cf_Int++;
}
}
if (pInt == null) pInt = new int[nInt];
return pInt;
}
#endif
static Mem sqlite3MemMallocMem( Mem dummy )
{
Mem pMem;
mem0.msMem.alloc++;
if ( mem0.msMem.next > 0 && mem0.aMem[mem0.msMem.next] != null )
{
pMem = mem0.aMem[mem0.msMem.next];
mem0.aMem[mem0.msMem.next] = null;
mem0.msMem.cached++;
mem0.msMem.next--;
}
else
pMem = new Mem();
return pMem;
}
static BtCursor sqlite3MemMallocBtCursor( BtCursor dummy )
{
BtCursor pBtCursor;
mem0.msBtCursor.alloc++;
if ( mem0.msBtCursor.next > 0 && mem0.aBtCursor[mem0.msBtCursor.next] != null )
{
pBtCursor = mem0.aBtCursor[mem0.msBtCursor.next];
Debug.Assert( pBtCursor.pNext == null && pBtCursor.pPrev == null && pBtCursor.wrFlag == 0 );
mem0.aBtCursor[mem0.msBtCursor.next] = null;
mem0.msBtCursor.cached++;
mem0.msBtCursor.next--;
}
else
pBtCursor = new BtCursor();
return pBtCursor;
}
#endif
/*
** Free memory.
*/
// -- overloads ---------------------------------------
static void sqlite3MemFree<T>( ref T x ) where T : class
{
x = null;
}
static void sqlite3MemFree( ref string x )
{
x = null;
}
//
/*
** Like free() but works for allocations obtained from sqlite3MemMalloc()
** or sqlite3MemRealloc().
**
** For this low-level routine, we already know that pPrior!=0 since
** cases where pPrior==0 will have been intecepted and dealt with
** by higher-level routines.
*/
#if SQLITE_POOL_MEM
#if !NO_TRUE
static void sqlite3MemFreeInt( ref int[] pPrior )
{
pPrior = null;
}
#else
static void sqlite3MemFree(ref byte[] pPrior)
{
if (pPrior == null) return;
if (pPrior.Length > mem0.aByteSize[0])
{
int savej = -1;
int Smallest = int.MaxValue;
int i;
for (i = 0; i < mem0.aByteSize.Length - 1; i++) if (pPrior.Length <= mem0.aByteSize[i]) break;
#if DEBUG
for (int j = 0; j < mem0.aByte[i].Length; j++) if (mem0.aByte[i][j] != null && mem0.aByte[i][j] == pPrior) Debugger.Break();
#endif
mem0.mf_Byte++;
for (int j = 0; j <= mem0.aByte_used[i]; j++)
{
if (mem0.aByte[i][j] == null)
{
mem0.aByte[i][j] = pPrior;
pPrior = null;
return;
}
if (mem0.aByte[i][j].Length < Smallest)
{
savej = j;
Smallest = mem0.aByte[i][j].Length;
}
}
if (mem0.aByte_used[i] < mem0.aByte[i].Length - 1) mem0.aByte[i][++mem0.aByte_used[i]] = pPrior;
else if (savej >= 0) mem0.aByte[i][savej] = pPrior;
}
pPrior = null;
return;
}
static void sqlite3MemFreeInt(ref int[] pPrior)
{
if (pPrior == null) return;
if (pPrior.Length >= 10)
{
int savei = -1;
int Smallest = int.MaxValue;
#if DEBUG
for (int i = 0; i < mem0.aInt.Length; i++) if (mem0.aInt[i] != null && mem0.aInt[i] == pPrior) Debugger.Break();
#endif
mem0.mf_Int++;
for (int i = 0; i < mem0.aInt.Length; i++)
{
if (mem0.aInt[i] == null)
{
mem0.aInt[i] = pPrior;
pPrior = null;
return;
}
if (mem0.aInt[i].Length < Smallest)
{
savei = i;
Smallest = mem0.aInt[i].Length;
}
}
if (savei >= 0) mem0.aInt[savei] = pPrior;
}
pPrior = null;
return;
}
#endif
static void sqlite3MemFreeMem( ref Mem pPrior )
{
if ( pPrior == null )
return;
#if FALSE && DEBUG
for (int i = mem0.msMem.next - 1; i >= 0; i--) if (mem0.aMem[i] != null && mem0.aMem[i] == pPrior) Debugger.Break();
#endif
mem0.msMem.dealloc++;
if ( mem0.msMem.next < mem0.aMem.Length - 1 )
{
pPrior.db = null;
pPrior._SumCtx = null;
pPrior._MD5Context = null;
pPrior._SubProgram = null;
pPrior.flags = MEM_Null;
pPrior.r = 0;
pPrior.u.i = 0;
pPrior.n = 0;
if ( pPrior.zBLOB != null )
sqlite3MemFree( ref pPrior.zBLOB );
mem0.aMem[++mem0.msMem.next] = pPrior;
if ( mem0.msMem.next > mem0.msMem.max )
mem0.msMem.max = mem0.msMem.next;
}
//Array.Resize( ref mem0.aMem, (int)(mem0.hw_Mem * 1.5 + 1 ));
//mem0.aMem[mem0.hw_Mem] = pPrior;
//mem0.hw_Mem = mem0.aMem.Length;
pPrior = null;
return;
}
static void sqlite3MemFreeBtCursor( ref BtCursor pPrior )
{
if ( pPrior == null )
return;
#if FALSE && DEBUG
for ( int i = mem0.msBtCursor.next - 1; i >= 0; i-- ) if ( mem0.aBtCursor[i] != null && mem0.aBtCursor[i] == pPrior ) Debugger.Break();
#endif
mem0.msBtCursor.dealloc++;
if ( mem0.msBtCursor.next < mem0.aBtCursor.Length - 1 )
{
mem0.aBtCursor[++mem0.msBtCursor.next] = pPrior;
if ( mem0.msBtCursor.next > mem0.msBtCursor.max )
mem0.msBtCursor.max = mem0.msBtCursor.next;
}
//Array.Resize( ref mem0.aBtCursor, (int)(mem0.hw_BtCursor * 1.5 + 1 ));
//mem0.aBtCursor[mem0.hw_BtCursor] = pPrior;
//mem0.hw_BtCursor = mem0.aBtCursor.Length;
pPrior = null;
return;
}
/*
** Like realloc(). Resize an allocation previously obtained from
** sqlite3MemMalloc().
**
** For this low-level interface, we know that pPrior!=0. Cases where
** pPrior==0 while have been intercepted by higher-level routine and
** redirected to xMalloc. Similarly, we know that nByte>0 becauses
** cases where nByte<=0 will have been intercepted by higher-level
** routines and redirected to xFree.
*/
static byte[] sqlite3MemRealloc( ref byte[] pPrior, int nByte )
{
// sqlite3_int64 p = (sqlite3_int64*)pPrior;
// Debug.Assert(pPrior!=0 && nByte>0 );
// nByte = ROUND8( nByte );
// p = (sqlite3_int64*)pPrior;
// p--;
// p = realloc(p, nByte+8 );
// if( p ){
// p[0] = nByte;
// p++;
// }
// return (void*)p;
Array.Resize( ref pPrior, nByte );
return pPrior;
}
#else
/*
** No-op versions of all memory allocation routines
*/
static byte[] sqlite3MemMalloc(int nByte) { return new byte[nByte]; }
static int[] sqlite3MemMallocInt(int nInt) { return new int[nInt]; }
static Mem sqlite3MemMallocMem( Mem pMem) { return new Mem(); }
static void sqlite3MemFree( ref byte[] pPrior ) { pPrior = null; }
static void sqlite3MemFreeInt( ref int[] pPrior ) { pPrior = null; }
static void sqlite3MemFreeMem(ref Mem pPrior) { pPrior = null; }
static int sqlite3MemInit() { return SQLITE_OK; }
static void sqlite3MemShutdown() { }
static BtCursor sqlite3MemMallocBtCursor( BtCursor dummy ){return new BtCursor();}
static void sqlite3MemFreeBtCursor(ref BtCursor pPrior) { pPrior = null; }
#endif
static byte[] sqlite3MemRealloc( byte[] pPrior, int nByte )
{
Array.Resize( ref pPrior, nByte );
return pPrior;
}
/*
** Report the allocated size of a prior return from xMalloc()
** or xRealloc().
*/
static int sqlite3MemSize( byte[] pPrior )
{
// sqlite3_int64 p;
// if( pPrior==0 ) return 0;
// p = (sqlite3_int64*)pPrior;
// p--;
// return p[0];
return pPrior == null ? 0 : (int)pPrior.Length;
}
/*
** Round up a request size to the next valid allocation size.
*/
static int sqlite3MemRoundup( int n )
{
return n;// ROUND8( n );
}
/*
** Initialize this module.
*/
static int sqlite3MemInit( object NotUsed )
{
UNUSED_PARAMETER( NotUsed );
if ( !sqlite3GlobalConfig.bMemstat )
{
/* If memory status is enabled, then the malloc.c wrapper will already
** hold the STATIC_MEM mutex when the routines here are invoked. */
mem0.mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MEM );
}
return SQLITE_OK;
}
/*
** Deinitialize this module.
*/
static void sqlite3MemShutdown( object NotUsed )
{
UNUSED_PARAMETER( NotUsed );
return;
}
/*
** This routine is the only routine in this file with external linkage.
**
** Populate the low-level memory allocation function pointers in
** sqlite3GlobalConfig.m with pointers to the routines in this file.
*/
static void sqlite3MemSetDefault()
{
sqlite3_mem_methods defaultMethods = new sqlite3_mem_methods(
sqlite3MemMalloc,
sqlite3MemMallocInt,
sqlite3MemMallocMem,
sqlite3MemFree,
sqlite3MemFreeInt,
sqlite3MemFreeMem,
sqlite3MemRealloc,
sqlite3MemSize,
sqlite3MemRoundup,
(dxMemInit)sqlite3MemInit,
(dxMemShutdown)sqlite3MemShutdown,
0
);
sqlite3_config( SQLITE_CONFIG_MALLOC, defaultMethods );
}
static void sqlite3DbFree( sqlite3 db, ref int[] pPrior )
{
if ( pPrior != null )
sqlite3MemFreeInt( ref pPrior );
}
static void sqlite3DbFree( sqlite3 db, ref Mem pPrior )
{
if ( pPrior != null )
sqlite3MemFreeMem( ref pPrior );
}
static void sqlite3DbFree( sqlite3 db, ref Mem[] pPrior )
{
if ( pPrior != null )
for ( int i = 0; i < pPrior.Length; i++ )
sqlite3MemFreeMem( ref pPrior[i] );
}
static void sqlite3DbFree<T>( sqlite3 db, ref T pT ) where T : class
{
}
static void sqlite3DbFree( sqlite3 db, ref string pString )
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
namespace System.Management
{
internal class WmiEventSink : IWmiEventSource
{
private static int s_hash = 0;
private int hash;
private ManagementOperationObserver watcher;
private object context;
private ManagementScope scope;
private object stub; // The secured IWbemObjectSink
// Used for Put's only
internal event InternalObjectPutEventHandler InternalObjectPut;
private ManagementPath path;
private string className;
private bool isLocal;
static ManagementOperationObserver watcherParameter;
static object contextParameter;
static ManagementScope scopeParameter;
static string pathParameter;
static string classNameParameter;
static WmiEventSink wmiEventSinkNew;
internal static WmiEventSink GetWmiEventSink(
ManagementOperationObserver watcher,
object context,
ManagementScope scope,
string path,
string className)
{
if(MTAHelper.IsNoContextMTA())
return new WmiEventSink(watcher, context, scope, path, className);
watcherParameter = watcher;
contextParameter = context;
scopeParameter = scope;
pathParameter = path;
classNameParameter = className;
//
// Ensure we are able to trap exceptions from worker thread.
//
ThreadDispatch disp = new ThreadDispatch ( new ThreadDispatch.ThreadWorkerMethod ( HackToCreateWmiEventSink ) ) ;
disp.Start ( ) ;
return wmiEventSinkNew;
}
static void HackToCreateWmiEventSink()
{
wmiEventSinkNew = new WmiEventSink(watcherParameter, contextParameter, scopeParameter, pathParameter, classNameParameter);
}
protected WmiEventSink (ManagementOperationObserver watcher,
object context,
ManagementScope scope,
string path,
string className)
{
try {
this.context = context;
this.watcher = watcher;
this.className = className;
this.isLocal = false;
if (null != path)
{
this.path = new ManagementPath (path);
if((0==String.Compare(this.path.Server, ".", StringComparison.OrdinalIgnoreCase)) ||
(0==String.Compare(this.path.Server, System.Environment.MachineName, StringComparison.OrdinalIgnoreCase)))
{
this.isLocal = true;
}
}
if (null != scope)
{
this.scope = (ManagementScope) scope.Clone ();
if (null == path) // use scope to see if sink is local
{
if((0==String.Compare(this.scope.Path.Server, ".", StringComparison.OrdinalIgnoreCase)) ||
(0==String.Compare(this.scope.Path.Server, System.Environment.MachineName, StringComparison.OrdinalIgnoreCase)))
{
this.isLocal = true;
}
}
}
WmiNetUtilsHelper.GetDemultiplexedStub_f (this, this.isLocal, out stub);
hash = Threading.Interlocked.Increment(ref s_hash);
} catch {}
}
public override int GetHashCode () {
return hash;
}
public IWbemObjectSink Stub {
get {
try {
return (null != stub) ? (IWbemObjectSink) stub : null;
} catch {
return null;
}
}
}
public virtual void Indicate (IntPtr pIWbemClassObject)
{
Marshal.AddRef(pIWbemClassObject);
IWbemClassObjectFreeThreaded obj = new IWbemClassObjectFreeThreaded(pIWbemClassObject);
try {
ObjectReadyEventArgs args = new ObjectReadyEventArgs (context,
ManagementBaseObject.GetBaseObject (obj, scope));
watcher.FireObjectReady (args);
} catch {}
}
public void SetStatus (
int flags,
int hResult,
String message,
IntPtr pErrorObj)
{
IWbemClassObjectFreeThreaded errObj = null;
if(pErrorObj != IntPtr.Zero)
{
Marshal.AddRef(pErrorObj);
errObj = new IWbemClassObjectFreeThreaded(pErrorObj);
}
try {
if (flags == (int) tag_WBEM_STATUS_TYPE.WBEM_STATUS_COMPLETE)
{
// Is this a Put? If so fire the ObjectPut event
if (null != path)
{
if (null == className)
path.RelativePath = message;
else
path.RelativePath = className;
// Fire the internal event (if anyone is interested)
if (null != InternalObjectPut)
{
try {
InternalObjectPutEventArgs iargs = new InternalObjectPutEventArgs (path);
InternalObjectPut (this, iargs);
} catch {}
}
ObjectPutEventArgs args = new ObjectPutEventArgs (context, path);
watcher.FireObjectPut(args);
}
// Fire Completed event
CompletedEventArgs args2 = null ;
if ( errObj != null )
{
args2 = new CompletedEventArgs (context, hResult,
new ManagementBaseObject (errObj)
);
}
else
{
args2 = new CompletedEventArgs (context, hResult,
null
);
}
watcher.FireCompleted (args2);
// Unhook and tidy up
watcher.RemoveSink (this);
}
else if (0 != (flags & (int) tag_WBEM_STATUS_TYPE.WBEM_STATUS_PROGRESS))
{
// Fire Progress event
ProgressEventArgs args = new ProgressEventArgs (context,
(int) (((uint)hResult & 0xFFFF0000) >> 16), hResult & 0xFFFF, message);
watcher.FireProgress (args);
}
} catch {}
}
internal void Cancel ()
{
try {
scope.GetIWbemServices().CancelAsyncCall_((IWbemObjectSink) stub);
} catch {}
}
internal void ReleaseStub ()
{
try {
/*
* We force a release of the stub here so as to allow
* unsecapp.exe to die as soon as possible.
*/
if (null != stub)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(stub);
stub = null;
}
} catch {}
}
}
// Special sink implementation for ManagementObject.Get
// Doesn't issue ObjectReady events
internal class WmiGetEventSink : WmiEventSink
{
private ManagementObject managementObject;
static ManagementOperationObserver watcherParameter;
static object contextParameter;
static ManagementScope scopeParameter;
static ManagementObject managementObjectParameter;
static WmiGetEventSink wmiGetEventSinkNew;
internal static WmiGetEventSink GetWmiGetEventSink(
ManagementOperationObserver watcher,
object context,
ManagementScope scope,
ManagementObject managementObject)
{
if(MTAHelper.IsNoContextMTA())
return new WmiGetEventSink(watcher, context, scope, managementObject);
watcherParameter = watcher;
contextParameter = context;
scopeParameter = scope;
managementObjectParameter = managementObject;
//
// Ensure we are able to trap exceptions from worker thread.
//
ThreadDispatch disp = new ThreadDispatch ( new ThreadDispatch.ThreadWorkerMethod ( HackToCreateWmiGetEventSink ) ) ;
disp.Start ( ) ;
return wmiGetEventSinkNew;
}
static void HackToCreateWmiGetEventSink()
{
wmiGetEventSinkNew = new WmiGetEventSink(watcherParameter, contextParameter, scopeParameter, managementObjectParameter);
}
private WmiGetEventSink (ManagementOperationObserver watcher,
object context,
ManagementScope scope,
ManagementObject managementObject) :
base (watcher, context, scope, null, null)
{
this.managementObject = managementObject;
}
public override void Indicate (IntPtr pIWbemClassObject)
{
Marshal.AddRef(pIWbemClassObject);
IWbemClassObjectFreeThreaded obj = new IWbemClassObjectFreeThreaded(pIWbemClassObject);
if (null != managementObject)
{
try {
managementObject.wbemObject = obj;
} catch {}
}
}
}
}
| |
#region license
// Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * 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 Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Text.RegularExpressions;
using System.Globalization;
using System.IO;
using System.Collections.Generic;
namespace Boo.Lang.Compiler.Ast.Visitors
{
/// <summary>
/// </summary>
public class BooPrinterVisitor : TextEmitter
{
[Flags]
public enum PrintOptions
{
None,
PrintLocals = 1,
WSA = 2,
}
public PrintOptions Options = PrintOptions.None;
public BooPrinterVisitor(TextWriter writer) : base(writer)
{
}
public BooPrinterVisitor(TextWriter writer, PrintOptions options) : this(writer)
{
this.Options = options;
}
public bool IsOptionSet(PrintOptions option)
{
return (option & Options) == option;
}
public void Print(CompileUnit ast)
{
OnCompileUnit(ast);
}
#region overridables
public virtual void WriteKeyword(string text)
{
Write(text);
}
public virtual void WriteOperator(string text)
{
Write(text);
}
#endregion
#region IAstVisitor Members
override public void OnModule(Module m)
{
Visit(m.Namespace);
if (m.Imports.Count > 0)
{
Visit(m.Imports);
WriteLine();
}
foreach (var member in m.Members)
{
Visit(member);
WriteLine();
}
if (m.Globals != null)
Visit(m.Globals.Statements);
foreach (var attribute in m.Attributes)
WriteModuleAttribute(attribute);
foreach (var attribute in m.AssemblyAttributes)
WriteAssemblyAttribute(attribute);
}
private void WriteModuleAttribute(Attribute attribute)
{
WriteAttribute(attribute, "module: ");
WriteLine();
}
private void WriteAssemblyAttribute(Attribute attribute)
{
WriteAttribute(attribute, "assembly: ");
WriteLine();
}
override public void OnNamespaceDeclaration(NamespaceDeclaration node)
{
WriteKeyword("namespace");
WriteLine(" {0}", node.Name);
WriteLine();
}
static bool IsExtendedRE(string s)
{
return s.IndexOfAny(new char[] { ' ', '\t' }) > -1;
}
static bool CanBeRepresentedAsQualifiedName(string s)
{
foreach (char ch in s)
if (!char.IsLetterOrDigit(ch) && ch != '_' && ch != '.')
return false;
return true;
}
override public void OnImport(Import p)
{
WriteKeyword("import");
Write(" {0}", p.Namespace);
if (null != p.AssemblyReference)
{
WriteKeyword(" from ");
var assemblyRef = p.AssemblyReference.Name;
if (CanBeRepresentedAsQualifiedName(assemblyRef))
Write(assemblyRef);
else
WriteStringLiteral(assemblyRef);
}
if (p.Expression.NodeType == NodeType.MethodInvocationExpression)
{
MethodInvocationExpression mie = (MethodInvocationExpression)p.Expression;
Write("(");
WriteCommaSeparatedList(mie.Arguments);
Write(")");
}
if (null != p.Alias)
{
WriteKeyword(" as ");
Write(p.Alias.Name);
}
WriteLine();
}
public bool IsWhiteSpaceAgnostic
{
get { return IsOptionSet(PrintOptions.WSA); }
}
private void WritePass()
{
if (!IsWhiteSpaceAgnostic)
{
WriteIndented();
WriteKeyword("pass");
WriteLine();
}
}
private void WriteBlockStatements(Block b)
{
if (b.IsEmpty)
{
WritePass();
}
else
{
Visit(b.Statements);
}
}
public void WriteBlock(Block b)
{
BeginBlock();
WriteBlockStatements(b);
EndBlock();
}
private void BeginBlock()
{
Indent();
}
private void EndBlock()
{
Dedent();
if (IsWhiteSpaceAgnostic)
{
WriteEnd();
}
}
private void WriteEnd()
{
WriteIndented();
WriteKeyword("end");
WriteLine();
}
override public void OnAttribute(Attribute att)
{
WriteAttribute(att);
}
override public void OnClassDefinition(ClassDefinition c)
{
WriteTypeDefinition("class", c);
}
override public void OnStructDefinition(StructDefinition node)
{
WriteTypeDefinition("struct", node);
}
override public void OnInterfaceDefinition(InterfaceDefinition id)
{
WriteTypeDefinition("interface", id);
}
override public void OnEnumDefinition(EnumDefinition ed)
{
WriteTypeDefinition("enum", ed);
}
override public void OnEvent(Event node)
{
WriteAttributes(node.Attributes, true);
WriteOptionalModifiers(node);
WriteKeyword("event ");
Write(node.Name);
WriteTypeReference(node.Type);
WriteLine();
}
private static bool IsInterfaceMember(TypeMember node)
{
return node.ParentNode != null && node.ParentNode.NodeType == NodeType.InterfaceDefinition;
}
override public void OnField(Field f)
{
WriteAttributes(f.Attributes, true);
WriteModifiers(f);
Write(f.Name);
WriteTypeReference(f.Type);
if (null != f.Initializer)
{
WriteOperator(" = ");
Visit(f.Initializer);
}
WriteLine();
}
override public void OnExplicitMemberInfo(ExplicitMemberInfo node)
{
Visit(node.InterfaceType);
Write(".");
}
override public void OnProperty(Property node)
{
bool interfaceMember = IsInterfaceMember(node);
WriteAttributes(node.Attributes, true);
WriteOptionalModifiers(node);
WriteIndented("");
Visit(node.ExplicitInfo);
Write(node.Name);
if (node.Parameters.Count > 0)
{
WriteParameterList(node.Parameters, "[", "]");
}
WriteTypeReference(node.Type);
WriteLine(":");
BeginBlock();
WritePropertyAccessor(node.Getter, "get", interfaceMember);
WritePropertyAccessor(node.Setter, "set", interfaceMember);
EndBlock();
}
private void WritePropertyAccessor(Method method, string name, bool interfaceMember)
{
if (null == method) return;
WriteAttributes(method.Attributes, true);
if (interfaceMember)
{
WriteIndented();
}
else
{
WriteModifiers(method);
}
WriteKeyword(name);
if (interfaceMember)
{
WriteLine();
}
else
{
WriteLine(":");
WriteBlock(method.Body);
}
}
override public void OnEnumMember(EnumMember node)
{
WriteAttributes(node.Attributes, true);
WriteIndented(node.Name);
if (null != node.Initializer)
{
WriteOperator(" = ");
Visit(node.Initializer);
}
WriteLine();
}
override public void OnConstructor(Constructor c)
{
OnMethod(c);
}
override public void OnDestructor(Destructor c)
{
OnMethod(c);
}
bool IsSimpleClosure(BlockExpression node)
{
switch (node.Body.Statements.Count)
{
case 0:
return true;
case 1:
switch (node.Body.Statements[0].NodeType)
{
case NodeType.IfStatement:
return false;
case NodeType.WhileStatement:
return false;
case NodeType.ForStatement:
return false;
}
return true;
}
return false;
}
override public void OnBlockExpression(BlockExpression node)
{
if (IsSimpleClosure(node))
{
DisableNewLine();
Write("{ ");
if (node.Parameters.Count > 0)
{
WriteCommaSeparatedList(node.Parameters);
Write(" | ");
}
if (node.Body.IsEmpty)
Write("return");
else
Visit(node.Body.Statements);
Write(" }");
EnableNewLine();
}
else
{
WriteKeyword("def ");
WriteParameterList(node.Parameters);
WriteTypeReference(node.ReturnType);
WriteLine(":");
WriteBlock(node.Body);
}
}
void WriteCallableDefinitionHeader(string keyword, CallableDefinition node)
{
WriteAttributes(node.Attributes, true);
WriteOptionalModifiers(node);
WriteKeyword(keyword);
IExplicitMember em = node as IExplicitMember;
if (null != em)
{
Visit(em.ExplicitInfo);
}
Write(node.Name);
if (node.GenericParameters.Count > 0)
{
WriteGenericParameterList(node.GenericParameters);
}
WriteParameterList(node.Parameters);
if (node.ReturnTypeAttributes.Count > 0)
{
Write(" ");
WriteAttributes(node.ReturnTypeAttributes, false);
}
WriteTypeReference(node.ReturnType);
}
private void WriteOptionalModifiers(TypeMember node)
{
if (IsInterfaceMember(node))
{
WriteIndented();
}
else
{
WriteModifiers(node);
}
}
override public void OnCallableDefinition(CallableDefinition node)
{
WriteCallableDefinitionHeader("callable ", node);
}
override public void OnMethod(Method m)
{
if (m.IsRuntime) WriteImplementationComment("runtime");
WriteCallableDefinitionHeader("def ", m);
if (IsInterfaceMember(m))
{
WriteLine();
}
else
{
WriteLine(":");
WriteLocals(m);
WriteBlock(m.Body);
}
}
private void WriteImplementationComment(string comment)
{
WriteIndented("// {0}", comment);
WriteLine();
}
public override void OnLocal(Local node)
{
WriteIndented("// Local {0}, {1}, PrivateScope: {2}", node.Name, node.Entity, node.PrivateScope);
WriteLine();
}
void WriteLocals(Method m)
{
if (!IsOptionSet(PrintOptions.PrintLocals)) return;
Visit(m.Locals);
}
void WriteTypeReference(TypeReference t)
{
if (null != t)
{
WriteKeyword(" as ");
Visit(t);
}
}
override public void OnParameterDeclaration(ParameterDeclaration p)
{
WriteAttributes(p.Attributes, false);
if (p.IsByRef)
WriteKeyword("ref ");
if (IsCallableTypeReferenceParameter(p))
{
if (p.IsParamArray) Write("*");
Visit(p.Type);
}
else
{
Write(p.Name);
WriteTypeReference(p.Type);
}
}
private static bool IsCallableTypeReferenceParameter(ParameterDeclaration p)
{
var parentNode = p.ParentNode;
return parentNode != null && parentNode.NodeType == NodeType.CallableTypeReference;
}
override public void OnGenericParameterDeclaration(GenericParameterDeclaration gp)
{
Write(gp.Name);
if (gp.BaseTypes.Count > 0 || gp.Constraints != GenericParameterConstraints.None)
{
Write("(");
WriteCommaSeparatedList(gp.BaseTypes);
if (gp.Constraints != GenericParameterConstraints.None)
{
if (gp.BaseTypes.Count != 0)
{
Write(", ");
}
WriteGenericParameterConstraints(gp.Constraints);
}
Write(")");
}
}
private void WriteGenericParameterConstraints(GenericParameterConstraints constraints)
{
List<string> constraintStrings = new List<string>();
if ((constraints & GenericParameterConstraints.ReferenceType) != GenericParameterConstraints.None)
{
constraintStrings.Add("class");
}
if ((constraints & GenericParameterConstraints.ValueType) != GenericParameterConstraints.None)
{
constraintStrings.Add("struct");
}
if ((constraints & GenericParameterConstraints.Constructable) != GenericParameterConstraints.None)
{
constraintStrings.Add("constructor");
}
Write(string.Join(", ", constraintStrings.ToArray()));
}
private KeyValuePair<T, string> CreateTranslation<T>(T value, string translation)
{
return new KeyValuePair<T, string>(value, translation);
}
override public void OnTypeofExpression(TypeofExpression node)
{
Write("typeof(");
Visit(node.Type);
Write(")");
}
override public void OnSimpleTypeReference(SimpleTypeReference t)
{
Write(t.Name);
}
override public void OnGenericTypeReference(GenericTypeReference node)
{
OnSimpleTypeReference(node);
WriteGenericArguments(node.GenericArguments);
}
override public void OnGenericTypeDefinitionReference(GenericTypeDefinitionReference node)
{
OnSimpleTypeReference(node);
Write("[of *");
for (int i = 1; i < node.GenericPlaceholders; i++)
{
Write(", *");
}
Write("]");
}
override public void OnGenericReferenceExpression(GenericReferenceExpression node)
{
Visit(node.Target);
WriteGenericArguments(node.GenericArguments);
}
void WriteGenericArguments(TypeReferenceCollection arguments)
{
Write("[of ");
WriteCommaSeparatedList(arguments);
Write("]");
}
override public void OnArrayTypeReference(ArrayTypeReference t)
{
Write("(");
Visit(t.ElementType);
if (null != t.Rank && t.Rank.Value > 1)
{
Write(", ");
t.Rank.Accept(this);
}
Write(")");
}
override public void OnCallableTypeReference(CallableTypeReference node)
{
Write("callable(");
WriteCommaSeparatedList(node.Parameters);
Write(")");
WriteTypeReference(node.ReturnType);
}
override public void OnMemberReferenceExpression(MemberReferenceExpression e)
{
Visit(e.Target);
Write(".");
Write(e.Name);
}
override public void OnTryCastExpression(TryCastExpression e)
{
Write("(");
Visit(e.Target);
WriteTypeReference(e.Type);
Write(")");
}
override public void OnCastExpression(CastExpression node)
{
Write("(");
Visit(node.Target);
WriteKeyword(" cast ");
Visit(node.Type);
Write(")");
}
override public void OnNullLiteralExpression(NullLiteralExpression node)
{
WriteKeyword("null");
}
override public void OnSelfLiteralExpression(SelfLiteralExpression node)
{
WriteKeyword("self");
}
override public void OnSuperLiteralExpression(SuperLiteralExpression node)
{
WriteKeyword("super");
}
override public void OnTimeSpanLiteralExpression(TimeSpanLiteralExpression node)
{
WriteTimeSpanLiteral(node.Value, _writer);
}
override public void OnBoolLiteralExpression(BoolLiteralExpression node)
{
if (node.Value)
{
WriteKeyword("true");
}
else
{
WriteKeyword("false");
}
}
override public void OnUnaryExpression(UnaryExpression node)
{
bool addParens = NeedParensAround(node) && !IsMethodInvocationArg(node) && node.Operator != UnaryOperatorType.SafeAccess;
if (addParens)
{
Write("(");
}
bool postOperator = AstUtil.IsPostUnaryOperator(node.Operator);
if (!postOperator)
{
WriteOperator(GetUnaryOperatorText(node.Operator));
}
Visit(node.Operand);
if (postOperator)
{
WriteOperator(GetUnaryOperatorText(node.Operator));
}
if (addParens)
{
Write(")");
}
}
private bool IsMethodInvocationArg(UnaryExpression node)
{
MethodInvocationExpression parent = node.ParentNode as MethodInvocationExpression;
return null != parent && node != parent.Target;
}
override public void OnConditionalExpression(ConditionalExpression e)
{
Write("(");
Visit(e.TrueValue);
WriteKeyword(" if ");
Visit(e.Condition);
WriteKeyword(" else ");
Visit(e.FalseValue);
Write(")");
}
bool NeedParensAround(Expression e)
{
if (e.ParentNode == null) return false;
switch (e.ParentNode.NodeType)
{
case NodeType.ExpressionStatement:
case NodeType.MacroStatement:
case NodeType.IfStatement:
case NodeType.WhileStatement:
case NodeType.UnlessStatement:
return false;
}
return true;
}
override public void OnBinaryExpression(BinaryExpression e)
{
bool needsParens = NeedParensAround(e);
if (needsParens)
{
Write("(");
}
Visit(e.Left);
Write(" ");
WriteOperator(GetBinaryOperatorText(e.Operator));
Write(" ");
if (e.Operator == BinaryOperatorType.TypeTest)
{
// isa rhs is encoded in a typeof expression
Visit(((TypeofExpression)e.Right).Type);
}
else
{
Visit(e.Right);
}
if (needsParens)
{
Write(")");
}
}
override public void OnRaiseStatement(RaiseStatement rs)
{
WriteIndented();
WriteKeyword("raise ");
Visit(rs.Exception);
Visit(rs.Modifier);
WriteLine();
}
override public void OnMethodInvocationExpression(MethodInvocationExpression e)
{
Visit(e.Target);
Write("(");
WriteCommaSeparatedList(e.Arguments);
if (e.NamedArguments.Count > 0)
{
if (e.Arguments.Count > 0)
{
Write(", ");
}
WriteCommaSeparatedList(e.NamedArguments);
}
Write(")");
}
override public void OnArrayLiteralExpression(ArrayLiteralExpression node)
{
WriteArray(node.Items, node.Type);
}
override public void OnListLiteralExpression(ListLiteralExpression node)
{
WriteDelimitedCommaSeparatedList("[", node.Items, "]");
}
private void WriteDelimitedCommaSeparatedList(string opening, IEnumerable<Expression> list, string closing)
{
Write(opening);
WriteCommaSeparatedList(list);
Write(closing);
}
public override void OnCollectionInitializationExpression(CollectionInitializationExpression node)
{
Visit(node.Collection);
Write(" ");
if (node.Initializer is ListLiteralExpression)
WriteDelimitedCommaSeparatedList("{ ", ((ListLiteralExpression) node.Initializer).Items, " }");
else
Visit(node.Initializer);
}
override public void OnGeneratorExpression(GeneratorExpression node)
{
Write("(");
Visit(node.Expression);
WriteGeneratorExpressionBody(node);
Write(")");
}
void WriteGeneratorExpressionBody(GeneratorExpression node)
{
WriteKeyword(" for ");
WriteCommaSeparatedList(node.Declarations);
WriteKeyword(" in ");
Visit(node.Iterator);
Visit(node.Filter);
}
override public void OnExtendedGeneratorExpression(ExtendedGeneratorExpression node)
{
Write("(");
Visit(node.Items[0].Expression);
for (int i=0; i<node.Items.Count; ++i)
{
WriteGeneratorExpressionBody(node.Items[i]);
}
Write(")");
}
override public void OnSlice(Slice node)
{
Visit(node.Begin);
if (null != node.End || WasOmitted(node.Begin))
{
Write(":");
}
Visit(node.End);
if (null != node.Step)
{
Write(":");
Visit(node.Step);
}
}
override public void OnSlicingExpression(SlicingExpression node)
{
Visit(node.Target);
Write("[");
WriteCommaSeparatedList(node.Indices);
Write("]");
}
override public void OnHashLiteralExpression(HashLiteralExpression node)
{
Write("{");
if (node.Items.Count > 0)
{
Write(" ");
WriteCommaSeparatedList(node.Items);
Write(" ");
}
Write("}");
}
override public void OnExpressionPair(ExpressionPair pair)
{
Visit(pair.First);
Write(": ");
Visit(pair.Second);
}
override public void OnRELiteralExpression(RELiteralExpression e)
{
if (IsExtendedRE(e.Value))
{
Write("@");
}
Write(e.Value);
}
override public void OnSpliceExpression(SpliceExpression e)
{
WriteSplicedExpression(e.Expression);
}
private void WriteSplicedExpression(Expression expression)
{
WriteOperator("$(");
Visit(expression);
WriteOperator(")");
}
public override void OnStatementTypeMember(StatementTypeMember node)
{
WriteModifiers(node);
Visit(node.Statement);
}
public override void OnSpliceTypeMember(SpliceTypeMember node)
{
WriteIndented();
Visit(node.TypeMember);
WriteLine();
}
public override void OnSpliceTypeDefinitionBody(SpliceTypeDefinitionBody node)
{
WriteIndented();
WriteSplicedExpression(node.Expression);
WriteLine();
}
override public void OnSpliceTypeReference(SpliceTypeReference node)
{
WriteSplicedExpression(node.Expression);
}
void WriteIndentedOperator(string op)
{
WriteIndented();
WriteOperator(op);
}
override public void OnQuasiquoteExpression(QuasiquoteExpression e)
{
WriteIndentedOperator("[|");
if (e.Node is Expression)
{
Write(" ");
Visit(e.Node);
Write(" ");
WriteIndentedOperator("|]");
}
else
{
WriteLine();
Indent();
Visit(e.Node);
Dedent();
WriteIndentedOperator("|]");
WriteLine();
}
}
override public void OnStringLiteralExpression(StringLiteralExpression e)
{
if (e != null && e.Value != null)
WriteStringLiteral(e.Value);
else
WriteKeyword("null");
}
override public void OnCharLiteralExpression(CharLiteralExpression e)
{
WriteKeyword("char");
Write("(");
WriteStringLiteral(e.Value);
Write(")");
}
override public void OnIntegerLiteralExpression(IntegerLiteralExpression e)
{
Write(e.Value.ToString());
if (e.IsLong)
{
Write("L");
}
}
override public void OnDoubleLiteralExpression(DoubleLiteralExpression e)
{
Write(e.Value.ToString("########0.0##########", CultureInfo.InvariantCulture));
if (e.IsSingle)
{
Write("F");
}
}
override public void OnReferenceExpression(ReferenceExpression node)
{
Write(node.Name);
}
override public void OnExpressionStatement(ExpressionStatement node)
{
WriteIndented();
Visit(node.Expression);
Visit(node.Modifier);
WriteLine();
}
override public void OnExpressionInterpolationExpression(ExpressionInterpolationExpression node)
{
Write("\"");
foreach (var arg in node.Expressions)
{
switch (arg.NodeType)
{
case NodeType.StringLiteralExpression:
WriteStringLiteralContents(((StringLiteralExpression)arg).Value, _writer, false);
break;
case NodeType.ReferenceExpression:
case NodeType.BinaryExpression:
Write("$");
Visit(arg);
break;
default:
Write("$(");
Visit(arg);
Write(")");
break;
}
}
Write("\"");
}
override public void OnStatementModifier(StatementModifier sm)
{
Write(" ");
WriteKeyword(sm.Type.ToString().ToLower());
Write(" ");
Visit(sm.Condition);
}
override public void OnLabelStatement(LabelStatement node)
{
WriteIndented(":");
WriteLine(node.Name);
}
override public void OnGotoStatement(GotoStatement node)
{
WriteIndented();
WriteKeyword("goto ");
Visit(node.Label);
Visit(node.Modifier);
WriteLine();
}
override public void OnMacroStatement(MacroStatement node)
{
WriteIndented(node.Name);
Write(" ");
WriteCommaSeparatedList(node.Arguments);
if (!node.Body.IsEmpty)
{
WriteLine(":");
WriteBlock(node.Body);
}
else
{
Visit(node.Modifier);
WriteLine();
}
}
override public void OnForStatement(ForStatement fs)
{
WriteIndented();
WriteKeyword("for ");
for (int i=0; i<fs.Declarations.Count; ++i)
{
if (i > 0) { Write(", "); }
Visit(fs.Declarations[i]);
}
WriteKeyword(" in ");
Visit(fs.Iterator);
WriteLine(":");
WriteBlock(fs.Block);
if(fs.OrBlock != null)
{
WriteIndented();
WriteKeyword("or:");
WriteLine();
WriteBlock(fs.OrBlock);
}
if(fs.ThenBlock != null)
{
WriteIndented();
WriteKeyword("then:");
WriteLine();
WriteBlock(fs.ThenBlock);
}
}
override public void OnTryStatement(TryStatement node)
{
WriteIndented();
WriteKeyword("try:");
WriteLine();
Indent();
WriteBlockStatements(node.ProtectedBlock);
Dedent();
Visit(node.ExceptionHandlers);
if (null != node.FailureBlock)
{
WriteIndented();
WriteKeyword("failure:");
WriteLine();
Indent();
WriteBlockStatements(node.FailureBlock);
Dedent();
}
if (null != node.EnsureBlock)
{
WriteIndented();
WriteKeyword("ensure:");
WriteLine();
Indent();
WriteBlockStatements(node.EnsureBlock);
Dedent();
}
if(IsWhiteSpaceAgnostic)
{
WriteEnd();
}
}
override public void OnExceptionHandler(ExceptionHandler node)
{
WriteIndented();
WriteKeyword("except");
if ((node.Flags & ExceptionHandlerFlags.Untyped) == ExceptionHandlerFlags.None)
{
if((node.Flags & ExceptionHandlerFlags.Anonymous) == ExceptionHandlerFlags.None)
{
Write(" ");
Visit(node.Declaration);
}
else
{
WriteTypeReference(node.Declaration.Type);
}
}
else if((node.Flags & ExceptionHandlerFlags.Anonymous) == ExceptionHandlerFlags.None)
{
Write(" ");
Write(node.Declaration.Name);
}
if((node.Flags & ExceptionHandlerFlags.Filter) == ExceptionHandlerFlags.Filter)
{
UnaryExpression unless = node.FilterCondition as UnaryExpression;
if(unless != null && unless.Operator == UnaryOperatorType.LogicalNot)
{
WriteKeyword(" unless ");
Visit(unless.Operand);
}
else
{
WriteKeyword(" if ");
Visit(node.FilterCondition);
}
}
WriteLine(":");
Indent();
WriteBlockStatements(node.Block);
Dedent();
}
override public void OnUnlessStatement(UnlessStatement node)
{
WriteConditionalBlock("unless", node.Condition, node.Block);
}
override public void OnBreakStatement(BreakStatement node)
{
WriteIndented();
WriteKeyword("break ");
Visit(node.Modifier);
WriteLine();
}
override public void OnContinueStatement(ContinueStatement node)
{
WriteIndented();
WriteKeyword("continue ");
Visit(node.Modifier);
WriteLine();
}
override public void OnYieldStatement(YieldStatement node)
{
WriteIndented();
WriteKeyword("yield ");
Visit(node.Expression);
Visit(node.Modifier);
WriteLine();
}
override public void OnWhileStatement(WhileStatement node)
{
WriteConditionalBlock("while", node.Condition, node.Block);
if(node.OrBlock != null)
{
WriteIndented();
WriteKeyword("or:");
WriteLine();
WriteBlock(node.OrBlock);
}
if(node.ThenBlock != null)
{
WriteIndented();
WriteKeyword("then:");
WriteLine();
WriteBlock(node.ThenBlock);
}
}
override public void OnIfStatement(IfStatement node)
{
WriteIfBlock("if ", node);
Block elseBlock = WriteElifs(node);
if (null != elseBlock)
{
WriteIndented();
WriteKeyword("else:");
WriteLine();
WriteBlock(elseBlock);
}
else
{
if (IsWhiteSpaceAgnostic)
{
WriteEnd();
}
}
}
private Block WriteElifs(IfStatement node)
{
Block falseBlock = node.FalseBlock;
while (IsElif(falseBlock))
{
IfStatement stmt = (IfStatement) falseBlock.Statements[0];
WriteIfBlock("elif ", stmt);
falseBlock = stmt.FalseBlock;
}
return falseBlock;
}
private void WriteIfBlock(string keyword, IfStatement ifs)
{
WriteIndented();
WriteKeyword(keyword);
Visit(ifs.Condition);
WriteLine(":");
Indent();
WriteBlockStatements(ifs.TrueBlock);
Dedent();
}
private static bool IsElif(Block block)
{
if (block == null) return false;
if (block.Statements.Count != 1) return false;
return block.Statements[0] is IfStatement;
}
override public void OnDeclarationStatement(DeclarationStatement d)
{
WriteIndented();
Visit(d.Declaration);
if (null != d.Initializer)
{
WriteOperator(" = ");
Visit(d.Initializer);
}
WriteLine();
}
override public void OnDeclaration(Declaration d)
{
Write(d.Name);
WriteTypeReference(d.Type);
}
override public void OnReturnStatement(ReturnStatement r)
{
WriteIndented();
WriteKeyword("return");
if (r.Expression != null || r.Modifier != null)
Write(" ");
Visit(r.Expression);
Visit(r.Modifier);
WriteLine();
}
override public void OnUnpackStatement(UnpackStatement us)
{
WriteIndented();
for (int i=0; i<us.Declarations.Count; ++i)
{
if (i > 0)
{
Write(", ");
}
Visit(us.Declarations[i]);
}
WriteOperator(" = ");
Visit(us.Expression);
Visit(us.Modifier);
WriteLine();
}
#endregion
public static string GetUnaryOperatorText(UnaryOperatorType op)
{
switch (op)
{
case UnaryOperatorType.Explode:
{
return "*";
}
case UnaryOperatorType.PostIncrement:
case UnaryOperatorType.Increment:
return "++";
case UnaryOperatorType.PostDecrement:
case UnaryOperatorType.Decrement:
return "--";
case UnaryOperatorType.UnaryNegation:
return "-";
case UnaryOperatorType.LogicalNot:
return "not ";
case UnaryOperatorType.OnesComplement:
return "~";
case UnaryOperatorType.AddressOf:
return "&";
case UnaryOperatorType.Indirection:
return "*";
case UnaryOperatorType.SafeAccess:
return "?";
}
throw new ArgumentException("op");
}
public static string GetBinaryOperatorText(BinaryOperatorType op)
{
switch (op)
{
case BinaryOperatorType.Assign:
return "=";
case BinaryOperatorType.Match:
return "=~";
case BinaryOperatorType.NotMatch:
return "!~";
case BinaryOperatorType.Equality:
return "==";
case BinaryOperatorType.Inequality:
return "!=";
case BinaryOperatorType.Addition:
return "+";
case BinaryOperatorType.Exponentiation:
return "**";
case BinaryOperatorType.InPlaceAddition:
return "+=";
case BinaryOperatorType.InPlaceBitwiseAnd:
return "&=";
case BinaryOperatorType.InPlaceBitwiseOr:
return "|=";
case BinaryOperatorType.InPlaceSubtraction:
return "-=";
case BinaryOperatorType.InPlaceMultiply:
return "*=";
case BinaryOperatorType.InPlaceModulus:
return "%=";
case BinaryOperatorType.InPlaceExclusiveOr:
return "^=";
case BinaryOperatorType.InPlaceDivision:
return "/=";
case BinaryOperatorType.Subtraction:
return "-";
case BinaryOperatorType.Multiply:
return "*";
case BinaryOperatorType.Division:
return "/";
case BinaryOperatorType.GreaterThan:
return ">";
case BinaryOperatorType.GreaterThanOrEqual:
return ">=";
case BinaryOperatorType.LessThan:
return "<";
case BinaryOperatorType.LessThanOrEqual:
return "<=";
case BinaryOperatorType.Modulus:
return "%";
case BinaryOperatorType.Member:
return "in";
case BinaryOperatorType.NotMember:
return "not in";
case BinaryOperatorType.ReferenceEquality:
return "is";
case BinaryOperatorType.ReferenceInequality:
return "is not";
case BinaryOperatorType.TypeTest:
return "isa";
case BinaryOperatorType.Or:
return "or";
case BinaryOperatorType.And:
return "and";
case BinaryOperatorType.BitwiseOr:
return "|";
case BinaryOperatorType.BitwiseAnd:
return "&";
case BinaryOperatorType.ExclusiveOr:
return "^";
case BinaryOperatorType.ShiftLeft:
return "<<";
case BinaryOperatorType.ShiftRight:
return ">>";
case BinaryOperatorType.InPlaceShiftLeft:
return "<<=";
case BinaryOperatorType.InPlaceShiftRight:
return ">>=";
}
throw new NotImplementedException(op.ToString());
}
public virtual void WriteStringLiteral(string text)
{
WriteStringLiteral(text, _writer);
}
public static void WriteTimeSpanLiteral(TimeSpan value, TextWriter writer)
{
double days = value.TotalDays;
if (days >= 1)
{
writer.Write(days.ToString(CultureInfo.InvariantCulture) + "d");
}
else
{
double hours = value.TotalHours;
if (hours >= 1)
{
writer.Write(hours.ToString(CultureInfo.InvariantCulture) + "h");
}
else
{
double minutes = value.TotalMinutes;
if (minutes >= 1)
{
writer.Write(minutes.ToString(CultureInfo.InvariantCulture) + "m");
}
else
{
double seconds = value.TotalSeconds;
if (seconds >= 1)
{
writer.Write(seconds.ToString(CultureInfo.InvariantCulture) + "s");
}
else
{
writer.Write(value.TotalMilliseconds.ToString(CultureInfo.InvariantCulture) + "ms");
}
}
}
}
}
public static void WriteStringLiteral(string text, TextWriter writer)
{
writer.Write("'");
WriteStringLiteralContents(text, writer);
writer.Write("'");
}
public static void WriteStringLiteralContents(string text, TextWriter writer)
{
WriteStringLiteralContents(text, writer, true);
}
public static void WriteStringLiteralContents(string text, TextWriter writer, bool single)
{
foreach (char ch in text)
{
switch (ch)
{
case '\r':
{
writer.Write("\\r");
break;
}
case '\n':
{
writer.Write("\\n");
break;
}
case '\t':
{
writer.Write("\\t");
break;
}
case '\\':
{
writer.Write("\\\\");
break;
}
case '\a':
{
writer.Write(@"\a");
break;
}
case '\b':
{
writer.Write(@"\b");
break;
}
case '\f':
{
writer.Write(@"\f");
break;
}
case '\0':
{
writer.Write(@"\0");
break;
}
case '\'':
{
if (single)
{
writer.Write("\\'");
}
else
{
writer.Write(ch);
}
break;
}
case '"':
{
if (!single)
{
writer.Write("\\\"");
}
else
{
writer.Write(ch);
}
break;
}
default:
{
writer.Write(ch);
break;
}
}
}
}
void WriteConditionalBlock(string keyword, Expression condition, Block block)
{
WriteIndented();
WriteKeyword(keyword + " ");
Visit(condition);
WriteLine(":");
WriteBlock(block);
}
void WriteParameterList(ParameterDeclarationCollection items)
{
WriteParameterList(items, "(", ")");
}
void WriteParameterList(ParameterDeclarationCollection items, string st, string ed)
{
Write(st);
int i = 0;
foreach (ParameterDeclaration item in items)
{
if (i > 0)
{
Write(", ");
}
if (item.IsParamArray)
{
Write("*");
}
Visit(item);
++i;
}
Write(ed);
}
void WriteGenericParameterList(GenericParameterDeclarationCollection items)
{
Write("[of ");
WriteCommaSeparatedList(items);
Write("]");
}
void WriteAttribute(Attribute attribute)
{
WriteAttribute(attribute, null);
}
void WriteAttribute(Attribute attribute, string prefix)
{
WriteIndented("[");
if (null != prefix)
{
Write(prefix);
}
Write(attribute.Name);
if (attribute.Arguments.Count > 0 ||
attribute.NamedArguments.Count > 0)
{
Write("(");
WriteCommaSeparatedList(attribute.Arguments);
if (attribute.NamedArguments.Count > 0)
{
if (attribute.Arguments.Count > 0)
{
Write(", ");
}
WriteCommaSeparatedList(attribute.NamedArguments);
}
Write(")");
}
Write("]");
}
void WriteAttributes(AttributeCollection attributes, bool addNewLines)
{
foreach (Boo.Lang.Compiler.Ast.Attribute attribute in attributes)
{
Visit(attribute);
if (addNewLines)
{
WriteLine();
}
else
{
Write(" ");
}
}
}
void WriteModifiers(TypeMember member)
{
WriteIndented();
if (member.IsPartial)
WriteKeyword("partial ");
if (member.IsPublic)
WriteKeyword("public ");
else if (member.IsProtected)
WriteKeyword("protected ");
else if (member.IsPrivate)
WriteKeyword("private ");
else if (member.IsInternal)
WriteKeyword("internal ");
if (member.IsStatic)
WriteKeyword("static ");
else if (member.IsOverride)
WriteKeyword("override ");
else if (member.IsModifierSet(TypeMemberModifiers.Virtual))
WriteKeyword("virtual ");
else if (member.IsModifierSet(TypeMemberModifiers.Abstract))
WriteKeyword("abstract ");
if (member.IsFinal)
WriteKeyword("final ");
if (member.IsNew)
WriteKeyword("new ");
if (member.HasTransientModifier)
WriteKeyword("transient ");
}
virtual protected void WriteTypeDefinition(string keyword, TypeDefinition td)
{
WriteAttributes(td.Attributes, true);
WriteModifiers(td);
WriteIndented();
WriteKeyword(keyword);
Write(" ");
var splice = td.ParentNode as SpliceTypeMember;
if (splice != null)
WriteSplicedExpression(splice.NameExpression);
else
Write(td.Name);
if (td.GenericParameters.Count != 0)
{
WriteGenericParameterList(td.GenericParameters);
}
if (td.BaseTypes.Count > 0)
{
Write("(");
WriteCommaSeparatedList<TypeReference>(td.BaseTypes);
Write(")");
}
WriteLine(":");
BeginBlock();
if (td.Members.Count > 0)
{
foreach (TypeMember member in td.Members)
{
WriteLine();
Visit(member);
}
}
else
{
WritePass();
}
EndBlock();
}
bool WasOmitted(Expression node)
{
return null != node &&
NodeType.OmittedExpression == node.NodeType;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace Lucene.Net.Search
{
/*
* 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 AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using BooleanWeight = Lucene.Net.Search.BooleanQuery.BooleanWeight;
/// <summary>
/// Description from Doug Cutting (excerpted from
/// LUCENE-1483):
/// <para/>
/// <see cref="BooleanScorer"/> uses an array to score windows of
/// 2K docs. So it scores docs 0-2K first, then docs 2K-4K,
/// etc. For each window it iterates through all query terms
/// and accumulates a score in table[doc%2K]. It also stores
/// in the table a bitmask representing which terms
/// contributed to the score. Non-zero scores are chained in
/// a linked list. At the end of scoring each window it then
/// iterates through the linked list and, if the bitmask
/// matches the boolean constraints, collects a hit. For
/// boolean queries with lots of frequent terms this can be
/// much faster, since it does not need to update a priority
/// queue for each posting, instead performing constant-time
/// operations per posting. The only downside is that it
/// results in hits being delivered out-of-order within the
/// window, which means it cannot be nested within other
/// scorers. But it works well as a top-level scorer.
/// <para/>
/// The new BooleanScorer2 implementation instead works by
/// merging priority queues of postings, albeit with some
/// clever tricks. For example, a pure conjunction (all terms
/// required) does not require a priority queue. Instead it
/// sorts the posting streams at the start, then repeatedly
/// skips the first to to the last. If the first ever equals
/// the last, then there's a hit. When some terms are
/// required and some terms are optional, the conjunction can
/// be evaluated first, then the optional terms can all skip
/// to the match and be added to the score. Thus the
/// conjunction can reduce the number of priority queue
/// updates for the optional terms.
/// </summary>
internal sealed class BooleanScorer : BulkScorer
{
private sealed class BooleanScorerCollector : ICollector
{
private BucketTable bucketTable;
private int mask;
private Scorer scorer;
public BooleanScorerCollector(int mask, BucketTable bucketTable)
{
this.mask = mask;
this.bucketTable = bucketTable;
}
public void Collect(int doc)
{
BucketTable table = bucketTable;
int i = doc & BucketTable.MASK;
Bucket bucket = table.buckets[i];
if (bucket.Doc != doc) // invalid bucket
{
bucket.Doc = doc; // set doc
bucket.Score = scorer.GetScore(); // initialize score
bucket.Bits = mask; // initialize mask
bucket.Coord = 1; // initialize coord
bucket.Next = table.first; // push onto valid list
table.first = bucket;
} // valid bucket
else
{
bucket.Score += scorer.GetScore(); // increment score
bucket.Bits |= mask; // add bits in mask
bucket.Coord++; // increment coord
}
}
public void SetNextReader(AtomicReaderContext context)
{
// not needed by this implementation
}
public void SetScorer(Scorer scorer)
{
this.scorer = scorer;
}
public bool AcceptsDocsOutOfOrder => true;
}
internal sealed class Bucket
{
internal int Doc { get; set; } // tells if bucket is valid
internal double Score { get; set; } // incremental score
// TODO: break out bool anyProhibited, int
// numRequiredMatched; then we can remove 32 limit on
// required clauses
internal int Bits { get; set; } // used for bool constraints
internal int Coord { get; set; } // count of terms in score
internal Bucket Next { get; set; } // next valid bucket
public Bucket()
{
// Initialize properties
Doc = -1;
}
}
/// <summary>
/// A simple hash table of document scores within a range. </summary>
internal sealed class BucketTable
{
public static readonly int SIZE = 1 << 11;
public static readonly int MASK = SIZE - 1;
internal readonly Bucket[] buckets = new Bucket[SIZE];
internal Bucket first = null; // head of valid list
public BucketTable()
{
// Pre-fill to save the lazy init when collecting
// each sub:
for (int idx = 0; idx < SIZE; idx++)
{
buckets[idx] = new Bucket();
}
}
public ICollector NewCollector(int mask)
{
return new BooleanScorerCollector(mask, this);
}
public int Count => SIZE; // LUCENENET NOTE: This was size() in Lucene.
}
internal sealed class SubScorer
{
public BulkScorer Scorer { get; set; }
// TODO: re-enable this if BQ ever sends us required clauses
//public boolean required = false;
public bool Prohibited { get; set; }
public ICollector Collector { get; set; }
public SubScorer Next { get; set; }
public bool More { get; set; }
public SubScorer(BulkScorer scorer, bool required, bool prohibited, ICollector collector, SubScorer next)
{
if (required)
{
throw new ArgumentException("this scorer cannot handle required=true");
}
this.Scorer = scorer;
this.More = true;
// TODO: re-enable this if BQ ever sends us required clauses
//this.required = required;
this.Prohibited = prohibited;
this.Collector = collector;
this.Next = next;
}
}
private SubScorer scorers = null;
private BucketTable bucketTable = new BucketTable();
private readonly float[] coordFactors;
// TODO: re-enable this if BQ ever sends us required clauses
//private int requiredMask = 0;
private readonly int minNrShouldMatch;
private int end;
private Bucket current;
// Any time a prohibited clause matches we set bit 0:
private const int PROHIBITED_MASK = 1;
private readonly Weight weight;
internal BooleanScorer(BooleanWeight weight, bool disableCoord, int minNrShouldMatch, IList<BulkScorer> optionalScorers, IList<BulkScorer> prohibitedScorers, int maxCoord)
{
this.minNrShouldMatch = minNrShouldMatch;
this.weight = weight;
foreach (BulkScorer scorer in optionalScorers)
{
scorers = new SubScorer(scorer, false, false, bucketTable.NewCollector(0), scorers);
}
foreach (BulkScorer scorer in prohibitedScorers)
{
scorers = new SubScorer(scorer, false, true, bucketTable.NewCollector(PROHIBITED_MASK), scorers);
}
coordFactors = new float[optionalScorers.Count + 1];
for (int i = 0; i < coordFactors.Length; i++)
{
coordFactors[i] = disableCoord ? 1.0f : weight.Coord(i, maxCoord);
}
}
public override bool Score(ICollector collector, int max)
{
bool more;
Bucket tmp;
FakeScorer fs = new FakeScorer();
// The internal loop will set the score and doc before calling collect.
collector.SetScorer(fs);
do
{
bucketTable.first = null;
while (current != null) // more queued
{
// check prohibited & required
if ((current.Bits & PROHIBITED_MASK) == 0)
{
// TODO: re-enable this if BQ ever sends us required
// clauses
//&& (current.bits & requiredMask) == requiredMask) {
// NOTE: Lucene always passes max =
// Integer.MAX_VALUE today, because we never embed
// a BooleanScorer inside another (even though
// that should work)... but in theory an outside
// app could pass a different max so we must check
// it:
if (current.Doc >= max)
{
tmp = current;
current = current.Next;
tmp.Next = bucketTable.first;
bucketTable.first = tmp;
continue;
}
if (current.Coord >= minNrShouldMatch)
{
fs.score = (float)(current.Score * coordFactors[current.Coord]);
fs.doc = current.Doc;
fs.freq = current.Coord;
collector.Collect(current.Doc);
}
}
current = current.Next; // pop the queue
}
if (bucketTable.first != null)
{
current = bucketTable.first;
bucketTable.first = current.Next;
return true;
}
// refill the queue
more = false;
end += BucketTable.SIZE;
for (SubScorer sub = scorers; sub != null; sub = sub.Next)
{
if (sub.More)
{
sub.More = sub.Scorer.Score(sub.Collector, end);
more |= sub.More;
}
}
current = bucketTable.first;
} while (current != null || more);
return false;
}
public override string ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("boolean(");
for (SubScorer sub = scorers; sub != null; sub = sub.Next)
{
buffer.Append(sub.Scorer.ToString());
buffer.Append(" ");
}
buffer.Append(")");
return buffer.ToString();
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2010 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 NUnit.Framework.Api;
namespace NUnit.Framework.Internal
{
/// <summary>
/// The TestResult class represents the result of a test.
/// </summary>
public abstract class TestResult : ITestResult
{
#region Fields
/// <summary>
/// Indicates the result of the test
/// </summary>
[CLSCompliant(false)]
protected ResultState resultState;
/// <summary>
/// The elapsed time for executing this test
/// </summary>
private TimeSpan time = TimeSpan.Zero;
/// <summary>
/// The test that this result pertains to
/// </summary>
[CLSCompliant(false)]
protected readonly ITest test;
/// <summary>
/// The stacktrace at the point of failure
/// </summary>
private string stackTrace;
/// <summary>
/// Message giving the reason for failure, error or skipping the test
/// </summary>
[CLSCompliant(false)]
protected string message;
/// <summary>
/// Number of asserts executed by this test
/// </summary>
[CLSCompliant(false)]
protected int assertCount = 0;
/// <summary>
/// List of child results
/// </summary>
#if CLR_2_0 || CLR_4_0
private System.Collections.Generic.List<ITestResult> children;
#else
private System.Collections.ArrayList children;
#endif
#endregion
#region Constructor
/// <summary>
/// Construct a test result given a Test
/// </summary>
/// <param name="test">The test to be used</param>
public TestResult(ITest test)
{
this.test = test;
this.resultState = ResultState.Inconclusive;
}
#endregion
#region ITestResult Members
/// <summary>
/// Gets the test with which this result is associated.
/// </summary>
public ITest Test
{
get { return test; }
}
/// <summary>
/// Gets the ResultState of the test result, which
/// indicates the success or failure of the test.
/// </summary>
public ResultState ResultState
{
get { return resultState; }
}
/// <summary>
/// Gets the name of the test result
/// </summary>
public virtual string Name
{
get { return test.Name; }
}
/// <summary>
/// Gets the full name of the test result
/// </summary>
public virtual string FullName
{
get { return test.FullName; }
}
/// <summary>
/// Gets or sets the elapsed time for running the test
/// </summary>
public TimeSpan Duration
{
get { return time; }
set { time = value; }
}
/// <summary>
/// Gets the message associated with a test
/// failure or with not running the test
/// </summary>
public string Message
{
get { return message; }
}
/// <summary>
/// Gets any stacktrace associated with an
/// error or failure. Not available in
/// the Compact Framework 1.0.
/// </summary>
public virtual string StackTrace
{
get { return stackTrace; }
}
/// <summary>
/// Gets or sets the count of asserts executed
/// when running the test.
/// </summary>
public int AssertCount
{
get { return assertCount; }
set { assertCount = value; }
}
/// <summary>
/// Gets the number of test cases that failed
/// when running the test and all its children.
/// </summary>
public abstract int FailCount { get; }
/// <summary>
/// Gets the number of test cases that passed
/// when running the test and all its children.
/// </summary>
public abstract int PassCount { get; }
/// <summary>
/// Gets the number of test cases that were skipped
/// when running the test and all its children.
/// </summary>
public abstract int SkipCount { get; }
/// <summary>
/// Gets the number of test cases that were inconclusive
/// when running the test and all its children.
/// </summary>
public abstract int InconclusiveCount { get; }
/// <summary>
/// Indicates whether this result has any child results.
/// Test HasChildren before accessing Children to avoid
/// the creation of an empty collection.
/// </summary>
public bool HasChildren
{
get { return children != null && children.Count > 0; }
}
/// <summary>
/// Gets the collection of child results.
/// </summary>
#if CLR_2_0 || CLR_4_0
public System.Collections.Generic.IList<ITestResult> Children
{
get
{
if (children == null)
children = new System.Collections.Generic.List<ITestResult>();
return children;
}
}
#else
public System.Collections.IList Children
{
get
{
if (children == null)
children = new System.Collections.ArrayList();
return children;
}
}
#endif
#endregion
#region IXmlNodeBuilder Members
/// <summary>
/// Returns the Xml representation of the result.
/// </summary>
/// <param name="recursive">If true, descendant results are included</param>
/// <returns>An XmlNode representing the result</returns>
public XmlNode ToXml(bool recursive)
{
XmlNode topNode = XmlNode.CreateTopLevelElement("dummy");
AddToXml(topNode, recursive);
return topNode.FirstChild;
}
/// <summary>
/// Adds the XML representation of the result as a child of the
/// supplied parent node..
/// </summary>
/// <param name="parentNode">The parent node.</param>
/// <param name="recursive">If true, descendant results are included</param>
/// <returns></returns>
public virtual XmlNode AddToXml(XmlNode parentNode, bool recursive)
{
// A result node looks like a test node with extra info added
XmlNode thisNode = this.test.AddToXml(parentNode, false);
thisNode.AddAttribute("result", ResultState.Status.ToString());
if (ResultState.Label != string.Empty) // && ResultState.Label != ResultState.Status.ToString())
thisNode.AddAttribute("label", ResultState.Label);
thisNode.AddAttribute("time", this.Duration.ToString());
if (this.test is TestSuite)
{
thisNode.AddAttribute("total", (PassCount + FailCount + SkipCount + InconclusiveCount).ToString());
thisNode.AddAttribute("passed", PassCount.ToString());
thisNode.AddAttribute("failed", FailCount.ToString());
thisNode.AddAttribute("inconclusive", InconclusiveCount.ToString());
thisNode.AddAttribute("skipped", SkipCount.ToString());
}
thisNode.AddAttribute("asserts", this.AssertCount.ToString());
switch (ResultState.Status)
{
case TestStatus.Failed:
AddFailureElement(thisNode);
break;
case TestStatus.Skipped:
AddReasonElement(thisNode);
break;
case TestStatus.Passed:
case TestStatus.Inconclusive:
if (this.Message != null)
AddReasonElement(thisNode);
break;
}
if (recursive && HasChildren)
foreach (TestResult child in Children)
child.AddToXml(thisNode, recursive);
return thisNode;
}
#endregion
#region Other Public Methods
/// <summary>
/// Add a child result
/// </summary>
/// <param name="result">The child result to be added</param>
public virtual void AddResult(TestResult result)
{
this.Children.Add(result);
this.assertCount += result.AssertCount;
switch (result.ResultState.Status)
{
case TestStatus.Passed:
if (this.resultState.Status == TestStatus.Inconclusive)
SetResult(ResultState.Success);
break;
case TestStatus.Failed:
if (this.resultState.Status != TestStatus.Failed)
SetResult(ResultState.Failure, "One or more child tests had errors");
break;
case TestStatus.Skipped:
switch (result.ResultState.Label)
{
case "Invalid":
if (this.ResultState != ResultState.NotRunnable && this.ResultState.Status != TestStatus.Failed)
SetResult(ResultState.Failure, "One or more child tests had errors");
break;
case "Ignored":
if (this.ResultState.Status == TestStatus.Inconclusive || this.ResultState.Status == TestStatus.Passed)
SetResult(ResultState.Ignored, "One or more child tests were ignored");
break;
default:
// Tests skipped for other reasons do not change the outcome
// of the containing suite when added.
break;
}
break;
case TestStatus.Inconclusive:
// An inconclusive result does not change the outcome
// of the containing suite when added.
break;
}
}
/// <summary>
/// Set the result of the test
/// </summary>
/// <param name="resultState">The ResultState to use in the result</param>
public void SetResult(ResultState resultState)
{
SetResult(resultState, null, null);
}
/// <summary>
/// Set the result of the test
/// </summary>
/// <param name="resultState">The ResultState to use in the result</param>
/// <param name="message">A message associated with the result state</param>
public void SetResult(ResultState resultState, string message)
{
SetResult(resultState, message, null);
}
/// <summary>
/// Set the result of the test
/// </summary>
/// <param name="resultState">The ResultState to use in the result</param>
/// <param name="message">A message associated with the result state</param>
/// <param name="stackTrace">Stack trace giving the location of the command</param>
public void SetResult(ResultState resultState, string message, string stackTrace)
{
this.resultState = resultState;
this.message = message;
this.stackTrace = stackTrace;
}
/// <summary>
/// Set the test result based on the type of exception thrown
/// </summary>
/// <param name="ex">The exception that was thrown</param>
public void RecordException(Exception ex)
{
if (ex is NUnitException)
ex = ex.InnerException;
#if !PORTABLE
if (ex is System.Threading.ThreadAbortException)
SetResult(ResultState.Cancelled, "Test cancelled by user", ex.StackTrace);
else
#endif
if (ex is AssertionException)
SetResult(ResultState.Failure, ex.Message, StackFilter.Filter(ex.StackTrace));
else if (ex is IgnoreException)
SetResult(ResultState.Ignored, ex.Message, StackFilter.Filter(ex.StackTrace));
else if (ex is InconclusiveException)
SetResult(ResultState.Inconclusive, ex.Message, StackFilter.Filter(ex.StackTrace));
else if (ex is SuccessException)
SetResult(ResultState.Success, ex.Message, StackFilter.Filter(ex.StackTrace));
else
SetResult(ResultState.Error,
ExceptionHelper.BuildMessage(ex),
ExceptionHelper.BuildStackTrace(ex));
}
#endregion
#region Helper Methods
/// <summary>
/// Adds a reason element to a node and returns it.
/// </summary>
/// <param name="targetNode">The target node.</param>
/// <returns>The new reason element.</returns>
private XmlNode AddReasonElement(XmlNode targetNode)
{
XmlNode reasonNode = targetNode.AddElement("reason");
reasonNode.AddElement("message").TextContent = this.Message;
return reasonNode;
}
/// <summary>
/// Adds a failure element to a node and returns it.
/// </summary>
/// <param name="targetNode">The target node.</param>
/// <returns>The new failure element.</returns>
private XmlNode AddFailureElement(XmlNode targetNode)
{
XmlNode failureNode = targetNode.AddElement("failure");
if (this.Message != null)
{
failureNode.AddElement("message").TextContent = this.Message;
}
if (this.StackTrace != null)
{
failureNode.AddElement("stack-trace").TextContent = this.StackTrace;
}
return failureNode;
}
//private static bool IsTestCase(ITest test)
//{
// return !(test is TestSuite);
//}
#endregion
}
}
| |
// KSPNameGen.cs
//
// This file is part of KSPNameGen, a free (gratis and libre) name generator for
// Kerbal Space Program.
// Kerbal Space Program is (c) 2011-2017 Squad. All Rights Reserved.
// KSPNameGen is (c) 2016-2017 the Kerbae ad Astra group <kerbaeadastra@gmail.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 directives
using System;
using System.IO;
using System.Reflection;
using static System.Console;
using static System.ConsoleKey;
using static System.IO.File;
using static KSPNameGen.NameArrays;
using static KSPNameGen.Utils;
// warning suppression declarations
#pragma warning disable RECS0135
namespace KSPNameGen
{
class KSPNameGen
{
// array definitions
static readonly string[] prompt = { // cache prompts
"Specify number of names to generate.", // NMBR
"Specify buffer size.", // Buffer
"Specify filepath (absolute or relative)." // Filepath
};
static readonly ConsoleColor[] colors =
(ConsoleColor[])Enum.GetValues(typeof(ConsoleColor)); // cache colors
// enum defs
enum Modes { Main, Options };
// variable definitions
static bool gen = true;
static bool state = true;
static bool writeFile;
static bool writeHelp;
static bool writeRoster;
static int[] cursor = { 0, 0 };
static int[] param = { 0, 0, 0, 0 };
static ulong bufferSize = 48;
static string filePath = "";
static Modes drawMode = Modes.Main;
static ConsoleKeyInfo input;
static readonly Random random = new Random();
const string help = "Standard names have a 'Kerman' surname, while" +
"\nFuture-style names have randomly generated surnames." + // TYPE
"\nProper names are chosen from a list, while constructed names are" +
"\nconstructed from a list of prefixes and suffixes." +
"\nIf the option 'combination' is chosen, then there is a 1/20 chance" +
"\nthat the generated name is proper."; // CMBO
const string rosterFormat =
"\tKERBAL\n" +
"\t{{\n" +
"\t\tname = {0}\n" +
"\t\tgender = {1}\n" +
"\t\ttype = Crew\n" +
"\t\ttrait = {2}\n" +
"\t\tbrave = {3}\n" +
"\t\tdumb = {4}\n" +
"\t\tbadS = {5}\n" +
"\t\tveteran = False\n" +
"\t\ttour = False\n" +
"\t\tstate = Available\n" +
"\t\tinactive = False\n" +
"\t\tinactiveTimeEnd = 0\n" +
"\t\tgExperienced = 0\n" +
"\t\toutDueToG = False\n" +
"\t\tToD = 0\n" +
"\t\tidx = -1\n" +
"\t\textraXP = 0\n" +
"\t\tCAREER_LOG\n" +
"\t\t{{\n" +
"\t\t\tflight = 0\n" +
"\t\t}}\n" +
"\t\tFLIGHT_LOG\n" +
"\t\t{{\n" +
"\t\t\tflight = 0\n" +
"\t\t}}\n" +
"\t}}\n";
// application logic begins here
static void Main(string[] args)
{
if (args.Length == 0)
{
Loop();
}
if (FlagExists(args, "-h") || FlagExists(args, "--help"))
{
Usage(false);
}
if (FlagExists(args, "-v") || FlagExists(args, "--version"))
{
Version();
}
string argument = "fpm";
if (FlagExists(args, "-t") || FlagExists(args, "--type"))
{
if (FlagParse(args, "-t", ref argument) ||
FlagParse(args, "--type", ref argument))
{
param = IntArrayify(argument);
}
else
{
Usage(true);
}
}
FlagParse(args, "-b", ref bufferSize);
FlagParse(args, "--buffer", ref bufferSize);
if (FlagExists(args, "-f") || FlagExists(args, "--file"))
{
if (FlagParse(args, "-f", ref filePath) ||
FlagParse(args, "--file", ref filePath))
{
if (Accessible(filePath))
{
writeFile = true;
}
else
{
WriteLine("A writable file was not specified.");
}
}
else
{
Usage(true);
}
}
if (FlagExists(args, "-i") || FlagExists(args, "--interactive"))
{
Loop();
}
ulong genNum = 0;
if (FlagExists(args, "-n") || FlagExists(args, "--number"))
{
if (FlagExists(args, "-r") || FlagExists(args, "--roster"))
{
if (FlagParse(args, "-n", out genNum, genNum) ||
FlagParse(args, "--number", out genNum, genNum))
{
RosterIterator(genNum, Stringify(param), bufferSize);
ReadKey(true);
Kill(0);
}
else
{
Usage(true);
}
}
if (FlagParse(args, "-n", out genNum, genNum) ||
FlagParse(args, "--number", out genNum, genNum))
{
Iterator(genNum, Stringify(param), bufferSize);
}
else
{
Usage(true);
}
}
else
{
Usage(true);
}
ReadKey(true);
Kill(0);
}
static void Usage(bool error)
{
Write(
"Usage: {0} [flags] [args]\n" +
"A list of valid flags and their arguments follow.\n" +
"-h --help: No argument. Displays this message.\n" +
"-t --type: A string indicating the type of name to " +
"generate. Defaults to fpm.\n" +
"-r --roster: Generates names, and then writes them to a " +
"ROSTER node so that it can be used in-game.\n" +
"-b --buffer: An integer indicating the number of names to " +
"write to stdout per frame.\n" +
"-f --file: A string indicating the output file, using " +
"either relative or absolute paths.\n" +
"-i --interactive: No argument. Forces interactive mode; default.\n" +
"-n --number: An integer indicating the number of names to " +
"generate. Also noninteractive.\n" +
"All other (invalid) flags and arguments will result in this " +
"message being shown.\n"
, GetBasename());
if (error) //
{
Kill(1);
}
else
{
Kill(0);
}
}
static void Version()
{
Write(
"KSPNameGen version {0}" +
"\nCopyright (c) 2016-2017 the Kerbae ad Astra group." +
"\nLicense MIT: The MIT License <https://opensource.org/licenses/MIT>" +
"\nThis is free software; you are free to change and " +
"redistribute it if and only if you include the license terms " +
"stated above when redistributing." +
"\nThere is NO WARRANTY, to the extent permitted by law.\n"
, ProductVersion.productVersion);
Kill(0);
}
static void Loop()
{
string inString;
Draw();
for (;;)
{
if (gen)
{
Draw();
NameGen();
}
else
{
WriteLine("Would you like to generate more names? " +
"(Y/N)");
inString = ReadKey(true).KeyChar.ToString();
switch (inString)
{
case "y":
gen = true;
break;
case "n":
Kill(0);
break;
default:
WriteLine("Invalid response.");
break;
}
}
}
}
static void NameGen()
{
switch (drawMode)
{
case Modes.Main:
if (state)
{
input = ReadKey(false);
switch (input.Key)
{
case DownArrow:
cursor[0]++;
cursor[0] %= 4;
cursor[1] = param[cursor[0]];
break;
case UpArrow:
cursor[0]--;
cursor[0] += 4;
cursor[0] %= 4;
cursor[1] = param[cursor[0]];
break;
case RightArrow:
cursor[1]++;
break;
case LeftArrow:
cursor[1]--;
break;
case Enter:
switch (param[3])
{
case 0: // Generate
state = false; //NMBR
return;
case 1: // Help
writeHelp = true;
break;
case 2: // Exit
Kill(0);
break;
case 3: // Options
drawMode = Modes.Options;
break;
}
break;
}
switch (cursor[0])
{
case 0: // TYPE
cursor[1] += 2;
cursor[1] %= 2;
break;
case 1: // CMBO
cursor[1] += 3;
cursor[1] %= 3;
break;
case 2: // GNDR
cursor[1] += 2;
cursor[1] %= 2;
break;
case 3: // ACTS
cursor[1] += 4;
cursor[1] %= 4;
break;
}
param[cursor[0]] = cursor[1];
return;
}
if (writeRoster)
{
RosterIterator(PromptI(prompt[0]), Stringify(param), bufferSize);
}
Iterator(PromptI(prompt[0]), Stringify(param), bufferSize);
gen = false;
state = true;
break;
case Modes.Options:
input = ReadKey(false);
switch (input.Key)
{
case DownArrow:
cursor[0]++;
cursor[0] %= 4;
break;
case UpArrow:
cursor[0]--;
cursor[0] += 4;
cursor[0] %= 4;
break;
case Enter:
switch (cursor[0])
{
case 0: //Buffer size
bufferSize = PromptI(prompt[1]);
return;
case 1: //Filepath
filePath = PromptS(prompt[2]);
break;
case 2: //Exit
writeFile = !writeFile;
writeFile &= Accessible(filePath);
break;
case 3: //Apply
drawMode = Modes.Main;
break;
}
break;
}
break;
}
}
static int[] IntArrayify(string par)
{
int[] output = { 0, 0, 0, 0 };
char[] parArr = par.ToCharArray();
if(parArr.Length != 3)
{
Usage(true);
}
output[0] = parArr[0] == 'f' ? 0 : 1;
output[1] = parArr[1] == 'p' ? 0 : parArr[1] == 'r' ? 1 : 2;
output[2] = parArr[2] == 'm' ? 0 : 1;
output[3] = 0;
return output;
}
static void Draw()
{
ConsoleColor oldBack = BackgroundColor;
ConsoleColor newBack = ConsoleColor.DarkRed;
ConsoleColor fexBack = ConsoleColor.Green;
ConsoleColor dneBack = ConsoleColor.Red;
Console.Clear();
switch (drawMode)
{
case Modes.Main:
WriteLine("KSPNameGen v{0}", ProductVersion.productVersion);
BackgroundColor = cursor[0] == 0 ? newBack : oldBack;
WriteLine(param[0] == 0 ?
"[Future] Standard " :
" Future [Standard] ");
BackgroundColor = cursor[0] == 1 ? newBack : oldBack;
WriteLine(param[1] == 0 ?
"[Proper] Mixed Constructed " :
param[1] == 1 ?
" Proper [Mixed] Constructed " :
" Proper Mixed [Constructed] ");
BackgroundColor = cursor[0] == 2 ? newBack : oldBack;
WriteLine(param[2] == 0 ?
"[Male] Female " :
" Male [Female] ");
BackgroundColor = cursor[0] == 3 ? newBack : oldBack;
WriteLine(param[3] == 0 ?
"[Generate] Help Exit Options " :
param[3] == 1 ?
" Generate [Help] Exit Options " :
param[3] == 2 ?
" Generate Help [Exit] Options " :
" Generate Help Exit [Options]");
BackgroundColor = oldBack;
if (writeHelp)
{
WriteLine(help);
writeHelp = false;
}
break;
case Modes.Options:
WriteLine("Options");
BackgroundColor = cursor[0] == 0 ? newBack : oldBack;
WriteLine("Buffer Size: {0,16}", bufferSize);
BackgroundColor = cursor[0] == 1 ? newBack : oldBack;
WriteLine("File Path: ");
BackgroundColor = Accessible(filePath) ? fexBack : dneBack;
WriteLine("{0,31}", filePath);
BackgroundColor = cursor[0] == 2 ? newBack : oldBack;
WriteLine(writeFile ?
"Write to File [x]" :
"Write to File [ ]");
BackgroundColor = cursor[0] == 3 ? newBack : oldBack;
WriteLine(cursor[0] == 3 ?
"[Apply] " :
" Apply ");
BackgroundColor = oldBack;
break;
}
}
static string Generate(string _param)
{
bool toggle = random.Next(20) == 0;
switch (_param)
{
case "spf":
return fpr[random.Next(fpr.Length)] + " Kerman";
case "spm":
return mpr[random.Next(mpr.Length)] + " Kerman";
case "scf":
return fcp[random.Next(fcp.Length)] + fcs
[random.Next(fcp.Length)] + " Kerman";
case "scm":
return mcp[random.Next(mcp.Length)] + mcs
[random.Next(mcp.Length)] + " Kerman";
case "srf":
if (toggle)
return fpr[random.Next(fpr.Length)] + " Kerman";
return fcp[random.Next(fcp.Length)] + fcs
[random.Next(fcp.Length)] + " Kerman";
case "srm":
if (toggle)
return mpr[random.Next(mpr.Length)] + " Kerman";
return mcp[random.Next(mcp.Length)] + mcs
[random.Next(mcp.Length)] + " Kerman";
case "fpf":
return fpr[random.Next(fpr.Length)] + " " + fcp
[random.Next(fcp.Length)] + fcs[random.Next(fcs.Length)];
case "fpm":
return mpr[random.Next(mpr.Length)] + " " + mcp
[random.Next(mcp.Length)] + mcs[random.Next(mcs.Length)];
case "fcf":
return fcp[random.Next(fcp.Length)] + fcs
[random.Next(fcs.Length)] + " " +
fcp[random.Next(fcp.Length)] + fcs[random.Next(fcs.Length)];
case "fcm":
return mcp[random.Next(mcp.Length)] +
mcs[random.Next(mcs.Length)] + " " +
mcp[random.Next(mcp.Length)] + mcs[random.Next(mcs.Length)];
case "frf":
if (toggle)
return fpr[random.Next(fpr.Length)] + " " +
fcp[random.Next(fcp.Length)] + fcs[random.Next(fcs.Length)];
return fcp[random.Next(fcp.Length)] +
fcs[random.Next(fcs.Length)] + " " +
fcp[random.Next(fcp.Length)] + fcs[random.Next(fcs.Length)];
case "frm":
if (toggle)
return mpr[random.Next(mpr.Length)] + " " +
mcp[random.Next(mcp.Length)] + mcs[random.Next(mcs.Length)];
return mcp[random.Next(mcp.Length)] +
mcs[random.Next(mcs.Length)] + " " +
mcp[random.Next(mcp.Length)] + mcs[random.Next(mcs.Length)];
default:
return null; // this should not ever happen, but it's just
// there to stop Mono from throwing a fit
}
}
static void Nyan(ulong inputLong)
{
ConsoleColor currentBackground = BackgroundColor;
for (ulong i = 0; i < inputLong / 15; i++)
{
foreach (ConsoleColor color in colors)
{
if (color == currentBackground)
{
continue;
}
ForegroundColor = color;
WriteLine(Generate(Stringify(param)));
}
}
gen = false;
param = new int[]{ 0, 0, 0 };
Loop();
}
static void Iterator(ulong number, string _param, ulong buffsize)
{
if (number > uint.MaxValue)
{
Nyan(number);
return;
}
if (writeFile)
{
StreamWriter sw = CreateText(filePath);
for (ulong i = 0; i < number; i++)
{
sw.WriteLine(Generate(_param));
}
sw.Dispose();
WriteLine("Complete.");
return;
}
string buffer = "";
string Generated = "";
for (ulong i = 0; i < number; i++)
{
Generated = Generate(_param);
buffer += Generated + "\n";
if (i % buffsize == 0)
{
Write(buffer);
buffer = "";
}
}
Write(buffer);
}
static void RosterIterator(ulong number, string _param, ulong buffsize)
{
if (writeFile)
{
StreamWriter sw = CreateText(filePath);
sw.Write("ROSTER\n{\n");
for (ulong i = 0; i < number; i++)
{
string gender = _param.ToCharArray()[2] == 'm' ? "Male" : "Female";
string trait = random.Next(0, 2) == 0 ? "Pilot" :
random.Next(0, 1) == 0 ? "Engineer" : "Scientist";
string brave = random.NextDouble().ToString();
string dumb = random.NextDouble().ToString();
string badS = random.Next(0, 9) == 0 ? "True" : "False";
sw.Write(
String.Format(rosterFormat, Generate(_param), gender, trait, brave, dumb, badS)
);
}
sw.Write("}\n");
sw.Dispose();
WriteLine("Complete.");
return;
}
string buffer = "";
string Generated = "";
Write("ROSTER\n{\n");
for (ulong i = 0; i < number; i++)
{
string gender = _param.ToCharArray()[2] == 'm' ? "Male" : "Female";
string trait = random.Next(0, 2) == 0 ? "Pilot" :
random.Next(0, 1) == 0 ? "Engineer" : "Scientist";
string brave = random.NextDouble().ToString();
string dumb = random.NextDouble().ToString();
string badS = random.Next(0, 9) == 0 ? "True" : "False";
Generated = Generate(_param);
buffer += String.Format(rosterFormat, Generated, gender, trait, brave, dumb, badS) + "\n";
if (i % buffsize == 0)
{
Write(buffer);
buffer = "";
}
}
Write(buffer);
Write("}\n");
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Media.Animation.SizeKeyFrameCollection.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Media.Animation
{
public partial class SizeKeyFrameCollection : System.Windows.Freezable, System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable
{
#region Methods and constructors
public int Add(SizeKeyFrame keyFrame)
{
return default(int);
}
public void Clear()
{
}
public System.Windows.Media.Animation.SizeKeyFrameCollection Clone()
{
return default(System.Windows.Media.Animation.SizeKeyFrameCollection);
}
protected override void CloneCore(System.Windows.Freezable sourceFreezable)
{
}
protected override void CloneCurrentValueCore(System.Windows.Freezable sourceFreezable)
{
}
public bool Contains(SizeKeyFrame keyFrame)
{
return default(bool);
}
public void CopyTo(SizeKeyFrame[] array, int index)
{
}
protected override System.Windows.Freezable CreateInstanceCore()
{
return default(System.Windows.Freezable);
}
protected override bool FreezeCore(bool isChecking)
{
return default(bool);
}
protected override void GetAsFrozenCore(System.Windows.Freezable sourceFreezable)
{
}
protected override void GetCurrentValueAsFrozenCore(System.Windows.Freezable sourceFreezable)
{
}
public System.Collections.IEnumerator GetEnumerator()
{
return default(System.Collections.IEnumerator);
}
public int IndexOf(SizeKeyFrame keyFrame)
{
return default(int);
}
public void Insert(int index, SizeKeyFrame keyFrame)
{
}
public void Remove(SizeKeyFrame keyFrame)
{
}
public void RemoveAt(int index)
{
}
public SizeKeyFrameCollection()
{
}
void System.Collections.ICollection.CopyTo(Array array, int index)
{
}
int System.Collections.IList.Add(Object keyFrame)
{
return default(int);
}
bool System.Collections.IList.Contains(Object keyFrame)
{
return default(bool);
}
int System.Collections.IList.IndexOf(Object keyFrame)
{
return default(int);
}
void System.Collections.IList.Insert(int index, Object keyFrame)
{
}
void System.Collections.IList.Remove(Object keyFrame)
{
}
#endregion
#region Properties and indexers
public int Count
{
get
{
return default(int);
}
}
public static System.Windows.Media.Animation.SizeKeyFrameCollection Empty
{
get
{
return default(System.Windows.Media.Animation.SizeKeyFrameCollection);
}
}
public bool IsFixedSize
{
get
{
return default(bool);
}
}
public bool IsReadOnly
{
get
{
return default(bool);
}
}
public bool IsSynchronized
{
get
{
return default(bool);
}
}
public SizeKeyFrame this [int index]
{
get
{
return default(SizeKeyFrame);
}
set
{
}
}
public Object SyncRoot
{
get
{
return default(Object);
}
}
Object System.Collections.IList.this [int index]
{
get
{
return default(Object);
}
set
{
}
}
#endregion
}
}
| |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// 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.
// -----------------------------------------------------------------------------
// The following code is a port of XNA StockEffects http://xbox.create.msdn.com/en-US/education/catalog/sample/stock_effects
// -----------------------------------------------------------------------------
// Microsoft Public License (Ms-PL)
//
// This license governs use of the accompanying software. If you use the
// software, you accept this license. If you do not accept the license, do not
// use the software.
//
// 1. Definitions
// The terms "reproduce," "reproduction," "derivative works," and
// "distribution" have the same meaning here as under U.S. copyright law.
// A "contribution" is the original software, or any additions or changes to
// the software.
// A "contributor" is any person that distributes its contribution under this
// license.
// "Licensed patents" are a contributor's patent claims that read directly on
// its contribution.
//
// 2. Grant of Rights
// (A) Copyright Grant- Subject to the terms of this license, including the
// license conditions and limitations in section 3, each contributor grants
// you a non-exclusive, worldwide, royalty-free copyright license to reproduce
// its contribution, prepare derivative works of its contribution, and
// distribute its contribution or any derivative works that you create.
// (B) Patent Grant- Subject to the terms of this license, including the license
// conditions and limitations in section 3, each contributor grants you a
// non-exclusive, worldwide, royalty-free license under its licensed patents to
// make, have made, use, sell, offer for sale, import, and/or otherwise dispose
// of its contribution in the software or derivative works of the contribution
// in the software.
//
// 3. Conditions and Limitations
// (A) No Trademark License- This license does not grant you rights to use any
// contributors' name, logo, or trademarks.
// (B) If you bring a patent claim against any contributor over patents that
// you claim are infringed by the software, your patent license from such
// contributor to the software ends automatically.
// (C) If you distribute any portion of the software, you must retain all
// copyright, patent, trademark, and attribution notices that are present in the
// software.
// (D) If you distribute any portion of the software in source code form, you
// may do so only under this license by including a complete copy of this
// license with your distribution. If you distribute any portion of the software
// in compiled or object code form, you may only do so under a license that
// complies with this license.
// (E) The software is licensed "as-is." You bear the risk of using it. The
// contributors give no express warranties, guarantees or conditions. You may
// have additional consumer rights under your local laws which this license
// cannot change. To the extent permitted under your local laws, the
// contributors exclude the implied warranties of merchantability, fitness for a
// particular purpose and non-infringement.
//-----------------------------------------------------------------------------
// SkinnedEffect.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
using System;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// Built-in effect for rendering skinned character models.
/// </summary>
public partial class SkinnedEffect : Effect, IEffectMatrices, IEffectLights, IEffectFog
{
public const int MaxBones = 72;
#region Effect Parameters
EffectParameter textureParam;
EffectParameter diffuseColorParam;
EffectParameter emissiveColorParam;
EffectParameter specularColorParam;
EffectParameter specularPowerParam;
EffectParameter eyePositionParam;
EffectParameter fogColorParam;
EffectParameter fogVectorParam;
EffectParameter worldParam;
EffectParameter worldInverseTransposeParam;
EffectParameter worldViewProjParam;
EffectParameter bonesParam;
EffectPass shaderPass;
#endregion
#region Fields
bool preferPerPixelLighting;
bool oneLight;
bool fogEnabled;
Matrix world = Matrix.Identity;
Matrix view = Matrix.Identity;
Matrix projection = Matrix.Identity;
Matrix worldView;
Vector4 diffuseColor = Vector4.One;
Vector3 emissiveColor = Vector3.Zero;
Vector3 ambientLightColor = Vector3.Zero;
float alpha = 1;
DirectionalLight light0;
DirectionalLight light1;
DirectionalLight light2;
float fogStart = 0;
float fogEnd = 1;
int weightsPerVertex = 4;
EffectDirtyFlags dirtyFlags = EffectDirtyFlags.All;
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the world matrix.
/// </summary>
public Matrix World
{
get { return world; }
set
{
world = value;
dirtyFlags |= EffectDirtyFlags.World | EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the view matrix.
/// </summary>
public Matrix View
{
get { return view; }
set
{
view = value;
dirtyFlags |= EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.EyePosition | EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the projection matrix.
/// </summary>
public Matrix Projection
{
get { return projection; }
set
{
projection = value;
dirtyFlags |= EffectDirtyFlags.WorldViewProj;
}
}
/// <summary>
/// Gets or sets the material diffuse color (range 0 to 1).
/// </summary>
public Vector4 DiffuseColor
{
get { return diffuseColor; }
set
{
diffuseColor = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets or sets the material emissive color (range 0 to 1).
/// </summary>
public Vector3 EmissiveColor
{
get { return emissiveColor; }
set
{
emissiveColor = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets or sets the material specular color (range 0 to 1).
/// </summary>
public Vector3 SpecularColor
{
get { return specularColorParam.GetValue<Vector3>(); }
set { specularColorParam.SetValue(value); }
}
/// <summary>
/// Gets or sets the material specular power.
/// </summary>
public float SpecularPower
{
get { return specularPowerParam.GetValue<float>(); }
set { specularPowerParam.SetValue(value); }
}
/// <summary>
/// Gets or sets the material alpha.
/// </summary>
public float Alpha
{
get { return alpha; }
set
{
alpha = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets or sets the per-pixel lighting prefer flag.
/// </summary>
public bool PreferPerPixelLighting
{
get { return preferPerPixelLighting; }
set
{
if (preferPerPixelLighting != value)
{
preferPerPixelLighting = value;
dirtyFlags |= EffectDirtyFlags.ShaderIndex;
}
}
}
/// <summary>
/// Gets or sets the ambient light color (range 0 to 1).
/// </summary>
public Vector3 AmbientLightColor
{
get { return ambientLightColor; }
set
{
ambientLightColor = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets the first directional light.
/// </summary>
public DirectionalLight DirectionalLight0 { get { return light0; } }
/// <summary>
/// Gets the second directional light.
/// </summary>
public DirectionalLight DirectionalLight1 { get { return light1; } }
/// <summary>
/// Gets the third directional light.
/// </summary>
public DirectionalLight DirectionalLight2 { get { return light2; } }
/// <summary>
/// Gets or sets the fog enable flag.
/// </summary>
public bool FogEnabled
{
get { return fogEnabled; }
set
{
if (fogEnabled != value)
{
fogEnabled = value;
dirtyFlags |= EffectDirtyFlags.ShaderIndex | EffectDirtyFlags.FogEnable;
}
}
}
/// <summary>
/// Gets or sets the fog start distance.
/// </summary>
public float FogStart
{
get { return fogStart; }
set
{
fogStart = value;
dirtyFlags |= EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the fog end distance.
/// </summary>
public float FogEnd
{
get { return fogEnd; }
set
{
fogEnd = value;
dirtyFlags |= EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the fog color.
/// </summary>
public Vector3 FogColor
{
get { return fogColorParam.GetValue<Vector3>(); }
set { fogColorParam.SetValue(value); }
}
/// <summary>
/// Gets or sets the current texture.
/// </summary>
public Texture2D Texture
{
get { return textureParam.GetResource<Texture2D>(); }
set { textureParam.SetResource(value); }
}
/// <summary>
/// Gets or sets the number of skinning weights to evaluate for each vertex (1, 2, or 4).
/// </summary>
public int WeightsPerVertex
{
get { return weightsPerVertex; }
set
{
if ((value != 1) &&
(value != 2) &&
(value != 4))
{
throw new ArgumentOutOfRangeException("value");
}
weightsPerVertex = value;
dirtyFlags |= EffectDirtyFlags.ShaderIndex;
}
}
/// <summary>
/// Sets an array of skinning bone transform matrices.
/// </summary>
public void SetBoneTransforms(Matrix[] boneTransforms)
{
if ((boneTransforms == null) || (boneTransforms.Length == 0))
throw new ArgumentNullException("boneTransforms");
if (boneTransforms.Length > MaxBones)
throw new ArgumentException();
bonesParam.SetValue(boneTransforms);
}
/// <summary>
/// Gets a copy of the current skinning bone transform matrices.
/// </summary>
public Matrix[] GetBoneTransforms(int count)
{
if (count <= 0 || count > MaxBones)
throw new ArgumentOutOfRangeException("count");
var bones = bonesParam.GetValueArray<Matrix>(count);
// Convert matrices from 43 to 44 format.
for (int i = 0; i < bones.Length; i++)
{
bones[i].M44 = 1;
}
return bones;
}
/// <summary>
/// This effect requires lighting, so we explicitly implement
/// IEffectLights.LightingEnabled, and do not allow turning it off.
/// </summary>
bool IEffectLights.LightingEnabled
{
get { return true; }
set { if (!value) throw new NotSupportedException("SkinnedEffect does not support setting LightingEnabled to false."); }
}
#endregion
#region Methods
private const string SkinnedEffectName = "Toolkit::SkinnedEffect";
/// <summary>
/// Creates a new SkinnedEffect with default parameter settings.
/// </summary>
public SkinnedEffect(GraphicsDevice device) : this(device, device.DefaultEffectPool)
{
}
/// <summary>
/// Creates a new SkinnedEffect with default parameter settings from a specified <see cref="EffectPool"/>.
/// </summary>
public SkinnedEffect(GraphicsDevice device, EffectPool pool)
: base(device, effectBytecode, pool)
{
DirectionalLight0.Enabled = true;
SpecularColor = Vector3.One;
SpecularPower = 16;
var identityBones = new Matrix[MaxBones];
for (int i = 0; i < MaxBones; i++)
{
identityBones[i] = Matrix.Identity;
}
SetBoneTransforms(identityBones);
}
protected override void Initialize()
{
textureParam = Parameters["Texture"];
diffuseColorParam = Parameters["DiffuseColor"];
emissiveColorParam = Parameters["EmissiveColor"];
specularColorParam = Parameters["SpecularColor"];
specularPowerParam = Parameters["SpecularPower"];
eyePositionParam = Parameters["EyePosition"];
fogColorParam = Parameters["FogColor"];
fogVectorParam = Parameters["FogVector"];
worldParam = Parameters["World"];
worldInverseTransposeParam = Parameters["WorldInverseTranspose"];
worldViewProjParam = Parameters["WorldViewProj"];
bonesParam = Parameters["Bones"];
light0 = new DirectionalLight(Parameters["DirLight0Direction"],
Parameters["DirLight0DiffuseColor"],
Parameters["DirLight0SpecularColor"],
null);
light1 = new DirectionalLight(Parameters["DirLight1Direction"],
Parameters["DirLight1DiffuseColor"],
Parameters["DirLight1SpecularColor"],
null);
light2 = new DirectionalLight(Parameters["DirLight2Direction"],
Parameters["DirLight2DiffuseColor"],
Parameters["DirLight2SpecularColor"],
null);
}
///// <summary>
///// Creates a new SkinnedEffect by cloning parameter settings from an existing instance.
///// </summary>
//protected SkinnedEffect(SkinnedEffect cloneSource)
// : base(cloneSource)
//{
// CacheEffectParameters(cloneSource);
// preferPerPixelLighting = cloneSource.preferPerPixelLighting;
// fogEnabled = cloneSource.fogEnabled;
// world = cloneSource.world;
// view = cloneSource.view;
// projection = cloneSource.projection;
// diffuseColor = cloneSource.diffuseColor;
// emissiveColor = cloneSource.emissiveColor;
// ambientLightColor = cloneSource.ambientLightColor;
// alpha = cloneSource.alpha;
// fogStart = cloneSource.fogStart;
// fogEnd = cloneSource.fogEnd;
// weightsPerVertex = cloneSource.weightsPerVertex;
//}
///// <summary>
///// Creates a clone of the current SkinnedEffect instance.
///// </summary>
//public override Effect Clone()
//{
// return new SkinnedEffect(this);
//}
/// <summary>
/// Sets up the standard key/fill/back lighting rig.
/// </summary>
public void EnableDefaultLighting()
{
AmbientLightColor = EffectHelpers.EnableDefaultLighting(light0, light1, light2);
}
/// <summary>
/// Lazily computes derived parameter values immediately before applying the effect.
/// </summary>
protected internal override EffectPass OnApply(EffectPass pass)
{
// Recompute the world+view+projection matrix or fog vector?
dirtyFlags = EffectHelpers.SetWorldViewProjAndFog(dirtyFlags, ref world, ref view, ref projection, ref worldView, fogEnabled, fogStart, fogEnd, worldViewProjParam, fogVectorParam);
// Recompute the world inverse transpose and eye position?
dirtyFlags = EffectHelpers.SetLightingMatrices(dirtyFlags, ref world, ref view, worldParam, worldInverseTransposeParam, eyePositionParam);
// Recompute the diffuse/emissive/alpha material color parameters?
if ((dirtyFlags & EffectDirtyFlags.MaterialColor) != 0)
{
EffectHelpers.SetMaterialColor(true, alpha, ref diffuseColor, ref emissiveColor, ref ambientLightColor, diffuseColorParam, emissiveColorParam);
dirtyFlags &= ~EffectDirtyFlags.MaterialColor;
}
// Check if we can use the only-bother-with-the-first-light shader optimization.
bool newOneLight = !light1.Enabled && !light2.Enabled;
if (oneLight != newOneLight)
{
oneLight = newOneLight;
dirtyFlags |= EffectDirtyFlags.ShaderIndex;
}
// Recompute the shader index?
if ((dirtyFlags & EffectDirtyFlags.ShaderIndex) != 0)
{
int shaderIndex = 0;
if (!fogEnabled)
shaderIndex += 1;
if (weightsPerVertex == 2)
shaderIndex += 2;
else if (weightsPerVertex == 4)
shaderIndex += 4;
if (preferPerPixelLighting)
shaderIndex += 12;
else if (oneLight)
shaderIndex += 6;
shaderPass = pass.SubPasses[shaderIndex];
dirtyFlags &= ~EffectDirtyFlags.ShaderIndex;
}
return base.OnApply(shaderPass);
}
#endregion
}
}
| |
//
// Log.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2005-2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Text;
using System.Collections.Generic;
using System.Threading;
namespace Hyena
{
internal delegate void LogNotifyHandler (LogNotifyArgs args);
internal class LogNotifyArgs : EventArgs
{
private LogEntry entry;
internal LogNotifyArgs (LogEntry entry)
{
this.entry = entry;
}
internal LogEntry Entry {
get { return entry; }
}
}
internal enum LogEntryType
{
Debug,
Warning,
Error,
Information
}
internal class LogEntry
{
private LogEntryType type;
private string message;
private string details;
private DateTime timestamp;
internal LogEntry (LogEntryType type, string message, string details)
{
this.type = type;
this.message = message;
this.details = details;
this.timestamp = DateTime.Now;
}
internal LogEntryType Type {
get { return type; }
}
internal string Message {
get { return message; }
}
internal string Details {
get { return details; }
}
internal DateTime TimeStamp {
get { return timestamp; }
}
}
internal static class Log
{
internal static event LogNotifyHandler Notify;
private static Dictionary<uint, DateTime> timers = new Dictionary<uint, DateTime> ();
private static uint next_timer_id = 1;
private static bool debugging = false;
internal static bool Debugging {
get { return debugging; }
set { debugging = value; }
}
internal static void Commit (LogEntryType type, string message, string details, bool showUser)
{
if (type == LogEntryType.Debug && !Debugging) {
return;
}
if (type != LogEntryType.Information || (type == LogEntryType.Information && !showUser)) {
switch (type) {
case LogEntryType.Error: ConsoleCrayon.ForegroundColor = ConsoleColor.Red; break;
case LogEntryType.Warning: ConsoleCrayon.ForegroundColor = ConsoleColor.DarkYellow; break;
case LogEntryType.Information: ConsoleCrayon.ForegroundColor = ConsoleColor.Green; break;
case LogEntryType.Debug: ConsoleCrayon.ForegroundColor = ConsoleColor.Blue; break;
}
var thread_name = String.Empty;
if (Debugging) {
var thread = Thread.CurrentThread;
thread_name = String.Format ("{0} ", thread.ManagedThreadId);
}
Console.Write ("[{5}{0} {1:00}:{2:00}:{3:00}.{4:000}]", TypeString (type), DateTime.Now.Hour,
DateTime.Now.Minute, DateTime.Now.Second, DateTime.Now.Millisecond, thread_name);
ConsoleCrayon.ResetColor ();
if (details != null) {
Console.WriteLine (" {0} - {1}", message, details);
} else {
Console.WriteLine (" {0}", message);
}
}
if (showUser) {
OnNotify (new LogEntry (type, message, details));
}
}
private static string TypeString (LogEntryType type)
{
switch (type) {
case LogEntryType.Debug: return "Debug";
case LogEntryType.Warning: return "Warn ";
case LogEntryType.Error: return "Error";
case LogEntryType.Information: return "Info ";
}
return null;
}
private static void OnNotify (LogEntry entry)
{
LogNotifyHandler handler = Notify;
if (handler != null) {
handler (new LogNotifyArgs (entry));
}
}
#region Timer Methods
internal static uint DebugTimerStart (string message)
{
return TimerStart (message, false);
}
internal static uint InformationTimerStart (string message)
{
return TimerStart (message, true);
}
private static uint TimerStart (string message, bool isInfo)
{
if (!Debugging && !isInfo) {
return 0;
}
if (isInfo) {
Information (message);
} else {
Debug (message);
}
return TimerStart (isInfo);
}
internal static uint DebugTimerStart ()
{
return TimerStart (false);
}
internal static uint InformationTimerStart ()
{
return TimerStart (true);
}
private static uint TimerStart (bool isInfo)
{
if (!Debugging && !isInfo) {
return 0;
}
uint timer_id = next_timer_id++;
timers.Add (timer_id, DateTime.Now);
return timer_id;
}
internal static void DebugTimerPrint (uint id)
{
if (!Debugging) {
return;
}
TimerPrint (id, "Operation duration: {0}", false);
}
internal static void DebugTimerPrint (uint id, string message)
{
if (!Debugging) {
return;
}
TimerPrint (id, message, false);
}
internal static void InformationTimerPrint (uint id)
{
TimerPrint (id, "Operation duration: {0}", true);
}
internal static void InformationTimerPrint (uint id, string message)
{
TimerPrint (id, message, true);
}
private static void TimerPrint (uint id, string message, bool isInfo)
{
if (!Debugging && !isInfo) {
return;
}
DateTime finish = DateTime.Now;
if (!timers.ContainsKey (id)) {
return;
}
TimeSpan duration = finish - timers[id];
string d_message;
if (duration.TotalSeconds < 60) {
d_message = duration.TotalSeconds.ToString ();
} else {
d_message = duration.ToString ();
}
if (isInfo) {
InformationFormat (message, d_message);
} else {
DebugFormat (message, d_message);
}
}
#endregion
#region Public Debug Methods
internal static void Debug (string message, string details)
{
if (Debugging) {
Commit (LogEntryType.Debug, message, details, false);
}
}
internal static void Debug (string message)
{
if (Debugging) {
Debug (message, null);
}
}
internal static void DebugFormat (string format, params object [] args)
{
if (Debugging) {
Debug (String.Format (format, args));
}
}
#endregion
#region Public Information Methods
internal static void Information (string message)
{
Information (message, null);
}
internal static void Information (string message, string details)
{
Information (message, details, false);
}
internal static void Information (string message, string details, bool showUser)
{
Commit (LogEntryType.Information, message, details, showUser);
}
internal static void Information (string message, bool showUser)
{
Information (message, null, showUser);
}
internal static void InformationFormat (string format, params object [] args)
{
Information (String.Format (format, args));
}
#endregion
#region Public Warning Methods
internal static void Warning (string message)
{
Warning (message, null);
}
internal static void Warning (string message, string details)
{
Warning (message, details, false);
}
internal static void Warning (string message, string details, bool showUser)
{
Commit (LogEntryType.Warning, message, details, showUser);
}
internal static void Warning (string message, bool showUser)
{
Warning (message, null, showUser);
}
internal static void WarningFormat (string format, params object [] args)
{
Warning (String.Format (format, args));
}
#endregion
#region Public Error Methods
internal static void Error (string message)
{
Error (message, null);
}
internal static void Error (string message, string details)
{
Error (message, details, false);
}
internal static void Error (string message, string details, bool showUser)
{
Commit (LogEntryType.Error, message, details, showUser);
}
internal static void Error (string message, bool showUser)
{
Error (message, null, showUser);
}
internal static void ErrorFormat (string format, params object [] args)
{
Error (String.Format (format, args));
}
#endregion
#region Public Exception Methods
internal static void DebugException (Exception e)
{
if (Debugging) {
Exception (e);
}
}
internal static void Exception (Exception e)
{
Exception (null, e);
}
internal static void Exception (string message, Exception e)
{
Stack<Exception> exception_chain = new Stack<Exception> ();
StringBuilder builder = new StringBuilder ();
while (e != null) {
exception_chain.Push (e);
e = e.InnerException;
}
while (exception_chain.Count > 0) {
e = exception_chain.Pop ();
builder.AppendFormat ("{0}: {1} (in `{2}')", e.GetType (), e.Message, e.Source).AppendLine ();
builder.Append (e.StackTrace);
if (exception_chain.Count > 0) {
builder.AppendLine ();
}
}
// FIXME: We should save these to an actual log file
Log.Warning (message ?? "Caught an exception", builder.ToString (), false);
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.Configuration.Environment.Abstractions
{
using System;
using System.Collections.Generic;
using Microsoft.Zelig.Runtime.TypeSystem;
using Microsoft.Zelig.TargetModel.ArmProcessor;
using ZeligIR = Microsoft.Zelig.CodeGeneration.IR;
public class ArmCallingConvention : ZeligIR.Abstractions.CallingConvention
{
class ArmCallState : ZeligIR.Abstractions.CallingConvention.CallState
{
//
// State
//
internal int m_numberOfWordsPassedInRegistersForIntegers;
internal int m_numberOfWordsPassedInRegistersForFloatingPoints;
internal int m_numberOfWordsPerArgument;
internal uint m_nextRegForArgumentsInteger;
internal uint m_nextRegForArgumentsFloatingPoint;
internal uint m_nextRegForResultValueInteger;
internal uint m_nextRegForResultValueFloatingPoint;
internal uint m_nextStackIn;
internal uint m_nextStackLocal;
internal uint m_nextStackOut;
//
// Constructor Methods
//
internal ArmCallState() // Default constructor required by TypeSystemSerializer.
{
}
internal ArmCallState( Direction direction ,
int numberOfWordsPassedInRegistersForIntegers ,
int numberOfWordsPassedInRegistersForFloatingPoints ,
int numberOfWordsPerArgument ) : base( direction )
{
m_numberOfWordsPassedInRegistersForIntegers = numberOfWordsPassedInRegistersForIntegers;
m_numberOfWordsPassedInRegistersForFloatingPoints = numberOfWordsPassedInRegistersForFloatingPoints;
m_numberOfWordsPerArgument = numberOfWordsPerArgument;
}
//
// Helper Methods
//
public override void ApplyTransformation( TransformationContext context )
{
ZeligIR.TransformationContextForCodeTransformation context2 = (ZeligIR.TransformationContextForCodeTransformation)context;
context2.Push( this );
base.ApplyTransformation( context2 );
context2.Transform( ref m_numberOfWordsPassedInRegistersForIntegers );
context2.Transform( ref m_numberOfWordsPassedInRegistersForFloatingPoints );
context2.Transform( ref m_numberOfWordsPerArgument );
context2.Transform( ref m_nextRegForArgumentsInteger );
context2.Transform( ref m_nextRegForArgumentsFloatingPoint );
context2.Transform( ref m_nextRegForResultValueInteger );
context2.Transform( ref m_nextRegForResultValueFloatingPoint );
context2.Transform( ref m_nextStackIn );
context2.Transform( ref m_nextStackLocal );
context2.Transform( ref m_nextStackOut );
context2.Pop();
}
public override ZeligIR.Abstractions.RegisterDescriptor GetNextRegister( ZeligIR.Abstractions.Platform platform ,
TypeRepresentation sourceTd ,
TypeRepresentation fragmentTd ,
ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment kind )
{
switch(kind)
{
case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.CopyIncomingArgumentFromPhysicalToPseudoRegister:
case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocatePhysicalRegisterForArgument:
case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocatePhysicalRegisterForReturnValue:
int idx = GetNextIndex( platform, sourceTd, fragmentTd, kind );
return platform.GetRegisters()[idx];
}
throw TypeConsistencyErrorException.Create( "Unexpected fragment kind {0}", kind );
}
public override int GetNextIndex( ZeligIR.Abstractions.Platform platform ,
TypeRepresentation sourceTd ,
TypeRepresentation fragmentTd ,
ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment kind )
{
switch(kind)
{
case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.CopyIncomingArgumentFromPhysicalToPseudoRegister:
case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocatePhysicalRegisterForArgument:
return GetNextIndex( platform, fragmentTd, ref m_nextRegForArgumentsInteger, ref m_nextRegForArgumentsFloatingPoint );
case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocatePhysicalRegisterForReturnValue:
return GetNextIndex( platform, fragmentTd, ref m_nextRegForResultValueInteger, ref m_nextRegForResultValueFloatingPoint );
case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.CopyIncomingArgumentFromStackToPseudoRegister:
case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocateStackInLocation:
return (int)m_nextStackIn++;
case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocateStackLocalLocation:
return (int)m_nextStackLocal++;
case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocateStackOutLocation:
return (int)m_nextStackOut++;
}
throw TypeConsistencyErrorException.Create( "Unexpected fragment kind {0}", kind );
}
public override bool CanMapToRegister( ZeligIR.Abstractions.Platform platform ,
TypeRepresentation td )
{
uint requiredRegisters = td.SizeOfHoldingVariableInWords;
if(ShouldUseFloatingPointRegister( platform, td ))
{
uint nextReg = m_nextRegForArgumentsFloatingPoint;
if(requiredRegisters == 2 && ((nextReg & 1) != 0)) nextReg++; // Align to Double-Precision register boundary.
return ( requiredRegisters <= m_numberOfWordsPassedInRegistersForFloatingPoints &&
nextReg + requiredRegisters <= m_numberOfWordsPassedInRegistersForFloatingPoints );
}
else
{
return ( requiredRegisters <= m_numberOfWordsPassedInRegistersForIntegers &&
m_nextRegForArgumentsInteger + requiredRegisters <= m_numberOfWordsPassedInRegistersForIntegers );
}
}
public override bool CanMapResultToRegister( ZeligIR.Abstractions.Platform platform ,
TypeRepresentation td )
{
uint requiredRegisters = td.SizeOfHoldingVariableInWords;
return (requiredRegisters <= m_numberOfWordsPerArgument);
}
//--//
private static bool ShouldUseFloatingPointRegister( ZeligIR.Abstractions.Platform platform ,
TypeRepresentation td )
{
if(td.IsFloatingPoint)
{
ArmPlatform paArm = (ArmPlatform)platform;
if(paArm.HasVFPv2)
{
return true;
}
}
return false;
}
private static int GetNextIndex( ZeligIR.Abstractions.Platform platform ,
TypeRepresentation td ,
ref uint nextRegInteger ,
ref uint nextRegFloatingPoint )
{
uint encoding;
if(ShouldUseFloatingPointRegister( platform, td ))
{
uint requiredRegisters = td.SizeOfHoldingVariableInWords;
uint nextReg = nextRegFloatingPoint;
if(requiredRegisters == 2 && ((nextReg & 1) != 0)) nextReg++; // Align to Double-Precision register boundary.
nextRegFloatingPoint = nextReg + requiredRegisters;
if(requiredRegisters == 2)
{
encoding = EncodingDefinition_VFP.c_register_d0 + (nextReg / 2);
}
else
{
encoding = EncodingDefinition_VFP.c_register_s0 + nextReg;
}
}
else
{
uint nextReg = nextRegInteger++;
encoding = EncodingDefinition.c_register_r0 + nextReg;
}
foreach(var regDesc in platform.GetRegisters())
{
if(regDesc.Encoding == encoding)
{
return regDesc.Index;
}
}
throw TypeConsistencyErrorException.Create( "Failed to find register with encoding {0}", encoding );
}
}
//
// State
//
internal int m_numberOfWordsPassedInRegistersForIntegers = 4;
internal int m_numberOfWordsPassedInRegistersForFloatingPoints = 4;
internal int m_numberOfWordsPerArgument = 2;
//
// Constructor Methods
//
public ArmCallingConvention() // Default constructor required by TypeSystemSerializer.
{
}
public ArmCallingConvention( ZeligIR.TypeSystemForCodeTransformation typeSystem ) : base( typeSystem )
{
}
//
// Helper Methods
//
public override void RegisterForNotifications( ZeligIR.TypeSystemForCodeTransformation ts ,
ZeligIR.CompilationSteps.DelegationCache cache )
{
}
//--//
public override CallState CreateCallState( Direction direction )
{
ArmPlatform paArm = (ArmPlatform)m_typeSystem.PlatformAbstraction;
if(paArm.HasVFPv2)
{
return new ArmCallState( direction, m_numberOfWordsPassedInRegistersForIntegers, m_numberOfWordsPassedInRegistersForFloatingPoints, m_numberOfWordsPerArgument );
}
else
{
return new ArmCallState( direction, m_numberOfWordsPassedInRegistersForIntegers, 0, m_numberOfWordsPerArgument );
}
}
public override ZeligIR.Expression[] AssignArgument( ZeligIR.ControlFlowGraphStateForCodeTransformation cfg ,
ZeligIR.Operator insertionOp ,
ZeligIR.Expression ex ,
TypeRepresentation td ,
ZeligIR.Abstractions.CallingConvention.CallState callState )
{
ZeligIR.VariableExpression sourceVar = ex as ZeligIR.VariableExpression;
ZeligIR.VariableExpression.DebugInfo debugInfo;
ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment kind;
if(callState.Direction == Direction.Caller)
{
//
// On the caller side, we don't associate the fragments with the original expression,
// since the same fragments will be used for multiple expressions, on different method calls.
//
sourceVar = null;
debugInfo = null;
}
else
{
debugInfo = sourceVar.DebugName;
}
if(callState.CanMapToRegister( cfg.TypeSystem.PlatformAbstraction, td ))
{
if(callState.Direction == Direction.Callee)
{
kind = ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.CopyIncomingArgumentFromPhysicalToPseudoRegister;
}
else
{
kind = ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocatePhysicalRegisterForArgument;
}
return cfg.MapExpressionToFragments( insertionOp, debugInfo, sourceVar, td, callState, kind );
}
else
{
if(callState.Direction == Direction.Callee)
{
kind = ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.CopyIncomingArgumentFromStackToPseudoRegister;
}
else
{
kind = ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocateStackOutLocation;
}
return cfg.MapExpressionToFragments( insertionOp, debugInfo, sourceVar, td, callState, kind );
}
}
public override ZeligIR.Expression[] AssignReturnValue( ZeligIR.ControlFlowGraphStateForCodeTransformation cfg ,
ZeligIR.Operator insertionOp ,
ZeligIR.VariableExpression exReturnValue ,
TypeRepresentation tdReturnValue ,
ZeligIR.Abstractions.CallingConvention.CallState callState )
{
ZeligIR.VariableExpression.DebugInfo debugInfo;
if(exReturnValue != null)
{
debugInfo = exReturnValue.DebugName;
}
else
{
debugInfo = null;
}
if(callState.Direction == Direction.Caller)
{
//
// On the caller side, we don't associate the fragments with the original expression,
// since the same fragments will be used for multiple expressions, on different method calls.
//
exReturnValue = null;
debugInfo = null;
}
if(callState.CanMapResultToRegister( cfg.TypeSystem.PlatformAbstraction, tdReturnValue ))
{
return cfg.MapExpressionToFragments( insertionOp, debugInfo, exReturnValue, tdReturnValue, callState, ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocatePhysicalRegisterForReturnValue );
}
else
{
ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment kind;
if(callState.Direction == Direction.Callee)
{
kind = ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocateStackInLocation;
}
else
{
kind = ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocateStackOutLocation;
}
//
// For methods whose return value is too big, share the return value variable as the first slot on the stack.
//
return cfg.MapExpressionToFragments( insertionOp, debugInfo, exReturnValue, tdReturnValue, callState, kind );
}
}
public override ZeligIR.VariableExpression[] CollectExpressionsToInvalidate( ZeligIR.ControlFlowGraphStateForCodeTransformation cfg ,
ZeligIR.CallOperator op ,
ZeligIR.Expression[] resFragments )
{
ZeligIR.VariableExpression[] res = ZeligIR.VariableExpression.SharedEmptyArray;
ZeligIR.Abstractions.CallingConvention.CallState callState = cfg.TypeSystem.CallingConvention.CreateCallState( Direction.Caller );
//
// Because of the aliasing between physical registers, it's important that we add the expressions to invalidate
// in the right order:
//
// 1) Actual return values (first because we need that value after the call)
// 2) Formal return values
// 3) Call arguments
// 4) Registers and stack locations affected by the calling convention.
//
res = MergeFragments( res, resFragments );
if(op != null)
{
MethodRepresentation md = op.TargetMethod;
{
TypeRepresentation tdReturn = md.ReturnType;
if(tdReturn != cfg.TypeSystem.WellKnownTypes.System_Void)
{
ZeligIR.Expression[] resFormalFragments = AssignReturnValue( cfg, null, null, tdReturn, callState );
res = MergeFragments( res, resFormalFragments );
}
}
foreach(TypeRepresentation tdArg in md.ThisPlusArguments)
{
ZeligIR.Expression[] argFragments = AssignArgument( cfg, null, null, tdArg, callState );
res = MergeFragments( res, argFragments );
}
}
foreach(ZeligIR.Abstractions.RegisterDescriptor regDesc in m_typeSystem.PlatformAbstraction.GetRegisters())
{
bool fAdd = false;
if(regDesc.InIntegerRegisterFile)
{
//
// These registers are part of the calling convention, they can be scratched.
//
if((regDesc.Encoding - EncodingDefinition.c_register_r0) < m_numberOfWordsPassedInRegistersForIntegers ||
regDesc.Encoding == EncodingDefinition.c_register_r12 ||
regDesc.Encoding == EncodingDefinition.c_register_lr )
{
fAdd = true;
}
}
if(regDesc.InFloatingPointRegisterFile)
{
//
// These registers are part of the calling convention, they can be scratched.
//
if(regDesc.IsDoublePrecision)
{
if(ArmCompilationState.GetDoublePrecisionEncoding( regDesc ) < m_numberOfWordsPassedInRegistersForFloatingPoints)
{
fAdd = true;
}
}
else
{
if(ArmCompilationState.GetSinglePrecisionEncoding( regDesc ) < m_numberOfWordsPassedInRegistersForFloatingPoints)
{
fAdd = true;
}
}
}
if(fAdd)
{
res = AddUniqueToFragment( res, cfg.AllocatePhysicalRegister( regDesc ) );
}
}
res = AddUniqueToFragment( res, cfg.AllocateConditionCode() );
return CollectAddressTakenExpressionsToInvalidate( cfg, res, op );
}
public override bool ShouldSaveRegister( ZeligIR.Abstractions.RegisterDescriptor regDesc )
{
if(regDesc.IsSpecial)
{
return false;
}
if(regDesc.IsSystemRegister)
{
return false;
}
if(regDesc.InIntegerRegisterFile)
{
if((regDesc.Encoding - EncodingDefinition.c_register_r0 ) < m_numberOfWordsPassedInRegistersForIntegers ||
regDesc.Encoding == EncodingDefinition.c_register_r12 ||
regDesc.Encoding == EncodingDefinition.c_register_lr )
{
//
// These registers are part of the calling convention, they can be scratched.
//
return false;
}
}
if(regDesc.InFloatingPointRegisterFile)
{
if(regDesc.IsDoublePrecision)
{
if(ArmCompilationState.GetDoublePrecisionEncoding( regDesc ) < m_numberOfWordsPassedInRegistersForFloatingPoints)
{
//
// These registers are part of the calling convention, they can be scratched.
//
return false;
}
}
else
{
if(ArmCompilationState.GetSinglePrecisionEncoding( regDesc ) < m_numberOfWordsPassedInRegistersForFloatingPoints)
{
//
// These registers are part of the calling convention, they can be scratched.
//
return false;
}
}
}
return true;
}
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;
namespace NuiEngine.NuiControl
{
/// <summary></summary>
public class FruityLoopsBackgroundPainter : Component, IProgressBackgroundPainter, IDisposable {
private IGlossPainter gloss;
private FruityLoopsProgressPainter.FruityLoopsProgressType type;
private Image img;
private Color OffLit = Color.FromArgb(49, 69, 74);
private Pen pOffLit; // = new Pen(new SolidBrush(OffLit),1f);
private Color OffLitTop = Color.FromArgb(66, 85, 90);
private Pen pOffLitTop; // = new Pen(new SolidBrush(OffLitTop),1f);
private Color OffLitBot = Color.FromArgb(24, 48, 49);
private Pen pOffLitBot; // = new Pen(new SolidBrush(OffLitBot),1f);
private Color OffMid = Color.FromArgb(24, 48, 49);
private Pen pOffMid; // = new Pen(new SolidBrush(OffMid),1f);
private Color OffMidTop = Color.FromArgb(24, 48, 49);
private Pen pOffMidTop; // = new Pen(new SolidBrush(OffMidTop),1f);
private Color OffMidBot = Color.FromArgb(8, 28, 24);
private Pen pOffMidBot; // = new Pen(new SolidBrush(OffMidBot),1f);
private Color OffDrk = Color.FromArgb(0, 24, 24);
private Pen pOffDrk; // = new Pen(new SolidBrush(OffDrk),1f);
private Color OffDrkTop = Color.FromArgb(8, 28, 24);
private Pen pOffDrkTop; // = new Pen(new SolidBrush(OffDrkTop),1f);
private Color OffDrkBot = Color.FromArgb(0, 16, 16);
private Pen pOffDrkBot; // = new Pen(new SolidBrush(OffDrkBot),1f);
private EventHandler onPropertiesChanged;
/// <summary></summary>
public event EventHandler PropertiesChanged {
add {
if (onPropertiesChanged != null) {
foreach (Delegate d in onPropertiesChanged.GetInvocationList()) {
if (object.ReferenceEquals(d, value)) { return; }
}
}
onPropertiesChanged = (EventHandler)Delegate.Combine(onPropertiesChanged, value);
}
remove { onPropertiesChanged = (EventHandler)Delegate.Remove(onPropertiesChanged, value); }
}
private void FireChange() {
if (onPropertiesChanged != null) { onPropertiesChanged(this, EventArgs.Empty); }
}
/// <summary></summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected virtual void component_PropertiesChanged(object sender, EventArgs e) {
FireChange();
}
/// <summary></summary>
[Category("Painters"), Description("Gets or sets the chain of gloss painters"), Browsable(true)]
public IGlossPainter GlossPainter {
get { return this.gloss; }
set {
this.gloss = value;
if (this.gloss != null) { this.gloss.PropertiesChanged += new EventHandler(component_PropertiesChanged); }
FireChange();
}
}
/// <summary></summary>
[Category("Appearance"), Description("Gets or sets the type of FruityLoops progress style"), Browsable(true)]
public FruityLoopsProgressPainter.FruityLoopsProgressType FruityType {
get { return type; }
set {
type = value;
if (type == FruityLoopsProgressPainter.FruityLoopsProgressType.DoubleLayer) {
OffLit = Color.FromArgb(49, 69, 74);
pOffLit = new Pen(new SolidBrush(OffLit), 1f);
OffLitTop = Color.FromArgb(57, 77, 82);
pOffLitTop = new Pen(new SolidBrush(OffLitTop), 1f);
OffLitBot = Color.FromArgb(24, 48, 49);
pOffLitBot = new Pen(new SolidBrush(OffLitBot), 1f);
OffDrk = Color.FromArgb(24, 48, 49);
pOffDrk = new Pen(new SolidBrush(OffDrk), 1f);
OffDrkTop = Color.FromArgb(16, 40, 41);
pOffDrkTop = new Pen(new SolidBrush(OffDrkTop), 1f);
OffDrkBot = Color.FromArgb(8, 18, 24);
pOffDrkBot = new Pen(new SolidBrush(OffDrkBot), 1f);
} else if (type == FruityLoopsProgressPainter.FruityLoopsProgressType.TripleLayer) {
OffLit = Color.FromArgb(49, 69, 74);
pOffLit = new Pen(new SolidBrush(OffLit), 1f);
OffLitTop = Color.FromArgb(66, 85, 90);
pOffLitTop = new Pen(new SolidBrush(OffLitTop), 1f);
OffLitBot = Color.FromArgb(24, 48, 49);
pOffLitBot = new Pen(new SolidBrush(OffLitBot), 1f);
OffMid = Color.FromArgb(24, 48, 49);
pOffMid = new Pen(new SolidBrush(OffMid), 1f);
OffMidTop = Color.FromArgb(24, 48, 49);
pOffMidTop = new Pen(new SolidBrush(OffMidTop), 1f);
OffMidBot = Color.FromArgb(8, 28, 24);
pOffMidBot = new Pen(new SolidBrush(OffMidBot), 1f);
OffDrk = Color.FromArgb(0, 24, 24);
pOffDrk = new Pen(new SolidBrush(OffDrk), 1f);
OffDrkTop = Color.FromArgb(8, 28, 24);
pOffDrkTop = new Pen(new SolidBrush(OffDrkTop), 1f);
OffDrkBot = Color.FromArgb(0, 16, 16);
pOffDrkBot = new Pen(new SolidBrush(OffDrkBot), 1f);
}
FireChange();
}
}
/// <summary></summary>
/// <param name="box"></param>
/// <param name="g"></param>
public void PaintBackground(Rectangle box, Graphics g) {
if (img == null) {
if (type == FruityLoopsProgressPainter.FruityLoopsProgressType.DoubleLayer) {
PaintDouble(box, g);
} else if (type == FruityLoopsProgressPainter.FruityLoopsProgressType.TripleLayer) {
PaintTriple(box, g);
}
}
g.DrawImageUnscaled(img, 0, 0);
if (gloss != null) {
gloss.PaintGloss(box, g);
}
}
/// <summary></summary>
/// <param name="r"></param>
/// <param name="g"></param>
protected virtual void PaintDouble(Rectangle r, Graphics g) {
bool lite = true;
img = new Bitmap(r.Width + 1, r.Height + 1);
Graphics gi = Graphics.FromImage(img);
for (int i = 1; i < r.Width + 1; i++) {
if (lite) {
gi.DrawLine(pOffLitTop, i, r.Y, i, r.Y + 1);
gi.DrawLine(pOffLitBot, i, r.Height, i, r.Height - 1);
gi.DrawLine(pOffLit, i, r.Y + 1, i, r.Height - 1);
} else {
gi.DrawLine(pOffDrkTop, i, r.Y, i, r.Y + 1);
gi.DrawLine(pOffDrkBot, i, r.Height, i, r.Height - 1);
gi.DrawLine(pOffDrk, i, r.Y + 1, i, r.Height - 1);
}
lite = !lite;
}
gi.Dispose();
}
/// <summary></summary>
/// <param name="r"></param>
/// <param name="g"></param>
protected virtual void PaintTriple(Rectangle r, Graphics g) {
int lite = 1;
img = new Bitmap(r.Width + 1, r.Height + 1);
Graphics gi = Graphics.FromImage(img);
for (int i = 1; i < r.Width + 1; i++) {
if (lite == 2) {
gi.DrawLine(pOffLitTop, i, r.Y, i, r.Y + 1);
gi.DrawLine(pOffLitBot, i, r.Height, i, r.Height - 1);
gi.DrawLine(pOffLit, i, r.Y + 1, i, r.Height - 1);
lite = 0;
} else if (lite == 1) {
gi.DrawLine(pOffMidTop, i, r.Y, i, r.Y + 1);
gi.DrawLine(pOffMidBot, i, r.Height, i, r.Height - 1);
gi.DrawLine(pOffMid, i, r.Y + 1, i, r.Height - 1);
lite = 2;
} else if (lite == 0) {
gi.DrawLine(pOffDrkTop, i, r.Y, i, r.Y + 1);
gi.DrawLine(pOffDrkBot, i, r.Height, i, r.Height - 1);
gi.DrawLine(pOffDrk, i, r.Y + 1, i, r.Height - 1);
lite = 1;
}
}
gi.Dispose();
}
/// <summary></summary>
public void Resize(Rectangle box) {
img = null;
}
/// <summary></summary>
protected override void Dispose(bool disposing) {
base.Dispose(disposing);
if (img != null) { img.Dispose(); }
if (pOffLit != null) { pOffLit.Dispose(); }
if (pOffLitTop != null) { pOffLitTop.Dispose(); }
if (pOffLitBot != null) { pOffLitBot.Dispose(); }
if (pOffMid != null) { pOffMid.Dispose(); }
if (pOffMidTop != null) { pOffMidTop.Dispose(); }
if (pOffMidBot != null) { pOffMidBot.Dispose(); }
if (pOffDrk != null) { pOffDrk.Dispose(); }
if (pOffDrkTop != null) { pOffDrkTop.Dispose(); }
if (pOffDrkBot != null) { pOffDrkBot.Dispose(); }
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Activities.Presentation.Toolbox
{
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Runtime;
using System.Diagnostics.CodeAnalysis;
//This class is responsible for storing information about tools
//associated with given category item. The public interface is ICollection, the IList implementation is required for XAML support.
[SuppressMessage(FxCop.Category.Design, "CA1039:ListsAreStronglyTyped",
Justification = "The nongeneric IList implementation is required for XAML support. It is implmented explicitly.")]
[SuppressMessage(FxCop.Category.Naming, "CA1710:IdentifiersShouldHaveCorrectSuffix",
Justification = "The collection suffix 'Items' suits better.")]
public sealed class ToolboxCategoryItems : ICollection<ToolboxCategory>, IList
{
ObservableCollection<ToolboxCategory> categories;
public ToolboxCategoryItems() : this(null)
{
}
internal ToolboxCategoryItems(NotifyCollectionChangedEventHandler listener)
{
this.categories = new ObservableCollection<ToolboxCategory>();
if (null != listener)
{
this.categories.CollectionChanged += listener;
}
}
public ToolboxCategory this[int index]
{
get
{
return this.categories[index];
}
}
#region ICollection<ToolboxCategory> Members
public void Add(ToolboxCategory item)
{
if (null == item)
{
throw FxTrace.Exception.ArgumentNull("item");
}
this.categories.Add(item);
}
public void Clear()
{
this.categories.Clear();
}
public bool Contains(ToolboxCategory item)
{
if (null == item)
{
throw FxTrace.Exception.ArgumentNull("item");
}
return this.categories.Contains(item);
}
public void CopyTo(ToolboxCategory[] array, int arrayIndex)
{
if (null == array)
{
throw FxTrace.Exception.ArgumentNull("array");
}
this.categories.CopyTo(array, arrayIndex);
}
public int Count
{
get { return this.categories.Count; }
}
public bool IsReadOnly
{
get { return ((ICollection<ToolboxCategory>)this.categories).IsReadOnly; }
}
public bool Remove(ToolboxCategory item)
{
if (null == item)
{
throw FxTrace.Exception.ArgumentNull("item");
}
return this.categories.Remove(item);
}
#endregion
#region IEnumerable<ToolboxCategory> Members
public IEnumerator<ToolboxCategory> GetEnumerator()
{
return this.categories.GetEnumerator();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return this.categories.GetEnumerator();
}
#endregion
#region IList Members
int IList.Add(object value)
{
this.Add((ToolboxCategory)value);
return this.categories.IndexOf((ToolboxCategory)value);
}
void IList.Clear()
{
this.Clear();
}
bool IList.Contains(object value)
{
return this.Contains((ToolboxCategory)value);
}
int IList.IndexOf(object value)
{
return this.categories.IndexOf((ToolboxCategory)value);
}
void IList.Insert(int index, object value)
{
if (null == value)
{
throw FxTrace.Exception.ArgumentNull("value");
}
this.categories.Insert(index, (ToolboxCategory)value);
}
bool IList.IsFixedSize
{
get { return ((IList)this.categories).IsFixedSize; }
}
bool IList.IsReadOnly
{
get { return ((IList)this.categories).IsReadOnly; }
}
void IList.Remove(object value)
{
this.Remove((ToolboxCategory)value);
}
void IList.RemoveAt(int index)
{
this.categories.RemoveAt(index);
}
object IList.this[int index]
{
get
{
return (this)[index];
}
set
{
if (null == value)
{
throw FxTrace.Exception.ArgumentNull("value");
}
this.categories[index] = (ToolboxCategory)value;
}
}
#endregion
#region ICollection Members
void ICollection.CopyTo(Array array, int index)
{
if (null == array)
{
throw FxTrace.Exception.ArgumentNull("array");
}
((ICollection)this.categories).CopyTo(array, index);
}
int ICollection.Count
{
get { return this.Count; }
}
bool ICollection.IsSynchronized
{
get { return ((ICollection)this.categories).IsSynchronized; }
}
object ICollection.SyncRoot
{
get { return ((ICollection)this.categories).SyncRoot; }
}
#endregion
}
}
| |
using System;
using NUnit.Framework;
using OpenQA.Selenium.Environment;
namespace OpenQA.Selenium
{
[TestFixture]
public class ClickTest : DriverTestFixture
{
[SetUp]
public void SetupMethod()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("clicks.html");
}
[TearDown]
public void TearDownMethod()
{
driver.SwitchTo().DefaultContent();
}
[Test]
public void CanClickOnALinkAndFollowIt()
{
driver.FindElement(By.Id("normal")).Click();
WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'");
Assert.AreEqual("XHTML Test Page", driver.Title);
}
[Test]
[IgnoreBrowser(Browser.Opera, "Not tested")]
public void CanClickOnALinkThatOverflowsAndFollowIt()
{
driver.FindElement(By.Id("overflowLink")).Click();
WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'");
}
[Test]
public void CanClickOnAnAnchorAndNotReloadThePage()
{
((IJavaScriptExecutor)driver).ExecuteScript("document.latch = true");
driver.FindElement(By.Id("anchor")).Click();
bool samePage = (bool)((IJavaScriptExecutor)driver).ExecuteScript("return document.latch");
Assert.AreEqual(true, samePage, "Latch was reset");
}
[Test]
public void CanClickOnALinkThatUpdatesAnotherFrame()
{
driver.SwitchTo().Frame("source");
driver.FindElement(By.Id("otherframe")).Click();
driver.SwitchTo().DefaultContent().SwitchTo().Frame("target");
Assert.That(driver.PageSource, Does.Contain("Hello WebDriver"));
}
[Test]
public void ElementsFoundByJsCanLoadUpdatesInAnotherFrame()
{
driver.SwitchTo().Frame("source");
IWebElement toClick = (IWebElement)((IJavaScriptExecutor)driver).ExecuteScript("return document.getElementById('otherframe');");
toClick.Click();
driver.SwitchTo().DefaultContent().SwitchTo().Frame("target");
Assert.That(driver.PageSource, Does.Contain("Hello WebDriver"));
}
[Test]
public void JsLocatedElementsCanUpdateFramesIfFoundSomehowElse()
{
driver.SwitchTo().Frame("source");
// Prime the cache of elements
driver.FindElement(By.Id("otherframe"));
// This _should_ return the same element
IWebElement toClick = (IWebElement)((IJavaScriptExecutor)driver).ExecuteScript("return document.getElementById('otherframe');");
toClick.Click();
driver.SwitchTo().DefaultContent().SwitchTo().Frame("target");
Assert.That(driver.PageSource, Does.Contain("Hello WebDriver"));
}
[Test]
public void CanClickOnAnElementWithTopSetToANegativeNumber()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("styledPage.html");
IWebElement searchBox = driver.FindElement(By.Name("searchBox"));
searchBox.SendKeys("Cheese");
driver.FindElement(By.Name("btn")).Click();
string log = driver.FindElement(By.Id("log")).Text;
Assert.AreEqual("click", log);
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void ShouldSetRelatedTargetForMouseOver()
{
driver.Url = javascriptPage;
driver.FindElement(By.Id("movable")).Click();
string log = driver.FindElement(By.Id("result")).Text;
// Note: It is not guaranteed that the relatedTarget property of the mouseover
// event will be the parent, when using native events. Only check that the mouse
// has moved to this element, not that the parent element was the related target.
if (this.IsNativeEventsEnabled)
{
Assert.That(log, Does.StartWith("parent matches?"));
}
else
{
Assert.AreEqual("parent matches? true", log);
}
}
[Test]
public void ShouldClickOnFirstBoundingClientRectWithNonZeroSize()
{
driver.FindElement(By.Id("twoClientRects")).Click();
WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'");
Assert.AreEqual("XHTML Test Page", driver.Title);
}
[Test]
[NeedsFreshDriver(IsCreatedAfterTest = true)]
[IgnoreBrowser(Browser.Opera, "Doesn't support multiple windows")]
public void ShouldOnlyFollowHrefOnce()
{
driver.Url = clicksPage;
int windowHandlesBefore = driver.WindowHandles.Count;
driver.FindElement(By.Id("new-window")).Click();
WaitFor(() => { return driver.WindowHandles.Count >= windowHandlesBefore + 1; }, "Window handles was not " + (windowHandlesBefore + 1).ToString());
Assert.AreEqual(windowHandlesBefore + 1, driver.WindowHandles.Count);
}
[Test]
[Ignore("Ignored for all browsers")]
public void ShouldSetRelatedTargetForMouseOut()
{
Assert.Fail("Must. Write. Meamingful. Test (but we don't fire mouse outs synthetically");
}
[Test]
public void ClickingLabelShouldSetCheckbox()
{
driver.Url = formsPage;
driver.FindElement(By.Id("label-for-checkbox-with-label")).Click();
Assert.That(driver.FindElement(By.Id("checkbox-with-label")).Selected, "Checkbox should be selected");
}
[Test]
public void CanClickOnALinkWithEnclosedImage()
{
driver.FindElement(By.Id("link-with-enclosed-image")).Click();
WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'");
Assert.AreEqual("XHTML Test Page", driver.Title);
}
[Test]
public void CanClickOnAnImageEnclosedInALink()
{
driver.FindElement(By.Id("link-with-enclosed-image")).FindElement(By.TagName("img")).Click();
WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'");
Assert.AreEqual("XHTML Test Page", driver.Title);
}
[Test]
public void CanClickOnALinkThatContainsTextWrappedInASpan()
{
driver.FindElement(By.Id("link-with-enclosed-span")).Click();
WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'");
Assert.AreEqual("XHTML Test Page", driver.Title);
}
[Test]
public void CanClickOnALinkThatContainsEmbeddedBlockElements()
{
driver.FindElement(By.Id("embeddedBlock")).Click();
WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'");
Assert.AreEqual("XHTML Test Page", driver.Title);
}
[Test]
public void CanClickOnAnElementEnclosedInALink()
{
driver.FindElement(By.Id("link-with-enclosed-span")).FindElement(By.TagName("span")).Click();
WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'");
Assert.AreEqual("XHTML Test Page", driver.Title);
}
// See http://code.google.com/p/selenium/issues/attachmentText?id=2700
[Test]
public void ShouldBeAbleToClickOnAnElementInTheViewport()
{
string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_out_of_bounds.html");
driver.Url = url;
IWebElement button = driver.FindElement(By.Id("button"));
button.Click();
}
[Test]
public void ClicksASurroundingStrongTag()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("ClickTest_testClicksASurroundingStrongTag.html");
driver.FindElement(By.TagName("a")).Click();
WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'");
}
[Test]
[IgnoreBrowser(Browser.IE, "Map click fails")]
[IgnoreBrowser(Browser.Opera, "Map click fails")]
public void CanClickAnImageMapArea()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/google_map.html");
driver.FindElement(By.Id("rectG")).Click();
WaitFor(() => { return driver.Title == "Target Page 1"; }, "Browser title was not 'Target Page 1'");
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/google_map.html");
driver.FindElement(By.Id("circleO")).Click();
WaitFor(() => { return driver.Title == "Target Page 2"; }, "Browser title was not 'Target Page 2'");
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/google_map.html");
driver.FindElement(By.Id("polyLE")).Click();
WaitFor(() => { return driver.Title == "Target Page 3"; }, "Browser title was not 'Target Page 3'");
}
[Test]
public void ShouldBeAbleToClickOnAnElementGreaterThanTwoViewports()
{
string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_too_big.html");
driver.Url = url;
IWebElement element = driver.FindElement(By.Id("click"));
element.Click();
WaitFor(() => { return driver.Title == "clicks"; }, "Browser title was not 'clicks'");
}
[Test]
[IgnoreBrowser(Browser.Opera, "Not Tested")]
public void ShouldBeAbleToClickOnAnElementInFrameGreaterThanTwoViewports()
{
string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_too_big_in_frame.html");
driver.Url = url;
IWebElement frame = driver.FindElement(By.Id("iframe1"));
driver.SwitchTo().Frame(frame);
IWebElement element = driver.FindElement(By.Id("click"));
element.Click();
WaitFor(() => { return driver.Title == "clicks"; }, "Browser title was not 'clicks'");
}
[Test]
public void ShouldBeAbleToClickOnRightToLeftLanguageLink()
{
String url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_rtl.html");
driver.Url = url;
IWebElement element = driver.FindElement(By.Id("ar_link"));
element.Click();
WaitFor(() => driver.Title == "clicks", "Expected title to be 'clicks'");
Assert.AreEqual("clicks", driver.Title);
}
[Test]
public void ShouldBeAbleToClickOnLinkInAbsolutelyPositionedFooter()
{
string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("fixedFooterNoScroll.html");
driver.Url = url;
driver.FindElement(By.Id("link")).Click();
WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'");
Assert.AreEqual("XHTML Test Page", driver.Title);
}
[Test]
public void ShouldBeAbleToClickOnLinkInAbsolutelyPositionedFooterInQuirksMode()
{
string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("fixedFooterNoScrollQuirksMode.html");
driver.Url = url;
driver.FindElement(By.Id("link")).Click();
WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'");
Assert.AreEqual("XHTML Test Page", driver.Title);
}
[Test]
public void ShouldBeAbleToClickOnLinksWithNoHrefAttribute()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.LinkText("No href"));
element.Click();
WaitFor(() => driver.Title == "Changed", "Expected title to be 'Changed'");
Assert.AreEqual("Changed", driver.Title);
}
[Test]
public void ShouldBeAbleToClickOnALinkThatWrapsToTheNextLine()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/link_that_wraps.html");
driver.FindElement(By.Id("link")).Click();
WaitFor(() => driver.Title == "Submitted Successfully!", "Expected title to be 'Submitted Successfully!'");
Assert.AreEqual("Submitted Successfully!", driver.Title);
}
[Test]
public void ShouldBeAbleToClickOnASpanThatWrapsToTheNextLine()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/span_that_wraps.html");
driver.FindElement(By.Id("span")).Click();
WaitFor(() => driver.Title == "Submitted Successfully!", "Expected title to be 'Submitted Successfully!'");
Assert.AreEqual("Submitted Successfully!", driver.Title);
}
[Test]
[IgnoreBrowser(Browser.IE, "Element is properly seen as obscured.")]
[IgnoreBrowser(Browser.Chrome, "Element is properly seen as obscured.")]
[IgnoreBrowser(Browser.Edge, "Element is properly seen as obscured.")]
[IgnoreBrowser(Browser.EdgeLegacy, "Element is properly seen as obscured.")]
[IgnoreBrowser(Browser.Firefox, "Element is properly seen as obscured.")]
[IgnoreBrowser(Browser.Safari, "Element is properly seen as obscured.")]
public void ShouldBeAbleToClickOnAPartiallyOverlappedLinkThatWrapsToTheNextLine()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/wrapped_overlapping_elements.html");
driver.FindElement(By.Id("link")).Click();
WaitFor(() => driver.Title == "Submitted Successfully!", "Expected title to be 'Submitted Successfully!'");
Assert.AreEqual("Submitted Successfully!", driver.Title);
}
[Test]
public void ClickingOnADisabledElementIsANoOp()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/disabled_element.html");
IWebElement element = driver.FindElement(By.Name("disabled"));
element.Click();
}
//------------------------------------------------------------------
// Tests below here are not included in the Java test suite
//------------------------------------------------------------------
[Test]
public void ShouldBeAbleToClickLinkContainingLineBreak()
{
driver.Url = simpleTestPage;
driver.FindElement(By.Id("multilinelink")).Click();
WaitFor(() => { return driver.Title == "We Arrive Here"; }, "Browser title was not 'We Arrive Here'");
Assert.AreEqual("We Arrive Here", driver.Title);
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using gagr = Google.Api.Gax.ResourceNames;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Billing.Budgets.V1Beta1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedBudgetServiceClientTest
{
[xunit::FactAttribute]
public void CreateBudgetRequestObject()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
CreateBudgetRequest request = new CreateBudgetRequest
{
ParentAsBillingAccountName = gagr::BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"),
Budget = new Budget(),
};
Budget expectedResponse = new Budget
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
DisplayName = "display_name137f65c2",
BudgetFilter = new Filter(),
Amount = new BudgetAmount(),
ThresholdRules =
{
new ThresholdRule(),
},
AllUpdatesRule = new AllUpdatesRule(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.CreateBudget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
Budget response = client.CreateBudget(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateBudgetRequestObjectAsync()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
CreateBudgetRequest request = new CreateBudgetRequest
{
ParentAsBillingAccountName = gagr::BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"),
Budget = new Budget(),
};
Budget expectedResponse = new Budget
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
DisplayName = "display_name137f65c2",
BudgetFilter = new Filter(),
Amount = new BudgetAmount(),
ThresholdRules =
{
new ThresholdRule(),
},
AllUpdatesRule = new AllUpdatesRule(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.CreateBudgetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Budget>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
Budget responseCallSettings = await client.CreateBudgetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Budget responseCancellationToken = await client.CreateBudgetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateBudgetRequestObject()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
UpdateBudgetRequest request = new UpdateBudgetRequest
{
Budget = new Budget(),
UpdateMask = new wkt::FieldMask(),
};
Budget expectedResponse = new Budget
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
DisplayName = "display_name137f65c2",
BudgetFilter = new Filter(),
Amount = new BudgetAmount(),
ThresholdRules =
{
new ThresholdRule(),
},
AllUpdatesRule = new AllUpdatesRule(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.UpdateBudget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
Budget response = client.UpdateBudget(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateBudgetRequestObjectAsync()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
UpdateBudgetRequest request = new UpdateBudgetRequest
{
Budget = new Budget(),
UpdateMask = new wkt::FieldMask(),
};
Budget expectedResponse = new Budget
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
DisplayName = "display_name137f65c2",
BudgetFilter = new Filter(),
Amount = new BudgetAmount(),
ThresholdRules =
{
new ThresholdRule(),
},
AllUpdatesRule = new AllUpdatesRule(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.UpdateBudgetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Budget>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
Budget responseCallSettings = await client.UpdateBudgetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Budget responseCancellationToken = await client.UpdateBudgetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetBudgetRequestObject()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
GetBudgetRequest request = new GetBudgetRequest
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
};
Budget expectedResponse = new Budget
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
DisplayName = "display_name137f65c2",
BudgetFilter = new Filter(),
Amount = new BudgetAmount(),
ThresholdRules =
{
new ThresholdRule(),
},
AllUpdatesRule = new AllUpdatesRule(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetBudget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
Budget response = client.GetBudget(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetBudgetRequestObjectAsync()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
GetBudgetRequest request = new GetBudgetRequest
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
};
Budget expectedResponse = new Budget
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
DisplayName = "display_name137f65c2",
BudgetFilter = new Filter(),
Amount = new BudgetAmount(),
ThresholdRules =
{
new ThresholdRule(),
},
AllUpdatesRule = new AllUpdatesRule(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetBudgetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Budget>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
Budget responseCallSettings = await client.GetBudgetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Budget responseCancellationToken = await client.GetBudgetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteBudgetRequestObject()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
DeleteBudgetRequest request = new DeleteBudgetRequest
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteBudget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteBudget(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteBudgetRequestObjectAsync()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
DeleteBudgetRequest request = new DeleteBudgetRequest
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteBudgetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteBudgetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteBudgetAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
}
}
| |
/*
* @(#)CheckAttribsImpl.java 1.11 2000/08/16
*
*/
using System;
namespace Comzept.Genesis.Tidy
{
/// <summary>
/// Check HTML attributes implementation
///
/// (c) 1998-2000 (W3C) MIT, INRIA, Keio University
/// See Tidy.java for the copyright notice.
/// Derived from <a href="http://www.w3.org/People/Raggett/tidy">
/// HTML Tidy Release 4 Aug 2000</a>
///
/// </summary>
/// <author> Dave Raggett dsr@w3.org
/// </author>
/// <author> Andy Quick ac.quick@sympatico.ca (translation to Java)
/// </author>
/// <version> 1.0, 1999/05/22
/// </version>
/// <version> 1.0.1, 1999/05/29
/// </version>
/// <version> 1.1, 1999/06/18 Java Bean
/// </version>
/// <version> 1.2, 1999/07/10 Tidy Release 7 Jul 1999
/// </version>
/// <version> 1.3, 1999/07/30 Tidy Release 26 Jul 1999
/// </version>
/// <version> 1.4, 1999/09/04 DOM support
/// </version>
/// <version> 1.5, 1999/10/23 Tidy Release 27 Sep 1999
/// </version>
/// <version> 1.6, 1999/11/01 Tidy Release 22 Oct 1999
/// </version>
/// <version> 1.7, 1999/12/06 Tidy Release 30 Nov 1999
/// </version>
/// <version> 1.8, 2000/01/22 Tidy Release 13 Jan 2000
/// </version>
/// <version> 1.9, 2000/06/03 Tidy Release 30 Apr 2000
/// </version>
/// <version> 1.10, 2000/07/22 Tidy Release 8 Jul 2000
/// </version>
/// <version> 1.11, 2000/08/16 Tidy Release 4 Aug 2000
/// </version>
public class CheckAttribsImpl
{
public class CheckHTML : CheckAttribs
{
public virtual void Check(Lexer lexer, Node node)
{
AttVal attval;
Attribute attribute;
node.checkUniqueAttributes(lexer);
for (attval = node.attributes; attval != null; attval = attval.next)
{
attribute = attval.checkAttribute(lexer, node);
if (attribute == AttributeTable.attrXmlns)
lexer.isvoyager = true;
}
}
}
public class CheckSCRIPT : CheckAttribs
{
public virtual void Check(Lexer lexer, Node node)
{
Attribute attribute;
AttVal lang, type;
node.checkUniqueAttributes(lexer);
lang = node.getAttrByName("language");
type = node.getAttrByName("type");
if (type == null)
{
Report.attrError(lexer, node, "type", Report.MISSING_ATTRIBUTE);
/* check for javascript */
if (lang != null)
{
System.String str = lang.value_Renamed;
if (str.Length > 10)
str = str.Substring(0, (10) - (0));
if ((Lexer.wstrcasecmp(str, "javascript") == 0) || (Lexer.wstrcasecmp(str, "jscript") == 0))
{
node.addAttribute("type", "text/javascript");
}
}
else
node.addAttribute("type", "text/javascript");
}
}
}
public class CheckTABLE : CheckAttribs
{
public virtual void Check(Lexer lexer, Node node)
{
AttVal attval;
Attribute attribute;
bool hasSummary = false;
node.checkUniqueAttributes(lexer);
for (attval = node.attributes; attval != null; attval = attval.next)
{
attribute = attval.checkAttribute(lexer, node);
if (attribute == AttributeTable.attrSummary)
hasSummary = true;
}
/* suppress warning for missing summary for HTML 2.0 and HTML 3.2 */
if (!hasSummary && lexer.doctype != Dict.VERS_HTML20 && lexer.doctype != Dict.VERS_HTML32)
{
lexer.badAccess |= Report.MISSING_SUMMARY;
Report.attrError(lexer, node, "summary", Report.MISSING_ATTRIBUTE);
}
/* convert <table border> to <table border="1"> */
if (lexer.configuration.XmlOut)
{
attval = node.getAttrByName("border");
if (attval != null)
{
if (attval.value_Renamed == null)
attval.value_Renamed = "1";
}
}
}
}
public class CheckCaption : CheckAttribs
{
public virtual void Check(Lexer lexer, Node node)
{
AttVal attval;
System.String value_Renamed = null;
node.checkUniqueAttributes(lexer);
for (attval = node.attributes; attval != null; attval = attval.next)
{
if (Lexer.wstrcasecmp(attval.attribute, "align") == 0)
{
value_Renamed = attval.value_Renamed;
break;
}
}
if (value_Renamed != null)
{
if (Lexer.wstrcasecmp(value_Renamed, "left") == 0 || Lexer.wstrcasecmp(value_Renamed, "right") == 0)
lexer.versions &= (short) (Dict.VERS_HTML40_LOOSE | Dict.VERS_FRAMES);
else if (Lexer.wstrcasecmp(value_Renamed, "top") == 0 || Lexer.wstrcasecmp(value_Renamed, "bottom") == 0)
lexer.versions &= Dict.VERS_FROM32;
else
Report.attrError(lexer, node, value_Renamed, Report.BAD_ATTRIBUTE_VALUE);
}
}
}
public class CheckHR : CheckAttribs
{
public virtual void Check(Lexer lexer, Node node)
{
if (node.getAttrByName("src") != null)
Report.attrError(lexer, node, "src", Report.PROPRIETARY_ATTR_VALUE);
}
}
public class CheckIMG : CheckAttribs
{
public virtual void Check(Lexer lexer, Node node)
{
AttVal attval;
Attribute attribute;
bool hasAlt = false;
bool hasSrc = false;
bool hasUseMap = false;
bool hasIsMap = false;
bool hasDataFld = false;
node.checkUniqueAttributes(lexer);
for (attval = node.attributes; attval != null; attval = attval.next)
{
attribute = attval.checkAttribute(lexer, node);
if (attribute == AttributeTable.attrAlt)
hasAlt = true;
else if (attribute == AttributeTable.attrSrc)
hasSrc = true;
else if (attribute == AttributeTable.attrUsemap)
hasUseMap = true;
else if (attribute == AttributeTable.attrIsmap)
hasIsMap = true;
else if (attribute == AttributeTable.attrDatafld)
hasDataFld = true;
else if (attribute == AttributeTable.attrWidth || attribute == AttributeTable.attrHeight)
lexer.versions &= ~ Dict.VERS_HTML20;
}
if (!hasAlt)
{
lexer.badAccess |= Report.MISSING_IMAGE_ALT;
Report.attrError(lexer, node, "alt", Report.MISSING_ATTRIBUTE);
if (lexer.configuration.altText != null)
node.addAttribute("alt", lexer.configuration.altText);
}
if (!hasSrc && !hasDataFld)
Report.attrError(lexer, node, "src", Report.MISSING_ATTRIBUTE);
if (hasIsMap && !hasUseMap)
Report.attrError(lexer, node, "ismap", Report.MISSING_IMAGEMAP);
}
}
public class CheckAREA : CheckAttribs
{
public virtual void Check(Lexer lexer, Node node)
{
AttVal attval;
Attribute attribute;
bool hasAlt = false;
bool hasHref = false;
node.checkUniqueAttributes(lexer);
for (attval = node.attributes; attval != null; attval = attval.next)
{
attribute = attval.checkAttribute(lexer, node);
if (attribute == AttributeTable.attrAlt)
hasAlt = true;
else if (attribute == AttributeTable.attrHref)
hasHref = true;
}
if (!hasAlt)
{
lexer.badAccess |= Report.MISSING_LINK_ALT;
Report.attrError(lexer, node, "alt", Report.MISSING_ATTRIBUTE);
}
if (!hasHref)
Report.attrError(lexer, node, "href", Report.MISSING_ATTRIBUTE);
}
}
public class CheckAnchor : CheckAttribs
{
public virtual void Check(Lexer lexer, Node node)
{
node.checkUniqueAttributes(lexer);
lexer.fixId(node);
}
}
public class CheckMap : CheckAttribs
{
public virtual void Check(Lexer lexer, Node node)
{
node.checkUniqueAttributes(lexer);
lexer.fixId(node);
}
}
public class CheckSTYLE : CheckAttribs
{
public virtual void Check(Lexer lexer, Node node)
{
AttVal type = node.getAttrByName("type");
node.checkUniqueAttributes(lexer);
if (type == null)
{
Report.attrError(lexer, node, "type", Report.MISSING_ATTRIBUTE);
node.addAttribute("type", "text/css");
}
}
}
public class CheckTableCell : CheckAttribs
{
public virtual void Check(Lexer lexer, Node node)
{
node.checkUniqueAttributes(lexer);
/*
HTML4 strict doesn't allow mixed content for
elements with %block; as their content model
*/
if (node.getAttrByName("width") != null || node.getAttrByName("height") != null)
lexer.versions &= ~ Dict.VERS_HTML40_STRICT;
}
}
/* add missing type attribute when appropriate */
public class CheckLINK : CheckAttribs
{
public virtual void Check(Lexer lexer, Node node)
{
AttVal rel = node.getAttrByName("rel");
node.checkUniqueAttributes(lexer);
if (rel != null && rel.value_Renamed != null && rel.value_Renamed.Equals("stylesheet"))
{
AttVal type = node.getAttrByName("type");
if (type == null)
{
Report.attrError(lexer, node, "type", Report.MISSING_ATTRIBUTE);
node.addAttribute("type", "text/css");
}
}
}
}
public static CheckAttribs getCheckHTML()
{
return _checkHTML;
}
public static CheckAttribs getCheckSCRIPT()
{
return _checkSCRIPT;
}
public static CheckAttribs getCheckTABLE()
{
return _checkTABLE;
}
public static CheckAttribs getCheckCaption()
{
return _checkCaption;
}
public static CheckAttribs getCheckIMG()
{
return _checkIMG;
}
public static CheckAttribs getCheckAREA()
{
return _checkAREA;
}
public static CheckAttribs getCheckAnchor()
{
return _checkAnchor;
}
public static CheckAttribs getCheckMap()
{
return _checkMap;
}
public static CheckAttribs getCheckSTYLE()
{
return _checkStyle;
}
public static CheckAttribs getCheckTableCell()
{
return _checkTableCell;
}
public static CheckAttribs getCheckLINK()
{
return _checkLINK;
}
public static CheckAttribs getCheckHR()
{
return _checkHR;
}
private static CheckAttribs _checkHTML = new CheckHTML();
private static CheckAttribs _checkSCRIPT = new CheckSCRIPT();
private static CheckAttribs _checkTABLE = new CheckTABLE();
private static CheckAttribs _checkCaption = new CheckCaption();
private static CheckAttribs _checkIMG = new CheckIMG();
private static CheckAttribs _checkAREA = new CheckAREA();
private static CheckAttribs _checkAnchor = new CheckAnchor();
private static CheckAttribs _checkMap = new CheckMap();
private static CheckAttribs _checkStyle = new CheckSTYLE();
private static CheckAttribs _checkTableCell = new CheckTableCell();
private static CheckAttribs _checkLINK = new CheckLINK();
private static CheckAttribs _checkHR = new CheckHR();
}
}
| |
// 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 Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Buffers.Text;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Formatting;
using System.Text.JsonLab.Tests.Resources;
using System.Text.Utf8;
using Xunit;
namespace System.Text.JsonLab.Tests
{
public class JsonObjectTests
{
public static IEnumerable<object[]> TestCases
{
get
{
return new List<object[]>
{
new object[] { true, TestCaseType.Basic, TestJson.BasicJson},
new object[] { true, TestCaseType.BasicLargeNum, TestJson.BasicJsonWithLargeNum}, // Json.NET treats numbers starting with 0 as octal (0425 becomes 277)
new object[] { true, TestCaseType.BroadTree, TestJson.BroadTree}, // \r\n behavior is different between Json.NET and JsonLab
new object[] { true, TestCaseType.DeepTree, TestJson.DeepTree},
new object[] { true, TestCaseType.FullSchema1, TestJson.FullJsonSchema1},
//new object[] { true, TestCaseType.FullSchema2, TestJson.FullJsonSchema2}, // Behavior of E-notation is different between Json.NET and JsonLab
new object[] { true, TestCaseType.HelloWorld, TestJson.HelloWorld},
new object[] { true, TestCaseType.LotsOfNumbers, TestJson.LotsOfNumbers},
new object[] { true, TestCaseType.LotsOfStrings, TestJson.LotsOfStrings},
new object[] { true, TestCaseType.ProjectLockJson, TestJson.ProjectLockJson},
//new object[] { true, TestCaseType.SpecialStrings, TestJson.JsonWithSpecialStrings}, // Behavior of escaping is different between Json.NET and JsonLab
//new object[] { true, TestCaseType.SpecialNumForm, TestJson.JsonWithSpecialNumFormat}, // Behavior of E-notation is different between Json.NET and JsonLab
new object[] { true, TestCaseType.Json400B, TestJson.Json400B},
new object[] { true, TestCaseType.Json4KB, TestJson.Json4KB},
new object[] { true, TestCaseType.Json40KB, TestJson.Json40KB},
new object[] { true, TestCaseType.Json400KB, TestJson.Json400KB},
new object[] { false, TestCaseType.Basic, TestJson.BasicJson},
new object[] { false, TestCaseType.BasicLargeNum, TestJson.BasicJsonWithLargeNum}, // Json.NET treats numbers starting with 0 as octal (0425 becomes 277)
new object[] { false, TestCaseType.BroadTree, TestJson.BroadTree}, // \r\n behavior is different between Json.NET and JsonLab
new object[] { false, TestCaseType.DeepTree, TestJson.DeepTree},
new object[] { false, TestCaseType.FullSchema1, TestJson.FullJsonSchema1},
//new object[] { false, TestCaseType.FullSchema2, TestJson.FullJsonSchema2}, // Behavior of E-notation is different between Json.NET and JsonLab
new object[] { false, TestCaseType.HelloWorld, TestJson.HelloWorld},
new object[] { false, TestCaseType.LotsOfNumbers, TestJson.LotsOfNumbers},
new object[] { false, TestCaseType.LotsOfStrings, TestJson.LotsOfStrings},
new object[] { false, TestCaseType.ProjectLockJson, TestJson.ProjectLockJson},
//new object[] { false, TestCaseType.SpecialStrings, TestJson.JsonWithSpecialStrings}, // Behavior of escaping is different between Json.NET and JsonLab
//new object[] { false, TestCaseType.SpecialNumForm, TestJson.JsonWithSpecialNumFormat}, // Behavior of E-notation is different between Json.NET and JsonLab
new object[] { false, TestCaseType.Json400B, TestJson.Json400B},
new object[] { false, TestCaseType.Json4KB, TestJson.Json4KB},
new object[] { false, TestCaseType.Json40KB, TestJson.Json40KB},
new object[] { false, TestCaseType.Json400KB, TestJson.Json400KB}
};
}
}
// TestCaseType is only used to give the json strings a descriptive name within the unit tests.
public enum TestCaseType
{
HelloWorld,
Basic,
BasicLargeNum,
SpecialNumForm,
SpecialStrings,
ProjectLockJson,
FullSchema1,
FullSchema2,
DeepTree,
BroadTree,
LotsOfNumbers,
LotsOfStrings,
Json400B,
Json4KB,
Json40KB,
Json400KB,
}
private string ReadHelloWorld(JToken obj)
{
string message = (string)obj["message"];
return message;
}
private string ReadJson400KB(JToken obj)
{
var sb = new StringBuilder();
foreach (JToken token in obj)
{
sb.Append((string)token["_id"]);
sb.Append((int)token["index"]);
sb.Append((string)token["guid"]);
sb.Append((bool)token["isActive"]);
sb.Append((string)token["balance"]);
sb.Append((string)token["picture"]);
sb.Append((int)token["age"]);
sb.Append((string)token["eyeColor"]);
sb.Append((string)token["name"]);
sb.Append((string)token["gender"]);
sb.Append((string)token["company"]);
sb.Append((string)token["email"]);
sb.Append((string)token["phone"]);
sb.Append((string)token["address"]);
sb.Append((string)token["about"]);
sb.Append((string)token["registered"]);
sb.Append((double)token["latitude"]);
sb.Append((double)token["longitude"]);
JToken tags = token["tags"];
foreach (JToken tag in tags)
{
sb.Append((string)tag);
}
JToken friends = token["friends"];
foreach (JToken friend in friends)
{
sb.Append((int)friend["id"]);
sb.Append((string)friend["name"]);
}
sb.Append((string)token["greeting"]);
sb.Append((string)token["favoriteFruit"]);
}
return sb.ToString();
}
private string ReadHelloWorld(JsonObject obj)
{
string message = (string)obj["message"];
return message;
}
private string ReadJson400KB(JsonObject obj)
{
var sb = new StringBuilder();
for (int i = 0; i < obj.ArrayLength; i++)
{
sb.Append((string)obj[i]["_id"]);
sb.Append((int)obj[i]["index"]);
sb.Append((string)obj[i]["guid"]);
sb.Append((bool)obj[i]["isActive"]);
sb.Append((string)obj[i]["balance"]);
sb.Append((string)obj[i]["picture"]);
sb.Append((int)obj[i]["age"]);
sb.Append((string)obj[i]["eyeColor"]);
sb.Append((string)obj[i]["name"]);
sb.Append((string)obj[i]["gender"]);
sb.Append((string)obj[i]["company"]);
sb.Append((string)obj[i]["email"]);
sb.Append((string)obj[i]["phone"]);
sb.Append((string)obj[i]["address"]);
sb.Append((string)obj[i]["about"]);
sb.Append((string)obj[i]["registered"]);
sb.Append((double)obj[i]["latitude"]);
sb.Append((double)obj[i]["longitude"]);
JsonObject tags = obj[i]["tags"];
for (int j = 0; j < tags.ArrayLength; j++)
{
sb.Append((string)tags[j]);
}
JsonObject friends = obj[i]["friends"];
for (int j = 0; j < friends.ArrayLength; j++)
{
sb.Append((int)friends[j]["id"]);
sb.Append((string)friends[j]["name"]);
}
sb.Append((string)obj[i]["greeting"]);
sb.Append((string)obj[i]["favoriteFruit"]);
}
return sb.ToString();
}
// TestCaseType is only used to give the json strings a descriptive name.
[Theory]
[MemberData(nameof(TestCases))]
public void ParseJson(bool compactData, TestCaseType type, string jsonString)
{
// Remove all formatting/indendation
if (compactData)
{
using (JsonTextReader jsonReader = new JsonTextReader(new StringReader(jsonString)))
{
jsonReader.FloatParseHandling = FloatParseHandling.Decimal;
JToken jtoken = JToken.ReadFrom(jsonReader);
var stringWriter = new StringWriter();
using (JsonTextWriter jsonWriter = new JsonTextWriter(stringWriter))
{
jtoken.WriteTo(jsonWriter);
jsonString = stringWriter.ToString();
}
}
}
byte[] dataUtf8 = Encoding.UTF8.GetBytes(jsonString);
JsonObject obj = JsonObject.Parse(dataUtf8);
var stream = new MemoryStream(dataUtf8);
var streamReader = new StreamReader(stream, Encoding.UTF8, false, 1024, true);
using (JsonTextReader jsonReader = new JsonTextReader(streamReader))
{
JToken jtoken = JToken.ReadFrom(jsonReader);
string expectedString = "";
string actualString = "";
if (type == TestCaseType.Json400KB)
{
expectedString = ReadJson400KB(jtoken);
actualString = ReadJson400KB(obj);
}
else if (type == TestCaseType.HelloWorld)
{
expectedString = ReadHelloWorld(jtoken);
actualString = ReadHelloWorld(obj);
}
Assert.Equal(expectedString, actualString);
}
string actual = obj.PrintJson();
// Change casing to match what JSON.NET does.
actual = actual.Replace("true", "True").Replace("false", "False");
TextReader reader = new StringReader(jsonString);
string expected = JsonTestHelper.NewtonsoftReturnStringHelper(reader);
Assert.Equal(expected, actual);
if (compactData)
{
var output = new ArrayFormatterWrapper(1024, SymbolTable.InvariantUtf8);
var jsonUtf8 = new Utf8JsonWriter<ArrayFormatterWrapper>(output);
jsonUtf8.Write(obj);
jsonUtf8.Flush();
ArraySegment<byte> formatted = output.Formatted;
string actualStr = Encoding.UTF8.GetString(formatted.Array, formatted.Offset, formatted.Count);
Assert.Equal(jsonString, actualStr);
}
obj.Dispose();
}
[Theory]
[InlineData("[{\"arrayWithObjects\":[\"text\",14,[],null,false,{},{\"time\":24},[\"1\",\"2\",\"3\"]]}]")]
[InlineData("[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]")]
[InlineData("[{\"a\":{}},{\"a\":{}},{\"a\":{}},{\"a\":{}},{\"a\":{}},{\"a\":{}},{\"a\":{}},{\"a\":{}},{\"a\":{}},{\"a\":{}},{\"a\":{}},{\"a\":{}},{\"a\":{}},{\"a\":{}},{\"a\":{}},{\"a\":{}},{\"a\":{}},{\"a\":{}}]")]
[InlineData("{\"a\":\"b\"}")]
[InlineData("{}")]
[InlineData("[]")]
public void CustomParseJson(string jsonString)
{
byte[] dataUtf8 = Encoding.UTF8.GetBytes(jsonString);
JsonObject obj = JsonObject.Parse(dataUtf8);
string actual = obj.PrintJson();
// Change casing to match what JSON.NET does.
actual = actual.Replace("true", "True").Replace("false", "False");
TextReader reader = new StringReader(jsonString);
string expected = JsonTestHelper.NewtonsoftReturnStringHelper(reader);
Assert.Equal(expected, actual);
}
[Fact]
public void ChangeEntryPointLibraryName()
{
string depsJson = TestJson.DepsJsonSignalR;
byte[] dataUtf8 = Encoding.UTF8.GetBytes(depsJson);
JsonObject obj = JsonObject.Parse(dataUtf8);
var targetsString = new Utf8Span("targets");
var librariesString = new Utf8Span("libraries");
JsonObject targets = obj[targetsString];
foreach (JsonObject target in targets)
{
Assert.True(target.TryGetChild(out JsonObject firstChild));
obj.Remove(firstChild);
}
JsonObject libraries = obj[librariesString];
Assert.True(libraries.TryGetChild(out JsonObject child));
obj.Remove(child);
string expected = ChangeEntryPointLibraryNameExpected();
var output = new ArrayFormatterWrapper(1024, SymbolTable.InvariantUtf8);
var jsonUtf8 = new Utf8JsonWriter<ArrayFormatterWrapper>(output);
jsonUtf8.Write(obj);
jsonUtf8.Flush();
ArraySegment<byte> formatted = output.Formatted;
string actualStr = Encoding.UTF8.GetString(formatted.Array, formatted.Offset, formatted.Count);
Assert.Equal(expected, actualStr);
}
[Fact]
public void ParseArray()
{
var buffer = StringToUtf8BufferWithEmptySpace(TestJson.SimpleArrayJson, 60);
JsonObject parsedObject = JsonObject.Parse(buffer);
try
{
Assert.Equal(2, parsedObject.ArrayLength);
var phoneNumber = (string)parsedObject[0];
var age = (int)parsedObject[1];
Assert.Equal("425-214-3151", phoneNumber);
Assert.Equal(25, age);
}
finally
{
parsedObject.Dispose();
}
}
[Fact]
public void ParseSimpleObject()
{
var buffer = StringToUtf8BufferWithEmptySpace(TestJson.SimpleObjectJson);
JsonObject parsedObject = JsonObject.Parse(buffer);
try
{
var age = (int)parsedObject["age"];
var ageStrring = (string)parsedObject["age"];
var first = (string)parsedObject["first"];
var last = (string)parsedObject["last"];
var phoneNumber = (string)parsedObject["phoneNumber"];
var street = (string)parsedObject["street"];
var city = (string)parsedObject["city"];
var zip = (int)parsedObject["zip"];
Assert.True(parsedObject.TryGetValue("age", out JsonObject age2));
Assert.Equal((int)age2, 30);
Assert.Equal(age, 30);
Assert.Equal(ageStrring, "30");
Assert.Equal(first, "John");
Assert.Equal(last, "Smith");
Assert.Equal(phoneNumber, "425-214-3151");
Assert.Equal(street, "1 Microsoft Way");
Assert.Equal(city, "Redmond");
Assert.Equal(zip, 98052);
}
finally
{
parsedObject.Dispose();
}
}
[Fact]
public void ParseNestedJson()
{
var buffer = StringToUtf8BufferWithEmptySpace(TestJson.ParseJson);
JsonObject parsedObject = JsonObject.Parse(buffer);
try
{
Assert.Equal(1, parsedObject.ArrayLength);
var person = parsedObject[0];
var age = (double)person["age"];
var first = (string)person["first"];
var last = (string)person["last"];
var phoneNums = person["phoneNumbers"];
Assert.Equal(2, phoneNums.ArrayLength);
var phoneNum1 = (string)phoneNums[0];
var phoneNum2 = (string)phoneNums[1];
var address = person["address"];
var street = (string)address["street"];
var city = (string)address["city"];
var zipCode = (double)address["zip"];
Assert.Equal(30, age);
Assert.Equal("John", first);
Assert.Equal("Smith", last);
Assert.Equal("425-000-1212", phoneNum1);
Assert.Equal("425-000-1213", phoneNum2);
Assert.Equal("1 Microsoft Way", street);
Assert.Equal("Redmond", city);
Assert.Equal(98052, zipCode);
try
{
var _ = person.ArrayLength;
throw new Exception("Never get here");
}
catch (Exception ex)
{
Assert.IsType<InvalidOperationException>(ex);
}
try
{
var _ = phoneNums[2];
throw new Exception("Never get here");
}
catch (Exception ex)
{
Assert.IsType<IndexOutOfRangeException>(ex);
}
}
finally
{
parsedObject.Dispose();
}
// Exceptional use case
//var a = x[1]; // IndexOutOfRangeException
//var b = x["age"]; // NullReferenceException
//var c = person[0]; // NullReferenceException
//var d = address["cit"]; // KeyNotFoundException
//var e = address[0]; // NullReferenceException
//var f = (double)address["city"]; // InvalidCastException
//var g = (bool)address["city"]; // InvalidCastException
//var h = (string)address["zip"]; // Integer converted to string implicitly
//var i = (string)person["phoneNumbers"]; // InvalidCastException
//var j = (string)person; // InvalidCastException
}
[Fact]
public void ParseBoolean()
{
var buffer = StringToUtf8BufferWithEmptySpace("[true,false]", 60);
JsonObject parsedObject = JsonObject.Parse(buffer);
try
{
var first = (bool)parsedObject[0];
var second = (bool)parsedObject[1];
Assert.Equal(true, first);
Assert.Equal(false, second);
}
finally
{
parsedObject.Dispose();
}
}
private static ArraySegment<byte> StringToUtf8BufferWithEmptySpace(string testString, int emptySpaceSize = 2048)
{
var utf8Bytes = new Utf8Span(testString).Bytes;
var buffer = new byte[utf8Bytes.Length + emptySpaceSize];
utf8Bytes.CopyTo(buffer);
return new ArraySegment<byte>(buffer, 0, utf8Bytes.Length);
}
private static string ChangeEntryPointLibraryNameExpected()
{
JToken deps = JObject.Parse(TestJson.DepsJsonSignalR);
foreach (JProperty target in deps["targets"])
{
JProperty targetLibrary = target.Value.Children<JProperty>().FirstOrDefault();
if (targetLibrary == null)
{
continue;
}
targetLibrary.Remove();
}
JProperty library = deps["libraries"].Children<JProperty>().First();
library.Remove();
using (var textWriter = new StringWriter())
using (var writer = new JsonTextWriter(textWriter))
{
deps.WriteTo(writer);
return textWriter.ToString();
}
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmExportUt
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmExportUt() : base()
{
Load += frmExportUt_Load;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.Button withEventsField_cmdExit;
public System.Windows.Forms.Button cmdExit {
get { return withEventsField_cmdExit; }
set {
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click -= cmdExit_Click;
}
withEventsField_cmdExit = value;
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click += cmdExit_Click;
}
}
}
public System.Windows.Forms.Button cmdClose;
public System.Windows.Forms.Panel picButtons;
public System.Windows.Forms.OpenFileDialog cmdlgOpen;
public System.Windows.Forms.SaveFileDialog cmdlgSave;
public System.Windows.Forms.FontDialog cmdlgFont;
public System.Windows.Forms.ColorDialog cmdlgColor;
public System.Windows.Forms.PrintDialog cmdlgPrint;
public System.Windows.Forms.TextBox Text1;
private System.Windows.Forms.Button withEventsField_cmdBrowse;
public System.Windows.Forms.Button cmdBrowse {
get { return withEventsField_cmdBrowse; }
set {
if (withEventsField_cmdBrowse != null) {
withEventsField_cmdBrowse.Click -= cmdBrowse_Click;
}
withEventsField_cmdBrowse = value;
if (withEventsField_cmdBrowse != null) {
withEventsField_cmdBrowse.Click += cmdBrowse_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdExportNow;
public System.Windows.Forms.Button cmdExportNow {
get { return withEventsField_cmdExportNow; }
set {
if (withEventsField_cmdExportNow != null) {
withEventsField_cmdExportNow.Click -= cmdExportNow_Click;
}
withEventsField_cmdExportNow = value;
if (withEventsField_cmdExportNow != null) {
withEventsField_cmdExportNow.Click += cmdExportNow_Click;
}
}
}
public System.Windows.Forms.Label Label1;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.cmdBrowse = new System.Windows.Forms.Button();
this.cmdExit = new System.Windows.Forms.Button();
this.picButtons = new System.Windows.Forms.Panel();
this.cmdClose = new System.Windows.Forms.Button();
this.cmdlgOpen = new System.Windows.Forms.OpenFileDialog();
this.cmdlgSave = new System.Windows.Forms.SaveFileDialog();
this.cmdlgFont = new System.Windows.Forms.FontDialog();
this.cmdlgColor = new System.Windows.Forms.ColorDialog();
this.cmdlgPrint = new System.Windows.Forms.PrintDialog();
this.Text1 = new System.Windows.Forms.TextBox();
this.cmdExportNow = new System.Windows.Forms.Button();
this.Label1 = new System.Windows.Forms.Label();
this.picButtons.SuspendLayout();
this.SuspendLayout();
//
//cmdBrowse
//
this.cmdBrowse.BackColor = System.Drawing.SystemColors.Control;
this.cmdBrowse.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdBrowse.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdBrowse.Location = new System.Drawing.Point(390, 48);
this.cmdBrowse.Name = "cmdBrowse";
this.cmdBrowse.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdBrowse.Size = new System.Drawing.Size(43, 17);
this.cmdBrowse.TabIndex = 1;
this.cmdBrowse.Text = "...";
this.ToolTip1.SetToolTip(this.cmdBrowse, "Browse file ");
this.cmdBrowse.UseVisualStyleBackColor = false;
//
//cmdExit
//
this.cmdExit.BackColor = System.Drawing.SystemColors.Control;
this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdExit.Font = new System.Drawing.Font("Times New Roman", 8.25f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(0));
this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdExit.Location = new System.Drawing.Point(360, 4);
this.cmdExit.Name = "cmdExit";
this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdExit.Size = new System.Drawing.Size(73, 27);
this.cmdExit.TabIndex = 6;
this.cmdExit.Text = "&Exit";
this.cmdExit.UseVisualStyleBackColor = false;
//
//picButtons
//
this.picButtons.BackColor = System.Drawing.Color.Blue;
this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picButtons.Controls.Add(this.cmdClose);
this.picButtons.Cursor = System.Windows.Forms.Cursors.Default;
this.picButtons.Dock = System.Windows.Forms.DockStyle.Top;
this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText;
this.picButtons.Location = new System.Drawing.Point(0, 0);
this.picButtons.Name = "picButtons";
this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picButtons.Size = new System.Drawing.Size(437, 38);
this.picButtons.TabIndex = 4;
//
//cmdClose
//
this.cmdClose.BackColor = System.Drawing.SystemColors.Control;
this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdClose.Location = new System.Drawing.Point(576, 3);
this.cmdClose.Name = "cmdClose";
this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdClose.Size = new System.Drawing.Size(73, 29);
this.cmdClose.TabIndex = 5;
this.cmdClose.TabStop = false;
this.cmdClose.Text = "E&xit";
this.cmdClose.UseVisualStyleBackColor = false;
//
//Text1
//
this.Text1.AcceptsReturn = true;
this.Text1.BackColor = System.Drawing.SystemColors.Window;
this.Text1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.Text1.Cursor = System.Windows.Forms.Cursors.IBeam;
this.Text1.Enabled = false;
this.Text1.ForeColor = System.Drawing.SystemColors.WindowText;
this.Text1.Location = new System.Drawing.Point(66, 46);
this.Text1.MaxLength = 0;
this.Text1.Name = "Text1";
this.Text1.ReadOnly = true;
this.Text1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Text1.Size = new System.Drawing.Size(317, 19);
this.Text1.TabIndex = 2;
//
//cmdExportNow
//
this.cmdExportNow.BackColor = System.Drawing.SystemColors.Control;
this.cmdExportNow.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdExportNow.Font = new System.Drawing.Font("Times New Roman", 8.25f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(0));
this.cmdExportNow.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdExportNow.Location = new System.Drawing.Point(318, 72);
this.cmdExportNow.Name = "cmdExportNow";
this.cmdExportNow.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdExportNow.Size = new System.Drawing.Size(113, 27);
this.cmdExportNow.TabIndex = 0;
this.cmdExportNow.Text = "Export &Now!";
this.cmdExportNow.UseVisualStyleBackColor = false;
//
//Label1
//
this.Label1.BackColor = System.Drawing.Color.Transparent;
this.Label1.Cursor = System.Windows.Forms.Cursors.Default;
this.Label1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label1.Location = new System.Drawing.Point(4, 50);
this.Label1.Name = "Label1";
this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label1.Size = new System.Drawing.Size(59, 15);
this.Label1.TabIndex = 3;
this.Label1.Text = "File Path:";
//
//frmExportUt
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(437, 106);
this.ControlBox = false;
this.Controls.Add(this.cmdExit);
this.Controls.Add(this.picButtons);
this.Controls.Add(this.Text1);
this.Controls.Add(this.cmdBrowse);
this.Controls.Add(this.cmdExportNow);
this.Controls.Add(this.Label1);
this.Cursor = System.Windows.Forms.Cursors.Default;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Location = new System.Drawing.Point(3, 19);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "frmExportUt";
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = " Export Utilities";
this.picButtons.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Capabilities.Handlers;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using System;
using System.Reflection;
using Caps = OpenSim.Framework.Capabilities.Caps;
namespace OpenSim.Region.ClientStack.Linden
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "UploadBakedTextureModule")]
public class UploadBakedTextureModule : INonSharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// For historical reasons this is fixed, but there
/// </summary>
private static readonly string m_uploadBakedTexturePath = "0010/";// This is in the LandManagementModule.
private IBakedTextureModule m_BakedTextureModule;
private bool m_persistBakedTextures;
private Scene m_scene;
public string Name { get { return "UploadBakedTextureModule"; } }
public Type ReplaceableInterface
{
get { return null; }
}
public void AddRegion(Scene s)
{
m_scene = s;
}
public void Close()
{
}
public void Initialise(IConfigSource source)
{
IConfig appearanceConfig = source.Configs["Appearance"];
if (appearanceConfig != null)
m_persistBakedTextures = appearanceConfig.GetBoolean("PersistBakedTextures", m_persistBakedTextures);
}
public void PostInitialise()
{
}
public void RegionLoaded(Scene s)
{
m_scene.EventManager.OnRegisterCaps += RegisterCaps;
m_scene.EventManager.OnNewPresence += RegisterNewPresence;
m_scene.EventManager.OnRemovePresence += DeRegisterPresence;
}
public void RegisterCaps(UUID agentID, Caps caps)
{
UploadBakedTextureHandler avatarhandler = new UploadBakedTextureHandler(
caps, m_scene.AssetService, m_persistBakedTextures);
caps.RegisterHandler(
"UploadBakedTexture",
new RestStreamHandler(
"POST",
"/CAPS/" + caps.CapsObjectPath + m_uploadBakedTexturePath,
avatarhandler.UploadBakedTexture,
"UploadBakedTexture",
agentID.ToString()));
}
public void RemoveRegion(Scene s)
{
s.EventManager.OnRegisterCaps -= RegisterCaps;
s.EventManager.OnNewPresence -= RegisterNewPresence;
s.EventManager.OnRemovePresence -= DeRegisterPresence;
m_BakedTextureModule = null;
m_scene = null;
}
private void CaptureAppearanceSettings(IClientAPI remoteClient, Primitive.TextureEntry textureEntry, byte[] visualParams, Vector3 avSize, WearableCacheItem[] cacheItems)
{
int maxCacheitemsLoop = cacheItems.Length;
if (maxCacheitemsLoop > AvatarWearable.MAX_WEARABLES)
{
maxCacheitemsLoop = AvatarWearable.MAX_WEARABLES;
m_log.WarnFormat("[CACHEDBAKES]: Too Many Cache items Provided {0}, the max is {1}. Truncating!", cacheItems.Length, AvatarWearable.MAX_WEARABLES);
}
m_BakedTextureModule = m_scene.RequestModuleInterface<IBakedTextureModule>();
if (cacheItems.Length > 0)
{
m_log.Debug("[Cacheitems]: " + cacheItems.Length);
for (int iter = 0; iter < maxCacheitemsLoop; iter++)
{
m_log.Debug("[Cacheitems] {" + iter + "/" + cacheItems[iter].TextureIndex + "}: c-" + cacheItems[iter].CacheId + ", t-" +
cacheItems[iter].TextureID);
}
ScenePresence p = null;
if (m_scene.TryGetScenePresence(remoteClient.AgentId, out p))
{
WearableCacheItem[] existingitems = p.Appearance.WearableCacheItems;
if (existingitems == null)
{
if (m_BakedTextureModule != null)
{
WearableCacheItem[] savedcache = null;
try
{
if (p.Appearance.WearableCacheItemsDirty)
{
savedcache = m_BakedTextureModule.Get(p.UUID);
p.Appearance.WearableCacheItems = savedcache;
p.Appearance.WearableCacheItemsDirty = false;
}
}
/*
* The following Catch types DO NOT WORK with m_BakedTextureModule.Get
* it jumps to the General Packet Exception Handler if you don't catch Exception!
*
catch (System.Net.Sockets.SocketException)
{
cacheItems = null;
}
catch (WebException)
{
cacheItems = null;
}
catch (InvalidOperationException)
{
cacheItems = null;
} */
catch (Exception)
{
// The service logs a sufficient error message.
}
if (savedcache != null)
existingitems = savedcache;
}
}
// Existing items null means it's a fully new appearance
if (existingitems == null)
{
for (int i = 0; i < maxCacheitemsLoop; i++)
{
if (textureEntry.FaceTextures.Length > cacheItems[i].TextureIndex)
{
Primitive.TextureEntryFace face = textureEntry.FaceTextures[cacheItems[i].TextureIndex];
if (face == null)
{
textureEntry.CreateFace(cacheItems[i].TextureIndex);
textureEntry.FaceTextures[cacheItems[i].TextureIndex].TextureID =
AppearanceManager.DEFAULT_AVATAR_TEXTURE;
continue;
}
cacheItems[i].TextureID = face.TextureID;
if (m_scene.AssetService != null)
cacheItems[i].TextureAsset =
m_scene.AssetService.GetCached(cacheItems[i].TextureID.ToString());
}
else
{
m_log.WarnFormat("[CACHEDBAKES]: Invalid Texture Index Provided, Texture doesn't exist or hasn't been uploaded yet {0}, the max is {1}. Skipping!", cacheItems[i].TextureIndex, textureEntry.FaceTextures.Length);
}
}
}
else
{
// for each uploaded baked texture
for (int i = 0; i < maxCacheitemsLoop; i++)
{
if (textureEntry.FaceTextures.Length > cacheItems[i].TextureIndex)
{
Primitive.TextureEntryFace face = textureEntry.FaceTextures[cacheItems[i].TextureIndex];
if (face == null)
{
textureEntry.CreateFace(cacheItems[i].TextureIndex);
textureEntry.FaceTextures[cacheItems[i].TextureIndex].TextureID =
AppearanceManager.DEFAULT_AVATAR_TEXTURE;
continue;
}
cacheItems[i].TextureID =
face.TextureID;
}
else
{
m_log.WarnFormat("[CACHEDBAKES]: Invalid Texture Index Provided, Texture doesn't exist or hasn't been uploaded yet {0}, the max is {1}. Skipping!", cacheItems[i].TextureIndex, textureEntry.FaceTextures.Length);
}
}
for (int i = 0; i < maxCacheitemsLoop; i++)
{
if (cacheItems[i].TextureAsset == null)
{
cacheItems[i].TextureAsset =
m_scene.AssetService.GetCached(cacheItems[i].TextureID.ToString());
}
}
}
p.Appearance.WearableCacheItems = cacheItems;
if (m_BakedTextureModule != null)
{
m_BakedTextureModule.Store(remoteClient.AgentId, cacheItems);
p.Appearance.WearableCacheItemsDirty = true;
}
}
}
}
private void DeRegisterPresence(UUID agentId)
{
ScenePresence presence = null;
if (m_scene.TryGetScenePresence(agentId, out presence))
{
presence.ControllingClient.OnSetAppearance -= CaptureAppearanceSettings;
}
}
private void RegisterNewPresence(ScenePresence presence)
{
presence.ControllingClient.OnSetAppearance += CaptureAppearanceSettings;
}
}
}
| |
/*
* 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.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Reflection;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Data.MSSQL
{
/// <summary>
/// A MSSQL Interface for the Region Server.
/// </summary>
public class MSSQLRegionData : IRegionData
{
private string m_Realm;
private List<string> m_ColumnNames = null;
private string m_ConnectionString;
private MSSQLManager m_database;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public MSSQLRegionData(string connectionString, string realm)
{
m_Realm = realm;
m_ConnectionString = connectionString;
m_database = new MSSQLManager(connectionString);
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
{
conn.Open();
Migration m = new Migration(conn, GetType().Assembly, "GridStore");
m.Update();
}
}
public List<RegionData> Get(string regionName, UUID scopeID)
{
string sql = "select * from ["+m_Realm+"] where regionName like @regionName";
if (scopeID != UUID.Zero)
sql += " and ScopeID = @scopeID";
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("@regionName", regionName));
cmd.Parameters.Add(m_database.CreateParameter("@scopeID", scopeID));
conn.Open();
return RunCommand(cmd);
}
}
public RegionData Get(int posX, int posY, UUID scopeID)
{
string sql = "select * from ["+m_Realm+"] where locX = @posX and locY = @posY";
if (scopeID != UUID.Zero)
sql += " and ScopeID = @scopeID";
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("@posX", posX.ToString()));
cmd.Parameters.Add(m_database.CreateParameter("@posY", posY.ToString()));
cmd.Parameters.Add(m_database.CreateParameter("@scopeID", scopeID));
conn.Open();
List<RegionData> ret = RunCommand(cmd);
if (ret.Count == 0)
return null;
return ret[0];
}
}
public RegionData Get(UUID regionID, UUID scopeID)
{
string sql = "select * from ["+m_Realm+"] where uuid = @regionID";
if (scopeID != UUID.Zero)
sql += " and ScopeID = @scopeID";
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("@regionID", regionID));
cmd.Parameters.Add(m_database.CreateParameter("@scopeID", scopeID));
conn.Open();
List<RegionData> ret = RunCommand(cmd);
if (ret.Count == 0)
return null;
return ret[0];
}
}
public List<RegionData> Get(int startX, int startY, int endX, int endY, UUID scopeID)
{
string sql = "select * from ["+m_Realm+"] where locX between @startX and @endX and locY between @startY and @endY";
if (scopeID != UUID.Zero)
sql += " and ScopeID = @scopeID";
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("@startX", startX));
cmd.Parameters.Add(m_database.CreateParameter("@startY", startY));
cmd.Parameters.Add(m_database.CreateParameter("@endX", endX));
cmd.Parameters.Add(m_database.CreateParameter("@endY", endY));
cmd.Parameters.Add(m_database.CreateParameter("@scopeID", scopeID));
conn.Open();
return RunCommand(cmd);
}
}
public List<RegionData> RunCommand(SqlCommand cmd)
{
List<RegionData> retList = new List<RegionData>();
SqlDataReader result = cmd.ExecuteReader();
while (result.Read())
{
RegionData ret = new RegionData();
ret.Data = new Dictionary<string, object>();
UUID regionID;
UUID.TryParse(result["uuid"].ToString(), out regionID);
ret.RegionID = regionID;
UUID scope;
UUID.TryParse(result["ScopeID"].ToString(), out scope);
ret.ScopeID = scope;
ret.RegionName = result["regionName"].ToString();
ret.posX = Convert.ToInt32(result["locX"]);
ret.posY = Convert.ToInt32(result["locY"]);
ret.sizeX = Convert.ToInt32(result["sizeX"]);
ret.sizeY = Convert.ToInt32(result["sizeY"]);
if (m_ColumnNames == null)
{
m_ColumnNames = new List<string>();
DataTable schemaTable = result.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
m_ColumnNames.Add(row["ColumnName"].ToString());
}
foreach (string s in m_ColumnNames)
{
if (s == "uuid")
continue;
if (s == "ScopeID")
continue;
if (s == "regionName")
continue;
if (s == "locX")
continue;
if (s == "locY")
continue;
ret.Data[s] = result[s].ToString();
}
retList.Add(ret);
}
return retList;
}
public bool Store(RegionData data)
{
if (data.Data.ContainsKey("uuid"))
data.Data.Remove("uuid");
if (data.Data.ContainsKey("ScopeID"))
data.Data.Remove("ScopeID");
if (data.Data.ContainsKey("regionName"))
data.Data.Remove("regionName");
if (data.Data.ContainsKey("posX"))
data.Data.Remove("posX");
if (data.Data.ContainsKey("posY"))
data.Data.Remove("posY");
if (data.Data.ContainsKey("sizeX"))
data.Data.Remove("sizeX");
if (data.Data.ContainsKey("sizeY"))
data.Data.Remove("sizeY");
if (data.Data.ContainsKey("locX"))
data.Data.Remove("locX");
if (data.Data.ContainsKey("locY"))
data.Data.Remove("locY");
string[] fields = new List<string>(data.Data.Keys).ToArray();
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand())
{
string update = "update [" + m_Realm + "] set locX=@posX, locY=@posY, sizeX=@sizeX, sizeY=@sizeY ";
foreach (string field in fields)
{
update += ", ";
update += "[" + field + "] = @" + field;
cmd.Parameters.Add(m_database.CreateParameter("@" + field, data.Data[field]));
}
update += " where uuid = @regionID";
if (data.ScopeID != UUID.Zero)
update += " and ScopeID = @scopeID";
cmd.CommandText = update;
cmd.Connection = conn;
cmd.Parameters.Add(m_database.CreateParameter("@regionID", data.RegionID));
cmd.Parameters.Add(m_database.CreateParameter("@regionName", data.RegionName));
cmd.Parameters.Add(m_database.CreateParameter("@scopeID", data.ScopeID));
cmd.Parameters.Add(m_database.CreateParameter("@posX", data.posX));
cmd.Parameters.Add(m_database.CreateParameter("@posY", data.posY));
cmd.Parameters.Add(m_database.CreateParameter("@sizeX", data.sizeX));
cmd.Parameters.Add(m_database.CreateParameter("@sizeY", data.sizeY));
conn.Open();
try
{
if (cmd.ExecuteNonQuery() < 1)
{
string insert = "insert into [" + m_Realm + "] ([uuid], [ScopeID], [locX], [locY], [sizeX], [sizeY], [regionName], [" +
String.Join("], [", fields) +
"]) values (@regionID, @scopeID, @posX, @posY, @sizeX, @sizeY, @regionName, @" + String.Join(", @", fields) + ")";
cmd.CommandText = insert;
try
{
if (cmd.ExecuteNonQuery() < 1)
{
return false;
}
}
catch (Exception ex)
{
m_log.Warn("[MSSQL Grid]: Error inserting into Regions table: " + ex.Message + ", INSERT sql: " + insert);
}
}
}
catch (Exception ex)
{
m_log.Warn("[MSSQL Grid]: Error updating Regions table: " + ex.Message + ", UPDATE sql: " + update);
}
}
return true;
}
public bool SetDataItem(UUID regionID, string item, string value)
{
string sql = "update [" + m_Realm +
"] set [" + item + "] = @" + item + " where uuid = @UUID";
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("@" + item, value));
cmd.Parameters.Add(m_database.CreateParameter("@UUID", regionID));
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
return true;
}
return false;
}
public bool Delete(UUID regionID)
{
string sql = "delete from [" + m_Realm +
"] where uuid = @UUID";
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("@UUID", regionID));
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
return true;
}
return false;
}
public List<RegionData> GetDefaultRegions(UUID scopeID)
{
string sql = "SELECT * FROM [" + m_Realm + "] WHERE (flags & 1) <> 0";
if (scopeID != UUID.Zero)
sql += " AND ScopeID = @scopeID";
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("@scopeID", scopeID));
conn.Open();
return RunCommand(cmd);
}
}
public List<RegionData> GetFallbackRegions(UUID scopeID, int x, int y)
{
string sql = "SELECT * FROM [" + m_Realm + "] WHERE (flags & 2) <> 0";
if (scopeID != UUID.Zero)
sql += " AND ScopeID = @scopeID";
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("@scopeID", scopeID));
conn.Open();
// TODO: distance-sort results
return RunCommand(cmd);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Newtonsoft.Json;
using NuGet.ContentModel;
using NuGet.Frameworks;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Microsoft.DotNet.Build.Tasks.Packaging
{
public class HarvestPackage : PackagingTask
{
/// <summary>
/// Package ID to harvest
/// </summary>
[Required]
public string PackageId { get; set; }
/// <summary>
/// Current package version.
/// </summary>
[Required]
public string PackageVersion { get; set; }
/// <summary>
/// Folder where packages have been restored
/// </summary>
[Required]
public string PackagesFolder { get; set; }
/// <summary>
/// Path to runtime.json that contains the runtime graph.
/// </summary>
[Required]
public string RuntimeFile { get; set; }
/// <summary>
/// Additional packages to consider for evaluating support but not harvesting assets.
/// Identity: Package ID
/// Version: Package version.
/// </summary>
public ITaskItem[] RuntimePackages { get; set; }
/// <summary>
/// Set to false to suppress harvesting of files and only harvest supported framework information.
/// </summary>
public bool HarvestAssets { get; set; }
/// <summary>
/// Set to partial paths to exclude from file harvesting.
/// </summary>
public string[] PathsToExclude { get; set; }
/// <summary>
/// Set to partial paths to suppress from both file and support harvesting.
/// </summary>
public string[] PathsToSuppress { get; set; }
/// <summary>
/// Frameworks to consider for support evaluation.
/// Identity: Framework
/// RuntimeIDs: Semi-colon seperated list of runtime IDs
/// </summary>
[Required]
public ITaskItem[] Frameworks { get; set; }
/// <summary>
/// Frameworks that were supported by previous package version.
/// Identity: Framework
/// Version: Assembly version if supported
/// </summary>
[Output]
public ITaskItem[] SupportedFrameworks { get; set; }
/// <summary>
/// Files harvested from previous package version.
/// Identity: path to file
/// AssemblyVersion: version of assembly
/// TargetFramework: target framework moniker to use for harvesting file's dependencies
/// TargetPath: path of file in package
/// IsReferenceAsset: true for files in Ref.
/// </summary>
[Output]
public ITaskItem[] Files { get; set; }
/// <summary>
/// Generates a table in markdown that lists the API version supported by
/// various packages at all levels of NETStandard.
/// </summary>
/// <returns></returns>
public override bool Execute()
{
if (!Directory.Exists(PackagesFolder))
{
Log.LogError($"PackagesFolder {PackagesFolder} does not exist.");
}
if (HasPackagesToHarvest())
{
if (HarvestAssets)
{
HarvestFilesFromPackage();
}
HarvestSupportedFrameworks();
}
return !Log.HasLoggedErrors;
}
private bool HasPackagesToHarvest()
{
bool result = true;
IEnumerable<string> packageDirs = new[] { Path.Combine(PackageId, PackageVersion) };
if (RuntimePackages != null)
{
packageDirs = packageDirs.Concat(
RuntimePackages.Select(p => Path.Combine(p.ItemSpec, p.GetMetadata("Version"))));
}
foreach (var packageDir in packageDirs)
{
var pathToPackage = Path.Combine(PackagesFolder, packageDir);
if (!Directory.Exists(pathToPackage))
{
Log.LogMessage($"Will not harvest files & support from package {packageDir} because {pathToPackage} does not exist.");
result = false;
}
}
return result;
}
private void HarvestSupportedFrameworks()
{
List<ITaskItem> supportedFrameworks = new List<ITaskItem>();
AggregateNuGetAssetResolver resolver = new AggregateNuGetAssetResolver(RuntimeFile);
string packagePath = Path.Combine(PackagesFolder, PackageId, PackageVersion);
// add the primary package
resolver.AddPackageItems(PackageId, GetPackageItems(packagePath));
if (RuntimePackages != null)
{
// add any split runtime packages
foreach (var runtimePackage in RuntimePackages)
{
var runtimePackageId = runtimePackage.ItemSpec;
var runtimePackageVersion = runtimePackage.GetMetadata("Version");
resolver.AddPackageItems(runtimePackageId, GetPackageItems(PackagesFolder, runtimePackageId, runtimePackageVersion));
}
}
// create a resolver that can be used to determine the API version for inbox assemblies
// since inbox assemblies are represented with placeholders we can remove the placeholders
// and use the netstandard reference assembly to determine the API version
var filesWithoutPlaceholders = GetPackageItems(packagePath)
.Where(f => !NuGetAssetResolver.IsPlaceholder(f));
NuGetAssetResolver resolverWithoutPlaceholders = new NuGetAssetResolver(RuntimeFile, filesWithoutPlaceholders);
string package = $"{PackageId}/{PackageVersion}";
foreach (var framework in Frameworks)
{
var runtimeIds = framework.GetMetadata("RuntimeIDs")?.Split(';');
NuGetFramework fx;
try
{
fx = FrameworkUtilities.ParseNormalized(framework.ItemSpec);
}
catch (Exception ex)
{
Log.LogError($"Could not parse Framework {framework.ItemSpec}. {ex}");
continue;
}
if (fx.Equals(NuGetFramework.UnsupportedFramework))
{
Log.LogError($"Did not recognize {framework.ItemSpec} as valid Framework.");
continue;
}
var compileAssets = resolver.ResolveCompileAssets(fx, PackageId);
bool hasCompileAsset, hasCompilePlaceHolder;
NuGetAssetResolver.ExamineAssets(Log, "Compile", package, fx.ToString(), compileAssets, out hasCompileAsset, out hasCompilePlaceHolder);
// start by making sure it has some asset available for compile
var isSupported = hasCompileAsset || hasCompilePlaceHolder;
if (!isSupported)
{
Log.LogMessage(LogImportance.Low, $"Skipping {fx} because it is not supported.");
continue;
}
foreach (var runtimeId in runtimeIds)
{
string target = String.IsNullOrEmpty(runtimeId) ? fx.ToString() : $"{fx}/{runtimeId}";
var runtimeAssets = resolver.ResolveRuntimeAssets(fx, runtimeId);
bool hasRuntimeAsset, hasRuntimePlaceHolder;
NuGetAssetResolver.ExamineAssets(Log, "Runtime", package, target, runtimeAssets, out hasRuntimeAsset, out hasRuntimePlaceHolder);
isSupported &= hasCompileAsset == hasRuntimeAsset;
isSupported &= hasCompilePlaceHolder == hasRuntimePlaceHolder;
if (!isSupported)
{
Log.LogMessage(LogImportance.Low, $"Skipping {fx} because it is not supported on {target}.");
break;
}
}
if (isSupported)
{
var supportedFramework = new TaskItem(framework.ItemSpec);
supportedFramework.SetMetadata("HarvestedFromPackage", package);
// set version
// first try the resolved compile asset for this package
var refAssm = compileAssets.FirstOrDefault(r => !NuGetAssetResolver.IsPlaceholder(r))?.Substring(PackageId.Length + 1);
if (refAssm == null)
{
// if we didn't have a compile asset it means this framework is supported inbox with a placeholder
// resolve the assets without placeholders to pick up the netstandard reference assembly.
compileAssets = resolverWithoutPlaceholders.ResolveCompileAssets(fx);
refAssm = compileAssets.FirstOrDefault(r => !NuGetAssetResolver.IsPlaceholder(r));
}
string version = "unknown";
if (refAssm != null)
{
version = VersionUtility.GetAssemblyVersion(Path.Combine(packagePath, refAssm))?.ToString() ?? version;
}
supportedFramework.SetMetadata("Version", version);
Log.LogMessage($"Validating version {version} for {supportedFramework.ItemSpec} because it was supported by {PackageId}/{PackageVersion}.");
supportedFrameworks.Add(supportedFramework);
}
}
SupportedFrameworks = supportedFrameworks.ToArray();
}
private static string[] includedExtensions = new[] { ".dll", ".xml", "._" };
public void HarvestFilesFromPackage()
{
string pathToPackage = Path.Combine(PackagesFolder, PackageId, PackageVersion);
if (!Directory.Exists(pathToPackage))
{
Log.LogError($"Cannot harvest from package {PackageId}/{PackageVersion} because {pathToPackage} does not exist.");
return;
}
var harvestedFiles = new List<ITaskItem>();
foreach (var extension in includedExtensions)
{
foreach (var packageFile in Directory.EnumerateFiles(pathToPackage, $"*{extension}", SearchOption.AllDirectories))
{
string packagePath = packageFile.Substring(pathToPackage.Length + 1).Replace('\\', '/');
if (ShouldExclude(packagePath))
{
Log.LogMessage($"Preferring live build of package path {packagePath} over the asset from last stable package.");
continue;
}
else
{
Log.LogMessage($"Including {packagePath} from last stable package {PackageId}/{PackageVersion}.");
}
var item = new TaskItem(packageFile);
var targetPath = Path.GetDirectoryName(packagePath).Replace('\\', '/');
item.SetMetadata("TargetPath", targetPath);
item.SetMetadata("TargetFramework", GetTargetFrameworkFromPackagePath(targetPath));
item.SetMetadata("HarvestDependencies", "true");
item.SetMetadata("IsReferenceAsset", IsReferencePackagePath(targetPath).ToString());
var assemblyVersion = VersionUtility.GetAssemblyVersion(packageFile);
if (assemblyVersion != null)
{
item.SetMetadata("AssemblyVersion", assemblyVersion.ToString());
}
harvestedFiles.Add(item);
}
}
Files = harvestedFiles.ToArray();
}
private bool ShouldExclude(string packagePath)
{
return ShouldSuppress(packagePath) || (PathsToExclude != null &&
PathsToExclude.Any(p => packagePath.StartsWith(p, StringComparison.OrdinalIgnoreCase)));
}
private bool ShouldSuppress(string packagePath)
{
return PathsToSuppress != null &&
PathsToSuppress.Any(p => packagePath.StartsWith(p, StringComparison.OrdinalIgnoreCase));
}
private static string GetTargetFrameworkFromPackagePath(string path)
{
var parts = path.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
if (parts.Length >= 2)
{
if (parts[0].Equals("lib", StringComparison.OrdinalIgnoreCase) ||
parts[0].Equals("ref", StringComparison.OrdinalIgnoreCase))
{
return parts[1];
}
if (parts.Length >= 4 &&
parts[0].Equals("runtimes", StringComparison.OrdinalIgnoreCase) &&
parts[2].Equals("lib", StringComparison.OrdinalIgnoreCase))
{
return parts[3];
}
}
return null;
}
private static bool IsReferencePackagePath(string path)
{
return path.StartsWith("ref", StringComparison.OrdinalIgnoreCase);
}
private IEnumerable<string> GetPackageItems(string packagesFolder, string packageId, string packageVersion)
{
string packageFolder = Path.Combine(packagesFolder, packageId, packageVersion);
return GetPackageItems(packageFolder);
}
private IEnumerable<string> GetPackageItems(string packageFolder)
{
return Directory.EnumerateFiles(packageFolder, "*", SearchOption.AllDirectories)
.Select(f => f.Substring(packageFolder.Length + 1).Replace('\\', '/'))
.Where(f => !ShouldSuppress(f));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Soldr.ProjectFileParser;
using QuickGraph;
using QuickGraph.Algorithms;
using Soldr.Common;
namespace Soldr.Resolver
{
public class BuildDependencyResolver
{
protected static readonly log4net.ILog _logger = log4net.LogManager.GetLogger(
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public const string CSPROJ_EXTENSION = ".csproj";
public const string SLN_EXTENSION = ".sln";
public static IEnumerable<Project> BuildOrder(IProjectFinder projectFinder, IEnumerable<Project> projects, int maxRecursionLevel)
{
return ProjectDependencyGraph(projectFinder, projects, true, maxRecursionLevel).TopologicalSort();
}
/// <summary>
/// Creates a graph representing all the dependencies within the given projects.
/// The edges will be from dependent project to dependency, unless <paramref name="reverse"/> is True,
/// in which case the edges will be from dependency to dependent (which is more useful for topological sorting -
/// which in this way will return the projects in build order)
/// </summary>
/// <param name="projects"></param>
/// <returns></returns>
public static AdjacencyGraph<Project, SEdge<Project>> ProjectDependencyGraph(IProjectFinder projectFinder, IEnumerable<Project> projects, bool reverse, int maxRecursionLevel)
{
// First add all the dependencies (edges)
var graph = DeepDependencies(projectFinder, projects, false, maxRecursionLevel)
.Distinct()
.Select(x => new SEdge<Project>(reverse ? x.Key : x.Value, reverse ? x.Value : x.Key))
.ToAdjacencyGraph<Project, SEdge<Project>>(false);
// Then make sure we have vertices for each input "root" project, regardless of if it has dependencies or not
graph.AddVertexRange(projects);
return graph;
}
/// <summary>
/// Builds a dependency graph between solutions. The vertices in the graph are the solution full file names.
/// </summary>
public static AdjacencyGraph<String, SEdge<String>> SolutionDependencyGraph(IProjectFinder projectFinder, IEnumerable<Project> projects, bool reverse, int maxRecursionLevel)
{
var graph = DeepDependencies(projectFinder, projects, true, maxRecursionLevel)
.Where(x => x.Key != x.Value)
.Select(x => ProjectEdgeToSLNEdge(projectFinder, x))
.Where(x => false == SolutionNamesEqual(x))
.Distinct()
.Select(x => new SEdge<String>(reverse ? x.Key : x.Value, reverse ? x.Value : x.Key))
.ToAdjacencyGraph<String, SEdge<String>>(false);
graph.AddVertexRange(projects.Select(x => SLNVertexName(projectFinder, x)));
return graph;
}
private static bool SolutionNamesEqual(KeyValuePair<string, string> x)
{
return x.Key.ToLowerInvariant().Equals(x.Value.ToLowerInvariant());
}
/// <summary>
/// Builds a graph of dependencies between solution files, from a list of .csproj and .sln files.
/// </summary>
/// <param name="inputFiles">Project (.csproj) and solution (.sln) files to start the dependency search from</param>
/// <param name="_excludedSLNs">Solution (.sln) files that should be excluded from the final dependency graph - useful for temporarily ignoring cyclic dependencies.
/// Note that .sln files may appear in the final graph even if they are not given in the input files list, if something in the input depends on them.</param>
/// <param name="maxRecursionLevel">How deep to resolve dependencies of the given inputs. 0 means no dependency resolution is performed. -1 means infinity.</param>
public static BuildDependencyInfo GetDependencyInfo(IProjectFinder projectFinder, IEnumerable<string> inputFiles, IEnumerable<string> _excludedSLNs, int maxRecursionLevel) //, bool findAllDependents)
{
string[] projectFiles;
string[] slnFiles;
ProcessInputFiles(inputFiles.Select(CanonicalPath), out projectFiles, out slnFiles);
var excludedSLNs = _excludedSLNs.Select(CanonicalPath)
.Select(x => x.ToLowerInvariant())
.ToArray();
if (excludedSLNs.Any(x => false == SLN_EXTENSION.Equals(System.IO.Path.GetExtension(x))))
{
var errorMessage = "excluded files must have extension: " + SLN_EXTENSION;
_logger.Error(errorMessage);
throw new ArgumentException(errorMessage, "_excludedSLNs");
}
var csprojProjects = projectFiles.Select(Project.FromCSProj);
var slnProjects = slnFiles.SelectMany(projectFinder.GetProjectsOfSLN);
var inputProjects = csprojProjects.Union(slnProjects).ToArray();
PrintInputInfo(excludedSLNs, projectFiles, slnFiles, inputProjects);
//Project[] projectsForDependencyGraph = findAllDependents
// ? projectFinder.AllProjectsInPath().ToArray()
// : inputProjects;
return new BuildDependencyInfo(ProjectDependencyGraph(projectFinder, inputProjects, false, maxRecursionLevel),
SolutionDependencyGraph(projectFinder, inputProjects, false, maxRecursionLevel),
excludedSLNs);
}
protected static IEnumerable<Project> GetAllProjectsInSolutionsOfProject(IProjectFinder projectFinder, Project project)
{
return projectFinder.GetProjectsOfSLN(projectFinder.GetSLNFileForProject(project));
}
protected static KeyValuePair<string, string> ProjectEdgeToSLNEdge(IProjectFinder projectFinder, KeyValuePair<Project, Project> x)
{
return new KeyValuePair<String, String>(SLNVertexName(projectFinder, x.Key),
SLNVertexName(projectFinder, x.Value));
}
private static string SLNVertexName(IProjectFinder projectFinder, Project project)
{
return projectFinder.GetSLNFileForProject(project).FullName;
}
protected struct ResolvedProjectDependencyInfo
{
public readonly int RecursionLevel;
public readonly Project Source;
public readonly Project Target;
public ResolvedProjectDependencyInfo(int _recursionLevel, Project _source, Project _target)
{
this.RecursionLevel = _recursionLevel;
this.Source = _source;
this.Target = _target;
}
}
/// <summary>
/// Finds all pairs of dependencies source -> target of projects that depend on each other.
/// </summary>
/// <param name="maxRecursionLevel">How deep to resolve dependencies of the given inputs. 0 means no dependency resolution is performed. -1 means infinity.</param>
/// <returns></returns>
public static IEnumerable<KeyValuePair<Project, Project>> DeepDependencies(IProjectFinder projectFinder, IEnumerable<Project> projects, bool includeAllProjectsInSolution, int maxRecursionLevel)
{
var projectsToTraverse = new Queue<ResolvedProjectDependencyInfo>(projects.Select(x => new ResolvedProjectDependencyInfo(0, x, x)));
var traversedProjects = new HashSet<Project>();
while (projectsToTraverse.Any())
{
var projectPair = projectsToTraverse.Dequeue();
var project = projectPair.Target;
if (projectPair.Source != projectPair.Target)
{
yield return new KeyValuePair<Project, Project>(projectPair.Source, projectPair.Target);
}
if ((0 <= maxRecursionLevel) && (projectPair.RecursionLevel >= maxRecursionLevel))
{
continue;
}
if (traversedProjects.Contains(project))
{
continue;
}
traversedProjects.Add(project);
if (includeAllProjectsInSolution)
{
foreach (var projectInSameSolution in GetAllProjectsInSolutionsOfProject(projectFinder, project)
.Where(x => false == traversedProjects.Contains(x)))
{
projectsToTraverse.Enqueue(new ResolvedProjectDependencyInfo(projectPair.RecursionLevel + 1, projectInSameSolution, projectInSameSolution));
}
}
foreach (var subProject in project.ProjectReferences)
{
projectsToTraverse.Enqueue(new ResolvedProjectDependencyInfo(projectPair.RecursionLevel + 1, project, subProject));
}
// TODO: Why do we allow a null projectFinder at all here?
if (null != projectFinder)
{
foreach (var assemblySubProject in project.AssemblyReferences.SelectMany(projectFinder.FindProjectForAssemblyReference))
{
projectsToTraverse.Enqueue(new ResolvedProjectDependencyInfo(projectPair.RecursionLevel + 1, project, assemblySubProject));
}
}
}
}
protected static void ProcessInputFiles(IEnumerable<string> inputFiles, out string[] projectFiles, out string[] slnFiles)
{
slnFiles = new string[] { };
projectFiles = new string[] { };
var filesByExtensions = inputFiles.GroupBy(System.IO.Path.GetExtension);
foreach (var extensionGroup in filesByExtensions)
{
switch (extensionGroup.Key)
{
case CSPROJ_EXTENSION:
projectFiles = extensionGroup.ToArray();
break;
case SLN_EXTENSION:
slnFiles = extensionGroup.ToArray();
break;
default:
{
var errorMessage = String.Format("Unknown file type: '{0}' in {1}", extensionGroup.Key, String.Join(", ", extensionGroup));
_logger.Error(errorMessage);
throw new ArgumentException(errorMessage, "_inputFiles");
}
}
}
}
protected static void PrintInputInfo(string[] excludedSLNs, IEnumerable<string> projectFiles, IEnumerable<string> slnFiles, Project[] projects)
{
if (projectFiles.Any())
{
_logger.DebugFormat("Input CSPROJ files:\n" + StringExtensions.Tabify(projectFiles));
}
if (slnFiles.Any())
{
_logger.DebugFormat("Input SLN files:\n" + StringExtensions.Tabify(slnFiles));
}
if (projects.Any())
{
_logger.DebugFormat("Input projects:\n" + StringExtensions.Tabify(projects.Select(x => x.Path)));
}
if (excludedSLNs.Any())
{
_logger.InfoFormat("Excluding solutions:\n" + StringExtensions.Tabify(excludedSLNs));
}
}
protected static string CanonicalPath(string x)
{
return PathExtensions.GetFullPath(x.Trim());
}
}
}
| |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using TrackableEntities;
using TrackableEntities.Client;
namespace AIM.Client.Entities.Models
{
[JsonObject(IsReference = true)]
[DataContract(IsReference = true, Namespace = "http://schemas.datacontract.org/2004/07/TrackableEntities.Models")]
public partial class JobHistory : ModelBase<JobHistory>, IEquatable<JobHistory>, ITrackable
{
[DataMember]
public int JobHistoryId
{
get { return _JobHistoryId; }
set
{
if (Equals(value, _JobHistoryId)) return;
_JobHistoryId = value;
NotifyPropertyChanged(m => m.JobHistoryId);
}
}
private int _JobHistoryId;
[DataMember]
public string EmployerName
{
get { return _EmployerName; }
set
{
if (Equals(value, _EmployerName)) return;
_EmployerName = value;
NotifyPropertyChanged(m => m.EmployerName);
}
}
private string _EmployerName;
[DataMember]
public string Position
{
get { return _Position; }
set
{
if (Equals(value, _Position)) return;
_Position = value;
NotifyPropertyChanged(m => m.Position);
}
}
private string _Position;
[DataMember]
public string Responsibilities
{
get { return _Responsibilities; }
set
{
if (Equals(value, _Responsibilities)) return;
_Responsibilities = value;
NotifyPropertyChanged(m => m.Responsibilities);
}
}
private string _Responsibilities;
[DataMember]
public string Supervisor
{
get { return _Supervisor; }
set
{
if (Equals(value, _Supervisor)) return;
_Supervisor = value;
NotifyPropertyChanged(m => m.Supervisor);
}
}
private string _Supervisor;
[DataMember]
public Nullable<decimal> StartingSalary
{
get { return _StartingSalary; }
set
{
if (Equals(value, _StartingSalary)) return;
_StartingSalary = value;
NotifyPropertyChanged(m => m.StartingSalary);
}
}
private Nullable<decimal> _StartingSalary;
[DataMember]
public Nullable<decimal> EndingSalary
{
get { return _EndingSalary; }
set
{
if (Equals(value, _EndingSalary)) return;
_EndingSalary = value;
NotifyPropertyChanged(m => m.EndingSalary);
}
}
private Nullable<decimal> _EndingSalary;
[DataMember]
public string ReasonForLeaving
{
get { return _ReasonForLeaving; }
set
{
if (Equals(value, _ReasonForLeaving)) return;
_ReasonForLeaving = value;
NotifyPropertyChanged(m => m.ReasonForLeaving);
}
}
private string _ReasonForLeaving;
[DataMember]
public Nullable<System.DateTime> DateFrom
{
get { return _DateFrom; }
set
{
if (Equals(value, _DateFrom)) return;
_DateFrom = value;
NotifyPropertyChanged(m => m.DateFrom);
}
}
private Nullable<System.DateTime> _DateFrom;
[DataMember]
public Nullable<System.DateTime> DateTo
{
get { return _DateTo; }
set
{
if (Equals(value, _DateTo)) return;
_DateTo = value;
NotifyPropertyChanged(m => m.DateTo);
}
}
private Nullable<System.DateTime> _DateTo;
[DataMember]
public string Street
{
get { return _Street; }
set
{
if (Equals(value, _Street)) return;
_Street = value;
NotifyPropertyChanged(m => m.Street);
}
}
private string _Street;
[DataMember]
public string Street2
{
get { return _Street2; }
set
{
if (Equals(value, _Street2)) return;
_Street2 = value;
NotifyPropertyChanged(m => m.Street2);
}
}
private string _Street2;
[DataMember]
public string City
{
get { return _City; }
set
{
if (Equals(value, _City)) return;
_City = value;
NotifyPropertyChanged(m => m.City);
}
}
private string _City;
[DataMember]
public StateEnum? State
{
get { return _state; }
set
{
if (Equals(value, _state)) return;
_state = value;
NotifyPropertyChanged(m => m.State);
}
}
private StateEnum? _state;
[DataMember]
public string Zip
{
get { return _Zip; }
set
{
if (Equals(value, _Zip)) return;
_Zip = value;
NotifyPropertyChanged(m => m.Zip);
}
}
private string _Zip;
[DataMember]
public string Phone
{
get { return _Phone; }
set
{
if (Equals(value, _Phone)) return;
_Phone = value;
NotifyPropertyChanged(m => m.Phone);
}
}
private string _Phone;
[DataMember]
public int? ApplicantId
{
get { return _ApplicantId; }
set
{
if (Equals(value, _ApplicantId)) return;
_ApplicantId = value;
NotifyPropertyChanged(m => m.ApplicantId);
}
}
private int? _ApplicantId;
[DataMember]
public Applicant Applicant
{
get { return _Applicant; }
set
{
if (Equals(value, _Applicant)) return;
_Applicant = value;
ApplicantChangeTracker = _Applicant == null ? null
: new ChangeTrackingCollection<Applicant> { _Applicant };
NotifyPropertyChanged(m => m.Applicant);
}
}
private Applicant _Applicant;
private ChangeTrackingCollection<Applicant> ApplicantChangeTracker { get; set; }
#region Change Tracking
[DataMember]
public TrackingState TrackingState { get; set; }
[DataMember]
public ICollection<string> ModifiedProperties { get; set; }
[JsonProperty, DataMember]
private Guid EntityIdentifier { get; set; }
#pragma warning disable 414
[JsonProperty, DataMember]
private Guid _entityIdentity = default(Guid);
#pragma warning restore 414
bool IEquatable<JobHistory>.Equals(JobHistory other)
{
if (EntityIdentifier != default(Guid))
return EntityIdentifier == other.EntityIdentifier;
return false;
}
#endregion Change Tracking
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.1434
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebsitePanel.Portal.ProviderControls {
public partial class SmarterMail50_EditAccount {
/// <summary>
/// passwordRow control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTableRow passwordRow;
/// <summary>
/// cbChangePassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox cbChangePassword;
/// <summary>
/// lblFirstName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblFirstName;
/// <summary>
/// txtFirstName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtFirstName;
/// <summary>
/// lblLastName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblLastName;
/// <summary>
/// txtLastName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtLastName;
/// <summary>
/// lblReplyTo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblReplyTo;
/// <summary>
/// txtReplyTo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtReplyTo;
/// <summary>
/// lblSignature control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblSignature;
/// <summary>
/// txtSignature control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtSignature;
/// <summary>
/// secAutoresponder control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secAutoresponder;
/// <summary>
/// AutoresponderPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel AutoresponderPanel;
/// <summary>
/// lblResponderEnabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblResponderEnabled;
/// <summary>
/// chkResponderEnabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkResponderEnabled;
/// <summary>
/// lblSubject control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblSubject;
/// <summary>
/// txtSubject control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtSubject;
/// <summary>
/// lblMessage control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblMessage;
/// <summary>
/// txtMessage control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtMessage;
/// <summary>
/// secForwarding control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secForwarding;
/// <summary>
/// ForwardingPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel ForwardingPanel;
/// <summary>
/// lblForwardTo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblForwardTo;
/// <summary>
/// txtForward control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtForward;
/// <summary>
/// chkDeleteOnForward control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkDeleteOnForward;
}
}
| |
#if !HIGHPRECISION
using Real = System.Single;
#else
using Real = System.Double;
#endif
using System;
using System.Runtime.InteropServices;
namespace Lumix
{
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Vec4 : ICloneable, IEquatable<Vec4>
{
public Real x;
public Real y;
public Real z;
public Real w;
/// <summary>
/// Returns the vector (0,0,0,0).
/// </summary>
public static Vec4 Zero { get { return new Vec4(); } }
/// <summary>
/// Returns the vector (1,1,1,1).
/// </summary>
public static Vec4 One { get { return new Vec4(1.0f, 1.0f, 1.0f, 1.0f); } }
/// <summary>
/// Returns the vector (1,0,0,0).
/// </summary>
public static Vec4 UnitX { get { return new Vec4(1.0f, 0.0f, 0.0f, 0.0f); } }
/// <summary>
/// Returns the vector (0,1,0,0).
/// </summary>
public static Vec4 UnitY { get { return new Vec4(0.0f, 1.0f, 0.0f, 0.0f); } }
/// <summary>
/// Returns the vector (0,0,1,0).
/// </summary>
public static Vec4 UnitZ { get { return new Vec4(0.0f, 0.0f, 1.0f, 0.0f); } }
/// <summary>
/// Returns the vector (0,0,0,1).
/// </summary>
public static Vec4 UnitW { get { return new Vec4(0.0f, 0.0f, 0.0f, 1.0f); } }
public Vec4(Real _x, Real _y, Real _z, Real _w)
{
x = _x;
y = _y;
z = _z;
w = _w;
}
public Vec4(float[] _values)
{
x = _values[0];
y = _values[1];
z = _values[2];
w = _values[3];
}
/// <summary>
///
/// </summary>
/// <param name="vector"></param>
public Vec4(Vec4 vector)
{
x = vector.x;
y = vector.y;
z = vector.z;
w = vector.w;
}
/// <summary>
///
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public Real this[int index]
{
get
{
switch (index)
{
case 0:
return x;
case 1:
return y;
case 2:
return z;
case 3:
return w;
default:
throw new IndexOutOfRangeException("Vector has only 4 indices!");
}
}
set
{
switch (index)
{
case 0:
x = value;
break;
case 1:
y = value;
break;
case 2:
z = value;
break;
case 3:
w = value;
break;
default:
throw new IndexOutOfRangeException("Vector has only 4 indices!");
}
}
}
object ICloneable.Clone()
{
return new Vec4(this);
}
public Vec4 Clone()
{
return new Vec4(this);
}
public override int GetHashCode()
{
return x.GetHashCode() ^ y.GetHashCode() ^ z.GetHashCode() ^ w.GetHashCode();
}
public override string ToString()
{
return string.Format("X:{0},Y:{1},Z:{2},W:{3}", x, y, z, w);
}
public override bool Equals(object obj)
{
if (!(obj is Vec4))
return false;
return Equals((Vec4)obj);
}
public bool Equals(Vec4 v)
{
return v.x == this.x && v.y == this.y && v.z == this.z & v.w == this.w;
}
}
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Vec3 : ICloneable, IEquatable<Vec3>
{
public Real x;
public Real y;
public Real z;
/// <summary>
/// Vector 3, all components set to 0,
/// </summary>
public static readonly Vec3 Zero = new Vec3(0, 0, 0);
/// <summary>
/// Vector 3, all components set to 1,
/// </summary>
public static readonly Vec3 One = new Vec3(1, 1, 1);
/// <summary>
/// Vector 3, points "up", y component is 1
/// </summary>
public static readonly Vec3 Up = new Vec3(0, 1, 0);
/// <summary>
/// Vector 3, points "up", y component is 1
/// </summary>
public static readonly Vec3 Down = new Vec3(0, -1, 0);
/// <summary>
/// Vector 3, points "forward", z component is 1
/// </summary>
public static readonly Vec3 Forward = new Vec3(0, 0, 1);
/// <summary>
/// Vector 3, points "back", z component is -1
/// </summary>
public static readonly Vec3 Back = new Vec3(0, 0, -1);
/// <summary>
///
/// </summary>
public static readonly Vec3 Right = new Vec3(1, 0, 0);
/// <summary>
///
/// </summary>
public static readonly Vec3 Left = new Vec3(-1, 0, 0);
/// <summary>
///
/// </summary>
public static readonly Vec3 PosInfinity = new Vec3(Mathf.PosInfinity, Mathf.PosInfinity, Mathf.PosInfinity);
/// <summary>
/// Returns the length (magnitude) of the vector.
/// </summary>
/// <remarks>
/// This operation requires a square root and is expensive in
///terms of CPU operations.If you don't need to know the exact
///length (e.g. for just comparing lengths) use squaredLength()
/// instead.
/// </remarks>
public Real Length
{
get { return Mathf.Sqrt(x * x + y * y + z * z); }
}
/// <summary>
/// Returns the square of the length(magnitude) of the vector.
/// </summary>
/// <remarks>
/// This method is for efficiency - calculating the actual
/// length of a vector requires a square root, which is expensive
/// in terms of the operations required.This method returns the
/// square of the length of the vector, i.e.the same as the
/// length but before the square root is taken.Use this if you
/// want to find the longest / shortest vector without incurring
/// the square root.
/// </remarks>
public Real SquaredLength
{
get { return x * x + y * y + z * z; }
}
/// <summary>
/// Gets a value indicating whether this instance is invalid.
/// </summary>
/// <value>
/// <c>true</c> if this instance is invalid; otherwise, <c>false</c>.
/// </value>
public bool IsInvalid
{
get
{
return Real.IsNaN(this.x) || Real.IsNaN(this.y) || Real.IsNaN(this.z);
}
}
/// <summary>
/// Get's a copy of this vector, just normalized
/// </summary>
public Vec3 Normalized
{
get
{
Vec3 ret = new Vec3(this);
ret.Normalize();
return ret;
}
}
public Vec3(Real _x, Real _y, Real _z)
{
x = _x;
y = _y;
z = _z;
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
public Vec3(Real value)
{
x = value;
y = value;
z = value;
}
/// <summary>
///
/// </summary>
/// <param name="vector"></param>
public Vec3(Vec3 vector)
{
x = vector.x;
y = vector.y;
z = vector.z;
}
/// <summary>
///
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public Real this[int index]
{
get
{
switch (index)
{
case 0:
return x;
case 1:
return y;
case 2:
return z;
default:
throw new IndexOutOfRangeException("Vector has only 3 indices!");
}
}
set
{
switch (index)
{
case 0:
x = value;
break;
case 1:
y = value;
break;
case 2:
z = value;
break;
default:
throw new IndexOutOfRangeException("Vector has only 3 indices!");
}
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
object ICloneable.Clone()
{
return new Vec3(this);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public Vec3 Clone()
{
return new Vec3(this);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return x.GetHashCode() ^ y.GetHashCode() ^ z.GetHashCode();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format("X:{0},Y:{1},Z:{2}", x, y, z);
}
public void Set(Real _x, Real _y, Real _z)
{
x = _x;
y = _y;
z = _z;
}
/// <summary>
///
/// </summary>
/// <param name="_left"></param>
/// <param name="_right"></param>
/// <returns></returns>
public static Vec3 Add(Vec3 _left, Vec3 _right)
{
return new Vec3(_left.x + _right.x, _left.y + _right.y, _left.z + _right.z);
}
/// <summary>
///
/// </summary>
/// <param name="_left"></param>
/// <param name="_right"></param>
/// <returns></returns>
public static Vec3 Subtract(Vec3 _left, Vec3 _right)
{
return new Vec3(_left.x - _right.x, _left.y - _right.y, _left.z - _right.z);
}
/// <summary>
///
/// </summary>
/// <param name="_left"></param>
/// <param name="_right"></param>
/// <returns></returns>
public static Vec3 Multiply(Vec3 _left, Vec3 _right)
{
return new Vec3(_left.x * _right.x, _left.y * _right.y, _left.z * _right.z);
}
/// <summary>
///
/// </summary>
/// <param name="_left"></param>
/// <param name="_right"></param>
/// <returns></returns>
public static Vec3 Multiply(Real _left, Vec3 _right)
{
return new Vec3(_left * _right.x, _left * _right.y, _left * _right.z);
}
/// <summary>
///
/// </summary>
/// <param name="_left"></param>
/// <param name="_right"></param>
/// <returns></returns>
public static Vec3 Divide(Vec3 _left, Vec3 _right)
{
return new Vec3(_left.x / _right.x, _left.y / _right.y, _left.z / _right.z);
}
/// <summary>
///
/// </summary>
/// <param name="_left"></param>
/// <param name="_right"></param>
/// <returns></returns>
public static Vec3 Divide(Vec3 _left, Real _right)
{
return new Vec3(_left.x / _right, _left.y / _right, _left.z / _right);
}
/// <summary>
///
/// </summary>
/// <param name="_left"></param>
/// <param name="_right"></param>
/// <returns></returns>
public static Vec3 operator +(Vec3 _left, Vec3 _right)
{
return Add(_left, _right);
}
/// <summary>
///
/// </summary>
/// <param name="_left"></param>
/// <param name="_right"></param>
/// <returns></returns>
public static Vec3 operator -(Vec3 _left, Vec3 _right)
{
return Subtract(_left, _right);
}
public static bool operator ==(Vec3 _left, Vec3 _right)
{
return _left.x == _right.x && _left.y == _right.y && _left.z == _right.z;
}
public static bool operator !=(Vec3 _left, Vec3 _right)
{
return !(_left == _right);
}
/// <summary>
///
/// </summary>
/// <param name="_left"></param>
/// <param name="_right"></param>
/// <returns></returns>
public static Vec3 operator *(Vec3 _left, Vec3 _right)
{
return Multiply(_left, _right);
}
/// <summary>
///
/// </summary>
/// <param name="_left"></param>
/// <param name="_right"></param>
/// <returns></returns>
public static Vec3 operator *(Real _left, Vec3 _right)
{
return Multiply(_left, _right);
}
/// <summary>
///
/// </summary>
/// <param name="_left"></param>
/// <param name="_right"></param>
/// <returns></returns>
public static Vec3 operator *(Vec3 _left, Real _right)
{
return Multiply(_right, _left);
}
/// <summary>
///
/// </summary>
/// <param name="_left"></param>
/// <param name="_right"></param>
/// <returns></returns>
public static Vec3 operator /(Vec3 _left, Vec3 _right)
{
return Divide(_left, _right);
}
/// <summary>
///
/// </summary>
/// <param name="_left"></param>
/// <param name="_right"></param>
/// <returns></returns>
public static Vec3 operator /(Vec3 _left, Real _right)
{
return Divide(_left, _right);
}
public static Vec3 operator -(Vec3 _value)
{
return new Vec3(-_value.x, -_value.y, -_value.z);
}
/// <summary>
/// Calculates the dot (scalar) product of this vector with another.
/// </summary>
/// <param name="_left"></param>
/// <param name="_right"></param>
/// <returns></returns>
public static Real DotProduct(Vec3 _left, Vec3 _right)
{
return _left.x * _right.x + _left.y * _right.y + _left.z * _right.z;
}
/// <summary>
/// Calculates the absolute dot (scalar) product of given vector with other.
/// </summary>
/// <param name="_left"></param>
/// <param name="_right"></param>
/// <returns></returns>
public static Real AbsDotProduct(Vec3 _left, Vec3 _right)
{
return Mathf.Abs(_left.x * _right.x) + Mathf.Abs(_left.y * _right.y) + Mathf.Abs(_left.z * _right.z);
}
/// <summary>
/// Calculates the dot (scalar) product of this vector with another.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public Real DotProduct(Vec3 _value)
{
return DotProduct(this, _value);
}
/// <summary>
/// Calculates the absolute dot (scalar) product of this vector with another.
/// </summary>
/// <param name="_other"></param>
/// <returns></returns>
public Real AbsDotProduct(Vec3 _other)
{
return AbsDotProduct(this, _other);
}
/// <summary>
/// Calculates the cross-product of 2 vectors, i.e. the vector that
/// lies perpendicular to them both.
/// </summary>
/// <param name="_left"></param>
/// <param name="_right"></param>
/// <returns></returns>
public static Vec3 CrossProduct(Vec3 _left, Vec3 _right)
{
return new Vec3(
_left.y * _right.z - _left.z * _right.y,
_left.z * _right.x - _left.x * _right.z,
_left.x * _right.y - _left.y * _right.x
);
}
/// <summary>
/// Calculates the cross-product of 2 vectors, i.e. the vector that
/// lies perpendicular to them both.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public Vec3 CrossProduct(Vec3 value)
{
return CrossProduct(this, value);
}
/// <summary>
/// Normalizes the vector.
/// </summary>
/// <returns>The previous length of the vector.</returns>
public float Normalize()
{
Real length = Mathf.Sqrt(x * x + y * y + z * z);
if (length > (Real)0.0)
{
Real invLength = (Real)1.0 / length;
x *= invLength;
y *= invLength;
z *= invLength;
}
return length;
}
/// <summary>
/// Sets this vector's components to the minimum of its own and the
/// ones of the passed in vector.
/// </summary>
/// <param name="_other"></param>
public void MakeFloor(Vec3 _other)
{
if (_other.x < x) x = _other.x;
if (_other.y < y) y = _other.y;
if (_other.z < z) z = _other.z;
}
/// <summary>
/// Sets this vector's components to the maximum of its own and the
/// ones of the passed in vector.
/// </summary>
/// <param name="_other"></param>
public void MakeCeil(Vec3 _other)
{
if (_other.x > x) x = _other.x;
if (_other.y > y) y = _other.y;
if (_other.z > z) z = _other.z;
}
/// <summary>
/// Determines whether the specified <see cref="System.Object" />, is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
if (!(obj is Vec3))
return false;
Vec3 v = (Vec3)obj;
return v.x == this.x && v.y == this.y && v.z == this.z;
}
public bool Equals(Vec3 v)
{
return v.x == this.x && v.y == this.y && v.z == this.z;
}
}
public struct Vec2
{
public Real x;
public Real y;
public Vec2(Real _constant)
{
x = _constant;
y = _constant;
}
public Vec2(Real _x, Real _y)
{
x = _x;
y = _y;
}
public static Vec2 Add(Vec2 _left, Vec2 _right)
{
return new Vec2(_left.x + _right.x, _left.y + _right.y);
}
public static Vec2 Divide(Vec2 _left, Vec2 _right)
{
return new Vec2(_left.x / _right.x, _left.y / _right.y);
}
public static Vec2 Divide(Vec2 _left, Real _right)
{
return new Vec2(_left.x / _right, _left.y / _right);
}
public static Vec2 Subtract(Vec2 _left, Vec2 _right)
{
return new Vec2(_left.x - _right.x, _left.y - _right.y);
}
public static Vec2 operator/(Vec2 _left, Vec2 _right)
{
return Divide(_left, _right);
}
public static Vec2 operator /(Vec2 _left, Real _right)
{
return Divide(_left, _right);
}
public static Int2 operator-(Vec2 _left, Int2 _right)
{
return new Int2(_left.x - _right.x, _left.y - _right.y);
}
public static Vec2 operator-(Vec2 _left, Vec2 _right)
{
return Subtract(_left, _right);
}
}
public struct Int2
{
public int x;
public int y;
public static readonly Int2 Zero = new Int2(0, 0);
public int this[int _index]
{
get
{
switch (_index)
{
case 0:
return x;
case 1:
return y;
default:
throw new IndexOutOfRangeException("index");
}
}
set
{
switch (_index)
{
case 0:
x = value;
break;
case 1:
y = value;
break;
default:
throw new IndexOutOfRangeException("index");
}
}
}
public Int2(float _x, float _y)
{
x = (int)_x;
y = (int)_y;
}
public Int2(int _x, int _y)
{
x = _x;
y = _y;
}
public Int2(Int2 _other)
{
x = _other.x;
y = _other.y;
}
public Int2(int _constant)
{
x = _constant;
y = _constant;
}
public static Int2 Add(Int2 _left, Int2 _right)
{
return new Int2(_left.x + _right.x, _left.y + _right.y);
}
public static Int2 operator + (Int2 _left, Int2 _right)
{
return Add(_left, _right);
}
public static Int2 Subtract(Int2 _left, Int2 _right)
{
return new Int2(_left.x - _right.x, _left.y - _right.y);
}
public static Int2 operator -(Int2 _left, Int2 _right)
{
return Subtract(_left, _right);
}
public static Int2 Divide(Int2 _left, Int2 _right)
{
return new Int2(_left.x / _right.x, _left.y / _right.y);
}
public static Int2 Divide(Int2 _left, int _right)
{
return new Int2(_left.x / _right, _left.y / _right);
}
public static Int2 operator /(Int2 _left, Int2 _right)
{
return Divide(_left, _right);
}
public static Int2 operator /(Int2 _left, int _right)
{
return Divide(_left, _right);
}
public static Int2 operator -(Int2 _left, Vec2 _right)
{
return new Int2(_left.x - _right.x, _left.y - _right.y);
}
public static implicit operator Vec2(Int2 _value)
{
return new Vec2(_value.x, _value.y);
}
public static Int2 Multiply(Int2 _left, int _right)
{
return new Int2(_left.x * _right, _left.y * _right);
}
public static Int2 operator*(Int2 _left, int _right)
{
return Multiply(_left, _right);
}
public int[] ToArray()
{
return new int[] { x, y };
}
public override string ToString()
{
return string.Format("x:{0},y:{1}", x, y);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans.Streams;
using Orleans.Runtime.Scheduler;
using Orleans.Runtime.Versions;
using Orleans.Versions;
using Orleans.Versions.Compatibility;
using Orleans.Versions.Selector;
namespace Orleans.Runtime
{
internal class TypeManager : SystemTarget, IClusterTypeManager, ISiloTypeManager, ISiloStatusListener, IDisposable
{
private readonly ILogger logger;
private readonly GrainTypeManager grainTypeManager;
private readonly ISiloStatusOracle statusOracle;
private readonly ImplicitStreamSubscriberTable implicitStreamSubscriberTable;
private readonly IInternalGrainFactory grainFactory;
private readonly CachedVersionSelectorManager versionSelectorManager;
private readonly OrleansTaskScheduler scheduler;
private readonly TimeSpan refreshClusterMapInterval;
private bool hasToRefreshClusterGrainInterfaceMap;
private IDisposable refreshClusterGrainInterfaceMapTimer;
private IVersionStore versionStore;
internal TypeManager(
SiloAddress myAddr,
GrainTypeManager grainTypeManager,
ISiloStatusOracle oracle,
OrleansTaskScheduler scheduler,
TimeSpan refreshClusterMapInterval,
ImplicitStreamSubscriberTable implicitStreamSubscriberTable,
IInternalGrainFactory grainFactory,
CachedVersionSelectorManager versionSelectorManager,
ILoggerFactory loggerFactory)
: base(Constants.TypeManagerId, myAddr, loggerFactory)
{
if (grainTypeManager == null)
throw new ArgumentNullException(nameof(grainTypeManager));
if (oracle == null)
throw new ArgumentNullException(nameof(oracle));
if (scheduler == null)
throw new ArgumentNullException(nameof(scheduler));
if (implicitStreamSubscriberTable == null)
throw new ArgumentNullException(nameof(implicitStreamSubscriberTable));
this.logger = loggerFactory.CreateLogger<TypeManager>();
this.grainTypeManager = grainTypeManager;
this.statusOracle = oracle;
this.implicitStreamSubscriberTable = implicitStreamSubscriberTable;
this.grainFactory = grainFactory;
this.versionSelectorManager = versionSelectorManager;
this.scheduler = scheduler;
this.refreshClusterMapInterval = refreshClusterMapInterval;
// We need this so we can place needed local activations
this.grainTypeManager.SetInterfaceMapsBySilo(new Dictionary<SiloAddress, GrainInterfaceMap>
{
{this.Silo, grainTypeManager.GetTypeCodeMap()}
});
}
internal async Task Initialize(IVersionStore store)
{
this.versionStore = store;
this.hasToRefreshClusterGrainInterfaceMap = true;
await this.OnRefreshClusterMapTimer(null);
this.refreshClusterGrainInterfaceMapTimer = this.RegisterTimer(
OnRefreshClusterMapTimer,
null,
this.refreshClusterMapInterval,
this.refreshClusterMapInterval);
}
public Task<IGrainTypeResolver> GetClusterGrainTypeResolver()
{
return Task.FromResult<IGrainTypeResolver>(grainTypeManager.GrainTypeResolver);
}
public Task<GrainInterfaceMap> GetSiloTypeCodeMap()
{
return Task.FromResult(grainTypeManager.GetTypeCodeMap());
}
public Task<ImplicitStreamSubscriberTable> GetImplicitStreamSubscriberTable(SiloAddress silo)
{
return Task.FromResult(implicitStreamSubscriberTable);
}
public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status)
{
hasToRefreshClusterGrainInterfaceMap = true;
if (status == SiloStatus.Active)
{
if (this.logger.IsEnabled(LogLevel.Information))
{
this.logger.LogInformation("Expediting cluster type map refresh due to new silo, {SiloAddress}", updatedSilo);
}
this.scheduler.QueueTask(() => this.OnRefreshClusterMapTimer(null), SchedulingContext);
}
}
private async Task OnRefreshClusterMapTimer(object _)
{
// Check if we have to refresh
if (!hasToRefreshClusterGrainInterfaceMap)
{
if (this.logger.IsEnabled(LogLevel.Trace)) logger.Trace("OnRefreshClusterMapTimer: no refresh required");
return;
}
while (hasToRefreshClusterGrainInterfaceMap)
{
hasToRefreshClusterGrainInterfaceMap = false;
if (this.logger.IsEnabled(LogLevel.Debug)) logger.Debug("OnRefreshClusterMapTimer: refresh start");
var activeSilos = statusOracle.GetApproximateSiloStatuses(onlyActive: true);
var knownSilosClusterGrainInterfaceMap = grainTypeManager.GrainInterfaceMapsBySilo;
// Build the new map. Always start by himself
var newSilosClusterGrainInterfaceMap = new Dictionary<SiloAddress, GrainInterfaceMap>
{
{this.Silo, grainTypeManager.GetTypeCodeMap()}
};
var getGrainInterfaceMapTasks = new List<Task<KeyValuePair<SiloAddress, GrainInterfaceMap>>>();
foreach (var siloAddress in activeSilos.Keys)
{
if (siloAddress.Equals(this.Silo)) continue;
GrainInterfaceMap value;
if (knownSilosClusterGrainInterfaceMap.TryGetValue(siloAddress, out value))
{
if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace("OnRefreshClusterMapTimer: value already found locally for {SiloAddress}", siloAddress);
newSilosClusterGrainInterfaceMap[siloAddress] = value;
}
else
{
// Value not found, let's get it
if (this.logger.IsEnabled(LogLevel.Debug)) this.logger.Debug("OnRefreshClusterMapTimer: value not found locally for {SiloAddress}", siloAddress);
getGrainInterfaceMapTasks.Add(GetTargetSiloGrainInterfaceMap(siloAddress));
}
}
if (getGrainInterfaceMapTasks.Any())
{
foreach (var keyValuePair in await Task.WhenAll(getGrainInterfaceMapTasks))
{
if (keyValuePair.Value != null)
newSilosClusterGrainInterfaceMap.Add(keyValuePair.Key, keyValuePair.Value);
}
}
grainTypeManager.SetInterfaceMapsBySilo(newSilosClusterGrainInterfaceMap);
if (this.versionStore.IsEnabled)
{
await this.GetAndSetDefaultCompatibilityStrategy();
foreach (var kvp in await GetStoredCompatibilityStrategies())
{
this.versionSelectorManager.CompatibilityDirectorManager.SetStrategy(kvp.Key, kvp.Value);
}
await this.GetAndSetDefaultSelectorStrategy();
foreach (var kvp in await GetSelectorStrategies())
{
this.versionSelectorManager.VersionSelectorManager.SetSelector(kvp.Key, kvp.Value);
}
}
versionSelectorManager.ResetCache();
// Either a new silo joined or a refresh failed, so continue until no refresh is required.
if (hasToRefreshClusterGrainInterfaceMap)
{
if (this.logger.IsEnabled(LogLevel.Debug))
{
this.logger.LogDebug("OnRefreshClusterMapTimer: cluster type map still requires a refresh and will be refreshed again after a short delay");
}
await Task.Delay(TimeSpan.FromSeconds(1));
}
}
}
private async Task GetAndSetDefaultSelectorStrategy()
{
try
{
var strategy = await this.versionStore.GetSelectorStrategy();
this.versionSelectorManager.VersionSelectorManager.SetSelector(strategy);
}
catch (Exception)
{
hasToRefreshClusterGrainInterfaceMap = true;
}
}
private async Task GetAndSetDefaultCompatibilityStrategy()
{
try
{
var strategy = await this.versionStore.GetCompatibilityStrategy();
this.versionSelectorManager.CompatibilityDirectorManager.SetStrategy(strategy);
}
catch (Exception)
{
hasToRefreshClusterGrainInterfaceMap = true;
}
}
private async Task<Dictionary<int, CompatibilityStrategy>> GetStoredCompatibilityStrategies()
{
try
{
return await this.versionStore.GetCompatibilityStrategies();
}
catch (Exception)
{
hasToRefreshClusterGrainInterfaceMap = true;
return new Dictionary<int, CompatibilityStrategy>();
}
}
private async Task<Dictionary<int, VersionSelectorStrategy>> GetSelectorStrategies()
{
try
{
return await this.versionStore.GetSelectorStrategies();
}
catch (Exception)
{
hasToRefreshClusterGrainInterfaceMap = true;
return new Dictionary<int, VersionSelectorStrategy>();
}
}
private async Task<KeyValuePair<SiloAddress, GrainInterfaceMap>> GetTargetSiloGrainInterfaceMap(SiloAddress siloAddress)
{
try
{
var remoteTypeManager = this.grainFactory.GetSystemTarget<ISiloTypeManager>(Constants.TypeManagerId, siloAddress);
var siloTypeCodeMap = await scheduler.QueueTask(() => remoteTypeManager.GetSiloTypeCodeMap(), SchedulingContext);
return new KeyValuePair<SiloAddress, GrainInterfaceMap>(siloAddress, siloTypeCodeMap);
}
catch (Exception ex)
{
// Will be retried on the next timer hit
logger.Error(ErrorCode.TypeManager_GetSiloGrainInterfaceMapError, $"Exception when trying to get GrainInterfaceMap for silos {siloAddress}", ex);
hasToRefreshClusterGrainInterfaceMap = true;
return new KeyValuePair<SiloAddress, GrainInterfaceMap>(siloAddress, null);
}
}
public void Dispose()
{
if (this.refreshClusterGrainInterfaceMapTimer != null)
{
this.refreshClusterGrainInterfaceMapTimer.Dispose();
}
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System.Collections.Generic;
using System.Globalization;
namespace System.Web.UI
{
public partial class HtmlBuilder
{
private Stack<Element> _elementStack = new Stack<Element>();
private string _formName;
private bool _isInAnchor = false;
private Control _commandTargetControl;
private HtmlBuilderDivTag _divTag;
private HtmlBuilderFormTag _formTag;
private HtmlBuilderTableTag _tableTag;
private HtmlOption _option;
/// <summary>
/// Element
/// </summary>
private struct Element
{
public HtmlTag Tag;
public string ValueIfUnknown;
public object State;
public Element(HtmlTag tag, object state)
{
Tag = tag;
State = state;
ValueIfUnknown = null;
}
public Element(string tag, object state)
{
Tag = HtmlTag.Unknown;
State = state;
ValueIfUnknown = tag;
}
}
/// <summary>
/// DivElementState
/// </summary>
private struct DivElementState
{
public bool IsState;
public HtmlBuilderDivTag DivState;
public DivElementState(bool isState, HtmlBuilderDivTag divState)
{
IsState = isState;
DivState = divState;
}
}
/// <summary>
/// HtmlOption
/// </summary>
public class HtmlOption
{
/// <summary>
/// Type
/// </summary>
public HtmlBuilderOptionType Type;
/// <summary>
/// Key
/// </summary>
public string Key;
/// <summary>
/// Value
/// </summary>
public string Value;
/// <summary>
/// Size
/// </summary>
public int Size;
}
/// <summary>
/// Gets or sets the command target control.
/// </summary>
/// <value>
/// The command target control.
/// </value>
public Control CommandTargetControl
{
get { return _commandTargetControl; }
protected set { _commandTargetControl = value; }
}
/// <summary>
/// Gets the div tag.
/// </summary>
public HtmlBuilderDivTag DivTag
{
get { return _divTag; }
}
/// <summary>
/// Gets the form tag.
/// </summary>
public HtmlBuilderFormTag FormTag
{
get { return _formTag; }
}
/// <summary>
/// Gets the table tag.
/// </summary>
public HtmlBuilderTableTag TableTag
{
get { return _tableTag; }
}
/// <summary>
/// Elements the pop.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="valueIfUnknown">The value if unknown.</param>
/// <param name="stopTag">The stop tag.</param>
/// <param name="stopValueIfUnknown">The stop value if unknown.</param>
public void ElementPop(HtmlTag tag, string valueIfUnknown, HtmlTag stopTag, string stopValueIfUnknown)
{
var stackTag = HtmlTag.__Undefined;
string stackValueIfUnknown = null;
while ((stackTag != tag || stackValueIfUnknown != valueIfUnknown) && _elementStack.Count > 0)
{
Element peekElement;
if (stopTag != HtmlTag.__Undefined)
{
peekElement = _elementStack.Peek();
var peekElementTag = peekElement.Tag;
switch (stopTag)
{
case HtmlTag.__OlUl:
if (peekElementTag == HtmlTag.Ol || peekElementTag == HtmlTag.Ul)
return;
break;
default:
if (peekElementTag == stopTag && peekElement.ValueIfUnknown == stopValueIfUnknown)
return;
break;
}
}
var element = _elementStack.Pop();
stackTag = element.Tag;
stackValueIfUnknown = element.ValueIfUnknown;
switch (stackTag)
{
case HtmlTag._CommandTarget:
_commandTargetControl = (Control)element.State;
break;
case HtmlTag.Script:
_writeCount++;
_textWriter.Write("//--> ]]>");
_textWriter.RenderEndTag();
break;
// Container
case HtmlTag.Div:
_writeCount++;
var divElementState = (DivElementState)element.State;
if (divElementState.IsState)
_divTag = divElementState.DivState;
_textWriter.RenderEndTag();
break;
// Content
case HtmlTag.A:
_writeCount++;
_isInAnchor = false;
_textWriter.RenderEndTag();
break;
// H1-3
case HtmlTag.H1:
case HtmlTag.H2:
case HtmlTag.H3:
_writeCount++;
_textWriter.RenderEndTag();
break;
// Paragraph
case HtmlTag.P:
_writeCount++;
_textWriter.RenderEndTag();
break;
// Span
case HtmlTag.Span:
_writeCount++;
_textWriter.RenderEndTag();
break;
// List
case HtmlTag.Li:
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Ol:
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Ul:
_writeCount++;
_textWriter.RenderEndTag();
break;
// Table
case HtmlTag.Colgroup:
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Table:
_writeCount++;
_tableTag = (HtmlBuilderTableTag)element.State;
_textWriter.RenderEndTag();
break;
case HtmlTag.Tbody:
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Td:
string nullTdBody;
if ((int)element.State == _writeCount && (nullTdBody = _tableTag.NullTdBody).Length > 0)
_textWriter.Write(nullTdBody);
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Tfoot:
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Th:
string nullTdBody2;
if ((int)element.State == _writeCount && (nullTdBody2 = _tableTag.NullTdBody).Length > 0)
_textWriter.Write(nullTdBody2);
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Thead:
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Tr:
var trCloseMethod = _tableTag.TrCloseMethod;
if (trCloseMethod != HtmlBuilderTableTag.TableTrCloseMethod.Undefined)
{
var tdCount = (_tableTag.ColumnCount - _tableTag.ColumnIndex);
switch (trCloseMethod)
{
case HtmlBuilderTableTag.TableTrCloseMethod.Td:
for (int tdIndex = 1; tdIndex < tdCount; tdIndex++)
{
_tableTag.AddAttribute(this, _textWriter, HtmlTag.Td, null);
_textWriter.RenderBeginTag(HtmlTextWriterTag.Td);
var nullTdBody3 = _tableTag.NullTdBody;
if (nullTdBody3.Length > 0)
_textWriter.Write(nullTdBody3);
_textWriter.RenderEndTag();
}
break;
case HtmlBuilderTableTag.TableTrCloseMethod.TdColspan:
if (tdCount > 0)
{
if (tdCount > 1)
_textWriter.AddAttribute(HtmlTextWriterAttribute.Colspan, tdCount.ToString());
_tableTag.AddAttribute(this, _textWriter, HtmlTag.Td, null);
_textWriter.RenderBeginTag(HtmlTextWriterTag.Td);
var nullTdBody4 = _tableTag.NullTdBody;
if (nullTdBody4.Length > 0)
_textWriter.Write(nullTdBody4);
_textWriter.RenderEndTag();
}
break;
}
}
_tableTag.IsTrHeader = false;
_writeCount++;
_textWriter.RenderEndTag();
break;
// Form
case HtmlTag._FormReference:
if (_formTag != null)
_formTag = null;
break;
case HtmlTag.Button:
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Fieldset:
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Form:
_writeCount++;
//Http.Instance.ExitForm(this);
if (_formTag != null)
_formTag = null;
_formName = null;
_textWriter.RenderEndTag();
break;
case HtmlTag.Label:
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Option:
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Select:
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Textarea:
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Unknown:
_writeCount++;
switch (element.ValueIfUnknown)
{
case "optgroup":
_textWriter.RenderEndTag();
break;
default:
_textWriter.RenderEndTag();
break;
}
break;
default:
_writeCount++;
_textWriter.RenderEndTag();
break;
}
}
}
/// <summary>
/// Elements the push.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="state">The state.</param>
public void ElementPush(HtmlTag tag, object state) { _elementStack.Push(new Element(tag, state)); }
/// <summary>
/// Elements the push.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="state">The state.</param>
public void ElementPush(string tag, object state) { _elementStack.Push(new Element(tag, state)); }
}
}
| |
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.Security.Cryptography;
namespace LumiSoft.Net.POP3.Client
{
/// <summary>
/// POP3 Client.
/// </summary>
/// <example>
/// <code>
///
/// /*
/// To make this code to work, you need to import following namespaces:
/// using LumiSoft.Net.Mime;
/// using LumiSoft.Net.POP3.Client;
/// */
///
/// using(POP3_Client c = new POP3_Client()){
/// c.Connect("ivx",110);
/// c.Authenticate("test","test",true);
///
/// POP3_MessagesInfo mInf = c.GetMessagesInfo();
///
/// // Get first message if there is any
/// if(mInf.Count > 0){
/// byte[] messageData = c.GetMessage(mInf.Messages[0].MessageNumber);
///
/// // Do your suff
///
/// // Parse message
/// MimeParser m = MimeParser(messageData);
/// string from = m.From;
/// string subject = m.Subject;
/// // ...
/// }
/// }
/// </code>
/// </example>
public class POP3_Client : IDisposable
{
private BufferedSocket m_pSocket = null;
private SocketLogger m_pLogger = null;
private bool m_Connected = false;
private bool m_Authenticated = false;
private string m_ApopHashKey = "";
private bool m_LogCmds = false;
/// <summary>
/// Occurs when POP3 session has finished and session log is available.
/// </summary>
public event LogEventHandler SessionLog = null;
/// <summary>
/// Default constructor.
/// </summary>
public POP3_Client()
{
}
#region function Dispose
/// <summary>
/// Clean up any resources being used.
/// </summary>
public void Dispose()
{
try{
Disconnect();
}
catch{
}
}
#endregion
#region function Connect
/// <summary>
/// Connects to specified host.
/// </summary>
/// <param name="host">Host name.</param>
/// <param name="port">Port number.</param>
public void Connect(string host,int port)
{
if(!m_Connected){
Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPEndPoint ipdest = new IPEndPoint(System.Net.Dns.Resolve(host).AddressList[0],port);
s.Connect(ipdest);
s.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.NoDelay,1);
m_pSocket = new BufferedSocket(s);
if(m_LogCmds && SessionLog != null){
m_pLogger = new SocketLogger(s,SessionLog);
m_pLogger.SessionID = Guid.NewGuid().ToString();
m_pSocket.Logger = m_pLogger;
}
// Set connected flag
m_Connected = true;
string reply = m_pSocket.ReadLine();
if(reply.StartsWith("+OK")){
// Try to read APOP hash key, if supports APOP
if(reply.IndexOf("<") > -1 && reply.IndexOf(">") > -1){
m_ApopHashKey = reply.Substring(reply.LastIndexOf("<"),reply.LastIndexOf(">") - reply.LastIndexOf("<") + 1);
}
}
}
}
#endregion
#region function Disconnect
/// <summary>
/// Closes connection to POP3 server.
/// </summary>
public void Disconnect()
{
try{
if(m_pSocket != null){
// Send QUIT
m_pSocket.SendLine("QUIT");
m_pSocket.Shutdown(SocketShutdown.Both);
}
}
catch{
}
if(m_pLogger != null){
m_pLogger.Flush();
}
m_pLogger = null;
m_pSocket = null;
m_Connected = false;
m_Authenticated = false;
}
#endregion
#region function Authenticate
/// <summary>
/// Authenticates user.
/// </summary>
/// <param name="userName">User login name.</param>
/// <param name="password">Password.</param>
/// <param name="tryApop"> If true and POP3 server supports APOP, then APOP is used, otherwise normal login used.</param>
public void Authenticate(string userName,string password,bool tryApop)
{
if(!m_Connected){
throw new Exception("You must connect first !");
}
if(m_Authenticated){
throw new Exception("You are already authenticated !");
}
// Supports APOP, use it
if(tryApop && m_ApopHashKey.Length > 0){
//--- Compute md5 hash -----------------------------------------------//
byte[] data = System.Text.Encoding.ASCII.GetBytes(m_ApopHashKey + password);
MD5 md5 = new MD5CryptoServiceProvider();
byte[] hash = md5.ComputeHash(data);
string hexHash = BitConverter.ToString(hash).ToLower().Replace("-","");
//---------------------------------------------------------------------//
m_pSocket.SendLine("APOP " + userName + " " + hexHash);
string reply = m_pSocket.ReadLine();
if(reply.StartsWith("+OK")){
m_Authenticated = true;
}
else{
throw new Exception("Server returned:" + reply);
}
}
else{ // Use normal LOGIN, don't support APOP
m_pSocket.SendLine("USER " + userName);
string reply = m_pSocket.ReadLine();
if(reply.StartsWith("+OK")){
m_pSocket.SendLine("PASS " + password);
reply = m_pSocket.ReadLine();
if(reply.StartsWith("+OK")){
m_Authenticated = true;
}
else{
throw new Exception("Server returned:" + reply);
}
}
else{
throw new Exception("Server returned:" + reply);
}
}
}
#endregion
#region function GetMessagesInfo
/// <summary>
/// Gets messages info.
/// </summary>
public POP3_MessagesInfo GetMessagesInfo()
{
if(!m_Connected){
throw new Exception("You must connect first !");
}
if(!m_Authenticated){
throw new Exception("You must authenticate first !");
}
POP3_MessagesInfo messagesInfo = new POP3_MessagesInfo();
// Before getting list get UIDL list, then we make full message info (UID,Nr,Size).
Hashtable uidlList = GetUidlList();
m_pSocket.SendLine("LIST");
/* NOTE: If reply is +OK, this is multiline respone and is terminated with '.'.
Examples:
C: LIST
S: +OK 2 messages (320 octets)
S: 1 120
S: 2 200
S: .
...
C: LIST 3
S: -ERR no such message, only 2 messages in maildrop
*/
// Read first line of reply, check if it's ok
string line = m_pSocket.ReadLine();
if(line.StartsWith("+OK")){
// Read lines while get only '.' on line itshelf.
while(true){
line = m_pSocket.ReadLine();
// End of data
if(line.Trim() == "."){
break;
}
else{
string[] param = line.Trim().Split(new char[]{' '});
int nr = Convert.ToInt32(param[0]);
long size = Convert.ToInt64(param[1]);
messagesInfo.Add(uidlList[nr].ToString(),nr,size);
}
}
}
else{
throw new Exception("Server returned:" + line);
}
return messagesInfo;
}
#endregion
#region function GetUidlList
/// <summary>
/// Gets uid listing.
/// </summary>
/// <returns>Returns Hashtable containing uidl listing. Key column contains message NR and value contains message UID.</returns>
public Hashtable GetUidlList()
{
if(!m_Connected){
throw new Exception("You must connect first !");
}
if(!m_Authenticated){
throw new Exception("You must authenticate first !");
}
Hashtable retVal = new Hashtable();
m_pSocket.SendLine("UIDL");
/* NOTE: If reply is +OK, this is multiline respone and is terminated with '.'.
Examples:
C: UIDL
S: +OK
S: 1 whqtswO00WBw418f9t5JxYwZ
S: 2 QhdPYR:00WBw1Ph7x7
S: .
...
C: UIDL 3
S: -ERR no such message
*/
// Read first line of reply, check if it's ok
string line = m_pSocket.ReadLine();
if(line.StartsWith("+OK")){
// Read lines while get only '.' on line itshelf.
while(true){
line = m_pSocket.ReadLine();
// End of data
if(line.Trim() == "."){
break;
}
else{
string[] param = line.Trim().Split(new char[]{' '});
int nr = Convert.ToInt32(param[0]);
string uid = param[1];
retVal.Add(nr,uid);
}
}
}
else{
throw new Exception("Server returned:" + line);
}
return retVal;
}
#endregion
#region function GetMessage
/*
/// <summary>
/// Transfers specified message to specified socket. This is good for example transfering message from remote POP3 server to POP3 client.
/// </summary>
/// <param name="nr">Message number.</param>
/// <param name="socket">Socket where to store message.</param>
public void GetMessage(int nr,Socket socket)
{
if(!m_Connected){
throw new Exception("You must connect first !");
}
if(!m_Authenticated){
throw new Exception("You must authenticate first !");
}
Core.SendLine(m_pSocket,"RETR " + nr.ToString());
// Read first line of reply, check if it's ok
string line = Core.ReadLine(m_pSocket);
if(line.StartsWith("+OK")){
NetworkStream readStream = new NetworkStream(m_pSocket);
NetworkStream storeStream = new NetworkStream(socket);
byte[] crlf = new byte[]{(byte)'\r',(byte)'\n'};
StreamLineReader reader = new StreamLineReader(readStream);
byte[] lineData = reader.ReadLine();
while(lineData != null){
// End of message reached
if(lineData.Length == 1 && lineData[0] == '.'){
return;
}
storeStream.Write(lineData,0,lineData.Length);
storeStream.Write(crlf,0,crlf.Length);
lineData = reader.ReadLine();
}
}
else{
throw new Exception("Server returned:" + line);
}
}
*/
/// <summary>
/// Gets specified message.
/// </summary>
/// <param name="nr">Message number.</param>
public byte[] GetMessage(int nr)
{
if(!m_Connected){
throw new Exception("You must connect first !");
}
if(!m_Authenticated){
throw new Exception("You must authenticate first !");
}
m_pSocket.SendLine("RETR " + nr.ToString());
// Read first line of reply, check if it's ok
string line = m_pSocket.ReadLine();
if(line.StartsWith("+OK")){
MemoryStream strm = new MemoryStream();
ReadReplyCode code = m_pSocket.ReadData(strm,100000000,"\r\n.\r\n",".\r\n");
if(code != ReadReplyCode.Ok){
throw new Exception("Error:" + code.ToString());
}
return Core.DoPeriodHandling(strm,false).ToArray();
}
else{
throw new Exception("Server returned:" + line);
}
}
#endregion
#region function DeleteMessage
/// <summary>
/// Deletes specified message
/// </summary>
/// <param name="messageNr">Message number.</param>
public void DeleteMessage(int messageNr)
{
if(!m_Connected){
throw new Exception("You must connect first !");
}
if(!m_Authenticated){
throw new Exception("You must authenticate first !");
}
m_pSocket.SendLine("DELE " + messageNr.ToString());
// Read first line of reply, check if it's ok
string line = m_pSocket.ReadLine();
if(!line.StartsWith("+OK")){
throw new Exception("Server returned:" + line);
}
}
#endregion
#region function GetTopOfMessage
/// <summary>
/// Gets top lines of message.
/// </summary>
/// <param name="nr">Message number which top lines to get.</param>
/// <param name="nLines">Number of lines to get.</param>
public byte[] GetTopOfMessage(int nr,int nLines)
{
if(!m_Connected){
throw new Exception("You must connect first !");
}
if(!m_Authenticated){
throw new Exception("You must authenticate first !");
}
m_pSocket.SendLine("TOP " + nr.ToString() + " " + nLines.ToString());
// Read first line of reply, check if it's ok
string line = m_pSocket.ReadLine();
if(line.StartsWith("+OK")){
MemoryStream strm = new MemoryStream();
ReadReplyCode code = m_pSocket.ReadData(strm,100000000,"\r\n.\r\n",".\r\n");
if(code != ReadReplyCode.Ok){
throw new Exception("Error:" + code.ToString());
}
return Core.DoPeriodHandling(strm,false).ToArray();
}
else{
throw new Exception("Server returned:" + line);
}
}
#endregion
#region function Reset
/// <summary>
/// Resets session.
/// </summary>
public void Reset()
{
if(!m_Connected){
throw new Exception("You must connect first !");
}
if(!m_Authenticated){
throw new Exception("You must authenticate first !");
}
m_pSocket.SendLine("RSET");
// Read first line of reply, check if it's ok
string line = m_pSocket.ReadLine();
if(!line.StartsWith("+OK")){
throw new Exception("Server returned:" + line);
}
}
#endregion
#region properties Implementation
/// <summary>
/// Gets or sets if to log commands.
/// </summary>
public bool LogCommands
{
get{ return m_LogCmds; }
set{ m_LogCmds = value; }
}
#endregion
}
}
| |
using System;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Devices.I2c;
using Windows.Foundation.Metadata;
namespace ABElectronics_Win10IOT_Libraries
{
/// <summary>
/// Class for controlling the ADC Pi and ADC Pi Plus expansion boards from AB Electronics UK
/// </summary>
public class ADCPi : IDisposable
{
// create byte array and fill with initial values to define size
private Byte[] __adcreading = {0, 0, 0, 0};
private byte bitrate = 18; // current bit rate
// Flag: Has Dispose already been called?
bool disposed = false;
// Instantiate a SafeHandle instance.
System.Runtime.InteropServices.SafeHandle handle = new Microsoft.Win32.SafeHandles.SafeFileHandle(IntPtr.Zero, true);
// internal variables
private byte config1 = 0x9C; // PGAx1, 18 bit, continuous conversion, channel 1
private byte config2 = 0x9C; // PGAx1, 18 bit, continuous-shot conversion, channel 1
private byte conversionmode = 1; // Conversion Mode
private byte currentchannel1; // channel variable for ADC 1
private byte currentchannel2; // channel variable for ADC 2
private readonly ABE_Helpers helper = new ABE_Helpers();
private I2cDevice i2cbus1; // i2c bus for ADC chip 1
private I2cDevice i2cbus2; // i2c bus for ADC chip 2
private double lsb = 0.0000078125; // default LSB value for 18 bit
private double pga = 0.5; // current PGA setting
private bool signbit;
/// <summary>
/// Create an instance of a ADC Pi bus.
/// </summary>
/// <param name="i2caddress1">I2C address for the U1 (channels 1 - 4)</param>
/// <param name="i2caddress2">I2C address for the U2 (channels 5 - 8)</param>
public ADCPi(byte i2caddress1 = 0x68, byte i2caddress2 = 0x69)
{
Address1 = i2caddress1;
Address2 = i2caddress2;
IsConnected = false;
}
/// <summary>
/// I2C address for the U1 (channels 1 - 4).
/// </summary>
public byte Address1 { get; set; }
/// <summary>
/// I2C address for the U2 (channels 5 - 8).
/// </summary>
public byte Address2 { get; set; }
/// <summary>
/// Shows if there is a connection with the ADC Pi.
/// </summary>
public bool IsConnected { get; private set; }
/// <summary>
/// Open a connection with the ADC Pi.
/// </summary>
public async Task Connect()
{
if (IsConnected)
{
return; // Already connected
}
if (!ApiInformation.IsTypePresent("Windows.Devices.I2c.I2cDevice"))
{
return; // This system does not support this feature: can't connect
}
// Initialize both I2C busses
try
{
var aqs = I2cDevice.GetDeviceSelector(ABE_Helpers.I2C_CONTROLLER_NAME); // Find the selector string for the I2C bus controller
var dis = await DeviceInformation.FindAllAsync(aqs); // Find the I2C bus controller device with our selector string
if (dis.Count == 0)
{
return; // Controller not found
}
var settings1 = new I2cConnectionSettings(Address1) {BusSpeed = I2cBusSpeed.FastMode};
var settings2 = new I2cConnectionSettings(Address2) {BusSpeed = I2cBusSpeed.FastMode};
i2cbus1 = await I2cDevice.FromIdAsync(dis[0].Id, settings1); // Create an I2cDevice with our selected bus controller and I2C settings
i2cbus2 = await I2cDevice.FromIdAsync(dis[0].Id, settings2); // Create an I2cDevice with our selected bus controller and I2C settings
// check if the i2c busses are not null
if (i2cbus1 != null && i2cbus2 != null)
{
// set the initial bit rate and trigger a Connected event handler
IsConnected = true;
SetBitRate(bitrate);
// Fire the Connected event handler
Connected?.Invoke(this, EventArgs.Empty);
}
}
catch (Exception ex)
{
IsConnected = false;
throw new Exception("I2C Initialization Failed", ex);
}
}
/// <summary>
/// Event occurs when connection is made.
/// </summary>
public event EventHandler Connected;
/// <summary>
/// Private method for updating the configuration to the selected <paramref name="channel" />.
/// </summary>
/// <param name="channel">ADC channel, 1 - 8</param>
private void SetChannel(byte channel)
{
// Checks to see if the selected channel is already the current channel.
// If not then update the appropriate config to the new channel settings.
if (channel < 5 && channel != currentchannel1)
{
switch (channel)
{
case 1:
config1 = helper.UpdateByte(config1, 5, false);
config1 = helper.UpdateByte(config1, 6, false);
currentchannel1 = 1;
break;
case 2:
config1 = helper.UpdateByte(config1, 5, true);
config1 = helper.UpdateByte(config1, 6, false);
currentchannel1 = 2;
break;
case 3:
config1 = helper.UpdateByte(config1, 5, false);
config1 = helper.UpdateByte(config1, 6, true);
currentchannel1 = 3;
break;
case 4:
config1 = helper.UpdateByte(config1, 5, true);
config1 = helper.UpdateByte(config1, 6, true);
currentchannel1 = 4;
break;
}
}
else if (channel >= 5 && channel <= 8 && channel != currentchannel2)
{
switch (channel)
{
case 5:
config2 = helper.UpdateByte(config2, 5, false);
config2 = helper.UpdateByte(config2, 6, false);
currentchannel2 = 5;
break;
case 6:
config2 = helper.UpdateByte(config2, 5, true);
config2 = helper.UpdateByte(config2, 6, false);
currentchannel2 = 6;
break;
case 7:
config2 = helper.UpdateByte(config2, 5, false);
config2 = helper.UpdateByte(config2, 6, true);
currentchannel2 = 7;
break;
case 8:
config2 = helper.UpdateByte(config2, 5, true);
config2 = helper.UpdateByte(config2, 6, true);
currentchannel2 = 8;
break;
}
}
}
/// <summary>
/// Returns the voltage from the selected ADC <paramref name="channel" />.
/// </summary>
/// <param name="channel">1 to 8</param>
/// <returns>Read voltage</returns>
public double ReadVoltage(byte channel)
{
var raw = ReadRaw(channel); // get the raw value
if (signbit) // check to see if the sign bit is present, if it is then the voltage is negative and can be ignored.
{
return 0.0; // returned a negative voltage so return 0
}
var voltage = raw * (lsb / pga) * 2.471; // calculate the voltage and return it
return voltage;
}
/// <summary>
/// Reads the raw value from the selected ADC <paramref name="channel" />.
/// </summary>
/// <param name="channel">1 to 8</param>
/// <returns>raw integer value from ADC buffer</returns>
public int ReadRaw(byte channel)
{
CheckConnected();
// variables for storing the raw bytes from the ADC
byte h = 0;
byte l = 0;
byte m = 0;
byte s = 0;
byte config = 0;
var t = 0;
signbit = false;
// create a new instance of the I2C device
I2cDevice bus;
SetChannel(channel);
// get the configuration and i2c bus for the selected channel
if (channel < 5)
{
config = config1;
bus = i2cbus1;
}
else if (channel >= 5 && channel <= 8)
{
config = config2;
bus = i2cbus2;
}
else
{
throw new ArgumentOutOfRangeException(nameof(channel));
}
// if the conversion mode is set to one-shot update the ready bit to 1
if (conversionmode == 0)
{
config = helper.UpdateByte(config, 7, true);
helper.WriteI2CByte(bus, config, 0x00);
config = helper.UpdateByte(config, 7, false);
}
// keep reading the ADC data until the conversion result is ready
var timeout = 15000; // number of reads before a timeout occurs
var x = 0;
do
{
if (bitrate == 18)
{
__adcreading = helper.ReadI2CBlockData(bus, config, 4);
h = __adcreading[0];
m = __adcreading[1];
l = __adcreading[2];
s = __adcreading[3];
}
else
{
__adcreading = helper.ReadI2CBlockData(bus, config, 3);
h = __adcreading[0];
m = __adcreading[1];
s = __adcreading[2];
}
// check bit 7 of s to see if the conversion result is ready
if (!helper.CheckBit(s, 7))
{
break;
}
if (x > timeout)
{
// timeout occurred
throw new TimeoutException();
}
x++;
} while (true);
// extract the returned bytes and combine in the correct order
switch (bitrate)
{
case 18:
t = ((h & 3) << 16) | (m << 8) | l;
signbit = helper.CheckIntBit(t, 17);
if (signbit)
{
t = helper.UpdateInt(t, 17, false);
}
break;
case 16:
t = (h << 8) | m;
signbit = helper.CheckIntBit(t, 15);
if (signbit)
{
t = helper.UpdateInt(t, 15, false);
}
break;
case 14:
t = ((h & 63) << 8) | m;
signbit = helper.CheckIntBit(t, 13);
if (signbit)
{
t = helper.UpdateInt(t, 13, false);
}
break;
case 12:
t = ((h & 15) << 8) | m;
signbit = helper.CheckIntBit(t, 11);
if (signbit)
{
t = helper.UpdateInt(t, 11, false);
}
break;
default:
throw new ArgumentOutOfRangeException();
}
return t;
}
/// <summary>
/// Set the PGA (Programmable Gain Amplifier) <paramref name="gain"/>.
/// </summary>
/// <param name="gain">Set to 1, 2, 4 or 8</param>
public void SetPGA(byte gain)
{
CheckConnected();
// update the configs with the new gain settings
switch (gain)
{
case 1:
config1 = helper.UpdateByte(config1, 0, false);
config1 = helper.UpdateByte(config1, 1, false);
config2 = helper.UpdateByte(config2, 0, false);
config2 = helper.UpdateByte(config2, 1, false);
pga = 0.5;
break;
case 2:
config1 = helper.UpdateByte(config1, 0, true);
config1 = helper.UpdateByte(config1, 1, false);
config2 = helper.UpdateByte(config2, 0, true);
config2 = helper.UpdateByte(config2, 1, false);
pga = 1;
break;
case 4:
config1 = helper.UpdateByte(config1, 0, false);
config1 = helper.UpdateByte(config1, 1, true);
config2 = helper.UpdateByte(config2, 0, false);
config2 = helper.UpdateByte(config2, 1, true);
pga = 2;
break;
case 8:
config1 = helper.UpdateByte(config1, 0, true);
config1 = helper.UpdateByte(config1, 1, true);
config2 = helper.UpdateByte(config2, 0, true);
config2 = helper.UpdateByte(config2, 1, true);
pga = 4;
break;
default:
throw new InvalidOperationException("Invalid Bitrate");
}
helper.WriteI2CSingleByte(i2cbus1, config1);
helper.WriteI2CSingleByte(i2cbus2, config2);
}
/// <summary>
/// Set the sample resolution (rate).
/// </summary>
/// <param name="rate">
/// 12 = 12 bit(240SPS max),
/// 14 = 14 bit(60SPS max),
/// 16 = 16 bit(15SPS max),
/// 18 = 18 bit(3.75SPS max)
/// </param>
public void SetBitRate(byte rate)
{
CheckConnected();
switch (rate)
{
case 12:
config1 = helper.UpdateByte(config1, 2, false);
config1 = helper.UpdateByte(config1, 3, false);
config2 = helper.UpdateByte(config2, 2, false);
config2 = helper.UpdateByte(config2, 3, false);
bitrate = 12;
lsb = 0.0005;
break;
case 14:
config1 = helper.UpdateByte(config1, 2, true);
config1 = helper.UpdateByte(config1, 3, false);
config2 = helper.UpdateByte(config2, 2, true);
config2 = helper.UpdateByte(config2, 3, false);
bitrate = 14;
lsb = 0.000125;
break;
case 16:
config1 = helper.UpdateByte(config1, 2, false);
config1 = helper.UpdateByte(config1, 3, true);
config2 = helper.UpdateByte(config2, 2, false);
config2 = helper.UpdateByte(config2, 3, true);
bitrate = 16;
lsb = 0.00003125;
break;
case 18:
config1 = helper.UpdateByte(config1, 2, true);
config1 = helper.UpdateByte(config1, 3, true);
config2 = helper.UpdateByte(config2, 2, true);
config2 = helper.UpdateByte(config2, 3, true);
bitrate = 18;
lsb = 0.0000078125;
break;
default:
throw new ArgumentOutOfRangeException(nameof(rate));
}
helper.WriteI2CSingleByte(i2cbus1, config1);
helper.WriteI2CSingleByte(i2cbus2, config2);
}
/// <summary>
/// Set the conversion mode for ADC.
/// </summary>
/// <param name="mode">0 = One shot conversion mode, 1 = Continuous conversion mode</param>
private void SetConversionMode(bool mode)
{
if (mode)
{
config1 = helper.UpdateByte(config1, 4, true);
config2 = helper.UpdateByte(config2, 4, true);
conversionmode = 1;
}
else
{
config1 = helper.UpdateByte(config1, 4, false);
config2 = helper.UpdateByte(config2, 4, false);
conversionmode = 0;
}
}
private void CheckConnected()
{
if (!IsConnected)
{
throw new InvalidOperationException("Not connected. You must call .Connect() first.");
}
}
/// <summary>
/// Dispose of the resources
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Protected implementation of Dispose pattern
/// </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
handle.Dispose();
// Free any other managed objects here.
i2cbus1?.Dispose();
i2cbus1 = null;
i2cbus2?.Dispose();
i2cbus2 = null;
IsConnected = false;
}
// Free any unmanaged objects here.
//
disposed = true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml;
namespace Microsoft.Web.XmlTransform.Extended
{
internal class XmlElementContext : XmlNodeContext
{
#region private data members
private readonly XmlElementContext _parentContext;
private string _xpath;
private string _parentXPath;
private readonly XmlDocument _xmlTargetDoc;
private readonly IServiceProvider _serviceProvider;
private XmlNode _transformNodes;
private XmlNodeList _targetNodes;
private XmlNodeList _targetParents;
private XmlAttribute _transformAttribute;
private XmlAttribute _locatorAttribute;
private XmlNamespaceManager _namespaceManager;
#endregion
public XmlElementContext(XmlElementContext parent, XmlElement element, XmlDocument xmlTargetDoc, IServiceProvider serviceProvider)
: base(element)
{
_parentContext = parent;
_xmlTargetDoc = xmlTargetDoc;
_serviceProvider = serviceProvider;
}
public T GetService<T>() where T : class
{
if (_serviceProvider != null)
{
var service = _serviceProvider.GetService(typeof(T)) as T;
// now it is legal to return service that's null -- due to SetTokenizeAttributeStorage
//Debug.Assert(service != null, String.Format(CultureInfo.InvariantCulture, "Service provider didn't provide {0}", typeof(ServiceType).Name));
return service;
}
Debug.Fail("No ServiceProvider");
return null;
}
#region data accessors
public XmlElement Element
{
get
{
return Node as XmlElement;
}
}
public string XPath
{
get { return _xpath ?? (_xpath = ConstructXPath()); }
}
public string ParentXPath
{
get { return _parentXPath ?? (_parentXPath = ConstructParentXPath()); }
}
public Transform ConstructTransform(out string argumentString)
{
try
{
return CreateObjectFromAttribute<Transform>(out argumentString, out _transformAttribute);
}
catch (Exception ex)
{
throw WrapException(ex);
}
}
public int TransformLineNumber
{
get
{
var lineInfo = _transformAttribute as IXmlLineInfo;
return lineInfo != null ? lineInfo.LineNumber : LineNumber;
}
}
public int TransformLinePosition
{
get
{
var lineInfo = _transformAttribute as IXmlLineInfo;
return lineInfo != null ? lineInfo.LinePosition : LinePosition;
}
}
public XmlAttribute TransformAttribute
{
get
{
return _transformAttribute;
}
}
public XmlAttribute LocatorAttribute
{
get
{
return _locatorAttribute;
}
}
#endregion
#region XPath construction
private string ConstructXPath()
{
try
{
string argumentString;
string parentPath = _parentContext == null ? String.Empty : _parentContext.XPath;
Locator locator = CreateLocator(out argumentString);
return locator.ConstructPath(parentPath, this, argumentString);
}
catch (Exception ex)
{
throw WrapException(ex);
}
}
private string ConstructParentXPath()
{
try
{
string argumentString;
var parentPath = _parentContext == null ? String.Empty : _parentContext.XPath;
var locator = CreateLocator(out argumentString);
return locator.ConstructParentPath(parentPath, this, argumentString);
}
catch (Exception ex)
{
throw WrapException(ex);
}
}
private Locator CreateLocator(out string argumentString)
{
var locator = CreateObjectFromAttribute<Locator>(out argumentString, out _locatorAttribute);
if (locator != null) return locator;
argumentString = null;
//avoid using singleton of "DefaultLocator.Instance", so unit tests can run parallel
locator = new DefaultLocator();
return locator;
}
#endregion
#region Context information
internal XmlNode TransformNode
{
get { return _transformNodes ?? (_transformNodes = CreateCloneInTargetDocument(Element)); }
}
internal XmlNodeList TargetNodes
{
get { return _targetNodes ?? (_targetNodes = GetTargetNodes(XPath)); }
}
internal XmlNodeList TargetParents
{
get
{
if (_targetParents == null && _parentContext != null)
{
_targetParents = GetTargetNodes(ParentXPath);
}
return _targetParents;
}
}
#endregion
#region Node helpers
private XmlDocument TargetDocument
{
get
{
return _xmlTargetDoc;
}
}
private XmlNode CreateCloneInTargetDocument(XmlNode sourceNode)
{
var infoDocument = TargetDocument as XmlFileInfoDocument;
XmlNode clonedNode;
if (infoDocument != null)
{
clonedNode = infoDocument.CloneNodeFromOtherDocument(sourceNode);
}
else
{
XmlReader reader = new XmlTextReader(new StringReader(sourceNode.OuterXml));
clonedNode = TargetDocument.ReadNode(reader);
}
ScrubTransformAttributesAndNamespaces(clonedNode);
return clonedNode;
}
private void ScrubTransformAttributesAndNamespaces(XmlNode node)
{
if (node.Attributes != null)
{
var attributesToRemove = new List<XmlAttribute>();
foreach (XmlAttribute attribute in node.Attributes)
{
if (attribute.NamespaceURI == XmlTransformation.TransformNamespace)
{
attributesToRemove.Add(attribute);
}
else if (attribute.Prefix != null && (attribute.Prefix.Equals("xmlns") || attribute.Name.Equals("xmlns")))
{
attributesToRemove.Add(attribute);
}
else
{
attribute.Prefix = null;
}
}
foreach (XmlAttribute attributeToRemove in attributesToRemove)
{
node.Attributes.Remove(attributeToRemove);
}
}
// Do the same recursively for child nodes
foreach (XmlNode childNode in node.ChildNodes)
{
ScrubTransformAttributesAndNamespaces(childNode);
}
}
private XmlNodeList GetTargetNodes(string xpath)
{
return TargetDocument.SelectNodes(xpath, GetNamespaceManager());
}
private Exception WrapException(Exception ex)
{
return XmlNodeException.Wrap(ex, Element);
}
private Exception WrapException(Exception ex, XmlNode node)
{
return XmlNodeException.Wrap(ex, node);
}
private XmlNamespaceManager GetNamespaceManager()
{
if (_namespaceManager == null)
{
XmlNodeList localNamespaces = Element.SelectNodes("namespace::*");
if (localNamespaces != null && localNamespaces.Count > 0)
{
if (Element.OwnerDocument != null)
_namespaceManager = new XmlNamespaceManager(Element.OwnerDocument.NameTable);
foreach (XmlAttribute nsAttribute in localNamespaces)
{
var index = nsAttribute.Name.IndexOf(':');
var prefix = index >= 0 ? nsAttribute.Name.Substring(index + 1) : "_defaultNamespace";
if (_namespaceManager != null) _namespaceManager.AddNamespace(prefix, nsAttribute.Value);
}
}
else
{
_namespaceManager = new XmlNamespaceManager(GetParentNameTable());
}
}
return _namespaceManager;
}
private XmlNameTable GetParentNameTable()
{
return _parentContext == null ? Element.OwnerDocument.NameTable : _parentContext.GetNamespaceManager().NameTable;
}
#endregion
#region Named object creation
private static Regex _nameAndArgumentsRegex;
private Regex NameAndArgumentsRegex
{
get { return _nameAndArgumentsRegex ?? (_nameAndArgumentsRegex = new Regex(@"\A\s*(?<name>\w+)(\s*\((?<arguments>.*)\))?\s*\Z", RegexOptions.Compiled | RegexOptions.Singleline)); }
}
private string ParseNameAndArguments(string name, out string arguments)
{
arguments = null;
var match = NameAndArgumentsRegex.Match(name);
if (match.Success)
{
if (!match.Groups["arguments"].Success) return match.Groups["name"].Captures[0].Value;
var argumentCaptures = match.Groups["arguments"].Captures;
if (argumentCaptures.Count == 1 && !String.IsNullOrEmpty(argumentCaptures[0].Value))
{
arguments = argumentCaptures[0].Value;
}
return match.Groups["name"].Captures[0].Value;
}
throw new XmlTransformationException(SR.XMLTRANSFORMATION_BadAttributeValue);
}
private TObjectType CreateObjectFromAttribute<TObjectType>(out string argumentString, out XmlAttribute objectAttribute) where TObjectType : class
{
objectAttribute = Element.Attributes.GetNamedItem(typeof(TObjectType).Name, XmlTransformation.TransformNamespace) as XmlAttribute;
try
{
if (objectAttribute != null)
{
var typeName = ParseNameAndArguments(objectAttribute.Value, out argumentString);
if (!String.IsNullOrEmpty(typeName))
{
var factory = GetService<NamedTypeFactory>();
return factory.Construct<TObjectType>(typeName);
}
}
}
catch (Exception ex)
{
throw WrapException(ex, objectAttribute);
}
argumentString = null;
return null;
}
#endregion
#region Error reporting helpers
internal bool HasTargetNode(out XmlElementContext failedContext, out bool existedInOriginal)
{
failedContext = null;
existedInOriginal = false;
if (TargetNodes.Count == 0)
{
failedContext = this;
while (failedContext._parentContext != null &&
failedContext._parentContext.TargetNodes.Count == 0)
{
failedContext = failedContext._parentContext;
}
existedInOriginal = ExistedInOriginal(failedContext.XPath);
return false;
}
return true;
}
internal bool HasTargetParent(out XmlElementContext failedContext, out bool existedInOriginal)
{
failedContext = null;
existedInOriginal = false;
if (TargetParents.Count == 0)
{
failedContext = this;
while (failedContext._parentContext != null &&
!String.IsNullOrEmpty(failedContext._parentContext.ParentXPath) &&
failedContext._parentContext.TargetParents.Count == 0)
{
failedContext = failedContext._parentContext;
}
existedInOriginal = ExistedInOriginal(failedContext.XPath);
return false;
}
return true;
}
private bool ExistedInOriginal(string xpath)
{
var service = GetService<IXmlOriginalDocumentService>();
if (service == null) return false;
var nodeList = service.SelectNodes(xpath, GetNamespaceManager());
return nodeList != null && nodeList.Count > 0;
}
#endregion
}
}
| |
#define STEAMNETWORKINGSOCKETS_ENABLE_SDR
// This file is provided under The MIT License as part of Steamworks.NET.
// Copyright (c) 2013-2019 Riley Labrecque
// Please see the included LICENSE.txt for additional information.
// This file is automatically generated.
// Changes to this file will be reverted when you update Steamworks.NET
#if UNITY_ANDROID || UNITY_IOS || UNITY_TIZEN || UNITY_TVOS || UNITY_WEBGL || UNITY_WSA || UNITY_PS4 || UNITY_WII || UNITY_XBOXONE || UNITY_SWITCH
#define DISABLESTEAMWORKS
#endif
#if !DISABLESTEAMWORKS
using System.Runtime.InteropServices;
using IntPtr = System.IntPtr;
namespace Steamworks {
public static class SteamGameServerNetworkingUtils {
/// <summary>
/// <para> Efficient message sending</para>
/// <para>/ Allocate and initialize a message object. Usually the reason</para>
/// <para>/ you call this is to pass it to ISteamNetworkingSockets::SendMessages.</para>
/// <para>/ The returned object will have all of the relevant fields cleared to zero.</para>
/// <para>/</para>
/// <para>/ Optionally you can also request that this system allocate space to</para>
/// <para>/ hold the payload itself. If cbAllocateBuffer is nonzero, the system</para>
/// <para>/ will allocate memory to hold a payload of at least cbAllocateBuffer bytes.</para>
/// <para>/ m_pData will point to the allocated buffer, m_cbSize will be set to the</para>
/// <para>/ size, and m_pfnFreeData will be set to the proper function to free up</para>
/// <para>/ the buffer.</para>
/// <para>/</para>
/// <para>/ If cbAllocateBuffer=0, then no buffer is allocated. m_pData will be NULL,</para>
/// <para>/ m_cbSize will be zero, and m_pfnFreeData will be NULL. You will need to</para>
/// <para>/ set each of these.</para>
/// </summary>
public static IntPtr AllocateMessage(int cbAllocateBuffer) {
InteropHelp.TestIfAvailableGameServer();
return NativeMethods.ISteamNetworkingUtils_AllocateMessage(CSteamGameServerAPIContext.GetSteamNetworkingUtils(), cbAllocateBuffer);
}
#if STEAMNETWORKINGSOCKETS_ENABLE_SDR
/// <summary>
/// <para>/ Fetch current status of the relay network.</para>
/// <para>/</para>
/// <para>/ SteamRelayNetworkStatus_t is also a callback. It will be triggered on</para>
/// <para>/ both the user and gameserver interfaces any time the status changes, or</para>
/// <para>/ ping measurement starts or stops.</para>
/// <para>/</para>
/// <para>/ SteamRelayNetworkStatus_t::m_eAvail is returned. If you want</para>
/// <para>/ more details, you can pass a non-NULL value.</para>
/// </summary>
public static ESteamNetworkingAvailability GetRelayNetworkStatus(out SteamRelayNetworkStatus_t pDetails) {
InteropHelp.TestIfAvailableGameServer();
return NativeMethods.ISteamNetworkingUtils_GetRelayNetworkStatus(CSteamGameServerAPIContext.GetSteamNetworkingUtils(), out pDetails);
}
/// <summary>
/// <para> "Ping location" functions</para>
/// <para> We use the ping times to the valve relays deployed worldwide to</para>
/// <para> generate a "marker" that describes the location of an Internet host.</para>
/// <para> Given two such markers, we can estimate the network latency between</para>
/// <para> two hosts, without sending any packets. The estimate is based on the</para>
/// <para> optimal route that is found through the Valve network. If you are</para>
/// <para> using the Valve network to carry the traffic, then this is precisely</para>
/// <para> the ping you want. If you are not, then the ping time will probably</para>
/// <para> still be a reasonable estimate.</para>
/// <para> This is extremely useful to select peers for matchmaking!</para>
/// <para> The markers can also be converted to a string, so they can be transmitted.</para>
/// <para> We have a separate library you can use on your app's matchmaking/coordinating</para>
/// <para> server to manipulate these objects. (See steamdatagram_gamecoordinator.h)</para>
/// <para>/ Return location info for the current host. Returns the approximate</para>
/// <para>/ age of the data, in seconds, or -1 if no data is available.</para>
/// <para>/</para>
/// <para>/ It takes a few seconds to initialize access to the relay network. If</para>
/// <para>/ you call this very soon after calling InitRelayNetworkAccess,</para>
/// <para>/ the data may not be available yet.</para>
/// <para>/</para>
/// <para>/ This always return the most up-to-date information we have available</para>
/// <para>/ right now, even if we are in the middle of re-calculating ping times.</para>
/// </summary>
public static float GetLocalPingLocation(out SteamNetworkPingLocation_t result) {
InteropHelp.TestIfAvailableGameServer();
return NativeMethods.ISteamNetworkingUtils_GetLocalPingLocation(CSteamGameServerAPIContext.GetSteamNetworkingUtils(), out result);
}
/// <summary>
/// <para>/ Estimate the round-trip latency between two arbitrary locations, in</para>
/// <para>/ milliseconds. This is a conservative estimate, based on routing through</para>
/// <para>/ the relay network. For most basic relayed connections, this ping time</para>
/// <para>/ will be pretty accurate, since it will be based on the route likely to</para>
/// <para>/ be actually used.</para>
/// <para>/</para>
/// <para>/ If a direct IP route is used (perhaps via NAT traversal), then the route</para>
/// <para>/ will be different, and the ping time might be better. Or it might actually</para>
/// <para>/ be a bit worse! Standard IP routing is frequently suboptimal!</para>
/// <para>/</para>
/// <para>/ But even in this case, the estimate obtained using this method is a</para>
/// <para>/ reasonable upper bound on the ping time. (Also it has the advantage</para>
/// <para>/ of returning immediately and not sending any packets.)</para>
/// <para>/</para>
/// <para>/ In a few cases we might not able to estimate the route. In this case</para>
/// <para>/ a negative value is returned. k_nSteamNetworkingPing_Failed means</para>
/// <para>/ the reason was because of some networking difficulty. (Failure to</para>
/// <para>/ ping, etc) k_nSteamNetworkingPing_Unknown is returned if we cannot</para>
/// <para>/ currently answer the question for some other reason.</para>
/// <para>/</para>
/// <para>/ Do you need to be able to do this from a backend/matchmaking server?</para>
/// <para>/ You are looking for the "ticketgen" library.</para>
/// </summary>
public static int EstimatePingTimeBetweenTwoLocations(ref SteamNetworkPingLocation_t location1, ref SteamNetworkPingLocation_t location2) {
InteropHelp.TestIfAvailableGameServer();
return NativeMethods.ISteamNetworkingUtils_EstimatePingTimeBetweenTwoLocations(CSteamGameServerAPIContext.GetSteamNetworkingUtils(), ref location1, ref location2);
}
/// <summary>
/// <para>/ Same as EstimatePingTime, but assumes that one location is the local host.</para>
/// <para>/ This is a bit faster, especially if you need to calculate a bunch of</para>
/// <para>/ these in a loop to find the fastest one.</para>
/// <para>/</para>
/// <para>/ In rare cases this might return a slightly different estimate than combining</para>
/// <para>/ GetLocalPingLocation with EstimatePingTimeBetweenTwoLocations. That's because</para>
/// <para>/ this function uses a slightly more complete set of information about what</para>
/// <para>/ route would be taken.</para>
/// </summary>
public static int EstimatePingTimeFromLocalHost(ref SteamNetworkPingLocation_t remoteLocation) {
InteropHelp.TestIfAvailableGameServer();
return NativeMethods.ISteamNetworkingUtils_EstimatePingTimeFromLocalHost(CSteamGameServerAPIContext.GetSteamNetworkingUtils(), ref remoteLocation);
}
/// <summary>
/// <para>/ Convert a ping location into a text format suitable for sending over the wire.</para>
/// <para>/ The format is a compact and human readable. However, it is subject to change</para>
/// <para>/ so please do not parse it yourself. Your buffer must be at least</para>
/// <para>/ k_cchMaxSteamNetworkingPingLocationString bytes.</para>
/// </summary>
public static void ConvertPingLocationToString(ref SteamNetworkPingLocation_t location, out string pszBuf, int cchBufSize) {
InteropHelp.TestIfAvailableGameServer();
IntPtr pszBuf2 = Marshal.AllocHGlobal(cchBufSize);
NativeMethods.ISteamNetworkingUtils_ConvertPingLocationToString(CSteamGameServerAPIContext.GetSteamNetworkingUtils(), ref location, pszBuf2, cchBufSize);
pszBuf = InteropHelp.PtrToStringUTF8(pszBuf2);
Marshal.FreeHGlobal(pszBuf2);
}
/// <summary>
/// <para>/ Parse back SteamNetworkPingLocation_t string. Returns false if we couldn't understand</para>
/// <para>/ the string.</para>
/// </summary>
public static bool ParsePingLocationString(string pszString, out SteamNetworkPingLocation_t result) {
InteropHelp.TestIfAvailableGameServer();
using (var pszString2 = new InteropHelp.UTF8StringHandle(pszString)) {
return NativeMethods.ISteamNetworkingUtils_ParsePingLocationString(CSteamGameServerAPIContext.GetSteamNetworkingUtils(), pszString2, out result);
}
}
/// <summary>
/// <para>/ Check if the ping data of sufficient recency is available, and if</para>
/// <para>/ it's too old, start refreshing it.</para>
/// <para>/</para>
/// <para>/ Please only call this function when you *really* do need to force an</para>
/// <para>/ immediate refresh of the data. (For example, in response to a specific</para>
/// <para>/ user input to refresh this information.) Don't call it "just in case",</para>
/// <para>/ before every connection, etc. That will cause extra traffic to be sent</para>
/// <para>/ for no benefit. The library will automatically refresh the information</para>
/// <para>/ as needed.</para>
/// <para>/</para>
/// <para>/ Returns true if sufficiently recent data is already available.</para>
/// <para>/</para>
/// <para>/ Returns false if sufficiently recent data is not available. In this</para>
/// <para>/ case, ping measurement is initiated, if it is not already active.</para>
/// <para>/ (You cannot restart a measurement already in progress.)</para>
/// <para>/</para>
/// <para>/ You can use GetRelayNetworkStatus or listen for SteamRelayNetworkStatus_t</para>
/// <para>/ to know when ping measurement completes.</para>
/// </summary>
public static bool CheckPingDataUpToDate(float flMaxAgeSeconds) {
InteropHelp.TestIfAvailableGameServer();
return NativeMethods.ISteamNetworkingUtils_CheckPingDataUpToDate(CSteamGameServerAPIContext.GetSteamNetworkingUtils(), flMaxAgeSeconds);
}
/// <summary>
/// <para> List of Valve data centers, and ping times to them. This might</para>
/// <para> be useful to you if you are use our hosting, or just need to measure</para>
/// <para> latency to a cloud data center where we are running relays.</para>
/// <para>/ Fetch ping time of best available relayed route from this host to</para>
/// <para>/ the specified data center.</para>
/// </summary>
public static int GetPingToDataCenter(SteamNetworkingPOPID popID, out SteamNetworkingPOPID pViaRelayPoP) {
InteropHelp.TestIfAvailableGameServer();
return NativeMethods.ISteamNetworkingUtils_GetPingToDataCenter(CSteamGameServerAPIContext.GetSteamNetworkingUtils(), popID, out pViaRelayPoP);
}
/// <summary>
/// <para>/ Get *direct* ping time to the relays at the data center.</para>
/// </summary>
public static int GetDirectPingToPOP(SteamNetworkingPOPID popID) {
InteropHelp.TestIfAvailableGameServer();
return NativeMethods.ISteamNetworkingUtils_GetDirectPingToPOP(CSteamGameServerAPIContext.GetSteamNetworkingUtils(), popID);
}
/// <summary>
/// <para>/ Get number of network points of presence in the config</para>
/// </summary>
public static int GetPOPCount() {
InteropHelp.TestIfAvailableGameServer();
return NativeMethods.ISteamNetworkingUtils_GetPOPCount(CSteamGameServerAPIContext.GetSteamNetworkingUtils());
}
/// <summary>
/// <para>/ Get list of all POP IDs. Returns the number of entries that were filled into</para>
/// <para>/ your list.</para>
/// </summary>
public static int GetPOPList(out SteamNetworkingPOPID list, int nListSz) {
InteropHelp.TestIfAvailableGameServer();
return NativeMethods.ISteamNetworkingUtils_GetPOPList(CSteamGameServerAPIContext.GetSteamNetworkingUtils(), out list, nListSz);
}
#endif
/// <summary>
/// <para> #ifdef STEAMNETWORKINGSOCKETS_ENABLE_SDR</para>
/// <para> Misc</para>
/// <para>/ Fetch current timestamp. This timer has the following properties:</para>
/// <para>/</para>
/// <para>/ - Monotonicity is guaranteed.</para>
/// <para>/ - The initial value will be at least 24*3600*30*1e6, i.e. about</para>
/// <para>/ 30 days worth of microseconds. In this way, the timestamp value of</para>
/// <para>/ 0 will always be at least "30 days ago". Also, negative numbers</para>
/// <para>/ will never be returned.</para>
/// <para>/ - Wraparound / overflow is not a practical concern.</para>
/// <para>/</para>
/// <para>/ If you are running under the debugger and stop the process, the clock</para>
/// <para>/ might not advance the full wall clock time that has elapsed between</para>
/// <para>/ calls. If the process is not blocked from normal operation, the</para>
/// <para>/ timestamp values will track wall clock time, even if you don't call</para>
/// <para>/ the function frequently.</para>
/// <para>/</para>
/// <para>/ The value is only meaningful for this run of the process. Don't compare</para>
/// <para>/ it to values obtained on another computer, or other runs of the same process.</para>
/// </summary>
public static SteamNetworkingMicroseconds GetLocalTimestamp() {
InteropHelp.TestIfAvailableGameServer();
return (SteamNetworkingMicroseconds)NativeMethods.ISteamNetworkingUtils_GetLocalTimestamp(CSteamGameServerAPIContext.GetSteamNetworkingUtils());
}
/// <summary>
/// <para>/ Set a function to receive network-related information that is useful for debugging.</para>
/// <para>/ This can be very useful during development, but it can also be useful for troubleshooting</para>
/// <para>/ problems with tech savvy end users. If you have a console or other log that customers</para>
/// <para>/ can examine, these log messages can often be helpful to troubleshoot network issues.</para>
/// <para>/ (Especially any warning/error messages.)</para>
/// <para>/</para>
/// <para>/ The detail level indicates what message to invoke your callback on. Lower numeric</para>
/// <para>/ value means more important, and the value you pass is the lowest priority (highest</para>
/// <para>/ numeric value) you wish to receive callbacks for.</para>
/// <para>/</para>
/// <para>/ Except when debugging, you should only use k_ESteamNetworkingSocketsDebugOutputType_Msg</para>
/// <para>/ or k_ESteamNetworkingSocketsDebugOutputType_Warning. For best performance, do NOT</para>
/// <para>/ request a high detail level and then filter out messages in your callback. This incurs</para>
/// <para>/ all of the expense of formatting the messages, which are then discarded. Setting a high</para>
/// <para>/ priority value (low numeric value) here allows the library to avoid doing this work.</para>
/// <para>/</para>
/// <para>/ IMPORTANT: This may be called from a service thread, while we own a mutex, etc.</para>
/// <para>/ Your output function must be threadsafe and fast! Do not make any other</para>
/// <para>/ Steamworks calls from within the handler.</para>
/// </summary>
public static void SetDebugOutputFunction(ESteamNetworkingSocketsDebugOutputType eDetailLevel, FSteamNetworkingSocketsDebugOutput pfnFunc) {
InteropHelp.TestIfAvailableGameServer();
NativeMethods.ISteamNetworkingUtils_SetDebugOutputFunction(CSteamGameServerAPIContext.GetSteamNetworkingUtils(), eDetailLevel, pfnFunc);
}
/// <summary>
/// <para> Set and get configuration values, see ESteamNetworkingConfigValue for individual descriptions.</para>
/// <para> Shortcuts for common cases. (Implemented as inline functions below)</para>
/// <para>/ Set a configuration value.</para>
/// <para>/ - eValue: which value is being set</para>
/// <para>/ - eScope: Onto what type of object are you applying the setting?</para>
/// <para>/ - scopeArg: Which object you want to change? (Ignored for global scope). E.g. connection handle, listen socket handle, interface pointer, etc.</para>
/// <para>/ - eDataType: What type of data is in the buffer at pValue? This must match the type of the variable exactly!</para>
/// <para>/ - pArg: Value to set it to. You can pass NULL to remove a non-global setting at this scope,</para>
/// <para>/ causing the value for that object to use global defaults. Or at global scope, passing NULL</para>
/// <para>/ will reset any custom value and restore it to the system default.</para>
/// <para>/ NOTE: When setting callback functions, do not pass the function pointer directly.</para>
/// <para>/ Your argument should be a pointer to a function pointer.</para>
/// </summary>
public static bool SetConfigValue(ESteamNetworkingConfigValue eValue, ESteamNetworkingConfigScope eScopeType, IntPtr scopeObj, ESteamNetworkingConfigDataType eDataType, IntPtr pArg) {
InteropHelp.TestIfAvailableGameServer();
return NativeMethods.ISteamNetworkingUtils_SetConfigValue(CSteamGameServerAPIContext.GetSteamNetworkingUtils(), eValue, eScopeType, scopeObj, eDataType, pArg);
}
/// <summary>
/// <para>/ Set a configuration value, using a struct to pass the value.</para>
/// <para>/ (This is just a convenience shortcut; see below for the implementation and</para>
/// <para>/ a little insight into how SteamNetworkingConfigValue_t is used when</para>
/// <para>/ setting config options during listen socket and connection creation.)</para>
/// <para>/ Get a configuration value.</para>
/// <para>/ - eValue: which value to fetch</para>
/// <para>/ - eScopeType: query setting on what type of object</para>
/// <para>/ - eScopeArg: the object to query the setting for</para>
/// <para>/ - pOutDataType: If non-NULL, the data type of the value is returned.</para>
/// <para>/ - pResult: Where to put the result. Pass NULL to query the required buffer size. (k_ESteamNetworkingGetConfigValue_BufferTooSmall will be returned.)</para>
/// <para>/ - cbResult: IN: the size of your buffer. OUT: the number of bytes filled in or required.</para>
/// </summary>
public static ESteamNetworkingGetConfigValueResult GetConfigValue(ESteamNetworkingConfigValue eValue, ESteamNetworkingConfigScope eScopeType, IntPtr scopeObj, out ESteamNetworkingConfigDataType pOutDataType, IntPtr pResult, out ulong cbResult) {
InteropHelp.TestIfAvailableGameServer();
return NativeMethods.ISteamNetworkingUtils_GetConfigValue(CSteamGameServerAPIContext.GetSteamNetworkingUtils(), eValue, eScopeType, scopeObj, out pOutDataType, pResult, out cbResult);
}
/// <summary>
/// <para>/ Returns info about a configuration value. Returns false if the value does not exist.</para>
/// <para>/ pOutNextValue can be used to iterate through all of the known configuration values.</para>
/// <para>/ (Use GetFirstConfigValue() to begin the iteration, will be k_ESteamNetworkingConfig_Invalid on the last value)</para>
/// <para>/ Any of the output parameters can be NULL if you do not need that information.</para>
/// <para>/</para>
/// <para>/ See k_ESteamNetworkingConfig_EnumerateDevVars for some more info about "dev" variables,</para>
/// <para>/ which are usually excluded from the set of variables enumerated using this function.</para>
/// </summary>
public static bool GetConfigValueInfo(ESteamNetworkingConfigValue eValue, IntPtr pOutName, out ESteamNetworkingConfigDataType pOutDataType, out ESteamNetworkingConfigScope pOutScope, out ESteamNetworkingConfigValue pOutNextValue) {
InteropHelp.TestIfAvailableGameServer();
return NativeMethods.ISteamNetworkingUtils_GetConfigValueInfo(CSteamGameServerAPIContext.GetSteamNetworkingUtils(), eValue, pOutName, out pOutDataType, out pOutScope, out pOutNextValue);
}
/// <summary>
/// <para>/ Return the lowest numbered configuration value available in the current environment.</para>
/// </summary>
public static ESteamNetworkingConfigValue GetFirstConfigValue() {
InteropHelp.TestIfAvailableGameServer();
return NativeMethods.ISteamNetworkingUtils_GetFirstConfigValue(CSteamGameServerAPIContext.GetSteamNetworkingUtils());
}
/// <summary>
/// <para> String conversions. You'll usually access these using the respective</para>
/// <para> inline methods.</para>
/// </summary>
public static void SteamNetworkingIPAddr_ToString(ref SteamNetworkingIPAddr addr, out string buf, uint cbBuf, bool bWithPort) {
InteropHelp.TestIfAvailableGameServer();
IntPtr buf2 = Marshal.AllocHGlobal((int)cbBuf);
NativeMethods.ISteamNetworkingUtils_SteamNetworkingIPAddr_ToString(CSteamGameServerAPIContext.GetSteamNetworkingUtils(), ref addr, buf2, cbBuf, bWithPort);
buf = InteropHelp.PtrToStringUTF8(buf2);
Marshal.FreeHGlobal(buf2);
}
public static bool SteamNetworkingIPAddr_ParseString(out SteamNetworkingIPAddr pAddr, string pszStr) {
InteropHelp.TestIfAvailableGameServer();
using (var pszStr2 = new InteropHelp.UTF8StringHandle(pszStr)) {
return NativeMethods.ISteamNetworkingUtils_SteamNetworkingIPAddr_ParseString(CSteamGameServerAPIContext.GetSteamNetworkingUtils(), out pAddr, pszStr2);
}
}
public static void SteamNetworkingIdentity_ToString(ref SteamNetworkingIdentity identity, out string buf, uint cbBuf) {
InteropHelp.TestIfAvailableGameServer();
IntPtr buf2 = Marshal.AllocHGlobal((int)cbBuf);
NativeMethods.ISteamNetworkingUtils_SteamNetworkingIdentity_ToString(CSteamGameServerAPIContext.GetSteamNetworkingUtils(), ref identity, buf2, cbBuf);
buf = InteropHelp.PtrToStringUTF8(buf2);
Marshal.FreeHGlobal(buf2);
}
public static bool SteamNetworkingIdentity_ParseString(out SteamNetworkingIdentity pIdentity, string pszStr) {
InteropHelp.TestIfAvailableGameServer();
using (var pszStr2 = new InteropHelp.UTF8StringHandle(pszStr)) {
return NativeMethods.ISteamNetworkingUtils_SteamNetworkingIdentity_ParseString(CSteamGameServerAPIContext.GetSteamNetworkingUtils(), out pIdentity, pszStr2);
}
}
}
}
#endif // !DISABLESTEAMWORKS
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.Diagnostics.Contracts;
namespace System.Windows
{
// Summary:
// Describes the width, height, and location of a rectangle.
// [Serializable]
// [ValueSerializer(typeof(RectValueSerializer))]
// [TypeConverter(typeof(RectConverter))]
public struct Rect // : IFormattable
{
//
// Summary:
// Initializes a new instance of the System.Windows.Rect structure that is of
// the specified size and is located at (0,0).
//
// Parameters:
// size:
// A System.Windows.Size structure that specifies the width and height of the
// rectangle.
//public Rect(Size size);
//
// Summary:
// Initializes a new instance of the System.Windows.Rect structure that is exactly
// large enough to contain the two specified points.
//
// Parameters:
// point1:
// The first point that the new rectangle must contain.
//
// point2:
// The second point that the new rectangle must contain.
//public Rect(Point point1, Point point2);
//
// Summary:
// Initializes a new instance of the System.Windows.Rect structure that has
// the specified top-left corner location and the specified width and height.
//
// Parameters:
// location:
// A point that specifies the location of the top-left corner of the rectangle.
//
// size:
// A System.Windows.Size structure that specifies the width and height of the
// rectangle.
//public Rect(Point location, Size size);
//
// Summary:
// Initializes a new instance of the System.Windows.Rect structure that is exactly
// large enough to contain the specified point and the sum of the specified
// point and the specified vector.
//
// Parameters:
// point:
// The first point the rectangle must contain.
//
// vector:
// The amount to offset the specified point. The resulting rectangle will be
// exactly large enough to contain both points.
//public Rect(Point point, Vector vector);
//
// Summary:
// Initializes a new instance of the System.Windows.Rect structure that has
// the specified x-coordinate, y-coordinate, width, and height.
//
// Parameters:
// x:
// The x-coordinate of the top-left corner of the rectangle.
//
// y:
// The y-coordinate of the top-left corner of the rectangle.
//
// width:
// The width of the rectangle.
//
// height:
// The height of the rectangle.
public Rect(double x, double y, double width, double height)
{
Contract.Requires((width >= 0.0) || double.IsNaN(width) || double.IsPositiveInfinity(width));
Contract.Requires((height >= 0.0) || double.IsNaN(height) || double.IsPositiveInfinity(height));
Contract.Ensures(Contract.ValueAtReturn(out this).X == x);
Contract.Ensures(Contract.ValueAtReturn(out this).Y == y);
Contract.Ensures(Contract.ValueAtReturn(out this).Width == width);
Contract.Ensures(Contract.ValueAtReturn(out this).Height == height);
}
// Summary:
// Compares two rectangles for inequality.
//
// Parameters:
// rect1:
// The first rectangle to compare.
//
// rect2:
// The second rectangle to compare.
//
// Returns:
// true if the rectangles do not have the same System.Windows.Rect.Location
// and System.Windows.Rect.Size values; otherwise, false.
[Pure]
public static bool operator !=(Rect rect1, Rect rect2)
{
Contract.Ensures(Contract.Result<bool>() ==
(rect1.X != rect2.X) || (rect1.Y != rect2.Y) != (rect1.Width != rect2.Width) != (rect1.Height != rect2.Height));
return default(bool);
}
//
// Summary:
// Compares two rectangles for exact equality.
//
// Parameters:
// rect1:
// The first rectangle to compare.
//
// rect2:
// The second rectangle to compare.
//
// Returns:
// true if the rectangles have the same System.Windows.Rect.Location and System.Windows.Rect.Size
// values; otherwise, false.
[Pure]
public static bool operator ==(Rect rect1, Rect rect2)
{
Contract.Ensures(Contract.Result<bool>() ==
(rect1.X == rect2.X) && (rect1.Y == rect2.Y) && (rect1.Width == rect2.Width) && (rect1.Height == rect2.Height));
return default(bool);
}
// Summary:
// Gets the y-axis value of the bottom of the rectangle.
//
// Returns:
// The y-axis value of the bottom of the rectangle. If the rectangle is empty,
// the value is System.Double.NegativeInfinity .
public double Bottom
{
get
{
Contract.Ensures(Contract.Result<double>() == (this.IsEmpty? Double.NegativeInfinity : this.Y + this.Height) || Double.IsNaN(Y) || Double.IsNaN(Height));
return default(double);
}
}
//
// Summary:
// Gets the position of the bottom-left corner of the rectangle
//
// Returns:
// The position of the bottom-left corner of the rectangle.
//public Point BottomLeft { get; }
//
// Summary:
// Gets the position of the bottom-right corner of the rectangle.
//
// Returns:
// The position of the bottom-right corner of the rectangle.
//public Point BottomRight { get; }
//
// Summary:
// Gets a special value that represents a rectangle with no position or area.
//
// Returns:
// The empty rectangle, which has System.Windows.Rect.X and System.Windows.Rect.Y
// property values of System.Double.PositiveInfinity, and has System.Windows.Rect.Width
// and System.Windows.Rect.Height property values of System.Double.NegativeInfinity.
public static Rect Empty
{
get
{
Contract.Ensures(Contract.Result<Rect>().Y == Double.PositiveInfinity);
Contract.Ensures(Contract.Result<Rect>().X == Double.PositiveInfinity);
Contract.Ensures(Contract.Result<Rect>().Height == Double.NegativeInfinity);
Contract.Ensures(Contract.Result<Rect>().Width == Double.NegativeInfinity);
return default(Rect);
}
}
//
// Summary:
// Gets or sets the height of the rectangle.
//
// Returns:
// A positive number that represents the height of the rectangle. The default
// is 0.
public double Height
{
get
{
Contract.Ensures(this.IsEmpty || Contract.Result<double>() >= 0.0 || Double.IsNaN(Contract.Result<double>()) || Double.IsPositiveInfinity(Contract.Result<double>()));
return default(double);
}
set
{
// Contract.Requires(!this.IsEmpty); => Is true, but impossible to proof with acceptable effort.
Contract.Requires((value >= 0.0) || Double.IsNaN(value) || Double.IsPositiveInfinity(value));
Contract.Ensures(this.Height == value);
}
}
//
// Summary:
// Gets a value that indicates whether the rectangle is the System.Windows.Rect.Empty
// rectangle.
//
// Returns:
// true if the rectangle is the System.Windows.Rect.Empty rectangle; otherwise,
// false.
public bool IsEmpty
{
get
{
Contract.Ensures(Contract.Result<bool>() == this.Width < 0.0);
return default(bool);
}
}
//
// Summary:
// Gets the x-axis value of the left side of the rectangle.
//
// Returns:
// The x-axis value of the left side of the rectangle.
public double Left
{
get
{
Contract.Ensures(!this.IsEmpty || Contract.Result<double>() == Double.PositiveInfinity || Double.IsNaN(Contract.Result<double>()));
Contract.Ensures(Contract.Result<double>() == this.X || Double.IsNaN(Contract.Result<double>()));
return default(double);
}
}
//
// Summary:
// Gets or sets the position of the top-left corner of the rectangle.
//
// Returns:
// The position of the top-left corner of the rectangle. The default is (0,
// 0).
//public Point Location { get; set; }
//
// Summary:
// Gets the x-axis value of the right side of the rectangle.
//
// Returns:
// The x-axis value of the right side of the rectangle.
public double Right
{
get
{
Contract.Ensures(!this.IsEmpty || Contract.Result<double>() == Double.NegativeInfinity || Double.IsNaN(Contract.Result<double>()));
return default(double);
}
}
//
// Summary:
// Gets or sets the width and height of the rectangle.
//
// Returns:
// A System.Windows.Size structure that specifies the width and height of the
// rectangle.
//public Size Size { get; set; }
//
// Summary:
// Gets the y-axis position of the top of the rectangle.
//
// Returns:
// The y-axis position of the top of the rectangle.
public double Top
{
get
{
Contract.Ensures(!this.IsEmpty || Contract.Result<double>() == Double.PositiveInfinity || Double.IsNaN(Contract.Result<double>()));
Contract.Ensures(Contract.Result<double>() == this.Y || Double.IsNaN(Contract.Result<double>()));
return default(double);
}
}
//
// Summary:
// Gets the position of the top-left corner of the rectangle.
//
// Returns:
// The position of the top-left corner of the rectangle.
//public Point TopLeft { get; }
//
// Summary:
// Gets the position of the top-right corner of the rectangle.
//
// Returns:
// The position of the top-right corner of the rectangle.
//public Point TopRight { get; }
//
// Summary:
// Gets or sets the width of the rectangle.
//
// Returns:
// A positive number that represents the width of the rectangle. The default
// is 0.
public double Width
{
get
{
Contract.Ensures(this.IsEmpty || Contract.Result<double>() >= 0.0 || Double.IsNaN(Contract.Result<double>()) || Double.IsPositiveInfinity(Contract.Result<double>()));
return default(double);
}
set
{
// Contract.Requires(!this.IsEmpty); => Is true, but impossible to proof with acceptable effort.
Contract.Requires(value >= 0.0 || Double.IsNaN(value) || Double.IsPositiveInfinity(value));
Contract.Ensures(this.Width == value);
}
}
//
// Summary:
// Gets or sets the x-axis value of the left side of the rectangle.
//
// Returns:
// The x-axis value of the left side of the rectangle.
public double X
{
get
{
Contract.Ensures(!this.IsEmpty || Contract.Result<double>() == Double.PositiveInfinity || Double.IsNaN(Contract.Result<double>()));
return default(double);
}
set
{
// Contract.Requires(!this.IsEmpty); => Is true, but impossible to proof with acceptable effort.
Contract.Ensures(this.X == value);
}
}
//
// Summary:
// Gets or sets the y-axis value of the top side of the rectangle.
//
// Returns:
// The y-axis value of the top side of the rectangle.
public double Y
{
get
{
Contract.Ensures(!this.IsEmpty || Contract.Result<double>() == Double.PositiveInfinity || Double.IsNaN(Contract.Result<double>()));
return default(double);
}
set
{
// Contract.Requires(!this.IsEmpty); => Is true, but impossible to proof with acceptable effort.
Contract.Ensures(this.Y == value);
}
}
// Summary:
// Indicates whether the rectangle contains the specified point.
//
// Parameters:
// point:
// The point to check.
//
// Returns:
// true if the rectangle contains the specified point; otherwise, false.
//public bool Contains(Point point);
//
// Summary:
// Indicates whether the rectangle contains the specified rectangle.
//
// Parameters:
// rect:
// The rectangle to check.
//
// Returns:
// true if rect is entirely contained by the rectangle; otherwise, false.
//public bool Contains(Rect rect);
//
// Summary:
// Indicates whether the rectangle contains the specified x-coordinate and y-coordinate.
//
// Parameters:
// x:
// The x-coordinate of the point to check.
//
// y:
// The y-coordinate of the point to check.
//
// Returns:
// true if (x, y) is contained by the rectangle; otherwise, false.
//public bool Contains(double x, double y);
//
// Summary:
// Indicates whether the specified object is equal to the current rectangle.
//
// Parameters:
// o:
// The object to compare to the current rectangle.
//
// Returns:
// true if o is a System.Windows.Rect and has the same System.Windows.Rect.Location
// and System.Windows.Rect.Size values as the current rectangle; otherwise,
// false.
//public override bool Equals(object o);
//
// Summary:
// Indicates whether the specified rectangle is equal to the current rectangle.
//
// Parameters:
// value:
// The rectangle to compare to the current rectangle.
//
// Returns:
// true if the specified rectangle has the same System.Windows.Rect.Location
// and System.Windows.Rect.Size values as the current rectangle; otherwise,
// false.
//public bool Equals(Rect value);
//
// Summary:
// Indicates whether the specified rectangles are equal.
//
// Parameters:
// rect1:
// The first rectangle to compare.
//
// rect2:
// The second rectangle to compare.
//
// Returns:
// true if the rectangles have the same System.Windows.Rect.Location and System.Windows.Rect.Size
// values; otherwise, false.
//public static bool Equals(Rect rect1, Rect rect2);
//
// Summary:
// Creates a hash code for the rectangle.
//
// Returns:
// A hash code for the current System.Windows.Rect structure.
//public override int GetHashCode();
//
// Summary:
// Expands the rectangle by using the specified System.Windows.Size, in all
// directions.
//
// Parameters:
// size:
// Specifies the amount to expand the rectangle. The System.Windows.Size structure's
// System.Windows.Size.Width property specifies the amount to increase the rectangle's
// System.Windows.Rect.Left and System.Windows.Rect.Right properties. The System.Windows.Size
// structure's System.Windows.Size.Height property specifies the amount to increase
// the rectangle's System.Windows.Rect.Top and System.Windows.Rect.Bottom properties.
public void Inflate(Size size)
{
// Contract.Requires(!this.IsEmpty); => Is true, but impossible to proof with acceptable effort.Contract.Requires(!this.IsEmpty);
}
//
// Summary:
// Expands or shrinks the rectangle by using the specified width and height
// amounts, in all directions.
//
// Parameters:
// width:
// The amount by which to expand or shrink the left and right sides of the rectangle.
//
// height:
// The amount by which to expand or shrink the top and bottom sides of the rectangle.
public void Inflate(double width, double height)
{
// Contract.Requires(!this.IsEmpty); => Is true, but impossible to proof with acceptable effort.
}
//
// Summary:
// Returns the rectangle that results from expanding the specified rectangle
// by the specified System.Windows.Size, in all directions.
//
// Parameters:
// rect:
// The System.Windows.Rect structure to modify.
//
// size:
// Specifies the amount to expand the rectangle. The System.Windows.Size structure's
// System.Windows.Size.Width property specifies the amount to increase the rectangle's
// System.Windows.Rect.Left and System.Windows.Rect.Right properties. The System.Windows.Size
// structure's System.Windows.Size.Height property specifies the amount to increase
// the rectangle's System.Windows.Rect.Top and System.Windows.Rect.Bottom properties.
//
// Returns:
// The resulting rectangle.
public static Rect Inflate(Rect rect, Size size)
{
// Contract.Requires(!this.IsEmpty); => Is true, but impossible to proof with acceptable effort.
return default(Rect);
}
//
// Summary:
// Creates a rectangle that results from expanding or shrinking the specified
// rectangle by the specified width and height amounts, in all directions.
//
// Parameters:
// rect:
// The System.Windows.Rect structure to modify.
//
// width:
// The amount by which to expand or shrink the left and right sides of the rectangle.
//
// height:
// The amount by which to expand or shrink the top and bottom sides of the rectangle.
//
// Returns:
// The resulting rectangle.
public static Rect Inflate(Rect rect, double width, double height)
{
// Contract.Requires(!this.IsEmpty); => Is true, but impossible to proof with acceptable effort.
return default(Rect);
}
//
// Summary:
// Finds the intersection of the current rectangle and the specified rectangle,
// and stores the result as the current rectangle.
//
// Parameters:
// rect:
// The rectangle to intersect with the current rectangle.
//public void Intersect(Rect rect);
//
// Summary:
// Returns the intersection of the specified rectangles.
//
// Parameters:
// rect1:
// The first rectangle to compare.
//
// rect2:
// The second rectangle to compare.
//
// Returns:
// The intersection of the two rectangles, or System.Windows.Rect.Empty if no
// intersection exists.
//public static Rect Intersect(Rect rect1, Rect rect2);
//
// Summary:
// Indicates whether the specified rectangle intersects with the current rectangle.
//
// Parameters:
// rect:
// The rectangle to check.
//
// Returns:
// true if the specified rectangle intersects with the current rectangle; otherwise,
// false.
//public bool IntersectsWith(Rect rect);
//
// Summary:
// Moves the rectangle by the specified vector.
//
// Parameters:
// offsetVector:
// A vector that specifies the horizontal and vertical amounts to move the rectangle.
//
// Exceptions:
// System.InvalidOperationException:
// This method is called on the System.Windows.Rect.Empty rectangle.
public void Offset(Vector offsetVector)
{
// Contract.Requires(!this.IsEmpty); => Is true, but impossible to proof with acceptable effort.
}
//
// Summary:
// Moves the rectangle by the specified horizontal and vertical amounts.
//
// Parameters:
// offsetX:
// The amount to move the rectangle horizontally.
//
// offsetY:
// The amount to move the rectangle vertically.
//
// Exceptions:
// System.InvalidOperationException:
// This method is called on the System.Windows.Rect.Empty rectangle.
public void Offset(double offsetX, double offsetY)
{
// Contract.Requires(!this.IsEmpty); => Is true, but impossible to proof with acceptable effort.
}
//
// Summary:
// Returns a rectangle that is offset from the specified rectangle by using
// the specified vector.
//
// Parameters:
// rect:
// The original rectangle.
//
// offsetVector:
// A vector that specifies the horizontal and vertical offsets for the new rectangle.
//
// Returns:
// The resulting rectangle.
//
// Exceptions:
// System.InvalidOperationException:
// rect is System.Windows.Rect.Empty.
public static Rect Offset(Rect rect, Vector offsetVector)
{
// Contract.Requires(!this.IsEmpty); => Is true, but impossible to proof with acceptable effort.
return default(Rect);
}
//
// Summary:
// Returns a rectangle that is offset from the specified rectangle by using
// the specified horizontal and vertical amounts.
//
// Parameters:
// rect:
// The rectangle to move.
//
// offsetX:
// The horizontal offset for the new rectangle.
//
// offsetY:
// The vertical offset for the new rectangle.
//
// Returns:
// The resulting rectangle.
//
// Exceptions:
// System.InvalidOperationException:
// rect is System.Windows.Rect.Empty.
public static Rect Offset(Rect rect, double offsetX, double offsetY)
{
// Contract.Requires(!this.IsEmpty); => Is true, but impossible to proof with acceptable effort.
return default(Rect);
}
//
// Summary:
// Creates a new rectangle from the specified string representation.
//
// Parameters:
// source:
// The string representation of the rectangle, in the form "x, y, width, height".
//
// Returns:
// The resulting rectangle.
//public static Rect Parse(string source);
//
// Summary:
// Multiplies the size of the current rectangle by the specified x and y values.
//
// Parameters:
// scaleX:
// The scale factor in the x-direction.
//
// scaleY:
// The scale factor in the y-direction.
//public void Scale(double scaleX, double scaleY);
//
// Summary:
// Returns a string representation of the rectangle.
//
// Returns:
// A string representation of the current rectangle. The string has the following
// form: "System.Windows.Rect.X,System.Windows.Rect.Y,System.Windows.Rect.Width,System.Windows.Rect.Height".
//public override string ToString();
//
// Summary:
// Returns a string representation of the rectangle by using the specified format
// provider.
//
// Parameters:
// provider:
// Culture-specific formatting information.
//
// Returns:
// A string representation of the current rectangle that is determined by the
// specified format provider.
//public string ToString(IFormatProvider provider);
//
// Summary:
// Transforms the rectangle by applying the specified matrix.
//
// Parameters:
// matrix:
// A matrix that specifies the transformation to apply.
//public void Transform(Matrix matrix);
//
// Summary:
// Returns the rectangle that results from applying the specified matrix to
// the specified rectangle.
//
// Parameters:
// rect:
// A rectangle that is the basis for the transformation.
//
// matrix:
// A matrix that specifies the transformation to apply.
//
// Returns:
// The rectangle that results from the operation.
//public static Rect Transform(Rect rect, Matrix matrix);
//
// Summary:
// Expands the current rectangle exactly enough to contain the specified point.
//
// Parameters:
// point:
// The point to include.
//public void Union(Point point);
//
// Summary:
// Expands the current rectangle exactly enough to contain the specified rectangle.
//
// Parameters:
// rect:
// The rectangle to include.
//public void Union(Rect rect);
//
// Summary:
// Creates a rectangle that is exactly large enough to include the specified
// rectangle and the specified point.
//
// Parameters:
// rect:
// The rectangle to include.
//
// point:
// The point to include.
//
// Returns:
// A rectangle that is exactly large enough to contain the specified rectangle
// and the specified point.
//public static Rect Union(Rect rect, Point point);
//
// Summary:
// Creates a rectangle that is exactly large enough to contain the two specified
// rectangles.
//
// Parameters:
// rect1:
// The first rectangle to include.
//
// rect2:
// The second rectangle to include.
//
// Returns:
// The resulting rectangle.
//public static Rect Union(Rect rect1, Rect rect2);
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="NavigationHelper.cs" company="Microsoft">
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// <summary>
// Contains code for the NavigationHelper class.
// </summary>
//-----------------------------------------------------------------------
namespace Microsoft.WindowsAzure.StorageClient
{
using System;
using System.Globalization;
/// <summary>
/// Contains methods for dealing with navigation.
/// </summary>
internal static class NavigationHelper
{
/// <summary>
/// The name of the root container.
/// </summary>
public const string RootContainerName = "$root";
/// <summary>
/// Used in address parsing.
/// </summary>
public const string Slash = "/";
/// <summary>
/// Used in address parsing.
/// </summary>
public const string Dot = ".";
/// <summary>
/// Used in address parsing.
/// </summary>
public const char SlashChar = '/';
/// <summary>
/// Used to split string on slash.
/// </summary>
public static readonly char[] SlashAsSplitOptions = new char[] { '/' };
/// <summary>
/// Used to split hostname.
/// </summary>
public static readonly char[] DotAsSplitOptions = new char[] { '.' };
/// <summary>
/// Retrieves the container part of a storage Uri, or "$root" if the container is implicit.
/// </summary>
/// <param name="blobAddress">The blob address.</param>
/// <param name="usePathStyleUris">If set to <c>true</c> use path style Uris.</param>
/// <returns>Name of the container.</returns>
/// <remarks>
/// The trailing slash is always removed.
/// <example>
/// GetContainerName(new Uri("http://test.blob.core.windows.net/mycontainer/myfolder/myblob")) will return "mycontainer"
/// GetConatinerName(new Uri("http://test.blob.core.windows.net/mycontainer/")) will return "mycontainer"
/// GetConatinerName(new Uri("http://test.blob.core.windows.net/myblob")) will return "$root"
/// GetConatinerName(new Uri("http://test.blob.core.windows.net/")) will throw ArgumentException
/// </example>
/// </remarks>
internal static string GetContainerName(Uri blobAddress, bool usePathStyleUris)
{
string containerName;
string blobName;
GetContainerNameAndBlobName(blobAddress, usePathStyleUris, out containerName, out blobName);
return containerName;
}
/// <summary>
/// Retrieves the blob part of a storage Uri.
/// </summary>
/// <param name="blobAddress">The blob address.</param>
/// <param name="usePathStyleUris">If set to <c>true</c> use path style Uris.</param>
/// <returns>The name of the blob.</returns>
internal static string GetBlobName(Uri blobAddress, bool usePathStyleUris)
{
string containerName;
string blobName;
GetContainerNameAndBlobName(blobAddress, usePathStyleUris, out containerName, out blobName);
return blobName;
}
/// <summary>
/// Retreives the complete container address from a storage Uri
/// Example GetContainerAddress(new Uri("http://test.blob.core.windows.net/mycontainer/myfolder/myblob"))
/// will return http://test.blob.core.windows.net/mycontainer.
/// </summary>
/// <param name="blobAddress">The BLOB address.</param>
/// <param name="usePathStyleUris">True to use path style Uris.</param>
/// <returns>Uri of the container.</returns>
internal static string GetContainerAddress(Uri blobAddress, bool usePathStyleUris)
{
string containerName;
Uri containerAddress;
GetContainerNameAndAddress(blobAddress, usePathStyleUris, out containerName, out containerAddress);
return containerAddress.AbsoluteUri;
}
/// <summary>
/// Retreives the parent name from a storage Uri.
/// </summary>
/// <param name="blobAddress">The BLOB address.</param>
/// <param name="delimiter">The delimiter.</param>
/// <param name="usePathStyleUris">If set to <c>true</c> use path style Uris.</param>
/// <returns>The name of the parent.</returns>
/// <remarks>
/// Adds the trailing delimiter as the prefix returned by the storage REST api always contains the delimiter.
/// </remarks>
/// <example>
/// GetParentName(new Uri("http://test.blob.core.windows.net/mycontainer/myfolder/myblob", "/")) will return "/mycontainer/myfolder/"
/// GetParentName(new Uri("http://test.blob.core.windows.net/mycontainer/myfolder|myblob", "|") will return "/mycontainer/myfolder|"
/// GetParentName(new Uri("http://test.blob.core.windows.net/mycontainer/myblob", "/") will return "/mycontainer/"
/// GetParentName(new Uri("http://test.blob.core.windows.net/mycontainer/", "/") will return "/mycontainer/"
/// </example>
internal static string GetParentName(Uri blobAddress, string delimiter, bool usePathStyleUris)
{
CommonUtils.AssertNotNull("blobAbsoluteUriString", blobAddress);
CommonUtils.AssertNotNullOrEmpty("delimiter", delimiter);
string containerName;
Uri containerUri;
GetContainerNameAndAddress(blobAddress, usePathStyleUris, out containerName, out containerUri);
// Get the blob path as the rest of the Uri
var blobPathUri = containerUri.MakeRelativeUri(blobAddress);
var blobPath = blobPathUri.OriginalString;
if (blobPath.EndsWith(delimiter))
{
blobPath = blobPath.Substring(0, blobPath.Length - delimiter.Length);
}
string parentName = null;
if (string.IsNullOrEmpty(blobPath))
{
// Case 1 /<ContainerName>[Delimiter]*? => /<ContainerName>
// Parent of container is container itself
parentName = containerName + delimiter;
}
else
{
var parentLength = blobPath.LastIndexOf(delimiter);
if (parentLength <= 0)
{
// Case 2 /<Container>/<folder>
// Parent of a folder is container
parentName = containerName + delimiter;
}
else
{
// Case 3 /<Container>/<folder>/[<subfolder>/]*<BlobName>
// Parent of blob is folder
parentName = blobPath.Substring(0, parentLength + delimiter.Length);
}
}
return parentName;
}
/// <summary>
/// Retrieves the parent address for a blob Uri.
/// </summary>
/// <param name="blobAddress">The BLOB address.</param>
/// <param name="delimiter">The delimiter.</param>
/// <param name="usePathStyleUris">If set to <c>true</c> use path style Uris.</param>
/// <returns>The address of the parent.</returns>
/// <example>
/// GetParentName(new Uri("http://test.blob.core.windows.net/mycontainer/myfolder/myblob", null))
/// will return "http://test.blob.core.windows.net/mycontainer/myfolder/"
/// </example>
internal static string GetParentAddress(Uri blobAddress, string delimiter, bool usePathStyleUris)
{
var parentName = GetParentName(blobAddress, delimiter, usePathStyleUris);
Uri parentUri = NavigationHelper.AppendPathToUri(new Uri(NavigationHelper.GetServiceClientBaseAddress(blobAddress, usePathStyleUris)), parentName);
return parentUri.AbsoluteUri;
}
/// <summary>
/// Get service client address from a complete Uri.
/// </summary>
/// <param name="address">Complete address of the resource.</param>
/// <param name="usePathStyleUris">True to use path style Uris.</param>
/// <returns>Uri of the service client.</returns>
/// <example>
/// GetServiceClientBaseAddress("http://testaccount.blob.core.windows.net/testconatiner/blob1")
/// returns "http://testaccount.blob.core.windows.net"
/// </example>
internal static string GetServiceClientBaseAddress(string address, bool? usePathStyleUris)
{
return GetServiceClientBaseAddress(new Uri(address), usePathStyleUris);
}
/// <summary>
/// Gets the service client base address.
/// </summary>
/// <param name="addressUri">The address Uri.</param>
/// <param name="usePathStyleUris">The use path style Uris.</param>
/// <returns>The base address of the client.</returns>
internal static string GetServiceClientBaseAddress(Uri addressUri, bool? usePathStyleUris)
{
if (usePathStyleUris == null)
{
// Automatically determine whether to use path style vs host style uris
usePathStyleUris = CommonUtils.UsePathStyleAddressing(addressUri);
}
if (usePathStyleUris.Value)
{
// Path style uri
string[] segments = addressUri.Segments;
if (segments.Length < 2)
{
string error = string.Format(CultureInfo.CurrentCulture, SR.PathStyleUriMissingAccountNameInformation, addressUri.AbsoluteUri);
throw new ArgumentException("address", error);
}
string completeAddress = addressUri.GetLeftPart(UriPartial.Authority) + Slash + segments[1];
completeAddress = completeAddress.Trim(SlashChar);
return completeAddress;
}
else
{
return addressUri.GetLeftPart(UriPartial.Authority);
}
}
/// <summary>
/// Appends a path to a Uri correctly using "/" as separator.
/// </summary>
/// <param name="uri">The base Uri.</param>
/// <param name="relativeOrAbslouteUri">The relative or absloute URI.</param>
/// <returns>The appended Uri.</returns>
/// <example>
/// AppendPathToUri(new Uri("http://test.blob.core.windows.net/test", "abc")
/// will return "http://test.blob.core.windows.net/test/abc"
/// AppendPathToUri(new Uri("http://test.blob.core.windows.net/test"), "http://test.blob.core.windows.net/test/abc")
/// will return "http://test.blob.core.windows.net/test/abc"
/// </example>
internal static Uri AppendPathToUri(Uri uri, string relativeOrAbslouteUri)
{
return AppendPathToUri(uri, relativeOrAbslouteUri, NavigationHelper.Slash);
}
/// <summary>
/// Append a relative path to a Uri, handling traling slashes appropiately.
/// </summary>
/// <param name="uri">The base Uri.</param>
/// <param name="relativeOrAbslouteUri">The relative or absloute URI.</param>
/// <param name="sep">The seperator.</param>
/// <returns>The appended Uri.</returns>
internal static Uri AppendPathToUri(Uri uri, string relativeOrAbslouteUri, string sep)
{
Uri relativeUri;
// Because of URI's Scheme, URI.TryCreate() can't differentiate a string with colon from an absolute URI.
// A workaround is added here to verify if a given string is an absolute URI.
if (Uri.TryCreate(relativeOrAbslouteUri, UriKind.Absolute, out relativeUri) && (relativeUri.Scheme == "http" || relativeUri.Scheme == "https"))
{
// Handle case if relPath is an absolute Uri
if (uri.IsBaseOf(relativeUri))
{
return relativeUri;
}
else
{
// Happens when using fiddler, DNS aliases, or potentially NATs
var absoluteUri = new Uri(relativeOrAbslouteUri);
return new Uri(uri, absoluteUri.AbsolutePath);
}
}
var ub = new UriBuilder(uri);
string appendString = null;
if (ub.Path.EndsWith(sep))
{
appendString = relativeOrAbslouteUri;
}
else
{
appendString = sep + relativeOrAbslouteUri;
}
string escapedRelativeOrAbslouteUri = Uri.EscapeUriString(appendString);
ub.Path += escapedRelativeOrAbslouteUri;
return ub.Uri;
}
/// <summary>
/// Get container name from address for styles of paths
/// Eg: http://test.blob.core.windows.net/container/blob => container
/// http://127.0.0.1:10000/test/container/blob => container.
/// </summary>
/// <param name="uri">The container Uri.</param>
/// <param name="usePathStyleUris">If set to <c>true</c> use path style Uris.</param>
/// <returns>The container name.</returns>
internal static string GetContainerNameFromContainerAddress(Uri uri, bool usePathStyleUris)
{
if (usePathStyleUris)
{
string[] parts = uri.AbsolutePath.Split(NavigationHelper.SlashAsSplitOptions);
if (parts.Length < 3)
{
string errorMessage = string.Format(CultureInfo.CurrentCulture, SR.MissingAccountInformationInUri, uri.AbsoluteUri);
throw new InvalidOperationException(errorMessage);
}
return parts[2];
}
else
{
return uri.AbsolutePath.Substring(1);
}
}
/// <summary>
/// Gets the canonical path from creds.
/// </summary>
/// <param name="credentials">The credentials.</param>
/// <param name="absolutePath">The absolute path.</param>
/// <returns>The canonical path.</returns>
internal static string GetCanonicalPathFromCreds(StorageCredentials credentials, string absolutePath)
{
string account = credentials.AccountName;
if (account == null)
{
string errorMessage = string.Format(CultureInfo.CurrentCulture, SR.CannotCreateSASSignatureForGivenCred);
throw new InvalidOperationException(errorMessage);
}
return NavigationHelper.Slash + account + absolutePath;
}
/// <summary>
/// Similar to getting container name from Uri.
/// </summary>
/// <param name="uri">The queue Uri.</param>
/// <param name="usePathStyleUris">If set to <c>true</c> use path style Uris.</param>
/// <returns>The queue name.</returns>
internal static string GetQueueNameFromUri(Uri uri, bool usePathStyleUris)
{
return GetContainerNameFromContainerAddress(uri, usePathStyleUris);
}
/// <summary>
/// Retrieve the container address and address.
/// </summary>
/// <param name="blobAddress">The BLOB address.</param>
/// <param name="usePathStyleUris">True to use path style Uris.</param>
/// <param name="containerName">Name of the container.</param>
/// <param name="containerUri">The container URI.</param>
private static void GetContainerNameAndAddress(Uri blobAddress, bool usePathStyleUris, out string containerName, out Uri containerUri)
{
containerName = GetContainerName(blobAddress, usePathStyleUris);
containerUri = NavigationHelper.AppendPathToUri(new Uri(GetServiceClientBaseAddress(blobAddress, usePathStyleUris)), containerName);
}
/// <summary>
/// Retrieve the container name and the blob name from a blob address.
/// </summary>
/// <param name="blobAddress">The blob address.</param>
/// <param name="usePathStyleUris">If set to <c>true</c> use path style Uris.</param>
/// <param name="containerName">The resulting container name.</param>
/// <param name="blobName">The resulting blob name.</param>
private static void GetContainerNameAndBlobName(Uri blobAddress, bool usePathStyleUris, out string containerName, out string blobName)
{
CommonUtils.AssertNotNull("blobAddress", blobAddress);
var addressParts = blobAddress.Segments;
int containerIndex = usePathStyleUris ? 2 : 1;
int firstBlobIndex = containerIndex + 1;
if (addressParts.Length - 1 < containerIndex)
{
// No reference appears to any container or blob
string error = string.Format(CultureInfo.CurrentCulture, SR.MissingContainerInformation, blobAddress);
throw new ArgumentException(error, "blobAddress");
}
else if (addressParts.Length - 1 == containerIndex)
{
// This is either the root directory of a container or a blob in the root container
string containerOrBlobName = addressParts[containerIndex];
if (containerOrBlobName[containerOrBlobName.Length - 1] == SlashChar)
{
// This is the root directory of a container
containerName = containerOrBlobName.Trim(SlashChar);
blobName = string.Empty;
}
else
{
// This is a blob implicitly in the root container
containerName = RootContainerName;
blobName = containerOrBlobName;
}
}
else
{
// This is a blob in an explicit container
containerName = addressParts[containerIndex].Trim(SlashChar);
string[] blobNameSegments = new string[addressParts.Length - firstBlobIndex];
Array.Copy(addressParts, firstBlobIndex, blobNameSegments, 0, blobNameSegments.Length);
blobName = string.Concat(blobNameSegments);
}
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Reflection;
using Common.Logging;
using Spring.Expressions;
using Spring.Messaging.Nms.Core;
using Spring.Messaging.Nms.Support;
using Spring.Messaging.Nms.Support.Converter;
using Spring.Messaging.Nms.Support.Destinations;
using Spring.Util;
using Apache.NMS;
namespace Spring.Messaging.Nms.Listener.Adapter
{
/// <summary>
/// Message listener adapter that delegates the handling of messages to target
/// listener methods via reflection, with flexible message type conversion.
/// Allows listener methods to operate on message content types, completely
/// independent from the NMS API.
/// </summary>
/// <remarks>
/// <para>By default, the content of incoming messages gets extracted before
/// being passed into the target listener method, to let the target method
/// operate on message content types such as String or byte array instead of
/// the raw Message. Message type conversion is delegated to a Spring
/// <see cref="IMessageConverter"/>. By default, a <see cref="SimpleMessageConverter"/>
/// will be used. (If you do not want such automatic message conversion taking
/// place, then be sure to set the <see cref="MessageConverter"/> property
/// to <code>null</code>.)
/// </para>
/// <para>If a target listener method returns a non-null object (typically of a
/// message content type such as <code>String</code> or byte array), it will get
/// wrapped in a NMS <code>Message</code> and sent to the response destination
/// (either the NMS "reply-to" destination or the <see cref="defaultResponseDestination"/>
/// specified.
/// </para>
/// <para>
/// The sending of response messages is only available when
/// using the <see cref="ISessionAwareMessageListener"/> entry point (typically through a
/// Spring message listener container). Usage as standard NMS MessageListener
/// does <i>not</i> support the generation of response messages.
/// </para>
/// <para>Consult the reference documentation for examples of method signatures compliant with this
/// adapter class.
/// </para>
/// </remarks>
/// <author>Juergen Hoeller</author>
/// <author>Mark Pollack (.NET)</author>
public class MessageListenerAdapter : IMessageListener, ISessionAwareMessageListener
{
#region Logging
private readonly ILog logger = LogManager.GetLogger(typeof (MessageListenerAdapter));
#endregion
#region Fields
/// <summary>
/// The default handler method name.
/// </summary>
public static string ORIGINAL_DEFAULT_HANDLER_METHOD = "HandleMessage";
private object handlerObject;
private string defaultHandlerMethod = ORIGINAL_DEFAULT_HANDLER_METHOD;
private IExpression processingExpression;
private object defaultResponseDestination;
private IDestinationResolver destinationResolver = new DynamicDestinationResolver();
private IMessageConverter messageConverter;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="MessageListenerAdapter"/> class with default settings.
/// </summary>
public MessageListenerAdapter()
{
InitDefaultStrategies();
handlerObject = this;
}
/// <summary>
/// Initializes a new instance of the <see cref="MessageListenerAdapter"/> class for the given handler object
/// </summary>
/// <param name="handlerObject">The delegate object.</param>
public MessageListenerAdapter(object handlerObject)
{
InitDefaultStrategies();
this.handlerObject = handlerObject;
}
#endregion
/// <summary>
/// Gets or sets the handler object to delegate message listening to.
/// </summary>
/// <remarks>
/// Specified listener methods have to be present on this target object.
/// If no explicit handler object has been specified, listener
/// methods are expected to present on this adapter instance, that is,
/// on a custom subclass of this adapter, defining listener methods.
/// </remarks>
/// <value>The handler object.</value>
public object HandlerObject
{
get { return handlerObject; }
set { handlerObject = value; }
}
/// <summary>
/// Gets or sets the default handler method to delegate to,
/// for the case where no specific listener method has been determined.
/// Out-of-the-box value is <see cref="ORIGINAL_DEFAULT_HANDLER_METHOD"/> ("HandleMessage"}.
/// </summary>
/// <value>The default handler method.</value>
public string DefaultHandlerMethod
{
get { return defaultHandlerMethod; }
set
{
defaultHandlerMethod = value;
processingExpression = Expression.Parse(defaultHandlerMethod + "(#convertedObject)");
}
}
/// <summary>
/// Sets the default destination to send response messages to. This will be applied
/// in case of a request message that does not carry a "JMSReplyTo" field.
/// Response destinations are only relevant for listener methods that return
/// result objects, which will be wrapped in a response message and sent to a
/// response destination.
/// <para>
/// Alternatively, specify a "DefaultResponseQueueName" or "DefaultResponseTopicName",
/// to be dynamically resolved via the DestinationResolver.
/// </para>
/// </summary>
/// <value>The default response destination.</value>
public object DefaultResponseDestination
{
set { defaultResponseDestination = value; }
}
/// <summary>
/// Sets the name of the default response queue to send response messages to.
/// This will be applied in case of a request message that does not carry a
/// "NMSReplyTo" field.
/// <para>Alternatively, specify a JMS Destination object as "defaultResponseDestination".</para>
/// </summary>
/// <value>The name of the default response destination queue.</value>
public string DefaultResponseQueueName
{
set { defaultResponseDestination = new DestinationNameHolder(value, false); }
}
/// <summary>
/// Sets the name of the default response topic to send response messages to.
/// This will be applied in case of a request message that does not carry a
/// "NMSReplyTo" field.
/// <para>Alternatively, specify a JMS Destination object as "defaultResponseDestination".</para>
/// </summary>
/// <value>The name of the default response destination topic.</value>
public string DefaultResponseTopicName
{
set { defaultResponseDestination = new DestinationNameHolder(value, true); }
}
/// <summary>
/// Gets or sets the destination resolver that should be used to resolve response
/// destination names for this adapter.
/// <para>The default resolver is a <see cref="DynamicDestinationResolver"/>.
/// Specify another implementation, for other strategies, perhaps from a directory service.</para>
/// </summary>
/// <value>The destination resolver.</value>
public IDestinationResolver DestinationResolver
{
get { return destinationResolver; }
set
{
AssertUtils.ArgumentNotNull(value, "DestinationResolver must not be null");
destinationResolver = value;
}
}
/// <summary>
/// Gets or sets the message converter that will convert incoming JMS messages to
/// listener method arguments, and objects returned from listener
/// methods back to NMS messages.
/// </summary>
/// <remarks>
/// <para>The default converter is a {@link SimpleMessageConverter}, which is able
/// to handle BytesMessages}, TextMessages, MapMessages, and ObjectMessages.
/// </para>
/// </remarks>
/// <value>The message converter.</value>
public IMessageConverter MessageConverter
{
get { return messageConverter; }
set { messageConverter = value; }
}
/// <summary>
/// Standard JMS {@link MessageListener} entry point.
/// <para>Delegates the message to the target listener method, with appropriate
/// conversion of the message arguments
/// </para>
/// </summary>
/// <remarks>
/// In case of an exception, the <see cref="HandleListenerException"/> method will be invoked.
/// <b>Note</b>
/// Does not support sending response messages based on
/// result objects returned from listener methods. Use the
/// <see cref="ISessionAwareMessageListener"/> entry point (typically through a Spring
/// message listener container) for handling result objects as well.
/// </remarks>
/// <param name="message">The incoming message.</param>
public void OnMessage(IMessage message)
{
try
{
OnMessage(message, null);
}
catch (Exception e)
{
HandleListenerException(e);
}
}
/// <summary>
/// Spring <see cref="ISessionAwareMessageListener"/> entry point.
/// <para>
/// Delegates the message to the target listener method, with appropriate
/// conversion of the message argument. If the target method returns a
/// non-null object, wrap in a NMS message and send it back.
/// </para>
/// </summary>
/// <param name="message">The incoming message.</param>
/// <param name="session">The session to operate on.</param>
public void OnMessage(IMessage message, ISession session)
{
if (handlerObject != this)
{
if (typeof(ISessionAwareMessageListener).IsInstanceOfType(handlerObject))
{
if (session != null)
{
((ISessionAwareMessageListener) handlerObject).OnMessage(message, session);
return;
}
else if (!typeof(IMessageListener).IsInstanceOfType(handlerObject))
{
throw new InvalidOperationException("MessageListenerAdapter cannot handle a " +
"SessionAwareMessageListener delegate if it hasn't been invoked with a Session itself");
}
}
if (typeof(IMessageListener).IsInstanceOfType(handlerObject))
{
((IMessageListener)handlerObject).OnMessage(message);
return;
}
}
// Regular case: find a handler method reflectively.
object convertedMessage = ExtractMessage(message);
IDictionary<string, object> vars = new Dictionary<string, object>();
vars["convertedObject"] = convertedMessage;
//Need to parse each time since have overloaded methods and
//expression processor caches target of first invocation.
//TODO - check JIRA as I believe this has been fixed, otherwise, use regular reflection. -MLP
//processingExpression = Expression.Parse(defaultHandlerMethod + "(#convertedObject)");
//Invoke message handler method and get result.
object result;
try
{
result = processingExpression.GetValue(handlerObject, vars);
}
catch (NMSException)
{
throw;
}
// Will only happen if dynamic method invocation falls back to standard reflection.
catch (TargetInvocationException ex)
{
Exception targetEx = ex.InnerException;
if (ObjectUtils.IsAssignable(typeof(NMSException), targetEx))
{
throw ReflectionUtils.UnwrapTargetInvocationException(ex);
}
else
{
throw new ListenerExecutionFailedException("Listener method '" + defaultHandlerMethod + "' threw exception", targetEx);
}
}
catch (Exception ex)
{
throw new ListenerExecutionFailedException("Failed to invoke target method '" + defaultHandlerMethod +
"' with argument " + convertedMessage, ex);
}
if (result != null)
{
HandleResult(result, message, session);
}
else
{
logger.Debug("No result object given - no result to handle");
}
}
/// <summary>
/// Initialize the default implementations for the adapter's strategies.
/// </summary>
protected virtual void InitDefaultStrategies()
{
MessageConverter = new SimpleMessageConverter();
processingExpression = Expression.Parse(defaultHandlerMethod + "(#convertedObject)");
}
/// <summary>
/// Handle the given exception that arose during listener execution.
/// The default implementation logs the exception at error level.
/// <para>This method only applies when used as standard NMS MessageListener.
/// In case of the Spring <see cref="ISessionAwareMessageListener"/> mechanism,
/// exceptions get handled by the caller instead.
/// </para>
/// </summary>
/// <param name="ex">The exception to handle.</param>
protected virtual void HandleListenerException(Exception ex)
{
logger.Error("Listener execution failed", ex);
}
/// <summary>
/// Extract the message body from the given message.
/// </summary>
/// <param name="message">The message.</param>
/// <returns>the content of the message, to be passed into the
/// listener method as argument</returns>
/// <exception cref="NMSException">if thrown by NMS API methods</exception>
private object ExtractMessage(IMessage message)
{
IMessageConverter converter = MessageConverter;
if (converter != null)
{
return converter.FromMessage(message);
}
return message;
}
/// <summary>
/// Gets the name of the listener method that is supposed to
/// handle the given message.
/// The default implementation simply returns the configured
/// default listener method, if any.
/// </summary>
/// <param name="originalIMessage">The NMS request message.</param>
/// <param name="extractedMessage">The converted JMS request message,
/// to be passed into the listener method as argument.</param>
/// <returns>the name of the listener method (never <code>null</code>)</returns>
/// <exception cref="NMSException">if thrown by NMS API methods</exception>
protected virtual string GetHandlerMethodName(IMessage originalIMessage, object extractedMessage)
{
return DefaultHandlerMethod;
}
/// <summary>
/// Handles the given result object returned from the listener method, sending a response message back.
/// </summary>
/// <param name="result">The result object to handle (never <code>null</code>).</param>
/// <param name="request">The original request message.</param>
/// <param name="session">The session to operate on (may be <code>null</code>).</param>
protected virtual void HandleResult(object result, IMessage request, ISession session)
{
if (session != null)
{
if (logger.IsDebugEnabled)
{
logger.Debug("Listener method returned result [" + result +
"] - generating response message for it");
}
IMessage response = BuildMessage(session, result);
PostProcessResponse(request, response);
IDestination destination = GetResponseDestination(request, response, session);
SendResponse(session, destination, response);
}
else
{
if (logger.IsDebugEnabled)
{
logger.Debug("Listener method returned result [" + result +
"]: not generating response message for it because of no NMS ISession given");
}
}
}
/// <summary>
/// Builds a JMS message to be sent as response based on the given result object.
/// </summary>
/// <param name="session">The JMS Session to operate on.</param>
/// <param name="result">The content of the message, as returned from the listener method.</param>
/// <returns>the JMS <code>Message</code> (never <code>null</code>)</returns>
/// <exception cref="MessageConversionException">If there was an error in message conversion</exception>
/// <exception cref="NMSException">if thrown by NMS API methods</exception>
protected virtual IMessage BuildMessage(ISession session, Object result)
{
IMessageConverter converter = MessageConverter;
if (converter != null)
{
return converter.ToMessage(result, session);
}
else
{
IMessage msg = result as IMessage;
if (msg == null)
{
throw new MessageConversionException(
"No IMessageConverter specified - cannot handle message [" + result + "]");
}
return msg;
}
}
/// <summary>
/// Post-process the given response message before it will be sent. The default implementation
/// sets the response's correlation id to the request message's correlation id.
/// </summary>
/// <param name="request">The original incoming message.</param>
/// <param name="response">The outgoing JMS message about to be sent.</param>
/// <exception cref="NMSException">if thrown by NMS API methods</exception>
protected virtual void PostProcessResponse(IMessage request, IMessage response)
{
response.NMSCorrelationID = request.NMSCorrelationID;
}
/// <summary>
/// Determine a response destination for the given message.
/// </summary>
/// <remarks>
/// <para>The default implementation first checks the JMS Reply-To
/// Destination of the supplied request; if that is not <code>null</code>
/// it is returned; if it is <code>null</code>, then the configured
/// <see cref="DefaultResponseDestination"/> default response destination
/// is returned; if this too is <code>null</code>, then an
/// <see cref="InvalidDestinationException"/>is thrown.
/// </para>
/// </remarks>
/// <param name="request">The original incoming message.</param>
/// <param name="response">The outgoing message about to be sent.</param>
/// <param name="session">The session to operate on.</param>
/// <returns>the response destination (never <code>null</code>)</returns>
/// <exception cref="NMSException">if thrown by NMS API methods</exception>
/// <exception cref="InvalidDestinationException">if no destination can be determined.</exception>
protected virtual IDestination GetResponseDestination(IMessage request, IMessage response, ISession session)
{
IDestination replyTo = request.NMSReplyTo;
if (replyTo == null)
{
replyTo = ResolveDefaultResponseDestination(session);
if (replyTo == null)
{
throw new InvalidDestinationException("Cannot determine response destination: " +
"Request message does not contain reply-to destination, and no default response destination set.");
}
}
return replyTo;
}
/// <summary>
/// Resolves the default response destination into a Destination, using this
/// accessor's <see cref="IDestinationResolver"/> in case of a destination name.
/// </summary>
/// <param name="session">The session to operate on.</param>
/// <returns>The located destination</returns>
protected virtual IDestination ResolveDefaultResponseDestination(ISession session)
{
IDestination dest = defaultResponseDestination as IDestination;
if (dest != null)
{
return dest;
}
DestinationNameHolder destNameHolder = defaultResponseDestination as DestinationNameHolder;
if (destNameHolder != null)
{
return DestinationResolver.ResolveDestinationName(session, destNameHolder.Name, destNameHolder.IsTopic);
}
return null;
}
/// <summary>
/// Sends the given response message to the given destination.
/// </summary>
/// <param name="session">The session to operate on.</param>
/// <param name="destination">The destination to send to.</param>
/// <param name="response">The outgoing message about to be sent.</param>
protected virtual void SendResponse(ISession session, IDestination destination, IMessage response)
{
IMessageProducer producer = session.CreateProducer(destination);
try
{
PostProcessProducer(producer, response);
producer.Send(response);
}
finally
{
NmsUtils.CloseMessageProducer(producer);
}
}
/// <summary>
/// Post-process the given message producer before using it to send the response.
/// The default implementation is empty.
/// </summary>
/// <param name="producer">The producer that will be used to send the message.</param>
/// <param name="response">The outgoing message about to be sent.</param>
protected virtual void PostProcessProducer(IMessageProducer producer, IMessage response)
{
}
}
/// <summary>
/// Internal class combining a destination name and its target destination type (queue or topic).
/// </summary>
internal class DestinationNameHolder
{
private readonly string name;
private readonly bool isTopic;
public DestinationNameHolder(string name, bool isTopic)
{
this.name = name;
this.isTopic = isTopic;
}
public string Name
{
get { return name; }
}
public bool IsTopic
{
get { return isTopic; }
}
}
}
| |
using System;
using System.Diagnostics;
public class D
{
private bool maybe;
public bool flag;
public D(bool b, bool f)
{
this.maybe = b;
this.flag = f;
}
public void Caller()
{
Callee1(new object());
Callee1(null);
Callee2(new object());
}
public void Callee1(object param)
{
param.ToString(); // BAD (maybe)
}
public void Callee2(object param)
{
if (param != null)
{
param.ToString(); // GOOD
}
param.ToString(); // BAD (maybe)
}
private static bool CustomIsNull(object x)
{
if (x is string) return false;
if (x == null) return true;
return x == null;
}
public void NullGuards()
{
var o1 = maybe ? null : new object();
if (o1 != null) o1.ToString(); // GOOD
var o2 = maybe ? null : "";
if (o2 is string) o2.ToString(); // GOOD
object o3 = null;
if ((o3 = maybe ? null : "") != null)
o3.ToString(); // GOOD
var o4 = maybe ? null : "";
if ((2 > 1 && o4 != null) != false)
o4.ToString(); // GOOD
var o5 = (o4 != null) ? "" : null;
if (o5 != null)
o4.ToString(); // GOOD
if (o4 != null)
o5.ToString(); // GOOD (false positive)
var o6 = maybe ? null : "";
if (!CustomIsNull(o6))
o6.ToString(); // GOOD
var o7 = maybe ? null : "";
var ok = o7 != null && 2 > 1;
if (ok)
o7.ToString(); // GOOD
else
o7.ToString(); // BAD (maybe)
var o8 = maybe ? null : "";
int track = o8 == null ? 42 : 1 + 1;
if (track == 2)
o8.ToString(); // GOOD
if (track != 42)
o8.ToString(); // GOOD
if (track < 42)
o8.ToString(); // GOOD (false positive)
if (track <= 41)
o8.ToString(); // GOOD (false positive)
}
public void Deref(int i)
{
int[] xs = maybe ? null : new int[2];
if (i > 1)
xs[0] = 5; // BAD (maybe)
if (i > 2)
maybe = xs[1] > 5; // BAD (maybe)
if (i > 3)
{
var l = xs.Length; // BAD (maybe)
}
if (i > 4)
foreach (var _ in xs) ; // BAD (maybe)
if (i > 5)
lock (xs) // BAD (maybe)
xs.ToString(); // Not reported - same basic block
if (i > 6)
{
Debug.Assert(xs != null);
xs[0] = xs[1]; // GOOD
}
}
public void F(bool b)
{
var x = b ? null : "abc";
x = x == null ? "" : x;
if (x == null)
x.ToString(); // BAD (always)
else
x.ToString(); // GOOD
}
public void LengthGuard(int[] a, int[] b)
{
int alen = a == null ? 0 : a.Length; // GOOD
int blen = b == null ? 0 : b.Length; // GOOD
var sum = 0;
if (alen == blen)
{
for (int i = 0; i < alen; i++)
{
sum += a[i]; // GOOD (false positive)
sum += b[i]; // GOOD (false positive)
}
}
int alen2;
if (a != null)
alen2 = a.Length; // GOOD
else
alen2 = 0;
for (int i = 1; i <= alen2; ++i)
{
sum += a[i - 1]; // GOOD (false positive)
}
}
public void MissedGuard(object obj)
{
obj.ToString(); // BAD (maybe)
var x = obj != null ? 1 : 0;
}
private object MkMaybe()
{
if (maybe) throw new Exception();
return new object();
}
public void Exceptions()
{
object obj = null;
try
{
obj = MkMaybe();
}
catch (Exception e)
{
}
obj.ToString(); // BAD (maybe)
object obj2 = null;
try
{
obj2 = MkMaybe();
}
catch (Exception e)
{
Debug.Assert(false);
}
obj2.ToString(); // GOOD
object obj3 = null;
try
{
obj3 = MkMaybe();
}
finally { }
obj3.ToString(); // GOOD
}
public void ClearNotNull()
{
var o = new Object();
if (o == null)
o.ToString(); // BAD (always)
o.ToString(); // GOOD
try
{
MkMaybe();
}
catch (Exception e)
{
if (e == null)
e.ToString(); // BAD (always)
e.ToString(); // GOOD
}
object n = null;
var o2 = n == null ? new Object() : n;
o2.ToString(); // GOOD
var o3 = "abc";
if (o3 == null)
o3.ToString(); // BAD (always)
o3.ToString(); // GOOD
var o4 = "" + null;
if (o4 == null)
o4.ToString(); // BAD (always)
o4.ToString(); // GOOD
}
public void CorrelatedConditions(bool cond, int num)
{
object o = null;
if (cond)
o = new Object();
if (cond)
o.ToString(); // GOOD
o = null;
if (flag)
o = "";
if (flag)
o.ToString(); // GOOD
o = null;
var other = maybe ? null : "";
if (other == null)
o = "";
if (other != null)
o.ToString(); // BAD (always) (reported as maybe)
else
o.ToString(); // GOOD (false positive)
var o2 = (num < 0) ? null : "";
if (num < 0)
o2 = "";
else
o2.ToString(); // GOOD (false positive)
}
public void TrackingVariable(int[] a)
{
object o = null;
object other = null;
if (maybe)
{
o = "abc";
other = "def";
}
if (other is string)
o.ToString(); // GOOD (false positive)
o = null;
int count = 0;
var found = false;
for (var i = 0; i < a.Length; i++)
{
if (a[i] == 42)
{
o = ((int)a[i]).ToString();
count++;
if (2 > i) { }
found = true;
}
if (a[i] > 10000)
{
o = null;
count = 0;
if (2 > i) { }
found = false;
}
}
if (count > 3)
o.ToString(); // GOOD (false positive)
if (found)
o.ToString(); // GOOD (false positive)
object prev = null;
for (var i = 0; i < a.Length; ++i)
{
if (i != 0)
prev.ToString(); // GOOD (false positive)
prev = a[i];
}
string s = null;
{
var s_null = true;
foreach (var i in a)
{
s_null = false;
s = "" + a;
}
if (!s_null)
s.ToString(); // GOOD (false positive)
}
object r = null;
var stat = MyStatus.INIT;
while (stat == MyStatus.INIT && stat != MyStatus.READY)
{
r = MkMaybe();
if (stat == MyStatus.INIT)
stat = MyStatus.READY;
}
r.ToString(); // GOOD (false positive)
}
public enum MyStatus
{
READY,
INIT
}
public void G(object obj)
{
string msg = null;
if (obj == null)
msg = "foo";
else if (obj.GetHashCode() > 7) // GOOD
msg = "bar";
if (msg != null)
{
msg += "foobar";
throw new Exception(msg);
}
obj.ToString(); // GOOD
}
public void LoopCorr(int iters)
{
int[] a = null;
if (iters > 0)
a = new int[iters];
for (var i = 0; i < iters; ++i)
a[i] = 0; // GOOD (false positive)
if (iters > 0)
{
string last = null;
for (var i = 0; i < iters; i++)
last = "abc";
last.ToString(); // GOOD (false positive)
}
int[] b = maybe ? null : new int[iters];
if (iters > 0 && (b == null || b.Length < iters))
throw new Exception();
for (var i = 0; i < iters; ++i)
{
b[i] = 0; // GOOD (false positive)
}
}
void Test(Exception e, bool b)
{
Exception ioe = null;
if (b)
ioe = new Exception("");
if (ioe != null)
ioe = e;
else
ioe.ToString(); // BAD (always)
}
public void LengthGuard2(int[] a, int[] b)
{
int alen = a == null ? 0 : a.Length; // GOOD
int sum = 0;
int i;
for (i = 0; i < alen; i++)
{
sum += a[i]; // GOOD (false positive)
}
int blen = b == null ? 0 : b.Length; // GOOD
for (i = 0; i < blen; i++)
{
sum += b[i]; // GOOD (false positive)
}
i = -3;
}
public void CorrConds2(object x, object y)
{
if ((x != null && y == null) || (x == null && y != null))
return;
if (x != null)
y.ToString(); // GOOD (false positive)
if (y != null)
x.ToString(); // GOOD (false positive)
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !SILVERLIGHT && !__IOS__
namespace NLog.Targets.Wrappers
{
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Principal;
using NLog.Common;
using NLog.Internal;
/// <summary>
/// Impersonates another user for the duration of the write.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/ImpersonatingWrapper-target">Documentation on NLog Wiki</seealso>
[SecuritySafeCritical]
[Target("ImpersonatingWrapper", IsWrapper = true)]
public class ImpersonatingTargetWrapper : WrapperTargetBase
{
private WindowsIdentity newIdentity;
private IntPtr duplicateTokenHandle = IntPtr.Zero;
/// <summary>
/// Initializes a new instance of the <see cref="ImpersonatingTargetWrapper" /> class.
/// </summary>
public ImpersonatingTargetWrapper()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ImpersonatingTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
public ImpersonatingTargetWrapper(Target wrappedTarget)
{
this.Domain = ".";
this.LogOnType = SecurityLogOnType.Interactive;
this.LogOnProvider = LogOnProviderType.Default;
this.ImpersonationLevel = SecurityImpersonationLevel.Impersonation;
this.WrappedTarget = wrappedTarget;
}
/// <summary>
/// Gets or sets username to change context to.
/// </summary>
/// <docgen category='Impersonation Options' order='10' />
public string UserName { get; set; }
/// <summary>
/// Gets or sets the user account password.
/// </summary>
/// <docgen category='Impersonation Options' order='10' />
public string Password { get; set; }
/// <summary>
/// Gets or sets Windows domain name to change context to.
/// </summary>
/// <docgen category='Impersonation Options' order='10' />
[DefaultValue(".")]
public string Domain { get; set; }
/// <summary>
/// Gets or sets the Logon Type.
/// </summary>
/// <docgen category='Impersonation Options' order='10' />
public SecurityLogOnType LogOnType { get; set; }
/// <summary>
/// Gets or sets the type of the logon provider.
/// </summary>
/// <docgen category='Impersonation Options' order='10' />
public LogOnProviderType LogOnProvider { get; set; }
/// <summary>
/// Gets or sets the required impersonation level.
/// </summary>
/// <docgen category='Impersonation Options' order='10' />
public SecurityImpersonationLevel ImpersonationLevel { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to revert to the credentials of the process instead of impersonating another user.
/// </summary>
/// <docgen category='Impersonation Options' order='10' />
[DefaultValue(false)]
public bool RevertToSelf { get; set; }
/// <summary>
/// Initializes the impersonation context.
/// </summary>
protected override void InitializeTarget()
{
if (!this.RevertToSelf)
{
this.newIdentity = this.CreateWindowsIdentity(out this.duplicateTokenHandle);
}
using (this.DoImpersonate())
{
base.InitializeTarget();
}
}
/// <summary>
/// Closes the impersonation context.
/// </summary>
protected override void CloseTarget()
{
using (this.DoImpersonate())
{
base.CloseTarget();
}
if (this.duplicateTokenHandle != IntPtr.Zero)
{
NativeMethods.CloseHandle(this.duplicateTokenHandle);
this.duplicateTokenHandle = IntPtr.Zero;
}
if (this.newIdentity != null)
{
this.newIdentity.Dispose();
this.newIdentity = null;
}
}
/// <summary>
/// Changes the security context, forwards the call to the <see cref="WrapperTargetBase.WrappedTarget"/>.Write()
/// and switches the context back to original.
/// </summary>
/// <param name="logEvent">The log event.</param>
protected override void Write(AsyncLogEventInfo logEvent)
{
using (this.DoImpersonate())
{
this.WrappedTarget.WriteAsyncLogEvent(logEvent);
}
}
/// <summary>
/// Changes the security context, forwards the call to the <see cref="WrapperTargetBase.WrappedTarget"/>.Write()
/// and switches the context back to original.
/// </summary>
/// <param name="logEvents">Log events.</param>
protected override void Write(AsyncLogEventInfo[] logEvents)
{
using (this.DoImpersonate())
{
this.WrappedTarget.WriteAsyncLogEvents(logEvents);
}
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
using (this.DoImpersonate())
{
this.WrappedTarget.Flush(asyncContinuation);
}
}
private IDisposable DoImpersonate()
{
if (this.RevertToSelf)
{
return new ContextReverter(WindowsIdentity.Impersonate(IntPtr.Zero));
}
return new ContextReverter(this.newIdentity.Impersonate());
}
//
// adapted from:
// http://www.codeproject.com/csharp/cpimpersonation1.asp
//
private WindowsIdentity CreateWindowsIdentity(out IntPtr handle)
{
// initialize tokens
IntPtr logonHandle;
if (!NativeMethods.LogonUser(
this.UserName,
this.Domain,
this.Password,
(int)this.LogOnType,
(int)this.LogOnProvider,
out logonHandle))
{
throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
}
if (!NativeMethods.DuplicateToken(logonHandle, (int)this.ImpersonationLevel, out handle))
{
NativeMethods.CloseHandle(logonHandle);
throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
}
NativeMethods.CloseHandle(logonHandle);
// create new identity using new primary token)
return new WindowsIdentity(handle);
}
/// <summary>
/// Helper class which reverts the given <see cref="WindowsImpersonationContext"/>
/// to its original value as part of <see cref="IDisposable.Dispose"/>.
/// </summary>
internal class ContextReverter : IDisposable
{
private WindowsImpersonationContext wic;
/// <summary>
/// Initializes a new instance of the <see cref="ContextReverter" /> class.
/// </summary>
/// <param name="windowsImpersonationContext">The windows impersonation context.</param>
public ContextReverter(WindowsImpersonationContext windowsImpersonationContext)
{
this.wic = windowsImpersonationContext;
}
/// <summary>
/// Reverts the impersonation context.
/// </summary>
public void Dispose()
{
this.wic.Undo();
}
}
}
}
#endif
| |
using System;
using Csla;
using Csla.Data;
using Csla.Serialization;
using System.ComponentModel.DataAnnotations;
using BusinessObjects.Properties;
using System.Linq;
using BusinessObjects.CoreBusinessClasses;
using DalEf;
using System.Collections.Generic;
namespace BusinessObjects.Documents
{
[Serializable]
public partial class cDocuments_CompensationChild : CoreBusinessChildClass<cDocuments_CompensationChild>
{
public static readonly PropertyInfo< System.Int32 > IdProperty = RegisterProperty< System.Int32 >(p => p.Id, string.Empty);
#if !SILVERLIGHT
[System.ComponentModel.DataObjectField(true, true)]
#endif
public System.Int32 Id
{
get { return GetProperty(IdProperty); }
internal set { SetProperty(IdProperty, value); }
}
private static readonly PropertyInfo<System.Int32> compenzationIdProperty = RegisterProperty<System.Int32>(p => p.CompenzationId, string.Empty);
[Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))]
public System.Int32 CompenzationId
{
get { return GetProperty(compenzationIdProperty); }
set { SetProperty(compenzationIdProperty, value); }
}
private static readonly PropertyInfo< System.Int32 > ordinalProperty = RegisterProperty<System.Int32>(p => p.Ordinal, string.Empty);
[Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))]
public System.Int32 Ordinal
{
get { return GetProperty(ordinalProperty); }
set { SetProperty(ordinalProperty, value); }
}
private static readonly PropertyInfo<System.Int32?> invoiceIdProperty = RegisterProperty<System.Int32?>(p => p.InvoiceId, string.Empty);
public System.Int32? InvoiceId
{
get { return GetProperty(invoiceIdProperty); }
set { SetProperty(invoiceIdProperty, value); }
}
private static readonly PropertyInfo<System.Decimal?> payedAmmountInvoiceProperty = RegisterProperty<System.Decimal?>(p => p.PayedAmmountInvoice, string.Empty, (decimal)1);
public System.Decimal? PayedAmmountInvoice
{
get { return GetProperty(payedAmmountInvoiceProperty); }
set { SetProperty(payedAmmountInvoiceProperty, value); }
}
private static readonly PropertyInfo<System.Int32?> incomingInvoiceIdProperty = RegisterProperty<System.Int32?>(p => p.IncomingInvoiceId, string.Empty);
public System.Int32? IncomingInvoiceId
{
get { return GetProperty(incomingInvoiceIdProperty); }
set { SetProperty(incomingInvoiceIdProperty, value); }
}
private static readonly PropertyInfo<System.Decimal?> payedAmmountIncomingInvoiceProperty = RegisterProperty<System.Decimal?>(p => p.PayedAmmountIncomingInvoice, string.Empty, (decimal)1);
public System.Decimal? PayedAmmountIncomingInvoice
{
get { return GetProperty(payedAmmountIncomingInvoiceProperty); }
set { SetProperty(payedAmmountIncomingInvoiceProperty, value); }
}
/// <summary>
/// Used for optimistic concurrency.
/// </summary>
[NotUndoable]
internal System.Byte[] LastChanged = new System.Byte[8];
public static cDocuments_CompensationChild NewDocuments_CompensationChild()
{
return DataPortal.CreateChild<cDocuments_CompensationChild>();
}
public static cDocuments_CompensationChild GetDocuments_CompensationChild(Documents_CompensationChildCol data)
{
return DataPortal.FetchChild<cDocuments_CompensationChild>(data);
}
#region Data Access
[RunLocal]
protected override void Child_Create()
{
BusinessRules.CheckRules();
}
private void Child_Fetch(Documents_CompensationChildCol data)
{
LoadProperty<int>(IdProperty, data.Id);
LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey));
LoadProperty<int>(compenzationIdProperty, data.CompensationId);
LoadProperty<int>(ordinalProperty, data.Ordinal);
LoadProperty<int?>(invoiceIdProperty, data.InvoiceId);
LoadProperty<decimal?>(payedAmmountInvoiceProperty, data.PayedAmmountInvoice);
LoadProperty<int?>(incomingInvoiceIdProperty, data.IncomingInvoiceId);
LoadProperty<decimal?>(payedAmmountIncomingInvoiceProperty, data.PayedAmmountIncomingInvoice);
ItemLoaded();
LastChanged = data.LastChanged;
BusinessRules.CheckRules();
}
partial void ItemLoaded();
private void Child_Insert(Documents_Compensation parent)
{
using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities"))
{
var data = new Documents_CompensationChildCol();
data.Documents_Compensation = parent;
data.CompensationId = ReadProperty<int>(compenzationIdProperty);
data.Ordinal = ReadProperty<int>(ordinalProperty);
data.InvoiceId = ReadProperty<int?>(invoiceIdProperty);
data.PayedAmmountInvoice = ReadProperty<decimal?>(payedAmmountInvoiceProperty);
data.IncomingInvoiceId = ReadProperty<int?>(incomingInvoiceIdProperty);
data.PayedAmmountIncomingInvoice = ReadProperty<decimal?>(payedAmmountIncomingInvoiceProperty);
ctx.ObjectContext.AddToDocuments_CompensationChildCol(data);
data.PropertyChanged += (o, e) =>
{
if (e.PropertyName == "Id")
{
LoadProperty<int>(IdProperty, data.Id);
LoadProperty<int>(compenzationIdProperty, data.CompensationId);
LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey));
LastChanged = data.LastChanged;
}
};
}
}
private void Child_Update()
{
using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities"))
{
var data = new Documents_CompensationChildCol();
data.Id = ReadProperty<int>(IdProperty);
data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey;
ctx.ObjectContext.Attach(data);
data.CompensationId = ReadProperty<int>(compenzationIdProperty);
data.Ordinal = ReadProperty<int>(ordinalProperty);
data.InvoiceId = ReadProperty<int?>(invoiceIdProperty);
data.PayedAmmountInvoice = ReadProperty<decimal?>(payedAmmountInvoiceProperty);
data.IncomingInvoiceId = ReadProperty<int?>(incomingInvoiceIdProperty);
data.PayedAmmountIncomingInvoice = ReadProperty<decimal?>(payedAmmountIncomingInvoiceProperty);
data.PropertyChanged += (o, e) =>
{
if (e.PropertyName == "LastChanged")
LastChanged = data.LastChanged;
};
}
}
private void Child_DeleteSelf()
{
using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities"))
{
var data = new Documents_CompensationChildCol();
data.Id = ReadProperty<int>(IdProperty);
data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey;
//data.SubjectId = parent.Id;
ctx.ObjectContext.Attach(data);
ctx.ObjectContext.DeleteObject(data);
}
}
#endregion
public void MarkChild()
{
this.MarkAsChild();
}
public void SetNew()
{
Id = 0;
MarkNew();
}
}
[Serializable]
public partial class cDocuments_CompensationChildCol : BusinessListBase<cDocuments_CompensationChildCol, cDocuments_CompensationChild>
{
internal static cDocuments_CompensationChildCol NewDocuments_CompensationChildCol()
{
return DataPortal.CreateChild<cDocuments_CompensationChildCol>();
}
public static cDocuments_CompensationChildCol GetDocuments_CompensationChildCol(IEnumerable<Documents_CompensationChildCol> dataSet)
{
var childList = new cDocuments_CompensationChildCol();
childList.Fetch(dataSet);
return childList;
}
#region Data Access
private void Fetch(IEnumerable<Documents_CompensationChildCol> dataSet)
{
RaiseListChangedEvents = false;
foreach (var data in dataSet)
this.Add(cDocuments_CompensationChild.GetDocuments_CompensationChild(data));
RaiseListChangedEvents = true;
}
#endregion //Data Access
}
}
| |
// 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A pool in the Azure Batch service.
/// </summary>
public partial class CloudPool : ITransportObjectProvider<Models.PoolAddParameter>, IInheritedBehaviors, IPropertyMetadata
{
private class PropertyContainer : PropertyCollection
{
public readonly PropertyAccessor<Common.AllocationState?> AllocationStateProperty;
public readonly PropertyAccessor<DateTime?> AllocationStateTransitionTimeProperty;
public readonly PropertyAccessor<IList<ApplicationPackageReference>> ApplicationPackageReferencesProperty;
public readonly PropertyAccessor<bool?> AutoScaleEnabledProperty;
public readonly PropertyAccessor<TimeSpan?> AutoScaleEvaluationIntervalProperty;
public readonly PropertyAccessor<string> AutoScaleFormulaProperty;
public readonly PropertyAccessor<AutoScaleRun> AutoScaleRunProperty;
public readonly PropertyAccessor<IList<CertificateReference>> CertificateReferencesProperty;
public readonly PropertyAccessor<CloudServiceConfiguration> CloudServiceConfigurationProperty;
public readonly PropertyAccessor<DateTime?> CreationTimeProperty;
public readonly PropertyAccessor<int?> CurrentDedicatedProperty;
public readonly PropertyAccessor<string> DisplayNameProperty;
public readonly PropertyAccessor<string> ETagProperty;
public readonly PropertyAccessor<string> IdProperty;
public readonly PropertyAccessor<bool?> InterComputeNodeCommunicationEnabledProperty;
public readonly PropertyAccessor<DateTime?> LastModifiedProperty;
public readonly PropertyAccessor<int?> MaxTasksPerComputeNodeProperty;
public readonly PropertyAccessor<IList<MetadataItem>> MetadataProperty;
public readonly PropertyAccessor<NetworkConfiguration> NetworkConfigurationProperty;
public readonly PropertyAccessor<ResizeError> ResizeErrorProperty;
public readonly PropertyAccessor<TimeSpan?> ResizeTimeoutProperty;
public readonly PropertyAccessor<StartTask> StartTaskProperty;
public readonly PropertyAccessor<Common.PoolState?> StateProperty;
public readonly PropertyAccessor<DateTime?> StateTransitionTimeProperty;
public readonly PropertyAccessor<PoolStatistics> StatisticsProperty;
public readonly PropertyAccessor<int?> TargetDedicatedProperty;
public readonly PropertyAccessor<TaskSchedulingPolicy> TaskSchedulingPolicyProperty;
public readonly PropertyAccessor<string> UrlProperty;
public readonly PropertyAccessor<VirtualMachineConfiguration> VirtualMachineConfigurationProperty;
public readonly PropertyAccessor<string> VirtualMachineSizeProperty;
public PropertyContainer() : base(BindingState.Unbound)
{
this.AllocationStateProperty = this.CreatePropertyAccessor<Common.AllocationState?>("AllocationState", BindingAccess.None);
this.AllocationStateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>("AllocationStateTransitionTime", BindingAccess.None);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor<IList<ApplicationPackageReference>>("ApplicationPackageReferences", BindingAccess.Read | BindingAccess.Write);
this.AutoScaleEnabledProperty = this.CreatePropertyAccessor<bool?>("AutoScaleEnabled", BindingAccess.Read | BindingAccess.Write);
this.AutoScaleEvaluationIntervalProperty = this.CreatePropertyAccessor<TimeSpan?>("AutoScaleEvaluationInterval", BindingAccess.Read | BindingAccess.Write);
this.AutoScaleFormulaProperty = this.CreatePropertyAccessor<string>("AutoScaleFormula", BindingAccess.Read | BindingAccess.Write);
this.AutoScaleRunProperty = this.CreatePropertyAccessor<AutoScaleRun>("AutoScaleRun", BindingAccess.None);
this.CertificateReferencesProperty = this.CreatePropertyAccessor<IList<CertificateReference>>("CertificateReferences", BindingAccess.Read | BindingAccess.Write);
this.CloudServiceConfigurationProperty = this.CreatePropertyAccessor<CloudServiceConfiguration>("CloudServiceConfiguration", BindingAccess.Read | BindingAccess.Write);
this.CreationTimeProperty = this.CreatePropertyAccessor<DateTime?>("CreationTime", BindingAccess.None);
this.CurrentDedicatedProperty = this.CreatePropertyAccessor<int?>("CurrentDedicated", BindingAccess.None);
this.DisplayNameProperty = this.CreatePropertyAccessor<string>("DisplayName", BindingAccess.Read | BindingAccess.Write);
this.ETagProperty = this.CreatePropertyAccessor<string>("ETag", BindingAccess.None);
this.IdProperty = this.CreatePropertyAccessor<string>("Id", BindingAccess.Read | BindingAccess.Write);
this.InterComputeNodeCommunicationEnabledProperty = this.CreatePropertyAccessor<bool?>("InterComputeNodeCommunicationEnabled", BindingAccess.Read | BindingAccess.Write);
this.LastModifiedProperty = this.CreatePropertyAccessor<DateTime?>("LastModified", BindingAccess.None);
this.MaxTasksPerComputeNodeProperty = this.CreatePropertyAccessor<int?>("MaxTasksPerComputeNode", BindingAccess.Read | BindingAccess.Write);
this.MetadataProperty = this.CreatePropertyAccessor<IList<MetadataItem>>("Metadata", BindingAccess.Read | BindingAccess.Write);
this.NetworkConfigurationProperty = this.CreatePropertyAccessor<NetworkConfiguration>("NetworkConfiguration", BindingAccess.Read | BindingAccess.Write);
this.ResizeErrorProperty = this.CreatePropertyAccessor<ResizeError>("ResizeError", BindingAccess.None);
this.ResizeTimeoutProperty = this.CreatePropertyAccessor<TimeSpan?>("ResizeTimeout", BindingAccess.Read | BindingAccess.Write);
this.StartTaskProperty = this.CreatePropertyAccessor<StartTask>("StartTask", BindingAccess.Read | BindingAccess.Write);
this.StateProperty = this.CreatePropertyAccessor<Common.PoolState?>("State", BindingAccess.None);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>("StateTransitionTime", BindingAccess.None);
this.StatisticsProperty = this.CreatePropertyAccessor<PoolStatistics>("Statistics", BindingAccess.None);
this.TargetDedicatedProperty = this.CreatePropertyAccessor<int?>("TargetDedicated", BindingAccess.Read | BindingAccess.Write);
this.TaskSchedulingPolicyProperty = this.CreatePropertyAccessor<TaskSchedulingPolicy>("TaskSchedulingPolicy", BindingAccess.Read | BindingAccess.Write);
this.UrlProperty = this.CreatePropertyAccessor<string>("Url", BindingAccess.None);
this.VirtualMachineConfigurationProperty = this.CreatePropertyAccessor<VirtualMachineConfiguration>("VirtualMachineConfiguration", BindingAccess.Read | BindingAccess.Write);
this.VirtualMachineSizeProperty = this.CreatePropertyAccessor<string>("VirtualMachineSize", BindingAccess.Read | BindingAccess.Write);
}
public PropertyContainer(Models.CloudPool protocolObject) : base(BindingState.Bound)
{
this.AllocationStateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.AllocationState, Common.AllocationState>(protocolObject.AllocationState),
"AllocationState",
BindingAccess.Read);
this.AllocationStateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.AllocationStateTransitionTime,
"AllocationStateTransitionTime",
BindingAccess.Read);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor(
ApplicationPackageReference.ConvertFromProtocolCollection(protocolObject.ApplicationPackageReferences),
"ApplicationPackageReferences",
BindingAccess.Read | BindingAccess.Write);
this.AutoScaleEnabledProperty = this.CreatePropertyAccessor(
protocolObject.EnableAutoScale,
"AutoScaleEnabled",
BindingAccess.Read);
this.AutoScaleEvaluationIntervalProperty = this.CreatePropertyAccessor(
protocolObject.AutoScaleEvaluationInterval,
"AutoScaleEvaluationInterval",
BindingAccess.Read);
this.AutoScaleFormulaProperty = this.CreatePropertyAccessor(
protocolObject.AutoScaleFormula,
"AutoScaleFormula",
BindingAccess.Read);
this.AutoScaleRunProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.AutoScaleRun, o => new AutoScaleRun(o).Freeze()),
"AutoScaleRun",
BindingAccess.Read);
this.CertificateReferencesProperty = this.CreatePropertyAccessor(
CertificateReference.ConvertFromProtocolCollection(protocolObject.CertificateReferences),
"CertificateReferences",
BindingAccess.Read | BindingAccess.Write);
this.CloudServiceConfigurationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.CloudServiceConfiguration, o => new CloudServiceConfiguration(o).Freeze()),
"CloudServiceConfiguration",
BindingAccess.Read);
this.CreationTimeProperty = this.CreatePropertyAccessor(
protocolObject.CreationTime,
"CreationTime",
BindingAccess.Read);
this.CurrentDedicatedProperty = this.CreatePropertyAccessor(
protocolObject.CurrentDedicated,
"CurrentDedicated",
BindingAccess.Read);
this.DisplayNameProperty = this.CreatePropertyAccessor(
protocolObject.DisplayName,
"DisplayName",
BindingAccess.Read);
this.ETagProperty = this.CreatePropertyAccessor(
protocolObject.ETag,
"ETag",
BindingAccess.Read);
this.IdProperty = this.CreatePropertyAccessor(
protocolObject.Id,
"Id",
BindingAccess.Read);
this.InterComputeNodeCommunicationEnabledProperty = this.CreatePropertyAccessor(
protocolObject.EnableInterNodeCommunication,
"InterComputeNodeCommunicationEnabled",
BindingAccess.Read);
this.LastModifiedProperty = this.CreatePropertyAccessor(
protocolObject.LastModified,
"LastModified",
BindingAccess.Read);
this.MaxTasksPerComputeNodeProperty = this.CreatePropertyAccessor(
protocolObject.MaxTasksPerNode,
"MaxTasksPerComputeNode",
BindingAccess.Read);
this.MetadataProperty = this.CreatePropertyAccessor(
MetadataItem.ConvertFromProtocolCollection(protocolObject.Metadata),
"Metadata",
BindingAccess.Read | BindingAccess.Write);
this.NetworkConfigurationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.NetworkConfiguration, o => new NetworkConfiguration(o).Freeze()),
"NetworkConfiguration",
BindingAccess.Read);
this.ResizeErrorProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ResizeError, o => new ResizeError(o).Freeze()),
"ResizeError",
BindingAccess.Read);
this.ResizeTimeoutProperty = this.CreatePropertyAccessor(
protocolObject.ResizeTimeout,
"ResizeTimeout",
BindingAccess.Read);
this.StartTaskProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.StartTask, o => new StartTask(o)),
"StartTask",
BindingAccess.Read | BindingAccess.Write);
this.StateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.PoolState, Common.PoolState>(protocolObject.State),
"State",
BindingAccess.Read);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.StateTransitionTime,
"StateTransitionTime",
BindingAccess.Read);
this.StatisticsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Stats, o => new PoolStatistics(o).Freeze()),
"Statistics",
BindingAccess.Read);
this.TargetDedicatedProperty = this.CreatePropertyAccessor(
protocolObject.TargetDedicated,
"TargetDedicated",
BindingAccess.Read);
this.TaskSchedulingPolicyProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.TaskSchedulingPolicy, o => new TaskSchedulingPolicy(o).Freeze()),
"TaskSchedulingPolicy",
BindingAccess.Read);
this.UrlProperty = this.CreatePropertyAccessor(
protocolObject.Url,
"Url",
BindingAccess.Read);
this.VirtualMachineConfigurationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.VirtualMachineConfiguration, o => new VirtualMachineConfiguration(o).Freeze()),
"VirtualMachineConfiguration",
BindingAccess.Read);
this.VirtualMachineSizeProperty = this.CreatePropertyAccessor(
protocolObject.VmSize,
"VirtualMachineSize",
BindingAccess.Read);
}
}
private PropertyContainer propertyContainer;
private readonly BatchClient parentBatchClient;
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="CloudPool"/> class.
/// </summary>
/// <param name='parentBatchClient'>The parent <see cref="BatchClient"/> to use.</param>
/// <param name='baseBehaviors'>The base behaviors to use.</param>
internal CloudPool(
BatchClient parentBatchClient,
IEnumerable<BatchClientBehavior> baseBehaviors)
{
this.propertyContainer = new PropertyContainer();
this.parentBatchClient = parentBatchClient;
InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors);
}
internal CloudPool(
BatchClient parentBatchClient,
Models.CloudPool protocolObject,
IEnumerable<BatchClientBehavior> baseBehaviors)
{
this.parentBatchClient = parentBatchClient;
InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors);
this.propertyContainer = new PropertyContainer(protocolObject);
}
#endregion Constructors
#region IInheritedBehaviors
/// <summary>
/// Gets or sets a list of behaviors that modify or customize requests to the Batch service
/// made via this <see cref="CloudPool"/>.
/// </summary>
/// <remarks>
/// <para>These behaviors are inherited by child objects.</para>
/// <para>Modifications are applied in the order of the collection. The last write wins.</para>
/// </remarks>
public IList<BatchClientBehavior> CustomBehaviors { get; set; }
#endregion IInheritedBehaviors
#region CloudPool
/// <summary>
/// Gets an <see cref="Common.AllocationState"/> which indicates what node allocation activity is occurring on the
/// pool.
/// </summary>
public Common.AllocationState? AllocationState
{
get { return this.propertyContainer.AllocationStateProperty.Value; }
}
/// <summary>
/// Gets the time at which the pool entered its current <see cref="AllocationState"/>.
/// </summary>
public DateTime? AllocationStateTransitionTime
{
get { return this.propertyContainer.AllocationStateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets or sets a list of application packages to be installed on each compute node in the pool.
/// </summary>
public IList<ApplicationPackageReference> ApplicationPackageReferences
{
get { return this.propertyContainer.ApplicationPackageReferencesProperty.Value; }
set
{
this.propertyContainer.ApplicationPackageReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<ApplicationPackageReference>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets whether the pool size should automatically adjust according to the <see cref="AutoScaleFormula"/>.
/// </summary>
/// <remarks>
/// <para>If false, the <see cref="TargetDedicated"/> property is required, and <see cref="AutoScaleFormula"/> must
/// be null.</para> <para>If true, the <see cref="AutoScaleFormula"/> property is required, and <see cref="TargetDedicated"/>
/// must be null. The pool automatically resizes according to the formula.</para><para>The default value is false.</para>
/// </remarks>
public bool? AutoScaleEnabled
{
get { return this.propertyContainer.AutoScaleEnabledProperty.Value; }
set { this.propertyContainer.AutoScaleEnabledProperty.Value = value; }
}
/// <summary>
/// Gets or sets a time interval at which to automatically adjust the pool size according to the <see cref="AutoScaleFormula"/>.
/// </summary>
/// <remarks>
/// The default value is 15 minutes. The minimum allowed value is 5 minutes.
/// </remarks>
public TimeSpan? AutoScaleEvaluationInterval
{
get { return this.propertyContainer.AutoScaleEvaluationIntervalProperty.Value; }
set { this.propertyContainer.AutoScaleEvaluationIntervalProperty.Value = value; }
}
/// <summary>
/// Gets or sets a formula for the desired number of compute nodes in the pool.
/// </summary>
/// <remarks>
/// <para>For how to write autoscale formulas, see https://azure.microsoft.com/documentation/articles/batch-automatic-scaling/.
/// This property is required if <see cref="AutoScaleEnabled"/> is set to true. It must be null if AutoScaleEnabled
/// is false.</para><para>The formula is checked for validity before the pool is created. If the formula is not valid,
/// an exception is thrown when you try to commit the <see cref="CloudPool"/>.</para>
/// </remarks>
public string AutoScaleFormula
{
get { return this.propertyContainer.AutoScaleFormulaProperty.Value; }
set { this.propertyContainer.AutoScaleFormulaProperty.Value = value; }
}
/// <summary>
/// Gets the results and errors from the last execution of the <see cref="AutoScaleFormula"/>.
/// </summary>
public AutoScaleRun AutoScaleRun
{
get { return this.propertyContainer.AutoScaleRunProperty.Value; }
}
/// <summary>
/// Gets or sets a list of certificates to be installed on each compute node in the pool.
/// </summary>
public IList<CertificateReference> CertificateReferences
{
get { return this.propertyContainer.CertificateReferencesProperty.Value; }
set
{
this.propertyContainer.CertificateReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<CertificateReference>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the <see cref="CloudServiceConfiguration"/> for the pool.
/// </summary>
public CloudServiceConfiguration CloudServiceConfiguration
{
get { return this.propertyContainer.CloudServiceConfigurationProperty.Value; }
set { this.propertyContainer.CloudServiceConfigurationProperty.Value = value; }
}
/// <summary>
/// Gets the creation time for the pool.
/// </summary>
public DateTime? CreationTime
{
get { return this.propertyContainer.CreationTimeProperty.Value; }
}
/// <summary>
/// Gets the number of compute nodes currently in the pool.
/// </summary>
public int? CurrentDedicated
{
get { return this.propertyContainer.CurrentDedicatedProperty.Value; }
}
/// <summary>
/// Gets or sets the display name of the pool.
/// </summary>
public string DisplayName
{
get { return this.propertyContainer.DisplayNameProperty.Value; }
set { this.propertyContainer.DisplayNameProperty.Value = value; }
}
/// <summary>
/// Gets the ETag for the pool.
/// </summary>
public string ETag
{
get { return this.propertyContainer.ETagProperty.Value; }
}
/// <summary>
/// Gets or sets the id of the pool.
/// </summary>
public string Id
{
get { return this.propertyContainer.IdProperty.Value; }
set { this.propertyContainer.IdProperty.Value = value; }
}
/// <summary>
/// Gets or sets whether the pool permits direct communication between its compute nodes.
/// </summary>
/// <remarks>
/// Enabling inter-node communication limits the maximum size of the pool due to deployment restrictions on the nodes
/// of the pool. This may result in the pool not reaching its desired size.
/// </remarks>
public bool? InterComputeNodeCommunicationEnabled
{
get { return this.propertyContainer.InterComputeNodeCommunicationEnabledProperty.Value; }
set { this.propertyContainer.InterComputeNodeCommunicationEnabledProperty.Value = value; }
}
/// <summary>
/// Gets the last modified time of the pool.
/// </summary>
public DateTime? LastModified
{
get { return this.propertyContainer.LastModifiedProperty.Value; }
}
/// <summary>
/// Gets or sets the maximum number of tasks that can run concurrently on a single compute node in the pool.
/// </summary>
/// <remarks>
/// The default value is 1. The maximum value of this setting depends on the size of the compute nodes in the pool
/// (the <see cref="VirtualMachineSize"/> property).
/// </remarks>
public int? MaxTasksPerComputeNode
{
get { return this.propertyContainer.MaxTasksPerComputeNodeProperty.Value; }
set { this.propertyContainer.MaxTasksPerComputeNodeProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of name-value pairs associated with the pool as metadata.
/// </summary>
public IList<MetadataItem> Metadata
{
get { return this.propertyContainer.MetadataProperty.Value; }
set
{
this.propertyContainer.MetadataProperty.Value = ConcurrentChangeTrackedModifiableList<MetadataItem>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the network configuration of the pool.
/// </summary>
public NetworkConfiguration NetworkConfiguration
{
get { return this.propertyContainer.NetworkConfigurationProperty.Value; }
set { this.propertyContainer.NetworkConfigurationProperty.Value = value; }
}
/// <summary>
/// Gets the resize error encountered while performing the last resize on the <see cref="CloudPool"/>. This error
/// is returned only when the Batch service encountered an error while resizing the pool, and when the pool's <see
/// cref="CloudPool.AllocationState"/> is <see cref="AllocationState">Steady</see>.
/// </summary>
public ResizeError ResizeError
{
get { return this.propertyContainer.ResizeErrorProperty.Value; }
}
/// <summary>
/// Gets or sets the timeout for allocation of compute nodes to the pool.
/// </summary>
public TimeSpan? ResizeTimeout
{
get { return this.propertyContainer.ResizeTimeoutProperty.Value; }
set { this.propertyContainer.ResizeTimeoutProperty.Value = value; }
}
/// <summary>
/// Gets or sets a task to run on each compute node as it joins the pool. The task runs when the node is added to
/// the pool or when the node is restarted.
/// </summary>
public StartTask StartTask
{
get { return this.propertyContainer.StartTaskProperty.Value; }
set { this.propertyContainer.StartTaskProperty.Value = value; }
}
/// <summary>
/// Gets the current state of the pool.
/// </summary>
public Common.PoolState? State
{
get { return this.propertyContainer.StateProperty.Value; }
}
/// <summary>
/// Gets the time at which the pool entered its current state.
/// </summary>
public DateTime? StateTransitionTime
{
get { return this.propertyContainer.StateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets the resource usage statistics for the pool.
/// </summary>
/// <remarks>
/// This property is populated only if the <see cref="CloudPool"/> was retrieved with an <see cref="ODATADetailLevel.ExpandClause"/>
/// including the 'stats' attribute; otherwise it is null.
/// </remarks>
public PoolStatistics Statistics
{
get { return this.propertyContainer.StatisticsProperty.Value; }
}
/// <summary>
/// Gets or sets the desired number of compute nodes in the pool.
/// </summary>
/// <remarks>
/// This property must be null if <see cref="AutoScaleEnabled"/> is set to true. It is required if AutoScaleEnabled
/// is set to false.
/// </remarks>
public int? TargetDedicated
{
get { return this.propertyContainer.TargetDedicatedProperty.Value; }
set { this.propertyContainer.TargetDedicatedProperty.Value = value; }
}
/// <summary>
/// Gets or sets how tasks are distributed among compute nodes in the pool.
/// </summary>
public TaskSchedulingPolicy TaskSchedulingPolicy
{
get { return this.propertyContainer.TaskSchedulingPolicyProperty.Value; }
set { this.propertyContainer.TaskSchedulingPolicyProperty.Value = value; }
}
/// <summary>
/// Gets the URL of the pool.
/// </summary>
public string Url
{
get { return this.propertyContainer.UrlProperty.Value; }
}
/// <summary>
/// Gets or sets the <see cref="VirtualMachineConfiguration"/> of the pool.
/// </summary>
public VirtualMachineConfiguration VirtualMachineConfiguration
{
get { return this.propertyContainer.VirtualMachineConfigurationProperty.Value; }
set { this.propertyContainer.VirtualMachineConfigurationProperty.Value = value; }
}
/// <summary>
/// Gets or sets the size of the virtual machines in the pool. All virtual machines in a pool are the same size.
/// </summary>
/// <remarks>
/// <para>For information about available sizes of virtual machines for Cloud Services pools (pools created with
/// a <see cref="CloudServiceConfiguration"/>), see https://azure.microsoft.com/documentation/articles/cloud-services-sizes-specs/.
/// Batch supports all Cloud Services VM sizes except ExtraSmall.</para><para>For information about available VM
/// sizes for pools using images from the Virtual Machines Marketplace (pools created with a <see cref="VirtualMachineConfiguration"/>)
/// see https://azure.microsoft.com/documentation/articles/virtual-machines-linux-sizes/ or https://azure.microsoft.com/documentation/articles/virtual-machines-windows-sizes/.
/// Batch supports all Azure VM sizes except STANDARD_A0 and those with premium storage (for example STANDARD_GS,
/// STANDARD_DS, and STANDARD_DSV2 series).</para>
/// </remarks>
public string VirtualMachineSize
{
get { return this.propertyContainer.VirtualMachineSizeProperty.Value; }
set { this.propertyContainer.VirtualMachineSizeProperty.Value = value; }
}
#endregion // CloudPool
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
get { return this.propertyContainer.HasBeenModified; }
}
bool IReadOnly.IsReadOnly
{
get { return this.propertyContainer.IsReadOnly; }
set { this.propertyContainer.IsReadOnly = value; }
}
#endregion //IPropertyMetadata
#region Internal/private methods
/// <summary>
/// Return a protocol object of the requested type.
/// </summary>
/// <returns>The protocol object of the requested type.</returns>
Models.PoolAddParameter ITransportObjectProvider<Models.PoolAddParameter>.GetTransportObject()
{
Models.PoolAddParameter result = new Models.PoolAddParameter()
{
ApplicationPackageReferences = UtilitiesInternal.ConvertToProtocolCollection(this.ApplicationPackageReferences),
EnableAutoScale = this.AutoScaleEnabled,
AutoScaleEvaluationInterval = this.AutoScaleEvaluationInterval,
AutoScaleFormula = this.AutoScaleFormula,
CertificateReferences = UtilitiesInternal.ConvertToProtocolCollection(this.CertificateReferences),
CloudServiceConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.CloudServiceConfiguration, (o) => o.GetTransportObject()),
DisplayName = this.DisplayName,
Id = this.Id,
EnableInterNodeCommunication = this.InterComputeNodeCommunicationEnabled,
MaxTasksPerNode = this.MaxTasksPerComputeNode,
Metadata = UtilitiesInternal.ConvertToProtocolCollection(this.Metadata),
NetworkConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.NetworkConfiguration, (o) => o.GetTransportObject()),
ResizeTimeout = this.ResizeTimeout,
StartTask = UtilitiesInternal.CreateObjectWithNullCheck(this.StartTask, (o) => o.GetTransportObject()),
TargetDedicated = this.TargetDedicated,
TaskSchedulingPolicy = UtilitiesInternal.CreateObjectWithNullCheck(this.TaskSchedulingPolicy, (o) => o.GetTransportObject()),
VirtualMachineConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.VirtualMachineConfiguration, (o) => o.GetTransportObject()),
VmSize = this.VirtualMachineSize,
};
return result;
}
#endregion // Internal/private methods
}
}
| |
// 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 Xunit;
namespace System.Linq.Tests
{
public class LastTests : EnumerableTests
{
[Fact]
public void SameResultsRepeatCallsIntQuery()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > int.MinValue
select x;
Assert.Equal(q.Last(), q.Last());
}
[Fact]
public void SameResultsRepeatCallsStringQuery()
{
var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", string.Empty }
where !string.IsNullOrEmpty(x)
select x;
Assert.Equal(q.Last(), q.Last());
}
public void TestEmptyIList<T>()
{
T[] source = { };
Assert.NotNull(source as IList<T>);
Assert.Throws<InvalidOperationException>(() => source.RunOnce().Last());
}
[Fact]
public void EmptyIListT()
{
TestEmptyIList<int>();
TestEmptyIList<string>();
TestEmptyIList<DateTime>();
TestEmptyIList<LastTests>();
}
[Fact]
public void IListTOneElement()
{
int[] source = { 5 };
int expected = 5;
Assert.NotNull(source as IList<int>);
Assert.Equal(expected, source.Last());
}
[Fact]
public void IListTManyElementsLastIsDefault()
{
int?[] source = { -10, 2, 4, 3, 0, 2, null };
int? expected = null;
Assert.IsAssignableFrom<IList<int?>>(source);
Assert.Equal(expected, source.Last());
}
[Fact]
public void IListTManyElementsLastIsNotDefault()
{
int?[] source = { -10, 2, 4, 3, 0, 2, null, 19 };
int? expected = 19;
Assert.IsAssignableFrom<IList<int?>>(source);
Assert.Equal(expected, source.Last());
}
private static IEnumerable<T> EmptySource<T>()
{
yield break;
}
private static void TestEmptyNotIList<T>()
{
var source = EmptySource<T>();
Assert.Null(source as IList<T>);
Assert.Throws<InvalidOperationException>(() => source.RunOnce().Last());
}
[Fact]
public void EmptyNotIListT()
{
TestEmptyNotIList<int>();
TestEmptyNotIList<string>();
TestEmptyNotIList<DateTime>();
TestEmptyNotIList<LastTests>();
}
[Fact]
public void OneElementNotIListT()
{
IEnumerable<int> source = NumberRangeGuaranteedNotCollectionType(-5, 1);
int expected = -5;
Assert.Null(source as IList<int>);
Assert.Equal(expected, source.Last());
}
[Fact]
public void ManyElementsNotIListT()
{
IEnumerable<int> source = NumberRangeGuaranteedNotCollectionType(3, 10);
int expected = 12;
Assert.Null(source as IList<int>);
Assert.Equal(expected, source.Last());
}
[Fact]
public void IListEmptySourcePredicate()
{
int[] source = { };
Assert.Throws<InvalidOperationException>(() => source.Last(x => true));
Assert.Throws<InvalidOperationException>(() => source.Last(x => false));
}
[Fact]
public void OneElementIListTruePredicate()
{
int[] source = { 4 };
Func<int, bool> predicate = IsEven;
int expected = 4;
Assert.Equal(expected, source.Last(predicate));
}
[Fact]
public void ManyElementsIListPredicateFalseForAll()
{
int[] source = { 9, 5, 1, 3, 17, 21 };
Func<int, bool> predicate = IsEven;
Assert.Throws<InvalidOperationException>(() => source.Last(predicate));
}
[Fact]
public void IListPredicateTrueOnlyForLast()
{
int[] source = { 9, 5, 1, 3, 17, 21, 50 };
Func<int, bool> predicate = IsEven;
int expected = 50;
Assert.Equal(expected, source.Last(predicate));
}
[Fact]
public void IListPredicateTrueForSome()
{
int[] source = { 3, 7, 10, 7, 9, 2, 11, 18, 13, 9 };
Func<int, bool> predicate = IsEven;
int expected = 18;
Assert.Equal(expected, source.Last(predicate));
}
[Fact]
public void IListPredicateTrueForSomeRunOnce()
{
int[] source = { 3, 7, 10, 7, 9, 2, 11, 18, 13, 9 };
Func<int, bool> predicate = IsEven;
int expected = 18;
Assert.Equal(expected, source.RunOnce().Last(predicate));
}
[Fact]
public void NotIListIListEmptySourcePredicate()
{
IEnumerable<int> source = Enumerable.Range(1, 0);
Assert.Throws<InvalidOperationException>(() => source.Last(x => true));
Assert.Throws<InvalidOperationException>(() => source.Last(x => false));
}
[Fact]
public void OneElementNotIListTruePredicate()
{
IEnumerable<int> source = NumberRangeGuaranteedNotCollectionType(4, 1);
Func<int, bool> predicate = IsEven;
int expected = 4;
Assert.Equal(expected, source.Last(predicate));
}
[Fact]
public void ManyElementsNotIListPredicateFalseForAll()
{
IEnumerable<int> source = ForceNotCollection(new int[] { 9, 5, 1, 3, 17, 21 });
Func<int, bool> predicate = IsEven;
Assert.Throws<InvalidOperationException>(() => source.Last(predicate));
}
[Fact]
public void NotIListPredicateTrueOnlyForLast()
{
IEnumerable<int> source = ForceNotCollection(new int[] { 9, 5, 1, 3, 17, 21, 50 });
Func<int, bool> predicate = IsEven;
int expected = 50;
Assert.Equal(expected, source.Last(predicate));
}
[Fact]
public void NotIListPredicateTrueForSome()
{
IEnumerable<int> source = ForceNotCollection(new int[] { 3, 7, 10, 7, 9, 2, 11, 18, 13, 9 });
Func<int, bool> predicate = IsEven;
int expected = 18;
Assert.Equal(expected, source.Last(predicate));
}
[Fact]
public void NotIListPredicateTrueForSomeRunOnce()
{
IEnumerable<int> source = ForceNotCollection(new int[] { 3, 7, 10, 7, 9, 2, 11, 18, 13, 9 });
Func<int, bool> predicate = IsEven;
int expected = 18;
Assert.Equal(expected, source.RunOnce().Last(predicate));
}
[Fact]
public void NullSource()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Last());
}
[Fact]
public void NullSourcePredicateUsed()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Last(i => i != 2));
}
[Fact]
public void NullPredicate()
{
Func<int, bool> predicate = null;
AssertExtensions.Throws<ArgumentNullException>("predicate", () => Enumerable.Range(0, 3).Last(predicate));
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using EnvDTE;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using NuGet.VisualStudio.Resources;
namespace NuGet.VisualStudio
{
public class VsPackageManager : PackageManager, IVsPackageManager
{
private readonly ISharedPackageRepository _sharedRepository;
private readonly IDictionary<string, IProjectManager> _projects;
private readonly ISolutionManager _solutionManager;
private readonly IFileSystemProvider _fileSystemProvider;
private readonly IDeleteOnRestartManager _deleteOnRestartManager;
private readonly VsPackageInstallerEvents _packageEvents;
private bool _bindingRedirectEnabled = true;
public VsPackageManager(ISolutionManager solutionManager,
IPackageRepository sourceRepository,
IFileSystemProvider fileSystemProvider,
IFileSystem fileSystem,
ISharedPackageRepository sharedRepository,
IDeleteOnRestartManager deleteOnRestartManager,
VsPackageInstallerEvents packageEvents)
: base(sourceRepository, new DefaultPackagePathResolver(fileSystem), fileSystem, sharedRepository)
{
_solutionManager = solutionManager;
_sharedRepository = sharedRepository;
_packageEvents = packageEvents;
_fileSystemProvider = fileSystemProvider;
_deleteOnRestartManager = deleteOnRestartManager;
_projects = new Dictionary<string, IProjectManager>(StringComparer.OrdinalIgnoreCase);
}
public bool BindingRedirectEnabled
{
get { return _bindingRedirectEnabled; }
set { _bindingRedirectEnabled = value; }
}
internal void EnsureCached(Project project)
{
if (_projects.ContainsKey(project.UniqueName))
{
return;
}
_projects[project.UniqueName] = CreateProjectManager(project);
}
public virtual IProjectManager GetProjectManager(Project project)
{
EnsureCached(project);
IProjectManager projectManager;
bool projectExists = _projects.TryGetValue(project.UniqueName, out projectManager);
Debug.Assert(projectExists, "Unknown project");
return projectManager;
}
private IProjectManager CreateProjectManager(Project project)
{
// Create the project system
IProjectSystem projectSystem = VsProjectSystemFactory.CreateProjectSystem(project, _fileSystemProvider);
var repository = new PackageReferenceRepository(projectSystem, _sharedRepository);
// Ensure the logger is null while registering the repository
FileSystem.Logger = null;
Logger = null;
// Ensure that this repository is registered with the shared repository if it needs to be
repository.RegisterIfNecessary();
// The source repository of the project is an aggregate since it might need to look for all
// available packages to perform updates on dependent packages
var sourceRepository = CreateProjectManagerSourceRepository();
var projectManager = new ProjectManager(sourceRepository, PathResolver, projectSystem, repository);
// The package reference repository also provides constraints for packages (via the allowedVersions attribute)
projectManager.ConstraintProvider = repository;
return projectManager;
}
public void InstallPackage(
IEnumerable<Project> projects,
IPackage package,
IEnumerable<PackageOperation> operations,
bool ignoreDependencies,
bool allowPrereleaseVersions,
ILogger logger,
IPackageOperationEventListener packageOperationEventListener)
{
if (package == null)
{
throw new ArgumentNullException("package");
}
if (operations == null)
{
throw new ArgumentNullException("operations");
}
if (projects == null)
{
throw new ArgumentNullException("projects");
}
ExecuteOperationsWithPackage(
projects,
package,
operations,
projectManager => AddPackageReference(projectManager, package.Id, package.Version, ignoreDependencies, allowPrereleaseVersions),
logger,
packageOperationEventListener);
}
public virtual void InstallPackage(
IProjectManager projectManager,
string packageId,
SemanticVersion version,
bool ignoreDependencies,
bool allowPrereleaseVersions,
ILogger logger)
{
InstallPackage(projectManager, packageId, version, ignoreDependencies, allowPrereleaseVersions,
skipAssemblyReferences: false, logger: logger);
}
public void InstallPackage(
IProjectManager projectManager,
string packageId,
SemanticVersion version,
bool ignoreDependencies,
bool allowPrereleaseVersions,
bool skipAssemblyReferences,
ILogger logger)
{
InitializeLogger(logger, projectManager);
IPackage package = PackageHelper.ResolvePackage(SourceRepository, LocalRepository, packageId, version, allowPrereleaseVersions);
if (skipAssemblyReferences)
{
package = new SkipAssemblyReferencesPackage(package);
}
RunSolutionAction(() =>
{
InstallPackage(
package,
projectManager != null ? projectManager.Project.TargetFramework : null,
ignoreDependencies,
allowPrereleaseVersions);
AddPackageReference(projectManager, package, ignoreDependencies, allowPrereleaseVersions);
AddSolutionPackageConfigEntry(package);
});
}
public void InstallPackage(IProjectManager projectManager, IPackage package, IEnumerable<PackageOperation> operations, bool ignoreDependencies,
bool allowPrereleaseVersions, ILogger logger)
{
if (package == null)
{
throw new ArgumentNullException("package");
}
if (operations == null)
{
throw new ArgumentNullException("operations");
}
ExecuteOperationsWithPackage(
projectManager,
package,
operations,
() => AddPackageReference(projectManager, package.Id, package.Version, ignoreDependencies, allowPrereleaseVersions),
logger);
}
public void UninstallPackage(IProjectManager projectManager, string packageId, SemanticVersion version, bool forceRemove, bool removeDependencies)
{
UninstallPackage(projectManager, packageId, version, forceRemove, removeDependencies, NullLogger.Instance);
}
public virtual void UninstallPackage(IProjectManager projectManager, string packageId, SemanticVersion version, bool forceRemove, bool removeDependencies, ILogger logger)
{
EventHandler<PackageOperationEventArgs> uninstallingHandler =
(sender, e) => _packageEvents.NotifyUninstalling(e);
EventHandler<PackageOperationEventArgs> uninstalledHandler =
(sender, e) => _packageEvents.NotifyUninstalled(e);
try
{
InitializeLogger(logger, projectManager);
bool appliesToProject;
IPackage package = FindLocalPackage(projectManager,
packageId,
version,
CreateAmbiguousUninstallException,
out appliesToProject);
PackageUninstalling += uninstallingHandler;
PackageUninstalled += uninstalledHandler;
if (appliesToProject)
{
RemovePackageReference(projectManager, packageId, forceRemove, removeDependencies);
}
else
{
UninstallPackage(package, forceRemove, removeDependencies);
}
}
finally
{
PackageUninstalling -= uninstallingHandler;
PackageUninstalled -= uninstalledHandler;
}
}
public void UpdatePackage(
IEnumerable<Project> projects,
IPackage package,
IEnumerable<PackageOperation> operations,
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger,
IPackageOperationEventListener packageOperationEventListener)
{
if (operations == null)
{
throw new ArgumentNullException("operations");
}
if (projects == null)
{
throw new ArgumentNullException("projects");
}
ExecuteOperationsWithPackage(
projects,
package,
operations,
projectManager => UpdatePackageReference(projectManager, package.Id, package.Version, updateDependencies, allowPrereleaseVersions),
logger,
packageOperationEventListener);
}
public virtual void UpdatePackageToSpecificVersion(IProjectManager projectManager, string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger)
{
UpdatePackage(projectManager,
packageId,
() => UpdatePackageReference(projectManager, packageId, version, updateDependencies, allowPrereleaseVersions),
() => SourceRepository.FindPackage(packageId, version, allowPrereleaseVersions, allowUnlisted: false),
updateDependencies,
allowPrereleaseVersions,
logger);
}
private void UpdatePackage(IProjectManager projectManager, string packageId, Action projectAction, Func<IPackage> resolvePackage, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger)
{
try
{
InitializeLogger(logger, projectManager);
bool appliesToProject;
IPackage package = FindLocalPackageForUpdate(projectManager, packageId, out appliesToProject);
// Find the package we're going to update to
IPackage newPackage = resolvePackage();
if (newPackage != null && package.Version != newPackage.Version)
{
if (appliesToProject)
{
RunSolutionAction(projectAction);
}
else
{
// We might be updating a solution only package
UpdatePackage(newPackage, updateDependencies, allowPrereleaseVersions);
}
}
else
{
Logger.Log(MessageLevel.Info, VsResources.NoUpdatesAvailable, packageId);
}
}
finally
{
ClearLogger(projectManager);
}
}
public void UpdatePackage(IProjectManager projectManager, IPackage package, IEnumerable<PackageOperation> operations, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger)
{
if (package == null)
{
throw new ArgumentNullException("package");
}
if (operations == null)
{
throw new ArgumentNullException("operations");
}
ExecuteOperationsWithPackage(projectManager, package, operations, () => UpdatePackageReference(projectManager, package.Id, package.Version, updateDependencies, allowPrereleaseVersions), logger);
}
public void UpdatePackage(string packageId, IVersionSpec versionSpec, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
UpdatePackage(packageId,
projectManager => UpdatePackageReference(projectManager, packageId, versionSpec, updateDependencies, allowPrereleaseVersions),
() => SourceRepository.FindPackage(packageId, versionSpec, allowPrereleaseVersions, allowUnlisted: false),
updateDependencies,
allowPrereleaseVersions,
logger,
eventListener);
}
public void UpdatePackageToSpecificVersion(string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
UpdatePackage(packageId,
projectManager => UpdatePackageReference(projectManager, packageId, version, updateDependencies, allowPrereleaseVersions),
() => SourceRepository.FindPackage(packageId, version, allowPrereleaseVersions, allowUnlisted: false),
updateDependencies,
allowPrereleaseVersions,
logger,
eventListener);
}
public void UpdatePackages(PackageUpdateMode updateMode, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
UpdatePackages(packageRepository: LocalRepository, updateMode: updateMode, updateDependencies: updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger, eventListener: eventListener);
}
public void UpdatePackages(IProjectManager projectManager, PackageUpdateMode updateMode, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger)
{
UpdatePackages(projectManager, updateDependencies, updateMode: updateMode, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger);
}
public void UpdatePackage(string packageId, PackageUpdateMode updateMode, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
UpdatePackage(packageId,
projectManager => UpdatePackageReference(projectManager, packageId, GetUpgradeVersionSpec(projectManager, packageId, updateMode), updateDependencies, allowPrereleaseVersions),
() => SourceRepository.FindPackage(packageId, GetUpgradeVersionSpec(packageId, updateMode), allowPrereleaseVersions: false, allowUnlisted: false),
updateDependencies,
allowPrereleaseVersions,
logger,
eventListener);
}
public void UpdatePackage(IProjectManager projectManager, string packageId, PackageUpdateMode updateMode, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger)
{
UpdatePackage(projectManager,
packageId,
() => UpdatePackageReference(projectManager, packageId, GetUpgradeVersionSpec(projectManager, packageId, updateMode), updateDependencies, allowPrereleaseVersions),
() => SourceRepository.FindPackage(packageId, GetUpgradeVersionSpec(packageId, updateMode), allowPrereleaseVersions: false, allowUnlisted: false),
updateDependencies,
allowPrereleaseVersions,
logger);
}
// Reinstall all packages in all projects
public void ReinstallPackages(
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger,
IPackageOperationEventListener eventListener)
{
UpdatePackages(
LocalRepository,
package => ReinstallPackage(
package.Id,
updateDependencies: updateDependencies,
allowPrereleaseVersions: allowPrereleaseVersions,
logger: logger,
eventListener: eventListener),
logger);
}
// Reinstall all packages in the specified project
public void ReinstallPackages(
IProjectManager projectManager,
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger)
{
UpdatePackages(
projectManager.LocalRepository,
package => ReinstallPackageInProject(projectManager, package, updateDependencies, allowPrereleaseVersions, logger),
logger);
}
/// <summary>
/// Reinstall the specified package in all projects.
/// </summary>
public void ReinstallPackage(
string packageId,
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger,
IPackageOperationEventListener eventListener)
{
bool appliesToProject;
IPackage package = FindLocalPackage(packageId, out appliesToProject);
if (appliesToProject)
{
ReinstallPackageToAllProjects(packageId, updateDependencies, allowPrereleaseVersions, logger, eventListener);
}
else
{
ReinstallSolutionPackage(package, updateDependencies, allowPrereleaseVersions, logger);
}
}
/// <summary>
/// Reinstall the specified package in the specified project.
/// </summary>
public void ReinstallPackage(
IProjectManager projectManager,
string packageId,
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger)
{
bool appliesToProject;
IPackage package = FindLocalPackageForUpdate(projectManager, packageId, out appliesToProject);
if (appliesToProject)
{
ReinstallPackageInProject(projectManager, package, updateDependencies, allowPrereleaseVersions, logger);
}
else
{
ReinstallSolutionPackage(package, updateDependencies, allowPrereleaseVersions, logger);
}
}
/// <summary>
/// Reinstall the specified package in the specified project, taking care of logging too.
/// </summary>
private void ReinstallPackageInProject(
IProjectManager projectManager,
IPackage package,
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger)
{
logger = logger ?? NullLogger.Instance;
try
{
InitializeLogger(logger, projectManager);
logger.Log(MessageLevel.Info, VsResources.ReinstallProjectPackage, package, projectManager.Project.ProjectName);
// Before we start reinstalling, need to make sure the package exists in the source repository.
// Otherwise, the package will be uninstalled and can't be reinstalled.
if (SourceRepository.Exists(package))
{
RunSolutionAction(
() =>
{
UninstallPackage(
projectManager,
package.Id,
package.Version,
forceRemove: true,
removeDependencies: updateDependencies,
logger: logger);
InstallPackage(
projectManager,
package.Id,
package.Version,
ignoreDependencies: !updateDependencies,
allowPrereleaseVersions: allowPrereleaseVersions || !package.IsReleaseVersion(),
logger: logger);
});
}
else
{
logger.Log(
MessageLevel.Warning,
VsResources.PackageRestoreSkipForProject,
package.GetFullName(),
projectManager.Project.ProjectName);
}
}
finally
{
ClearLogger(projectManager);
}
}
// Reinstall one package in all projects.
// We need to uninstall the package from all projects BEFORE
// reinstalling it back, so that the package will be refreshed from source repository.
private void ReinstallPackageToAllProjects(
string packageId,
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger,
IPackageOperationEventListener eventListener)
{
logger = logger ?? NullLogger.Instance;
eventListener = eventListener ?? NullPackageOperationEventListener.Instance;
var projectsHasPackage = new Dictionary<Project, SemanticVersion>();
var versionsChecked = new Dictionary<SemanticVersion, bool>();
// first uninstall from all projects that has the package installed
RunActionOnProjects(
_solutionManager.GetProjects(),
project =>
{
IProjectManager projectManager = GetProjectManager(project);
// find the package version installed in this project
IPackage projectPackage = projectManager.LocalRepository.FindPackage(packageId);
if (projectPackage != null)
{
bool packageExistInSource;
if (!versionsChecked.TryGetValue(projectPackage.Version, out packageExistInSource))
{
// version has not been checked, so check it here
packageExistInSource = SourceRepository.Exists(packageId, projectPackage.Version);
// mark the version as checked so that we don't have to check again if we
// encounter another project with the same version.
versionsChecked[projectPackage.Version] = packageExistInSource;
}
if (packageExistInSource)
{
// save the version installed in this project so that we can restore the correct version later
projectsHasPackage.Add(project, projectPackage.Version);
UninstallPackage(
projectManager,
packageId,
version: null,
forceRemove: true,
removeDependencies: updateDependencies,
logger: logger);
}
else
{
logger.Log(
MessageLevel.Warning,
VsResources.PackageRestoreSkipForProject,
projectPackage.GetFullName(),
project.Name);
}
}
},
logger,
eventListener);
// now reinstall back to all the affected projects
RunActionOnProjects(
projectsHasPackage.Keys,
project =>
{
var projectManager = GetProjectManager(project);
if (!projectManager.LocalRepository.Exists(packageId))
{
SemanticVersion oldVersion = projectsHasPackage[project];
InstallPackage(
projectManager,
packageId,
version: oldVersion,
ignoreDependencies: !updateDependencies,
allowPrereleaseVersions: allowPrereleaseVersions || !String.IsNullOrEmpty(oldVersion.SpecialVersion),
logger: logger);
}
},
logger,
eventListener);
}
private void ReinstallSolutionPackage(
IPackage package,
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger)
{
logger = logger ?? NullLogger.Instance;
try
{
InitializeLogger(logger);
logger.Log(MessageLevel.Info, VsResources.ReinstallSolutionPackage, package);
if (SourceRepository.Exists(package))
{
RunSolutionAction(
() =>
{
UninstallPackage(package, forceRemove: true, removeDependencies: !updateDependencies);
InstallPackage(package, ignoreDependencies: !updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions || !package.IsReleaseVersion());
});
}
else
{
logger.Log(
MessageLevel.Warning,
VsResources.PackageRestoreSkipForSolution,
package.GetFullName());
}
}
finally
{
ClearLogger();
}
}
protected override void ExecuteUninstall(IPackage package)
{
// Check if the package is in use before removing it
if (!_sharedRepository.IsReferenced(package.Id, package.Version))
{
base.ExecuteUninstall(package);
}
}
private IPackage FindLocalPackageForUpdate(IProjectManager projectManager, string packageId, out bool appliesToProject)
{
return FindLocalPackage(projectManager, packageId, null /* version */, CreateAmbiguousUpdateException, out appliesToProject);
}
private IPackage FindLocalPackage(IProjectManager projectManager,
string packageId,
SemanticVersion version,
Func<IProjectManager, IList<IPackage>, Exception> getAmbiguousMatchException,
out bool appliesToProject)
{
IPackage package = null;
bool existsInProject = false;
appliesToProject = false;
if (projectManager != null)
{
// Try the project repository first
package = projectManager.LocalRepository.FindPackage(packageId, version);
existsInProject = package != null;
}
// Fallback to the solution repository (it might be a solution only package)
if (package == null)
{
if (version != null)
{
// Get the exact package
package = LocalRepository.FindPackage(packageId, version);
}
else
{
// Get all packages by this name to see if we find an ambiguous match
var packages = LocalRepository.FindPackagesById(packageId).ToList();
if (packages.Count > 1)
{
throw getAmbiguousMatchException(projectManager, packages);
}
// Pick the only one of default if none match
package = packages.SingleOrDefault();
}
}
// Can't find the package in the solution or in the project then fail
if (package == null)
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackage, packageId));
}
appliesToProject = IsProjectLevel(package);
if (appliesToProject)
{
if (!existsInProject)
{
if (_sharedRepository.IsReferenced(package.Id, package.Version))
{
// If the package doesn't exist in the project and is referenced by other projects
// then fail.
if (projectManager != null)
{
if (version == null)
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackageInProject,
package.Id,
projectManager.Project.ProjectName));
}
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackageInProject,
package.GetFullName(),
projectManager.Project.ProjectName));
}
}
else
{
// The operation applies to solution level since it's not installed in the current project
// but it is installed in some other project
appliesToProject = false;
}
}
}
// Can't have a project level operation if no project was specified
if (appliesToProject && projectManager == null)
{
throw new InvalidOperationException(VsResources.ProjectNotSpecified);
}
return package;
}
private IPackage FindLocalPackage(string packageId, out bool appliesToProject)
{
// It doesn't matter if there are multiple versions of the package installed at solution level,
// we just want to know that one exists.
var packages = LocalRepository.FindPackagesById(packageId).ToList();
// Can't find the package in the solution.
if (!packages.Any())
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackage, packageId));
}
IPackage package = packages.FirstOrDefault();
appliesToProject = IsProjectLevel(package);
if (!appliesToProject)
{
if (packages.Count > 1)
{
throw CreateAmbiguousUpdateException(projectManager: null, packages: packages);
}
}
else if (!_sharedRepository.IsReferenced(package.Id, package.Version))
{
// If this package applies to a project but isn't installed in any project then
// it's probably a borked install.
throw new PackageNotInstalledException(
String.Format(CultureInfo.CurrentCulture,
VsResources.PackageNotInstalledInAnyProject, packageId));
}
return package;
}
/// <summary>
/// Check to see if this package applies to a project based on 2 criteria:
/// 1. The package has project content (i.e. content that can be applied to a project lib or content files)
/// 2. The package is referenced by any other project
///
/// This logic will probably fail in one edge case. If there is a meta package that applies to a project
/// that ended up not being installed in any of the projects and it only exists at solution level.
/// If this happens, then we think that the following operation applies to the solution instead of showing an error.
/// To solve that edge case we'd have to walk the graph to find out what the package applies to.
/// </summary>
public bool IsProjectLevel(IPackage package)
{
return package.HasProjectContent() || _sharedRepository.IsReferenced(package.Id, package.Version);
}
private Exception CreateAmbiguousUpdateException(IProjectManager projectManager, IList<IPackage> packages)
{
if (projectManager != null && packages.Any(IsProjectLevel))
{
return new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackageInProject,
packages[0].Id,
projectManager.Project.ProjectName));
}
return new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.AmbiguousUpdate,
packages[0].Id));
}
private Exception CreateAmbiguousUninstallException(IProjectManager projectManager, IList<IPackage> packages)
{
if (projectManager != null && packages.Any(IsProjectLevel))
{
return new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.AmbiguousProjectLevelUninstal,
packages[0].Id,
projectManager.Project.ProjectName));
}
return new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.AmbiguousUninstall,
packages[0].Id));
}
private void RemovePackageReference(IProjectManager projectManager, string packageId, bool forceRemove, bool removeDependencies)
{
RunProjectAction(projectManager, () => projectManager.RemovePackageReference(packageId, forceRemove, removeDependencies));
}
private void UpdatePackageReference(IProjectManager projectManager, string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions)
{
RunProjectAction(projectManager, () => projectManager.UpdatePackageReference(packageId, version, updateDependencies, allowPrereleaseVersions));
}
private void UpdatePackageReference(IProjectManager projectManager, string packageId, IVersionSpec versionSpec, bool updateDependencies, bool allowPrereleaseVersions)
{
RunProjectAction(projectManager, () => projectManager.UpdatePackageReference(packageId, versionSpec, updateDependencies, allowPrereleaseVersions));
}
private void AddPackageReference(IProjectManager projectManager, string packageId, SemanticVersion version, bool ignoreDependencies, bool allowPrereleaseVersions)
{
RunProjectAction(projectManager, () => projectManager.AddPackageReference(packageId, version, ignoreDependencies, allowPrereleaseVersions));
}
private void AddPackageReference(IProjectManager projectManager, IPackage package, bool ignoreDependencies, bool allowPrereleaseVersions)
{
RunProjectAction(projectManager, () => projectManager.AddPackageReference(package, ignoreDependencies, allowPrereleaseVersions));
}
private void ExecuteOperationsWithPackage(IEnumerable<Project> projects, IPackage package, IEnumerable<PackageOperation> operations, Action<IProjectManager> projectAction, ILogger logger, IPackageOperationEventListener eventListener)
{
if (eventListener == null)
{
eventListener = NullPackageOperationEventListener.Instance;
}
ExecuteOperationsWithPackage(
null,
package,
operations,
() =>
{
bool successfulAtLeastOnce = false;
foreach (var project in projects)
{
try
{
eventListener.OnBeforeAddPackageReference(project);
IProjectManager projectManager = GetProjectManager(project);
InitializeLogger(logger, projectManager);
projectAction(projectManager);
successfulAtLeastOnce = true;
}
catch (Exception ex)
{
eventListener.OnAddPackageReferenceError(project, ex);
}
finally
{
eventListener.OnAfterAddPackageReference(project);
}
}
// Throw an exception only if all the update failed for all projects
// so we rollback any solution level operations that might have happened
if (projects.Any() && !successfulAtLeastOnce)
{
throw new InvalidOperationException(VsResources.OperationFailed);
}
},
logger);
}
private void ExecuteOperationsWithPackage(IProjectManager projectManager, IPackage package, IEnumerable<PackageOperation> operations, Action action, ILogger logger)
{
try
{
InitializeLogger(logger, projectManager);
RunSolutionAction(() =>
{
if (operations.Any())
{
foreach (var operation in operations)
{
Execute(operation);
}
}
else if (LocalRepository.Exists(package))
{
Logger.Log(MessageLevel.Info, VsResources.Log_PackageAlreadyInstalled, package.GetFullName());
}
action();
AddSolutionPackageConfigEntry(package);
});
}
finally
{
ClearLogger(projectManager);
}
}
private Project GetProject(IProjectManager projectManager)
{
// We only support project systems that implement IVsProjectSystem
var vsProjectSystem = projectManager.Project as IVsProjectSystem;
if (vsProjectSystem == null)
{
return null;
}
// Find the project by it's unique name
return _solutionManager.GetProject(vsProjectSystem.UniqueName);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "If we failed to add binding redirects we don't want it to stop the install/update.")]
private void AddBindingRedirects(IProjectManager projectManager)
{
// Find the project by it's unique name
Project project = GetProject(projectManager);
// If we can't find the project or it doesn't support binding redirects then don't add any redirects
if (project == null || !project.SupportsBindingRedirects())
{
return;
}
try
{
RuntimeHelpers.AddBindingRedirects(_solutionManager, project, _fileSystemProvider);
}
catch (Exception e)
{
// If there was an error adding binding redirects then print a warning and continue
Logger.Log(MessageLevel.Warning, String.Format(CultureInfo.CurrentCulture, VsResources.Warning_FailedToAddBindingRedirects, projectManager.Project.ProjectName, e.Message));
}
}
private void InitializeLogger(ILogger logger, IProjectManager projectManager = null)
{
// Setup logging on all of our objects
Logger = logger;
FileSystem.Logger = logger;
if (projectManager != null)
{
projectManager.Logger = logger;
projectManager.Project.Logger = logger;
}
}
private void ClearLogger(IProjectManager projectManager = null)
{
// clear logging on all of our objects
Logger = null;
FileSystem.Logger = null;
if (projectManager != null)
{
projectManager.Logger = null;
projectManager.Project.Logger = null;
}
}
/// <summary>
/// Runs the specified action and rolls back any installed packages if on failure.
/// </summary>
private void RunSolutionAction(Action action)
{
var packagesAdded = new List<IPackage>();
EventHandler<PackageOperationEventArgs> installHandler = (sender, e) =>
{
// Record packages that we are installing so that if one fails, we can rollback
packagesAdded.Add(e.Package);
_packageEvents.NotifyInstalling(e);
};
EventHandler<PackageOperationEventArgs> installedHandler = (sender, e) =>
{
_packageEvents.NotifyInstalled(e);
};
PackageInstalling += installHandler;
PackageInstalled += installedHandler;
try
{
// Execute the action
action();
}
catch
{
if (packagesAdded.Any())
{
// Only print the rollback warning if we have something to rollback
Logger.Log(MessageLevel.Warning, VsResources.Warning_RollingBack);
}
// Don't log anything during the rollback
Logger = null;
// Rollback the install if it fails
Uninstall(packagesAdded);
throw;
}
finally
{
// Remove the event handler
PackageInstalling -= installHandler;
PackageInstalled -= installedHandler;
}
}
/// <summary>
/// Runs the action on projects and log any error that may occur.
/// </summary>
private void RunActionOnProjects(
IEnumerable<Project> projects,
Action<Project> action,
ILogger logger,
IPackageOperationEventListener eventListener)
{
foreach (var project in projects)
{
try
{
eventListener.OnBeforeAddPackageReference(project);
action(project);
}
catch (Exception exception)
{
logger.Log(MessageLevel.Error, ExceptionUtility.Unwrap(exception).Message);
eventListener.OnAddPackageReferenceError(project, exception);
}
finally
{
eventListener.OnAfterAddPackageReference(project);
}
}
}
/// <summary>
/// Runs action on the project manager and rollsback any package installs if it fails.
/// </summary>
private void RunProjectAction(IProjectManager projectManager, Action action)
{
if (projectManager == null)
{
return;
}
// Keep track of what was added and removed
var packagesAdded = new Stack<IPackage>();
var packagesRemoved = new List<IPackage>();
EventHandler<PackageOperationEventArgs> removeHandler = (sender, e) =>
{
packagesRemoved.Add(e.Package);
_packageEvents.NotifyReferenceRemoved(e);
};
EventHandler<PackageOperationEventArgs> addingHandler = (sender, e) =>
{
packagesAdded.Push(e.Package);
_packageEvents.NotifyReferenceAdded(e);
// If this package doesn't exist at solution level (it might not be because of leveling)
// then we need to install it.
if (!LocalRepository.Exists(e.Package))
{
ExecuteInstall(e.Package);
}
};
// Try to get the project for this project manager
Project project = GetProject(projectManager);
IVsProjectBuildSystem build = null;
if (project != null)
{
build = project.ToVsProjectBuildSystem();
}
// Add the handlers
projectManager.PackageReferenceRemoved += removeHandler;
projectManager.PackageReferenceAdding += addingHandler;
try
{
if (build != null)
{
// Start a batch edit so there is no background compilation until we're done
// processing project actions
build.StartBatchEdit();
}
action();
if (BindingRedirectEnabled && projectManager.Project.IsBindingRedirectSupported)
{
// Only add binding redirects if install was successful
AddBindingRedirects(projectManager);
}
}
catch
{
// We need to Remove the handlers here since we're going to attempt
// a rollback and we don't want modify the collections while rolling back.
projectManager.PackageReferenceRemoved -= removeHandler;
projectManager.PackageReferenceAdded -= addingHandler;
// When things fail attempt a rollback
RollbackProjectActions(projectManager, packagesAdded, packagesRemoved);
// Rollback solution packages
Uninstall(packagesAdded);
// Clear removed packages so we don't try to remove them again (small optimization)
packagesRemoved.Clear();
throw;
}
finally
{
if (build != null)
{
// End the batch edit when we are done.
build.EndBatchEdit();
}
// Remove the handlers
projectManager.PackageReferenceRemoved -= removeHandler;
projectManager.PackageReferenceAdding -= addingHandler;
// Remove any packages that would be removed as a result of updating a dependency or the package itself
// We can execute the uninstall directly since we don't need to resolve dependencies again.
Uninstall(packagesRemoved);
}
}
private static void RollbackProjectActions(IProjectManager projectManager, IEnumerable<IPackage> packagesAdded, IEnumerable<IPackage> packagesRemoved)
{
// Disable logging when rolling back project operations
projectManager.Logger = null;
foreach (var package in packagesAdded)
{
// Remove each package that was added
projectManager.RemovePackageReference(package, forceRemove: false, removeDependencies: false);
}
foreach (var package in packagesRemoved)
{
// Add each package that was removed
projectManager.AddPackageReference(package, ignoreDependencies: true, allowPrereleaseVersions: true);
}
}
private void Uninstall(IEnumerable<IPackage> packages)
{
// Packages added to the sequence are added in the order in which they were visited. However for operations on satellite packages to work correctly,
// we need to ensure they are always uninstalled prior to the corresponding core package. To address this, we run it by Reduce which reorders it for us and ensures it
// returns the minimal set of operations required.
var packageOperations = packages.Select(p => new PackageOperation(p, PackageAction.Uninstall))
.Reduce();
foreach (var operation in packageOperations)
{
ExecuteUninstall(operation.Package);
}
}
private void UpdatePackage(string packageId, Action<IProjectManager> projectAction, Func<IPackage> resolvePackage, bool updateDependencies, bool allowPrereleaseVersions,
ILogger logger, IPackageOperationEventListener eventListener)
{
bool appliesToProject;
IPackage package = FindLocalPackage(packageId, out appliesToProject);
if (appliesToProject)
{
eventListener = eventListener ?? NullPackageOperationEventListener.Instance;
foreach (var project in _solutionManager.GetProjects())
{
IProjectManager projectManager = GetProjectManager(project);
try
{
InitializeLogger(logger, projectManager);
if (projectManager.LocalRepository.Exists(packageId))
{
eventListener.OnBeforeAddPackageReference(project);
try
{
RunSolutionAction(() => projectAction(projectManager));
}
catch (Exception e)
{
logger.Log(MessageLevel.Error, ExceptionUtility.Unwrap(e).Message);
eventListener.OnAddPackageReferenceError(project, e);
}
finally
{
eventListener.OnAfterAddPackageReference(project);
}
}
}
finally
{
ClearLogger(projectManager);
}
}
}
else
{
// Find the package we're going to update to
IPackage newPackage = resolvePackage();
if (newPackage != null && package.Version != newPackage.Version)
{
try
{
InitializeLogger(logger, projectManager: null);
// We might be updating a solution only package
UpdatePackage(newPackage, updateDependencies, allowPrereleaseVersions);
}
finally
{
ClearLogger(projectManager: null);
}
}
else
{
logger.Log(MessageLevel.Info, VsResources.NoUpdatesAvailable, packageId);
}
}
}
private void UpdatePackages(IProjectManager projectManager, bool updateDependencies, PackageUpdateMode updateMode, bool allowPrereleaseVersions, ILogger logger)
{
UpdatePackages(
projectManager.LocalRepository,
package => UpdatePackage(projectManager, package.Id, updateMode, updateDependencies, allowPrereleaseVersions, logger),
logger);
}
private void UpdatePackages(IPackageRepository packageRepository, PackageUpdateMode updateMode, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
UpdatePackages(
packageRepository,
package => UpdatePackage(package.Id, updateMode, updateDependencies, allowPrereleaseVersions, logger, eventListener),
logger);
}
private void UpdatePackages(IPackageRepository localRepository, Action<IPackage> updateAction, ILogger logger)
{
var packageSorter = new PackageSorter(targetFramework: null);
// Get the packages in reverse dependency order then run update on each one i.e. if A -> B run Update(A) then Update(B)
var packages = packageSorter.GetPackagesByDependencyOrder(localRepository).Reverse();
foreach (var package in packages)
{
// While updating we might remove packages that were initially in the list. e.g.
// A 1.0 -> B 2.0, A 2.0 -> [], since updating to A 2.0 removes B, we end up skipping it.
if (localRepository.Exists(package.Id))
{
try
{
updateAction(package);
}
catch (PackageNotInstalledException e)
{
logger.Log(MessageLevel.Warning, ExceptionUtility.Unwrap(e).Message);
}
catch (Exception e)
{
logger.Log(MessageLevel.Error, ExceptionUtility.Unwrap(e).Message);
}
}
}
}
private void AddSolutionPackageConfigEntry(IPackage package)
{
var sharedPackageRepository = LocalRepository as ISharedPackageRepository;
if (sharedPackageRepository != null && !IsProjectLevel(package))
{
sharedPackageRepository.AddPackageReferenceEntry(package.Id, package.Version);
}
}
private IPackageRepository CreateProjectManagerSourceRepository()
{
// The source repo for the project manager is the aggregate of the shared repo and the selected repo.
// For dependency resolution, we want VS to look for packages in the selected source and then use the fallback logic
var fallbackRepository = SourceRepository as FallbackRepository;
if (fallbackRepository != null)
{
var primaryRepositories = new[] { _sharedRepository, fallbackRepository.SourceRepository.Clone() };
return new FallbackRepository(new AggregateRepository(primaryRepositories), fallbackRepository.DependencyResolver);
}
return new AggregateRepository(new[] { _sharedRepository, SourceRepository.Clone() });
}
private IVersionSpec GetUpgradeVersionSpec(string packageId, PackageUpdateMode updateMode)
{
bool appliesToProject;
IPackage package = FindLocalPackage(packageId, out appliesToProject);
return VersionUtility.GetUpgradeVersionSpec(package.Version, updateMode);
}
private IVersionSpec GetUpgradeVersionSpec(IProjectManager projectManager, string packageId, PackageUpdateMode updateMode)
{
bool appliesToProject;
IPackage package = FindLocalPackageForUpdate(projectManager, packageId, out appliesToProject);
return VersionUtility.GetUpgradeVersionSpec(package.Version, updateMode);
}
protected override void OnUninstalled(PackageOperationEventArgs e)
{
base.OnUninstalled(e);
_deleteOnRestartManager.MarkPackageDirectoryForDeletion(e.Package);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.Framework.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OmniSharp.Models;
using OmniSharp.Options;
using OmniSharp.Services;
namespace OmniSharp.Dnx
{
public class DnxPaths
{
private readonly IOmnisharpEnvironment _env;
private readonly DnxOptions _options;
private readonly ILogger _logger;
public DnxRuntimePathResult RuntimePath { get; private set; }
public string Dnx { get; private set; }
public string Dnu { get; private set; }
public string Klr { get; private set; }
public string Kpm { get; private set; }
public string K { get; private set; }
public DnxPaths(IOmnisharpEnvironment env,
DnxOptions options,
ILoggerFactory loggerFactory)
{
_env = env;
_options = options;
_logger = loggerFactory.CreateLogger<DnxPaths>();
RuntimePath = GetRuntimePath();
Dnx = FirstPath(RuntimePath.Value, "dnx", "dnx.exe");
Dnu = FirstPath(RuntimePath.Value, "dnu", "dnu.cmd");
Klr = FirstPath(RuntimePath.Value, "klr", "klr.exe");
Kpm = FirstPath(RuntimePath.Value, "kpm", "kpm.cmd");
K = FirstPath(RuntimePath.Value, "k", "k.cmd");
}
private DnxRuntimePathResult GetRuntimePath()
{
var root = ResolveRootDirectory(_env.Path);
var globalJson = Path.Combine(root, "global.json");
var versionOrAliasToken = GetRuntimeVersionOrAlias(globalJson);
var versionOrAlias = versionOrAliasToken?.Value<string>() ?? _options.Alias ?? "default";
var seachedLocations = new List<string>();
foreach (var location in GetRuntimeLocations())
{
// Need to expand variables, because DNX_HOME variable might include %USERPROFILE%.
var paths = GetRuntimePathsFromVersionOrAlias(versionOrAlias, Environment.ExpandEnvironmentVariables(location));
foreach (var path in paths)
{
if (string.IsNullOrEmpty(path))
{
continue;
}
if (Directory.Exists(path))
{
_logger.LogInformation(string.Format("Using runtime '{0}'.", path));
return new DnxRuntimePathResult()
{
Value = path
};
}
seachedLocations.Add(path);
}
}
var message = new ErrorMessage()
{
Text = string.Format("The specified runtime path '{0}' does not exist. Searched locations {1}.\nVisit https://github.com/aspnet/Home for an installation guide.", versionOrAlias, string.Join("\n", seachedLocations))
};
if (versionOrAliasToken != null)
{
message.FileName = globalJson;
message.Line = ((IJsonLineInfo)versionOrAliasToken).LineNumber;
message.Column = ((IJsonLineInfo)versionOrAliasToken).LinePosition;
}
_logger.LogError(message.Text);
return new DnxRuntimePathResult()
{
Error = message
};
}
private JToken GetRuntimeVersionOrAlias(string globalJson)
{
if (File.Exists(globalJson))
{
_logger.LogInformation("Looking for sdk version in '{0}'.", globalJson);
using (var stream = File.OpenRead(globalJson))
{
using (var streamReader = new StreamReader(stream))
{
using (var textReader = new JsonTextReader(streamReader))
{
var obj = JObject.Load(textReader);
return obj["sdk"]?["version"];
}
}
}
}
return null;
}
private static string ResolveRootDirectory(string projectPath)
{
var di = new DirectoryInfo(projectPath);
while (di.Parent != null)
{
if (di.EnumerateFiles("global.json").Any())
{
return di.FullName;
}
di = di.Parent;
}
// If we don't find any files then make the project folder the root
return projectPath;
}
private IEnumerable<string> GetRuntimeLocations()
{
yield return Environment.GetEnvironmentVariable("DNX_HOME") ?? string.Empty;
yield return Environment.GetEnvironmentVariable("KRE_HOME") ?? string.Empty;
// %HOME% and %USERPROFILE% might point to different places.
foreach (var home in new string[] { Environment.GetEnvironmentVariable("HOME"), Environment.GetEnvironmentVariable("USERPROFILE") }.Where(s => !string.IsNullOrEmpty(s)))
{
// Newer path
yield return Path.Combine(home, ".dnx");
// New path
yield return Path.Combine(home, ".k");
// Old path
yield return Path.Combine(home, ".kre");
}
}
private IEnumerable<string> GetRuntimePathsFromVersionOrAlias(string versionOrAlias, string runtimePath)
{
// Newer format
yield return GetRuntimePathFromVersionOrAlias(versionOrAlias, runtimePath, ".dnx", "dnx-mono.{0}", "dnx-clr-win-x86.{0}", "runtimes");
// New format
yield return GetRuntimePathFromVersionOrAlias(versionOrAlias, runtimePath, ".k", "kre-mono.{0}", "kre-clr-win-x86.{0}", "runtimes");
// Old format
yield return GetRuntimePathFromVersionOrAlias(versionOrAlias, runtimePath, ".kre", "KRE-Mono.{0}", "KRE-CLR-x86.{0}", "packages");
}
private string GetRuntimePathFromVersionOrAlias(string versionOrAlias,
string runtimeHome,
string sdkFolder,
string monoFormat,
string windowsFormat,
string runtimeFolder)
{
if (string.IsNullOrEmpty(runtimeHome))
{
return null;
}
var aliasDirectory = Path.Combine(runtimeHome, "alias");
var aliasFiles = new[] { "{0}.alias", "{0}.txt" };
// Check alias first
foreach (var shortAliasFile in aliasFiles)
{
var aliasFile = Path.Combine(aliasDirectory, string.Format(shortAliasFile, versionOrAlias));
if (File.Exists(aliasFile))
{
var fullName = File.ReadAllText(aliasFile).Trim();
return Path.Combine(runtimeHome, runtimeFolder, fullName);
}
}
// There was no alias, look for the input as a version
var version = versionOrAlias;
if (PlatformHelper.IsMono)
{
return Path.Combine(runtimeHome, runtimeFolder, string.Format(monoFormat, versionOrAlias));
}
else
{
return Path.Combine(runtimeHome, runtimeFolder, string.Format(windowsFormat, versionOrAlias));
}
}
internal static string FirstPath(string runtimePath, params string[] candidates)
{
if (runtimePath == null)
{
return null;
}
return candidates
.Select(candidate => Path.Combine(runtimePath, "bin", candidate))
.FirstOrDefault(File.Exists);
}
}
}
| |
#region Namespaces
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Epi.Data;
#endregion
namespace Epi.Data.SqlServer.Forms
{
/// <summary>
/// Dialog for building a SQL Server connection string
/// </summary>
public partial class ConnectionStringDialog : DialogBase, IConnectionStringGui // Form,
{
#region Public Data Members
///// <summary>
///// Sql server connection string
///// </summary>
//public string connectionString;
#endregion //Public Data Members
#region Constructors
/// <summary>
/// Default Constructor
/// </summary>
public ConnectionStringDialog()
{
InitializeComponent();
this.cmbServerName.Items.Add(SharedStrings.BROWSE_FOR_MORE);
this.cmbServerName.Items.Add("(local)");
this.cmbServerName.Text = "";
dbConnectionStringBuilder = new SqlConnectionStringBuilder();
}
#endregion
#region IConnectionStringBuilder Members
public bool ShouldIgnoreNonExistance
{
set { }
}
public virtual void SetDatabaseName(string databaseName)
{
this.cmbDatabaseName.Text = databaseName;
}
public virtual void SetServerName(string serverName)
{
this.cmbServerName.Text = serverName;
}
public virtual void SetUserName(string userName)
{
txtUserName.Text = userName;
}
public virtual void SetPassword(string password)
{
txtPassword.Text = password;
}
/// <summary>
///
/// </summary>
protected SqlConnectionStringBuilder dbConnectionStringBuilder;
/// <summary>
/// Gets or sets the SqlDBConnectionString Object
/// </summary>
public DbConnectionStringBuilder DbConnectionStringBuilder
{
get
{
return dbConnectionStringBuilder;
}
//set
//{
// dbConnectionStringBuilder = (SqlConnectionStringBuilder)value;
//}
}
/// <summary>
/// Sets the preferred database name
/// </summary>
public virtual string PreferredDatabaseName
{
set
{
cmbDatabaseName.Text = value;
}
get
{
return cmbDatabaseName.Text;
}
}
/// <summary>
/// Gets a user friendly description of the connection string
/// </summary>
public virtual string ConnectionStringDescription
{
get
{
return cmbServerName.Text + "::" + cmbDatabaseName.Text;
}
}
/// <summary>
/// Gets whether or not the user entered a password
/// </summary>
public bool UsesPassword
{
get
{
if (this.txtPassword.Text.Length > 0)
{
return true;
}
else
{
return false;
}
}
}
#endregion //IConnectionStringBuilder Members
#region Event Handlers
/// <summary>
/// Handles the Click event of the OK button
/// </summary>
/// <param name="sender">Object that fired the event</param>
/// <param name="e">.NET supplied event parameters</param>
private void btnOK_Click(object sender, EventArgs e)
{
OnOkClick();
}
/// <summary>
/// Class the OnAuthenticationCheckChanged method
/// </summary>
/// <param name="sender">Object that fired the event</param>
/// <param name="e">.NET supplied event parameters</param>
private void rdbAuthentication_CheckedChanged(object sender, EventArgs e)
{
lblPassword.Enabled = rdbSqlAuthentication.Checked;
lblUserName.Enabled = rdbSqlAuthentication.Checked;
txtPassword.Enabled = rdbSqlAuthentication.Checked;
txtUserName.Enabled = rdbSqlAuthentication.Checked;
}
/// <summary>
/// Handles the Click event of the Cancel button
/// </summary>
/// <param name="sender">Object that fired the event</param>
/// <param name="e">.NET supplied event parameters</param>
private void btnCancel_Click(object sender, EventArgs e)
{
OnCancelClick();
}
/// <summary>
/// Handles the Change event of the Server Name's selection
/// </summary>
/// <param name="sender">Object that fired the event</param>
/// <param name="e">.NET supplied event parameters</param>
private void cmbServerName_SelectedIndexChanged(object sender, EventArgs e)
{
// if last item in list (Browse for Servers)
if ((string)cmbServerName.SelectedItem == SharedStrings.BROWSE_FOR_MORE)
{
string serverName = BrowseForServers.BrowseNetworkServers().ToString();
if (!string.IsNullOrEmpty(serverName))
{
this.cmbServerName.Items.Insert(0, serverName);
this.cmbServerName.SelectedIndex = 0;
cmbDatabaseName.DataSource = null;
PreferredDatabaseName = string.Empty;
List<String> databases = new List<String>();
using (var con = new SqlConnection("Data Source=" + serverName + ";Initial Catalog=master;Trusted_Connection=yes"))
{
try
{
con.Open();
DataTable Databases = con.GetSchema("Databases");
con.Close();
foreach (DataRow databas in Databases.Rows)
{
databases.Add(databas.Field<String>("database_name"));
}
}
catch(Exception)
{
}
}
if (databases.Count>0)
cmbDatabaseName.DataSource = databases;
/* string database = this.cmbDatabaseName.Text;
Epi.Data.SqlServer.SqlDatabase db = new SqlDatabase();
dbConnectionStringBuilder = new System.Data.SqlClient.SqlConnectionStringBuilder();
dbConnectionStringBuilder.DataSource = cmbServerName.Text;
dbConnectionStringBuilder.UserID = txtUserName.Text;
if (rdbWindowsAuthentication.Checked)
{
dbConnectionStringBuilder.IntegratedSecurity = true;
}
else
{
dbConnectionStringBuilder.UserID = txtUserName.Text;
dbConnectionStringBuilder.Password = txtPassword.Text;
}
db.ConnectionString = this.DbConnectionStringBuilder.ToString();
try
{
if (db.TestConnection())
{
this.cmbDatabaseName.Text = string.Empty;
List<string> databaseNamesList = db.GetDatabaseNameList();
cmbDatabaseName.DataSource = databaseNamesList;
}
else
{
MessageBox.Show("Connection failed."); // TODO: hard coded string.
}
}
catch (Exception ex)
{
MessageBox.Show("Connection failed: " + ex.Message); // TODO: hard coded string
}*/
return;
}
this.cmbServerName.SelectedText = string.Empty;
}
else
{
string serverName = cmbServerName.Text;
if (!string.IsNullOrEmpty(serverName))
{
List<String> databases = new List<String>();
cmbDatabaseName.DataSource = null;
PreferredDatabaseName = string.Empty;
using (var con = new SqlConnection("Data Source=" + serverName + ";Integrated Security=True"))
{
try
{
con.Open();
DataTable Databases = con.GetSchema("Databases");
con.Close();
foreach (DataRow databas in Databases.Rows)
{
databases.Add(databas.Field<String>("database_name"));
}
}
catch(Exception )
{
}
}
if (databases.Count > 0)
cmbDatabaseName.DataSource = databases;
}
}
}
/// <summary>
/// Handles the Click event of the Test button
/// </summary>
/// <param name="sender">Object that fired the event</param>
/// <param name="e">.NET supplied event parameters</param>
protected virtual void btnTest_Click(object sender, EventArgs e)
{
//string database = this.cmbDatabaseName.Text;
//Epi.Data.SqlServer.SqlDatabase db = new SqlDatabase();
//db.ConnectionString = this.DbConnectionStringBuilder.ToString(); //connectionString;
//try
//{
// if (db.TestConnection())
// {
// MessageBox.Show("Success!");
// this.cmbDatabaseName.Items.Clear();
// List<string> databaseNamesList = db.GetDatabaseNameList();
// foreach (string name in databaseNamesList)
// {
// this.cmbDatabaseName.Items.Add(name);
// }
// }
// else
// {
// MessageBox.Show("Connection failed.");
// }
//}
//catch (Exception ex)
//{
// MessageBox.Show("Connection failed: " + ex.Message);
//}
}
#endregion Event Handlers
#region Private Methods
#endregion Private Methods
#region Protected Methods
/// <summary>
/// Validates if all the necessary input is provided.
/// </summary>
/// <returns></returns>
protected override bool ValidateInput()
{
base.ValidateInput();
if (string.IsNullOrEmpty(cmbServerName.Text.Trim()))
{
ErrorMessages.Add("Server name is required"); // TODO: Hard coded string
}
// TODO: Check if this is required.
//if (string.IsNullOrEmpty(txtDatabaseName.Text.Trim()))
//{
// ErrorMessages.Add("Database name is required"); // TODO: Hard coded string
//}
if (rdbSqlAuthentication.Checked)
{
// Check if user id and password are provided ...
if (string.IsNullOrEmpty(txtUserName.Text.Trim()))
{
ErrorMessages.Add("Login name is required");
}
if (string.IsNullOrEmpty(txtPassword.Text.Trim()))
{
ErrorMessages.Add("Password is required");
}
}
return (ErrorMessages.Count == 0);
}
/// <summary>
/// Occurs when cancel is clicked
/// </summary>
protected void OnCancelClick()
{
this.dbConnectionStringBuilder.ConnectionString = string.Empty;
this.PreferredDatabaseName = string.Empty;
this.DialogResult = DialogResult.Cancel;
this.Close();
}
/// <summary>
/// Occurs when OK is clicked
/// </summary>
protected virtual void OnOkClick()
{
if (ValidateInput() == true)
{
//BuildConnectionString(cmbDatabaseName.Text);
dbConnectionStringBuilder = new SqlConnectionStringBuilder();
dbConnectionStringBuilder.DataSource = cmbServerName.Text;
dbConnectionStringBuilder.InitialCatalog = cmbDatabaseName.Text;
dbConnectionStringBuilder.UserID = txtUserName.Text;
if (rdbWindowsAuthentication.Checked)
{
dbConnectionStringBuilder.IntegratedSecurity = true;
}
else
{
dbConnectionStringBuilder.UserID = txtUserName.Text;
dbConnectionStringBuilder.Password = txtPassword.Text;
}
//removed //zack
//connectionString = dbConnectionStringBuilder.ToString();
this.DialogResult = DialogResult.OK;
this.Hide();
}
else
{
ShowErrorMessages();
}
}
#endregion //Protected Methods
private void cmbDatabaseName_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
| |
// 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.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Globalization;
using System.Reflection;
using System.Threading;
using Microsoft.Internal;
using Microsoft.Internal.Collections;
namespace System.ComponentModel.Composition.ReflectionModel
{
internal class GenericSpecializationPartCreationInfo : IReflectionPartCreationInfo
{
private readonly IReflectionPartCreationInfo _originalPartCreationInfo;
private readonly ReflectionComposablePartDefinition _originalPart;
private readonly Type[] _specialization;
private readonly string[] _specializationIdentities;
private IEnumerable<ExportDefinition> _exports;
private IEnumerable<ImportDefinition> _imports;
private readonly Lazy<Type> _lazyPartType;
private List<LazyMemberInfo> _members;
private List<Lazy<ParameterInfo>> _parameters;
private Dictionary<LazyMemberInfo, MemberInfo[]> _membersTable;
private Dictionary<Lazy<ParameterInfo>, ParameterInfo> _parametersTable;
private ConstructorInfo _constructor;
private object _lock = new object();
public GenericSpecializationPartCreationInfo(IReflectionPartCreationInfo originalPartCreationInfo, ReflectionComposablePartDefinition originalPart, Type[] specialization)
{
if(originalPartCreationInfo == null)
{
throw new ArgumentNullException(nameof(originalPartCreationInfo));
}
if(originalPart == null)
{
throw new ArgumentNullException(nameof(originalPart));
}
if(specialization == null)
{
throw new ArgumentNullException(nameof(specialization));
}
_originalPartCreationInfo = originalPartCreationInfo;
_originalPart = originalPart;
_specialization = specialization;
_specializationIdentities = new string[_specialization.Length];
for (int i = 0; i < _specialization.Length; i++)
{
_specializationIdentities[i] = AttributedModelServices.GetTypeIdentity(_specialization[i]);
}
_lazyPartType = new Lazy<Type>(
() => _originalPartCreationInfo.GetPartType().MakeGenericType(specialization),
LazyThreadSafetyMode.PublicationOnly);
}
public ReflectionComposablePartDefinition OriginalPart
{
get
{
return _originalPart;
}
}
public Type GetPartType()
{
return _lazyPartType.Value;
}
public Lazy<Type> GetLazyPartType()
{
return _lazyPartType;
}
public ConstructorInfo GetConstructor()
{
if (_constructor == null)
{
ConstructorInfo genericConstuctor = _originalPartCreationInfo.GetConstructor();
ConstructorInfo result = null;
if (genericConstuctor != null)
{
foreach (ConstructorInfo constructor in GetPartType().GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
{
if (constructor.MetadataToken == genericConstuctor.MetadataToken)
{
result = constructor;
break;
}
}
}
Thread.MemoryBarrier();
lock (_lock)
{
if (_constructor == null)
{
_constructor = result;
}
}
}
return _constructor;
}
public IDictionary<string, object> GetMetadata()
{
var originalMetadata = new Dictionary<string, object>(_originalPartCreationInfo.GetMetadata(), StringComparers.MetadataKeyNames);
originalMetadata.Remove(CompositionConstants.IsGenericPartMetadataName);
originalMetadata.Remove(CompositionConstants.GenericPartArityMetadataName);
originalMetadata.Remove(CompositionConstants.GenericParameterConstraintsMetadataName);
originalMetadata.Remove(CompositionConstants.GenericParameterAttributesMetadataName);
return originalMetadata;
}
private MemberInfo[] GetAccessors(LazyMemberInfo originalLazyMember)
{
BuildTables();
if(_membersTable == null)
{
throw new ArgumentNullException(nameof(_membersTable));
}
return _membersTable[originalLazyMember];
}
private ParameterInfo GetParameter(Lazy<ParameterInfo> originalParameter)
{
BuildTables();
if (_parametersTable == null)
{
throw new ArgumentNullException(nameof(_parametersTable));
}
return _parametersTable[originalParameter];
}
private void BuildTables()
{
if (_membersTable != null)
{
return;
}
PopulateImportsAndExports();
List<LazyMemberInfo> members = null;
List<Lazy<ParameterInfo>> parameters = null;
lock (_lock)
{
if (_membersTable == null)
{
members = _members;
parameters = _parameters;
if (members == null)
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
}
}
//
// Get all members that can be of interest and extract their MetadataTokens
//
Dictionary<LazyMemberInfo, MemberInfo[]> membersTable = BuildMembersTable(members);
Dictionary<Lazy<ParameterInfo>, ParameterInfo> parametersTable = BuildParametersTable(parameters);
lock (_lock)
{
if (_membersTable == null)
{
_membersTable = membersTable;
_parametersTable = parametersTable;
Thread.MemoryBarrier();
_parameters = null;
_members = null;
}
}
}
private Dictionary<LazyMemberInfo, MemberInfo[]> BuildMembersTable(List<LazyMemberInfo> members)
{
if (members == null)
{
throw new ArgumentNullException(nameof(members));
}
Dictionary<LazyMemberInfo, MemberInfo[]> membersTable = new Dictionary<LazyMemberInfo, MemberInfo[]>();
Dictionary<int, MemberInfo> specializedPartMembers = new Dictionary<int, MemberInfo>();
Type closedGenericPartType = GetPartType();
specializedPartMembers[closedGenericPartType.MetadataToken] = closedGenericPartType;
foreach (MethodInfo method in closedGenericPartType.GetAllMethods())
{
specializedPartMembers[method.MetadataToken] = method;
}
foreach (FieldInfo field in closedGenericPartType.GetAllFields())
{
specializedPartMembers[field.MetadataToken] = field;
}
foreach (var iface in closedGenericPartType.GetInterfaces())
{
specializedPartMembers[iface.MetadataToken] = iface;
}
foreach (var type in closedGenericPartType.GetNestedTypes())
{
specializedPartMembers[type.MetadataToken] = type;
}
//Walk the base class list
var baseType = closedGenericPartType.BaseType;
while (baseType != null && baseType != typeof(object))
{
specializedPartMembers[baseType.MetadataToken] = baseType;
baseType = baseType.BaseType;
}
//
// Now go through the members table and resolve them into the new closed type based on the tokens
//
foreach (LazyMemberInfo lazyMemberInfo in members)
{
MemberInfo[] genericAccessors = lazyMemberInfo.GetAccessors();
MemberInfo[] accessors = new MemberInfo[genericAccessors.Length];
for (int i = 0; i < genericAccessors.Length; i++)
{
if (genericAccessors[i] != null)
{
specializedPartMembers.TryGetValue(genericAccessors[i].MetadataToken, out accessors[i]);
if (accessors[i] == null)
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
}
}
membersTable[lazyMemberInfo] = accessors;
}
return membersTable;
}
private Dictionary<Lazy<ParameterInfo>, ParameterInfo> BuildParametersTable(List<Lazy<ParameterInfo>> parameters)
{
if (parameters != null)
{
Dictionary<Lazy<ParameterInfo>, ParameterInfo> parametersTable = new Dictionary<Lazy<ParameterInfo>, ParameterInfo>();
// GENTODO - error case
ParameterInfo[] constructorParameters = GetConstructor().GetParameters();
foreach (var lazyParameter in parameters)
{
parametersTable[lazyParameter] = constructorParameters[lazyParameter.Value.Position];
}
return parametersTable;
}
else
{
return null;
}
}
private List<ImportDefinition> PopulateImports(List<LazyMemberInfo> members, List<Lazy<ParameterInfo>> parameters)
{
List<ImportDefinition> imports = new List<ImportDefinition>();
foreach (ImportDefinition originalImport in _originalPartCreationInfo.GetImports())
{
ReflectionImportDefinition reflectionImport = originalImport as ReflectionImportDefinition;
if (reflectionImport == null)
{
// we always ignore these
continue;
}
imports.Add(TranslateImport(reflectionImport, members, parameters));
}
return imports;
}
private ImportDefinition TranslateImport(ReflectionImportDefinition reflectionImport, List<LazyMemberInfo> members, List<Lazy<ParameterInfo>> parameters)
{
bool isExportFactory = false;
ContractBasedImportDefinition productImport = reflectionImport;
IPartCreatorImportDefinition exportFactoryImportDefinition = reflectionImport as IPartCreatorImportDefinition;
if (exportFactoryImportDefinition != null)
{
productImport = exportFactoryImportDefinition.ProductImportDefinition;
isExportFactory = true;
}
string contractName = Translate(productImport.ContractName);
string requiredTypeIdentity = Translate(productImport.RequiredTypeIdentity);
IDictionary<string, object> metadata = TranslateImportMetadata(productImport);
ReflectionMemberImportDefinition memberImport = reflectionImport as ReflectionMemberImportDefinition;
ImportDefinition import = null;
if (memberImport != null)
{
LazyMemberInfo lazyMember = memberImport.ImportingLazyMember;
LazyMemberInfo importingMember = new LazyMemberInfo(lazyMember.MemberType, () => GetAccessors(lazyMember));
if (isExportFactory)
{
import = new PartCreatorMemberImportDefinition(
importingMember,
((ICompositionElement)memberImport).Origin,
new ContractBasedImportDefinition(
contractName,
requiredTypeIdentity,
productImport.RequiredMetadata,
productImport.Cardinality,
productImport.IsRecomposable,
false,
CreationPolicy.NonShared,
metadata));
}
else
{
import = new ReflectionMemberImportDefinition(
importingMember,
contractName,
requiredTypeIdentity,
productImport.RequiredMetadata,
productImport.Cardinality,
productImport.IsRecomposable,
false,
productImport.RequiredCreationPolicy,
metadata,
((ICompositionElement)memberImport).Origin);
}
members.Add(lazyMember);
}
else
{
ReflectionParameterImportDefinition parameterImport = reflectionImport as ReflectionParameterImportDefinition;
if (parameterImport == null)
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
Lazy<ParameterInfo> lazyParameter = parameterImport.ImportingLazyParameter;
Lazy<ParameterInfo> parameter = new Lazy<ParameterInfo>(() => GetParameter(lazyParameter));
if (isExportFactory)
{
import = new PartCreatorParameterImportDefinition(
parameter,
((ICompositionElement)parameterImport).Origin,
new ContractBasedImportDefinition(
contractName,
requiredTypeIdentity,
productImport.RequiredMetadata,
productImport.Cardinality,
false,
true,
CreationPolicy.NonShared,
metadata));
}
else
{
import = new ReflectionParameterImportDefinition(
parameter,
contractName,
requiredTypeIdentity,
productImport.RequiredMetadata,
productImport.Cardinality,
productImport.RequiredCreationPolicy,
metadata,
((ICompositionElement)parameterImport).Origin);
}
parameters.Add(lazyParameter);
}
return import;
}
private List<ExportDefinition> PopulateExports(List<LazyMemberInfo> members)
{
List<ExportDefinition> exports = new List<ExportDefinition>();
foreach (ExportDefinition originalExport in _originalPartCreationInfo.GetExports())
{
ReflectionMemberExportDefinition reflectionExport = originalExport as ReflectionMemberExportDefinition;
if (reflectionExport == null)
{
// we always ignore these
continue;
}
exports.Add(TranslateExpot(reflectionExport, members));
}
return exports;
}
public ExportDefinition TranslateExpot(ReflectionMemberExportDefinition reflectionExport, List<LazyMemberInfo> members)
{
ExportDefinition export = null;
LazyMemberInfo lazyMember = reflectionExport.ExportingLazyMember;
var capturedLazyMember = lazyMember;
var capturedReflectionExport = reflectionExport;
string contractName = Translate(reflectionExport.ContractName, reflectionExport.Metadata.GetValue<int[]>(CompositionConstants.GenericExportParametersOrderMetadataName));
LazyMemberInfo exportingMember = new LazyMemberInfo(capturedLazyMember.MemberType, () => GetAccessors(capturedLazyMember));
Lazy<IDictionary<string, object>> lazyMetadata = new Lazy<IDictionary<string, object>>(() => TranslateExportMetadata(capturedReflectionExport));
export = new ReflectionMemberExportDefinition(
exportingMember,
new LazyExportDefinition(contractName, lazyMetadata),
((ICompositionElement)reflectionExport).Origin);
members.Add(capturedLazyMember);
return export;
}
private string Translate(string originalValue, int[] genericParametersOrder)
{
if (genericParametersOrder != null)
{
string[] specializationIdentities = GenericServices.Reorder(_specializationIdentities, genericParametersOrder);
return string.Format(CultureInfo.InvariantCulture, originalValue, specializationIdentities);
}
else
{
return Translate(originalValue);
}
}
private string Translate(string originalValue)
{
return string.Format(CultureInfo.InvariantCulture, originalValue, _specializationIdentities);
}
private IDictionary<string, object> TranslateImportMetadata(ContractBasedImportDefinition originalImport)
{
int[] importParametersOrder = originalImport.Metadata.GetValue<int[]>(CompositionConstants.GenericImportParametersOrderMetadataName);
if (importParametersOrder != null)
{
Dictionary<string, object> metadata = new Dictionary<string, object>(originalImport.Metadata, StringComparers.MetadataKeyNames);
// Get the newly re-qualified name of the generic contract and the subset of applicable types from the specialization
metadata[CompositionConstants.GenericContractMetadataName] = GenericServices.GetGenericName(originalImport.ContractName, importParametersOrder, _specialization.Length);
metadata[CompositionConstants.GenericParametersMetadataName] = GenericServices.Reorder(_specialization, importParametersOrder);
metadata.Remove(CompositionConstants.GenericImportParametersOrderMetadataName);
return metadata.AsReadOnly();
}
else
{
return originalImport.Metadata;
}
}
private IDictionary<string, object> TranslateExportMetadata(ReflectionMemberExportDefinition originalExport)
{
Dictionary<string, object> metadata = new Dictionary<string, object>(originalExport.Metadata, StringComparers.MetadataKeyNames);
string exportTypeIdentity = originalExport.Metadata.GetValue<string>(CompositionConstants.ExportTypeIdentityMetadataName);
if (!string.IsNullOrEmpty(exportTypeIdentity))
{
metadata[CompositionConstants.ExportTypeIdentityMetadataName] = Translate(exportTypeIdentity, originalExport.Metadata.GetValue<int[]>(CompositionConstants.GenericExportParametersOrderMetadataName));
}
metadata.Remove(CompositionConstants.GenericExportParametersOrderMetadataName);
return metadata;
}
private void PopulateImportsAndExports()
{
if ((_exports == null) || (_imports == null))
{
List<LazyMemberInfo> members = new List<LazyMemberInfo>();
List<Lazy<ParameterInfo>> parameters = new List<Lazy<ParameterInfo>>();
// we are very careful to not call any 3rd party code in either of these
var exports = PopulateExports(members);
var imports = PopulateImports(members, parameters);
Thread.MemoryBarrier();
lock (_lock)
{
if ((_exports == null) || (_imports == null))
{
_members = members;
if (parameters.Count > 0)
{
_parameters = parameters;
}
_exports = exports;
_imports = imports;
}
}
}
}
public IEnumerable<ExportDefinition> GetExports()
{
PopulateImportsAndExports();
return _exports;
}
public IEnumerable<ImportDefinition> GetImports()
{
PopulateImportsAndExports();
return _imports;
}
public bool IsDisposalRequired
{
get { return _originalPartCreationInfo.IsDisposalRequired; }
}
public bool IsIdentityComparison
{
get
{
return false;
}
}
public string DisplayName
{
get { return Translate(_originalPartCreationInfo.DisplayName); }
}
public ICompositionElement Origin
{
get { return _originalPartCreationInfo.Origin; }
}
public override bool Equals(object obj)
{
GenericSpecializationPartCreationInfo that = obj as GenericSpecializationPartCreationInfo;
if (that == null)
{
return false;
}
return (_originalPartCreationInfo.Equals(that._originalPartCreationInfo)) &&
(_specialization.IsArrayEqual(that._specialization));
}
public override int GetHashCode()
{
return _originalPartCreationInfo.GetHashCode();
}
public static bool CanSpecialize(IDictionary<string, object> partMetadata, Type[] specialization)
{
int partArity = partMetadata.GetValue<int>(CompositionConstants.GenericPartArityMetadataName);
if (partArity != specialization.Length)
{
return false;
}
object[] genericParameterConstraints = partMetadata.GetValue<object[]>(CompositionConstants.GenericParameterConstraintsMetadataName);
GenericParameterAttributes[] genericParameterAttributes = partMetadata.GetValue<GenericParameterAttributes[]>(CompositionConstants.GenericParameterAttributesMetadataName);
// if no constraints and attributes been specifed, anything can be created
if ((genericParameterConstraints == null) && (genericParameterAttributes == null))
{
return true;
}
if ((genericParameterConstraints != null) && (genericParameterConstraints.Length != partArity))
{
return false;
}
if ((genericParameterAttributes != null) && (genericParameterAttributes.Length != partArity))
{
return false;
}
for (int i = 0; i < partArity; i++)
{
if (!GenericServices.CanSpecialize(
specialization[i],
(genericParameterConstraints[i] as Type[]).CreateTypeSpecializations(specialization),
genericParameterAttributes[i]))
{
return false;
}
}
return true;
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
#if FEATURE_CORE_DLR
using System.Linq.Expressions;
#endif
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Runtime.CompilerServices;
using Microsoft.Scripting.Ast;
using Microsoft.Scripting.Runtime;
using IronPython.Runtime.Binding;
using IronPython.Runtime.Operations;
namespace IronPython.Runtime {
[PythonType("buffer"), DontMapGetMemberNamesToDir]
public sealed class PythonBuffer : ICodeFormattable, IDynamicMetaObjectProvider, IList<byte> {
internal object _object;
private int _offset;
private int _size;
private readonly CodeContext/*!*/ _context;
public PythonBuffer(CodeContext/*!*/ context, object @object)
: this(context, @object, 0) {
}
public PythonBuffer(CodeContext/*!*/ context, object @object, int offset)
: this(context, @object, offset, -1) {
}
public PythonBuffer(CodeContext/*!*/ context, object @object, int offset, int size) {
if (!InitBufferObject(@object, offset, size)) {
throw PythonOps.TypeError("expected buffer object");
}
_context = context;
}
private bool InitBufferObject(object o, int offset, int size) {
if (offset < 0) {
throw PythonOps.ValueError("offset must be zero or positive");
} else if (size < -1) {
// -1 is the way to ask for the default size so we allow -1 as a size
throw PythonOps.ValueError("size must be zero or positive");
}
// we currently support only buffers, strings and arrays
// of primitives, strings, bytes, and bytearray objects.
int length;
if (o is PythonBuffer) {
PythonBuffer py = (PythonBuffer)o;
o = py._object; // grab the internal object
length = py._size;
} else if (o is string) {
string strobj = (string)o;
length = strobj.Length;
} else if (o is Bytes) {
length = ((Bytes)o).Count;
} else if (o is ByteArray) {
length = ((ByteArray)o).Count;
} else if (o is Array || o is IPythonArray) {
Array arr = o as Array;
if (arr != null) {
Type t = arr.GetType().GetElementType();
if (!t.IsPrimitive && t != typeof(string)) {
return false;
}
length = arr.Length;
} else {
IPythonArray pa = (IPythonArray)o;
length = pa.Count;
}
} else if (o is IPythonBufferable) {
length = ((IPythonBufferable)o).Size;
_object = o;
} else {
return false;
}
// reset the size based on the given buffer's original size
if (size >= (length - offset) || size == -1) {
_size = length - offset;
} else {
_size = size;
}
_object = o;
_offset = offset;
return true;
}
public override string ToString() {
object res = GetSelectedRange();
if (res is Bytes) {
return PythonOps.MakeString((Bytes)res);
} else if (res is ByteArray) {
return PythonOps.MakeString((ByteArray)res);
} else if (res is IPythonBufferable) {
return PythonOps.MakeString((IList<byte>)GetSelectedRange());
} else if (res is byte[]) {
return ((byte[])GetSelectedRange()).MakeString();
}
return res.ToString();
}
public int __cmp__([NotNull]PythonBuffer other) {
if (Object.ReferenceEquals(this, other)) return 0;
return PythonOps.Compare(ToString(), other.ToString());
}
[PythonHidden]
public override bool Equals(object obj) {
PythonBuffer b = obj as PythonBuffer;
if (b == null) {
return false;
}
return __cmp__(b) == 0;
}
public override int GetHashCode() {
return _object.GetHashCode() ^ _offset ^ (_size << 16 | (_size >> 16));
}
private Slice GetSlice() {
object end = null;
if (_size >= 0) {
end = _offset + _size;
}
return new Slice(_offset, end);
}
public object __getslice__(object start, object stop) {
return this[new Slice(start, stop)];
}
private static Exception ReadOnlyError() {
return PythonOps.TypeError("buffer is read-only");
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
public object __setslice__(object start, object stop, object value) {
throw ReadOnlyError();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
public void __delitem__(int index) {
throw ReadOnlyError();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
public void __delslice__(object start, object stop) {
throw ReadOnlyError();
}
public object this[object s] {
[SpecialName]
get {
return PythonOps.GetIndex(_context, GetSelectedRange(), s);
}
[SpecialName]
set {
throw ReadOnlyError();
}
}
private object GetSelectedRange() {
IPythonArray arr = _object as IPythonArray;
if (arr != null) {
return arr.tostring();
}
ByteArray bytearr = _object as ByteArray;
if (bytearr != null) {
return new Bytes((IList<byte>)bytearr[GetSlice()]);
}
IPythonBufferable pyBuf = _object as IPythonBufferable;
if (pyBuf != null) {
return new Bytes(pyBuf.GetBytes(_offset, _size));
}
return PythonOps.GetIndex(_context, _object, GetSlice());
}
public static object operator +(PythonBuffer a, PythonBuffer b) {
PythonContext context = PythonContext.GetContext(a._context);
return context.Operation(
PythonOperationKind.Add,
PythonOps.GetIndex(a._context, a._object, a.GetSlice()),
PythonOps.GetIndex(a._context, b._object, b.GetSlice())
);
}
public static object operator +(PythonBuffer a, string b) {
return a.ToString() + b;
}
public static object operator *(PythonBuffer b, int n) {
PythonContext context = PythonContext.GetContext(b._context);
return context.Operation(
PythonOperationKind.Multiply,
PythonOps.GetIndex(b._context, b._object, b.GetSlice()),
n
);
}
public static object operator *(int n, PythonBuffer b) {
PythonContext context = PythonContext.GetContext(b._context);
return context.Operation(
PythonOperationKind.Multiply,
PythonOps.GetIndex(b._context, b._object, b.GetSlice()),
n
);
}
public int __len__() {
return Math.Max(_size, 0);
}
internal int Size {
get {
return _size;
}
}
#region ICodeFormattable Members
public string/*!*/ __repr__(CodeContext/*!*/ context) {
return string.Format("<read-only buffer for 0x{0:X16}, size {1}, offset {2} at 0x{3:X16}>",
PythonOps.Id(_object), _size, _offset, PythonOps.Id(this));
}
#endregion
/// <summary>
/// A DynamicMetaObject which is just used to support custom conversions to COM.
/// </summary>
class BufferMeta : DynamicMetaObject, IComConvertible {
public BufferMeta(Expression expr, BindingRestrictions restrictions, object value)
: base(expr, restrictions, value) {
}
#region IComConvertible Members
DynamicMetaObject IComConvertible.GetComMetaObject() {
return new DynamicMetaObject(
Expression.Call(
typeof(PythonOps).GetMethod("ConvertBufferToByteArray"),
Utils.Convert(
Expression,
typeof(PythonBuffer)
)
),
BindingRestrictions.Empty
);
}
#endregion
}
#region IDynamicMetaObjectProvider Members
DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) {
return new BufferMeta(parameter, BindingRestrictions.Empty, this);
}
#endregion
#region IList[System.Byte] implementation
byte[] _objectByteCache = null;
internal byte[] byteCache {
get {
return _objectByteCache ?? (_objectByteCache = PythonOps.ConvertBufferToByteArray(this));
}
}
[PythonHidden]
int IList<byte>.IndexOf(byte item) {
for (int i = 0; i < byteCache.Length; ++i) {
if (byteCache[i] == item)
return i;
}
return -1;
}
[PythonHidden]
void IList<byte>.Insert(int index, byte item) {
throw ReadOnlyError();
}
[PythonHidden]
void IList<byte>.RemoveAt(int index) {
throw ReadOnlyError();
}
byte IList<byte>.this[int index] {
[PythonHidden]
get {
return byteCache[index];
}
[PythonHidden]
set {
throw ReadOnlyError();
}
}
#endregion
#region IEnumerable implementation
[PythonHidden]
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
return byteCache.GetEnumerator();
}
#endregion
#region IEnumerable[System.Byte] implementation
[PythonHidden]
IEnumerator<byte> IEnumerable<byte>.GetEnumerator() {
return ((IEnumerable<byte>)byteCache).GetEnumerator();
}
#endregion
#region ICollection[System.Byte] implementation
[PythonHidden]
void ICollection<byte>.Add(byte item) {
throw ReadOnlyError();
}
[PythonHidden]
void ICollection<byte>.Clear() {
throw ReadOnlyError();
}
[PythonHidden]
bool ICollection<byte>.Contains(byte item) {
return ((IList<byte>)this).IndexOf(item) != -1;
}
[PythonHidden]
void ICollection<byte>.CopyTo(byte[] array, int arrayIndex) {
byteCache.CopyTo(array, arrayIndex);
}
[PythonHidden]
bool ICollection<byte>.Remove(byte item) {
throw ReadOnlyError();
}
int ICollection<byte>.Count {
[PythonHidden]
get {
return byteCache.Length;
}
}
bool ICollection<byte>.IsReadOnly {
[PythonHidden]
get {
return true;
}
}
#endregion
}
/// <summary>
/// A marker interface so we can recognize and access sequence members on our array objects.
/// </summary>
internal interface IPythonArray : IList<object> {
string tostring();
}
public interface IPythonBufferable {
IntPtr UnsafeAddress {
get;
}
int Size {
get;
}
byte[] GetBytes(int offset, int length);
}
}
| |
/*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using Avro.IO;
using System.IO;
namespace Avro.Generic
{
/// <summary>
/// A function that can read the Avro type from the stream.
/// </summary>
/// <typeparam name="T">Type to read.</typeparam>
/// <returns>The read object.</returns>
public delegate T Reader<T>();
/// <summary>
/// A general purpose reader of data from avro streams. This can optionally resolve if the reader's and writer's
/// schemas are different. This class is a wrapper around DefaultReader and offers a little more type safety. The default reader
/// has the flexibility to return any type of object for each read call because the Read() method is generic. This
/// class on the other hand can only return a single type because the type is a parameter to the class. Any
/// user defined extension should, however, be done to DefaultReader. This class is sealed.
/// </summary>
/// <typeparam name="T"></typeparam>
public sealed class GenericReader<T> : DatumReader<T>
{
private readonly DefaultReader reader;
/// <summary>
/// Constructs a generic reader for the given schemas using the DefaultReader. If the
/// reader's and writer's schemas are different this class performs the resolution.
/// </summary>
/// <param name="writerSchema">The schema used while generating the data</param>
/// <param name="readerSchema">The schema desired by the reader</param>
public GenericReader(Schema writerSchema, Schema readerSchema)
: this(new DefaultReader(writerSchema, readerSchema))
{
}
/// <summary>
/// Constructs a generic reader by directly using the given DefaultReader
/// </summary>
/// <param name="reader">The actual reader to use</param>
public GenericReader(DefaultReader reader)
{
this.reader = reader;
}
/// <summary>
/// Schema used to write the data.
/// </summary>
public Schema WriterSchema { get { return reader.WriterSchema; } }
/// <summary>
/// Schema used to read the data.
/// </summary>
public Schema ReaderSchema { get { return reader.ReaderSchema; } }
/// <summary>
/// Reads an object off the stream.
/// </summary>
/// <param name="reuse">
/// If not null, the implemenation will try to use to return the object
/// </param>
/// <param name="d">Decoder to read from.</param>
/// <returns>Object we read from the decoder.</returns>
public T Read(T reuse, Decoder d)
{
return reader.Read(reuse, d);
}
}
/// <summary>
/// The default implementation for the generic reader. It constructs new .NET objects for avro objects on the
/// stream and returns the .NET object. Users can directly use this class or, if they want to customize the
/// object types for differnt Avro schema types, can derive from this class. There are enough hooks in this
/// class to allow customization.
/// </summary>
/// <remarks>
/// <list type="table">
/// <listheader><term>Avro Type</term><description>.NET Type</description></listheader>
/// <item><term>null</term><description>null reference</description></item>
/// </list>
/// </remarks>
public class DefaultReader
{
/// <summary>
/// Schema to use when reading data with this reader.
/// </summary>
public Schema ReaderSchema { get; private set; }
/// <summary>
/// Schema used to write data that we are reading with this reader.
/// </summary>
public Schema WriterSchema { get; private set; }
/// <summary>
/// Constructs the default reader for the given schemas using the DefaultReader. If the
/// reader's and writer's schemas are different this class performs the resolution.
/// This default implemenation maps Avro types to .NET types as follows:
/// </summary>
/// <param name="writerSchema">The schema used while generating the data</param>
/// <param name="readerSchema">The schema desired by the reader</param>
public DefaultReader(Schema writerSchema, Schema readerSchema)
{
this.ReaderSchema = readerSchema;
this.WriterSchema = writerSchema;
}
/// <summary>
/// Reads an object off the stream.
/// </summary>
/// <typeparam name="T">The type of object to read. A single schema typically returns an object of a single .NET class.
/// The only exception is UnionSchema, which can return a object of different types based on the branch selected.
/// </typeparam>
/// <param name="reuse">If not null, the implemenation will try to use to return the object</param>
/// <param name="decoder">The decoder for deserialization</param>
/// <returns>Object read from the decoder.</returns>
public T Read<T>(T reuse, Decoder decoder)
{
if (!ReaderSchema.CanRead(WriterSchema))
throw new AvroException("Schema mismatch. Reader: " + ReaderSchema + ", writer: " + WriterSchema);
return (T)Read(reuse, WriterSchema, ReaderSchema, decoder);
}
/// <summary>
/// Reads an object off the stream.
/// </summary>
/// <param name="reuse">
/// If not null, the implemenation will try to use to return the object.
/// </param>
/// <param name="writerSchema">Schema used to write the data.</param>
/// <param name="readerSchema">Schema to use when reading the data.</param>
/// <param name="d">Decoder to read from.</param>
/// <returns>Object read from the decoder.</returns>
public object Read(object reuse, Schema writerSchema, Schema readerSchema, Decoder d)
{
if (readerSchema.Tag == Schema.Type.Union && writerSchema.Tag != Schema.Type.Union)
{
readerSchema = findBranch(readerSchema as UnionSchema, writerSchema);
}
/*
if (!readerSchema.CanRead(writerSchema))
{
throw new AvroException("Schema mismatch. Reader: " + readerSchema + ", writer: " + writerSchema);
}
*/
switch (writerSchema.Tag)
{
case Schema.Type.Null:
return ReadNull(readerSchema, d);
case Schema.Type.Boolean:
return Read<bool>(writerSchema.Tag, readerSchema, d.ReadBoolean);
case Schema.Type.Int:
{
int i = Read<int>(writerSchema.Tag, readerSchema, d.ReadInt);
switch (readerSchema.Tag)
{
case Schema.Type.Long:
return (long)i;
case Schema.Type.Float:
return (float)i;
case Schema.Type.Double:
return (double)i;
default:
return i;
}
}
case Schema.Type.Long:
{
long l = Read<long>(writerSchema.Tag, readerSchema, d.ReadLong);
switch (readerSchema.Tag)
{
case Schema.Type.Float:
return (float)l;
case Schema.Type.Double:
return (double)l;
default:
return l;
}
}
case Schema.Type.Float:
{
float f = Read<float>(writerSchema.Tag, readerSchema, d.ReadFloat);
switch (readerSchema.Tag)
{
case Schema.Type.Double:
return (double)f;
default:
return f;
}
}
case Schema.Type.Double:
return Read<double>(writerSchema.Tag, readerSchema, d.ReadDouble);
case Schema.Type.String:
return Read<string>(writerSchema.Tag, readerSchema, d.ReadString);
case Schema.Type.Bytes:
return Read<byte[]>(writerSchema.Tag, readerSchema, d.ReadBytes);
case Schema.Type.Error:
case Schema.Type.Record:
return ReadRecord(reuse, (RecordSchema)writerSchema, readerSchema, d);
case Schema.Type.Enumeration:
return ReadEnum(reuse, (EnumSchema)writerSchema, readerSchema, d);
case Schema.Type.Fixed:
return ReadFixed(reuse, (FixedSchema)writerSchema, readerSchema, d);
case Schema.Type.Array:
return ReadArray(reuse, (ArraySchema)writerSchema, readerSchema, d);
case Schema.Type.Map:
return ReadMap(reuse, (MapSchema)writerSchema, readerSchema, d);
case Schema.Type.Union:
return ReadUnion(reuse, (UnionSchema)writerSchema, readerSchema, d);
case Schema.Type.Logical:
return ReadLogical(reuse, (LogicalSchema)writerSchema, readerSchema, d);
default:
throw new AvroException("Unknown schema type: " + writerSchema);
}
}
/// <summary>
/// Deserializes a null from the stream.
/// </summary>
/// <param name="readerSchema">Reader's schema, which should be a NullSchema</param>
/// <param name="d">The decoder for deserialization</param>
/// <returns></returns>
protected virtual object ReadNull(Schema readerSchema, Decoder d)
{
d.ReadNull();
return null;
}
/// <summary>
/// A generic function to read primitive types
/// </summary>
/// <typeparam name="T">The .NET type to read</typeparam>
/// <param name="tag">The Avro type tag for the object on the stream</param>
/// <param name="readerSchema">A schema compatible to the Avro type</param>
/// <param name="reader">A function that can read the avro type from the stream</param>
/// <returns>The primitive type just read</returns>
protected T Read<T>(Schema.Type tag, Schema readerSchema, Reader<T> reader)
{
return reader();
}
/// <summary>
/// Deserializes a record from the stream.
/// </summary>
/// <param name="reuse">If not null, a record object that could be reused for returning the result</param>
/// <param name="writerSchema">The writer's RecordSchema</param>
/// <param name="readerSchema">The reader's schema, must be RecordSchema too.</param>
/// <param name="dec">The decoder for deserialization</param>
/// <returns>The record object just read</returns>
protected virtual object ReadRecord(object reuse, RecordSchema writerSchema, Schema readerSchema, Decoder dec)
{
RecordSchema rs = (RecordSchema)readerSchema;
object rec = CreateRecord(reuse, rs);
foreach (Field wf in writerSchema)
{
try
{
Field rf;
if (rs.TryGetFieldAlias(wf.Name, out rf))
{
object obj = null;
TryGetField(rec, wf.Name, rf.Pos, out obj);
AddField(rec, wf.Name, rf.Pos, Read(obj, wf.Schema, rf.Schema, dec));
}
else
Skip(wf.Schema, dec);
}
catch (Exception ex)
{
throw new AvroException(ex.Message + " in field " + wf.Name, ex);
}
}
var defaultStream = new MemoryStream();
var defaultEncoder = new BinaryEncoder(defaultStream);
var defaultDecoder = new BinaryDecoder(defaultStream);
foreach (Field rf in rs)
{
if (writerSchema.Contains(rf.Name)) continue;
defaultStream.Position = 0; // reset for writing
Resolver.EncodeDefaultValue(defaultEncoder, rf.Schema, rf.DefaultValue);
defaultStream.Flush();
defaultStream.Position = 0; // reset for reading
object obj = null;
TryGetField(rec, rf.Name, rf.Pos, out obj);
AddField(rec, rf.Name, rf.Pos, Read(obj, rf.Schema, rf.Schema, defaultDecoder));
}
return rec;
}
/// <summary>
/// Creates a new record object. Derived classes can override this to return an object of their choice.
/// </summary>
/// <param name="reuse">If appropriate, will reuse this object instead of constructing a new one</param>
/// <param name="readerSchema">The schema the reader is using</param>
/// <returns></returns>
protected virtual object CreateRecord(object reuse, RecordSchema readerSchema)
{
GenericRecord ru = (reuse == null || !(reuse is GenericRecord) || !(reuse as GenericRecord).Schema.Equals(readerSchema)) ?
new GenericRecord(readerSchema) :
reuse as GenericRecord;
return ru;
}
/// <summary>
/// Used by the default implementation of ReadRecord() to get the existing field of a record object. The derived
/// classes can override this to make their own interpretation of the record object.
/// </summary>
/// <param name="record">The record object to be probed into. This is guaranteed to be one that was returned
/// by a previous call to CreateRecord.</param>
/// <param name="fieldName">The name of the field to probe.</param>
/// <param name="fieldPos">Position of the field in the schema - not used in the base implementation.</param>
/// <param name="value">The value of the field, if found. Null otherwise.</param>
/// <returns>True if and only if a field with the given name is found.</returns>
protected virtual bool TryGetField(object record, string fieldName, int fieldPos, out object value)
{
return (record as GenericRecord).TryGetValue(fieldPos, out value);
}
/// <summary>
/// Used by the default implementation of ReadRecord() to add a field to a record object. The derived
/// classes can override this to suit their own implementation of the record object.
/// </summary>
/// <param name="record">The record object to be probed into. This is guaranteed to be one that was returned
/// by a previous call to CreateRecord.</param>
/// <param name="fieldName">The name of the field to probe.</param>
/// <param name="fieldPos">Position of the field in the schema - not used in the base implementation.</param>
/// <param name="fieldValue">The value to be added for the field</param>
protected virtual void AddField(object record, string fieldName, int fieldPos, object fieldValue)
{
(record as GenericRecord).Add(fieldPos, fieldValue);
}
/// <summary>
/// Deserializes a enum. Uses CreateEnum to construct the new enum object.
/// </summary>
/// <param name="reuse">If appropirate, uses this instead of creating a new enum object.</param>
/// <param name="writerSchema">The schema the writer used while writing the enum</param>
/// <param name="readerSchema">The schema the reader is using</param>
/// <param name="d">The decoder for deserialization.</param>
/// <returns>An enum object.</returns>
protected virtual object ReadEnum(object reuse, EnumSchema writerSchema, Schema readerSchema, Decoder d)
{
return CreateEnum(reuse, readerSchema as EnumSchema, writerSchema[d.ReadEnum()]);
}
/// <summary>
/// Used by the default implementation of ReadEnum to construct a new enum object.
/// </summary>
/// <param name="reuse">If appropriate, use this enum object instead of a new one.</param>
/// <param name="es">The enum schema used by the reader.</param>
/// <param name="symbol">The symbol that needs to be used.</param>
/// <returns>The default implemenation returns a GenericEnum.</returns>
protected virtual object CreateEnum(object reuse, EnumSchema es, string symbol)
{
if (reuse is GenericEnum)
{
GenericEnum ge = reuse as GenericEnum;
if (ge.Schema.Equals(es))
{
ge.Value = symbol;
return ge;
}
}
return new GenericEnum(es, symbol);
}
/// <summary>
/// Deserializes an array and returns an array object. It uses CreateArray() and works on it before returning it.
/// It also uses GetArraySize(), ResizeArray(), SetArrayElement() and GetArrayElement() methods. Derived classes can
/// override these methods to customize their behavior.
/// </summary>
/// <param name="reuse">If appropriate, uses this instead of creating a new array object.</param>
/// <param name="writerSchema">The schema used by the writer.</param>
/// <param name="readerSchema">The schema that the reader uses.</param>
/// <param name="d">The decoder for deserialization.</param>
/// <returns>The deserialized array object.</returns>
protected virtual object ReadArray(object reuse, ArraySchema writerSchema, Schema readerSchema, Decoder d)
{
ArraySchema rs = (ArraySchema)readerSchema;
object result = CreateArray(reuse, rs);
int i = 0;
for (int n = (int)d.ReadArrayStart(); n != 0; n = (int)d.ReadArrayNext())
{
if (GetArraySize(result) < (i + n)) ResizeArray(ref result, i + n);
for (int j = 0; j < n; j++, i++)
{
SetArrayElement(result, i, Read(GetArrayElement(result, i), writerSchema.ItemSchema, rs.ItemSchema, d));
}
}
if (GetArraySize(result) != i) ResizeArray(ref result, i);
return result;
}
/// <summary>
/// Creates a new array object. The initial size of the object could be anything. The users
/// should use GetArraySize() to determine the size. The default implementation creates an <c>object[]</c>.
/// </summary>
/// <param name="reuse">If appropriate use this instead of creating a new one.</param>
/// <param name="rs">Array schema, not used in base implementation</param>
/// <returns>An object suitable to deserialize an avro array</returns>
protected virtual object CreateArray(object reuse, ArraySchema rs)
{
return (reuse != null && reuse is object[]) ? (object[])reuse : new object[0];
}
/// <summary>
/// Returns the size of the given array object.
/// </summary>
/// <param name="array">Array object whose size is required. This is guaranteed to be somthing returned by
/// a previous call to CreateArray().</param>
/// <returns>The size of the array</returns>
protected virtual int GetArraySize(object array)
{
return (array as object[]).Length;
}
/// <summary>
/// Resizes the array to the new value.
/// </summary>
/// <param name="array">Array object whose size is required. This is guaranteed to be somthing returned by
/// a previous call to CreateArray().</param>
/// <param name="n">The new size.</param>
protected virtual void ResizeArray(ref object array, int n)
{
object[] o = array as object[];
Array.Resize(ref o, n);
array = o;
}
/// <summary>
/// Assigns a new value to the object at the given index
/// </summary>
/// <param name="array">Array object whose size is required. This is guaranteed to be somthing returned by
/// a previous call to CreateArray().</param>
/// <param name="index">The index to reassign to.</param>
/// <param name="value">The value to assign.</param>
protected virtual void SetArrayElement(object array, int index, object value)
{
object[] a = array as object[];
a[index] = value;
}
/// <summary>
/// Returns the element at the given index.
/// </summary>
/// <param name="array">Array object whose size is required. This is guaranteed to be somthing returned by
/// a previous call to CreateArray().</param>
/// <param name="index">The index to look into.</param>
/// <returns>The object the given index. Null if no object has been assigned to that index.</returns>
protected virtual object GetArrayElement(object array, int index)
{
return (array as object[])[index];
}
/// <summary>
/// Deserialized an avro map. The default implemenation creats a new map using CreateMap() and then
/// adds elements to the map using AddMapEntry().
/// </summary>
/// <param name="reuse">If appropriate, use this instead of creating a new map object.</param>
/// <param name="writerSchema">The schema the writer used to write the map.</param>
/// <param name="readerSchema">The schema the reader is using.</param>
/// <param name="d">The decoder for serialization.</param>
/// <returns>The deserialized map object.</returns>
protected virtual object ReadMap(object reuse, MapSchema writerSchema, Schema readerSchema, Decoder d)
{
MapSchema rs = (MapSchema)readerSchema;
object result = CreateMap(reuse, rs);
for (int n = (int)d.ReadMapStart(); n != 0; n = (int)d.ReadMapNext())
{
for (int j = 0; j < n; j++)
{
string k = d.ReadString();
AddMapEntry(result, k, Read(null, writerSchema.ValueSchema, rs.ValueSchema, d));
}
}
return result;
}
/// <summary>
/// Used by the default implementation of ReadMap() to create a fresh map object. The default
/// implementaion of this method returns a IDictionary<string, map>.
/// </summary>
/// <param name="reuse">If appropriate, use this map object instead of creating a new one.</param>
/// <param name="ms">Map schema to use when creating the object.</param>
/// <returns>An empty map object.</returns>
protected virtual object CreateMap(object reuse, MapSchema ms)
{
if (reuse != null && reuse is IDictionary<string, object>)
{
IDictionary<string, object> result = reuse as IDictionary<string, object>;
result.Clear();
return result;
}
return new Dictionary<string, object>();
}
/// <summary>
/// Adds an entry to the map.
/// </summary>
/// <param name="map">A map object, which is guaranteed to be one returned by a previous call to CreateMap().</param>
/// <param name="key">The key to add.</param>
/// <param name="value">The value to add.</param>
protected virtual void AddMapEntry(object map, string key, object value)
{
(map as IDictionary<string, object>).Add(key, value);
}
/// <summary>
/// Deserialized an object based on the writer's uninon schema.
/// </summary>
/// <param name="reuse">If appropriate, uses this object instead of creating a new one.</param>
/// <param name="writerSchema">The UnionSchema that the writer used.</param>
/// <param name="readerSchema">The schema the reader uses.</param>
/// <param name="d">The decoder for serialization.</param>
/// <returns>The deserialized object.</returns>
protected virtual object ReadUnion(object reuse, UnionSchema writerSchema, Schema readerSchema, Decoder d)
{
int index = d.ReadUnionIndex();
Schema ws = writerSchema[index];
if (readerSchema is UnionSchema)
readerSchema = findBranch(readerSchema as UnionSchema, ws);
else
if (!readerSchema.CanRead(ws))
throw new AvroException("Schema mismatch. Reader: " + ReaderSchema + ", writer: " + WriterSchema);
return Read(reuse, ws, readerSchema, d);
}
/// <summary>
/// Deserializes an object based on the writer's logical schema. Uses the underlying logical type to convert
/// the value to the logical type.
/// </summary>
/// <param name="reuse">If appropriate, uses this object instead of creating a new one.</param>
/// <param name="writerSchema">The UnionSchema that the writer used.</param>
/// <param name="readerSchema">The schema the reader uses.</param>
/// <param name="d">The decoder for serialization.</param>
/// <returns>The deserialized object.</returns>
protected virtual object ReadLogical(object reuse, LogicalSchema writerSchema, Schema readerSchema, Decoder d)
{
LogicalSchema ls = (LogicalSchema)readerSchema;
return writerSchema.LogicalType.ConvertToLogicalValue(Read(reuse, writerSchema.BaseSchema, ls.BaseSchema, d), ls);
}
/// <summary>
/// Deserializes a fixed object and returns the object. The default implementation uses CreateFixed()
/// and GetFixedBuffer() and returns what CreateFixed() returned.
/// </summary>
/// <param name="reuse">If appropriate, uses this object instead of creating a new one.</param>
/// <param name="writerSchema">The FixedSchema the writer used during serialization.</param>
/// <param name="readerSchema">The schema that the readr uses. Must be a FixedSchema with the same
/// size as the writerSchema.</param>
/// <param name="d">The decoder for deserialization.</param>
/// <returns>The deserilized object.</returns>
protected virtual object ReadFixed(object reuse, FixedSchema writerSchema, Schema readerSchema, Decoder d)
{
FixedSchema rs = (FixedSchema)readerSchema;
if (rs.Size != writerSchema.Size)
{
throw new AvroException("Size mismatch between reader and writer fixed schemas. Writer: " + writerSchema +
", reader: " + readerSchema);
}
object ru = CreateFixed(reuse, rs);
byte[] bb = GetFixedBuffer(ru);
d.ReadFixed(bb);
return ru;
}
/// <summary>
/// Returns a fixed object.
/// </summary>
/// <param name="reuse">If appropriate, uses this object instead of creating a new one.</param>
/// <param name="rs">The reader's FixedSchema.</param>
/// <returns>A fixed object with an appropriate buffer.</returns>
protected virtual object CreateFixed(object reuse, FixedSchema rs)
{
return (reuse != null && reuse is GenericFixed && (reuse as GenericFixed).Schema.Equals(rs)) ?
(GenericFixed)reuse : new GenericFixed(rs);
}
/// <summary>
/// Returns a buffer of appropriate size to read data into.
/// </summary>
/// <param name="f">The fixed object. It is guaranteed that this is something that has been previously
/// returned by CreateFixed</param>
/// <returns>A byte buffer of fixed's size.</returns>
protected virtual byte[] GetFixedBuffer(object f)
{
return (f as GenericFixed).Value;
}
/// <summary>
/// Skip an instance of a schema.
/// </summary>
/// <param name="writerSchema">Schema to skip.</param>
/// <param name="d">Decoder we're reading from.</param>
protected virtual void Skip(Schema writerSchema, Decoder d)
{
switch (writerSchema.Tag)
{
case Schema.Type.Null:
d.SkipNull();
break;
case Schema.Type.Boolean:
d.SkipBoolean();
break;
case Schema.Type.Int:
d.SkipInt();
break;
case Schema.Type.Long:
d.SkipLong();
break;
case Schema.Type.Float:
d.SkipFloat();
break;
case Schema.Type.Double:
d.SkipDouble();
break;
case Schema.Type.String:
d.SkipString();
break;
case Schema.Type.Bytes:
d.SkipBytes();
break;
case Schema.Type.Record:
foreach (Field f in writerSchema as RecordSchema) Skip(f.Schema, d);
break;
case Schema.Type.Enumeration:
d.SkipEnum();
break;
case Schema.Type.Fixed:
d.SkipFixed((writerSchema as FixedSchema).Size);
break;
case Schema.Type.Array:
{
Schema s = (writerSchema as ArraySchema).ItemSchema;
for (long n = d.ReadArrayStart(); n != 0; n = d.ReadArrayNext())
{
for (long i = 0; i < n; i++) Skip(s, d);
}
}
break;
case Schema.Type.Map:
{
Schema s = (writerSchema as MapSchema).ValueSchema;
for (long n = d.ReadMapStart(); n != 0; n = d.ReadMapNext())
{
for (long i = 0; i < n; i++) { d.SkipString(); Skip(s, d); }
}
}
break;
case Schema.Type.Union:
Skip((writerSchema as UnionSchema)[d.ReadUnionIndex()], d);
break;
case Schema.Type.Logical:
Skip((writerSchema as LogicalSchema).BaseSchema, d);
break;
default:
throw new AvroException("Unknown schema type: " + writerSchema);
}
}
/// <summary>
/// Finds the branch of the union schema associated with the given schema.
/// </summary>
/// <param name="us">Union schema.</param>
/// <param name="s">Schema to find in the union schema.</param>
/// <returns>Schema branch in the union schema.</returns>
protected static Schema findBranch(UnionSchema us, Schema s)
{
int index = us.MatchingBranch(s);
if (index >= 0) return us[index];
throw new AvroException("No matching schema for " + s + " in " + us);
}
}
}
| |
// 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.Globalization;
using System.IO;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle;
namespace System.Net.Http
{
#if HTTP_DLL
internal enum WindowsProxyUsePolicy
#else
public enum WindowsProxyUsePolicy
#endif
{
DoNotUseProxy = 0, // Don't use a proxy at all.
UseWinHttpProxy = 1, // Use configuration as specified by "netsh winhttp" machine config command. Automatic detect not supported.
UseWinInetProxy = 2, // WPAD protocol and PAC files supported.
UseCustomProxy = 3 // Use the custom proxy specified in the Proxy property.
}
#if HTTP_DLL
internal enum CookieUsePolicy
#else
public enum CookieUsePolicy
#endif
{
IgnoreCookies = 0,
UseInternalCookieStoreOnly = 1,
UseSpecifiedCookieContainer = 2
}
#if HTTP_DLL
internal class WinHttpHandler : HttpMessageHandler
#else
public class WinHttpHandler : HttpMessageHandler
#endif
{
#if NET46
internal static readonly Version HttpVersion20 = new Version(2, 0);
internal static readonly Version HttpVersionUnknown = new Version(0, 0);
#else
internal static Version HttpVersion20 => HttpVersionInternal.Version20;
internal static Version HttpVersionUnknown => HttpVersionInternal.Unknown;
#endif
private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue);
[ThreadStatic]
private static StringBuilder t_requestHeadersBuilder;
private object _lockObject = new object();
private bool _doManualDecompressionCheck = false;
private WinInetProxyHelper _proxyHelper = null;
private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection;
private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections;
private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression;
private CookieUsePolicy _cookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly;
private CookieContainer _cookieContainer = null;
private SslProtocols _sslProtocols = SslProtocols.None; // Use most secure protocols available.
private Func<
HttpRequestMessage,
X509Certificate2,
X509Chain,
SslPolicyErrors,
bool> _serverCertificateValidationCallback = null;
private bool _checkCertificateRevocationList = false;
private ClientCertificateOption _clientCertificateOption = ClientCertificateOption.Manual;
private X509Certificate2Collection _clientCertificates = null; // Only create collection when required.
private ICredentials _serverCredentials = null;
private bool _preAuthenticate = false;
private WindowsProxyUsePolicy _windowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinHttpProxy;
private ICredentials _defaultProxyCredentials = null;
private IWebProxy _proxy = null;
private int _maxConnectionsPerServer = int.MaxValue;
private TimeSpan _sendTimeout = TimeSpan.FromSeconds(30);
private TimeSpan _receiveHeadersTimeout = TimeSpan.FromSeconds(30);
private TimeSpan _receiveDataTimeout = TimeSpan.FromSeconds(30);
private int _maxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeadersLength;
private int _maxResponseDrainSize = 64 * 1024;
private IDictionary<String, Object> _properties; // Only create dictionary when required.
private volatile bool _operationStarted;
private volatile bool _disposed;
private SafeWinHttpHandle _sessionHandle;
private WinHttpAuthHelper _authHelper = new WinHttpAuthHelper();
public WinHttpHandler()
{
}
#region Properties
public bool AutomaticRedirection
{
get
{
return _automaticRedirection;
}
set
{
CheckDisposedOrStarted();
_automaticRedirection = value;
}
}
public int MaxAutomaticRedirections
{
get
{
return _maxAutomaticRedirections;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxAutomaticRedirections = value;
}
}
public DecompressionMethods AutomaticDecompression
{
get
{
return _automaticDecompression;
}
set
{
CheckDisposedOrStarted();
_automaticDecompression = value;
}
}
public CookieUsePolicy CookieUsePolicy
{
get
{
return _cookieUsePolicy;
}
set
{
if (value != CookieUsePolicy.IgnoreCookies
&& value != CookieUsePolicy.UseInternalCookieStoreOnly
&& value != CookieUsePolicy.UseSpecifiedCookieContainer)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_cookieUsePolicy = value;
}
}
public CookieContainer CookieContainer
{
get
{
return _cookieContainer;
}
set
{
CheckDisposedOrStarted();
_cookieContainer = value;
}
}
public SslProtocols SslProtocols
{
get
{
return _sslProtocols;
}
set
{
SecurityProtocol.ThrowOnNotAllowed(value, allowNone: true);
CheckDisposedOrStarted();
_sslProtocols = value;
}
}
public Func<
HttpRequestMessage,
X509Certificate2,
X509Chain,
SslPolicyErrors,
bool> ServerCertificateValidationCallback
{
get
{
return _serverCertificateValidationCallback;
}
set
{
CheckDisposedOrStarted();
_serverCertificateValidationCallback = value;
}
}
public bool CheckCertificateRevocationList
{
get
{
return _checkCertificateRevocationList;
}
set
{
CheckDisposedOrStarted();
_checkCertificateRevocationList = value;
}
}
public ClientCertificateOption ClientCertificateOption
{
get
{
return _clientCertificateOption;
}
set
{
if (value != ClientCertificateOption.Manual
&& value != ClientCertificateOption.Automatic)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_clientCertificateOption = value;
}
}
public X509Certificate2Collection ClientCertificates
{
get
{
if (_clientCertificateOption != ClientCertificateOption.Manual)
{
throw new InvalidOperationException(SR.Format(SR.net_http_invalid_enable_first, "ClientCertificateOptions", "Manual"));
}
if (_clientCertificates == null)
{
_clientCertificates = new X509Certificate2Collection();
}
return _clientCertificates;
}
}
public bool PreAuthenticate
{
get
{
return _preAuthenticate;
}
set
{
_preAuthenticate = value;
}
}
public ICredentials ServerCredentials
{
get
{
return _serverCredentials;
}
set
{
_serverCredentials = value;
}
}
public WindowsProxyUsePolicy WindowsProxyUsePolicy
{
get
{
return _windowsProxyUsePolicy;
}
set
{
if (value != WindowsProxyUsePolicy.DoNotUseProxy &&
value != WindowsProxyUsePolicy.UseWinHttpProxy &&
value != WindowsProxyUsePolicy.UseWinInetProxy &&
value != WindowsProxyUsePolicy.UseCustomProxy)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_windowsProxyUsePolicy = value;
}
}
public ICredentials DefaultProxyCredentials
{
get
{
return _defaultProxyCredentials;
}
set
{
CheckDisposedOrStarted();
_defaultProxyCredentials = value;
}
}
public IWebProxy Proxy
{
get
{
return _proxy;
}
set
{
CheckDisposedOrStarted();
_proxy = value;
}
}
public int MaxConnectionsPerServer
{
get
{
return _maxConnectionsPerServer;
}
set
{
if (value < 1)
{
// In WinHTTP, setting this to 0 results in it being reset to 2.
// So, we'll only allow settings above 0.
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxConnectionsPerServer = value;
}
}
public TimeSpan SendTimeout
{
get
{
return _sendTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_sendTimeout = value;
}
}
public TimeSpan ReceiveHeadersTimeout
{
get
{
return _receiveHeadersTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_receiveHeadersTimeout = value;
}
}
public TimeSpan ReceiveDataTimeout
{
get
{
return _receiveDataTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_receiveDataTimeout = value;
}
}
public int MaxResponseHeadersLength
{
get
{
return _maxResponseHeadersLength;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxResponseHeadersLength = value;
}
}
public int MaxResponseDrainSize
{
get
{
return _maxResponseDrainSize;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxResponseDrainSize = value;
}
}
public IDictionary<string, object> Properties
{
get
{
if (_properties == null)
{
_properties = new Dictionary<String, object>();
}
return _properties;
}
}
#endregion
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
_disposed = true;
if (disposing && _sessionHandle != null)
{
SafeWinHttpHandle.DisposeAndClearHandle(ref _sessionHandle);
}
}
base.Dispose(disposing);
}
#if HTTP_DLL
protected internal override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
#else
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
#endif
{
if (request == null)
{
throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest);
}
// Check for invalid combinations of properties.
if (_proxy != null && _windowsProxyUsePolicy != WindowsProxyUsePolicy.UseCustomProxy)
{
throw new InvalidOperationException(SR.net_http_invalid_proxyusepolicy);
}
if (_windowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy && _proxy == null)
{
throw new InvalidOperationException(SR.net_http_invalid_proxy);
}
if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer &&
_cookieContainer == null)
{
throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer);
}
CheckDisposed();
SetOperationStarted();
TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
// Create state object and save current values of handler settings.
var state = new WinHttpRequestState();
state.Tcs = tcs;
state.CancellationToken = cancellationToken;
state.RequestMessage = request;
state.Handler = this;
state.CheckCertificateRevocationList = _checkCertificateRevocationList;
state.ServerCertificateValidationCallback = _serverCertificateValidationCallback;
state.WindowsProxyUsePolicy = _windowsProxyUsePolicy;
state.Proxy = _proxy;
state.ServerCredentials = _serverCredentials;
state.DefaultProxyCredentials = _defaultProxyCredentials;
state.PreAuthenticate = _preAuthenticate;
Task.Factory.StartNew(
s => {
var whrs = (WinHttpRequestState)s;
whrs.Handler.StartRequest(whrs);
},
state,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
return tcs.Task;
}
private static bool IsChunkedModeForSend(HttpRequestMessage requestMessage)
{
bool chunkedMode = requestMessage.Headers.TransferEncodingChunked.HasValue &&
requestMessage.Headers.TransferEncodingChunked.Value;
HttpContent requestContent = requestMessage.Content;
if (requestContent != null)
{
if (requestContent.Headers.ContentLength.HasValue)
{
if (chunkedMode)
{
// Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics.
// Current .NET Desktop HttpClientHandler allows both headers to be specified but ends up
// stripping out 'Content-Length' and using chunked semantics. WinHttpHandler will maintain
// the same behavior.
requestContent.Headers.ContentLength = null;
}
}
else
{
if (!chunkedMode)
{
// Neither 'Content-Length' nor 'Transfer-Encoding: chunked' semantics was given.
// Current .NET Desktop HttpClientHandler uses 'Content-Length' semantics and
// buffers the content as well in some cases. But the WinHttpHandler can't access
// the protected internal TryComputeLength() method of the content. So, it
// will use'Transfer-Encoding: chunked' semantics.
chunkedMode = true;
requestMessage.Headers.TransferEncodingChunked = true;
}
}
}
else if (chunkedMode)
{
throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content);
}
return chunkedMode;
}
private static void AddRequestHeaders(
SafeWinHttpHandle requestHandle,
HttpRequestMessage requestMessage,
CookieContainer cookies)
{
// Get a StringBuilder to use for creating the request headers.
// We cache one in TLS to avoid creating a new one for each request.
StringBuilder requestHeadersBuffer = t_requestHeadersBuilder;
if (requestHeadersBuffer != null)
{
requestHeadersBuffer.Clear();
}
else
{
t_requestHeadersBuilder = requestHeadersBuffer = new StringBuilder();
}
// Manually add cookies.
if (cookies != null && cookies.Count > 0)
{
string cookieHeader = WinHttpCookieContainerAdapter.GetCookieHeader(requestMessage.RequestUri, cookies);
if (!string.IsNullOrEmpty(cookieHeader))
{
requestHeadersBuffer.AppendLine(cookieHeader);
}
}
// Serialize general request headers.
requestHeadersBuffer.AppendLine(requestMessage.Headers.ToString());
// Serialize entity-body (content) headers.
if (requestMessage.Content != null)
{
// TODO (#5523): Content-Length header isn't getting correctly placed using ToString()
// This is a bug in HttpContentHeaders that needs to be fixed.
if (requestMessage.Content.Headers.ContentLength.HasValue)
{
long contentLength = requestMessage.Content.Headers.ContentLength.Value;
requestMessage.Content.Headers.ContentLength = null;
requestMessage.Content.Headers.ContentLength = contentLength;
}
requestHeadersBuffer.AppendLine(requestMessage.Content.Headers.ToString());
}
// Add request headers to WinHTTP request handle.
if (!Interop.WinHttp.WinHttpAddRequestHeaders(
requestHandle,
requestHeadersBuffer,
(uint)requestHeadersBuffer.Length,
Interop.WinHttp.WINHTTP_ADDREQ_FLAG_ADD))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void EnsureSessionHandleExists(WinHttpRequestState state)
{
if (_sessionHandle == null)
{
lock (_lockObject)
{
if (_sessionHandle == null)
{
SafeWinHttpHandle sessionHandle;
uint accessType;
// If a custom proxy is specified and it is really the system web proxy
// (initial WebRequest.DefaultWebProxy) then we need to update the settings
// since that object is only a sentinel.
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy)
{
Debug.Assert(state.Proxy != null);
try
{
state.Proxy.GetProxy(state.RequestMessage.RequestUri);
}
catch (PlatformNotSupportedException)
{
// This is the system web proxy.
state.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
state.Proxy = null;
}
}
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.DoNotUseProxy ||
state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy)
{
// Either no proxy at all or a custom IWebProxy proxy is specified.
// For a custom IWebProxy, we'll need to calculate and set the proxy
// on a per request handle basis using the request Uri. For now,
// we set the session handle to have no proxy.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY;
}
else if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinHttpProxy)
{
// Use WinHTTP per-machine proxy settings which are set using the "netsh winhttp" command.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
}
else
{
// Use WinInet per-user proxy settings.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY;
}
WinHttpTraceHelper.Trace("WinHttpHandler.EnsureSessionHandleExists: proxy accessType={0}", accessType);
sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
accessType,
Interop.WinHttp.WINHTTP_NO_PROXY_NAME,
Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
if (sessionHandle.IsInvalid)
{
int lastError = Marshal.GetLastWin32Error();
WinHttpTraceHelper.Trace("WinHttpHandler.EnsureSessionHandleExists: error={0}", lastError);
if (lastError != Interop.WinHttp.ERROR_INVALID_PARAMETER)
{
ThrowOnInvalidHandle(sessionHandle);
}
// We must be running on a platform earlier than Win8.1/Win2K12R2 which doesn't support
// WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY. So, we'll need to read the Wininet style proxy
// settings ourself using our WinInetProxyHelper object.
_proxyHelper = new WinInetProxyHelper();
sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
_proxyHelper.ManualSettingsOnly ? Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY : Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY,
_proxyHelper.ManualSettingsOnly ? _proxyHelper.Proxy : Interop.WinHttp.WINHTTP_NO_PROXY_NAME,
_proxyHelper.ManualSettingsOnly ? _proxyHelper.ProxyBypass : Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
ThrowOnInvalidHandle(sessionHandle);
}
uint optionAssuredNonBlockingTrue = 1; // TRUE
if (!Interop.WinHttp.WinHttpSetOption(
sessionHandle,
Interop.WinHttp.WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS,
ref optionAssuredNonBlockingTrue,
(uint)sizeof(uint)))
{
// This option is not available on downlevel Windows versions. While it improves
// performance, we can ignore the error that the option is not available.
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION)
{
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
SetSessionHandleOptions(sessionHandle);
_sessionHandle = sessionHandle;
}
}
}
}
private async void StartRequest(WinHttpRequestState state)
{
if (state.CancellationToken.IsCancellationRequested)
{
state.Tcs.TrySetCanceled(state.CancellationToken);
state.ClearSendRequestState();
return;
}
SafeWinHttpHandle connectHandle = null;
try
{
EnsureSessionHandleExists(state);
// Specify an HTTP server.
connectHandle = Interop.WinHttp.WinHttpConnect(
_sessionHandle,
state.RequestMessage.RequestUri.Host,
(ushort)state.RequestMessage.RequestUri.Port,
0);
ThrowOnInvalidHandle(connectHandle);
connectHandle.SetParentHandle(_sessionHandle);
// Try to use the requested version if a known/supported version was explicitly requested.
// Otherwise, we simply use winhttp's default.
string httpVersion = null;
if (state.RequestMessage.Version == HttpVersionInternal.Version10)
{
httpVersion = "HTTP/1.0";
}
else if (state.RequestMessage.Version == HttpVersionInternal.Version11)
{
httpVersion = "HTTP/1.1";
}
// Turn off additional URI reserved character escaping (percent-encoding). This matches
// .NET Framework behavior. System.Uri establishes the baseline rules for percent-encoding
// of reserved characters.
uint flags = Interop.WinHttp.WINHTTP_FLAG_ESCAPE_DISABLE;
if (state.RequestMessage.RequestUri.Scheme == UriScheme.Https)
{
flags |= Interop.WinHttp.WINHTTP_FLAG_SECURE;
}
// Create an HTTP request handle.
state.RequestHandle = Interop.WinHttp.WinHttpOpenRequest(
connectHandle,
state.RequestMessage.Method.Method,
state.RequestMessage.RequestUri.PathAndQuery,
httpVersion,
Interop.WinHttp.WINHTTP_NO_REFERER,
Interop.WinHttp.WINHTTP_DEFAULT_ACCEPT_TYPES,
flags);
ThrowOnInvalidHandle(state.RequestHandle);
state.RequestHandle.SetParentHandle(connectHandle);
// Set callback function.
SetStatusCallback(state.RequestHandle, WinHttpRequestCallback.StaticCallbackDelegate);
// Set needed options on the request handle.
SetRequestHandleOptions(state);
bool chunkedModeForSend = IsChunkedModeForSend(state.RequestMessage);
AddRequestHeaders(
state.RequestHandle,
state.RequestMessage,
_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer ? _cookieContainer : null);
uint proxyAuthScheme = 0;
uint serverAuthScheme = 0;
state.RetryRequest = false;
// The only way to abort pending async operations in WinHTTP is to close the WinHTTP handle.
// We will detect a cancellation request on the cancellation token by registering a callback.
// If the callback is invoked, then we begin the abort process by disposing the handle. This
// will have the side-effect of WinHTTP cancelling any pending I/O and accelerating its callbacks
// on the handle and thus releasing the awaiting tasks in the loop below. This helps to provide
// a more timely, cooperative, cancellation pattern.
using (state.CancellationToken.Register(s => ((WinHttpRequestState)s).RequestHandle.Dispose(), state))
{
do
{
_authHelper.PreAuthenticateRequest(state, proxyAuthScheme);
await InternalSendRequestAsync(state);
if (state.RequestMessage.Content != null)
{
await InternalSendRequestBodyAsync(state, chunkedModeForSend).ConfigureAwait(false);
}
bool receivedResponse = await InternalReceiveResponseHeadersAsync(state) != 0;
if (receivedResponse)
{
// If we're manually handling cookies, we need to add them to the container after
// each response has been received.
if (state.Handler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer)
{
WinHttpCookieContainerAdapter.AddResponseCookiesToContainer(state);
}
_authHelper.CheckResponseForAuthentication(
state,
ref proxyAuthScheme,
ref serverAuthScheme);
}
} while (state.RetryRequest);
}
state.CancellationToken.ThrowIfCancellationRequested();
// Since the headers have been read, set the "receive" timeout to be based on each read
// call of the response body data. WINHTTP_OPTION_RECEIVE_TIMEOUT sets a timeout on each
// lower layer winsock read.
uint optionData = unchecked((uint)_receiveDataTimeout.TotalMilliseconds);
SetWinHttpOption(state.RequestHandle, Interop.WinHttp.WINHTTP_OPTION_RECEIVE_TIMEOUT, ref optionData);
HttpResponseMessage responseMessage = WinHttpResponseParser.CreateResponseMessage(state, _doManualDecompressionCheck);
state.Tcs.TrySetResult(responseMessage);
}
catch (Exception ex)
{
HandleAsyncException(state, state.SavedException ?? ex);
}
finally
{
SafeWinHttpHandle.DisposeAndClearHandle(ref connectHandle);
state.ClearSendRequestState();
}
}
private void SetSessionHandleOptions(SafeWinHttpHandle sessionHandle)
{
SetSessionHandleConnectionOptions(sessionHandle);
SetSessionHandleTlsOptions(sessionHandle);
SetSessionHandleTimeoutOptions(sessionHandle);
}
private void SetSessionHandleConnectionOptions(SafeWinHttpHandle sessionHandle)
{
uint optionData = (uint)_maxConnectionsPerServer;
SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_SERVER, ref optionData);
SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_1_0_SERVER, ref optionData);
}
private void SetSessionHandleTlsOptions(SafeWinHttpHandle sessionHandle)
{
uint optionData = 0;
SslProtocols sslProtocols =
(_sslProtocols == SslProtocols.None) ? SecurityProtocol.DefaultSecurityProtocols : _sslProtocols;
if ((sslProtocols & SslProtocols.Tls) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1;
}
if ((sslProtocols & SslProtocols.Tls11) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1;
}
if ((sslProtocols & SslProtocols.Tls12) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2;
}
SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_SECURE_PROTOCOLS, ref optionData);
}
private void SetSessionHandleTimeoutOptions(SafeWinHttpHandle sessionHandle)
{
if (!Interop.WinHttp.WinHttpSetTimeouts(
sessionHandle,
0,
0,
(int)_sendTimeout.TotalMilliseconds,
(int)_receiveHeadersTimeout.TotalMilliseconds))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void SetRequestHandleOptions(WinHttpRequestState state)
{
SetRequestHandleProxyOptions(state);
SetRequestHandleDecompressionOptions(state.RequestHandle);
SetRequestHandleRedirectionOptions(state.RequestHandle);
SetRequestHandleCookieOptions(state.RequestHandle);
SetRequestHandleTlsOptions(state.RequestHandle);
SetRequestHandleClientCertificateOptions(state.RequestHandle, state.RequestMessage.RequestUri);
SetRequestHandleCredentialsOptions(state);
SetRequestHandleBufferingOptions(state.RequestHandle);
SetRequestHandleHttp2Options(state.RequestHandle, state.RequestMessage.Version);
}
private void SetRequestHandleProxyOptions(WinHttpRequestState state)
{
// We've already set the proxy on the session handle if we're using no proxy or default proxy settings.
// We only need to change it on the request handle if we have a specific IWebProxy or need to manually
// implement Wininet-style auto proxy detection.
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy ||
state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinInetProxy)
{
var proxyInfo = new Interop.WinHttp.WINHTTP_PROXY_INFO();
bool updateProxySettings = false;
Uri uri = state.RequestMessage.RequestUri;
try
{
if (state.Proxy != null)
{
Debug.Assert(state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy);
updateProxySettings = true;
if (state.Proxy.IsBypassed(uri))
{
proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY;
}
else
{
proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY;
Uri proxyUri = state.Proxy.GetProxy(uri);
string proxyString = proxyUri.Scheme + "://" + proxyUri.Authority;
proxyInfo.Proxy = Marshal.StringToHGlobalUni(proxyString);
}
}
else if (_proxyHelper != null && _proxyHelper.AutoSettingsUsed)
{
if (_proxyHelper.GetProxyForUrl(_sessionHandle, uri, out proxyInfo))
{
updateProxySettings = true;
}
}
if (updateProxySettings)
{
GCHandle pinnedHandle = GCHandle.Alloc(proxyInfo, GCHandleType.Pinned);
try
{
SetWinHttpOption(
state.RequestHandle,
Interop.WinHttp.WINHTTP_OPTION_PROXY,
pinnedHandle.AddrOfPinnedObject(),
(uint)Marshal.SizeOf(proxyInfo));
}
finally
{
pinnedHandle.Free();
}
}
}
finally
{
Marshal.FreeHGlobal(proxyInfo.Proxy);
Marshal.FreeHGlobal(proxyInfo.ProxyBypass);
}
}
}
private void SetRequestHandleDecompressionOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = 0;
if (_automaticDecompression != DecompressionMethods.None)
{
if ((_automaticDecompression & DecompressionMethods.GZip) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_DECOMPRESSION_FLAG_GZIP;
}
if ((_automaticDecompression & DecompressionMethods.Deflate) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_DECOMPRESSION_FLAG_DEFLATE;
}
try
{
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_DECOMPRESSION, ref optionData);
}
catch (WinHttpException ex)
{
if (ex.NativeErrorCode != (int)Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION)
{
throw;
}
// We are running on a platform earlier than Win8.1 for which WINHTTP.DLL
// doesn't support this option. So, we'll have to do the decompression
// manually.
_doManualDecompressionCheck = true;
}
}
}
private void SetRequestHandleRedirectionOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = 0;
if (_automaticRedirection)
{
optionData = (uint)_maxAutomaticRedirections;
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS,
ref optionData);
}
optionData = _automaticRedirection ?
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP :
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_NEVER;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY, ref optionData);
}
private void SetRequestHandleCookieOptions(SafeWinHttpHandle requestHandle)
{
if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer ||
_cookieUsePolicy == CookieUsePolicy.IgnoreCookies)
{
uint optionData = Interop.WinHttp.WINHTTP_DISABLE_COOKIES;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_DISABLE_FEATURE, ref optionData);
}
}
private void SetRequestHandleTlsOptions(SafeWinHttpHandle requestHandle)
{
// If we have a custom server certificate validation callback method then
// we need to have WinHTTP ignore some errors so that the callback method
// will have a chance to be called.
uint optionData;
if (_serverCertificateValidationCallback != null)
{
optionData =
Interop.WinHttp.SECURITY_FLAG_IGNORE_UNKNOWN_CA |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_CN_INVALID |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_SECURITY_FLAGS, ref optionData);
}
else if (_checkCertificateRevocationList)
{
// If no custom validation method, then we let WinHTTP do the revocation check itself.
optionData = Interop.WinHttp.WINHTTP_ENABLE_SSL_REVOCATION;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_ENABLE_FEATURE, ref optionData);
}
}
private void SetRequestHandleClientCertificateOptions(SafeWinHttpHandle requestHandle, Uri requestUri)
{
if (requestUri.Scheme != UriScheme.Https)
{
return;
}
X509Certificate2 clientCertificate = null;
if (_clientCertificateOption == ClientCertificateOption.Manual)
{
clientCertificate = CertificateHelper.GetEligibleClientCertificate(ClientCertificates);
}
else
{
clientCertificate = CertificateHelper.GetEligibleClientCertificate();
}
if (clientCertificate != null)
{
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
clientCertificate.Handle,
(uint)Marshal.SizeOf<Interop.Crypt32.CERT_CONTEXT>());
}
else
{
SetNoClientCertificate(requestHandle);
}
}
internal static void SetNoClientCertificate(SafeWinHttpHandle requestHandle)
{
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
IntPtr.Zero,
0);
}
private void SetRequestHandleCredentialsOptions(WinHttpRequestState state)
{
// By default, WinHTTP sets the default credentials policy such that it automatically sends default credentials
// (current user's logged on Windows credentials) to a proxy when needed (407 response). It only sends
// default credentials to a server (401 response) if the server is considered to be on the Intranet.
// WinHttpHandler uses a more granual opt-in model for using default credentials that can be different between
// proxy and server credentials. It will explicitly allow default credentials to be sent at a later stage in
// the request processing (after getting a 401/407 response) when the proxy or server credential is set as
// CredentialCache.DefaultNetworkCredential. For now, we set the policy to prevent any default credentials
// from being automatically sent until we get a 401/407 response.
_authHelper.ChangeDefaultCredentialsPolicy(
state.RequestHandle,
Interop.WinHttp.WINHTTP_AUTH_TARGET_SERVER,
allowDefaultCredentials:false);
}
private void SetRequestHandleBufferingOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = (uint)(_maxResponseHeadersLength * 1024);
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE, ref optionData);
optionData = (uint)_maxResponseDrainSize;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE, ref optionData);
}
private void SetRequestHandleHttp2Options(SafeWinHttpHandle requestHandle, Version requestVersion)
{
Debug.Assert(requestHandle != null);
uint optionData = (requestVersion == HttpVersion20) ? Interop.WinHttp.WINHTTP_PROTOCOL_FLAG_HTTP2 : 0;
if (Interop.WinHttp.WinHttpSetOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_ENABLE_HTTP_PROTOCOL,
ref optionData))
{
WinHttpTraceHelper.Trace("WinHttpHandler.SetRequestHandleHttp2Options: HTTP/2 option supported, setting to {0}", optionData);
}
else
{
WinHttpTraceHelper.Trace("WinHttpHandler.SetRequestHandleHttp2Options: HTTP/2 option not supported");
}
}
private void SetWinHttpOption(SafeWinHttpHandle handle, uint option, ref uint optionData)
{
Debug.Assert(handle != null);
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
ref optionData))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void SetWinHttpOption(SafeWinHttpHandle handle, uint option, string optionData)
{
Debug.Assert(handle != null);
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
optionData,
(uint)optionData.Length))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private static void SetWinHttpOption(
SafeWinHttpHandle handle,
uint option,
IntPtr optionData,
uint optionSize)
{
Debug.Assert(handle != null);
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
optionData,
optionSize))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void HandleAsyncException(WinHttpRequestState state, Exception ex)
{
if (state.CancellationToken.IsCancellationRequested)
{
// If the exception was due to the cancellation token being canceled, throw cancellation exception.
state.Tcs.TrySetCanceled(state.CancellationToken);
}
else if (ex is WinHttpException || ex is IOException || ex is InvalidOperationException)
{
// Wrap expected exceptions as HttpRequestExceptions since this is considered an error during
// execution. All other exception types, including ArgumentExceptions and ProtocolViolationExceptions
// are 'unexpected' or caused by user error and should not be wrapped.
state.Tcs.TrySetException(new HttpRequestException(SR.net_http_client_execution_error, ex));
}
else
{
state.Tcs.TrySetException(ex);
}
}
private void SetOperationStarted()
{
if (!_operationStarted)
{
_operationStarted = true;
}
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_operationStarted)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
private void SetStatusCallback(
SafeWinHttpHandle requestHandle,
Interop.WinHttp.WINHTTP_STATUS_CALLBACK callback)
{
const uint notificationFlags =
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_HANDLES |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_REDIRECT |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_SEND_REQUEST;
IntPtr oldCallback = Interop.WinHttp.WinHttpSetStatusCallback(
requestHandle,
callback,
notificationFlags,
IntPtr.Zero);
if (oldCallback == new IntPtr(Interop.WinHttp.WINHTTP_INVALID_STATUS_CALLBACK))
{
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_INVALID_HANDLE) // Ignore error if handle was already closed.
{
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
}
private void ThrowOnInvalidHandle(SafeWinHttpHandle handle)
{
if (handle.IsInvalid)
{
int lastError = Marshal.GetLastWin32Error();
WinHttpTraceHelper.Trace("WinHttpHandler.ThrowOnInvalidHandle: error={0}", lastError);
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
private RendezvousAwaitable<int> InternalSendRequestAsync(WinHttpRequestState state)
{
lock (state.Lock)
{
state.Pin();
if (!Interop.WinHttp.WinHttpSendRequest(
state.RequestHandle,
null,
0,
IntPtr.Zero,
0,
0,
state.ToIntPtr()))
{
// Dispose (which will unpin) the state object. Since this failed, WinHTTP won't associate
// our context value (state object) to the request handle. And thus we won't get HANDLE_CLOSING
// notifications which would normally cause the state object to be unpinned and disposed.
state.Dispose();
WinHttpException.ThrowExceptionUsingLastError();
}
}
return state.LifecycleAwaitable;
}
private async Task InternalSendRequestBodyAsync(WinHttpRequestState state, bool chunkedModeForSend)
{
using (var requestStream = new WinHttpRequestStream(state, chunkedModeForSend))
{
await state.RequestMessage.Content.CopyToAsync(
requestStream,
state.TransportContext).ConfigureAwait(false);
await requestStream.EndUploadAsync(state.CancellationToken).ConfigureAwait(false);
}
}
private RendezvousAwaitable<int> InternalReceiveResponseHeadersAsync(WinHttpRequestState state)
{
lock (state.Lock)
{
if (!Interop.WinHttp.WinHttpReceiveResponse(state.RequestHandle, IntPtr.Zero))
{
throw WinHttpException.CreateExceptionUsingLastError();
}
}
return state.LifecycleAwaitable;
}
}
}
| |
// ****************************************************************
// Copyright 2008, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
#if !NETCF_1_0
using System;
using System.Runtime.InteropServices;
namespace NAssert.Constraints
{
/// <summary>Helper routines for working with floating point numbers</summary>
/// <remarks>
/// <para>
/// The floating point comparison code is based on this excellent article:
/// http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
/// </para>
/// <para>
/// "ULP" means Unit in the Last Place and in the context of this library refers to
/// the distance between two adjacent floating point numbers. IEEE floating point
/// numbers can only represent a finite subset of natural numbers, with greater
/// accuracy for smaller numbers and lower accuracy for very large numbers.
/// </para>
/// <para>
/// If a comparison is allowed "2 ulps" of deviation, that means the values are
/// allowed to deviate by up to 2 adjacent floating point values, which might be
/// as low as 0.0000001 for small numbers or as high as 10.0 for large numbers.
/// </para>
/// </remarks>
public class FloatingPointNumerics
{
#region struct FloatIntUnion
/// <summary>Union of a floating point variable and an integer</summary>
[StructLayout(LayoutKind.Explicit)]
private struct FloatIntUnion
{
/// <summary>The union's value as a floating point variable</summary>
[FieldOffset(0)]
public float Float;
/// <summary>The union's value as an integer</summary>
[FieldOffset(0)]
public int Int;
/// <summary>The union's value as an unsigned integer</summary>
[FieldOffset(0)]
public uint UInt;
}
#endregion // struct FloatIntUnion
#region struct DoubleLongUnion
/// <summary>Union of a double precision floating point variable and a long</summary>
[StructLayout(LayoutKind.Explicit)]
private struct DoubleLongUnion
{
/// <summary>The union's value as a double precision floating point variable</summary>
[FieldOffset(0)]
public double Double;
/// <summary>The union's value as a long</summary>
[FieldOffset(0)]
public long Long;
/// <summary>The union's value as an unsigned long</summary>
[FieldOffset(0)]
public ulong ULong;
}
#endregion // struct DoubleLongUnion
/// <summary>Compares two floating point values for equality</summary>
/// <param name="left">First floating point value to be compared</param>
/// <param name="right">Second floating point value t be compared</param>
/// <param name="maxUlps">
/// Maximum number of representable floating point values that are allowed to
/// be between the left and the right floating point values
/// </param>
/// <returns>True if both numbers are equal or close to being equal</returns>
/// <remarks>
/// <para>
/// Floating point values can only represent a finite subset of natural numbers.
/// For example, the values 2.00000000 and 2.00000024 can be stored in a float,
/// but nothing inbetween them.
/// </para>
/// <para>
/// This comparison will count how many possible floating point values are between
/// the left and the right number. If the number of possible values between both
/// numbers is less than or equal to maxUlps, then the numbers are considered as
/// being equal.
/// </para>
/// <para>
/// Implementation partially follows the code outlined here:
/// http://www.anttirt.net/2007/08/19/proper-floating-point-comparisons/
/// </para>
/// </remarks>
public static bool AreAlmostEqualUlps(float left, float right, int maxUlps)
{
FloatIntUnion leftUnion = new FloatIntUnion();
FloatIntUnion rightUnion = new FloatIntUnion();
leftUnion.Float = left;
rightUnion.Float = right;
uint leftSignMask = (leftUnion.UInt >> 31);
uint rightSignMask = (rightUnion.UInt >> 31);
uint leftTemp = ((0x80000000 - leftUnion.UInt) & leftSignMask);
leftUnion.UInt = leftTemp | (leftUnion.UInt & ~leftSignMask);
uint rightTemp = ((0x80000000 - rightUnion.UInt) & rightSignMask);
rightUnion.UInt = rightTemp | (rightUnion.UInt & ~rightSignMask);
return (Math.Abs(leftUnion.Int - rightUnion.Int) <= maxUlps);
}
/// <summary>Compares two double precision floating point values for equality</summary>
/// <param name="left">First double precision floating point value to be compared</param>
/// <param name="right">Second double precision floating point value t be compared</param>
/// <param name="maxUlps">
/// Maximum number of representable double precision floating point values that are
/// allowed to be between the left and the right double precision floating point values
/// </param>
/// <returns>True if both numbers are equal or close to being equal</returns>
/// <remarks>
/// <para>
/// Double precision floating point values can only represent a limited series of
/// natural numbers. For example, the values 2.0000000000000000 and 2.0000000000000004
/// can be stored in a double, but nothing inbetween them.
/// </para>
/// <para>
/// This comparison will count how many possible double precision floating point
/// values are between the left and the right number. If the number of possible
/// values between both numbers is less than or equal to maxUlps, then the numbers
/// are considered as being equal.
/// </para>
/// <para>
/// Implementation partially follows the code outlined here:
/// http://www.anttirt.net/2007/08/19/proper-floating-point-comparisons/
/// </para>
/// </remarks>
public static bool AreAlmostEqualUlps(double left, double right, long maxUlps)
{
DoubleLongUnion leftUnion = new DoubleLongUnion();
DoubleLongUnion rightUnion = new DoubleLongUnion();
leftUnion.Double = left;
rightUnion.Double = right;
ulong leftSignMask = (leftUnion.ULong >> 63);
ulong rightSignMask = (rightUnion.ULong >> 63);
ulong leftTemp = ((0x8000000000000000 - leftUnion.ULong) & leftSignMask);
leftUnion.ULong = leftTemp | (leftUnion.ULong & ~leftSignMask);
ulong rightTemp = ((0x8000000000000000 - rightUnion.ULong) & rightSignMask);
rightUnion.ULong = rightTemp | (rightUnion.ULong & ~rightSignMask);
return (Math.Abs(leftUnion.Long - rightUnion.Long) <= maxUlps);
}
/// <summary>
/// Reinterprets the memory contents of a floating point value as an integer value
/// </summary>
/// <param name="value">
/// Floating point value whose memory contents to reinterpret
/// </param>
/// <returns>
/// The memory contents of the floating point value interpreted as an integer
/// </returns>
public static int ReinterpretAsInt(float value)
{
FloatIntUnion union = new FloatIntUnion();
union.Float = value;
return union.Int;
}
/// <summary>
/// Reinterprets the memory contents of a double precision floating point
/// value as an integer value
/// </summary>
/// <param name="value">
/// Double precision floating point value whose memory contents to reinterpret
/// </param>
/// <returns>
/// The memory contents of the double precision floating point value
/// interpreted as an integer
/// </returns>
public static long ReinterpretAsLong(double value)
{
DoubleLongUnion union = new DoubleLongUnion();
union.Double = value;
return union.Long;
}
/// <summary>
/// Reinterprets the memory contents of an integer as a floating point value
/// </summary>
/// <param name="value">Integer value whose memory contents to reinterpret</param>
/// <returns>
/// The memory contents of the integer value interpreted as a floating point value
/// </returns>
public static float ReinterpretAsFloat(int value)
{
FloatIntUnion union = new FloatIntUnion();
union.Int = value;
return union.Float;
}
/// <summary>
/// Reinterprets the memory contents of an integer value as a double precision
/// floating point value
/// </summary>
/// <param name="value">Integer whose memory contents to reinterpret</param>
/// <returns>
/// The memory contents of the integer interpreted as a double precision
/// floating point value
/// </returns>
public static double ReinterpretAsDouble(long value)
{
DoubleLongUnion union = new DoubleLongUnion();
union.Long = value;
return union.Double;
}
private FloatingPointNumerics()
{
}
}
}
#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.Runtime.InteropServices;
using Xunit;
namespace System.Buffers.Tests
{
public class BufferReferenceTests
{
public static void TestMemoryManager(Func<MemoryManager<byte>> create, Action<MemoryManager<byte>> dispose = null)
{
RunTest(BufferLifetimeBasics, create, dispose);
RunTest(MemoryHandleDoubleFree, create, dispose);
RunTest(Span, create, dispose);
RunTest(Buffer, create, dispose);
RunTest(Pin, create, dispose);
RunTest(Dispose, create, dispose);
RunTest(buffer => TestBuffer(() => buffer.Memory), create, dispose);
//RunTest(OverRelease, create, dispose); // TODO: corfxlab #1571
}
public static void TestAutoOwnedBuffer(Func<MemoryManager<byte>> create, Action<MemoryManager<byte>> dispose = null)
{
RunTest(BufferLifetimeBasicsAuto, create, dispose);
RunTest(MemoryHandleDoubleFreeAuto, create, dispose);
RunTest(Span, create, dispose);
RunTest(Buffer, create, dispose);
RunTest(Pin, create, dispose);
RunTest(DisposeAuto, create, dispose);
RunTest(buffer => TestBuffer(() => buffer.Memory), create, dispose);
//RunTest(OverRelease, create, dispose); // TODO: corfxlab #1571
}
static void RunTest(Action<MemoryManager<byte>> test, Func<MemoryManager<byte>> create,
Action<MemoryManager<byte>> dispose)
{
var buffer = create();
try
{
test(buffer);
}
finally
{
dispose?.Invoke(buffer);
}
}
static void MemoryAccessBasics(MemoryManager<byte> buffer)
{
var span = buffer.GetSpan();
span[10] = 10;
var memory = buffer.Memory;
Assert.Equal(memory.Length, span.Length);
Assert.Equal(10, span[10]);
Assert.Equal(10, memory.Span[10]);
var array = memory.ToArray();
Assert.Equal(memory.Length, array.Length);
Assert.Equal(10, array[10]);
Span<byte> copy = new byte[20];
memory.Span.Slice(10, 20).CopyTo(copy);
Assert.Equal(10, copy[0]);
}
// tests OwnedMemory.Span overloads
static void Span(MemoryManager<byte> buffer)
{
var span = buffer.GetSpan();
var memory = buffer.Memory;
var fullSlice = buffer.GetSpan().Slice(0, memory.Length);
for (int i = 0; i < span.Length; i++)
{
span[i] = (byte)(i % 254 + 1);
Assert.Equal(span[i], fullSlice[i]);
}
var slice = buffer.GetSpan().Slice(5, memory.Length - 5);
Assert.Equal(span.Length - 5, slice.Length);
for (int i = 0; i < slice.Length; i++)
{
Assert.Equal(span[i + 5], slice[i]);
}
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
buffer.GetSpan().Slice(memory.Length, 1);
});
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
buffer.GetSpan().Slice(1, memory.Length);
});
}
// tests that OwnedMemory.Memory and OwnedMemory.ReadOnlyMemory point to the same memory
static void Buffer(MemoryManager<byte> buffer)
{
var rwBuffer = buffer.Memory;
var rwSpan = rwBuffer.Span;
ReadOnlyMemory<byte> roBuffer = buffer.Memory;
var roSpan = roBuffer.Span;
Assert.Equal(roSpan.Length, rwSpan.Length);
for (int i = 0; i < roSpan.Length; i++)
{
var value = roSpan[i];
byte newValue = (byte)(value + 1);
rwSpan[i] = newValue;
Assert.Equal(newValue, roSpan[i]);
}
}
static void Pin(MemoryManager<byte> buffer)
{
var memory = buffer.Memory;
var handle = memory.Pin();
unsafe
{
Assert.NotEqual(0L, new IntPtr(handle.Pointer).ToInt64());
}
handle.Dispose();
}
static void Dispose(MemoryManager<byte> buffer)
{
var length = buffer.Memory.Length;
((IDisposable)buffer).Dispose();
Assert.ThrowsAny<ObjectDisposedException>(() =>
{
var ignore = buffer.GetSpan();
});
Assert.ThrowsAny<ObjectDisposedException>(() =>
{
buffer.GetSpan().Slice(0, length);
});
Assert.ThrowsAny<ObjectDisposedException>(() =>
{
buffer.Pin();
});
Assert.ThrowsAny<ObjectDisposedException>(() =>
{
var rwBuffer = buffer.Memory;
});
Assert.ThrowsAny<ObjectDisposedException>((Action)(() =>
{
ReadOnlyMemory<byte> roBuffer = buffer.Memory;
}));
}
static void DisposeAuto(MemoryManager<byte> buffer)
{
var length = buffer.Memory.Length;
((IDisposable)buffer).Dispose();
Assert.ThrowsAny<ObjectDisposedException>(() =>
{
var ignore = buffer.GetSpan();
});
Assert.ThrowsAny<ObjectDisposedException>(() =>
{
buffer.GetSpan().Slice(0, length);
});
Assert.ThrowsAny<ObjectDisposedException>(() =>
{
buffer.Pin();
});
Assert.ThrowsAny<ObjectDisposedException>(() =>
{
var rwBuffer = buffer.Memory;
});
Assert.ThrowsAny<ObjectDisposedException>((Action)(() =>
{
ReadOnlyMemory<byte> roBuffer = buffer.Memory;
}));
}
static void OverRelease(MemoryManager<byte> buffer)
{
Assert.ThrowsAny<InvalidOperationException>(() =>
{
buffer.Unpin();
});
}
static void BufferLifetimeBasics(MemoryManager<byte> buffer)
{
Memory<byte> copyStoredForLater;
try
{
Memory<byte> memory = buffer.Memory;
Memory<byte> slice = memory.Slice(10);
copyStoredForLater = slice;
MemoryHandle handle = slice.Pin();
handle.Dispose(); // release reservation
}
finally
{
((IDisposable)buffer).Dispose(); // can finish dispose with no exception
}
Assert.ThrowsAny<ObjectDisposedException>(() =>
{
// memory is disposed; cannot use copy stored for later
var span = copyStoredForLater.Span;
});
}
static void BufferLifetimeBasicsAuto(MemoryManager<byte> buffer)
{
Memory<byte> copyStoredForLater;
try
{
Memory<byte> memory = buffer.Memory;
Memory<byte> slice = memory.Slice(10);
copyStoredForLater = slice;
var handle = slice.Pin();
handle.Dispose(); // release reservation
}
finally
{
((IDisposable)buffer).Dispose(); // can finish dispose with no exception
}
Assert.ThrowsAny<ObjectDisposedException>(() =>
{
// memory is disposed; cannot use copy stored for later
var span = copyStoredForLater.Span;
});
}
static void MemoryHandleDoubleFree(MemoryManager<byte> buffer)
{
var memory = buffer.Memory;
var handle = memory.Pin();
buffer.Pin();
handle.Dispose();
handle.Dispose();
buffer.Unpin();
buffer.Unpin();
}
static void MemoryHandleDoubleFreeAuto(MemoryManager<byte> buffer)
{
var memory = buffer.Memory;
var handle = memory.Pin();
buffer.Pin();
handle.Dispose();
handle.Dispose();
buffer.Unpin();
}
public static void TestBuffer(Func<Memory<byte>> create)
{
BufferBasics(create());
BufferLifetime(create());
}
public static void TestBuffer(Func<ReadOnlyMemory<byte>> create)
{
BufferBasics(create());
BufferLifetime(create());
}
static void BufferBasics(Memory<byte> buffer)
{
var span = buffer.Span;
Assert.Equal(buffer.Length, span.Length);
Assert.True(buffer.IsEmpty || buffer.Length != 0);
Assert.True(!buffer.IsEmpty || buffer.Length == 0);
for (int i = 0; i < span.Length; i++) span[i] = 100;
var array = buffer.ToArray();
for (int i = 0; i < array.Length; i++) Assert.Equal(array[i], span[i]);
if (MemoryMarshal.TryGetArray<byte>(buffer, out var segment))
{
Assert.Equal(segment.Count, array.Length);
for (int i = 0; i < array.Length; i++) Assert.Equal(array[i], segment.Array[i + segment.Offset]);
}
if (buffer.Length > 0)
{
var slice = buffer.Slice(1);
for (int i = 0; i < slice.Length; i++) slice.Span[i] = 101;
for (int i = 0; i < slice.Length; i++) Assert.Equal(slice.Span[i], span[i + 1]);
}
}
static void BufferLifetime(Memory<byte> buffer)
{
var array = buffer.ToArray();
using (var pinned = buffer.Pin())
{
unsafe
{
var p = (byte*)pinned.Pointer;
if (buffer.Length == 0)
{
Assert.True(null == p);
}
else
{
Assert.True(null != p);
for (int i = 0; i < buffer.Length; i++)
{
Assert.Equal(array[i], p[i]);
}
}
}
}
// TODO: the following using statement does not work ...
// AutoDisposeBuffer is getting disposed above. Are we ok with this?
//using(var handle = buffer.Retain())
//{
//}
}
static void BufferBasics(ReadOnlyMemory<byte> buffer)
{
var span = buffer.Span;
Assert.Equal(buffer.Length, span.Length);
Assert.True(buffer.IsEmpty || buffer.Length != 0);
Assert.True(!buffer.IsEmpty || buffer.Length == 0);
var array = buffer.ToArray();
for (int i = 0; i < array.Length; i++) Assert.Equal(array[i], span[i]);
if (buffer.Length > 0)
{
var slice = buffer.Slice(1);
for (int i = 0; i < slice.Length; i++) Assert.Equal(slice.Span[i], span[i + 1]);
}
}
static void BufferLifetime(ReadOnlyMemory<byte> buffer)
{
var array = buffer.ToArray();
using (var pinned = buffer.Pin())
{
unsafe
{
var p = (byte*)pinned.Pointer;
if (buffer.Length == 0)
{
Assert.True(null == p);
}
else
{
Assert.True(null != p);
for (int i = 0; i < buffer.Length; i++)
{
Assert.Equal(array[i], p[i]);
}
}
}
}
}
}
}
| |
using System;
using System.Data.Common;
using System.Diagnostics;
using System.Data;
using System.Xml.Linq;
using ALinq.SqlClient;
using Oracle.DataAccess.Client;
namespace ALinq.Oracle.Odp
{
class OracleTypeSystemProvider : SqlTypeSystem.Sql2000Provider
{
public override IProviderType Parse(string stype)
{
if (stype == "Cursor")
return new SqlTypeSystem.SqlType(SqlDbType.Udt);
return base.Parse(stype);
}
public override IProviderType ReturnTypeOfFunction(SqlFunctionCall functionCall)
{
switch (functionCall.Name)
{
case "TO_BYTE":
return SqlTypeSystem.Create(SqlDbType.Decimal);
}
return base.ReturnTypeOfFunction(functionCall);
}
public override IProviderType From(Type type, int? size)
{
if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
type = type.GetGenericArguments()[0];
}
TypeCode typeCode = Type.GetTypeCode(type);
switch (typeCode)
{
case TypeCode.Object:
if (type != typeof(Guid))
{
if ((type == typeof(byte[])) || (type == typeof(Binary)))
{
return base.GetBestType(SqlDbType.VarBinary, size);
}
if (type == typeof(char[]))
{
return base.GetBestType(SqlDbType.NVarChar, size);
}
if (type == typeof(TimeSpan))
{
return SqlTypeSystem.Create(SqlDbType.BigInt);
}
if ((type != typeof(XDocument)) && (type != typeof(XElement)))
{
return new SqlTypeSystem.SqlType(type);
}
return SqlTypeSystem.theNText;
}
return SqlTypeSystem.Create(SqlDbType.UniqueIdentifier);
case TypeCode.Boolean:
return SqlTypeSystem.Create(SqlDbType.Bit);
case TypeCode.Char:
return SqlTypeSystem.Create(SqlDbType.NChar, 1);
case TypeCode.SByte:
case TypeCode.Int16:
return SqlTypeSystem.Create(SqlDbType.SmallInt);
case TypeCode.Byte:
return SqlTypeSystem.Create(SqlDbType.TinyInt);
case TypeCode.UInt16:
case TypeCode.Int32:
return SqlTypeSystem.Create(SqlDbType.Int);
case TypeCode.UInt32:
case TypeCode.Int64:
return SqlTypeSystem.Create(SqlDbType.BigInt);
case TypeCode.UInt64:
return SqlTypeSystem.Create(SqlDbType.Decimal, 20, 0);
case TypeCode.Single:
return SqlTypeSystem.Create(SqlDbType.Real);
case TypeCode.Double:
return SqlTypeSystem.Create(SqlDbType.Float);
case TypeCode.Decimal:
{
int? nullable = size;
return SqlTypeSystem.Create(SqlDbType.Decimal, 0x1d, nullable.HasValue ? nullable.GetValueOrDefault() : 4);
}
case TypeCode.DateTime:
return SqlTypeSystem.Create(SqlDbType.DateTime);
case TypeCode.String:
return base.GetBestType(SqlDbType.NVarChar, size);
}
throw SqlClient.Error.UnexpectedTypeCode(typeCode);
}
public override void InitializeParameter(IProviderType type, DbParameter parameter, object value)
{
var parameter2 = parameter as OracleParameter;//System.Data.SqlClient.SqlParameter;
if (parameter2 == null)
{
base.InitializeParameter(type, parameter, value);
return;
}
var type2 = (SqlTypeSystem.SqlType)type;
if (type2.IsRuntimeOnlyType)
{
throw SqlClient.Error.BadParameterType(type2.GetClosestRuntimeType());
}
Debug.Assert(parameter2 != null);
parameter2.OracleDbType = ToOracleType((SqlDbType)type2.SqlDbType);
if (type2.HasPrecisionAndScale)
{
parameter2.Precision = (byte)type2.Precision;
parameter2.Scale = (byte)type2.Scale;
}
if (type2.HasPrecisionAndScale)
{
parameter2.Precision = (byte)type2.Precision;
parameter2.Scale = (byte)type2.Scale;
}
parameter.Value = GetParameterValue(type2, value);
if (!((parameter.Direction == ParameterDirection.Input) && type2.IsFixedSize) &&
(parameter.Direction == ParameterDirection.Input))
return;
if (type2.Size.HasValue)
{
if (parameter.Size < type2.Size)
{
parameter.Size = type2.Size.Value;
}
}
if (!type2.IsLargeType)
{
return;
}
}
OracleDbType ToOracleType(SqlDbType sqlDbType)
{
switch (sqlDbType)
{
case SqlDbType.BigInt:
return OracleDbType.Decimal;
case SqlDbType.Binary:
return OracleDbType.Blob;
case SqlDbType.Bit:
return OracleDbType.Byte;
case SqlDbType.Char:
return OracleDbType.Char;
case SqlDbType.Date:
case SqlDbType.DateTime:
case SqlDbType.DateTime2:
return OracleDbType.Date;
case SqlDbType.DateTimeOffset:
break;
case SqlDbType.Decimal:
return OracleDbType.Decimal;
case SqlDbType.Float:
return OracleDbType.Double;
case SqlDbType.Image:
return OracleDbType.LongRaw;
case SqlDbType.Int:
return OracleDbType.Int32;
case SqlDbType.Money:
return OracleDbType.Decimal;
case SqlDbType.NChar:
return OracleDbType.NChar;
case SqlDbType.NText:
return OracleDbType.NClob;
case SqlDbType.NVarChar:
return OracleDbType.NVarchar2;
case SqlDbType.Real:
return OracleDbType.Single;
case SqlDbType.SmallDateTime:
return OracleDbType.Date;
case SqlDbType.SmallInt:
return OracleDbType.Int16;
case SqlDbType.SmallMoney:
return OracleDbType.Decimal;
case SqlDbType.Text:
return OracleDbType.Clob;
case SqlDbType.Time:
return OracleDbType.Date;
case SqlDbType.Timestamp:
return OracleDbType.TimeStamp;
case SqlDbType.TinyInt:
return OracleDbType.Byte;
case SqlDbType.Udt:
return OracleDbType.RefCursor;
case SqlDbType.UniqueIdentifier:
return OracleDbType.Raw;
case SqlDbType.VarBinary:
return OracleDbType.LongRaw;
case SqlDbType.VarChar:
return OracleDbType.Varchar2;
case SqlDbType.Variant:
return OracleDbType.LongRaw;
case SqlDbType.Xml:
return OracleDbType.Varchar2;
}
return OracleDbType.Varchar2;
}
protected override object GetParameterValue(SqlTypeSystem.SqlType type, object value)
{
if (value != null && value.GetType() == typeof(Guid))
{
return ((Guid)value).ToByteArray();
}
return base.GetParameterValue(type, value);
}
}
}
| |
using System;
using System.IO;
using System.Runtime.InteropServices;
using NAudio.Wave;
namespace NAudio.Ogg
{
/// <summary>
/// Provides access to the unmanaged ogg encoder DLL
/// </summary>
[Obsolete("Don't expect this class to stay in NAudio, it has not been used for many years")]
public class OggEncoder : IDisposable
{
private const int READ = 1024;
private IntPtr memPool = IntPtr.Zero;
private int memPos = 0;
private const int MEM_POOL_SIZE = 2048;
private IntPtr AllocateHGlobal(int bytes)
{
if(memPool == IntPtr.Zero)
{
memPool = Marshal.AllocHGlobal(MEM_POOL_SIZE);
memPos = 0;
}
if(memPos + bytes > MEM_POOL_SIZE)
{
throw new ApplicationException("Need a bigger memory pool");
}
IntPtr ret = new IntPtr(memPool.ToInt32() + memPos);
memPos += bytes;
for(int n = 0; n < bytes; n++)
{
Marshal.WriteByte(ret,n,0);
}
GC.KeepAlive(this);
return ret;
//return Marshal.AllocHGlobal(bytes);
}
private void FreeHGlobal()
{
Marshal.FreeHGlobal(memPool);
memPos = 0;
memPool = IntPtr.Zero;
}
// some buffers comfortably big enough for the various ogg / vorbis structures
IntPtr os; // ogg_stream_state take physical pages, weld into a logical stream of packets
IntPtr op; // ogg_packet one raw packet of data for decode
IntPtr vi; // vorbis_info struct that stores all the static vorbis bitstream settings
IntPtr vc; // vorbis_comment struct that stores all the user comments
IntPtr vd; // vorbis_dsp_state central working state for the packet->PCM decoder
IntPtr vb; // vorbis_block local working space for packet->PCM decode
//ogg_page og = new ogg_page(); // ogg_page one Ogg bitstream page. Vorbis packets are inside
IntPtr og; // ogg_page one Ogg bitstream page. Vorbis packets are inside
/// <summary>
/// Creates a new ogg encoder
/// </summary>
public OggEncoder()
{
// We must use IntPtrs as the vd structure will contain a
// pointer to the vi structure, so we can't allow it to move
// around in memory during a garbage collection
// we are allocating comfortably more than we need to just for safety
os = AllocateHGlobal(512);
vb = AllocateHGlobal(256);
vd = AllocateHGlobal(256);
vi = AllocateHGlobal(64);
op = AllocateHGlobal(64);
vc = AllocateHGlobal(32);
og = AllocateHGlobal(32);
}
/// <summary>
/// Finalizer for the ogg encoder
/// </summary>
~OggEncoder()
{
System.Diagnostics.Debug.Assert(true,"Ogg encoder wasn't disposed");
Dispose(false);
}
/// <summary>
/// Function to encode a Wave file to OGG
/// </summary>
/// <param name="infile">Wave file name</param>
/// <param name="outfile">Ogg file name</param>
public void Encode(string infile, string outfile)
{
WaveFileReader reader = new WaveFileReader(infile);
Stream stdout = File.OpenWrite(outfile);
try
{
// Encode setup
OggInterop.vorbis_info_init(vi);
// choose an encoding mode
/*********************************************************************
Encoding using a VBR quality mode. The usable range is -.1
(lowest quality, smallest file) to 1. (highest quality, largest file).
Example quality mode .4: 44kHz stereo coupled, roughly 128kbps VBR
ret = vorbis_encode_init_vbr(&vi,2,44100,.4);
---------------------------------------------------------------------
Encoding using an average bitrate mode (ABR).
example: 44kHz stereo coupled, average 128kbps VBR
ret = vorbis_encode_init(&vi,2,44100,-1,128000,-1);
---------------------------------------------------------------------
Encode using a qulity mode, but select that quality mode by asking for
an approximate bitrate. This is not ABR, it is true VBR, but selected
using the bitrate interface, and then turning bitrate management off:
ret = ( vorbis_encode_setup_managed(&vi,2,44100,-1,128000,-1) ||
vorbis_encode_ctl(&vi,OV_ECTL_RATEMANAGE_AVG,NULL) ||
vorbis_encode_setup_init(&vi));
*********************************************************************/
// do not continue if setup failed; this can happen if we ask for a
// mode that libVorbis does not support (eg, too low a bitrate, etc,
// will return 'OV_EIMPL')
if(OggInterop.vorbis_encode_init_vbr(vi,reader.WaveFormat.Channels,reader.WaveFormat.SampleRate,0.5f) != 0)
throw new ApplicationException("vorbis_encode_init_vbr");
// add a comment
//vorbis_comment_init(vc);
//vorbis_comment_add_tag(vc,"ENCODER","OggEncoder.cs");
//vorbis_comment_add_tag(vc,"ARTIST","Mark Heath");
//vorbis_comment_add_tag(vc,"TITLE",Path.GetFileNameWithoutExtension(infile));
// MRH: possibly redundant step, but in the oggtools app
// seems to let us get past the null reference exception in
// vorbis_analysis_init the second time through
// (but then we get stuck on vorbis_info_clear)
OggInterop.vorbis_encode_setup_init(vi);
// set up the analysis state and auxiliary encoding storage
if(OggInterop.vorbis_analysis_init(vd,vi) != 0)
throw new ApplicationException("vorbis_analysis_init error");
if(OggInterop.vorbis_block_init(vd,vb) != 0)
throw new ApplicationException("vorbis_block_init error");
// set up our packet->stream encoder
// pick a random serial number; that way we can more likely build
// chained streams just by concatenation
Random rand = new Random();
if(OggInterop.ogg_stream_init(os,rand.Next()) != 0)
throw new ApplicationException("ogg_stream_init error");
// Vorbis streams begin with three headers; the initial header (with
// most of the codec setup parameters) which is mandated by the Ogg
// bitstream spec. The second header holds any comment fields. The
// third header holds the bitstream codebook. We merely need to
// make the headers, then pass them to libvorbis one at a time;
// libvorbis handles the additional Ogg bitstream constraints
IntPtr header = AllocateHGlobal(64); //ogg_packet
IntPtr header_comments = AllocateHGlobal(64); //ogg_packet
IntPtr header_codebook = AllocateHGlobal(64); //ogg_packet
OggInterop.vorbis_analysis_headerout(vd,vc,header,header_comments,header_codebook);
OggInterop.ogg_stream_packetin(os,header); // automatically placed in its own page
OggInterop.ogg_stream_packetin(os,header_comments);
OggInterop.ogg_stream_packetin(os,header_codebook);
// This ensures the actual audio data will start on a new page, as per spec
while(OggInterop.ogg_stream_flush(os,og) != 0)
{
WriteOg(og,stdout);
}
float[][] samplebuffer = new float[reader.WaveFormat.Channels][];
for(int channel = 0; channel < reader.WaveFormat.Channels; channel++)
{
samplebuffer[channel] = new float[READ];
}
bool eos=false;
while(!eos)
{
int samples = reader.Read(samplebuffer,READ);
if(samples == 0)
{
// end of file. this can be done implicitly in the mainline,
//but it's easier to see here in non-clever fashion.
//Tell the library we're at end of stream so that it can handle
//the last frame and mark end of stream in the output properly
OggInterop.vorbis_analysis_wrote(vd,0);
}
else
{
// data to encode
// expose the buffer to submit data
IntPtr bufferpointer = OggInterop.vorbis_analysis_buffer(vd,samples);
int[] floatpointers = new int[reader.WaveFormat.Channels];
Marshal.Copy(bufferpointer,floatpointers,0,reader.WaveFormat.Channels);
for(int channel = 0; channel < reader.WaveFormat.Channels; channel++)
{
IntPtr channelbuffer = new IntPtr(floatpointers[channel]);
Marshal.Copy(samplebuffer[channel],0,channelbuffer,samples);
}
// tell the library how much we actually submitted
OggInterop.vorbis_analysis_wrote(vd,samples);
}
// vorbis does some data preanalysis, then divvies up blocks for
// more involved (potentially parallel) processing. Get a single
// block for encoding now
while(OggInterop.vorbis_analysis_blockout(vd,vb)==1)
{
/* analysis, assume we want to use bitrate management */
OggInterop.vorbis_analysis(vb,IntPtr.Zero);
OggInterop.vorbis_bitrate_addblock(vb);
while(OggInterop.vorbis_bitrate_flushpacket(vd,op) != 0)
{
/* weld the packet into the bitstream */
OggInterop.ogg_stream_packetin(os,op);
/* write out pages (if any) */
while(!eos)
{
int result=OggInterop.ogg_stream_pageout(os,og);
if(result==0)
break;
WriteOg(og,stdout);
/* this could be set above, but for illustrative purposes, I do
it here (to show that vorbis does know where the stream ends) */
if(OggInterop.ogg_page_eos(og) != 0)
eos=true;
}
}
}
}
// clean up and exit. vorbis_info_clear() must be called last */
if(OggInterop.ogg_stream_clear(os) != 0)
throw new ApplicationException("ogg_stream_clear error");
if(OggInterop.vorbis_block_clear(vb) != 0)
throw new ApplicationException("vorbis_block_clear error");
OggInterop.vorbis_dsp_clear(vd);
//vorbis_comment_clear(vc);
OggInterop.vorbis_info_clear(vi);
// ogg_page and ogg_packet structs always point to storage in
// libvorbis. They're never freed or manipulated directly
}
finally
{
reader.Dispose();
stdout.Close();
}
GC.KeepAlive(this);
}
/* private void WriteOg(ogg_page og,Stream stdout)
{
byte[] ogheader = new byte[og.header_len];
Marshal.Copy(og.header,ogheader,0,og.header_len);
stdout.Write(ogheader,0,og.header_len);
byte[] ogbody = new byte[og.body_len];
Marshal.Copy(og.body,ogbody,0,og.body_len);
stdout.Write(ogbody,0,og.body_len);
}
*/
private void WriteOg(IntPtr ogptr,Stream stdout)
{
ogg_page og = new ogg_page();
//Marshal.PtrToStructure(ogptr,og);
og.header = Marshal.ReadIntPtr(ogptr);
og.header_len = Marshal.ReadInt32(ogptr,4);
og.body = Marshal.ReadIntPtr(ogptr,8);
og.body_len = Marshal.ReadInt32(ogptr,12);
byte[] ogheader = new byte[og.header_len];
Marshal.Copy(og.header,ogheader,0,og.header_len);
stdout.Write(ogheader,0,og.header_len);
byte[] ogbody = new byte[og.body_len];
Marshal.Copy(og.body,ogbody,0,og.body_len);
stdout.Write(ogbody,0,og.body_len);
}
#region IDisposable Members
private void Dispose(bool disposing)
{
FreeHGlobal();
}
/// <summary>
/// Closes the encoder and frees any associated memory
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
namespace Revit.SDK.Samples.CreateBeamSystem.CS
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using Autodesk.Revit.DB;
/// <summary>
/// utility class contains some methods deal with 3D arithmetic
/// </summary>
public class GeometryUtil
{
/// <summary>
/// The Application Creation object is used to create new instances of utility objects.
/// </summary>
public static Autodesk.Revit.Creation.Application CreApp;
/// <summary>
/// judge whether two XYZs are equal
/// </summary>
/// <param name="pnt1">first XYZ</param>
/// <param name="pnt2">second XYZ</param>
/// <returns>is equal</returns>
public static bool CompareXYZ(Autodesk.Revit.DB.XYZ pnt1, Autodesk.Revit.DB.XYZ pnt2)
{
return (MathUtil.CompareDouble(pnt1.X, pnt2.X) &&
MathUtil.CompareDouble(pnt1.Y, pnt2.Y) &&
MathUtil.CompareDouble(pnt1.Z, pnt2.Z));
}
/// <summary>
/// sorted lines end to end to make a closed loop profile
/// if input lines can't make a profile, null will return
/// </summary>
/// <param name="originLines">lines to be sorted</param>
/// <returns>sorted lines which can make a closed loop profile</returns>
public static List<Line> SortLines(List<Line> originLines)
{
// at least 3 lines to form the profile
if (originLines.Count < 3)
{
return null;
}
List<Line> lines = new List<Line>(originLines);
List<Line> result = new List<Line>();
// sorted line end to end in order
result.Add(lines[0]);
Autodesk.Revit.DB.XYZ intersectPnt = lines[0].get_EndPoint(1);
lines[0] = null;
for (int i = 0; i < lines.Count; i++)
{
for (int j = 1; j < lines.Count; j++)
{
if (null == lines[j])
{
continue;
}
if (CompareXYZ(lines[j].get_EndPoint(0), intersectPnt))
{
result.Add(lines[j]);
intersectPnt = lines[j].get_EndPoint(1);
lines[j] = null;
break;
}
else if (CompareXYZ(lines[j].get_EndPoint(1), intersectPnt))
{
Autodesk.Revit.DB.XYZ startPnt = lines[j].get_EndPoint(1);
Autodesk.Revit.DB.XYZ endPnt = lines[j].get_EndPoint(0);
lines[j] = null;
Line inversedLine = CreApp.NewLine(startPnt, endPnt, true);
result.Add(inversedLine);
intersectPnt = inversedLine.get_EndPoint(1);
break;
}
}
}
// there is line doesn't included in the closed loop
if (result.Count != lines.Count)
{
return null;
}
// the last point in the sorted loop is same to the firs point
if (!CompareXYZ(intersectPnt, result[0].get_EndPoint(0)))
{
return null;
}
// make sure there is only one closed region enclosed by the closed loop
for (int i = 0; i < result.Count - 2; i++)
{
for (int j = i + 2; j < result.Count; j++)
{
if (i == 0 && j == (result.Count - 1))
{
continue;
}
Line2D line1 = ConvertTo2DLine(result[i]);
Line2D line2 = ConvertTo2DLine(result[j]);
int count = Line2D.FindIntersection(line1, line2);
// line shouldn't intersect with lines which not adjoin to it
if (count > 0)
{
return null;
}
}
}
return result;
}
/// <summary>
/// judge whether the lines are in the same horizontal plane
/// </summary>
/// <param name="lines">lines to be judged</param>
/// <returns>is in the same horizontal plane</returns>
public static bool InSameHorizontalPlane(List<Line> lines)
{
// all the Z coordinate of lines' start point and end point should be equal
Autodesk.Revit.DB.XYZ firstPnt = lines[0].get_EndPoint(0);
for (int i = 0; i < lines.Count; i++)
{
if (!MathUtil.CompareDouble(lines[i].get_EndPoint(0).Z, firstPnt.Z) ||
!MathUtil.CompareDouble(lines[i].get_EndPoint(1).Z, firstPnt.Z))
{
return false;
}
}
return true;
}
/// <summary>
/// use the X and Y coordinate of 3D Line to new a Line2D instance
/// </summary>
/// <param name="line">3D Line</param>
/// <returns>2D Line</returns>
private static Line2D ConvertTo2DLine(Line line)
{
PointF pnt1 = new PointF((float)line.get_EndPoint(0).X, (float)line.get_EndPoint(0).Y);
PointF pnt2 = new PointF((float)line.get_EndPoint(1).X, (float)line.get_EndPoint(1).Y);
return new Line2D(pnt1, pnt2);
}
}
/// <summary>
/// utility class contains some methods deal with some general arithmetic
/// </summary>
public class MathUtil
{
/// <summary>
/// the minimum double used to compare
/// </summary>
public const double Double_Epsilon = 0.00001;
/// <summary>
/// the minimum positive float used to compare to as zero
/// </summary>
public const float Float_Epsilon = 0.00001f;
/// <summary>
/// forbidden default constructor
/// </summary>
private MathUtil()
{
}
/// <summary>
/// compare whether 2 double is equal using internal precision
/// </summary>
/// <param name="d1">first value</param>
/// <param name="d2">second value</param>
/// <returns>is Equal</returns>
public static bool CompareDouble(double d1, double d2)
{
return Math.Abs(d1 - d2) < Double_Epsilon;
}
/// <summary>
/// dot multiply two vector
/// </summary>
/// <param name="pnt1">first vector</param>
/// <param name="pnt2">second vector</param>
/// <returns>result</returns>
public static float Dot(PointF pnt1, PointF pnt2)
{
return pnt1.X * pnt2.X + pnt1.Y * pnt2.Y;
}
/// <summary>
/// multiply a float with a vector
/// </summary>
/// <param name="f">float value</param>
/// <param name="pnt">vector</param>
/// <returns>result</returns>
public static PointF Multiply(float f, PointF pnt)
{
return new PointF(f * pnt.X, f * pnt.Y);
}
/// <summary>
/// add 2 vector
/// </summary>
/// <param name="f1">first vector</param>
/// <param name="f2">second vector</param>
/// <returns>result</returns>
public static PointF Add(PointF f1, PointF f2)
{
return new PointF(f1.X + f2.X, f1.Y + f2.Y);
}
/// <summary>
/// subtract 2 vector
/// </summary>
/// <param name="f1">first vector</param>
/// <param name="f2">second vector</param>
/// <returns>result</returns>
public static PointF Subtract(PointF f1, PointF f2)
{
return new PointF(f1.X - f2.X, f1.Y - f2.Y);
}
/// <summary>
/// find and calculate the intersection of two interval [u0, u1] and [v0, v1]
/// </summary>
/// <param name="u0">first interval</param>
/// <param name="u1">first interval</param>
/// <param name="v0">second interval</param>
/// <param name="v1">second interval</param>
/// <param name="w">2 intersections</param>
/// <returns>number of intersection</returns>
public static int FindIntersection(float u0, float u1, float v0, float v1, ref float[] w)
{
if (u1 < v0 || u0 > v1)
{
return 0;
}
if (u1 == v0)
{
w[0] = u1;
return 1;
}
if (u0 == v1)
{
w[0] = u0;
return 1;
}
if (u1 > v0)
{
if (u0 < v1)
{
if (u0 < v0)
{
w[0] = v0;
}
else
{
w[0] = u0;
}
if (u1 > v1)
{
w[1] = v1;
}
else
{
w[1] = u1;
}
return 2;
}
else
{
w[0] = u0;
return 1;
}
}
else
{
w[0] = u1;
return 1;
}
}
/// <summary>
/// get the minimum value of 2 float
/// </summary>
/// <param name="f1">first float</param>
/// <param name="f2">second float</param>
/// <returns>minimum float</returns>
public static float GetMin(float f1, float f2)
{
if (f1 < f2)
{
return f1;
}
return f2;
}
/// <summary>
/// get the maximum value of 2 float
/// </summary>
/// <param name="f1">first float</param>
/// <param name="f2">second float</param>
/// <returns>maximum float</returns>
public static float GetMax(float f1, float f2)
{
if (f1 > f2)
{
return f1;
}
return f2;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudioTools
{
internal class ProjectEventArgs : EventArgs
{
public IVsProject Project { get; }
public ProjectEventArgs(IVsProject project)
{
this.Project = project;
}
}
internal class SolutionEventsListener : IVsSolutionEvents3, IVsSolutionEvents4, IVsUpdateSolutionEvents2, IVsUpdateSolutionEvents3, IDisposable
{
private readonly IVsSolution _solution;
private readonly IVsSolutionBuildManager3 _buildManager;
private uint _cookie1 = VSConstants.VSCOOKIE_NIL;
private uint _cookie2 = VSConstants.VSCOOKIE_NIL;
private uint _cookie3 = VSConstants.VSCOOKIE_NIL;
public event EventHandler SolutionOpened;
public event EventHandler SolutionClosed;
public event EventHandler<ProjectEventArgs> ProjectLoaded;
public event EventHandler<ProjectEventArgs> ProjectUnloading;
public event EventHandler<ProjectEventArgs> ProjectClosing;
public event EventHandler<ProjectEventArgs> ProjectRenamed;
public event EventHandler BuildCompleted;
public event EventHandler BuildStarted;
public event EventHandler ActiveSolutionConfigurationChanged;
public SolutionEventsListener(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
throw new ArgumentNullException("serviceProvider");
}
this._solution = serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution;
if (this._solution == null)
{
throw new InvalidOperationException("Cannot get solution service");
}
this._buildManager = serviceProvider.GetService(typeof(SVsSolutionBuildManager)) as IVsSolutionBuildManager3;
}
public SolutionEventsListener(IVsSolution service, IVsSolutionBuildManager3 buildManager = null)
{
if (service == null)
{
throw new ArgumentNullException("service");
}
this._solution = service;
this._buildManager = buildManager;
}
public void StartListeningForChanges()
{
ErrorHandler.ThrowOnFailure(this._solution.AdviseSolutionEvents(this, out this._cookie1));
if (this._buildManager != null)
{
var bm2 = this._buildManager as IVsSolutionBuildManager2;
if (bm2 != null)
{
ErrorHandler.ThrowOnFailure(bm2.AdviseUpdateSolutionEvents(this, out this._cookie2));
}
ErrorHandler.ThrowOnFailure(this._buildManager.AdviseUpdateSolutionEvents3(this, out this._cookie3));
}
}
public void Dispose()
{
// Ignore failures in UnadviseSolutionEvents
if (this._cookie1 != VSConstants.VSCOOKIE_NIL)
{
this._solution.UnadviseSolutionEvents(this._cookie1);
this._cookie1 = VSConstants.VSCOOKIE_NIL;
}
if (this._cookie2 != VSConstants.VSCOOKIE_NIL)
{
((IVsSolutionBuildManager2)this._buildManager).UnadviseUpdateSolutionEvents(this._cookie2);
this._cookie2 = VSConstants.VSCOOKIE_NIL;
}
if (this._cookie3 != VSConstants.VSCOOKIE_NIL)
{
this._buildManager.UnadviseUpdateSolutionEvents3(this._cookie3);
this._cookie3 = VSConstants.VSCOOKIE_NIL;
}
}
int IVsUpdateSolutionEvents2.OnActiveProjectCfgChange(IVsHierarchy pIVsHierarchy)
{
return VSConstants.E_NOTIMPL;
}
int IVsUpdateSolutionEvents2.UpdateProjectCfg_Begin(IVsHierarchy pHierProj, IVsCfg pCfgProj, IVsCfg pCfgSln, uint dwAction, ref int pfCancel)
{
return VSConstants.E_NOTIMPL;
}
int IVsUpdateSolutionEvents2.UpdateProjectCfg_Done(IVsHierarchy pHierProj, IVsCfg pCfgProj, IVsCfg pCfgSln, uint dwAction, int fSuccess, int fCancel)
{
return VSConstants.E_NOTIMPL;
}
public int OnActiveProjectCfgChange(IVsHierarchy pIVsHierarchy)
{
return VSConstants.E_NOTIMPL;
}
public int UpdateSolution_Begin(ref int pfCancelUpdate)
{
var buildStarted = BuildStarted;
if (buildStarted != null)
{
buildStarted(this, EventArgs.Empty);
}
return VSConstants.S_OK;
}
public int UpdateSolution_Cancel()
{
return VSConstants.E_NOTIMPL;
}
public int UpdateSolution_Done(int fSucceeded, int fModified, int fCancelCommand)
{
var buildCompleted = BuildCompleted;
if (buildCompleted != null)
{
buildCompleted(this, EventArgs.Empty);
}
return VSConstants.S_OK;
}
public int UpdateSolution_StartUpdate(ref int pfCancelUpdate)
{
return VSConstants.E_NOTIMPL;
}
int IVsUpdateSolutionEvents3.OnAfterActiveSolutionCfgChange(IVsCfg pOldActiveSlnCfg, IVsCfg pNewActiveSlnCfg)
{
var evt = ActiveSolutionConfigurationChanged;
if (evt != null)
{
evt(this, EventArgs.Empty);
}
return VSConstants.S_OK;
}
int IVsUpdateSolutionEvents3.OnBeforeActiveSolutionCfgChange(IVsCfg pOldActiveSlnCfg, IVsCfg pNewActiveSlnCfg)
{
return VSConstants.E_NOTIMPL;
}
public int OnAfterCloseSolution(object pUnkReserved)
{
var evt = SolutionClosed;
if (evt != null)
{
evt(this, EventArgs.Empty);
}
return VSConstants.S_OK;
}
public int OnAfterClosingChildren(IVsHierarchy pHierarchy)
{
return VSConstants.E_NOTIMPL;
}
public int OnAfterLoadProject(IVsHierarchy pStubHierarchy, IVsHierarchy pRealHierarchy)
{
return VSConstants.E_NOTIMPL;
}
public int OnAfterMergeSolution(object pUnkReserved)
{
return VSConstants.E_NOTIMPL;
}
public int OnAfterOpenProject(IVsHierarchy pHierarchy, int fAdded)
{
var project = pHierarchy as IVsProject;
if (project != null)
{
var evt = ProjectLoaded;
if (evt != null)
{
evt(this, new ProjectEventArgs(project));
}
}
return VSConstants.S_OK;
}
public int OnAfterOpenSolution(object pUnkReserved, int fNewSolution)
{
var evt = SolutionOpened;
if (evt != null)
{
evt(this, EventArgs.Empty);
}
return VSConstants.S_OK;
}
public int OnAfterOpeningChildren(IVsHierarchy pHierarchy)
{
return VSConstants.E_NOTIMPL;
}
public int OnBeforeCloseProject(IVsHierarchy pHierarchy, int fRemoved)
{
var project = pHierarchy as IVsProject;
if (project != null)
{
var evt = ProjectClosing;
if (evt != null)
{
evt(this, new ProjectEventArgs(project));
}
}
return VSConstants.S_OK;
}
public int OnBeforeCloseSolution(object pUnkReserved)
{
return VSConstants.E_NOTIMPL;
}
public int OnBeforeClosingChildren(IVsHierarchy pHierarchy)
{
return VSConstants.E_NOTIMPL;
}
public int OnBeforeOpeningChildren(IVsHierarchy pHierarchy)
{
return VSConstants.E_NOTIMPL;
}
public int OnBeforeUnloadProject(IVsHierarchy pRealHierarchy, IVsHierarchy pStubHierarchy)
{
var project = pRealHierarchy as IVsProject;
if (project != null)
{
var evt = ProjectUnloading;
if (evt != null)
{
evt(this, new ProjectEventArgs(project));
}
}
return VSConstants.S_OK;
}
public int OnQueryCloseProject(IVsHierarchy pHierarchy, int fRemoving, ref int pfCancel)
{
return VSConstants.E_NOTIMPL;
}
public int OnQueryCloseSolution(object pUnkReserved, ref int pfCancel)
{
return VSConstants.E_NOTIMPL;
}
public int OnQueryUnloadProject(IVsHierarchy pRealHierarchy, ref int pfCancel)
{
return VSConstants.E_NOTIMPL;
}
public int OnAfterAsynchOpenProject(IVsHierarchy pHierarchy, int fAdded)
{
return VSConstants.E_NOTIMPL;
}
public int OnAfterChangeProjectParent(IVsHierarchy pHierarchy)
{
return VSConstants.E_NOTIMPL;
}
public int OnAfterRenameProject(IVsHierarchy pHierarchy)
{
var project = pHierarchy as IVsProject;
if (project != null)
{
var evt = ProjectRenamed;
if (evt != null)
{
evt(this, new ProjectEventArgs(project));
}
}
return VSConstants.S_OK;
}
public int OnQueryChangeProjectParent(IVsHierarchy pHierarchy, IVsHierarchy pNewParentHier, ref int pfCancel)
{
return VSConstants.E_NOTIMPL;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
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>, Task<SiloHandle>> CreateSiloAsync { private get; set; } = InProcessSiloHandle.CreateAsync;
/// <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();
await WaitForInitialStabilization();
}
catch (TimeoutException te)
{
FlushLogToConsole();
throw new TimeoutException("Timeout during test initialization", te);
}
catch (Exception ex)
{
await StopAllSilosAsync();
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;
}
}
private async Task WaitForInitialStabilization()
{
// Poll each silo to check that it knows the expected number of active silos.
// If any silo does not have the expected number of active silos in its cluster membership oracle, try again.
// If the cluster membership has not stabilized after a certain period of time, give up and continue anyway.
var totalWait = Stopwatch.StartNew();
while (true)
{
var silos = this.Silos;
var expectedCount = silos.Count;
var remainingSilos = expectedCount;
foreach (var silo in silos)
{
var hooks = this.InternalClient.GetTestHooks(silo);
var statuses = await hooks.GetApproximateSiloStatuses();
var activeCount = statuses.Count(s => s.Value == SiloStatus.Active);
if (activeCount != expectedCount) break;
remainingSilos--;
}
if (remainingSilos == 0)
{
totalWait.Stop();
break;
}
WriteLog($"{remainingSilos} silos do not have a consistent cluster view, waiting until stabilization.");
await Task.Delay(TimeSpan.FromMilliseconds(100));
if (totalWait.Elapsed < TimeSpan.FromSeconds(60))
{
WriteLog($"Warning! {remainingSilos} silos do not have a consistent cluster view after {totalWait.ElapsedMilliseconds}ms, continuing without stabilization.");
break;
}
}
}
/// <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.GetRequiredService<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 StartAdditionalSiloAsync(startAdditionalSiloOnNewPort).GetAwaiter().GetResult();
}
/// <summary>
/// Start an additional silo, so that it joins the existing cluster.
/// </summary>
/// <returns>SiloHandle for the newly started silo.</returns>
public async Task<SiloHandle> StartAdditionalSiloAsync(bool startAdditionalSiloOnNewPort = false)
{
return (await this.StartAdditionalSilosAsync(1, startAdditionalSiloOnNewPort)).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>> StartAdditionalSilosAsync(int silosToStart, bool startAdditionalSiloOnNewPort = false)
{
var instances = new List<SiloHandle>();
if (silosToStart > 0)
{
var siloStartTasks = Enumerable.Range(this.startedInstances, silosToStart)
.Select(instanceNumber => Task.Run(() => StartSiloAsync((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 async Task StopSecondarySilosAsync()
{
foreach (var instance in this.additionalSilos.ToList())
{
await StopSiloAsync(instance);
}
}
/// <summary>
/// Stops the default Primary silo.
/// </summary>
public async Task StopPrimarySiloAsync()
{
if (Primary == null) throw new InvalidOperationException("There is no primary silo");
await StopClusterClientAsync();
await StopSiloAsync(Primary);
}
private async Task StopClusterClientAsync()
{
try
{
await this.InternalClient?.Close();
}
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()
{
StopAllSilosAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Stop all current silos.
/// </summary>
public async Task StopAllSilosAsync()
{
await StopClusterClientAsync();
await StopSecondarySilosAsync();
if (Primary != null)
{
await StopPrimarySiloAsync();
}
AppDomain.CurrentDomain.UnhandledException -= ReportUnobservedException;
}
/// <summary>
/// Do a semi-graceful Stop of the specified silo.
/// </summary>
/// <param name="instance">Silo to be stopped.</param>
public async Task StopSiloAsync(SiloHandle instance)
{
if (instance != null)
{
await StopSiloAsync(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 async Task KillSiloAsync(SiloHandle instance)
{
if (instance != null)
{
// do NOT stop, just kill directly, to simulate crash.
await StopSiloAsync(instance, false);
}
}
/// <summary>
/// Performs a hard kill on client. Client will not cleanup resources.
/// </summary>
public async Task KillClientAsync()
{
await this.InternalClient?.AbortAsync();
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 async Task<SiloHandle> RestartSiloAsync(SiloHandle instance)
{
if (instance != null)
{
var instanceNumber = instance.InstanceNumber;
var siloName = instance.Name;
await StopSiloAsync(instance);
var newInstance = await StartSiloAsync(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 async Task<SiloHandle> RestartStoppedSecondarySiloAsync(string siloName)
{
if (siloName == null) throw new ArgumentNullException(nameof(siloName));
var siloHandle = this.Silos.Single(s => s.Name.Equals(siloName, StringComparison.Ordinal));
var newInstance = await this.StartSiloAsync(this.Silos.IndexOf(siloHandle), this.options);
additionalSilos.Add(newInstance);
return newInstance;
}
/// <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 = await StartSiloAsync(this.startedInstances, this.options);
silosToStart--;
}
if (silosToStart > 0)
{
await this.StartAdditionalSilosAsync(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 async Task<SiloHandle> StartSiloAsync(TestCluster cluster, int instanceNumber, TestClusterOptions clusterOptions, IReadOnlyList<IConfigurationSource> configurationOverrides = null, bool startSiloOnNewPort = false)
{
if (cluster == null) throw new ArgumentNullException(nameof(cluster));
return await cluster.StartSiloAsync(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 async Task<SiloHandle> StartSiloAsync(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 = await this.CreateSiloAsync(siloSpecificOptions.SiloName,configurationSources);
handle.InstanceNumber = (short)instanceNumber;
Interlocked.Increment(ref this.startedInstances);
return handle;
}
private async Task StopSiloAsync(SiloHandle instance, bool stopGracefully)
{
try
{
await instance.StopSiloAsync(stopGracefully);
instance.Dispose();
}
finally
{
Interlocked.Decrement(ref this.startedInstances);
}
}
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());
}
}
}
| |
using System.Collections.Generic;
using System.Threading.Tasks;
using Refit;
using EmsApi.Dto.V2;
namespace EmsApi.Client.V2
{
/// <summary>
/// The interface methods that match the REST signature for the EMS API.
/// </summary>
/// <remarks>
/// These methods are used by the Refit library to generate an implementation to
/// make the actual HTTP calls, so they need to mirror the exposed routes exactly.
/// The library uses code generation to compile the stub implementation into this
/// assembly, so every time this project is built a RefitStubs.g.cs file is generated
/// in the obj folder and included.
///
/// Note: It's important to not use constants in the REST attributes below, the library
/// does not properly generate stubs for these (it seems to omit them).
/// </remarks>
public interface IEmsApi
{
/// <summary>
/// Returns a set of EMS systems the currently logged in user is able to access.
/// </summary>
[Get( "/v2/ems-systems" )]
Task<IEnumerable<EmsSystem>> GetEmsSystems( [Property] CallContext context = null );
/// <summary>
/// Returns some additional server information about the ems system.
/// </summary>
[Get( "/v2/ems-systems/1" )]
Task<EmsSystemInfo> GetEmsSystemInfo( [Property] CallContext context = null );
/// <summary>
/// Returns some additional server information about the ems system.
/// </summary>
/// <param name="search">
/// The case-insensitive search used to filter the returned EMS system information.
/// </param>
[Get( "/v2/ems-systems/1" )]
Task<EmsSystemInfo> GetEmsSystemInfoWithSearch( string search, [Property] CallContext context = null );
/// <summary>
/// Ping an EMS system to verify that the specified system is currently up and running.
/// </summary>
[Get( "/v2/ems-systems/1/ping" )]
Task<bool> PingEmsSystem( [Property] CallContext context = null );
/// <summary>
/// Returns a set of EMS securable items and any associated metadata.
/// </summary>
[Get( "/v2/ems-systems/1/securables" )]
Task<EmsSecurableContainer> GetEmsSecurables( [Property] CallContext context = null );
/// <summary>
/// Returns whether the user has permissions for the provided securable and access right.
/// </summary>
[Get( "/v2/ems-systems/1/securables/{securableId}" )]
Task<EmsSecurableEffectiveAccess> GetEmsSecurableAccess( string securableId, string accessRight, [Property] CallContext context = null );
/// <summary>
/// Returns whether the provided user has permissions for the provided securable and access right.
/// </summary>
/// <remarks>
/// You must have Admin privileges to the EMS API to be able to call this route.
/// </remarks>
[Get( "/v2/admin/ems-systems/1/securables/{securableId}" )]
Task<EmsSecurableEffectiveAccess> AdminGetEmsSecurableAccess( string securableId, string accessRight, string username, [Property] CallContext context = null );
/// <summary>
/// Returns the list of fleets the user has access to in their security context.
/// </summary>
[Get( "/v2/ems-systems/1/assets/fleets" )]
Task<IEnumerable<Fleet>> GetFleets( [Property] CallContext context = null );
/// <summary>
/// Returns information for a fleet on the system.
/// </summary>
/// <param name="fleetId">
/// The unique identifier of the fleet.
/// </param>
[Get( "/v2/ems-systems/1/assets/fleets/{fleetId}" )]
Task<Fleet> GetFleet( int fleetId, [Property] CallContext context = null );
/// <summary>
/// Returns the list of aircraft the user has access to in their security context.
/// </summary>
/// <param name="fleetId">
/// The fleet id to filter by, if any.
/// </param>
[Get( "/v2/ems-systems/1/assets/aircraft" )]
Task<IEnumerable<Aircraft>> GetAllAircraft( int? fleetId = null, [Property] CallContext context = null );
/// <summary>
/// Returns info for an aircraft on the system.
/// </summary>
/// <param name="aircraftId">
/// The unique identifier of the aircraft.
/// </param>
[Get( "/v2/ems-systems/1/assets/aircraft/{aircraftId}" )]
Task<Aircraft> GetSingleAircraft( int aircraftId, [Property] CallContext context = null );
/// <summary>
/// Returns the list of flight phases.
/// </summary>
[Get( "/v2/ems-systems/1/assets/flight-phases" )]
Task<IEnumerable<FlightPhase>> GetFlightPhases( [Property] CallContext context = null );
/// <summary>
/// Returns information for a flight phase on the system.
/// </summary>
/// <param name="flightPhaseId">
/// The unique identifier of the flight phase.
/// </param>
[Get( "/v2/ems-systems/1/assets/flight-phases/{flightPhaseId}" )]
Task<FlightPhase> GetFlightPhase( int flightPhaseId, [Property] CallContext context = null );
/// <summary>
/// Returns the list of airports that have been visited by the EMS system.
/// </summary>
[Get( "/v2/ems-systems/1/assets/airports" )]
Task<IEnumerable<Airport>> GetAirports( [Property] CallContext context = null );
/// <summary>
/// Returns information for an airport on the system.
/// </summary>
/// <param name="airportId">
/// The unique identifier for the airport.
/// </param>
[Get( "/v2/ems-systems/1/assets/airports/{airportId}" )]
Task<Airport> GetAirport( int airportId, [Property] CallContext context = null );
/// <summary>
/// Returns the current trajectory configuration.
/// </summary>
[Get( "/v2/ems-systems/1/trajectory-configurations" )]
Task<IEnumerable<TrajectoryConfiguration>> GetTrajectoryConfigurations( [Property] CallContext context = null );
/// <summary>
/// Returns a trajectory path for the given flight.
/// </summary>
/// <param name="flightId">
/// The flight id to return trajectories for.
/// </param>
[Get( "/v2/ems-systems/1/flights/{flightId}/trajectories" )]
Task<TrajectoryValueArray> GetTrajectory( int flightId, [Property] CallContext context = null );
/// <summary>
/// Returns a KML document XML for the given flight and trajectory id, as a raw string.
/// </summary>
/// <param name="flightId">
/// The flight id to return a trajectory for.
/// </param>
/// <param name="trajectoryId">
/// The string identifier for the trajectory type to return.
/// </param>
[Get( "/v2/ems-systems/1/flights/{flightId}/kml-trajectories/{trajectoryId}" )]
Task<string> GetTrajectoryKml( int flightId, string trajectoryId, [Property] CallContext context = null );
/// <summary>
/// Returns information about the set of APM profiles on the given EMS system.
/// </summary>
/// <param name="parentGroupId">
/// The optional parent profile group ID whose contents to search.
/// </param>
/// <param name="search">
/// An optional profile name search string used to match profiles to return.
/// </param>
[Get( "/v2/ems-systems/1/profiles" )]
Task<IEnumerable<Profile>> GetProfiles( string parentGroupId = null, string search = null, [Property] CallContext context = null );
/// <summary>
/// Returns a profile group with a matching ID containing only its immediate
/// children in a hierarchical tree used to organize profiles.
/// </summary>
/// <param name="groupId">
/// The unique identifier of the profile group whose contents to return. If
/// not specified, the contents of the root group are returned.
/// </param>
[Get( "/v2/ems-systems/1/profile-groups" )]
Task<ProfileGroup> GetProfileGroup( string groupId = null, [Property] CallContext context = null );
/// <summary>
/// Returns APM profile results for the given flight and profile id.
/// </summary>
/// <param name="flightId">
/// The flight id to return APM results for.
/// </param>
/// <param name="profileId">
/// The APM profile guid to return results for, e.g. "A7483C44-9DB9-4A44-9EB5-F67681EE52B0"
/// for the library flight safety events profile.
/// </param>
[Get( "/v2/ems-systems/1/flights/{flightId}/profiles/{profileId}/query" )]
Task<ProfileResults> GetProfileResults( int flightId, string profileId, [Property] CallContext context = null );
/// <summary>
/// Returns a "glossary" for a specific profile and version, which helps define the
/// results that can be returned in a profile.
/// </summary>
/// <param name="profileId">
/// The unique identifier of the profile whose glossary to return, e.g. "A7483C44-9DB9-4A44-9EB5-F67681EE52B0".
/// </param>
/// <param name="profileVersionNumber">
/// Integer version of the profile to return. If not specified the current version of the profile is used by default.
/// </param>
/// <param name="format">
/// The format of the returned glossary. Options are "json" or "csv". Defaults to JSON.
/// </param>
[Get( "/v2/ems-systems/1/profiles/{profileId}/glossary" )]
Task<ProfileGlossary> GetProfileGlossary( string profileId, int? profileVersionNumber = null, string format = null, [Property] CallContext context = null );
/// <summary>
/// Returns the events for a specific profile.
/// </summary>
/// <param name="profileId">
/// The unique identifier of the profile whose events to return, e.g. "A7483C44-9DB9-4A44-9EB5-F67681EE52B0".
/// </param>
[Get( "/v2/ems-systems/1/profiles/{profileId}/events" )]
Task<IEnumerable<Event>> GetProfileEvents( string profileId, [Property] CallContext context = null );
/// <summary>
/// Returns an event for a specific profile.
/// </summary>
/// <param name="profileId">
/// The unique identifier of the profile whose events to return, e.g. "A7483C44-9DB9-4A44-9EB5-F67681EE52B0".
/// </param>
/// <param name="eventId">
/// The integer ID for the event.
/// </param>
[Get( "/v2/ems-systems/1/profiles/{profileId}/events/{eventId}" )]
Task<Event> GetProfileEvent( string profileId, int eventId, [Property] CallContext context = null );
/// <summary>
/// Returns information about the parameter sets on the given EMS system.
/// </summary>
/// <param name="groupId">
/// The optional ID of the parameter set group to return.
/// </param>
[Get( "/v2/ems-systems/1/parameter-sets" )]
Task<ParameterSetGroup> GetParameterSets( string groupId = null, [Property] CallContext context = null );
/// <summary>
/// Searches for analytics by name.
/// </summary>
/// <param name="text">
/// The search terms used to find a list of analytics by name.
/// </param>
/// <param name="group">
/// An optional group ID to specify where to limit the search. If not specified, all groups are searched.
/// </param>
/// <param name="maxResults">
/// The optional maximum number of matching results to return. If not specified, a default value of 200
/// is used. Use 0 to return all results.
/// </param>
/// <param name="category">
/// The category of analytics to search, including "Full", "Physical" or "Logical". A null value specifies
/// the default analytic set, which represents the full set of values exposed by the backing EMS system.
/// </param>
[Get( "/v2/ems-systems/1/analytics" )]
Task<IEnumerable<AnalyticInfo>> GetAnalytics( string text, string group = null, int? maxResults = null, Category category = Category.Full, [Property] CallContext context = null );
/// <summary>
/// Searches for analytics by name for a specific flight.
/// </summary>
/// <param name="flightId">
/// The integer ID of the flight record to use when searching analytics.
/// </param>
/// <param name="text">
/// The search terms used to find a list of analytics by name.
/// </param>
/// <param name="group">
/// An optional group ID to specify where to limit the search. If not specified, all groups are searched.
/// </param>
/// <param name="maxResults">
/// The optional maximum number of matching results to return. If not specified, a default value of 200
/// is used. Use 0 to return all results.
/// </param>
/// <param name="category">
/// The category of analytics to search, including "Full", "Physical" or "Logical". A null value specifies
/// the default analytic set, which represents the full set of values exposed by the backing EMS system.
/// </param>
[Get( "/v2/ems-systems/1/flights/{flightId}/analytics" )]
Task<IEnumerable<AnalyticInfo>> GetAnalyticsWithFlight( int flightId, string text, string group = null, int? maxResults = null, Category category = Category.Full, [Property] CallContext context = null );
/// <summary>
/// Retrieves metadata information associated with an analytic such as a description or units.
/// </summary>
/// <param name="analyticId">
/// The analytic ID for which data is retrieved. These identifiers are typically obtained from nodes in an analytic group tree.
/// </param>
[Post( "/v2/ems-systems/1/analytics" )]
Task<AnalyticInfo> GetAnalyticInfo( [Body] AnalyticId analyticId, [Property] CallContext context = null );
/// <summary>
/// Retrieves metadata information associated with an analytic such as a description or units.
/// </summary>
/// <param name="flightId">
/// The integer ID of the flight record to use when retrieving the analytic information.
/// </param>
/// <param name="analyticId">
/// The analytic ID for which data is retrieved. These identifiers are typically obtained from nodes in an analytic group tree.
/// </param>
[Post( "/v2/ems-systems/1/flights/{flightId}/analytics" )]
Task<AnalyticInfo> GetAnalyticInfoWithFlight( int flightId, [Body] AnalyticId analyticId, [Property] CallContext context = null );
/// <summary>
/// Retrieves the contents of an analytic group, which is a hierarchical tree structure used to organize analytics.
/// </summary>
/// <param name="analyticGroupId">
/// The ID of the group whose contents to retrieve. If not specified, the contents of the root group will be returned.
/// </param>
/// <param name="category">
/// The category of analytics we are interested in. "Full", "Physical" or "Logical". A null value specifies the default
/// analytic set, which represents the full set of values exposed by the backing EMS system.
/// </param>
[Get( "/v2/ems-systems/1/analytic-groups" )]
Task<AnalyticGroupContents> GetAnalyticGroup( string analyticGroupId = null, Category category = Category.Full, [Property] CallContext context = null );
/// <summary>
/// Retrieves the contents of an analytic group, which is a hierarchical tree structure used to organize analytics.
/// </summary>
/// <param name="flightId">
/// The integer ID of the flight record to use when retrieving the analytic information.
/// </param>
/// <param name="analyticGroupId">
/// The ID of the group whose contents to retrieve. If not specified, the contents of the root group will be returned.
/// </param>
/// <param name="category">
/// The category of analytics we are interested in. "Full", "Physical" or "Logical". A null value specifies the default
/// analytic set, which represents the full set of values exposed by the backing EMS system.
/// </param>
[Get( "/v2/ems-systems/1/flights/{flightId}/analytic-groups" )]
Task<AnalyticGroupContents> GetAnalyticGroupWithFlight( int flightId, string analyticGroupId = null, Category category = Category.Full, [Property] CallContext context = null );
/// <summary>
/// Queries offsets and values in time-series data for a specified flight and analytic.
/// </summary>
/// <param name="flightId">
/// The integer ID of the flight record for which to query data.
/// </param>
/// <param name="query">
/// The information used to construct a query for which results are returned.
/// </param>
[Post( "/v2/ems-systems/1/flights/{flightId}/analytics/query" )]
Task<QueryResult> GetAnalyticResults( int flightId, [Body] Query query, [Property] CallContext context = null );
/// <summary>
/// Returns the analytic metadata for a flight.
/// </summary>
/// <param name="flightId">
/// The integer ID of the flight record for which to retrieve data.
/// </param>
/// <param name="analyticId">
/// The analytic ID (wrapped in double quotes) for which metadata is retrieved.
/// These identifiers are typically obtained from nodes in an analytic group tree.
/// </param>
[Post( "/v2/ems-systems/1/flights/{flightId}/analytics/metadata" )]
Task<Metadata> GetAnalyticMetadata( int flightId, [Body] AnalyticId analyticId, [Property] CallContext context = null );
/// <summary>
/// Returns information about the analytic set groups on the given EMS system.
/// </summary>
[Get( "/v2/ems-systems/1/analytic-set-groups" )]
Task<AnalyticSetGroup> GetAnalyticSetGroups( [Property] CallContext context = null );
/// <summary>
/// Returns information about an analytic set group on the given EMS system.
/// </summary>
/// <param name="groupId">
/// The ID of the analytic set group to return.
/// </param>
[Get( "/v2/ems-systems/1/analytic-set-groups/{groupId}" )]
Task<AnalyticSetGroup> GetAnalyticSetGroup( string groupId, [Property] CallContext context = null );
/// <summary>
/// Creates an analytic set group.
/// </summary>
/// <param name="newAnalyticSetGroup">
/// The information needed to create a new analytic set group.
/// </param>
[Post( "/v2/ems-systems/1/analytic-set-groups" )]
Task<AnalyticSetGroupCreated> CreateAnalyticSetGroup( [Body] NewAnalyticSetGroup newAnalyticSetGroup, [Property] CallContext context = null );
/// <summary>
/// Updates an analytic set group. This will alter the location of any analytic sets and groups contained within.
/// </summary>
/// <param name="groupId">
/// The ID of the group to update.
/// </param>
/// <param name="updateAnalyticSetGroup">
/// The information required to update the analytic set group.
/// </param>
[Put( "/v2/ems-systems/1/analytic-set-groups/{groupId}" )]
Task<AnalyticSetGroupUpdated> UpdateAnalyticSetGroup( string groupId, [Body] UpdateAnalyticSetGroup updateAnalyticSetGroup, [Property] CallContext context = null );
/// <summary>
/// Deletes an analytic set group. The group must be empty in order to remove it.
/// </summary>
/// <param name="groupId">
/// The ID of the analytic set group to delete.
/// </param>
[Delete( "/v2/ems-systems/1/analytic-set-groups/{groupId}" )]
Task<object> DeleteAnalyticSetGroup( string groupId, [Property] CallContext context = null );
/// <summary>
/// Returns information about the analytic set on the given EMS system.
/// </summary>
/// <param name="groupId">
/// The ID of the analytic set group where the analytic set exists.
/// </param>
/// <param name="analyticSetName">
/// The name of the analytic set to return.
/// </param>
[Get( "/v2/ems-systems/1/analytic-set-groups/{groupId}/analytic-sets/{analyticSetName}" )]
Task<AnalyticSet> GetAnalyticSet( string groupId, string analyticSetName, [Property] CallContext context = null );
/// <summary>
/// Creates a new analytic set.
/// </summary>
/// <param name="groupId">
/// The ID of the analytic set group where the new analytic set will be created.
/// </param>
/// <param name="newAnalyticSet">
/// The name of analytic set to be created.
/// </param>
[Post( "/v2/ems-systems/1/analytic-set-groups/{groupId}/analytic-sets" )]
Task<AnalyticSetCreated> CreateAnalyticSet( string groupId, [Body] NewAnalyticSet newAnalyticSet, [Property] CallContext context = null );
/// <summary>
/// Updates an existing analytic set.
/// </summary>
/// <param name="groupId">
/// The ID of the analytic set group where the analytic set to update exists.
/// </param>
/// <param name="analyticSetName">
/// The name of the analytic set to update.
/// </param>
/// <param name="updateAnalyticSet">
/// The information required to update the analytic set.
/// </param>
[Put( "/v2/ems-systems/1/analytic-set-groups/{groupId}/analytic-sets/{analyticSetName}" )]
Task<object> UpdateAnalyticSet( string groupId, string analyticSetName, [Body] UpdateAnalyticSet updateAnalyticSet, [Property] CallContext context = null );
/// <summary>
/// Deletes an analytic set.
/// </summary>
/// <param name="groupId">
/// The ID of the analytic set group where the analytic set to remove exists.
/// </param>
/// <param name="analyticSetName">
/// The name of the analytic set to remove.
/// </param>
[Delete( "/v2/ems-systems/1/analytic-set-groups/{groupId}/analytic-sets/{analyticSetName}" )]
Task<object> DeleteAnalyticSet( string groupId, string analyticSetName, [Property] CallContext context = null );
/// <summary>
/// Returns the specified analytic collection.
/// </summary>
/// <param name="groupId">
/// The ID of the group that contains the analytic collection.
/// </param>
/// <param name="analyticCollectionName">
/// The name of the analytic collection to return.
/// </param>
[Get( "/v2/ems-systems/1/analytic-set-groups/{groupId}/analytic-collections/{analyticCollectionName}" )]
Task<AnalyticCollection> GetAnalyticCollection( string groupId, string analyticCollectionName, [Property] CallContext context = null );
/// <summary>
/// Creates a new analytic collection.
/// </summary>
/// <param name="groupId">
/// The ID of the group where the collection will be created.
/// </param>
/// <param name="newAnalyticCollection">
/// The name to assign to the new collection.
/// </param>
[Post( "/v2/ems-systems/1/analytic-set-groups/{groupId}/analytic-collections" )]
Task<AnalyticCollectionCreated> CreateAnalyticCollection( string groupId, [Body] NewAnalyticCollection newAnalyticCollection, [Property] CallContext context = null );
/// <summary>
/// Updates an analytic collection.
/// </summary>
/// <param name="groupId">
/// The ID of the group that contains the analytic collection to update.
/// </param>
/// <param name="analyticCollectionName">
/// The name of the collection to update.
/// </param>
/// <param name="updateAnalyticCollection">
/// The information required to update the collection.
/// </param>
[Put( "/v2/ems-systems/1/analytic-set-groups/{groupId}/analytic-collections/{analyticCollectionName}" )]
Task<object> UpdateAnalyticCollection( string groupId, string analyticCollectionName, [Body] UpdateAnalyticCollection updateAnalyticCollection, [Property] CallContext context = null );
/// <summary>
/// Deletes an analytic collection.
/// </summary>
/// <param name="groupId">
/// The ID of the group where the collection to be removed exists.
/// </param>
/// <param name="analyticCollectionName">
/// The name of the collection to be removed.
/// </param>
[Delete( "/v2/ems-systems/1/analytic-set-groups/{groupId}/analytic-collections/{analyticCollectionName}" )]
Task<object> DeleteAnalyticCollection( string groupId, string analyticCollectionName, [Property] CallContext context = null );
/// <summary>
/// Returns a database group with a matching ID containing only its immediate children
/// in a hierarchical tree used to organize databases.
/// </summary>
/// <param name="groupId">
/// The unique identifier of the EMS database group whose contents to return. If not specified,
/// the contents of the root group are returned.
/// </param>
[Get( "/v2/ems-systems/1/database-groups" )]
Task<DatabaseGroup> GetDatabaseGroup( string groupId = null, [Property] CallContext context = null );
/// <summary>
/// Returns a field group with a matching ID containing only its immediate children in a
/// hierarchical tree used to organize fields.
/// </summary>
/// <param name="databaseId">
/// The unique identifier of the EMS database containing a field group to return.
/// </param>
/// <param name="groupId">
/// The unique identifier of a field group whose contents to return. If not specified,
/// the contents of the root group are returned.
/// </param>
[Get( "/v2/ems-systems/1/databases/{databaseId}/field-groups" )]
Task<FieldGroup> GetDatabaseFieldGroup( string databaseId, string groupId = null, [Property] CallContext context = null );
/// <summary>
/// Returns information about a database field matching the specified ID.
/// </summary>
/// <param name="databaseId">
/// The unique identifier of the EMS database containing a field to return.
/// </param>
/// <param name="fieldId">
/// The unique identifier of the field whose information to return.
/// </param>
[Get( "/v2/ems-systems/1/databases/{databaseId}/fields/{fieldId}" )]
Task<Field> GetDatabaseFieldDefinition( string databaseId, string fieldId, [Property] CallContext context = null );
/// <summary>
/// Returns all the fields matching the specified search options.
/// </summary>
/// <param name="databaseId">
/// The unique identifier of the database containing fields to return.
/// </param>
/// <param name="search">
/// An optional field name search string used to match fields to return.
/// </param>
/// <param name="fieldGroupId">
/// The optional parent field group ID whose contents to search.
/// </param>
/// <param name="includeProfiles">
/// An optional setting to indicate whether to search fields in profiles. By default,
/// this is false since including profile fields will significantly increase search time.
/// </param>
/// <param name="maxResults">
/// The maximum number of fields to return. This defaults to 200 fields. If this is set to
/// 0 all the results will be returned.
/// </param>
[Get( "/v2/ems-systems/1/databases/{databaseId}/fields" )]
Task<IEnumerable<Field>> SearchDatabaseFields( string databaseId, string search = null, string fieldGroupId = null, bool includeProfiles = false, int maxResults = 200, [Property] CallContext context = null );
/// <summary>
/// Queries a database for information, composing the query with information provided in the
/// specified query structure.
/// </summary>
/// <param name="databaseId">
/// The unique identifier of the EMS database to query.
/// </param>
/// <param name="query">
/// The information used to construct a query for which results are returned.
/// </param>
[Post( "/v2/ems-systems/1/databases/{databaseId}/query" )]
Task<DbQueryResult> QueryDatabase( string databaseId, [Body] DbQuery query, [Property] CallContext context = null );
/// <summary>
/// Creates a query on a database using the provided query structure and returns an ID that
/// can be used to fetch result data through other async-query routes.
/// </summary>
/// <param name="databaseId">
/// The unique identifier of the EMS database to query.
/// </param>
/// <param name="query">
/// The information used to construct a query for which results are returned.
/// </param>
[Post( "/v2/ems-systems/1/databases/{databaseId}/async-query" )]
Task<AsyncQueryInfo> StartAsyncDatabaseQuery( string databaseId, [Body] DbQuery query, [Property] CallContext context = null );
/// <summary>
/// Returns rows between (inclusive) the start and end indexes from the async query with the given ID.
/// </summary>
/// <param name="databaseId">
/// The unique identifier of the EMS database to query.
/// </param>
/// <param name="queryId">
/// The unique identifier of the query created by the API.
/// </param>
/// <param name="start">
/// The zero-based index of the first row to return.
/// </param>
/// <param name="end">
/// The zero-based index of the last row to return.
/// </param>
[Get( "/v2/ems-systems/1/databases/{databaseId}/async-query/{queryId}/read/{start}/{end}" )]
Task<AsyncQueryData> ReadAsyncDatabaseQuery( string databaseId, string queryId, int start, int end, [Property] CallContext context = null );
/// <summary>
/// Stops the async query with the given ID.
/// </summary>
/// <param name="databaseId">
/// The unique identifier of the EMS database to query.
/// </param>
/// <param name="queryId">
/// The unique identifier of the query created by the API.
/// </param>
[Delete( "/v2/ems-systems/1/databases/{databaseId}/async-query/{queryId}" )]
Task StopAsyncDatabaseQuery( string databaseId, string queryId, [Property] CallContext context = null );
/// <summary>
/// Creates one or more new data entities in the database.
/// </summary>
/// <param name="databaseId">
/// The unique identifier of the EMS database to add data entities to.
/// </param>
/// <param name="create">
/// The information used to create one or more new data entities.
/// </param>
[Post( "/v2/ems-systems/1/databases/{databaseId}/create" )]
Task<CreateResult> CreateDatabaseEntity( string databaseId, [Body] Create create, [Property] CallContext context = null );
/// <summary>
/// Runs an update query on one or more rows of data in the database.
/// </summary>
/// <param name="databaseId">
/// The unique identifier of the EMS database to update.
/// </param>
/// <param name="update">
/// The information used to construct an update query.
/// </param>
[Put( "/v2/ems-systems/1/databases/{databaseId}/update" )]
Task<UpdateResult> UpdateDatabase( string databaseId, [Body] Update update, [Property] CallContext context = null );
/// <summary>
/// Deletes one or more existing data entities in the database.
/// </summary>
/// <param name="databaseId">
/// The unique identifier of the EMS database to delete data entities from.
/// </param>
/// <param name="delete">
/// The information used to delete one or more data entities.
/// </param>
[Post( "/v2/ems-systems/1/databases/{databaseId}/delete" )]
Task<DeleteResult> DeleteDatabaseEntity( string databaseId, [Body] Delete delete, [Property] CallContext context = null );
/// <summary>
/// Adds a comment to a specific comment field.
/// </summary>
/// <param name="databaseId">
/// The unique identifier of the EMS database the comment field exists on.
/// </param>
/// <param name="commentFieldId">
/// The unique identifier of the comment field to add a comment to.
/// </param>
/// <param name="newComment">
/// The context and information of the new comment.
/// </param>
[Post( "/v2/ems-systems/1/databases/{databaseId}/comments/{commentFieldId}" )]
Task CreateComment( string databaseId, string commentFieldId, [Body] NewComment newComment, [Property] CallContext context = null );
/// <summary>
/// Starts a new upload.
/// </summary>
/// <param name="request">
/// The parameters for the upload.
/// </param>
[Post( "/v2/ems-systems/1/uploads" )]
Task<UploadParameters> StartUpload( [Body] UploadRequest request, [Property] CallContext context = null );
/// <summary>
/// Uploads a chunk of a file. This will fail if any chunks have been skipped in the specified file.
/// </summary>
/// <param name="transferId">
/// The ID of the upload, returned originally by the upload start call.
/// </param>
/// <param name="first">
/// The byte index of the first byte that will be uploaded.
/// </param>
/// <param name="last">
/// The byte index of the last byte that will be uploaded.
/// </param>
/// <param name="chunk">
/// The bytes to upload with the chunk.
/// </param>
/// <remarks>
/// The practical limit for a single chunk is less than 4MB or so, dependent on the web server's configuration.
/// If you receive 500 responses, try smaller chunk sizes.
/// </remarks>
[Put( "/v2/ems-systems/1/uploads/{transferId}/{first}/{last}" )]
Task<UploadResult> UploadChunk( string transferId, long first, long last, [Body] byte[] chunk, [Property] CallContext context = null );
/// <summary>
/// Gets the status of an upload in progress.
/// </summary>
/// <param name="transferId">
/// The ID of the upload, returned originally by the upload start call.
/// </param>
[Get( "/v2/ems-systems/1/uploads/{transferId}" )]
Task<UploadStatus> GetUploadStatus( string transferId, [Property] CallContext context = null );
/// <summary>
/// Gets the list of upload records from the server.
/// </summary>
/// <param name="maxEntries">
/// The maximum number of entries to return; this is capped at 50, and 50
/// will be used if it's not specified.
/// </param>
[Get( "/v2/uploads" )]
Task<IEnumerable<UploadRecord>> GetUploads( int maxEntries = 50, [Property] CallContext context = null );
/// <summary>
/// Completes an existing upload in progress.
/// </summary>
/// <param name="transferId">
/// The ID of the upload, returned originally by the upload start call.
/// </param>
[Get( "/v2/ems-systems/1/uploads/{transferId}/finish" )]
Task<UploadRecord> FinishUpload( string transferId, [Property] CallContext context = null );
/// <summary>
/// Cancels an existing upload in progress.
/// </summary>
/// <param name="transferId">
/// The ID of the upload, returned originally by the upload start call.
/// </param>
[Get( "/v2/ems-systems/1/uploads/{transferId}/cancel" )]
Task<UploadRecord> CancelUpload( string transferId, [Property] CallContext context = null );
/// <summary>
/// Gets the EMS processing status for a single upload.
/// </summary>
/// <param name="uploadId">
/// The ID of the upload for which to return status information.
/// </param>
[Get( "/v2/ems-systems/1/uploads/processing-status/{uploadId}" )]
Task<UploadProcessingStatus> GetProcessingStatusSingle( string uploadId, [Property] CallContext context = null );
/// <summary>
/// Gets the EMS processing status for a set of uploads.
/// </summary>
/// <param name="ids">
/// An array of upload ids for which to return information.
/// </param>
[Post( "/v2/ems-systems/1/uploads/processing-status" )]
Task<IEnumerable<UploadProcessingStatus>> GetProcessingStatusMultiple( [Body] string[] ids, [Property] CallContext context = null );
/// <summary>
/// Retrieves the list of user accounts.
/// </summary>
/// <param name="username">
/// The optional username search string used to search the list of users. Only users that contain this search
/// string in their user name are returned.
/// </param>
/// <remarks>
/// You must have Admin privileges to the EMS API to be able to call this route.
/// </remarks>
[Get( "/v2/admin/users" )]
Task<IEnumerable<AdminUser>> AdminGetUsers( string username = null, [Property] CallContext context = null );
/// <summary>
/// Returns the swagger specification as a raw JSON string.
/// </summary>
/// <param name="apiVersion">
/// The version of the API to return the specification for. The default is "v2".
/// </param>
[Get( "/{apiVersion}/swagger" )]
Task<string> GetSwaggerSpecification( string apiVersion = "v2", [Property] CallContext context = null );
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.OpsWorks.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.OpsWorks.Model.Internal.MarshallTransformations
{
/// <summary>
/// Create Stack Request Marshaller
/// </summary>
internal class CreateStackRequestMarshaller : IMarshaller<IRequest, CreateStackRequest>
{
public IRequest Marshall(CreateStackRequest createStackRequest)
{
IRequest request = new DefaultRequest(createStackRequest, "AmazonOpsWorks");
string target = "OpsWorks_20130218.CreateStack";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
string uriResourcePath = "";
if (uriResourcePath.Contains("?"))
{
string queryString = uriResourcePath.Substring(uriResourcePath.IndexOf("?") + 1);
uriResourcePath = uriResourcePath.Substring(0, uriResourcePath.IndexOf("?"));
foreach (string s in queryString.Split('&', ';'))
{
string[] nameValuePair = s.Split('=');
if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
{
request.Parameters.Add(nameValuePair[0], nameValuePair[1]);
}
else
{
request.Parameters.Add(nameValuePair[0], null);
}
}
}
request.ResourcePath = uriResourcePath;
using (StringWriter stringWriter = new StringWriter())
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
if (createStackRequest != null && createStackRequest.IsSetName())
{
writer.WritePropertyName("Name");
writer.Write(createStackRequest.Name);
}
if (createStackRequest != null && createStackRequest.IsSetRegion())
{
writer.WritePropertyName("Region");
writer.Write(createStackRequest.Region);
}
if (createStackRequest != null && createStackRequest.IsSetVpcId())
{
writer.WritePropertyName("VpcId");
writer.Write(createStackRequest.VpcId);
}
if (createStackRequest != null)
{
if (createStackRequest.Attributes != null && createStackRequest.Attributes.Count > 0)
{
writer.WritePropertyName("Attributes");
writer.WriteObjectStart();
foreach (string createStackRequestAttributesKey in createStackRequest.Attributes.Keys)
{
string attributesListValue;
bool attributesListValueHasValue = createStackRequest.Attributes.TryGetValue(createStackRequestAttributesKey, out attributesListValue);
writer.WritePropertyName(createStackRequestAttributesKey);
writer.Write(attributesListValue);
}
writer.WriteObjectEnd();
}
}
if (createStackRequest != null && createStackRequest.IsSetServiceRoleArn())
{
writer.WritePropertyName("ServiceRoleArn");
writer.Write(createStackRequest.ServiceRoleArn);
}
if (createStackRequest != null && createStackRequest.IsSetDefaultInstanceProfileArn())
{
writer.WritePropertyName("DefaultInstanceProfileArn");
writer.Write(createStackRequest.DefaultInstanceProfileArn);
}
if (createStackRequest != null && createStackRequest.IsSetDefaultOs())
{
writer.WritePropertyName("DefaultOs");
writer.Write(createStackRequest.DefaultOs);
}
if (createStackRequest != null && createStackRequest.IsSetHostnameTheme())
{
writer.WritePropertyName("HostnameTheme");
writer.Write(createStackRequest.HostnameTheme);
}
if (createStackRequest != null && createStackRequest.IsSetDefaultAvailabilityZone())
{
writer.WritePropertyName("DefaultAvailabilityZone");
writer.Write(createStackRequest.DefaultAvailabilityZone);
}
if (createStackRequest != null && createStackRequest.IsSetDefaultSubnetId())
{
writer.WritePropertyName("DefaultSubnetId");
writer.Write(createStackRequest.DefaultSubnetId);
}
if (createStackRequest != null && createStackRequest.IsSetCustomJson())
{
writer.WritePropertyName("CustomJson");
writer.Write(createStackRequest.CustomJson);
}
if (createStackRequest != null)
{
StackConfigurationManager configurationManager = createStackRequest.ConfigurationManager;
if (configurationManager != null)
{
writer.WritePropertyName("ConfigurationManager");
writer.WriteObjectStart();
if (configurationManager != null && configurationManager.IsSetName())
{
writer.WritePropertyName("Name");
writer.Write(configurationManager.Name);
}
if (configurationManager != null && configurationManager.IsSetVersion())
{
writer.WritePropertyName("Version");
writer.Write(configurationManager.Version);
}
writer.WriteObjectEnd();
}
}
if (createStackRequest != null && createStackRequest.IsSetUseCustomCookbooks())
{
writer.WritePropertyName("UseCustomCookbooks");
writer.Write(createStackRequest.UseCustomCookbooks);
}
if (createStackRequest != null)
{
Source customCookbooksSource = createStackRequest.CustomCookbooksSource;
if (customCookbooksSource != null)
{
writer.WritePropertyName("CustomCookbooksSource");
writer.WriteObjectStart();
if (customCookbooksSource != null && customCookbooksSource.IsSetType())
{
writer.WritePropertyName("Type");
writer.Write(customCookbooksSource.Type);
}
if (customCookbooksSource != null && customCookbooksSource.IsSetUrl())
{
writer.WritePropertyName("Url");
writer.Write(customCookbooksSource.Url);
}
if (customCookbooksSource != null && customCookbooksSource.IsSetUsername())
{
writer.WritePropertyName("Username");
writer.Write(customCookbooksSource.Username);
}
if (customCookbooksSource != null && customCookbooksSource.IsSetPassword())
{
writer.WritePropertyName("Password");
writer.Write(customCookbooksSource.Password);
}
if (customCookbooksSource != null && customCookbooksSource.IsSetSshKey())
{
writer.WritePropertyName("SshKey");
writer.Write(customCookbooksSource.SshKey);
}
if (customCookbooksSource != null && customCookbooksSource.IsSetRevision())
{
writer.WritePropertyName("Revision");
writer.Write(customCookbooksSource.Revision);
}
writer.WriteObjectEnd();
}
}
if (createStackRequest != null && createStackRequest.IsSetDefaultSshKeyName())
{
writer.WritePropertyName("DefaultSshKeyName");
writer.Write(createStackRequest.DefaultSshKeyName);
}
if (createStackRequest != null && createStackRequest.IsSetDefaultRootDeviceType())
{
writer.WritePropertyName("DefaultRootDeviceType");
writer.Write(createStackRequest.DefaultRootDeviceType);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Reflection.Internal;
namespace System.Reflection.Metadata.Ecma335
{
internal struct StringStreamReader
{
private static string[] virtualValues;
internal readonly MemoryBlock Block;
internal StringStreamReader(MemoryBlock block, MetadataKind metadataKind)
{
if (virtualValues == null && metadataKind != MetadataKind.Ecma335)
{
// Note:
// Virtual values shall not contain surrogates, otherwise StartsWith might be inconsistent
// when comparing to a text that ends with a high surrogate.
var values = new string[(int)StringHandle.VirtualIndex.Count];
values[(int)StringHandle.VirtualIndex.System_Runtime_WindowsRuntime] = "System.Runtime.WindowsRuntime";
values[(int)StringHandle.VirtualIndex.System_Runtime] = "System.Runtime";
values[(int)StringHandle.VirtualIndex.System_ObjectModel] = "System.ObjectModel";
values[(int)StringHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml] = "System.Runtime.WindowsRuntime.UI.Xaml";
values[(int)StringHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime] = "System.Runtime.InteropServices.WindowsRuntime";
values[(int)StringHandle.VirtualIndex.System_Numerics_Vectors] = "System.Numerics.Vectors";
values[(int)StringHandle.VirtualIndex.Dispose] = "Dispose";
values[(int)StringHandle.VirtualIndex.AttributeTargets] = "AttributeTargets";
values[(int)StringHandle.VirtualIndex.AttributeUsageAttribute] = "AttributeUsageAttribute";
values[(int)StringHandle.VirtualIndex.Color] = "Color";
values[(int)StringHandle.VirtualIndex.CornerRadius] = "CornerRadius";
values[(int)StringHandle.VirtualIndex.DateTimeOffset] = "DateTimeOffset";
values[(int)StringHandle.VirtualIndex.Duration] = "Duration";
values[(int)StringHandle.VirtualIndex.DurationType] = "DurationType";
values[(int)StringHandle.VirtualIndex.EventHandler1] = "EventHandler`1";
values[(int)StringHandle.VirtualIndex.EventRegistrationToken] = "EventRegistrationToken";
values[(int)StringHandle.VirtualIndex.Exception] = "Exception";
values[(int)StringHandle.VirtualIndex.GeneratorPosition] = "GeneratorPosition";
values[(int)StringHandle.VirtualIndex.GridLength] = "GridLength";
values[(int)StringHandle.VirtualIndex.GridUnitType] = "GridUnitType";
values[(int)StringHandle.VirtualIndex.ICommand] = "ICommand";
values[(int)StringHandle.VirtualIndex.IDictionary2] = "IDictionary`2";
values[(int)StringHandle.VirtualIndex.IDisposable] = "IDisposable";
values[(int)StringHandle.VirtualIndex.IEnumerable] = "IEnumerable";
values[(int)StringHandle.VirtualIndex.IEnumerable1] = "IEnumerable`1";
values[(int)StringHandle.VirtualIndex.IList] = "IList";
values[(int)StringHandle.VirtualIndex.IList1] = "IList`1";
values[(int)StringHandle.VirtualIndex.INotifyCollectionChanged] = "INotifyCollectionChanged";
values[(int)StringHandle.VirtualIndex.INotifyPropertyChanged] = "INotifyPropertyChanged";
values[(int)StringHandle.VirtualIndex.IReadOnlyDictionary2] = "IReadOnlyDictionary`2";
values[(int)StringHandle.VirtualIndex.IReadOnlyList1] = "IReadOnlyList`1";
values[(int)StringHandle.VirtualIndex.KeyTime] = "KeyTime";
values[(int)StringHandle.VirtualIndex.KeyValuePair2] = "KeyValuePair`2";
values[(int)StringHandle.VirtualIndex.Matrix] = "Matrix";
values[(int)StringHandle.VirtualIndex.Matrix3D] = "Matrix3D";
values[(int)StringHandle.VirtualIndex.Matrix3x2] = "Matrix3x2";
values[(int)StringHandle.VirtualIndex.Matrix4x4] = "Matrix4x4";
values[(int)StringHandle.VirtualIndex.NotifyCollectionChangedAction] = "NotifyCollectionChangedAction";
values[(int)StringHandle.VirtualIndex.NotifyCollectionChangedEventArgs] = "NotifyCollectionChangedEventArgs";
values[(int)StringHandle.VirtualIndex.NotifyCollectionChangedEventHandler] = "NotifyCollectionChangedEventHandler";
values[(int)StringHandle.VirtualIndex.Nullable1] = "Nullable`1";
values[(int)StringHandle.VirtualIndex.Plane] = "Plane";
values[(int)StringHandle.VirtualIndex.Point] = "Point";
values[(int)StringHandle.VirtualIndex.PropertyChangedEventArgs] = "PropertyChangedEventArgs";
values[(int)StringHandle.VirtualIndex.PropertyChangedEventHandler] = "PropertyChangedEventHandler";
values[(int)StringHandle.VirtualIndex.Quaternion] = "Quaternion";
values[(int)StringHandle.VirtualIndex.Rect] = "Rect";
values[(int)StringHandle.VirtualIndex.RepeatBehavior] = "RepeatBehavior";
values[(int)StringHandle.VirtualIndex.RepeatBehaviorType] = "RepeatBehaviorType";
values[(int)StringHandle.VirtualIndex.Size] = "Size";
values[(int)StringHandle.VirtualIndex.System] = "System";
values[(int)StringHandle.VirtualIndex.System_Collections] = "System.Collections";
values[(int)StringHandle.VirtualIndex.System_Collections_Generic] = "System.Collections.Generic";
values[(int)StringHandle.VirtualIndex.System_Collections_Specialized] = "System.Collections.Specialized";
values[(int)StringHandle.VirtualIndex.System_ComponentModel] = "System.ComponentModel";
values[(int)StringHandle.VirtualIndex.System_Numerics] = "System.Numerics";
values[(int)StringHandle.VirtualIndex.System_Windows_Input] = "System.Windows.Input";
values[(int)StringHandle.VirtualIndex.Thickness] = "Thickness";
values[(int)StringHandle.VirtualIndex.TimeSpan] = "TimeSpan";
values[(int)StringHandle.VirtualIndex.Type] = "Type";
values[(int)StringHandle.VirtualIndex.Uri] = "Uri";
values[(int)StringHandle.VirtualIndex.Vector2] = "Vector2";
values[(int)StringHandle.VirtualIndex.Vector3] = "Vector3";
values[(int)StringHandle.VirtualIndex.Vector4] = "Vector4";
values[(int)StringHandle.VirtualIndex.Windows_Foundation] = "Windows.Foundation";
values[(int)StringHandle.VirtualIndex.Windows_UI] = "Windows.UI";
values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml] = "Windows.UI.Xaml";
values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Controls_Primitives] = "Windows.UI.Xaml.Controls.Primitives";
values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Media] = "Windows.UI.Xaml.Media";
values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation] = "Windows.UI.Xaml.Media.Animation";
values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Media3D] = "Windows.UI.Xaml.Media.Media3D";
virtualValues = values;
AssertFilled();
}
this.Block = TrimEnd(block);
}
[Conditional("DEBUG")]
private static void AssertFilled()
{
for (int i = 0; i < virtualValues.Length; i++)
{
Debug.Assert(virtualValues[i] != null, "Missing virtual value for StringHandle.VirtualIndex." + (StringHandle.VirtualIndex)i);
}
}
// Trims the alignment padding of the heap.
// See StgStringPool::InitOnMem in ndp\clr\src\Utilcode\StgPool.cpp.
// This is especially important for EnC.
private static MemoryBlock TrimEnd(MemoryBlock block)
{
if (block.Length == 0)
{
return block;
}
int i = block.Length - 1;
while (i >= 0 && block.PeekByte(i) == 0)
{
i--;
}
// this shouldn't happen in valid metadata:
if (i == block.Length - 1)
{
return block;
}
// +1 for terminating \0
return block.GetMemoryBlockAt(0, i + 2);
}
internal string GetVirtualValue(StringHandle.VirtualIndex index)
{
return virtualValues[(int)index];
}
internal string GetString(StringHandle handle, MetadataStringDecoder utf8Decoder)
{
int index = handle.Index;
byte[] prefix;
if (handle.IsVirtual)
{
switch (handle.StringKind)
{
case StringKind.Plain:
return virtualValues[index];
case StringKind.WinRTPrefixed:
prefix = MetadataReader.WinRTPrefix;
break;
default:
Debug.Assert(false, "We should not get here");
return null;
}
}
else
{
prefix = null;
}
int bytesRead;
char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0';
return this.Block.PeekUtf8NullTerminated(index, prefix, utf8Decoder, out bytesRead, otherTerminator);
}
internal StringHandle GetNextHandle(StringHandle handle)
{
if (handle.IsVirtual)
{
return default(StringHandle);
}
int terminator = this.Block.IndexOf(0, handle.Index);
if (terminator == -1 || terminator == Block.Length - 1)
{
return default(StringHandle);
}
return StringHandle.FromIndex((uint)(terminator + 1));
}
internal bool Equals(StringHandle handle, string value, MetadataStringDecoder utf8Decoder)
{
Debug.Assert(value != null);
if (handle.IsVirtual)
{
// TODO:This can allocate unnecessarily for <WinRT> prefixed handles.
return GetString(handle, utf8Decoder) == value;
}
if (handle.IsNil)
{
return value.Length == 0;
}
// TODO: MetadataStringComparer needs to use the user-supplied encoding.
// Need to pass the decoder down and use in Utf8NullTerminatedEquals.
char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0';
return this.Block.Utf8NullTerminatedEquals(handle.Index, value, otherTerminator);
}
internal bool StartsWith(StringHandle handle, string value, MetadataStringDecoder utf8Decoder)
{
Debug.Assert(value != null);
if (handle.IsVirtual)
{
// TODO:This can allocate unnecessarily for <WinRT> prefixed handles.
return GetString(handle, utf8Decoder).StartsWith(value, StringComparison.Ordinal);
}
if (handle.IsNil)
{
return value.Length == 0;
}
// TODO: MetadataStringComparer needs to use the user-supplied encoding.
// Need to pass the decoder down and use in Utf8NullTerminatedEquals.
char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0';
return this.Block.Utf8NullTerminatedStartsWith(handle.Index, value, otherTerminator);
}
/// <summary>
/// Returns true if the given raw (non-virtual) handle represents the same string as given ASCII string.
/// </summary>
internal bool EqualsRaw(StringHandle rawHandle, string asciiString)
{
Debug.Assert(!rawHandle.IsVirtual);
Debug.Assert(rawHandle.StringKind != StringKind.DotTerminated, "Not supported");
return this.Block.CompareUtf8NullTerminatedStringWithAsciiString(rawHandle.Index, asciiString) == 0;
}
/// <summary>
/// Returns the heap index of the given ASCII character or -1 if not found prior null terminator or end of heap.
/// </summary>
internal int IndexOfRaw(int startIndex, char asciiChar)
{
Debug.Assert(asciiChar != 0 && asciiChar <= 0x7f);
return this.Block.Utf8NullTerminatedOffsetOfAsciiChar(startIndex, asciiChar);
}
/// <summary>
/// Returns true if the given raw (non-virtual) handle represents a string that starts with given ASCII prefix.
/// </summary>
internal bool StartsWithRaw(StringHandle rawHandle, string asciiPrefix)
{
Debug.Assert(!rawHandle.IsVirtual);
Debug.Assert(rawHandle.StringKind != StringKind.DotTerminated, "Not supported");
return this.Block.Utf8NullTerminatedStringStartsWithAsciiPrefix(rawHandle.Index, asciiPrefix);
}
/// <summary>
/// Equivalent to Array.BinarySearch, searches for given raw (non-virtual) handle in given array of ASCII strings.
/// </summary>
internal int BinarySearchRaw(string[] asciiKeys, StringHandle rawHandle)
{
Debug.Assert(!rawHandle.IsVirtual);
Debug.Assert(rawHandle.StringKind != StringKind.DotTerminated, "Not supported");
return this.Block.BinarySearch(asciiKeys, rawHandle.Index);
}
}
internal unsafe struct BlobStreamReader
{
private struct VirtualHeapBlob
{
public readonly GCHandle Pinned;
public readonly byte[] Array;
public VirtualHeapBlob(byte[] array)
{
Pinned = GCHandle.Alloc(array, GCHandleType.Pinned);
Array = array;
}
}
// Container for virtual heap blobs that unpins handles on finalization.
// This is not handled via dispose because the only resource is managed memory.
private sealed class VirtualHeapBlobTable
{
public readonly Dictionary<BlobHandle, VirtualHeapBlob> Table;
public VirtualHeapBlobTable()
{
Table = new Dictionary<BlobHandle, VirtualHeapBlob>();
}
~VirtualHeapBlobTable()
{
if (Table != null)
{
foreach (var blob in Table.Values)
{
blob.Pinned.Free();
}
}
}
}
// Since the number of virtual blobs we need is small (the number of attribute classes in .winmd files)
// we can create a pinned handle for each of them.
// If we needed many more blobs we could create and pin a single byte[] and allocate blobs there.
private VirtualHeapBlobTable lazyVirtualHeapBlobs;
private static byte[][] virtualHeapBlobs;
internal readonly MemoryBlock Block;
internal BlobStreamReader(MemoryBlock block, MetadataKind metadataKind)
{
this.lazyVirtualHeapBlobs = null;
this.Block = block;
if (virtualHeapBlobs == null && metadataKind != MetadataKind.Ecma335)
{
var blobs = new byte[(int)BlobHandle.VirtualIndex.Count][];
blobs[(int)BlobHandle.VirtualIndex.ContractPublicKeyToken] = new byte[]
{
0xB0, 0x3F, 0x5F, 0x7F, 0x11, 0xD5, 0x0A, 0x3A
};
blobs[(int)BlobHandle.VirtualIndex.ContractPublicKey] = new byte[]
{
0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00, 0x06, 0x02, 0x00, 0x00,
0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00,
0x07, 0xD1, 0xFA, 0x57, 0xC4, 0xAE, 0xD9, 0xF0, 0xA3, 0x2E, 0x84, 0xAA, 0x0F, 0xAE, 0xFD, 0x0D,
0xE9, 0xE8, 0xFD, 0x6A, 0xEC, 0x8F, 0x87, 0xFB, 0x03, 0x76, 0x6C, 0x83, 0x4C, 0x99, 0x92, 0x1E,
0xB2, 0x3B, 0xE7, 0x9A, 0xD9, 0xD5, 0xDC, 0xC1, 0xDD, 0x9A, 0xD2, 0x36, 0x13, 0x21, 0x02, 0x90,
0x0B, 0x72, 0x3C, 0xF9, 0x80, 0x95, 0x7F, 0xC4, 0xE1, 0x77, 0x10, 0x8F, 0xC6, 0x07, 0x77, 0x4F,
0x29, 0xE8, 0x32, 0x0E, 0x92, 0xEA, 0x05, 0xEC, 0xE4, 0xE8, 0x21, 0xC0, 0xA5, 0xEF, 0xE8, 0xF1,
0x64, 0x5C, 0x4C, 0x0C, 0x93, 0xC1, 0xAB, 0x99, 0x28, 0x5D, 0x62, 0x2C, 0xAA, 0x65, 0x2C, 0x1D,
0xFA, 0xD6, 0x3D, 0x74, 0x5D, 0x6F, 0x2D, 0xE5, 0xF1, 0x7E, 0x5E, 0xAF, 0x0F, 0xC4, 0x96, 0x3D,
0x26, 0x1C, 0x8A, 0x12, 0x43, 0x65, 0x18, 0x20, 0x6D, 0xC0, 0x93, 0x34, 0x4D, 0x5A, 0xD2, 0x93
};
blobs[(int)BlobHandle.VirtualIndex.AttributeUsage_AllowSingle] = new byte[]
{
// preable:
0x01, 0x00,
// target (template parameter):
0x00, 0x00, 0x00, 0x00,
// named arg count:
0x01, 0x00,
// SERIALIZATION_TYPE_PROPERTY
0x54,
// ELEMENT_TYPE_BOOLEAN
0x02,
// "AllowMultiple".Length
0x0D,
// "AllowMultiple"
0x41, 0x6C, 0x6C, 0x6F, 0x77, 0x4D, 0x75, 0x6C, 0x74, 0x69, 0x70, 0x6C, 0x65,
// false
0x00
};
blobs[(int)BlobHandle.VirtualIndex.AttributeUsage_AllowMultiple] = new byte[]
{
// preable:
0x01, 0x00,
// target (template parameter):
0x00, 0x00, 0x00, 0x00,
// named arg count:
0x01, 0x00,
// SERIALIZATION_TYPE_PROPERTY
0x54,
// ELEMENT_TYPE_BOOLEAN
0x02,
// "AllowMultiple".Length
0x0D,
// "AllowMultiple"
0x41, 0x6C, 0x6C, 0x6F, 0x77, 0x4D, 0x75, 0x6C, 0x74, 0x69, 0x70, 0x6C, 0x65,
// true
0x01
};
virtualHeapBlobs = blobs;
}
}
internal byte[] GetBytes(BlobHandle handle)
{
if (handle.IsVirtual)
{
// consider: if we returned an ImmutableArray we wouldn't need to copy
return GetVirtualBlobArray(handle, unique: true);
}
int offset = handle.Index;
int bytesRead;
int numberOfBytes = this.Block.PeekCompressedInteger(offset, out bytesRead);
if (numberOfBytes == BlobReader.InvalidCompressedInteger)
{
return EmptyArray<byte>.Instance;
}
return this.Block.PeekBytes(offset + bytesRead, numberOfBytes);
}
internal BlobReader GetBlobReader(BlobHandle handle)
{
if (handle.IsVirtual)
{
if (lazyVirtualHeapBlobs == null)
{
Interlocked.CompareExchange(ref lazyVirtualHeapBlobs, new VirtualHeapBlobTable(), null);
}
int index = (int)handle.GetVirtualIndex();
int length = virtualHeapBlobs[index].Length;
VirtualHeapBlob virtualBlob;
lock (lazyVirtualHeapBlobs)
{
if (!lazyVirtualHeapBlobs.Table.TryGetValue(handle, out virtualBlob))
{
virtualBlob = new VirtualHeapBlob(GetVirtualBlobArray(handle, unique: false));
lazyVirtualHeapBlobs.Table.Add(handle, virtualBlob);
}
}
return new BlobReader(new MemoryBlock((byte*)virtualBlob.Pinned.AddrOfPinnedObject(), length));
}
int offset, size;
Block.PeekHeapValueOffsetAndSize(handle.Index, out offset, out size);
return new BlobReader(this.Block.GetMemoryBlockAt(offset, size));
}
internal BlobHandle GetNextHandle(BlobHandle handle)
{
if (handle.IsVirtual)
{
return default(BlobHandle);
}
int offset, size;
if (!Block.PeekHeapValueOffsetAndSize(handle.Index, out offset, out size))
{
return default(BlobHandle);
}
int nextIndex = offset + size;
if (nextIndex >= Block.Length)
{
return default(BlobHandle);
}
return BlobHandle.FromIndex((uint)nextIndex);
}
internal byte[] GetVirtualBlobArray(BlobHandle handle, bool unique)
{
BlobHandle.VirtualIndex index = handle.GetVirtualIndex();
byte[] result = virtualHeapBlobs[(int)index];
switch (index)
{
case BlobHandle.VirtualIndex.AttributeUsage_AllowMultiple:
case BlobHandle.VirtualIndex.AttributeUsage_AllowSingle:
result = (byte[])result.Clone();
handle.SubstituteTemplateParameters(result);
break;
default:
if (unique)
{
result = (byte[])result.Clone();
}
break;
}
return result;
}
}
internal struct GuidStreamReader
{
internal readonly MemoryBlock Block;
internal const int GuidSize = 16;
public GuidStreamReader(MemoryBlock block)
{
this.Block = block;
}
internal Guid GetGuid(GuidHandle handle)
{
if (handle.IsNil)
{
return default(Guid);
}
// Metadata Spec: The Guid heap is an array of GUIDs, each 16 bytes wide.
// Its first element is numbered 1, its second 2, and so on.
return this.Block.PeekGuid((handle.Index - 1) * GuidSize);
}
}
internal struct UserStringStreamReader
{
internal readonly MemoryBlock Block;
public UserStringStreamReader(MemoryBlock block)
{
this.Block = block;
}
internal string GetString(UserStringHandle handle)
{
int offset, size;
if (!Block.PeekHeapValueOffsetAndSize(handle.Index, out offset, out size))
{
return string.Empty;
}
// Spec: Furthermore, there is an additional terminal byte (so all byte counts are odd, not even).
// The size in the blob header is the length of the string in bytes + 1.
return this.Block.PeekUtf16(offset, size & ~1);
}
internal UserStringHandle GetNextHandle(UserStringHandle handle)
{
int offset, size;
if (!Block.PeekHeapValueOffsetAndSize(handle.Index, out offset, out size))
{
return default(UserStringHandle);
}
int nextIndex = offset + size;
if (nextIndex >= Block.Length)
{
return default(UserStringHandle);
}
return UserStringHandle.FromIndex((uint)nextIndex);
}
}
}
| |
//
// MRCharacterItemsDisplay.cs
//
// Author:
// Steve Jakab <>
//
// Copyright (c) 2015 Steve Jakab
//
// 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 UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
namespace PortableRealm
{
public class MRCharacterItemsDisplay : MRTabItems, MRITouchable
{
#region Properties
public MRCharacterMat Parent
{
get{
return mParent;
}
set{
mParent = value;
}
}
#endregion
#region Methods
// Called when the script instance is being loaded
void Awake()
{
mActiveWeapon = MRGame.TheGame.NewGamePieceStack();
mActiveArmor = MRGame.TheGame.NewGamePieceStack();
mActiveBreastplate = MRGame.TheGame.NewGamePieceStack();
mActiveHelmet = MRGame.TheGame.NewGamePieceStack();
mActiveShield = MRGame.TheGame.NewGamePieceStack();
mActiveHorse = MRGame.TheGame.NewGamePieceStack();
mActiveBoots = MRGame.TheGame.NewGamePieceStack();
mActiveGloves = MRGame.TheGame.NewGamePieceStack();
mActiveItems = MRGame.TheGame.NewGamePieceStack();
mInactiveWeapon = MRGame.TheGame.NewGamePieceStack();
mInactiveArmor = MRGame.TheGame.NewGamePieceStack();
mInactiveBreastplate = MRGame.TheGame.NewGamePieceStack();
mInactiveHelmet = MRGame.TheGame.NewGamePieceStack();
mInactiveShield = MRGame.TheGame.NewGamePieceStack();
mInactiveHorse = MRGame.TheGame.NewGamePieceStack();
mInactiveItems = MRGame.TheGame.NewGamePieceStack();
}
// Use this for initialization
protected override void Start ()
{
base.Start();
// get the chit positions, stats, and curses
Transform[] transforms = gameObject.GetComponentsInChildren<Transform>();
foreach (Transform subTrans in transforms)
{
if (subTrans.gameObject.name == "ActiveChits")
mActiveChitsArea = subTrans.gameObject;
else if (subTrans.gameObject.name == "FatiguedChits")
mFatiguedChitsArea = subTrans.gameObject;
else if (subTrans.gameObject.name == "WoundedChits")
mWoundedChitsArea = subTrans.gameObject;
else if (subTrans.gameObject.name == "ActiveItems")
mActiveItemsArea = subTrans.gameObject;
else if (subTrans.gameObject.name == "InactiveItems")
mInactiveItemsArea = subTrans.gameObject;
else if (subTrans.gameObject.name == "Gold")
{
TextMesh[] texts = subTrans.gameObject.GetComponentsInChildren<TextMesh>();
foreach (TextMesh text in texts)
{
if (text.gameObject.name == "Amount")
mGold = text;
}
}
else if (subTrans.gameObject.name == "Fame")
{
TextMesh[] texts = subTrans.gameObject.GetComponentsInChildren<TextMesh>();
foreach (TextMesh text in texts)
{
if (text.gameObject.name == "Amount")
mFame = text;
}
}
else if (subTrans.gameObject.name == "Notoriety")
{
TextMesh[] texts = subTrans.gameObject.GetComponentsInChildren<TextMesh>();
foreach (TextMesh text in texts)
{
if (text.gameObject.name == "Amount")
mNotoriety = text;
}
}
else if (subTrans.gameObject.name == "Weight")
{
TextMesh[] texts = subTrans.gameObject.GetComponentsInChildren<TextMesh>();
foreach (TextMesh text in texts)
{
if (text.gameObject.name == "Value")
mWeight = text;
}
}
else if (subTrans.gameObject.name == "Vulnerability")
{
TextMesh[] texts = subTrans.gameObject.GetComponentsInChildren<TextMesh>();
foreach (TextMesh text in texts)
{
if (text.gameObject.name == "Value")
mVulnerability = text;
}
}
else if (subTrans.gameObject.name == "Ashes")
{
mCurses.Add(MRGame.eCurses.Ashes, subTrans.gameObject);
}
else if (subTrans.gameObject.name == "Disgust")
{
mCurses.Add(MRGame.eCurses.Disgust, subTrans.gameObject);
}
else if (subTrans.gameObject.name == "Eyemist")
{
mCurses.Add(MRGame.eCurses.Eyemist, subTrans.gameObject);
}
else if (subTrans.gameObject.name == "Illhealth")
{
mCurses.Add(MRGame.eCurses.IllHealth, subTrans.gameObject);
}
else if (subTrans.gameObject.name == "Squeak")
{
mCurses.Add(MRGame.eCurses.Squeak, subTrans.gameObject);
}
else if (subTrans.gameObject.name == "Wither")
{
mCurses.Add(MRGame.eCurses.Wither, subTrans.gameObject);
}
}
mActiveChitsBackground = null;
transforms = mActiveChitsArea.GetComponentsInChildren<Transform>();
foreach (Transform activeTrans in transforms)
{
if (activeTrans.gameObject.name.StartsWith("chit"))
{
mActiveChitsPositions[int.Parse(activeTrans.gameObject.name.Substring("chit".Length)) - 1] = activeTrans.gameObject;
}
else if (activeTrans.gameObject.name == "Background")
{
mActiveChitsBackground = activeTrans.gameObject;
}
}
transforms = mFatiguedChitsArea.GetComponentsInChildren<Transform>();
foreach (Transform fatigueTrans in transforms)
{
if (fatigueTrans.gameObject.name.StartsWith("chit"))
{
mFatiguedChitsPositions[int.Parse(fatigueTrans.gameObject.name.Substring("chit".Length)) - 1] = fatigueTrans.gameObject;
}
}
GameObject woundedBackground = null;
transforms = mWoundedChitsArea.GetComponentsInChildren<Transform>();
foreach (Transform woundTrans in transforms)
{
if (woundTrans.gameObject.name.StartsWith("chit"))
{
mWoundedChitsPositions[int.Parse(woundTrans.gameObject.name.Substring("chit".Length)) - 1] = woundTrans.gameObject;
}
else if (woundTrans.gameObject.name == "Background")
{
woundedBackground = woundTrans.gameObject;
}
}
// get the item positions
transforms = mActiveItemsArea.GetComponentsInChildren<Transform>();
foreach (Transform activeTrans in transforms)
{
if (activeTrans.gameObject.name == "weapon")
{
SetupTreasureStack(activeTrans.gameObject, mActiveWeapon);
}
else if (activeTrans.gameObject.name == "armor")
{
SetupTreasureStack(activeTrans.gameObject, mActiveArmor);
}
else if (activeTrans.gameObject.name == "shield")
{
SetupTreasureStack(activeTrans.gameObject, mActiveShield);
}
else if (activeTrans.gameObject.name == "helmet")
{
SetupTreasureStack(activeTrans.gameObject, mActiveHelmet);
}
else if (activeTrans.gameObject.name == "breastplate")
{
SetupTreasureStack(activeTrans.gameObject, mActiveBreastplate);
}
else if (activeTrans.gameObject.name == "horse")
{
SetupTreasureStack(activeTrans.gameObject, mActiveHorse);
}
else if (activeTrans.gameObject.name == "boots")
{
SetupTreasureStack(activeTrans.gameObject, mActiveBoots);
}
else if (activeTrans.gameObject.name == "gloves")
{
SetupTreasureStack(activeTrans.gameObject, mActiveGloves);
}
else if (activeTrans.gameObject.name == "treasures")
{
SetupTreasureStack(activeTrans.gameObject, mActiveItems);
}
}
transforms = mInactiveItemsArea.GetComponentsInChildren<Transform>();
foreach (Transform inactiveTrans in transforms)
{
if (inactiveTrans.gameObject.name == "weapon")
{
SetupTreasureStack(inactiveTrans.gameObject, mInactiveWeapon);
}
else if (inactiveTrans.gameObject.name == "armor")
{
SetupTreasureStack(inactiveTrans.gameObject, mInactiveArmor);
}
else if (inactiveTrans.gameObject.name == "shield")
{
SetupTreasureStack(inactiveTrans.gameObject, mInactiveShield);
}
else if (inactiveTrans.gameObject.name == "helmet")
{
SetupTreasureStack(inactiveTrans.gameObject, mInactiveHelmet);
}
else if (inactiveTrans.gameObject.name == "breastplate")
{
SetupTreasureStack(inactiveTrans.gameObject, mInactiveBreastplate);
}
else if (inactiveTrans.gameObject.name == "horse")
{
SetupTreasureStack(inactiveTrans.gameObject, mInactiveHorse);
}
else if (inactiveTrans.gameObject.name == "treasures")
{
SetupTreasureStack(inactiveTrans.gameObject, mInactiveItems);
}
}
// adjust the active and wounded areas so they are on the far left and right of the view area
Vector3 left = Parent.CharacterMatCamera.ViewportToWorldPoint(new Vector3(0, 0, 0));
Vector3 activePos = mActiveChitsArea.transform.position;
float activeLeft = mActiveChitsBackground.GetComponent<Renderer>().bounds.min.x;
float delta = left.x - activeLeft;
mActiveChitsArea.transform.position = new Vector3(activePos.x + delta, activePos.y, activePos.z);
activePos = mActiveItemsArea.transform.position;
mActiveItemsArea.transform.position = new Vector3(activePos.x + delta, activePos.y, activePos.z);
Vector3 right = Parent.CharacterMatCamera.ViewportToWorldPoint(new Vector3(1, 0, 0));
Vector3 woundedPos = mWoundedChitsArea.transform.position;
float woudnedRight = woundedBackground.GetComponent<Renderer>().bounds.max.x;
delta = right.x - woudnedRight;
mWoundedChitsArea.transform.position = new Vector3(woundedPos.x + delta, woundedPos.y, woundedPos.z);
}
// Update is called once per frame
protected override void Update ()
{
base.Update();
if (Parent.Visible && Parent.Controllable is MRCharacter)
{
MRCharacter character = (MRCharacter)Parent.Controllable;
mFatiguedChitsArea.SetActive(true);
mWoundedChitsArea.SetActive(true);
if (MRGame.TheGame.CurrentView == MRGame.eViews.SelectAttack ||
MRGame.TheGame.CurrentView == MRGame.eViews.SelectManeuver ||
MRGame.TheGame.CurrentView == MRGame.eViews.SelectChit)
{
// hide fatigued and wounded chits
mFatiguedChitsArea.SetActive(false);
mWoundedChitsArea.SetActive(false);
Bounds b = mActiveChitsBackground.GetComponent<Renderer>().bounds;
Vector3 bmax = mParent.CharacterMatCamera.WorldToViewportPoint(b.max);
Vector3 bmin = mParent.CharacterMatCamera.WorldToViewportPoint(b.min);
Vector3 activeUpRight = mParent.CharacterMatCamera.WorldToScreenPoint(mActiveChitsBackground.GetComponent<Renderer>().bounds.max);
MRMainUI.TheUI.DisplayAttackManeuverDialog(activeUpRight.x / Screen.width, activeUpRight.y / (Screen.height * 2));
}
// display gold, fame, and notoriety
mGold.text = character.EffectiveGold.ToString();
mFame.text = ((int)(character.EffectiveFame)).ToString();
mNotoriety.text = ((int)(character.EffectiveNotoriety)).ToString();
// display weight and vulnerability
mWeight.text = character.BaseWeight.ToChitString();
mVulnerability.text = character.CurrentVulnerability.ToChitString();
// display the character's chits in their proper locations
IList<MRActionChit> chits = character.Chits;
for (int i = 0; i < chits.Count; ++i)
{
MRActionChit chit = chits[i];
if (chit != null)
{
if (chit.Stack != null)
chit.Stack.RemovePiece(chit);
chit.Visible = true;
chit.Selectable = character.CanSelectChit(chit);
switch (chit.State)
{
case MRActionChit.eState.Active:
chit.Parent = mActiveChitsPositions[i].transform;
chit.Layer = mActiveChitsPositions[i].layer;
chit.Position = mActiveChitsPositions[i].transform.position;
chit.LocalScale = new Vector3(1.3f, 1.3f, 1f);
break;
case MRActionChit.eState.Fatigued:
chit.Parent = mFatiguedChitsPositions[i].transform;
chit.Layer = mFatiguedChitsPositions[i].layer;
chit.Position = mFatiguedChitsPositions[i].transform.position;
chit.LocalScale = new Vector3(1.3f, 1.3f, 1f);
break;
case MRActionChit.eState.Wounded:
chit.Parent = mWoundedChitsPositions[i].transform;
chit.Layer = mWoundedChitsPositions[i].layer;
chit.Position = mWoundedChitsPositions[i].transform.position;
chit.LocalScale = new Vector3(1.3f, 1.3f, 1f);
break;
}
}
}
MRUtility.SetObjectVisibility(mActiveChitsArea, true);
MRUtility.SetObjectVisibility(mFatiguedChitsArea, true);
MRUtility.SetObjectVisibility(mWoundedChitsArea, true);
// display active items in their proper locations
mActiveWeapon.Clear();
mActiveBreastplate.Clear();
mActiveArmor.Clear();
mActiveHelmet.Clear();
mActiveShield.Clear();
mActiveItems.Clear();
mActiveHorse.Clear();
IList<MRItem> activeItems = character.ActiveItems;
foreach (MRItem item in activeItems)
{
if (item is MRWeapon)
{
mActiveWeapon.AddPieceToTop(item);
}
else if (item is MRArmor)
{
MRArmor armor = (MRArmor)item;
switch (armor.Type)
{
case MRArmor.eType.Breastplate:
mActiveBreastplate.AddPieceToTop(armor);
break;
case MRArmor.eType.Full:
mActiveArmor.AddPieceToTop(armor);
break;
case MRArmor.eType.Helmet:
mActiveHelmet.AddPieceToTop(armor);
break;
case MRArmor.eType.Shield:
mActiveShield.AddPieceToTop(armor);
break;
default:
break;
}
}
else if (item is MRTreasure)
{
MRTreasure treasure = (MRTreasure)item;
treasure.Hidden = false;
mActiveItems.AddPieceToTop(treasure);
}
else if (item is MRHorse)
{
MRHorse horse = (MRHorse)item;
mActiveHorse.AddPieceToTop(horse);
}
}
// display inactive items in their proper locations
mInactiveWeapon.Clear();
mInactiveBreastplate.Clear();
mInactiveArmor.Clear();
mInactiveHelmet.Clear();
mInactiveShield.Clear();
mInactiveItems.Clear();
mInactiveHorse.Clear();
IList<MRItem> inactiveItems = character.InactiveItems;
foreach (MRItem item in inactiveItems)
{
if (item is MRWeapon)
{
mInactiveWeapon.AddPieceToTop(item);
}
else if (item is MRArmor)
{
MRArmor armor = (MRArmor)item;
switch (armor.Type)
{
case MRArmor.eType.Breastplate:
mInactiveBreastplate.AddPieceToTop(armor);
break;
case MRArmor.eType.Full:
mInactiveArmor.AddPieceToTop(armor);
break;
case MRArmor.eType.Helmet:
mInactiveHelmet.AddPieceToTop(armor);
break;
case MRArmor.eType.Shield:
mInactiveShield.AddPieceToTop(armor);
break;
default:
break;
}
}
else if (item is MRTreasure)
{
MRTreasure treasure = (MRTreasure)item;
treasure.Hidden = false;
mInactiveItems.AddPieceToTop(treasure);
}
else if (item is MRHorse)
{
MRHorse horse = (MRHorse)item;
mInactiveHorse.AddPieceToTop(horse);
}
}
// display curses
foreach (MRGame.eCurses curse in Enum.GetValues(typeof(MRGame.eCurses)))
{
mCurses[curse].GetComponent<Renderer>().enabled = character.HasCurse(curse);
}
// display ui elements
if (MRGame.TheGame.CurrentView == MRGame.eViews.SelectAttack)
{
MRMainUI.TheUI.DisplayInstructionMessage("Select Attack");
}
else if (MRGame.TheGame.CurrentView == MRGame.eViews.SelectManeuver)
{
MRMainUI.TheUI.DisplayInstructionMessage("Select Maneuver");
}
else if (MRGame.TheGame.CurrentView == MRGame.eViews.SelectChit)
{
MRMainUI.TheUI.DisplayInstructionMessage("Select Chit");
}
}
}
public bool OnTouched(GameObject touchedObject)
{
return true;
}
public bool OnReleased(GameObject touchedObject)
{
return true;
}
public bool OnSingleTapped(GameObject touchedObject)
{
return true;
}
public bool OnDoubleTapped(GameObject touchedObject)
{
if (Parent.Visible && Parent.Controllable is MRCharacter)
{
// see if an action chit has been selected
MRActionChit selectedChit = touchedObject.GetComponentInChildren<MRActionChit>();
if (selectedChit != null)
{
OnGamePieceSelected(selectedChit);
}
}
return true;
}
public bool OnTouchHeld(GameObject touchedObject)
{
return true;
}
public virtual bool OnTouchMove(GameObject touchedObject, float delta_x, float delta_y)
{
return true;
}
public virtual bool OnButtonActivate(GameObject touchedObject)
{
return true;
}
public bool OnPinchZoom(float pinchDelta)
{
return true;
}
private void SetupTreasureStack(GameObject locationObj, MRGamePieceStack stack)
{
stack.Layer = LayerMask.NameToLayer("CharacterMat");
MRTreasureChartLocation location = locationObj.GetComponentInChildren<MRTreasureChartLocation>();
if (location != null)
location.Treasures = stack;
}
/// <summary>
/// Called when a game piece has been selected.
/// </summary>
/// <param name="piece">The game piece.</param>
public void OnGamePieceSelected(MRIGamePiece piece)
{
MRCharacter character = Parent.Controllable as MRCharacter;
MRActionChit chit = piece as MRActionChit;
MRItem item = piece as MRItem;
switch (MRGame.TheGame.CurrentView)
{
case MRGame.eViews.FatigueCharacter:
if (chit != null)
{
// heal, wound, or fatigue the selected chit
if (character.FatigueBalance != 0)
character.FatigueChit(chit);
else if (character.WoundBalance > 0)
character.WoundChit(chit);
else if (character.HealBalance > 0)
character.HealChit(chit);
}
break;
case MRGame.eViews.SelectChit:
if (chit != null)
{
if (character.SelectChitData != null)
{
character.SelectChitData.SelectedChit = chit;
}
else
{
MRMainUI.TheUI.HideAttackManeuverDialog();
MRMainUI.TheUI.DisplayInstructionMessage(null);
MRGame.TheGame.PopView();
}
}
break;
case MRGame.eViews.Alert:
if (chit != null && character.SelectChitFilter != null && character.SelectChitFilter.IsValidSelectChit(chit))
{
chit.Alert(character.SelectChitFilter.Action);
MRUpdateEvent evt = MRGame.TheGame.GetUpdateEvent(typeof(MRAlertEvent));
if (evt != null)
{
evt.EndEvent();
}
}
else if (item != null && item.Active && item is MRWeapon)
{
((MRWeapon)item).Alerted = !((MRWeapon)item).Alerted;
MRUpdateEvent evt = MRGame.TheGame.GetUpdateEvent(typeof(MRAlertEvent));
if (evt != null)
{
evt.EndEvent();
}
}
break;
case MRGame.eViews.SelectAttack:
if (chit != null && character.SelectChitFilter != null && character.SelectChitFilter.IsValidSelectChit(chit))
{
if (MRGame.TheGame.CombatManager.SetAttack(character, (MRFightChit)chit, MRCombatManager.eAttackType.None))
{
MRMainUI.TheUI.HideAttackManeuverDialog();
MRMainUI.TheUI.DisplayInstructionMessage(null);
MRGame.TheGame.PopView();
}
}
break;
case MRGame.eViews.SelectManeuver:
if (chit != null && character.SelectChitFilter != null && character.SelectChitFilter.IsValidSelectChit(chit))
{
if (MRGame.TheGame.CombatManager.SetManeuver(character, (MRMoveChit)chit, MRCombatManager.eDefenseType.None))
{
MRMainUI.TheUI.HideAttackManeuverDialog();
MRMainUI.TheUI.DisplayInstructionMessage(null);
MRGame.TheGame.PopView();
}
}
break;
case MRGame.eViews.Characters:
if (item != null && character.CanRearrangeItems)
{
// by default, set the item active or inactive
if (item.Active)
character.DeactivateItem(item);
else
character.ActivateItem(item, true);
}
break;
default:
break;
}
}
/// <summary>
/// Called when the player selects "none" or "cancel" when selecting an attack or maneuver chit.
/// </summary>
/// <param name="option">The option selected.</param>
public void OnAttackManeuverSelected(MRCombatManager.eAttackManeuverOption option)
{
if (MRGame.TheGame.CurrentView == MRGame.eViews.SelectAttack ||
MRGame.TheGame.CurrentView == MRGame.eViews.SelectManeuver ||
MRGame.TheGame.CurrentView == MRGame.eViews.SelectChit)
{
if (option == MRCombatManager.eAttackManeuverOption.None)
{
if (MRGame.TheGame.CurrentView == MRGame.eViews.SelectAttack)
MRGame.TheGame.CombatManager.SetAttack((MRCharacter)Parent.Controllable, null, MRCombatManager.eAttackType.None);
else if (MRGame.TheGame.CurrentView == MRGame.eViews.SelectManeuver)
MRGame.TheGame.CombatManager.SetManeuver((MRCharacter)Parent.Controllable, null, MRCombatManager.eDefenseType.None);
}
MRMainUI.TheUI.HideAttackManeuverDialog();
MRMainUI.TheUI.DisplayInstructionMessage(null);
MRGame.TheGame.PopView();
}
else if (MRGame.TheGame.CurrentView == MRGame.eViews.Alert)
{
}
}
#endregion
#region Members
private MRCharacterMat mParent;
private GameObject mActiveChitsArea;
private GameObject mFatiguedChitsArea;
private GameObject mWoundedChitsArea;
private GameObject mActiveChitsBackground;
private GameObject[] mActiveChitsPositions = new GameObject[12];
private GameObject[] mFatiguedChitsPositions = new GameObject[12];
private GameObject[] mWoundedChitsPositions = new GameObject[12];
private GameObject mActiveItemsArea;
private GameObject mInactiveItemsArea;
private MRGamePieceStack mActiveWeapon;
private MRGamePieceStack mActiveArmor;
private MRGamePieceStack mActiveBreastplate;
private MRGamePieceStack mActiveHelmet;
private MRGamePieceStack mActiveShield;
private MRGamePieceStack mActiveHorse;
private MRGamePieceStack mActiveBoots;
private MRGamePieceStack mActiveGloves;
private MRGamePieceStack mActiveItems;
private MRGamePieceStack mInactiveWeapon;
private MRGamePieceStack mInactiveArmor;
private MRGamePieceStack mInactiveBreastplate;
private MRGamePieceStack mInactiveHelmet;
private MRGamePieceStack mInactiveShield;
private MRGamePieceStack mInactiveHorse;
private MRGamePieceStack mInactiveItems;
private TextMesh mGold;
private TextMesh mFame;
private TextMesh mNotoriety;
private TextMesh mWeight;
private TextMesh mVulnerability;
private IDictionary<MRGame.eCurses, GameObject> mCurses = new Dictionary<MRGame.eCurses, GameObject>();
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.CodeAnalysis.Editor.Tagging;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Projection;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Outlining
{
/// <summary>
/// Shared implementation of the outliner tagger provider.
///
/// Note: the outliner tagger is a normal buffer tagger provider and not a view tagger provider.
/// This is important for two reasons. The first is that if it were view-based then we would lose
/// the state of the collapsed/open regions when they scrolled in and out of view. Also, if the
/// editor doesn't know about all the regions in the file, then it wouldn't be able to
/// persist them to the SUO file to persist this data across sessions.
/// </summary>
[Export(typeof(ITaggerProvider))]
[Export(typeof(OutliningTaggerProvider))]
[TagType(typeof(IOutliningRegionTag))]
[ContentType(ContentTypeNames.RoslynContentType)]
internal partial class OutliningTaggerProvider : AsynchronousTaggerProvider<IOutliningRegionTag>,
IEqualityComparer<IOutliningRegionTag>
{
public const string OutliningRegionTextViewRole = nameof(OutliningRegionTextViewRole);
private const int MaxPreviewText = 1000;
private const string Ellipsis = "...";
private readonly ITextEditorFactoryService _textEditorFactoryService;
private readonly IEditorOptionsFactoryService _editorOptionsFactoryService;
private readonly IProjectionBufferFactoryService _projectionBufferFactoryService;
[ImportingConstructor]
public OutliningTaggerProvider(
IForegroundNotificationService notificationService,
ITextEditorFactoryService textEditorFactoryService,
IEditorOptionsFactoryService editorOptionsFactoryService,
IProjectionBufferFactoryService projectionBufferFactoryService,
[ImportMany] IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners)
: base(new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.Outlining), notificationService)
{
_textEditorFactoryService = textEditorFactoryService;
_editorOptionsFactoryService = editorOptionsFactoryService;
_projectionBufferFactoryService = projectionBufferFactoryService;
}
protected override IEqualityComparer<IOutliningRegionTag> TagComparer => this;
bool IEqualityComparer<IOutliningRegionTag>.Equals(IOutliningRegionTag x, IOutliningRegionTag y)
{
// This is only called if the spans for the tags were the same. In that case, we consider ourselves the same
// unless the CollapsedForm properties are different.
return EqualityComparer<object>.Default.Equals(x.CollapsedForm, y.CollapsedForm);
}
int IEqualityComparer<IOutliningRegionTag>.GetHashCode(IOutliningRegionTag obj)
{
return EqualityComparer<object>.Default.GetHashCode(obj.CollapsedForm);
}
protected override ITaggerEventSource CreateEventSource(ITextView textViewOpt, ITextBuffer subjectBuffer)
{
// We listen to the following events:
// 1) Text changes. These can obviously affect outlining, so we need to recompute when
// we hear about them.
// 2) Parse option changes. These can affect outlining when, for example, we change from
// DEBUG to RELEASE (affecting the inactive/active regions).
// 3) When we hear about a workspace being registered. Outlining may run before a
// we even know about a workspace. This can happen, for example, in the TypeScript
// case. With TypeScript a file is opened, but the workspace is not generated until
// some time later when they have examined the file system. As such, initially,
// the file will not have outline spans. When the workspace is created, we want to
// then produce the right outlining spans.
return TaggerEventSources.Compose(
TaggerEventSources.OnTextChanged(subjectBuffer, TaggerDelay.OnIdle),
TaggerEventSources.OnParseOptionChanged(subjectBuffer, TaggerDelay.OnIdle),
TaggerEventSources.OnWorkspaceRegistrationChanged(subjectBuffer, TaggerDelay.OnIdle));
}
/// <summary>
/// Keep this in sync with <see cref="ProduceTagsSynchronously"/>
/// </summary>
protected override async Task ProduceTagsAsync(
TaggerContext<IOutliningRegionTag> context, DocumentSnapshotSpan documentSnapshotSpan, int? caretPosition)
{
try
{
var outliningService = TryGetOutliningService(context, documentSnapshotSpan);
if (outliningService != null)
{
var regions = await outliningService.GetOutliningSpansAsync(
documentSnapshotSpan.Document, context.CancellationToken).ConfigureAwait(false);
ProcessOutliningSpans(context, documentSnapshotSpan.SnapshotSpan, outliningService, regions);
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
/// <summary>
/// Keep this in sync with <see cref="ProduceTagsAsync"/>
/// </summary>
protected override void ProduceTagsSynchronously(
TaggerContext<IOutliningRegionTag> context, DocumentSnapshotSpan documentSnapshotSpan, int? caretPosition)
{
try
{
var outliningService = TryGetOutliningService(context, documentSnapshotSpan);
if (outliningService != null)
{
var document = documentSnapshotSpan.Document;
var cancellationToken = context.CancellationToken;
// Try to call through the synchronous service if possible. Otherwise, fallback
// and make a blocking call against the async service.
var synchronousOutliningService = outliningService as ISynchronousOutliningService;
var regions = synchronousOutliningService != null
? synchronousOutliningService.GetOutliningSpans(document, cancellationToken)
: outliningService.GetOutliningSpansAsync(document, cancellationToken).WaitAndGetResult(cancellationToken);
ProcessOutliningSpans(context, documentSnapshotSpan.SnapshotSpan, outliningService, regions);
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private IOutliningService TryGetOutliningService(
TaggerContext<IOutliningRegionTag> context,
DocumentSnapshotSpan documentSnapshotSpan)
{
var cancellationToken = context.CancellationToken;
using (Logger.LogBlock(FunctionId.Tagger_Outlining_TagProducer_ProduceTags, cancellationToken))
{
var document = documentSnapshotSpan.Document;
var snapshotSpan = documentSnapshotSpan.SnapshotSpan;
var snapshot = snapshotSpan.Snapshot;
if (document != null)
{
return document.Project.LanguageServices.GetService<IOutliningService>();
}
}
return null;
}
private void ProcessOutliningSpans(
TaggerContext<IOutliningRegionTag> context, SnapshotSpan snapshotSpan, IOutliningService outliningService, IList<OutliningSpan> regions)
{
if (regions != null)
{
var snapshot = snapshotSpan.Snapshot;
regions = GetMultiLineRegions(outliningService, regions, snapshot);
// Create the outlining tags.
var tagSpans =
from region in regions
let spanToCollapse = new SnapshotSpan(snapshot, region.TextSpan.ToSpan())
let hintSpan = new SnapshotSpan(snapshot, region.HintSpan.ToSpan())
let tag = new Tag(snapshot.TextBuffer,
region.BannerText,
hintSpan,
region.AutoCollapse,
region.IsDefaultCollapsed,
_textEditorFactoryService,
_projectionBufferFactoryService,
_editorOptionsFactoryService)
select new TagSpan<IOutliningRegionTag>(spanToCollapse, tag);
foreach (var tagSpan in tagSpans)
{
context.AddTag(tagSpan);
}
}
}
private static bool s_exceptionReported = false;
private IList<OutliningSpan> GetMultiLineRegions(IOutliningService service, IList<OutliningSpan> regions, ITextSnapshot snapshot)
{
// Remove any spans that aren't multiline.
var multiLineRegions = new List<OutliningSpan>(regions.Count);
foreach (var region in regions)
{
if (region != null && region.TextSpan.Length > 0)
{
// Check if any clients produced an invalid OutliningSpan. If so, filter them
// out and report a non-fatal watson so we can attempt to determine the source
// of the issue.
var snapshotSpan = snapshot.GetFullSpan().Span;
var regionSpan = region.TextSpan.ToSpan();
if (!snapshotSpan.Contains(regionSpan))
{
if (!s_exceptionReported)
{
s_exceptionReported = true;
try
{
throw new InvalidOutliningRegionException(service, snapshot, snapshotSpan, regionSpan);
}
catch (InvalidOutliningRegionException e) when (FatalError.ReportWithoutCrash(e))
{
}
}
continue;
}
var startLine = snapshot.GetLineNumberFromPosition(region.TextSpan.Start);
var endLine = snapshot.GetLineNumberFromPosition(region.TextSpan.End);
if (startLine != endLine)
{
multiLineRegions.Add(region);
}
}
}
return multiLineRegions;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// a set of lightweight static helpers for lazy initialization.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Diagnostics;
namespace System.Threading
{
/// <summary>
/// Provides lazy initialization routines.
/// </summary>
/// <remarks>
/// These routines avoid needing to allocate a dedicated, lazy-initialization instance, instead using
/// references to ensure targets have been initialized as they are accessed.
/// </remarks>
public static class LazyInitializer
{
/// <summary>
/// Initializes a target reference type with the type's default constructor if the target has not
/// already been initialized.
/// </summary>
/// <typeparam name="T">The reference type of the reference to be initialized.</typeparam>
/// <param name="target">A reference of type <typeparamref name="T"/> to initialize if it has not
/// already been initialized.</param>
/// <returns>The initialized reference of type <typeparamref name="T"/>.</returns>
/// <exception cref="T:System.MissingMemberException">Type <typeparamref name="T"/> does not have a default
/// constructor.</exception>
/// <exception cref="T:System.MemberAccessException">
/// Permissions to access the constructor of type <typeparamref name="T"/> were missing.
/// </exception>
/// <remarks>
/// <para>
/// This method may only be used on reference types. To ensure initialization of value
/// types, see other overloads of EnsureInitialized.
/// </para>
/// <para>
/// This method may be used concurrently by multiple threads to initialize <paramref name="target"/>.
/// In the event that multiple threads access this method concurrently, multiple instances of <typeparamref name="T"/>
/// may be created, but only one will be stored into <paramref name="target"/>. In such an occurrence, this method will not dispose of the
/// objects that were not stored. If such objects must be disposed, it is up to the caller to determine
/// if an object was not used and to then dispose of the object appropriately.
/// </para>
/// </remarks>
public static T EnsureInitialized<T>(ref T target) where T : class =>
Volatile.Read(ref target) ?? EnsureInitializedCore(ref target);
/// <summary>
/// Initializes a target reference type with the type's default constructor (slow path)
/// </summary>
/// <typeparam name="T">The reference type of the reference to be initialized.</typeparam>
/// <param name="target">The variable that need to be initialized</param>
/// <returns>The initialized variable</returns>
private static T EnsureInitializedCore<T>(ref T target) where T : class
{
try
{
Interlocked.CompareExchange(ref target, Activator.CreateInstance<T>(), null);
}
catch (MissingMethodException)
{
throw new MissingMemberException(SR.Lazy_CreateValue_NoParameterlessCtorForT);
}
Debug.Assert(target != null);
return target;
}
/// <summary>
/// Initializes a target reference type using the specified function if it has not already been
/// initialized.
/// </summary>
/// <typeparam name="T">The reference type of the reference to be initialized.</typeparam>
/// <param name="target">The reference of type <typeparamref name="T"/> to initialize if it has not
/// already been initialized.</param>
/// <param name="valueFactory">The <see cref="T:System.Func{T}"/> invoked to initialize the
/// reference.</param>
/// <returns>The initialized reference of type <typeparamref name="T"/>.</returns>
/// <exception cref="T:System.MissingMemberException">Type <typeparamref name="T"/> does not have a
/// default constructor.</exception>
/// <exception cref="T:System.InvalidOperationException"><paramref name="valueFactory"/> returned
/// null.</exception>
/// <remarks>
/// <para>
/// This method may only be used on reference types, and <paramref name="valueFactory"/> may
/// not return a null reference (Nothing in Visual Basic). To ensure initialization of value types or
/// to allow null reference types, see other overloads of EnsureInitialized.
/// </para>
/// <para>
/// This method may be used concurrently by multiple threads to initialize <paramref name="target"/>.
/// In the event that multiple threads access this method concurrently, multiple instances of <typeparamref name="T"/>
/// may be created, but only one will be stored into <paramref name="target"/>. In such an occurrence, this method will not dispose of the
/// objects that were not stored. If such objects must be disposed, it is up to the caller to determine
/// if an object was not used and to then dispose of the object appropriately.
/// </para>
/// </remarks>
public static T EnsureInitialized<T>(ref T target, Func<T> valueFactory) where T : class =>
Volatile.Read(ref target) ?? EnsureInitializedCore(ref target, valueFactory);
/// <summary>
/// Initialize the target using the given delegate (slow path).
/// </summary>
/// <typeparam name="T">The reference type of the reference to be initialized.</typeparam>
/// <param name="target">The variable that need to be initialized</param>
/// <param name="valueFactory">The delegate that will be executed to initialize the target</param>
/// <returns>The initialized variable</returns>
private static T EnsureInitializedCore<T>(ref T target, Func<T> valueFactory) where T : class
{
T value = valueFactory();
if (value == null)
{
throw new InvalidOperationException(SR.Lazy_StaticInit_InvalidOperation);
}
Interlocked.CompareExchange(ref target, value, null);
Debug.Assert(target != null);
return target;
}
/// <summary>
/// Initializes a target reference or value type with its default constructor if it has not already
/// been initialized.
/// </summary>
/// <typeparam name="T">The type of the reference to be initialized.</typeparam>
/// <param name="target">A reference or value of type <typeparamref name="T"/> to initialize if it
/// has not already been initialized.</param>
/// <param name="initialized">A reference to a boolean that determines whether the target has already
/// been initialized.</param>
/// <param name="syncLock">A reference to an object used as the mutually exclusive lock for initializing
/// <paramref name="target"/>. If <paramref name="syncLock"/> is null, a new object will be instantiated.</param>
/// <returns>The initialized value of type <typeparamref name="T"/>.</returns>
public static T EnsureInitialized<T>(ref T target, ref bool initialized, ref object syncLock)
{
// Fast path.
if (Volatile.Read(ref initialized))
{
return target;
}
return EnsureInitializedCore(ref target, ref initialized, ref syncLock);
}
/// <summary>
/// Ensure the target is initialized and return the value (slow path). This overload permits nulls
/// and also works for value type targets. Uses the type's default constructor to create the value.
/// </summary>
/// <typeparam name="T">The type of target.</typeparam>
/// <param name="target">A reference to the target to be initialized.</param>
/// <param name="initialized">A reference to a location tracking whether the target has been initialized.</param>
/// <param name="syncLock">A reference to a location containing a mutual exclusive lock. If <paramref name="syncLock"/> is null,
/// a new object will be instantiated.</param>
/// </param>
/// <returns>The initialized object.</returns>
private static T EnsureInitializedCore<T>(ref T target, ref bool initialized, ref object syncLock)
{
// Lazily initialize the lock if necessary and then double check if initialization is still required.
lock (EnsureLockInitialized(ref syncLock))
{
if (!Volatile.Read(ref initialized))
{
try
{
target = Activator.CreateInstance<T>();
}
catch (MissingMethodException)
{
throw new MissingMemberException(SR.Lazy_CreateValue_NoParameterlessCtorForT);
}
Volatile.Write(ref initialized, true);
}
}
return target;
}
/// <summary>
/// Initializes a target reference or value type with a specified function if it has not already been
/// initialized.
/// </summary>
/// <typeparam name="T">The type of the reference to be initialized.</typeparam>
/// <param name="target">A reference or value of type <typeparamref name="T"/> to initialize if it
/// has not already been initialized.</param>
/// <param name="initialized">A reference to a boolean that determines whether the target has already
/// been initialized.</param>
/// <param name="syncLock">A reference to an object used as the mutually exclusive lock for initializing
/// <paramref name="target"/>. If <paramref name="syncLock"/> is null, a new object will be instantiated.</param>
/// <param name="valueFactory">The <see cref="T:System.Func{T}"/> invoked to initialize the
/// reference or value.</param>
/// <returns>The initialized value of type <typeparamref name="T"/>.</returns>
public static T EnsureInitialized<T>(ref T target, ref bool initialized, ref object syncLock, Func<T> valueFactory)
{
// Fast path.
if (Volatile.Read(ref initialized))
{
return target;
}
return EnsureInitializedCore(ref target, ref initialized, ref syncLock, valueFactory);
}
/// <summary>
/// Ensure the target is initialized and return the value (slow path). This overload permits nulls
/// and also works for value type targets. Uses the supplied function to create the value.
/// </summary>
/// <typeparam name="T">The type of target.</typeparam>
/// <param name="target">A reference to the target to be initialized.</param>
/// <param name="initialized">A reference to a location tracking whether the target has been initialized.</param>
/// <param name="syncLock">A reference to a location containing a mutual exclusive lock. If <paramref name="syncLock"/> is null,
/// a new object will be instantiated.</param>
/// <param name="valueFactory">
/// The <see cref="T:System.Func{T}"/> to invoke in order to produce the lazily-initialized value.
/// </param>
/// <returns>The initialized object.</returns>
private static T EnsureInitializedCore<T>(ref T target, ref bool initialized, ref object syncLock, Func<T> valueFactory)
{
// Lazily initialize the lock if necessary and then double check if initialization is still required.
lock (EnsureLockInitialized(ref syncLock))
{
if (!Volatile.Read(ref initialized))
{
target = valueFactory();
Volatile.Write(ref initialized, true);
}
}
return target;
}
/// <summary>
/// Initializes a target reference type with a specified function if it has not already been initialized.
/// </summary>
/// <typeparam name="T">The type of the reference to be initialized. Has to be reference type.</typeparam>
/// <param name="target">A reference of type <typeparamref name="T"/> to initialize if it has not already been initialized.</param>
/// <param name="syncLock">A reference to an object used as the mutually exclusive lock for initializing
/// <paramref name="target"/>. If <paramref name="syncLock"/> is null, a new object will be instantiated.</param>
/// <param name="valueFactory">The <see cref="T:System.Func{T}"/> invoked to initialize the reference.</param>
/// <returns>The initialized value of type <typeparamref name="T"/>.</returns>
public static T EnsureInitialized<T>(ref T target, ref object syncLock, Func<T> valueFactory) where T : class =>
Volatile.Read(ref target) ?? EnsureInitializedCore(ref target, ref syncLock, valueFactory);
/// <summary>
/// Ensure the target is initialized and return the value (slow path). This overload works only for reference type targets.
/// Uses the supplied function to create the value.
/// </summary>
/// <typeparam name="T">The type of target. Has to be reference type.</typeparam>
/// <param name="target">A reference to the target to be initialized.</param>
/// <param name="syncLock">A reference to a location containing a mutual exclusive lock. If <paramref name="syncLock"/> is null,
/// a new object will be instantiated.</param>
/// <param name="valueFactory">
/// The <see cref="T:System.Func{T}"/> to invoke in order to produce the lazily-initialized value.
/// </param>
/// <returns>The initialized object.</returns>
private static T EnsureInitializedCore<T>(ref T target, ref object syncLock, Func<T> valueFactory) where T : class
{
// Lazily initialize the lock if necessary and then double check if initialization is still required.
lock (EnsureLockInitialized(ref syncLock))
{
if (Volatile.Read(ref target) == null)
{
Volatile.Write(ref target, valueFactory());
if (target == null)
{
throw new InvalidOperationException(SR.Lazy_StaticInit_InvalidOperation);
}
}
}
return target;
}
/// <summary>
/// Ensure the lock object is initialized.
/// </summary>
/// <param name="syncLock">A reference to a location containing a mutual exclusive lock. If <paramref name="syncLock"/> is null,
/// a new object will be instantiated.</param>
/// <returns>Initialized lock object.</returns>
private static object EnsureLockInitialized(ref object syncLock) =>
syncLock ??
Interlocked.CompareExchange(ref syncLock, new object(), null) ??
syncLock;
}
}
| |
// Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Text;
using System.Collections.Generic;
//TODO: Reflection should be done at a higher level than this class
using System.Reflection;
namespace NDesk.DBus
{
//maybe this should be nullable?
struct Signature
{
//TODO: this class needs some work
//Data should probably include the null terminator
public static readonly Signature Empty = new Signature (String.Empty);
public static bool operator == (Signature a, Signature b)
{
/*
//TODO: remove this hack to handle bad case when Data is null
if (a.data == null || b.data == null)
throw new Exception ("Encountered Signature with null buffer");
*/
/*
if (a.data == null && b.data == null)
return true;
if (a.data == null || b.data == null)
return false;
*/
if (a.data.Length != b.data.Length)
return false;
for (int i = 0 ; i != a.data.Length ; i++)
if (a.data[i] != b.data[i])
return false;
return true;
}
public static bool operator != (Signature a, Signature b)
{
return !(a == b);
}
public override bool Equals (object o)
{
if (o == null)
return false;
if (!(o is Signature))
return false;
return this == (Signature)o;
}
public override int GetHashCode ()
{
return data.GetHashCode ();
}
public static Signature operator + (Signature s1, Signature s2)
{
return Concat (s1, s2);
}
//these need to be optimized
public static Signature Concat (Signature s1, Signature s2)
{
return new Signature (s1.Value + s2.Value);
}
public static Signature Copy (Signature sig)
{
return new Signature (sig.Value);
}
public Signature (string value)
{
this.data = Encoding.ASCII.GetBytes (value);
}
public Signature (byte[] value)
{
this.data = new byte[value.Length];
for (int i = 0 ; i != value.Length ; i++)
this.data[i] = value[i];
}
//this will become obsolete soon
internal Signature (DType value)
{
this.data = new byte[1];
this.data[0] = (byte)value;
}
internal Signature (DType[] value)
{
this.data = new byte[value.Length];
/*
MemoryStream ms = new MemoryStream (this.data);
foreach (DType t in value)
ms.WriteByte ((byte)t);
*/
for (int i = 0 ; i != value.Length ; i++)
this.data[i] = (byte)value[i];
}
byte[] data;
//TODO: this should be private, but MessageWriter and Monitor still use it
//[Obsolete]
public byte[] GetBuffer ()
{
return data;
}
internal DType this[int index]
{
get {
return (DType)data[index];
}
}
public int Length
{
get {
return data.Length;
}
}
//[Obsolete]
public string Value
{
get {
/*
//FIXME: hack to handle bad case when Data is null
if (data == null)
return String.Empty;
*/
return Encoding.ASCII.GetString (data);
}
}
public override string ToString ()
{
return Value;
/*
StringBuilder sb = new StringBuilder ();
foreach (DType t in data) {
//we shouldn't rely on object mapping here, but it's an easy way to get string representations for now
Type type = DTypeToType (t);
if (type != null) {
sb.Append (type.Name);
} else {
char c = (char)t;
if (!Char.IsControl (c))
sb.Append (c);
else
sb.Append (@"\" + (int)c);
}
sb.Append (" ");
}
return sb.ToString ();
*/
}
public Signature MakeArraySignature ()
{
return new Signature (DType.Array) + this;
}
public static Signature MakeStruct (params Signature[] elems)
{
Signature sig = Signature.Empty;
sig += new Signature (DType.StructBegin);
foreach (Signature elem in elems)
sig += elem;
sig += new Signature (DType.StructEnd);
return sig;
}
public static Signature MakeDictEntry (Signature keyType, Signature valueType)
{
Signature sig = Signature.Empty;
sig += new Signature (DType.DictEntryBegin);
sig += keyType;
sig += valueType;
sig += new Signature (DType.DictEntryEnd);
return sig;
}
public static Signature MakeDict (Signature keyType, Signature valueType)
{
return MakeDictEntry (keyType, valueType).MakeArraySignature ();
}
/*
//TODO: complete this
public bool IsPrimitive
{
get {
if (this == Signature.Empty)
return true;
return false;
}
}
*/
public bool IsDict
{
get {
if (Length < 3)
return false;
if (!IsArray)
return false;
if (this[2] != DType.DictEntryBegin)
return false;
return true;
}
}
public bool IsArray
{
get {
if (Length < 2)
return false;
if (this[0] != DType.Array)
return false;
return true;
}
}
public Signature GetElementSignature ()
{
if (!IsArray)
throw new Exception ("Cannot get the element signature of a non-array (signature was '" + this + "')");
//TODO: improve this
if (Length != 2)
throw new NotSupportedException ("Parsing signatures with more than one primitive value is not supported (signature was '" + this + "')");
return new Signature (this[1]);
}
public Type[] ToTypes ()
{
List<Type> types = new List<Type> ();
for (int i = 0 ; i != data.Length ; types.Add (ToType (ref i)));
return types.ToArray ();
}
public Type ToType ()
{
int pos = 0;
Type ret = ToType (ref pos);
if (pos != data.Length)
throw new Exception ("Sig parse error: at " + pos + " but should be at " + data.Length);
return ret;
}
internal static DType TypeCodeToDType (TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.Empty:
return DType.Invalid;
case TypeCode.Object:
return DType.Invalid;
case TypeCode.DBNull:
return DType.Invalid;
case TypeCode.Boolean:
return DType.Boolean;
case TypeCode.Char:
return DType.UInt16;
case TypeCode.SByte:
return DType.Byte;
case TypeCode.Byte:
return DType.Byte;
case TypeCode.Int16:
return DType.Int16;
case TypeCode.UInt16:
return DType.UInt16;
case TypeCode.Int32:
return DType.Int32;
case TypeCode.UInt32:
return DType.UInt32;
case TypeCode.Int64:
return DType.Int64;
case TypeCode.UInt64:
return DType.UInt64;
case TypeCode.Single:
return DType.Single;
case TypeCode.Double:
return DType.Double;
case TypeCode.Decimal:
return DType.Invalid;
case TypeCode.DateTime:
return DType.Invalid;
case TypeCode.String:
return DType.String;
default:
return DType.Invalid;
}
}
//FIXME: this method is bad, get rid of it
internal static DType TypeToDType (Type type)
{
if (type == typeof (void))
return DType.Invalid;
if (type == typeof (string))
return DType.String;
if (type == typeof (ObjectPath))
return DType.ObjectPath;
if (type == typeof (Signature))
return DType.Signature;
if (type == typeof (object))
return DType.Variant;
if (type.IsPrimitive)
return TypeCodeToDType (Type.GetTypeCode (type));
if (type.IsEnum)
return TypeToDType (type.GetElementType ());
//needs work
if (type.IsArray)
return DType.Array;
//if (type.UnderlyingSystemType != null)
// return TypeToDType (type.UnderlyingSystemType);
if (Mapper.IsPublic (type))
return DType.ObjectPath;
if (!type.IsPrimitive && !type.IsEnum)
return DType.Struct;
//TODO: maybe throw an exception here
return DType.Invalid;
}
/*
public static DType TypeToDType (Type type)
{
if (type == null)
return DType.Invalid;
else if (type == typeof (byte))
return DType.Byte;
else if (type == typeof (bool))
return DType.Boolean;
else if (type == typeof (short))
return DType.Int16;
else if (type == typeof (ushort))
return DType.UInt16;
else if (type == typeof (int))
return DType.Int32;
else if (type == typeof (uint))
return DType.UInt32;
else if (type == typeof (long))
return DType.Int64;
else if (type == typeof (ulong))
return DType.UInt64;
else if (type == typeof (float)) //not supported by libdbus at time of writing
return DType.Single;
else if (type == typeof (double))
return DType.Double;
else if (type == typeof (string))
return DType.String;
else if (type == typeof (ObjectPath))
return DType.ObjectPath;
else if (type == typeof (Signature))
return DType.Signature;
else
return DType.Invalid;
}
*/
public Type ToType (ref int pos)
{
DType dtype = (DType)data[pos++];
switch (dtype) {
case DType.Invalid:
return typeof (void);
case DType.Byte:
return typeof (byte);
case DType.Boolean:
return typeof (bool);
case DType.Int16:
return typeof (short);
case DType.UInt16:
return typeof (ushort);
case DType.Int32:
return typeof (int);
case DType.UInt32:
return typeof (uint);
case DType.Int64:
return typeof (long);
case DType.UInt64:
return typeof (ulong);
case DType.Single: ////not supported by libdbus at time of writing
return typeof (float);
case DType.Double:
return typeof (double);
case DType.String:
return typeof (string);
case DType.ObjectPath:
return typeof (ObjectPath);
case DType.Signature:
return typeof (Signature);
case DType.Array:
//peek to see if this is in fact a dictionary
if ((DType)data[pos] == DType.DictEntryBegin) {
//skip over the {
pos++;
Type keyType = ToType (ref pos);
Type valueType = ToType (ref pos);
//skip over the }
pos++;
return typeof (IDictionary<,>).MakeGenericType (new Type[] {keyType, valueType});
} else {
return ToType (ref pos).MakeArrayType ();
}
case DType.Struct:
return typeof (ValueType);
case DType.DictEntry:
return typeof (System.Collections.Generic.KeyValuePair<,>);
case DType.Variant:
return typeof (object);
default:
throw new NotSupportedException ("Parsing or converting this signature is not yet supported (signature was '" + this + "'), at DType." + dtype);
}
}
public static Signature GetSig (object[] objs)
{
return GetSig (Type.GetTypeArray (objs));
}
public static Signature GetSig (Type[] types)
{
if (types == null)
throw new ArgumentNullException ("types");
Signature sig = Signature.Empty;
foreach (Type type in types)
sig += GetSig (type);
return sig;
}
public static Signature GetSig (Type type)
{
if (type == null)
throw new ArgumentNullException ("type");
//this is inelegant, but works for now
if (type == typeof (Signature))
return new Signature (DType.Signature);
if (type == typeof (ObjectPath))
return new Signature (DType.ObjectPath);
if (type == typeof (void))
return Signature.Empty;
if (type == typeof (string))
return new Signature (DType.String);
if (type == typeof (object))
return new Signature (DType.Variant);
if (type.IsArray)
return GetSig (type.GetElementType ()).MakeArraySignature ();
if (type.IsGenericType && (type.GetGenericTypeDefinition () == typeof (IDictionary<,>) || type.GetGenericTypeDefinition () == typeof (Dictionary<,>))) {
Type[] genArgs = type.GetGenericArguments ();
return Signature.MakeDict (GetSig (genArgs[0]), GetSig (genArgs[1]));
}
if (Mapper.IsPublic (type)) {
return new Signature (DType.ObjectPath);
}
if (!type.IsPrimitive && !type.IsEnum) {
Signature sig = Signature.Empty;
foreach (FieldInfo fi in type.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
sig += GetSig (fi.FieldType);
return Signature.MakeStruct (sig);
}
DType dtype = Signature.TypeToDType (type);
return new Signature (dtype);
}
}
enum ArgDirection
{
In,
Out,
}
enum DType : byte
{
Invalid = (byte)'\0',
Byte = (byte)'y',
Boolean = (byte)'b',
Int16 = (byte)'n',
UInt16 = (byte)'q',
Int32 = (byte)'i',
UInt32 = (byte)'u',
Int64 = (byte)'x',
UInt64 = (byte)'t',
Single = (byte)'f', //This is not yet supported!
Double = (byte)'d',
String = (byte)'s',
ObjectPath = (byte)'o',
Signature = (byte)'g',
Array = (byte)'a',
//TODO: remove Struct and DictEntry -- they are not relevant to wire protocol
Struct = (byte)'r',
DictEntry = (byte)'e',
Variant = (byte)'v',
StructBegin = (byte)'(',
StructEnd = (byte)')',
DictEntryBegin = (byte)'{',
DictEntryEnd = (byte)'}',
}
}
| |
//--------------------------------------------------------------------------------------
// File: DXMUTMesh.cs
//
// Support code for loading DirectX .X files.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
using System;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
namespace Microsoft.Samples.DirectX.UtilityToolkit
{
/// <summary>Class for loading and rendering file-based meshes</summary>
public sealed class FrameworkMesh : IDisposable
{
#region Instance Data
private string meshFileName;
private Mesh systemMemoryMesh = null; // System Memory mesh, lives through a resize
private Mesh localMemoryMesh = null; // Local mesh, rebuilt on resize
private Material[] meshMaterials = null; // Materials for the mesh
private BaseTexture[] meshTextures = null; // Textures for the mesh
private bool isUsingMeshMaterials = true; // Should the mesh be rendered with the materials
/// <summary>Returns the system memory mesh</summary>
public Mesh SystemMesh { get { return systemMemoryMesh; } }
/// <summary>Returns the local memory mesh</summary>
public Mesh LocalMesh { get { return localMemoryMesh; } }
/// <summary>Should the mesh be rendered with materials</summary>
public bool IsUsingMaterials{ get { return isUsingMeshMaterials; } set { isUsingMeshMaterials = value; } }
/// <summary>Number of materials in mesh</summary>
public int NumberMaterials { get { return meshMaterials.Length; } }
/// <summary>Gets a texture from the mesh</summary>
public BaseTexture GetTexture(int index) { return meshTextures[index]; }
/// <summary>Gets a material from the mesh</summary>
public Material GetMaterial(int index) { return meshMaterials[index]; }
#endregion
#region Creation
/// <summary>Create a new mesh using this file</summary>
public FrameworkMesh(Device device, string name)
{
meshFileName = name;
Create(device, meshFileName);
}
/// <summary>Create a new mesh</summary>
public FrameworkMesh() : this(null, "FrameworkMeshFile_Mesh") {}
/// <summary>Create the mesh data</summary>
public void Create(Device device, string name)
{
// Hook the device events
System.Diagnostics.Debug.Assert(device != null, "Device should not be null.");
device.DeviceLost += new EventHandler(OnLostDevice);
device.DeviceReset += new EventHandler(OnResetDevice);
device.Disposing += new EventHandler(OnDeviceDisposing);
GraphicsStream adjacency; // Adjacency information
ExtendedMaterial[] materials; // Mesh material information
// First try to find the filename
string path = string.Empty;
try
{
path = Utility.FindMediaFile(name);
}
catch(MediaNotFoundException)
{
// The media was not found, maybe a full path was passed in?
if (System.IO.File.Exists(name))
{
path = name;
}
else
{
// No idea what this is trying to find
throw new MediaNotFoundException();
}
}
// Now load the mesh
systemMemoryMesh = Mesh.FromFile(path, MeshFlags.SystemMemory, device, out adjacency,
out materials);
using (adjacency)
{
// Optimize the mesh for performance
systemMemoryMesh.OptimizeInPlace(MeshFlags.OptimizeVertexCache | MeshFlags.OptimizeCompact |
MeshFlags.OptimizeAttributeSort, adjacency);
// Find the folder of where the mesh file is located
string folder = Utility.AppendDirectorySeparator(new System.IO.FileInfo(path).DirectoryName);
// Create the materials
CreateMaterials(folder, device, adjacency, materials);
}
// Finally call reset
OnResetDevice(device, EventArgs.Empty);
}
// TODO: Create with XOF
/// <summary>Create the materials for the mesh</summary>
public void CreateMaterials(string folder, Device device, GraphicsStream adjacency, ExtendedMaterial[] materials)
{
// Does the mesh have materials?
if ((materials != null) && (materials.Length > 0))
{
// Allocate the arrays for the materials
meshMaterials = new Material[materials.Length];
meshTextures = new BaseTexture[materials.Length];
// Copy each material and create it's texture
for(int i = 0; i < materials.Length; i++)
{
// Copy the material first
meshMaterials[i] = materials[i].Material3D;
// Is there a texture for this material?
if ((materials[i].TextureFilename == null) || (materials[i].TextureFilename.Length == 0) )
continue; // No, just continue now
ImageInformation info = new ImageInformation();
string textureFile = folder + materials[i].TextureFilename;
try
{
// First look for the texture in the same folder as the input folder
info = TextureLoader.ImageInformationFromFile(textureFile);
}
catch
{
try
{
// Couldn't find it, look in the media folder
textureFile = Utility.FindMediaFile(materials[i].TextureFilename);
info = TextureLoader.ImageInformationFromFile(textureFile);
}
catch (MediaNotFoundException)
{
// Couldn't find it anywhere, skip it
continue;
}
}
switch (info.ResourceType)
{
case ResourceType.Textures:
meshTextures[i] = TextureLoader.FromFile(device, textureFile);
break;
case ResourceType.CubeTexture:
meshTextures[i] = TextureLoader.FromCubeFile(device, textureFile);
break;
case ResourceType.VolumeTexture:
meshTextures[i] = TextureLoader.FromVolumeFile(device, textureFile);
break;
}
}
}
}
#endregion
#region Class Methods
/// <summary>Updates the mesh to a new vertex format</summary>
public void SetVertexFormat(Device device, VertexFormats format)
{
Mesh tempSystemMesh = null;
Mesh tempLocalMesh = null;
VertexFormats oldFormat = VertexFormats.None;
using(systemMemoryMesh)
{
using (localMemoryMesh)
{
// Clone the meshes
if (systemMemoryMesh != null)
{
oldFormat = systemMemoryMesh.VertexFormat;
tempSystemMesh = systemMemoryMesh.Clone(systemMemoryMesh.Options.Value,
format, device);
}
if (localMemoryMesh != null)
{
tempLocalMesh = localMemoryMesh.Clone(localMemoryMesh.Options.Value,
format, device);
}
}
}
// Store the new meshes
systemMemoryMesh = tempSystemMesh;
localMemoryMesh = tempLocalMesh;
// Compute normals if they are being requested and the old mesh didn't have them
if ( ((oldFormat & VertexFormats.Normal) == 0) && (format != 0) )
{
if (systemMemoryMesh != null)
systemMemoryMesh.ComputeNormals();
if (localMemoryMesh != null)
localMemoryMesh.ComputeNormals();
}
}
/// <summary>Updates the mesh to a new vertex declaration</summary>
public void SetVertexDeclaration(Device device, VertexElement[] decl)
{
Mesh tempSystemMesh = null;
Mesh tempLocalMesh = null;
VertexElement[] oldDecl = null;
using(systemMemoryMesh)
{
using (localMemoryMesh)
{
// Clone the meshes
if (systemMemoryMesh != null)
{
oldDecl = systemMemoryMesh.Declaration;
tempSystemMesh = systemMemoryMesh.Clone(systemMemoryMesh.Options.Value,
decl, device);
}
if (localMemoryMesh != null)
{
tempLocalMesh = localMemoryMesh.Clone(localMemoryMesh.Options.Value,
decl, device);
}
}
}
// Store the new meshes
systemMemoryMesh = tempSystemMesh;
localMemoryMesh = tempLocalMesh;
bool hadNormal = false;
// Check if the old declaration contains a normal.
for(int i = 0; i < oldDecl.Length; i++)
{
if (oldDecl[i].DeclarationUsage == DeclarationUsage.Normal)
{
hadNormal = true;
break;
}
}
// Check to see if the new declaration has a normal
bool hasNormalNow = false;
for(int i = 0; i < decl.Length; i++)
{
if (decl[i].DeclarationUsage == DeclarationUsage.Normal)
{
hasNormalNow = true;
break;
}
}
// Compute normals if they are being requested and the old mesh didn't have them
if ( !hadNormal && hasNormalNow )
{
if (systemMemoryMesh != null)
systemMemoryMesh.ComputeNormals();
if (localMemoryMesh != null)
localMemoryMesh.ComputeNormals();
}
}
/// <summary>Occurs after the device has been reset</summary>
private void OnResetDevice(object sender, EventArgs e)
{
Device device = sender as Device;
if (systemMemoryMesh == null)
throw new InvalidOperationException("There is no system memory mesh. Nothing to do here.");
// Make a local memory version of the mesh. Note: because we are passing in
// no flags, the default behavior is to clone into local memory.
localMemoryMesh = systemMemoryMesh.Clone((systemMemoryMesh.Options.Value & ~MeshFlags.SystemMemory),
systemMemoryMesh.VertexFormat, device);
}
/// <summary>Occurs before the device is going to be reset</summary>
private void OnLostDevice(object sender, EventArgs e)
{
if (localMemoryMesh != null)
localMemoryMesh.Dispose();
localMemoryMesh = null;
}
/// <summary>Renders this mesh</summary>
public void Render(Device device, bool canDrawOpaque, bool canDrawAlpha)
{
if (localMemoryMesh == null)
throw new InvalidOperationException("No local memory mesh.");
// Frist, draw the subsets without alpha
if (canDrawOpaque)
{
for (int i = 0; i < meshMaterials.Length; i++)
{
if (isUsingMeshMaterials)
{
if (meshMaterials[i].DiffuseColor.Alpha < 1.0f)
continue; // Only drawing opaque right now
// set the device material and texture
device.Material = meshMaterials[i];
device.SetTexture(0, meshTextures[i]);
}
localMemoryMesh.DrawSubset(i);
}
}
// Then, draw the subsets with alpha
if (canDrawAlpha)
{
for (int i = 0; i < meshMaterials.Length; i++)
{
if (meshMaterials[i].DiffuseColor.Alpha == 1.0f)
continue; // Only drawing non-opaque right now
// set the device material and texture
device.Material = meshMaterials[i];
device.SetTexture(0, meshTextures[i]);
localMemoryMesh.DrawSubset(i);
}
}
}
/// <summary>Renders this mesh</summary>
public void Render(Device device) { Render(device, true, true); }
// TODO: Render with effect
/// <summary>Compute a bounding sphere for this mesh</summary>
public float ComputeBoundingSphere(out Vector3 center)
{
if (systemMemoryMesh == null)
throw new InvalidOperationException("There is no system memory mesh. Nothing to do here.");
// Get the object declaration
int strideSize = VertexInformation.GetFormatSize(systemMemoryMesh.VertexFormat);
// Lock the vertex buffer
GraphicsStream data = null;
try
{
data = systemMemoryMesh.LockVertexBuffer(LockFlags.ReadOnly);
// Now compute the bounding sphere
return Geometry.ComputeBoundingSphere(data, systemMemoryMesh.NumberVertices,
systemMemoryMesh.VertexFormat, out center);
}
finally
{
// Make sure to unlock the vertex buffer
if (data != null)
systemMemoryMesh.UnlockVertexBuffer();
}
}
#endregion
#region IDisposable Members
/// <summary>Cleans up any resources required when this object is disposed</summary>
public void Dispose()
{
OnLostDevice(null, EventArgs.Empty);
if (meshTextures != null)
{
for(int i = 0; i < meshTextures.Length; i++)
{
if (meshTextures[i] != null)
meshTextures[i].Dispose();
}
}
meshTextures = null;
meshMaterials = null;
if (systemMemoryMesh != null)
systemMemoryMesh.Dispose();
systemMemoryMesh = null;
}
/// <summary>Cleans up any resources required when this object is disposed</summary>
private void OnDeviceDisposing(object sender, EventArgs e)
{
// Just dispose of our class
Dispose();
}
#endregion
}
}
| |
// ***********************************************************************
// Copyright (c) 2008-2014 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
#if NETCF
using System.Linq;
#endif
using NUnit.Framework.Interfaces;
namespace NUnit.Framework.Internal.Builders
{
/// <summary>
/// NUnitTestCaseBuilder is a utility class used by attributes
/// that build test cases.
/// </summary>
public class NUnitTestCaseBuilder
{
private readonly Randomizer _randomizer = Randomizer.CreateRandomizer();
private readonly TestNameGenerator _nameGenerator;
/// <summary>
/// Constructs an <see cref="NUnitTestCaseBuilder"/>
/// </summary>
public NUnitTestCaseBuilder()
{
_nameGenerator = new TestNameGenerator();
}
/// <summary>
/// Builds a single NUnitTestMethod, either as a child of the fixture
/// or as one of a set of test cases under a ParameterizedTestMethodSuite.
/// </summary>
/// <param name="method">The MethodInfo from which to construct the TestMethod</param>
/// <param name="parentSuite">The suite or fixture to which the new test will be added</param>
/// <param name="parms">The ParameterSet to be used, or null</param>
/// <returns></returns>
public TestMethod BuildTestMethod(IMethodInfo method, Test parentSuite, TestCaseParameters parms)
{
var testMethod = new TestMethod(method, parentSuite)
{
Seed = _randomizer.Next()
};
CheckTestMethodSignature(testMethod, parms);
if (parms == null || parms.Arguments == null)
testMethod.ApplyAttributesToTest(method.MethodInfo);
// NOTE: After the call to CheckTestMethodSignature, the Method
// property of testMethod may no longer be the same as the
// original MethodInfo, so we don't use it here.
string prefix = testMethod.Method.TypeInfo.FullName;
// Needed to give proper fullname to test in a parameterized fixture.
// Without this, the arguments to the fixture are not included.
if (parentSuite != null)
prefix = parentSuite.FullName;
if (parms != null)
{
parms.ApplyToTest(testMethod);
if (parms.TestName != null)
{
// The test is simply for efficiency
testMethod.Name = parms.TestName.Contains("{")
? new TestNameGenerator(parms.TestName).GetDisplayName(testMethod, parms.OriginalArguments)
: parms.TestName;
}
else
{
testMethod.Name = _nameGenerator.GetDisplayName(testMethod, parms.OriginalArguments);
}
}
else
{
testMethod.Name = _nameGenerator.GetDisplayName(testMethod, null);
}
testMethod.FullName = prefix + "." + testMethod.Name;
return testMethod;
}
#region Helper Methods
/// <summary>
/// Helper method that checks the signature of a TestMethod and
/// any supplied parameters to determine if the test is valid.
///
/// Currently, NUnitTestMethods are required to be public,
/// non-abstract methods, either static or instance,
/// returning void. They may take arguments but the _values must
/// be provided or the TestMethod is not considered runnable.
///
/// Methods not meeting these criteria will be marked as
/// non-runnable and the method will return false in that case.
/// </summary>
/// <param name="testMethod">The TestMethod to be checked. If it
/// is found to be non-runnable, it will be modified.</param>
/// <param name="parms">Parameters to be used for this test, or null</param>
/// <returns>True if the method signature is valid, false if not</returns>
/// <remarks>
/// The return value is no longer used internally, but is retained
/// for testing purposes.
/// </remarks>
private static bool CheckTestMethodSignature(TestMethod testMethod, TestCaseParameters parms)
{
if (testMethod.Method.IsAbstract)
return MarkAsNotRunnable(testMethod, "Method is abstract");
if (!testMethod.Method.IsPublic)
return MarkAsNotRunnable(testMethod, "Method is not public");
IParameterInfo[] parameters;
#if NETCF
if (testMethod.Method.IsGenericMethodDefinition)
{
if (parms != null && parms.Arguments != null)
{
var mi = testMethod.Method.MakeGenericMethodEx(parms.Arguments);
if (mi == null)
return MarkAsNotRunnable(testMethod, "Cannot determine generic types by probing");
testMethod.Method = mi;
parameters = testMethod.Method.GetParameters();
}
else
parameters = new IParameterInfo[0];
}
else
parameters = testMethod.Method.GetParameters();
int minArgsNeeded = parameters.Length;
#else
parameters = testMethod.Method.GetParameters();
int minArgsNeeded = 0;
foreach (var parameter in parameters)
{
// IsOptional is supported since .NET 1.1
if (!parameter.IsOptional)
minArgsNeeded++;
}
#endif
int maxArgsNeeded = parameters.Length;
object[] arglist = null;
int argsProvided = 0;
if (parms != null)
{
testMethod.parms = parms;
testMethod.RunState = parms.RunState;
arglist = parms.Arguments;
if (arglist != null)
argsProvided = arglist.Length;
if (testMethod.RunState != RunState.Runnable)
return false;
}
#if NETCF
ITypeInfo returnType = testMethod.Method.IsGenericMethodDefinition && (parms == null || parms.Arguments == null) ? new TypeWrapper(typeof(void)) : testMethod.Method.ReturnType;
#else
ITypeInfo returnType = testMethod.Method.ReturnType;
#endif
#if NET_4_0 || NET_4_5 || PORTABLE
if (AsyncInvocationRegion.IsAsyncOperation(testMethod.Method.MethodInfo))
{
if (returnType.IsType(typeof(void)))
return MarkAsNotRunnable(testMethod, "Async test method must have non-void return type");
var returnsGenericTask = returnType.IsGenericType &&
returnType.GetGenericTypeDefinition() == typeof(System.Threading.Tasks.Task<>);
if (returnsGenericTask && (parms == null || !parms.HasExpectedResult))
return MarkAsNotRunnable(testMethod,
"Async test method must have non-generic Task return type when no result is expected");
if (!returnsGenericTask && parms != null && parms.HasExpectedResult)
return MarkAsNotRunnable(testMethod,
"Async test method must have Task<T> return type when a result is expected");
}
else
#endif
if (returnType.IsType(typeof(void)))
{
if (parms != null && parms.HasExpectedResult)
return MarkAsNotRunnable(testMethod, "Method returning void cannot have an expected result");
}
else if (parms == null || !parms.HasExpectedResult)
return MarkAsNotRunnable(testMethod, "Method has non-void return value, but no result is expected");
if (argsProvided > 0 && maxArgsNeeded == 0)
return MarkAsNotRunnable(testMethod, "Arguments provided for method not taking any");
if (argsProvided == 0 && minArgsNeeded > 0)
return MarkAsNotRunnable(testMethod, "No arguments were provided");
if (argsProvided < minArgsNeeded)
return MarkAsNotRunnable(testMethod, string.Format("Not enough arguments provided, provide at least {0} arguments.", minArgsNeeded));
if (argsProvided > maxArgsNeeded)
return MarkAsNotRunnable(testMethod, string.Format("Too many arguments provided, provide at most {0} arguments.", maxArgsNeeded));
if (testMethod.Method.IsGenericMethodDefinition && arglist != null)
{
var typeArguments = new GenericMethodHelper(testMethod.Method.MethodInfo).GetTypeArguments(arglist);
foreach (Type o in typeArguments)
if (o == null || o == TypeHelper.NonmatchingType)
return MarkAsNotRunnable(testMethod, "Unable to determine type arguments for method");
testMethod.Method = testMethod.Method.MakeGenericMethod(typeArguments);
parameters = testMethod.Method.GetParameters();
}
if (arglist != null && parameters != null)
TypeHelper.ConvertArgumentList(arglist, parameters);
return true;
}
private static bool MarkAsNotRunnable(TestMethod testMethod, string reason)
{
testMethod.RunState = RunState.NotRunnable;
testMethod.Properties.Set(PropertyNames.SkipReason, reason);
return false;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*============================================================
**
**
**
**
**
** Purpose: For writing text to streams in a particular
** encoding.
**
**
===========================================================*/
using System;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Permissions;
using System.Runtime.Serialization;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
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]
[ComVisible(true)]
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.
internal const int DefaultBufferSize = 1024; // char[]
private const int DefaultFileStreamBufferSize = 4096;
private const int MinBufferSize = 128;
private const Int32 DontCopyOnWriteLineThreshold = 512;
// Bit bucket - Null has no backing store. Non closable.
public new static readonly StreamWriter Null = new StreamWriter(Stream.Null, new UTF8Encoding(false, true), 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;
#if MDA_SUPPORTED
[NonSerialized]
// For StreamWriterBufferedDataLost MDA
private MdaHelper mdaHelper;
#endif
// 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(Environment.GetResourceString("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 volatile Encoding _UTF8NoBOM;
internal static Encoding UTF8NoBOM {
[FriendAccessAllowed]
get {
if (_UTF8NoBOM == null) {
// No need for double lock - we just want to avoid extra
// allocations in the common case.
UTF8Encoding noBOM = new UTF8Encoding(false, true);
Thread.MemoryBarrier();
_UTF8NoBOM = noBOM;
}
return _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 ? "stream" : "encoding"));
if (!stream.CanWrite)
throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotWritable"));
if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
Contract.EndContractBlock();
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) {
}
[System.Security.SecuritySafeCritical]
public StreamWriter(String path, bool append, Encoding encoding, int bufferSize): this(path, append, encoding, bufferSize, true) {
}
[System.Security.SecurityCritical]
internal StreamWriter(String path, bool append, Encoding encoding, int bufferSize, bool checkHost)
: base(null)
{ // Ask for CurrentCulture all the time
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
Contract.EndContractBlock();
Stream stream = CreateFile(path, append, checkHost);
Init(stream, encoding, bufferSize, false);
}
[System.Security.SecuritySafeCritical]
private void Init(Stream streamArg, Encoding encodingArg, int bufferSize, bool shouldLeaveOpen)
{
this.stream = streamArg;
this.encoding = encodingArg;
this.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;
#if MDA_SUPPORTED
if (Mda.StreamWriterBufferedDataLost.Enabled) {
String callstack = null;
if (Mda.StreamWriterBufferedDataLost.CaptureAllocatedCallStack)
callstack = Environment.GetStackTrace(null, false);
mdaHelper = new MdaHelper(this, callstack);
}
#endif
}
[System.Security.SecurityCritical]
private static Stream CreateFile(String path, bool append, bool checkHost) {
FileMode mode = append? FileMode.Append: FileMode.Create;
FileStream f = new FileStream(path, mode, FileAccess.Write, FileShare.Read,
DefaultFileStreamBufferSize, FileOptions.SequentialScan, Path.GetFileName(path), false, false, checkHost);
return f;
}
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);
#if MDA_SUPPORTED
// Disable buffered data loss mda
if (mdaHelper != null)
GC.SuppressFinalize(mdaHelper);
#endif
}
}
}
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)
__Error.WriterClosed();
// Perf boost for Flush on non-dirty writers.
if (charPos==0 && ((!flushStream && !flushEncoder) || CompatibilitySwitches.IsAppEarlierThanWindowsPhone8))
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;
Contract.Assert(n > 0, "StreamWriter::Write(char[]) isn't making progress! This is most likely a race condition in user code.");
Buffer.InternalBlockCopy(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("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
CheckAsyncTaskInProgress();
while (count > 0) {
if (charPos == charLen) Flush(false, false);
int n = charLen - charPos;
if (n > count) n = count;
Contract.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code.");
Buffer.InternalBlockCopy(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)
{
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;
Contract.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);
}
}
#region Task based Async APIs
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
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 overriden.
// 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 (this.GetType() != typeof(StreamWriter))
return base.WriteAsync(value);
if (stream == null)
__Error.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, Int32 charPos, Int32 charLen, Char[] coreNewLine,
bool autoFlush, bool appendNewLine)
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
charBuffer[charPos] = value;
charPos++;
if (appendNewLine)
{
for (Int32 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);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
charBuffer[charPos] = coreNewLine[i];
charPos++;
}
}
if (autoFlush) {
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
_this.CharPos_Prop = charPos;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
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 overriden.
// 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 (this.GetType() != typeof(StreamWriter))
return base.WriteAsync(value);
if (value != null)
{
if (stream == null)
__Error.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, Int32 charPos, Int32 charLen, Char[] coreNewLine,
bool autoFlush, bool appendNewLine)
{
Contract.Requires(value != null);
int count = value.Length;
int index = 0;
while (count > 0)
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
int n = charLen - charPos;
if (n > count)
n = count;
Contract.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 (Int32 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);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
charBuffer[charPos] = coreNewLine[i];
charPos++;
}
}
if (autoFlush) {
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
_this.CharPos_Prop = charPos;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
// 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 overriden.
// 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 (this.GetType() != typeof(StreamWriter))
return base.WriteAsync(buffer, index, count);
if (stream == null)
__Error.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, Int32 index, Int32 count,
Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine,
bool autoFlush, bool appendNewLine)
{
Contract.Requires(count == 0 || (count > 0 && buffer != null));
Contract.Requires(index >= 0);
Contract.Requires(count >= 0);
Contract.Requires(buffer == null || (buffer != null && buffer.Length - index >= count));
while (count > 0)
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
int n = charLen - charPos;
if (n > count) n = count;
Contract.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code.");
Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char));
charPos += n;
index += n;
count -= n;
}
if (appendNewLine)
{
for (Int32 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);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
charBuffer[charPos] = coreNewLine[i];
charPos++;
}
}
if (autoFlush) {
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
_this.CharPos_Prop = charPos;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
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 overriden.
// 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 (this.GetType() != typeof(StreamWriter))
return base.WriteLineAsync();
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, null, 0, 0, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
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 overriden.
// 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 (this.GetType() != typeof(StreamWriter))
return base.WriteLineAsync(value);
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync(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 overriden.
// 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 (this.GetType() != typeof(StreamWriter))
return base.WriteLineAsync(value);
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
// 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 overriden.
// 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 (this.GetType() != typeof(StreamWriter))
return base.WriteLineAsync(buffer, index, count);
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, buffer, index, count, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
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 overriden. 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 (this.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)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = FlushAsyncInternal(true, true, charBuffer, charPos);
_asyncWriteTask = task;
return task;
}
private Int32 CharPos_Prop {
set { this.charPos = value; }
}
private bool HaveWrittenPreamble_Prop {
set { this.haveWrittenPreamble = value; }
}
private Task FlushAsyncInternal(bool flushStream, bool flushEncoder,
Char[] sCharBuffer, Int32 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, this.haveWrittenPreamble,
this.encoding, this.encoder, this.byteBuffer, this.stream);
this.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, Int32 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
#if MDA_SUPPORTED
// StreamWriterBufferedDataLost MDA
// Instead of adding a finalizer to StreamWriter for detecting buffered data loss
// (ie, when the user forgets to call Close/Flush on the StreamWriter), we will
// have a separate object with normal finalization semantics that maintains a
// back pointer to this StreamWriter and alerts about any data loss
private sealed class MdaHelper
{
private StreamWriter streamWriter;
private String allocatedCallstack; // captures the callstack when this streamwriter was allocated
internal MdaHelper(StreamWriter sw, String cs)
{
streamWriter = sw;
allocatedCallstack = cs;
}
// Finalizer
~MdaHelper()
{
// Make sure people closed this StreamWriter, exclude StreamWriter::Null.
if (streamWriter.charPos != 0 && streamWriter.stream != null && streamWriter.stream != Stream.Null) {
String fileName = (streamWriter.stream is FileStream) ? ((FileStream)streamWriter.stream).NameInternal : "<unknown>";
String callStack = allocatedCallstack;
if (callStack == null)
callStack = Environment.GetResourceString("IO_StreamWriterBufferedDataLostCaptureAllocatedFromCallstackNotEnabled");
String message = Environment.GetResourceString("IO_StreamWriterBufferedDataLost", streamWriter.stream.GetType().FullName, fileName, callStack);
Mda.StreamWriterBufferedDataLost.ReportError(message);
}
}
} // class MdaHelper
#endif // MDA_SUPPORTED
} // 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.Net;
using System.Collections.Generic;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Data.Null;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.PhysicsModules.SharedBase;
using OpenSim.Region.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.CoreModules.Avatar.Gods;
using OpenSim.Region.CoreModules.Asset;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Authentication;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.UserAccounts;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence;
using OpenSim.Region.PhysicsModule.BasicPhysics;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Tests.Common
{
/// <summary>
/// Helpers for setting up scenes.
/// </summary>
public class SceneHelpers
{
/// <summary>
/// We need a scene manager so that test clients can retrieve a scene when performing teleport tests.
/// </summary>
public SceneManager SceneManager { get; private set; }
public ISimulationDataService SimDataService { get; private set; }
private AgentCircuitManager m_acm = new AgentCircuitManager();
private IEstateDataService m_estateDataService = null;
private LocalAssetServicesConnector m_assetService;
private LocalAuthenticationServicesConnector m_authenticationService;
private LocalInventoryServicesConnector m_inventoryService;
private LocalGridServicesConnector m_gridService;
private LocalUserAccountServicesConnector m_userAccountService;
private LocalPresenceServicesConnector m_presenceService;
private CoreAssetCache m_cache;
private PhysicsScene m_physicsScene;
public SceneHelpers() : this(null) {}
public SceneHelpers(CoreAssetCache cache)
{
SceneManager = new SceneManager();
m_assetService = StartAssetService(cache);
m_authenticationService = StartAuthenticationService();
m_inventoryService = StartInventoryService();
m_gridService = StartGridService();
m_userAccountService = StartUserAccountService();
m_presenceService = StartPresenceService();
m_inventoryService.PostInitialise();
m_assetService.PostInitialise();
m_userAccountService.PostInitialise();
m_presenceService.PostInitialise();
m_cache = cache;
m_physicsScene = StartPhysicsScene();
SimDataService
= OpenSim.Server.Base.ServerUtils.LoadPlugin<ISimulationDataService>("OpenSim.Tests.Common.dll", null);
}
/// <summary>
/// Set up a test scene
/// </summary>
/// <remarks>
/// Automatically starts services, as would the normal runtime.
/// </remarks>
/// <returns></returns>
public TestScene SetupScene()
{
return SetupScene("Unit test region", UUID.Random(), 1000, 1000);
}
public TestScene SetupScene(string name, UUID id, uint x, uint y)
{
return SetupScene(name, id, x, y, new IniConfigSource());
}
public TestScene SetupScene(string name, UUID id, uint x, uint y, IConfigSource configSource)
{
return SetupScene(name, id, x, y, Constants.RegionSize, Constants.RegionSize, configSource);
}
/// <summary>
/// Set up a scene.
/// </summary>
/// <param name="name">Name of the region</param>
/// <param name="id">ID of the region</param>
/// <param name="x">X co-ordinate of the region</param>
/// <param name="y">Y co-ordinate of the region</param>
/// <param name="sizeX">X size of scene</param>
/// <param name="sizeY">Y size of scene</param>
/// <param name="configSource"></param>
/// <returns></returns>
public TestScene SetupScene(
string name, UUID id, uint x, uint y, uint sizeX, uint sizeY, IConfigSource configSource)
{
Console.WriteLine("Setting up test scene {0}", name);
// We must set up a console otherwise setup of some modules may fail
MainConsole.Instance = new MockConsole();
RegionInfo regInfo = new RegionInfo(x, y, new IPEndPoint(IPAddress.Loopback, 9000), "127.0.0.1");
regInfo.RegionName = name;
regInfo.RegionID = id;
regInfo.RegionSizeX = sizeX;
regInfo.RegionSizeY = sizeY;
TestScene testScene = new TestScene(
regInfo, m_acm, SimDataService, m_estateDataService, configSource, null);
testScene.RegionInfo.EstateSettings = new EstateSettings();
testScene.RegionInfo.EstateSettings.EstateOwner = UUID.Random();
INonSharedRegionModule godsModule = new GodsModule();
godsModule.Initialise(new IniConfigSource());
godsModule.AddRegion(testScene);
// Add scene to physics
((INonSharedRegionModule)m_physicsScene).AddRegion(testScene);
((INonSharedRegionModule)m_physicsScene).RegionLoaded(testScene);
// Add scene to services
m_assetService.AddRegion(testScene);
if (m_cache != null)
{
m_cache.AddRegion(testScene);
m_cache.RegionLoaded(testScene);
testScene.AddRegionModule(m_cache.Name, m_cache);
}
m_assetService.RegionLoaded(testScene);
testScene.AddRegionModule(m_assetService.Name, m_assetService);
m_authenticationService.AddRegion(testScene);
m_authenticationService.RegionLoaded(testScene);
testScene.AddRegionModule(m_authenticationService.Name, m_authenticationService);
m_inventoryService.AddRegion(testScene);
m_inventoryService.RegionLoaded(testScene);
testScene.AddRegionModule(m_inventoryService.Name, m_inventoryService);
m_gridService.AddRegion(testScene);
m_gridService.RegionLoaded(testScene);
testScene.AddRegionModule(m_gridService.Name, m_gridService);
m_userAccountService.AddRegion(testScene);
m_userAccountService.RegionLoaded(testScene);
testScene.AddRegionModule(m_userAccountService.Name, m_userAccountService);
m_presenceService.AddRegion(testScene);
m_presenceService.RegionLoaded(testScene);
testScene.AddRegionModule(m_presenceService.Name, m_presenceService);
testScene.SetModuleInterfaces();
testScene.LandChannel = new TestLandChannel(testScene);
testScene.LoadWorldMap();
testScene.LoginsEnabled = true;
testScene.RegisterRegionWithGrid();
SceneManager.Add(testScene);
return testScene;
}
private static LocalAssetServicesConnector StartAssetService(CoreAssetCache cache)
{
IConfigSource config = new IniConfigSource();
config.AddConfig("Modules");
config.Configs["Modules"].Set("AssetServices", "LocalAssetServicesConnector");
config.AddConfig("AssetService");
config.Configs["AssetService"].Set("LocalServiceModule", "OpenSim.Services.AssetService.dll:AssetService");
config.Configs["AssetService"].Set("StorageProvider", "OpenSim.Tests.Common.dll");
LocalAssetServicesConnector assetService = new LocalAssetServicesConnector();
assetService.Initialise(config);
if (cache != null)
{
IConfigSource cacheConfig = new IniConfigSource();
cacheConfig.AddConfig("Modules");
cacheConfig.Configs["Modules"].Set("AssetCaching", "CoreAssetCache");
cacheConfig.AddConfig("AssetCache");
cache.Initialise(cacheConfig);
}
return assetService;
}
private static LocalAuthenticationServicesConnector StartAuthenticationService()
{
IConfigSource config = new IniConfigSource();
config.AddConfig("Modules");
config.AddConfig("AuthenticationService");
config.Configs["Modules"].Set("AuthenticationServices", "LocalAuthenticationServicesConnector");
config.Configs["AuthenticationService"].Set(
"LocalServiceModule", "OpenSim.Services.AuthenticationService.dll:PasswordAuthenticationService");
config.Configs["AuthenticationService"].Set("StorageProvider", "OpenSim.Data.Null.dll");
LocalAuthenticationServicesConnector service = new LocalAuthenticationServicesConnector();
service.Initialise(config);
return service;
}
private static LocalInventoryServicesConnector StartInventoryService()
{
IConfigSource config = new IniConfigSource();
config.AddConfig("Modules");
config.AddConfig("InventoryService");
config.Configs["Modules"].Set("InventoryServices", "LocalInventoryServicesConnector");
config.Configs["InventoryService"].Set("LocalServiceModule", "OpenSim.Services.InventoryService.dll:XInventoryService");
config.Configs["InventoryService"].Set("StorageProvider", "OpenSim.Tests.Common.dll");
LocalInventoryServicesConnector inventoryService = new LocalInventoryServicesConnector();
inventoryService.Initialise(config);
return inventoryService;
}
private static LocalGridServicesConnector StartGridService()
{
IConfigSource config = new IniConfigSource();
config.AddConfig("Modules");
config.AddConfig("GridService");
config.Configs["Modules"].Set("GridServices", "LocalGridServicesConnector");
config.Configs["GridService"].Set("StorageProvider", "OpenSim.Data.Null.dll:NullRegionData");
config.Configs["GridService"].Set("LocalServiceModule", "OpenSim.Services.GridService.dll:GridService");
config.Configs["GridService"].Set("ConnectionString", "!static");
LocalGridServicesConnector gridService = new LocalGridServicesConnector();
gridService.Initialise(config);
return gridService;
}
/// <summary>
/// Start a user account service
/// </summary>
/// <param name="testScene"></param>
/// <returns></returns>
private static LocalUserAccountServicesConnector StartUserAccountService()
{
IConfigSource config = new IniConfigSource();
config.AddConfig("Modules");
config.AddConfig("UserAccountService");
config.Configs["Modules"].Set("UserAccountServices", "LocalUserAccountServicesConnector");
config.Configs["UserAccountService"].Set("StorageProvider", "OpenSim.Data.Null.dll");
config.Configs["UserAccountService"].Set(
"LocalServiceModule", "OpenSim.Services.UserAccountService.dll:UserAccountService");
LocalUserAccountServicesConnector userAccountService = new LocalUserAccountServicesConnector();
userAccountService.Initialise(config);
return userAccountService;
}
/// <summary>
/// Start a presence service
/// </summary>
/// <param name="testScene"></param>
private static LocalPresenceServicesConnector StartPresenceService()
{
// Unfortunately, some services share data via statics, so we need to null every time to stop interference
// between tests.
// This is a massive non-obvious pita.
NullPresenceData.Instance = null;
IConfigSource config = new IniConfigSource();
config.AddConfig("Modules");
config.AddConfig("PresenceService");
config.Configs["Modules"].Set("PresenceServices", "LocalPresenceServicesConnector");
config.Configs["PresenceService"].Set("StorageProvider", "OpenSim.Data.Null.dll");
config.Configs["PresenceService"].Set(
"LocalServiceModule", "OpenSim.Services.PresenceService.dll:PresenceService");
LocalPresenceServicesConnector presenceService = new LocalPresenceServicesConnector();
presenceService.Initialise(config);
return presenceService;
}
private static PhysicsScene StartPhysicsScene()
{
IConfigSource config = new IniConfigSource();
config.AddConfig("Startup");
config.Configs["Startup"].Set("physics", "basicphysics");
PhysicsScene pScene = new BasicScene();
INonSharedRegionModule mod = pScene as INonSharedRegionModule;
mod.Initialise(config);
return pScene;
}
/// <summary>
/// Setup modules for a scene using their default settings.
/// </summary>
/// <param name="scene"></param>
/// <param name="modules"></param>
public static void SetupSceneModules(Scene scene, params object[] modules)
{
SetupSceneModules(scene, new IniConfigSource(), modules);
}
/// <summary>
/// Setup modules for a scene.
/// </summary>
/// <remarks>
/// If called directly, then all the modules must be shared modules.
/// </remarks>
/// <param name="scenes"></param>
/// <param name="config"></param>
/// <param name="modules"></param>
public static void SetupSceneModules(Scene scene, IConfigSource config, params object[] modules)
{
SetupSceneModules(new Scene[] { scene }, config, modules);
}
/// <summary>
/// Setup modules for a scene using their default settings.
/// </summary>
/// <param name="scenes"></param>
/// <param name="modules"></param>
public static void SetupSceneModules(Scene[] scenes, params object[] modules)
{
SetupSceneModules(scenes, new IniConfigSource(), modules);
}
/// <summary>
/// Setup modules for scenes.
/// </summary>
/// <remarks>
/// If called directly, then all the modules must be shared modules.
///
/// We are emulating here the normal calls made to setup region modules
/// (Initialise(), PostInitialise(), AddRegion, RegionLoaded()).
/// TODO: Need to reuse normal runtime module code.
/// </remarks>
/// <param name="scenes"></param>
/// <param name="config"></param>
/// <param name="modules"></param>
public static void SetupSceneModules(Scene[] scenes, IConfigSource config, params object[] modules)
{
List<IRegionModuleBase> newModules = new List<IRegionModuleBase>();
foreach (object module in modules)
{
IRegionModuleBase m = (IRegionModuleBase)module;
// Console.WriteLine("MODULE {0}", m.Name);
m.Initialise(config);
newModules.Add(m);
}
foreach (IRegionModuleBase module in newModules)
{
if (module is ISharedRegionModule) ((ISharedRegionModule)module).PostInitialise();
}
foreach (IRegionModuleBase module in newModules)
{
foreach (Scene scene in scenes)
{
module.AddRegion(scene);
scene.AddRegionModule(module.Name, module);
}
}
// RegionLoaded is fired after all modules have been appropriately added to all scenes
foreach (IRegionModuleBase module in newModules)
foreach (Scene scene in scenes)
module.RegionLoaded(scene);
foreach (Scene scene in scenes) { scene.SetModuleInterfaces(); }
}
/// <summary>
/// Generate some standard agent connection data.
/// </summary>
/// <param name="agentId"></param>
/// <returns></returns>
public static AgentCircuitData GenerateAgentData(UUID agentId)
{
AgentCircuitData acd = GenerateCommonAgentData();
acd.AgentID = agentId;
acd.firstname = "testfirstname";
acd.lastname = "testlastname";
acd.ServiceURLs = new Dictionary<string, object>();
return acd;
}
/// <summary>
/// Generate some standard agent connection data.
/// </summary>
/// <param name="agentId"></param>
/// <returns></returns>
public static AgentCircuitData GenerateAgentData(UserAccount ua)
{
AgentCircuitData acd = GenerateCommonAgentData();
acd.AgentID = ua.PrincipalID;
acd.firstname = ua.FirstName;
acd.lastname = ua.LastName;
acd.ServiceURLs = ua.ServiceURLs;
return acd;
}
private static AgentCircuitData GenerateCommonAgentData()
{
AgentCircuitData acd = new AgentCircuitData();
// XXX: Sessions must be unique, otherwise one presence can overwrite another in NullPresenceData.
acd.SessionID = UUID.Random();
acd.SecureSessionID = UUID.Random();
acd.circuitcode = 123;
acd.BaseFolder = UUID.Zero;
acd.InventoryFolder = UUID.Zero;
acd.startpos = Vector3.Zero;
acd.CapsPath = "http://wibble.com";
acd.Appearance = new AvatarAppearance();
return acd;
}
/// <summary>
/// Add a root agent where the details of the agent connection (apart from the id) are unimportant for the test
/// </summary>
/// <remarks>
/// XXX: Use the version of this method that takes the UserAccount structure wherever possible - this will
/// make the agent circuit data (e.g. first, lastname) consistent with the user account data.
/// </remarks>
/// <param name="scene"></param>
/// <param name="agentId"></param>
/// <returns></returns>
public static ScenePresence AddScenePresence(Scene scene, UUID agentId)
{
return AddScenePresence(scene, GenerateAgentData(agentId));
}
/// <summary>
/// Add a root agent.
/// </summary>
/// <param name="scene"></param>
/// <param name="ua"></param>
/// <returns></returns>
public static ScenePresence AddScenePresence(Scene scene, UserAccount ua)
{
return AddScenePresence(scene, GenerateAgentData(ua));
}
/// <summary>
/// Add a root agent.
/// </summary>
/// <remarks>
/// This function
///
/// 1) Tells the scene that an agent is coming. Normally, the login service (local if standalone, from the
/// userserver if grid) would give initial login data back to the client and separately tell the scene that the
/// agent was coming.
///
/// 2) Connects the agent with the scene
///
/// This function performs actions equivalent with notifying the scene that an agent is
/// coming and then actually connecting the agent to the scene. The one step missed out is the very first
/// </remarks>
/// <param name="scene"></param>
/// <param name="agentData"></param>
/// <returns></returns>
public static ScenePresence AddScenePresence(Scene scene, AgentCircuitData agentData)
{
return AddScenePresence(scene, new TestClient(agentData, scene), agentData);
}
/// <summary>
/// Add a root agent.
/// </summary>
/// <remarks>
/// This function
///
/// 1) Tells the scene that an agent is coming. Normally, the login service (local if standalone, from the
/// userserver if grid) would give initial login data back to the client and separately tell the scene that the
/// agent was coming.
///
/// 2) Connects the agent with the scene
///
/// This function performs actions equivalent with notifying the scene that an agent is
/// coming and then actually connecting the agent to the scene. The one step missed out is the very first
/// </remarks>
/// <param name="scene"></param>
/// <param name="agentData"></param>
/// <returns></returns>
public static ScenePresence AddScenePresence(
Scene scene, IClientAPI client, AgentCircuitData agentData)
{
// We emulate the proper login sequence here by doing things in four stages
// Stage 0: login
// We need to punch through to the underlying service because scene will not, correctly, let us call it
// through it's reference to the LPSC
LocalPresenceServicesConnector lpsc = (LocalPresenceServicesConnector)scene.PresenceService;
lpsc.m_PresenceService.LoginAgent(agentData.AgentID.ToString(), agentData.SessionID, agentData.SecureSessionID);
// Stages 1 & 2
ScenePresence sp = IntroduceClientToScene(scene, client, agentData, TeleportFlags.ViaLogin);
// Stage 3: Complete the entrance into the region. This converts the child agent into a root agent.
sp.CompleteMovement(sp.ControllingClient, true);
return sp;
}
/// <summary>
/// Introduce an agent into the scene by adding a new client.
/// </summary>
/// <returns>The scene presence added</returns>
/// <param name='scene'></param>
/// <param name='testClient'></param>
/// <param name='agentData'></param>
/// <param name='tf'></param>
private static ScenePresence IntroduceClientToScene(
Scene scene, IClientAPI client, AgentCircuitData agentData, TeleportFlags tf)
{
string reason;
// Stage 1: tell the scene to expect a new user connection
if (!scene.NewUserConnection(agentData, (uint)tf, null, out reason))
Console.WriteLine("NewUserConnection failed: " + reason);
// Stage 2: add the new client as a child agent to the scene
scene.AddNewAgent(client, PresenceType.User);
return scene.GetScenePresence(client.AgentId);
}
public static ScenePresence AddChildScenePresence(Scene scene, UUID agentId)
{
return AddChildScenePresence(scene, GenerateAgentData(agentId));
}
public static ScenePresence AddChildScenePresence(Scene scene, AgentCircuitData acd)
{
acd.child = true;
// XXX: ViaLogin may not be correct for child agents
TestClient client = new TestClient(acd, scene);
return IntroduceClientToScene(scene, client, acd, TeleportFlags.ViaLogin);
}
/// <summary>
/// Add a test object
/// </summary>
/// <param name="scene"></param>
/// <returns></returns>
public static SceneObjectGroup AddSceneObject(Scene scene)
{
return AddSceneObject(scene, "Test Object", UUID.Random());
}
/// <summary>
/// Add a test object
/// </summary>
/// <param name="scene"></param>
/// <param name="name"></param>
/// <param name="ownerId"></param>
/// <returns></returns>
public static SceneObjectGroup AddSceneObject(Scene scene, string name, UUID ownerId)
{
SceneObjectGroup so = new SceneObjectGroup(CreateSceneObjectPart(name, UUID.Random(), ownerId));
//part.UpdatePrimFlags(false, false, true);
//part.ObjectFlags |= (uint)PrimFlags.Phantom;
scene.AddNewSceneObject(so, true);
return so;
}
/// <summary>
/// Add a test object
/// </summary>
/// <param name="scene"></param>
/// <param name="parts">
/// The number of parts that should be in the scene object
/// </param>
/// <param name="ownerId"></param>
/// <param name="partNamePrefix">
/// The prefix to be given to part names. This will be suffixed with "Part<part no>"
/// (e.g. mynamePart1 for the root part)
/// </param>
/// <param name="uuidTail">
/// The hexadecimal last part of the UUID for parts created. A UUID of the form "00000000-0000-0000-0000-{0:XD12}"
/// will be given to the root part, and incremented for each part thereafter.
/// </param>
/// <returns></returns>
public static SceneObjectGroup AddSceneObject(Scene scene, int parts, UUID ownerId, string partNamePrefix, int uuidTail)
{
SceneObjectGroup so = CreateSceneObject(parts, ownerId, partNamePrefix, uuidTail);
scene.AddNewSceneObject(so, false);
return so;
}
/// <summary>
/// Create a scene object part.
/// </summary>
/// <param name="name"></param>
/// <param name="id"></param>
/// <param name="ownerId"></param>
/// <returns></returns>
public static SceneObjectPart CreateSceneObjectPart(string name, UUID id, UUID ownerId)
{
return new SceneObjectPart(
ownerId, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero)
{ Name = name, UUID = id, Scale = new Vector3(1, 1, 1) };
}
/// <summary>
/// Create a scene object but do not add it to the scene.
/// </summary>
/// <remarks>
/// UUID always starts at 00000000-0000-0000-0000-000000000001. For some purposes, (e.g. serializing direct
/// to another object's inventory) we do not need a scene unique ID. So it would be better to add the
/// UUID when we actually add an object to a scene rather than on creation.
/// </remarks>
/// <param name="parts">The number of parts that should be in the scene object</param>
/// <param name="ownerId"></param>
/// <returns></returns>
public static SceneObjectGroup CreateSceneObject(int parts, UUID ownerId)
{
return CreateSceneObject(parts, ownerId, 0x1);
}
/// <summary>
/// Create a scene object but do not add it to the scene.
/// </summary>
/// <param name="parts">The number of parts that should be in the scene object</param>
/// <param name="ownerId"></param>
/// <param name="uuidTail">
/// The hexadecimal last part of the UUID for parts created. A UUID of the form "00000000-0000-0000-0000-{0:XD12}"
/// will be given to the root part, and incremented for each part thereafter.
/// </param>
/// <returns></returns>
public static SceneObjectGroup CreateSceneObject(int parts, UUID ownerId, int uuidTail)
{
return CreateSceneObject(parts, ownerId, "", uuidTail);
}
/// <summary>
/// Create a scene object but do not add it to the scene.
/// </summary>
/// <param name="parts">
/// The number of parts that should be in the scene object
/// </param>
/// <param name="ownerId"></param>
/// <param name="partNamePrefix">
/// The prefix to be given to part names. This will be suffixed with "Part<part no>"
/// (e.g. mynamePart1 for the root part)
/// </param>
/// <param name="uuidTail">
/// The hexadecimal last part of the UUID for parts created. A UUID of the form "00000000-0000-0000-0000-{0:XD12}"
/// will be given to the root part, and incremented for each part thereafter.
/// </param>
/// <returns></returns>
public static SceneObjectGroup CreateSceneObject(int parts, UUID ownerId, string partNamePrefix, int uuidTail)
{
string rawSogId = string.Format("00000000-0000-0000-0000-{0:X12}", uuidTail);
SceneObjectGroup sog
= new SceneObjectGroup(
CreateSceneObjectPart(string.Format("{0}Part1", partNamePrefix), new UUID(rawSogId), ownerId));
if (parts > 1)
for (int i = 2; i <= parts; i++)
sog.AddPart(
CreateSceneObjectPart(
string.Format("{0}Part{1}", partNamePrefix, i),
new UUID(string.Format("00000000-0000-0000-0000-{0:X12}", uuidTail + i - 1)),
ownerId));
return sog;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using NetGore;
using NetGore.IO;
namespace DemoGame
{
/// <summary>
/// Represents a unique ID for a persistent Character instance.
/// </summary>
[Serializable]
[TypeConverter(typeof(CharacterIDTypeConverter))]
public struct CharacterID : IComparable<CharacterID>, IConvertible, IFormattable, IComparable<int>, IEquatable<int>
{
/// <summary>
/// Represents the largest possible value of CharacterID. This field is constant.
/// </summary>
public const int MaxValue = int.MaxValue;
/// <summary>
/// Represents the smallest possible value of CharacterID. This field is constant.
/// </summary>
public const int MinValue = int.MinValue;
/// <summary>
/// The underlying value. This contains the actual value of the struct instance.
/// </summary>
readonly int _value;
/// <summary>
/// Initializes a new instance of the <see cref="CharacterID"/> struct.
/// </summary>
/// <param name="value">Value to assign to the new CharacterID.</param>
/// <exception cref="ArgumentOutOfRangeException"><c>value</c> is out of range.</exception>
public CharacterID(int value)
{
if (value < MinValue || value > MaxValue)
throw new ArgumentOutOfRangeException("value");
_value = value;
}
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="other">Another object to compare to.</param>
/// <returns>
/// True if <paramref name="other"/> and this instance are the same type and represent the same value; otherwise, false.
/// </returns>
public bool Equals(CharacterID other)
{
return other._value == _value;
}
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="obj">Another object to compare to.</param>
/// <returns>
/// True if <paramref name="obj"/> and this instance are the same type and represent the same value; otherwise, false.
/// </returns>
public override bool Equals(object obj)
{
return obj is CharacterID && this == (CharacterID)obj;
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>
/// A 32-bit signed integer that is the hash code for this instance.
/// </returns>
public override int GetHashCode()
{
return _value.GetHashCode();
}
/// <summary>
/// Gets the raw internal value of this CharacterID.
/// </summary>
/// <returns>The raw internal value.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
public int GetRawValue()
{
return _value;
}
/// <summary>
/// Reads an CharacterID from an IValueReader.
/// </summary>
/// <param name="reader">IValueReader to read from.</param>
/// <param name="name">Unique name of the value to read.</param>
/// <returns>The CharacterID read from the IValueReader.</returns>
public static CharacterID Read(IValueReader reader, string name)
{
var value = reader.ReadInt(name);
return new CharacterID(value);
}
/// <summary>
/// Reads an CharacterID from an <see cref="IDataRecord"/>.
/// </summary>
/// <param name="reader"><see cref="IDataRecord"/> to get the value from.</param>
/// <param name="i">The index of the field to find.</param>
/// <returns>The CharacterID read from the <see cref="IDataRecord"/>.</returns>
public static CharacterID Read(IDataRecord reader, int i)
{
var value = reader.GetValue(i);
if (value is int)
return new CharacterID((int)value);
var convertedValue = Convert.ToInt32(value);
return new CharacterID(convertedValue);
}
/// <summary>
/// Reads an CharacterID from an <see cref="IDataRecord"/>.
/// </summary>
/// <param name="reader"><see cref="IDataRecord"/> to get the value from.</param>
/// <param name="name">The name of the field to find.</param>
/// <returns>The CharacterID read from the <see cref="IDataRecord"/>.</returns>
public static CharacterID Read(IDataRecord reader, string name)
{
return Read(reader, reader.GetOrdinal(name));
}
/// <summary>
/// Reads an CharacterID from a BitStream.
/// </summary>
/// <param name="bitStream">BitStream to read from.</param>
/// <returns>The CharacterID read from the BitStream.</returns>
public static CharacterID Read(BitStream bitStream)
{
var value = bitStream.ReadInt();
return new CharacterID(value);
}
/// <summary>
/// Converts the numeric value of this instance to its equivalent string representation.
/// </summary>
/// <returns>The string representation of the value of this instance, consisting of a sequence
/// of digits ranging from 0 to 9, without leading zeroes.</returns>
public override string ToString()
{
return _value.ToString();
}
/// <summary>
/// Writes the CharacterID to an IValueWriter.
/// </summary>
/// <param name="writer">IValueWriter to write to.</param>
/// <param name="name">Unique name of the CharacterID that will be used to distinguish it
/// from other values when reading.</param>
public void Write(IValueWriter writer, string name)
{
writer.Write(name, _value);
}
/// <summary>
/// Writes the CharacterID to an IValueWriter.
/// </summary>
/// <param name="bitStream">BitStream to write to.</param>
public void Write(BitStream bitStream)
{
bitStream.Write(_value);
}
#region IComparable<CharacterID> Members
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared.
/// The return value has the following meanings:
/// Value
/// Meaning
/// Less than zero
/// This object is less than the <paramref name="other"/> parameter.
/// Zero
/// This object is equal to <paramref name="other"/>.
/// Greater than zero
/// This object is greater than <paramref name="other"/>.
/// </returns>
public int CompareTo(CharacterID other)
{
return _value.CompareTo(other._value);
}
#endregion
#region IComparable<int> Members
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings:
/// Value
/// Meaning
/// Less than zero
/// This object is less than the <paramref name="other"/> parameter.
/// Zero
/// This object is equal to <paramref name="other"/>.
/// Greater than zero
/// This object is greater than <paramref name="other"/>.
/// </returns>
public int CompareTo(int other)
{
return _value.CompareTo(other);
}
#endregion
#region IConvertible Members
/// <summary>
/// Returns the <see cref="T:System.TypeCode"/> for this instance.
/// </summary>
/// <returns>
/// The enumerated constant that is the <see cref="T:System.TypeCode"/> of the class or value type that implements this interface.
/// </returns>
public TypeCode GetTypeCode()
{
return _value.GetTypeCode();
}
/// <summary>
/// Converts the value of this instance to an equivalent Boolean value using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation
/// that supplies culture-specific formatting information.</param>
/// <returns>
/// A Boolean value equivalent to the value of this instance.
/// </returns>
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return ((IConvertible)_value).ToBoolean(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 8-bit unsigned integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 8-bit unsigned integer equivalent to the value of this instance.
/// </returns>
byte IConvertible.ToByte(IFormatProvider provider)
{
return ((IConvertible)_value).ToByte(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent Unicode character using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// A Unicode character equivalent to the value of this instance.
/// </returns>
char IConvertible.ToChar(IFormatProvider provider)
{
return ((IConvertible)_value).ToChar(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent <see cref="T:System.DateTime"/> using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// A <see cref="T:System.DateTime"/> instance equivalent to the value of this instance.
/// </returns>
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
return ((IConvertible)_value).ToDateTime(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent <see cref="T:System.Decimal"/> number using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information. </param>
/// <returns>
/// A <see cref="T:System.Decimal"/> number equivalent to the value of this instance.
/// </returns>
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return ((IConvertible)_value).ToDecimal(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent double-precision floating-point number using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// A double-precision floating-point number equivalent to the value of this instance.
/// </returns>
double IConvertible.ToDouble(IFormatProvider provider)
{
return ((IConvertible)_value).ToDouble(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 16-bit signed integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 16-bit signed integer equivalent to the value of this instance.
/// </returns>
short IConvertible.ToInt16(IFormatProvider provider)
{
return ((IConvertible)_value).ToInt16(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 32-bit signed integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 32-bit signed integer equivalent to the value of this instance.
/// </returns>
int IConvertible.ToInt32(IFormatProvider provider)
{
return ((IConvertible)_value).ToInt32(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 64-bit signed integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 64-bit signed integer equivalent to the value of this instance.
/// </returns>
long IConvertible.ToInt64(IFormatProvider provider)
{
return ((IConvertible)_value).ToInt64(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 8-bit signed integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 8-bit signed integer equivalent to the value of this instance.
/// </returns>
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return ((IConvertible)_value).ToSByte(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent single-precision floating-point number using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information. </param>
/// <returns>
/// A single-precision floating-point number equivalent to the value of this instance.
/// </returns>
float IConvertible.ToSingle(IFormatProvider provider)
{
return ((IConvertible)_value).ToSingle(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent <see cref="T:System.String"/> using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// A <see cref="T:System.String"/> instance equivalent to the value of this instance.
/// </returns>
public string ToString(IFormatProvider provider)
{
return ((IConvertible)_value).ToString(provider);
}
/// <summary>
/// Converts the value of this instance to an <see cref="T:System.Object"/> of the specified <see cref="T:System.Type"/> that has an equivalent value, using the specified culture-specific formatting information.
/// </summary>
/// <param name="conversionType">The <see cref="T:System.Type"/> to which the value of this instance is converted.</param>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An <see cref="T:System.Object"/> instance of type <paramref name="conversionType"/> whose value is equivalent to the value of this instance.
/// </returns>
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
return ((IConvertible)_value).ToType(conversionType, provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 16-bit unsigned integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 16-bit unsigned integer equivalent to the value of this instance.
/// </returns>
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return ((IConvertible)_value).ToUInt16(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 32-bit unsigned integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 32-bit unsigned integer equivalent to the value of this instance.
/// </returns>
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return ((IConvertible)_value).ToUInt32(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 64-bit unsigned integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 64-bit unsigned integer equivalent to the value of this instance.
/// </returns>
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return ((IConvertible)_value).ToUInt64(provider);
}
#endregion
#region IEquatable<int> Members
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
public bool Equals(int other)
{
return _value.Equals(other);
}
#endregion
#region IFormattable Members
/// <summary>
/// Formats the value of the current instance using the specified format.
/// </summary>
/// <param name="format">The <see cref="T:System.String"/> specifying the format to use.
/// -or-
/// null to use the default format defined for the type of the <see cref="T:System.IFormattable"/> implementation.
/// </param>
/// <param name="formatProvider">The <see cref="T:System.IFormatProvider"/> to use to format the value.
/// -or-
/// null to obtain the numeric format information from the current locale setting of the operating system.
/// </param>
/// <returns>
/// A <see cref="T:System.String"/> containing the value of the current instance in the specified format.
/// </returns>
public string ToString(string format, IFormatProvider formatProvider)
{
return _value.ToString(format, formatProvider);
}
#endregion
/// <summary>
/// Implements operator ++.
/// </summary>
/// <param name="l">The CharacterID to increment.</param>
/// <returns>The incremented CharacterID.</returns>
public static CharacterID operator ++(CharacterID l)
{
return new CharacterID(l._value + 1);
}
/// <summary>
/// Implements operator --.
/// </summary>
/// <param name="l">The CharacterID to decrement.</param>
/// <returns>The decremented CharacterID.</returns>
public static CharacterID operator --(CharacterID l)
{
return new CharacterID(l._value - 1);
}
/// <summary>
/// Implements operator +.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>Result of the left side plus the right side.</returns>
public static CharacterID operator +(CharacterID left, CharacterID right)
{
return new CharacterID(left._value + right._value);
}
/// <summary>
/// Implements operator -.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>Result of the left side minus the right side.</returns>
public static CharacterID operator -(CharacterID left, CharacterID right)
{
return new CharacterID(left._value - right._value);
}
/// <summary>
/// Implements operator ==.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are equal.</returns>
public static bool operator ==(CharacterID left, int right)
{
return left._value == right;
}
/// <summary>
/// Implements operator !=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are not equal.</returns>
public static bool operator !=(CharacterID left, int right)
{
return left._value != right;
}
/// <summary>
/// Implements operator ==.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are equal.</returns>
public static bool operator ==(int left, CharacterID right)
{
return left == right._value;
}
/// <summary>
/// Implements operator !=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are not equal.</returns>
public static bool operator !=(int left, CharacterID right)
{
return left != right._value;
}
/// <summary>
/// Casts a CharacterID to an Int32.
/// </summary>
/// <param name="CharacterID">CharacterID to cast.</param>
/// <returns>The Int32.</returns>
public static explicit operator int(CharacterID CharacterID)
{
return CharacterID._value;
}
/// <summary>
/// Casts an Int32 to a CharacterID.
/// </summary>
/// <param name="value">Int32 to cast.</param>
/// <returns>The CharacterID.</returns>
public static explicit operator CharacterID(int value)
{
return new CharacterID(value);
}
/// <summary>
/// Implements the operator >.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than the right.</returns>
public static bool operator >(int left, CharacterID right)
{
return left > right._value;
}
/// <summary>
/// Implements the operator <.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than the left.</returns>
public static bool operator <(int left, CharacterID right)
{
return left < right._value;
}
/// <summary>
/// Implements the operator >.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than the right.</returns>
public static bool operator >(CharacterID left, CharacterID right)
{
return left._value > right._value;
}
/// <summary>
/// Implements the operator <.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than the left.</returns>
public static bool operator <(CharacterID left, CharacterID right)
{
return left._value < right._value;
}
/// <summary>
/// Implements the operator >.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than the right.</returns>
public static bool operator >(CharacterID left, int right)
{
return left._value > right;
}
/// <summary>
/// Implements the operator <.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than the left.</returns>
public static bool operator <(CharacterID left, int right)
{
return left._value < right;
}
/// <summary>
/// Implements the operator >=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than or equal to the right.</returns>
public static bool operator >=(int left, CharacterID right)
{
return left >= right._value;
}
/// <summary>
/// Implements the operator <=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than or equal to the left.</returns>
public static bool operator <=(int left, CharacterID right)
{
return left <= right._value;
}
/// <summary>
/// Implements the operator >=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than or equal to the right.</returns>
public static bool operator >=(CharacterID left, int right)
{
return left._value >= right;
}
/// <summary>
/// Implements the operator <=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than or equal to the left.</returns>
public static bool operator <=(CharacterID left, int right)
{
return left._value <= right;
}
/// <summary>
/// Implements the operator >=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than or equal to the right.</returns>
public static bool operator >=(CharacterID left, CharacterID right)
{
return left._value >= right._value;
}
/// <summary>
/// Implements the operator <=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than or equal to the left.</returns>
public static bool operator <=(CharacterID left, CharacterID right)
{
return left._value <= right._value;
}
/// <summary>
/// Implements operator !=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are not equal.</returns>
public static bool operator !=(CharacterID left, CharacterID right)
{
return left._value != right._value;
}
/// <summary>
/// Implements operator ==.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are equal.</returns>
public static bool operator ==(CharacterID left, CharacterID right)
{
return left._value == right._value;
}
}
/// <summary>
/// Adds extensions to some data I/O objects for performing Read and Write operations for the CharacterID.
/// All of the operations are implemented in the CharacterID struct. These extensions are provided
/// purely for the convenience of accessing all the I/O operations from the same place.
/// </summary>
public static class CharacterIDReadWriteExtensions
{
/// <summary>
/// Gets the value in the <paramref name="dict"/> entry at the given <paramref name="key"/> as type CharacterID.
/// </summary>
/// <typeparam name="T">The key Type.</typeparam>
/// <param name="dict">The IDictionary.</param>
/// <param name="key">The key for the value to get.</param>
/// <returns>The value at the given <paramref name="key"/> parsed as a CharacterID.</returns>
public static CharacterID AsCharacterID<T>(this IDictionary<T, string> dict, T key)
{
return Parser.Invariant.ParseCharacterID(dict[key]);
}
/// <summary>
/// Tries to get the value in the <paramref name="dict"/> entry at the given <paramref name="key"/> as type CharacterID.
/// </summary>
/// <typeparam name="T">The key Type.</typeparam>
/// <param name="dict">The IDictionary.</param>
/// <param name="key">The key for the value to get.</param>
/// <param name="defaultValue">The value to use if the value at the <paramref name="key"/> could not be parsed.</param>
/// <returns>The value at the given <paramref name="key"/> parsed as an int, or the
/// <paramref name="defaultValue"/> if the <paramref name="key"/> did not exist in the <paramref name="dict"/>
/// or the value at the given <paramref name="key"/> could not be parsed.</returns>
public static CharacterID AsCharacterID<T>(this IDictionary<T, string> dict, T key, CharacterID defaultValue)
{
string value;
if (!dict.TryGetValue(key, out value))
return defaultValue;
CharacterID parsed;
if (!Parser.Invariant.TryParse(value, out parsed))
return defaultValue;
return parsed;
}
/// <summary>
/// Reads the CharacterID from an <see cref="IDataRecord"/>.
/// </summary>
/// <param name="r"><see cref="IDataRecord"/> to read the CharacterID from.</param>
/// <param name="i">The field index to read.</param>
/// <returns>The CharacterID read from the <see cref="IDataRecord"/>.</returns>
public static CharacterID GetCharacterID(this IDataRecord r, int i)
{
return CharacterID.Read(r, i);
}
/// <summary>
/// Reads the CharacterID from an <see cref="IDataRecord"/>.
/// </summary>
/// <param name="r"><see cref="IDataRecord"/> to read the CharacterID from.</param>
/// <param name="name">The name of the field to read the value from.</param>
/// <returns>The CharacterID read from the <see cref="IDataRecord"/>.</returns>
public static CharacterID GetCharacterID(this IDataRecord r, string name)
{
return CharacterID.Read(r, name);
}
/// <summary>
/// Parses the CharacterID from a string.
/// </summary>
/// <param name="parser">The Parser to use.</param>
/// <param name="value">The string to parse.</param>
/// <returns>The CharacterID parsed from the string.</returns>
public static CharacterID ParseCharacterID(this Parser parser, string value)
{
return new CharacterID(parser.ParseInt(value));
}
/// <summary>
/// Reads the CharacterID from a BitStream.
/// </summary>
/// <param name="bitStream">BitStream to read the CharacterID from.</param>
/// <returns>The CharacterID read from the BitStream.</returns>
public static CharacterID ReadCharacterID(this BitStream bitStream)
{
return CharacterID.Read(bitStream);
}
/// <summary>
/// Reads the CharacterID from an IValueReader.
/// </summary>
/// <param name="valueReader">IValueReader to read the CharacterID from.</param>
/// <param name="name">The unique name of the value to read.</param>
/// <returns>The CharacterID read from the IValueReader.</returns>
public static CharacterID ReadCharacterID(this IValueReader valueReader, string name)
{
return CharacterID.Read(valueReader, name);
}
/// <summary>
/// Tries to parse the CharacterID from a string.
/// </summary>
/// <param name="parser">The Parser to use.</param>
/// <param name="value">The string to parse.</param>
/// <param name="outValue">If this method returns true, contains the parsed CharacterID.</param>
/// <returns>True if the parsing was successfully; otherwise false.</returns>
public static bool TryParse(this Parser parser, string value, out CharacterID outValue)
{
int tmp;
var ret = parser.TryParse(value, out tmp);
outValue = new CharacterID(tmp);
return ret;
}
/// <summary>
/// Writes a CharacterID to a BitStream.
/// </summary>
/// <param name="bitStream">BitStream to write to.</param>
/// <param name="value">CharacterID to write.</param>
public static void Write(this BitStream bitStream, CharacterID value)
{
value.Write(bitStream);
}
/// <summary>
/// Writes a CharacterID to a IValueWriter.
/// </summary>
/// <param name="valueWriter">IValueWriter to write to.</param>
/// <param name="name">Unique name of the CharacterID that will be used to distinguish it
/// from other values when reading.</param>
/// <param name="value">CharacterID to write.</param>
public static void Write(this IValueWriter valueWriter, string name, CharacterID value)
{
value.Write(valueWriter, name);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Avalonia.Input;
using Avalonia.Input.Platform;
using static Avalonia.X11.XLib;
namespace Avalonia.X11
{
class X11Clipboard : IClipboard
{
private readonly X11Info _x11;
private IDataObject _storedDataObject;
private IntPtr _handle;
private TaskCompletionSource<IntPtr[]> _requestedFormatsTcs;
private TaskCompletionSource<object> _requestedDataTcs;
private readonly IntPtr[] _textAtoms;
private readonly IntPtr _avaloniaSaveTargetsAtom;
private readonly Dictionary<string, IntPtr> _formatAtoms = new Dictionary<string, IntPtr>();
private readonly Dictionary<IntPtr, string> _atomFormats = new Dictionary<IntPtr, string>();
public X11Clipboard(AvaloniaX11Platform platform)
{
_x11 = platform.Info;
_handle = CreateEventWindow(platform, OnEvent);
_avaloniaSaveTargetsAtom = XInternAtom(_x11.Display, "AVALONIA_SAVE_TARGETS_PROPERTY_ATOM", false);
_textAtoms = new[]
{
_x11.Atoms.XA_STRING,
_x11.Atoms.OEMTEXT,
_x11.Atoms.UTF8_STRING,
_x11.Atoms.UTF16_STRING
}.Where(a => a != IntPtr.Zero).ToArray();
}
bool IsStringAtom(IntPtr atom)
{
return _textAtoms.Contains(atom);
}
Encoding GetStringEncoding(IntPtr atom)
{
return (atom == _x11.Atoms.XA_STRING
|| atom == _x11.Atoms.OEMTEXT)
? Encoding.ASCII
: atom == _x11.Atoms.UTF8_STRING
? Encoding.UTF8
: atom == _x11.Atoms.UTF16_STRING
? Encoding.Unicode
: null;
}
private unsafe void OnEvent(ref XEvent ev)
{
if (ev.type == XEventName.SelectionRequest)
{
var sel = ev.SelectionRequestEvent;
var resp = new XEvent
{
SelectionEvent =
{
type = XEventName.SelectionNotify,
send_event = 1,
display = _x11.Display,
selection = sel.selection,
target = sel.target,
requestor = sel.requestor,
time = sel.time,
property = IntPtr.Zero
}
};
if (sel.selection == _x11.Atoms.CLIPBOARD)
{
resp.SelectionEvent.property = WriteTargetToProperty(sel.target, sel.requestor, sel.property);
}
XSendEvent(_x11.Display, sel.requestor, false, new IntPtr((int)EventMask.NoEventMask), ref resp);
}
IntPtr WriteTargetToProperty(IntPtr target, IntPtr window, IntPtr property)
{
Encoding textEnc;
if (target == _x11.Atoms.TARGETS)
{
var atoms = new HashSet<IntPtr> { _x11.Atoms.TARGETS, _x11.Atoms.MULTIPLE };
foreach (var fmt in _storedDataObject.GetDataFormats())
{
if (fmt == DataFormats.Text)
foreach (var ta in _textAtoms)
atoms.Add(ta);
else
atoms.Add(_x11.Atoms.GetAtom(fmt));
}
XChangeProperty(_x11.Display, window, property,
_x11.Atoms.XA_ATOM, 32, PropertyMode.Replace, atoms.ToArray(), atoms.Count);
return property;
}
else if(target == _x11.Atoms.SAVE_TARGETS && _x11.Atoms.SAVE_TARGETS != IntPtr.Zero)
{
return property;
}
else if ((textEnc = GetStringEncoding(target)) != null
&& _storedDataObject?.Contains(DataFormats.Text) == true)
{
var text = _storedDataObject.GetText();
if(text == null)
return IntPtr.Zero;
var data = textEnc.GetBytes(text);
fixed (void* pdata = data)
XChangeProperty(_x11.Display, window, property, target, 8,
PropertyMode.Replace,
pdata, data.Length);
return property;
}
else if (target == _x11.Atoms.MULTIPLE && _x11.Atoms.MULTIPLE != IntPtr.Zero)
{
XGetWindowProperty(_x11.Display, window, property, IntPtr.Zero, new IntPtr(0x7fffffff), false,
_x11.Atoms.ATOM_PAIR, out _, out var actualFormat, out var nitems, out _, out var prop);
if (nitems == IntPtr.Zero)
return IntPtr.Zero;
if (actualFormat == 32)
{
var data = (IntPtr*)prop.ToPointer();
for (var c = 0; c < nitems.ToInt32(); c += 2)
{
var subTarget = data[c];
var subProp = data[c + 1];
var converted = WriteTargetToProperty(subTarget, window, subProp);
data[c + 1] = converted;
}
XChangeProperty(_x11.Display, window, property, _x11.Atoms.ATOM_PAIR, 32, PropertyMode.Replace,
prop.ToPointer(), nitems.ToInt32());
}
XFree(prop);
return property;
}
else if(_storedDataObject?.Contains(_x11.Atoms.GetAtomName(target)) == true)
{
var objValue = _storedDataObject.Get(_x11.Atoms.GetAtomName(target));
if(!(objValue is byte[] bytes))
{
if (objValue is string s)
bytes = Encoding.UTF8.GetBytes(s);
else
return IntPtr.Zero;
}
XChangeProperty(_x11.Display, window, property, target, 8,
PropertyMode.Replace,
bytes, bytes.Length);
return property;
}
else
return IntPtr.Zero;
}
if (ev.type == XEventName.SelectionNotify && ev.SelectionEvent.selection == _x11.Atoms.CLIPBOARD)
{
var sel = ev.SelectionEvent;
if (sel.property == IntPtr.Zero)
{
_requestedFormatsTcs?.TrySetResult(null);
_requestedDataTcs?.TrySetResult(null);
}
XGetWindowProperty(_x11.Display, _handle, sel.property, IntPtr.Zero, new IntPtr (0x7fffffff), true, (IntPtr)Atom.AnyPropertyType,
out var actualTypeAtom, out var actualFormat, out var nitems, out var bytes_after, out var prop);
Encoding textEnc = null;
if (nitems == IntPtr.Zero)
{
_requestedFormatsTcs?.TrySetResult(null);
_requestedDataTcs?.TrySetResult(null);
}
else
{
if (sel.property == _x11.Atoms.TARGETS)
{
if (actualFormat != 32)
_requestedFormatsTcs?.TrySetResult(null);
else
{
var formats = new IntPtr[nitems.ToInt32()];
Marshal.Copy(prop, formats, 0, formats.Length);
_requestedFormatsTcs?.TrySetResult(formats);
}
}
else if ((textEnc = GetStringEncoding(actualTypeAtom)) != null)
{
var text = textEnc.GetString((byte*)prop.ToPointer(), nitems.ToInt32());
_requestedDataTcs?.TrySetResult(text);
}
else
{
if (actualTypeAtom == _x11.Atoms.INCR)
{
// TODO: Actually implement that monstrosity
_requestedDataTcs.TrySetResult(null);
}
else
{
var data = new byte[(int)nitems * (actualFormat / 8)];
Marshal.Copy(prop, data, 0, data.Length);
_requestedDataTcs?.TrySetResult(data);
}
}
}
XFree(prop);
}
}
Task<IntPtr[]> SendFormatRequest()
{
if (_requestedFormatsTcs == null || _requestedFormatsTcs.Task.IsCompleted)
_requestedFormatsTcs = new TaskCompletionSource<IntPtr[]>();
XConvertSelection(_x11.Display, _x11.Atoms.CLIPBOARD, _x11.Atoms.TARGETS, _x11.Atoms.TARGETS, _handle,
IntPtr.Zero);
return _requestedFormatsTcs.Task;
}
Task<object> SendDataRequest(IntPtr format)
{
if (_requestedDataTcs == null || _requestedFormatsTcs.Task.IsCompleted)
_requestedDataTcs = new TaskCompletionSource<object>();
XConvertSelection(_x11.Display, _x11.Atoms.CLIPBOARD, format, format, _handle, IntPtr.Zero);
return _requestedDataTcs.Task;
}
bool HasOwner => XGetSelectionOwner(_x11.Display, _x11.Atoms.CLIPBOARD) != IntPtr.Zero;
public async Task<string> GetTextAsync()
{
if (!HasOwner)
return null;
var res = await SendFormatRequest();
var target = _x11.Atoms.UTF8_STRING;
if (res != null)
{
var preferredFormats = new[] {_x11.Atoms.UTF16_STRING, _x11.Atoms.UTF8_STRING, _x11.Atoms.XA_STRING};
foreach (var pf in preferredFormats)
if (res.Contains(pf))
{
target = pf;
break;
}
}
return (string)await SendDataRequest(target);
}
void StoreAtomsInClipboardManager(IntPtr[] atoms)
{
if (_x11.Atoms.CLIPBOARD_MANAGER != IntPtr.Zero && _x11.Atoms.SAVE_TARGETS != IntPtr.Zero)
{
var clipboardManager = XGetSelectionOwner(_x11.Display, _x11.Atoms.CLIPBOARD_MANAGER);
if (clipboardManager != IntPtr.Zero)
{
XChangeProperty(_x11.Display, _handle, _avaloniaSaveTargetsAtom, _x11.Atoms.XA_ATOM, 32,
PropertyMode.Replace,
atoms, atoms.Length);
XConvertSelection(_x11.Display, _x11.Atoms.CLIPBOARD_MANAGER, _x11.Atoms.SAVE_TARGETS,
_avaloniaSaveTargetsAtom, _handle, IntPtr.Zero);
}
}
}
public Task SetTextAsync(string text)
{
var data = new DataObject();
data.Set(DataFormats.Text, text);
return SetDataObjectAsync(data);
}
public Task ClearAsync()
{
return SetTextAsync(null);
}
public Task SetDataObjectAsync(IDataObject data)
{
_storedDataObject = data;
XSetSelectionOwner(_x11.Display, _x11.Atoms.CLIPBOARD, _handle, IntPtr.Zero);
StoreAtomsInClipboardManager(_textAtoms);
return Task.CompletedTask;
}
public async Task<string[]> GetFormatsAsync()
{
if (!HasOwner)
return null;
var res = await SendFormatRequest();
if (res == null)
return null;
var rv = new List<string>();
if (_textAtoms.Any(res.Contains))
rv.Add(DataFormats.Text);
foreach (var t in res)
rv.Add(_x11.Atoms.GetAtomName(t));
return rv.ToArray();
}
public async Task<object> GetDataAsync(string format)
{
if (!HasOwner)
return null;
if (format == DataFormats.Text)
return await GetTextAsync();
var formatAtom = _x11.Atoms.GetAtom(format);
var res = await SendFormatRequest();
if (!res.Contains(formatAtom))
return null;
return await SendDataRequest(formatAtom);
}
}
}
| |
// SampSharp
// Copyright 2020 Tim Potze
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Diagnostics.CodeAnalysis;
namespace SampSharp.Entities.SAMP
{
/// <summary>
/// Contains all map icons.
/// </summary>
[SuppressMessage("ReSharper", "IdentifierTypo")]
[SuppressMessage("ReSharper", "CommentTypo")]
public enum MapIcon
{
/// <summary>
/// Can be used in any colour. Used for Single Player objectives.
/// </summary>
ColoredSquareTriangleDynamic = 0,
/// <summary>
/// 2 times bigger than ID 0 and without the border.
/// </summary>
[Obsolete("This element will cause your game to crash if you have map legends enabled while viewing the map",
false)]
WhiteSquare = 1,
/// <summary>
/// Will be used on the minimap by default.
/// </summary>
[Obsolete("This element will cause your game to crash if you have map legends enabled while viewing the map",
false)]
PlayerPosition = 2,
/// <summary>
/// Your position when on the large map.
/// </summary>
PlayerMenuMap = 3,
/// <summary>
/// Always appears on the radar toward the north.
/// </summary>
[Obsolete("This element will cause your game to crash if you have map legends enabled while viewing the map",
false)]
North = 4,
/// <summary>
/// Air Yard
/// </summary>
AirYard = 5,
/// <summary>
/// Ammunation
/// </summary>
Ammunation = 6,
/// <summary>
/// Barber
/// </summary>
Barber = 7,
/// <summary>
/// Big Smoke
/// </summary>
BigSmoke = 8,
/// <summary>
/// Boat Yard
/// </summary>
BoatYard = 9,
/// <summary>
/// Burger Shot
/// </summary>
BurgerShot = 10,
/// <summary>
/// Quarry
/// </summary>
Quarry = 11,
/// <summary>
/// Catalina
/// </summary>
Catalina = 12,
/// <summary>
/// Cesar
/// </summary>
Cesar = 13,
/// <summary>
/// Cluckin' Bell
/// </summary>
CluckinBell = 14,
/// <summary>
/// Carl Johnson
/// </summary>
CarlJohnson = 15,
/// <summary>
/// C.R.A.S.H
/// </summary>
Crash = 16,
/// <summary>
/// Diner
/// </summary>
Diner = 17,
/// <summary>
/// Emmet
/// </summary>
Emmet = 18,
/// <summary>
/// Enemy Attack
/// </summary>
EnemyAttack = 19,
/// <summary>
/// Fire
/// </summary>
Fire = 20,
/// <summary>
/// Girlfriend
/// </summary>
Girlfriend = 21,
/// <summary>
/// Hospital
/// </summary>
Hospital = 22,
/// <summary>
/// Loco
/// </summary>
Loco = 23,
/// <summary>
/// Madd Dogg
/// </summary>
MaddDogg = 24,
/// <summary>
/// Caligulas
/// </summary>
Caligulas = 25,
/// <summary>
/// MC Loc
/// </summary>
McLoc = 26,
/// <summary>
/// Mod garage
/// </summary>
ModGarage = 27,
/// <summary>
/// OG Loc
/// </summary>
OgLoc = 28,
/// <summary>
/// Well Stacked Pizza Co
/// </summary>
WellStackedPizzaCo = 29,
/// <summary>
/// Police
/// </summary>
Police = 30,
/// <summary>
/// A property you're free to purchase.
/// </summary>
FreeProperty = 31,
/// <summary>
/// A property that isn't available for purchase.
/// </summary>
Property = 32,
/// <summary>
/// Race
/// </summary>
Race = 33,
/// <summary>
/// Ryder
/// </summary>
Ryder = 34,
/// <summary>
/// Used for safehouses where you save the game in singleplayer.
/// </summary>
SaveGame = 35,
/// <summary>
/// School
/// </summary>
School = 36,
/// <summary>
/// Unknown
/// </summary>
Unknown = 37,
/// <summary>
/// Sweet
/// </summary>
Sweet = 38,
/// <summary>
/// Tattoo
/// </summary>
Tattoo = 39,
/// <summary>
/// The Truth
/// </summary>
TheTruth = 40,
/// <summary>
/// Can be placed by players on the pause menu map by right-clicking
/// </summary>
Waypoint = 41,
/// <summary>
/// Toreno
/// </summary>
Toreno = 42,
/// <summary>
/// Triads
/// </summary>
Triads = 43,
/// <summary>
/// Triads Casino
/// </summary>
TriadsCasino = 44,
/// <summary>
/// Clothes
/// </summary>
Clothes = 45,
/// <summary>
/// Woozie
/// </summary>
Woozie = 46,
/// <summary>
/// Zero
/// </summary>
Zero = 47,
/// <summary>
/// Club
/// </summary>
Club = 48,
/// <summary>
/// Bar
/// </summary>
Bar = 49,
/// <summary>
/// Restaurant
/// </summary>
Restaurant = 50,
/// <summary>
/// Truck
/// </summary>
Truck = 51,
/// <summary>
/// Frequently used for banks.
/// </summary>
Robbery = 52,
/// <summary>
/// Race
/// </summary>
RaceFlag = 53,
/// <summary>
/// Gym
/// </summary>
Gym = 54,
/// <summary>
/// Car
/// </summary>
Car = 55,
/// <summary>
/// Light
/// </summary>
[Obsolete("This element will cause your game to crash if you have map legends enabled while viewing the map",
false)]
Light = 56,
/// <summary>
/// Closest airport
/// </summary>
ClosestAirport = 57,
/// <summary>
/// Varrios Los Aztecas
/// </summary>
VarriosLosAztecas = 58,
/// <summary>
/// Ballas
/// </summary>
Ballas = 59,
/// <summary>
/// Los Santos Vagos
/// </summary>
LosSantosVagos = 60,
/// <summary>
/// San Fierro Rifa
/// </summary>
SanFierroRifa = 61,
/// <summary>
/// Grove street
/// </summary>
GroveStreet = 62,
/// <summary>
/// Pay 'n' Spray
/// </summary>
PayNSpray = 63
}
}
| |
#region Using directives
using System;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Xml.Schema;
using log4net;
using Commanigy.Iquomi.Data;
#endregion
namespace Commanigy.Iquomi.Web {
/// <summary>
///
/// </summary>
public partial class UcServiceCharge : System.Web.UI.UserControl {
private static readonly ILog log = LogManager.GetLogger(
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType
);
private DbServiceCharge item;
public DbServiceCharge Item {
get {
item.MethodTypeId = this.MethodTypeId;
item.SchemaType = this.SchemaType;
item.Script = this.Script;
item.Price = this.Price;
item.ChargeUnitId = this.ChargeUnitId;
return item;
}
set {
item = value;
this.MethodTypeId = item.MethodTypeId;
this.SchemaType = item.SchemaType;
this.Script = item.Script;
this.Price = item.Price;
this.ChargeUnitId = item.ChargeUnitId;
}
}
private DbService service;
public DbService Service {
get {
return this.service;
}
set {
this.service = value;
XmlSchema schema = null;
try {
schema = service.GetXmlSchema();
// log.Debug("Enumerating elements for schema = " + schema);
if (!schema.IsCompiled) {
XmlSchemaSet xss = new XmlSchemaSet();
xss.Add(schema);
xss.Compile();
// log.Debug("Global Elements");
foreach (XmlQualifiedName o in xss.GlobalElements.Names) {
// log.Debug("Namespace: " + o.Namespace + ". Name: " + o.Name);
if (schema.TargetNamespace != null && schema.TargetNamespace.Equals(o.Namespace)) {
this.FldSchemaType.Items.Add(o.Name);
}
}
// log.Debug("Global Types");
foreach (XmlQualifiedName o in xss.GlobalTypes.Names) {
// log.Debug("Namespace: " + o.Namespace + ". Name: " + o.Name);
if (schema.TargetNamespace != null && schema.TargetNamespace.Equals(o.Namespace)) {
this.FldSchemaType.Items.Add(o.Name);
}
}
// log.Debug("Global Attributes");
// foreach (XmlQualifiedName o in xss.GlobalAttributes.Names) {
// log.Debug("Namespace: " + o.Namespace + ". Name: " + o.Name);
// if (schema.TargetNamespace.Equals(o.Namespace)) {
// log.Debug(o.Name);
// }
// }
}
}
catch (XmlSchemaException xse) {
log.Warn("Service \"" + service.Name + "\" contains invalid Xml Schema", xse);
}
catch (XmlException xe) {
log.Warn("Cannot read schema for service \"" + service.Name + "\"", xe);
}
// if (schema != null) {
// foreach (XmlQualifiedName o in schema.SchemaTypes.Names) {
// log.Debug(o.Namespace + ": " + o.Name);
// if (schema.TargetNamespace.Equals(o.Namespace)) {
// this.FldSchemaType.Items.Add(o.Name);
// }
// }
// }
}
}
#region Properties
/// <summary>
/// Property SchemaType (string)
/// </summary>
public string SchemaType {
get {
return FldSchemaType.SelectedValue;
}
set {
FldSchemaType.SelectedValue = value;
}
}
/// <summary>
/// Property Type (int)
/// </summary>
public int MethodTypeId {
get {
return Convert.ToInt32(FldMethodTypeId.SelectedValue);
}
set {
FldMethodTypeId.SelectedValue = Convert.ToString(value);
}
}
/// <summary>
/// Property Script (string)
/// </summary>
public string Script {
get {
return FldScript.Text;
}
set {
FldScript.Text = value;
}
}
/// <summary>
/// Property ChargeUnitId (int)
/// </summary>
public int ChargeUnitId {
get {
return Convert.ToInt32(FldChargeUnitId.SelectedValue);
}
set {
FldChargeUnitId.SelectedValue = Convert.ToString(value);
}
}
/// <summary>
/// Property Price (float)
/// </summary>
public float Price {
get {
try {
return Convert.ToSingle(FldPrice.Text);
}
catch (FormatException) {
return 0.0f;
}
}
set {
FldPrice.Text = Convert.ToString(value);
}
}
#endregion
private void Page_Load(object sender, System.EventArgs e) {
if (!Page.IsPostBack) {
FldSchemaType.Enabled = (FldSchemaType.Items.Count > 0);
DbMethodType[] y = (DbMethodType[])DbMethodType.DbFindAll();
foreach (DbMethodType a in y) {
FldMethodTypeId.Items.Add(new ListItem(a.Name, Convert.ToString(a.Id)));
}
FldMethodTypeId.Items.Insert(0, new ListItem("", ""));
DbChargeUnit chargeUnit = new DbChargeUnit();
DataTable dt = (DataTable)chargeUnit.DbFindAll();
foreach (DataRow dr in dt.Rows) {
ListItem li = new ListItem(
String.Format("{0}: {1}",
dr["ChargeUnitCommonName"].ToString(),
dr["ChargeUnitDescriptionName"].ToString()
),
dr["ChargeUnitId"].ToString()
);
FldChargeUnitId.Items.Add(li);
}
FldMethodTypeId.DataBind();
FldChargeUnitId.DataBind();
}
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type ConversationRequest.
/// </summary>
public partial class ConversationRequest : BaseRequest, IConversationRequest
{
/// <summary>
/// Constructs a new ConversationRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public ConversationRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified Conversation using POST.
/// </summary>
/// <param name="conversationToCreate">The Conversation to create.</param>
/// <returns>The created Conversation.</returns>
public System.Threading.Tasks.Task<Conversation> CreateAsync(Conversation conversationToCreate)
{
return this.CreateAsync(conversationToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified Conversation using POST.
/// </summary>
/// <param name="conversationToCreate">The Conversation to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created Conversation.</returns>
public async System.Threading.Tasks.Task<Conversation> CreateAsync(Conversation conversationToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<Conversation>(conversationToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified Conversation.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified Conversation.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<Conversation>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified Conversation.
/// </summary>
/// <returns>The Conversation.</returns>
public System.Threading.Tasks.Task<Conversation> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified Conversation.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The Conversation.</returns>
public async System.Threading.Tasks.Task<Conversation> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<Conversation>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified Conversation using PATCH.
/// </summary>
/// <param name="conversationToUpdate">The Conversation to update.</param>
/// <returns>The updated Conversation.</returns>
public System.Threading.Tasks.Task<Conversation> UpdateAsync(Conversation conversationToUpdate)
{
return this.UpdateAsync(conversationToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified Conversation using PATCH.
/// </summary>
/// <param name="conversationToUpdate">The Conversation to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated Conversation.</returns>
public async System.Threading.Tasks.Task<Conversation> UpdateAsync(Conversation conversationToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<Conversation>(conversationToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IConversationRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IConversationRequest Expand(Expression<Func<Conversation, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IConversationRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IConversationRequest Select(Expression<Func<Conversation, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="conversationToInitialize">The <see cref="Conversation"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(Conversation conversationToInitialize)
{
if (conversationToInitialize != null && conversationToInitialize.AdditionalData != null)
{
if (conversationToInitialize.Threads != null && conversationToInitialize.Threads.CurrentPage != null)
{
conversationToInitialize.Threads.AdditionalData = conversationToInitialize.AdditionalData;
object nextPageLink;
conversationToInitialize.AdditionalData.TryGetValue("threads@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
conversationToInitialize.Threads.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
}
}
}
}
| |
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2012 Atif Aziz. 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.
#endregion
namespace MoreLinq
{
using System;
using System.Collections.Generic;
using System.Linq;
static partial class MoreEnumerable
{
/// <summary>
/// Splits the source sequence by a separator.
/// </summary>
/// <typeparam name="TSource">Type of element in the source sequence.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="separator">Separator element.</param>
/// <returns>A sequence of splits of elements.</returns>
public static IEnumerable<IEnumerable<TSource>> Split<TSource>(this IEnumerable<TSource> source,
TSource separator)
{
return Split(source, separator, int.MaxValue);
}
/// <summary>
/// Splits the source sequence by a separator given a maximum count of splits.
/// </summary>
/// <typeparam name="TSource">Type of element in the source sequence.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="separator">Separator element.</param>
/// <param name="count">Maximum number of splits.</param>
/// <returns>A sequence of splits of elements.</returns>
public static IEnumerable<IEnumerable<TSource>> Split<TSource>(this IEnumerable<TSource> source,
TSource separator, int count)
{
return Split(source, separator, count, s => s);
}
/// <summary>
/// Splits the source sequence by a separator and then transforms
/// the splits into results.
/// </summary>
/// <typeparam name="TSource">Type of element in the source sequence.</typeparam>
/// <typeparam name="TResult">Type of the result sequence elements.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="separator">Separator element.</param>
/// <param name="resultSelector">Function used to project splits
/// of source elements into elements of the resulting sequence.</param>
/// <returns>
/// A sequence of values typed as <typeparamref name="TResult"/>.
/// </returns>
public static IEnumerable<TResult> Split<TSource, TResult>(this IEnumerable<TSource> source,
TSource separator,
Func<IEnumerable<TSource>, TResult> resultSelector)
{
return Split(source, separator, int.MaxValue, resultSelector);
}
/// <summary>
/// Splits the source sequence by a separator, given a maximum count
/// of splits, and then transforms the splits into results.
/// </summary>
/// <typeparam name="TSource">Type of element in the source sequence.</typeparam>
/// <typeparam name="TResult">Type of the result sequence elements.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="separator">Separator element.</param>
/// <param name="count">Maximum number of splits.</param>
/// <param name="resultSelector">Function used to project splits
/// of source elements into elements of the resulting sequence.</param>
/// <returns>
/// A sequence of values typed as <typeparamref name="TResult"/>.
/// </returns>
public static IEnumerable<TResult> Split<TSource, TResult>(this IEnumerable<TSource> source,
TSource separator, int count,
Func<IEnumerable<TSource>, TResult> resultSelector)
{
return Split(source, separator, null, count, resultSelector);
}
/// <summary>
/// Splits the source sequence by a separator and then transforms the
/// splits into results.
/// </summary>
/// <typeparam name="TSource">Type of element in the source sequence.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="separator">Separator element.</param>
/// <param name="comparer">Comparer used to determine separator
/// element equality.</param>
/// <returns>A sequence of splits of elements.</returns>
public static IEnumerable<IEnumerable<TSource>> Split<TSource>(this IEnumerable<TSource> source,
TSource separator, IEqualityComparer<TSource>? comparer)
{
return Split(source, separator, comparer, int.MaxValue);
}
/// <summary>
/// Splits the source sequence by a separator, given a maximum count
/// of splits. A parameter specifies how the separator is compared
/// for equality.
/// </summary>
/// <typeparam name="TSource">Type of element in the source sequence.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="separator">Separator element.</param>
/// <param name="comparer">Comparer used to determine separator
/// element equality.</param>
/// <param name="count">Maximum number of splits.</param>
/// <returns>A sequence of splits of elements.</returns>
public static IEnumerable<IEnumerable<TSource>> Split<TSource>(this IEnumerable<TSource> source,
TSource separator, IEqualityComparer<TSource>? comparer, int count)
{
return Split(source, separator, comparer, count, s => s);
}
/// <summary>
/// Splits the source sequence by a separator and then transforms the
/// splits into results. A parameter specifies how the separator is
/// compared for equality.
/// </summary>
/// <typeparam name="TSource">Type of element in the source sequence.</typeparam>
/// <typeparam name="TResult">Type of the result sequence elements.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="separator">Separator element.</param>
/// <param name="comparer">Comparer used to determine separator
/// element equality.</param>
/// <param name="resultSelector">Function used to project splits
/// of source elements into elements of the resulting sequence.</param>
/// <returns>
/// A sequence of values typed as <typeparamref name="TResult"/>.
/// </returns>
public static IEnumerable<TResult> Split<TSource, TResult>(this IEnumerable<TSource> source,
TSource separator, IEqualityComparer<TSource> comparer,
Func<IEnumerable<TSource>, TResult> resultSelector)
{
return Split(source, separator, comparer, int.MaxValue, resultSelector);
}
/// <summary>
/// Splits the source sequence by a separator, given a maximum count
/// of splits, and then transforms the splits into results. A
/// parameter specifies how the separator is compared for equality.
/// </summary>
/// <typeparam name="TSource">Type of element in the source sequence.</typeparam>
/// <typeparam name="TResult">Type of the result sequence elements.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="separator">Separator element.</param>
/// <param name="comparer">Comparer used to determine separator
/// element equality.</param>
/// <param name="count">Maximum number of splits.</param>
/// <param name="resultSelector">Function used to project splits
/// of source elements into elements of the resulting sequence.</param>
/// <returns>
/// A sequence of values typed as <typeparamref name="TResult"/>.
/// </returns>
public static IEnumerable<TResult> Split<TSource, TResult>(this IEnumerable<TSource> source,
TSource separator, IEqualityComparer<TSource>? comparer, int count,
Func<IEnumerable<TSource>, TResult> resultSelector)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));
if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector));
comparer ??= EqualityComparer<TSource>.Default;
return Split(source, item => comparer.Equals(item, separator), count, resultSelector);
}
/// <summary>
/// Splits the source sequence by separator elements identified by a
/// function.
/// </summary>
/// <typeparam name="TSource">Type of element in the source sequence.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="separatorFunc">Predicate function used to determine
/// the splitter elements in the source sequence.</param>
/// <returns>A sequence of splits of elements.</returns>
public static IEnumerable<IEnumerable<TSource>> Split<TSource>(this IEnumerable<TSource> source,
Func<TSource, bool> separatorFunc)
{
return Split(source, separatorFunc, int.MaxValue);
}
/// <summary>
/// Splits the source sequence by separator elements identified by a
/// function, given a maximum count of splits.
/// </summary>
/// <typeparam name="TSource">Type of element in the source sequence.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="separatorFunc">Predicate function used to determine
/// the splitter elements in the source sequence.</param>
/// <param name="count">Maximum number of splits.</param>
/// <returns>A sequence of splits of elements.</returns>
public static IEnumerable<IEnumerable<TSource>> Split<TSource>(this IEnumerable<TSource> source,
Func<TSource, bool> separatorFunc, int count)
{
return Split(source, separatorFunc, count, s => s);
}
/// <summary>
/// Splits the source sequence by separator elements identified by
/// a function and then transforms the splits into results.
/// </summary>
/// <typeparam name="TSource">Type of element in the source sequence.</typeparam>
/// <typeparam name="TResult">Type of the result sequence elements.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="separatorFunc">Predicate function used to determine
/// the splitter elements in the source sequence.</param>
/// <param name="resultSelector">Function used to project splits
/// of source elements into elements of the resulting sequence.</param>
/// <returns>
/// A sequence of values typed as <typeparamref name="TResult"/>.
/// </returns>
public static IEnumerable<TResult> Split<TSource, TResult>(this IEnumerable<TSource> source,
Func<TSource, bool> separatorFunc,
Func<IEnumerable<TSource>, TResult> resultSelector)
{
return Split(source, separatorFunc, int.MaxValue, resultSelector);
}
/// <summary>
/// Splits the source sequence by separator elements identified by
/// a function, given a maximum count of splits, and then transforms
/// the splits into results.
/// </summary>
/// <typeparam name="TSource">Type of element in the source sequence.</typeparam>
/// <typeparam name="TResult">Type of the result sequence elements.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="separatorFunc">Predicate function used to determine
/// the splitter elements in the source sequence.</param>
/// <param name="count">Maximum number of splits.</param>
/// <param name="resultSelector">Function used to project a split
/// group of source elements into an element of the resulting sequence.</param>
/// <returns>
/// A sequence of values typed as <typeparamref name="TResult"/>.
/// </returns>
public static IEnumerable<TResult> Split<TSource, TResult>(this IEnumerable<TSource> source,
Func<TSource, bool> separatorFunc, int count,
Func<IEnumerable<TSource>, TResult> resultSelector)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (separatorFunc == null) throw new ArgumentNullException(nameof(separatorFunc));
if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));
if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector));
return _(); IEnumerable<TResult> _()
{
if (count == 0) // No splits?
{
yield return resultSelector(source);
}
else
{
List<TSource>? items = null;
foreach (var item in source)
{
if (count > 0 && separatorFunc(item))
{
yield return resultSelector(items ?? Enumerable.Empty<TSource>());
count--;
items = null;
}
else
{
items ??= new List<TSource>();
items.Add(item);
}
}
if (items != null && items.Count > 0)
yield return resultSelector(items);
}
}
}
}
}
| |
// 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.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Xunit;
namespace Microsoft.AspNetCore.Authentication.Certificate.Test
{
public class ClientCertificateAuthenticationTests
{
[Fact]
public async Task VerifySchemeDefaults()
{
var services = new ServiceCollection();
services.AddAuthentication().AddCertificate();
var sp = services.BuildServiceProvider();
var schemeProvider = sp.GetRequiredService<IAuthenticationSchemeProvider>();
var scheme = await schemeProvider.GetSchemeAsync(CertificateAuthenticationDefaults.AuthenticationScheme);
Assert.NotNull(scheme);
Assert.Equal("CertificateAuthenticationHandler", scheme.HandlerType.Name);
Assert.Null(scheme.DisplayName);
}
[Fact]
public void VerifyIsSelfSignedExtensionMethod()
{
Assert.True(Certificates.SelfSignedValidWithNoEku.IsSelfSigned());
}
[Fact]
public async Task VerifyValidSelfSignedWithClientEkuAuthenticates()
{
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
AllowedCertificateTypes = CertificateTypes.SelfSigned,
Events = successfulValidationEvents
},
Certificates.SelfSignedValidWithClientEku);
using var server = host.GetTestServer();
var response = await server.CreateClient().GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task VerifyValidSelfSignedWithNoEkuAuthenticates()
{
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
AllowedCertificateTypes = CertificateTypes.SelfSigned,
Events = successfulValidationEvents
},
Certificates.SelfSignedValidWithNoEku);
using var server = host.GetTestServer();
var response = await server.CreateClient().GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task VerifyValidSelfSignedWithClientEkuFailsWhenSelfSignedCertsNotAllowed()
{
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
AllowedCertificateTypes = CertificateTypes.Chained
},
Certificates.SelfSignedValidWithClientEku);
using var server = host.GetTestServer();
var response = await server.CreateClient().GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task VerifyValidSelfSignedWithNoEkuFailsWhenSelfSignedCertsNotAllowed()
{
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
AllowedCertificateTypes = CertificateTypes.Chained,
Events = successfulValidationEvents
},
Certificates.SelfSignedValidWithNoEku);
using var server = host.GetTestServer();
var response = await server.CreateClient().GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task VerifyValidSelfSignedWithServerFailsEvenIfSelfSignedCertsAreAllowed()
{
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
AllowedCertificateTypes = CertificateTypes.SelfSigned,
Events = successfulValidationEvents
},
Certificates.SelfSignedValidWithServerEku);
using var server = host.GetTestServer();
var response = await server.CreateClient().GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task VerifyValidSelfSignedWithServerPassesWhenSelfSignedCertsAreAllowedAndPurposeValidationIsOff()
{
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
AllowedCertificateTypes = CertificateTypes.SelfSigned,
ValidateCertificateUse = false,
Events = successfulValidationEvents
},
Certificates.SelfSignedValidWithServerEku);
using var server = host.GetTestServer();
var response = await server.CreateClient().GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task VerifyValidSelfSignedWithServerFailsPurposeValidationIsOffButSelfSignedCertsAreNotAllowed()
{
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
AllowedCertificateTypes = CertificateTypes.Chained,
ValidateCertificateUse = false,
Events = successfulValidationEvents
},
Certificates.SelfSignedValidWithServerEku);
using var server = host.GetTestServer();
var response = await server.CreateClient().GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task VerifyExpiredSelfSignedFails()
{
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
AllowedCertificateTypes = CertificateTypes.SelfSigned,
ValidateCertificateUse = false,
Events = successfulValidationEvents
},
Certificates.SelfSignedExpired);
using var server = host.GetTestServer();
var response = await server.CreateClient().GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task VerifyExpiredSelfSignedPassesIfDateRangeValidationIsDisabled()
{
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
AllowedCertificateTypes = CertificateTypes.SelfSigned,
ValidateValidityPeriod = false,
Events = successfulValidationEvents
},
Certificates.SelfSignedExpired);
using var server = host.GetTestServer();
var response = await server.CreateClient().GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[ConditionalFact]
[SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/32813")]
public async Task VerifyNotYetValidSelfSignedFails()
{
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
AllowedCertificateTypes = CertificateTypes.SelfSigned,
ValidateCertificateUse = false,
Events = successfulValidationEvents
},
Certificates.SelfSignedNotYetValid);
using var server = host.GetTestServer();
var response = await server.CreateClient().GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task VerifyNotYetValidSelfSignedPassesIfDateRangeValidationIsDisabled()
{
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
AllowedCertificateTypes = CertificateTypes.SelfSigned,
ValidateValidityPeriod = false,
Events = successfulValidationEvents
},
Certificates.SelfSignedNotYetValid);
using var server = host.GetTestServer();
var response = await server.CreateClient().GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task VerifyFailingInTheValidationEventReturnsForbidden()
{
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
ValidateCertificateUse = false,
Events = failedValidationEvents
},
Certificates.SelfSignedValidWithServerEku);
using var server = host.GetTestServer();
var response = await server.CreateClient().GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task DoingNothingInTheValidationEventReturnsOK()
{
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
AllowedCertificateTypes = CertificateTypes.SelfSigned,
ValidateCertificateUse = false,
Events = unprocessedValidationEvents
},
Certificates.SelfSignedValidWithServerEku);
using var server = host.GetTestServer();
var response = await server.CreateClient().GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task VerifyNotSendingACertificateEndsUpInForbidden()
{
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
Events = successfulValidationEvents
});
using var server = host.GetTestServer();
var response = await server.CreateClient().GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task VerifyUntrustedClientCertEndsUpInForbidden()
{
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
Events = successfulValidationEvents
}, Certificates.SignedClient);
using var server = host.GetTestServer();
var response = await server.CreateClient().GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task VerifyValidationFailureCanBeHandled()
{
var failCalled = false;
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
Events = new CertificateAuthenticationEvents()
{
OnAuthenticationFailed = context =>
{
context.Fail("Validation failed: " + context.Exception);
failCalled = true;
return Task.CompletedTask;
}
}
}, Certificates.SignedClient);
using var server = host.GetTestServer();
var response = await server.CreateClient().GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.True(failCalled);
}
[Fact]
public async Task VerifyClientCertWithUntrustedRootAndTrustedChainEndsUpInForbidden()
{
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
Events = successfulValidationEvents,
CustomTrustStore = new X509Certificate2Collection() { Certificates.SignedSecondaryRoot },
ChainTrustValidationMode = X509ChainTrustMode.CustomRootTrust,
RevocationMode = X509RevocationMode.NoCheck
}, Certificates.SignedClient);
using var server = host.GetTestServer();
var response = await server.CreateClient().GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task VerifyValidClientCertWithTrustedChainAuthenticates()
{
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
Events = successfulValidationEvents,
CustomTrustStore = new X509Certificate2Collection() { Certificates.SelfSignedPrimaryRoot, Certificates.SignedSecondaryRoot },
ChainTrustValidationMode = X509ChainTrustMode.CustomRootTrust,
RevocationMode = X509RevocationMode.NoCheck
}, Certificates.SignedClient);
using var server = host.GetTestServer();
var response = await server.CreateClient().GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task VerifyValidClientCertWithAdditionalCertificatesAuthenticates()
{
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
Events = successfulValidationEvents,
ChainTrustValidationMode = X509ChainTrustMode.CustomRootTrust,
CustomTrustStore = new X509Certificate2Collection() { Certificates.SelfSignedPrimaryRoot, },
AdditionalChainCertificates = new X509Certificate2Collection() { Certificates.SignedSecondaryRoot },
RevocationMode = X509RevocationMode.NoCheck
}, Certificates.SignedClient);
using var server = host.GetTestServer();
var response = await server.CreateClient().GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task VerifyValidClientCertFailsWithoutAdditionalCertificatesAuthenticates()
{
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
Events = successfulValidationEvents,
ChainTrustValidationMode = X509ChainTrustMode.CustomRootTrust,
CustomTrustStore = new X509Certificate2Collection() { Certificates.SelfSignedPrimaryRoot, },
RevocationMode = X509RevocationMode.NoCheck
}, Certificates.SignedClient);
using var server = host.GetTestServer();
var response = await server.CreateClient().GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task VerifyHeaderIsUsedIfCertIsNotPresent()
{
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
AllowedCertificateTypes = CertificateTypes.SelfSigned,
Events = successfulValidationEvents
},
wireUpHeaderMiddleware: true);
using var server = host.GetTestServer();
var client = server.CreateClient();
client.DefaultRequestHeaders.Add("X-Client-Cert", Convert.ToBase64String(Certificates.SelfSignedValidWithNoEku.RawData));
var response = await client.GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task VerifyHeaderEncodedCertFailsOnBadEncoding()
{
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
Events = successfulValidationEvents
},
wireUpHeaderMiddleware: true);
using var server = host.GetTestServer();
var client = server.CreateClient();
client.DefaultRequestHeaders.Add("X-Client-Cert", "OOPS" + Convert.ToBase64String(Certificates.SelfSignedValidWithNoEku.RawData));
var response = await client.GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task VerifySettingTheAzureHeaderOnTheForwarderOptionsWorks()
{
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
AllowedCertificateTypes = CertificateTypes.SelfSigned,
Events = successfulValidationEvents
},
wireUpHeaderMiddleware: true,
headerName: "X-ARR-ClientCert");
using var server = host.GetTestServer();
var client = server.CreateClient();
client.DefaultRequestHeaders.Add("X-ARR-ClientCert", Convert.ToBase64String(Certificates.SelfSignedValidWithNoEku.RawData));
var response = await client.GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task VerifyACustomHeaderFailsIfTheHeaderIsNotPresent()
{
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
Events = successfulValidationEvents
},
wireUpHeaderMiddleware: true,
headerName: "X-ARR-ClientCert");
using var server = host.GetTestServer();
var client = server.CreateClient();
client.DefaultRequestHeaders.Add("random-Weird-header", Convert.ToBase64String(Certificates.SelfSignedValidWithNoEku.RawData));
var response = await client.GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task VerifyNoEventWireupWithAValidCertificateCreatesADefaultUser()
{
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
AllowedCertificateTypes = CertificateTypes.SelfSigned
},
Certificates.SelfSignedValidWithNoEku);
using var server = host.GetTestServer();
var response = await server.CreateClient().GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
XElement responseAsXml = null;
if (response.Content != null &&
response.Content.Headers.ContentType != null &&
response.Content.Headers.ContentType.MediaType == "text/xml")
{
var responseContent = await response.Content.ReadAsStringAsync();
responseAsXml = XElement.Parse(responseContent);
}
Assert.NotNull(responseAsXml);
// There should always be an Issuer and a Thumbprint.
var actual = responseAsXml.Elements("claim").Where(claim => claim.Attribute("Type").Value == "issuer");
Assert.Single(actual);
Assert.Equal(Certificates.SelfSignedValidWithNoEku.Issuer, actual.First().Value);
actual = responseAsXml.Elements("claim").Where(claim => claim.Attribute("Type").Value == ClaimTypes.Thumbprint);
Assert.Single(actual);
Assert.Equal(Certificates.SelfSignedValidWithNoEku.Thumbprint, actual.First().Value);
// Now the optional ones
if (!string.IsNullOrEmpty(Certificates.SelfSignedValidWithNoEku.SubjectName.Name))
{
actual = responseAsXml.Elements("claim").Where(claim => claim.Attribute("Type").Value == ClaimTypes.X500DistinguishedName);
if (actual.Any())
{
Assert.Single(actual);
Assert.Equal(Certificates.SelfSignedValidWithNoEku.SubjectName.Name, actual.First().Value);
}
}
if (!string.IsNullOrEmpty(Certificates.SelfSignedValidWithNoEku.SerialNumber))
{
actual = responseAsXml.Elements("claim").Where(claim => claim.Attribute("Type").Value == ClaimTypes.SerialNumber);
if (actual.Any())
{
Assert.Single(actual);
Assert.Equal(Certificates.SelfSignedValidWithNoEku.SerialNumber, actual.First().Value);
}
}
if (!string.IsNullOrEmpty(Certificates.SelfSignedValidWithNoEku.GetNameInfo(X509NameType.DnsName, false)))
{
actual = responseAsXml.Elements("claim").Where(claim => claim.Attribute("Type").Value == ClaimTypes.Dns);
if (actual.Any())
{
Assert.Single(actual);
Assert.Equal(Certificates.SelfSignedValidWithNoEku.GetNameInfo(X509NameType.DnsName, false), actual.First().Value);
}
}
if (!string.IsNullOrEmpty(Certificates.SelfSignedValidWithNoEku.GetNameInfo(X509NameType.EmailName, false)))
{
actual = responseAsXml.Elements("claim").Where(claim => claim.Attribute("Type").Value == ClaimTypes.Email);
if (actual.Any())
{
Assert.Single(actual);
Assert.Equal(Certificates.SelfSignedValidWithNoEku.GetNameInfo(X509NameType.EmailName, false), actual.First().Value);
}
}
if (!string.IsNullOrEmpty(Certificates.SelfSignedValidWithNoEku.GetNameInfo(X509NameType.SimpleName, false)))
{
actual = responseAsXml.Elements("claim").Where(claim => claim.Attribute("Type").Value == ClaimTypes.Name);
if (actual.Any())
{
Assert.Single(actual);
Assert.Equal(Certificates.SelfSignedValidWithNoEku.GetNameInfo(X509NameType.SimpleName, false), actual.First().Value);
}
}
if (!string.IsNullOrEmpty(Certificates.SelfSignedValidWithNoEku.GetNameInfo(X509NameType.UpnName, false)))
{
actual = responseAsXml.Elements("claim").Where(claim => claim.Attribute("Type").Value == ClaimTypes.Upn);
if (actual.Any())
{
Assert.Single(actual);
Assert.Equal(Certificates.SelfSignedValidWithNoEku.GetNameInfo(X509NameType.UpnName, false), actual.First().Value);
}
}
if (!string.IsNullOrEmpty(Certificates.SelfSignedValidWithNoEku.GetNameInfo(X509NameType.UrlName, false)))
{
actual = responseAsXml.Elements("claim").Where(claim => claim.Attribute("Type").Value == ClaimTypes.Uri);
if (actual.Any())
{
Assert.Single(actual);
Assert.Equal(Certificates.SelfSignedValidWithNoEku.GetNameInfo(X509NameType.UrlName, false), actual.First().Value);
}
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task VerifyValidationResultCanBeCached(bool cache)
{
const string Expected = "John Doe";
var validationCount = 0;
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
AllowedCertificateTypes = CertificateTypes.SelfSigned,
Events = new CertificateAuthenticationEvents
{
OnCertificateValidated = context =>
{
validationCount++;
// Make sure we get the validated principal
Assert.NotNull(context.Principal);
var claims = new[]
{
new Claim(ClaimTypes.Name, Expected, ClaimValueTypes.String, context.Options.ClaimsIssuer),
new Claim("ValidationCount", validationCount.ToString(CultureInfo.InvariantCulture), ClaimValueTypes.String, context.Options.ClaimsIssuer)
};
context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
context.Success();
return Task.CompletedTask;
}
}
},
Certificates.SelfSignedValidWithNoEku, null, null, false, "", cache);
using var server = host.GetTestServer();
var response = await server.CreateClient().GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
XElement responseAsXml = null;
if (response.Content != null &&
response.Content.Headers.ContentType != null &&
response.Content.Headers.ContentType.MediaType == "text/xml")
{
var responseContent = await response.Content.ReadAsStringAsync();
responseAsXml = XElement.Parse(responseContent);
}
Assert.NotNull(responseAsXml);
var name = responseAsXml.Elements("claim").Where(claim => claim.Attribute("Type").Value == ClaimTypes.Name);
Assert.Single(name);
Assert.Equal(Expected, name.First().Value);
var count = responseAsXml.Elements("claim").Where(claim => claim.Attribute("Type").Value == "ValidationCount");
Assert.Single(count);
Assert.Equal("1", count.First().Value);
// Second request should not trigger validation if caching
response = await server.CreateClient().GetAsync("https://example.com/");
responseAsXml = null;
if (response.Content != null &&
response.Content.Headers.ContentType != null &&
response.Content.Headers.ContentType.MediaType == "text/xml")
{
var responseContent = await response.Content.ReadAsStringAsync();
responseAsXml = XElement.Parse(responseContent);
}
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
name = responseAsXml.Elements("claim").Where(claim => claim.Attribute("Type").Value == ClaimTypes.Name);
Assert.Single(name);
Assert.Equal(Expected, name.First().Value);
count = responseAsXml.Elements("claim").Where(claim => claim.Attribute("Type").Value == "ValidationCount");
Assert.Single(count);
var expected = cache ? "1" : "2";
Assert.Equal(expected, count.First().Value);
}
[Fact]
public async Task VerifyValidationEventPrincipalIsPropogated()
{
const string Expected = "John Doe";
using var host = await CreateHost(
new CertificateAuthenticationOptions
{
AllowedCertificateTypes = CertificateTypes.SelfSigned,
Events = new CertificateAuthenticationEvents
{
OnCertificateValidated = context =>
{
// Make sure we get the validated principal
Assert.NotNull(context.Principal);
var claims = new[]
{
new Claim(ClaimTypes.Name, Expected, ClaimValueTypes.String, context.Options.ClaimsIssuer)
};
context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
context.Success();
return Task.CompletedTask;
}
}
},
Certificates.SelfSignedValidWithNoEku);
using var server = host.GetTestServer();
var response = await server.CreateClient().GetAsync("https://example.com/");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
XElement responseAsXml = null;
if (response.Content != null &&
response.Content.Headers.ContentType != null &&
response.Content.Headers.ContentType.MediaType == "text/xml")
{
var responseContent = await response.Content.ReadAsStringAsync();
responseAsXml = XElement.Parse(responseContent);
}
Assert.NotNull(responseAsXml);
var actual = responseAsXml.Elements("claim").Where(claim => claim.Attribute("Type").Value == ClaimTypes.Name);
Assert.Single(actual);
Assert.Equal(Expected, actual.First().Value);
Assert.Single(responseAsXml.Elements("claim"));
}
private static async Task<IHost> CreateHost(
CertificateAuthenticationOptions configureOptions,
X509Certificate2 clientCertificate = null,
Func<HttpContext, bool> handler = null,
Uri baseAddress = null,
bool wireUpHeaderMiddleware = false,
string headerName = "",
bool useCache = false)
{
var host = new HostBuilder()
.ConfigureWebHost(builder =>
builder.UseTestServer()
.Configure(app =>
{
app.Use((context, next) =>
{
if (clientCertificate != null)
{
context.Connection.ClientCertificate = clientCertificate;
}
return next(context);
});
if (wireUpHeaderMiddleware)
{
app.UseCertificateForwarding();
}
app.UseAuthentication();
app.Run(async (context) =>
{
var request = context.Request;
var response = context.Response;
var authenticationResult = await context.AuthenticateAsync();
if (authenticationResult.Succeeded)
{
response.StatusCode = (int)HttpStatusCode.OK;
response.ContentType = "text/xml";
await response.WriteAsync("<claims>");
foreach (Claim claim in context.User.Claims)
{
await response.WriteAsync($"<claim Type=\"{claim.Type}\" Issuer=\"{claim.Issuer}\">{claim.Value}</claim>");
}
await response.WriteAsync("</claims>");
}
else
{
await context.ChallengeAsync();
}
});
})
.ConfigureServices(services =>
{
AuthenticationBuilder authBuilder;
if (configureOptions != null)
{
authBuilder = services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme).AddCertificate(options =>
{
options.CustomTrustStore = configureOptions.CustomTrustStore;
options.ChainTrustValidationMode = configureOptions.ChainTrustValidationMode;
options.AllowedCertificateTypes = configureOptions.AllowedCertificateTypes;
options.Events = configureOptions.Events;
options.ValidateCertificateUse = configureOptions.ValidateCertificateUse;
options.RevocationFlag = configureOptions.RevocationFlag;
options.RevocationMode = configureOptions.RevocationMode;
options.ValidateValidityPeriod = configureOptions.ValidateValidityPeriod;
options.AdditionalChainCertificates = configureOptions.AdditionalChainCertificates;
});
}
else
{
authBuilder = services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme).AddCertificate();
}
if (useCache)
{
authBuilder.AddCertificateCache();
}
if (wireUpHeaderMiddleware && !string.IsNullOrEmpty(headerName))
{
services.AddCertificateForwarding(options =>
{
options.CertificateHeader = headerName;
});
}
}))
.Build();
await host.StartAsync();
var server = host.GetTestServer();
server.BaseAddress = baseAddress;
return host;
}
private readonly CertificateAuthenticationEvents successfulValidationEvents = new CertificateAuthenticationEvents()
{
OnCertificateValidated = context =>
{
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, context.ClientCertificate.Subject, ClaimValueTypes.String, context.Options.ClaimsIssuer),
new Claim(ClaimTypes.Name, context.ClientCertificate.Subject, ClaimValueTypes.String, context.Options.ClaimsIssuer)
};
context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
context.Success();
return Task.CompletedTask;
}
};
private readonly CertificateAuthenticationEvents failedValidationEvents = new CertificateAuthenticationEvents()
{
OnCertificateValidated = context =>
{
context.Fail("Not validated");
return Task.CompletedTask;
}
};
private readonly CertificateAuthenticationEvents unprocessedValidationEvents = new CertificateAuthenticationEvents()
{
OnCertificateValidated = context =>
{
return Task.CompletedTask;
}
};
private static class Certificates
{
public static X509Certificate2 SelfSignedPrimaryRoot { get; private set; } =
new X509Certificate2(GetFullyQualifiedFilePath("validSelfSignedPrimaryRootCertificate.cer"));
public static X509Certificate2 SignedSecondaryRoot { get; private set; } =
new X509Certificate2(GetFullyQualifiedFilePath("validSignedSecondaryRootCertificate.cer"));
public static X509Certificate2 SignedClient { get; private set; } =
new X509Certificate2(GetFullyQualifiedFilePath("validSignedClientCertificate.cer"));
public static X509Certificate2 SelfSignedValidWithClientEku { get; private set; } =
new X509Certificate2(GetFullyQualifiedFilePath("validSelfSignedClientEkuCertificate.cer"));
public static X509Certificate2 SelfSignedValidWithNoEku { get; private set; } =
new X509Certificate2(GetFullyQualifiedFilePath("validSelfSignedNoEkuCertificate.cer"));
public static X509Certificate2 SelfSignedValidWithServerEku { get; private set; } =
new X509Certificate2(GetFullyQualifiedFilePath("validSelfSignedServerEkuCertificate.cer"));
public static X509Certificate2 SelfSignedNotYetValid { get; private set; } =
new X509Certificate2(GetFullyQualifiedFilePath("selfSignedNoEkuCertificateNotValidYet.cer"));
public static X509Certificate2 SelfSignedExpired { get; private set; } =
new X509Certificate2(GetFullyQualifiedFilePath("selfSignedNoEkuCertificateExpired.cer"));
private static string GetFullyQualifiedFilePath(string filename)
{
var filePath = Path.Combine(AppContext.BaseDirectory, filename);
if (!File.Exists(filePath))
{
throw new FileNotFoundException(filePath);
}
return filePath;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Authentication.ExtendedProtection;
namespace System.Net.Security
{
//
// Used when working with SSPI APIs, like SafeSspiAuthDataHandle(). Holds the pointer to the auth data blob.
//
#if DEBUG
internal sealed class SafeSspiAuthDataHandle : DebugSafeHandle
{
#else
internal sealed class SafeSspiAuthDataHandle : SafeHandleZeroOrMinusOneIsInvalid
{
#endif
public SafeSspiAuthDataHandle() : base(true)
{
}
protected override bool ReleaseHandle()
{
return Interop.SspiCli.SspiFreeAuthIdentity(handle) == Interop.SecurityStatus.OK;
}
}
//
// A set of Safe Handles that depend on native FreeContextBuffer finalizer.
//
#if DEBUG
internal abstract class SafeFreeContextBuffer : DebugSafeHandle
{
#else
internal abstract class SafeFreeContextBuffer : SafeHandleZeroOrMinusOneIsInvalid
{
#endif
protected SafeFreeContextBuffer() : base(true) { }
// This must be ONLY called from this file.
internal void Set(IntPtr value)
{
this.handle = value;
}
internal static int EnumeratePackages(out int pkgnum, out SafeFreeContextBuffer pkgArray)
{
int res = -1;
SafeFreeContextBuffer_SECURITY pkgArray_SECURITY = null;
res = Interop.SspiCli.EnumerateSecurityPackagesW(out pkgnum, out pkgArray_SECURITY);
pkgArray = pkgArray_SECURITY;
if (res != 0 && pkgArray != null)
{
pkgArray.SetHandleAsInvalid();
}
return res;
}
internal static SafeFreeContextBuffer CreateEmptyHandle()
{
return new SafeFreeContextBuffer_SECURITY();
}
//
// After PInvoke call the method will fix the refHandle.handle with the returned value.
// The caller is responsible for creating a correct SafeHandle template or null can be passed if no handle is returned.
//
// This method switches between three non-interruptible helper methods. (This method can't be both non-interruptible and
// reference imports from all three DLLs - doing so would cause all three DLLs to try to be bound to.)
//
public unsafe static int QueryContextAttributes(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, byte* buffer, SafeHandle refHandle)
{
return QueryContextAttributes_SECURITY(phContext, contextAttribute, buffer, refHandle);
}
private unsafe static int QueryContextAttributes_SECURITY(
SafeDeleteContext phContext,
Interop.SspiCli.ContextAttribute contextAttribute,
byte* buffer,
SafeHandle refHandle)
{
int status = (int)Interop.SecurityStatus.InvalidHandle;
try
{
bool ignore = false;
phContext.DangerousAddRef(ref ignore);
status = Interop.SspiCli.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer);
}
finally
{
phContext.DangerousRelease();
}
if (status == 0 && refHandle != null)
{
if (refHandle is SafeFreeContextBuffer)
{
((SafeFreeContextBuffer)refHandle).Set(*(IntPtr*)buffer);
}
else
{
((SafeFreeCertContext)refHandle).Set(*(IntPtr*)buffer);
}
}
if (status != 0 && refHandle != null)
{
refHandle.SetHandleAsInvalid();
}
return status;
}
public static int SetContextAttributes(
SafeDeleteContext phContext,
Interop.SspiCli.ContextAttribute contextAttribute, byte[] buffer)
{
return SetContextAttributes_SECURITY(phContext, contextAttribute, buffer);
}
private static int SetContextAttributes_SECURITY(
SafeDeleteContext phContext,
Interop.SspiCli.ContextAttribute contextAttribute,
byte[] buffer)
{
try
{
bool ignore = false;
phContext.DangerousAddRef(ref ignore);
return Interop.SspiCli.SetContextAttributesW(ref phContext._handle, contextAttribute, buffer, buffer.Length);
}
finally
{
phContext.DangerousRelease();
}
}
}
internal sealed class SafeFreeContextBuffer_SECURITY : SafeFreeContextBuffer
{
internal SafeFreeContextBuffer_SECURITY() : base() { }
protected override bool ReleaseHandle()
{
return Interop.SspiCli.FreeContextBuffer(handle) == 0;
}
}
//
// Implementation of handles required CertFreeCertificateContext
//
#if DEBUG
internal sealed class SafeFreeCertContext : DebugSafeHandle
{
#else
internal sealed class SafeFreeCertContext : SafeHandleZeroOrMinusOneIsInvalid
{
#endif
internal SafeFreeCertContext() : base(true) { }
// This must be ONLY called from this file.
internal void Set(IntPtr value)
{
this.handle = value;
}
private const uint CRYPT_ACQUIRE_SILENT_FLAG = 0x00000040;
protected override bool ReleaseHandle()
{
Interop.Crypt32.CertFreeCertificateContext(handle);
return true;
}
}
//
// Implementation of handles dependable on FreeCredentialsHandle
//
#if DEBUG
internal abstract class SafeFreeCredentials : DebugSafeHandle
{
#else
internal abstract class SafeFreeCredentials : SafeHandle
{
#endif
internal Interop.SspiCli.SSPIHandle _handle; //should be always used as by ref in PInvokes parameters
protected SafeFreeCredentials() : base(IntPtr.Zero, true)
{
_handle = new Interop.SspiCli.SSPIHandle();
}
#if TRACE_VERBOSE
public override string ToString()
{
return "0x" + _handle.ToString();
}
#endif
public override bool IsInvalid
{
get { return IsClosed || _handle.IsZero; }
}
#if DEBUG
public new IntPtr DangerousGetHandle()
{
Debug.Fail("This method should never be called for this type");
throw NotImplemented.ByDesign;
}
#endif
public unsafe static int AcquireCredentialsHandle(
string package,
Interop.SspiCli.CredentialUse intent,
ref Interop.SspiCli.AuthIdentity authdata,
out SafeFreeCredentials outCredential)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SafeFreeCredentials::AcquireCredentialsHandle#1("
+ package + ", "
+ intent + ", "
+ authdata + ")");
}
int errorCode = -1;
long timeStamp;
outCredential = new SafeFreeCredential_SECURITY();
errorCode = Interop.SspiCli.AcquireCredentialsHandleW(
null,
package,
(int)intent,
null,
ref authdata,
null,
null,
ref outCredential._handle,
out timeStamp);
#if TRACE_VERBOSE
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("Unmanaged::AcquireCredentialsHandle() returns 0x"
+ String.Format("{0:x}", errorCode)
+ ", handle = " + outCredential.ToString());
}
#endif
if (errorCode != 0)
{
outCredential.SetHandleAsInvalid();
}
return errorCode;
}
public unsafe static int AcquireDefaultCredential(
string package,
Interop.SspiCli.CredentialUse intent,
out SafeFreeCredentials outCredential)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SafeFreeCredentials::AcquireDefaultCredential("
+ package + ", "
+ intent + ")");
}
int errorCode = -1;
long timeStamp;
outCredential = new SafeFreeCredential_SECURITY();
errorCode = Interop.SspiCli.AcquireCredentialsHandleW(
null,
package,
(int)intent,
null,
IntPtr.Zero,
null,
null,
ref outCredential._handle,
out timeStamp);
#if TRACE_VERBOSE
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("Unmanaged::AcquireCredentialsHandle() returns 0x"
+ errorCode.ToString("x")
+ ", handle = " + outCredential.ToString());
}
#endif
if (errorCode != 0)
{
outCredential.SetHandleAsInvalid();
}
return errorCode;
}
public unsafe static int AcquireCredentialsHandle(
string package,
Interop.SspiCli.CredentialUse intent,
ref SafeSspiAuthDataHandle authdata,
out SafeFreeCredentials outCredential)
{
int errorCode = -1;
long timeStamp;
outCredential = new SafeFreeCredential_SECURITY();
errorCode = Interop.SspiCli.AcquireCredentialsHandleW(
null,
package,
(int)intent,
null,
authdata,
null,
null,
ref outCredential._handle,
out timeStamp);
if (errorCode != 0)
{
outCredential.SetHandleAsInvalid();
}
return errorCode;
}
public unsafe static int AcquireCredentialsHandle(
string package,
Interop.SspiCli.CredentialUse intent,
ref Interop.SspiCli.SecureCredential authdata,
out SafeFreeCredentials outCredential)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SafeFreeCredentials::AcquireCredentialsHandle#2("
+ package + ", "
+ intent + ", "
+ authdata + ")");
}
int errorCode = -1;
long timeStamp;
// If there is a certificate, wrap it into an array.
// Not threadsafe.
IntPtr copiedPtr = authdata.certContextArray;
try
{
IntPtr certArrayPtr = new IntPtr(&copiedPtr);
if (copiedPtr != IntPtr.Zero)
{
authdata.certContextArray = certArrayPtr;
}
outCredential = new SafeFreeCredential_SECURITY();
errorCode = Interop.SspiCli.AcquireCredentialsHandleW(
null,
package,
(int)intent,
null,
ref authdata,
null,
null,
ref outCredential._handle,
out timeStamp);
}
finally
{
authdata.certContextArray = copiedPtr;
}
#if TRACE_VERBOSE
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("Unmanaged::AcquireCredentialsHandle() returns 0x"
+ errorCode.ToString("x")
+ ", handle = " + outCredential.ToString());
}
#endif
if (errorCode != 0)
{
outCredential.SetHandleAsInvalid();
}
return errorCode;
}
}
//
// This is a class holding a Credential handle reference, used for static handles cache
//
#if DEBUG
internal sealed class SafeCredentialReference : DebugCriticalHandleMinusOneIsInvalid
{
#else
internal sealed class SafeCredentialReference : CriticalHandleMinusOneIsInvalid
{
#endif
//
// Static cache will return the target handle if found the reference in the table.
//
internal SafeFreeCredentials Target;
internal static SafeCredentialReference CreateReference(SafeFreeCredentials target)
{
SafeCredentialReference result = new SafeCredentialReference(target);
if (result.IsInvalid)
{
return null;
}
return result;
}
private SafeCredentialReference(SafeFreeCredentials target) : base()
{
// Bumps up the refcount on Target to signify that target handle is statically cached so
// its dispose should be postponed
bool ignore = false;
target.DangerousAddRef(ref ignore);
Target = target;
SetHandle(new IntPtr(0)); // make this handle valid
}
protected override bool ReleaseHandle()
{
SafeFreeCredentials target = Target;
if (target != null)
{
target.DangerousRelease();
}
Target = null;
return true;
}
}
internal sealed class SafeFreeCredential_SECURITY : SafeFreeCredentials
{
public SafeFreeCredential_SECURITY() : base() { }
protected override bool ReleaseHandle()
{
return Interop.SspiCli.FreeCredentialsHandle(ref _handle) == 0;
}
}
//
// Implementation of handles that are dependent on DeleteSecurityContext
//
#if DEBUG
internal abstract class SafeDeleteContext : DebugSafeHandle
{
#else
internal abstract class SafeDeleteContext : SafeHandle
{
#endif
private const string dummyStr = " ";
private static readonly byte[] s_dummyBytes = new byte[] { 0 };
//
// ATN: _handle is internal since it is used on PInvokes by other wrapper methods.
// However all such wrappers MUST manually and reliably adjust refCounter of SafeDeleteContext handle.
//
internal Interop.SspiCli.SSPIHandle _handle;
protected SafeFreeCredentials _EffectiveCredential;
protected SafeDeleteContext() : base(IntPtr.Zero, true)
{
_handle = new Interop.SspiCli.SSPIHandle();
}
public override bool IsInvalid
{
get
{
return IsClosed || _handle.IsZero;
}
}
public override string ToString()
{
return _handle.ToString();
}
#if DEBUG
//This method should never be called for this type
public new IntPtr DangerousGetHandle()
{
throw new InvalidOperationException();
}
#endif
//-------------------------------------------------------------------
internal unsafe static int InitializeSecurityContext(
ref SafeFreeCredentials inCredentials,
ref SafeDeleteContext refContext,
string targetName,
Interop.SspiCli.ContextFlags inFlags,
Interop.SspiCli.Endianness endianness,
SecurityBuffer inSecBuffer,
SecurityBuffer[] inSecBuffers,
SecurityBuffer outSecBuffer,
ref Interop.SspiCli.ContextFlags outFlags)
{
#if TRACE_VERBOSE
if (GlobalLog.IsEnabled)
{
GlobalLog.Enter("SafeDeleteContext::InitializeSecurityContext");
GlobalLog.Print(" credential = " + inCredentials.ToString());
GlobalLog.Print(" refContext = " + LoggingHash.ObjectToString(refContext));
GlobalLog.Print(" targetName = " + targetName);
GlobalLog.Print(" inFlags = " + inFlags);
GlobalLog.Print(" reservedI = 0x0");
GlobalLog.Print(" endianness = " + endianness);
if (inSecBuffers == null)
{
GlobalLog.Print(" inSecBuffers = (null)");
}
else
{
GlobalLog.Print(" inSecBuffers[] = length:" + inSecBuffers.Length);
}
}
#endif
if (outSecBuffer == null)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("SafeDeleteContext::InitializeSecurityContext()|outSecBuffer != null");
}
Debug.Fail("SafeDeleteContext::InitializeSecurityContext()|outSecBuffer != null");
}
if (inSecBuffer != null && inSecBuffers != null)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("SafeDeleteContext::InitializeSecurityContext()|inSecBuffer == null || inSecBuffers == null");
}
Debug.Fail("SafeDeleteContext::InitializeSecurityContext()|inSecBuffer == null || inSecBuffers == null");
}
if (inCredentials == null)
{
throw new ArgumentNullException(nameof(inCredentials));
}
Interop.SspiCli.SecurityBufferDescriptor inSecurityBufferDescriptor = null;
if (inSecBuffer != null)
{
inSecurityBufferDescriptor = new Interop.SspiCli.SecurityBufferDescriptor(1);
}
else if (inSecBuffers != null)
{
inSecurityBufferDescriptor = new Interop.SspiCli.SecurityBufferDescriptor(inSecBuffers.Length);
}
Interop.SspiCli.SecurityBufferDescriptor outSecurityBufferDescriptor = new Interop.SspiCli.SecurityBufferDescriptor(1);
// Actually, this is returned in outFlags.
bool isSspiAllocated = (inFlags & Interop.SspiCli.ContextFlags.AllocateMemory) != 0 ? true : false;
int errorCode = -1;
Interop.SspiCli.SSPIHandle contextHandle = new Interop.SspiCli.SSPIHandle();
if (refContext != null)
{
contextHandle = refContext._handle;
}
// These are pinned user byte arrays passed along with SecurityBuffers.
GCHandle[] pinnedInBytes = null;
GCHandle pinnedOutBytes = new GCHandle();
// Optional output buffer that may need to be freed.
SafeFreeContextBuffer outFreeContextBuffer = null;
try
{
pinnedOutBytes = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned);
Interop.SspiCli.SecurityBufferStruct[] inUnmanagedBuffer = new Interop.SspiCli.SecurityBufferStruct[inSecurityBufferDescriptor == null ? 1 : inSecurityBufferDescriptor.Count];
fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer)
{
if (inSecurityBufferDescriptor != null)
{
// Fix Descriptor pointer that points to unmanaged SecurityBuffers.
inSecurityBufferDescriptor.UnmanagedPointer = inUnmanagedBufferPtr;
pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.Count];
SecurityBuffer securityBuffer;
for (int index = 0; index < inSecurityBufferDescriptor.Count; ++index)
{
securityBuffer = inSecBuffer != null ? inSecBuffer : inSecBuffers[index];
if (securityBuffer != null)
{
// Copy the SecurityBuffer content into unmanaged place holder.
inUnmanagedBuffer[index].count = securityBuffer.size;
inUnmanagedBuffer[index].type = securityBuffer.type;
// Use the unmanaged token if it's not null; otherwise use the managed buffer.
if (securityBuffer.unmanagedToken != null)
{
inUnmanagedBuffer[index].token = securityBuffer.unmanagedToken.DangerousGetHandle();
}
else if (securityBuffer.token == null || securityBuffer.token.Length == 0)
{
inUnmanagedBuffer[index].token = IntPtr.Zero;
}
else
{
pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned);
inUnmanagedBuffer[index].token = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset);
}
#if TRACE_VERBOSE
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SecBuffer: cbBuffer:" + securityBuffer.size + " BufferType:" + securityBuffer.type);
}
#endif
}
}
}
Interop.SspiCli.SecurityBufferStruct[] outUnmanagedBuffer = new Interop.SspiCli.SecurityBufferStruct[1];
fixed (void* outUnmanagedBufferPtr = outUnmanagedBuffer)
{
// Fix Descriptor pointer that points to unmanaged SecurityBuffers.
outSecurityBufferDescriptor.UnmanagedPointer = outUnmanagedBufferPtr;
outUnmanagedBuffer[0].count = outSecBuffer.size;
outUnmanagedBuffer[0].type = outSecBuffer.type;
if (outSecBuffer.token == null || outSecBuffer.token.Length == 0)
{
outUnmanagedBuffer[0].token = IntPtr.Zero;
}
else
{
outUnmanagedBuffer[0].token = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset);
}
if (isSspiAllocated)
{
outFreeContextBuffer = SafeFreeContextBuffer.CreateEmptyHandle();
}
if (refContext == null || refContext.IsInvalid)
{
refContext = new SafeDeleteContext_SECURITY();
}
if (targetName == null || targetName.Length == 0)
{
targetName = dummyStr;
}
fixed (char* namePtr = targetName)
{
errorCode = MustRunInitializeSecurityContext_SECURITY(
ref inCredentials,
contextHandle.IsZero ? null : &contextHandle,
(byte*)(((object)targetName == (object)dummyStr) ? null : namePtr),
inFlags,
endianness,
inSecurityBufferDescriptor,
refContext,
outSecurityBufferDescriptor,
ref outFlags,
outFreeContextBuffer);
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SafeDeleteContext:InitializeSecurityContext Marshalling OUT buffer");
}
// Get unmanaged buffer with index 0 as the only one passed into PInvoke.
outSecBuffer.size = outUnmanagedBuffer[0].count;
outSecBuffer.type = outUnmanagedBuffer[0].type;
if (outSecBuffer.size > 0)
{
outSecBuffer.token = new byte[outSecBuffer.size];
Marshal.Copy(outUnmanagedBuffer[0].token, outSecBuffer.token, 0, outSecBuffer.size);
}
else
{
outSecBuffer.token = null;
}
}
}
}
finally
{
if (pinnedInBytes != null)
{
for (int index = 0; index < pinnedInBytes.Length; index++)
{
if (pinnedInBytes[index].IsAllocated)
{
pinnedInBytes[index].Free();
}
}
}
if (pinnedOutBytes.IsAllocated)
{
pinnedOutBytes.Free();
}
if (outFreeContextBuffer != null)
{
outFreeContextBuffer.Dispose();
}
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Leave("SafeDeleteContext::InitializeSecurityContext() unmanaged InitializeSecurityContext()", "errorCode:0x" + errorCode.ToString("x8") + " refContext:" + LoggingHash.ObjectToString(refContext));
}
return errorCode;
}
//
// After PInvoke call the method will fix the handleTemplate.handle with the returned value.
// The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavor or null can be passed if no handle is returned.
//
private static unsafe int MustRunInitializeSecurityContext_SECURITY(
ref SafeFreeCredentials inCredentials,
void* inContextPtr,
byte* targetName,
Interop.SspiCli.ContextFlags inFlags,
Interop.SspiCli.Endianness endianness,
Interop.SspiCli.SecurityBufferDescriptor inputBuffer,
SafeDeleteContext outContext,
Interop.SspiCli.SecurityBufferDescriptor outputBuffer,
ref Interop.SspiCli.ContextFlags attributes,
SafeFreeContextBuffer handleTemplate)
{
int errorCode = (int)Interop.SecurityStatus.InvalidHandle;
try
{
bool ignore = false;
inCredentials.DangerousAddRef(ref ignore);
outContext.DangerousAddRef(ref ignore);
Interop.SspiCli.SSPIHandle credentialHandle = inCredentials._handle;
long timeStamp;
errorCode = Interop.SspiCli.InitializeSecurityContextW(
ref credentialHandle,
inContextPtr,
targetName,
inFlags,
0,
endianness,
inputBuffer,
0,
ref outContext._handle,
outputBuffer,
ref attributes,
out timeStamp);
}
finally
{
//
// When a credential handle is first associated with the context we keep credential
// ref count bumped up to ensure ordered finalization.
// If the credential handle has been changed we de-ref the old one and associate the
// context with the new cred handle but only if the call was successful.
if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0)
{
// Disassociate the previous credential handle
if (outContext._EffectiveCredential != null)
{
outContext._EffectiveCredential.DangerousRelease();
}
outContext._EffectiveCredential = inCredentials;
}
else
{
inCredentials.DangerousRelease();
}
outContext.DangerousRelease();
}
// The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer.
if (handleTemplate != null)
{
//ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes
handleTemplate.Set(((Interop.SspiCli.SecurityBufferStruct*)outputBuffer.UnmanagedPointer)->token);
if (handleTemplate.IsInvalid)
{
handleTemplate.SetHandleAsInvalid();
}
}
if (inContextPtr == null && (errorCode & 0x80000000) != 0)
{
// an error on the first call, need to set the out handle to invalid value
outContext._handle.SetToInvalid();
}
return errorCode;
}
//-------------------------------------------------------------------
internal unsafe static int AcceptSecurityContext(
ref SafeFreeCredentials inCredentials,
ref SafeDeleteContext refContext,
Interop.SspiCli.ContextFlags inFlags,
Interop.SspiCli.Endianness endianness,
SecurityBuffer inSecBuffer,
SecurityBuffer[] inSecBuffers,
SecurityBuffer outSecBuffer,
ref Interop.SspiCli.ContextFlags outFlags)
{
#if TRACE_VERBOSE
if (GlobalLog.IsEnabled)
{
GlobalLog.Enter("SafeDeleteContext::AcceptSecurityContex");
GlobalLog.Print(" credential = " + inCredentials.ToString());
GlobalLog.Print(" refContext = " + LoggingHash.ObjectToString(refContext));
GlobalLog.Print(" inFlags = " + inFlags);
if (inSecBuffers == null)
{
GlobalLog.Print(" inSecBuffers = (null)");
}
else
{
GlobalLog.Print(" inSecBuffers[] = length:" + inSecBuffers.Length);
}
}
#endif
if (outSecBuffer == null)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("SafeDeleteContext::AcceptSecurityContext()|outSecBuffer != null");
}
Debug.Fail("SafeDeleteContext::AcceptSecurityContext()|outSecBuffer != null");
}
if (inSecBuffer != null && inSecBuffers != null)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("SafeDeleteContext::AcceptSecurityContext()|inSecBuffer == null || inSecBuffers == null");
}
Debug.Fail("SafeDeleteContext::AcceptSecurityContext()|inSecBuffer == null || inSecBuffers == null");
}
if (inCredentials == null)
{
throw new ArgumentNullException(nameof(inCredentials));
}
Interop.SspiCli.SecurityBufferDescriptor inSecurityBufferDescriptor = null;
if (inSecBuffer != null)
{
inSecurityBufferDescriptor = new Interop.SspiCli.SecurityBufferDescriptor(1);
}
else if (inSecBuffers != null)
{
inSecurityBufferDescriptor = new Interop.SspiCli.SecurityBufferDescriptor(inSecBuffers.Length);
}
Interop.SspiCli.SecurityBufferDescriptor outSecurityBufferDescriptor = new Interop.SspiCli.SecurityBufferDescriptor(1);
// Actually, this is returned in outFlags.
bool isSspiAllocated = (inFlags & Interop.SspiCli.ContextFlags.AllocateMemory) != 0 ? true : false;
int errorCode = -1;
Interop.SspiCli.SSPIHandle contextHandle = new Interop.SspiCli.SSPIHandle();
if (refContext != null)
{
contextHandle = refContext._handle;
}
// These are pinned user byte arrays passed along with SecurityBuffers.
GCHandle[] pinnedInBytes = null;
GCHandle pinnedOutBytes = new GCHandle();
// Optional output buffer that may need to be freed.
SafeFreeContextBuffer outFreeContextBuffer = null;
try
{
pinnedOutBytes = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned);
var inUnmanagedBuffer = new Interop.SspiCli.SecurityBufferStruct[inSecurityBufferDescriptor == null ? 1 : inSecurityBufferDescriptor.Count];
fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer)
{
if (inSecurityBufferDescriptor != null)
{
// Fix Descriptor pointer that points to unmanaged SecurityBuffers.
inSecurityBufferDescriptor.UnmanagedPointer = inUnmanagedBufferPtr;
pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.Count];
SecurityBuffer securityBuffer;
for (int index = 0; index < inSecurityBufferDescriptor.Count; ++index)
{
securityBuffer = inSecBuffer != null ? inSecBuffer : inSecBuffers[index];
if (securityBuffer != null)
{
// Copy the SecurityBuffer content into unmanaged place holder.
inUnmanagedBuffer[index].count = securityBuffer.size;
inUnmanagedBuffer[index].type = securityBuffer.type;
// Use the unmanaged token if it's not null; otherwise use the managed buffer.
if (securityBuffer.unmanagedToken != null)
{
inUnmanagedBuffer[index].token = securityBuffer.unmanagedToken.DangerousGetHandle();
}
else if (securityBuffer.token == null || securityBuffer.token.Length == 0)
{
inUnmanagedBuffer[index].token = IntPtr.Zero;
}
else
{
pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned);
inUnmanagedBuffer[index].token = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset);
}
#if TRACE_VERBOSE
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SecBuffer: cbBuffer:" + securityBuffer.size + " BufferType:" + securityBuffer.type);
}
#endif
}
}
}
var outUnmanagedBuffer = new Interop.SspiCli.SecurityBufferStruct[1];
fixed (void* outUnmanagedBufferPtr = outUnmanagedBuffer)
{
// Fix Descriptor pointer that points to unmanaged SecurityBuffers.
outSecurityBufferDescriptor.UnmanagedPointer = outUnmanagedBufferPtr;
// Copy the SecurityBuffer content into unmanaged place holder.
outUnmanagedBuffer[0].count = outSecBuffer.size;
outUnmanagedBuffer[0].type = outSecBuffer.type;
if (outSecBuffer.token == null || outSecBuffer.token.Length == 0)
{
outUnmanagedBuffer[0].token = IntPtr.Zero;
}
else
{
outUnmanagedBuffer[0].token = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset);
}
if (isSspiAllocated)
{
outFreeContextBuffer = SafeFreeContextBuffer.CreateEmptyHandle();
}
if (refContext == null || refContext.IsInvalid)
{
refContext = new SafeDeleteContext_SECURITY();
}
errorCode = MustRunAcceptSecurityContext_SECURITY(
ref inCredentials,
contextHandle.IsZero ? null : &contextHandle,
inSecurityBufferDescriptor,
inFlags,
endianness,
refContext,
outSecurityBufferDescriptor,
ref outFlags,
outFreeContextBuffer);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SafeDeleteContext:AcceptSecurityContext Marshalling OUT buffer");
}
// Get unmanaged buffer with index 0 as the only one passed into PInvoke.
outSecBuffer.size = outUnmanagedBuffer[0].count;
outSecBuffer.type = outUnmanagedBuffer[0].type;
if (outSecBuffer.size > 0)
{
outSecBuffer.token = new byte[outSecBuffer.size];
Marshal.Copy(outUnmanagedBuffer[0].token, outSecBuffer.token, 0, outSecBuffer.size);
}
else
{
outSecBuffer.token = null;
}
}
}
}
finally
{
if (pinnedInBytes != null)
{
for (int index = 0; index < pinnedInBytes.Length; index++)
{
if (pinnedInBytes[index].IsAllocated)
{
pinnedInBytes[index].Free();
}
}
}
if (pinnedOutBytes.IsAllocated)
{
pinnedOutBytes.Free();
}
if (outFreeContextBuffer != null)
{
outFreeContextBuffer.Dispose();
}
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Leave("SafeDeleteContext::AcceptSecurityContex() unmanaged AcceptSecurityContex()", "errorCode:0x" + errorCode.ToString("x8") + " refContext:" + LoggingHash.ObjectToString(refContext));
}
return errorCode;
}
//
// After PInvoke call the method will fix the handleTemplate.handle with the returned value.
// The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavor or null can be passed if no handle is returned.
//
private static unsafe int MustRunAcceptSecurityContext_SECURITY(
ref SafeFreeCredentials inCredentials,
void* inContextPtr,
Interop.SspiCli.SecurityBufferDescriptor inputBuffer,
Interop.SspiCli.ContextFlags inFlags,
Interop.SspiCli.Endianness endianness,
SafeDeleteContext outContext,
Interop.SspiCli.SecurityBufferDescriptor outputBuffer,
ref Interop.SspiCli.ContextFlags outFlags,
SafeFreeContextBuffer handleTemplate)
{
int errorCode = (int)Interop.SecurityStatus.InvalidHandle;
// Run the body of this method as a non-interruptible block.
try
{
bool ignore = false;
inCredentials.DangerousAddRef(ref ignore);
outContext.DangerousAddRef(ref ignore);
Interop.SspiCli.SSPIHandle credentialHandle = inCredentials._handle;
long timeStamp;
errorCode = Interop.SspiCli.AcceptSecurityContext(
ref credentialHandle,
inContextPtr,
inputBuffer,
inFlags,
endianness,
ref outContext._handle,
outputBuffer,
ref outFlags,
out timeStamp);
}
finally
{
//
// When a credential handle is first associated with the context we keep credential
// ref count bumped up to ensure ordered finalization.
// If the credential handle has been changed we de-ref the old one and associate the
// context with the new cred handle but only if the call was successful.
if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0)
{
// Disassociate the previous credential handle.
if (outContext._EffectiveCredential != null)
{
outContext._EffectiveCredential.DangerousRelease();
}
outContext._EffectiveCredential = inCredentials;
}
else
{
inCredentials.DangerousRelease();
}
outContext.DangerousRelease();
}
// The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer.
if (handleTemplate != null)
{
//ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes.
handleTemplate.Set(((Interop.SspiCli.SecurityBufferStruct*)outputBuffer.UnmanagedPointer)->token);
if (handleTemplate.IsInvalid)
{
handleTemplate.SetHandleAsInvalid();
}
}
if (inContextPtr == null && (errorCode & 0x80000000) != 0)
{
// An error on the first call, need to set the out handle to invalid value.
outContext._handle.SetToInvalid();
}
return errorCode;
}
internal unsafe static int CompleteAuthToken(
ref SafeDeleteContext refContext,
SecurityBuffer[] inSecBuffers)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Enter("SafeDeleteContext::CompleteAuthToken");
GlobalLog.Print(" refContext = " + LoggingHash.ObjectToString(refContext));
#if TRACE_VERBOSE
GlobalLog.Print(" inSecBuffers[] = length:" + inSecBuffers.Length);
#endif
}
if (inSecBuffers == null)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("SafeDeleteContext::CompleteAuthToken()|inSecBuffers == null");
}
Debug.Fail("SafeDeleteContext::CompleteAuthToken()|inSecBuffers == null");
}
var inSecurityBufferDescriptor = new Interop.SspiCli.SecurityBufferDescriptor(inSecBuffers.Length);
int errorCode = (int)Interop.SecurityStatus.InvalidHandle;
// These are pinned user byte arrays passed along with SecurityBuffers.
GCHandle[] pinnedInBytes = null;
var inUnmanagedBuffer = new Interop.SspiCli.SecurityBufferStruct[inSecurityBufferDescriptor.Count];
fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer)
{
// Fix Descriptor pointer that points to unmanaged SecurityBuffers.
inSecurityBufferDescriptor.UnmanagedPointer = inUnmanagedBufferPtr;
pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.Count];
SecurityBuffer securityBuffer;
for (int index = 0; index < inSecurityBufferDescriptor.Count; ++index)
{
securityBuffer = inSecBuffers[index];
if (securityBuffer != null)
{
inUnmanagedBuffer[index].count = securityBuffer.size;
inUnmanagedBuffer[index].type = securityBuffer.type;
// Use the unmanaged token if it's not null; otherwise use the managed buffer.
if (securityBuffer.unmanagedToken != null)
{
inUnmanagedBuffer[index].token = securityBuffer.unmanagedToken.DangerousGetHandle();
}
else if (securityBuffer.token == null || securityBuffer.token.Length == 0)
{
inUnmanagedBuffer[index].token = IntPtr.Zero;
}
else
{
pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned);
inUnmanagedBuffer[index].token = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset);
}
#if TRACE_VERBOSE
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SecBuffer: cbBuffer:" + securityBuffer.size + " BufferType:" + securityBuffer.type);
}
#endif
}
}
Interop.SspiCli.SSPIHandle contextHandle = new Interop.SspiCli.SSPIHandle();
if (refContext != null)
{
contextHandle = refContext._handle;
}
try
{
if (refContext == null || refContext.IsInvalid)
{
refContext = new SafeDeleteContext_SECURITY();
}
try
{
bool ignore = false;
refContext.DangerousAddRef(ref ignore);
errorCode = Interop.SspiCli.CompleteAuthToken(contextHandle.IsZero ? null : &contextHandle, inSecurityBufferDescriptor);
}
finally
{
refContext.DangerousRelease();
}
}
finally
{
if (pinnedInBytes != null)
{
for (int index = 0; index < pinnedInBytes.Length; index++)
{
if (pinnedInBytes[index].IsAllocated)
{
pinnedInBytes[index].Free();
}
}
}
}
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Leave("SafeDeleteContext::CompleteAuthToken() unmanaged CompleteAuthToken()", "errorCode:0x" + errorCode.ToString("x8") + " refContext:" + LoggingHash.ObjectToString(refContext));
}
return errorCode;
}
}
internal sealed class SafeDeleteContext_SECURITY : SafeDeleteContext
{
internal SafeDeleteContext_SECURITY() : base() { }
protected override bool ReleaseHandle()
{
if (this._EffectiveCredential != null)
{
this._EffectiveCredential.DangerousRelease();
}
return Interop.SspiCli.DeleteSecurityContext(ref _handle) == 0;
}
}
// Based on SafeFreeContextBuffer.
internal abstract class SafeFreeContextBufferChannelBinding : ChannelBinding
{
private int _size;
public override int Size
{
get { return _size; }
}
public override bool IsInvalid
{
get { return handle == new IntPtr(0) || handle == new IntPtr(-1); }
}
internal unsafe void Set(IntPtr value)
{
this.handle = value;
}
internal static SafeFreeContextBufferChannelBinding CreateEmptyHandle()
{
return new SafeFreeContextBufferChannelBinding_SECURITY();
}
public unsafe static int QueryContextChannelBinding(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, Bindings* buffer, SafeFreeContextBufferChannelBinding refHandle)
{
return QueryContextChannelBinding_SECURITY(phContext, contextAttribute, buffer, refHandle);
}
private unsafe static int QueryContextChannelBinding_SECURITY(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, Bindings* buffer, SafeFreeContextBufferChannelBinding refHandle)
{
int status = (int)Interop.SecurityStatus.InvalidHandle;
// SCHANNEL only supports SECPKG_ATTR_ENDPOINT_BINDINGS and SECPKG_ATTR_UNIQUE_BINDINGS which
// map to our enum ChannelBindingKind.Endpoint and ChannelBindingKind.Unique.
if (contextAttribute != Interop.SspiCli.ContextAttribute.EndpointBindings &&
contextAttribute != Interop.SspiCli.ContextAttribute.UniqueBindings)
{
return status;
}
try
{
bool ignore = false;
phContext.DangerousAddRef(ref ignore);
status = Interop.SspiCli.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer);
}
finally
{
phContext.DangerousRelease();
}
if (status == 0 && refHandle != null)
{
refHandle.Set((*buffer).pBindings);
refHandle._size = (*buffer).BindingsLength;
}
if (status != 0 && refHandle != null)
{
refHandle.SetHandleAsInvalid();
}
return status;
}
}
internal sealed class SafeFreeContextBufferChannelBinding_SECURITY : SafeFreeContextBufferChannelBinding
{
protected override bool ReleaseHandle()
{
return Interop.SspiCli.FreeContextBuffer(handle) == 0;
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.ComponentModel;
using Axiom.MathLib;
namespace Multiverse.Tools.WorldEditor
{
public class Tree : IWorldObject, IObjectDelete
{
protected string name;
protected string descriptionFilename;
protected float scale;
protected float scaleVariance;
protected uint instances;
protected WorldEditor app;
protected Forest parent;
protected Axiom.SceneManagers.Multiverse.TreeType sceneTree;
protected bool inScene = false;
protected bool inTree = false;
protected WorldTreeNode node = null;
protected WorldTreeNode parentNode = null;
protected List<ToolStripButton> buttonBar;
public Tree(string name, string descriptionFilename, float scale, float scalevariance, uint instances, Forest parent, WorldEditor app)
{
this.app = app;
this.name = name;
this.parent = parent;
this.descriptionFilename = descriptionFilename;
this.scale = scale;
this.scaleVariance = scalevariance;
this.instances = instances;
}
[BrowsableAttribute(false)]
public string Name
{
get
{
return name;
}
set
{
name = value;
if (inTree)
{
node.Text = name;
}
}
}
[DescriptionAttribute("The type of this object."), CategoryAttribute("Miscellaneous")]
public string ObjectType
{
get
{
return "Tree";
}
}
[TypeConverter(typeof(TreeDescriptionFilenameUITypeEditor)), CategoryAttribute("Miscellaneous"), DescriptionAttribute("Name of the selected SpeedTree file.")]
public string TreeDescriptionFilename
{
get
{
return app.Assets.assetFromAssetName(descriptionFilename).Name;
}
set
{
descriptionFilename = app.Assets.assetFromName(value).AssetName;
if (inScene)
{
this.sceneTree.filename = descriptionFilename;
parent.ForestSemantic.UpdateTreeType();
}
}
}
[BrowsableAttribute(true), CategoryAttribute("Miscellaneous"), DescriptionAttribute("Base size of the trees.")]
public float Scale
{
get
{
return this.scale;
}
set
{
this.scale = value;
if (inScene)
{
sceneTree.size = value;
parent.ForestSemantic.UpdateTreeType();
}
}
}
[BrowsableAttribute(true), CategoryAttribute("Miscellaneous"), DescriptionAttribute("Variance of tree size from the base scale (mm). Tree sizes vary randomly between (Scale - Variance) to (Scale + Variance).")]
public float ScaleVariance
{
get
{
return this.scaleVariance;
}
set
{
this.scaleVariance = value;
if (inScene)
{
sceneTree.sizeVariance = value;
parent.ForestSemantic.UpdateTreeType();
}
}
}
[BrowsableAttribute(true), CategoryAttribute("Miscellaneous"), DescriptionAttribute("Number of trees of this type in the forest.")]
public uint Instances
{
get
{
return this.instances;
}
set
{
this.instances = value;
if (inScene)
{
sceneTree.numInstances = value;
parent.ForestSemantic.UpdateTreeType();
}
}
}
public void ToXml(XmlWriter w)
{
w.WriteStartElement("Tree");
w.WriteAttributeString("Name", name);
w.WriteAttributeString("Filename", descriptionFilename);
w.WriteAttributeString("Scale", scale.ToString());
w.WriteAttributeString("ScaleVariance", scaleVariance.ToString());
w.WriteAttributeString("Instances", instances.ToString());
w.WriteEndElement(); // end Tree
}
public Tree(XmlReader r, Forest parent, WorldEditor worldEditor)
{
this.app = worldEditor;
this.parent = parent;
FromXml(r);
}
protected void FromXml(XmlReader r)
{
// first parse the attributes
for (int i = 0; i < r.AttributeCount; i++)
{
r.MoveToAttribute(i);
// set the field in this object based on the element we just read
switch (r.Name)
{
case "Name":
this.name = r.Value;
break;
case "Filename":
this.descriptionFilename = r.Value;
break;
case "Scale":
this.scale = float.Parse(r.Value);
break;
case "ScaleVariance":
this.scaleVariance = float.Parse(r.Value);
break;
case "Instances":
this.instances = uint.Parse(r.Value);
break;
}
}
r.MoveToElement(); //Moves the reader back to the element node.
}
public void AddToScene()
{
if (!inScene)
{
inScene = true;
sceneTree = new Axiom.SceneManagers.Multiverse.TreeType(descriptionFilename, scale, scaleVariance, instances);
this.parent.ForestSemantic.AddTreeType(sceneTree);
}
}
public void UpdateScene(UpdateTypes type, UpdateHint hint)
{
}
[BrowsableAttribute(false)]
public bool WorldViewSelectable
{
get
{
return false;
}
set
{
// This property is not relevent for this object.
}
}
public void RemoveFromScene()
{
if (inScene)
{
if (this.parent.ForestSemantic != null && this.sceneTree != null)
{
this.parent.ForestSemantic.DeleteTreeType(this.sceneTree);
}
}
inScene = false;
}
public void AddToTree(WorldTreeNode parentNode)
{
this.parentNode = parentNode;
if (!inTree)
{
// create a node for the collection and add it to the parent
this.node = app.MakeTreeNode(this, name);
parentNode.Nodes.Add(node);
// build the menu
CommandMenuBuilder menuBuilder = new CommandMenuBuilder();
menuBuilder.Add("Copy Description", "", app.copyToClipboardMenuButton_Click);
menuBuilder.Add("Help", "Tree_Type", app.HelpClickHandler);
menuBuilder.Add("Delete", new DeleteObjectCommandFactory(app, parent, this), app.DefaultCommandClickHandler);
node.ContextMenuStrip = menuBuilder.Menu;
buttonBar = menuBuilder.ButtonBar;
inTree = true;
}
}
[BrowsableAttribute(false)]
public bool IsGlobal
{
get
{
return false;
}
}
[BrowsableAttribute(false)]
public bool IsTopLevel
{
get
{
return false;
}
}
[BrowsableAttribute(false)]
public bool AcceptObjectPlacement
{
get
{
return false;
}
set
{
//not implemented for this type of object
}
}
public void Clone(IWorldContainer copyParent)
{
Tree clone = new Tree(name, descriptionFilename, scale, scaleVariance, instances, copyParent as Forest, app);
copyParent.Add(clone);
}
[BrowsableAttribute(false)]
public string ObjectAsString
{
get
{
string objString = String.Format("Name:{0}: {1}\r\n", ObjectType, Name);
objString += String.Format("\tTreeDescriptionFilename={0}\r\n",TreeDescriptionFilename);
objString += String.Format("\tScale={0}\r\n",Scale);
objString += String.Format("\tScaleVariance={0}\r\n",ScaleVariance);
objString += String.Format("\tInstances={0}\r\n",Instances);
objString += "\r\n";
return objString;
}
}
[BrowsableAttribute(false)]
public List<ToolStripButton> ButtonBar
{
get
{
return buttonBar;
}
}
public void RemoveFromTree()
{
if (node != null && inTree)
{
if (node.IsSelected)
{
node.UnSelect();
}
parentNode.Nodes.Remove(node);
parentNode = null;
node = null;
}
inTree = false;
}
public void CheckAssets()
{
bool missing = false;
if (!app.CheckAssetFileExists(descriptionFilename))
{
int extOff = descriptionFilename.LastIndexOf('.');
string treName = string.Format("{0}.tre", descriptionFilename.Substring(0, extOff));
if (descriptionFilename != treName)
{
if (!app.CheckAssetFileExists(treName))
{
missing = true;
}
}
else
{
missing = true;
}
}
if (missing)
{
app.AddMissingAsset(descriptionFilename);
}
}
[BrowsableAttribute(false)]
public Vector3 FocusLocation
{
get
{
return this.parent.FocusLocation;
}
}
[BrowsableAttribute(false)]
public bool Highlight
{
get
{
return parent.Highlight;
}
set
{
parent.Highlight = value;
}
}
[BrowsableAttribute(false)]
public WorldTreeNode Node
{
get
{
return node;
}
}
#region IWorldDelete
[BrowsableAttribute(false)]
public IWorldContainer Parent
{
get
{
return parent as IWorldContainer;
}
}
#endregion IWorldDelete
public void ToManifest(System.IO.StreamWriter w)
{
int extIndex = descriptionFilename.LastIndexOf('.');
string basename = descriptionFilename.Substring(0, extIndex);
w.WriteLine("SpeedTree:{0}", basename);
}
public void Dispose()
{
RemoveFromScene();
}
}
}
| |
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 EventFeedback.Web.Api.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
/*
* REST API Documentation for the MOTI School Bus Application
*
* The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using SchoolBusAPI.Models;
namespace SchoolBusAPI.Models
{
/// <summary>
/// The MOTI-defined Districts - must match the official MOTI List
/// </summary>
[MetaDataExtension (Description = "The MOTI-defined Districts - must match the official MOTI List")]
public partial class District : AuditableEntity, IEquatable<District>
{
/// <summary>
/// Default constructor, required by entity framework
/// </summary>
public District()
{
this.Id = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="District" /> class.
/// </summary>
/// <param name="Id">A system-generated unique identifier for a District (required).</param>
/// <param name="MinistryDistrictID">The Ministry ID for the District (required).</param>
/// <param name="Name">The name of the District (required).</param>
/// <param name="Region">The region in which the District is found..</param>
/// <param name="StartDate">The effective date of the District record - NOT CURRENTLY ENFORCED IN SCHOOL BUS.</param>
/// <param name="EndDate">The end date of the District record; null if active - NOT CURRENTLY ENFORCED IN SCHOOL BUS.</param>
public District(int Id, int MinistryDistrictID, string Name, Region Region = null, DateTime? StartDate = null, DateTime? EndDate = null)
{
this.Id = Id;
this.MinistryDistrictID = MinistryDistrictID;
this.Name = Name;
this.Region = Region;
this.StartDate = StartDate;
this.EndDate = EndDate;
}
/// <summary>
/// A system-generated unique identifier for a District
/// </summary>
/// <value>A system-generated unique identifier for a District</value>
[MetaDataExtension (Description = "A system-generated unique identifier for a District")]
public int Id { get; set; }
/// <summary>
/// The Ministry ID for the District
/// </summary>
/// <value>The Ministry ID for the District</value>
[MetaDataExtension (Description = "The Ministry ID for the District")]
public int MinistryDistrictID { get; set; }
/// <summary>
/// The name of the District
/// </summary>
/// <value>The name of the District</value>
[MetaDataExtension (Description = "The name of the District")]
[MaxLength(255)]
public string Name { get; set; }
/// <summary>
/// The region in which the District is found.
/// </summary>
/// <value>The region in which the District is found.</value>
[MetaDataExtension (Description = "The region in which the District is found.")]
public Region Region { get; set; }
/// <summary>
/// Foreign key for Region
/// </summary>
[ForeignKey("Region")]
[JsonIgnore]
[MetaDataExtension (Description = "The region in which the District is found.")]
public int? RegionId { get; set; }
/// <summary>
/// The effective date of the District record - NOT CURRENTLY ENFORCED IN SCHOOL BUS
/// </summary>
/// <value>The effective date of the District record - NOT CURRENTLY ENFORCED IN SCHOOL BUS</value>
[MetaDataExtension (Description = "The effective date of the District record - NOT CURRENTLY ENFORCED IN SCHOOL BUS")]
public DateTime? StartDate { get; set; }
/// <summary>
/// The end date of the District record; null if active - NOT CURRENTLY ENFORCED IN SCHOOL BUS
/// </summary>
/// <value>The end date of the District record; null if active - NOT CURRENTLY ENFORCED IN SCHOOL BUS</value>
[MetaDataExtension (Description = "The end date of the District record; null if active - NOT CURRENTLY ENFORCED IN SCHOOL BUS")]
public DateTime? EndDate { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class District {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" MinistryDistrictID: ").Append(MinistryDistrictID).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Region: ").Append(Region).Append("\n");
sb.Append(" StartDate: ").Append(StartDate).Append("\n");
sb.Append(" EndDate: ").Append(EndDate).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
if (obj.GetType() != GetType()) { return false; }
return Equals((District)obj);
}
/// <summary>
/// Returns true if District instances are equal
/// </summary>
/// <param name="other">Instance of District to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(District other)
{
if (ReferenceEquals(null, other)) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
this.Id == other.Id ||
this.Id.Equals(other.Id)
) &&
(
this.MinistryDistrictID == other.MinistryDistrictID ||
this.MinistryDistrictID.Equals(other.MinistryDistrictID)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Region == other.Region ||
this.Region != null &&
this.Region.Equals(other.Region)
) &&
(
this.StartDate == other.StartDate ||
this.StartDate != null &&
this.StartDate.Equals(other.StartDate)
) &&
(
this.EndDate == other.EndDate ||
this.EndDate != null &&
this.EndDate.Equals(other.EndDate)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks
hash = hash * 59 + this.Id.GetHashCode();
hash = hash * 59 + this.MinistryDistrictID.GetHashCode(); if (this.Name != null)
{
hash = hash * 59 + this.Name.GetHashCode();
}
if (this.Region != null)
{
hash = hash * 59 + this.Region.GetHashCode();
} if (this.StartDate != null)
{
hash = hash * 59 + this.StartDate.GetHashCode();
}
if (this.EndDate != null)
{
hash = hash * 59 + this.EndDate.GetHashCode();
}
return hash;
}
}
#region Operators
/// <summary>
/// Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(District left, District right)
{
return Equals(left, right);
}
/// <summary>
/// Not Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(District left, District right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
// 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.Security;
using Debug = System.Diagnostics.Debug;
using System.Collections.Generic;
using System.Threading;
using System.Runtime.CompilerServices;
using Internal.Runtime.Augments;
using Internal.Runtime.CompilerHelpers;
using Internal.Runtime.CompilerServices;
#if BIT64
using nuint = System.UInt64;
#else
using nuint = System.UInt32;
#endif
namespace System.Runtime.InteropServices
{
/// <summary>
/// This PInvokeMarshal class should provide full public Marshal
/// implementation for all things related to P/Invoke marshalling
/// </summary>
[CLSCompliant(false)]
public partial class PInvokeMarshal
{
[ThreadStatic]
internal static int s_lastWin32Error;
public static int GetLastWin32Error()
{
return s_lastWin32Error;
}
public static void SetLastWin32Error(int errorCode)
{
s_lastWin32Error = errorCode;
}
public static int GetHRForLastWin32Error()
{
int dwLastError = GetLastWin32Error();
if ((dwLastError & 0x80000000) == 0x80000000)
return dwLastError;
else
return (dwLastError & 0x0000FFFF) | unchecked((int)0x80070000);
}
public static unsafe IntPtr AllocHGlobal(IntPtr cb)
{
return MemAlloc(cb);
}
public static unsafe IntPtr AllocHGlobal(int cb)
{
return AllocHGlobal((IntPtr)cb);
}
public static void FreeHGlobal(IntPtr hglobal)
{
MemFree(hglobal);
}
public static unsafe IntPtr AllocCoTaskMem(int cb)
{
IntPtr allocatedMemory = CoTaskMemAlloc(new UIntPtr(unchecked((uint)cb)));
if (allocatedMemory == IntPtr.Zero)
{
throw new OutOfMemoryException();
}
return allocatedMemory;
}
public static void FreeCoTaskMem(IntPtr ptr)
{
CoTaskMemFree(ptr);
}
public static IntPtr SecureStringToGlobalAllocAnsi(SecureString s)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
return s.MarshalToString(globalAlloc: true, unicode: false);
}
public static IntPtr SecureStringToGlobalAllocUnicode(SecureString s)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
return s.MarshalToString(globalAlloc: true, unicode: true); ;
}
public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
return s.MarshalToString(globalAlloc: false, unicode: false);
}
public static IntPtr SecureStringToCoTaskMemUnicode(SecureString s)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
return s.MarshalToString(globalAlloc: false, unicode: true);
}
public static unsafe void CopyToManaged(IntPtr source, Array destination, int startIndex, int length)
{
if (source == IntPtr.Zero)
throw new ArgumentNullException(nameof(source));
if (destination == null)
throw new ArgumentNullException(nameof(destination));
if (!destination.IsBlittable())
throw new ArgumentException(nameof(destination), SR.Arg_CopyNonBlittableArray);
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.Arg_CopyOutOfRange);
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.Arg_CopyOutOfRange);
if ((uint)startIndex + (uint)length > (uint)destination.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.Arg_CopyOutOfRange);
nuint bytesToCopy = (nuint)length * destination.ElementSize;
nuint startOffset = (nuint)startIndex * destination.ElementSize;
fixed (byte* pDestination = &destination.GetRawArrayData())
{
byte* destinationData = pDestination + startOffset;
Buffer.Memmove(destinationData, (byte*)source, bytesToCopy);
}
}
public static unsafe void CopyToNative(Array source, int startIndex, IntPtr destination, int length)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (!source.IsBlittable())
throw new ArgumentException(nameof(source), SR.Arg_CopyNonBlittableArray);
if (destination == IntPtr.Zero)
throw new ArgumentNullException(nameof(destination));
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.Arg_CopyOutOfRange);
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.Arg_CopyOutOfRange);
if ((uint)startIndex + (uint)length > (uint)source.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.Arg_CopyOutOfRange);
nuint bytesToCopy = (nuint)length * source.ElementSize;
nuint startOffset = (nuint)startIndex * source.ElementSize;
fixed (byte* pSource = &source.GetRawArrayData())
{
byte* sourceData = pSource + startOffset;
Buffer.Memmove((byte*)destination, sourceData, bytesToCopy);
}
}
public static unsafe IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index)
{
if (arr == null)
throw new ArgumentNullException(nameof(arr));
byte* p = (byte*)Unsafe.AsPointer(ref arr.GetRawArrayData()) + (nuint)index * arr.ElementSize;
return (IntPtr)p;
}
#region Delegate marshalling
private static object s_thunkPoolHeap;
/// <summary>
/// Return the stub to the pinvoke marshalling stub
/// </summary>
/// <param name="del">The delegate</param>
public static IntPtr GetFunctionPointerForDelegate(Delegate del)
{
if (del == null)
return IntPtr.Zero;
NativeFunctionPointerWrapper fpWrapper = del.Target as NativeFunctionPointerWrapper;
if (fpWrapper != null)
{
//
// Marshalling a delegate created from native function pointer back into function pointer
// This is easy - just return the 'wrapped' native function pointer
//
return fpWrapper.NativeFunctionPointer;
}
else
{
//
// Marshalling a managed delegate created from managed code into a native function pointer
//
return GetPInvokeDelegates().GetValue(del, s_AllocateThunk ?? (s_AllocateThunk = AllocateThunk)).Thunk;
}
}
/// <summary>
/// Used to lookup whether a delegate already has thunk allocated for it
/// </summary>
private static ConditionalWeakTable<Delegate, PInvokeDelegateThunk> s_pInvokeDelegates;
private static ConditionalWeakTable<Delegate, PInvokeDelegateThunk>.CreateValueCallback s_AllocateThunk;
private static ConditionalWeakTable<Delegate, PInvokeDelegateThunk> GetPInvokeDelegates()
{
//
// Create the dictionary on-demand to avoid the dependency in the McgModule.ctor
// Otherwise NUTC will complain that McgModule being eager ctor depends on a deferred
// ctor type
//
if (s_pInvokeDelegates == null)
{
Interlocked.CompareExchange(
ref s_pInvokeDelegates,
new ConditionalWeakTable<Delegate, PInvokeDelegateThunk>(),
null
);
}
return s_pInvokeDelegates;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal unsafe struct ThunkContextData
{
public GCHandle Handle; // A weak GCHandle to the delegate
public IntPtr FunctionPtr; // Function pointer for open static delegates
}
internal sealed class PInvokeDelegateThunk
{
public IntPtr Thunk; // Thunk pointer
public IntPtr ContextData; // ThunkContextData pointer which will be stored in the context slot of the thunk
public PInvokeDelegateThunk(Delegate del)
{
Thunk = RuntimeAugments.AllocateThunk(s_thunkPoolHeap);
Debug.Assert(Thunk != IntPtr.Zero);
if (Thunk == IntPtr.Zero)
{
// We've either run out of memory, or failed to allocate a new thunk due to some other bug. Now we should fail fast
Environment.FailFast("Insufficient number of thunks.");
}
else
{
//
// Allocate unmanaged memory for GCHandle of delegate and function pointer of open static delegate
// We will store this pointer on the context slot of thunk data
//
ContextData = AllocHGlobal(2 * IntPtr.Size);
unsafe
{
ThunkContextData* thunkData = (ThunkContextData*)ContextData;
// allocate a weak GChandle for the delegate
thunkData->Handle = GCHandle.Alloc(del, GCHandleType.Weak);
// if it is an open static delegate get the function pointer
thunkData->FunctionPtr = del.GetRawFunctionPointerForOpenStaticDelegate();
}
}
}
~PInvokeDelegateThunk()
{
// Free the thunk
RuntimeAugments.FreeThunk(s_thunkPoolHeap, Thunk);
unsafe
{
if (ContextData != IntPtr.Zero)
{
// free the GCHandle
GCHandle handle = ((ThunkContextData*)ContextData)->Handle;
if (handle != null)
{
handle.Free();
}
// Free the allocated context data memory
FreeHGlobal(ContextData);
}
}
}
}
private static PInvokeDelegateThunk AllocateThunk(Delegate del)
{
if (s_thunkPoolHeap == null)
{
// TODO: Free s_thunkPoolHeap if the thread lose the race
Interlocked.CompareExchange(
ref s_thunkPoolHeap,
RuntimeAugments.CreateThunksHeap(RuntimeImports.GetInteropCommonStubAddress()),
null
);
Debug.Assert(s_thunkPoolHeap != null);
}
var delegateThunk = new PInvokeDelegateThunk(del);
//
// For open static delegates set target to ReverseOpenStaticDelegateStub which calls the static function pointer directly
//
bool openStaticDelegate = del.GetRawFunctionPointerForOpenStaticDelegate() != IntPtr.Zero;
IntPtr pTarget = RuntimeAugments.InteropCallbacks.GetDelegateMarshallingStub(del.GetTypeHandle(), openStaticDelegate);
Debug.Assert(pTarget != IntPtr.Zero);
RuntimeAugments.SetThunkData(s_thunkPoolHeap, delegateThunk.Thunk, delegateThunk.ContextData, pTarget);
return delegateThunk;
}
/// <summary>
/// Retrieve the corresponding P/invoke instance from the stub
/// </summary>
public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, RuntimeTypeHandle delegateType)
{
if (ptr == IntPtr.Zero)
return null;
//
// First try to see if this is one of the thunks we've allocated when we marshal a managed
// delegate to native code
// s_thunkPoolHeap will be null if there isn't any managed delegate to native
//
IntPtr pContext;
IntPtr pTarget;
if (s_thunkPoolHeap != null && RuntimeAugments.TryGetThunkData(s_thunkPoolHeap, ptr, out pContext, out pTarget))
{
GCHandle handle;
unsafe
{
// Pull out Handle from context
handle = ((ThunkContextData*)pContext)->Handle;
}
Delegate target = Unsafe.As<Delegate>(handle.Target);
//
// The delegate might already been garbage collected
// User should use GC.KeepAlive or whatever ways necessary to keep the delegate alive
// until they are done with the native function pointer
//
if (target == null)
{
Environment.FailFast(SR.Delegate_GarbageCollected);
}
return target;
}
//
// Otherwise, the stub must be a pure native function pointer
// We need to create the delegate that points to the invoke method of a
// NativeFunctionPointerWrapper derived class
//
IntPtr pDelegateCreationStub = RuntimeAugments.InteropCallbacks.GetForwardDelegateCreationStub(delegateType);
Debug.Assert(pDelegateCreationStub != IntPtr.Zero);
return CalliIntrinsics.Call<Delegate>(pDelegateCreationStub, ptr);
}
/// <summary>
/// Retrieves the function pointer for the current open static delegate that is being called
/// </summary>
public static IntPtr GetCurrentCalleeOpenStaticDelegateFunctionPointer()
{
//
// RH keeps track of the current thunk that is being called through a secret argument / thread
// statics. No matter how that's implemented, we get the current thunk which we can use for
// look up later
//
IntPtr pContext = RuntimeImports.GetCurrentInteropThunkContext();
Debug.Assert(pContext != null);
IntPtr fnPtr;
unsafe
{
// Pull out function pointer for open static delegate
fnPtr = ((ThunkContextData*)pContext)->FunctionPtr;
}
Debug.Assert(fnPtr != null);
return fnPtr;
}
/// <summary>
/// Retrieves the current delegate that is being called
/// </summary>
public static T GetCurrentCalleeDelegate<T>() where T : class // constraint can't be System.Delegate
{
//
// RH keeps track of the current thunk that is being called through a secret argument / thread
// statics. No matter how that's implemented, we get the current thunk which we can use for
// look up later
//
IntPtr pContext = RuntimeImports.GetCurrentInteropThunkContext();
Debug.Assert(pContext != null);
GCHandle handle;
unsafe
{
// Pull out Handle from context
handle = ((ThunkContextData*)pContext)->Handle;
}
T target = Unsafe.As<T>(handle.Target);
//
// The delegate might already been garbage collected
// User should use GC.KeepAlive or whatever ways necessary to keep the delegate alive
// until they are done with the native function pointer
//
if (target == null)
{
Environment.FailFast(SR.Delegate_GarbageCollected);
}
return target;
}
[McgIntrinsics]
private static unsafe class CalliIntrinsics
{
internal static T Call<T>(IntPtr pfn, IntPtr arg0) { throw new NotSupportedException(); }
}
#endregion
#region String marshalling
public static unsafe String PtrToStringUni(IntPtr ptr, int len)
{
if (ptr == IntPtr.Zero)
throw new ArgumentNullException(nameof(ptr));
if (len < 0)
throw new ArgumentException(nameof(len));
return new String((char*)ptr, 0, len);
}
public static unsafe String PtrToStringUni(IntPtr ptr)
{
if (IntPtr.Zero == ptr)
{
return null;
}
else if (IsWin32Atom(ptr))
{
return null;
}
else
{
return new String((char*)ptr);
}
}
public static unsafe void StringBuilderToUnicodeString(System.Text.StringBuilder stringBuilder, ushort* destination)
{
stringBuilder.UnsafeCopyTo((char*)destination);
}
public static unsafe void UnicodeStringToStringBuilder(ushort* newBuffer, System.Text.StringBuilder stringBuilder)
{
stringBuilder.ReplaceBuffer((char*)newBuffer);
}
public static unsafe void StringBuilderToAnsiString(System.Text.StringBuilder stringBuilder, byte* pNative,
bool bestFit, bool throwOnUnmappableChar)
{
int len;
// Convert StringBuilder to UNICODE string
// Optimize for the most common case. If there is only a single char[] in the StringBuilder,
// get it and convert it to ANSI
char[] buffer = stringBuilder.GetBuffer(out len);
if (buffer != null)
{
fixed (char* pManaged = buffer)
{
StringToAnsiString(pManaged, len, pNative, /*terminateWithNull=*/true, bestFit, throwOnUnmappableChar);
}
}
else // Otherwise, convert StringBuilder to string and then convert to ANSI
{
string str = stringBuilder.ToString();
// Convert UNICODE string to ANSI string
fixed (char* pManaged = str)
{
StringToAnsiString(pManaged, str.Length, pNative, /*terminateWithNull=*/true, bestFit, throwOnUnmappableChar);
}
}
}
public static unsafe void AnsiStringToStringBuilder(byte* newBuffer, System.Text.StringBuilder stringBuilder)
{
if (newBuffer == null)
throw new ArgumentNullException(nameof(newBuffer));
int lenAnsi;
int lenUnicode;
CalculateStringLength(newBuffer, out lenAnsi, out lenUnicode);
if (lenUnicode > 0)
{
char[] buffer = new char[lenUnicode];
fixed (char* pTemp = &buffer[0])
{
ConvertMultiByteToWideChar(newBuffer,
lenAnsi,
pTemp,
lenUnicode);
}
stringBuilder.ReplaceBuffer(buffer);
}
else
{
stringBuilder.Clear();
}
}
/// <summary>
/// Convert ANSI string to unicode string, with option to free native memory. Calls generated by MCG
/// </summary>
/// <remarks>Input assumed to be zero terminated. Generates String.Empty for zero length string.
/// This version is more efficient than ConvertToUnicode in src\Interop\System\Runtime\InteropServices\Marshal.cs in that it can skip calling
/// MultiByteToWideChar for ASCII string, and it does not need another char[] buffer</remarks>
public static unsafe string AnsiStringToString(byte* pchBuffer)
{
if (pchBuffer == null)
{
return null;
}
int lenAnsi;
int lenUnicode;
CalculateStringLength(pchBuffer, out lenAnsi, out lenUnicode);
string result = String.Empty;
if (lenUnicode > 0)
{
result = string.FastAllocateString(lenUnicode);
fixed (char* pTemp = result)
{
ConvertMultiByteToWideChar(pchBuffer,
lenAnsi,
pTemp,
lenUnicode);
}
}
return result;
}
/// <summary>
/// Convert UNICODE string to ANSI string.
/// </summary>
/// <remarks>This version is more efficient than StringToHGlobalAnsi in Interop\System\Runtime\InteropServices\Marshal.cs in that
/// it could allocate single byte per character, instead of SystemMaxDBCSCharSize per char, and it can skip calling WideCharToMultiByte for ASCII string</remarks>
public static unsafe byte* StringToAnsiString(string str, bool bestFit, bool throwOnUnmappableChar)
{
if (str != null)
{
int lenUnicode = str.Length;
fixed (char* pManaged = str)
{
return StringToAnsiString(pManaged, lenUnicode, null, /*terminateWithNull=*/true, bestFit, throwOnUnmappableChar);
}
}
return null;
}
/// <summary>
/// Convert UNICODE wide char array to ANSI ByVal byte array.
/// </summary>
/// <remarks>
/// * This version works with array instead string, it means that there will be NO NULL to terminate the array.
/// * The buffer to store the byte array must be allocated by the caller and must fit managedArray.Length.
/// </remarks>
/// <param name="managedArray">UNICODE wide char array</param>
/// <param name="pNative">Allocated buffer where the ansi characters must be placed. Could NOT be null. Buffer size must fit char[].Length.</param>
public static unsafe void ByValWideCharArrayToAnsiCharArray(char[] managedArray, byte* pNative, int expectedCharCount,
bool bestFit, bool throwOnUnmappableChar)
{
// Zero-init pNative if it is NULL
if (managedArray == null)
{
Buffer.ZeroMemory((byte*)pNative, expectedCharCount);
return;
}
int lenUnicode = managedArray.Length;
if (lenUnicode < expectedCharCount)
throw new ArgumentException(SR.WrongSizeArrayInNStruct);
fixed (char* pManaged = managedArray)
{
StringToAnsiString(pManaged, lenUnicode, pNative, /*terminateWithNull=*/false, bestFit, throwOnUnmappableChar);
}
}
public static unsafe void ByValAnsiCharArrayToWideCharArray(byte* pNative, char[] managedArray)
{
// This should never happen because it is a embedded array
Debug.Assert(pNative != null);
// This should never happen because the array is always allocated by the marshaller
Debug.Assert(managedArray != null);
// COMPAT: Use the managed array length as the maximum length of native buffer
// This obviously doesn't make sense but desktop CLR does that
int lenInBytes = managedArray.Length;
fixed (char* pManaged = managedArray)
{
ConvertMultiByteToWideChar(pNative,
lenInBytes,
pManaged,
lenInBytes);
}
}
public static unsafe void WideCharArrayToAnsiCharArray(char[] managedArray, byte* pNative, bool bestFit, bool throwOnUnmappableChar)
{
// Do nothing if array is NULL. This matches desktop CLR behavior
if (managedArray == null)
return;
// Desktop CLR crash (AV at runtime) - we can do better in .NET Native
if (pNative == null)
throw new ArgumentNullException(nameof(pNative));
int lenUnicode = managedArray.Length;
fixed (char* pManaged = managedArray)
{
StringToAnsiString(pManaged, lenUnicode, pNative, /*terminateWithNull=*/false, bestFit, throwOnUnmappableChar);
}
}
/// <summary>
/// Convert ANSI ByVal byte array to UNICODE wide char array, best fit
/// </summary>
/// <remarks>
/// * This version works with array instead to string, it means that the len must be provided and there will be NO NULL to
/// terminate the array.
/// * The buffer to the UNICODE wide char array must be allocated by the caller.
/// </remarks>
/// <param name="pNative">Pointer to the ANSI byte array. Could NOT be null.</param>
/// <param name="lenInBytes">Maximum buffer size.</param>
/// <param name="managedArray">Wide char array that has already been allocated.</param>
public static unsafe void AnsiCharArrayToWideCharArray(byte* pNative, char[] managedArray)
{
// Do nothing if native is NULL. This matches desktop CLR behavior
if (pNative == null)
return;
// Desktop CLR crash (AV at runtime) - we can do better in .NET Native
if (managedArray == null)
throw new ArgumentNullException(nameof(managedArray));
// COMPAT: Use the managed array length as the maximum length of native buffer
// This obviously doesn't make sense but desktop CLR does that
int lenInBytes = managedArray.Length;
fixed (char* pManaged = managedArray)
{
ConvertMultiByteToWideChar(pNative,
lenInBytes,
pManaged,
lenInBytes);
}
}
/// <summary>
/// Convert a single UNICODE wide char to a single ANSI byte.
/// </summary>
/// <param name="managedArray">single UNICODE wide char value</param>
public static unsafe byte WideCharToAnsiChar(char managedValue, bool bestFit, bool throwOnUnmappableChar)
{
// @TODO - we really shouldn't allocate one-byte arrays and then destroy it
byte* nativeArray = StringToAnsiString(&managedValue, 1, null, /*terminateWithNull=*/false, bestFit, throwOnUnmappableChar);
byte native = (*nativeArray);
CoTaskMemFree(new IntPtr(nativeArray));
return native;
}
/// <summary>
/// Convert a single ANSI byte value to a single UNICODE wide char value, best fit.
/// </summary>
/// <param name="nativeValue">Single ANSI byte value.</param>
public static unsafe char AnsiCharToWideChar(byte nativeValue)
{
char ch;
ConvertMultiByteToWideChar(&nativeValue, 1, &ch, 1);
return ch;
}
/// <summary>
/// Convert UNICODE string to ANSI ByVal string.
/// </summary>
/// <remarks>This version is more efficient than StringToHGlobalAnsi in Interop\System\Runtime\InteropServices\Marshal.cs in that
/// it could allocate single byte per character, instead of SystemMaxDBCSCharSize per char, and it can skip calling WideCharToMultiByte for ASCII string</remarks>
/// <param name="str">Unicode string.</param>
/// <param name="pNative"> Allocated buffer where the ansi string must be placed. Could NOT be null. Buffer size must fit str.Length.</param>
public static unsafe void StringToByValAnsiString(string str, byte* pNative, int charCount, bool bestFit, bool throwOnUnmappableChar, bool truncate = true)
{
if (pNative == null)
throw new ArgumentNullException(nameof(pNative));
if (str != null)
{
// Truncate the string if it is larger than specified by SizeConst
int lenUnicode;
if (truncate)
{
lenUnicode = str.Length;
if (lenUnicode >= charCount)
lenUnicode = charCount - 1;
}
else
{
lenUnicode = charCount;
}
fixed (char* pManaged = str)
{
StringToAnsiString(pManaged, lenUnicode, pNative, /*terminateWithNull=*/true, bestFit, throwOnUnmappableChar);
}
}
else
{
(*pNative) = (byte)'\0';
}
}
/// <summary>
/// Convert ANSI string to unicode string, with option to free native memory. Calls generated by MCG
/// </summary>
/// <remarks>Input assumed to be zero terminated. Generates String.Empty for zero length string.
/// This version is more efficient than ConvertToUnicode in src\Interop\System\Runtime\InteropServices\Marshal.cs in that it can skip calling
/// MultiByteToWideChar for ASCII string, and it does not need another char[] buffer</remarks>
public static unsafe string ByValAnsiStringToString(byte* pchBuffer, int charCount)
{
// Match desktop CLR behavior
if (charCount == 0)
throw new MarshalDirectiveException();
int lenAnsi = GetAnsiStringLen(pchBuffer);
int lenUnicode = charCount;
string result = String.Empty;
if (lenUnicode > 0)
{
char* unicodeBuf = stackalloc char[lenUnicode];
int unicodeCharWritten = ConvertMultiByteToWideChar(pchBuffer,
lenAnsi,
unicodeBuf,
lenUnicode);
// If conversion failure, return empty string to match desktop CLR behavior
if (unicodeCharWritten > 0)
result = new string(unicodeBuf, 0, unicodeCharWritten);
}
return result;
}
private static unsafe int GetAnsiStringLen(byte* pchBuffer)
{
byte* pchBufferOriginal = pchBuffer;
while (*pchBuffer != 0)
{
pchBuffer++;
}
return (int)(pchBuffer - pchBufferOriginal);
}
// c# string (UTF-16) to UTF-8 encoded byte array
private static unsafe byte* StringToAnsiString(char* pManaged, int lenUnicode, byte* pNative, bool terminateWithNull,
bool bestFit, bool throwOnUnmappableChar)
{
bool allAscii = true;
for (int i = 0; i < lenUnicode; i++)
{
if (pManaged[i] >= 128)
{
allAscii = false;
break;
}
}
int length;
if (allAscii) // If all ASCII, map one UNICODE character to one ANSI char
{
length = lenUnicode;
}
else // otherwise, let OS count number of ANSI chars
{
length = GetByteCount(pManaged, lenUnicode);
}
if (pNative == null)
{
pNative = (byte*)CoTaskMemAlloc((System.UIntPtr)(length + 1));
}
if (allAscii) // ASCII conversion
{
byte* pDst = pNative;
char* pSrc = pManaged;
while (lenUnicode > 0)
{
unchecked
{
*pDst++ = (byte)(*pSrc++);
lenUnicode--;
}
}
}
else // Let OS convert
{
ConvertWideCharToMultiByte(pManaged,
lenUnicode,
pNative,
length,
bestFit,
throwOnUnmappableChar);
}
// Zero terminate
if (terminateWithNull)
*(pNative + length) = 0;
return pNative;
}
/// <summary>
/// This is a auxiliary function that counts the length of the ansi buffer and
/// estimate the length of the buffer in Unicode. It returns true if all bytes
/// in the buffer are ANSII.
/// </summary>
private static unsafe bool CalculateStringLength(byte* pchBuffer, out int ansiBufferLen, out int unicodeBufferLen)
{
ansiBufferLen = 0;
bool allAscii = true;
{
byte* p = pchBuffer;
byte b = *p++;
while (b != 0)
{
if (b >= 128)
{
allAscii = false;
}
ansiBufferLen++;
b = *p++;
}
}
if (allAscii)
{
unicodeBufferLen = ansiBufferLen;
}
else // If non ASCII, let OS calculate number of characters
{
unicodeBufferLen = GetCharCount(pchBuffer, ansiBufferLen);
}
return allAscii;
}
#endregion
}
}
| |
using System;
using BigMath;
namespace Raksha.Math.EC.Multiplier
{
/**
* Class implementing the WNAF (Window Non-Adjacent Form) multiplication
* algorithm.
*/
internal class WNafMultiplier
: ECMultiplier
{
/**
* Computes the Window NAF (non-adjacent Form) of an integer.
* @param width The width <code>w</code> of the Window NAF. The width is
* defined as the minimal number <code>w</code>, such that for any
* <code>w</code> consecutive digits in the resulting representation, at
* most one is non-zero.
* @param k The integer of which the Window NAF is computed.
* @return The Window NAF of the given width, such that the following holds:
* <code>k = −<sub>i=0</sub><sup>l-1</sup> k<sub>i</sub>2<sup>i</sup>
* </code>, where the <code>k<sub>i</sub></code> denote the elements of the
* returned <code>sbyte[]</code>.
*/
public sbyte[] WindowNaf(sbyte width, BigInteger k)
{
// The window NAF is at most 1 element longer than the binary
// representation of the integer k. sbyte can be used instead of short or
// int unless the window width is larger than 8. For larger width use
// short or int. However, a width of more than 8 is not efficient for
// m = log2(q) smaller than 2305 Bits. Note: Values for m larger than
// 1000 Bits are currently not used in practice.
sbyte[] wnaf = new sbyte[k.BitLength + 1];
// 2^width as short and BigInteger
short pow2wB = (short)(1 << width);
BigInteger pow2wBI = BigInteger.ValueOf(pow2wB);
int i = 0;
// The actual length of the WNAF
int length = 0;
// while k >= 1
while (k.Sign > 0)
{
// if k is odd
if (k.TestBit(0))
{
// k Mod 2^width
BigInteger remainder = k.Mod(pow2wBI);
// if remainder > 2^(width - 1) - 1
if (remainder.TestBit(width - 1))
{
wnaf[i] = (sbyte)(remainder.IntValue - pow2wB);
}
else
{
wnaf[i] = (sbyte)remainder.IntValue;
}
// wnaf[i] is now in [-2^(width-1), 2^(width-1)-1]
k = k.Subtract(BigInteger.ValueOf(wnaf[i]));
length = i;
}
else
{
wnaf[i] = 0;
}
// k = k/2
k = k.ShiftRight(1);
i++;
}
length++;
// Reduce the WNAF array to its actual length
sbyte[] wnafShort = new sbyte[length];
Array.Copy(wnaf, 0, wnafShort, 0, length);
return wnafShort;
}
/**
* Multiplies <code>this</code> by an integer <code>k</code> using the
* Window NAF method.
* @param k The integer by which <code>this</code> is multiplied.
* @return A new <code>ECPoint</code> which equals <code>this</code>
* multiplied by <code>k</code>.
*/
public ECPoint Multiply(ECPoint p, BigInteger k, PreCompInfo preCompInfo)
{
WNafPreCompInfo wnafPreCompInfo;
if ((preCompInfo != null) && (preCompInfo is WNafPreCompInfo))
{
wnafPreCompInfo = (WNafPreCompInfo)preCompInfo;
}
else
{
// Ignore empty PreCompInfo or PreCompInfo of incorrect type
wnafPreCompInfo = new WNafPreCompInfo();
}
// floor(log2(k))
int m = k.BitLength;
// width of the Window NAF
sbyte width;
// Required length of precomputation array
int reqPreCompLen;
// Determine optimal width and corresponding length of precomputation
// array based on literature values
if (m < 13)
{
width = 2;
reqPreCompLen = 1;
}
else
{
if (m < 41)
{
width = 3;
reqPreCompLen = 2;
}
else
{
if (m < 121)
{
width = 4;
reqPreCompLen = 4;
}
else
{
if (m < 337)
{
width = 5;
reqPreCompLen = 8;
}
else
{
if (m < 897)
{
width = 6;
reqPreCompLen = 16;
}
else
{
if (m < 2305)
{
width = 7;
reqPreCompLen = 32;
}
else
{
width = 8;
reqPreCompLen = 127;
}
}
}
}
}
}
// The length of the precomputation array
int preCompLen = 1;
ECPoint[] preComp = wnafPreCompInfo.GetPreComp();
ECPoint twiceP = wnafPreCompInfo.GetTwiceP();
// Check if the precomputed ECPoints already exist
if (preComp == null)
{
// Precomputation must be performed from scratch, create an empty
// precomputation array of desired length
preComp = new ECPoint[]{ p };
}
else
{
// Take the already precomputed ECPoints to start with
preCompLen = preComp.Length;
}
if (twiceP == null)
{
// Compute twice(p)
twiceP = p.Twice();
}
if (preCompLen < reqPreCompLen)
{
// Precomputation array must be made bigger, copy existing preComp
// array into the larger new preComp array
ECPoint[] oldPreComp = preComp;
preComp = new ECPoint[reqPreCompLen];
Array.Copy(oldPreComp, 0, preComp, 0, preCompLen);
for (int i = preCompLen; i < reqPreCompLen; i++)
{
// Compute the new ECPoints for the precomputation array.
// The values 1, 3, 5, ..., 2^(width-1)-1 times p are
// computed
preComp[i] = twiceP.Add(preComp[i - 1]);
}
}
// Compute the Window NAF of the desired width
sbyte[] wnaf = WindowNaf(width, k);
int l = wnaf.Length;
// Apply the Window NAF to p using the precomputed ECPoint values.
ECPoint q = p.Curve.Infinity;
for (int i = l - 1; i >= 0; i--)
{
q = q.Twice();
if (wnaf[i] != 0)
{
if (wnaf[i] > 0)
{
q = q.Add(preComp[(wnaf[i] - 1)/2]);
}
else
{
// wnaf[i] < 0
q = q.Subtract(preComp[(-wnaf[i] - 1)/2]);
}
}
}
// Set PreCompInfo in ECPoint, such that it is available for next
// multiplication.
wnafPreCompInfo.SetPreComp(preComp);
wnafPreCompInfo.SetTwiceP(twiceP);
p.SetPreCompInfo(wnafPreCompInfo);
return q;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using DjvuNet.Compression;
using DjvuNet.Graphics;
namespace DjvuNet.JB2
{
public abstract class JB2Codec
{
#region Private Variables
private readonly bool _encoding;
private const sbyte NewMark = 1;
private const sbyte NewMarkLibraryOnly = 2;
private const sbyte NewMarkImageOnly = 3;
private const sbyte MatchedRefine = 4;
private const sbyte MatchedRefineLibraryOnly = 5;
private const sbyte MatchedRefineImageOnly = 6;
private const sbyte MatchedCopy = 7;
private const sbyte NonMarkData = 8;
private const sbyte RequiredDictOrReset = 9;
private const sbyte PreservedComment = 10;
private const Int32 MinusOneObject = -1;
private readonly List<MutableValue<sbyte>> _bitcells = new List<MutableValue<sbyte>>();
private readonly MutableValue<sbyte> _distRefinementFlag = new MutableValue<sbyte>();
private int _lastBottom;
private int _lastLeft;
private int _lastRight;
private int _lastRowBottom;
private int _lastRowLeft;
private readonly List<MutableValue<int>> _leftcell = new List<MutableValue<int>>();
private readonly List<Rectangle> _libinfo = new List<Rectangle>();
private readonly MutableValue<sbyte> _offsetTypeDist = new MutableValue<sbyte>();
private bool _refinementp;
private readonly MutableValue<int> rel_loc_x_current = new MutableValue<int>();
private readonly MutableValue<int> rel_loc_x_last = new MutableValue<int>();
private readonly MutableValue<int> rel_loc_y_current = new MutableValue<int>();
private readonly MutableValue<int> rel_loc_y_last = new MutableValue<int>();
private readonly List<MutableValue<int>> rightcell = new List<MutableValue<int>>();
private readonly List<int> shape2lib_Renamed_Field = new List<int>();
private readonly int[] short_list = new int[3];
private int _shortListPos;
#endregion Private Variables
#region Protected Variables
protected const int Bigpositive = 262142;
protected const int Bignegative = -262143;
protected const sbyte StartOfData = 0;
protected const sbyte EndOfData = 11;
protected MutableValue<int> AbsLocX = new MutableValue<int>();
protected MutableValue<int> AbsLocY = new MutableValue<int>();
protected MutableValue<int> AbsSizeX = new MutableValue<int>();
protected MutableValue<int> AbsSizeY = new MutableValue<int>();
protected sbyte[] Bitdist = new sbyte[1024];
protected sbyte[] Cbitdist = new sbyte[2048];
protected MutableValue<int> DistCommentByte = new MutableValue<int>();
protected MutableValue<int> DistCommentLength = new MutableValue<int>();
protected MutableValue<int> DistMatchIndex = new MutableValue<int>();
protected MutableValue<int> DistRecordType = new MutableValue<int>();
protected bool GotStartRecordP;
protected int ImageColumns;
protected int ImageRows;
protected MutableValue<int> ImageSizeDist = new MutableValue<int>();
protected MutableValue<int> InheritedShapeCountDist = new MutableValue<int>();
protected List<int> Lib2Shape = new List<int>();
protected MutableValue<int> RelSizeX = new MutableValue<int>();
protected MutableValue<int> RelSizeY = new MutableValue<int>();
#endregion Protected Variables
#region Constructors
protected JB2Codec(bool encoding)
{
_encoding = encoding;
for (int i = 0; i < Bitdist.Length; )
{
Bitdist[i++] = 0;
}
for (int i = 0; i < Cbitdist.Length; )
{
Cbitdist[i++] = 0;
}
_bitcells.Add(new MutableValue<sbyte>());
_leftcell.Add(new MutableValue<int>());
rightcell.Add(new MutableValue<int>());
}
#endregion Constructors
#region Protected Methods
protected virtual int CodeNum(int low, int high, MutableValue<int> ctx, int v)
{
bool negative = false;
int cutoff = 0;
int ictx = ctx.Value;
if (ictx >= _bitcells.Count)
{
throw new IndexOutOfRangeException("Image bad MutableValue<int>");
}
for (int phase = 1, range = -1; range != 1; ictx = ctx.Value)
{
bool decision;
if (ictx == 0)
{
ictx = _bitcells.Count;
ctx.Value = ictx;
MutableValue<sbyte> pbitcells = new MutableValue<sbyte>();
MutableValue<int> pleftcell = new MutableValue<int>();
MutableValue<int> prightcell = new MutableValue<int>();
_bitcells.Add(pbitcells);
_leftcell.Add(pleftcell);
rightcell.Add(prightcell);
decision = _encoding
? (((low < cutoff) && (high >= cutoff))
? CodeBit((v >= cutoff), pbitcells)
: (v >= cutoff))
: ((low >= cutoff) || ((high >= cutoff) && CodeBit(false, pbitcells)));
ctx = (decision ? prightcell : pleftcell);
}
else
{
decision = _encoding
? (((low < cutoff) && (high >= cutoff))
? CodeBit((v >= cutoff), (MutableValue<sbyte>)_bitcells[ictx])
: (v >= cutoff))
: ((low >= cutoff) ||
((high >= cutoff) && CodeBit(false, (MutableValue<sbyte>)_bitcells[ictx])));
ctx = (MutableValue<int>)(decision ? rightcell[ictx] : _leftcell[ictx]);
}
switch (phase)
{
case 1:
{
negative = !decision;
if (negative)
{
if (_encoding)
{
v = -v - 1;
}
int temp = -low - 1;
low = -high - 1;
high = temp;
}
phase = 2;
cutoff = 1;
break;
}
case 2:
{
if (!decision)
{
phase = 3;
range = (cutoff + 1) >> 1;
if (range == 1)
{
cutoff = 0;
}
else
{
cutoff -= (range >> 1);
}
}
else
{
cutoff = (cutoff << 1) + 1;
}
break;
}
case 3:
{
range /= 2;
if (range != 1)
{
if (!decision)
{
cutoff -= (range >> 1);
}
else
{
cutoff += (range >> 1);
}
}
else if (!decision)
{
cutoff--;
}
break;
}
}
}
int result = negative ? (-cutoff - 1) : cutoff;
return result;
}
protected abstract void CodeAbsoluteLocation(JB2Blit jblt, int rows, int columns);
protected abstract void CodeBitmapByCrossCoding(Bitmap bm, Bitmap cbm, int xd2c, int dw, int dy,
int cy, int up1, int up0, int xup1, int xup0,
int xdn1);
protected abstract void CodeBitmapDirectly(Bitmap bm, int dw, int dy, int up2, int up1, int up0);
protected virtual void CodeEventualLosslessRefinement()
{
_refinementp = CodeBit(_refinementp, _distRefinementFlag);
}
protected abstract void CodeInheritedShapeCount(JB2Dictionary jim);
protected void CodeAbsoluteMarkSize(Bitmap bm)
{
CodeAbsoluteMarkSize(bm, 0);
}
protected abstract void CodeAbsoluteMarkSize(Bitmap bm, int border);
protected virtual void CodeImageSize(JB2Dictionary ignored)
{
_lastLeft = 1;
_lastRowBottom = 0;
_lastRowLeft = _lastRight = 0;
FillShortList(_lastRowBottom);
GotStartRecordP = true;
}
protected virtual void CodeImageSize(JB2Image ignored)
{
_lastLeft = 1 + ImageColumns;
_lastRowBottom = ImageRows;
_lastRowLeft = _lastRight = 0;
FillShortList(_lastRowBottom);
GotStartRecordP = true;
}
protected virtual int CodeRecordA(int rectype, JB2Dictionary jim, JB2Shape xjshp)
{
Bitmap bm = null;
int shapeno = -1;
rectype = CodeRecordType(rectype);
JB2Shape jshp = xjshp;
switch (rectype)
{
case NewMarkLibraryOnly:
case MatchedRefineLibraryOnly:
{
if (!_encoding)
{
jshp = new JB2Shape().Init(-1);
}
else if (jshp == null)
{
jshp = new JB2Shape();
}
bm = jshp.Bitmap;
break;
}
}
switch (rectype)
{
case StartOfData:
{
CodeImageSize(jim);
CodeEventualLosslessRefinement();
if (!_encoding)
{
InitLibrary(jim);
}
break;
}
case NewMarkLibraryOnly:
{
CodeAbsoluteMarkSize(bm, 4);
CodeBitmapDirectly(bm);
break;
}
case MatchedRefineLibraryOnly:
{
int match = CodeMatchIndex(jshp.Parent, jim);
if (!_encoding)
{
jshp.Parent = Convert.ToInt32((Lib2Shape[match]));
}
Bitmap cbm = jim.GetShape(jshp.Parent).Bitmap;
Rectangle lmatch = (Rectangle)_libinfo[match];
CodeRelativeMarkSize(bm, (1 + lmatch.Left) - lmatch.Right, (1 + lmatch.Top) - lmatch.Bottom, 4);
CodeBitmapByCrossCoding(bm, cbm, jshp.Parent);
break;
}
case PreservedComment:
{
jim.Comment = CodeComment(jim.Comment);
break;
}
case RequiredDictOrReset:
{
if (!GotStartRecordP)
{
CodeInheritedShapeCount(jim);
}
else
{
ResetNumcoder();
}
break;
}
case EndOfData:
break;
default:
throw new ArgumentException("Image bad type");
}
if (!_encoding)
{
switch (rectype)
{
case NewMarkLibraryOnly:
case MatchedRefineLibraryOnly:
{
if (xjshp != null)
{
jshp = jshp.Duplicate();
}
shapeno = jim.AddShape(jshp);
AddLibrary(shapeno, jshp);
break;
}
}
}
return rectype;
}
protected virtual int CodeRecordB(int rectype, JB2Image jim, JB2Shape xjshp, JB2Blit xjblt)
{
Bitmap bm = null;
int shapeno = -1;
JB2Shape jshp = xjshp;
JB2Blit jblt = xjblt;
rectype = CodeRecordType(rectype);
switch (rectype)
{
case NewMark:
case NewMarkImageOnly:
case MatchedRefine:
case MatchedRefineImageOnly:
case NonMarkData:
{
if (jblt == null)
{
jblt = new JB2Blit();
}
// fall through
}
goto case NewMarkLibraryOnly;
case NewMarkLibraryOnly:
case MatchedRefineLibraryOnly:
{
if (!_encoding)
{
jshp = new JB2Shape().Init((rectype == NonMarkData) ? (-2) : (-1));
}
else if (jshp == null)
{
jshp = new JB2Shape();
}
bm = jshp.Bitmap;
break;
}
case MatchedCopy:
{
if (jblt == null)
{
jblt = new JB2Blit();
}
break;
}
}
bool needAddLibrary = false;
bool needAddBlit = false;
switch (rectype)
{
case StartOfData:
{
CodeImageSize(jim);
CodeEventualLosslessRefinement();
if (!_encoding)
{
InitLibrary(jim);
}
break;
}
case NewMark:
{
needAddBlit = needAddLibrary = true;
CodeAbsoluteMarkSize(bm, 4);
CodeBitmapDirectly(bm);
CodeRelativeLocation(jblt, bm.ImageHeight, bm.ImageWidth);
break;
}
case NewMarkLibraryOnly:
{
needAddLibrary = true;
CodeAbsoluteMarkSize(bm, 4);
CodeBitmapDirectly(bm);
break;
}
case NewMarkImageOnly:
{
needAddBlit = true;
CodeAbsoluteMarkSize(bm, 3);
CodeBitmapDirectly(bm);
CodeRelativeLocation(jblt, bm.ImageHeight, bm.ImageWidth);
break;
}
case MatchedRefine:
{
needAddBlit = true;
needAddLibrary = true;
int match = CodeMatchIndex(jshp.Parent, jim);
if (!_encoding)
{
jshp.Parent = Convert.ToInt32((Lib2Shape[match]));
}
Bitmap cbm = jim.GetShape(jshp.Parent).Bitmap;
Rectangle lmatch = (Rectangle)_libinfo[match];
CodeRelativeMarkSize(bm, (1 + lmatch.Left) - lmatch.Right, (1 + lmatch.Top) - lmatch.Bottom, 4);
// verbose("2.d time="+System.currentTimeMillis()+",rectype="+rectype);
CodeBitmapByCrossCoding(bm, cbm, match);
// verbose("2.e time="+System.currentTimeMillis()+",rectype="+rectype);
CodeRelativeLocation(jblt, bm.ImageHeight, bm.ImageWidth);
break;
}
case MatchedRefineLibraryOnly:
{
needAddLibrary = true;
int match = CodeMatchIndex(jshp.Parent, jim);
if (!_encoding)
{
jshp.Parent = Convert.ToInt32((Lib2Shape[match]));
}
Bitmap cbm = jim.GetShape(jshp.Parent).Bitmap;
Rectangle lmatch = (Rectangle)_libinfo[match];
CodeRelativeMarkSize(bm, (1 + lmatch.Left) - lmatch.Right, (1 + lmatch.Top) - lmatch.Bottom, 4);
break;
}
case MatchedRefineImageOnly:
{
needAddBlit = true;
int match = CodeMatchIndex(jshp.Parent, jim);
if (!_encoding)
{
jshp.Parent = Convert.ToInt32((Lib2Shape[match]));
}
Bitmap cbm = jim.GetShape(jshp.Parent).Bitmap;
Rectangle lmatch = (Rectangle)_libinfo[match];
CodeRelativeMarkSize(bm, (1 + lmatch.Left) - lmatch.Right, (1 + lmatch.Top) - lmatch.Bottom, 4);
CodeBitmapByCrossCoding(bm, cbm, match);
CodeRelativeLocation(jblt, bm.ImageHeight, bm.ImageWidth);
break;
}
case MatchedCopy:
{
int match = CodeMatchIndex(jblt.ShapeNumber, jim);
if (!_encoding)
{
jblt.ShapeNumber = Convert.ToInt32((Lib2Shape[match]));
}
bm = jim.GetShape(jblt.ShapeNumber).Bitmap;
Rectangle lmatch = (Rectangle)_libinfo[match];
jblt.Left += lmatch.Right;
jblt.Bottom += lmatch.Bottom;
CodeRelativeLocation(jblt, (1 + lmatch.Top) - lmatch.Bottom,
(1 + lmatch.Left) - lmatch.Right);
jblt.Left -= lmatch.Right;
jblt.Bottom -= lmatch.Bottom;
break;
}
case NonMarkData:
{
needAddBlit = true;
CodeAbsoluteMarkSize(bm, 3);
CodeBitmapDirectly(bm);
CodeAbsoluteLocation(jblt, bm.ImageHeight, bm.ImageWidth);
break;
}
case PreservedComment:
{
jim.Comment = CodeComment(jim.Comment);
break;
}
case RequiredDictOrReset:
{
if (!GotStartRecordP)
{
CodeInheritedShapeCount(jim);
}
else
{
ResetNumcoder();
}
break;
}
case EndOfData:
break;
default:
throw new ArgumentException("Image unknown type");
}
if (!_encoding)
{
switch (rectype)
{
case NewMark:
case NewMarkLibraryOnly:
case MatchedRefine:
case MatchedRefineLibraryOnly:
case NewMarkImageOnly:
case MatchedRefineImageOnly:
case NonMarkData:
{
if (xjshp != null)
{
jshp = jshp.Duplicate();
}
shapeno = jim.AddShape(jshp);
Shape2Lib(shapeno, MinusOneObject);
if (needAddLibrary)
{
AddLibrary(shapeno, jshp);
}
if (needAddBlit)
{
jblt.ShapeNumber = shapeno;
if (xjblt != null)
{
jblt = (JB2Blit)xjblt.Duplicate();
}
jim.AddBlit(jblt);
}
break;
}
case MatchedCopy:
{
if (xjblt != null)
{
jblt = (JB2Blit)xjblt.Duplicate();
}
jim.AddBlit(jblt);
break;
}
}
}
return rectype;
}
protected void CodeRelativeMarkSize(Bitmap bm, int cw, int ch)
{
CodeRelativeMarkSize(bm, cw, ch, 0);
}
protected void FillShortList(int v)
{
short_list[0] = short_list[1] = short_list[2] = v;
_shortListPos = 0;
}
protected int GetCrossContext(Bitmap bm, Bitmap cbm, int up1, int up0, int xup1, int xup0, int xdn1,
int column)
{
return ((bm.GetByteAt((up1 + column) - 1) << 10) | (bm.GetByteAt(up1 + column) << 9) |
(bm.GetByteAt(up1 + column + 1) << 8) | (bm.GetByteAt((up0 + column) - 1) << 7) |
(cbm.GetByteAt(xup1 + column) << 6) | (cbm.GetByteAt((xup0 + column) - 1) << 5) |
(cbm.GetByteAt(xup0 + column) << 4) | (cbm.GetByteAt(xup0 + column + 1) << 3) |
(cbm.GetByteAt((xdn1 + column) - 1) << 2) | (cbm.GetByteAt(xdn1 + column) << 1) |
(cbm.GetByteAt(xdn1 + column + 1)));
}
protected int GetDirectContext(Bitmap bm, int up2, int up1, int up0, int column)
{
return ((bm.GetByteAt((up2 + column) - 1) << 9) | (bm.GetByteAt(up2 + column) << 8) |
(bm.GetByteAt(up2 + column + 1) << 7) | (bm.GetByteAt((up1 + column) - 2) << 6) |
(bm.GetByteAt((up1 + column) - 1) << 5) | (bm.GetByteAt(up1 + column) << 4) |
(bm.GetByteAt(up1 + column + 1) << 3) | (bm.GetByteAt(up1 + column + 2) << 2) |
(bm.GetByteAt((up0 + column) - 2) << 1) | (bm.GetByteAt((up0 + column) - 1)));
}
protected abstract void CodeRelativeMarkSize(Bitmap bm, int cw, int ch, int border);
protected abstract int GetDiff(int ignored, MutableValue<int> rel_loc);
protected virtual int AddLibrary(int shapeno, JB2Shape jshp)
{
int libno = Lib2Shape.Count;
Lib2Shape.Add(shapeno);
Shape2Lib(shapeno, libno);
//final Rectangle r = new Rectangle();
//libinfo.addElement(r);
//jshp.getGBitmap().compute_bounding_box(r);
_libinfo.Add(jshp.Bitmap.ComputeBoundingBox());
return libno;
}
protected virtual void ResetNumcoder()
{
DistCommentByte.Value = 0;
DistCommentLength.Value = 0;
DistRecordType.Value = 0;
DistMatchIndex.Value = 0;
AbsLocX.Value = 0;
AbsLocY.Value = 0;
AbsSizeX.Value = 0;
AbsSizeY.Value = 0;
ImageSizeDist.Value = 0;
InheritedShapeCountDist.Value = 0;
rel_loc_x_current.Value = 0;
rel_loc_x_last.Value = 0;
rel_loc_y_current.Value = 0;
rel_loc_y_last.Value = 0;
RelSizeX.Value = 0;
RelSizeY.Value = 0;
_bitcells.Clear();
_leftcell.Clear();
rightcell.Clear();
_bitcells.Add(new MutableValue<sbyte>());
_leftcell.Add(new MutableValue<int>());
rightcell.Add(new MutableValue<int>());
GC.Collect();
}
protected void Shape2Lib(int shapeno, int libno)
{
int size = shape2lib_Renamed_Field.Count;
if (size <= shapeno)
{
while (size++ < shapeno)
{
shape2lib_Renamed_Field.Add(MinusOneObject);
}
shape2lib_Renamed_Field.Add(libno);
}
else
{
shape2lib_Renamed_Field[shapeno] = libno;
}
}
protected int ShiftCrossContext(Bitmap bm, Bitmap cbm, int context, int n, int up1, int up0,
int xup1, int xup0, int xdn1, int column)
{
return (((context << 1) & 0x636) | (bm.GetByteAt(up1 + column + 1) << 8) |
(cbm.GetByteAt(xup1 + column) << 6) | (cbm.GetByteAt(xup0 + column + 1) << 3) |
(cbm.GetByteAt(xdn1 + column + 1)) | (n << 7));
}
protected int ShiftDirectContext(Bitmap bm, int context, int next, int up2, int up1, int up0,
int column)
{
return (((context << 1) & 0x37a) | (bm.GetByteAt(up1 + column + 2) << 2) |
(bm.GetByteAt(up2 + column + 1) << 7) | next);
}
protected abstract bool CodeBit(bool bit, MutableValue<sbyte> ctx);
protected abstract int CodeBit(bool bit, sbyte[] array, int offset);
protected abstract String CodeComment(String comment);
protected abstract int CodeMatchIndex(int index, JB2Dictionary jim);
protected abstract int CodeRecordType(int rectype);
protected virtual void CodeBitmapByCrossCoding(Bitmap bm, Bitmap cbm, int libno)
{
// Bitmap cbm=new Bitmap();
// synchronized(xcbm)
// {
// cbm.init(xcbm);
// }
lock (bm)
{
int cw = cbm.ImageWidth;
int dw = bm.ImageWidth;
int dh = bm.ImageHeight;
Rectangle lmatch = (Rectangle)_libinfo[libno];
//int xd2c = ((1 + (dw / 2)) - dw) - ((((1 + lmatch.Left) - lmatch.Right) / 2) - lmatch.Left);
//int yd2c = ((1 + (dh / 2)) - dh) - ((((1 + lmatch.Top) - lmatch.Bottom) / 2) - lmatch.Top);
int xd2c = ((1 + (dw >> 1)) - dw) - ((((1 + lmatch.Left) - lmatch.Right) >> 1) - lmatch.Left);
int yd2c = ((1 + (dh >> 1)) - dh) - ((((1 + lmatch.Top) - lmatch.Bottom) >> 1) - lmatch.Top);
bm.MinimumBorder = 2;
cbm.MinimumBorder = 2 - xd2c;
cbm.MinimumBorder = (2 + dw + xd2c) - cw;
int dy = dh - 1;
int cy = dy + yd2c;
CodeBitmapByCrossCoding(bm, cbm, xd2c, dw, dy, cy, bm.RowOffset(dy + 1), bm.RowOffset(dy),
cbm.RowOffset(cy + 1) + xd2c, cbm.RowOffset(cy) + xd2c,
cbm.RowOffset(cy - 1) + xd2c);
}
}
protected virtual void CodeBitmapDirectly(Bitmap bm)
{
lock (bm)
{
bm.MinimumBorder = 3;
int dy = bm.ImageHeight - 1;
CodeBitmapDirectly(bm, bm.ImageWidth, dy, bm.RowOffset(dy + 2), bm.RowOffset(dy + 1), bm.RowOffset(dy));
}
}
protected virtual void CodeRelativeLocation(JB2Blit jblt, int rows, int columns)
{
if (!GotStartRecordP)
{
throw new SystemException("Image no start");
}
int bottom = 0;
int left = 0;
int top = 0;
int right = 0;
if (_encoding)
{
left = jblt.Left + 1;
bottom = jblt.Bottom + 1;
right = (left + columns) - 1;
top = (bottom + rows) - 1;
}
bool new_row = CodeBit((left < _lastLeft), _offsetTypeDist);
if (new_row)
{
int x_diff = GetDiff(left - _lastRowLeft, rel_loc_x_last);
int y_diff = GetDiff(top - _lastRowBottom, rel_loc_y_last);
if (!_encoding)
{
left = _lastRowLeft + x_diff;
top = _lastRowBottom + y_diff;
right = (left + columns) - 1;
bottom = (top - rows) + 1;
}
_lastLeft = _lastRowLeft = left;
_lastRight = right;
_lastBottom = _lastRowBottom = bottom;
FillShortList(bottom);
}
else
{
int x_diff = GetDiff(left - _lastRight, rel_loc_x_current);
int y_diff = GetDiff(bottom - _lastBottom, rel_loc_y_current);
if (!_encoding)
{
left = _lastRight + x_diff;
bottom = _lastBottom + y_diff;
right = (left + columns) - 1;
top = (bottom + rows) - 1;
}
_lastLeft = left;
_lastRight = right;
_lastBottom = UpdateShortList(bottom);
}
if (!_encoding)
{
jblt.Bottom = bottom - 1;
jblt.Left = left - 1;
}
}
protected virtual void InitLibrary(JB2Dictionary jim)
{
int nshape = jim.InheritedShapes;
shape2lib_Renamed_Field.Clear();
Lib2Shape.Clear();
_libinfo.Clear();
for (int i = 0; i < nshape; i++)
{
int x = i;
shape2lib_Renamed_Field.Add(x);
Lib2Shape.Add(x);
JB2Shape jshp = jim.GetShape(i);
//final Rectangle r = new Rectangle();
//libinfo.addElement(r);
//jshp.getGBitmap().compute_bounding_box(r);
_libinfo.Add(jshp.Bitmap.ComputeBoundingBox());
}
}
protected virtual int UpdateShortList(int v)
{
if (++_shortListPos == 3)
{
_shortListPos = 0;
}
short_list[_shortListPos] = v;
return (short_list[0] >= short_list[1])
? ((short_list[0] > short_list[2])
? ((short_list[1] >= short_list[2]) ? short_list[1] : short_list[2])
: short_list[0])
: ((short_list[0] < short_list[2])
? ((short_list[1] >= short_list[2]) ? short_list[2] : short_list[1])
: short_list[0]);
}
#endregion Protected Methods
}
}
| |
/*
* CID0019.cs - ru culture handler.
*
* Copyright (c) 2003 Southern Storm Software, Pty Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Generated from "ru.txt".
namespace I18N.Other
{
using System;
using System.Globalization;
using I18N.Common;
public class CID0019 : RootCulture
{
public CID0019() : base(0x0019) {}
public CID0019(int culture) : base(culture) {}
public override String Name
{
get
{
return "ru";
}
}
public override String ThreeLetterISOLanguageName
{
get
{
return "rus";
}
}
public override String ThreeLetterWindowsLanguageName
{
get
{
return "RUS";
}
}
public override String TwoLetterISOLanguageName
{
get
{
return "ru";
}
}
public override DateTimeFormatInfo DateTimeFormat
{
get
{
DateTimeFormatInfo dfi = base.DateTimeFormat;
dfi.AbbreviatedDayNames = new String[] {"\u0412\u0441", "\u041F\u043D", "\u0412\u0442", "\u0421\u0440", "\u0427\u0442", "\u041F\u0442", "\u0421\u0431"};
dfi.DayNames = new String[] {"\u0432\u043E\u0441\u043A\u0440\u0435\u0441\u0435\u043D\u044C\u0435", "\u043F\u043E\u043D\u0435\u0434\u0435\u043B\u044C\u043D\u0438\u043A", "\u0432\u0442\u043E\u0440\u043D\u0438\u043A", "\u0441\u0440\u0435\u0434\u0430", "\u0447\u0435\u0442\u0432\u0435\u0440\u0433", "\u043F\u044F\u0442\u043D\u0438\u0446\u0430", "\u0441\u0443\u0431\u0431\u043E\u0442\u0430"};
dfi.AbbreviatedMonthNames = new String[] {"\u044F\u043D\u0432", "\u0444\u0435\u0432", "\u043C\u0430\u0440", "\u0430\u043F\u0440", "\u043C\u0430\u0439", "\u0438\u044E\u043D", "\u0438\u044E\u043B", "\u0430\u0432\u0433", "\u0441\u0435\u043D", "\u043E\u043A\u0442", "\u043D\u043E\u044F", "\u0434\u0435\u043A", ""};
dfi.MonthNames = new String[] {"\u042F\u043D\u0432\u0430\u0440\u044C", "\u0424\u0435\u0432\u0440\u0430\u043B\u044C", "\u041C\u0430\u0440\u0442", "\u0410\u043F\u0440\u0435\u043B\u044C", "\u041C\u0430\u0439", "\u0418\u044E\u043D\u044C", "\u0418\u044E\u043B\u044C", "\u0410\u0432\u0433\u0443\u0441\u0442", "\u0421\u0435\u043D\u0442\u044F\u0431\u0440\u044C", "\u041E\u043A\u0442\u044F\u0431\u0440\u044C", "\u041D\u043E\u044F\u0431\u0440\u044C", "\u0414\u0435\u043A\u0430\u0431\u0440\u044C", ""};
dfi.DateSeparator = ".";
dfi.TimeSeparator = ":";
dfi.LongDatePattern = "d MMMM yyyy '\u0433.'";
dfi.LongTimePattern = "H:mm:ss z";
dfi.ShortDatePattern = "dd.MM.yy";
dfi.ShortTimePattern = "H:mm";
dfi.FullDateTimePattern = "d MMMM yyyy '\u0433.' H:mm:ss z";
dfi.I18NSetDateTimePatterns(new String[] {
"d:dd.MM.yy",
"D:d MMMM yyyy '\u0433.'",
"f:d MMMM yyyy '\u0433.' H:mm:ss z",
"f:d MMMM yyyy '\u0433.' H:mm:ss z",
"f:d MMMM yyyy '\u0433.' H:mm:ss",
"f:d MMMM yyyy '\u0433.' H:mm",
"F:d MMMM yyyy '\u0433.' HH:mm:ss",
"g:dd.MM.yy H:mm:ss z",
"g:dd.MM.yy H:mm:ss z",
"g:dd.MM.yy H:mm:ss",
"g:dd.MM.yy H:mm",
"G:dd.MM.yy HH:mm:ss",
"m:MMMM dd",
"M:MMMM dd",
"r:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'",
"R:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'",
"s:yyyy'-'MM'-'dd'T'HH':'mm':'ss",
"t:H:mm:ss z",
"t:H:mm:ss z",
"t:H:mm:ss",
"t:H:mm",
"T:HH:mm:ss",
"u:yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
"U:dddd, dd MMMM yyyy HH:mm:ss",
"y:yyyy MMMM",
"Y:yyyy MMMM",
});
return dfi;
}
set
{
base.DateTimeFormat = value; // not used
}
}
public override String ResolveLanguage(String name)
{
switch(name)
{
case "ab": return "\u0410\u0431\u0445\u0430\u0437\u0441\u043a\u0438\u0439";
case "aa": return "\u0410\u0444\u0430\u0440";
case "af": return "\u0410\u0444\u0440\u0438\u043a\u0430\u0430\u043d\u0441";
case "sq": return "\u0410\u043b\u0431\u0430\u043d\u0441\u043a\u0438\u0439";
case "am": return "\u0410\u043c\u0445\u0430\u0440\u0441\u043a\u0438\u0439";
case "ar": return "\u0410\u0440\u0430\u0431\u0441\u043a\u0438\u0439";
case "hy": return "\u0410\u0440\u043c\u044f\u043d\u0441\u043a\u0438\u0439";
case "as": return "\u0410\u0441\u0441\u0430\u043c\u0441\u043a\u0438\u0439";
case "ay": return "\u0410\u044f\u043c\u0430\u0440\u0430";
case "az": return "\u0410\u0437\u0435\u0440\u0431\u0430\u0439\u0434\u0436\u0430\u043d\u0441\u043a\u0438\u0439";
case "ba": return "\u0411\u0430\u0448\u043a\u0438\u0440\u0441\u043a\u0438\u0439";
case "eu": return "\u0411\u0430\u0441\u043a\u0441\u043a\u0438\u0439";
case "bn": return "\u0411\u0435\u043d\u0433\u0430\u043b\u044c\u0441\u043a\u0438\u0439";
case "dz": return "\u0411\u0443\u0442\u0430\u043d\u0441\u043a\u0438\u0439";
case "bh": return "\u0411\u0438\u0445\u0430\u0440\u0441\u043a\u0438\u0439";
case "bi": return "\u0411\u0438\u0441\u043b\u0430\u043c\u0430";
case "br": return "\u0411\u0440\u0435\u0442\u043e\u043d\u0441\u043a\u0438\u0439";
case "bg": return "\u0411\u043e\u043b\u0433\u0430\u0440\u0441\u043a\u0438\u0439";
case "my": return "\u0411\u0438\u0440\u043c\u0430\u043d\u0441\u043a\u0438\u0439";
case "be": return "\u0411\u0435\u043b\u043e\u0440\u0443\u0441\u0441\u043a\u0438\u0439";
case "km": return "\u041a\u0430\u043c\u0431\u043e\u0434\u0436\u0438\u0439\u0441\u043a\u0438\u0439";
case "ca": return "\u041a\u0430\u0442\u0430\u043b\u0430\u043d\u0441\u043a\u0438\u0439";
case "zh": return "\u041a\u0438\u0442\u0430\u0439\u0441\u043a\u0438\u0439";
case "co": return "\u041a\u043e\u0440\u0441\u0438\u043a\u0430\u043d\u0441\u043a\u0438\u0439";
case "hr": return "\u0425\u043e\u0440\u0432\u0430\u0442\u0441\u043a\u0438\u0439";
case "cs": return "\u0427\u0435\u0448\u0441\u043a\u0438\u0439";
case "da": return "\u0414\u0430\u0442\u0441\u043a\u0438\u0439";
case "nl": return "\u0413\u043e\u043b\u043b\u0430\u043d\u0434\u0441\u043a\u0438\u0439";
case "en": return "\u0410\u043d\u0433\u043b\u0438\u0439\u0441\u043a\u0438\u0439";
case "eo": return "\u042d\u0441\u043f\u0435\u0440\u0430\u043d\u0442\u043e";
case "et": return "\u042d\u0441\u0442\u043e\u043d\u0441\u043a\u0438\u0439";
case "fo": return "\u0424\u0430\u0440\u0435\u0440\u0441\u043a\u0438\u0439";
case "fj": return "\u0424\u0438\u0434\u0436\u0438";
case "fi": return "\u0424\u0438\u043d\u0441\u043a\u0438\u0439";
case "fr": return "\u0424\u0440\u0430\u043d\u0446\u0443\u0437\u0441\u043a\u0438\u0439";
case "fy": return "\u0424\u0440\u0438\u0437\u0441\u043a\u0438\u0439";
case "gl": return "\u0413\u0430\u043b\u0438\u0446\u0438\u0439\u0441\u043a\u0438\u0439";
case "ka": return "\u0413\u0440\u0443\u0437\u0438\u043d\u0441\u043a\u0438\u0439";
case "de": return "\u041d\u0435\u043c\u0435\u0446\u043a\u0438\u0439";
case "el": return "\u0413\u0440\u0435\u0447\u0435\u0441\u043a\u0438\u0439";
case "kl": return "\u0413\u0440\u0435\u043d\u043b\u0430\u043d\u0434\u0441\u043a\u0438\u0439";
case "gn": return "\u0413\u0443\u0430\u0440\u0430\u043d\u0438";
case "gu": return "\u0413\u0443\u044f\u0440\u0430\u0442\u0438";
case "ha": return "\u0425\u043e\u0441\u0430";
case "he": return "\u0418\u0432\u0440\u0438\u0442";
case "hi": return "\u0425\u0438\u043d\u0434\u0438";
case "hu": return "\u0412\u0435\u043d\u0433\u0435\u0440\u0441\u043a\u0438\u0439";
case "is": return "\u0418\u0441\u043b\u0430\u043d\u0434\u0441\u043a\u0438\u0439";
case "id": return "\u0418\u043d\u0434\u043e\u043d\u0435\u0437\u0438\u0439\u0441\u043a\u0438\u0439";
case "ia": return "\u0421\u043c\u0435\u0448\u0430\u043d\u043d\u044b\u0439 \u044f\u0437\u044b\u043a";
case "ie": return "\u0421\u043c\u0435\u0448\u0430\u043d\u043d\u044b\u0439 \u044f\u0437\u044b\u043a";
case "iu": return "\u0418\u043d\u0430\u043a\u0442\u0438\u0442\u0443\u0442";
case "ik": return "\u0418\u043d\u0430\u043f\u0438\u0430\u043a";
case "ga": return "\u0418\u0440\u043b\u0430\u043d\u0434\u0441\u043a\u0438\u0439";
case "it": return "\u0418\u0442\u0430\u043b\u044c\u044f\u043d\u0441\u043a\u0438\u0439";
case "ja": return "\u042f\u043f\u043e\u043d\u0441\u043a\u0438\u0439";
case "jv": return "\u042f\u0432\u0430\u043d\u0441\u043a\u0438\u0439";
case "kn": return "\u041a\u0430\u043d\u0430\u0434\u0430";
case "ks": return "\u041a\u0430\u0448\u043c\u0438\u0440\u0441\u043a\u0438\u0439";
case "kk": return "\u041a\u0430\u0437\u0430\u0445\u0441\u043a\u0438\u0439";
case "rw": return "\u041a\u0438\u043d\u044f\u0440\u0432\u0430\u043d\u0434\u0430";
case "ky": return "\u041a\u0438\u0440\u0433\u0438\u0437\u0441\u043a\u0438\u0439";
case "rn": return "\u041a\u0438\u0440\u0443\u043d\u0434\u0438\u0439\u0441\u043a\u0438\u0439";
case "ko": return "\u041a\u043e\u0440\u0435\u0439\u0441\u043a\u0438\u0439";
case "ku": return "\u041a\u0443\u0440\u0434\u0438\u0448";
case "lo": return "\u041b\u0430\u043e\u0441\u0441\u043a\u0438\u0439";
case "la": return "\u041b\u0430\u0442\u0438\u043d\u0441\u043a\u0438\u0439";
case "lv": return "\u041b\u0430\u0442\u0432\u0438\u0439\u0441\u043a\u0438\u0439";
case "ln": return "\u041b\u0438\u043d\u0433\u0430\u043b\u0430";
case "lt": return "\u041b\u0438\u0442\u043e\u0432\u0441\u043a\u0438\u0439";
case "mk": return "\u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0441\u043a\u0438\u0439";
case "mg": return "\u041c\u0430\u043b\u0430\u0433\u0430\u0441\u0438\u0439\u0441\u043a\u0438\u0439";
case "ms": return "\u041c\u0430\u043b\u0430\u0439\u0441\u043a\u0438\u0439";
case "ml": return "\u041c\u0430\u043b\u0430\u044f\u043b\u0430\u043c";
case "mt": return "\u041c\u0430\u043b\u044c\u0442\u0438\u0439\u0441\u043a\u0438\u0439";
case "mi": return "\u041c\u0430\u043e\u0440\u0438";
case "mr": return "\u041c\u0430\u0440\u0430\u0442\u0438\u0439\u0441\u043a\u0438\u0439";
case "mo": return "\u041c\u043e\u043b\u0434\u0430\u0432\u0441\u043a\u0438\u0439";
case "mn": return "\u041c\u043e\u043d\u0433\u043e\u043b\u044c\u0441\u043a\u0438\u0439";
case "na": return "\u041d\u0430\u0443\u0440\u0443";
case "ne": return "\u041d\u0435\u043f\u0430\u043b\u044c\u0441\u043a\u0438\u0439";
case "no": return "\u041d\u043e\u0440\u0432\u0435\u0436\u0441\u043a\u0438\u0439";
case "oc": return "\u041e\u043a\u0438\u0442\u0430\u043d";
case "or": return "\u041e\u0440\u0438\u044f";
case "om": return "\u041e\u0440\u043e\u043c\u043e (\u0410\u0444\u0430\u043d)";
case "ps": return "\u041f\u0430\u0448\u0442\u043e (\u041f\u0443\u0448\u0442\u043e)";
case "fa": return "\u041f\u0435\u0440\u0441\u0438\u0434\u0441\u043a\u0438\u0439";
case "pl": return "\u041f\u043e\u043b\u044c\u0441\u043a\u0438\u0439";
case "pt": return "\u041f\u043e\u0440\u0442\u0443\u0433\u0430\u043b\u044c\u0441\u043a\u0438\u0439";
case "pa": return "\u041f\u0430\u043d\u0434\u0436\u0430\u0431\u0441\u043a\u0438\u0439";
case "qu": return "\u041a\u0435\u0447\u0443\u0430";
case "rm": return "\u0420\u0430\u0435\u0442\u043e-\u0440\u043e\u043c\u0430\u043d\u0441\u043a\u0438\u0439";
case "ro": return "\u0420\u0443\u043c\u044b\u043d\u0441\u043a\u0438\u0439";
case "ru": return "\u0440\u0443\u0441\u0441\u043A\u0438\u0439";
case "sm": return "\u0421\u0430\u043c\u043e\u0430";
case "sg": return "\u0421\u0430\u043d\u0433\u043e";
case "sa": return "\u0421\u0430\u043d\u0441\u043a\u0440\u0438\u0442";
case "gd": return "\u0413\u0430\u044d\u043b\u044c\u0441\u043a\u0438\u0439";
case "sr": return "\u0421\u0435\u0440\u0431\u0441\u043a\u0438\u0439";
case "sh": return "\u0421\u0435\u0440\u0431\u0441\u043a\u043e-\u0445\u043e\u0440\u0432\u0430\u0442\u0441\u043a\u0438\u0439";
case "st": return "\u0421\u0435\u0441\u043e\u0442\u043e";
case "tn": return "\u0421\u0435\u0442\u0441\u0432\u0430\u043d\u0430";
case "sn": return "\u0428\u043e\u043d\u0430";
case "sd": return "\u0421\u0438\u043d\u0434\u0438";
case "si": return "\u0421\u0438\u043d\u0433\u0430\u043b\u044c\u0441\u043a\u0438\u0439";
case "ss": return "\u0421\u0438\u0441\u0432\u0430\u0442\u0438";
case "sk": return "\u0421\u043b\u043e\u0432\u0430\u0446\u043a\u0438\u0439";
case "sl": return "\u0421\u043b\u043e\u0432\u0435\u043d\u0441\u043a\u0438\u0439";
case "so": return "\u0421\u043e\u043c\u0430\u043b\u0438";
case "es": return "\u0418\u0441\u043f\u0430\u043d\u0441\u043a\u0438\u0439";
case "su": return "\u0421\u0430\u043d\u0434\u0430\u043d\u0438\u0437\u0441\u043a\u0438\u0439";
case "sw": return "\u0421\u0443\u0430\u0445\u0438\u043b\u0438";
case "sv": return "\u0428\u0432\u0435\u0434\u0441\u043a\u0438\u0439";
case "tl": return "\u0422\u0430\u0433\u0430\u043b\u043e\u0433";
case "tg": return "\u0422\u0430\u0434\u0436\u0438\u043a\u0441\u043a\u0438\u0439";
case "ta": return "\u0422\u0430\u043c\u0438\u043b\u044c\u0441\u043a\u0438\u0439";
case "tt": return "\u0422\u0430\u0442\u0430\u0440\u0441\u043a\u0438\u0439";
case "te": return "\u0422\u0435\u043b\u0443\u0433\u0443";
case "th": return "\u0422\u0430\u0439\u0441\u043a\u0438\u0439";
case "bo": return "\u0422\u0438\u0431\u0435\u0442\u0441\u043a\u0438\u0439";
case "ti": return "\u0422\u0438\u0433\u0440\u0438\u043d\u0438\u0430";
case "to": return "\u0422\u043e\u043d\u0433\u0430";
case "ts": return "\u0422\u0441\u043e\u043d\u0433\u0430";
case "tr": return "\u0422\u0443\u0440\u0435\u0446\u043a\u0438\u0439";
case "tk": return "\u0422\u0443\u0440\u043a\u043c\u0435\u043d\u0441\u043a\u0438\u0439";
case "tw": return "\u0422\u0432\u0438";
case "ug": return "\u0423\u0439\u0433\u0443\u0440\u0441\u043a\u0438\u0439";
case "uk": return "\u0423\u043a\u0440\u0430\u0438\u043d\u0441\u043a\u0438\u0439";
case "ur": return "\u0423\u0440\u0434\u0443";
case "uz": return "\u0423\u0437\u0431\u0435\u043a\u0441\u043a\u0438\u0439";
case "vi": return "\u0412\u044c\u0435\u0442\u043d\u0430\u043c\u0441\u043a\u0438\u0439";
case "vo": return "\u0412\u043e\u043b\u0430\u043f\u0430\u043a";
case "cy": return "\u0412\u0430\u043b\u043b\u0438\u0439\u0441\u043a\u0438\u0439";
case "wo": return "\u0412\u043e\u043b\u043e\u0444";
case "xh": return "\u0425\u043e\u0437\u0430";
case "yi": return "\u0418\u0434\u0438\u0448";
case "yo": return "\u0419\u043e\u0440\u0443\u0431\u0430";
case "za": return "\u0417\u0443\u0430\u043d\u0433";
case "zu": return "\u0417\u0443\u043b\u0443\u0441\u0441\u043a\u0438\u0439";
}
return base.ResolveLanguage(name);
}
public override String ResolveCountry(String name)
{
switch(name)
{
case "AL": return "\u0410\u043b\u0431\u0430\u043d\u0438\u044f";
case "AS": return "\u0410\u0437\u0438\u044f";
case "AT": return "\u0410\u0432\u0441\u0442\u0440\u0438\u044f";
case "AU": return "\u0410\u0432\u0441\u0442\u0440\u0430\u043b\u0438\u044f";
case "BA": return "\u0411\u043e\u0441\u043d\u0438\u044f";
case "BE": return "\u0411\u0435\u043b\u044c\u0433\u0438\u044f";
case "BG": return "\u0411\u043e\u043b\u0433\u0430\u0440\u0438\u044f";
case "BR": return "\u0411\u0440\u0430\u0437\u0438\u043b\u0438\u044f";
case "CA": return "\u041a\u0430\u043d\u0430\u0434\u0430";
case "CH": return "\u0428\u0432\u0435\u0439\u0446\u0430\u0440\u0438\u044f";
case "CN": return "\u041a\u0438\u0442\u0430\u0439 (\u041a\u041d\u0420)";
case "CZ": return "\u0427\u0435\u0445\u0438\u044f";
case "DE": return "\u0413\u0435\u0440\u043c\u0430\u043d\u0438\u044f";
case "DK": return "\u0414\u0430\u043d\u0438\u044f";
case "EE": return "\u042d\u0441\u0442\u043e\u043d\u0438\u044f";
case "ES": return "\u0418\u0441\u043f\u0430\u043d\u0438\u044f";
case "FI": return "\u0424\u0438\u043d\u043b\u044f\u043d\u0434\u0438\u044f";
case "FR": return "\u0424\u0440\u0430\u043d\u0446\u0438\u044f";
case "GB": return "\u0412\u0435\u043b\u0438\u043a\u043e\u0431\u0440\u0438\u0442\u0430\u043d\u0438\u044f";
case "GR": return "\u0413\u0440\u0435\u0446\u0438\u044f";
case "HR": return "\u0425\u043e\u0440\u0432\u0430\u0442\u0438\u044f";
case "HU": return "\u0412\u0435\u043d\u0433\u0440\u0438\u044f";
case "IE": return "\u0418\u0440\u043b\u0430\u043d\u0434\u0438\u044f";
case "IL": return "\u255a\u0442\u0401\u0448\u0404";
case "IS": return "\u0418\u0441\u043b\u0430\u043d\u0434\u0438\u044f";
case "IT": return "\u0418\u0442\u0430\u043b\u0438\u044f";
case "JP": return "\u042f\u043f\u043e\u043d\u0438\u044f";
case "KR": return "\u041a\u043e\u0440\u0435\u044f";
case "LA": return "\u041b\u0430\u0442\u0438\u043d\u0441\u043a\u0430\u044f \u0410\u043c\u0435\u0440\u0438\u043a\u0430";
case "LT": return "\u041b\u0438\u0442\u0432\u0430";
case "LV": return "\u041b\u0430\u0442\u0432\u0438\u044f";
case "MK": return "\u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0438\u044f";
case "NL": return "\u041d\u0438\u0434\u0435\u0440\u043b\u0430\u043d\u0434\u044b";
case "NO": return "\u041d\u043e\u0440\u0432\u0435\u0433\u0438\u044f";
case "NZ": return "\u041d\u043e\u0432\u0430\u044f \u0417\u0435\u043b\u0430\u043d\u0434\u0438\u044f";
case "PL": return "\u041f\u043e\u043b\u044c\u0448\u0430";
case "PT": return "\u041f\u043e\u0440\u0442\u0443\u0433\u0430\u043b\u0438\u044f";
case "RO": return "\u0420\u0443\u043c\u044b\u043d\u0438\u044f";
case "RU": return "\u0420\u043e\u0441\u0441\u0438\u044f";
case "SE": return "\u0428\u0432\u0435\u0446\u0438\u044f";
case "SI": return "\u0421\u043b\u043e\u0432\u0435\u043d\u0438\u044f";
case "SK": return "\u0421\u043b\u043e\u0432\u0430\u043a\u0438\u044f";
case "SP": return "\u0421\u0435\u0440\u0431\u0438\u044f";
case "TH": return "\u0422\u0430\u0438\u043b\u0430\u043d\u0434";
case "TR": return "\u0422\u0443\u0440\u0446\u0438\u044f";
case "TW": return "\u0422\u0430\u0439\u0432\u0430\u043d\u044c";
case "UA": return "\u0423\u043A\u0440\u0430\u0438\u043D\u0430";
case "US": return "\u0421\u0428\u0410";
case "ZA": return "\u042e\u0410\u0420";
}
return base.ResolveCountry(name);
}
private class PrivateTextInfo : _I18NTextInfo
{
public PrivateTextInfo(int culture) : base(culture) {}
public override int ANSICodePage
{
get
{
return 1251;
}
}
public override int EBCDICCodePage
{
get
{
return 20880;
}
}
public override int MacCodePage
{
get
{
return 10007;
}
}
public override int OEMCodePage
{
get
{
return 866;
}
}
public override String ListSeparator
{
get
{
return ";";
}
}
}; // class PrivateTextInfo
public override TextInfo TextInfo
{
get
{
return new PrivateTextInfo(LCID);
}
}
}; // class CID0019
public class CNru : CID0019
{
public CNru() : base() {}
}; // class CNru
}; // namespace I18N.Other
| |
/* ====================================================================
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Drawing.Printing;
using System.IO;
using System.Xml;
using Oranikle.Report.Engine;
using Oranikle.Report.Viewer;
namespace Oranikle.ReportDesigner
{
/// <summary>
/// RdlReader is a application for displaying reports based on RDL.
/// </summary>
internal class MDIChild : Form
{
public delegate void RdlChangeHandler(object sender, EventArgs e);
public event RdlChangeHandler OnSelectionChanged;
public event RdlChangeHandler OnSelectionMoved;
public event RdlChangeHandler OnReportItemInserted;
public event RdlChangeHandler OnDesignTabChanged;
public event DesignCtl.OpenSubreportEventHandler OnOpenSubreport;
public event DesignCtl.HeightEventHandler OnHeightChanged;
private Oranikle.ReportDesigner.RdlEditPreview rdlDesigner;
string _SourceFile;
TabPage _Tab; // TabPage for this MDI Child
public MDIChild(int width, int height)
{
this.rdlDesigner = new Oranikle.ReportDesigner.RdlEditPreview();
this.SuspendLayout();
//
// rdlDesigner
//
this.rdlDesigner.Dock = System.Windows.Forms.DockStyle.Fill;
this.rdlDesigner.Location = new System.Drawing.Point(0, 0);
this.rdlDesigner.Name = "rdlDesigner";
this.rdlDesigner.Size = new System.Drawing.Size(width, height);
this.rdlDesigner.TabIndex = 0;
// register event for RDL changed.
rdlDesigner.OnRdlChanged += new RdlEditPreview.RdlChangeHandler(rdlDesigner_RdlChanged);
rdlDesigner.OnHeightChanged += new DesignCtl.HeightEventHandler(rdlDesigner_HeightChanged);
rdlDesigner.OnSelectionChanged += new RdlEditPreview.RdlChangeHandler(rdlDesigner_SelectionChanged);
rdlDesigner.OnSelectionMoved += new RdlEditPreview.RdlChangeHandler(rdlDesigner_SelectionMoved);
rdlDesigner.OnReportItemInserted += new RdlEditPreview.RdlChangeHandler(rdlDesigner_ReportItemInserted);
rdlDesigner.OnDesignTabChanged += new RdlEditPreview.RdlChangeHandler(rdlDesigner_DesignTabChanged);
rdlDesigner.OnOpenSubreport += new DesignCtl.OpenSubreportEventHandler(rdlDesigner_OpenSubreport);
//
// MDIChild
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(width, height);
this.Controls.Add(this.rdlDesigner);
this.Name = "";
this.Text = "";
this.Closing += new System.ComponentModel.CancelEventHandler(this.MDIChild_Closing);
this.ResumeLayout(false);
}
internal TabPage Tab
{
get { return _Tab; }
set { _Tab = value; }
}
public RdlEditPreview Editor
{
get
{
return rdlDesigner.CanEdit? rdlDesigner: null; // only return when it can edit
}
}
public RdlEditPreview RdlEditor
{
get
{
return rdlDesigner; // always return
}
}
public void ShowEditLines(bool bShow)
{
rdlDesigner.ShowEditLines(bShow);
}
internal void ShowPreviewWaitDialog(bool bShow)
{
rdlDesigner.ShowPreviewWaitDialog(bShow);
}
internal bool ShowReportItemOutline
{
get { return rdlDesigner.ShowReportItemOutline; }
set { rdlDesigner.ShowReportItemOutline = value; }
}
public string CurrentInsert
{
get {return rdlDesigner.CurrentInsert; }
set
{
rdlDesigner.CurrentInsert = value;
}
}
public int CurrentLine
{
get {return rdlDesigner.CurrentLine; }
}
public int CurrentCh
{
get {return rdlDesigner.CurrentCh; }
}
internal string DesignTab
{
get {return rdlDesigner.DesignTab;}
set { rdlDesigner.DesignTab = value; }
}
internal DesignXmlDraw DrawCtl
{
get {return rdlDesigner.DrawCtl;}
}
public XmlDocument ReportDocument
{
get {return rdlDesigner.ReportDocument;}
}
internal void SetFocus()
{
rdlDesigner.SetFocus();
}
public StyleInfo SelectedStyle
{
get {return rdlDesigner.SelectedStyle;}
}
public string SelectionName
{
get {return rdlDesigner.SelectionName;}
}
public PointF SelectionPosition
{
get {return rdlDesigner.SelectionPosition;}
}
public SizeF SelectionSize
{
get {return rdlDesigner.SelectionSize;}
}
public void ApplyStyleToSelected(string name, string v)
{
rdlDesigner.ApplyStyleToSelected(name, v);
}
public bool FileSave()
{
string file = SourceFile;
if (file == "" || file == null) // if no file name then do SaveAs
{
return FileSaveAs();
}
string rdl = GetRdlText();
return FileSave(file, rdl);
}
private bool FileSave(string file, string rdl)
{
StreamWriter writer=null;
bool bOK=true;
try
{
writer = new StreamWriter(file);
writer.Write(rdl);
// editRDL.ClearUndo();
// editRDL.Modified = false;
// SetTitle();
// statusBar.Text = "Saved " + curFileName;
}
catch (Exception ae)
{
bOK=false;
MessageBox.Show(ae.Message + "\r\n" + ae.StackTrace);
// statusBar.Text = "Save of file '" + curFileName + "' failed";
}
finally
{
writer.Close();
}
if (bOK)
this.Modified=false;
return bOK;
}
public bool Export(string type)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "Export to " + type.ToUpper();
switch (type.ToLower())
{
case "csv":
sfd.Filter = "CSV file (*.csv)|*.csv|All files (*.*)|*.*";
break;
case "dmp":
sfd.Filter = "DMP file (*.dmp)|*.dmp|All files (*.*)|*.*";
break;
case "xml":
sfd.Filter = "XML file (*.xml)|*.xml|All files (*.*)|*.*";
break;
case "pdf":
sfd.Filter = "PDF file (*.pdf)|*.pdf|All files (*.*)|*.*";
break;
case "tif": case "tiff":
sfd.Filter = "TIF file (*.tif, *.tiff)|*.tiff;*.tif|All files (*.*)|*.*";
break;
case "rtf":
sfd.Filter = "RTF file (*.rtf)|*.rtf|All files (*.*)|*.*";
break;
case "xlsx": case "excel":
type = "xlsx";
sfd.Filter = "Excel file (*.xlsx)|*.xlsx|All files (*.*)|*.*";
break;
case "html":
case "htm":
sfd.Filter = "Web Page (*.html, *.htm)|*.html;*.htm|All files (*.*)|*.*";
break;
case "mhtml":
case "mht":
sfd.Filter = "MHT (*.mht)|*.mhtml;*.mht|All files (*.*)|*.*";
break;
default:
throw new Exception("Only HTML, MHT, XML, CSV, RTF, Excel, TIF and PDF are allowed as Export types.");
}
sfd.FilterIndex = 1;
if (SourceFile != null)
sfd.FileName = Path.GetFileNameWithoutExtension(SourceFile) + "." + type;
else
sfd.FileName = "*." + type;
try
{
if (sfd.ShowDialog(this) != DialogResult.OK)
return false;
// save the report in the requested rendered format
bool rc = true;
// tif can be either in color or black and white; ask user what they want
if (type == "tif" || type == "tiff")
{
DialogResult dr = MessageBox.Show(this, "Do you want to display colors in TIF?", "Export", MessageBoxButtons.YesNoCancel);
if (dr == DialogResult.No)
type = "tifbw";
else if (dr == DialogResult.Cancel)
return false;
}
try { SaveAs(sfd.FileName, type); }
catch (Exception ex)
{
MessageBox.Show(this,
ex.Message, "Export Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
rc = false;
}
return rc;
}
finally
{
sfd.Dispose();
}
}
public bool FileSaveAs()
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "RDLC files (*.rdlc)|*.rdlc|All files (*.*)|*.*";
sfd.FilterIndex = 1;
string file = SourceFile;
sfd.FileName = file == null? "*.rdlc": file;
try
{
if (sfd.ShowDialog(this) != DialogResult.OK)
return false;
// User wants to save!
string rdl = GetRdlText();
if (FileSave(sfd.FileName, rdl))
{ // Save was successful
Text = sfd.FileName;
Tab.Text = Path.GetFileName(sfd.FileName);
_SourceFile = sfd.FileName;
Tab.ToolTipText = sfd.FileName;
return true;
}
}
finally
{
sfd.Dispose();
}
return false;
}
public string GetRdlText()
{
return this.rdlDesigner.GetRdlText();
}
public bool Modified
{
get {return rdlDesigner.Modified;}
set
{
rdlDesigner.Modified = value;
SetTitle();
}
}
/// <summary>
/// The RDL file that should be displayed.
/// </summary>
public string SourceFile
{
get {return _SourceFile;}
set
{
_SourceFile = value;
string rdl = GetRdlSource();
this.rdlDesigner.SetRdlText(rdl == null? "": rdl);
}
}
public string SourceRdl
{
get {return this.rdlDesigner.GetRdlText();}
set {this.rdlDesigner.SetRdlText(value);}
}
private string GetRdlSource()
{
StreamReader fs=null;
string prog=null;
try
{
fs = new StreamReader(_SourceFile);
prog = fs.ReadToEnd();
}
finally
{
if (fs != null)
fs.Close();
}
return prog;
}
/// <summary>
/// Number of pages in the report.
/// </summary>
public int PageCount
{
get {return this.rdlDesigner.PageCount;}
}
/// <summary>
/// Current page in view on report
/// </summary>
public int PageCurrent
{
get {return this.rdlDesigner.PageCurrent;}
}
/// <summary>
/// Page height of the report.
/// </summary>
public float PageHeight
{
get {return this.rdlDesigner.PageHeight;}
}
/// <summary>
/// Turns the Selection Tool on in report preview
/// </summary>
public bool SelectionTool
{
get
{
return this.rdlDesigner.SelectionTool;
}
set
{
this.rdlDesigner.SelectionTool = value;
}
}
/// <summary>
/// Page width of the report.
/// </summary>
public float PageWidth
{
get {return this.rdlDesigner.PageWidth;}
}
/// <summary>
/// Zoom
/// </summary>
public float Zoom
{
get {return this.rdlDesigner.Zoom;}
set {this.rdlDesigner.Zoom = value;}
}
/// <summary>
/// ZoomMode
/// </summary>
public ZoomEnum ZoomMode
{
get {return this.rdlDesigner.ZoomMode;}
set {this.rdlDesigner.ZoomMode = value;}
}
/// <summary>
/// Print the report.
/// </summary>
public void Print(PrintDocument pd)
{
this.rdlDesigner.Print(pd);
}
public void SaveAs(string filename, string ext)
{
rdlDesigner.SaveAs(filename, ext);
}
private void MDIChild_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (!OkToClose())
{
e.Cancel = true;
return;
}
if (Tab == null)
return;
Control ctl = Tab.Parent;
ctl.Controls.Remove(Tab);
Tab.Tag = null; // this is the Tab reference to this
Tab = null;
}
public bool OkToClose()
{
if (!this.Modified)
return true;
DialogResult r =
MessageBox.Show(this, String.Format("Do you want to save changes you made to '{0}'?",
_SourceFile==null?"Untitled":Path.GetFileName(_SourceFile)),
"Oranikle Reporting Designer",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Exclamation,MessageBoxDefaultButton.Button3);
bool bOK = true;
if (r == DialogResult.Cancel)
bOK = false;
else if (r == DialogResult.Yes)
{
if (!FileSave())
bOK = false;
}
return bOK;
}
private void rdlDesigner_RdlChanged(object sender, System.EventArgs e)
{
SetTitle();
}
private void rdlDesigner_HeightChanged(object sender, HeightEventArgs e)
{
if (OnHeightChanged != null)
OnHeightChanged(this, e);
}
private void rdlDesigner_SelectionChanged(object sender, System.EventArgs e)
{
if (OnSelectionChanged != null)
OnSelectionChanged(this, e);
}
private void rdlDesigner_DesignTabChanged(object sender, System.EventArgs e)
{
if (OnDesignTabChanged != null)
OnDesignTabChanged(this, e);
}
private void rdlDesigner_ReportItemInserted(object sender, System.EventArgs e)
{
if (OnReportItemInserted != null)
OnReportItemInserted(this, e);
}
private void rdlDesigner_SelectionMoved(object sender, System.EventArgs e)
{
if (OnSelectionMoved != null)
OnSelectionMoved(this, e);
}
private void rdlDesigner_OpenSubreport(object sender, SubReportEventArgs e)
{
if (OnOpenSubreport != null)
{
OnOpenSubreport(this, e);
}
}
private void InitializeComponent()
{
this.SuspendLayout();
//
// MDIChild
//
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(228)))), ((int)(((byte)(241)))), ((int)(((byte)(249)))));
this.ClientSize = new System.Drawing.Size(284, 262);
this.Name = "MDIChild";
this.ResumeLayout(false);
}
private void SetTitle()
{
string title = this.Text;
if (title.Length < 1)
return;
char m = title[title.Length-1];
if (this.Modified)
{
if (m != '*')
title = title + "*";
}
else if (m == '*')
title = title.Substring(0, title.Length-1);
if (title != this.Text)
this.Text = title;
return;
}
public Oranikle.Report.Viewer.RdlViewer Viewer
{
get {return rdlDesigner.Viewer;}
}
}
}
| |
/*
* InformationMachineAPI.PCL
*
*
*/
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using InformationMachineAPI.PCL;
namespace InformationMachineAPI.PCL.Models
{
public class RecalledProductPurchaseData : INotifyPropertyChanged
{
// These fields hold the values for the public properties.
private long productId;
private long id;
private long storeId;
private string storeName;
private DateTime? orderPurchaseDate;
private DateTime? orderRecordedAt;
private string orderNumber;
private string email;
private string zip;
private string userId;
private string clientId;
private DateTime? userCreatedAt;
/// <summary>
/// TODO: Write general description for this method
/// </summary>
[JsonProperty("product_id")]
public long ProductId
{
get
{
return this.productId;
}
set
{
this.productId = value;
onPropertyChanged("ProductId");
}
}
/// <summary>
/// TODO: Write general description for this method
/// </summary>
[JsonProperty("id")]
public long Id
{
get
{
return this.id;
}
set
{
this.id = value;
onPropertyChanged("Id");
}
}
/// <summary>
/// TODO: Write general description for this method
/// </summary>
[JsonProperty("store_id")]
public long StoreId
{
get
{
return this.storeId;
}
set
{
this.storeId = value;
onPropertyChanged("StoreId");
}
}
/// <summary>
/// TODO: Write general description for this method
/// </summary>
[JsonProperty("store_name")]
public string StoreName
{
get
{
return this.storeName;
}
set
{
this.storeName = value;
onPropertyChanged("StoreName");
}
}
/// <summary>
/// TODO: Write general description for this method
/// </summary>
[JsonProperty("order_purchase_date")]
public DateTime? OrderPurchaseDate
{
get
{
return this.orderPurchaseDate;
}
set
{
this.orderPurchaseDate = value;
onPropertyChanged("OrderPurchaseDate");
}
}
/// <summary>
/// TODO: Write general description for this method
/// </summary>
[JsonProperty("order_recorded_at")]
public DateTime? OrderRecordedAt
{
get
{
return this.orderRecordedAt;
}
set
{
this.orderRecordedAt = value;
onPropertyChanged("OrderRecordedAt");
}
}
/// <summary>
/// TODO: Write general description for this method
/// </summary>
[JsonProperty("order_number")]
public string OrderNumber
{
get
{
return this.orderNumber;
}
set
{
this.orderNumber = value;
onPropertyChanged("OrderNumber");
}
}
/// <summary>
/// TODO: Write general description for this method
/// </summary>
[JsonProperty("email")]
public string Email
{
get
{
return this.email;
}
set
{
this.email = value;
onPropertyChanged("Email");
}
}
/// <summary>
/// TODO: Write general description for this method
/// </summary>
[JsonProperty("zip")]
public string Zip
{
get
{
return this.zip;
}
set
{
this.zip = value;
onPropertyChanged("Zip");
}
}
/// <summary>
/// TODO: Write general description for this method
/// </summary>
[JsonProperty("user_id")]
public string UserId
{
get
{
return this.userId;
}
set
{
this.userId = value;
onPropertyChanged("UserId");
}
}
/// <summary>
/// TODO: Write general description for this method
/// </summary>
[JsonProperty("client_id")]
public string ClientId
{
get
{
return this.clientId;
}
set
{
this.clientId = value;
onPropertyChanged("ClientId");
}
}
/// <summary>
/// TODO: Write general description for this method
/// </summary>
[JsonProperty("user_created_at")]
public DateTime? UserCreatedAt
{
get
{
return this.userCreatedAt;
}
set
{
this.userCreatedAt = value;
onPropertyChanged("UserCreatedAt");
}
}
/// <summary>
/// Property changed event for observer pattern
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises event when a property is changed
/// </summary>
/// <param name="propertyName">Name of the changed property</param>
protected void onPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.LogReceiverService
{
using System;
using System.IO;
#if WCF_SUPPORTED
using System.Runtime.Serialization;
#endif
using System.Xml;
using System.Xml.Serialization;
using NUnit.Framework;
#if !NUNIT
using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
using TearDown = Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute;
#endif
using NLog.Layouts;
using NLog.LogReceiverService;
[TestFixture]
public class LogReceiverServiceTests : NLogTestBase
{
[Test]
public void ToLogEventInfoTest()
{
var events = new NLogEvents
{
BaseTimeUtc = new DateTime(2010, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks,
ClientName = "foo",
LayoutNames = new StringCollection { "foo", "bar", "baz" },
Strings = new StringCollection { "logger1", "logger2", "logger3", "zzz", "message1" },
Events =
new[]
{
new NLogEvent
{
Id = 1,
LevelOrdinal = 2,
LoggerOrdinal = 0,
TimeDelta = 30000000,
MessageOrdinal = 4,
Values = "0|1|2"
},
new NLogEvent
{
Id = 2,
LevelOrdinal = 3,
LoggerOrdinal = 2,
MessageOrdinal = 4,
TimeDelta = 30050000,
Values = "0|1|3",
}
}
};
var converted = events.ToEventInfo();
Assert.AreEqual(2, converted.Count);
Assert.AreEqual("message1", converted[0].FormattedMessage);
Assert.AreEqual("message1", converted[1].FormattedMessage);
Assert.AreEqual(new DateTime(2010, 1, 1, 0, 0, 3, 0, DateTimeKind.Utc), converted[0].TimeStamp.ToUniversalTime());
Assert.AreEqual(new DateTime(2010, 1, 1, 0, 0, 3, 5, DateTimeKind.Utc), converted[1].TimeStamp.ToUniversalTime());
Assert.AreEqual("logger1", converted[0].LoggerName);
Assert.AreEqual("logger3", converted[1].LoggerName);
Assert.AreEqual(LogLevel.Info, converted[0].Level);
Assert.AreEqual(LogLevel.Warn, converted[1].Level);
Layout fooLayout = "${event-context:foo}";
Layout barLayout = "${event-context:bar}";
Layout bazLayout = "${event-context:baz}";
Assert.AreEqual("logger1", fooLayout.Render(converted[0]));
Assert.AreEqual("logger1", fooLayout.Render(converted[1]));
Assert.AreEqual("logger2", barLayout.Render(converted[0]));
Assert.AreEqual("logger2", barLayout.Render(converted[1]));
Assert.AreEqual("logger3", bazLayout.Render(converted[0]));
Assert.AreEqual("zzz", bazLayout.Render(converted[1]));
}
[Test]
public void NoLayoutsTest()
{
var events = new NLogEvents
{
BaseTimeUtc = new DateTime(2010, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks,
ClientName = "foo",
LayoutNames = new StringCollection(),
Strings = new StringCollection { "logger1", "logger2", "logger3", "zzz", "message1" },
Events =
new[]
{
new NLogEvent
{
Id = 1,
LevelOrdinal = 2,
LoggerOrdinal = 0,
TimeDelta = 30000000,
MessageOrdinal = 4,
Values = null,
},
new NLogEvent
{
Id = 2,
LevelOrdinal = 3,
LoggerOrdinal = 2,
MessageOrdinal = 4,
TimeDelta = 30050000,
Values = null,
}
}
};
var converted = events.ToEventInfo();
Assert.AreEqual(2, converted.Count);
Assert.AreEqual("message1", converted[0].FormattedMessage);
Assert.AreEqual("message1", converted[1].FormattedMessage);
Assert.AreEqual(new DateTime(2010, 1, 1, 0, 0, 3, 0, DateTimeKind.Utc), converted[0].TimeStamp.ToUniversalTime());
Assert.AreEqual(new DateTime(2010, 1, 1, 0, 0, 3, 5, DateTimeKind.Utc), converted[1].TimeStamp.ToUniversalTime());
Assert.AreEqual("logger1", converted[0].LoggerName);
Assert.AreEqual("logger3", converted[1].LoggerName);
Assert.AreEqual(LogLevel.Info, converted[0].Level);
Assert.AreEqual(LogLevel.Warn, converted[1].Level);
}
#if !SILVERLIGHT && !NET_CF && !NET2_0
/// <summary>
/// Ensures that serialization formats of DataContractSerializer and XmlSerializer are the same
/// on the same <see cref="NLogEvents"/> object.
/// </summary>
[Test]
public void CompareSerializationFormats()
{
var events = new NLogEvents
{
BaseTimeUtc = DateTime.UtcNow.Ticks,
ClientName = "foo",
LayoutNames = new StringCollection { "foo", "bar", "baz" },
Strings = new StringCollection { "logger1", "logger2", "logger3" },
Events =
new[]
{
new NLogEvent
{
Id = 1,
LevelOrdinal = 2,
LoggerOrdinal = 0,
TimeDelta = 34,
Values = "1|2|3"
},
new NLogEvent
{
Id = 2,
LevelOrdinal = 3,
LoggerOrdinal = 2,
TimeDelta = 345,
Values = "1|2|3",
}
}
};
var serializer1 = new XmlSerializer(typeof(NLogEvents));
var sw1 = new StringWriter();
using (var writer1 = XmlWriter.Create(sw1, new XmlWriterSettings { Indent = true }))
{
var namespaces = new XmlSerializerNamespaces();
namespaces.Add("i", "http://www.w3.org/2001/XMLSchema-instance");
serializer1.Serialize(writer1, events, namespaces);
}
var serializer2 = new DataContractSerializer(typeof(NLogEvents));
var sw2 = new StringWriter();
using (var writer2 = XmlWriter.Create(sw2, new XmlWriterSettings { Indent = true }))
{
serializer2.WriteObject(writer2, events);
}
var xml1 = sw1.ToString();
var xml2 = sw2.ToString();
Assert.AreEqual(xml1, xml2);
}
#endif
}
}
| |
/*
* XFileTokenizer.cs
* Copyright (c) 2006, 2007 David Astle
*
* 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.
*/
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using System.Text;
using System.IO;
using System.Globalization;
#endregion
namespace FlatRedBall.Graphics.Model.Animation.Content
{
/// <summary>
/// Tokenizes a .X file and provides methods to parse those tokens.
/// </summary>
public sealed class XFileTokenizer
{
#region Member Variables
// Use an invariant number formatter so the parse methods will work on computers from all
// nations
// Used to build each token so that we don't have to deal with the inefficiency of
// string concatenation.
private StringBuilder sb = new StringBuilder();
// Designates the starting index of the stringbuilder for the current token
// we are building. This allows us to not clear the string builder every time
// we start building a new token, and increases performance.
private int index = 0;
// The length of the current token.
private int length = 0;
// Stores the index of the current token when other classes are using this to read a
// a file.
private int tokenIndex = 0;
private Stack<long> parseIndices = new Stack<long>();
private List<string> tokens;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of XFileTokenizer.
/// </summary>
/// <param name="fileName">The .X file to tokenize.</param>
public XFileTokenizer(string fileName)
{
string s = "";
using (System.IO.StreamReader sr = new System.IO.StreamReader(fileName))
{
s = sr.ReadToEnd();
sr.Close();
}
//string s = File.ReadAllText(fileName);
tokens = TokensFromString(s);
}
#endregion
#region Properties
/// <summary>
/// Returns current token while ITERATING through the tokens
/// </summary>
public string CurrentToken
{ get { return tokens[tokenIndex - 1]; } }
/// <summary>
/// Returns the next token without advancing the stream index
/// </summary>
public string Peek
{ get { return tokens[tokenIndex]; } }
// Returns current string while BUILDING the tokens
private string CurrentString
{ get { return sb.ToString(index, length); } }
/// <summary>
/// True if the index is at the end of the stream.
/// </summary>
public bool AtEnd
{ get { return tokenIndex >= tokens.Count - 1; } }
/// <summary>
/// The number of tokens in the stream.
/// </summary>
public int Count
{ get { return tokens.Count; } }
#endregion
#region Methods
// Adds a character to our current token.
private void AddChar(int c)
{
sb.Append((char)c);
length++;
}
// Tells the stringbuilder that we are starting a new token.
private void ResetString()
{
index = index + length;
// clear sb if it is getting too big; allows us to read long files
if (index > int.MaxValue / 2)
{
sb.Remove(0, sb.Length);
index = 0;
}
length = 0;
}
// When parsing a token fails, throws an error that says
// what tokens surround the ill-parsed token
private void Throw(Type type, Exception innerException, String inputString)
{
string error = "Failed to parse " + type.ToString() +
" from string \"" + inputString + "\" at token number " +
tokenIndex.ToString() + "\nvalue: " +
tokens[tokenIndex] + "\nSurrounding tokens: \n";
int start = tokenIndex - 15;
if (start < 0)
start = 0;
long end = tokenIndex + 15;
if (end > Count - 1)
end = Count - 1;
for (int i = start; i <= end; i++)
{
if (i == tokenIndex)
error += "*" + tokens[i];
else
error += tokens[i];
error += "|||";
}
throw new Exception(error, innerException);
}
/// <summary>
/// Skips a node in a .X file and all child nodes; should be called after the opening
/// brace, "{", has been read.
/// </summary>
public void SkipNode()
{
string next = NextToken();
while (next != "}")
if ((next = NextToken()) == "{")
SkipNode();
}
/// <summary>
/// Parses an integer from a .X file
/// </summary>
/// <returns>The integer represented by the next token</returns>
public int NextInt()
{
int x = 0;
try
{
x = int.Parse(tokens[tokenIndex++]);
}
catch (Exception e)
{
Throw(typeof(int), e, tokens[tokenIndex]);
}
tokenIndex++;
return x;
}
/// <summary>
/// Parses a float from a .X file
/// </summary>
/// <returns>The float represented by the next token</returns>
public float NextFloat()
{
float x = 0;
try
{
x = float.Parse(tokens[tokenIndex++], System.Globalization.NumberStyles.Float);
}
catch (Exception e)
{
Throw(typeof(float), e, tokens[tokenIndex]);
}
finally
{
tokenIndex++;
}
return x;
}
/// <summary>
/// The current token index of the tokenizer.
/// </summary>
public long CurrentIndex
{
get { return tokenIndex; }
}
/// <summary>
/// Parses a string from a .X file
/// </summary>
/// <returns>The string represented by the next token</returns>
public string NextString()
{
string s = NextToken().Trim('"');
SkipToken();
return s;
}
/// <summary>
/// Reads a generic token from a .X file
/// </summary>
/// <returns>The next token</returns>
public string NextToken()
{
string s = null;
try
{
s = tokens[tokenIndex];
}
catch
{
string error = "Tried to read token when there were " +
" no more tokens left.";
error += "\n";
error += "Token Index: " + tokenIndex;
throw new IndexOutOfRangeException(error);
}
finally
{
tokenIndex++;
}
return s;
}
/// <summary>
/// Reads the next Vector2 in the stream.
/// </summary>
/// <returns>The parsed Vector2</returns>
public Vector2 NextVector2()
{
try
{
Vector2 v = new Vector2(
float.Parse(tokens[tokenIndex]),
float.Parse(tokens[tokenIndex + 2]));
return v;
}
catch (Exception e)
{
Throw(typeof(Vector2), e, tokens[tokenIndex]);
}
finally
{
tokenIndex += 5;
}
return Vector2.Zero;
}
/// <summary>
/// Reads the next Vector3 in the stream.
/// </summary>
/// <returns>The parsed Vector3</returns>
public Vector3 NextVector3()
{
try
{
Vector3 v = new Vector3(
float.Parse(tokens[tokenIndex]),
float.Parse(tokens[tokenIndex + 2]),
float.Parse(tokens[tokenIndex + 4]));
return v;
}
catch (Exception e)
{
Throw(typeof(Vector3), e, tokens[tokenIndex]);
}
finally
{
tokenIndex += 7;
}
return Vector3.Zero;
}
/// <summary>
/// Reads the next Vector4 in the stream.
/// </summary>
/// <returns>The parsed Vector4</returns>
public Vector4 NextVector4()
{
tokenIndex += 9;
try
{
Vector4 v = new Vector4(
float.Parse(tokens[tokenIndex - 9]),
float.Parse(tokens[tokenIndex - 7]),
float.Parse(tokens[tokenIndex - 5]),
float.Parse(tokens[tokenIndex - 3]));
return v;
}
catch (Exception e)
{
Throw(typeof(Vector4), e, tokens[tokenIndex]);
}
return Vector4.Zero;
}
/// <summary>
/// Reads the next Matrix in the stream.
/// </summary>
/// <returns>The parsed Matrix</returns>
public Matrix NextMatrix()
{
try
{
Matrix m = new Matrix(
float.Parse(tokens[tokenIndex]), float.Parse(tokens[tokenIndex + 2]),
float.Parse(tokens[tokenIndex + 4]), float.Parse(tokens[tokenIndex + 6]),
float.Parse(tokens[tokenIndex + 8]), float.Parse(tokens[tokenIndex + 10]),
float.Parse(tokens[tokenIndex + 12]), float.Parse(tokens[tokenIndex + 14]),
float.Parse(tokens[tokenIndex + 16]), float.Parse(tokens[tokenIndex + 18]),
float.Parse(tokens[tokenIndex + 20]), float.Parse(tokens[tokenIndex + 22]),
float.Parse(tokens[tokenIndex + 24]), float.Parse(tokens[tokenIndex + 26]),
float.Parse(tokens[tokenIndex + 28]), float.Parse(tokens[tokenIndex + 30]));
return m;
}
catch (Exception e)
{
Throw(typeof(Matrix), e, tokens[tokenIndex]);
}
finally
{
tokenIndex += 33;
}
return new Matrix();
}
/// <summary>
/// Skips tokens in the stream.
/// </summary>
/// <returns>The number of tokens to skip.</returns>
public void SkipTokens(int numToSkip)
{ tokenIndex += numToSkip; }
/// <summary>
/// Skips a nodes name and its opening curly bracket.
/// </summary>
/// <returns>The current instance for cascaded calls.</returns>
public XFileTokenizer SkipName()
{
ReadName();
return this;
}
/// <summary>
/// Reads a nodes name and its opening curly bracket.
/// </summary>
/// <returns>Null if the node does not contain a name, the nodes name otherwise.</returns>
public string ReadName()
{
string next = tokens[tokenIndex++];
if (next != "{")
{
tokenIndex++;
return next;
}
return null;
}
/// <summary>
/// Skips a token in the stream.
/// </summary>
/// <returns>The current tokenizer for cascaded calls.</returns>
public XFileTokenizer SkipToken()
{
tokenIndex++;
return this;
}
/// <summary>
/// Resets the tokenizer to the beginning of the stream.
/// </summary>
public void Reset()
{
tokenIndex = 0;
sb.Remove(0, sb.Length);
index = 0;
length = 0;
}
// Takes a string and turns it into an array of tokens. This is created for performance
// over readability. It is far longer than it *needs* to be and
// uses a finite state machine to parse the tokens.
private List<string> TokensFromString(string ms)
{
// If we are currently in a state of the FSM such that we are building a token,
// this is set to a positive value indicating the state.
int groupnum = -1;
// Each state in which we build a token is further broken up into substates.
// This indicates the location in our current state.
int groupLoc = 1;
// Since we dont know before hand how big our token array is, and we want
// it to pack nicely into an array, we can use is a list.
List<string> strings = new List<string>();
// The length of the string
long msLength = ms.Length;
for (int i = 0; i < msLength; i++)
{
// Current character
int c = ms[i];
// Yes, I used a goto. They are generally ok in switch statements, although
// I'm extending my welcome here. The code goes to FSMSTART whenever
// we have broken out of a state and want to transition to the start state
// (that is, we are not currently building a token).
FSMSTART:
switch (groupnum)
{
// State in which we are building a number token
case 0:
switch (groupLoc)
{
// check if it has - sign
case 1:
if (c == '-')
{
AddChar(c);
groupLoc = 2;
break;
}
else if (c >= '0' && c <= '9')
{
AddChar(c);
groupLoc = 3;
break;
}
goto default;
// we are passed minus sign but before period
// A number most proceed a minus sign, but not necessarily
// precede a period without a minus sign.
case 2:
if (c >= '0' && c <= '9')
{
AddChar(c);
groupLoc = 3;
break;
}
goto default;
// It is alright to accept a period now
case 3:
if (c >= '0' && c <= '9' || c=='E' || c=='e')
{
AddChar(c);
break;
}
else if (c == '.')
{
AddChar(c);
groupLoc = 4;
break;
}
// we are done with the token because the next char
// is not part of a number
strings.Add(CurrentString);
ResetString();
groupLoc = 1;
groupnum = -1;
goto FSMSTART;
// we are just passed period, waiting for a number
case 4:
if (c >= '0' && c <= '9')
{
groupLoc = 5;
AddChar(c);
break;
}
goto default;
// we are passed period and the number after it
case 5:
if (c >= '0' && c <= '9')
{
AddChar(c);
break;
}
strings.Add(CurrentString);
ResetString();
groupLoc = 1;
groupnum = -1;
goto FSMSTART;
// token does not make a valid number, ignore it and
// move on
default:
groupLoc = 1;
groupnum = -1;
ResetString();
break;
}
break;
// a string (may or may not start with " and ends with ")
case 1:
switch (groupLoc)
{
// first character
case 1:
AddChar(c);
if (c == '"')
groupLoc = 3;
else
groupLoc = 2;
break;
// not a string
case 2:
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
|| c == '_' || (c >= '0' && c <= '9') || c == '.' || c == '-'
|| c== '/' || c=='\\' || c==':')
{
AddChar(c);
break;
}
strings.Add(CurrentString);
ResetString();
groupLoc = 1;
groupnum = -1;
goto FSMSTART;
// is a string
case 3:
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
|| c == '_' || (c >= '0' && c <= '9') || c == '.' || c == '-'
|| c == '/' || c == '\\' || c == ':' || c==' ')
{
AddChar(c);
break;
}
// end of string
else if (c == '"')
{
AddChar(c);
strings.Add(CurrentString);
ResetString();
groupLoc = 1;
groupnum = -1;
break;
}
strings.Add(CurrentString);
ResetString();
groupLoc = 1;
groupnum = -1;
goto FSMSTART;
// token does not make a valid string; ignore and move on
default:
groupLoc = 1;
groupnum = -1;
ResetString();
break;
}
break;
// A constraint identifier OR array. Read about X file format
// to see what this is (i.e., [...])
case 2:
switch (groupLoc)
{
// Read first char ([)
case 1:
AddChar(c);
groupLoc = 2;
break;
// can now accept letters or periods
case 2:
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
{
AddChar(c);
groupLoc = 3;
break;
}
else if (c == ' ' || c == '.')
{
if (c != ' ')
AddChar(c);
groupLoc = 5;
break;
}
// Since first token after [ is a #, this is an array
else if (c >= '0' && c <= '9')
{
AddChar(c);
groupLoc = 4;
break;
}
goto default;
// passed first letter. Can now accept a variety
// of chars
case 3:
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
|| c == '_' || (c >= '0' && c <= '9'))
{
AddChar(c);
break;
}
else if (c == ']')
goto case 10;
goto default;
// we are reading an array and can at this point only accept
// numbers
case 4:
if (c >= '0' && c <= '9')
{
AddChar(c);
break;
}
else if (c == ']')
goto case 10;
goto default;
// can acept periods or spaces (open constraint identifier)
case 5:
if (c == '.' || c == ' ')
{
AddChar(c);
break;
}
else if (c == ']')
goto case 10;
goto default;
// we have finished a valid token
case 10:
AddChar(c);
strings.Add(CurrentString);
ResetString();
groupLoc = 1;
groupnum = -1;
break;
// token is invalid
default:
ResetString();
groupLoc = 1;
groupnum = -1;
break;
}
break;
// A guid (starts with < ends with >)
case 3:
switch (groupLoc)
{
// first char (<)
case 1:
AddChar(c); ;
groupLoc = 2;
break;
// after first character can accept alphanumeric chars, spaces, and hyphens,
// but there must be at leaast on char between < and >
case 2:
if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
|| c == '-' || c == ' ')
{
if (c != ' ')
AddChar(c);
groupLoc = 3;
break;
}
goto default;
// same as case 2 except we have read one token after start
case 3:
if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
|| c == '-' || c == ' ')
{
if (c != ' ')
AddChar(c);
break;
}
// valid GUID
else if (c == '>')
{
AddChar(c);
strings.Add(CurrentString);
ResetString();
groupLoc = 1;
groupnum = -1;
break;
}
goto default;
// invalid token
default:
ResetString();
groupLoc = 1;
groupnum = -1;
break;
}
break;
// reset group location on new line after reading a comment
case 5:
if (c == '\n')
{
groupLoc = 1;
groupnum = -1;
}
break;
case -1:
// characters that comprise tokens alone
if (c == ';' || c == ',' || c == '{' || c == '}')
{
strings.Add(((char)c).ToString());
ResetString();
groupLoc = 1;
groupnum = -1;
break;
}
// an array or constraint identfiier
else if (c == '[')
{
groupnum = 2;
goto case 2;
}
// a guid
else if (c == '<')
{
groupnum = 3;
goto case 3;
}
// a string or name
else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
|| c == '"' || c=='_')
{
groupnum = 1;
goto case 1;
}
// a number
else if ((c == '-') || (c >= '0' && c <= '9'))
{
groupnum = 0;
goto case 0;
}
// a comment
else if (c == '/' || c == '#')
{
groupnum = 5;
goto case 5;
}
break;
default:
break;
}
}
return strings;
}
#endregion
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Messages.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Raft.Messages {
/// <summary>Holder for reflection information generated from Messages.proto</summary>
public static partial class MessagesReflection {
#region Descriptor
/// <summary>File descriptor for Messages.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static MessagesReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cg5NZXNzYWdlcy5wcm90byJDCgRUZXN0Eg0KBXF1ZXJ5GAEgASgJEhMKC3Bh",
"Z2VfbnVtYmVyGAIgASgFEhcKD3Jlc3VsdF9wZXJfcGFnZRgDIAEoBUIQqgIN",
"UmFmdC5NZXNzYWdlc2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Raft.Messages.Test), global::Raft.Messages.Test.Parser, new[]{ "Query", "PageNumber", "ResultPerPage" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class Test : pb::IMessage<Test> {
private static readonly pb::MessageParser<Test> _parser = new pb::MessageParser<Test>(() => new Test());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Test> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Raft.Messages.MessagesReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Test() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Test(Test other) : this() {
query_ = other.query_;
pageNumber_ = other.pageNumber_;
resultPerPage_ = other.resultPerPage_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Test Clone() {
return new Test(this);
}
/// <summary>Field number for the "query" field.</summary>
public const int QueryFieldNumber = 1;
private string query_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Query {
get { return query_; }
set {
query_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "page_number" field.</summary>
public const int PageNumberFieldNumber = 2;
private int pageNumber_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int PageNumber {
get { return pageNumber_; }
set {
pageNumber_ = value;
}
}
/// <summary>Field number for the "result_per_page" field.</summary>
public const int ResultPerPageFieldNumber = 3;
private int resultPerPage_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int ResultPerPage {
get { return resultPerPage_; }
set {
resultPerPage_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Test);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Test other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Query != other.Query) return false;
if (PageNumber != other.PageNumber) return false;
if (ResultPerPage != other.ResultPerPage) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Query.Length != 0) hash ^= Query.GetHashCode();
if (PageNumber != 0) hash ^= PageNumber.GetHashCode();
if (ResultPerPage != 0) hash ^= ResultPerPage.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Query.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Query);
}
if (PageNumber != 0) {
output.WriteRawTag(16);
output.WriteInt32(PageNumber);
}
if (ResultPerPage != 0) {
output.WriteRawTag(24);
output.WriteInt32(ResultPerPage);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Query.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Query);
}
if (PageNumber != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(PageNumber);
}
if (ResultPerPage != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(ResultPerPage);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Test other) {
if (other == null) {
return;
}
if (other.Query.Length != 0) {
Query = other.Query;
}
if (other.PageNumber != 0) {
PageNumber = other.PageNumber;
}
if (other.ResultPerPage != 0) {
ResultPerPage = other.ResultPerPage;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Query = input.ReadString();
break;
}
case 16: {
PageNumber = input.ReadInt32();
break;
}
case 24: {
ResultPerPage = input.ReadInt32();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections.Generic;
using System.Linq;
using BTDB.Buffer;
using BTDB.EventStoreLayer;
using NUnit.Framework;
namespace BTDBTest
{
[TestFixture]
public class EventStoreTest
{
[Test]
public void CanWriteSimpleEvent()
{
var manager = new EventStoreManager();
var appender = manager.AppendToStore(new MemoryEventFileStorage());
appender.Store(null, new object[] { 1 });
var eventObserver = new StoringEventObserver();
appender.ReadFromStartToEnd(eventObserver);
Assert.AreEqual(new object[] { null }, eventObserver.Metadata);
Assert.AreEqual(new[] { new object[] { 1 } }, eventObserver.Events);
Assert.True(appender.IsKnownAsAppendable());
Assert.False(appender.IsKnownAsCorrupted());
Assert.False(appender.IsKnownAsFinished());
Assert.AreEqual(10, appender.KnownAppendablePosition());
}
[Test]
public void CanFinalizeEventStore()
{
var manager = new EventStoreManager();
var appender = manager.AppendToStore(new MemoryEventFileStorage());
appender.FinalizeStore();
Assert.False(appender.IsKnownAsAppendable());
Assert.False(appender.IsKnownAsCorrupted());
Assert.True(appender.IsKnownAsFinished());
}
[Test]
public void CanFinalizeEventStoreAfterReadFromStart()
{
var manager = new EventStoreManager();
manager.CompressionStrategy = new NoCompressionStrategy();
var file1 = new MemoryEventFileStorage(4096, 4096);
var appender = manager.AppendToStore(file1);
appender.Store(null, new object[] { new byte[4000] });
appender.Store(null, new object[] { new byte[4000] });
Assert.AreNotSame(file1, appender.CurrentFileStorage);
var reader = manager.OpenReadOnlyStore(file1);
reader.ReadFromStartToEnd(new SkippingEventObserver());
Assert.False(reader.IsKnownAsAppendable());
Assert.False(reader.IsKnownAsCorrupted());
Assert.True(reader.IsKnownAsFinished());
Assert.True(appender.IsKnownAsAppendable());
Assert.False(appender.IsKnownAsCorrupted());
Assert.False(appender.IsKnownAsFinished());
}
[Test]
public void CanReadLongerEventsFromIncompleteFile()
{
var manager = new EventStoreManager();
manager.CompressionStrategy = new NoCompressionStrategy();
var file1 = new MemoryEventFileStorage();
var appender = manager.AppendToStore(file1);
appender.Store(null, new object[] { new byte[8000] });
var file2 = new MemoryEventFileStorage();
var buf = ByteBuffer.NewSync(new byte[4096]);
file1.Read(buf, 0);
file2.Write(buf, 0);
var reader = manager.OpenReadOnlyStore(file2);
reader.ReadFromStartToEnd(new SkippingEventObserver());
Assert.False(reader.IsKnownAsCorrupted());
Assert.False(reader.IsKnownAsAppendable());
Assert.False(reader.IsKnownAsFinished());
buf = ByteBuffer.NewSync(new byte[4096]);
file1.Read(buf, 4096);
file2.Write(buf, 4096);
reader.ReadToEnd(new SkippingEventObserver());
Assert.False(reader.IsKnownAsCorrupted());
Assert.True(reader.IsKnownAsAppendable());
Assert.False(reader.IsKnownAsFinished());
}
[Test]
public void CanFinalizeEventStoreOnEverySectorPosition()
{
for (int i = 4000; i < 4600; i++)
{
var manager = new EventStoreManager();
manager.CompressionStrategy = new NoCompressionStrategy();
var file1 = new MemoryEventFileStorage(4096, 8192);
var appender = manager.AppendToStore(file1);
appender.Store(null, new object[] { new byte[i] });
appender.Store(null, new object[] { new byte[7000] });
}
}
[Test]
public void CanFinalizeEventStoreAfterReadFromStartFirstNearlyFull()
{
var manager = new EventStoreManager();
manager.CompressionStrategy = new NoCompressionStrategy();
var file1 = new MemoryEventFileStorage(4096, 4096);
var appender = manager.AppendToStore(file1);
appender.Store(null, new object[] { new byte[4080] });
appender.Store(null, new object[] { new byte[4000] });
Assert.AreNotSame(file1, appender.CurrentFileStorage);
var reader = manager.OpenReadOnlyStore(file1);
reader.ReadFromStartToEnd(new SkippingEventObserver());
Assert.False(reader.IsKnownAsAppendable());
Assert.False(reader.IsKnownAsCorrupted());
Assert.True(reader.IsKnownAsFinished());
Assert.True(appender.IsKnownAsAppendable());
Assert.False(appender.IsKnownAsCorrupted());
Assert.False(appender.IsKnownAsFinished());
}
[Test]
public void CreatesNewFileWhenOldOneIsFull()
{
var manager = new EventStoreManager();
var appender = manager.AppendToStore(new MemoryEventFileStorage());
appender.Store(null, new object[] { 1 });
appender.ReadFromStartToEnd(new SkippingEventObserver());
appender.FinalizeStore();
Assert.False(appender.IsKnownAsAppendable());
Assert.False(appender.IsKnownAsCorrupted());
Assert.True(appender.IsKnownAsFinished());
}
class StoringEventObserver : IEventStoreObserver
{
public readonly List<object> Metadata = new List<object>();
public readonly List<object[]> Events = new List<object[]>();
uint _lastEventCount;
public bool ObservedMetadata(object metadata, uint eventCount)
{
Metadata.Add(metadata);
_lastEventCount = eventCount;
return true;
}
public virtual bool ShouldStopReadingNextEvents()
{
return false;
}
public void ObservedEvents(object[] events)
{
Assert.AreEqual(_lastEventCount, events.Length);
Events.Add(events);
}
}
class StoringEventObserverWithStop : StoringEventObserver
{
public override bool ShouldStopReadingNextEvents()
{
return true;
}
}
public class User : IEquatable<User>
{
public string Name { get; set; }
public int Age { get; set; }
public bool Equals(User other)
{
if (other == null) return false;
return Name == other.Name && Age == other.Age;
}
}
[Test]
public void CanWriteMultipleEventsWithMetadata()
{
var manager = new EventStoreManager();
var appender = manager.AppendToStore(new MemoryEventFileStorage());
var metadata = new User { Name = "A", Age = 1 };
var events = new object[]
{
new User {Name = "B", Age = 2},
new User {Name = "C", Age = 3}
};
appender.Store(metadata, events);
var eventObserver = new StoringEventObserver();
appender.ReadFromStartToEnd(eventObserver);
Assert.AreEqual(new object[] { metadata }, eventObserver.Metadata);
Assert.AreEqual(new[] { events }, eventObserver.Events);
}
[Test]
public void CanWriteSimpleEventAndReadItIndependently()
{
var manager = new EventStoreManager();
manager.SetNewTypeNameMapper(new SimplePersonTypeMapper());
var file = new MemoryEventFileStorage();
var appender = manager.AppendToStore(file);
var user = new User { Name = "A", Age = 1 };
appender.Store(null, new object[] { user });
manager = new EventStoreManager();
manager.SetNewTypeNameMapper(new SimplePersonTypeMapper());
var reader = manager.OpenReadOnlyStore(file);
var eventObserver = new StoringEventObserver();
reader.ReadFromStartToEnd(eventObserver);
Assert.AreEqual(new object[] { null }, eventObserver.Metadata);
Assert.AreEqual(new[] { new object[] { user } }, eventObserver.Events);
}
[Test]
public void CustomEventIsReadFromSecondSplit()
{
var manager = new EventStoreManager();
manager.CompressionStrategy = new NoCompressionStrategy();
manager.SetNewTypeNameMapper(new SimplePersonTypeMapper());
var appender = manager.AppendToStore(new MemoryEventFileStorage(4096, 4096));
var first = appender.CurrentFileStorage;
var user = new User { Name = "A", Age = 1 };
while (appender.CurrentFileStorage == first)
appender.Store(null, new object[] { user });
var second = appender.CurrentFileStorage;
manager = new EventStoreManager();
manager.CompressionStrategy = new NoCompressionStrategy();
manager.SetNewTypeNameMapper(new SimplePersonTypeMapper());
var reader = manager.OpenReadOnlyStore(second);
var eventObserver = new StoringEventObserver();
reader.ReadFromStartToEnd(eventObserver);
Assert.AreEqual(new object[] { null }, eventObserver.Metadata);
Assert.AreEqual(new[] { new object[] { user } }, eventObserver.Events);
}
public class SimplePersonTypeMapper : ITypeNameMapper
{
public string ToName(Type type)
{
if (type == typeof(User)) return "User";
throw new ArgumentOutOfRangeException();
}
public Type ToType(string name)
{
if (name == "User") return typeof(User);
throw new ArgumentOutOfRangeException();
}
}
public class UserEvent : IEquatable<UserEvent>
{
public long Id { get; set; }
public User User1 { get; set; }
public User User2 { get; set; }
public bool Equals(UserEvent other)
{
if (Id != other.Id) return false;
if (User1 != other.User1 && (User1 == null || !User1.Equals(other.User1))) return false;
return User2 == other.User2 || (User2 != null && User2.Equals(other.User2));
}
}
[Test]
public void NestedObjectsTest()
{
var manager = new EventStoreManager();
var file = new MemoryEventFileStorage();
var appender = manager.AppendToStore(file);
var userEvent = new UserEvent { Id = 10, User1 = new User { Name = "A", Age = 1 } };
appender.Store(null, new object[] { userEvent });
manager = new EventStoreManager();
var reader = manager.OpenReadOnlyStore(file);
var eventObserver = new StoringEventObserver();
reader.ReadFromStartToEnd(eventObserver);
Assert.AreEqual(new object[] { null }, eventObserver.Metadata);
Assert.AreEqual(new[] { new object[] { userEvent } }, eventObserver.Events);
}
[Test]
public void SameReferenceTest()
{
var manager = new EventStoreManager();
var file = new MemoryEventFileStorage();
var appender = manager.AppendToStore(file);
var user = new User { Name = "A", Age = 1 };
var userEvent = new UserEvent { Id = 10, User1 = user, User2 = user };
appender.Store(null, new object[] { userEvent });
manager = new EventStoreManager();
var reader = manager.OpenReadOnlyStore(file);
var eventObserver = new StoringEventObserver();
reader.ReadFromStartToEnd(eventObserver);
var readUserEvent = (UserEvent)eventObserver.Events[0][0];
Assert.AreSame(readUserEvent.User1, readUserEvent.User2);
}
public class UserEventMore : IEquatable<UserEventMore>
{
public long Id { get; set; }
public User User1 { get; set; }
public User User2 { get; set; }
public User User3 { get; set; }
public bool Equals(UserEventMore other)
{
if (Id != other.Id) return false;
if (User1 != other.User1 && (User1 == null || !User1.Equals(other.User1))) return false;
if (User2 != other.User2 && (User2 == null || !User2.Equals(other.User2))) return false;
return User3 == other.User3 || (User3 != null && User3.Equals(other.User3));
}
}
public class OverloadableTypeMapper : ITypeNameMapper
{
readonly ITypeNameMapper _parent = new FullNameTypeMapper();
readonly Type _type;
readonly string _name;
public OverloadableTypeMapper(Type type, string name)
{
_type = type;
_name = name;
}
public string ToName(Type type)
{
if (type == _type) return _name;
return _parent.ToName(type);
}
public Type ToType(string name)
{
if (name == _name) return _type;
return _parent.ToType(name);
}
}
[Test]
public void UpgradeToMoreObjectProperties()
{
var manager = new EventStoreManager();
manager.SetNewTypeNameMapper(new OverloadableTypeMapper(typeof(UserEvent), "UserEvent"));
var file = new MemoryEventFileStorage();
var appender = manager.AppendToStore(file);
var user = new User { Name = "A", Age = 1 };
var userEvent = new UserEvent { Id = 10, User1 = user, User2 = user };
appender.Store(null, new object[] { userEvent, new User { Name = "B" } });
manager = new EventStoreManager();
manager.SetNewTypeNameMapper(new OverloadableTypeMapper(typeof(UserEventMore), "UserEvent"));
var reader = manager.OpenReadOnlyStore(file);
var eventObserver = new StoringEventObserver();
reader.ReadFromStartToEnd(eventObserver);
var readUserEvent = (UserEventMore)eventObserver.Events[0][0];
Assert.AreSame(readUserEvent.User1, readUserEvent.User2);
Assert.AreEqual("A", readUserEvent.User1.Name);
Assert.AreEqual(10, readUserEvent.Id);
Assert.IsNull(readUserEvent.User3);
Assert.AreEqual("B", ((User)eventObserver.Events[0][1]).Name);
}
public class UserEventLess : IEquatable<UserEventLess>
{
public long Id { get; set; }
public User User2 { get; set; }
public bool Equals(UserEventLess other)
{
if (Id != other.Id) return false;
return User2 == other.User2 || (User2 != null && User2.Equals(other.User2));
}
}
[Test]
public void UpgradeToLessObjectProperties()
{
var manager = new EventStoreManager();
manager.SetNewTypeNameMapper(new OverloadableTypeMapper(typeof(UserEvent), "UserEvent"));
var file = new MemoryEventFileStorage();
var appender = manager.AppendToStore(file);
var user = new User { Name = "A", Age = 1 };
var userEvent = new UserEvent { Id = 10, User1 = user, User2 = user };
appender.Store(null, new object[] { userEvent, new User { Name = "B" } });
manager = new EventStoreManager();
manager.SetNewTypeNameMapper(new OverloadableTypeMapper(typeof(UserEventLess), "UserEvent"));
var reader = manager.OpenReadOnlyStore(file);
var eventObserver = new StoringEventObserver();
reader.ReadFromStartToEnd(eventObserver);
var readUserEvent = (UserEventLess)eventObserver.Events[0][0];
Assert.AreEqual("A", readUserEvent.User2.Name);
Assert.AreEqual(10, readUserEvent.Id);
Assert.AreEqual("B", ((User)eventObserver.Events[0][1]).Name);
}
public class UserEventList : IEquatable<UserEventList>
{
public long Id { get; set; }
public List<User> List { get; set; }
public bool Equals(UserEventList other)
{
if (Id != other.Id) return false;
if (List == other.List) return true;
if (List == null || other.List == null) return false;
if (List.Count != other.List.Count) return false;
return List.Zip(other.List, (u1, u2) => u1 == u2 || (u1 != null && u1.Equals(u2))).All(b => b);
}
}
[Test]
public void SupportsList()
{
var manager = new EventStoreManager();
var file = new MemoryEventFileStorage();
var appender = manager.AppendToStore(file);
var userA = new User { Name = "A", Age = 1 };
var userB = new User { Name = "B", Age = 2 };
var userEvent = new UserEventList { Id = 10, List = new List<User> { userA, userB, userA } };
appender.Store(null, new object[] { userEvent });
manager = new EventStoreManager();
var reader = manager.OpenReadOnlyStore(file);
var eventObserver = new StoringEventObserver();
reader.ReadFromStartToEnd(eventObserver);
var readUserEvent = (UserEventList)eventObserver.Events[0][0];
Assert.AreEqual(readUserEvent, userEvent);
}
[Test]
public void SkipListOnUpgrade()
{
var manager = new EventStoreManager();
manager.SetNewTypeNameMapper(new OverloadableTypeMapper(typeof(UserEventList), "UserEvent"));
var file = new MemoryEventFileStorage();
var appender = manager.AppendToStore(file);
var userA = new User { Name = "A", Age = 1 };
var userB = new User { Name = "B", Age = 2 };
var userEvent = new UserEventList { Id = 10, List = new List<User> { userA, userB, userA } };
appender.Store(null, new object[] { userEvent });
manager = new EventStoreManager();
manager.SetNewTypeNameMapper(new OverloadableTypeMapper(typeof(UserEvent), "UserEvent"));
var reader = manager.OpenReadOnlyStore(file);
var eventObserver = new StoringEventObserver();
reader.ReadFromStartToEnd(eventObserver);
var readUserEvent = (UserEvent)eventObserver.Events[0][0];
Assert.AreEqual(10, readUserEvent.Id);
Assert.IsNull(readUserEvent.User1);
}
public class UserEventDictionary : IEquatable<UserEventDictionary>
{
public long Id { get; set; }
public Dictionary<string, User> Dict { get; set; }
public bool Equals(UserEventDictionary other)
{
if (Id != other.Id) return false;
if (Dict == other.Dict) return true;
if (Dict == null || other.Dict == null) return false;
if (Dict.Count != other.Dict.Count) return false;
foreach (var p in Dict)
{
User u;
if (!other.Dict.TryGetValue(p.Key, out u)) return false;
if (p.Value != u && (p.Value == null || !p.Value.Equals(u))) return false;
}
return true;
}
}
[Test]
public void SupportsDictionary()
{
var manager = new EventStoreManager();
var file = new MemoryEventFileStorage();
var appender = manager.AppendToStore(file);
var userA = new User { Name = "A", Age = 1 };
var userB = new User { Name = "B", Age = 2 };
var userEvent = new UserEventDictionary { Id = 10, Dict = new Dictionary<string, User> { { "A", userA }, { "B", userB } } };
appender.Store(null, new object[] { userEvent });
manager = new EventStoreManager();
var reader = manager.OpenReadOnlyStore(file);
var eventObserver = new StoringEventObserver();
reader.ReadFromStartToEnd(eventObserver);
var readUserEvent = (UserEventDictionary)eventObserver.Events[0][0];
Assert.AreEqual(readUserEvent, userEvent);
}
[Test]
public void SupportsDataOverMaxBlockSize()
{
var manager = new EventStoreManager();
var file = new MemoryEventFileStorage();
var appender = manager.AppendToStore(file);
var randomData = new byte[20000];
new Random().NextBytes(randomData);
appender.Store(null, new object[] { randomData });
Assert.Less(10000, appender.KnownAppendablePosition());
manager = new EventStoreManager();
var reader = manager.OpenReadOnlyStore(file);
var eventObserver = new StoringEventObserver();
reader.ReadFromStartToEnd(eventObserver);
Assert.AreEqual(new object[] { null }, eventObserver.Metadata);
Assert.AreEqual(new[] { new object[] { randomData } }, eventObserver.Events);
}
[Test]
public void CompressionShortensData()
{
var manager = new EventStoreManager();
var file = new MemoryEventFileStorage();
var appender = manager.AppendToStore(file);
var compressibleData = new byte[20000];
appender.Store(null, new object[] { compressibleData });
Assert.Greater(2000, appender.KnownAppendablePosition());
manager = new EventStoreManager();
var reader = manager.OpenReadOnlyStore(file);
var eventObserver = new StoringEventObserver();
reader.ReadFromStartToEnd(eventObserver);
Assert.AreEqual(new object[] { null }, eventObserver.Metadata);
Assert.AreEqual(new[] { new object[] { compressibleData } }, eventObserver.Events);
}
[Test]
public void CanStopReadBatchesAfterFirst()
{
var manager = new EventStoreManager();
var file = new MemoryEventFileStorage();
var appender = manager.AppendToStore(file);
var metadata = new User { Name = "A", Age = 1 };
var events = new object[]
{
new User {Name = "B", Age = 2},
new User {Name = "C", Age = 3}
};
appender.Store(metadata, events);
appender.Store(metadata, events);
var reader = manager.OpenReadOnlyStore(file);
var eventObserver = new StoringEventObserverWithStop();
reader.ReadFromStartToEnd(eventObserver);
Assert.False(reader.IsKnownAsCorrupted());
Assert.False(reader.IsKnownAsFinished());
Assert.False(reader.IsKnownAsAppendable());
Assert.AreEqual(new object[] { metadata }, eventObserver.Metadata);
Assert.AreEqual(new[] { events }, eventObserver.Events);
}
[Test]
public void MoreComplexRepeatedAppendingAndReading()
{
var manager = new EventStoreManager();
for (var i = 490; i < 520; i += 2)
{
var file = new MemoryEventFileStorage();
var appender = manager.AppendToStore(file);
appender.Store(null, new object[] { new byte[i] });
var eventObserver = new StoringEventObserver();
appender.ReadFromStartToEnd(eventObserver);
appender.Store(null, new object[] { new byte[i] });
appender.ReadFromStartToEnd(eventObserver);
}
}
public class SpecificList
{
public List<ulong> Ulongs { get; set; }
}
public class SpecificDictIList
{
public IDictionary<ulong, IList<ulong>> Dict { get; set; }
}
[Test]
public void MixedIListAndList()
{
var manager = new EventStoreManager();
var file = new MemoryEventFileStorage();
var appender = manager.AppendToStore(file);
var e1 = new SpecificDictIList { Dict = new Dictionary<ulong, IList<ulong>>() };
var e2 = new SpecificList { Ulongs = new List<ulong>() };
appender.Store(null, new object[] { e2 });
appender.Store(null, new object[] { e1 });
manager = new EventStoreManager();
appender = manager.AppendToStore(file);
var eventObserver = new StoringEventObserver();
appender.ReadFromStartToEnd(eventObserver);
appender.Store(null, new object[] { e1 });
}
public class UsersIList
{
public IList<User> Users { get; set; }
}
[Test]
public void UseArrayForStoreIList()
{
var manager = new EventStoreManager();
var file = new MemoryEventFileStorage();
var appender = manager.AppendToStore(file);
var e = new UsersIList { Users = new[] { new User { Name = "A" }, new User { Name = "B" } } };
appender.Store(null, new object[] { e });
}
}
}
| |
//
// Copyright (C) 2010 Jackson Harper (jackson@manosdemono.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.IO;
using System.Linq;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using Manos.Http;
using Manos.Routing;
using Manos.Caching;
using Manos.Templates;
using Manos.Logging;
namespace Manos {
/// <summary>
/// A pre-packaged set of routes/actions that can be registered in the constructor of a ManoApp-derived class.
/// </summary>
public class ManosModule : IManosModule {
private RouteHandler routes = new RouteHandler ();
public ManosModule ()
{
//StartInternal ();
}
public RouteHandler Routes {
get { return routes; }
}
public IManosCache Cache {
get {
return AppHost.Cache;
}
}
public IManosLogger Log {
get {
return AppHost.Log;
}
}
public virtual string Get404Response()
{
return default404;
}
public virtual string Get500Response()
{
return default500;
}
private RouteHandler AddRouteHandler (IManosModule module, string [] patterns, HttpMethod [] methods)
{
if (module == null)
throw new ArgumentNullException ("module");
if (patterns == null)
throw new ArgumentNullException ("patterns");
if (methods == null)
throw new ArgumentNullException ("methods");
module.StartInternal ();
module.Routes.MatchOps = SimpleOpsForPatterns (patterns);
module.Routes.Methods = methods;
Routes.Children.Add (module.Routes);
return module.Routes;
}
private RouteHandler AddRouteHandler (ManosAction action, IMatchOperation[] matchOperations, HttpMethod [] methods)
{
return AddRouteHandler (new ActionTarget (action), matchOperations, methods);
}
private RouteHandler AddRouteHandler (ManosAction action, string [] patterns, HttpMethod [] methods)
{
return AddRouteHandler (new ActionTarget (action), patterns, methods);
}
private RouteHandler AddRouteHandler (IManosTarget target, IMatchOperation[] matchOperations, HttpMethod [] methods)
{
// TODO: Need to decide if this is a good or bad idea
// RemoveImplicitHandlers (action);
if (target == null)
throw new ArgumentNullException ("action");
if (matchOperations == null)
throw new ArgumentNullException ("matchOperations");
if (methods == null)
throw new ArgumentNullException ("methods");
RouteHandler res = new RouteHandler (matchOperations, methods, target);
Routes.Children.Add (res);
return res;
}
private RouteHandler AddRouteHandler (IManosTarget target, string [] patterns, HttpMethod [] methods)
{
// TODO: Need to decide if this is a good or bad idea
// RemoveImplicitHandlers (action);
if (target == null)
throw new ArgumentNullException ("action");
if (patterns == null)
throw new ArgumentNullException ("patterns");
if (methods == null)
throw new ArgumentNullException ("methods");
RouteHandler res = new RouteHandler (SimpleOpsForPatterns (patterns), methods, target);
Routes.Children.Add (res);
return res;
}
private RouteHandler AddImplicitRouteHandlerForModule (IManosModule module, string [] patterns, HttpMethod [] methods)
{
return AddImplicitRouteHandlerForModule (module, StringOpsForPatterns (patterns), methods);
}
private RouteHandler AddImplicitRouteHandlerForModule (IManosModule module, IMatchOperation [] ops, HttpMethod [] methods)
{
module.StartInternal ();
module.Routes.IsImplicit = true;
module.Routes.MatchOps = ops;
module.Routes.Methods = methods;
Routes.Children.Add (module.Routes);
return module.Routes;
}
private RouteHandler AddImplicitRouteHandlerForTarget (IManosTarget target, string[] patterns, HttpMethod[] methods, MatchType matchType)
{
return AddImplicitRouteHandlerForTarget (target, OpsForPatterns (patterns, matchType), methods);
//return AddImplicitRouteHandlerForTarget (target, StringOpsForPatterns (patterns), methods);
}
private RouteHandler AddImplicitRouteHandlerForTarget (IManosTarget target, IMatchOperation [] ops, HttpMethod [] methods)
{
RouteHandler res = new RouteHandler (ops, methods, target) {
IsImplicit = true,
};
Routes.Children.Add (res);
return res;
}
private IMatchOperation [] SimpleOpsForPatterns (string [] patterns)
{
return OpsForPatterns (patterns, MatchType.Simple);
}
private IMatchOperation [] StringOpsForPatterns (string [] patterns)
{
return OpsForPatterns (patterns, MatchType.String);
}
private IMatchOperation [] OpsForPatterns (string [] patterns, MatchType type)
{
var ops = new IMatchOperation [patterns.Length];
for (int i = 0; i < ops.Length; i++) {
ops [i] = MatchOperationFactory.Create (patterns [i], type);
}
return ops;
}
public RouteHandler Route (string pattern, IManosModule module)
{
return AddRouteHandler (module, new string [] { pattern }, HttpMethods.RouteMethods);
}
public RouteHandler Route (string pattern, ManosAction action)
{
return AddRouteHandler (action, new string [] { pattern }, HttpMethods.RouteMethods);
}
public RouteHandler Route (string pattern, MatchType matchType, ManosAction action)
{
IMatchOperation [] ops = OpsForPatterns (new string [] { pattern }, matchType);
return AddRouteHandler (action, ops, HttpMethods.GetMethods);
}
public RouteHandler Route (ManosAction action, params string [] patterns)
{
return AddRouteHandler (action, patterns, HttpMethods.RouteMethods);
}
public RouteHandler Route (IManosModule module, params string [] patterns)
{
return AddRouteHandler (module, patterns, HttpMethods.RouteMethods);
}
public RouteHandler Get (string pattern, IManosModule module)
{
return AddRouteHandler (module, new string [] { pattern }, HttpMethods.GetMethods);
}
public RouteHandler Get (string pattern, ManosAction action)
{
return AddRouteHandler (action, new string [] { pattern }, HttpMethods.GetMethods);
}
public RouteHandler Get (string pattern, MatchType matchType, ManosAction action)
{
IMatchOperation [] ops = OpsForPatterns (new string [] { pattern }, matchType);
return AddRouteHandler (action, ops, HttpMethods.GetMethods);
}
public RouteHandler Get (ManosAction action, params string [] patterns)
{
return AddRouteHandler (action, patterns, HttpMethods.GetMethods);
}
public RouteHandler Get (IManosModule module, params string [] patterns)
{
return AddRouteHandler (module, patterns, HttpMethods.GetMethods);
}
//
public RouteHandler Put (string pattern, IManosModule module)
{
return AddRouteHandler (module, new string [] { pattern }, HttpMethods.PutMethods);
}
public RouteHandler Put (string pattern, ManosAction action)
{
return AddRouteHandler (action, new string [] { pattern }, HttpMethods.PutMethods);
}
public RouteHandler Put (ManosAction action, params string [] patterns)
{
return AddRouteHandler (action, patterns, HttpMethods.PutMethods);
}
public RouteHandler Put (string pattern, MatchType matchType, ManosAction action)
{
IMatchOperation [] ops = OpsForPatterns (new string [] { pattern }, matchType);
return AddRouteHandler (action, ops, HttpMethods.GetMethods);
}
public RouteHandler Put (IManosModule module, params string [] patterns)
{
return AddRouteHandler (module, patterns, HttpMethods.PutMethods);
}
public RouteHandler Post (string pattern, IManosModule module)
{
return AddRouteHandler (module, new string [] { pattern }, HttpMethods.PostMethods);
}
public RouteHandler Post (string pattern, ManosAction action)
{
return AddRouteHandler (action, new string [] { pattern }, HttpMethods.PostMethods);
}
public RouteHandler Post (string pattern, MatchType matchType, ManosAction action)
{
IMatchOperation [] ops = OpsForPatterns (new string [] { pattern }, matchType);
return AddRouteHandler (action, ops, HttpMethods.GetMethods);
}
public RouteHandler Post (ManosAction action, params string [] patterns)
{
return AddRouteHandler (action, patterns, HttpMethods.PostMethods);
}
public RouteHandler Post (IManosModule module, params string [] patterns)
{
return AddRouteHandler (module, patterns, HttpMethods.PostMethods);
}
//
public RouteHandler Delete (string pattern, IManosModule module)
{
return AddRouteHandler (module, new string [] { pattern }, HttpMethods.DeleteMethods);
}
public RouteHandler Delete (string pattern, ManosAction action)
{
return AddRouteHandler (action, new string [] { pattern }, HttpMethods.DeleteMethods);
}
public RouteHandler Delete (string pattern, MatchType matchType, ManosAction action)
{
IMatchOperation [] ops = OpsForPatterns (new string [] { pattern }, matchType);
return AddRouteHandler (action, ops, HttpMethods.GetMethods);
}
public RouteHandler Delete (ManosAction action, params string [] patterns)
{
return AddRouteHandler (action, patterns, HttpMethods.DeleteMethods);
}
public RouteHandler Delete (IManosModule module, params string [] patterns)
{
return AddRouteHandler (module, patterns, HttpMethods.DeleteMethods);
}
//
public RouteHandler Head (string pattern, IManosModule module)
{
return AddRouteHandler (module, new string [] { pattern }, HttpMethods.HeadMethods);
}
public RouteHandler Head (string pattern, ManosAction action)
{
return AddRouteHandler (action, new string [] { pattern }, HttpMethods.HeadMethods);
}
public RouteHandler Head (string pattern, MatchType matchType, ManosAction action)
{
IMatchOperation [] ops = OpsForPatterns (new string [] { pattern }, matchType);
return AddRouteHandler (action, ops, HttpMethods.GetMethods);
}
public RouteHandler Head (ManosAction action, params string [] patterns)
{
return AddRouteHandler (action, patterns, HttpMethods.HeadMethods);
}
public RouteHandler Head (IManosModule module, params string [] patterns)
{
return AddRouteHandler (module, patterns, HttpMethods.HeadMethods);
}
//
public RouteHandler Options (string pattern, IManosModule module)
{
return AddRouteHandler (module, new string [] { pattern }, HttpMethods.OptionsMethods);
}
public RouteHandler Options (string pattern, ManosAction action)
{
return AddRouteHandler (action, new string [] { pattern }, HttpMethods.OptionsMethods);
}
public RouteHandler Options (string pattern, MatchType matchType, ManosAction action)
{
IMatchOperation [] ops = OpsForPatterns (new string [] { pattern }, matchType);
return AddRouteHandler (action, ops, HttpMethods.GetMethods);
}
public RouteHandler Options (ManosAction action, params string [] patterns)
{
return AddRouteHandler (action, patterns, HttpMethods.OptionsMethods);
}
public RouteHandler Options (IManosModule module, params string [] patterns)
{
return AddRouteHandler (module, patterns, HttpMethods.OptionsMethods);
}
//
public RouteHandler Trace (string pattern, IManosModule module)
{
return AddRouteHandler (module, new string [] { pattern }, HttpMethods.TraceMethods);
}
public RouteHandler Trace (string pattern, ManosAction action)
{
return AddRouteHandler (action, new string [] { pattern }, HttpMethods.TraceMethods);
}
public RouteHandler Trace (string pattern, MatchType matchType, ManosAction action)
{
IMatchOperation [] ops = OpsForPatterns (new string [] { pattern }, matchType);
return AddRouteHandler (action, ops, HttpMethods.GetMethods);
}
public RouteHandler Trace (ManosAction action, params string [] patterns)
{
return AddRouteHandler (action, patterns, HttpMethods.TraceMethods);
}
public RouteHandler Trace (IManosModule module, params string [] patterns)
{
return AddRouteHandler (module, patterns, HttpMethods.TraceMethods);
}
public static Timeout AddTimeout (TimeSpan timespan, TimeoutCallback callback)
{
return AddTimeout (timespan, RepeatBehavior.Single, null, callback);
}
public static Timeout AddTimeout (TimeSpan timespan, IRepeatBehavior repeat, TimeoutCallback callback)
{
return AddTimeout (timespan, repeat, null, callback);
}
public static Timeout AddTimeout (TimeSpan timespan, object data, TimeoutCallback callback)
{
return AddTimeout (timespan, RepeatBehavior.Single, data, callback);
}
public static Timeout AddTimeout (TimeSpan timespan, IRepeatBehavior repeat, object data, TimeoutCallback callback)
{
return AppHost.AddTimeout (timespan, repeat, data, callback);
}
public static void AddPipe (ManosPipe pipe)
{
AppHost.AddPipe (pipe);
}
public static void RenderTemplate (ManosContext ctx, string template, object data)
{
TemplateEngine.RenderToStream (template, ctx.Response.Writer, data);
}
public void StartInternal ()
{
AddImplicitRoutes ();
}
private void AddImplicitRoutes ()
{
MethodInfo[] methods = GetType ().GetMethods ();
foreach (MethodInfo meth in methods) {
if (meth.ReturnType != typeof(void))
continue;
if (IsIgnored (meth))
continue;
ParameterInfo [] parameters = meth.GetParameters ();
if (IsActionSignature (meth, parameters)) {
AddActionHandler (Routes, meth);
continue;
}
if (IsParameterizedActionSignature (meth, parameters)) {
AddParameterizedActionHandler (Routes, meth);
continue;
}
}
PropertyInfo [] properties = GetType ().GetProperties ();
foreach (PropertyInfo prop in properties) {
if (!typeof (ManosModule).IsAssignableFrom (prop.PropertyType))
continue;
if (IsIgnored (prop))
continue;
AddImplicitModule (prop);
}
}
private bool IsActionSignature (MethodInfo method, ParameterInfo [] parameters)
{
if (parameters.Length != 1)
return false;
if (method.DeclaringType.Assembly == typeof (ManosModule).Assembly)
return false;
if (parameters [0].ParameterType != typeof (IManosContext))
return false;
return true;
}
private bool IsParameterizedActionSignature (MethodInfo method, ParameterInfo [] parameters)
{
if (parameters.Length < 1) {
return false;
}
if (method.DeclaringType.Assembly == typeof (ManosModule).Assembly)
return false;
if (parameters [0].ParameterType != typeof (IManosContext))
return false;
return true;
}
private bool IsIgnored (MemberInfo info)
{
object [] atts = info.GetCustomAttributes (typeof (IgnoreHandlerAttribute), false);
return atts.Length > 0;
}
private void AddActionHandler (RouteHandler routes, MethodInfo info)
{
HttpMethodAttribute [] atts = (HttpMethodAttribute []) info.GetCustomAttributes (typeof (HttpMethodAttribute), false);
if (atts.Length == 0) {
AddDefaultHandlerForAction (routes, info);
return;
}
foreach (HttpMethodAttribute att in atts) {
AddHandlerForAction (routes, att, info);
}
}
private void AddDefaultHandlerForAction (RouteHandler routes, MethodInfo info)
{
ManosAction action = ActionForMethod (info);
ActionTarget target = new ActionTarget (action);
AddImplicitRouteHandlerForTarget (target, new string [] { "/" + info.Name }, HttpMethods.RouteMethods, MatchType.String);
}
private void AddHandlerForAction (RouteHandler routes, HttpMethodAttribute att, MethodInfo info)
{
ManosAction action = ActionForMethod (info);
ActionTarget target = new ActionTarget (action);
string[] patterns = null == att.Patterns ? new string [] { "/" + info.Name } : att.Patterns;
AddImplicitRouteHandlerForTarget (target, OpsForPatterns (patterns, att.MatchType), att.Methods);
}
private ManosAction ActionForMethod (MethodInfo info)
{
ManosAction action;
if (info.IsStatic)
action = (ManosAction) Delegate.CreateDelegate (typeof (ManosAction), info);
else
action = (ManosAction) Delegate.CreateDelegate (typeof (ManosAction), this, info);
return action;
}
private void AddParameterizedActionHandler (RouteHandler routes, MethodInfo info)
{
HttpMethodAttribute [] atts = (HttpMethodAttribute []) info.GetCustomAttributes (typeof (HttpMethodAttribute), false);
if (atts.Length == 0) {
AddDefaultHandlerForParameterizedAction (routes, info);
return;
}
foreach (HttpMethodAttribute att in atts) {
AddHandlerForParameterizedAction (routes, att, info);
}
}
private void AddDefaultHandlerForParameterizedAction (RouteHandler routes, MethodInfo info)
{
ParameterizedAction action = ParameterizedActionFactory.CreateAction (info);
ParameterizedActionTarget target = new ParameterizedActionTarget (this, info, action);
AddImplicitRouteHandlerForTarget (target, new string [] { "/" + info.Name }, HttpMethods.RouteMethods, MatchType.String);
}
private void AddHandlerForParameterizedAction (RouteHandler routes, HttpMethodAttribute att, MethodInfo info)
{
ParameterizedAction action = ParameterizedActionFactory.CreateAction (info);
ParameterizedActionTarget target = new ParameterizedActionTarget (this, info, action);
AddImplicitRouteHandlerForTarget (target, att.Patterns, att.Methods, att.MatchType);
}
private void AddImplicitModule (PropertyInfo prop)
{
var value = (ManosModule) prop.GetValue (this, null);
if (value == null) {
try {
value = (ManosModule) Activator.CreateInstance (prop.PropertyType);
} catch (Exception e) {
throw new Exception (String.Format ("Unable to create default property value for '{0}'", prop), e);
}
prop.SetValue (this, value, null);
}
AddImplicitRouteHandlerForModule (value, new string [] { "/" + prop.Name }, HttpMethods.RouteMethods);
}
private static string default404 = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"" +
"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" +
"<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">" +
"<head>" +
" <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />" +
" <title>The page you were looking for doesn't exist (404)</title>" +
"<style type=\"text/css\">" +
"body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }" +
"div.dialog {" +
"width: 25em;" +
"padding: 0 4em;" +
"margin: 4em auto 0 auto;" +
"border: 1px solid #ccc;" +
"border-right-color: #999;" +
"border-bottom-color: #999;" +
"}" +
"h1 { font-size: 100%; color: #f00; line-height: 1.5em; }" +
"</style>" +
"</head>" +
"<body>" +
" <div class=\"dialog\">" +
" <h1>404 - The page you were looking for doesn't exist.</h1>" +
" <p>You may have mistyped the address or the page may have moved.</p>" +
" <p><small>Powered by <a href=\"http://manosdemono.org\">manos</a></small></p>" +
" </div>" +
"</body>" +
"</html>";
private static string default500 = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"" +
"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" +
"<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">" +
"<head>" +
" <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />" +
" <title>We're sorry, but something went wrong (500)</title>" +
"<style type=\"text/css\">" +
"body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }" +
"div.dialog {" +
"width: 25em;" +
"padding: 0 4em;" +
"margin: 4em auto 0 auto;" +
"border: 1px solid #ccc;" +
"border-right-color: #999;" +
"border-bottom-color: #999;" +
"}" +
"h1 { font-size: 100%; color: #f00; line-height: 1.5em; }" +
"</style>" +
"</head>" +
"<body>" +
" <div class=\"dialog\">" +
" <h1>500 - We're sorry, but something went wrong.</h1>" +
" <p><small>Powered by <a href=\"http://manosdemono.org\">manos</a></small></p>" +
" </div>" +
"</body>" +
"</html>";
}
}
| |
// 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.Text;
namespace System.Xml.Xsl.Runtime
{
internal class DecimalFormat
{
public NumberFormatInfo info;
public char digit;
public char zeroDigit;
public char patternSeparator;
internal DecimalFormat(NumberFormatInfo info, char digit, char zeroDigit, char patternSeparator)
{
this.info = info;
this.digit = digit;
this.zeroDigit = zeroDigit;
this.patternSeparator = patternSeparator;
}
}
internal class DecimalFormatter
{
private NumberFormatInfo _posFormatInfo;
private NumberFormatInfo _negFormatInfo;
private string _posFormat;
private string _negFormat;
private char _zeroDigit;
// These characters have special meaning for CLR and must be escaped
// <spec>https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings</spec>
private const string ClrSpecialChars = "0#.,%\u2030Ee\\'\";";
// This character is used to escape literal (passive) digits '0'..'9'
private const char EscChar = '\a';
public DecimalFormatter(string formatPicture, DecimalFormat decimalFormat)
{
Debug.Assert(formatPicture != null && decimalFormat != null);
if (formatPicture.Length == 0)
{
throw XsltException.Create(SR.Xslt_InvalidFormat);
}
_zeroDigit = decimalFormat.zeroDigit;
_posFormatInfo = (NumberFormatInfo)decimalFormat.info.Clone();
StringBuilder temp = new StringBuilder();
bool integer = true;
bool sawPattern = false, sawZeroDigit = false, sawDigit = false, sawDecimalSeparator = false;
bool digitOrZeroDigit = false;
char decimalSeparator = _posFormatInfo.NumberDecimalSeparator[0];
char groupSeparator = _posFormatInfo.NumberGroupSeparator[0];
char percentSymbol = _posFormatInfo.PercentSymbol[0];
char perMilleSymbol = _posFormatInfo.PerMilleSymbol[0];
int commaIndex = 0;
int groupingSize = 0;
int decimalIndex = -1;
int lastDigitIndex = -1;
for (int i = 0; i < formatPicture.Length; i++)
{
char ch = formatPicture[i];
if (ch == decimalFormat.digit)
{
if (sawZeroDigit && integer)
{
throw XsltException.Create(SR.Xslt_InvalidFormat1, formatPicture);
}
lastDigitIndex = temp.Length;
sawDigit = digitOrZeroDigit = true;
temp.Append('#');
continue;
}
if (ch == decimalFormat.zeroDigit)
{
if (sawDigit && !integer)
{
throw XsltException.Create(SR.Xslt_InvalidFormat2, formatPicture);
}
lastDigitIndex = temp.Length;
sawZeroDigit = digitOrZeroDigit = true;
temp.Append('0');
continue;
}
if (ch == decimalFormat.patternSeparator)
{
if (!digitOrZeroDigit)
{
throw XsltException.Create(SR.Xslt_InvalidFormat8);
}
if (sawPattern)
{
throw XsltException.Create(SR.Xslt_InvalidFormat3, formatPicture);
}
sawPattern = true;
if (decimalIndex < 0)
{
decimalIndex = lastDigitIndex + 1;
}
groupingSize = RemoveTrailingComma(temp, commaIndex, decimalIndex);
if (groupingSize > 9)
{
groupingSize = 0;
}
_posFormatInfo.NumberGroupSizes = new int[] { groupingSize };
if (!sawDecimalSeparator)
{
_posFormatInfo.NumberDecimalDigits = 0;
}
_posFormat = temp.ToString();
temp.Length = 0;
decimalIndex = -1;
lastDigitIndex = -1;
commaIndex = 0;
sawDigit = sawZeroDigit = digitOrZeroDigit = false;
sawDecimalSeparator = false;
integer = true;
_negFormatInfo = (NumberFormatInfo)decimalFormat.info.Clone();
_negFormatInfo.NegativeSign = string.Empty;
continue;
}
if (ch == decimalSeparator)
{
if (sawDecimalSeparator)
{
throw XsltException.Create(SR.Xslt_InvalidFormat5, formatPicture);
}
decimalIndex = temp.Length;
sawDecimalSeparator = true;
sawDigit = sawZeroDigit = integer = false;
temp.Append('.');
continue;
}
if (ch == groupSeparator)
{
commaIndex = temp.Length;
lastDigitIndex = commaIndex;
temp.Append(',');
continue;
}
if (ch == percentSymbol)
{
temp.Append('%');
continue;
}
if (ch == perMilleSymbol)
{
temp.Append('\u2030');
continue;
}
if (ch == '\'')
{
int pos = formatPicture.IndexOf('\'', i + 1);
if (pos < 0)
{
pos = formatPicture.Length - 1;
}
temp.Append(formatPicture, i, pos - i + 1);
i = pos;
continue;
}
// Escape literal digits with EscChar, double literal EscChar
if ('0' <= ch && ch <= '9' || ch == EscChar)
{
if (decimalFormat.zeroDigit != '0')
{
temp.Append(EscChar);
}
}
// Escape characters having special meaning for CLR
if (ClrSpecialChars.IndexOf(ch) >= 0)
{
temp.Append('\\');
}
temp.Append(ch);
}
if (!digitOrZeroDigit)
{
throw XsltException.Create(SR.Xslt_InvalidFormat8);
}
NumberFormatInfo formatInfo = sawPattern ? _negFormatInfo : _posFormatInfo;
if (decimalIndex < 0)
{
decimalIndex = lastDigitIndex + 1;
}
groupingSize = RemoveTrailingComma(temp, commaIndex, decimalIndex);
if (groupingSize > 9)
{
groupingSize = 0;
}
formatInfo.NumberGroupSizes = new int[] { groupingSize };
if (!sawDecimalSeparator)
{
formatInfo.NumberDecimalDigits = 0;
}
if (sawPattern)
{
_negFormat = temp.ToString();
}
else
{
_posFormat = temp.ToString();
}
}
private static int RemoveTrailingComma(StringBuilder builder, int commaIndex, int decimalIndex)
{
if (commaIndex > 0 && commaIndex == (decimalIndex - 1))
{
builder.Remove(decimalIndex - 1, 1);
}
else if (decimalIndex > commaIndex)
{
return decimalIndex - commaIndex - 1;
}
return 0;
}
public string Format(double value)
{
NumberFormatInfo formatInfo;
string subPicture;
if (value < 0 && _negFormatInfo != null)
{
formatInfo = _negFormatInfo;
subPicture = _negFormat;
}
else
{
formatInfo = _posFormatInfo;
subPicture = _posFormat;
}
string result = value.ToString(subPicture, formatInfo);
if (_zeroDigit != '0')
{
StringBuilder builder = new StringBuilder(result.Length);
int shift = _zeroDigit - '0';
for (int i = 0; i < result.Length; i++)
{
char ch = result[i];
if ((uint)(ch - '0') <= 9)
{
ch += (char)shift;
}
else if (ch == EscChar)
{
// This is an escaped literal digit or EscChar, thus unescape it. We make use
// of the fact that no extra EscChar could be inserted by value.ToString().
Debug.Assert(i + 1 < result.Length);
ch = result[++i];
Debug.Assert('0' <= ch && ch <= '9' || ch == EscChar);
}
builder.Append(ch);
}
result = builder.ToString();
}
return result;
}
public static string Format(double value, string formatPicture, DecimalFormat decimalFormat)
{
return new DecimalFormatter(formatPicture, decimalFormat).Format(value);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace LumiSoft.Net.RTP
{
/// <summary>
/// A data packet consisting of the fixed RTP header, a possibly empty list of contributing
/// sources (see below), and the payload data. Some underlying protocols may require an
/// encapsulation of the RTP packet to be defined. Typically one packet of the underlying
/// protocol contains a single RTP packet, but several RTP packets MAY be contained if
/// permitted by the encapsulation method (see Section 11).
/// </summary>
public class RTP_Packet
{
private int m_Version = 2;
private bool m_IsMarker = false;
private int m_PayloadType = 0;
private ushort m_SequenceNumber = 0;
private uint m_Timestamp = 0;
private uint m_SSRC = 0;
private uint[] m_CSRC = null;
private byte[] m_Data = null;
/// <summary>
/// Default constructor.
/// </summary>
public RTP_Packet()
{
}
#region static method Parse
/// <summary>
/// Parses RTP packet.
/// </summary>
/// <param name="buffer">Buffer containing RTP packet.</param>
/// <param name="size">Number of bytes used in buffer.</param>
/// <returns>Returns parsed RTP packet.</returns>
public static RTP_Packet Parse(byte[] buffer,int size)
{
RTP_Packet packet = new RTP_Packet();
packet.ParseInternal(buffer,size);
return packet;
}
#endregion
#region method Validate
/// <summary>
/// Validates RTP packet.
/// </summary>
public void Validate()
{
// TODO: Validate RTP apcket
}
#endregion
#region method ToByte
/// <summary>
/// Stores this packet to the specified buffer.
/// </summary>
/// <param name="buffer">Buffer where to store packet.</param>
/// <param name="offset">Offset in buffer.</param>
public void ToByte(byte[] buffer,ref int offset)
{
/* RFC 3550.5.1 RTP Fixed Header Fields.
The RTP header has the following format:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|V=2|P|X| CC |M| PT | sequence number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| timestamp |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| synchronization source (SSRC) identifier |
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
| contributing source (CSRC) identifiers |
| .... |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
5.3. Available if X bit filled.
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| defined by profile | length |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| header extension |
| .... |
*/
int cc = 0;
if(m_CSRC != null){
cc = m_CSRC.Length;
}
// V P X CC
buffer[offset++] = (byte)(m_Version << 6 | 0 << 5 | cc & 0xF);
// M PT
buffer[offset++] = (byte)(Convert.ToInt32(m_IsMarker) << 7 | m_PayloadType & 0x7F);
// sequence number
buffer[offset++] = (byte)(m_SequenceNumber >> 8);
buffer[offset++] = (byte)(m_SequenceNumber & 0xFF);
// timestamp
buffer[offset++] = (byte)((m_Timestamp >> 24) & 0xFF);
buffer[offset++] = (byte)((m_Timestamp >> 16) & 0xFF);
buffer[offset++] = (byte)((m_Timestamp >> 8) & 0xFF);
buffer[offset++] = (byte)(m_Timestamp & 0xFF);
// SSRC
buffer[offset++] = (byte)((m_SSRC >> 24) & 0xFF);
buffer[offset++] = (byte)((m_SSRC >> 16) & 0xFF);
buffer[offset++] = (byte)((m_SSRC >> 8) & 0xFF);
buffer[offset++] = (byte)(m_SSRC & 0xFF);
// CSRCs
if(m_CSRC != null){
foreach(int csrc in m_CSRC){
buffer[offset++] = (byte)((csrc >> 24) & 0xFF);
buffer[offset++] = (byte)((csrc >> 16) & 0xFF);
buffer[offset++] = (byte)((csrc >> 8) & 0xFF);
buffer[offset++] = (byte)(csrc & 0xFF);
}
}
// X
Array.Copy(m_Data,0,buffer,offset,m_Data.Length);
offset += m_Data.Length;
}
#endregion
#region override method ToString
/// <summary>
/// Returns this packet info as string.
/// </summary>
/// <returns>Returns packet info.</returns>
public override string ToString()
{
StringBuilder retVal = new StringBuilder();
retVal.Append("----- RTP Packet\r\n");
retVal.Append("Version: " + m_Version.ToString() + "\r\n");
retVal.Append("IsMaker: " + m_IsMarker.ToString() + "\r\n");
retVal.Append("PayloadType: " + m_PayloadType.ToString() + "\r\n");
retVal.Append("SeqNo: " + m_SequenceNumber.ToString() + "\r\n");
retVal.Append("Timestamp: " + m_Timestamp.ToString() + "\r\n");
retVal.Append("SSRC: " + m_SSRC.ToString() + "\r\n");
retVal.Append("Data: " + m_Data.Length + " bytes.\r\n");
return retVal.ToString();
}
#endregion
#region method ParseInternal
/// <summary>
/// Parses RTP packet from the specified buffer.
/// </summary>
/// <param name="buffer">Buffer containing RTP packet.</param>
/// <param name="size">Number of bytes used in buffer.</param>
private void ParseInternal(byte[] buffer,int size)
{
/* RFC 3550.5.1 RTP Fixed Header Fields.
The RTP header has the following format:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|V=2|P|X| CC |M| PT | sequence number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| timestamp |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| synchronization source (SSRC) identifier |
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
| contributing source (CSRC) identifiers |
| .... |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
5.3. Available if X bit filled.
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| defined by profile | length |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| header extension |
| .... |
*/
int offset = 0;
// V
m_Version = buffer[offset] >> 6;
// P
bool isPadded = Convert.ToBoolean((buffer[offset] >> 5) & 0x1);
// X
bool hasExtention = Convert.ToBoolean((buffer[offset] >> 4) & 0x1);
// CC
int csrcCount = buffer[offset++] & 0xF;
// M
m_IsMarker = Convert.ToBoolean(buffer[offset] >> 7);
// PT
m_PayloadType = buffer[offset++] & 0x7F;
// sequence number
m_SequenceNumber = (ushort)(buffer[offset++] << 8 | buffer[offset++]);
// timestamp
m_Timestamp = (uint)(buffer[offset++] << 24 | buffer[offset++] << 16 | buffer[offset++] << 8 | buffer[offset++]);
// SSRC
m_SSRC = (uint)(buffer[offset++] << 24 | buffer[offset++] << 16 | buffer[offset++] << 8 | buffer[offset++]);
// CSRC
m_CSRC = new uint[csrcCount];
for(int i=0;i<csrcCount;i++){
m_CSRC[i] = (uint)(buffer[offset++] << 24 | buffer[offset++] << 16 | buffer[offset++] << 8 | buffer[offset++]);
}
// X
if(hasExtention){
// Skip extention
offset++;
offset += buffer[offset];
}
// TODO: Padding
// Data
m_Data = new byte[size - offset];
Array.Copy(buffer,offset,m_Data,0,m_Data.Length);
}
#endregion
#region Properties Implementation
/// <summary>
/// Gets RTP version.
/// </summary>
public int Version
{
get{ return m_Version; }
}
/// <summary>
/// Gets if packet is padded to some bytes boundary.
/// </summary>
public bool IsPadded
{
get{ return false; }
}
/// <summary>
/// Gets marker bit. The usage of this bit depends on payload type.
/// </summary>
public bool IsMarker
{
get{ return m_IsMarker; }
set{ m_IsMarker = value; }
}
/// <summary>
/// Gets payload type.
/// </summary>
/// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception>
public int PayloadType
{
get{ return m_PayloadType; }
set{
if(value < 0 || value > 128){
throw new ArgumentException("Payload value must be >= 0 and <= 128.");
}
m_PayloadType = value;
}
}
/// <summary>
/// Gets or sets RTP packet sequence number.
/// </summary>
/// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception>
public ushort SeqNo
{
get{ return m_SequenceNumber; }
set{ m_SequenceNumber = value; }
}
/// <summary>
/// Gets sets packet timestamp.
/// </summary>
/// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception>
public uint Timestamp
{
get{ return m_Timestamp; }
set{
if(value < 1){
throw new ArgumentException("Timestamp value must be >= 1.");
}
m_Timestamp = value;
}
}
/// <summary>
/// Gets or sets synchronization source ID.
/// </summary>
/// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception>
public uint SSRC
{
get{ return m_SSRC; }
set{
if(value < 1){
throw new ArgumentException("SSRC value must be >= 1.");
}
m_SSRC = value;
}
}
/// <summary>
/// Gets or sets the contributing sources for the payload contained in this packet.
/// Value null means none.
/// </summary>
public uint[] CSRC
{
get{ return m_CSRC; }
set{ m_CSRC = value; }
}
/// <summary>
/// Gets SSRC + CSRCs as joined array.
/// </summary>
public uint[] Sources
{
get{
uint[] retVal = new uint[1];
if(m_CSRC != null){
retVal = new uint[1 + m_CSRC.Length];
}
retVal[0] = m_SSRC;
Array.Copy(m_CSRC,retVal,m_CSRC.Length);
return retVal;
}
}
/// <summary>
/// Gets or sets RTP data. Data must be encoded with PayloadType encoding.
/// </summary>
/// <exception cref="ArgumentNullException">Is raised when null value is passed.</exception>
public byte[] Data
{
get{ return m_Data; }
set{
if(value == null){
throw new ArgumentNullException("Data");
}
m_Data = value;
}
}
#endregion
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Text;
using System.Collections;
using System.Diagnostics;
#if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using System.Globalization;
#if HAVE_METHOD_IMPL_ATTRIBUTE
using System.Runtime.CompilerServices;
#endif
using Newtonsoft.Json.Serialization;
namespace ArangoDB.Client.Utility.Newtonsoft.Json
{
internal static class CollectionUtils
{
/// <summary>
/// Determines whether the collection is <c>null</c> or empty.
/// </summary>
/// <param name="collection">The collection.</param>
/// <returns>
/// <c>true</c> if the collection is <c>null</c> or empty; otherwise, <c>false</c>.
/// </returns>
public static bool IsNullOrEmpty<T>(ICollection<T> collection)
{
if (collection != null)
{
return (collection.Count == 0);
}
return true;
}
/// <summary>
/// Adds the elements of the specified collection to the specified generic <see cref="IList{T}"/>.
/// </summary>
/// <param name="initial">The list to add to.</param>
/// <param name="collection">The collection of elements to add.</param>
public static void AddRange<T>(this IList<T> initial, IEnumerable<T> collection)
{
if (initial == null)
{
throw new ArgumentNullException(nameof(initial));
}
if (collection == null)
{
return;
}
foreach (T value in collection)
{
initial.Add(value);
}
}
#if !HAVE_COVARIANT_GENERICS
public static void AddRange<T>(this IList<T> initial, IEnumerable collection)
{
ValidationUtils.ArgumentNotNull(initial, nameof(initial));
// because earlier versions of .NET didn't support covariant generics
initial.AddRange(collection.Cast<T>());
}
#endif
public static bool IsDictionaryType(Type type)
{
ValidationUtils.ArgumentNotNull(type, nameof(type));
if (typeof(IDictionary).IsAssignableFrom(type))
{
return true;
}
if (ReflectionUtils.ImplementsGenericDefinition(type, typeof(IDictionary<,>)))
{
return true;
}
#if HAVE_READ_ONLY_COLLECTIONS
if (ReflectionUtils.ImplementsGenericDefinition(type, typeof(IReadOnlyDictionary<,>)))
{
return true;
}
#endif
return false;
}
public static ConstructorInfo ResolveEnumerableCollectionConstructor(Type collectionType, Type collectionItemType)
{
Type genericConstructorArgument = typeof(IList<>).MakeGenericType(collectionItemType);
return ResolveEnumerableCollectionConstructor(collectionType, collectionItemType, genericConstructorArgument);
}
public static ConstructorInfo ResolveEnumerableCollectionConstructor(Type collectionType, Type collectionItemType, Type constructorArgumentType)
{
Type genericEnumerable = typeof(IEnumerable<>).MakeGenericType(collectionItemType);
ConstructorInfo match = null;
foreach (ConstructorInfo constructor in collectionType.GetConstructors(BindingFlags.Public | BindingFlags.Instance))
{
IList<ParameterInfo> parameters = constructor.GetParameters();
if (parameters.Count == 1)
{
Type parameterType = parameters[0].ParameterType;
if (genericEnumerable == parameterType)
{
// exact match
match = constructor;
break;
}
// in case we can't find an exact match, use first inexact
if (match == null)
{
if (parameterType.IsAssignableFrom(constructorArgumentType))
{
match = constructor;
}
}
}
}
return match;
}
public static bool AddDistinct<T>(this IList<T> list, T value)
{
return list.AddDistinct(value, EqualityComparer<T>.Default);
}
public static bool AddDistinct<T>(this IList<T> list, T value, IEqualityComparer<T> comparer)
{
if (list.ContainsValue(value, comparer))
{
return false;
}
list.Add(value);
return true;
}
// this is here because LINQ Bridge doesn't support Contains with IEqualityComparer<T>
public static bool ContainsValue<TSource>(this IEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer)
{
if (comparer == null)
{
comparer = EqualityComparer<TSource>.Default;
}
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
foreach (TSource local in source)
{
if (comparer.Equals(local, value))
{
return true;
}
}
return false;
}
public static bool AddRangeDistinct<T>(this IList<T> list, IEnumerable<T> values, IEqualityComparer<T> comparer)
{
bool allAdded = true;
foreach (T value in values)
{
if (!list.AddDistinct(value, comparer))
{
allAdded = false;
}
}
return allAdded;
}
public static int IndexOf<T>(this IEnumerable<T> collection, Func<T, bool> predicate)
{
int index = 0;
foreach (T value in collection)
{
if (predicate(value))
{
return index;
}
index++;
}
return -1;
}
public static bool Contains<T>(this List<T> list, T value, IEqualityComparer comparer)
{
for (int i = 0; i < list.Count; i++)
{
if (comparer.Equals(value, list[i]))
{
return true;
}
}
return false;
}
public static int IndexOfReference<T>(this List<T> list, T item)
{
for (int i = 0; i < list.Count; i++)
{
if (ReferenceEquals(item, list[i]))
{
return i;
}
}
return -1;
}
#if HAVE_FAST_REVERSE
// faster reverse in .NET Framework with value types - https://github.com/JamesNK/Newtonsoft.Json/issues/1430
public static void FastReverse<T>(this List<T> list)
{
int i = 0;
int j = list.Count - 1;
while (i < j)
{
T temp = list[i];
list[i] = list[j];
list[j] = temp;
i++;
j--;
}
}
#endif
private static IList<int> GetDimensions(IList values, int dimensionsCount)
{
IList<int> dimensions = new List<int>();
IList currentArray = values;
while (true)
{
dimensions.Add(currentArray.Count);
// don't keep calculating dimensions for arrays inside the value array
if (dimensions.Count == dimensionsCount)
{
break;
}
if (currentArray.Count == 0)
{
break;
}
object v = currentArray[0];
if (v is IList list)
{
currentArray = list;
}
else
{
break;
}
}
return dimensions;
}
private static void CopyFromJaggedToMultidimensionalArray(IList values, Array multidimensionalArray, int[] indices)
{
int dimension = indices.Length;
if (dimension == multidimensionalArray.Rank)
{
multidimensionalArray.SetValue(JaggedArrayGetValue(values, indices), indices);
return;
}
int dimensionLength = multidimensionalArray.GetLength(dimension);
IList list = (IList)JaggedArrayGetValue(values, indices);
int currentValuesLength = list.Count;
if (currentValuesLength != dimensionLength)
{
throw new Exception("Cannot deserialize non-cubical array as multidimensional array.");
}
int[] newIndices = new int[dimension + 1];
for (int i = 0; i < dimension; i++)
{
newIndices[i] = indices[i];
}
for (int i = 0; i < multidimensionalArray.GetLength(dimension); i++)
{
newIndices[dimension] = i;
CopyFromJaggedToMultidimensionalArray(values, multidimensionalArray, newIndices);
}
}
private static object JaggedArrayGetValue(IList values, int[] indices)
{
IList currentList = values;
for (int i = 0; i < indices.Length; i++)
{
int index = indices[i];
if (i == indices.Length - 1)
{
return currentList[index];
}
else
{
currentList = (IList)currentList[index];
}
}
return currentList;
}
public static Array ToMultidimensionalArray(IList values, Type type, int rank)
{
IList<int> dimensions = GetDimensions(values, rank);
while (dimensions.Count < rank)
{
dimensions.Add(0);
}
Array multidimensionalArray = Array.CreateInstance(type, dimensions.ToArray());
CopyFromJaggedToMultidimensionalArray(values, multidimensionalArray, ArrayEmpty<int>());
return multidimensionalArray;
}
// 4.6 has Array.Empty<T> to return a cached empty array. Lacking that in other
// frameworks, Enumerable.Empty<T> happens to be implemented as a cached empty
// array in all versions (in .NET Core the same instance as Array.Empty<T>).
// This includes the internal Linq bridge for 2.0.
// Since this method is simple and only 11 bytes long in a release build it's
// pretty much guaranteed to be inlined, giving us fast access of that cached
// array. With 4.5 and up we use AggressiveInlining just to be sure, so it's
// effectively the same as calling Array.Empty<T> even when not available.
#if HAVE_METHOD_IMPL_ATTRIBUTE
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public static T[] ArrayEmpty<T>()
{
T[] array = Enumerable.Empty<T>() as T[];
Debug.Assert(array != null);
// Defensively guard against a version of Linq where Enumerable.Empty<T> doesn't
// return an array, but throw in debug versions so a better strategy can be
// used if that ever happens.
return array ?? new T[0];
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.