context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// 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.Collections.ObjectModel;
using System.Dynamic.Utils;
namespace System.Runtime.CompilerServices
{
/// <summary>
/// The builder for read only collection.
/// </summary>
/// <typeparam name="T">The type of the collection element.</typeparam>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
internal sealed class ReadOnlyCollectionBuilder<T> : IList<T>, System.Collections.IList
{
private const int DefaultCapacity = 4;
private T[] _items;
private int _size;
private int _version;
private Object _syncRoot;
/// <summary>
/// Constructs a ReadOnlyCollectionBuilder.
/// </summary>
public ReadOnlyCollectionBuilder()
{
_items = Array.Empty<T>();
}
/// <summary>
/// Constructs a ReadOnlyCollectionBuilder with a given initial capacity.
/// The contents are empty but builder will have reserved room for the given
/// number of elements before any reallocations are required.
/// </summary>
public ReadOnlyCollectionBuilder(int capacity)
{
ContractUtils.Requires(capacity >= 0, "capacity");
_items = new T[capacity];
}
/// <summary>
/// Constructs a ReadOnlyCollectionBuilder, copying contents of the given collection.
/// </summary>
/// <param name="collection"></param>
public ReadOnlyCollectionBuilder(IEnumerable<T> collection)
{
ContractUtils.Requires(collection != null, "collection");
ICollection<T> c = collection as ICollection<T>;
if (c != null)
{
int count = c.Count;
_items = new T[count];
c.CopyTo(_items, 0);
_size = count;
}
else
{
_size = 0;
_items = new T[DefaultCapacity];
using (IEnumerator<T> en = collection.GetEnumerator())
{
while (en.MoveNext())
{
Add(en.Current);
}
}
}
}
/// <summary>
/// Gets and sets the capacity of this ReadOnlyCollectionBuilder
/// </summary>
public int Capacity
{
get { return _items.Length; }
set
{
ContractUtils.Requires(value >= _size, "value");
if (value != _items.Length)
{
if (value > 0)
{
T[] newItems = new T[value];
if (_size > 0)
{
Array.Copy(_items, 0, newItems, 0, _size);
}
_items = newItems;
}
else
{
_items = Array.Empty<T>();
}
}
}
}
/// <summary>
/// Returns number of elements in the ReadOnlyCollectionBuilder.
/// </summary>
public int Count
{
get { return _size; }
}
#region IList<T> Members
/// <summary>
/// Returns the index of the first occurrence of a given value in the builder.
/// </summary>
/// <param name="item">An item to search for.</param>
/// <returns>The index of the first occurrence of an item.</returns>
public int IndexOf(T item)
{
return Array.IndexOf(_items, item, 0, _size);
}
/// <summary>
/// Inserts an item to the <see cref="ReadOnlyCollectionBuilder{T}"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which item should be inserted.</param>
/// <param name="item">The object to insert into the <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
public void Insert(int index, T item)
{
ContractUtils.Requires(index <= _size, "index");
if (_size == _items.Length)
{
EnsureCapacity(_size + 1);
}
if (index < _size)
{
Array.Copy(_items, index, _items, index + 1, _size - index);
}
_items[index] = item;
_size++;
_version++;
}
/// <summary>
/// Removes the <see cref="ReadOnlyCollectionBuilder{T}"/> item at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the item to remove.</param>
public void RemoveAt(int index)
{
ContractUtils.Requires(index >= 0 && index < _size, "index");
_size--;
if (index < _size)
{
Array.Copy(_items, index + 1, _items, index, _size - index);
}
_items[_size] = default(T);
_version++;
}
/// <summary>
/// Gets or sets the element at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <returns>The element at the specified index.</returns>
public T this[int index]
{
get
{
ContractUtils.Requires(index < _size, "index");
return _items[index];
}
set
{
ContractUtils.Requires(index < _size, "index");
_items[index] = value;
_version++;
}
}
#endregion
#region ICollection<T> Members
/// <summary>
/// Adds an item to the <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </summary>
/// <param name="item">The object to add to the <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
public void Add(T item)
{
if (_size == _items.Length)
{
EnsureCapacity(_size + 1);
}
_items[_size++] = item;
_version++;
}
/// <summary>
/// Removes all items from the <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </summary>
public void Clear()
{
if (_size > 0)
{
Array.Clear(_items, 0, _size);
_size = 0;
}
_version++;
}
/// <summary>
/// Determines whether the <see cref="ReadOnlyCollectionBuilder{T}"/> contains a specific value
/// </summary>
/// <param name="item">the object to locate in the <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
/// <returns>true if item is found in the <see cref="ReadOnlyCollectionBuilder{T}"/>; otherwise, false.</returns>
public bool Contains(T item)
{
if ((Object)item == null)
{
for (int i = 0; i < _size; i++)
{
if ((Object)_items[i] == null)
{
return true;
}
}
return false;
}
else
{
EqualityComparer<T> c = EqualityComparer<T>.Default;
for (int i = 0; i < _size; i++)
{
if (c.Equals(_items[i], item))
{
return true;
}
}
return false;
}
}
/// <summary>
/// Copies the elements of the <see cref="ReadOnlyCollectionBuilder{T}"/> to an <see cref="Array"/>,
/// starting at particular <see cref="Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
/// <param name="arrayIndex">The zero-based index in array at which copying begins.</param>
public void CopyTo(T[] array, int arrayIndex)
{
Array.Copy(_items, 0, array, arrayIndex, _size);
}
bool ICollection<T>.IsReadOnly
{
get { return false; }
}
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </summary>
/// <param name="item">The object to remove from the <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
/// <returns>true if item was successfully removed from the <see cref="ReadOnlyCollectionBuilder{T}"/>;
/// otherwise, false. This method also returns false if item is not found in the original <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </returns>
public bool Remove(T item)
{
int index = IndexOf(item);
if (index >= 0)
{
RemoveAt(index);
return true;
}
return false;
}
#endregion
#region IEnumerable<T> Members
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.</returns>
public IEnumerator<T> GetEnumerator()
{
return new Enumerator(this);
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region IList Members
bool System.Collections.IList.IsReadOnly
{
get { return false; }
}
int System.Collections.IList.Add(object value)
{
ValidateNullValue(value, "value");
try
{
Add((T)value);
}
catch (InvalidCastException)
{
ThrowInvalidTypeException(value, "value");
}
return Count - 1;
}
bool System.Collections.IList.Contains(object value)
{
if (IsCompatibleObject(value))
{
return Contains((T)value);
}
else return false;
}
int System.Collections.IList.IndexOf(object value)
{
if (IsCompatibleObject(value))
{
return IndexOf((T)value);
}
return -1;
}
void System.Collections.IList.Insert(int index, object value)
{
ValidateNullValue(value, "value");
try
{
Insert(index, (T)value);
}
catch (InvalidCastException)
{
ThrowInvalidTypeException(value, "value");
}
}
bool System.Collections.IList.IsFixedSize
{
get { return false; }
}
void System.Collections.IList.Remove(object value)
{
if (IsCompatibleObject(value))
{
Remove((T)value);
}
}
object System.Collections.IList.this[int index]
{
get
{
return this[index];
}
set
{
ValidateNullValue(value, "value");
try
{
this[index] = (T)value;
}
catch (InvalidCastException)
{
ThrowInvalidTypeException(value, "value");
}
}
}
#endregion
#region ICollection Members
void System.Collections.ICollection.CopyTo(Array array, int index)
{
ContractUtils.RequiresNotNull(array, "array");
ContractUtils.Requires(array.Rank == 1, "array");
Array.Copy(_items, 0, array, index, _size);
}
bool System.Collections.ICollection.IsSynchronized
{
get { return false; }
}
object System.Collections.ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
#endregion
/// <summary>
/// Reverses the order of the elements in the entire <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </summary>
public void Reverse()
{
Reverse(0, Count);
}
/// <summary>
/// Reverses the order of the elements in the specified range.
/// </summary>
/// <param name="index">The zero-based starting index of the range to reverse.</param>
/// <param name="count">The number of elements in the range to reverse.</param>
public void Reverse(int index, int count)
{
ContractUtils.Requires(index >= 0, "index");
ContractUtils.Requires(count >= 0, "count");
Array.Reverse(_items, index, count);
_version++;
}
/// <summary>
/// Copies the elements of the <see cref="ReadOnlyCollectionBuilder{T}"/> to a new array.
/// </summary>
/// <returns>An array containing copies of the elements of the <see cref="ReadOnlyCollectionBuilder{T}"/>.</returns>
public T[] ToArray()
{
T[] array = new T[_size];
Array.Copy(_items, 0, array, 0, _size);
return array;
}
/// <summary>
/// Creates a <see cref="ReadOnlyCollection{T}"/> containing all of the the elements of the <see cref="ReadOnlyCollectionBuilder{T}"/>,
/// avoiding copying the elements to the new array if possible. Resets the <see cref="ReadOnlyCollectionBuilder{T}"/> after the
/// <see cref="ReadOnlyCollection{T}"/> has been created.
/// </summary>
/// <returns>A new instance of <see cref="ReadOnlyCollection{T}"/>.</returns>
public ReadOnlyCollection<T> ToReadOnlyCollection()
{
// Can we use the stored array?
T[] items;
if (_size == _items.Length)
{
items = _items;
}
else
{
items = ToArray();
}
_items = Array.Empty<T>();
_size = 0;
_version++;
return new TrueReadOnlyCollection<T>(items);
}
private void EnsureCapacity(int min)
{
if (_items.Length < min)
{
int newCapacity = DefaultCapacity;
if (_items.Length > 0)
{
newCapacity = _items.Length * 2;
}
if (newCapacity < min)
{
newCapacity = min;
}
Capacity = newCapacity;
}
}
private static bool IsCompatibleObject(object value)
{
return ((value is T) || (value == null && default(T) == null));
}
private static void ValidateNullValue(object value, string argument)
{
if (value == null && !(default(T) == null))
{
throw new ArgumentException(Strings.InvalidNullValue(typeof(T)), argument);
}
}
private static void ThrowInvalidTypeException(object value, string argument)
{
throw new ArgumentException(Strings.InvalidObjectType(value != null ? value.GetType() : (object)"null", typeof(T)), argument);
}
private class Enumerator : IEnumerator<T>, System.Collections.IEnumerator
{
private readonly ReadOnlyCollectionBuilder<T> _builder;
private readonly int _version;
private int _index;
private T _current;
internal Enumerator(ReadOnlyCollectionBuilder<T> builder)
{
_builder = builder;
_version = builder._version;
_index = 0;
_current = default(T);
}
#region IEnumerator<T> Members
public T Current
{
get { return _current; }
}
#endregion
#region IDisposable Members
public void Dispose()
{
GC.SuppressFinalize(this);
}
#endregion
#region IEnumerator Members
object System.Collections.IEnumerator.Current
{
get
{
if (_index == 0 || _index > _builder._size)
{
throw Error.EnumerationIsDone();
}
return _current;
}
}
public bool MoveNext()
{
if (_version == _builder._version)
{
if (_index < _builder._size)
{
_current = _builder._items[_index++];
return true;
}
else
{
_index = _builder._size + 1;
_current = default(T);
return false;
}
}
else
{
throw Error.CollectionModifiedWhileEnumerating();
}
}
#endregion
#region IEnumerator Members
void System.Collections.IEnumerator.Reset()
{
if (_version != _builder._version)
{
throw Error.CollectionModifiedWhileEnumerating();
}
_index = 0;
_current = default(T);
}
#endregion
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using Ocelot.DownstreamRouteFinder.UrlMatcher;
using Ocelot.Responses;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.DownstreamRouteFinder.UrlMatcher
{
public class UrlPathPlaceholderNameAndValueFinderTests
{
private readonly IPlaceholderNameAndValueFinder _finder;
private string _downstreamUrlPath;
private string _downstreamPathTemplate;
private Response<List<PlaceholderNameAndValue>> _result;
private string _query;
public UrlPathPlaceholderNameAndValueFinderTests()
{
_finder = new UrlPathPlaceholderNameAndValueFinder();
}
[Fact]
public void can_match_down_stream_url()
{
this.Given(x => x.GivenIHaveAUpstreamPath(""))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate(""))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(new List<PlaceholderNameAndValue>()))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_nothing_then_placeholder_no_value_is_blank()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{url}", "")
};
this.Given(x => x.GivenIHaveAUpstreamPath(""))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/{url}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_nothing_then_placeholder_value_is_test()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{url}", "test")
};
this.Given(x => x.GivenIHaveAUpstreamPath("/test"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/{url}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void should_match_everything_in_path_with_query()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{everything}", "test/toot")
};
this.Given(x => x.GivenIHaveAUpstreamPath("/test/toot"))
.And(x => GivenIHaveAQuery("?$filter=Name%20eq%20'Sam'"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/{everything}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void should_match_everything_in_path()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{everything}", "test/toot")
};
this.Given(x => x.GivenIHaveAUpstreamPath("/test/toot"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/{everything}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_forward_slash_then_placeholder_no_value_is_blank()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{url}", "")
};
this.Given(x => x.GivenIHaveAUpstreamPath("/"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/{url}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_forward_slash()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
};
this.Given(x => x.GivenIHaveAUpstreamPath("/"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_forward_slash_then_placeholder_then_another_value()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{url}", "1")
};
this.Given(x => x.GivenIHaveAUpstreamPath("/1/products"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/{url}/products"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void should_not_find_anything()
{
this.Given(x => x.GivenIHaveAUpstreamPath("/products"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/products/"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(new List<PlaceholderNameAndValue>()))
.BDDfy();
}
[Fact]
public void should_find_query_string()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{productId}", "1")
};
this.Given(x => x.GivenIHaveAUpstreamPath("/products"))
.And(x => x.GivenIHaveAQuery("?productId=1"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/products?productId={productId}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void should_find_query_string_dont_include_hardcoded()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{productId}", "1")
};
this.Given(x => x.GivenIHaveAUpstreamPath("/products"))
.And(x => x.GivenIHaveAQuery("?productId=1&categoryId=2"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/products?productId={productId}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void should_find_multiple_query_string()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{productId}", "1"),
new PlaceholderNameAndValue("{categoryId}", "2")
};
this.Given(x => x.GivenIHaveAUpstreamPath("/products"))
.And(x => x.GivenIHaveAQuery("?productId=1&categoryId=2"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/products?productId={productId}&categoryId={categoryId}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void should_find_multiple_query_string_and_path()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{productId}", "1"),
new PlaceholderNameAndValue("{categoryId}", "2"),
new PlaceholderNameAndValue("{account}", "3")
};
this.Given(x => x.GivenIHaveAUpstreamPath("/products/3"))
.And(x => x.GivenIHaveAQuery("?productId=1&categoryId=2"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/products/{account}?productId={productId}&categoryId={categoryId}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void should_find_multiple_query_string_and_path_that_ends_with_slash()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{productId}", "1"),
new PlaceholderNameAndValue("{categoryId}", "2"),
new PlaceholderNameAndValue("{account}", "3")
};
this.Given(x => x.GivenIHaveAUpstreamPath("/products/3/"))
.And(x => x.GivenIHaveAQuery("?productId=1&categoryId=2"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/products/{account}/?productId={productId}&categoryId={categoryId}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_no_slash()
{
this.Given(x => x.GivenIHaveAUpstreamPath("api"))
.Given(x => x.GivenIHaveAnUpstreamUrlTemplate("api"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(new List<PlaceholderNameAndValue>()))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_one_slash()
{
this.Given(x => x.GivenIHaveAUpstreamPath("api/"))
.Given(x => x.GivenIHaveAnUpstreamUrlTemplate("api/"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(new List<PlaceholderNameAndValue>()))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_downstream_template()
{
this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/"))
.Given(x => x.GivenIHaveAnUpstreamUrlTemplate("api/product/products/"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(new List<PlaceholderNameAndValue>()))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_downstream_template_with_one_place_holder()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{productId}", "1")
};
this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/1"))
.Given(x => x.GivenIHaveAnUpstreamUrlTemplate("api/product/products/{productId}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_downstream_template_with_two_place_holders()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{productId}", "1"),
new PlaceholderNameAndValue("{categoryId}", "2")
};
this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/1/2"))
.Given(x => x.GivenIHaveAnUpstreamUrlTemplate("api/product/products/{productId}/{categoryId}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_downstream_template_with_two_place_holders_seperated_by_something()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{productId}", "1"),
new PlaceholderNameAndValue("{categoryId}", "2")
};
this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/1/categories/2"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("api/product/products/{productId}/categories/{categoryId}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_downstream_template_with_three_place_holders_seperated_by_something()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{productId}", "1"),
new PlaceholderNameAndValue("{categoryId}", "2"),
new PlaceholderNameAndValue("{variantId}", "123")
};
this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/1/categories/2/variant/123"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("api/product/products/{productId}/categories/{categoryId}/variant/{variantId}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_downstream_template_with_three_place_holders()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{productId}", "1"),
new PlaceholderNameAndValue("{categoryId}", "2")
};
this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/1/categories/2/variant/"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("api/product/products/{productId}/categories/{categoryId}/variant/"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_downstream_template_with_place_holder_to_final_url_path()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{finalUrlPath}", "product/products/categories/"),
};
this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/categories/"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("api/{finalUrlPath}/"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
private void ThenTheTemplatesVariablesAre(List<PlaceholderNameAndValue> expectedResults)
{
foreach (var expectedResult in expectedResults)
{
var result = _result.Data.First(t => t.Name == expectedResult.Name);
result.Value.ShouldBe(expectedResult.Value);
}
}
private void GivenIHaveAUpstreamPath(string downstreamPath)
{
_downstreamUrlPath = downstreamPath;
}
private void GivenIHaveAnUpstreamUrlTemplate(string downstreamUrlTemplate)
{
_downstreamPathTemplate = downstreamUrlTemplate;
}
private void WhenIFindTheUrlVariableNamesAndValues()
{
_result = _finder.Find(_downstreamUrlPath, _query, _downstreamPathTemplate);
}
private void GivenIHaveAQuery(string query)
{
_query = query;
}
}
}
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using NUnit.TestUtilities;
using NUnit.TestUtilities.Collections;
using static NUnit.Framework.Constraints.UniqueItemsConstraint;
namespace NUnit.Framework.Constraints
{
[TestFixture]
public class UniqueItemsConstraintTests : ConstraintTestBase
{
[SetUp]
public void SetUp()
{
TheConstraint = new UniqueItemsConstraint();
StringRepresentation = "<uniqueitems>";
ExpectedDescription = "all items unique";
}
static object[] SuccessData = new object[] { new int[] { 1, 3, 17, -2, 34 }, new object[0] };
static object[] FailureData = new object[] { new object[] {
new int[] { 1, 3, 17, 3, 34 },
"< 1, 3, 17, 3, 34 >" + Environment.NewLine + " Not unique items: < 3 >" }
};
[Test, SetCulture("")]
[TestCaseSource(nameof(IgnoreCaseData))]
public void HonorsIgnoreCase(IEnumerable actual)
{
var constraint = new UniqueItemsConstraint().IgnoreCase;
var result = constraint.ApplyTo(actual);
Assert.That(result.IsSuccess, Is.False, "{0} should not be unique ignoring case", actual);
}
private static readonly object[] IgnoreCaseData =
{
new object[] {new SimpleObjectCollection("x", "y", "z", "Z")},
new object[] {new[] {'A', 'B', 'C', 'c'}},
new object[] {new[] {"a", "b", "c", "C"}}
};
private static readonly object[] DuplicateItemsData =
{
new object[] {new[] { 1, 2, 3, 2 }, new[] { 2 }},
new object[] {new[] { 2, 1, 2, 3, 2 }, new[] { 2 }},
new object[] {new[] { 2, 1, 2, 3, 3 }, new[] { 2, 3 }},
new object[] {new[] { "x", null, "x" }, new[] { "x" }}
};
static readonly IEnumerable<int> RANGE = Enumerable.Range(0, 10000);
static readonly TestCaseData[] PerformanceData_FastPath =
{
// Generic container
new TestCaseData(RANGE, false),
new TestCaseData(new List<int>(RANGE), false),
new TestCaseData(new List<double>(RANGE.Select(v => (double)v)), false),
new TestCaseData(new List<string>(RANGE.Select(v => v.ToString())), false),
new TestCaseData(new List<string>(RANGE.Select(v => v.ToString())), true),
// Non-generic container
new TestCaseData(new SimpleObjectCollection(RANGE), false)
{
ArgDisplayNames = new[] { "IEnumerable<int>", "false" }
},
new TestCaseData(new SimpleObjectCollection(RANGE.Cast<object>()), false)
{
ArgDisplayNames = new[] { "IEnumerable<object>", "false" },
},
new TestCaseData(new SimpleObjectCollection(RANGE.Select(v => (double)v).Cast<object>()), false)
{
ArgDisplayNames = new[] { "IEnumerable<double>", "false" }
},
new TestCaseData(new SimpleObjectCollection(RANGE.Select(v => v.ToString()).Cast<object>()), false)
{
ArgDisplayNames = new[] { "IEnumerable<string>", "false" }
},
new TestCaseData(new SimpleObjectCollection(RANGE.Select(v => v.ToString()).Cast<object>()), true)
{
ArgDisplayNames = new[] { "IEnumerable<string>", "true" }
},
new TestCaseData(new SimpleObjectCollection(RANGE.Select(v => new TestReferenceType() { A = v }).Cast<object>()), true)
{
ArgDisplayNames = new[] { "IEnumerable<TestReferenceType>", "true" }
},
};
static TestCaseData[] PerformanceData_FastPath_MixedTypes
{
get
{
var refTypes = RANGE.Take(5000).Select(o => new TestReferenceType() { A = o }).Cast<object>();
var valueTypes = RANGE.Skip<int>(5000).Select(o => new TestValueType() { A = o }).Cast<object>();
var container = new List<object>();
container.AddRange(refTypes);
container.AddRange(valueTypes);
return new TestCaseData[] {
new TestCaseData(new SimpleObjectCollection(container.Cast<object>()), true)
{
ArgDisplayNames = new[] { "IEnumerable<dynamic>", "true" }
}
};
}
}
[TestCaseSource(nameof(PerformanceData_FastPath))]
[TestCaseSource(nameof(PerformanceData_FastPath_MixedTypes))]
public void PerformanceTests_FastPath(IEnumerable values, bool ignoreCase)
{
Warn.Unless(() =>
{
if (ignoreCase)
Assert.That(values, Is.Unique.IgnoreCase);
else
Assert.That(values, Is.Unique);
}, HelperConstraints.HasMaxTime(100));
}
private static IEnumerable<int> RANGE_SLOWPATH = Enumerable.Range(0, 750);
private static readonly TestCaseData[] SlowpathData =
{
new TestCaseData(RANGE_SLOWPATH.Select(o => o.ToString()).Cast<object>())
{
ArgDisplayNames = new[] { "IEnumerable<string>" }
},
new TestCaseData(RANGE_SLOWPATH.Select(o => new DateTimeOffset(o, TimeSpan.Zero)).Cast<object>())
{
ArgDisplayNames = new[] { "IEnumerable<DateTimeOffset>" }
},
new TestCaseData(RANGE_SLOWPATH.Select(o => (char)o).Cast<object>())
{
ArgDisplayNames = new[] { "IEnumerable<char>" }
},
new TestCaseData(RANGE_SLOWPATH.Select(o => (double)o).Cast<object>())
{
ArgDisplayNames = new[] { "IEnumerable<double>" }
},
new TestCaseData(RANGE_SLOWPATH.Select(o => new KeyValuePair<int, int>(o, o)).Cast<object>())
{
ArgDisplayNames = new[] { "IEnumerable<KeyValuePair<,>>" }
},
new TestCaseData(RANGE_SLOWPATH.Select(o => new DictionaryEntry(o, o)).Cast<object>())
{
ArgDisplayNames = new[] { "IEnumerable<DictionaryEntry>" }
}
};
[TestCaseSource(nameof(SlowpathData))]
public void SlowPath_TakenWhenSpecialTypes(IEnumerable<object> testData)
{
var allData = new List<object>();
allData.Add(new TestValueType() { A = 1 });
allData.AddRange(testData);
var items = new SimpleObjectCollection((IEnumerable<object>)allData);
var constraint = new UniqueItemsConstraint();
var stopwatch = new Stopwatch();
stopwatch.Start();
constraint.ApplyTo(items);
stopwatch.Stop();
Assert.That(stopwatch.ElapsedMilliseconds, Is.GreaterThanOrEqualTo(50));
}
[TestCaseSource(nameof(DuplicateItemsData))]
public void DuplicateItemsTests(IEnumerable items, IEnumerable expectedFailures)
{
var constraint = new UniqueItemsConstraint().IgnoreCase;
var result = constraint.ApplyTo(items) as UniqueItemsConstraintResult;
Assert.That(result, Is.Not.Null);
Assert.That(result.NonUniqueItems, Is.EqualTo(expectedFailures));
}
private static TestCaseData[] RequiresDefaultComparer
{
get
{
var sameRef = new TestReferenceType() { A = 1 };
return new TestCaseData[] {
new TestCaseData() {
Arguments = new object[]
{
new SimpleObjectCollection(new TestValueType() { A = 1 }, new TestValueType() { A = 2 }),
true
},
ArgDisplayNames = new[] { "ValueTypes", "true" }
},
new TestCaseData() {
Arguments = new object[]
{
new SimpleObjectCollection(new TestValueType() { A = 1 }, new TestValueType() { A = 1 }),
false
},
ArgDisplayNames = new[] { "ValueTypes", "false" }
},
new TestCaseData() {
Arguments = new object[]
{
new SimpleObjectCollection(new TestReferenceType() { A = 1 }, new TestReferenceType() { A = 1 }),
true
},
ArgDisplayNames = new[] { "ReferenceTypes", "true" }
},
new TestCaseData() {
Arguments = new object[]
{
new SimpleObjectCollection(sameRef, sameRef),
false
},
ArgDisplayNames = new[] { "ReferenceTypes", "false" }
},
new TestCaseData() {
Arguments = new object[]
{
new SimpleObjectCollection(
new TestReferenceType_OverridesEquals() { A = 1 },
new TestReferenceType_OverridesEquals() { A = 1 }
),
false
},
ArgDisplayNames = new[] { "ReferenceTypesOverridesEquals", "false" }
},
new TestCaseData() {
Arguments = new object[]
{
new SimpleObjectCollection(new TestValueType() { A = 1 }, new TestReferenceType() { A = 1 }),
true
},
ArgDisplayNames = new[] { "MixedTypes", "true" }
},
new TestCaseData() {
Arguments = new object[]
{
new SimpleObjectCollection(new TestValueType() { A = 1 }, sameRef, sameRef),
false
},
ArgDisplayNames = new[] { "MixedTypes", "false" }
}
};
}
}
[TestCaseSource(nameof(RequiresDefaultComparer))]
public void DuplicateItemsTests_RequiresDefaultComparer(IEnumerable items, bool success)
{
var constraint = new UniqueItemsConstraint();
var result = constraint.ApplyTo(items) as UniqueItemsConstraintResult;
Assert.That(result, Is.Not.Null);
Assert.That(result.IsSuccess, Is.EqualTo(success));
}
private sealed class TestReferenceType
{
public int A { get; set; }
}
private sealed class TestReferenceType_OverridesEquals
{
public int A { get; set; }
public override bool Equals(object obj)
{
if (obj is TestReferenceType_OverridesEquals other)
return other.A == this.A;
return false;
}
public override int GetHashCode()
{
return this.A.GetHashCode();
}
}
private struct TestValueType
{
public int A { get; set; }
}
}
}
| |
// 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.Globalization;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Numerics.Tests
{
public class Vector2Tests
{
[Fact]
public void Vector2MarshalSizeTest()
{
Assert.Equal(8, Marshal.SizeOf<Vector2>());
Assert.Equal(8, Marshal.SizeOf<Vector2>(new Vector2()));
}
[Fact]
public void Vector2CopyToTest()
{
Vector2 v1 = new Vector2(2.0f, 3.0f);
float[] a = new float[3];
float[] b = new float[2];
Assert.Throws<NullReferenceException>(() => v1.CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => v1.CopyTo(a, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => v1.CopyTo(a, a.Length));
AssertExtensions.Throws<ArgumentException>(null, () => v1.CopyTo(a, 2));
v1.CopyTo(a, 1);
v1.CopyTo(b);
Assert.Equal(0.0, a[0]);
Assert.Equal(2.0, a[1]);
Assert.Equal(3.0, a[2]);
Assert.Equal(2.0, b[0]);
Assert.Equal(3.0, b[1]);
}
[Fact]
public void Vector2GetHashCodeTest()
{
Vector2 v1 = new Vector2(2.0f, 3.0f);
Vector2 v2 = new Vector2(2.0f, 3.0f);
Vector2 v3 = new Vector2(3.0f, 2.0f);
Assert.Equal(v1.GetHashCode(), v1.GetHashCode());
Assert.Equal(v1.GetHashCode(), v2.GetHashCode());
Assert.NotEqual(v1.GetHashCode(), v3.GetHashCode());
Vector2 v4 = new Vector2(0.0f, 0.0f);
Vector2 v6 = new Vector2(1.0f, 0.0f);
Vector2 v7 = new Vector2(0.0f, 1.0f);
Vector2 v8 = new Vector2(1.0f, 1.0f);
Assert.NotEqual(v4.GetHashCode(), v6.GetHashCode());
Assert.NotEqual(v4.GetHashCode(), v7.GetHashCode());
Assert.NotEqual(v4.GetHashCode(), v8.GetHashCode());
Assert.NotEqual(v7.GetHashCode(), v6.GetHashCode());
Assert.NotEqual(v8.GetHashCode(), v6.GetHashCode());
Assert.NotEqual(v8.GetHashCode(), v7.GetHashCode());
}
[Fact]
public void Vector2ToStringTest()
{
string separator = CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator;
CultureInfo enUsCultureInfo = new CultureInfo("en-US");
Vector2 v1 = new Vector2(2.0f, 3.0f);
string v1str = v1.ToString();
string expectedv1 = string.Format(CultureInfo.CurrentCulture
, "<{1:G}{0} {2:G}>"
, new object[] { separator, 2, 3 });
Assert.Equal(expectedv1, v1str);
string v1strformatted = v1.ToString("c", CultureInfo.CurrentCulture);
string expectedv1formatted = string.Format(CultureInfo.CurrentCulture
, "<{1:c}{0} {2:c}>"
, new object[] { separator, 2, 3 });
Assert.Equal(expectedv1formatted, v1strformatted);
string v2strformatted = v1.ToString("c", enUsCultureInfo);
string expectedv2formatted = string.Format(enUsCultureInfo
, "<{1:c}{0} {2:c}>"
, new object[] { enUsCultureInfo.NumberFormat.NumberGroupSeparator, 2, 3 });
Assert.Equal(expectedv2formatted, v2strformatted);
string v3strformatted = v1.ToString("c");
string expectedv3formatted = string.Format(CultureInfo.CurrentCulture
, "<{1:c}{0} {2:c}>"
, new object[] { separator, 2, 3 });
Assert.Equal(expectedv3formatted, v3strformatted);
}
// A test for Distance (Vector2f, Vector2f)
[Fact]
public void Vector2DistanceTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(3.0f, 4.0f);
float expected = (float)System.Math.Sqrt(8);
float actual;
actual = Vector2.Distance(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Distance did not return the expected value.");
}
// A test for Distance (Vector2f, Vector2f)
// Distance from the same point
[Fact]
public void Vector2DistanceTest2()
{
Vector2 a = new Vector2(1.051f, 2.05f);
Vector2 b = new Vector2(1.051f, 2.05f);
float actual = Vector2.Distance(a, b);
Assert.Equal(0.0f, actual);
}
// A test for DistanceSquared (Vector2f, Vector2f)
[Fact]
public void Vector2DistanceSquaredTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(3.0f, 4.0f);
float expected = 8.0f;
float actual;
actual = Vector2.DistanceSquared(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.DistanceSquared did not return the expected value.");
}
// A test for Dot (Vector2f, Vector2f)
[Fact]
public void Vector2DotTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(3.0f, 4.0f);
float expected = 11.0f;
float actual;
actual = Vector2.Dot(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Dot did not return the expected value.");
}
// A test for Dot (Vector2f, Vector2f)
// Dot test for perpendicular vector
[Fact]
public void Vector2DotTest1()
{
Vector2 a = new Vector2(1.55f, 1.55f);
Vector2 b = new Vector2(-1.55f, 1.55f);
float expected = 0.0f;
float actual = Vector2.Dot(a, b);
Assert.Equal(expected, actual);
}
// A test for Dot (Vector2f, Vector2f)
// Dot test with specail float values
[Fact]
public void Vector2DotTest2()
{
Vector2 a = new Vector2(float.MinValue, float.MinValue);
Vector2 b = new Vector2(float.MaxValue, float.MaxValue);
float actual = Vector2.Dot(a, b);
Assert.True(float.IsNegativeInfinity(actual), "Vector2f.Dot did not return the expected value.");
}
// A test for Length ()
[Fact]
public void Vector2LengthTest()
{
Vector2 a = new Vector2(2.0f, 4.0f);
Vector2 target = a;
float expected = (float)System.Math.Sqrt(20);
float actual;
actual = target.Length();
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Length did not return the expected value.");
}
// A test for Length ()
// Length test where length is zero
[Fact]
public void Vector2LengthTest1()
{
Vector2 target = new Vector2();
target.X = 0.0f;
target.Y = 0.0f;
float expected = 0.0f;
float actual;
actual = target.Length();
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Length did not return the expected value.");
}
// A test for LengthSquared ()
[Fact]
public void Vector2LengthSquaredTest()
{
Vector2 a = new Vector2(2.0f, 4.0f);
Vector2 target = a;
float expected = 20.0f;
float actual;
actual = target.LengthSquared();
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.LengthSquared did not return the expected value.");
}
// A test for LengthSquared ()
// LengthSquared test where the result is zero
[Fact]
public void Vector2LengthSquaredTest1()
{
Vector2 a = new Vector2(0.0f, 0.0f);
float expected = 0.0f;
float actual = a.LengthSquared();
Assert.Equal(expected, actual);
}
// A test for Min (Vector2f, Vector2f)
[Fact]
public void Vector2MinTest()
{
Vector2 a = new Vector2(-1.0f, 4.0f);
Vector2 b = new Vector2(2.0f, 1.0f);
Vector2 expected = new Vector2(-1.0f, 1.0f);
Vector2 actual;
actual = Vector2.Min(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Min did not return the expected value.");
}
[Fact]
public void Vector2MinMaxCodeCoverageTest()
{
Vector2 min = new Vector2(0, 0);
Vector2 max = new Vector2(1, 1);
Vector2 actual;
// Min.
actual = Vector2.Min(min, max);
Assert.Equal(actual, min);
actual = Vector2.Min(max, min);
Assert.Equal(actual, min);
// Max.
actual = Vector2.Max(min, max);
Assert.Equal(actual, max);
actual = Vector2.Max(max, min);
Assert.Equal(actual, max);
}
// A test for Max (Vector2f, Vector2f)
[Fact]
public void Vector2MaxTest()
{
Vector2 a = new Vector2(-1.0f, 4.0f);
Vector2 b = new Vector2(2.0f, 1.0f);
Vector2 expected = new Vector2(2.0f, 4.0f);
Vector2 actual;
actual = Vector2.Max(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Max did not return the expected value.");
}
// A test for Clamp (Vector2f, Vector2f, Vector2f)
[Fact]
public void Vector2ClampTest()
{
Vector2 a = new Vector2(0.5f, 0.3f);
Vector2 min = new Vector2(0.0f, 0.1f);
Vector2 max = new Vector2(1.0f, 1.1f);
// Normal case.
// Case N1: specified value is in the range.
Vector2 expected = new Vector2(0.5f, 0.3f);
Vector2 actual = Vector2.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value.");
// Normal case.
// Case N2: specified value is bigger than max value.
a = new Vector2(2.0f, 3.0f);
expected = max;
actual = Vector2.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value.");
// Case N3: specified value is smaller than max value.
a = new Vector2(-1.0f, -2.0f);
expected = min;
actual = Vector2.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value.");
// Case N4: combination case.
a = new Vector2(-2.0f, 4.0f);
expected = new Vector2(min.X, max.Y);
actual = Vector2.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value.");
// User specified min value is bigger than max value.
max = new Vector2(0.0f, 0.1f);
min = new Vector2(1.0f, 1.1f);
// Case W1: specified value is in the range.
a = new Vector2(0.5f, 0.3f);
expected = max;
actual = Vector2.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value.");
// Normal case.
// Case W2: specified value is bigger than max and min value.
a = new Vector2(2.0f, 3.0f);
expected = max;
actual = Vector2.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value.");
// Case W3: specified value is smaller than min and max value.
a = new Vector2(-1.0f, -2.0f);
expected = max;
actual = Vector2.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value.");
}
// A test for Lerp (Vector2f, Vector2f, float)
[Fact]
public void Vector2LerpTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(3.0f, 4.0f);
float t = 0.5f;
Vector2 expected = new Vector2(2.0f, 3.0f);
Vector2 actual;
actual = Vector2.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector2f, Vector2f, float)
// Lerp test with factor zero
[Fact]
public void Vector2LerpTest1()
{
Vector2 a = new Vector2(0.0f, 0.0f);
Vector2 b = new Vector2(3.18f, 4.25f);
float t = 0.0f;
Vector2 expected = Vector2.Zero;
Vector2 actual = Vector2.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector2f, Vector2f, float)
// Lerp test with factor one
[Fact]
public void Vector2LerpTest2()
{
Vector2 a = new Vector2(0.0f, 0.0f);
Vector2 b = new Vector2(3.18f, 4.25f);
float t = 1.0f;
Vector2 expected = new Vector2(3.18f, 4.25f);
Vector2 actual = Vector2.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector2f, Vector2f, float)
// Lerp test with factor > 1
[Fact]
public void Vector2LerpTest3()
{
Vector2 a = new Vector2(0.0f, 0.0f);
Vector2 b = new Vector2(3.18f, 4.25f);
float t = 2.0f;
Vector2 expected = b * 2.0f;
Vector2 actual = Vector2.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector2f, Vector2f, float)
// Lerp test with factor < 0
[Fact]
public void Vector2LerpTest4()
{
Vector2 a = new Vector2(0.0f, 0.0f);
Vector2 b = new Vector2(3.18f, 4.25f);
float t = -2.0f;
Vector2 expected = -(b * 2.0f);
Vector2 actual = Vector2.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector2f, Vector2f, float)
// Lerp test with special float value
[Fact]
public void Vector2LerpTest5()
{
Vector2 a = new Vector2(45.67f, 90.0f);
Vector2 b = new Vector2(float.PositiveInfinity, float.NegativeInfinity);
float t = 0.408f;
Vector2 actual = Vector2.Lerp(a, b, t);
Assert.True(float.IsPositiveInfinity(actual.X), "Vector2f.Lerp did not return the expected value.");
Assert.True(float.IsNegativeInfinity(actual.Y), "Vector2f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector2f, Vector2f, float)
// Lerp test from the same point
[Fact]
public void Vector2LerpTest6()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(1.0f, 2.0f);
float t = 0.5f;
Vector2 expected = new Vector2(1.0f, 2.0f);
Vector2 actual = Vector2.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Lerp did not return the expected value.");
}
// A test for Transform(Vector2f, Matrix4x4)
[Fact]
public void Vector2TransformTest()
{
Vector2 v = new Vector2(1.0f, 2.0f);
Matrix4x4 m =
Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f));
m.M41 = 10.0f;
m.M42 = 20.0f;
m.M43 = 30.0f;
Vector2 expected = new Vector2(10.316987f, 22.183012f);
Vector2 actual;
actual = Vector2.Transform(v, m);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Transform did not return the expected value.");
}
// A test for Transform(Vector2f, Matrix3x2)
[Fact]
public void Vector2Transform3x2Test()
{
Vector2 v = new Vector2(1.0f, 2.0f);
Matrix3x2 m = Matrix3x2.CreateRotation(MathHelper.ToRadians(30.0f));
m.M31 = 10.0f;
m.M32 = 20.0f;
Vector2 expected = new Vector2(9.866025f, 22.23205f);
Vector2 actual;
actual = Vector2.Transform(v, m);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Transform did not return the expected value.");
}
// A test for TransformNormal (Vector2f, Matrix4x4)
[Fact]
public void Vector2TransformNormalTest()
{
Vector2 v = new Vector2(1.0f, 2.0f);
Matrix4x4 m =
Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f));
m.M41 = 10.0f;
m.M42 = 20.0f;
m.M43 = 30.0f;
Vector2 expected = new Vector2(0.3169873f, 2.18301272f);
Vector2 actual;
actual = Vector2.TransformNormal(v, m);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Tranform did not return the expected value.");
}
// A test for TransformNormal (Vector2f, Matrix3x2)
[Fact]
public void Vector2TransformNormal3x2Test()
{
Vector2 v = new Vector2(1.0f, 2.0f);
Matrix3x2 m = Matrix3x2.CreateRotation(MathHelper.ToRadians(30.0f));
m.M31 = 10.0f;
m.M32 = 20.0f;
Vector2 expected = new Vector2(-0.133974612f, 2.232051f);
Vector2 actual;
actual = Vector2.TransformNormal(v, m);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Transform did not return the expected value.");
}
// A test for Transform (Vector2f, Quaternion)
[Fact]
public void Vector2TransformByQuaternionTest()
{
Vector2 v = new Vector2(1.0f, 2.0f);
Matrix4x4 m =
Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f));
Quaternion q = Quaternion.CreateFromRotationMatrix(m);
Vector2 expected = Vector2.Transform(v, m);
Vector2 actual = Vector2.Transform(v, q);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Transform did not return the expected value.");
}
// A test for Transform (Vector2f, Quaternion)
// Transform Vector2f with zero quaternion
[Fact]
public void Vector2TransformByQuaternionTest1()
{
Vector2 v = new Vector2(1.0f, 2.0f);
Quaternion q = new Quaternion();
Vector2 expected = v;
Vector2 actual = Vector2.Transform(v, q);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Transform did not return the expected value.");
}
// A test for Transform (Vector2f, Quaternion)
// Transform Vector2f with identity quaternion
[Fact]
public void Vector2TransformByQuaternionTest2()
{
Vector2 v = new Vector2(1.0f, 2.0f);
Quaternion q = Quaternion.Identity;
Vector2 expected = v;
Vector2 actual = Vector2.Transform(v, q);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Transform did not return the expected value.");
}
// A test for Normalize (Vector2f)
[Fact]
public void Vector2NormalizeTest()
{
Vector2 a = new Vector2(2.0f, 3.0f);
Vector2 expected = new Vector2(0.554700196225229122018341733457f, 0.8320502943378436830275126001855f);
Vector2 actual;
actual = Vector2.Normalize(a);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Normalize did not return the expected value.");
}
// A test for Normalize (Vector2f)
// Normalize zero length vector
[Fact]
public void Vector2NormalizeTest1()
{
Vector2 a = new Vector2(); // no parameter, default to 0.0f
Vector2 actual = Vector2.Normalize(a);
Assert.True(float.IsNaN(actual.X) && float.IsNaN(actual.Y), "Vector2f.Normalize did not return the expected value.");
}
// A test for Normalize (Vector2f)
// Normalize infinite length vector
[Fact]
public void Vector2NormalizeTest2()
{
Vector2 a = new Vector2(float.MaxValue, float.MaxValue);
Vector2 actual = Vector2.Normalize(a);
Vector2 expected = new Vector2(0, 0);
Assert.Equal(expected, actual);
}
// A test for operator - (Vector2f)
[Fact]
public void Vector2UnaryNegationTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 expected = new Vector2(-1.0f, -2.0f);
Vector2 actual;
actual = -a;
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator - did not return the expected value.");
}
// A test for operator - (Vector2f)
// Negate test with special float value
[Fact]
public void Vector2UnaryNegationTest1()
{
Vector2 a = new Vector2(float.PositiveInfinity, float.NegativeInfinity);
Vector2 actual = -a;
Assert.True(float.IsNegativeInfinity(actual.X), "Vector2f.operator - did not return the expected value.");
Assert.True(float.IsPositiveInfinity(actual.Y), "Vector2f.operator - did not return the expected value.");
}
// A test for operator - (Vector2f)
// Negate test with special float value
[Fact]
public void Vector2UnaryNegationTest2()
{
Vector2 a = new Vector2(float.NaN, 0.0f);
Vector2 actual = -a;
Assert.True(float.IsNaN(actual.X), "Vector2f.operator - did not return the expected value.");
Assert.True(float.Equals(0.0f, actual.Y), "Vector2f.operator - did not return the expected value.");
}
// A test for operator - (Vector2f, Vector2f)
[Fact]
public void Vector2SubtractionTest()
{
Vector2 a = new Vector2(1.0f, 3.0f);
Vector2 b = new Vector2(2.0f, 1.5f);
Vector2 expected = new Vector2(-1.0f, 1.5f);
Vector2 actual;
actual = a - b;
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator - did not return the expected value.");
}
// A test for operator * (Vector2f, float)
[Fact]
public void Vector2MultiplyOperatorTest()
{
Vector2 a = new Vector2(2.0f, 3.0f);
const float factor = 2.0f;
Vector2 expected = new Vector2(4.0f, 6.0f);
Vector2 actual;
actual = a * factor;
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator * did not return the expected value.");
}
// A test for operator * (float, Vector2f)
[Fact]
public void Vector2MultiplyOperatorTest2()
{
Vector2 a = new Vector2(2.0f, 3.0f);
const float factor = 2.0f;
Vector2 expected = new Vector2(4.0f, 6.0f);
Vector2 actual;
actual = factor * a;
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator * did not return the expected value.");
}
// A test for operator * (Vector2f, Vector2f)
[Fact]
public void Vector2MultiplyOperatorTest3()
{
Vector2 a = new Vector2(2.0f, 3.0f);
Vector2 b = new Vector2(4.0f, 5.0f);
Vector2 expected = new Vector2(8.0f, 15.0f);
Vector2 actual;
actual = a * b;
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator * did not return the expected value.");
}
// A test for operator / (Vector2f, float)
[Fact]
public void Vector2DivisionTest()
{
Vector2 a = new Vector2(2.0f, 3.0f);
float div = 2.0f;
Vector2 expected = new Vector2(1.0f, 1.5f);
Vector2 actual;
actual = a / div;
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator / did not return the expected value.");
}
// A test for operator / (Vector2f, Vector2f)
[Fact]
public void Vector2DivisionTest1()
{
Vector2 a = new Vector2(2.0f, 3.0f);
Vector2 b = new Vector2(4.0f, 5.0f);
Vector2 expected = new Vector2(2.0f / 4.0f, 3.0f / 5.0f);
Vector2 actual;
actual = a / b;
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator / did not return the expected value.");
}
// A test for operator / (Vector2f, float)
// Divide by zero
[Fact]
public void Vector2DivisionTest2()
{
Vector2 a = new Vector2(-2.0f, 3.0f);
float div = 0.0f;
Vector2 actual = a / div;
Assert.True(float.IsNegativeInfinity(actual.X), "Vector2f.operator / did not return the expected value.");
Assert.True(float.IsPositiveInfinity(actual.Y), "Vector2f.operator / did not return the expected value.");
}
// A test for operator / (Vector2f, Vector2f)
// Divide by zero
[Fact]
public void Vector2DivisionTest3()
{
Vector2 a = new Vector2(0.047f, -3.0f);
Vector2 b = new Vector2();
Vector2 actual = a / b;
Assert.True(float.IsInfinity(actual.X), "Vector2f.operator / did not return the expected value.");
Assert.True(float.IsInfinity(actual.Y), "Vector2f.operator / did not return the expected value.");
}
// A test for operator + (Vector2f, Vector2f)
[Fact]
public void Vector2AdditionTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(3.0f, 4.0f);
Vector2 expected = new Vector2(4.0f, 6.0f);
Vector2 actual;
actual = a + b;
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator + did not return the expected value.");
}
// A test for Vector2f (float, float)
[Fact]
public void Vector2ConstructorTest()
{
float x = 1.0f;
float y = 2.0f;
Vector2 target = new Vector2(x, y);
Assert.True(MathHelper.Equal(target.X, x) && MathHelper.Equal(target.Y, y), "Vector2f(x,y) constructor did not return the expected value.");
}
// A test for Vector2f ()
// Constructor with no parameter
[Fact]
public void Vector2ConstructorTest2()
{
Vector2 target = new Vector2();
Assert.Equal(target.X, 0.0f);
Assert.Equal(target.Y, 0.0f);
}
// A test for Vector2f (float, float)
// Constructor with special floating values
[Fact]
public void Vector2ConstructorTest3()
{
Vector2 target = new Vector2(float.NaN, float.MaxValue);
Assert.Equal(target.X, float.NaN);
Assert.Equal(target.Y, float.MaxValue);
}
// A test for Vector2f (float)
[Fact]
public void Vector2ConstructorTest4()
{
float value = 1.0f;
Vector2 target = new Vector2(value);
Vector2 expected = new Vector2(value, value);
Assert.Equal(expected, target);
value = 2.0f;
target = new Vector2(value);
expected = new Vector2(value, value);
Assert.Equal(expected, target);
}
// A test for Add (Vector2f, Vector2f)
[Fact]
public void Vector2AddTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(5.0f, 6.0f);
Vector2 expected = new Vector2(6.0f, 8.0f);
Vector2 actual;
actual = Vector2.Add(a, b);
Assert.Equal(expected, actual);
}
// A test for Divide (Vector2f, float)
[Fact]
public void Vector2DivideTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
float div = 2.0f;
Vector2 expected = new Vector2(0.5f, 1.0f);
Vector2 actual;
actual = Vector2.Divide(a, div);
Assert.Equal(expected, actual);
}
// A test for Divide (Vector2f, Vector2f)
[Fact]
public void Vector2DivideTest1()
{
Vector2 a = new Vector2(1.0f, 6.0f);
Vector2 b = new Vector2(5.0f, 2.0f);
Vector2 expected = new Vector2(1.0f / 5.0f, 6.0f / 2.0f);
Vector2 actual;
actual = Vector2.Divide(a, b);
Assert.Equal(expected, actual);
}
// A test for Equals (object)
[Fact]
public void Vector2EqualsTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(1.0f, 2.0f);
// case 1: compare between same values
object obj = b;
bool expected = true;
bool actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 2: compare between different values
b.X = 10.0f;
obj = b;
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 3: compare between different types.
obj = new Quaternion();
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 3: compare against null.
obj = null;
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
}
// A test for Multiply (Vector2f, float)
[Fact]
public void Vector2MultiplyTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
const float factor = 2.0f;
Vector2 expected = new Vector2(2.0f, 4.0f);
Vector2 actual = Vector2.Multiply(a, factor);
Assert.Equal(expected, actual);
}
// A test for Multiply (float, Vector2f)
[Fact]
public void Vector2MultiplyTest2()
{
Vector2 a = new Vector2(1.0f, 2.0f);
const float factor = 2.0f;
Vector2 expected = new Vector2(2.0f, 4.0f);
Vector2 actual = Vector2.Multiply(factor, a);
Assert.Equal(expected, actual);
}
// A test for Multiply (Vector2f, Vector2f)
[Fact]
public void Vector2MultiplyTest3()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(5.0f, 6.0f);
Vector2 expected = new Vector2(5.0f, 12.0f);
Vector2 actual;
actual = Vector2.Multiply(a, b);
Assert.Equal(expected, actual);
}
// A test for Negate (Vector2f)
[Fact]
public void Vector2NegateTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 expected = new Vector2(-1.0f, -2.0f);
Vector2 actual;
actual = Vector2.Negate(a);
Assert.Equal(expected, actual);
}
// A test for operator != (Vector2f, Vector2f)
[Fact]
public void Vector2InequalityTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(1.0f, 2.0f);
// case 1: compare between same values
bool expected = false;
bool actual = a != b;
Assert.Equal(expected, actual);
// case 2: compare between different values
b.X = 10.0f;
expected = true;
actual = a != b;
Assert.Equal(expected, actual);
}
// A test for operator == (Vector2f, Vector2f)
[Fact]
public void Vector2EqualityTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(1.0f, 2.0f);
// case 1: compare between same values
bool expected = true;
bool actual = a == b;
Assert.Equal(expected, actual);
// case 2: compare between different values
b.X = 10.0f;
expected = false;
actual = a == b;
Assert.Equal(expected, actual);
}
// A test for Subtract (Vector2f, Vector2f)
[Fact]
public void Vector2SubtractTest()
{
Vector2 a = new Vector2(1.0f, 6.0f);
Vector2 b = new Vector2(5.0f, 2.0f);
Vector2 expected = new Vector2(-4.0f, 4.0f);
Vector2 actual;
actual = Vector2.Subtract(a, b);
Assert.Equal(expected, actual);
}
// A test for UnitX
[Fact]
public void Vector2UnitXTest()
{
Vector2 val = new Vector2(1.0f, 0.0f);
Assert.Equal(val, Vector2.UnitX);
}
// A test for UnitY
[Fact]
public void Vector2UnitYTest()
{
Vector2 val = new Vector2(0.0f, 1.0f);
Assert.Equal(val, Vector2.UnitY);
}
// A test for One
[Fact]
public void Vector2OneTest()
{
Vector2 val = new Vector2(1.0f, 1.0f);
Assert.Equal(val, Vector2.One);
}
// A test for Zero
[Fact]
public void Vector2ZeroTest()
{
Vector2 val = new Vector2(0.0f, 0.0f);
Assert.Equal(val, Vector2.Zero);
}
// A test for Equals (Vector2f)
[Fact]
public void Vector2EqualsTest1()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(1.0f, 2.0f);
// case 1: compare between same values
bool expected = true;
bool actual = a.Equals(b);
Assert.Equal(expected, actual);
// case 2: compare between different values
b.X = 10.0f;
expected = false;
actual = a.Equals(b);
Assert.Equal(expected, actual);
}
// A test for Vector2f comparison involving NaN values
[Fact]
public void Vector2EqualsNanTest()
{
Vector2 a = new Vector2(float.NaN, 0);
Vector2 b = new Vector2(0, float.NaN);
Assert.False(a == Vector2.Zero);
Assert.False(b == Vector2.Zero);
Assert.True(a != Vector2.Zero);
Assert.True(b != Vector2.Zero);
Assert.False(a.Equals(Vector2.Zero));
Assert.False(b.Equals(Vector2.Zero));
// Counterintuitive result - IEEE rules for NaN comparison are weird!
Assert.False(a.Equals(a));
Assert.False(b.Equals(b));
}
// A test for Reflect (Vector2f, Vector2f)
[Fact]
public void Vector2ReflectTest()
{
Vector2 a = Vector2.Normalize(new Vector2(1.0f, 1.0f));
// Reflect on XZ plane.
Vector2 n = new Vector2(0.0f, 1.0f);
Vector2 expected = new Vector2(a.X, -a.Y);
Vector2 actual = Vector2.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Reflect did not return the expected value.");
// Reflect on XY plane.
n = new Vector2(0.0f, 0.0f);
expected = new Vector2(a.X, a.Y);
actual = Vector2.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Reflect did not return the expected value.");
// Reflect on YZ plane.
n = new Vector2(1.0f, 0.0f);
expected = new Vector2(-a.X, a.Y);
actual = Vector2.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Reflect did not return the expected value.");
}
// A test for Reflect (Vector2f, Vector2f)
// Reflection when normal and source are the same
[Fact]
public void Vector2ReflectTest1()
{
Vector2 n = new Vector2(0.45f, 1.28f);
n = Vector2.Normalize(n);
Vector2 a = n;
Vector2 expected = -n;
Vector2 actual = Vector2.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Reflect did not return the expected value.");
}
// A test for Reflect (Vector2f, Vector2f)
// Reflection when normal and source are negation
[Fact]
public void Vector2ReflectTest2()
{
Vector2 n = new Vector2(0.45f, 1.28f);
n = Vector2.Normalize(n);
Vector2 a = -n;
Vector2 expected = n;
Vector2 actual = Vector2.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Reflect did not return the expected value.");
}
[Fact]
public void Vector2AbsTest()
{
Vector2 v1 = new Vector2(-2.5f, 2.0f);
Vector2 v3 = Vector2.Abs(new Vector2(0.0f, float.NegativeInfinity));
Vector2 v = Vector2.Abs(v1);
Assert.Equal(2.5f, v.X);
Assert.Equal(2.0f, v.Y);
Assert.Equal(0.0f, v3.X);
Assert.Equal(float.PositiveInfinity, v3.Y);
}
[Fact]
public void Vector2SqrtTest()
{
Vector2 v1 = new Vector2(-2.5f, 2.0f);
Vector2 v2 = new Vector2(5.5f, 4.5f);
Assert.Equal(2, (int)Vector2.SquareRoot(v2).X);
Assert.Equal(2, (int)Vector2.SquareRoot(v2).Y);
Assert.Equal(float.NaN, Vector2.SquareRoot(v1).X);
}
// A test to make sure these types are blittable directly into GPU buffer memory layouts
[Fact]
public unsafe void Vector2SizeofTest()
{
Assert.Equal(8, sizeof(Vector2));
Assert.Equal(16, sizeof(Vector2_2x));
Assert.Equal(12, sizeof(Vector2PlusFloat));
Assert.Equal(24, sizeof(Vector2PlusFloat_2x));
}
[StructLayout(LayoutKind.Sequential)]
struct Vector2_2x
{
private Vector2 _a;
private Vector2 _b;
}
[StructLayout(LayoutKind.Sequential)]
struct Vector2PlusFloat
{
private Vector2 _v;
private float _f;
}
[StructLayout(LayoutKind.Sequential)]
struct Vector2PlusFloat_2x
{
private Vector2PlusFloat _a;
private Vector2PlusFloat _b;
}
[Fact]
public void SetFieldsTest()
{
Vector2 v3 = new Vector2(4f, 5f);
v3.X = 1.0f;
v3.Y = 2.0f;
Assert.Equal(1.0f, v3.X);
Assert.Equal(2.0f, v3.Y);
Vector2 v4 = v3;
v4.Y = 0.5f;
Assert.Equal(1.0f, v4.X);
Assert.Equal(0.5f, v4.Y);
Assert.Equal(2.0f, v3.Y);
}
[Fact]
public void EmbeddedVectorSetFields()
{
EmbeddedVectorObject evo = new EmbeddedVectorObject();
evo.FieldVector.X = 5.0f;
evo.FieldVector.Y = 5.0f;
Assert.Equal(5.0f, evo.FieldVector.X);
Assert.Equal(5.0f, evo.FieldVector.Y);
}
private class EmbeddedVectorObject
{
public Vector2 FieldVector;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace Apache.Geode.Client.Tests
{
using Apache.Geode.Client;
public class Position
: IDataSerializable
{
#region Private members
private long m_avg20DaysVol;
private string m_bondRating;
private double m_convRatio;
private string m_country;
private double m_delta;
private long m_industry;
private long m_issuer;
private double m_mktValue;
private double m_qty;
private string m_secId;
private string m_secLinks;
private string m_secType;
private int m_sharesOutstanding;
private string m_underlyer;
private long m_volatility;
private int m_pid;
private static int m_count = 0;
#endregion
#region Private methods
private void Init()
{
m_avg20DaysVol = 0;
m_bondRating = null;
m_convRatio = 0.0;
m_country = null;
m_delta = 0.0;
m_industry = 0;
m_issuer = 0;
m_mktValue = 0.0;
m_qty = 0.0;
m_secId = null;
m_secLinks = null;
m_secType = null;
m_sharesOutstanding = 0;
m_underlyer = null;
m_volatility = 0;
m_pid = 0;
}
private UInt64 GetObjectSize(ISerializable obj)
{
return (obj == null ? 0 : obj.ObjectSize);
}
#endregion
#region Public accessors
public string SecId
{
get
{
return m_secId;
}
}
public int Id
{
get
{
return m_pid;
}
}
public int SharesOutstanding
{
get
{
return m_sharesOutstanding;
}
}
public static int Count
{
get
{
return m_count;
}
set
{
m_count = value;
}
}
public override string ToString()
{
return "Position [secId=" + m_secId + " sharesOutstanding=" + m_sharesOutstanding + " type=" + m_secType + " id=" + m_pid + "]";
}
#endregion
#region Constructors
public Position()
{
Init();
}
//This ctor is for a data validation test
public Position(Int32 iForExactVal)
{
Init();
char[] id = new char[iForExactVal + 1];
for (int i = 0; i <= iForExactVal; i++)
{
id[i] = 'a';
}
m_secId = id.ToString();
m_qty = iForExactVal % 2 == 0 ? 1000 : 100;
m_mktValue = m_qty * 2;
m_sharesOutstanding = iForExactVal;
m_secType = "a";
m_pid = iForExactVal;
}
public Position(string id, int shares)
{
Init();
m_secId = id;
m_qty = shares * (m_count % 2 == 0 ? 10.0 : 100.0);
m_mktValue = m_qty * 1.2345998;
m_sharesOutstanding = shares;
m_secType = "a";
m_pid = m_count++;
}
#endregion
#region IDataSerializable Members
public void FromData(DataInput input)
{
m_avg20DaysVol = input.ReadInt64();
m_bondRating = input.ReadUTF();
m_convRatio = input.ReadDouble();
m_country = input.ReadUTF();
m_delta = input.ReadDouble();
m_industry = input.ReadInt64();
m_issuer = input.ReadInt64();
m_mktValue = input.ReadDouble();
m_qty = input.ReadDouble();
m_secId = input.ReadUTF();
m_secLinks = input.ReadUTF();
m_secType = input.ReadUTF();
m_sharesOutstanding = input.ReadInt32();
m_underlyer = input.ReadUTF();
m_volatility = input.ReadInt64();
m_pid = input.ReadInt32();
}
public void ToData(DataOutput output)
{
output.WriteInt64(m_avg20DaysVol);
output.WriteUTF(m_bondRating);
output.WriteDouble(m_convRatio);
output.WriteUTF(m_country);
output.WriteDouble(m_delta);
output.WriteInt64(m_industry);
output.WriteInt64(m_issuer);
output.WriteDouble(m_mktValue);
output.WriteDouble(m_qty);
output.WriteUTF(m_secId);
output.WriteUTF(m_secLinks);
output.WriteUTF(m_secType);
output.WriteInt32(m_sharesOutstanding);
output.WriteUTF(m_underlyer);
output.WriteInt64(m_volatility);
output.WriteInt32(m_pid);
}
public UInt64 ObjectSize
{
get
{
UInt64 objectSize = 0;
objectSize += (UInt64)sizeof(long);
objectSize += (UInt64) (m_bondRating.Length * sizeof(char));
objectSize += (UInt64)sizeof(double);
objectSize += (UInt64)(m_country.Length * sizeof(char));
objectSize += (UInt64)sizeof(double);
objectSize += (UInt64)sizeof(Int64);
objectSize += (UInt64)sizeof(Int64);
objectSize += (UInt64)sizeof(double);
objectSize += (UInt64)sizeof(double);
objectSize += (UInt64)(m_secId.Length * sizeof(char));
objectSize += (UInt64)(m_secLinks.Length * sizeof(char));
objectSize += (UInt64)(m_secType == null ? 0 : sizeof(char) * m_secType.Length);
objectSize += (UInt64)sizeof(Int32);
objectSize += (UInt64)(m_underlyer.Length * sizeof(char));
objectSize += (UInt64)sizeof(Int64);
objectSize += (UInt64)sizeof(Int32);
return objectSize;
}
}
#endregion
public static ISerializable CreateDeserializable()
{
return new Position();
}
}
}
| |
using System;
using System.Collections;
using System.Text;
using BigMath;
using Raksha.Asn1;
using Raksha.Asn1.Utilities;
using Raksha.Asn1.X509;
using Raksha.Crypto;
using Raksha.Math;
using Raksha.Security;
using Raksha.Security.Certificates;
using Raksha.Utilities;
using Raksha.Utilities.Collections;
using Raksha.Utilities.Date;
using Raksha.Utilities.Encoders;
using Raksha.X509.Extension;
namespace Raksha.X509
{
/**
* The following extensions are listed in RFC 2459 as relevant to CRLs
*
* Authority Key Identifier
* Issuer Alternative Name
* CRL Number
* Delta CRL Indicator (critical)
* Issuing Distribution Point (critical)
*/
public class X509Crl
: X509ExtensionBase
// TODO Add interface Crl?
{
private readonly CertificateList c;
private readonly string sigAlgName;
private readonly byte[] sigAlgParams;
private readonly bool isIndirect;
public X509Crl(
CertificateList c)
{
this.c = c;
try
{
this.sigAlgName = X509SignatureUtilities.GetSignatureName(c.SignatureAlgorithm);
if (c.SignatureAlgorithm.Parameters != null)
{
this.sigAlgParams = ((Asn1Encodable)c.SignatureAlgorithm.Parameters).GetDerEncoded();
}
else
{
this.sigAlgParams = null;
}
this.isIndirect = IsIndirectCrl;
}
catch (Exception e)
{
throw new CrlException("CRL contents invalid: " + e);
}
}
protected override X509Extensions GetX509Extensions()
{
return Version == 2
? c.TbsCertList.Extensions
: null;
}
public virtual byte[] GetEncoded()
{
try
{
return c.GetDerEncoded();
}
catch (Exception e)
{
throw new CrlException(e.ToString());
}
}
public virtual void Verify(
AsymmetricKeyParameter publicKey)
{
if (!c.SignatureAlgorithm.Equals(c.TbsCertList.Signature))
{
throw new CrlException("Signature algorithm on CertificateList does not match TbsCertList.");
}
ISigner sig = SignerUtilities.GetSigner(SigAlgName);
sig.Init(false, publicKey);
byte[] encoded = this.GetTbsCertList();
sig.BlockUpdate(encoded, 0, encoded.Length);
if (!sig.VerifySignature(this.GetSignature()))
{
throw new SignatureException("CRL does not verify with supplied public key.");
}
}
public virtual int Version
{
get { return c.Version; }
}
public virtual X509Name IssuerDN
{
get { return c.Issuer; }
}
public virtual DateTime ThisUpdate
{
get { return c.ThisUpdate.ToDateTime(); }
}
public virtual DateTimeObject NextUpdate
{
get
{
return c.NextUpdate == null
? null
: new DateTimeObject(c.NextUpdate.ToDateTime());
}
}
private ISet LoadCrlEntries()
{
ISet entrySet = new HashSet();
IEnumerable certs = c.GetRevokedCertificateEnumeration();
X509Name previousCertificateIssuer = IssuerDN;
foreach (CrlEntry entry in certs)
{
X509CrlEntry crlEntry = new X509CrlEntry(entry, isIndirect, previousCertificateIssuer);
entrySet.Add(crlEntry);
previousCertificateIssuer = crlEntry.GetCertificateIssuer();
}
return entrySet;
}
public virtual X509CrlEntry GetRevokedCertificate(
BigInteger serialNumber)
{
IEnumerable certs = c.GetRevokedCertificateEnumeration();
X509Name previousCertificateIssuer = IssuerDN;
foreach (CrlEntry entry in certs)
{
X509CrlEntry crlEntry = new X509CrlEntry(entry, isIndirect, previousCertificateIssuer);
if (serialNumber.Equals(entry.UserCertificate.Value))
{
return crlEntry;
}
previousCertificateIssuer = crlEntry.GetCertificateIssuer();
}
return null;
}
public virtual ISet GetRevokedCertificates()
{
ISet entrySet = LoadCrlEntries();
if (entrySet.Count > 0)
{
return entrySet; // TODO? Collections.unmodifiableSet(entrySet);
}
return null;
}
public virtual byte[] GetTbsCertList()
{
try
{
return c.TbsCertList.GetDerEncoded();
}
catch (Exception e)
{
throw new CrlException(e.ToString());
}
}
public virtual byte[] GetSignature()
{
return c.Signature.GetBytes();
}
public virtual string SigAlgName
{
get { return sigAlgName; }
}
public virtual string SigAlgOid
{
get { return c.SignatureAlgorithm.ObjectID.Id; }
}
public virtual byte[] GetSigAlgParams()
{
return Arrays.Clone(sigAlgParams);
}
public override bool Equals(
object obj)
{
if (obj == this)
return true;
X509Crl other = obj as X509Crl;
if (other == null)
return false;
return c.Equals(other.c);
// NB: May prefer this implementation of Equals if more than one certificate implementation in play
//return Arrays.AreEqual(this.GetEncoded(), other.GetEncoded());
}
public override int GetHashCode()
{
return c.GetHashCode();
}
/**
* Returns a string representation of this CRL.
*
* @return a string representation of this CRL.
*/
public override string ToString()
{
StringBuilder buf = new StringBuilder();
string nl = Platform.NewLine;
buf.Append(" Version: ").Append(this.Version).Append(nl);
buf.Append(" IssuerDN: ").Append(this.IssuerDN).Append(nl);
buf.Append(" This update: ").Append(this.ThisUpdate).Append(nl);
buf.Append(" Next update: ").Append(this.NextUpdate).Append(nl);
buf.Append(" Signature Algorithm: ").Append(this.SigAlgName).Append(nl);
byte[] sig = this.GetSignature();
buf.Append(" Signature: ");
buf.Append(Hex.ToHexString(sig, 0, 20)).Append(nl);
for (int i = 20; i < sig.Length; i += 20)
{
int count = System.Math.Min(20, sig.Length - i);
buf.Append(" ");
buf.Append(Hex.ToHexString(sig, i, count)).Append(nl);
}
X509Extensions extensions = c.TbsCertList.Extensions;
if (extensions != null)
{
IEnumerator e = extensions.ExtensionOids.GetEnumerator();
if (e.MoveNext())
{
buf.Append(" Extensions: ").Append(nl);
}
do
{
DerObjectIdentifier oid = (DerObjectIdentifier) e.Current;
X509Extension ext = extensions.GetExtension(oid);
if (ext.Value != null)
{
Asn1Object asn1Value = X509ExtensionUtilities.FromExtensionValue(ext.Value);
buf.Append(" critical(").Append(ext.IsCritical).Append(") ");
try
{
if (oid.Equals(X509Extensions.CrlNumber))
{
buf.Append(new CrlNumber(DerInteger.GetInstance(asn1Value).PositiveValue)).Append(nl);
}
else if (oid.Equals(X509Extensions.DeltaCrlIndicator))
{
buf.Append(
"Base CRL: "
+ new CrlNumber(DerInteger.GetInstance(
asn1Value).PositiveValue))
.Append(nl);
}
else if (oid.Equals(X509Extensions.IssuingDistributionPoint))
{
buf.Append(IssuingDistributionPoint.GetInstance((Asn1Sequence) asn1Value)).Append(nl);
}
else if (oid.Equals(X509Extensions.CrlDistributionPoints))
{
buf.Append(CrlDistPoint.GetInstance((Asn1Sequence) asn1Value)).Append(nl);
}
else if (oid.Equals(X509Extensions.FreshestCrl))
{
buf.Append(CrlDistPoint.GetInstance((Asn1Sequence) asn1Value)).Append(nl);
}
else
{
buf.Append(oid.Id);
buf.Append(" value = ").Append(
Asn1Dump.DumpAsString(asn1Value))
.Append(nl);
}
}
catch (Exception)
{
buf.Append(oid.Id);
buf.Append(" value = ").Append("*****").Append(nl);
}
}
else
{
buf.Append(nl);
}
}
while (e.MoveNext());
}
ISet certSet = GetRevokedCertificates();
if (certSet != null)
{
foreach (X509CrlEntry entry in certSet)
{
buf.Append(entry);
buf.Append(nl);
}
}
return buf.ToString();
}
/**
* Checks whether the given certificate is on this CRL.
*
* @param cert the certificate to check for.
* @return true if the given certificate is on this CRL,
* false otherwise.
*/
// public bool IsRevoked(
// Certificate cert)
// {
// if (!cert.getType().Equals("X.509"))
// {
// throw new RuntimeException("X.509 CRL used with non X.509 Cert");
// }
public virtual bool IsRevoked(
X509Certificate cert)
{
CrlEntry[] certs = c.GetRevokedCertificates();
if (certs != null)
{
// BigInteger serial = ((X509Certificate)cert).SerialNumber;
BigInteger serial = cert.SerialNumber;
for (int i = 0; i < certs.Length; i++)
{
if (certs[i].UserCertificate.Value.Equals(serial))
{
return true;
}
}
}
return false;
}
protected virtual bool IsIndirectCrl
{
get
{
Asn1OctetString idp = GetExtensionValue(X509Extensions.IssuingDistributionPoint);
bool isIndirect = false;
try
{
if (idp != null)
{
isIndirect = IssuingDistributionPoint.GetInstance(
X509ExtensionUtilities.FromExtensionValue(idp)).IsIndirectCrl;
}
}
catch (Exception e)
{
// TODO
// throw new ExtCrlException("Exception reading IssuingDistributionPoint", e);
throw new CrlException("Exception reading IssuingDistributionPoint" + e);
}
return isIndirect;
}
}
}
}
| |
// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using Android.App;
using Android.Net;
using Android.OS;
using Android.Widget;
using Android.Support.CustomTabs;
using Xamarin.Auth;
#if !AZURE_MOBILE_SERVICES
namespace Android.Support.CustomTabs.Chromium.SharedUtilities
#else
namespace Android.Support.CustomTabs.Chromium.SharedUtilities._MobileServices
#endif
{
/// <summary>
/// This is a helper class to manage the connection from Activity to the CustomTabs
/// Service.
/// </summary>
#if XAMARIN_CUSTOM_TABS_INTERNAL
internal partial class CustomTabActivityHelper : Java.Lang.Object, IServiceConnectionCallback
#else
public partial class CustomTabActivityHelper : Java.Lang.Object, IServiceConnectionCallback
#endif
{
private CustomTabsSession custom_tabs_session;
private CustomTabsClient custom_tabs_client;
private CustomTabsServiceConnection custom_tabs_service_connection;
private CustomTabsActivityManager custom_tabs_activity_manager;
private IConnectionCallback connection_callback;
private CustomTabsIntent.Builder custom_tabs_intent_builder = null;
private Activity activity;
private Android.Net.Uri uri = null;
private bool service_bound = false;
private string packageName = null;
public CustomTabActivityHelper()
{
this.NavigationEventHandler = NavigationEventHandlerDefaultImplementation;
return;
}
/// <summary>
/// Opens the URL on a Custom Tab if possible. Otherwise fallsback to opening it on a WebView.
/// </summary>
/// <param name="activity"> The host activity. </param>
/// <param name="custom_tabs_intent"> a CustomTabsIntent to be used if Custom Tabs is available. </param>
/// <param name="uri"> the Uri to be opened. </param>
/// <param name="fallback"> a CustomTabFallback to be used if Custom Tabs is not available. </param>
public /*static*/ void LaunchUrlWithCustomTabsOrFallback
(
Activity a,
CustomTabsIntent custom_tabs_intent,
string package_name_for_custom_tabs,
Android.Net.Uri u,
ICustomTabFallback fallback
)
{
uri = u;
activity = a;
bool fallback_neccessary = false;
//If we cant find a package name, it means theres no browser that supports
//Chrome Custom Tabs installed. So, we fallback to the webview
if (package_name_for_custom_tabs == null)
{
fallback_neccessary = true;
}
else
{
custom_tabs_activity_manager = new CustomTabsActivityManager(this.activity);
custom_tabs_activity_manager.BindService(package_name_for_custom_tabs);
//custom_tabs_intent.Intent.SetPackage(package_name_for_custom_tabs);
custom_tabs_session = custom_tabs_activity_manager.Session;
custom_tabs_intent_builder = new CustomTabsIntent.Builder(custom_tabs_session);
// direct call to CustomtTasIntent.LaunchUrl was ported from java samples and refactored
// seems like API changed
//------------------------------------------------------------------------------
//custom_tabs_intent.LaunchUrl(activity, uri);
//return;
//------------------------------------------------------------------------------
custom_tabs_activity_manager = new CustomTabsActivityManager(activity);
custom_tabs_intent = custom_tabs_intent_builder.Build();
CustomTabsHelper.AddKeepAliveExtra(activity, custom_tabs_intent.Intent);
//custom_tabs_intent.LaunchUrl(activity, uri);
custom_tabs_activity_manager.CustomTabsServiceConnected +=
// custom_tabs_activit_manager_CustomTabsServiceConnected
delegate
{
System.Diagnostics.Debug.WriteLine("CustomTabsActivityManager.CustomTabsServiceConnected");
custom_tabs_activity_manager.LaunchUrl(uri.ToString());
System.Diagnostics.Debug.WriteLine("CustomTabsActivityManager.LaunchUrl");
return;
}
;
System.Diagnostics.Debug.WriteLine($"CustomTabsActivityManager.BindService({package_name_for_custom_tabs})");
service_bound = custom_tabs_activity_manager.BindService(package_name_for_custom_tabs);
//custom_tabs_activity_manager.LaunchUrl(uri.ToString());
//------------------------------------------------------------------------------
if (service_bound == false)
{
System.Diagnostics.Debug.WriteLine($"FALLBACK: No Packages that support CustomTabs");
// No Packages that support CustomTabs
fallback_neccessary = true;
}
}
if (fallback_neccessary == true && fallback != null)
{
fallback.OpenUri(activity, uri);
}
return;
}
protected void custom_tabs_activit_manager_CustomTabsServiceConnected
(
Content.ComponentName name,
CustomTabsClient client
)
{
custom_tabs_intent_builder = new CustomTabsIntent.Builder(custom_tabs_activity_manager.Session);
custom_tabs_intent_builder.EnableUrlBarHiding();
if (CustomTabsConfiguration.IsWarmUpUsed)
{
System.Diagnostics.Debug.WriteLine("CustomTabsActivityManager.WarmUp()");
client.Warmup(0);
//custom_tabs_activity_manager.Warmup();
}
if (CustomTabsConfiguration.IsPrefetchUsed)
{
System.Diagnostics.Debug.WriteLine("CustomTabsActivityManager PREFETCH");
custom_tabs_activity_manager.MayLaunchUrl(uri.ToString(), null, null);
}
if (CustomTabsConfiguration.AreAnimationsUsed)
{
custom_tabs_intent_builder.SetStartAnimations
(
activity,
Xamarin.Auth.Resource.Animation.slide_in_right,
Xamarin.Auth.Resource.Animation.slide_out_left
);
custom_tabs_intent_builder.SetExitAnimations
(
activity,
global::Android.Resource.Animation.SlideInLeft,
global::Android.Resource.Animation.SlideOutRight
);
}
custom_tabs_activity_manager.LaunchUrl(uri.ToString(), custom_tabs_intent_builder.Build());
return;
}
/// <summary>
/// Creates or retrieves an exiting CustomTabsSession.
/// </summary>
/// <returns> a CustomTabsSession. </returns>
public virtual CustomTabsSession Session
{
get
{
if (custom_tabs_client == null)
{
custom_tabs_session = null;
}
else if (custom_tabs_session == null)
{
/*
public CustomTabsSession NewSession(OnNavigationEventDelegate onNavigationEventHandler);
public virtual CustomTabsSession NewSession(CustomTabsCallback callback);
public CustomTabsSession NewSession
(
OnNavigationEventDelegate onNavigationEventHandler,
CustomTabsClient.ExtraCallbackDelegate extraCallbackHandler
);
*/
custom_tabs_session = custom_tabs_client.NewSession
(
HandleOnNavigationEventDelegate
);
}
return custom_tabs_session;
}
}
public CustomTabsClient.OnNavigationEventDelegate NavigationEventHandler
{
get;
set;
}
protected void NavigationEventHandlerDefaultImplementation(int navigationEvent, Bundle extras)
{
return;
}
void HandleOnNavigationEventDelegate(int navigationEvent, Bundle extras)
{
return;
}
/*
not available in 23.3.0
downgraded from 25.1.1. because of Xamarin.Forms support 23.3.0
<!--
<package id = "Xamarin.Android.Support.CustomTabs" version="23.3.0" targetFramework="monoandroid71" />
-->
public CustomTabsClient.ExtraCallbackDelegate ExtraCallback
{
get;
set;
} = null;
*/
/// <summary>
/// Register a Callback to be called when connected or disconnected from the Custom Tabs Service.
/// </summary>
public virtual IConnectionCallback ConnectionCallback
{
get;
set;
}
public string UriTest
{
get;
set;
} = "http://xamarin.com";
/// <summary>
/// Binds the Activity to the Custom Tabs Service. </summary>
/// <param name="activity"> the activity to be binded to the service. </param>
public virtual void BindCustomTabsService(Activity activity)
{
if (custom_tabs_client != null)
{
return;
};
List<string> packages = PackageManagerHelper.GetPackageNameToUse(activity, this.UriTest);
string packageName = "";
if (packageName == null)
{
Toast.MakeText
(
activity,
"No packages supporting CustomTabs found!",
ToastLength.Short
).Show();
return;
}
custom_tabs_service_connection = new ServiceConnection(this);
CustomTabsClient.BindCustomTabsService(activity, packageName, custom_tabs_service_connection);
return;
}
/// <summary>
/// Unbinds the Activity from the Custom Tabs Service. </summary>
/// <param name="activity"> the activity that is connected to the service. </param>
public virtual void UnbindCustomTabsService(Activity activity)
{
if (custom_tabs_service_connection == null)
{
return;
}
activity.UnbindService(custom_tabs_service_connection);
custom_tabs_client = null;
custom_tabs_session = null;
custom_tabs_service_connection = null;
return;
}
/// <summary>
/// Warmup
/// Tells the browser of a likely future navigation to a URL.
/// </summary>
/// <seealso cref= <seealso cref="CustomTabsSession#mayLaunchUrl(Uri, Bundle, List)"/>. </seealso>
/// <returns> true if call to mayLaunchUrl was accepted. </returns>
public virtual bool MayLaunchUrl
(
Android.Net.Uri uri,
Bundle extras,
IList<Bundle> other_likely_bundles
)
{
if (custom_tabs_client == null)
{
return false;
}
custom_tabs_session = custom_tabs_activity_manager.Session;
if (custom_tabs_session == null)
{
return false;
}
return custom_tabs_session.MayLaunchUrl(uri, extras, other_likely_bundles);
}
public virtual void OnServiceConnected(CustomTabsClient client)
{
System.Diagnostics.Debug.WriteLine("CustomTabsActivityHelper.OnServiceConnected");
custom_tabs_client = client;
if (CustomTabsConfiguration.IsWarmUpUsed)
{
System.Diagnostics.Debug.WriteLine(" warmup");
custom_tabs_client.Warmup(0L);
}
if (connection_callback != null)
{
System.Diagnostics.Debug.WriteLine(" connection_callback.OnCustomTabsConnected()");
connection_callback.OnCustomTabsConnected();
}
return;
}
public virtual void OnServiceDisconnected()
{
System.Diagnostics.Debug.WriteLine("CustomTabsActivityHelper.OnServiceConnected");
custom_tabs_client = null;
custom_tabs_session = null;
if (connection_callback != null)
{
System.Diagnostics.Debug.WriteLine(" connection_callback.OnCustomTabsDisconnected()");
connection_callback.OnCustomTabsDisconnected();
}
return;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: The CLR implementation of Variant.
**
**
===========================================================*/
namespace System {
using System;
using System.Reflection;
using System.Threading;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
[Serializable]
[StructLayout(LayoutKind.Sequential)]
internal struct Variant {
//Do Not change the order of these fields.
//They are mapped to the native VariantData * data structure.
private Object m_objref;
private int m_data1;
private int m_data2;
private int m_flags;
// The following bits have been taken up as follows
// bits 0-15 - Type code
// bit 16 - Array
// bits 19-23 - Enums
// bits 24-31 - Optional VT code (for roundtrip VT preservation)
//What are the consequences of making this an enum?
///////////////////////////////////////////////////////////////////////
// If you update this, update the corresponding stuff in OAVariantLib.cs,
// COMOAVariant.cpp (2 tables, forwards and reverse), and perhaps OleVariant.h
///////////////////////////////////////////////////////////////////////
internal const int CV_EMPTY=0x0;
internal const int CV_VOID=0x1;
internal const int CV_BOOLEAN=0x2;
internal const int CV_CHAR=0x3;
internal const int CV_I1=0x4;
internal const int CV_U1=0x5;
internal const int CV_I2=0x6;
internal const int CV_U2=0x7;
internal const int CV_I4=0x8;
internal const int CV_U4=0x9;
internal const int CV_I8=0xa;
internal const int CV_U8=0xb;
internal const int CV_R4=0xc;
internal const int CV_R8=0xd;
internal const int CV_STRING=0xe;
internal const int CV_PTR=0xf;
internal const int CV_DATETIME = 0x10;
internal const int CV_TIMESPAN = 0x11;
internal const int CV_OBJECT=0x12;
internal const int CV_DECIMAL = 0x13;
internal const int CV_ENUM=0x15;
internal const int CV_MISSING=0x16;
internal const int CV_NULL=0x17;
internal const int CV_LAST=0x18;
internal const int TypeCodeBitMask=0xffff;
internal const int VTBitMask=unchecked((int)0xff000000);
internal const int VTBitShift=24;
internal const int ArrayBitMask =0x10000;
// Enum enum and Mask
internal const int EnumI1 =0x100000;
internal const int EnumU1 =0x200000;
internal const int EnumI2 =0x300000;
internal const int EnumU2 =0x400000;
internal const int EnumI4 =0x500000;
internal const int EnumU4 =0x600000;
internal const int EnumI8 =0x700000;
internal const int EnumU8 =0x800000;
internal const int EnumMask =0xF00000;
internal static readonly Type [] ClassTypes = {
typeof(System.Empty),
typeof(void),
typeof(Boolean),
typeof(Char),
typeof(SByte),
typeof(Byte),
typeof(Int16),
typeof(UInt16),
typeof(Int32),
typeof(UInt32),
typeof(Int64),
typeof(UInt64),
typeof(Single),
typeof(Double),
typeof(String),
typeof(void), // ptr for the moment
typeof(DateTime),
typeof(TimeSpan),
typeof(Object),
typeof(Decimal),
typeof(Object), // Treat enum as Object
typeof(System.Reflection.Missing),
typeof(System.DBNull),
};
internal static readonly Variant Empty = new Variant();
internal static readonly Variant Missing = new Variant(Variant.CV_MISSING, Type.Missing, 0, 0);
internal static readonly Variant DBNull = new Variant(Variant.CV_NULL, System.DBNull.Value, 0, 0);
//
// Native Methods
//
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern double GetR8FromVar();
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern float GetR4FromVar();
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void SetFieldsR4(float val);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void SetFieldsR8(double val);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void SetFieldsObject(Object val);
// Use this function instead of an ECALL - saves about 150 clock cycles
// by avoiding the ecall transition and because the JIT inlines this.
// Ends up only taking about 1/8 the time of the ECALL version.
internal long GetI8FromVar()
{
return ((long)m_data2<<32 | ((long)m_data1 & 0xFFFFFFFFL));
}
//
// Constructors
//
internal Variant(int flags, Object or, int data1, int data2) {
m_flags = flags;
m_objref=or;
m_data1=data1;
m_data2=data2;
}
public Variant(bool val) {
m_objref= null;
m_flags = CV_BOOLEAN;
m_data1 = (val)?Boolean.True:Boolean.False;
m_data2 = 0;
}
public Variant(sbyte val) {
m_objref=null;
m_flags=CV_I1;
m_data1=(int)val;
m_data2=(int)(((long)val)>>32);
}
public Variant(byte val) {
m_objref=null;
m_flags=CV_U1;
m_data1=(int)val;
m_data2=0;
}
public Variant(short val) {
m_objref=null;
m_flags=CV_I2;
m_data1=(int)val;
m_data2=(int)(((long)val)>>32);
}
public Variant(ushort val) {
m_objref=null;
m_flags=CV_U2;
m_data1=(int)val;
m_data2=0;
}
public Variant(char val) {
m_objref=null;
m_flags=CV_CHAR;
m_data1=(int)val;
m_data2=0;
}
public Variant(int val) {
m_objref=null;
m_flags=CV_I4;
m_data1=val;
m_data2=val >> 31;
}
public Variant(uint val) {
m_objref=null;
m_flags=CV_U4;
m_data1=(int)val;
m_data2=0;
}
public Variant(long val) {
m_objref=null;
m_flags=CV_I8;
m_data1 = (int)val;
m_data2 = (int)(val >> 32);
}
public Variant(ulong val) {
m_objref=null;
m_flags=CV_U8;
m_data1 = (int)val;
m_data2 = (int)(val >> 32);
}
[System.Security.SecuritySafeCritical] // auto-generated
public Variant(float val) {
m_objref=null;
m_flags=CV_R4;
m_data1=0;
m_data2=0;
SetFieldsR4(val);
}
[System.Security.SecurityCritical] // auto-generated
public Variant(double val) {
m_objref=null;
m_flags=CV_R8;
m_data1=0;
m_data2=0;
SetFieldsR8(val);
}
public Variant(DateTime val) {
m_objref=null;
m_flags=CV_DATETIME;
ulong ticks = (ulong)val.Ticks;
m_data1 = (int)ticks;
m_data2 = (int)(ticks>>32);
}
public Variant(Decimal val) {
m_objref = (Object)val;
m_flags = CV_DECIMAL;
m_data1=0;
m_data2=0;
}
[System.Security.SecuritySafeCritical] // auto-generated
public Variant(Object obj) {
m_data1=0;
m_data2=0;
VarEnum vt = VarEnum.VT_EMPTY;
if (obj is DateTime) {
m_objref=null;
m_flags=CV_DATETIME;
ulong ticks = (ulong)((DateTime)obj).Ticks;
m_data1 = (int)ticks;
m_data2 = (int)(ticks>>32);
return;
}
if (obj is String) {
m_flags=CV_STRING;
m_objref=obj;
return;
}
if (obj == null) {
this = Empty;
return;
}
if (obj == System.DBNull.Value) {
this = DBNull;
return;
}
if (obj == Type.Missing) {
this = Missing;
return;
}
if (obj is Array) {
m_flags=CV_OBJECT | ArrayBitMask;
m_objref=obj;
return;
}
// Compiler appeasement
m_flags = CV_EMPTY;
m_objref = null;
// Check to see if the object passed in is a wrapper object.
if (obj is UnknownWrapper)
{
vt = VarEnum.VT_UNKNOWN;
obj = ((UnknownWrapper)obj).WrappedObject;
}
else if (obj is DispatchWrapper)
{
vt = VarEnum.VT_DISPATCH;
obj = ((DispatchWrapper)obj).WrappedObject;
}
else if (obj is ErrorWrapper)
{
vt = VarEnum.VT_ERROR;
obj = (Object)(((ErrorWrapper)obj).ErrorCode);
Contract.Assert(obj != null, "obj != null");
}
else if (obj is CurrencyWrapper)
{
vt = VarEnum.VT_CY;
obj = (Object)(((CurrencyWrapper)obj).WrappedObject);
Contract.Assert(obj != null, "obj != null");
}
else if (obj is BStrWrapper)
{
vt = VarEnum.VT_BSTR;
obj = (Object)(((BStrWrapper)obj).WrappedObject);
}
if (obj != null)
{
SetFieldsObject(obj);
}
// If the object passed in is one of the wrappers then set the VARIANT type.
if (vt != VarEnum.VT_EMPTY)
m_flags |= ((int)vt << VTBitShift);
}
[System.Security.SecurityCritical] // auto-generated
unsafe public Variant(void* voidPointer,Type pointerType) {
if (pointerType == null)
throw new ArgumentNullException("pointerType");
if (!pointerType.IsPointer)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"),"pointerType");
Contract.EndContractBlock();
m_objref = pointerType;
m_flags=CV_PTR;
m_data1=(int)voidPointer;
m_data2=0;
}
//This is a family-only accessor for the CVType.
//This is never to be exposed externally.
internal int CVType {
get {
return (m_flags&TypeCodeBitMask);
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public Object ToObject() {
switch (CVType) {
case CV_EMPTY:
return null;
case CV_BOOLEAN:
return (Object)(m_data1!=0);
case CV_I1:
return (Object)((sbyte)m_data1);
case CV_U1:
return (Object)((byte)m_data1);
case CV_CHAR:
return (Object)((char)m_data1);
case CV_I2:
return (Object)((short)m_data1);
case CV_U2:
return (Object)((ushort)m_data1);
case CV_I4:
return (Object)(m_data1);
case CV_U4:
return (Object)((uint)m_data1);
case CV_I8:
return (Object)(GetI8FromVar());
case CV_U8:
return (Object)((ulong)GetI8FromVar());
case CV_R4:
return (Object)(GetR4FromVar());
case CV_R8:
return (Object)(GetR8FromVar());
case CV_DATETIME:
return new DateTime(GetI8FromVar());
case CV_TIMESPAN:
return new TimeSpan(GetI8FromVar());
case CV_ENUM:
return BoxEnum();
case CV_MISSING:
return Type.Missing;
case CV_NULL:
return System.DBNull.Value;
case CV_DECIMAL:
case CV_STRING:
case CV_OBJECT:
default:
return m_objref;
}
}
// This routine will return an boxed enum.
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern Object BoxEnum();
// Helper code for marshaling managed objects to VARIANT's (we use
// managed variants as an intermediate type.
[System.Security.SecuritySafeCritical] // auto-generated
internal static void MarshalHelperConvertObjectToVariant(Object o, ref Variant v)
{
#if FEATURE_REMOTING
IConvertible ic = System.Runtime.Remoting.RemotingServices.IsTransparentProxy(o) ? null : o as IConvertible;
#else
IConvertible ic = o as IConvertible;
#endif
if (o == null)
{
v = Empty;
}
else if (ic == null)
{
// This path should eventually go away. But until
// the work is done to have all of our wrapper types implement
// IConvertible, this is a cheapo way to get the work done.
v = new Variant(o);
}
else
{
IFormatProvider provider = CultureInfo.InvariantCulture;
switch (ic.GetTypeCode())
{
case TypeCode.Empty:
v = Empty;
break;
case TypeCode.Object:
v = new Variant((Object)o);
break;
case TypeCode.DBNull:
v = DBNull;
break;
case TypeCode.Boolean:
v = new Variant(ic.ToBoolean(provider));
break;
case TypeCode.Char:
v = new Variant(ic.ToChar(provider));
break;
case TypeCode.SByte:
v = new Variant(ic.ToSByte(provider));
break;
case TypeCode.Byte:
v = new Variant(ic.ToByte(provider));
break;
case TypeCode.Int16:
v = new Variant(ic.ToInt16(provider));
break;
case TypeCode.UInt16:
v = new Variant(ic.ToUInt16(provider));
break;
case TypeCode.Int32:
v = new Variant(ic.ToInt32(provider));
break;
case TypeCode.UInt32:
v = new Variant(ic.ToUInt32(provider));
break;
case TypeCode.Int64:
v = new Variant(ic.ToInt64(provider));
break;
case TypeCode.UInt64:
v = new Variant(ic.ToUInt64(provider));
break;
case TypeCode.Single:
v = new Variant(ic.ToSingle(provider));
break;
case TypeCode.Double:
v = new Variant(ic.ToDouble(provider));
break;
case TypeCode.Decimal:
v = new Variant(ic.ToDecimal(provider));
break;
case TypeCode.DateTime:
v = new Variant(ic.ToDateTime(provider));
break;
case TypeCode.String:
v = new Variant(ic.ToString(provider));
break;
default:
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnknownTypeCode", ic.GetTypeCode()));
}
}
}
// Helper code for marshaling VARIANTS to managed objects (we use
// managed variants as an intermediate type.
internal static Object MarshalHelperConvertVariantToObject(ref Variant v)
{
return v.ToObject();
}
// Helper code: on the back propagation path where a VT_BYREF VARIANT*
// is marshaled to a "ref Object", we use this helper to force the
// updated object back to the original type.
[System.Security.SecurityCritical] // auto-generated
internal static void MarshalHelperCastVariant(Object pValue, int vt, ref Variant v)
{
IConvertible iv = pValue as IConvertible;
if (iv == null)
{
switch (vt)
{
case 9: /*VT_DISPATCH*/
v = new Variant(new DispatchWrapper(pValue));
break;
case 12: /*VT_VARIANT*/
v = new Variant(pValue);
break;
case 13: /*VT_UNKNOWN*/
v = new Variant(new UnknownWrapper(pValue));
break;
case 36: /*VT_RECORD*/
v = new Variant(pValue);
break;
case 8: /*VT_BSTR*/
if (pValue == null)
{
v = new Variant(null);
v.m_flags = CV_STRING;
}
else
{
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_CannotCoerceByRefVariant"));
}
break;
default:
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_CannotCoerceByRefVariant"));
}
}
else
{
IFormatProvider provider = CultureInfo.InvariantCulture;
switch (vt)
{
case 0: /*VT_EMPTY*/
v = Empty;
break;
case 1: /*VT_NULL*/
v = DBNull;
break;
case 2: /*VT_I2*/
v = new Variant(iv.ToInt16(provider));
break;
case 3: /*VT_I4*/
v = new Variant(iv.ToInt32(provider));
break;
case 4: /*VT_R4*/
v = new Variant(iv.ToSingle(provider));
break;
case 5: /*VT_R8*/
v = new Variant(iv.ToDouble(provider));
break;
case 6: /*VT_CY*/
v = new Variant(new CurrencyWrapper(iv.ToDecimal(provider)));
break;
case 7: /*VT_DATE*/
v = new Variant(iv.ToDateTime(provider));
break;
case 8: /*VT_BSTR*/
v = new Variant(iv.ToString(provider));
break;
case 9: /*VT_DISPATCH*/
v = new Variant(new DispatchWrapper((Object)iv));
break;
case 10: /*VT_ERROR*/
v = new Variant(new ErrorWrapper(iv.ToInt32(provider)));
break;
case 11: /*VT_BOOL*/
v = new Variant(iv.ToBoolean(provider));
break;
case 12: /*VT_VARIANT*/
v = new Variant((Object)iv);
break;
case 13: /*VT_UNKNOWN*/
v = new Variant(new UnknownWrapper((Object)iv));
break;
case 14: /*VT_DECIMAL*/
v = new Variant(iv.ToDecimal(provider));
break;
// case 15: /*unused*/
// NOT SUPPORTED
case 16: /*VT_I1*/
v = new Variant(iv.ToSByte(provider));
break;
case 17: /*VT_UI1*/
v = new Variant(iv.ToByte(provider));
break;
case 18: /*VT_UI2*/
v = new Variant(iv.ToUInt16(provider));
break;
case 19: /*VT_UI4*/
v = new Variant(iv.ToUInt32(provider));
break;
case 20: /*VT_I8*/
v = new Variant(iv.ToInt64(provider));
break;
case 21: /*VT_UI8*/
v = new Variant(iv.ToUInt64(provider));
break;
case 22: /*VT_INT*/
v = new Variant(iv.ToInt32(provider));
break;
case 23: /*VT_UINT*/
v = new Variant(iv.ToUInt32(provider));
break;
default:
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_CannotCoerceByRefVariant"));
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using SimpleJSON;
using Torii.Exceptions;
using Torii.UI;
using Torii.Util;
using UnityEngine;
namespace Torii.Resource
{
/// <summary>
/// ResourceManager is used to load/cache resources at runtime.
/// </summary>
public static class ResourceManager
{
// the cache of loaded resources, indexed by path they were loaded from
private static readonly Dictionary<string, GenericResource> _resources;
// the resource handlers to use by Type
private static readonly Dictionary<Type, IResourceHandler> _handlers;
// special handling for Unity text assets
private static readonly Dictionary<Type, ITextAssetHandler> _textAssetProcessors;
// the loaded ResourceLifespans
private static readonly ResourceLifespans _lifespans;
// the file to load resource lifespans from
//private static readonly string lifespansDataFileName = "resourcelifespans.json";
/// <summary>
/// Statically initialize the ResourceManager.
/// </summary>
static ResourceManager()
{
_resources = new Dictionary<string, GenericResource>();
_handlers = new Dictionary<Type, IResourceHandler>();
_textAssetProcessors = new Dictionary<Type, ITextAssetHandler>();
_lifespans = new ResourceLifespans();
}
/// <summary>
/// Remove all resources with the given lifespan from the cache.
/// </summary>
/// <param name="span">The lifespan, for example "level".</param>
/// <exception cref="ArgumentException">If the lifespan didn't exist.</exception>
public static void ClearLifespan(string span)
{
// get the ID of this span
int spanID = _lifespans[span];
// get the list of resources to remove
List<string> toRemove = new List<string>();
foreach (var res in _resources)
{
if (res.Value.Lifespan == spanID)
{
toRemove.Add(res.Key);
res.Value.OnExpire?.Invoke();
}
}
// remove the resources
foreach (string key in toRemove)
{
switch (_resources[key].ResourceType)
{
case ResourceType.Streamed:
_resources.Remove(key);
break;
case ResourceType.Unity:
Resources.UnloadAsset((UnityEngine.Object)_resources[key].GetData());
_resources.Remove(key);
break;
}
}
}
/// <summary>
/// Unity assets are handled differently. This unloads all unused Unity resources.
/// </summary>
public static void ClearUnusedUnityAssets()
{
Resources.UnloadUnusedAssets();
}
/// <summary>
/// Load a resource with type T from a location on disk. Loads it for global lifespan.
/// </summary>
/// <param name="path">The path to the resource.</param>
/// <typeparam name="T">The type of the resource.</typeparam>
/// <returns>The loaded resource.</returns>
public static T Load<T>(string path)
{
return Load<T>(path, _lifespans["global"]);
}
/// <summary>
/// Load a resource with type T from a location on disk, and give it a lifespan.
/// </summary>
/// <param name="path">The path to the resource.</param>
/// <param name="span">The lifespan of the resource.</param>
/// <typeparam name="T">The type of the resource.</typeparam>
/// <returns>The loaded resource.</returns>
/// <exception cref="ArgumentException">If the lifespan didn't exist.</exception>
public static T Load<T>(string path, string span)
{
return Load<T>(path, _lifespans[span]);
}
/// <summary>
/// Load a resource with type T from a location on disk, and give it a lifespan with an ID.
/// </summary>
/// <param name="path">The path to the resource.</param>
/// <param name="span">The lifespan of the resource.</param>
/// <typeparam name="T">The type of the resource.</typeparam>
/// <returns>The loaded resource.</returns>
/// <exception cref="ArgumentException">If the path is empty, or the handler for type wasn't found.</exception>
/// <exception cref="FileNotFoundException">If the file was not found.</exception>
public static T Load<T>(string path, int span)
{
Resource<T> res;
// check the cache first, as this would be cheaper
if (checkCache(path, out res)) return res.Data;
path = path.Trim();
// do a bunch of checks to see if this resource can actually be loaded
if (path.Equals(string.Empty))
{
throw new ArgumentException("Could not load resource: path argument cannot be empty", nameof(path));
}
if (!File.Exists(path))
{
throw new FileNotFoundException("Could not load resource: File '" + path + "' not found", path);
}
if (!_handlers.ContainsKey(typeof(T)))
{
throw new ArgumentException("Could not load resource: No handler found for type " + typeof(T));
}
// load the resource
_handlers[typeof(T)].Load(path, span);
return ((Resource<T>)_resources[path]).Data;
}
/// <summary>
/// Load a resource from Unity's Resources.
/// </summary>
/// <param name="path">The path to the resource (in Unity's assets).</param>
/// <typeparam name="T">The type of the resource.</typeparam>
/// <returns>The loaded resource.</returns>
public static T UnityLoad<T>(string path) where T : class
{
return UnityLoad<T>(path, _lifespans["global"]);
}
/// <summary>
/// Load a resource from Unity's resource.
/// </summary>
/// <param name="path">The path to the resource (in Unity's assets).</param>
/// <param name="span">The lifespan to give this resource.</param>
/// <typeparam name="T">The type of the resource.</typeparam>
/// <returns>The loaded resource.</returns>
/// <exception cref="ArgumentException">If the given lifespan was invalid.</exception>
public static T UnityLoad<T>(string path, string span) where T : class
{
return UnityLoad<T>(path, _lifespans[span]);
}
/// <summary>
/// Load a resource from Unity's resource.
/// </summary>
/// <param name="path">The path to the resource (in Unity's assets).</param>
/// <param name="span">The lifespan to give this resource.</param>
/// <typeparam name="T">The type of the resource.</typeparam>
/// <returns>The loaded resource.</returns>
/// <exception cref="ToriiResourceLoadException">If there was some error loading the resource.</exception>
public static T UnityLoad<T>(string path, int span) where T : class
{
// prepend "Resources" to the start of the path to prevent edge cases
// where the same name file in StreamingAssets could conflict
string resourcePath = PathUtil.Combine("Resources", path);
Resource<T> res;
if (checkCache(resourcePath, out res)) return res.Data;
// check if the asset can be processed as text
if (_textAssetProcessors.ContainsKey(typeof(T)))
{
ITextAssetHandler handler = _textAssetProcessors[typeof(T)];
TextAsset textAsset = Resources.Load<TextAsset>(path);
// check to see if we loaded successfully
if (textAsset == null)
{
throw new ToriiResourceLoadException("Unable to load resource: '" + path + "'", typeof(T));
}
res = new Resource<T>(span)
{
Data = (T)handler.Process(textAsset)
};
// we don't need the text asset anymore
Resources.UnloadAsset(textAsset);
}
else
{
// otherwise just load it using Unity's resource handling
res = new Resource<T>(span, ResourceType.Unity)
{
Data = Resources.Load(path, typeof(T)) as T
};
}
if (res.Data == null)
{
throw new ToriiResourceLoadException("Unable to load resource: '" + path + "'", typeof(T));
}
_resources[resourcePath] = res;
return res.Data;
}
/// <summary>
/// Used to register a loaded resource into the cache. Only call this from within custom resource handlers.
/// </summary>
/// <param name="path">The path of the resource you're loading.</param>
/// <param name="r">The instance of the resource loaded.</param>
public static void RegisterResource(string path, GenericResource r)
{
_resources[path] = r;
}
/// <summary>
/// Register a new resource handler.
/// </summary>
/// <param name="handler">An instance of the handler.</param>
public static void RegisterHandler(IResourceHandler handler)
{
_handlers[handler.HandlerType] = handler;
}
/// <summary>
/// Register a new text asset processor.
/// </summary>
/// <param name="handler">An instance of the text asset handler.</param>
public static void RegisterTextAssetProcessor(ITextAssetHandler handler)
{
_textAssetProcessors[handler.HandlerType] = handler;
}
// check the cache to see if a resource exists
private static bool checkCache<T>(string path, out T data) where T : class
{
if (_resources.ContainsKey(path))
{
data = _resources[path] as T;
return true;
}
data = null;
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Content.Shared.CCVar;
using Content.Shared.CharacterAppearance;
using Content.Shared.Dataset;
using Content.Shared.GameTicking;
using Content.Shared.Random.Helpers;
using Content.Shared.Roles;
using Content.Shared.Species;
using Robust.Shared.Configuration;
using Robust.Shared.Enums;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Prototypes;
using Robust.Shared.Random;
using Robust.Shared.Serialization;
namespace Content.Shared.Preferences
{
/// <summary>
/// Character profile. Looks immutable, but uses non-immutable semantics internally for serialization/code sanity purposes.
/// </summary>
[Serializable, NetSerializable]
public sealed class HumanoidCharacterProfile : ICharacterProfile
{
public const int MinimumAge = 18;
public const int MaximumAge = 120;
public const int MaxNameLength = 32;
private readonly Dictionary<string, JobPriority> _jobPriorities;
private readonly List<string> _antagPreferences;
private HumanoidCharacterProfile(
string name,
string species,
int age,
Sex sex,
Gender gender,
HumanoidCharacterAppearance appearance,
ClothingPreference clothing,
BackpackPreference backpack,
Dictionary<string, JobPriority> jobPriorities,
PreferenceUnavailableMode preferenceUnavailable,
List<string> antagPreferences)
{
Name = name;
Species = species;
Age = age;
Sex = sex;
Gender = gender;
Appearance = appearance;
Clothing = clothing;
Backpack = backpack;
_jobPriorities = jobPriorities;
PreferenceUnavailable = preferenceUnavailable;
_antagPreferences = antagPreferences;
}
/// <summary>Copy constructor but with overridable references (to prevent useless copies)</summary>
private HumanoidCharacterProfile(
HumanoidCharacterProfile other,
Dictionary<string, JobPriority> jobPriorities,
List<string> antagPreferences)
: this(other.Name, other.Species, other.Age, other.Sex, other.Gender, other.Appearance, other.Clothing, other.Backpack,
jobPriorities, other.PreferenceUnavailable, antagPreferences)
{
}
/// <summary>Copy constructor</summary>
private HumanoidCharacterProfile(HumanoidCharacterProfile other)
: this(other, new Dictionary<string, JobPriority>(other.JobPriorities), new List<string>(other.AntagPreferences))
{
}
public HumanoidCharacterProfile(
string name,
string species,
int age,
Sex sex,
Gender gender,
HumanoidCharacterAppearance appearance,
ClothingPreference clothing,
BackpackPreference backpack,
IReadOnlyDictionary<string, JobPriority> jobPriorities,
PreferenceUnavailableMode preferenceUnavailable,
IReadOnlyList<string> antagPreferences)
: this(name, species, age, sex, gender, appearance, clothing, backpack, new Dictionary<string, JobPriority>(jobPriorities),
preferenceUnavailable, new List<string>(antagPreferences))
{
}
public static HumanoidCharacterProfile Default()
{
return new(
"John Doe",
SpeciesManager.DefaultSpecies,
MinimumAge,
Sex.Male,
Gender.Male,
HumanoidCharacterAppearance.Default(),
ClothingPreference.Jumpsuit,
BackpackPreference.Backpack,
new Dictionary<string, JobPriority>
{
{SharedGameTicker.FallbackOverflowJob, JobPriority.High}
},
PreferenceUnavailableMode.SpawnAsOverflow,
new List<string>());
}
public static HumanoidCharacterProfile Random()
{
var random = IoCManager.Resolve<IRobustRandom>();
var species = random.Pick(IoCManager.Resolve<IPrototypeManager>()
.EnumeratePrototypes<SpeciesPrototype>().Where(x => x.RoundStart).ToArray()).ID;
var sex = random.Prob(0.5f) ? Sex.Male : Sex.Female;
var gender = sex == Sex.Male ? Gender.Male : Gender.Female;
var prototypeManager = IoCManager.Resolve<IPrototypeManager>();
var firstName = random.Pick(sex.FirstNames(prototypeManager).Values);
var lastName = random.Pick(prototypeManager.Index<DatasetPrototype>("names_last"));
var name = $"{firstName} {lastName}";
var age = random.Next(MinimumAge, MaximumAge);
return new HumanoidCharacterProfile(name, species, age, sex, gender, HumanoidCharacterAppearance.Random(sex), ClothingPreference.Jumpsuit, BackpackPreference.Backpack,
new Dictionary<string, JobPriority>
{
{SharedGameTicker.FallbackOverflowJob, JobPriority.High}
}, PreferenceUnavailableMode.StayInLobby, new List<string>());
}
public string Name { get; private set; }
public string Species { get; private set; }
public int Age { get; private set; }
public Sex Sex { get; private set; }
public Gender Gender { get; private set; }
public ICharacterAppearance CharacterAppearance => Appearance;
public HumanoidCharacterAppearance Appearance { get; private set; }
public ClothingPreference Clothing { get; private set; }
public BackpackPreference Backpack { get; private set; }
public IReadOnlyDictionary<string, JobPriority> JobPriorities => _jobPriorities;
public IReadOnlyList<string> AntagPreferences => _antagPreferences;
public PreferenceUnavailableMode PreferenceUnavailable { get; private set; }
public HumanoidCharacterProfile WithName(string name)
{
return new(this) { Name = name };
}
public HumanoidCharacterProfile WithAge(int age)
{
return new(this) { Age = age };
}
public HumanoidCharacterProfile WithSex(Sex sex)
{
return new(this) { Sex = sex };
}
public HumanoidCharacterProfile WithGender(Gender gender)
{
return new(this) { Gender = gender };
}
public HumanoidCharacterProfile WithSpecies(string species)
{
return new(this) { Species = species };
}
public HumanoidCharacterProfile WithCharacterAppearance(HumanoidCharacterAppearance appearance)
{
return new(this) { Appearance = appearance };
}
public HumanoidCharacterProfile WithClothingPreference(ClothingPreference clothing)
{
return new(this) { Clothing = clothing };
}
public HumanoidCharacterProfile WithBackpackPreference(BackpackPreference backpack)
{
return new(this) { Backpack = backpack };
}
public HumanoidCharacterProfile WithJobPriorities(IEnumerable<KeyValuePair<string, JobPriority>> jobPriorities)
{
return new(this, new Dictionary<string, JobPriority>(jobPriorities), _antagPreferences);
}
public HumanoidCharacterProfile WithJobPriority(string jobId, JobPriority priority)
{
var dictionary = new Dictionary<string, JobPriority>(_jobPriorities);
if (priority == JobPriority.Never)
{
dictionary.Remove(jobId);
}
else
{
dictionary[jobId] = priority;
}
return new(this, dictionary, _antagPreferences);
}
public HumanoidCharacterProfile WithPreferenceUnavailable(PreferenceUnavailableMode mode)
{
return new(this) { PreferenceUnavailable = mode };
}
public HumanoidCharacterProfile WithAntagPreferences(IEnumerable<string> antagPreferences)
{
return new(this, _jobPriorities, new List<string>(antagPreferences));
}
public HumanoidCharacterProfile WithAntagPreference(string antagId, bool pref)
{
var list = new List<string>(_antagPreferences);
if(pref)
{
if(!list.Contains(antagId))
{
list.Add(antagId);
}
}
else
{
if(list.Contains(antagId))
{
list.Remove(antagId);
}
}
return new(this, _jobPriorities, list);
}
public string Summary =>
Loc.GetString(
"humanoid-character-profile-summary",
("name", Name),
("gender", Gender.ToString().ToLowerInvariant()),
("age", Age)
);
public bool MemberwiseEquals(ICharacterProfile maybeOther)
{
if (maybeOther is not HumanoidCharacterProfile other) return false;
if (Name != other.Name) return false;
if (Age != other.Age) return false;
if (Sex != other.Sex) return false;
if (Gender != other.Gender) return false;
if (PreferenceUnavailable != other.PreferenceUnavailable) return false;
if (Clothing != other.Clothing) return false;
if (Backpack != other.Backpack) return false;
if (!_jobPriorities.SequenceEqual(other._jobPriorities)) return false;
if (!_antagPreferences.SequenceEqual(other._antagPreferences)) return false;
return Appearance.MemberwiseEquals(other.Appearance);
}
public void EnsureValid()
{
var age = Math.Clamp(Age, MinimumAge, MaximumAge);
var sex = Sex switch
{
Sex.Male => Sex.Male,
Sex.Female => Sex.Female,
_ => Sex.Male // Invalid enum values.
};
var gender = Gender switch
{
Gender.Epicene => Gender.Epicene,
Gender.Female => Gender.Female,
Gender.Male => Gender.Male,
Gender.Neuter => Gender.Neuter,
_ => Gender.Epicene // Invalid enum values.
};
string name;
if (string.IsNullOrEmpty(Name))
{
name = RandomName();
}
else if (Name.Length > MaxNameLength)
{
name = Name[..MaxNameLength];
}
else
{
name = Name;
}
name = name.Trim();
if (IoCManager.Resolve<IConfigurationManager>().GetCVar(CCVars.RestrictedNames))
{
name = Regex.Replace(name, @"[^A-Z,a-z,0-9, -]", string.Empty);
}
if (string.IsNullOrEmpty(name))
{
name = RandomName();
}
var appearance = HumanoidCharacterAppearance.EnsureValid(Appearance);
var prefsUnavailableMode = PreferenceUnavailable switch
{
PreferenceUnavailableMode.StayInLobby => PreferenceUnavailableMode.StayInLobby,
PreferenceUnavailableMode.SpawnAsOverflow => PreferenceUnavailableMode.SpawnAsOverflow,
_ => PreferenceUnavailableMode.StayInLobby // Invalid enum values.
};
var clothing = Clothing switch
{
ClothingPreference.Jumpsuit => ClothingPreference.Jumpsuit,
ClothingPreference.Jumpskirt => ClothingPreference.Jumpskirt,
_ => ClothingPreference.Jumpsuit // Invalid enum values.
};
var backpack = Backpack switch
{
BackpackPreference.Backpack => BackpackPreference.Backpack,
BackpackPreference.Satchel => BackpackPreference.Satchel,
BackpackPreference.Duffelbag => BackpackPreference.Duffelbag,
_ => BackpackPreference.Backpack // Invalid enum values.
};
var prototypeManager = IoCManager.Resolve<IPrototypeManager>();
var priorities = new Dictionary<string, JobPriority>(JobPriorities
.Where(p => prototypeManager.HasIndex<JobPrototype>(p.Key) && p.Value switch
{
JobPriority.Never => false, // Drop never since that's assumed default.
JobPriority.Low => true,
JobPriority.Medium => true,
JobPriority.High => true,
_ => false
}));
var antags = AntagPreferences
.Where(prototypeManager.HasIndex<AntagPrototype>)
.ToList();
Name = name;
Age = age;
Sex = sex;
Gender = gender;
Appearance = appearance;
Clothing = clothing;
Backpack = backpack;
_jobPriorities.Clear();
foreach (var (job, priority) in priorities)
{
_jobPriorities.Add(job, priority);
}
PreferenceUnavailable = prefsUnavailableMode;
_antagPreferences.Clear();
_antagPreferences.AddRange(antags);
string RandomName()
{
var random = IoCManager.Resolve<IRobustRandom>();
var protoMan = IoCManager.Resolve<IPrototypeManager>();
var firstName = random.Pick(Sex.FirstNames(protoMan).Values);
var lastName = random.Pick(protoMan.Index<DatasetPrototype>("names_last"));
return $"{firstName} {lastName}";
}
}
public override bool Equals(object? obj)
{
return obj is HumanoidCharacterProfile other && MemberwiseEquals(other);
}
public override int GetHashCode()
{
return HashCode.Combine(
HashCode.Combine(
Name,
Species,
Age,
Sex,
Gender,
Appearance,
Clothing,
Backpack
),
PreferenceUnavailable,
_jobPriorities,
_antagPreferences
);
}
}
}
| |
using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Xsl;
using System.Xml.XPath;
using Microsoft.XmlDiffPatch;
namespace Lewis.SST
{
/// <summary>The SQL Schema Tool is a commandline executable application for generating XML schema documents from SQL server databases,
/// comparing those databases or the XML schema documents, and finally generating a DiffGram XML document from the compare results.
/// <para>
/// The tool limitations currently are that it does not support "WITH NOCHECK" or extended properties. Additionally, the tool only
/// supports adding calculated columns using CREATE TABLE or ALTER TABLE ADD 'column name' SQL statements. Also, calculated columns
/// are added last in order, so that the columns they may be dependant on will already be in place. Column Default Constraints are
/// dropped using sp_unbindefault and they are not re-added later in the diffgram SQL script script using sp_bindefault.
/// </para>
/// <para>
/// Instead the tool assigns the default value to the column using the ALTER TABLE ADD DEFAULT 'default value' FOR column_name
/// method. Doing the diffgram schema this way does cause a DB updated with the diffgram to not compare exactly using the Redgate
/// SQL Compare tool. However, the equivalent DB functionality is still there.
/// </para>
/// <para>
/// The order of columns will also be different between the source and destination DBs as the calculated columns are added to the
/// table last. This by design so as to avoid dependency issues with other columns that the calculation may be dependant on.
/// Speaking of dependant objects, especially stored procedures, these are output in the order indicated in the sysdepends table.
/// If the sysdepends table gets out of sync with the database, then the stored procedures will likely also be out of sync.
/// </para>
/// <para>
/// This tool uses embedded XSLT 'style sheets' to transform the generated XML docs into the SQL script files. Also the code was
/// changed to use XPathDocuments as suppliers of the XML to the XMLTransformation object. The performance increase is significant
/// over using the XmlDataDocument object.
/// </para>
/// <para>
/// Check out the following URL for great tips on error handling in SQL:
/// <see href="http://www.sommarskog.se/error-handling-II.html#whyerrorcheck">SQL Error Handling</see>
///
/// </para>
/// </summary>
class NamespaceDoc
{// this class is used for nothing except Ndoc output for the namespace
}
/// <summary>
/// Commandline tool to compare a source against a destination DB, create XML output,
/// Translate the XML output into a SQL script and perform an upgrade of the destination
/// using a SQL script.
/// <para/>
/// <remarks>The following are the parameters used for this tool:
/// <code>
///
/// /? or /Help for this help message
///
/// PARAMETERS: (SQL Connections or Files to use)
/// =============================================================================
/// /Src_Server=[Source sql server]
/// /Src_Database=[Source sql catalog or database] OR
/// /Src_Catalog=[Source sql catalog or database]
/// /Src_Trusted - use trusted connection, user and pwd not required
/// /Src_User=[Source sql server user login] OR
/// /Src_UID=[Source sql server user login]
/// /Src_Password=[Source sql server user password] OR
/// /Src_PWD=[Source sql server user password]
/// /Src_File=[output filename for source SQL server schema create script]
/// /Src_Schema=[filename for existing source SQL server schema xml file]
///
/// When connecting to a SQL server:
/// When wanting to just get the SQL create schema XML/SQL file(s)
/// for a single SQL DB, only use the Src_?????? parameters or the
/// /CreateXMLFile parameter.
///
/// Only use the Dest_?????? parameters when doing a compare.
///
/// /Dest_Server=[Destination sql server]
/// /Dest_Database=[Destination sql catalog or database] OR
/// /Dest_Catalog=[Destination sql catalog or database]
/// /Dest_Trusted - use trusted connection, user and pwd not required
/// /Dest_User=[Destination sql server user login] OR
/// /Dest_UID=[Destination sql server user login]
/// /Dest_Password=[Destination sql server user password] OR
/// /Dest_PWD=[Destination sql server user password]
/// /Dest_File=[output filename for destination SQL server schema create script]
/// /Dest_Schema=[filename for existing destination SQL server schema xml file]
///
/// When providing just a single schema or diff XML file,
/// Use the following parameters:
///
/// /DiffXMLFile=[XML file name] - used by itself, this will apply the SQL diff
/// transform against specified XML file. Turns on the transform flag.
/// Autogenerates SQL file name from XML input file name if none is
/// provided via the next parameter '/DiffSQLFile'.
///
/// /DiffSQLFile=[SQL file name] - used with the '/DiffXMLFile' paramter, this
/// will assign the SQL file name used for the transformation output.
///
/// /CreateXMLFile=[XML file name] - used by itself, this will apply the SQL
/// Create transform against specified XML file. Turns on the transform
/// flag. Autogenerates SQL file name from XML input file name if none
/// is provided via the next parameter '/CreateSQLFile'.
///
/// /CreateSQLFile=[SQL file name] - used with the '/CreateXMLFile' paramter, this
/// will assign the SQL file name used for the transformation output.
///
/// OPTIONS: (changes operations of compare or output)
/// =============================================================================
/// /CompareSprocText - add this option to command line to compare source and
/// dest stored procedure text line by line. Otherwise if both source and
/// dest sprocs exists, the source sproc is always forced to 'alter
/// procedure'.
///
/// /Transform - add this option to command line to perform translation of the
/// XML file into a SQL file for creating or updating the SQL Destination
/// DB. Requires some combination of Source and Dest SQL connections
/// and/or XML Schema files.
///
/// /Primary - add this option for force all tables to use the Primary
/// filegroup for CREATE TABLE or ALTER TABLE when serializing the schema.
/// This option will also cause the compare to ignore FileGroups, since
/// they all will be set to PRIMARY.
/// </code>
/// </remarks>
/// <para/>
/// <note type="caution">Passwords entered as a command parameter in conjunction with a batch file calling SST and the output redirector '>' to some textfile can cause credentials to be stored in plain text.</note>
/// </summary>
class CommandLine
{
private static string _src_server;
private static string _src_user;
private static string _src_db;
private static string _src_password;
private static string _src_trusted = "false";
private static string _src_file;
private static string _src_schema;
private static string _dest_server;
private static string _dest_user;
private static string _dest_db;
private static string _dest_password;
private static string _dest_trusted = "false";
private static string _dest_file;
private static string _dest_schema;
private static string _diffXMLFile;
private static string _createXMLFile;
private static string _diffName;
private static string _createName;
private static bool _CompareSprocs = false;
private static bool _Translate = false;
private static bool _Primary = false;
/// <summary>
/// const value for the help text that is displayed when the /? parameter is used.
/// </summary>
private const string _help =
@"SST Version: {0}
/? or /Help for this help message
PARAMETERS: (SQL Connections or Files to use)
=============================================================================
/Src_Server=[Source sql server]
/Src_Database=[Source sql catalog or database] OR
/Src_Catalog=[Source sql catalog or database]
/Src_Trusted - use trusted connection, user and pwd not required
/Src_User=[Source sql server user login] OR
/Src_UID=[Source sql server user login]
/Src_Password=[Source sql server user password] OR
/Src_PWD=[Source sql server user password]
/Src_File=[output filename for source SQL server schema create script]
/Src_Schema=[filename for existing source SQL server schema xml file]
When connecting to a SQL server:
When wanting to just get the SQL create schema XML/SQL file(s)
for a single SQL DB, only use the Src_?????? parameters or the
/CreateXMLFile parameter.
Only use the Dest_?????? parameters when doing a compare.
/Dest_Server=[Destination sql server]
/Dest_Database=[Destination sql catalog or database] OR
/Dest_Catalog=[Destination sql catalog or database]
/Dest_Trusted - use trusted connection, user and pwd not required
/Dest_User=[Destination sql server user login] OR
/Dest_UID=[Destination sql server user login]
/Dest_Password=[Destination sql server user password] OR
/Dest_PWD=[Destination sql server user password]
/Dest_File=[output filename for destination SQL server schema create script]
/Dest_Schema=[filename for existing destination SQL server schema xml file]
When providing just a single schema or diff XML file,
Use the following parameters:
/DiffXMLFile=[XML file name] - used by itself, this will apply the SQL diff
transform against specified XML file. Turns on the transform flag.
Autogenerates SQL file name from XML input file name if none is
provided via the next parameter '/DiffSQLFile'.
/DiffSQLFile=[SQL file name] - used with the '/DiffXMLFile' paramter, this
will assign the SQL file name used for the transformation output.
/CreateXMLFile=[XML file name] - used by itself, this will apply the SQL
Create transform against specified XML file. Turns on the transform
flag. Autogenerates SQL file name from XML input file name if none
is provided via the next parameter '/CreateSQLFile'.
/CreateSQLFile=[SQL file name] - used with the '/CreateXMLFile' paramter, this
will assign the SQL file name used for the transformation output.
OPTIONS: (changes operations of compare or output)
=============================================================================
/CompareSprocText - add this option to command line to compare source and
dest stored procedure text line by line. Otherwise if both source and
dest sprocs exists, the source sproc is always forced to 'alter
procedure'.
/Transform - add this option to command line to perform translation of the
XML file into a SQL file for creating or updating the SQL Destination
DB. Requires some combination of Source and Dest SQL connections
and/or XML Schema files.
/Primary - add this option for force all tables to use the Primary
filegroup for CREATE TABLE or ALTER TABLE when serializing the schema.
This option will also cause the compare to ignore FileGroups, since
they all will be set to PRIMARY.
";
/// <summary>
/// The main entry point for the application.
/// Handles processing of the command line args.
/// </summary>
/// <param name="args">Passes arguments string array into the appropriate methods and functions contained within the class.</param>
[STAThread]
static void Main(string[] args)
{
if (args.Length > 0)
{
// TODO: add additional commandline args functions
foreach (string arg in args)
{
if (arg.Split('=').Length == 2)
{
string command = arg.Split('=')[0].Trim().ToLower();
string argument = arg.Split('=')[1].Trim();
if (command.IndexOf("/src_server") >= 0)
{
_src_server = argument;
}
else if (command.IndexOf("/src_user") >= 0 || command.IndexOf("/src_uid") >= 0)
{
_src_user = argument;
}
else if (command.IndexOf("/src_password") >= 0 || command.IndexOf("/src_pwd") >= 0)
{
_src_password = argument;
}
else if (command.IndexOf("/src_database") >= 0 || command.IndexOf("/src_catalog") >= 0)
{
_src_db = argument;
}
else if (command.IndexOf("/src_file") >= 0)
{
_src_file = argument;
_Translate = true;
}
else if (command.IndexOf("/src_schema") >= 0)
{
_src_schema = argument;
}
if (command.IndexOf("/dest_server") >= 0)
{
_dest_server = argument;
}
else if (command.IndexOf("/dest_user") >= 0 || command.IndexOf("/dest_uid") >= 0)
{
_dest_user = argument;
}
else if (command.IndexOf("/dest_password") >= 0 || command.IndexOf("/dest_pwd") >= 0)
{
_dest_password = argument;
}
else if (command.IndexOf("/dest_database") >= 0 || command.IndexOf("/dest_catalog") >= 0)
{
_dest_db = argument;
}
else if (command.IndexOf("/dest_file") >= 0)
{
_dest_file = argument;
_Translate = true;
}
else if (command.IndexOf("/dest_schema") >= 0)
{
_dest_schema = argument;
}
else if (command.IndexOf("/diffxmlfile") >= 0)
{
_diffXMLFile = argument;
_Translate = true;
}
else if (command.IndexOf("/diffsqlfile") >= 0)
{
_diffName = argument;
_Translate = true;
}
else if (command.IndexOf("/createxmlfile") >= 0)
{
_createXMLFile = argument;
_Translate = true;
}
else if (command.IndexOf("/createsqlfile") >= 0)
{
_createName = argument;
_Translate = true;
}
}
if (arg.Split('=').Length == 1 && arg.Length > 0)
{
if (arg.IndexOf("/?") >= 0 || arg.ToLower().IndexOf("/help") >= 0)
{
Assembly a = Assembly.GetExecutingAssembly();
Console.WriteLine("{0}", string.Format(_help, System.Diagnostics.FileVersionInfo.GetVersionInfo(a.Location).FileVersion));
return;
}
else if (arg.ToLower().IndexOf("/src_trusted") >= 0)
{
_src_trusted = "true";
}
else if (arg.ToLower().IndexOf("/dest_trusted") >= 0)
{
_dest_trusted = "true";
}
else if (arg.ToLower().IndexOf("/comparesproctext") >= 0)
{
_CompareSprocs = true;
}
else if (arg.ToLower().IndexOf("/transform") >= 0)
{
_Translate = true;
}
else if (arg.ToLower().IndexOf("/translate") >= 0) // this is for my benefit since I keep typing it in wrong on the commandline.
{
_Translate = true;
}
else if (arg.ToLower().IndexOf("/primary") >= 0)
{
_Primary = true;
}
}
}
}
else
{
Assembly a = Assembly.GetExecutingAssembly();
Console.WriteLine("{0}", string.Format(_help, System.Diagnostics.FileVersionInfo.GetVersionInfo(a.Location).FileVersion));
return;
}
if (_src_trusted.ToLower() == "true")
{
_src_user = null;
_src_password = null;
}
else
{
if (_src_server != null && _src_db != null && (_src_user == null || _src_password == null))
{
Console.WriteLine("You must enter the trusted argument or a user name and password for the source SQL server in the commandline arguments.");
return;
}
}
if (_dest_trusted.ToLower() == "true")
{
_dest_user = null;
_dest_password = null;
}
else
{
if (_dest_server != null && _dest_db != null && (_dest_user == null || _dest_password == null))
{
Console.WriteLine("You must enter the trusted argument or a user name and password for the destination SQL server in the commandline arguments.");
return;
}
}
if (_src_server != null && _src_db != null && _dest_server != null && _dest_db != null)
{
if (_src_server.ToLower() == _dest_server.ToLower() && _src_db.ToLower() == _dest_db.ToLower())
{
Console.WriteLine("Thats silly, you can't compare the same SQL server and database against itself!");
return;
}
}
if (_src_schema != null && _dest_schema != null)
{
if (_src_schema.ToLower() == _dest_schema.ToLower())
{
Console.WriteLine("Thats silly, you can't compare the same SQL server and database XML file against itself!");
return;
}
}
// TODO: add the ability to exclude database objects by name or regex string
// TODO: add error checks for file.exists on all passed in file names for files that are supposed to already exist
if (_src_server != null && _src_db != null && _src_schema == null)
{
_src_schema = SerializeDB(_src_server, _src_db, _src_user, _src_password, _src_file, _Translate, _Primary);
}
if (_dest_server != null && _dest_db != null && _dest_schema == null)
{
_dest_schema = SerializeDB(_dest_server, _dest_db, _dest_user, _dest_password, _dest_file, _Translate, _Primary);
}
if (_src_schema != null && _dest_schema != null)
{
string diffName = null;
// some logic to create default diff XML file name
if (_diffXMLFile == null || _diffXMLFile.Length == 0)
{
if (_src_server != null && _src_db != null && _dest_server != null && _dest_db != null)
{
diffName = string.Format("{0}_{1}_DIFF_{2}_{3}_SCHEMA.xml", _src_server.Replace("\\", "_"), _src_db, _dest_server.Replace("\\", "_"), _dest_db);
}
else
{
string src = _src_schema.ToLower().Replace("_schema", "").Replace(".xml", "");
string dest = _dest_schema.ToLower().Replace("_schema", "").Replace(".xml", "");
diffName = string.Format("{0}_DIFF_{1}_SCHEMA.xml", src, dest);
}
}
else
{
diffName = _diffXMLFile;
}
string SQLfile = diffName.ToLower().Replace(".xml", ".sql");
if (!SQLfile.EndsWith(".sql")) SQLfile += ".sql";
// do the compare
CompareSchema(_src_schema, _dest_schema, diffName, SQLfile, _CompareSprocs, _Translate);
return;
}
if (_diffXMLFile != null && _diffXMLFile.Length > 0 && _src_schema == null && _dest_schema == null && _Translate)
{
// perform garbage collection to free up memory
GC.Collect();
Console.WriteLine("Please wait. Beginning SQL transformation of DiffGram XML...");
string diffName = string.Empty;
if (_diffName == null)
{
diffName = _diffXMLFile.ToLower().Replace(".xml", ".sql");
}
else
{
diffName = _diffName;
}
if (!diffName.EndsWith(".sql")) diffName += ".sql";
SQLTransform(_diffXMLFile, "Lewis.SST.Xslt.Diff_DB_Objs.xslt", diffName);
Console.WriteLine("SQL Diff Schema has been saved to " + diffName + ".");
return;
}
if (_createXMLFile != null && _createXMLFile.Length > 0 && _src_schema == null && _dest_schema == null && _Translate)
{
// perform garbage collection to free up memory
GC.Collect();
Console.WriteLine("Please wait. Beginning SQL transformation of schema XML...");
string createName = string.Empty;
if (_createName == null)
{
createName = _createXMLFile.ToLower().Replace(".xml", ".sql");
}
else
{
createName = _createName;
}
if (!createName.EndsWith(".sql")) createName += ".sql";
SQLTransform(_createXMLFile, "Lewis.SST.Xslt.Create_DB_Objs.xslt", createName);
Console.WriteLine("SQL Create Schema has been saved to " + createName + ".");
return;
}
if (_src_schema != null && _src_schema.Length > 0 && _createXMLFile == null && _dest_schema == null && _Translate)
{
// perform garbage collection to free up memory
GC.Collect();
Console.WriteLine("Please wait. Beginning SQL transformation of schema XML...");
string createName = _src_schema.ToLower().Replace(".xml", ".sql");
if (_src_file != null && _src_file.Length > 0)
{
createName = _src_file;
}
if (!createName.EndsWith(".sql")) createName += ".sql";
SQLTransform(_src_schema, "Lewis.SST.Xslt.Create_DB_Objs.xslt", createName);
Console.WriteLine("SQL Create Schema has been saved to " + createName + ".");
return;
}
}
}
}
| |
using System;
using System.Reflection;
/*
* Regression tests for the mono JIT.
*
* Each test needs to be of the form:
*
* public static int test_<result>_<name> ();
*
* where <result> is an integer (the value that needs to be returned by
* the method to make it pass.
* <name> is a user-displayed name used to identify the test.
*
* The tests can be driven in two ways:
* *) running the program directly: Main() uses reflection to find and invoke
* the test methods (this is useful mostly to check that the tests are correct)
* *) with the --regression switch of the jit (this is the preferred way since
* all the tests will be run with optimizations on and off)
*
* The reflection logic could be moved to a .dll since we need at least another
* regression test file written in IL code to have better control on how
* the IL code looks.
*/
public partial class Tests
{
public static int test_0_sin_precision()
{
double d1 = Math.Sin(1);
double d2 = Math.Sin(1) - d1;
return (d2 == 0) ? 0 : 1;
}
public static int test_0_cos_precision()
{
double d1 = Math.Cos(1);
double d2 = Math.Cos(1) - d1;
return (d2 == 0) ? 0 : 1;
}
public static int test_0_tan_precision()
{
double d1 = Math.Tan(1);
double d2 = Math.Tan(1) - d1;
return (d2 == 0) ? 0 : 1;
}
public static int test_0_atan_precision()
{
double d1 = Math.Atan(double.NegativeInfinity);
double d2 = Math.Atan(double.NegativeInfinity) - d1;
return (d2 == 0) ? 0 : 1;
}
public static int test_0_sqrt_precision()
{
double d1 = Math.Sqrt(2);
double d2 = Math.Sqrt(2) - d1;
return (d2 == 0) ? 0 : 1;
}
public static int test_2_sqrt()
{
return (int)Math.Sqrt(4);
}
public static int test_0_sqrt_precision_and_not_spill()
{
double expected = 0;
double[] operands = new double[3];
double[] temporaries = new double[3];
for (int i = 0; i < 3; i++)
{
operands[i] = (i + 1) * (i + 1) * (i + 1);
if (i == 0)
{
expected = operands[0];
}
else
{
temporaries[i] = operands[i] / expected;
temporaries[i] = Math.Sqrt(temporaries[i]);
expected = temporaries[i];
}
//Console.Write( "{0}: {1}\n", i, temporaries [i] );
}
expected = temporaries[2];
double result = Math.Sqrt(operands[2] / Math.Sqrt(operands[1] / operands[0]));
//Console.Write( "result: {0,20:G}\n", result );
return (result == expected) ? 0 : 1;
}
public static int test_0_sqrt_precision_and_spill()
{
double expected = 0;
double[] operands = new double[9];
double[] temporaries = new double[9];
for (int i = 0; i < 9; i++)
{
operands[i] = (i + 1) * (i + 1) * (i + 1);
if (i == 0)
{
expected = operands[0];
}
else
{
temporaries[i] = operands[i] / expected;
temporaries[i] = Math.Sqrt(temporaries[i]);
expected = temporaries[i];
}
//Console.Write( "{0}: {1}\n", i, temporaries [i] );
}
expected = temporaries[8];
double result = Math.Sqrt(operands[8] / Math.Sqrt(operands[7] / Math.Sqrt(operands[6] / Math.Sqrt(operands[5] / Math.Sqrt(operands[4] / Math.Sqrt(operands[3] / Math.Sqrt(operands[2] / Math.Sqrt(operands[1] / operands[0]))))))));
//Console.Write( "result: {0,20:G}\n", result );
return (result == expected) ? 0 : 1;
}
public static int test_0_div_precision_and_spill()
{
double expected = 0;
double[] operands = new double[9];
double[] temporaries = new double[9];
for (int i = 0; i < 9; i++)
{
operands[i] = (i + 1) * (i + 1);
if (i == 0)
{
expected = operands[0];
}
else
{
temporaries[i] = operands[i] / expected;
expected = temporaries[i];
}
//Console.Write( "{0}: {1}\n", i, temporaries [i] );
}
expected = temporaries[8];
double result = (operands[8] / (operands[7] / (operands[6] / (operands[5] / (operands[4] / (operands[3] / (operands[2] / (operands[1] / operands[0]))))))));
//Console.Write( "result: {0,20:G}\n", result );
return (result == expected) ? 0 : 1;
}
public static int test_0_sqrt_nan()
{
return Double.IsNaN(Math.Sqrt(Double.NaN)) ? 0 : 1;
}
public static int test_0_sin_nan()
{
return Double.IsNaN(Math.Sin(Double.NaN)) ? 0 : 1;
}
public static int test_0_cos_nan()
{
return Double.IsNaN(Math.Cos(Double.NaN)) ? 0 : 1;
}
public static int test_0_tan_nan()
{
return Double.IsNaN(Math.Tan(Double.NaN)) ? 0 : 1;
}
public static int test_0_atan_nan()
{
return Double.IsNaN(Math.Atan(Double.NaN)) ? 0 : 1;
}
public static int test_0_min()
{
if (Math.Min(5, 6) != 5)
return 1;
if (Math.Min(6, 5) != 5)
return 2;
if (Math.Min(-100, -101) != -101)
return 3;
if (Math.Min((long)5, (long)6) != 5)
return 4;
if (Math.Min((long)6, (long)5) != 5)
return 5;
if (Math.Min((long)-100, (long)-101) != -101)
return 6;
return 0;
}
public static int test_0_max()
{
if (Math.Max(5, 6) != 6)
return 1;
if (Math.Max(6, 5) != 6)
return 2;
if (Math.Max(-100, -101) != -100)
return 3;
if (Math.Max((long)5, (long)6) != 6)
return 4;
if (Math.Max((long)6, (long)5) != 6)
return 5;
if (Math.Max((long)-100, (long)-101) != -100)
return 6;
return 0;
}
public static int test_0_min_un()
{
uint a = (uint)int.MaxValue + 10;
for (uint b = 7; b <= 10; ++b)
{
if (Math.Min(a, b) != b)
return (int)b;
if (Math.Min(b, a) != b)
return (int)b;
}
if (Math.Min((ulong)5, (ulong)6) != 5)
return 4;
if (Math.Min((ulong)6, (ulong)5) != 5)
return 5;
ulong la = (ulong)long.MaxValue + 10;
for (ulong b = 7; b <= 10; ++b)
{
if (Math.Min(la, b) != b)
return (int)b;
if (Math.Min(b, la) != b)
return (int)b;
}
return 0;
}
public static int test_0_max_un()
{
uint a = (uint)int.MaxValue + 10;
for (uint b = 7; b <= 10; ++b)
{
if (Math.Max(a, b) != a)
return (int)b;
if (Math.Max(b, a) != a)
return (int)b;
}
if (Math.Max((ulong)5, (ulong)6) != 6)
return 4;
if (Math.Max((ulong)6, (ulong)5) != 6)
return 5;
ulong la = (ulong)long.MaxValue + 10;
for (ulong b = 7; b <= 10; ++b)
{
if (Math.Max(la, b) != la)
return (int)b;
if (Math.Max(b, la) != la)
return (int)b;
}
return 0;
}
public static int test_0_abs()
{
double d = -5.0;
if (Math.Abs(d) != 5.0)
return 1;
return 0;
}
public static int test_0_round()
{
if (Math.Round(5.0) != 5.0)
return 1;
if (Math.Round(5.000000000000001) != 5.0)
return 2;
if (Math.Round(5.499999999999999) != 5.0)
return 3;
if (Math.Round(5.5) != 6.0)
return 4;
if (Math.Round(5.999999999999999) != 6.0)
return 5;
if (Math.Round(Double.Epsilon) != 0)
return 6;
if (!Double.IsNaN(Math.Round(Double.NaN)))
return 7;
if (!Double.IsPositiveInfinity(Math.Round(Double.PositiveInfinity)))
return 8;
if (!Double.IsNegativeInfinity(Math.Round(Double.NegativeInfinity)))
return 9;
if (Math.Round(Double.MinValue) != Double.MinValue)
return 10;
if (Math.Round(Double.MaxValue) != Double.MaxValue)
return 11;
return 0;
}
}
| |
// ***********************************************************************
// Copyright (c) 2014-2015 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.Reflection;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
namespace NUnit.Framework.Internal.Builders
{
/// <summary>
/// NUnitTestFixtureBuilder is able to build a fixture given
/// a class marked with a TestFixtureAttribute or an unmarked
/// class containing test methods. In the first case, it is
/// called by the attribute and in the second directly by
/// NUnitSuiteBuilder.
/// </summary>
public class NUnitTestFixtureBuilder
{
#region Static Fields
static readonly string NO_TYPE_ARGS_MSG =
"Fixture type contains generic parameters. You must either provide " +
"Type arguments or specify constructor arguments that allow NUnit " +
"to deduce the Type arguments.";
#endregion
#region Instance Fields
private ITestCaseBuilder _testBuilder = new DefaultTestCaseBuilder();
#endregion
#region Public Methods
/// <summary>
/// Build a TestFixture from type provided. A non-null TestSuite
/// must always be returned, since the method is generally called
/// because the user has marked the target class as a fixture.
/// If something prevents the fixture from being used, it should
/// be returned nonetheless, labelled as non-runnable.
/// </summary>
/// <param name="typeInfo">An ITypeInfo for the fixture to be used.</param>
/// <returns>A TestSuite object or one derived from TestSuite.</returns>
// TODO: This should really return a TestFixture, but that requires changes to the Test hierarchy.
public TestSuite BuildFrom(ITypeInfo typeInfo)
{
var fixture = new TestFixture(typeInfo);
if (fixture.RunState != RunState.NotRunnable)
CheckTestFixtureIsValid(fixture);
fixture.ApplyAttributesToTest(typeInfo.Type.GetTypeInfo());
AddTestCasesToFixture(fixture);
return fixture;
}
/// <summary>
/// Overload of BuildFrom called by tests that have arguments.
/// Builds a fixture using the provided type and information
/// in the ITestFixtureData object.
/// </summary>
/// <param name="typeInfo">The TypeInfo for which to construct a fixture.</param>
/// <param name="testFixtureData">An object implementing ITestFixtureData or null.</param>
/// <returns></returns>
public TestSuite BuildFrom(ITypeInfo typeInfo, ITestFixtureData testFixtureData)
{
Guard.ArgumentNotNull(testFixtureData, "testFixtureData");
object[] arguments = testFixtureData.Arguments;
if (typeInfo.ContainsGenericParameters)
{
Type[] typeArgs = testFixtureData.TypeArgs;
if (typeArgs.Length == 0)
{
int cnt = 0;
foreach (object o in arguments)
if (o is Type) cnt++;
else break;
typeArgs = new Type[cnt];
for (int i = 0; i < cnt; i++)
typeArgs[i] = (Type)arguments[i];
if (cnt > 0)
{
object[] args = new object[arguments.Length - cnt];
for (int i = 0; i < args.Length; i++)
args[i] = arguments[cnt + i];
arguments = args;
}
}
if (typeArgs.Length > 0 ||
TypeHelper.CanDeduceTypeArgsFromArgs(typeInfo.Type, arguments, ref typeArgs))
{
typeInfo = typeInfo.MakeGenericType(typeArgs);
}
}
var fixture = new TestFixture(typeInfo);
if (arguments != null && arguments.Length > 0)
{
string name = fixture.Name = typeInfo.GetDisplayName(arguments);
string nspace = typeInfo.Namespace;
fixture.FullName = nspace != null && nspace != ""
? nspace + "." + name
: name;
fixture.Arguments = arguments;
}
if (fixture.RunState != RunState.NotRunnable)
fixture.RunState = testFixtureData.RunState;
foreach (string key in testFixtureData.Properties.Keys)
foreach (object val in testFixtureData.Properties[key])
fixture.Properties.Add(key, val);
if (fixture.RunState != RunState.NotRunnable)
CheckTestFixtureIsValid(fixture);
fixture.ApplyAttributesToTest(typeInfo.Type.GetTypeInfo());
AddTestCasesToFixture(fixture);
return fixture;
}
#endregion
#region Helper Methods
/// <summary>
/// Method to add test cases to the newly constructed fixture.
/// </summary>
/// <param name="fixture">The fixture to which cases should be added</param>
private void AddTestCasesToFixture(TestFixture fixture)
{
// TODO: Check this logic added from Neil's build.
if (fixture.TypeInfo.ContainsGenericParameters)
{
fixture.RunState = RunState.NotRunnable;
fixture.Properties.Set(PropertyNames.SkipReason, NO_TYPE_ARGS_MSG);
return;
}
var methods = fixture.TypeInfo.GetMethods(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
foreach (IMethodInfo method in methods)
{
Test test = BuildTestCase(method, fixture);
if (test != null)
{
fixture.Add(test);
}
}
}
/// <summary>
/// Method to create a test case from a MethodInfo and add
/// it to the fixture being built. It first checks to see if
/// any global TestCaseBuilder addin wants to build the
/// test case. If not, it uses the internal builder
/// collection maintained by this fixture builder.
///
/// The default implementation has no test case builders.
/// Derived classes should add builders to the collection
/// in their constructor.
/// </summary>
/// <param name="method">The method for which a test is to be created</param>
/// <param name="suite">The test suite being built.</param>
/// <returns>A newly constructed Test</returns>
private Test BuildTestCase(IMethodInfo method, TestSuite suite)
{
return _testBuilder.CanBuildFrom(method, suite)
? _testBuilder.BuildFrom(method, suite)
: null;
}
private static void CheckTestFixtureIsValid(TestFixture fixture)
{
if (fixture.TypeInfo.ContainsGenericParameters)
{
fixture.RunState = RunState.NotRunnable;
fixture.Properties.Set(PropertyNames.SkipReason, NO_TYPE_ARGS_MSG);
}
else if (!fixture.TypeInfo.IsStaticClass)
{
Type[] argTypes = Reflect.GetTypeArray(fixture.Arguments);
if (!fixture.TypeInfo.HasConstructor(argTypes))
{
fixture.RunState = RunState.NotRunnable;
fixture.Properties.Set(PropertyNames.SkipReason, "No suitable constructor was found");
}
}
}
private static bool IsStaticClass(Type type)
{
return type.GetTypeInfo().IsAbstract && type.GetTypeInfo().IsSealed;
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.Generic;
namespace NFCoreEx
{
public class NFCKernel : NFIKernel
{
#region Instance
private static NFIKernel _Instance = null;
private static readonly object _syncLock = new object();
public static NFIKernel Instance
{
get
{
lock (_syncLock)
{
if (_Instance == null)
{
_Instance = new NFCKernel();
}
return _Instance;
}
}
}
#endregion
public NFCKernel()
{
mhtObject = new Dictionary<NFIDENTID, NFIObject>();
mhtClassHandleDel = new Dictionary<string, ClassHandleDel>();
mxLogicClassManager = new NFCLogicClassManager();
mxElementManager = new NFCElementManager();
}
~NFCKernel()
{
mhtObject = null;
mxElementManager = null;
mxLogicClassManager = null;
}
public override bool AddHeartBeat(NFIDENTID self, string strHeartBeatName, NFIHeartBeat.HeartBeatEventHandler handler, float fTime, NFIDataList valueList)
{
NFIObject xGameObject = GetObject(self);
if (null != xGameObject)
{
xGameObject.GetHeartBeatManager().AddHeartBeat(strHeartBeatName, fTime, handler, valueList);
}
return true;
}
public override void RegisterPropertyCallback(NFIDENTID self, string strPropertyName, NFIProperty.PropertyEventHandler handler)
{
NFIObject xGameObject = GetObject(self);
if (null != xGameObject)
{
xGameObject.GetPropertyManager().RegisterCallback(strPropertyName, handler);
}
}
public override void RegisterRecordCallback(NFIDENTID self, string strRecordName, NFIRecord.RecordEventHandler handler)
{
NFIObject xGameObject = GetObject(self);
if (null != xGameObject)
{
xGameObject.GetRecordManager().RegisterCallback(strRecordName, handler);
}
}
public override void RegisterClassCallBack(string strClassName, NFIObject.ClassEventHandler handler)
{
if(mhtClassHandleDel.ContainsKey(strClassName))
{
ClassHandleDel xHandleDel = (ClassHandleDel)mhtClassHandleDel[strClassName];
xHandleDel.AddDel(handler);
}
else
{
ClassHandleDel xHandleDel = new ClassHandleDel();
xHandleDel.AddDel(handler);
mhtClassHandleDel[strClassName] = xHandleDel;
}
}
public override void RegisterEventCallBack(NFIDENTID self, int nEventID, NFIEvent.EventHandler handler, NFIDataList valueList)
{
NFIObject xGameObject = GetObject(self);
if (null != xGameObject)
{
xGameObject.GetEventManager().RegisterCallback(nEventID, handler, valueList);
}
}
public override bool FindHeartBeat(NFIDENTID self, string strHeartBeatName)
{
NFIObject xGameObject = GetObject(self);
if (null != xGameObject)
{
//gameObject.GetHeartBeatManager().AddHeartBeat()
}
return false;
}
public override bool RemoveHeartBeat(NFIDENTID self, string strHeartBeatName)
{
return true;
}
public override bool UpDate(float fTime)
{
foreach (NFIDENTID id in mhtObject.Keys)
{
NFIObject xGameObject = (NFIObject)mhtObject[id];
xGameObject.GetHeartBeatManager().Update(fTime);
}
return true;
}
/////////////////////////////////////////////////////////////
//public override bool AddRecordCallBack( NFIDENTID self, string strRecordName, RECORD_EVENT_FUNC cb );
//public override bool AddPropertyCallBack( NFIDENTID self, string strCriticalName, PROPERTY_EVENT_FUNC cb );
// public override bool AddClassCallBack( string strClassName, CLASS_EVENT_FUNC cb );
//
// public override bool RemoveClassCallBack( string strClassName, CLASS_EVENT_FUNC cb );
/////////////////////////////////////////////////////////////////
public override NFIObject GetObject(NFIDENTID ident)
{
if (null != ident && mhtObject.ContainsKey(ident))
{
return (NFIObject)mhtObject[ident];
}
return null;
}
public override NFIObject CreateObject(NFIDENTID self, int nContainerID, int nGroupID, string strClassName, string strConfigIndex, NFIDataList arg)
{
if (!mhtObject.ContainsKey(self))
{
NFIObject xNewObject = new NFCObject(self, nContainerID, nGroupID, strClassName, strConfigIndex);
mhtObject.Add(self, xNewObject);
NFCDataList varConfigID = new NFCDataList();
varConfigID.AddString(strConfigIndex);
xNewObject.GetPropertyManager().AddProperty("ConfigID", varConfigID);
NFCDataList varConfigClass = new NFCDataList();
varConfigClass.AddString(strClassName);
xNewObject.GetPropertyManager().AddProperty("ClassName", varConfigClass);
if (arg.Count() % 2 == 0)
{
for (int i = 0; i < arg.Count() - 1; i += 2)
{
string strPropertyName = arg.StringVal(i);
NFIDataList.VARIANT_TYPE eType = arg.GetType(i + 1);
switch (eType)
{
case NFIDataList.VARIANT_TYPE.VTYPE_INT:
{
NFIDataList xDataList = new NFCDataList();
xDataList.AddInt(arg.IntVal(i+1));
xNewObject.GetPropertyManager().AddProperty(strPropertyName, xDataList);
}
break;
case NFIDataList.VARIANT_TYPE.VTYPE_FLOAT:
{
NFIDataList xDataList = new NFCDataList();
xDataList.AddFloat(arg.FloatVal(i + 1));
xNewObject.GetPropertyManager().AddProperty(strPropertyName, xDataList);
}
break;
case NFIDataList.VARIANT_TYPE.VTYPE_DOUBLE:
{
NFIDataList xDataList = new NFCDataList();
xDataList.AddDouble(arg.DoubleVal(i + 1));
xNewObject.GetPropertyManager().AddProperty(strPropertyName, xDataList);
}
break;
case NFIDataList.VARIANT_TYPE.VTYPE_STRING:
{
NFIDataList xDataList = new NFCDataList();
xDataList.AddString(arg.StringVal(i + 1));
xNewObject.GetPropertyManager().AddProperty(strPropertyName, xDataList);
}
break;
case NFIDataList.VARIANT_TYPE.VTYPE_OBJECT:
{
NFIDataList xDataList = new NFCDataList();
xDataList.AddObject(arg.ObjectVal(i + 1));
xNewObject.GetPropertyManager().AddProperty(strPropertyName, xDataList);
}
break;
default:
break;
}
}
}
InitProperty(self, strClassName);
InitRecord(self, strClassName);
if (mhtClassHandleDel.ContainsKey(strClassName))
{
ClassHandleDel xHandleDel = (ClassHandleDel)mhtClassHandleDel[strClassName];
if (null != xHandleDel && null != xHandleDel.GetHandler())
{
NFIObject.ClassEventHandler xHandlerList = xHandleDel.GetHandler();
xHandlerList(self, nContainerID, nGroupID, NFIObject.CLASS_EVENT_TYPE.OBJECT_CREATE, strClassName, strConfigIndex);
xHandlerList(self, nContainerID, nGroupID, NFIObject.CLASS_EVENT_TYPE.OBJECT_LOADDATA, strClassName, strConfigIndex);
xHandlerList(self, nContainerID, nGroupID, NFIObject.CLASS_EVENT_TYPE.OBJECT_CREATE_FINISH, strClassName, strConfigIndex);
}
}
//NFCLog.Instance.Log(NFCLog.LOG_LEVEL.DEBUG, "Create object: " + self.ToString() + " ClassName: " + strClassName + " SceneID: " + nContainerID + " GroupID: " + nGroupID);
return xNewObject;
}
return null;
}
public override bool DestroyObject(NFIDENTID self)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
string strClassName = xGameObject.ClassName();
ClassHandleDel xHandleDel = (ClassHandleDel)mhtClassHandleDel[strClassName];
if (null != xHandleDel && null != xHandleDel.GetHandler())
{
NFIObject.ClassEventHandler xHandlerList = xHandleDel.GetHandler();
xHandlerList(self, xGameObject.ContainerID(), xGameObject.GroupID(), NFIObject.CLASS_EVENT_TYPE.OBJECT_DESTROY, xGameObject.ClassName(), xGameObject.ConfigIndex());
}
mhtObject.Remove(self);
//NFCLog.Instance.Log(NFCLog.LOG_LEVEL.DEBUG, "Destroy object: " + self.ToString() + " ClassName: " + strClassName + " SceneID: " + xGameObject.ContainerID() + " GroupID: " + xGameObject.GroupID());
return true;
}
return false;
}
public override bool FindProperty(NFIDENTID self, string strPropertyName)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.FindProperty(strPropertyName);
}
return false;
}
public override bool SetPropertyInt(NFIDENTID self, string strPropertyName, Int64 nValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetPropertyInt(strPropertyName, nValue);
}
return false;
}
public override bool SetPropertyFloat(NFIDENTID self, string strPropertyName, float fValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetPropertyFloat(strPropertyName, fValue);
}
return false;
}
public override bool SetPropertyDouble(NFIDENTID self, string strPropertyName, double dValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetPropertyDouble(strPropertyName, dValue);
}
return false;
}
public override bool SetPropertyString(NFIDENTID self, string strPropertyName, string strValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetPropertyString(strPropertyName, strValue);
}
return false;
}
public override bool SetPropertyObject(NFIDENTID self, string strPropertyName, NFIDENTID objectValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetPropertyObject(strPropertyName, objectValue);
}
return false;
}
public override Int64 QueryPropertyInt(NFIDENTID self, string strPropertyName)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryPropertyInt(strPropertyName);
}
return 0;
}
public override float QueryPropertyFloat(NFIDENTID self, string strPropertyName)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryPropertyFloat(strPropertyName);
}
return 0.0f;
}
public override double QueryPropertyDouble(NFIDENTID self, string strPropertyName)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryPropertyDouble(strPropertyName);
}
return 0.0;
}
public override string QueryPropertyString(NFIDENTID self, string strPropertyName)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryPropertyString(strPropertyName);
}
return "";
}
public override NFIDENTID QueryPropertyObject(NFIDENTID self, string strPropertyName)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryPropertyObject(strPropertyName);
}
return new NFIDENTID();
}
public override NFIRecord FindRecord(NFIDENTID self, string strRecordName)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.GetRecordManager().GetRecord(strRecordName);
}
return null;
}
public override bool SetRecordInt(NFIDENTID self, string strRecordName, int nRow, int nCol, Int64 nValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetRecordInt(strRecordName, nRow, nCol, nValue);
}
return false;
}
public override bool SetRecordFloat(NFIDENTID self, string strRecordName, int nRow, int nCol, float fValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetRecordFloat(strRecordName, nRow, nCol, fValue);
}
return false;
}
public override bool SetRecordDouble(NFIDENTID self, string strRecordName, int nRow, int nCol, double dwValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetRecordDouble(strRecordName, nRow, nCol, dwValue);
}
return false;
}
public override bool SetRecordString(NFIDENTID self, string strRecordName, int nRow, int nCol, string strValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetRecordString(strRecordName, nRow, nCol, strValue);
}
return false;
}
public override bool SetRecordObject(NFIDENTID self, string strRecordName, int nRow, int nCol, NFIDENTID objectValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetRecordObject(strRecordName, nRow, nCol, objectValue);
}
return false;
}
public override Int64 QueryRecordInt(NFIDENTID self, string strRecordName, int nRow, int nCol)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryRecordInt(strRecordName, nRow, nCol);
}
return 0;
}
public override float QueryRecordFloat(NFIDENTID self, string strRecordName, int nRow, int nCol)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryRecordFloat(strRecordName, nRow, nCol);
}
return 0.0f;
}
public override double QueryRecordDouble(NFIDENTID self, string strRecordName, int nRow, int nCol)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryRecordDouble(strRecordName, nRow, nCol);
}
return 0.0;
}
public override string QueryRecordString(NFIDENTID self, string strRecordName, int nRow, int nCol)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryRecordString(strRecordName, nRow, nCol);
}
return "";
}
public override NFIDENTID QueryRecordObject(NFIDENTID self, string strRecordName, int nRow, int nCol)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryRecordObject(strRecordName, nRow, nCol);
}
return new NFIDENTID();
}
public override NFIDataList GetObjectList()
{
NFIDataList varData = new NFCDataList();
foreach (KeyValuePair<NFIDENTID, NFIObject> kv in mhtObject)
{
varData.AddObject(kv.Key);
}
return varData;
}
public override int FindRecordRow(NFIDENTID self, string strRecordName, int nCol, int nValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
NFCoreEx.NFIRecord xRecord = xGameObject.GetRecordManager().GetRecord(strRecordName);
if (null != xRecord)
{
return xRecord.FindInt(nCol, nValue);
}
}
return -1;
}
public override int FindRecordRow(NFIDENTID self, string strRecordName, int nCol, float fValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
NFCoreEx.NFIRecord xRecord = xGameObject.GetRecordManager().GetRecord(strRecordName);
if (null != xRecord)
{
return xRecord.FindFloat(nCol, fValue);
}
}
return -1;
}
public override int FindRecordRow(NFIDENTID self, string strRecordName, int nCol, double fValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
NFCoreEx.NFIRecord xRecord = xGameObject.GetRecordManager().GetRecord(strRecordName);
if (null != xRecord)
{
return xRecord.FindDouble(nCol, fValue);
}
}
return -1;
}
public override int FindRecordRow(NFIDENTID self, string strRecordName, int nCol, string strValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
NFCoreEx.NFIRecord xRecord = xGameObject.GetRecordManager().GetRecord(strRecordName);
if (null != xRecord)
{
return xRecord.FindString(nCol, strValue);
}
}
return -1;
}
public override int FindRecordRow(NFIDENTID self, string strRecordName, int nCol, NFIDENTID nValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
NFCoreEx.NFIRecord xRecord = xGameObject.GetRecordManager().GetRecord(strRecordName);
if (null != xRecord)
{
return xRecord.FindObject(nCol, nValue);
}
}
return -1;
}
void InitProperty(NFIDENTID self, string strClassName)
{
NFILogicClass xLogicClass = NFCLogicClassManager.Instance.GetElement(strClassName);
NFIDataList xDataList = xLogicClass.GetPropertyManager().GetPropertyList();
for (int i = 0; i < xDataList.Count(); ++i )
{
string strPropertyName = xDataList.StringVal(i);
NFIProperty xProperty = xLogicClass.GetPropertyManager().GetProperty(strPropertyName);
NFIObject xObject = GetObject(self);
NFIPropertyManager xPropertyManager = xObject.GetPropertyManager();
xPropertyManager.AddProperty(strPropertyName, xProperty.GetValue());
}
}
void InitRecord(NFIDENTID self, string strClassName)
{
NFILogicClass xLogicClass = NFCLogicClassManager.Instance.GetElement(strClassName);
NFIDataList xDataList = xLogicClass.GetRecordManager().GetRecordList();
for (int i = 0; i < xDataList.Count(); ++i)
{
string strRecordyName = xDataList.StringVal(i);
NFIRecord xRecord = xLogicClass.GetRecordManager().GetRecord(strRecordyName);
NFIObject xObject = GetObject(self);
NFIRecordManager xRecordManager = xObject.GetRecordManager();
xRecordManager.AddRecord(strRecordyName, xRecord.GetRows(), xRecord.GetColsData());
}
}
Dictionary<NFIDENTID, NFIObject> mhtObject;
Dictionary<string, ClassHandleDel> mhtClassHandleDel;
NFIElementManager mxElementManager;
NFILogicClassManager mxLogicClassManager;
class ClassHandleDel
{
public ClassHandleDel()
{
mhtHandleDelList = new Dictionary<NFIObject.ClassEventHandler, string>();
}
public void AddDel(NFIObject.ClassEventHandler handler)
{
if (!mhtHandleDelList.ContainsKey(handler))
{
mhtHandleDelList.Add(handler, handler.ToString());
mHandleDel += handler;
}
}
public NFIObject.ClassEventHandler GetHandler()
{
return mHandleDel;
}
private NFIObject.ClassEventHandler mHandleDel;
private Dictionary<NFIObject.ClassEventHandler, string> mhtHandleDelList;
}
}
}
| |
//
// https://github.com/ServiceStack/ServiceStack.Text
// ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers.
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2012 ServiceStack Ltd.
//
// Licensed under the same terms of ServiceStack: new BSD license.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Linq;
using ServiceStack.Text.Common;
namespace ServiceStack.Text
{
public static class TranslateListWithElements
{
private static Dictionary<Type, ConvertInstanceDelegate> TranslateICollectionCache
= new Dictionary<Type, ConvertInstanceDelegate>();
public static object TranslateToGenericICollectionCache(object from, Type toInstanceOfType, Type elementType)
{
ConvertInstanceDelegate translateToFn;
if (TranslateICollectionCache.TryGetValue(toInstanceOfType, out translateToFn))
return translateToFn(from, toInstanceOfType);
var genericType = typeof(TranslateListWithElements<>).MakeGenericType(elementType);
var mi = genericType.GetPublicStaticMethod("LateBoundTranslateToGenericICollection");
translateToFn = (ConvertInstanceDelegate)mi.MakeDelegate(typeof(ConvertInstanceDelegate));
Dictionary<Type, ConvertInstanceDelegate> snapshot, newCache;
do
{
snapshot = TranslateICollectionCache;
newCache = new Dictionary<Type, ConvertInstanceDelegate>(TranslateICollectionCache);
newCache[elementType] = translateToFn;
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref TranslateICollectionCache, newCache, snapshot), snapshot));
return translateToFn(from, toInstanceOfType);
}
private static Dictionary<ConvertibleTypeKey, ConvertInstanceDelegate> TranslateConvertibleICollectionCache
= new Dictionary<ConvertibleTypeKey, ConvertInstanceDelegate>();
public static object TranslateToConvertibleGenericICollectionCache(
object from, Type toInstanceOfType, Type fromElementType)
{
var typeKey = new ConvertibleTypeKey(toInstanceOfType, fromElementType);
ConvertInstanceDelegate translateToFn;
if (TranslateConvertibleICollectionCache.TryGetValue(typeKey, out translateToFn)) return translateToFn(from, toInstanceOfType);
var toElementType = toInstanceOfType.GetGenericType().GenericTypeArguments()[0];
var genericType = typeof(TranslateListWithConvertibleElements<,>).MakeGenericType(fromElementType, toElementType);
var mi = genericType.GetPublicStaticMethod("LateBoundTranslateToGenericICollection");
translateToFn = (ConvertInstanceDelegate)mi.MakeDelegate(typeof(ConvertInstanceDelegate));
Dictionary<ConvertibleTypeKey, ConvertInstanceDelegate> snapshot, newCache;
do
{
snapshot = TranslateConvertibleICollectionCache;
newCache = new Dictionary<ConvertibleTypeKey, ConvertInstanceDelegate>(TranslateConvertibleICollectionCache);
newCache[typeKey] = translateToFn;
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref TranslateConvertibleICollectionCache, newCache, snapshot), snapshot));
return translateToFn(from, toInstanceOfType);
}
public static object TryTranslateToGenericICollection(Type fromPropertyType, Type toPropertyType, object fromValue)
{
var args = typeof(ICollection<>).GetGenericArgumentsIfBothHaveSameGenericDefinitionTypeAndArguments(
fromPropertyType, toPropertyType);
if (args != null)
{
return TranslateToGenericICollectionCache(
fromValue, toPropertyType, args[0]);
}
var varArgs = typeof(ICollection<>).GetGenericArgumentsIfBothHaveConvertibleGenericDefinitionTypeAndArguments(
fromPropertyType, toPropertyType);
if (varArgs != null)
{
return TranslateToConvertibleGenericICollectionCache(
fromValue, toPropertyType, varArgs.Args1[0]);
}
return null;
}
}
public class ConvertibleTypeKey
{
public Type ToInstanceType { get; set; }
public Type FromElemenetType { get; set; }
public ConvertibleTypeKey()
{
}
public ConvertibleTypeKey(Type toInstanceType, Type fromElemenetType)
{
ToInstanceType = toInstanceType;
FromElemenetType = fromElemenetType;
}
public bool Equals(ConvertibleTypeKey other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.ToInstanceType, ToInstanceType) && Equals(other.FromElemenetType, FromElemenetType);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(ConvertibleTypeKey)) return false;
return Equals((ConvertibleTypeKey)obj);
}
public override int GetHashCode()
{
unchecked
{
return ((ToInstanceType != null ? ToInstanceType.GetHashCode() : 0) * 397)
^ (FromElemenetType != null ? FromElemenetType.GetHashCode() : 0);
}
}
}
public class TranslateListWithElements<T>
{
public static object CreateInstance(Type toInstanceOfType)
{
if (toInstanceOfType.IsGeneric())
{
if (toInstanceOfType.HasAnyTypeDefinitionsOf(
typeof(ICollection<>), typeof(IList<>)))
{
return ReflectionExtensions.CreateInstance(typeof(List<T>));
}
}
return ReflectionExtensions.CreateInstance(toInstanceOfType);
}
public static IList TranslateToIList(IList fromList, Type toInstanceOfType)
{
var to = (IList)ReflectionExtensions.CreateInstance(toInstanceOfType);
foreach (var item in fromList)
{
to.Add(item);
}
return to;
}
public static object LateBoundTranslateToGenericICollection(
object fromList, Type toInstanceOfType)
{
if (fromList == null) return null; //AOT
return TranslateToGenericICollection(
(ICollection<T>)fromList, toInstanceOfType);
}
public static ICollection<T> TranslateToGenericICollection(
ICollection<T> fromList, Type toInstanceOfType)
{
var to = (ICollection<T>)CreateInstance(toInstanceOfType);
foreach (var item in fromList)
{
to.Add(item);
}
return to;
}
}
public class TranslateListWithConvertibleElements<TFrom, TTo>
{
private static readonly Func<TFrom, TTo> ConvertFn;
static TranslateListWithConvertibleElements()
{
ConvertFn = GetConvertFn();
}
public static object LateBoundTranslateToGenericICollection(
object fromList, Type toInstanceOfType)
{
return TranslateToGenericICollection(
(ICollection<TFrom>)fromList, toInstanceOfType);
}
public static ICollection<TTo> TranslateToGenericICollection(
ICollection<TFrom> fromList, Type toInstanceOfType)
{
if (fromList == null) return null; //AOT
var to = (ICollection<TTo>)TranslateListWithElements<TTo>.CreateInstance(toInstanceOfType);
foreach (var item in fromList)
{
var toItem = ConvertFn(item);
to.Add(toItem);
}
return to;
}
private static Func<TFrom, TTo> GetConvertFn()
{
if (typeof(TTo) == typeof(string))
{
return x => (TTo)(object)TypeSerializer.SerializeToString(x);
}
if (typeof(TFrom) == typeof(string))
{
return x => TypeSerializer.DeserializeFromString<TTo>((string)(object)x);
}
return x => TypeSerializer.DeserializeFromString<TTo>(TypeSerializer.SerializeToString(x));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Analytics
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// JobOperations operations.
/// </summary>
public partial interface IJobOperations
{
/// <summary>
/// Gets statistics of the specified job.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// JobInfo ID.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<JobStatistics>> GetStatisticsWithHttpMessagesAsync(string accountName, Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the job debug data information specified by the job ID.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// JobInfo ID.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<JobDataPath>> GetDebugDataPathWithHttpMessagesAsync(string accountName, Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Builds (compiles) the specified job in the specified Data Lake
/// Analytics account for job correctness and validation.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='parameters'>
/// The parameters to build a job.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<JobInformation>> BuildWithHttpMessagesAsync(string accountName, JobInformation parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Cancels the running job specified by the job ID.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// JobInfo ID to cancel.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> CancelWithHttpMessagesAsync(string accountName, Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the job information for the specified job ID.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// JobInfo ID.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<JobInformation>> GetWithHttpMessagesAsync(string accountName, Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Submits a job to the specified Data Lake Analytics account.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// The job ID (a GUID) for the job being submitted.
/// </param>
/// <param name='parameters'>
/// The parameters to submit a job.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<JobInformation>> CreateWithHttpMessagesAsync(string accountName, Guid jobIdentity, JobInformation parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the jobs, if any, associated with the specified Data Lake
/// Analytics account. The response includes a link to the next page
/// of results, if any.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to
/// just those requested, e.g.
/// Categories?$select=CategoryName,Description. Optional.
/// </param>
/// <param name='count'>
/// The Boolean value of true or false to request a count of the
/// matching resources included with the resources in the response,
/// e.g. Categories?$count=true. Optional.
/// </param>
/// <param name='search'>
/// A free form search. A free-text search expression to match for
/// whether a particular entry should be included in the feed, e.g.
/// Categories?$search=blue OR green. Optional.
/// </param>
/// <param name='format'>
/// The return format. Return the response in particular formatxii
/// without access to request headers for standard content-type
/// negotiation (e.g Orders?$format=json). Optional.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<JobInformation>>> ListWithHttpMessagesAsync(string accountName, ODataQuery<JobInformation> odataQuery = default(ODataQuery<JobInformation>), string select = default(string), bool? count = default(bool?), string search = default(string), string format = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the jobs, if any, associated with the specified Data Lake
/// Analytics account. The response includes a link to the next page
/// of results, if any.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<JobInformation>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
/*
* Copyright (c) 2016 Robert Adams
*
* 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.
*/
// Derived from WebGLConstants.js from Cesium project. (Apache 2.0)
namespace org.herbal3d.BasilOS {
public class WebGLConstants {
public const uint DEPTH_BUFFER_BIT = 0x00000100;
public const uint STENCIL_BUFFER_BIT = 0x00000400;
public const uint COLOR_BUFFER_BIT = 0x00004000;
public const uint POINTS = 0x0000;
public const uint LINES = 0x0001;
public const uint LINE_LOOP = 0x0002;
public const uint LINE_STRIP = 0x0003;
public const uint TRIANGLES = 0x0004;
public const uint TRIANGLE_STRIP = 0x0005;
public const uint TRIANGLE_FAN = 0x0006;
public const uint ZERO = 0;
public const uint ONE = 1;
public const uint SRC_COLOR = 0x0300;
public const uint ONE_MINUS_SRC_COLOR = 0x0301;
public const uint SRC_ALPHA = 0x0302;
public const uint ONE_MINUS_SRC_ALPHA = 0x0303;
public const uint DST_ALPHA = 0x0304;
public const uint ONE_MINUS_DST_ALPHA = 0x0305;
public const uint DST_COLOR = 0x0306;
public const uint ONE_MINUS_DST_COLOR = 0x0307;
public const uint SRC_ALPHA_SATURATE = 0x0308;
public const uint FUNC_ADD = 0x8006;
public const uint BLEND_EQUATION = 0x8009;
public const uint BLEND_EQUATION_RGB = 0x8009; // same as BLEND_EQUATION
public const uint BLEND_EQUATION_ALPHA = 0x883D;
public const uint FUNC_SUBTRACT = 0x800A;
public const uint FUNC_REVERSE_SUBTRACT = 0x800B;
public const uint BLEND_DST_RGB = 0x80C8;
public const uint BLEND_SRC_RGB = 0x80C9;
public const uint BLEND_DST_ALPHA = 0x80CA;
public const uint BLEND_SRC_ALPHA = 0x80CB;
public const uint CONSTANT_COLOR = 0x8001;
public const uint ONE_MINUS_CONSTANT_COLOR = 0x8002;
public const uint CONSTANT_ALPHA = 0x8003;
public const uint ONE_MINUS_CONSTANT_ALPHA = 0x8004;
public const uint BLEND_COLOR = 0x8005;
public const uint ARRAY_BUFFER = 0x8892;
public const uint ELEMENT_ARRAY_BUFFER = 0x8893;
public const uint ARRAY_BUFFER_BINDING = 0x8894;
public const uint ELEMENT_ARRAY_BUFFER_BINDING = 0x8895;
public const uint STREAM_DRAW = 0x88E0;
public const uint STATIC_DRAW = 0x88E4;
public const uint DYNAMIC_DRAW = 0x88E8;
public const uint BUFFER_SIZE = 0x8764;
public const uint BUFFER_USAGE = 0x8765;
public const uint CURRENT_VERTEX_ATTRIB = 0x8626;
public const uint FRONT = 0x0404;
public const uint BACK = 0x0405;
public const uint FRONT_AND_BACK = 0x0408;
public const uint CULL_FACE = 0x0B44;
public const uint BLEND = 0x0BE2;
public const uint DITHER = 0x0BD0;
public const uint STENCIL_TEST = 0x0B90;
public const uint DEPTH_TEST = 0x0B71;
public const uint SCISSOR_TEST = 0x0C11;
public const uint POLYGON_OFFSET_FILL = 0x8037;
public const uint SAMPLE_ALPHA_TO_COVERAGE = 0x809E;
public const uint SAMPLE_COVERAGE = 0x80A0;
public const uint NO_ERROR = 0;
public const uint INVALID_ENUM = 0x0500;
public const uint INVALID_VALUE = 0x0501;
public const uint INVALID_OPERATION = 0x0502;
public const uint OUT_OF_MEMORY = 0x0505;
public const uint CW = 0x0900;
public const uint CCW = 0x0901;
public const uint LINE_WIDTH = 0x0B21;
public const uint ALIASED_POINT_SIZE_RANGE = 0x846D;
public const uint ALIASED_LINE_WIDTH_RANGE = 0x846E;
public const uint CULL_FACE_MODE = 0x0B45;
public const uint FRONT_FACE = 0x0B46;
public const uint DEPTH_RANGE = 0x0B70;
public const uint DEPTH_WRITEMASK = 0x0B72;
public const uint DEPTH_CLEAR_VALUE = 0x0B73;
public const uint DEPTH_FUNC = 0x0B74;
public const uint STENCIL_CLEAR_VALUE = 0x0B91;
public const uint STENCIL_FUNC = 0x0B92;
public const uint STENCIL_FAIL = 0x0B94;
public const uint STENCIL_PASS_DEPTH_FAIL = 0x0B95;
public const uint STENCIL_PASS_DEPTH_PASS = 0x0B96;
public const uint STENCIL_REF = 0x0B97;
public const uint STENCIL_VALUE_MASK = 0x0B93;
public const uint STENCIL_WRITEMASK = 0x0B98;
public const uint STENCIL_BACK_FUNC = 0x8800;
public const uint STENCIL_BACK_FAIL = 0x8801;
public const uint STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802;
public const uint STENCIL_BACK_PASS_DEPTH_PASS = 0x8803;
public const uint STENCIL_BACK_REF = 0x8CA3;
public const uint STENCIL_BACK_VALUE_MASK = 0x8CA4;
public const uint STENCIL_BACK_WRITEMASK = 0x8CA5;
public const uint VIEWPORT = 0x0BA2;
public const uint SCISSOR_BOX = 0x0C10;
public const uint COLOR_CLEAR_VALUE = 0x0C22;
public const uint COLOR_WRITEMASK = 0x0C23;
public const uint UNPACK_ALIGNMENT = 0x0CF5;
public const uint PACK_ALIGNMENT = 0x0D05;
public const uint MAX_TEXTURE_SIZE = 0x0D33;
public const uint MAX_VIEWPORT_DIMS = 0x0D3A;
public const uint SUBPIXEL_BITS = 0x0D50;
public const uint RED_BITS = 0x0D52;
public const uint GREEN_BITS = 0x0D53;
public const uint BLUE_BITS = 0x0D54;
public const uint ALPHA_BITS = 0x0D55;
public const uint DEPTH_BITS = 0x0D56;
public const uint STENCIL_BITS = 0x0D57;
public const uint POLYGON_OFFSET_UNITS = 0x2A00;
public const uint POLYGON_OFFSET_FACTOR = 0x8038;
public const uint TEXTURE_BINDING_2D = 0x8069;
public const uint SAMPLE_BUFFERS = 0x80A8;
public const uint SAMPLES = 0x80A9;
public const uint SAMPLE_COVERAGE_VALUE = 0x80AA;
public const uint SAMPLE_COVERAGE_INVERT = 0x80AB;
public const uint COMPRESSED_TEXTURE_FORMATS = 0x86A3;
public const uint DONT_CARE = 0x1100;
public const uint FASTEST = 0x1101;
public const uint NICEST = 0x1102;
public const uint GENERATE_MIPMAP_HINT = 0x8192;
public const uint BYTE = 0x1400;
public const uint UNSIGNED_BYTE = 0x1401;
public const uint SHORT = 0x1402;
public const uint UNSIGNED_SHORT = 0x1403;
public const uint INT = 0x1404;
public const uint UNSIGNED_INT = 0x1405;
public const uint FLOAT = 0x1406;
public const uint DEPTH_COMPONENT = 0x1902;
public const uint ALPHA = 0x1906;
public const uint RGB = 0x1907;
public const uint RGBA = 0x1908;
public const uint LUMINANCE = 0x1909;
public const uint LUMINANCE_ALPHA = 0x190A;
public const uint UNSIGNED_SHORT_4_4_4_4 = 0x8033;
public const uint UNSIGNED_SHORT_5_5_5_1 = 0x8034;
public const uint UNSIGNED_SHORT_5_6_5 = 0x8363;
public const uint FRAGMENT_SHADER = 0x8B30;
public const uint VERTEX_SHADER = 0x8B31;
public const uint MAX_VERTEX_ATTRIBS = 0x8869;
public const uint MAX_VERTEX_UNIFORM_VECTORS = 0x8DFB;
public const uint MAX_VARYING_VECTORS = 0x8DFC;
public const uint MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8B4D;
public const uint MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8B4C;
public const uint MAX_TEXTURE_IMAGE_UNITS = 0x8872;
public const uint MAX_FRAGMENT_UNIFORM_VECTORS = 0x8DFD;
public const uint SHADER_TYPE = 0x8B4F;
public const uint DELETE_STATUS = 0x8B80;
public const uint LINK_STATUS = 0x8B82;
public const uint VALIDATE_STATUS = 0x8B83;
public const uint ATTACHED_SHADERS = 0x8B85;
public const uint ACTIVE_UNIFORMS = 0x8B86;
public const uint ACTIVE_ATTRIBUTES = 0x8B89;
public const uint SHADING_LANGUAGE_VERSION = 0x8B8C;
public const uint CURRENT_PROGRAM = 0x8B8D;
public const uint NEVER = 0x0200;
public const uint LESS = 0x0201;
public const uint EQUAL = 0x0202;
public const uint LEQUAL = 0x0203;
public const uint GREATER = 0x0204;
public const uint NOTEQUAL = 0x0205;
public const uint GEQUAL = 0x0206;
public const uint ALWAYS = 0x0207;
public const uint KEEP = 0x1E00;
public const uint REPLACE = 0x1E01;
public const uint INCR = 0x1E02;
public const uint DECR = 0x1E03;
public const uint INVERT = 0x150A;
public const uint INCR_WRAP = 0x8507;
public const uint DECR_WRAP = 0x8508;
public const uint VENDOR = 0x1F00;
public const uint RENDERER = 0x1F01;
public const uint VERSION = 0x1F02;
public const uint NEAREST = 0x2600;
public const uint LINEAR = 0x2601;
public const uint NEAREST_MIPMAP_NEAREST = 0x2700;
public const uint LINEAR_MIPMAP_NEAREST = 0x2701;
public const uint NEAREST_MIPMAP_LINEAR = 0x2702;
public const uint LINEAR_MIPMAP_LINEAR = 0x2703;
public const uint TEXTURE_MAG_FILTER = 0x2800;
public const uint TEXTURE_MIN_FILTER = 0x2801;
public const uint TEXTURE_WRAP_S = 0x2802;
public const uint TEXTURE_WRAP_T = 0x2803;
public const uint TEXTURE_2D = 0x0DE1;
public const uint TEXTURE = 0x1702;
public const uint TEXTURE_CUBE_MAP = 0x8513;
public const uint TEXTURE_BINDING_CUBE_MAP = 0x8514;
public const uint TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515;
public const uint TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516;
public const uint TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517;
public const uint TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518;
public const uint TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519;
public const uint TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851A;
public const uint MAX_CUBE_MAP_TEXTURE_SIZE = 0x851C;
public const uint TEXTURE0 = 0x84C0;
public const uint TEXTURE1 = 0x84C1;
public const uint TEXTURE2 = 0x84C2;
public const uint TEXTURE3 = 0x84C3;
public const uint TEXTURE4 = 0x84C4;
public const uint TEXTURE5 = 0x84C5;
public const uint TEXTURE6 = 0x84C6;
public const uint TEXTURE7 = 0x84C7;
public const uint TEXTURE8 = 0x84C8;
public const uint TEXTURE9 = 0x84C9;
public const uint TEXTURE10 = 0x84CA;
public const uint TEXTURE11 = 0x84CB;
public const uint TEXTURE12 = 0x84CC;
public const uint TEXTURE13 = 0x84CD;
public const uint TEXTURE14 = 0x84CE;
public const uint TEXTURE15 = 0x84CF;
public const uint TEXTURE16 = 0x84D0;
public const uint TEXTURE17 = 0x84D1;
public const uint TEXTURE18 = 0x84D2;
public const uint TEXTURE19 = 0x84D3;
public const uint TEXTURE20 = 0x84D4;
public const uint TEXTURE21 = 0x84D5;
public const uint TEXTURE22 = 0x84D6;
public const uint TEXTURE23 = 0x84D7;
public const uint TEXTURE24 = 0x84D8;
public const uint TEXTURE25 = 0x84D9;
public const uint TEXTURE26 = 0x84DA;
public const uint TEXTURE27 = 0x84DB;
public const uint TEXTURE28 = 0x84DC;
public const uint TEXTURE29 = 0x84DD;
public const uint TEXTURE30 = 0x84DE;
public const uint TEXTURE31 = 0x84DF;
public const uint ACTIVE_TEXTURE = 0x84E0;
public const uint REPEAT = 0x2901;
public const uint CLAMP_TO_EDGE = 0x812F;
public const uint MIRRORED_REPEAT = 0x8370;
public const uint FLOAT_VEC2 = 0x8B50;
public const uint FLOAT_VEC3 = 0x8B51;
public const uint FLOAT_VEC4 = 0x8B52;
public const uint INT_VEC2 = 0x8B53;
public const uint INT_VEC3 = 0x8B54;
public const uint INT_VEC4 = 0x8B55;
public const uint BOOL = 0x8B56;
public const uint BOOL_VEC2 = 0x8B57;
public const uint BOOL_VEC3 = 0x8B58;
public const uint BOOL_VEC4 = 0x8B59;
public const uint FLOAT_MAT2 = 0x8B5A;
public const uint FLOAT_MAT3 = 0x8B5B;
public const uint FLOAT_MAT4 = 0x8B5C;
public const uint SAMPLER_2D = 0x8B5E;
public const uint SAMPLER_CUBE = 0x8B60;
public const uint VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622;
public const uint VERTEX_ATTRIB_ARRAY_SIZE = 0x8623;
public const uint VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624;
public const uint VERTEX_ATTRIB_ARRAY_TYPE = 0x8625;
public const uint VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886A;
public const uint VERTEX_ATTRIB_ARRAY_POINTER = 0x8645;
public const uint VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889F;
public const uint IMPLEMENTATION_COLOR_READ_TYPE = 0x8B9A;
public const uint IMPLEMENTATION_COLOR_READ_FORMAT = 0x8B9B;
public const uint COMPILE_STATUS = 0x8B81;
public const uint LOW_FLOAT = 0x8DF0;
public const uint MEDIUM_FLOAT = 0x8DF1;
public const uint HIGH_FLOAT = 0x8DF2;
public const uint LOW_INT = 0x8DF3;
public const uint MEDIUM_INT = 0x8DF4;
public const uint HIGH_INT = 0x8DF5;
public const uint FRAMEBUFFER = 0x8D40;
public const uint RENDERBUFFER = 0x8D41;
public const uint RGBA4 = 0x8056;
public const uint RGB5_A1 = 0x8057;
public const uint RGB565 = 0x8D62;
public const uint DEPTH_COMPONENT16 = 0x81A5;
public const uint STENCIL_INDEX = 0x1901;
public const uint STENCIL_INDEX8 = 0x8D48;
public const uint DEPTH_STENCIL = 0x84F9;
public const uint RENDERBUFFER_WIDTH = 0x8D42;
public const uint RENDERBUFFER_HEIGHT = 0x8D43;
public const uint RENDERBUFFER_INTERNAL_FORMAT = 0x8D44;
public const uint RENDERBUFFER_RED_SIZE = 0x8D50;
public const uint RENDERBUFFER_GREEN_SIZE = 0x8D51;
public const uint RENDERBUFFER_BLUE_SIZE = 0x8D52;
public const uint RENDERBUFFER_ALPHA_SIZE = 0x8D53;
public const uint RENDERBUFFER_DEPTH_SIZE = 0x8D54;
public const uint RENDERBUFFER_STENCIL_SIZE = 0x8D55;
public const uint FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8CD0;
public const uint FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8CD1;
public const uint FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8CD2;
public const uint FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8CD3;
public const uint COLOR_ATTACHMENT0 = 0x8CE0;
public const uint DEPTH_ATTACHMENT = 0x8D00;
public const uint STENCIL_ATTACHMENT = 0x8D20;
public const uint DEPTH_STENCIL_ATTACHMENT = 0x821A;
public const uint NONE = 0;
public const uint FRAMEBUFFER_COMPLETE = 0x8CD5;
public const uint FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8CD6;
public const uint FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8CD7;
public const uint FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 0x8CD9;
public const uint FRAMEBUFFER_UNSUPPORTED = 0x8CDD;
public const uint FRAMEBUFFER_BINDING = 0x8CA6;
public const uint RENDERBUFFER_BINDING = 0x8CA7;
public const uint MAX_RENDERBUFFER_SIZE = 0x84E8;
public const uint INVALID_FRAMEBUFFER_OPERATION = 0x0506;
public const uint UNPACK_FLIP_Y_WEBGL = 0x9240;
public const uint UNPACK_PREMULTIPLY_ALPHA_WEBGL = 0x9241;
public const uint CONTEXT_LOST_WEBGL = 0x9242;
public const uint UNPACK_COLORSPACE_CONVERSION_WEBGL = 0x9243;
public const uint BROWSER_DEFAULT_WEBGL = 0x9244;
// Desktop OpenGL
public const uint DOUBLE = 0x140A;
// WebGL 2
public const uint READ_BUFFER = 0x0C02;
public const uint UNPACK_ROW_LENGTH = 0x0CF2;
public const uint UNPACK_SKIP_ROWS = 0x0CF3;
public const uint UNPACK_SKIP_PIXELS = 0x0CF4;
public const uint PACK_ROW_LENGTH = 0x0D02;
public const uint PACK_SKIP_ROWS = 0x0D03;
public const uint PACK_SKIP_PIXELS = 0x0D04;
public const uint COLOR = 0x1800;
public const uint DEPTH = 0x1801;
public const uint STENCIL = 0x1802;
public const uint RED = 0x1903;
public const uint RGB8 = 0x8051;
public const uint RGBA8 = 0x8058;
public const uint RGB10_A2 = 0x8059;
public const uint TEXTURE_BINDING_3D = 0x806A;
public const uint UNPACK_SKIP_IMAGES = 0x806D;
public const uint UNPACK_IMAGE_HEIGHT = 0x806E;
public const uint TEXTURE_3D = 0x806F;
public const uint TEXTURE_WRAP_R = 0x8072;
public const uint MAX_3D_TEXTURE_SIZE = 0x8073;
public const uint UNSIGNED_INT_2_10_10_10_REV = 0x8368;
public const uint MAX_ELEMENTS_VERTICES = 0x80E8;
public const uint MAX_ELEMENTS_INDICES = 0x80E9;
public const uint TEXTURE_MIN_LOD = 0x813A;
public const uint TEXTURE_MAX_LOD = 0x813B;
public const uint TEXTURE_BASE_LEVEL = 0x813C;
public const uint TEXTURE_MAX_LEVEL = 0x813D;
public const uint MIN = 0x8007;
public const uint MAX = 0x8008;
public const uint DEPTH_COMPONENT24 = 0x81A6;
public const uint MAX_TEXTURE_LOD_BIAS = 0x84FD;
public const uint TEXTURE_COMPARE_MODE = 0x884C;
public const uint TEXTURE_COMPARE_FUNC = 0x884D;
public const uint CURRENT_QUERY = 0x8865;
public const uint QUERY_RESULT = 0x8866;
public const uint QUERY_RESULT_AVAILABLE = 0x8867;
public const uint STREAM_READ = 0x88E1;
public const uint STREAM_COPY = 0x88E2;
public const uint STATIC_READ = 0x88E5;
public const uint STATIC_COPY = 0x88E6;
public const uint DYNAMIC_READ = 0x88E9;
public const uint DYNAMIC_COPY = 0x88EA;
public const uint MAX_DRAW_BUFFERS = 0x8824;
public const uint DRAW_BUFFER0 = 0x8825;
public const uint DRAW_BUFFER1 = 0x8826;
public const uint DRAW_BUFFER2 = 0x8827;
public const uint DRAW_BUFFER3 = 0x8828;
public const uint DRAW_BUFFER4 = 0x8829;
public const uint DRAW_BUFFER5 = 0x882A;
public const uint DRAW_BUFFER6 = 0x882B;
public const uint DRAW_BUFFER7 = 0x882C;
public const uint DRAW_BUFFER8 = 0x882D;
public const uint DRAW_BUFFER9 = 0x882E;
public const uint DRAW_BUFFER10 = 0x882F;
public const uint DRAW_BUFFER11 = 0x8830;
public const uint DRAW_BUFFER12 = 0x8831;
public const uint DRAW_BUFFER13 = 0x8832;
public const uint DRAW_BUFFER14 = 0x8833;
public const uint DRAW_BUFFER15 = 0x8834;
public const uint MAX_FRAGMENT_UNIFORM_COMPONENTS = 0x8B49;
public const uint MAX_VERTEX_UNIFORM_COMPONENTS = 0x8B4A;
public const uint SAMPLER_3D = 0x8B5F;
public const uint SAMPLER_2D_SHADOW = 0x8B62;
public const uint FRAGMENT_SHADER_DERIVATIVE_HINT = 0x8B8B;
public const uint PIXEL_PACK_BUFFER = 0x88EB;
public const uint PIXEL_UNPACK_BUFFER = 0x88EC;
public const uint PIXEL_PACK_BUFFER_BINDING = 0x88ED;
public const uint PIXEL_UNPACK_BUFFER_BINDING = 0x88EF;
public const uint FLOAT_MAT2x3 = 0x8B65;
public const uint FLOAT_MAT2x4 = 0x8B66;
public const uint FLOAT_MAT3x2 = 0x8B67;
public const uint FLOAT_MAT3x4 = 0x8B68;
public const uint FLOAT_MAT4x2 = 0x8B69;
public const uint FLOAT_MAT4x3 = 0x8B6A;
public const uint SRGB = 0x8C40;
public const uint SRGB8 = 0x8C41;
public const uint SRGB8_ALPHA8 = 0x8C43;
public const uint COMPARE_REF_TO_TEXTURE = 0x884E;
public const uint RGBA32F = 0x8814;
public const uint RGB32F = 0x8815;
public const uint RGBA16F = 0x881A;
public const uint RGB16F = 0x881B;
public const uint VERTEX_ATTRIB_ARRAY_INTEGER = 0x88FD;
public const uint MAX_ARRAY_TEXTURE_LAYERS = 0x88FF;
public const uint MIN_PROGRAM_TEXEL_OFFSET = 0x8904;
public const uint MAX_PROGRAM_TEXEL_OFFSET = 0x8905;
public const uint MAX_VARYING_COMPONENTS = 0x8B4B;
public const uint TEXTURE_2D_ARRAY = 0x8C1A;
public const uint TEXTURE_BINDING_2D_ARRAY = 0x8C1D;
public const uint R11F_G11F_B10F = 0x8C3A;
public const uint UNSIGNED_INT_10F_11F_11F_REV = 0x8C3B;
public const uint RGB9_E5 = 0x8C3D;
public const uint UNSIGNED_INT_5_9_9_9_REV = 0x8C3E;
public const uint TRANSFORM_FEEDBACK_BUFFER_MODE = 0x8C7F;
public const uint MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS = 0x8C80;
public const uint TRANSFORM_FEEDBACK_VARYINGS = 0x8C83;
public const uint TRANSFORM_FEEDBACK_BUFFER_START = 0x8C84;
public const uint TRANSFORM_FEEDBACK_BUFFER_SIZE = 0x8C85;
public const uint TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN = 0x8C88;
public const uint RASTERIZER_DISCARD = 0x8C89;
public const uint MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS = 0x8C8A;
public const uint MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS = 0x8C8B;
public const uint INTERLEAVED_ATTRIBS = 0x8C8C;
public const uint SEPARATE_ATTRIBS = 0x8C8D;
public const uint TRANSFORM_FEEDBACK_BUFFER = 0x8C8E;
public const uint TRANSFORM_FEEDBACK_BUFFER_BINDING = 0x8C8F;
public const uint RGBA32UI = 0x8D70;
public const uint RGB32UI = 0x8D71;
public const uint RGBA16UI = 0x8D76;
public const uint RGB16UI = 0x8D77;
public const uint RGBA8UI = 0x8D7C;
public const uint RGB8UI = 0x8D7D;
public const uint RGBA32I = 0x8D82;
public const uint RGB32I = 0x8D83;
public const uint RGBA16I = 0x8D88;
public const uint RGB16I = 0x8D89;
public const uint RGBA8I = 0x8D8E;
public const uint RGB8I = 0x8D8F;
public const uint RED_INTEGER = 0x8D94;
public const uint RGB_INTEGER = 0x8D98;
public const uint RGBA_INTEGER = 0x8D99;
public const uint SAMPLER_2D_ARRAY = 0x8DC1;
public const uint SAMPLER_2D_ARRAY_SHADOW = 0x8DC4;
public const uint SAMPLER_CUBE_SHADOW = 0x8DC5;
public const uint UNSIGNED_INT_VEC2 = 0x8DC6;
public const uint UNSIGNED_INT_VEC3 = 0x8DC7;
public const uint UNSIGNED_INT_VEC4 = 0x8DC8;
public const uint INT_SAMPLER_2D = 0x8DCA;
public const uint INT_SAMPLER_3D = 0x8DCB;
public const uint INT_SAMPLER_CUBE = 0x8DCC;
public const uint INT_SAMPLER_2D_ARRAY = 0x8DCF;
public const uint UNSIGNED_INT_SAMPLER_2D = 0x8DD2;
public const uint UNSIGNED_INT_SAMPLER_3D = 0x8DD3;
public const uint UNSIGNED_INT_SAMPLER_CUBE = 0x8DD4;
public const uint UNSIGNED_INT_SAMPLER_2D_ARRAY = 0x8DD7;
public const uint DEPTH_COMPONENT32F = 0x8CAC;
public const uint DEPTH32F_STENCIL8 = 0x8CAD;
public const uint FLOAT_32_UNSIGNED_INT_24_8_REV = 0x8DAD;
public const uint FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING = 0x8210;
public const uint FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE = 0x8211;
public const uint FRAMEBUFFER_ATTACHMENT_RED_SIZE = 0x8212;
public const uint FRAMEBUFFER_ATTACHMENT_GREEN_SIZE = 0x8213;
public const uint FRAMEBUFFER_ATTACHMENT_BLUE_SIZE = 0x8214;
public const uint FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE = 0x8215;
public const uint FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE = 0x8216;
public const uint FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE = 0x8217;
public const uint FRAMEBUFFER_DEFAULT = 0x8218;
public const uint UNSIGNED_INT_24_8 = 0x84FA;
public const uint DEPTH24_STENCIL8 = 0x88F0;
public const uint UNSIGNED_NORMALIZED = 0x8C17;
public const uint DRAW_FRAMEBUFFER_BINDING = 0x8CA6; // Same as FRAMEBUFFER_BINDING
public const uint READ_FRAMEBUFFER = 0x8CA8;
public const uint DRAW_FRAMEBUFFER = 0x8CA9;
public const uint READ_FRAMEBUFFER_BINDING = 0x8CAA;
public const uint RENDERBUFFER_SAMPLES = 0x8CAB;
public const uint FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER = 0x8CD4;
public const uint MAX_COLOR_ATTACHMENTS = 0x8CDF;
public const uint COLOR_ATTACHMENT1 = 0x8CE1;
public const uint COLOR_ATTACHMENT2 = 0x8CE2;
public const uint COLOR_ATTACHMENT3 = 0x8CE3;
public const uint COLOR_ATTACHMENT4 = 0x8CE4;
public const uint COLOR_ATTACHMENT5 = 0x8CE5;
public const uint COLOR_ATTACHMENT6 = 0x8CE6;
public const uint COLOR_ATTACHMENT7 = 0x8CE7;
public const uint COLOR_ATTACHMENT8 = 0x8CE8;
public const uint COLOR_ATTACHMENT9 = 0x8CE9;
public const uint COLOR_ATTACHMENT10 = 0x8CEA;
public const uint COLOR_ATTACHMENT11 = 0x8CEB;
public const uint COLOR_ATTACHMENT12 = 0x8CEC;
public const uint COLOR_ATTACHMENT13 = 0x8CED;
public const uint COLOR_ATTACHMENT14 = 0x8CEE;
public const uint COLOR_ATTACHMENT15 = 0x8CEF;
public const uint FRAMEBUFFER_INCOMPLETE_MULTISAMPLE = 0x8D56;
public const uint MAX_SAMPLES = 0x8D57;
public const uint HALF_FLOAT = 0x140B;
public const uint RG = 0x8227;
public const uint RG_INTEGER = 0x8228;
public const uint R8 = 0x8229;
public const uint RG8 = 0x822B;
public const uint R16F = 0x822D;
public const uint R32F = 0x822E;
public const uint RG16F = 0x822F;
public const uint RG32F = 0x8230;
public const uint R8I = 0x8231;
public const uint R8UI = 0x8232;
public const uint R16I = 0x8233;
public const uint R16UI = 0x8234;
public const uint R32I = 0x8235;
public const uint R32UI = 0x8236;
public const uint RG8I = 0x8237;
public const uint RG8UI = 0x8238;
public const uint RG16I = 0x8239;
public const uint RG16UI = 0x823A;
public const uint RG32I = 0x823B;
public const uint RG32UI = 0x823C;
public const uint VERTEX_ARRAY_BINDING = 0x85B5;
public const uint R8_SNORM = 0x8F94;
public const uint RG8_SNORM = 0x8F95;
public const uint RGB8_SNORM = 0x8F96;
public const uint RGBA8_SNORM = 0x8F97;
public const uint SIGNED_NORMALIZED = 0x8F9C;
public const uint COPY_READ_BUFFER = 0x8F36;
public const uint COPY_WRITE_BUFFER = 0x8F37;
public const uint COPY_READ_BUFFER_BINDING = 0x8F36; // Same as COPY_READ_BUFFER
public const uint COPY_WRITE_BUFFER_BINDING = 0x8F37; // Same as COPY_WRITE_BUFFER
public const uint UNIFORM_BUFFER = 0x8A11;
public const uint UNIFORM_BUFFER_BINDING = 0x8A28;
public const uint UNIFORM_BUFFER_START = 0x8A29;
public const uint UNIFORM_BUFFER_SIZE = 0x8A2A;
public const uint MAX_VERTEX_UNIFORM_BLOCKS = 0x8A2B;
public const uint MAX_FRAGMENT_UNIFORM_BLOCKS = 0x8A2D;
public const uint MAX_COMBINED_UNIFORM_BLOCKS = 0x8A2E;
public const uint MAX_UNIFORM_BUFFER_BINDINGS = 0x8A2F;
public const uint MAX_UNIFORM_BLOCK_SIZE = 0x8A30;
public const uint MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS = 0x8A31;
public const uint MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS = 0x8A33;
public const uint UNIFORM_BUFFER_OFFSET_ALIGNMENT = 0x8A34;
public const uint ACTIVE_UNIFORM_BLOCKS = 0x8A36;
public const uint UNIFORM_TYPE = 0x8A37;
public const uint UNIFORM_SIZE = 0x8A38;
public const uint UNIFORM_BLOCK_INDEX = 0x8A3A;
public const uint UNIFORM_OFFSET = 0x8A3B;
public const uint UNIFORM_ARRAY_STRIDE = 0x8A3C;
public const uint UNIFORM_MATRIX_STRIDE = 0x8A3D;
public const uint UNIFORM_IS_ROW_MAJOR = 0x8A3E;
public const uint UNIFORM_BLOCK_BINDING = 0x8A3F;
public const uint UNIFORM_BLOCK_DATA_SIZE = 0x8A40;
public const uint UNIFORM_BLOCK_ACTIVE_UNIFORMS = 0x8A42;
public const uint UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES = 0x8A43;
public const uint UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER = 0x8A44;
public const uint UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER = 0x8A46;
public const uint INVALID_INDEX = 0xFFFFFFFF;
public const uint MAX_VERTEX_OUTPUT_COMPONENTS = 0x9122;
public const uint MAX_FRAGMENT_INPUT_COMPONENTS = 0x9125;
public const uint MAX_SERVER_WAIT_TIMEOUT = 0x9111;
public const uint OBJECT_TYPE = 0x9112;
public const uint SYNC_CONDITION = 0x9113;
public const uint SYNC_STATUS = 0x9114;
public const uint SYNC_FLAGS = 0x9115;
public const uint SYNC_FENCE = 0x9116;
public const uint SYNC_GPU_COMMANDS_COMPLETE = 0x9117;
public const uint UNSIGNALED = 0x9118;
public const uint SIGNALED = 0x9119;
public const uint ALREADY_SIGNALED = 0x911A;
public const uint TIMEOUT_EXPIRED = 0x911B;
public const uint CONDITION_SATISFIED = 0x911C;
public const uint WAIT_FAILED = 0x911D;
public const uint SYNC_FLUSH_COMMANDS_BIT = 0x00000001;
public const uint VERTEX_ATTRIB_ARRAY_DIVISOR = 0x88FE;
public const uint ANY_SAMPLES_PASSED = 0x8C2F;
public const uint ANY_SAMPLES_PASSED_CONSERVATIVE = 0x8D6A;
public const uint SAMPLER_BINDING = 0x8919;
public const uint RGB10_A2UI = 0x906F;
public const uint INT_2_10_10_10_REV = 0x8D9F;
public const uint TRANSFORM_FEEDBACK = 0x8E22;
public const uint TRANSFORM_FEEDBACK_PAUSED = 0x8E23;
public const uint TRANSFORM_FEEDBACK_ACTIVE = 0x8E24;
public const uint TRANSFORM_FEEDBACK_BINDING = 0x8E25;
public const uint COMPRESSED_R11_EAC = 0x9270;
public const uint COMPRESSED_SIGNED_R11_EAC = 0x9271;
public const uint COMPRESSED_RG11_EAC = 0x9272;
public const uint COMPRESSED_SIGNED_RG11_EAC = 0x9273;
public const uint COMPRESSED_RGB8_ETC2 = 0x9274;
public const uint COMPRESSED_SRGB8_ETC2 = 0x9275;
public const uint COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9276;
public const uint COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9277;
public const uint COMPRESSED_RGBA8_ETC2_EAC = 0x9278;
public const uint COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 0x9279;
public const uint TEXTURE_IMMUTABLE_FORMAT = 0x912F;
public const uint MAX_ELEMENT_INDEX = 0x8D6B;
public const uint TEXTURE_IMMUTABLE_LEVELS = 0x82DF;
}
}
| |
// ****************************************************************
// Copyright 2007, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org.
// ****************************************************************
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Diagnostics;
using System.Globalization;
using System.Security.Principal;
using System.Threading;
namespace NUnit.Core
{
/// <summary>
/// Helper class used to save and restore certain static or
/// singleton settings in the environment that affect tests
/// or which might be changed by the user tests.
///
/// An internal class is used to hold settings and a stack
/// of these objects is pushed and popped as Save and Restore
/// are called.
///
/// Static methods for each setting forward to the internal
/// object on the top of the stack.
/// </summary>
public class TestExecutionContext
{
#region Static Fields
/// <summary>
/// The current context, head of the list of saved contexts.
/// </summary>
private static TestExecutionContext current = new TestExecutionContext();
#endregion
#region Instance Fields
/// <summary>
/// Indicates whether trace is enabled
/// </summary>
private bool tracing;
/// <summary>
/// Indicates whether logging is enabled
/// </summary>
private bool logging;
/// <summary>
/// Destination for standard output
/// </summary>
private TextWriter outWriter;
/// <summary>
/// Destination for standard error
/// </summary>
private TextWriter errorWriter;
/// <summary>
/// Destination for Trace output
/// </summary>
private TextWriter traceWriter;
/// <summary>
/// Default timeout for test cases
/// </summary>
private int testCaseTimeout;
private Log4NetCapture logCapture;
/// <summary>
/// The current working directory
/// </summary>
private string currentDirectory;
/// <summary>
/// The current culture
/// </summary>
private CultureInfo currentCulture;
/// <summary>
/// The current UI culture
/// </summary>
private CultureInfo currentUICulture;
/// <summary>
/// The current Principal.
/// </summary>
private IPrincipal currentPrincipal;
/// <summary>
/// The currently executing test
/// </summary>
private Test currentTest;
/// <summary>
/// The active TestResult for the current test
/// </summary>
private TestResult currentResult;
/// <summary>
/// Link to a prior saved context
/// </summary>
public TestExecutionContext prior;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="TestExecutionContext"/> class.
/// </summary>
public TestExecutionContext()
{
this.prior = null;
this.tracing = false;
this.logging = false;
this.outWriter = Console.Out;
this.errorWriter = Console.Error;
this.traceWriter = null;
this.logCapture = new Log4NetCapture();
this.testCaseTimeout = 0;
this.currentDirectory = Environment.CurrentDirectory;
this.currentCulture = CultureInfo.CurrentCulture;
this.currentUICulture = CultureInfo.CurrentUICulture;
this.currentPrincipal = Thread.CurrentPrincipal;
}
/// <summary>
/// Initializes a new instance of the <see cref="TestExecutionContext"/> class.
/// </summary>
/// <param name="other">An existing instance of TestExecutionContext.</param>
public TestExecutionContext(TestExecutionContext other)
{
this.prior = other;
this.tracing = other.tracing;
this.logging = other.logging;
this.outWriter = other.outWriter;
this.errorWriter = other.errorWriter;
this.traceWriter = other.traceWriter;
this.logCapture = other.logCapture;
this.testCaseTimeout = other.testCaseTimeout;
this.currentTest = other.currentTest;
this.currentResult = other.currentResult;
this.currentDirectory = Environment.CurrentDirectory;
this.currentCulture = CultureInfo.CurrentCulture;
this.currentUICulture = CultureInfo.CurrentUICulture;
this.currentPrincipal = Thread.CurrentPrincipal;
}
#endregion
#region Static Singleton Instance
/// <summary>
/// Gets the current context.
/// </summary>
/// <value>The current context.</value>
public static TestExecutionContext CurrentContext
{
get { return current; }
}
#endregion
#region Properties
/// <summary>
/// Controls whether trace and debug output are written
/// to the standard output.
/// </summary>
public bool Tracing
{
get { return tracing; }
set
{
if (tracing != value)
{
if (traceWriter != null && tracing)
StopTracing();
tracing = value;
if (traceWriter != null && tracing)
StartTracing();
}
}
}
/// <summary>
/// Controls whether log output is captured
/// </summary>
public bool Logging
{
get { return logCapture.Enabled; }
set { logCapture.Enabled = value; }
}
/// <summary>
/// Controls where Console.Out is directed
/// </summary>
public TextWriter Out
{
get { return outWriter; }
set
{
if (outWriter != value)
{
outWriter = value;
Console.Out.Flush();
Console.SetOut(outWriter);
}
}
}
/// <summary>
/// Controls where Console.Error is directed
/// </summary>
public TextWriter Error
{
get { return errorWriter; }
set
{
if (errorWriter != value)
{
errorWriter = value;
Console.Error.Flush();
Console.SetError(errorWriter);
}
}
}
/// <summary>
/// Controls where Trace output is directed
/// </summary>
public TextWriter TraceWriter
{
get { return traceWriter; }
set
{
if (traceWriter != value)
{
if (traceWriter != null && tracing)
StopTracing();
traceWriter = value;
if (traceWriter != null && tracing)
StartTracing();
}
}
}
/// <summary>
/// Gets or sets the Log writer, which is actually held by a log4net
/// TextWriterAppender. When first set, the appender will be created
/// and will thereafter send any log events to the writer.
///
/// In normal operation, LogWriter is set to an EventListenerTextWriter
/// connected to the EventQueue in the test domain. The events are
/// subsequently captured in the Gui an the output displayed in
/// the Log tab. The application under test does not need to define
/// any additional appenders.
/// </summary>
public TextWriter LogWriter
{
get { return logCapture.Writer; }
set { logCapture.Writer = value; }
}
private void StopTracing()
{
traceWriter.Close();
System.Diagnostics.Trace.Listeners.Remove("NUnit");
}
private void StartTracing()
{
System.Diagnostics.Trace.Listeners.Add(new TextWriterTraceListener(traceWriter, "NUnit"));
}
/// <summary>
/// Saves and restores the CurrentDirectory
/// </summary>
public string CurrentDirectory
{
get { return currentDirectory; }
set
{
currentDirectory = value;
Environment.CurrentDirectory = currentDirectory;
}
}
/// <summary>
/// Saves or restores the CurrentCulture
/// </summary>
public CultureInfo CurrentCulture
{
get { return currentCulture; }
set
{
currentCulture = value;
Thread.CurrentThread.CurrentCulture = currentCulture;
}
}
/// <summary>
/// Saves or restores the CurrentUICulture
/// </summary>
public CultureInfo CurrentUICulture
{
get { return currentUICulture; }
set
{
currentUICulture = value;
Thread.CurrentThread.CurrentUICulture = currentUICulture;
}
}
/// <summary>
/// Gets or sets the current <see cref="IPrincipal"/> for the Thread.
/// </summary>
public IPrincipal CurrentPrincipal
{
get { return this.currentPrincipal; }
set
{
this.currentPrincipal = value;
Thread.CurrentPrincipal = this.currentPrincipal;
}
}
/// <summary>
/// Gets or sets the test case timeout vaue
/// </summary>
public int TestCaseTimeout
{
get { return testCaseTimeout; }
set { testCaseTimeout = value; }
}
/// <summary>
/// Gets or sets the current test
/// </summary>
public Test CurrentTest
{
get { return currentTest; }
set { currentTest = value; }
}
/// <summary>
/// Gets or sets the current test result
/// </summary>
public TestResult CurrentResult
{
get { return currentResult; }
set { currentResult = value; }
}
#endregion
#region Static Methods
/// <summary>
/// Saves the old context and makes a fresh one
/// current without changing any settings.
/// </summary>
public static void Save()
{
TestExecutionContext.current = new TestExecutionContext(current);
}
/// <summary>
/// Restores the last saved context and puts
/// any saved settings back into effect.
/// </summary>
public static void Restore()
{
current.ReverseChanges();
current = current.prior;
}
#endregion
#region Instance Methods
/// <summary>
/// Used to restore settings to their prior
/// values before reverting to a prior context.
/// </summary>
public void ReverseChanges()
{
if (prior == null)
throw new InvalidOperationException("TestContext: too many Restores");
this.Tracing = prior.Tracing;
this.Out = prior.Out;
this.Error = prior.Error;
this.CurrentDirectory = prior.CurrentDirectory;
this.CurrentCulture = prior.CurrentCulture;
this.CurrentUICulture = prior.CurrentUICulture;
this.TestCaseTimeout = prior.TestCaseTimeout;
this.CurrentPrincipal = prior.CurrentPrincipal;
}
/// <summary>
/// Record any changed values in the current context
/// </summary>
public void Update()
{
this.currentDirectory = Environment.CurrentDirectory;
this.currentCulture = CultureInfo.CurrentCulture;
this.currentUICulture = CultureInfo.CurrentUICulture;
this.currentPrincipal = System.Threading.Thread.CurrentPrincipal;
}
#endregion
}
}
| |
using System.Collections;
using System.Collections.Generic;
using System.Text;
public struct NodePosition
{
public int x;
public int y;
public NodePosition(int x, int y)
{
this.x = x;
this.y = y;
}
}
public class Path : List<NodePosition>
{
public override string ToString()
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < Count; ++i)
{
sb.Append(string.Format("Node {0}: {1}, {2}", i, this[i].x, this[i].y));
if (i < Count - 1)
{
sb.Append(" - ");
}
}
return sb.ToString();
}
}
public class Map
{
const int MAP_WIDTH = 20;
const int MAP_HEIGHT = 20;
static int[] map = new int[MAP_WIDTH * MAP_HEIGHT]
{
// 0001020304050607080910111213141516171819
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 00
1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,1, // 01
1,9,9,1,1,9,9,9,1,9,1,9,1,9,1,9,9,9,1,1, // 02
1,9,9,1,1,9,9,9,1,9,1,9,1,9,1,9,9,9,1,1, // 03
1,9,1,1,1,1,9,9,1,9,1,9,1,1,1,1,9,9,1,1, // 04
1,9,1,1,9,1,1,1,1,9,1,1,1,1,9,1,1,1,1,1, // 05
1,9,9,9,9,1,1,1,1,1,1,9,9,9,9,1,1,1,1,1, // 06
1,9,9,9,9,9,9,9,9,1,1,1,9,9,9,9,9,9,9,1, // 07
1,9,1,1,1,1,1,1,1,1,1,9,1,1,1,1,1,1,1,1, // 08
1,9,1,9,9,9,9,9,9,9,1,1,9,9,9,9,9,9,9,1, // 09
1,9,1,1,1,1,9,1,1,9,1,1,1,1,1,1,1,1,1,1, // 10
1,9,9,9,9,9,1,9,1,9,1,9,9,9,9,9,1,1,1,1, // 11
1,9,1,9,1,9,9,9,1,9,1,9,1,9,1,9,9,9,1,1, // 12
1,9,1,9,1,9,9,9,1,9,1,9,1,9,1,9,9,9,1,1, // 13
1,9,1,1,1,1,9,9,1,9,1,9,1,1,1,1,9,9,1,1, // 14
1,9,1,1,9,1,1,1,1,9,1,1,1,1,9,1,1,1,1,1, // 15
1,9,9,9,9,1,1,1,1,1,1,9,9,9,9,1,1,1,1,1, // 16
1,1,9,9,9,9,9,9,9,1,1,1,9,9,9,1,9,9,9,9, // 17
1,9,1,1,1,1,1,1,1,1,1,9,1,1,1,1,1,1,1,1, // 18
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 19
};
public static int GetMap(int x, int y)
{
if (x < 0 || x >= MAP_WIDTH || y < 0 || y >= MAP_HEIGHT)
{
return 9;
}
return map[(y * MAP_WIDTH) + x];
}
}
public class MapSearchNode
{
public NodePosition position;
AStarPathfinder pathfinder = null;
public MapSearchNode(AStarPathfinder _pathfinder)
{
position = new NodePosition(0, 0);
pathfinder = _pathfinder;
}
public MapSearchNode(NodePosition pos, AStarPathfinder _pathfinder)
{
position = new NodePosition(pos.x, pos.y);
pathfinder = _pathfinder;
}
// Here's the heuristic function that estimates the distance from a Node
// to the Goal.
public float GoalDistanceEstimate(MapSearchNode nodeGoal)
{
double X = (double)position.x - (double)nodeGoal.position.x;
double Y = (double)position.y - (double)nodeGoal.position.y;
return ((float)System.Math.Sqrt((X * X) + (Y * Y)));
}
public bool IsGoal(MapSearchNode nodeGoal)
{
return (position.x == nodeGoal.position.x && position.y == nodeGoal.position.y);
}
public bool ValidNeigbour(int xOffset, int yOffset)
{
// Return true if the node is navigable and within grid bounds
return (Map.GetMap(position.x + xOffset, position.y + yOffset) < 9);
}
void AddNeighbourNode(int xOffset, int yOffset, NodePosition parentPos, AStarPathfinder aStarSearch)
{
if (ValidNeigbour(xOffset, yOffset) &&
!(parentPos.x == position.x + xOffset && parentPos.y == position.y + yOffset))
{
NodePosition neighbourPos = new NodePosition(position.x + xOffset, position.y + yOffset);
MapSearchNode newNode = pathfinder.AllocateMapSearchNode(neighbourPos);
aStarSearch.AddSuccessor(newNode);
}
}
// This generates the successors to the given Node. It uses a helper function called
// AddSuccessor to give the successors to the AStar class. The A* specific initialisation
// is done for each node internally, so here you just set the state information that
// is specific to the application
public bool GetSuccessors(AStarPathfinder aStarSearch, MapSearchNode parentNode)
{
NodePosition parentPos = new NodePosition(0, 0);
if (parentNode != null)
{
parentPos = parentNode.position;
}
// push each possible move except allowing the search to go backwards
AddNeighbourNode(-1, 0, parentPos, aStarSearch);
AddNeighbourNode( 0, -1, parentPos, aStarSearch);
AddNeighbourNode( 1, 0, parentPos, aStarSearch);
AddNeighbourNode( 0, 1, parentPos, aStarSearch);
return true;
}
// given this node, what does it cost to move to successor. In the case
// of our map the answer is the map terrain value at this node since that is
// conceptually where we're moving
public float GetCost(MapSearchNode successor)
{
// Implementation specific
return Map.GetMap(successor.position.x, successor.position.y);
}
public bool IsSameState(MapSearchNode rhs)
{
return (position.x == rhs.position.x &&
position.y == rhs.position.y);
}
}
public class AStarExample
{
static void Main()
{
AStarPathfinder pathfinder = new AStarPathfinder();
Pathfind(new NodePosition(0, 0), new NodePosition(2, 4), pathfinder);
}
static bool Pathfind(NodePosition startPos, NodePosition goalPos, AStarPathfinder pathfinder)
{
// Reset the allocated MapSearchNode pointer
pathfinder.InitiatePathfind();
// Create a start state
MapSearchNode nodeStart = pathfinder.AllocateMapSearchNode(startPos);
// Define the goal state
MapSearchNode nodeEnd = pathfinder.AllocateMapSearchNode(goalPos);
// Set Start and goal states
pathfinder.SetStartAndGoalStates(nodeStart, nodeEnd);
// Set state to Searching and perform the search
AStarPathfinder.SearchState searchState = AStarPathfinder.SearchState.Searching;
uint searchSteps = 0;
do
{
searchState = pathfinder.SearchStep();
searchSteps++;
}
while (searchState == AStarPathfinder.SearchState.Searching);
// Search complete
bool pathfindSucceeded = (searchState == AStarPathfinder.SearchState.Succeeded);
if (pathfindSucceeded)
{
// Success
Path newPath = new Path();
int numSolutionNodes = 0; // Don't count the starting cell in the path length
// Get the start node
MapSearchNode node = pathfinder.GetSolutionStart();
newPath.Add(node.position);
++numSolutionNodes;
// Get all remaining solution nodes
for( ;; )
{
node = pathfinder.GetSolutionNext();
if( node == null )
{
break;
}
++numSolutionNodes;
newPath.Add(node.position);
};
// Once you're done with the solution we can free the nodes up
pathfinder.FreeSolutionNodes();
System.Console.WriteLine("Solution path length: " + numSolutionNodes);
System.Console.WriteLine("Solution: " + newPath.ToString());
}
else if (searchState == AStarPathfinder.SearchState.Failed)
{
// FAILED, no path to goal
System.Console.WriteLine("Pathfind FAILED!");
}
return pathfindSucceeded;
}
}
| |
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Index.Extensions;
using Lucene.Net.Util;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Assert = Lucene.Net.TestFramework.Assert;
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 DefaultSimilarity = Lucene.Net.Search.Similarities.DefaultSimilarity;
using Directory = Lucene.Net.Store.Directory;
using OpenMode = Lucene.Net.Index.OpenMode;
/// <summary>
/// Tests <seealso cref="PhraseQuery"/>.
/// </summary>
/// <seealso cref= TestPositionIncrement </seealso>
/*
* Remove ThreadLeaks and run with (Eclipse or command line):
* -ea -Drt.seed=AFD1E7E84B35D2B1
* to get leaked thread errors.
*/
[TestFixture]
public class TestPhraseQuery : LuceneTestCase
{
/// <summary>
/// threshold for comparing floats </summary>
public const float SCORE_COMP_THRESH = 1e-6f;
private static IndexSearcher searcher;
private static IndexReader reader;
private PhraseQuery query;
private static Directory directory;
[OneTimeSetUp]
public override void BeforeClass()
{
base.BeforeClass();
directory = NewDirectory();
Analyzer analyzer = new AnalyzerAnonymousInnerClassHelper();
RandomIndexWriter writer = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, directory, analyzer);
Documents.Document doc = new Documents.Document();
doc.Add(NewTextField("field", "one two three four five", Field.Store.YES));
doc.Add(NewTextField("repeated", "this is a repeated field - first part", Field.Store.YES));
IIndexableField repeatedField = NewTextField("repeated", "second part of a repeated field", Field.Store.YES);
doc.Add(repeatedField);
doc.Add(NewTextField("palindrome", "one two three two one", Field.Store.YES));
writer.AddDocument(doc);
doc = new Documents.Document();
doc.Add(NewTextField("nonexist", "phrase exist notexist exist found", Field.Store.YES));
writer.AddDocument(doc);
doc = new Documents.Document();
doc.Add(NewTextField("nonexist", "phrase exist notexist exist found", Field.Store.YES));
writer.AddDocument(doc);
reader = writer.GetReader();
writer.Dispose();
searcher = NewSearcher(reader);
}
private class AnalyzerAnonymousInnerClassHelper : Analyzer
{
public AnalyzerAnonymousInnerClassHelper()
{
}
protected internal override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
return new TokenStreamComponents(new MockTokenizer(reader, MockTokenizer.WHITESPACE, false));
}
public override int GetPositionIncrementGap(string fieldName)
{
return 100;
}
}
[SetUp]
public override void SetUp()
{
base.SetUp();
query = new PhraseQuery();
}
[OneTimeTearDown]
public override void AfterClass()
{
searcher = null;
reader.Dispose();
reader = null;
directory.Dispose();
directory = null;
base.AfterClass();
}
[Test]
public virtual void TestNotCloseEnough()
{
query.Slop = 2;
query.Add(new Term("field", "one"));
query.Add(new Term("field", "five"));
ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(0, hits.Length);
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
}
[Test]
public virtual void TestBarelyCloseEnough()
{
query.Slop = 3;
query.Add(new Term("field", "one"));
query.Add(new Term("field", "five"));
ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length);
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
}
/// <summary>
/// Ensures slop of 0 works for exact matches, but not reversed
/// </summary>
[Test]
public virtual void TestExact()
{
// slop is zero by default
query.Add(new Term("field", "four"));
query.Add(new Term("field", "five"));
ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length, "exact match");
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
query = new PhraseQuery();
query.Add(new Term("field", "two"));
query.Add(new Term("field", "one"));
hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(0, hits.Length, "reverse not exact");
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
}
[Test]
public virtual void TestSlop1()
{
// Ensures slop of 1 works with terms in order.
query.Slop = 1;
query.Add(new Term("field", "one"));
query.Add(new Term("field", "two"));
ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length, "in order");
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
// Ensures slop of 1 does not work for phrases out of order;
// must be at least 2.
query = new PhraseQuery();
query.Slop = 1;
query.Add(new Term("field", "two"));
query.Add(new Term("field", "one"));
hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(0, hits.Length, "reversed, slop not 2 or more");
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
}
/// <summary>
/// As long as slop is at least 2, terms can be reversed
/// </summary>
[Test]
public virtual void TestOrderDoesntMatter()
{
query.Slop = 2; // must be at least two for reverse order match
query.Add(new Term("field", "two"));
query.Add(new Term("field", "one"));
ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length, "just sloppy enough");
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
query = new PhraseQuery();
query.Slop = 2;
query.Add(new Term("field", "three"));
query.Add(new Term("field", "one"));
hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(0, hits.Length, "not sloppy enough");
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
}
/// <summary>
/// slop is the total number of positional moves allowed
/// to line up a phrase
/// </summary>
[Test]
public virtual void TestMulipleTerms()
{
query.Slop = 2;
query.Add(new Term("field", "one"));
query.Add(new Term("field", "three"));
query.Add(new Term("field", "five"));
ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length, "two total moves");
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
query = new PhraseQuery();
query.Slop = 5; // it takes six moves to match this phrase
query.Add(new Term("field", "five"));
query.Add(new Term("field", "three"));
query.Add(new Term("field", "one"));
hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(0, hits.Length, "slop of 5 not close enough");
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
query.Slop = 6;
hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length, "slop of 6 just right");
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
}
[Test]
public virtual void TestPhraseQueryWithStopAnalyzer()
{
Directory directory = NewDirectory();
Analyzer stopAnalyzer = new MockAnalyzer(Random, MockTokenizer.SIMPLE, true, MockTokenFilter.ENGLISH_STOPSET);
RandomIndexWriter writer = new RandomIndexWriter(Random, directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, stopAnalyzer));
Documents.Document doc = new Documents.Document();
doc.Add(NewTextField("field", "the stop words are here", Field.Store.YES));
writer.AddDocument(doc);
IndexReader reader = writer.GetReader();
writer.Dispose();
IndexSearcher searcher = NewSearcher(reader);
// valid exact phrase query
PhraseQuery query = new PhraseQuery();
query.Add(new Term("field", "stop"));
query.Add(new Term("field", "words"));
ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length);
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
reader.Dispose();
directory.Dispose();
}
[Test]
public virtual void TestPhraseQueryInConjunctionScorer()
{
Directory directory = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, directory);
Documents.Document doc = new Documents.Document();
doc.Add(NewTextField("source", "marketing info", Field.Store.YES));
writer.AddDocument(doc);
doc = new Documents.Document();
doc.Add(NewTextField("contents", "foobar", Field.Store.YES));
doc.Add(NewTextField("source", "marketing info", Field.Store.YES));
writer.AddDocument(doc);
IndexReader reader = writer.GetReader();
writer.Dispose();
IndexSearcher searcher = NewSearcher(reader);
PhraseQuery phraseQuery = new PhraseQuery();
phraseQuery.Add(new Term("source", "marketing"));
phraseQuery.Add(new Term("source", "info"));
ScoreDoc[] hits = searcher.Search(phraseQuery, null, 1000).ScoreDocs;
Assert.AreEqual(2, hits.Length);
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, phraseQuery, searcher);
TermQuery termQuery = new TermQuery(new Term("contents", "foobar"));
BooleanQuery booleanQuery = new BooleanQuery();
booleanQuery.Add(termQuery, Occur.MUST);
booleanQuery.Add(phraseQuery, Occur.MUST);
hits = searcher.Search(booleanQuery, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length);
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, termQuery, searcher);
reader.Dispose();
writer = new RandomIndexWriter(Random, directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetOpenMode(OpenMode.CREATE));
doc = new Documents.Document();
doc.Add(NewTextField("contents", "map entry woo", Field.Store.YES));
writer.AddDocument(doc);
doc = new Documents.Document();
doc.Add(NewTextField("contents", "woo map entry", Field.Store.YES));
writer.AddDocument(doc);
doc = new Documents.Document();
doc.Add(NewTextField("contents", "map foobarword entry woo", Field.Store.YES));
writer.AddDocument(doc);
reader = writer.GetReader();
writer.Dispose();
searcher = NewSearcher(reader);
termQuery = new TermQuery(new Term("contents", "woo"));
phraseQuery = new PhraseQuery();
phraseQuery.Add(new Term("contents", "map"));
phraseQuery.Add(new Term("contents", "entry"));
hits = searcher.Search(termQuery, null, 1000).ScoreDocs;
Assert.AreEqual(3, hits.Length);
hits = searcher.Search(phraseQuery, null, 1000).ScoreDocs;
Assert.AreEqual(2, hits.Length);
booleanQuery = new BooleanQuery();
booleanQuery.Add(termQuery, Occur.MUST);
booleanQuery.Add(phraseQuery, Occur.MUST);
hits = searcher.Search(booleanQuery, null, 1000).ScoreDocs;
Assert.AreEqual(2, hits.Length);
booleanQuery = new BooleanQuery();
booleanQuery.Add(phraseQuery, Occur.MUST);
booleanQuery.Add(termQuery, Occur.MUST);
hits = searcher.Search(booleanQuery, null, 1000).ScoreDocs;
Assert.AreEqual(2, hits.Length);
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, booleanQuery, searcher);
reader.Dispose();
directory.Dispose();
}
[Test]
public virtual void TestSlopScoring()
{
Directory directory = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random, directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMergePolicy(NewLogMergePolicy()).SetSimilarity(new DefaultSimilarity()));
Documents.Document doc = new Documents.Document();
doc.Add(NewTextField("field", "foo firstname lastname foo", Field.Store.YES));
writer.AddDocument(doc);
Documents.Document doc2 = new Documents.Document();
doc2.Add(NewTextField("field", "foo firstname zzz lastname foo", Field.Store.YES));
writer.AddDocument(doc2);
Documents.Document doc3 = new Documents.Document();
doc3.Add(NewTextField("field", "foo firstname zzz yyy lastname foo", Field.Store.YES));
writer.AddDocument(doc3);
IndexReader reader = writer.GetReader();
writer.Dispose();
IndexSearcher searcher = NewSearcher(reader);
searcher.Similarity = new DefaultSimilarity();
PhraseQuery query = new PhraseQuery();
query.Add(new Term("field", "firstname"));
query.Add(new Term("field", "lastname"));
query.Slop = int.MaxValue;
ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(3, hits.Length);
// Make sure that those matches where the terms appear closer to
// each other get a higher score:
Assert.AreEqual(0.71, hits[0].Score, 0.01);
Assert.AreEqual(0, hits[0].Doc);
Assert.AreEqual(0.44, hits[1].Score, 0.01);
Assert.AreEqual(1, hits[1].Doc);
Assert.AreEqual(0.31, hits[2].Score, 0.01);
Assert.AreEqual(2, hits[2].Doc);
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
reader.Dispose();
directory.Dispose();
}
[Test]
public virtual void TestToString()
{
PhraseQuery q = new PhraseQuery(); // Query "this hi this is a test is"
q.Add(new Term("field", "hi"), 1);
q.Add(new Term("field", "test"), 5);
Assert.AreEqual(q.ToString(), "field:\"? hi ? ? ? test\"");
q.Add(new Term("field", "hello"), 1);
Assert.AreEqual(q.ToString(), "field:\"? hi|hello ? ? ? test\"");
}
[Test]
public virtual void TestWrappedPhrase()
{
query.Add(new Term("repeated", "first"));
query.Add(new Term("repeated", "part"));
query.Add(new Term("repeated", "second"));
query.Add(new Term("repeated", "part"));
query.Slop = 100;
ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length, "slop of 100 just right");
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
query.Slop = 99;
hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(0, hits.Length, "slop of 99 not enough");
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
}
// work on two docs like this: "phrase exist notexist exist found"
[Test]
public virtual void TestNonExistingPhrase()
{
// phrase without repetitions that exists in 2 docs
query.Add(new Term("nonexist", "phrase"));
query.Add(new Term("nonexist", "notexist"));
query.Add(new Term("nonexist", "found"));
query.Slop = 2; // would be found this way
ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(2, hits.Length, "phrase without repetitions exists in 2 docs");
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
// phrase with repetitions that exists in 2 docs
query = new PhraseQuery();
query.Add(new Term("nonexist", "phrase"));
query.Add(new Term("nonexist", "exist"));
query.Add(new Term("nonexist", "exist"));
query.Slop = 1; // would be found
hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(2, hits.Length, "phrase with repetitions exists in two docs");
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
// phrase I with repetitions that does not exist in any doc
query = new PhraseQuery();
query.Add(new Term("nonexist", "phrase"));
query.Add(new Term("nonexist", "notexist"));
query.Add(new Term("nonexist", "phrase"));
query.Slop = 1000; // would not be found no matter how high the slop is
hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(0, hits.Length, "nonexisting phrase with repetitions does not exist in any doc");
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
// phrase II with repetitions that does not exist in any doc
query = new PhraseQuery();
query.Add(new Term("nonexist", "phrase"));
query.Add(new Term("nonexist", "exist"));
query.Add(new Term("nonexist", "exist"));
query.Add(new Term("nonexist", "exist"));
query.Slop = 1000; // would not be found no matter how high the slop is
hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(0, hits.Length, "nonexisting phrase with repetitions does not exist in any doc");
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
}
/// <summary>
/// Working on a 2 fields like this:
/// Field("field", "one two three four five")
/// Field("palindrome", "one two three two one")
/// Phrase of size 2 occuriong twice, once in order and once in reverse,
/// because doc is a palyndrome, is counted twice.
/// Also, in this case order in query does not matter.
/// Also, when an exact match is found, both sloppy scorer and exact scorer scores the same.
/// </summary>
[Test]
public virtual void TestPalyndrome2()
{
// search on non palyndrome, find phrase with no slop, using exact phrase scorer
query.Slop = 0; // to use exact phrase scorer
query.Add(new Term("field", "two"));
query.Add(new Term("field", "three"));
ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length, "phrase found with exact phrase scorer");
float score0 = hits[0].Score;
//System.out.println("(exact) field: two three: "+score0);
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
// search on non palyndrome, find phrase with slop 2, though no slop required here.
query.Slop = 2; // to use sloppy scorer
hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length, "just sloppy enough");
float score1 = hits[0].Score;
//System.out.println("(sloppy) field: two three: "+score1);
Assert.AreEqual(score0, score1, SCORE_COMP_THRESH, "exact scorer and sloppy scorer score the same when slop does not matter");
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
// search ordered in palyndrome, find it twice
query = new PhraseQuery();
query.Slop = 2; // must be at least two for both ordered and reversed to match
query.Add(new Term("palindrome", "two"));
query.Add(new Term("palindrome", "three"));
hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length, "just sloppy enough");
//float score2 = hits[0].Score;
//System.out.println("palindrome: two three: "+score2);
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
//commented out for sloppy-phrase efficiency (issue 736) - see SloppyPhraseScorer.phraseFreq().
//Assert.IsTrue("ordered scores higher in palindrome",score1+SCORE_COMP_THRESH<score2);
// search reveresed in palyndrome, find it twice
query = new PhraseQuery();
query.Slop = 2; // must be at least two for both ordered and reversed to match
query.Add(new Term("palindrome", "three"));
query.Add(new Term("palindrome", "two"));
hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length, "just sloppy enough");
//float score3 = hits[0].Score;
//System.out.println("palindrome: three two: "+score3);
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
//commented out for sloppy-phrase efficiency (issue 736) - see SloppyPhraseScorer.phraseFreq().
//Assert.IsTrue("reversed scores higher in palindrome",score1+SCORE_COMP_THRESH<score3);
//Assert.AreEqual("ordered or reversed does not matter",score2, score3, SCORE_COMP_THRESH);
}
/// <summary>
/// Working on a 2 fields like this:
/// Field("field", "one two three four five")
/// Field("palindrome", "one two three two one")
/// Phrase of size 3 occuriong twice, once in order and once in reverse,
/// because doc is a palyndrome, is counted twice.
/// Also, in this case order in query does not matter.
/// Also, when an exact match is found, both sloppy scorer and exact scorer scores the same.
/// </summary>
[Test]
public virtual void TestPalyndrome3()
{
// search on non palyndrome, find phrase with no slop, using exact phrase scorer
query.Slop = 0; // to use exact phrase scorer
query.Add(new Term("field", "one"));
query.Add(new Term("field", "two"));
query.Add(new Term("field", "three"));
ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length, "phrase found with exact phrase scorer");
float score0 = hits[0].Score;
//System.out.println("(exact) field: one two three: "+score0);
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
// just make sure no exc:
searcher.Explain(query, 0);
// search on non palyndrome, find phrase with slop 3, though no slop required here.
query.Slop = 4; // to use sloppy scorer
hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length, "just sloppy enough");
float score1 = hits[0].Score;
//System.out.println("(sloppy) field: one two three: "+score1);
Assert.AreEqual(score0, score1, SCORE_COMP_THRESH, "exact scorer and sloppy scorer score the same when slop does not matter");
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
// search ordered in palyndrome, find it twice
query = new PhraseQuery();
query.Slop = 4; // must be at least four for both ordered and reversed to match
query.Add(new Term("palindrome", "one"));
query.Add(new Term("palindrome", "two"));
query.Add(new Term("palindrome", "three"));
hits = searcher.Search(query, null, 1000).ScoreDocs;
// just make sure no exc:
searcher.Explain(query, 0);
Assert.AreEqual(1, hits.Length, "just sloppy enough");
//float score2 = hits[0].Score;
//System.out.println("palindrome: one two three: "+score2);
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
//commented out for sloppy-phrase efficiency (issue 736) - see SloppyPhraseScorer.phraseFreq().
//Assert.IsTrue("ordered scores higher in palindrome",score1+SCORE_COMP_THRESH<score2);
// search reveresed in palyndrome, find it twice
query = new PhraseQuery();
query.Slop = 4; // must be at least four for both ordered and reversed to match
query.Add(new Term("palindrome", "three"));
query.Add(new Term("palindrome", "two"));
query.Add(new Term("palindrome", "one"));
hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length, "just sloppy enough");
//float score3 = hits[0].Score;
//System.out.println("palindrome: three two one: "+score3);
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, searcher);
//commented out for sloppy-phrase efficiency (issue 736) - see SloppyPhraseScorer.phraseFreq().
//Assert.IsTrue("reversed scores higher in palindrome",score1+SCORE_COMP_THRESH<score3);
//Assert.AreEqual("ordered or reversed does not matter",score2, score3, SCORE_COMP_THRESH);
}
// LUCENE-1280
[Test]
public virtual void TestEmptyPhraseQuery()
{
BooleanQuery q2 = new BooleanQuery();
q2.Add(new PhraseQuery(), Occur.MUST);
q2.ToString();
}
/* test that a single term is rewritten to a term query */
[Test]
public virtual void TestRewrite()
{
PhraseQuery pq = new PhraseQuery();
pq.Add(new Term("foo", "bar"));
Query rewritten = pq.Rewrite(searcher.IndexReader);
Assert.IsTrue(rewritten is TermQuery);
}
[Test]
public virtual void TestRandomPhrases()
{
Directory dir = NewDirectory();
Analyzer analyzer = new MockAnalyzer(Random);
RandomIndexWriter w = new RandomIndexWriter(Random, dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer).SetMergePolicy(NewLogMergePolicy()));
IList<IList<string>> docs = new List<IList<string>>();
Documents.Document d = new Documents.Document();
Field f = NewTextField("f", "", Field.Store.NO);
d.Add(f);
Random r = Random;
int NUM_DOCS = AtLeast(10);
for (int i = 0; i < NUM_DOCS; i++)
{
// must be > 4096 so it spans multiple chunks
int termCount = TestUtil.NextInt32(Random, 4097, 8200);
IList<string> doc = new List<string>();
StringBuilder sb = new StringBuilder();
while (doc.Count < termCount)
{
if (r.Next(5) == 1 || docs.Count == 0)
{
// make new non-empty-string term
string term;
while (true)
{
term = TestUtil.RandomUnicodeString(r);
if (term.Length > 0)
{
break;
}
}
IOException priorException = null;
TokenStream ts = analyzer.GetTokenStream("ignore", new StringReader(term));
try
{
ICharTermAttribute termAttr = ts.AddAttribute<ICharTermAttribute>();
ts.Reset();
while (ts.IncrementToken())
{
string text = termAttr.ToString();
doc.Add(text);
sb.Append(text).Append(' ');
}
ts.End();
}
catch (IOException e)
{
priorException = e;
}
finally
{
IOUtils.DisposeWhileHandlingException(priorException, ts);
}
}
else
{
// pick existing sub-phrase
IList<string> lastDoc = docs[r.Next(docs.Count)];
int len = TestUtil.NextInt32(r, 1, 10);
int start = r.Next(lastDoc.Count - len);
for (int k = start; k < start + len; k++)
{
string t = lastDoc[k];
doc.Add(t);
sb.Append(t).Append(' ');
}
}
}
docs.Add(doc);
f.SetStringValue(sb.ToString());
w.AddDocument(d);
}
IndexReader reader = w.GetReader();
IndexSearcher s = NewSearcher(reader);
w.Dispose();
// now search
int num = AtLeast(10);
for (int i = 0; i < num; i++)
{
int docID = r.Next(docs.Count);
IList<string> doc = docs[docID];
int numTerm = TestUtil.NextInt32(r, 2, 20);
int start = r.Next(doc.Count - numTerm);
PhraseQuery pq = new PhraseQuery();
StringBuilder sb = new StringBuilder();
for (int t = start; t < start + numTerm; t++)
{
pq.Add(new Term("f", doc[t]));
sb.Append(doc[t]).Append(' ');
}
TopDocs hits = s.Search(pq, NUM_DOCS);
bool found = false;
for (int j = 0; j < hits.ScoreDocs.Length; j++)
{
if (hits.ScoreDocs[j].Doc == docID)
{
found = true;
break;
}
}
Assert.IsTrue(found, "phrase '" + sb + "' not found; start=" + start);
}
reader.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestNegativeSlop()
{
PhraseQuery query = new PhraseQuery();
query.Add(new Term("field", "two"));
query.Add(new Term("field", "one"));
try
{
query.Slop = -2;
Assert.Fail("didn't get expected exception");
}
#pragma warning disable 168
catch (ArgumentException expected)
#pragma warning restore 168
{
// expected exception
}
}
}
}
| |
/*
* Menu.cs - Implementation of the "System.Windows.Forms.Menu" class.
*
* Copyright (C) 2004 Southern Storm Software, Pty Ltd.
* Copyright (C) 2004 Neil Cawse.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Windows.Forms
{
using System.ComponentModel;
using System.Collections;
using System.Drawing;
using System.Drawing.Text;
using System.Windows.Forms.Themes;
public abstract class Menu
#if CONFIG_COMPONENT_MODEL
: Component
#endif
{
// Internal state.
private int numItems;
internal MenuItem[] itemList;
private MenuItemCollection items;
private int suppressUpdates;
protected Rectangle[] itemBounds;
private StringFormat format;
// Interval before popping up a menu when the mouse is hovered.
internal const int itemSelectInterval = 350;
protected internal Timer itemSelectTimer;
// Constructor.
protected Menu(MenuItem[] items)
{
format = new StringFormat();
format.FormatFlags |= StringFormatFlags.NoWrap;
format.HotkeyPrefix = HotkeyPrefix.Show;
if(items != null)
{
this.numItems = items.Length;
this.itemList = new MenuItem [numItems];
Array.Copy(items, 0, this.itemList, 0, numItems);
this.items = null;
this.suppressUpdates = 0;
}
else
{
this.numItems = 0;
this.itemList = new MenuItem [0];
this.items = null;
this.suppressUpdates = 0;
}
}
// Suppress updates on this menu while it is being modified.
internal void SuppressUpdates()
{
++suppressUpdates;
}
// Allow updates on this menu after it was modified.
[TODO]
internal void AllowUpdates()
{
--suppressUpdates;
if(suppressUpdates == 0)
{
// Fix: force a repaint/recalc of the menu
}
}
// Get or set this object's properties.
public IntPtr Handle
{
get
{
// Menu handles are not used in this implementation.
return IntPtr.Zero;
}
}
public virtual bool IsParent
{
get
{
return (numItems > 0);
}
}
public MenuItem MdiListItem
{
get
{
int index;
MenuItem list;
for(index = 0; index < numItems; ++index)
{
if(itemList[index].MdiList)
{
return itemList[index];
}
else
{
list = itemList[index].MdiListItem;
if(list != null)
{
return list;
}
}
}
return null;
}
}
public MenuItemCollection MenuItems
{
get
{
if(items == null)
{
items = new MenuItemCollection(this);
}
return items;
}
}
// Get the context menu that contains this item.
public ContextMenu GetContextMenu()
{
Menu menu = this;
while(menu != null && !(menu is ContextMenu))
{
if(menu is MenuItem)
{
menu = ((MenuItem)menu).parent;
}
else
{
return null;
}
}
return (ContextMenu)menu;
}
// Get the main menu that contains this item.
public MainMenu GetMainMenu()
{
Menu menu = this;
while(menu != null && !(menu is MainMenu))
{
if(menu is MenuItem)
{
menu = ((MenuItem)menu).parent;
}
else
{
return null;
}
}
return (MainMenu)menu;
}
// Merge another menu with this one.
[TODO]
public virtual void MergeMenu(Menu menuSrc)
{
return;
}
// Convert this object into a string.
public override String ToString()
{
return base.ToString() + ", Item.Count=" + numItems.ToString();
}
// Clone the contents of another menu into this one.
[TODO]
protected void CloneMenu(Menu menuSrc)
{
return;
}
// Offset from each item to the menu text.
internal virtual Point ItemPaddingOrigin
{
get
{
return new Point(6, 3);
}
}
// How much bigger each item is than the text.
internal Size ItemPaddingSize
{
get
{
return new Size(12, 6);
}
}
// Padding offset from top left of menu.
internal virtual Point MenuPaddingOrigin
{
get
{
return new Point(1, 1);
}
}
// How much bigger the menu is than the text.
internal Size MenuPaddingSize
{
get
{
return new Size(2, 2);
}
}
protected internal void DrawMenuItem(Graphics g, int item, bool highlighted)
{
Rectangle bounds = itemBounds[item];
// Get the area for the text
Rectangle textBounds = new Rectangle(
bounds.X + ItemPaddingOrigin.X,
bounds.Y + ItemPaddingOrigin.Y,
bounds.Width - ItemPaddingSize.Width,
bounds.Height - ItemPaddingSize.Height);
MenuItem menuItem = itemList[item];
if (menuItem.Text == "-")
{
g.FillRectangle(SystemBrushes.Menu, bounds);
ThemeManager.MainPainter.DrawSeparator(g, bounds);
}
else
{
if (menuItem.OwnerDraw)
{
DrawItemEventArgs drawItem = new DrawItemEventArgs(g, SystemInformation.MenuFont, bounds, item, DrawItemState.None);
menuItem.OnDrawItem(drawItem);
}
else
{
Brush fore, back;
if (highlighted)
{
fore = SystemBrushes.HighlightText;
back = SystemBrushes.Highlight;
}
else
{
fore = SystemBrushes.MenuText;
back = SystemBrushes.Menu;
}
g.FillRectangle(back, bounds);
g.DrawString(menuItem.Text, SystemInformation.MenuFont, fore, textBounds, format);
if (this is ContextMenu && menuItem.itemList.Length > 0)
{
int x = bounds.Right - 7;
int y = (bounds.Bottom + bounds.Top) / 2;
g.FillPolygon(fore, new PointF[]{
new Point(x, y), new Point(x - 5, y - 5), new Point(x - 5, y + 5)});
}
}
}
}
protected internal int ItemFromPoint(Point p)
{
if (itemBounds == null)
return -1;
for (int i = 0; i < MenuItems.Count; i++)
{
if (itemBounds[i].Contains(p))
return i;
}
return -1;
}
// Start the select item timer.
protected internal void StartTimer(int item)
{
// If we are hovering on a new item, then we need to time.
if (item != -1)
{
// Start the timer for this item.
if (itemSelectTimer == null)
{
itemSelectTimer = new Timer();
itemSelectTimer.Tick +=new EventHandler(ItemSelectTimerTick);
}
else
{
itemSelectTimer.Stop();
}
itemSelectTimer.Interval = Menu.itemSelectInterval;
itemSelectTimer.Start();
}
else if (itemSelectTimer != null && itemSelectTimer.Enabled)
{
itemSelectTimer.Stop();
}
}
protected virtual internal void ItemSelectTimerTick(object sender, EventArgs e)
{
itemSelectTimer.Stop();
}
[TODO]
internal protected bool ProcessCmdKey(ref Message msg, Keys keyData)
{
return false;
}
#if CONFIG_COMPONENT_MODEL
// Dispose of this menu.
protected override void Dispose(bool disposing)
{
if (itemSelectTimer != null)
{
itemSelectTimer.Dispose();
itemSelectTimer = null;
}
base.Dispose(disposing);
}
#endif
// Collection of menu items.
public class MenuItemCollection : IList
{
// Internal State.
private Menu owner;
// Constructor.
public MenuItemCollection(Menu owner)
{
this.owner = owner;
}
// Retrieve a particular item from this collection.
public virtual MenuItem this[int index]
{
get
{
if(index < 0 || index >= owner.numItems)
{
throw new ArgumentOutOfRangeException
("index", S._("SWF_MenuItemIndex"));
}
return owner.itemList[index];
}
}
// Implement the ICollection interface.
public void CopyTo(Array array, int index)
{
IEnumerator e = GetEnumerator();
while(e.MoveNext())
{
array.SetValue(e.Current, index);
}
}
public int Count
{
get
{
return owner.numItems;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
Object ICollection.SyncRoot
{
get
{
return this;
}
}
// Implement the IList interface.
int IList.Add(Object value)
{
MenuItem item = (value as MenuItem);
if(item != null)
{
return Add(item);
}
else
{
throw new ArgumentException
(S._("SWF_InvalidMenuItem"), "value");
}
}
public void Clear()
{
if(owner.numItems != 0)
{
owner.SuppressUpdates();
while(owner.numItems > 0)
{
RemoveAt(owner.numItems - 1);
}
owner.AllowUpdates();
}
}
bool IList.Contains(Object value)
{
MenuItem item = (value as MenuItem);
if(item != null)
{
return Contains(item);
}
else
{
return false;
}
}
int IList.IndexOf(Object value)
{
MenuItem item = (value as MenuItem);
if(item != null)
{
return IndexOf(item);
}
else
{
return -1;
}
}
void IList.Insert(int index, Object value)
{
MenuItem item = (value as MenuItem);
if(item != null)
{
Add(index, item);
}
else
{
throw new ArgumentException
(S._("SWF_InvalidMenuItem"), "value");
}
}
void IList.Remove(Object value)
{
MenuItem item = (value as MenuItem);
if(item != null)
{
Remove(item);
}
}
public virtual void RemoveAt(int index)
{
if(index < 0 || index >= owner.numItems)
{
throw new ArgumentOutOfRangeException
("index", S._("SWF_MenuItemIndex"));
}
else
{
owner.SuppressUpdates();
owner.itemList[index].parent = null;
MenuItem[] items = new MenuItem [owner.numItems - 1];
Array.Copy(owner.itemList, 0, items, 0, index);
Array.Copy(owner.itemList, index + 1, items, index,
owner.numItems - index - 1);
owner.itemList = items;
--(owner.numItems);
owner.AllowUpdates();
}
}
bool IList.IsFixedSize
{
get
{
return false;
}
}
bool IList.IsReadOnly
{
get
{
return false;
}
}
Object IList.this[int index]
{
get
{
return this[index];
}
set
{
throw new NotSupportedException();
}
}
// Implement the IEnumerable interface.
public IEnumerator GetEnumerator()
{
return owner.itemList.GetEnumerator();
}
// Add a menu item to this menu.
public virtual int Add(MenuItem item)
{
return Add(owner.numItems, item);
}
public virtual int Add(int index, MenuItem item)
{
if(item == null)
{
throw new ArgumentNullException("item");
}
else if(item.parent != null)
{
throw new ArgumentException
(S._("SWF_ItemAlreadyInUse"), "item");
}
if(index < 0 || index > owner.numItems)
{
throw new ArgumentOutOfRangeException
("index", S._("SWF_MenuItemIndex"));
}
owner.SuppressUpdates();
MenuItem[] items = new MenuItem [owner.numItems + 1];
Array.Copy(owner.itemList, 0, items, 0, index);
items[index] = item;
item.parent = owner;
if(index < owner.numItems)
{
Array.Copy(owner.itemList, index, items, index + 1,
owner.numItems - index);
}
owner.itemList = items;
++(owner.numItems);
owner.AllowUpdates();
return index;
}
public virtual MenuItem Add(String caption)
{
MenuItem item = new MenuItem(caption);
Add(item);
return item;
}
public virtual MenuItem Add(String caption, EventHandler onClick)
{
MenuItem item = new MenuItem(caption, onClick);
Add(item);
return item;
}
public virtual MenuItem Add(String caption, MenuItem[] items)
{
MenuItem item = new MenuItem(caption, items);
Add(item);
return item;
}
// Add a range of menu items to this menu.
public virtual void AddRange(MenuItem[] items)
{
if(items == null)
{
throw new ArgumentNullException("items");
}
owner.SuppressUpdates();
foreach(MenuItem item in items)
{
Add(owner.numItems, item);
}
owner.AllowUpdates();
}
// Determine if this menu contains a particular item
public bool Contains(MenuItem item)
{
foreach(MenuItem i in owner.itemList)
{
if(i == item)
{
return true;
}
}
return false;
}
// Get the index of a specific menu item.
public int IndexOf(MenuItem item)
{
int index;
for(index = 0; index < owner.numItems; ++index)
{
if(owner.itemList[index] == item)
{
return index;
}
}
return -1;
}
// Remove a specific menu item.
public virtual void Remove(MenuItem item)
{
owner.SuppressUpdates();
int index = IndexOf(item);
if(index != -1)
{
owner.itemList[index].parent = null;
MenuItem[] items = new MenuItem [owner.numItems - 1];
Array.Copy(owner.itemList, 0, items, 0, index);
Array.Copy(owner.itemList, index + 1, items, index,
owner.numItems - index - 1);
owner.itemList = items;
--(owner.numItems);
}
owner.AllowUpdates();
}
// Move a menu item to a new position.
internal void Move(MenuItem item, int index)
{
if(index < 0 || index >= owner.numItems)
{
throw new ArgumentOutOfRangeException
("index", S._("SWF_MenuItemIndex"));
}
int oldIndex = IndexOf(item);
owner.SuppressUpdates();
if(index < oldIndex)
{
RemoveAt(oldIndex);
Add(index, item);
}
else if(index > oldIndex)
{
RemoveAt(oldIndex);
Add(index - 1, item);
}
owner.AllowUpdates();
}
}; // class MenuItemCollection
}; // class Menu
}; // namespace System.Windows.Forms
| |
using CppSharp.AST;
using CppSharp.AST.Extensions;
using CppSharp.Generators;
using CppSharp.Generators.AST;
using CppSharp.Generators.CLI;
using CppSharp.Generators.CSharp;
namespace CppSharp.Types.Std
{
[TypeMap("va_list")]
public class VaList : TypeMap
{
public override string CLISignature(CLITypePrinterContext ctx)
{
return "va_list";
}
public override string CSharpSignature(CSharpTypePrinterContext ctx)
{
return "va_list";
}
public override bool IsIgnored
{
get { return true; }
}
}
[TypeMap("std::string", GeneratorKind.CLI)]
public class String : TypeMap
{
public override string CLISignature(CLITypePrinterContext ctx)
{
return "System::String^";
}
public override void CLIMarshalToNative(MarshalContext ctx)
{
ctx.Return.Write("clix::marshalString<clix::E_UTF8>({0})",
ctx.Parameter.Name);
}
public override void CLIMarshalToManaged(MarshalContext ctx)
{
ctx.Return.Write("clix::marshalString<clix::E_UTF8>({0})",
ctx.ReturnVarName);
}
public override string CSharpSignature(CSharpTypePrinterContext ctx)
{
return "Std.String";
}
public override void CSharpMarshalToNative(MarshalContext ctx)
{
ctx.Return.Write("new Std.String()");
}
public override void CSharpMarshalToManaged(MarshalContext ctx)
{
ctx.Return.Write(ctx.ReturnVarName);
}
}
[TypeMap("std::wstring")]
public class WString : TypeMap
{
public override string CLISignature(CLITypePrinterContext ctx)
{
return "System::String^";
}
public override void CLIMarshalToNative(MarshalContext ctx)
{
ctx.Return.Write("clix::marshalString<clix::E_UTF16>({0})",
ctx.Parameter.Name);
}
public override void CLIMarshalToManaged(MarshalContext ctx)
{
ctx.Return.Write("clix::marshalString<clix::E_UTF16>({0})",
ctx.ReturnVarName);
}
public override string CSharpSignature(CSharpTypePrinterContext ctx)
{
return "string";
}
public override void CSharpMarshalToNative(MarshalContext ctx)
{
ctx.Return.Write("new Std.WString()");
}
public override void CSharpMarshalToManaged(MarshalContext ctx)
{
ctx.Return.Write(ctx.ReturnVarName);
}
}
[TypeMap("std::vector")]
public class Vector : TypeMap
{
public override bool IsIgnored
{
get
{
var type = Type as TemplateSpecializationType;
var pointeeType = type.Arguments[0].Type;
var checker = new TypeIgnoreChecker(TypeMapDatabase);
pointeeType.Visit(checker);
return checker.IsIgnored;
}
}
public override string CLISignature(CLITypePrinterContext ctx)
{
return string.Format("System::Collections::Generic::List<{0}>^",
ctx.GetTemplateParameterList());
}
public override void CLIMarshalToNative(MarshalContext ctx)
{
var templateType = Type as TemplateSpecializationType;
var type = templateType.Arguments[0].Type;
var isPointerToPrimitive = type.Type.IsPointerToPrimitiveType();
var managedType = isPointerToPrimitive
? new CILType(typeof(System.IntPtr))
: type.Type;
var entryString = (ctx.Parameter != null) ? ctx.Parameter.Name
: ctx.ArgName;
var tmpVarName = "_tmp" + entryString;
var cppTypePrinter = new CppTypePrinter(ctx.Driver.TypeDatabase);
var nativeType = type.Type.Visit(cppTypePrinter);
ctx.SupportBefore.WriteLine("auto {0} = std::vector<{1}>();",
tmpVarName, nativeType);
ctx.SupportBefore.WriteLine("for each({0} _element in {1})",
managedType, entryString);
ctx.SupportBefore.WriteStartBraceIndent();
{
var param = new Parameter
{
Name = "_element",
QualifiedType = type
};
var elementCtx = new MarshalContext(ctx.Driver)
{
Parameter = param,
ArgName = param.Name,
};
var marshal = new CLIMarshalManagedToNativePrinter(elementCtx);
type.Type.Visit(marshal);
if (!string.IsNullOrWhiteSpace(marshal.Context.SupportBefore))
ctx.SupportBefore.Write(marshal.Context.SupportBefore);
if (isPointerToPrimitive)
ctx.SupportBefore.WriteLine("auto _marshalElement = {0}.ToPointer();",
marshal.Context.Return);
else
ctx.SupportBefore.WriteLine("auto _marshalElement = {0};",
marshal.Context.Return);
ctx.SupportBefore.WriteLine("{0}.push_back(_marshalElement);",
tmpVarName);
}
ctx.SupportBefore.WriteCloseBraceIndent();
ctx.Return.Write(tmpVarName);
}
public override void CLIMarshalToManaged(MarshalContext ctx)
{
var templateType = Type as TemplateSpecializationType;
var type = templateType.Arguments[0].Type;
var isPointerToPrimitive = type.Type.IsPointerToPrimitiveType();
var managedType = isPointerToPrimitive
? new CILType(typeof(System.IntPtr))
: type.Type;
var tmpVarName = "_tmp" + ctx.ArgName;
ctx.SupportBefore.WriteLine(
"auto {0} = gcnew System::Collections::Generic::List<{1}>();",
tmpVarName, managedType);
ctx.SupportBefore.WriteLine("for(auto _element : {0})",
ctx.ReturnVarName);
ctx.SupportBefore.WriteStartBraceIndent();
{
var elementCtx = new MarshalContext(ctx.Driver)
{
ReturnVarName = "_element",
ReturnType = type
};
var marshal = new CLIMarshalNativeToManagedPrinter(elementCtx);
type.Type.Visit(marshal);
if (!string.IsNullOrWhiteSpace(marshal.Context.SupportBefore))
ctx.SupportBefore.Write(marshal.Context.SupportBefore);
ctx.SupportBefore.WriteLine("auto _marshalElement = {0};",
marshal.Context.Return);
if (isPointerToPrimitive)
ctx.SupportBefore.WriteLine("{0}->Add({1}(_marshalElement));",
tmpVarName, managedType);
else
ctx.SupportBefore.WriteLine("{0}->Add(_marshalElement);",
tmpVarName);
}
ctx.SupportBefore.WriteCloseBraceIndent();
ctx.Return.Write(tmpVarName);
}
public override string CSharpSignature(CSharpTypePrinterContext ctx)
{
if (ctx.CSharpKind == CSharpTypePrinterContextKind.Native)
return "Std.Vector";
return string.Format("Std.Vector<{0}>", ctx.GetTemplateParameterList());
}
public override void CSharpMarshalToNative(MarshalContext ctx)
{
ctx.Return.Write("{0}.Internal", ctx.Parameter.Name);
}
public override void CSharpMarshalToManaged(MarshalContext ctx)
{
var templateType = Type as TemplateSpecializationType;
var type = templateType.Arguments[0].Type;
ctx.Return.Write("new Std.Vector<{0}>({1})", type,
ctx.ReturnVarName);
}
}
[TypeMap("std::map")]
public class Map : TypeMap
{
public override bool IsIgnored { get { return true; } }
public override string CLISignature(CLITypePrinterContext ctx)
{
var type = Type as TemplateSpecializationType;
return string.Format(
"System::Collections::Generic::Dictionary<{0}, {1}>^",
type.Arguments[0].Type, type.Arguments[1].Type);
}
public override void CLIMarshalToNative(MarshalContext ctx)
{
throw new System.NotImplementedException();
}
public override void CLIMarshalToManaged(MarshalContext ctx)
{
throw new System.NotImplementedException();
}
public override string CSharpSignature(CSharpTypePrinterContext ctx)
{
if (ctx.CSharpKind == CSharpTypePrinterContextKind.Native)
return "Std.Map";
var type = Type as TemplateSpecializationType;
return string.Format(
"System.Collections.Generic.Dictionary<{0}, {1}>",
type.Arguments[0].Type, type.Arguments[1].Type);
}
}
[TypeMap("std::list")]
public class List : TypeMap
{
public override bool IsIgnored { get { return true; } }
}
[TypeMap("std::shared_ptr")]
public class SharedPtr : TypeMap
{
public override string CLISignature(CLITypePrinterContext ctx)
{
throw new System.NotImplementedException();
}
public override void CLIMarshalToNative(MarshalContext ctx)
{
throw new System.NotImplementedException();
}
public override void CLIMarshalToManaged(MarshalContext ctx)
{
throw new System.NotImplementedException();
}
}
[TypeMap("std::ostream", GeneratorKind.CLI)]
public class OStream : TypeMap
{
public override string CLISignature(CLITypePrinterContext ctx)
{
return "System::IO::TextWriter^";
}
public override void CLIMarshalToNative(MarshalContext ctx)
{
var marshal = (CLIMarshalManagedToNativePrinter) ctx.MarshalToNative;
if (!ctx.Parameter.Type.Desugar().IsPointer())
marshal.ArgumentPrefix.Write("*");
var marshalCtxName = string.Format("ctx_{0}", ctx.Parameter.Name);
ctx.SupportBefore.WriteLine("msclr::interop::marshal_context {0};", marshalCtxName);
ctx.Return.Write("{0}.marshal_as<std::ostream*>({1})",
marshalCtxName, ctx.Parameter.Name);
}
}
[TypeMap("std::nullptr_t")]
public class NullPtr : TypeMap
{
public override bool DoesMarshalling { get { return false; } }
public override void CLITypeReference(CLITypeReferenceCollector collector,
ASTRecord<Declaration> loc)
{
var typeRef = collector.GetTypeReference(loc.Value);
var include = new Include
{
File = "cstddef",
Kind = Include.IncludeKind.Angled,
};
typeRef.Include = include;
}
}
}
| |
using Lucene.Net.Index;
using Lucene.Net.Store;
using Lucene.Net.Util;
using Lucene.Net.Util.Automaton;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Codecs.Bloom
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
///
/// A <see cref="PostingsFormat"/> useful for low doc-frequency fields such as primary
/// keys. Bloom filters are maintained in a ".blm" file which offers "fast-fail"
/// for reads in segments known to have no record of the key. A choice of
/// delegate <see cref="PostingsFormat"/> is used to record all other Postings data.
/// <para/>
/// A choice of <see cref="BloomFilterFactory"/> can be passed to tailor Bloom Filter
/// settings on a per-field basis. The default configuration is
/// <see cref="DefaultBloomFilterFactory"/> which allocates a ~8mb bitset and hashes
/// values using <see cref="MurmurHash2"/>. This should be suitable for most purposes.
/// <para/>
/// The format of the blm file is as follows:
///
/// <list type="bullet">
/// <item><description>BloomFilter (.blm) --> Header, DelegatePostingsFormatName,
/// NumFilteredFields, Filter<sup>NumFilteredFields</sup>, Footer</description></item>
/// <item><description>Filter --> FieldNumber, FuzzySet</description></item>
/// <item><description>FuzzySet -->See <see cref="FuzzySet.Serialize(DataOutput)"/></description></item>
/// <item><description>Header --> CodecHeader (<see cref="CodecUtil.WriteHeader(DataOutput, string, int)"/>) </description></item>
/// <item><description>DelegatePostingsFormatName --> String (<see cref="DataOutput.WriteString(string)"/>)
/// The name of a ServiceProvider registered <see cref="PostingsFormat"/></description></item>
/// <item><description>NumFilteredFields --> Uint32 (<see cref="DataOutput.WriteInt32(int)"/>) </description></item>
/// <item><description>FieldNumber --> Uint32 (<see cref="DataOutput.WriteInt32(int)"/>) The number of the
/// field in this segment</description></item>
/// <item><description>Footer --> CodecFooter (<see cref="CodecUtil.WriteFooter(IndexOutput)"/>) </description></item>
/// </list>
/// <para/>
/// @lucene.experimental
/// </summary>
[PostingsFormatName("BloomFilter")] // LUCENENET specific - using PostingsFormatName attribute to ensure the default name passed from subclasses is the same as this class name
public sealed class BloomFilteringPostingsFormat : PostingsFormat
{
// LUCENENET specific - removed this static variable because our name is determined by the PostingsFormatNameAttribute
//public static readonly string BLOOM_CODEC_NAME = "BloomFilter";
public static readonly int VERSION_START = 1;
public static readonly int VERSION_CHECKSUM = 2;
public static readonly int VERSION_CURRENT = VERSION_CHECKSUM;
/// <summary>Extension of Bloom Filters file.</summary>
private const string BLOOM_EXTENSION = "blm";
private readonly BloomFilterFactory _bloomFilterFactory = new DefaultBloomFilterFactory();
private readonly PostingsFormat _delegatePostingsFormat;
/// <summary>
/// Creates Bloom filters for a selection of fields created in the index. This
/// is recorded as a set of Bitsets held as a segment summary in an additional
/// "blm" file. This <see cref="PostingsFormat"/> delegates to a choice of delegate
/// <see cref="PostingsFormat"/> for encoding all other postings data.
/// </summary>
/// <param name="delegatePostingsFormat">The <see cref="PostingsFormat"/> that records all the non-bloom filter data i.e. postings info.</param>
/// <param name="bloomFilterFactory">The <see cref="BloomFilterFactory"/> responsible for sizing BloomFilters appropriately.</param>
public BloomFilteringPostingsFormat(PostingsFormat delegatePostingsFormat,
BloomFilterFactory bloomFilterFactory) : base()
{
_delegatePostingsFormat = delegatePostingsFormat;
_bloomFilterFactory = bloomFilterFactory;
}
/// <summary>
/// Creates Bloom filters for a selection of fields created in the index. This
/// is recorded as a set of Bitsets held as a segment summary in an additional
/// "blm" file. This <see cref="PostingsFormat"/> delegates to a choice of delegate
/// <see cref="PostingsFormat"/> for encoding all other postings data. This choice of
/// constructor defaults to the <see cref="DefaultBloomFilterFactory"/> for
/// configuring per-field BloomFilters.
/// </summary>
/// <param name="delegatePostingsFormat">The <see cref="PostingsFormat"/> that records all the non-bloom filter data i.e. postings info.</param>
public BloomFilteringPostingsFormat(PostingsFormat delegatePostingsFormat)
: this(delegatePostingsFormat, new DefaultBloomFilterFactory())
{
}
/// <summary>
/// Used only by core Lucene at read-time via Service Provider instantiation -
/// do not use at Write-time in application code.
/// </summary>
public BloomFilteringPostingsFormat()
: base()
{
}
public override FieldsConsumer FieldsConsumer(SegmentWriteState state)
{
if (_delegatePostingsFormat == null)
{
throw new InvalidOperationException("Error - constructed without a choice of PostingsFormat");
}
return new BloomFilteredFieldsConsumer(this, _delegatePostingsFormat.FieldsConsumer(state), state);
}
public override FieldsProducer FieldsProducer(SegmentReadState state)
{
return new BloomFilteredFieldsProducer(this, state);
}
internal class BloomFilteredFieldsProducer : FieldsProducer
{
private readonly BloomFilteringPostingsFormat outerInstance;
private readonly FieldsProducer _delegateFieldsProducer;
private readonly JCG.Dictionary<string, FuzzySet> _bloomsByFieldName = new JCG.Dictionary<string, FuzzySet>();
public BloomFilteredFieldsProducer(BloomFilteringPostingsFormat outerInstance, SegmentReadState state)
{
this.outerInstance = outerInstance;
var bloomFileName = IndexFileNames.SegmentFileName(
state.SegmentInfo.Name, state.SegmentSuffix, BLOOM_EXTENSION);
ChecksumIndexInput bloomIn = null;
var success = false;
try
{
bloomIn = state.Directory.OpenChecksumInput(bloomFileName, state.Context);
var version = CodecUtil.CheckHeader(bloomIn, /*BLOOM_CODEC_NAME*/ outerInstance.Name, VERSION_START, VERSION_CURRENT);
// Load the hash function used in the BloomFilter
// hashFunction = HashFunction.forName(bloomIn.readString());
// Load the delegate postings format
var delegatePostingsFormat = ForName(bloomIn.ReadString());
_delegateFieldsProducer = delegatePostingsFormat
.FieldsProducer(state);
var numBlooms = bloomIn.ReadInt32();
for (var i = 0; i < numBlooms; i++)
{
var fieldNum = bloomIn.ReadInt32();
var bloom = FuzzySet.Deserialize(bloomIn);
var fieldInfo = state.FieldInfos.FieldInfo(fieldNum);
_bloomsByFieldName.Add(fieldInfo.Name, bloom);
}
if (version >= VERSION_CHECKSUM)
{
CodecUtil.CheckFooter(bloomIn);
}
else
{
#pragma warning disable 612, 618
CodecUtil.CheckEOF(bloomIn);
#pragma warning restore 612, 618
}
IOUtils.Dispose(bloomIn);
success = true;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(bloomIn, _delegateFieldsProducer);
}
}
}
public override IEnumerator<string> GetEnumerator()
{
return _delegateFieldsProducer.GetEnumerator();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_delegateFieldsProducer.Dispose();
}
}
public override Terms GetTerms(string field)
{
FuzzySet filter;
if (!_bloomsByFieldName.TryGetValue(field, out filter) || filter == null)
{
return _delegateFieldsProducer.GetTerms(field);
}
else
{
var result = _delegateFieldsProducer.GetTerms(field);
return result == null ? null : new BloomFilteredTerms(result, filter);
}
}
public override int Count => _delegateFieldsProducer.Count;
[Obsolete("iterate fields and add their Count instead.")]
public override long UniqueTermCount => _delegateFieldsProducer.UniqueTermCount;
internal class BloomFilteredTerms : Terms
{
private readonly Terms _delegateTerms;
private readonly FuzzySet _filter;
public BloomFilteredTerms(Terms terms, FuzzySet filter)
{
_delegateTerms = terms;
_filter = filter;
}
public override TermsEnum Intersect(CompiledAutomaton compiled,
BytesRef startTerm)
{
return _delegateTerms.Intersect(compiled, startTerm);
}
public override TermsEnum GetIterator(TermsEnum reuse)
{
if (!(reuse is BloomFilteredTermsEnum))
return new BloomFilteredTermsEnum(_delegateTerms, reuse, _filter);
// recycle the existing BloomFilteredTermsEnum by asking the delegate
// to recycle its contained TermsEnum
var bfte = (BloomFilteredTermsEnum) reuse;
// We have been handed something we cannot reuse (either null, wrong
// class or wrong filter) so allocate a new object
if (bfte.filter != _filter) return new BloomFilteredTermsEnum(_delegateTerms, reuse, _filter);
bfte.Reset(_delegateTerms, bfte.delegateTermsEnum);
return bfte;
}
public override IComparer<BytesRef> Comparer => _delegateTerms.Comparer;
public override long Count => _delegateTerms.Count;
public override long SumTotalTermFreq => _delegateTerms.SumTotalTermFreq;
public override long SumDocFreq => _delegateTerms.SumDocFreq;
public override int DocCount => _delegateTerms.DocCount;
public override bool HasFreqs => _delegateTerms.HasFreqs;
public override bool HasOffsets => _delegateTerms.HasOffsets;
public override bool HasPositions => _delegateTerms.HasPositions;
public override bool HasPayloads => _delegateTerms.HasPayloads;
}
internal sealed class BloomFilteredTermsEnum : TermsEnum
{
private Terms _delegateTerms;
internal TermsEnum delegateTermsEnum;
private TermsEnum _reuseDelegate;
internal readonly FuzzySet filter;
public BloomFilteredTermsEnum(Terms delegateTerms, TermsEnum reuseDelegate, FuzzySet filter)
{
_delegateTerms = delegateTerms;
_reuseDelegate = reuseDelegate;
this.filter = filter;
}
internal void Reset(Terms delegateTerms, TermsEnum reuseDelegate)
{
_delegateTerms = delegateTerms;
_reuseDelegate = reuseDelegate;
delegateTermsEnum = null;
}
private TermsEnum Delegate =>
// pull the iterator only if we really need it -
// this can be a relativly heavy operation depending on the
// delegate postings format and they underlying directory
// (clone IndexInput)
delegateTermsEnum ?? (delegateTermsEnum = _delegateTerms.GetIterator(_reuseDelegate));
public override sealed BytesRef Next()
{
return Delegate.Next();
}
public override sealed IComparer<BytesRef> Comparer => _delegateTerms.Comparer;
public override sealed bool SeekExact(BytesRef text)
{
// The magical fail-fast speed up that is the entire point of all of
// this code - save a disk seek if there is a match on an in-memory
// structure
// that may occasionally give a false positive but guaranteed no false
// negatives
if (filter.Contains(text) == FuzzySet.ContainsResult.NO)
{
return false;
}
return Delegate.SeekExact(text);
}
public override sealed SeekStatus SeekCeil(BytesRef text)
{
return Delegate.SeekCeil(text);
}
public override sealed void SeekExact(long ord)
{
Delegate.SeekExact(ord);
}
public override sealed BytesRef Term => Delegate.Term;
public override sealed long Ord => Delegate.Ord;
public override sealed int DocFreq => Delegate.DocFreq;
public override sealed long TotalTermFreq => Delegate.TotalTermFreq;
public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs,
DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags)
{
return Delegate.DocsAndPositions(liveDocs, reuse, flags);
}
public override DocsEnum Docs(IBits liveDocs, DocsEnum reuse, DocsFlags flags)
{
return Delegate.Docs(liveDocs, reuse, flags);
}
}
public override long RamBytesUsed()
{
var sizeInBytes = ((_delegateFieldsProducer != null) ? _delegateFieldsProducer.RamBytesUsed() : 0);
foreach (var entry in _bloomsByFieldName)
{
sizeInBytes += entry.Key.Length * RamUsageEstimator.NUM_BYTES_CHAR;
sizeInBytes += entry.Value.RamBytesUsed();
}
return sizeInBytes;
}
public override void CheckIntegrity()
{
_delegateFieldsProducer.CheckIntegrity();
}
}
internal class BloomFilteredFieldsConsumer : FieldsConsumer
{
private readonly BloomFilteringPostingsFormat outerInstance;
private readonly FieldsConsumer _delegateFieldsConsumer;
private readonly Dictionary<FieldInfo, FuzzySet> _bloomFilters = new Dictionary<FieldInfo, FuzzySet>();
private readonly SegmentWriteState _state;
public BloomFilteredFieldsConsumer(BloomFilteringPostingsFormat outerInstance, FieldsConsumer fieldsConsumer,
SegmentWriteState state)
{
this.outerInstance = outerInstance;
_delegateFieldsConsumer = fieldsConsumer;
_state = state;
}
public override TermsConsumer AddField(FieldInfo field)
{
var bloomFilter = outerInstance._bloomFilterFactory.GetSetForField(_state, field);
if (bloomFilter != null)
{
Debug.Assert((_bloomFilters.ContainsKey(field) == false));
_bloomFilters.Add(field, bloomFilter);
return new WrappedTermsConsumer(_delegateFieldsConsumer.AddField(field), bloomFilter);
}
// No, use the unfiltered fieldsConsumer - we are not interested in
// recording any term Bitsets.
return _delegateFieldsConsumer.AddField(field);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_delegateFieldsConsumer.Dispose();
// Now we are done accumulating values for these fields
var nonSaturatedBlooms = new List<KeyValuePair<FieldInfo, FuzzySet>>();
foreach (var entry in _bloomFilters)
{
var bloomFilter = entry.Value;
if (!outerInstance._bloomFilterFactory.IsSaturated(bloomFilter, entry.Key))
nonSaturatedBlooms.Add(entry);
}
var bloomFileName = IndexFileNames.SegmentFileName(
_state.SegmentInfo.Name, _state.SegmentSuffix, BLOOM_EXTENSION);
IndexOutput bloomOutput = null;
try
{
bloomOutput = _state.Directory.CreateOutput(bloomFileName, _state.Context);
CodecUtil.WriteHeader(bloomOutput, /*BLOOM_CODEC_NAME*/ outerInstance.Name, VERSION_CURRENT);
// remember the name of the postings format we will delegate to
bloomOutput.WriteString(outerInstance._delegatePostingsFormat.Name);
// First field in the output file is the number of fields+blooms saved
bloomOutput.WriteInt32(nonSaturatedBlooms.Count);
foreach (var entry in nonSaturatedBlooms)
{
var fieldInfo = entry.Key;
var bloomFilter = entry.Value;
bloomOutput.WriteInt32(fieldInfo.Number);
SaveAppropriatelySizedBloomFilter(bloomOutput, bloomFilter, fieldInfo);
}
CodecUtil.WriteFooter(bloomOutput);
}
finally
{
IOUtils.Dispose(bloomOutput);
}
//We are done with large bitsets so no need to keep them hanging around
_bloomFilters.Clear();
}
}
private void SaveAppropriatelySizedBloomFilter(DataOutput bloomOutput,
FuzzySet bloomFilter, FieldInfo fieldInfo)
{
var rightSizedSet = outerInstance._bloomFilterFactory.Downsize(fieldInfo,
bloomFilter) ?? bloomFilter;
rightSizedSet.Serialize(bloomOutput);
}
}
internal class WrappedTermsConsumer : TermsConsumer
{
private readonly TermsConsumer _delegateTermsConsumer;
private readonly FuzzySet _bloomFilter;
public WrappedTermsConsumer(TermsConsumer termsConsumer, FuzzySet bloomFilter)
{
_delegateTermsConsumer = termsConsumer;
_bloomFilter = bloomFilter;
}
public override PostingsConsumer StartTerm(BytesRef text)
{
return _delegateTermsConsumer.StartTerm(text);
}
public override void FinishTerm(BytesRef text, TermStats stats)
{
// Record this term in our BloomFilter
if (stats.DocFreq > 0)
{
_bloomFilter.AddValue(text);
}
_delegateTermsConsumer.FinishTerm(text, stats);
}
public override void Finish(long sumTotalTermFreq, long sumDocFreq, int docCount)
{
_delegateTermsConsumer.Finish(sumTotalTermFreq, sumDocFreq, docCount);
}
public override IComparer<BytesRef> Comparer => _delegateTermsConsumer.Comparer;
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace applicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// RouteFiltersOperations operations.
/// </summary>
public partial interface IRouteFiltersOperations
{
/// <summary>
/// Deletes the specified route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='expand'>
/// Expands referenced express route bgp peering resources.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<RouteFilter>> GetWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a route filter in a specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the create or update route filter operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<RouteFilter>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates a route filter in a specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the update route filter operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<RouteFilter>> UpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all route filters in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<RouteFilter>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all route filters in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<RouteFilter>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a route filter in a specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the create or update route filter operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<RouteFilter>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates a route filter in a specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the update route filter operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<RouteFilter>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all route filters in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<RouteFilter>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all route filters in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<RouteFilter>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
#region The MIT License - Copyright (C) 2012-2016 Pieter Geerkens
/////////////////////////////////////////////////////////////////////////////////////////
// PG Software Solutions - Monad Utilities
/////////////////////////////////////////////////////////////////////////////////////////
// The MIT License:
// ----------------
//
// Copyright (c) 2012-2016 Pieter Geerkens (email: pgeerkens@hotmail.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
// NON-INFRINGEMENT. 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.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using PGSolutions.Monads;
using System;
namespace PGSolutions.Monads.Demos {
using StateBool = State<GcdStart,bool>;
using StateInt = State<GcdStart,int>;
using StateRes = State<GcdStart,GcdResult>;
using static State;
using static StateExtensions;
using static StateTransform;
using static BindingFlags;
using static GcdS4;
/// <summary>TODO</summary>
public interface ITest {
/// <summary>TODO</summary>
StateRes Transform { get; }
/// <summary>TODO</summary>
string Title { get; }
/// <summary>TODO</summary>
string Name { get; }
}
/// <summary>TODO</summary>
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores")]
public static class GcdS4 { // Beware! - These must be declared & initialized in this order
/// <summary>TODO</summary>
/// <param name="getAll">Specify true if old implementations desired to run as well as just nes ones.</param>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public static X<IEnumerable<ITest>> GetTests(bool getAll) => (
from item in (
from type in new List<Type>() { typeof(Imperative), typeof(Haskell), typeof(Linq), typeof(Best) }
from info in ( type.GetMethodDescriptions(s => s.Substring(0, 3) == "Run",
Static | NonPublic | Public,
f => f?.GetValue(null) as StateRes) | null )
select info
)
where getAll
|| ( item.Name != nameof(Haskell)+"."+nameof(Haskell.Run1)
&& item.Name != nameof(Haskell)+"."+nameof(Haskell.Run2)
&& item.Name != nameof(Linq) +"."+nameof(Linq.Run1)
&& item.Name != nameof(Linq) +"."+nameof(Linq.Run2)
)
select new Test(item.Details, item.Description, item.Name) as ITest
).AsX();
/// <summary>TODO</summary>
public static X<ITest> GetTest(string name) {
return ( from test in GetTests(true) | new List<ITest>()
where test.Name == name
select test
).FirstOrDefault().AsX();
}
#region Utilities
/// <summary>TODO</summary>
internal delegate StateRes ResultExtractor(StateInt stateInt);
/// <summary>TODO</summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
internal static readonly ResultExtractor GetResult = s => from gcd in s select new GcdResult(gcd);
/// <summary>Functor to calculate GCD of two input integers.</summary>
internal static readonly Transform<GcdStart> AlgorithmTransform = s => {
var x = s.A; var y = s.B; // explicitly exposes the immutability of s.
return x > y ? new GcdStart(x - y, y )
: x < y ? new GcdStart( x, y - x)
: s;
};
/// <summary>State monad to calculate GCD of two input integers.</summary>
internal static readonly StateBool AlgorithMonad = s => NewPayload(AlgorithmTransform(s), s.A != s.B);
/// <summary>Extract either member from state as the exposed int value.</summary>
internal static readonly StateInt GcdExtract = s => NewPayload(s, s.A);
/// <summary>TODO</summary>
internal struct Test : ITest {
/// <summary>TODO</summary>
public Test(StateRes transform, string title, string name) {
Transform = transform; Title = title; Name = name;
}
/// <summary>TODO</summary>
public StateRes Transform { get; }
/// <summary>TODO</summary>
public string Title { get; }
/// <summary>TODO</summary>
public string Name { get; }
}
#endregion
/// <summary>TODO</summary>
public static StateRes BestRun => s => Best.Run(s);
}
/// <summary>TODO</summary>
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
internal static class Imperative
{
// ~ 0.14 sec
/// <summary>TODO</summary>
[Description("Fully imperative; w/ substitution.")]
public static StateRes Run1 => GetResult(new StateInt(s => {
s.ContractedNotNull(nameof(s));
while(s.A != s.B) s = AlgorithmTransform(s);
return NewPayload(s, s.A);
}));
// ~ 0.04 sec
/// <summary>TODO</summary>
[Description("Fully imperative; unrolled w/ substitution.")]
public static StateRes Run2 => GetResult(new StateInt(s => {
s.ContractedNotNull(nameof(s));
while(s.A != s.B)
{
var x = s.A; var y = s.B;
s = x > y ? new GcdStart(x-y, x)
: x < y ? new GcdStart(x, y-x)
: s;
}
return NewPayload(s, s.A);
}));
}
/// <summary>TODO</summary>
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
internal static class Haskell
{
#region Older Haskell implementations
/* from http://mvanier.livejournal.com/5846.html
gcd_s3 :: State GCDState Int
gcd_s3 =
do (x, y) <- get
case compare x y of
GT -> do put (x-y, y )
gcd_s3
LT -> do put ( x, y-x)
gcd_s3
EQ -> return x
run_gcd_s3 :: Int -> Int -> Int
run_gcd_s3 x y = fst (runState gcd_s3 (x, y))
*/
private static readonly StateBool GcdBody = new StateBool(s => NewPayload(s, s.A != s.B));
// ~ 4.1 sec
/// <summary>TODO</summary>
[Description("Straight Haskel (iterative).")]
public static StateRes Run1 => GetResult(
GetCompose<GcdStart>(s =>
s.A > s.B ? Put(new GcdStart(s.A - s.B, s.B))
: s.A < s.B ? Put(new GcdStart(s.A, s.B - s.A))
: Put(s)).Then(GcdBody)
.DoWhile().Then(GcdExtract));
// ~ 2.6 sec
/// <summary>TODO</summary>
[Description("Straight Haskel w/ Modify() instead of Get.Compose(s => Put(transform(s))).")]
public static StateRes Run2 => GetResult(AlgorithmTransform.Modify().Then(GcdBody)
.DoWhile().Then(GcdExtract));
#endregion
// ~ 1.5 sec
/// <summary>TODO</summary>
[Description("Straight Haskel w/ DoWhile().")]
public static StateRes Run3 => GetResult(AlgorithMonad.DoWhile().Then(GcdExtract));
}
/// <summary>TODO</summary>
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
internal static class Linq
{
#region Older LINQ implementations
// ~ 3.5 sec
/// <summary>TODO</summary>
[Description("Basic LINQ w/ Enumerate(Transform<TState>, TState) and using l'let'.")]
public static StateRes Run1 => GetResult(new StateBool(start =>
(from payload in AlgorithMonad.Enumerate(start)
where !payload.Item2
select payload
).First()).Then(GcdExtract));
// ~ 2.3 sec
/// <summary>TODO</summary>
[Description("Better LINQ w/ Enumerate(State<TState,TValue>, TState).")]
public static StateRes Run2 => GetResult(new StateBool(start =>
(from payload in AlgorithMonad.Enumerate(start)
where !payload.Item2
select payload
).First()).Then(GcdExtract));
#endregion
// ~ 1.5 sec
/// <summary>TODO</summary>
[Description("Best LINQ w/ Enumerate(Transform<TState>, TState) and w/o using 'let'.")]
public static StateRes Run3 => GetResult(new StateInt(start =>
( from s in AlgorithmTransform.Enumerate(start)
where s.A == s.B
select NewPayload(s, s.A)
).First()));
}
/// <summary>TODO</summary>
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
internal static class Best
{
// ~ 1.0 sec
/// <summary>TODO</summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
[Description("Optimized DoWhile().")]
public static StateRes Run => GetResult(AlgorithmTransform.DoWhile(s => s.A != s.B)
.Then(GcdExtract));
}
}
| |
using System;
using System.Linq;
using CppSharp.AST;
using CppSharp.AST.Extensions;
using CppSharp.Generators.CSharp;
using CppSharp.Passes;
using NUnit.Framework;
namespace CppSharp.Generator.Tests.AST
{
[TestFixture]
public class TestAST : ASTTestFixture
{
[OneTimeSetUp]
public void Init()
{
CppSharp.AST.Type.TypePrinterDelegate = type =>
{
PrimitiveType primitiveType;
return type.IsPrimitiveType(out primitiveType) ? primitiveType.ToString() : string.Empty;
};
ParseLibrary("AST.h", "ASTExtensions.h");
}
[OneTimeTearDown]
public void CleanUp()
{
ParserOptions.Dispose();
}
[Test]
public void TestASTParameter()
{
var func = AstContext.FindFunction("TestParameterProperties").FirstOrDefault();
Assert.IsNotNull(func);
var paramNames = new[] { "a", "b", "c" };
var paramTypes = new[]
{
new QualifiedType(new BuiltinType(PrimitiveType.Bool)),
new QualifiedType(
new PointerType()
{
Modifier = PointerType.TypeModifier.LVReference,
QualifiedPointee = new QualifiedType(
new BuiltinType(PrimitiveType.Short),
new TypeQualifiers { IsConst = true })
}),
new QualifiedType(
new PointerType
{
Modifier = PointerType.TypeModifier.Pointer,
QualifiedPointee = new QualifiedType(new BuiltinType(PrimitiveType.Int))
})
};
for (int i = 0; i < func.Parameters.Count; i++)
{
var param = func.Parameters[i];
Assert.AreEqual(paramNames[i], param.Name, "Parameter.Name");
Assert.AreEqual(paramTypes[i], param.QualifiedType, "Parameter.QualifiedType");
Assert.AreEqual(i, param.Index, "Parameter.Index");
}
Assert.IsTrue(func.Parameters[2].HasDefaultValue, "Parameter.HasDefaultValue");
}
[Test]
public void TestASTHelperMethods()
{
var @class = AstContext.FindClass("Math::Complex").FirstOrDefault();
Assert.IsNotNull(@class, "Couldn't find Math::Complex class.");
var plusOperator = @class.FindOperator(CXXOperatorKind.Plus).FirstOrDefault();
Assert.IsNotNull(plusOperator, "Couldn't find operator+ in Math::Complex class.");
var typedef = AstContext.FindTypedef("Math::Single").FirstOrDefault();
Assert.IsNotNull(typedef);
}
#region TestVisitor
class TestVisitor : IDeclVisitor<bool>
{
public bool VisitDeclaration(Declaration decl)
{
throw new System.NotImplementedException();
}
public bool VisitTranslationUnit(TranslationUnit unit)
{
throw new System.NotImplementedException();
}
public bool VisitClassDecl(Class @class)
{
throw new System.NotImplementedException();
}
public bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecialization specialization)
{
throw new NotImplementedException();
}
public bool VisitFieldDecl(Field field)
{
throw new System.NotImplementedException();
}
public bool VisitFunctionDecl(Function function)
{
throw new System.NotImplementedException();
}
public bool VisitMethodDecl(Method method)
{
return true;
}
public bool VisitParameterDecl(Parameter parameter)
{
throw new System.NotImplementedException();
}
public bool VisitTypedefDecl(TypedefDecl typedef)
{
throw new System.NotImplementedException();
}
public bool VisitTypeAliasDecl(TypeAlias typeAlias)
{
throw new NotImplementedException();
}
public bool VisitEnumDecl(Enumeration @enum)
{
throw new System.NotImplementedException();
}
public bool VisitEnumItemDecl(Enumeration.Item item)
{
throw new NotImplementedException();
}
public bool VisitVariableDecl(Variable variable)
{
throw new System.NotImplementedException();
}
public bool VisitClassTemplateDecl(ClassTemplate template)
{
throw new System.NotImplementedException();
}
public bool VisitFunctionTemplateDecl(FunctionTemplate template)
{
throw new System.NotImplementedException();
}
public bool VisitMacroDefinition(MacroDefinition macro)
{
throw new System.NotImplementedException();
}
public bool VisitNamespace(Namespace @namespace)
{
throw new System.NotImplementedException();
}
public bool VisitEvent(Event @event)
{
throw new System.NotImplementedException();
}
public bool VisitProperty(Property property)
{
throw new System.NotImplementedException();
}
public bool VisitFriend(Friend friend)
{
throw new System.NotImplementedException();
}
public bool VisitTemplateParameterDecl(TypeTemplateParameter templateParameter)
{
throw new NotImplementedException();
}
public bool VisitNonTypeTemplateParameterDecl(NonTypeTemplateParameter nonTypeTemplateParameter)
{
throw new NotImplementedException();
}
public bool VisitTemplateTemplateParameterDecl(TemplateTemplateParameter templateTemplateParameter)
{
throw new NotImplementedException();
}
public bool VisitTypeAliasTemplateDecl(TypeAliasTemplate typeAliasTemplate)
{
throw new NotImplementedException();
}
public bool VisitFunctionTemplateSpecializationDecl(FunctionTemplateSpecialization specialization)
{
throw new NotImplementedException();
}
public bool VisitVarTemplateDecl(VarTemplate template)
{
throw new NotImplementedException();
}
public bool VisitVarTemplateSpecializationDecl(VarTemplateSpecialization template)
{
throw new NotImplementedException();
}
public bool VisitTypedefNameDecl(TypedefNameDecl typedef)
{
throw new NotImplementedException();
}
}
#endregion
[Test]
public void TestASTVisitor()
{
var testVisitor = new TestVisitor();
var plusOperator = AstContext.TranslationUnits
.SelectMany(u => u.Namespaces.Where(n => n.Name == "Math"))
.SelectMany(n => n.Classes.Where(c => c.Name == "Complex"))
.SelectMany(c => c.Methods.Where(m => m.OperatorKind == CXXOperatorKind.Plus))
.First();
Assert.IsTrue(plusOperator.Visit(testVisitor));
}
[Test]
public void TestASTEnumItemByName()
{
var @enum = AstContext.FindEnum("TestASTEnumItemByName").Single();
Assert.NotNull(@enum);
Assert.IsTrue(@enum.ItemsByName.ContainsKey("TestItemByName"));
}
[Test]
public void TestASTFunctionTemplates()
{
var @class = AstContext.FindClass("TestTemplateFunctions").FirstOrDefault();
Assert.IsNotNull(@class, "Couldn't find TestTemplateFunctions class.");
Assert.AreEqual(6, @class.Templates.Count);
var twoParamMethodTemplate = @class.Templates.OfType<FunctionTemplate>()
.FirstOrDefault(t => t.Name == "MethodTemplateWithTwoTypeParameter");
Assert.IsNotNull(twoParamMethodTemplate);
Assert.AreEqual(2, twoParamMethodTemplate.Parameters.Count);
Assert.AreEqual("T", twoParamMethodTemplate.Parameters[0].Name);
Assert.AreEqual("S", twoParamMethodTemplate.Parameters[1].Name);
var twoParamMethod = twoParamMethodTemplate.TemplatedFunction as Method;
Assert.IsNotNull(twoParamMethod);
Assert.IsInstanceOf<TemplateParameterType>(twoParamMethod.Parameters[0].Type);
Assert.IsInstanceOf<TemplateParameterType>(twoParamMethod.Parameters[1].Type);
Assert.AreEqual(twoParamMethodTemplate.Parameters[0],
((TemplateParameterType) twoParamMethod.Parameters[0].Type).Parameter);
Assert.AreEqual(twoParamMethodTemplate.Parameters[1],
((TemplateParameterType) twoParamMethod.Parameters[1].Type).Parameter);
Assert.AreEqual(0, ((TemplateParameterType) twoParamMethod.Parameters[0].Type).Index);
Assert.AreEqual(1, ((TemplateParameterType) twoParamMethod.Parameters[1].Type).Index);
}
[Test]
public void TestASTClassTemplates()
{
var template = AstContext.TranslationUnits
.SelectMany(u => u.Templates.OfType<ClassTemplate>())
.FirstOrDefault(t => t.Name == "TestTemplateClass");
Assert.IsNotNull(template, "Couldn't find TestTemplateClass class.");
Assert.AreEqual(1, template.Parameters.Count);
var templateTypeParameter = template.Parameters[0];
Assert.AreEqual("T", templateTypeParameter.Name);
var ctor = template.TemplatedClass.Constructors
.FirstOrDefault(c => c.Parameters.Count == 1 && c.Parameters[0].Name == "v");
Assert.IsNotNull(ctor);
var paramType = ctor.Parameters[0].Type as TemplateParameterType;
Assert.IsNotNull(paramType);
Assert.AreEqual(templateTypeParameter, paramType.Parameter);
Assert.AreEqual(5, template.Specializations.Count);
Assert.AreEqual(TemplateSpecializationKind.ExplicitInstantiationDefinition, template.Specializations[0].SpecializationKind);
Assert.AreEqual(TemplateSpecializationKind.ExplicitInstantiationDefinition, template.Specializations[3].SpecializationKind);
Assert.AreEqual(TemplateSpecializationKind.Undeclared, template.Specializations[4].SpecializationKind);
var typeDef = AstContext.FindTypedef("TestTemplateClassInt").FirstOrDefault();
Assert.IsNotNull(typeDef, "Couldn't find TestTemplateClassInt typedef.");
var integerInst = typeDef.Type as TemplateSpecializationType;
Assert.AreEqual(1, integerInst.Arguments.Count);
var intArgument = integerInst.Arguments[0];
Assert.AreEqual(new BuiltinType(PrimitiveType.Int), intArgument.Type.Type);
ClassTemplateSpecialization classTemplateSpecialization;
Assert.IsTrue(typeDef.Type.TryGetDeclaration(out classTemplateSpecialization));
Assert.AreSame(classTemplateSpecialization.TemplatedDecl.TemplatedClass, template.TemplatedClass);
}
[Test]
public void TestFindClassInNamespace()
{
Assert.IsNotNull(AstContext.FindClass("HiddenInNamespace").FirstOrDefault());
}
[Test]
public void TestLineNumber()
{
Assert.AreEqual(70, AstContext.FindClass("HiddenInNamespace").First().LineNumberStart);
}
[Test]
public void TestLineNumberOfFriend()
{
Assert.AreEqual(93, AstContext.FindFunction("operator+").First().LineNumberStart);
}
static string StripWindowsNewLines(string text)
{
return text.ReplaceLineBreaks(string.Empty);
}
[Test]
public void TestSignature()
{
Assert.AreEqual("void testSignature()", AstContext.FindFunction("testSignature").Single().Signature);
Assert.AreEqual("void testImpl(){}",
StripWindowsNewLines(AstContext.FindFunction("testImpl").Single().Signature));
Assert.AreEqual("void testConstSignature() const",
AstContext.FindClass("HasConstFunction").Single().FindMethod("testConstSignature").Signature);
Assert.AreEqual("void testConstSignatureWithTrailingMacro() const",
AstContext.FindClass("HasConstFunction").Single().FindMethod("testConstSignatureWithTrailingMacro").Signature);
// TODO: restore when the const of a return type is fixed properly
//Assert.AreEqual("const int& testConstRefSignature()", AstContext.FindClass("HasConstFunction").Single().FindMethod("testConstRefSignature").Signature);
//Assert.AreEqual("const int& testStaticConstRefSignature()", AstContext.FindClass("HasConstFunction").Single().FindMethod("testStaticConstRefSignature").Signature);
}
[Test]
public void TestAmbiguity()
{
new CheckAmbiguousFunctions { Context = Driver.Context }.VisitASTContext(AstContext);
Assert.IsTrue(AstContext.FindClass("HasAmbiguousFunctions").Single().FindMethod("ambiguous").IsAmbiguous);
}
[Test]
public void TestAtomics()
{
var type = AstContext.FindClass("Atomics").Single().Fields
.Find(f => f.Name == "AtomicInt").Type as BuiltinType;
Assert.IsTrue(type != null && type.IsPrimitiveType(PrimitiveType.Int));
}
[Test]
public void TestMacroLineNumber()
{
Assert.AreEqual(103, AstContext.FindClass("HasAmbiguousFunctions").First().Specifiers.Last().LineNumberStart);
}
[Test]
public void TestImplicitDeclaration()
{
Assert.IsTrue(AstContext.FindClass("ImplicitCtor").First().Constructors.First(
c => c.Parameters.Count == 0).IsImplicit);
}
[Test]
public void TestSpecializationArguments()
{
var classTemplate = AstContext.FindDecl<ClassTemplate>("TestSpecializationArguments").FirstOrDefault();
Assert.IsTrue(classTemplate.Specializations[0].Arguments[0].Type.Type.IsPrimitiveType(PrimitiveType.Int));
}
[Test]
public void TestFunctionInstantiatedFrom()
{
var classTemplate = AstContext.FindDecl<ClassTemplate>("TestSpecializationArguments").FirstOrDefault();
Assert.AreEqual(classTemplate.Specializations[0].Constructors.First(
c => !c.IsCopyConstructor && !c.IsMoveConstructor).InstantiatedFrom,
classTemplate.TemplatedClass.Constructors.First(c => !c.IsCopyConstructor && !c.IsMoveConstructor));
}
[Test]
public void TestComments()
{
var @class = AstContext.FindCompleteClass("TestComments");
var commentClass = @class.Comment.FullComment.CommentToString(CommentKind.BCPLSlash);
Assert.AreEqual(@"/// <summary>
/// <para>Hash set/map base class.</para>
/// <para>Note that to prevent extra memory use due to vtable pointer, %HashBase intentionally does not declare a virtual destructor</para>
/// <para>and therefore %HashBase pointers should never be used.</para>
/// </summary>".Replace("\r", string.Empty), commentClass.Replace("\r", string.Empty));
var method = @class.Methods.First(m => m.Name == "GetIOHandlerControlSequence");
var commentMethod = method.Comment.FullComment.CommentToString(CommentKind.BCPL);
Assert.AreEqual(@"// <summary>
// <para>Get the string that needs to be written to the debugger stdin file</para>
// <para>handle when a control character is typed.</para>
// </summary>
// <param name=""ch"">The character that was typed along with the control key</param>
// <returns>
// <para>The string that should be written into the file handle that is</para>
// <para>feeding the input stream for the debugger, or NULL if there is</para>
// <para>no string for this control key.</para>
// </returns>
// <remarks>
// <para>Some GUI programs will intercept "control + char" sequences and want</para>
// <para>to have them do what normally would happen when using a real</para>
// <para>terminal, so this function allows GUI programs to emulate this</para>
// <para>functionality.</para>
// </remarks>".Replace("\r", string.Empty), commentMethod.Replace("\r", string.Empty));
var methodTestDoxygen = @class.Methods.First(m => m.Name == "SBAttachInfo");
var commentMethodDoxygen = methodTestDoxygen.Comment.FullComment.CommentToString(CommentKind.BCPLSlash);
Assert.AreEqual(@"/// <summary>Attach to a process by name.</summary>
/// <param name=""path"">A full or partial name for the process to attach to.</param>
/// <param name=""wait_for"">
/// <para>If <c>false,</c> attach to an existing process whose name matches.</para>
/// <para>If <c>true,</c> then wait for the next process whose name matches.</para>
/// </param>
/// <remarks>
/// <para>This function implies that a future call to SBTarget::Attach(...)</para>
/// <para>will be synchronous.</para>
/// </remarks>".Replace("\r", string.Empty), commentMethodDoxygen.Replace("\r", string.Empty));
}
[Test]
public void TestCompletionOfClassTemplates()
{
var templates = AstContext.FindDecl<ClassTemplate>("ForwardedTemplate").ToList();
var template = templates.Single(t => t.DebugText.Replace("\r", string.Empty) ==
"template <typename T>\r\nclass ForwardedTemplate\r\n{\r\n}".Replace("\r", string.Empty));
Assert.IsFalse(template.IsIncomplete);
}
[Test]
public void TestOriginalNamesOfSpecializations()
{
var template = AstContext.FindDecl<ClassTemplate>("TestSpecializationArguments").First();
Assert.That(template.Specializations[0].Constructors.First().QualifiedName,
Is.Not.EqualTo(template.Specializations[1].Constructors.First().QualifiedName));
}
[Test]
public void TestPrintingConstPointerWithConstType()
{
var cppTypePrinter = new CppTypePrinter { PrintScopeKind = TypePrintScopeKind.Qualified };
var builtin = new BuiltinType(PrimitiveType.Char);
var pointee = new QualifiedType(builtin, new TypeQualifiers { IsConst = true });
var pointer = new QualifiedType(new PointerType(pointee), new TypeQualifiers { IsConst = true });
var type = pointer.Visit(cppTypePrinter);
Assert.That(type, Is.EqualTo("const char* const"));
}
[Test]
public void TestPrintingSpecializationWithConstValue()
{
var template = AstContext.FindDecl<ClassTemplate>("TestSpecializationArguments").First();
var cppTypePrinter = new CppTypePrinter { PrintScopeKind = TypePrintScopeKind.Qualified };
Assert.That(template.Specializations.Last().Visit(cppTypePrinter),
Is.EqualTo("TestSpecializationArguments<const TestASTEnumItemByName>"));
}
[Test]
public void TestLayoutBase()
{
var @class = AstContext.FindCompleteClass("TestComments");
Assert.That(@class.Layout.Bases.Count, Is.EqualTo(0));
}
[Test]
public void TestFunctionSpecifications()
{
var constExprNoExcept = AstContext.FindFunction("constExprNoExcept").First();
Assert.IsTrue(constExprNoExcept.IsConstExpr);
var functionType = (FunctionType) constExprNoExcept.FunctionType.Type;
Assert.That(functionType.ExceptionSpecType,
Is.EqualTo(ExceptionSpecType.BasicNoexcept));
var regular = AstContext.FindFunction("testSignature").First();
Assert.IsFalse(regular.IsConstExpr);
var regularFunctionType = (FunctionType) regular.FunctionType.Type;
Assert.That(regularFunctionType.ExceptionSpecType,
Is.EqualTo(ExceptionSpecType.None));
}
[Test]
public void TestFunctionSpecializationInfo()
{
var functionWithSpecInfo = AstContext.FindFunction(
"functionWithSpecInfo").First(f => !f.IsDependent);
var @float = new QualifiedType(new BuiltinType(PrimitiveType.Float));
Assert.That(functionWithSpecInfo.SpecializationInfo.Arguments.Count, Is.EqualTo(2));
foreach (var arg in functionWithSpecInfo.SpecializationInfo.Arguments)
Assert.That(arg.Type, Is.EqualTo(@float));
}
[Test]
public void TestVolatile()
{
var cppTypePrinter = new CppTypePrinter { PrintScopeKind = TypePrintScopeKind.Qualified };
var builtin = new BuiltinType(PrimitiveType.Char);
var pointee = new QualifiedType(builtin, new TypeQualifiers { IsConst = true, IsVolatile = true });
var type = pointee.Visit(cppTypePrinter);
Assert.That(type, Is.EqualTo("const volatile char"));
}
[Test]
public void TestFindFunctionInNamespace()
{
var function = AstContext.FindFunction("Math::function").FirstOrDefault();
Assert.That(function, Is.Not.Null);
}
[Test]
public void TestPrintNestedInSpecialization()
{
var template = AstContext.FindDecl<ClassTemplate>("TestTemplateClass").First();
var cppTypePrinter = new CppTypePrinter { PrintScopeKind = TypePrintScopeKind.Qualified };
Assert.That(template.Specializations[3].Classes[0].Visit(cppTypePrinter),
Is.EqualTo("TestTemplateClass<Math::Complex>::NestedInTemplate"));
}
[Test]
public void TestPrintQualifiedSpecialization()
{
var functionWithSpecializationArg = AstContext.FindFunction("functionWithSpecializationArg").First();
var cppTypePrinter = new CppTypePrinter { PrintScopeKind = TypePrintScopeKind.Qualified };
Assert.That(functionWithSpecializationArg.Parameters[0].Visit(cppTypePrinter),
Is.EqualTo("const TestTemplateClass<int>"));
}
[Test]
public void TestDependentNameType()
{
var template = AstContext.FindDecl<ClassTemplate>(
"TestSpecializationArguments").First();
var type = template.TemplatedClass.Fields[0].Type.Visit(
new CSharpTypePrinter(Driver.Context));
Assert.That($"{type}",
Is.EqualTo("global::Test.TestTemplateClass<T>.NestedInTemplate"));
}
}
}
| |
namespace System.Workflow.Activities.Rules.Design
{
partial class RuleSetDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RuleSetDialog));
this.nameColumnHeader = new System.Windows.Forms.ColumnHeader();
this.rulesListView = new System.Windows.Forms.ListView();
this.priorityColumnHeader = new System.Windows.Forms.ColumnHeader();
this.reevaluationCountColumnHeader = new System.Windows.Forms.ColumnHeader();
this.activeColumnHeader = new System.Windows.Forms.ColumnHeader();
this.rulePreviewColumnHeader = new System.Windows.Forms.ColumnHeader();
this.rulesGroupBox = new System.Windows.Forms.GroupBox();
this.panel1 = new System.Windows.Forms.Panel();
this.chainingLabel = new System.Windows.Forms.Label();
this.chainingBehaviourComboBox = new System.Windows.Forms.ComboBox();
this.rulesToolStrip = new System.Windows.Forms.ToolStrip();
this.imageList = new System.Windows.Forms.ImageList(this.components);
this.newRuleToolStripButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.deleteToolStripButton = new System.Windows.Forms.ToolStripButton();
this.buttonOK = new System.Windows.Forms.Button();
this.ruleGroupBox = new System.Windows.Forms.GroupBox();
this.reevaluationComboBox = new System.Windows.Forms.ComboBox();
this.elseTextBox = new System.Workflow.Activities.Rules.Design.IntellisenseTextBox();
this.elseLabel = new System.Windows.Forms.Label();
this.thenTextBox = new System.Workflow.Activities.Rules.Design.IntellisenseTextBox();
this.thenLabel = new System.Windows.Forms.Label();
this.conditionTextBox = new System.Workflow.Activities.Rules.Design.IntellisenseTextBox();
this.conditionLabel = new System.Windows.Forms.Label();
this.nameTextBox = new System.Windows.Forms.TextBox();
this.nameLabel = new System.Windows.Forms.Label();
this.activeCheckBox = new System.Windows.Forms.CheckBox();
this.reevaluationLabel = new System.Windows.Forms.Label();
this.priorityTextBox = new System.Windows.Forms.TextBox();
this.priorityLabel = new System.Windows.Forms.Label();
this.buttonCancel = new System.Windows.Forms.Button();
this.headerTextLabel = new System.Windows.Forms.Label();
this.pictureBoxHeader = new System.Windows.Forms.PictureBox();
this.okCancelTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.conditionErrorProvider = new System.Windows.Forms.ErrorProvider(this.components);
this.thenErrorProvider = new System.Windows.Forms.ErrorProvider(this.components);
this.elseErrorProvider = new System.Windows.Forms.ErrorProvider(this.components);
this.rulesGroupBox.SuspendLayout();
this.panel1.SuspendLayout();
this.rulesToolStrip.SuspendLayout();
this.ruleGroupBox.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxHeader)).BeginInit();
this.okCancelTableLayoutPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.conditionErrorProvider)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.thenErrorProvider)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.elseErrorProvider)).BeginInit();
this.SuspendLayout();
//
// nameColumnHeader
//
this.nameColumnHeader.Name = "nameColumnHeader";
resources.ApplyResources(this.nameColumnHeader, "nameColumnHeader");
//
// rulesListView
//
this.rulesListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.nameColumnHeader,
this.priorityColumnHeader,
this.reevaluationCountColumnHeader,
this.activeColumnHeader,
this.rulePreviewColumnHeader});
resources.ApplyResources(this.rulesListView, "rulesListView");
this.rulesListView.FullRowSelect = true;
this.rulesListView.HideSelection = false;
this.rulesListView.MultiSelect = false;
this.rulesListView.Name = "rulesListView";
this.rulesListView.UseCompatibleStateImageBehavior = false;
this.rulesListView.View = System.Windows.Forms.View.Details;
this.rulesListView.SelectedIndexChanged += new System.EventHandler(this.rulesListView_SelectedIndexChanged);
this.rulesListView.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.rulesListView_ColumnClick);
//
// priorityColumnHeader
//
resources.ApplyResources(this.priorityColumnHeader, "priorityColumnHeader");
//
// reevaluationCountColumnHeader
//
resources.ApplyResources(this.reevaluationCountColumnHeader, "reevaluationCountColumnHeader");
//
// activeColumnHeader
//
resources.ApplyResources(this.activeColumnHeader, "activeColumnHeader");
//
// rulePreviewColumnHeader
//
resources.ApplyResources(this.rulePreviewColumnHeader, "rulePreviewColumnHeader");
//
// rulesGroupBox
//
this.rulesGroupBox.Controls.Add(this.panel1);
resources.ApplyResources(this.rulesGroupBox, "rulesGroupBox");
this.rulesGroupBox.Name = "rulesGroupBox";
this.rulesGroupBox.TabStop = false;
//
// panel1
//
this.panel1.Controls.Add(this.chainingLabel);
this.panel1.Controls.Add(this.chainingBehaviourComboBox);
this.panel1.Controls.Add(this.rulesToolStrip);
this.panel1.Controls.Add(this.rulesListView);
resources.ApplyResources(this.panel1, "panel1");
this.panel1.Name = "panel1";
//
// chainingLabel
//
resources.ApplyResources(this.chainingLabel, "chainingLabel");
this.chainingLabel.Name = "chainingLabel";
//
// chainingBehaviourComboBox
//
this.chainingBehaviourComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.chainingBehaviourComboBox.FormattingEnabled = true;
resources.ApplyResources(this.chainingBehaviourComboBox, "chainingBehaviourComboBox");
this.chainingBehaviourComboBox.Name = "chainingBehaviourComboBox";
this.chainingBehaviourComboBox.SelectedIndexChanged += new System.EventHandler(this.chainingBehaviourComboBox_SelectedIndexChanged);
//
// rulesToolStrip
//
this.rulesToolStrip.BackColor = System.Drawing.SystemColors.Control;
this.rulesToolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.rulesToolStrip.ImageList = this.imageList;
this.rulesToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newRuleToolStripButton,
this.toolStripSeparator1,
this.deleteToolStripButton});
resources.ApplyResources(this.rulesToolStrip, "rulesToolStrip");
this.rulesToolStrip.Name = "rulesToolStrip";
this.rulesToolStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
this.rulesToolStrip.TabStop = true;
//
// imageList
//
this.imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList.ImageStream")));
this.imageList.TransparentColor = System.Drawing.Color.Transparent;
this.imageList.Images.SetKeyName(0, "NewRule.bmp");
this.imageList.Images.SetKeyName(1, "RenameRule.bmp");
this.imageList.Images.SetKeyName(2, "Delete.bmp");
//
// newRuleToolStripButton
//
resources.ApplyResources(this.newRuleToolStripButton, "newRuleToolStripButton");
this.newRuleToolStripButton.Name = "newRuleToolStripButton";
this.newRuleToolStripButton.Click += new System.EventHandler(this.newRuleToolStripButton_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1");
//
// deleteToolStripButton
//
resources.ApplyResources(this.deleteToolStripButton, "deleteToolStripButton");
this.deleteToolStripButton.Name = "deleteToolStripButton";
this.deleteToolStripButton.Click += new System.EventHandler(this.deleteToolStripButton_Click);
//
// buttonOK
//
resources.ApplyResources(this.buttonOK, "buttonOK");
this.buttonOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.buttonOK.Name = "buttonOK";
//
// ruleGroupBox
//
this.ruleGroupBox.Controls.Add(this.reevaluationComboBox);
this.ruleGroupBox.Controls.Add(this.elseTextBox);
this.ruleGroupBox.Controls.Add(this.elseLabel);
this.ruleGroupBox.Controls.Add(this.thenTextBox);
this.ruleGroupBox.Controls.Add(this.thenLabel);
this.ruleGroupBox.Controls.Add(this.conditionTextBox);
this.ruleGroupBox.Controls.Add(this.conditionLabel);
this.ruleGroupBox.Controls.Add(this.nameTextBox);
this.ruleGroupBox.Controls.Add(this.nameLabel);
this.ruleGroupBox.Controls.Add(this.activeCheckBox);
this.ruleGroupBox.Controls.Add(this.reevaluationLabel);
this.ruleGroupBox.Controls.Add(this.priorityTextBox);
this.ruleGroupBox.Controls.Add(this.priorityLabel);
resources.ApplyResources(this.ruleGroupBox, "ruleGroupBox");
this.ruleGroupBox.Name = "ruleGroupBox";
this.ruleGroupBox.TabStop = false;
//
// reevaluationComboBox
//
this.reevaluationComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.reevaluationComboBox.FormattingEnabled = true;
resources.ApplyResources(this.reevaluationComboBox, "reevaluationComboBox");
this.reevaluationComboBox.Name = "reevaluationComboBox";
this.reevaluationComboBox.SelectedIndexChanged += new System.EventHandler(this.reevaluationComboBox_SelectedIndexChanged);
//
// elseTextBox
//
this.elseTextBox.AcceptsReturn = true;
resources.ApplyResources(this.elseTextBox, "elseTextBox");
this.elseTextBox.Name = "elseTextBox";
this.elseTextBox.Validating += new System.ComponentModel.CancelEventHandler(this.elseTextBox_Validating);
//
// elseLabel
//
resources.ApplyResources(this.elseLabel, "elseLabel");
this.elseLabel.Name = "elseLabel";
//
// thenTextBox
//
this.thenTextBox.AcceptsReturn = true;
resources.ApplyResources(this.thenTextBox, "thenTextBox");
this.thenTextBox.Name = "thenTextBox";
this.thenTextBox.Validating += new System.ComponentModel.CancelEventHandler(this.thenTextBox_Validating);
//
// thenLabel
//
resources.ApplyResources(this.thenLabel, "thenLabel");
this.thenLabel.Name = "thenLabel";
//
// conditionTextBox
//
this.conditionTextBox.AcceptsReturn = true;
resources.ApplyResources(this.conditionTextBox, "conditionTextBox");
this.conditionTextBox.Name = "conditionTextBox";
this.conditionTextBox.Validating += new System.ComponentModel.CancelEventHandler(this.conditionTextBox_Validating);
//
// conditionLabel
//
resources.ApplyResources(this.conditionLabel, "conditionLabel");
this.conditionLabel.Name = "conditionLabel";
//
// nameTextBox
//
resources.ApplyResources(this.nameTextBox, "nameTextBox");
this.nameTextBox.Name = "nameTextBox";
this.nameTextBox.Validating += new System.ComponentModel.CancelEventHandler(this.nameTextBox_Validating);
//
// nameLabel
//
resources.ApplyResources(this.nameLabel, "nameLabel");
this.nameLabel.Name = "nameLabel";
//
// activeCheckBox
//
resources.ApplyResources(this.activeCheckBox, "activeCheckBox");
this.activeCheckBox.Name = "activeCheckBox";
this.activeCheckBox.CheckedChanged += new System.EventHandler(this.activeCheckBox_CheckedChanged);
//
// reevaluationLabel
//
resources.ApplyResources(this.reevaluationLabel, "reevaluationLabel");
this.reevaluationLabel.Name = "reevaluationLabel";
//
// priorityTextBox
//
resources.ApplyResources(this.priorityTextBox, "priorityTextBox");
this.priorityTextBox.Name = "priorityTextBox";
this.priorityTextBox.Validating += new System.ComponentModel.CancelEventHandler(this.priorityTextBox_Validating);
//
// priorityLabel
//
resources.ApplyResources(this.priorityLabel, "priorityLabel");
this.priorityLabel.Name = "priorityLabel";
//
// buttonCancel
//
resources.ApplyResources(this.buttonCancel, "buttonCancel");
this.buttonCancel.CausesValidation = false;
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// headerTextLabel
//
resources.ApplyResources(this.headerTextLabel, "headerTextLabel");
this.headerTextLabel.Name = "headerTextLabel";
//
// pictureBoxHeader
//
resources.ApplyResources(this.pictureBoxHeader, "pictureBoxHeader");
this.pictureBoxHeader.Name = "pictureBoxHeader";
this.pictureBoxHeader.TabStop = false;
//
// okCancelTableLayoutPanel
//
resources.ApplyResources(this.okCancelTableLayoutPanel, "okCancelTableLayoutPanel");
this.okCancelTableLayoutPanel.CausesValidation = false;
this.okCancelTableLayoutPanel.Controls.Add(this.buttonOK, 0, 0);
this.okCancelTableLayoutPanel.Controls.Add(this.buttonCancel, 1, 0);
this.okCancelTableLayoutPanel.Name = "okCancelTableLayoutPanel";
//
// conditionErrorProvider
//
this.conditionErrorProvider.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.NeverBlink;
this.conditionErrorProvider.ContainerControl = this;
//
// thenErrorProvider
//
this.thenErrorProvider.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.NeverBlink;
this.thenErrorProvider.ContainerControl = this;
//
// elseErrorProvider
//
this.elseErrorProvider.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.NeverBlink;
this.elseErrorProvider.ContainerControl = this;
//
// RuleSetDialog
//
this.AcceptButton = this.buttonOK;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.buttonCancel;
this.Controls.Add(this.ruleGroupBox);
this.Controls.Add(this.headerTextLabel);
this.Controls.Add(this.pictureBoxHeader);
this.Controls.Add(this.okCancelTableLayoutPanel);
this.Controls.Add(this.rulesGroupBox);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.HelpButton = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "RuleSetDialog";
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.rulesGroupBox.ResumeLayout(false);
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.rulesToolStrip.ResumeLayout(false);
this.rulesToolStrip.PerformLayout();
this.ruleGroupBox.ResumeLayout(false);
this.ruleGroupBox.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxHeader)).EndInit();
this.okCancelTableLayoutPanel.ResumeLayout(false);
this.okCancelTableLayoutPanel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.conditionErrorProvider)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.thenErrorProvider)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.elseErrorProvider)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
void buttonCancel_Click(object sender, EventArgs e)
{
this.conditionTextBox.Validating -= this.conditionTextBox_Validating;
this.thenTextBox.Validating -= this.thenTextBox_Validating;
this.elseTextBox.Validating -= this.elseTextBox_Validating;
}
#endregion
private System.Windows.Forms.ColumnHeader nameColumnHeader;
private System.Windows.Forms.ListView rulesListView;
private System.Windows.Forms.ColumnHeader priorityColumnHeader;
private System.Windows.Forms.ColumnHeader reevaluationCountColumnHeader;
private System.Windows.Forms.ColumnHeader activeColumnHeader;
private System.Windows.Forms.ColumnHeader rulePreviewColumnHeader;
private System.Windows.Forms.GroupBox rulesGroupBox;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.ToolStrip rulesToolStrip;
private System.Windows.Forms.ToolStripButton newRuleToolStripButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripButton deleteToolStripButton;
private System.Windows.Forms.ImageList imageList;
private System.Windows.Forms.Button buttonOK;
private System.Windows.Forms.GroupBox ruleGroupBox;
private System.Windows.Forms.Button buttonCancel;
private System.Windows.Forms.Label headerTextLabel;
private System.Windows.Forms.PictureBox pictureBoxHeader;
private System.Windows.Forms.TableLayoutPanel okCancelTableLayoutPanel;
private System.Windows.Forms.CheckBox activeCheckBox;
private System.Windows.Forms.Label reevaluationLabel;
private System.Windows.Forms.TextBox priorityTextBox;
private System.Windows.Forms.Label priorityLabel;
private System.Windows.Forms.TextBox nameTextBox;
private System.Windows.Forms.Label nameLabel;
private System.Windows.Forms.ErrorProvider conditionErrorProvider;
private System.Windows.Forms.ErrorProvider thenErrorProvider;
private System.Windows.Forms.ErrorProvider elseErrorProvider;
private IntellisenseTextBox elseTextBox;
private System.Windows.Forms.Label elseLabel;
private IntellisenseTextBox thenTextBox;
private System.Windows.Forms.Label thenLabel;
private IntellisenseTextBox conditionTextBox;
private System.Windows.Forms.Label conditionLabel;
private System.Windows.Forms.ComboBox reevaluationComboBox;
private System.Windows.Forms.ComboBox chainingBehaviourComboBox;
private System.Windows.Forms.Label chainingLabel;
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.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 = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// ReportInProductRunResponse
/// </summary>
[DataContract]
public partial class ReportInProductRunResponse : IEquatable<ReportInProductRunResponse>, IValidatableObject
{
public ReportInProductRunResponse()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="ReportInProductRunResponse" /> class.
/// </summary>
/// <param name="EndPosition">The last position in the result set. .</param>
/// <param name="ExceededMaxResults">ExceededMaxResults.</param>
/// <param name="LastWarehouseRefreshDateTime">LastWarehouseRefreshDateTime.</param>
/// <param name="ResultSetSize">The number of results returned in this response. .</param>
/// <param name="Rows">Rows.</param>
/// <param name="StartPosition">Starting position of the current result set..</param>
/// <param name="TotalSetSize">The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response..</param>
public ReportInProductRunResponse(string EndPosition = default(string), string ExceededMaxResults = default(string), string LastWarehouseRefreshDateTime = default(string), string ResultSetSize = default(string), List<ReportInProductRunResponseRow> Rows = default(List<ReportInProductRunResponseRow>), string StartPosition = default(string), string TotalSetSize = default(string))
{
this.EndPosition = EndPosition;
this.ExceededMaxResults = ExceededMaxResults;
this.LastWarehouseRefreshDateTime = LastWarehouseRefreshDateTime;
this.ResultSetSize = ResultSetSize;
this.Rows = Rows;
this.StartPosition = StartPosition;
this.TotalSetSize = TotalSetSize;
}
/// <summary>
/// The last position in the result set.
/// </summary>
/// <value>The last position in the result set. </value>
[DataMember(Name="endPosition", EmitDefaultValue=false)]
public string EndPosition { get; set; }
/// <summary>
/// Gets or Sets ExceededMaxResults
/// </summary>
[DataMember(Name="exceededMaxResults", EmitDefaultValue=false)]
public string ExceededMaxResults { get; set; }
/// <summary>
/// Gets or Sets LastWarehouseRefreshDateTime
/// </summary>
[DataMember(Name="lastWarehouseRefreshDateTime", EmitDefaultValue=false)]
public string LastWarehouseRefreshDateTime { get; set; }
/// <summary>
/// The number of results returned in this response.
/// </summary>
/// <value>The number of results returned in this response. </value>
[DataMember(Name="resultSetSize", EmitDefaultValue=false)]
public string ResultSetSize { get; set; }
/// <summary>
/// Gets or Sets Rows
/// </summary>
[DataMember(Name="rows", EmitDefaultValue=false)]
public List<ReportInProductRunResponseRow> Rows { get; set; }
/// <summary>
/// Starting position of the current result set.
/// </summary>
/// <value>Starting position of the current result set.</value>
[DataMember(Name="startPosition", EmitDefaultValue=false)]
public string StartPosition { get; set; }
/// <summary>
/// The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.
/// </summary>
/// <value>The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.</value>
[DataMember(Name="totalSetSize", EmitDefaultValue=false)]
public string TotalSetSize { 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 ReportInProductRunResponse {\n");
sb.Append(" EndPosition: ").Append(EndPosition).Append("\n");
sb.Append(" ExceededMaxResults: ").Append(ExceededMaxResults).Append("\n");
sb.Append(" LastWarehouseRefreshDateTime: ").Append(LastWarehouseRefreshDateTime).Append("\n");
sb.Append(" ResultSetSize: ").Append(ResultSetSize).Append("\n");
sb.Append(" Rows: ").Append(Rows).Append("\n");
sb.Append(" StartPosition: ").Append(StartPosition).Append("\n");
sb.Append(" TotalSetSize: ").Append(TotalSetSize).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)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as ReportInProductRunResponse);
}
/// <summary>
/// Returns true if ReportInProductRunResponse instances are equal
/// </summary>
/// <param name="other">Instance of ReportInProductRunResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ReportInProductRunResponse other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.EndPosition == other.EndPosition ||
this.EndPosition != null &&
this.EndPosition.Equals(other.EndPosition)
) &&
(
this.ExceededMaxResults == other.ExceededMaxResults ||
this.ExceededMaxResults != null &&
this.ExceededMaxResults.Equals(other.ExceededMaxResults)
) &&
(
this.LastWarehouseRefreshDateTime == other.LastWarehouseRefreshDateTime ||
this.LastWarehouseRefreshDateTime != null &&
this.LastWarehouseRefreshDateTime.Equals(other.LastWarehouseRefreshDateTime)
) &&
(
this.ResultSetSize == other.ResultSetSize ||
this.ResultSetSize != null &&
this.ResultSetSize.Equals(other.ResultSetSize)
) &&
(
this.Rows == other.Rows ||
this.Rows != null &&
this.Rows.SequenceEqual(other.Rows)
) &&
(
this.StartPosition == other.StartPosition ||
this.StartPosition != null &&
this.StartPosition.Equals(other.StartPosition)
) &&
(
this.TotalSetSize == other.TotalSetSize ||
this.TotalSetSize != null &&
this.TotalSetSize.Equals(other.TotalSetSize)
);
}
/// <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 etc, of course :)
if (this.EndPosition != null)
hash = hash * 59 + this.EndPosition.GetHashCode();
if (this.ExceededMaxResults != null)
hash = hash * 59 + this.ExceededMaxResults.GetHashCode();
if (this.LastWarehouseRefreshDateTime != null)
hash = hash * 59 + this.LastWarehouseRefreshDateTime.GetHashCode();
if (this.ResultSetSize != null)
hash = hash * 59 + this.ResultSetSize.GetHashCode();
if (this.Rows != null)
hash = hash * 59 + this.Rows.GetHashCode();
if (this.StartPosition != null)
hash = hash * 59 + this.StartPosition.GetHashCode();
if (this.TotalSetSize != null)
hash = hash * 59 + this.TotalSetSize.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
/*
* Copyright (C) 2014 The Libphonenumber 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.
*/
/* This file is automatically generated by {@link BuildMetadataProtoFromXml}.
* Please don't modify it directly.
*/
namespace Google.PhoneNumbers {
using System;
using System.Collections.Generic;
public class ShortNumbersRegionCodeSet {
// A set of all region codes for which data is available.
internal static ISet<String> getRegionCodeSet() {
// The capacity is set to %d as there are %d different entries,
// and this offers a load factor of roughly 0.75.
ISet<String> regionCodeSet = new HashSet<String>();
regionCodeSet.Add("AC");
regionCodeSet.Add("AD");
regionCodeSet.Add("AE");
regionCodeSet.Add("AF");
regionCodeSet.Add("AG");
regionCodeSet.Add("AI");
regionCodeSet.Add("AL");
regionCodeSet.Add("AM");
regionCodeSet.Add("AO");
regionCodeSet.Add("AR");
regionCodeSet.Add("AS");
regionCodeSet.Add("AT");
regionCodeSet.Add("AU");
regionCodeSet.Add("AW");
regionCodeSet.Add("AX");
regionCodeSet.Add("AZ");
regionCodeSet.Add("BA");
regionCodeSet.Add("BB");
regionCodeSet.Add("BD");
regionCodeSet.Add("BE");
regionCodeSet.Add("BF");
regionCodeSet.Add("BG");
regionCodeSet.Add("BH");
regionCodeSet.Add("BI");
regionCodeSet.Add("BJ");
regionCodeSet.Add("BL");
regionCodeSet.Add("BM");
regionCodeSet.Add("BN");
regionCodeSet.Add("BO");
regionCodeSet.Add("BQ");
regionCodeSet.Add("BR");
regionCodeSet.Add("BS");
regionCodeSet.Add("BT");
regionCodeSet.Add("BW");
regionCodeSet.Add("BY");
regionCodeSet.Add("BZ");
regionCodeSet.Add("CA");
regionCodeSet.Add("CC");
regionCodeSet.Add("CD");
regionCodeSet.Add("CH");
regionCodeSet.Add("CI");
regionCodeSet.Add("CK");
regionCodeSet.Add("CL");
regionCodeSet.Add("CM");
regionCodeSet.Add("CN");
regionCodeSet.Add("CO");
regionCodeSet.Add("CR");
regionCodeSet.Add("CU");
regionCodeSet.Add("CV");
regionCodeSet.Add("CW");
regionCodeSet.Add("CX");
regionCodeSet.Add("CY");
regionCodeSet.Add("CZ");
regionCodeSet.Add("DE");
regionCodeSet.Add("DJ");
regionCodeSet.Add("DK");
regionCodeSet.Add("DM");
regionCodeSet.Add("DO");
regionCodeSet.Add("DZ");
regionCodeSet.Add("EC");
regionCodeSet.Add("EE");
regionCodeSet.Add("EG");
regionCodeSet.Add("EH");
regionCodeSet.Add("ES");
regionCodeSet.Add("ET");
regionCodeSet.Add("FI");
regionCodeSet.Add("FJ");
regionCodeSet.Add("FK");
regionCodeSet.Add("FM");
regionCodeSet.Add("FO");
regionCodeSet.Add("FR");
regionCodeSet.Add("GA");
regionCodeSet.Add("GB");
regionCodeSet.Add("GD");
regionCodeSet.Add("GE");
regionCodeSet.Add("GF");
regionCodeSet.Add("GG");
regionCodeSet.Add("GH");
regionCodeSet.Add("GI");
regionCodeSet.Add("GL");
regionCodeSet.Add("GM");
regionCodeSet.Add("GN");
regionCodeSet.Add("GP");
regionCodeSet.Add("GR");
regionCodeSet.Add("GT");
regionCodeSet.Add("GU");
regionCodeSet.Add("GW");
regionCodeSet.Add("GY");
regionCodeSet.Add("HK");
regionCodeSet.Add("HN");
regionCodeSet.Add("HR");
regionCodeSet.Add("HT");
regionCodeSet.Add("HU");
regionCodeSet.Add("ID");
regionCodeSet.Add("IE");
regionCodeSet.Add("IL");
regionCodeSet.Add("IM");
regionCodeSet.Add("IN");
regionCodeSet.Add("IQ");
regionCodeSet.Add("IR");
regionCodeSet.Add("IS");
regionCodeSet.Add("IT");
regionCodeSet.Add("JE");
regionCodeSet.Add("JM");
regionCodeSet.Add("JO");
regionCodeSet.Add("JP");
regionCodeSet.Add("KE");
regionCodeSet.Add("KG");
regionCodeSet.Add("KH");
regionCodeSet.Add("KI");
regionCodeSet.Add("KM");
regionCodeSet.Add("KN");
regionCodeSet.Add("KR");
regionCodeSet.Add("KW");
regionCodeSet.Add("KY");
regionCodeSet.Add("KZ");
regionCodeSet.Add("LA");
regionCodeSet.Add("LB");
regionCodeSet.Add("LC");
regionCodeSet.Add("LI");
regionCodeSet.Add("LK");
regionCodeSet.Add("LR");
regionCodeSet.Add("LS");
regionCodeSet.Add("LT");
regionCodeSet.Add("LU");
regionCodeSet.Add("LV");
regionCodeSet.Add("LY");
regionCodeSet.Add("MA");
regionCodeSet.Add("MC");
regionCodeSet.Add("MD");
regionCodeSet.Add("ME");
regionCodeSet.Add("MF");
regionCodeSet.Add("MG");
regionCodeSet.Add("MH");
regionCodeSet.Add("MK");
regionCodeSet.Add("ML");
regionCodeSet.Add("MM");
regionCodeSet.Add("MN");
regionCodeSet.Add("MO");
regionCodeSet.Add("MP");
regionCodeSet.Add("MQ");
regionCodeSet.Add("MR");
regionCodeSet.Add("MS");
regionCodeSet.Add("MT");
regionCodeSet.Add("MU");
regionCodeSet.Add("MV");
regionCodeSet.Add("MW");
regionCodeSet.Add("MX");
regionCodeSet.Add("MY");
regionCodeSet.Add("MZ");
regionCodeSet.Add("NA");
regionCodeSet.Add("NC");
regionCodeSet.Add("NF");
regionCodeSet.Add("NG");
regionCodeSet.Add("NI");
regionCodeSet.Add("NL");
regionCodeSet.Add("NO");
regionCodeSet.Add("NP");
regionCodeSet.Add("NR");
regionCodeSet.Add("NU");
regionCodeSet.Add("NZ");
regionCodeSet.Add("OM");
regionCodeSet.Add("PA");
regionCodeSet.Add("PE");
regionCodeSet.Add("PF");
regionCodeSet.Add("PG");
regionCodeSet.Add("PH");
regionCodeSet.Add("PK");
regionCodeSet.Add("PL");
regionCodeSet.Add("PM");
regionCodeSet.Add("PR");
regionCodeSet.Add("PT");
regionCodeSet.Add("PW");
regionCodeSet.Add("PY");
regionCodeSet.Add("QA");
regionCodeSet.Add("RE");
regionCodeSet.Add("RO");
regionCodeSet.Add("RS");
regionCodeSet.Add("RU");
regionCodeSet.Add("RW");
regionCodeSet.Add("SA");
regionCodeSet.Add("SB");
regionCodeSet.Add("SC");
regionCodeSet.Add("SD");
regionCodeSet.Add("SE");
regionCodeSet.Add("SG");
regionCodeSet.Add("SH");
regionCodeSet.Add("SI");
regionCodeSet.Add("SJ");
regionCodeSet.Add("SK");
regionCodeSet.Add("SL");
regionCodeSet.Add("SM");
regionCodeSet.Add("SN");
regionCodeSet.Add("SR");
regionCodeSet.Add("ST");
regionCodeSet.Add("SV");
regionCodeSet.Add("SX");
regionCodeSet.Add("SY");
regionCodeSet.Add("SZ");
regionCodeSet.Add("TC");
regionCodeSet.Add("TD");
regionCodeSet.Add("TG");
regionCodeSet.Add("TH");
regionCodeSet.Add("TJ");
regionCodeSet.Add("TL");
regionCodeSet.Add("TM");
regionCodeSet.Add("TN");
regionCodeSet.Add("TO");
regionCodeSet.Add("TR");
regionCodeSet.Add("TT");
regionCodeSet.Add("TV");
regionCodeSet.Add("TW");
regionCodeSet.Add("TZ");
regionCodeSet.Add("UA");
regionCodeSet.Add("UG");
regionCodeSet.Add("US");
regionCodeSet.Add("UY");
regionCodeSet.Add("UZ");
regionCodeSet.Add("VA");
regionCodeSet.Add("VC");
regionCodeSet.Add("VE");
regionCodeSet.Add("VG");
regionCodeSet.Add("VI");
regionCodeSet.Add("VN");
regionCodeSet.Add("VU");
regionCodeSet.Add("WF");
regionCodeSet.Add("WS");
regionCodeSet.Add("YE");
regionCodeSet.Add("YT");
regionCodeSet.Add("ZA");
regionCodeSet.Add("ZM");
regionCodeSet.Add("ZW");
return regionCodeSet;
}
}
}
| |
/*
* CP10017.cs - Ukraine (Mac) code page.
*
* Copyright (c) 2002 Southern Storm Software, Pty Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Generated from "mac-10007.ucm".
namespace I18N.Other
{
using System;
using I18N.Common;
public class CP10017 : ByteEncoding
{
public CP10017()
: base(10017, ToChars, "Ukraine (Mac)",
"windows-10017", "windows-10017", "windows-10017",
false, false, false, false, 1251)
{}
private static readonly char[] ToChars = {
'\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005',
'\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B',
'\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011',
'\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017',
'\u0018', '\u0019', '\u001A', '\u001B', '\u001C', '\u001D',
'\u001E', '\u001F', '\u0020', '\u0021', '\u0022', '\u0023',
'\u0024', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029',
'\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F',
'\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035',
'\u0036', '\u0037', '\u0038', '\u0039', '\u003A', '\u003B',
'\u003C', '\u003D', '\u003E', '\u003F', '\u0040', '\u0041',
'\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047',
'\u0048', '\u0049', '\u004A', '\u004B', '\u004C', '\u004D',
'\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u0053',
'\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059',
'\u005A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F',
'\u0060', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065',
'\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B',
'\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071',
'\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077',
'\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D',
'\u007E', '\u007F', '\u0410', '\u0411', '\u0412', '\u0413',
'\u0414', '\u0415', '\u0416', '\u0417', '\u0418', '\u0419',
'\u041A', '\u041B', '\u041C', '\u041D', '\u041E', '\u041F',
'\u0420', '\u0421', '\u0422', '\u0423', '\u0424', '\u0425',
'\u0426', '\u0427', '\u0428', '\u0429', '\u042A', '\u042B',
'\u042C', '\u042D', '\u042E', '\u042F', '\u2020', '\u00B0',
'\u00A2', '\u00A3', '\u00A7', '\u2022', '\u00B6', '\u0406',
'\u00AE', '\u00A9', '\u2122', '\u0402', '\u0452', '\u2260',
'\u0403', '\u0453', '\u221E', '\u00B1', '\u2264', '\u2265',
'\u0456', '\u00B5', '\u2202', '\u0408', '\u0404', '\u0454',
'\u0407', '\u0457', '\u0409', '\u0459', '\u040A', '\u045A',
'\u0458', '\u0405', '\u00AC', '\u221A', '\u0192', '\u2248',
'\u2206', '\u00AB', '\u00BB', '\u2026', '\u00A0', '\u040B',
'\u045B', '\u040C', '\u045C', '\u0455', '\u2013', '\u2014',
'\u201C', '\u201D', '\u2018', '\u2019', '\u00F7', '\u201E',
'\u040E', '\u045E', '\u040F', '\u045F', '\u2116', '\u0401',
'\u0451', '\u044F', '\u0430', '\u0431', '\u0432', '\u0433',
'\u0434', '\u0435', '\u0436', '\u0437', '\u0438', '\u0439',
'\u043A', '\u043B', '\u043C', '\u043D', '\u043E', '\u043F',
'\u0440', '\u0441', '\u0442', '\u0443', '\u0444', '\u0445',
'\u0446', '\u0447', '\u0448', '\u0449', '\u044A', '\u044B',
'\u044C', '\u044D', '\u044E', '\u00A4',
};
protected override void ToBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(chars[charIndex++]);
if(ch >= 128) switch(ch)
{
case 0x00A2:
case 0x00A3:
case 0x00A9:
case 0x00B1:
case 0x00B5:
break;
case 0x00A0: ch = 0xCA; break;
case 0x00A4: ch = 0xFF; break;
case 0x00A7: ch = 0xA4; break;
case 0x00AB: ch = 0xC7; break;
case 0x00AC: ch = 0xC2; break;
case 0x00AE: ch = 0xA8; break;
case 0x00B0: ch = 0xA1; break;
case 0x00B6: ch = 0xA6; break;
case 0x00BB: ch = 0xC8; break;
case 0x00F7: ch = 0xD6; break;
case 0x0192: ch = 0xC4; break;
case 0x0401: ch = 0xDD; break;
case 0x0402: ch = 0xAB; break;
case 0x0403: ch = 0xAE; break;
case 0x0404: ch = 0xB8; break;
case 0x0405: ch = 0xC1; break;
case 0x0406: ch = 0xA7; break;
case 0x0407: ch = 0xBA; break;
case 0x0408: ch = 0xB7; break;
case 0x0409: ch = 0xBC; break;
case 0x040A: ch = 0xBE; break;
case 0x040B: ch = 0xCB; break;
case 0x040C: ch = 0xCD; break;
case 0x040E: ch = 0xD8; break;
case 0x040F: ch = 0xDA; break;
case 0x0410:
case 0x0411:
case 0x0412:
case 0x0413:
case 0x0414:
case 0x0415:
case 0x0416:
case 0x0417:
case 0x0418:
case 0x0419:
case 0x041A:
case 0x041B:
case 0x041C:
case 0x041D:
case 0x041E:
case 0x041F:
case 0x0420:
case 0x0421:
case 0x0422:
case 0x0423:
case 0x0424:
case 0x0425:
case 0x0426:
case 0x0427:
case 0x0428:
case 0x0429:
case 0x042A:
case 0x042B:
case 0x042C:
case 0x042D:
case 0x042E:
case 0x042F:
ch -= 0x0390;
break;
case 0x0430:
case 0x0431:
case 0x0432:
case 0x0433:
case 0x0434:
case 0x0435:
case 0x0436:
case 0x0437:
case 0x0438:
case 0x0439:
case 0x043A:
case 0x043B:
case 0x043C:
case 0x043D:
case 0x043E:
case 0x043F:
case 0x0440:
case 0x0441:
case 0x0442:
case 0x0443:
case 0x0444:
case 0x0445:
case 0x0446:
case 0x0447:
case 0x0448:
case 0x0449:
case 0x044A:
case 0x044B:
case 0x044C:
case 0x044D:
case 0x044E:
ch -= 0x0350;
break;
case 0x044F: ch = 0xDF; break;
case 0x0451: ch = 0xDE; break;
case 0x0452: ch = 0xAC; break;
case 0x0453: ch = 0xAF; break;
case 0x0454: ch = 0xB9; break;
case 0x0455: ch = 0xCF; break;
case 0x0456: ch = 0xB4; break;
case 0x0457: ch = 0xBB; break;
case 0x0458: ch = 0xC0; break;
case 0x0459: ch = 0xBD; break;
case 0x045A: ch = 0xBF; break;
case 0x045B: ch = 0xCC; break;
case 0x045C: ch = 0xCE; break;
case 0x045E: ch = 0xD9; break;
case 0x045F: ch = 0xDB; break;
case 0x2013: ch = 0xD0; break;
case 0x2014: ch = 0xD1; break;
case 0x2018: ch = 0xD4; break;
case 0x2019: ch = 0xD5; break;
case 0x201C: ch = 0xD2; break;
case 0x201D: ch = 0xD3; break;
case 0x201E: ch = 0xD7; break;
case 0x2020: ch = 0xA0; break;
case 0x2022: ch = 0xA5; break;
case 0x2026: ch = 0xC9; break;
case 0x2116: ch = 0xDC; break;
case 0x2122: ch = 0xAA; break;
case 0x2202: ch = 0xB6; break;
case 0x2206: ch = 0xC6; break;
case 0x221A: ch = 0xC3; break;
case 0x221E: ch = 0xB0; break;
case 0x2248: ch = 0xC5; break;
case 0x2260: ch = 0xAD; break;
case 0x2264: ch = 0xB2; break;
case 0x2265: ch = 0xB3; break;
default: ch = 0x3F; break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
protected override void ToBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(s[charIndex++]);
if(ch >= 128) switch(ch)
{
case 0x00A2:
case 0x00A3:
case 0x00A9:
case 0x00B1:
case 0x00B5:
break;
case 0x00A0: ch = 0xCA; break;
case 0x00A4: ch = 0xFF; break;
case 0x00A7: ch = 0xA4; break;
case 0x00AB: ch = 0xC7; break;
case 0x00AC: ch = 0xC2; break;
case 0x00AE: ch = 0xA8; break;
case 0x00B0: ch = 0xA1; break;
case 0x00B6: ch = 0xA6; break;
case 0x00BB: ch = 0xC8; break;
case 0x00F7: ch = 0xD6; break;
case 0x0192: ch = 0xC4; break;
case 0x0401: ch = 0xDD; break;
case 0x0402: ch = 0xAB; break;
case 0x0403: ch = 0xAE; break;
case 0x0404: ch = 0xB8; break;
case 0x0405: ch = 0xC1; break;
case 0x0406: ch = 0xA7; break;
case 0x0407: ch = 0xBA; break;
case 0x0408: ch = 0xB7; break;
case 0x0409: ch = 0xBC; break;
case 0x040A: ch = 0xBE; break;
case 0x040B: ch = 0xCB; break;
case 0x040C: ch = 0xCD; break;
case 0x040E: ch = 0xD8; break;
case 0x040F: ch = 0xDA; break;
case 0x0410:
case 0x0411:
case 0x0412:
case 0x0413:
case 0x0414:
case 0x0415:
case 0x0416:
case 0x0417:
case 0x0418:
case 0x0419:
case 0x041A:
case 0x041B:
case 0x041C:
case 0x041D:
case 0x041E:
case 0x041F:
case 0x0420:
case 0x0421:
case 0x0422:
case 0x0423:
case 0x0424:
case 0x0425:
case 0x0426:
case 0x0427:
case 0x0428:
case 0x0429:
case 0x042A:
case 0x042B:
case 0x042C:
case 0x042D:
case 0x042E:
case 0x042F:
ch -= 0x0390;
break;
case 0x0430:
case 0x0431:
case 0x0432:
case 0x0433:
case 0x0434:
case 0x0435:
case 0x0436:
case 0x0437:
case 0x0438:
case 0x0439:
case 0x043A:
case 0x043B:
case 0x043C:
case 0x043D:
case 0x043E:
case 0x043F:
case 0x0440:
case 0x0441:
case 0x0442:
case 0x0443:
case 0x0444:
case 0x0445:
case 0x0446:
case 0x0447:
case 0x0448:
case 0x0449:
case 0x044A:
case 0x044B:
case 0x044C:
case 0x044D:
case 0x044E:
ch -= 0x0350;
break;
case 0x044F: ch = 0xDF; break;
case 0x0451: ch = 0xDE; break;
case 0x0452: ch = 0xAC; break;
case 0x0453: ch = 0xAF; break;
case 0x0454: ch = 0xB9; break;
case 0x0455: ch = 0xCF; break;
case 0x0456: ch = 0xB4; break;
case 0x0457: ch = 0xBB; break;
case 0x0458: ch = 0xC0; break;
case 0x0459: ch = 0xBD; break;
case 0x045A: ch = 0xBF; break;
case 0x045B: ch = 0xCC; break;
case 0x045C: ch = 0xCE; break;
case 0x045E: ch = 0xD9; break;
case 0x045F: ch = 0xDB; break;
case 0x2013: ch = 0xD0; break;
case 0x2014: ch = 0xD1; break;
case 0x2018: ch = 0xD4; break;
case 0x2019: ch = 0xD5; break;
case 0x201C: ch = 0xD2; break;
case 0x201D: ch = 0xD3; break;
case 0x201E: ch = 0xD7; break;
case 0x2020: ch = 0xA0; break;
case 0x2022: ch = 0xA5; break;
case 0x2026: ch = 0xC9; break;
case 0x2116: ch = 0xDC; break;
case 0x2122: ch = 0xAA; break;
case 0x2202: ch = 0xB6; break;
case 0x2206: ch = 0xC6; break;
case 0x221A: ch = 0xC3; break;
case 0x221E: ch = 0xB0; break;
case 0x2248: ch = 0xC5; break;
case 0x2260: ch = 0xAD; break;
case 0x2264: ch = 0xB2; break;
case 0x2265: ch = 0xB3; break;
default: ch = 0x3F; break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
}; // class CP10017
public class ENCwindows_10017 : CP10017
{
public ENCwindows_10017() : base() {}
}; // class ENCwindows_10017
}; // namespace I18N.Other
| |
using System;
using System.Threading;
using Content.Server.Body.Components;
using Content.Server.Chemistry.Components;
using Content.Server.Chemistry.Components.SolutionManager;
using Content.Server.CombatMode;
using Content.Server.DoAfter;
using Content.Shared.Chemistry.Components;
using Content.Shared.Chemistry.Reagent;
using Content.Shared.Database;
using Content.Shared.FixedPoint;
using Content.Shared.Hands;
using Content.Shared.Interaction;
using Content.Shared.MobState.Components;
using Robust.Shared.GameStates;
using Robust.Shared.Player;
namespace Content.Server.Chemistry.EntitySystems;
public sealed partial class ChemistrySystem
{
private void InitializeInjector()
{
SubscribeLocalEvent<InjectorComponent, SolutionChangedEvent>(OnSolutionChange);
SubscribeLocalEvent<InjectorComponent, HandDeselectedEvent>(OnInjectorDeselected);
SubscribeLocalEvent<InjectorComponent, ComponentStartup>(OnInjectorStartup);
SubscribeLocalEvent<InjectorComponent, UseInHandEvent>(OnInjectorUse);
SubscribeLocalEvent<InjectorComponent, AfterInteractEvent>(OnInjectorAfterInteract);
SubscribeLocalEvent<InjectorComponent, ComponentGetState>(OnInjectorGetState);
SubscribeLocalEvent<InjectionCompleteEvent>(OnInjectionComplete);
SubscribeLocalEvent<InjectionCancelledEvent>(OnInjectionCancelled);
}
private static void OnInjectionCancelled(InjectionCancelledEvent ev)
{
ev.Component.CancelToken = null;
}
private void OnInjectionComplete(InjectionCompleteEvent ev)
{
ev.Component.CancelToken = null;
UseInjector(ev.Target, ev.User, ev.Component);
}
private void UseInjector(EntityUid target, EntityUid user, InjectorComponent component)
{
// Handle injecting/drawing for solutions
if (component.ToggleState == SharedInjectorComponent.InjectorToggleMode.Inject)
{
if (_solutions.TryGetInjectableSolution(target, out var injectableSolution))
{
TryInject(component, target, injectableSolution, user, false);
}
else if (_solutions.TryGetRefillableSolution(target, out var refillableSolution))
{
TryInject(component, target, refillableSolution, user, true);
}
else if (TryComp<BloodstreamComponent>(target, out var bloodstream))
{
TryInjectIntoBloodstream(component, bloodstream, user);
}
else
{
_popup.PopupEntity(Loc.GetString("injector-component-cannot-transfer-message",
("target", target)), component.Owner, Filter.Entities(user));
}
}
else if (component.ToggleState == SharedInjectorComponent.InjectorToggleMode.Draw)
{
if (_solutions.TryGetDrawableSolution(target, out var drawableSolution))
{
TryDraw(component, target, drawableSolution, user);
}
else
{
_popup.PopupEntity(Loc.GetString("injector-component-cannot-draw-message",
("target", target)), component.Owner, Filter.Entities(user));
}
}
}
private static void OnInjectorDeselected(EntityUid uid, InjectorComponent component, HandDeselectedEvent args)
{
component.CancelToken?.Cancel();
component.CancelToken = null;
}
private void OnSolutionChange(EntityUid uid, InjectorComponent component, SolutionChangedEvent args)
{
Dirty(component);
}
private void OnInjectorGetState(EntityUid uid, InjectorComponent component, ref ComponentGetState args)
{
_solutions.TryGetSolution(uid, InjectorComponent.SolutionName, out var solution);
var currentVolume = solution?.CurrentVolume ?? FixedPoint2.Zero;
var maxVolume = solution?.MaxVolume ?? FixedPoint2.Zero;
args.State = new SharedInjectorComponent.InjectorComponentState(currentVolume, maxVolume, component.ToggleState);
}
private void OnInjectorAfterInteract(EntityUid uid, InjectorComponent component, AfterInteractEvent args)
{
if (args.Handled || !args.CanReach) return;
if (component.CancelToken != null)
{
component.CancelToken.Cancel();
component.CancelToken = null;
args.Handled = true;
return;
}
//Make sure we have the attacking entity
if (args.Target is not { Valid: true } target ||
!HasComp<SolutionContainerManagerComponent>(uid))
{
return;
}
// Is the target a mob? If yes, use a do-after to give them time to respond.
if (HasComp<MobStateComponent>(target) ||
HasComp<BloodstreamComponent>(target))
{
InjectDoAfter(component, args.User, target);
args.Handled = true;
return;
}
UseInjector(target, args.User, component);
args.Handled = true;
}
private void OnInjectorStartup(EntityUid uid, InjectorComponent component, ComponentStartup args)
{
Dirty(component);
}
private void OnInjectorUse(EntityUid uid, InjectorComponent component, UseInHandEvent args)
{
if (args.Handled) return;
Toggle(component, args.User);
args.Handled = true;
}
/// <summary>
/// Toggle between draw/inject state if applicable
/// </summary>
private void Toggle(InjectorComponent component, EntityUid user)
{
if (component.InjectOnly)
{
return;
}
string msg;
switch (component.ToggleState)
{
case SharedInjectorComponent.InjectorToggleMode.Inject:
component.ToggleState = SharedInjectorComponent.InjectorToggleMode.Draw;
msg = "injector-component-drawing-text";
break;
case SharedInjectorComponent.InjectorToggleMode.Draw:
component.ToggleState = SharedInjectorComponent.InjectorToggleMode.Inject;
msg = "injector-component-injecting-text";
break;
default:
throw new ArgumentOutOfRangeException();
}
_popup.PopupEntity(Loc.GetString(msg), component.Owner, Filter.Entities(user));
}
/// <summary>
/// Send informative pop-up messages and wait for a do-after to complete.
/// </summary>
private void InjectDoAfter(InjectorComponent component, EntityUid user, EntityUid target)
{
// Create a pop-up for the user
_popup.PopupEntity(Loc.GetString("injector-component-injecting-user"), target, Filter.Entities(user));
if (!_solutions.TryGetSolution(component.Owner, InjectorComponent.SolutionName, out var solution))
return;
var actualDelay = MathF.Max(component.Delay, 1f);
if (user != target)
{
// Create a pop-up for the target
var userName = MetaData(user).EntityName;
_popup.PopupEntity(Loc.GetString("injector-component-injecting-target",
("user", userName)), user, Filter.Entities(target));
// Check if the target is incapacitated or in combat mode and modify time accordingly.
if (TryComp<MobStateComponent>(target, out var mobState) && mobState.IsIncapacitated())
{
actualDelay /= 2;
}
else if (TryComp<CombatModeComponent>(target, out var combat) && combat.IsInCombatMode)
{
// Slightly increase the delay when the target is in combat mode. Helps prevents cheese injections in
// combat with fast syringes & lag.
actualDelay += 1;
}
// Add an admin log, using the "force feed" log type. It's not quite feeding, but the effect is the same.
if (component.ToggleState == SharedInjectorComponent.InjectorToggleMode.Inject)
{
_logs.Add(LogType.ForceFeed,
$"{EntityManager.ToPrettyString(user):user} is attempting to inject {EntityManager.ToPrettyString(target):target} with a solution {SolutionContainerSystem.ToPrettyString(solution):solution}");
}
}
else
{
// Self-injections take half as long.
actualDelay /= 2;
if (component.ToggleState == SharedInjectorComponent.InjectorToggleMode.Inject)
_logs.Add(LogType.Ingestion,
$"{EntityManager.ToPrettyString(user):user} is attempting to inject themselves with a solution {SolutionContainerSystem.ToPrettyString(solution):solution}.");
}
component.CancelToken = new CancellationTokenSource();
_doAfter.DoAfter(new DoAfterEventArgs(user, actualDelay, component.CancelToken.Token, target)
{
BreakOnUserMove = true,
BreakOnDamage = true,
BreakOnStun = true,
BreakOnTargetMove = true,
MovementThreshold = 0.1f,
BroadcastFinishedEvent = new InjectionCompleteEvent()
{
Component = component,
User = user,
Target = target,
},
BroadcastCancelledEvent = new InjectionCancelledEvent()
{
Component = component,
}
});
}
private void TryInjectIntoBloodstream(InjectorComponent component, BloodstreamComponent targetBloodstream, EntityUid user)
{
// Get transfer amount. May be smaller than _transferAmount if not enough room
var realTransferAmount = FixedPoint2.Min(component.TransferAmount, targetBloodstream.ChemicalSolution.AvailableVolume);
if (realTransferAmount <= 0)
{
_popup.PopupEntity(Loc.GetString("injector-component-cannot-inject-message", ("target", targetBloodstream.Owner)),
component.Owner, Filter.Entities(user));
return;
}
// Move units from attackSolution to targetSolution
var removedSolution = _solutions.SplitSolution(user, targetBloodstream.ChemicalSolution, realTransferAmount);
_blood.TryAddToChemicals((targetBloodstream).Owner, removedSolution, targetBloodstream);
removedSolution.DoEntityReaction(targetBloodstream.Owner, ReactionMethod.Injection);
_popup.PopupEntity(Loc.GetString("injector-component-inject-success-message",
("amount", removedSolution.TotalVolume),
("target", targetBloodstream.Owner)), component.Owner, Filter.Entities(user));
Dirty(component);
AfterInject(component);
}
private void TryInject(InjectorComponent component, EntityUid targetEntity, Solution targetSolution, EntityUid user, bool asRefill)
{
if (!_solutions.TryGetSolution(component.Owner, InjectorComponent.SolutionName, out var solution)
|| solution.CurrentVolume == 0)
{
return;
}
// Get transfer amount. May be smaller than _transferAmount if not enough room
var realTransferAmount = FixedPoint2.Min(component.TransferAmount, targetSolution.AvailableVolume);
if (realTransferAmount <= 0)
{
_popup.PopupEntity(Loc.GetString("injector-component-target-already-full-message", ("target", targetEntity)),
component.Owner, Filter.Entities(user));
return;
}
// Move units from attackSolution to targetSolution
var removedSolution = _solutions.SplitSolution(component.Owner, solution, realTransferAmount);
removedSolution.DoEntityReaction(targetEntity, ReactionMethod.Injection);
if (!asRefill)
{
_solutions.Inject(targetEntity, targetSolution, removedSolution);
}
else
{
_solutions.Refill(targetEntity, targetSolution, removedSolution);
}
_popup.PopupEntity(Loc.GetString("injector-component-transfer-success-message",
("amount", removedSolution.TotalVolume),
("target", targetEntity)), component.Owner, Filter.Entities(user));
Dirty(component);
AfterInject(component);
}
private void AfterInject(InjectorComponent component)
{
// Automatically set syringe to draw after completely draining it.
if (_solutions.TryGetSolution(component.Owner, InjectorComponent.SolutionName, out var solution)
&& solution.CurrentVolume == 0)
{
component.ToggleState = SharedInjectorComponent.InjectorToggleMode.Draw;
}
}
private void AfterDraw(InjectorComponent component)
{
// Automatically set syringe to inject after completely filling it.
if (_solutions.TryGetSolution(component.Owner, InjectorComponent.SolutionName, out var solution)
&& solution.AvailableVolume == 0)
{
component.ToggleState = SharedInjectorComponent.InjectorToggleMode.Inject;
}
}
private void TryDraw(InjectorComponent component, EntityUid targetEntity, Solution targetSolution, EntityUid user)
{
if (!_solutions.TryGetSolution(component.Owner, InjectorComponent.SolutionName, out var solution)
|| solution.AvailableVolume == 0)
{
return;
}
// Get transfer amount. May be smaller than _transferAmount if not enough room
var realTransferAmount = FixedPoint2.Min(component.TransferAmount, targetSolution.DrawAvailable);
if (realTransferAmount <= 0)
{
_popup.PopupEntity(Loc.GetString("injector-component-target-is-empty-message", ("target", targetEntity)),
component.Owner, Filter.Entities(user));
return;
}
// Move units from attackSolution to targetSolution
var removedSolution = _solutions.Draw(targetEntity, targetSolution, realTransferAmount);
if (!_solutions.TryAddSolution(component.Owner, solution, removedSolution))
{
return;
}
_popup.PopupEntity(Loc.GetString("injector-component-draw-success-message",
("amount", removedSolution.TotalVolume),
("target", targetEntity)), component.Owner, Filter.Entities(user));
Dirty(component);
AfterDraw(component);
}
private sealed class InjectionCompleteEvent : EntityEventArgs
{
public InjectorComponent Component { get; init; } = default!;
public EntityUid User { get; init; }
public EntityUid Target { get; init; }
}
private sealed class InjectionCancelledEvent : EntityEventArgs
{
public InjectorComponent Component { get; init; } = default!;
}
}
| |
using System;
using System.Diagnostics;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using System.IO;
using System.Xml.Serialization;
namespace MeatieroidsWindows
{
// The screen manager manages instances of GameScreen. It maintains a list of screens
// which will have their update and draw methods called if they are active, and sends
// user input to whatever the active screens are
public class ScreenManager : DrawableGameComponent
{
private SpriteBatch spriteBatch;
private SpriteFont gameFont;
private Texture2D fadeTexture;
// lists of screens and screens waiting to be updated by the draw and update methods
private List<GameScreen> screens = new List<GameScreen>();
private List<GameScreen> screensToUpdate = new List<GameScreen>();
// user input handler for the game
private InputManager userInput = new InputManager();
// initialization flags for the screen manager
private bool isInitialized;
private bool isSoundEnabled;
// public properties and game settings
public SpriteBatch SpriteBatch
{
get { return spriteBatch; }
}
public SpriteFont GameFont
{
get { return gameFont; }
}
public int DiffucultyLevel { get; set; }
public int CurrentHighScore { get; set; }
public bool SoundEnabled { get; set; }
public GameScreen[] GetScreens()
{
return screens.ToArray();
}
//Constructs a new screen manager component.
public ScreenManager(Game game) : base(game) { }
// Initializes the screen manager component.
public override void Initialize()
{
base.Initialize();
isInitialized = true;
isSoundEnabled = true;
}
protected override void LoadContent()
{
ContentManager content = Game.Content;
//netSession = new NetworkManager();
spriteBatch = new SpriteBatch(GraphicsDevice);
gameFont = content.Load<SpriteFont>("menufont");
fadeTexture = content.Load<Texture2D>("images/blankBG");
StorageDevice.BeginShowSelector(PlayerIndex.One, StorageLoadCompletedCallback, null);
// Tell each of the screens to load their content.
foreach (GameScreen Screen in screens)
Screen.LoadContent();
}
void StorageLoadCompletedCallback(IAsyncResult result)
{
StorageDevice device = StorageDevice.EndShowSelector(result);
int score = new int();
if (device.IsConnected)
{
ScreenManager.DoLoadGame(device, ref score);
CurrentHighScore = score;
}
}
protected override void UnloadContent()
{
StorageDevice.BeginShowSelector(PlayerIndex.One, StorageSaveCompletedCallback, null);
foreach (GameScreen screen in screens)
screen.UnloadContent();
}
private void StorageSaveCompletedCallback(IAsyncResult result)
{
StorageDevice device = StorageDevice.EndShowSelector(result);
if (device.IsConnected)
{
ScreenManager.DoSaveGame(device, CurrentHighScore);
}
}
public override void Update(GameTime gameTime)
{
// Read the keyboard and gamepad input and check for messages on the network
userInput.Update();
screensToUpdate.Clear();
foreach (GameScreen screen in screens)
screensToUpdate.Add(screen);
bool otherScreenHasFocus = !Game.IsActive;
bool coveredByOtherScreen = false;
// Loop as long as there are screens waiting to be updated.
while (screensToUpdate.Count > 0)
{
// Pop the topmost screen off the waiting list.
GameScreen CurrentScreen = screensToUpdate[screensToUpdate.Count - 1];
screensToUpdate.RemoveAt(screensToUpdate.Count - 1);
// Update the screen.
CurrentScreen.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
//if the screen is about to be shown or is active
if (CurrentScreen.ScreenState == ScreenState.TransitionOn || CurrentScreen.ScreenState == ScreenState.Active)
{
// if this is the active screen
if (!otherScreenHasFocus)
{
CurrentScreen.HandleInput(userInput);
otherScreenHasFocus = true;
}
if (!CurrentScreen.IsPopupWindow)
coveredByOtherScreen = true;
}
}
}
public override void Draw(GameTime gameTime)
{
foreach (GameScreen CurrentScreen in screens)
{
if (CurrentScreen.ScreenState == ScreenState.Hidden)
continue;
CurrentScreen.Draw(gameTime);
}
}
public void AddScreen(GameScreen screen)
{
// set the player that is controlling this screen
screen.ScreenManager = this;
screen.IsExiting = false;
if (isInitialized)
screen.LoadContent();
screens.Add(screen);
}
// pops a screen off the screens list.
public void RemoveScreen(GameScreen screen)
{
// remove the screen from the list and delete everything it loaded
if (isInitialized)
screen.UnloadContent();
screens.Remove(screen);
screensToUpdate.Remove(screen);
}
// use to make grayish background for popups
public void FadeBackBufferToBlack(int alpha)
{
Viewport viewport = GraphicsDevice.Viewport;
spriteBatch.Begin();
spriteBatch.Draw(fadeTexture, new Rectangle(0, 0, viewport.Width, viewport.Height), new Color(0, 0, 0, (byte)alpha));
spriteBatch.End();
}
public struct SaveGameData
{
public int Score;
}
public static void DoSaveGame(StorageDevice device, int scoreToSave)
{
// Create the data to save.
SaveGameData data = new SaveGameData();
data.Score = scoreToSave;
IAsyncResult res = device.BeginOpenContainer("Meatieroids", null, null);
res.AsyncWaitHandle.WaitOne();
// Open a storage container.
StorageContainer container = device.EndOpenContainer(res);
// Get the path of the save game.
string filename = "hiscore.sav";
// Open the file, creating it if necessary.
FileStream stream = File.Open(filename, FileMode.OpenOrCreate);
if (device.FreeSpace > 0)
{
// Convert the object to XML data and put it in the stream.
XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));
serializer.Serialize(stream, data);
}
// Close the file.
stream.Close();
// Dispose the container, to commit changes.
container.Dispose();
}
private static void DoLoadGame(StorageDevice device, ref int score)
{
// Open a storage container.
IAsyncResult res = device.BeginOpenContainer("Meatieroids", null, null);
res.AsyncWaitHandle.WaitOne();
StorageContainer container = device.EndOpenContainer(res);
// Get the path of the save game.
string filename = "hiscore.sav";
// Check to see whether the save exists.
if (!File.Exists(filename))
// Notify the user there is no save.
return;
// Open the file.
FileStream stream = File.Open(filename, FileMode.OpenOrCreate,
FileAccess.Read);
//Read the data from the file.
XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));
SaveGameData data = (SaveGameData)serializer.Deserialize(stream);
score = data.Score;
stream.Close();
// Dispose the container.
container.Dispose();
}
}
}
| |
// Copyright (c) Rotorz Limited. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root.
using Rotorz.Settings;
using UnityEditor;
using UnityEngine;
namespace Rotorz.Tile.Editor
{
/// <summary>
/// Tool for picking the brush that was used to paint an existing tile.
/// </summary>
/// <intro>
/// <para>Please refer to the user guide for more information regarding the
/// <a href="https://github.com/rotorz/unity3d-tile-system/wiki/Picker-Tool">Picker Tool</a>.</para>
/// </intro>
public class PickerTool : ToolBase
{
private readonly string label = TileLang.FormatActionWithShortcut(
TileLang.ParticularText("Tool Name", "Picker"), "I"
);
#region Tool Information
/// <inheritdoc/>
public override string Label {
get { return this.label; }
}
/// <inheritdoc/>
public override Texture2D IconNormal {
get { return RotorzEditorStyles.Skin.ToolPicker; }
}
/// <inheritdoc/>
public override Texture2D IconActive {
get { return RotorzEditorStyles.Skin.GetInverted(RotorzEditorStyles.Skin.ToolPicker); }
}
/// <inheritdoc/>
public override CursorInfo Cursor {
get { return ToolCursors.Picker; }
}
/// <inheritdoc/>
public override void OnEnable()
{
ToolUtility.ShowBrushPalette(false);
}
#endregion
#region Tool Interaction
/// <inheritdoc/>
public override void OnRefreshToolEvent(ToolEvent e, IToolContext context)
{
base.OnRefreshToolEvent(e, context);
if (Event.current.isMouse) {
ToolUtility.ActivePlop = null;
// "Can pick plops"
if (this.CanPickPlops) {
var go = HandleUtility.PickGameObject(Event.current.mousePosition, true);
if (go != null) {
ToolUtility.ActivePlop = go.GetComponentInParent<PlopInstance>();
if (ToolUtility.ActivePlop != null) {
// "Interact with active system only"
if (this.InteractWithActiveSystemOnly && ToolUtility.ActivePlop.Owner != context.TileSystem) {
ToolUtility.ActivePlop = null;
}
}
}
}
}
}
/// <inheritdoc/>
public override void OnTool(ToolEvent e, IToolContext context)
{
switch (e.Type) {
case EventType.MouseDown:
ToolBase fallbackRestoreTool;
Brush pickedBrush = null;
if (ToolUtility.ActivePlop != null && ToolUtility.ActivePlop.Brush != null) {
fallbackRestoreTool = ToolManager.Instance.Find<PlopTool>();
// Get plop at pointer.
pickedBrush = ToolUtility.ActivePlop.Brush;
// Pick rotation from tile also!
ToolUtility.Rotation = ToolUtility.ActivePlop.PaintedRotation;
}
else {
fallbackRestoreTool = ToolManager.DefaultPaintTool;
// Get tile at pointer.
var tile = context.TileSystem.GetTile(e.MousePointerTileIndex);
if (tile != null) {
pickedBrush = tile.brush;
// Pick rotation from tile also!
ToolUtility.Rotation = tile.PaintedRotation;
}
}
// Select brush in tool window and force auto scroll.
if (e.IsLeftButtonPressed) {
ToolUtility.SelectedBrush = pickedBrush;
ToolUtility.RevealBrush(pickedBrush);
}
else {
ToolUtility.SelectedBrushSecondary = pickedBrush;
}
ToolUtility.RepaintBrushPalette();
// Switch to previous tool or the "Paint" tool.
var toolManager = ToolManager.Instance;
if (toolManager.PreviousTool != null && toolManager.PreviousTool != this) {
toolManager.CurrentTool = toolManager.PreviousTool;
}
else {
toolManager.CurrentTool = fallbackRestoreTool;
}
break;
}
}
#endregion
#region Tool Options
/// <inheritdoc/>
protected override void PrepareOptions(ISettingStore store)
{
base.PrepareOptions(store);
this.settingCanPickPlops = store.Fetch<bool>("CanPickPlops", true);
this.settingInteractWithActiveSystemOnly = store.Fetch<bool>("InteractWithActiveSystemOnly", true);
}
private Setting<bool> settingCanPickPlops;
private Setting<bool> settingInteractWithActiveSystemOnly;
/// <summary>
/// Gets or sets whether tool can pick brush from plops.
/// </summary>
public bool CanPickPlops {
get { return this.settingCanPickPlops.Value; }
set { this.settingCanPickPlops.Value = value; }
}
/// <summary>
/// Gets or sets whether brush should only be picked from plops that are
/// associated with the active tile system.
/// </summary>
public bool InteractWithActiveSystemOnly {
get { return this.settingInteractWithActiveSystemOnly.Value; }
set { this.settingInteractWithActiveSystemOnly.Value = value; }
}
#endregion
#region Tool Options Interface
/// <inheritdoc/>
public override void OnAdvancedToolOptionsGUI()
{
// Repaint scene views when options are changed so that handles updated.
EditorGUI.BeginChangeCheck();
this.CanPickPlops = EditorGUILayout.ToggleLeft(TileLang.ParticularText("Property", "Can pick plops"), this.CanPickPlops);
++EditorGUI.indentLevel;
if (this.CanPickPlops) {
this.InteractWithActiveSystemOnly = EditorGUILayout.ToggleLeft(TileLang.ParticularText("Property", "Interact with active system only"), this.InteractWithActiveSystemOnly);
}
--EditorGUI.indentLevel;
if (EditorGUI.EndChangeCheck()) {
SceneView.RepaintAll();
}
}
#endregion
#region Scene View
/// <inheritdoc/>
protected override NozzleIndicator GetNozzleIndicator(TileSystem system, TileIndex index, BrushNozzle nozzle)
{
NozzleIndicator mode = RtsPreferences.ToolPreferredNozzleIndicator;
if (mode == NozzleIndicator.Automatic) {
mode = NozzleIndicator.Flat;
// Determine based upon active tile.
var tile = system.GetTile(index);
if (tile != null && tile.brush != null && tile.brush.UseWireIndicatorInEditor) {
mode = NozzleIndicator.Wireframe;
}
}
return mode;
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Threading;
namespace Elephanet
{
/// <summary>
/// Concurrent HashSet implementaion from http://stackoverflow.com/questions/18922985/concurrent-hashsett-in-net-framework
/// as .NET framework doesnt have one.
/// </summary>
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public class ConcurrentHashSet<T> : ICollection<T>, ISet<T>, ISerializable, IDeserializationCallback
{
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
private readonly HashSet<T> _hashSet = new HashSet<T>();
public ConcurrentHashSet()
{
}
public ConcurrentHashSet(IEqualityComparer<T> comparer)
{
_hashSet = new HashSet<T>(comparer);
}
public ConcurrentHashSet(IEnumerable<T> collection)
{
_hashSet = new HashSet<T>(collection);
}
public ConcurrentHashSet(IEnumerable<T> collection, IEqualityComparer<T> comparer)
{
_hashSet = new HashSet<T>(collection, comparer);
}
protected ConcurrentHashSet(SerializationInfo info, StreamingContext context)
{
_hashSet = new HashSet<T>();
// not sure about this one really...
var iSerializable = _hashSet as ISerializable;
iSerializable.GetObjectData(info, context);
}
#region Dispose
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
if (_lock != null)
_lock.Dispose();
}
public IEnumerator<T> GetEnumerator()
{
return _hashSet.GetEnumerator();
}
~ConcurrentHashSet()
{
Dispose(false);
}
public void OnDeserialization(object sender)
{
_hashSet.OnDeserialization(sender);
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
_hashSet.GetObjectData(info, context);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
public void Add(T item)
{
_lock.EnterWriteLock();
try
{
_hashSet.Add(item);
}
finally
{
if (_lock.IsWriteLockHeld) _lock.ExitWriteLock();
}
}
public void UnionWith(IEnumerable<T> other)
{
_lock.EnterWriteLock();
_lock.EnterReadLock();
try
{
_hashSet.UnionWith(other);
}
finally
{
if (_lock.IsWriteLockHeld) _lock.ExitWriteLock();
if (_lock.IsReadLockHeld) _lock.ExitReadLock();
}
}
public void IntersectWith(IEnumerable<T> other)
{
_lock.EnterWriteLock();
_lock.EnterReadLock();
try
{
_hashSet.IntersectWith(other);
}
finally
{
if (_lock.IsWriteLockHeld) _lock.ExitWriteLock();
if (_lock.IsReadLockHeld) _lock.ExitReadLock();
}
}
public void ExceptWith(IEnumerable<T> other)
{
_lock.EnterWriteLock();
_lock.EnterReadLock();
try
{
_hashSet.ExceptWith(other);
}
finally
{
if (_lock.IsWriteLockHeld) _lock.ExitWriteLock();
if (_lock.IsReadLockHeld) _lock.ExitReadLock();
}
}
public void SymmetricExceptWith(IEnumerable<T> other)
{
_lock.EnterWriteLock();
try
{
_hashSet.SymmetricExceptWith(other);
}
finally
{
if (_lock.IsWriteLockHeld) _lock.ExitWriteLock();
}
}
public bool IsSubsetOf(IEnumerable<T> other)
{
_lock.EnterWriteLock();
try
{
return _hashSet.IsSubsetOf(other);
}
finally
{
if (_lock.IsWriteLockHeld) _lock.ExitWriteLock();
}
}
public bool IsSupersetOf(IEnumerable<T> other)
{
_lock.EnterWriteLock();
try
{
return _hashSet.IsSupersetOf(other);
}
finally
{
if (_lock.IsWriteLockHeld) _lock.ExitWriteLock();
}
}
public bool IsProperSupersetOf(IEnumerable<T> other)
{
_lock.EnterWriteLock();
try
{
return _hashSet.IsProperSupersetOf(other);
}
finally
{
if (_lock.IsWriteLockHeld) _lock.ExitWriteLock();
}
}
public bool IsProperSubsetOf(IEnumerable<T> other)
{
_lock.EnterWriteLock();
try
{
return _hashSet.IsProperSubsetOf(other);
}
finally
{
if (_lock.IsWriteLockHeld) _lock.ExitWriteLock();
}
}
public bool Overlaps(IEnumerable<T> other)
{
_lock.EnterWriteLock();
try
{
return _hashSet.Overlaps(other);
}
finally
{
if (_lock.IsWriteLockHeld) _lock.ExitWriteLock();
}
}
public bool SetEquals(IEnumerable<T> other)
{
_lock.EnterWriteLock();
try
{
return _hashSet.SetEquals(other);
}
finally
{
if (_lock.IsWriteLockHeld) _lock.ExitWriteLock();
}
}
bool ISet<T>.Add(T item)
{
_lock.EnterWriteLock();
try
{
return _hashSet.Add(item);
}
finally
{
if (_lock.IsWriteLockHeld) _lock.ExitWriteLock();
}
}
public void Clear()
{
_lock.EnterWriteLock();
try
{
_hashSet.Clear();
}
finally
{
if (_lock.IsWriteLockHeld) _lock.ExitWriteLock();
}
}
public bool Contains(T item)
{
_lock.EnterWriteLock();
try
{
return _hashSet.Contains(item);
}
finally
{
if (_lock.IsWriteLockHeld) _lock.ExitWriteLock();
}
}
public void CopyTo(T[] array, int arrayIndex)
{
_lock.EnterWriteLock();
try
{
_hashSet.CopyTo(array, arrayIndex);
}
finally
{
if (_lock.IsWriteLockHeld) _lock.ExitWriteLock();
}
}
public bool Remove(T item)
{
_lock.EnterWriteLock();
try
{
return _hashSet.Remove(item);
}
finally
{
if (_lock.IsWriteLockHeld) _lock.ExitWriteLock();
}
}
public int Count
{
get
{
_lock.EnterWriteLock();
try
{
return _hashSet.Count;
}
finally
{
if (_lock.IsWriteLockHeld) _lock.ExitWriteLock();
}
}
}
public bool IsReadOnly
{
get { return false; }
}
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Encog.ML.Data.Basic;
namespace Encog.ML.Data.Buffer
{
/// <summary>
/// This class is not memory based, so very long files can be used, without
/// running out of memory. This dataset uses a Encog binary training file as a
/// buffer.
///
/// When used with a slower access dataset, such as CSV, XML or SQL, where
/// parsing must occur, this dataset can be used to load from the slower dataset
/// and train at much higher speeds.
///
/// If you are going to create a binary file, by using the add methods, you must
/// call beginLoad to cause Encog to open an output file. Once the data has been
/// loaded, call endLoad. You can also use the BinaryDataLoader class, with a
/// CODEC, to load many other popular external formats.
///
/// The binary files produced by this class are in the Encog binary training
/// format, and can be used with any Encog platform. Encog binary files are
/// stored using "little endian" numbers.
/// </summary>
public class BufferedMLDataSet : IMLDataSetAddable
{
/// <summary>
/// Error message for ADD.
/// </summary>
public const String ErrorAdd = "Add can only be used after calling beginLoad.";
/// <summary>
/// True, if we are in the process of loading.
/// </summary>
[NonSerialized]
private bool _loading;
/// <summary>
/// The file being used.
/// </summary>
private readonly String _file;
/// <summary>
/// The EGB file we are working wtih.
/// </summary>
[NonSerialized]
private EncogEGBFile _egb;
/// <summary>
/// Additional sets that were opened.
/// </summary>
[NonSerialized]
private readonly IList<BufferedMLDataSet> _additional = new List<BufferedMLDataSet>();
/// <summary>
/// The owner.
/// </summary>
[NonSerialized]
private BufferedMLDataSet _owner;
/// <summary>
/// Construct a buffered dataset using the specified file.
/// </summary>
/// <param name="binaryFile">The file to read/write binary data to/from.</param>
public BufferedMLDataSet(String binaryFile)
{
_file = binaryFile;
_egb = new EncogEGBFile(binaryFile);
if (File.Exists(_file))
{
_egb.Open();
}
}
/// <summary>
/// Create an enumerator.
/// </summary>
/// <returns>The enumerator</returns>
public IEnumerator<IMLDataPair> GetEnumerator()
{
if (_loading)
{
throw new IMLDataError(
"Can't create enumerator while loading, call EndLoad first.");
}
var result = new BufferedNeuralDataSetEnumerator(this);
return result;
}
/// <summary>
/// Open the binary file for reading.
/// </summary>
public void Open()
{
_egb.Open();
}
/// <summary>
/// The record count.
/// </summary>
public int Count
{
get
{
return _egb == null ? 0 : _egb.NumberOfRecords;
}
}
/// <summary>
/// Open an additional training set.
/// </summary>
/// <returns>An additional training set.</returns>
public IMLDataSet OpenAdditional()
{
var result = new BufferedMLDataSet(_file) {_owner = this};
_additional.Add(result);
return result;
}
/// <summary>
/// Add only input data, for an unsupervised dataset.
/// </summary>
/// <param name="data1">The data to be added.</param>
public void Add(IMLData data1)
{
if (!_loading)
{
throw new IMLDataError(ErrorAdd);
}
_egb.Write(data1);
_egb.Write(1.0);
}
/// <summary>
/// Add both the input and ideal data.
/// </summary>
/// <param name="inputData">The input data.</param>
/// <param name="idealData">The ideal data.</param>
public void Add(IMLData inputData, IMLData idealData)
{
if (!_loading)
{
throw new IMLDataError(ErrorAdd);
}
_egb.Write(inputData);
_egb.Write(idealData);
_egb.Write(1.0);
}
/// <summary>
/// Add a data pair of both input and ideal data.
/// </summary>
/// <param name="pair">The pair to add.</param>
public void Add(IMLDataPair pair)
{
if (!_loading)
{
throw new IMLDataError(ErrorAdd);
}
_egb.Write(pair.Input);
_egb.Write(pair.Ideal);
_egb.Write(pair.Significance);
}
/// <summary>
/// Close the dataset.
/// </summary>
public void Close()
{
Object[] obj = _additional.ToArray();
foreach (var set in obj.Cast<BufferedMLDataSet>())
{
set.Close();
}
_additional.Clear();
if (_owner != null)
{
_owner.RemoveAdditional(this);
}
_egb.Close();
_egb = null;
}
/// <summary>
/// The ideal data size.
/// </summary>
public int IdealSize
{
get
{
return _egb == null ? 0 : _egb.IdealCount;
}
}
/// <summary>
/// The input data size.
/// </summary>
public int InputSize
{
get
{
return _egb == null ? 0 : _egb.InputCount;
}
}
/// <summary>
/// True if this dataset is supervised.
/// </summary>
public bool Supervised
{
get
{
if (_egb == null)
{
return false;
}
return _egb.IdealCount > 0;
}
}
/// <summary>
/// Remove an additional dataset that was created.
/// </summary>
/// <param name="child">The additional dataset to remove.</param>
public void RemoveAdditional(BufferedMLDataSet child)
{
lock (this)
{
_additional.Remove(child);
}
}
/// <summary>
/// Begin loading to the binary file. After calling this method the add
/// methods may be called.
/// </summary>
/// <param name="inputSize">The input size.</param>
/// <param name="idealSize">The ideal size.</param>
public void BeginLoad(int inputSize, int idealSize)
{
_egb.Create(inputSize, idealSize);
_loading = true;
}
/// <summary>
/// This method should be called once all the data has been loaded. The
/// underlying file will be closed. The binary fill will then be opened for
/// reading.
/// </summary>
public void EndLoad()
{
if (!_loading)
{
throw new BufferedDataError("Must call beginLoad, before endLoad.");
}
_egb.Close();
_loading = false;
}
/// <summary>
/// The binary file used.
/// </summary>
public String BinaryFile
{
get { return _file; }
}
/// <summary>
/// The EGB file to use.
/// </summary>
public EncogEGBFile EGB
{
get { return _egb; }
}
/// <summary>
/// Load the binary dataset to memory. Memory access is faster.
/// </summary>
/// <returns>A memory dataset.</returns>
public IMLDataSet LoadToMemory()
{
var result = new BasicMLDataSet();
foreach (IMLDataPair pair in this)
{
result.Add(pair);
}
return result;
}
/// <summary>
/// Load the specified training set.
/// </summary>
/// <param name="training">The training set to load.</param>
public void Load(IMLDataSet training)
{
BeginLoad(training.InputSize, training.IdealSize);
foreach (IMLDataPair pair in training)
{
Add(pair);
}
EndLoad();
}
/// <summary>
/// The owner. Set when create additional is used.
/// </summary>
public BufferedMLDataSet Owner
{
get { return _owner; }
set { _owner = value; }
}
/// <inheritdoc/>
public IMLDataPair this[int x]
{
get
{
var input = new double[InputSize];
var ideal = new double[IdealSize];
_egb.SetLocation(x);
_egb.Read(input);
_egb.Read(ideal);
var inputData = new BasicMLData(input, false);
var idealData = new BasicMLData(ideal, false);
var result = new BasicMLDataPair(inputData, idealData);
result.Significance = _egb.Read();
return result;
}
}
}
}
| |
//
// System.Data.SqlTypes.SqlInt32
//
// Author:
// Rodrigo Moya (rodrigo@ximian.com)
// Daniel Morgan (danmorg@sc.rr.com)
// Tim Coleman (tim@timcoleman.com)
// Ville Palo (vi64pa@koti.soon.fi)
//
// (C) Ximian, Inc. 2002
// (C) Copyright 2002 Tim Coleman
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Globalization;
namespace System.Data.SqlTypes
{
/// <summary>
/// a 32-bit signed integer to be used in reading or writing
/// of data from a database
/// </summary>
public struct SqlInt32 : INullable, IComparable
{
#region Fields
int value;
private bool notNull;
public static readonly SqlInt32 MaxValue = new SqlInt32 (2147483647);
public static readonly SqlInt32 MinValue = new SqlInt32 (-2147483648);
public static readonly SqlInt32 Null;
public static readonly SqlInt32 Zero = new SqlInt32 (0);
#endregion
#region Constructors
public SqlInt32(int value)
{
this.value = value;
notNull = true;
}
#endregion
#region Properties
public bool IsNull {
get { return !notNull; }
}
public int Value {
get {
if (this.IsNull)
throw new SqlNullValueException ();
else
return value;
}
}
#endregion
#region Methods
public static SqlInt32 Add (SqlInt32 x, SqlInt32 y)
{
return (x + y);
}
public static SqlInt32 BitwiseAnd(SqlInt32 x, SqlInt32 y)
{
return (x & y);
}
public static SqlInt32 BitwiseOr(SqlInt32 x, SqlInt32 y)
{
return (x | y);
}
public int CompareTo(object value)
{
if (value == null)
return 1;
else if (!(value is SqlInt32))
throw new ArgumentException (Locale.GetText ("Value is not a System.Data.SqlTypes.SqlInt32"));
return CompareSqlInt32 ((SqlInt32) value);
}
#if NET_2_0
public int CompareTo (SqlInt32 value)
{
return CompareSqlInt32 (value);
}
#endif
private int CompareSqlInt32 (SqlInt32 value)
{
if (value.IsNull)
return 1;
else
return this.value.CompareTo (value.Value);
}
public static SqlInt32 Divide(SqlInt32 x, SqlInt32 y)
{
return (x / y);
}
public override bool Equals(object value)
{
if (!(value is SqlInt32))
return false;
else if (this.IsNull && ((SqlInt32)value).IsNull)
return true;
else if (((SqlInt32)value).IsNull)
return false;
else
return (bool) (this == (SqlInt32)value);
}
public static SqlBoolean Equals(SqlInt32 x, SqlInt32 y)
{
return (x == y);
}
public override int GetHashCode()
{
return value;
}
public static SqlBoolean GreaterThan (SqlInt32 x, SqlInt32 y)
{
return (x > y);
}
public static SqlBoolean GreaterThanOrEqual (SqlInt32 x, SqlInt32 y)
{
return (x >= y);
}
public static SqlBoolean LessThan(SqlInt32 x, SqlInt32 y)
{
return (x < y);
}
public static SqlBoolean LessThanOrEqual(SqlInt32 x, SqlInt32 y)
{
return (x <= y);
}
public static SqlInt32 Mod(SqlInt32 x, SqlInt32 y)
{
return (x % y);
}
#if NET_2_0
public static SqlInt32 Modulus (SqlInt32 x, SqlInt32 y)
{
return (x % y);
}
#endif
public static SqlInt32 Multiply(SqlInt32 x, SqlInt32 y)
{
return (x * y);
}
public static SqlBoolean NotEquals(SqlInt32 x, SqlInt32 y)
{
return (x != y);
}
public static SqlInt32 OnesComplement(SqlInt32 x)
{
return ~x;
}
public static SqlInt32 Parse(string s)
{
return new SqlInt32 (Int32.Parse (s));
}
public static SqlInt32 Subtract(SqlInt32 x, SqlInt32 y)
{
return (x - y);
}
public SqlBoolean ToSqlBoolean()
{
return ((SqlBoolean)this);
}
public SqlByte ToSqlByte()
{
return ((SqlByte)this);
}
public SqlDecimal ToSqlDecimal()
{
return ((SqlDecimal)this);
}
public SqlDouble ToSqlDouble()
{
return ((SqlDouble)this);
}
public SqlInt16 ToSqlInt16()
{
return ((SqlInt16)this);
}
public SqlInt64 ToSqlInt64()
{
return ((SqlInt64)this);
}
public SqlMoney ToSqlMoney()
{
return ((SqlMoney)this);
}
public SqlSingle ToSqlSingle()
{
return ((SqlSingle)this);
}
public SqlString ToSqlString ()
{
return ((SqlString)this);
}
public override string ToString()
{
if (this.IsNull)
return "Null";
else
return value.ToString ();
}
public static SqlInt32 Xor(SqlInt32 x, SqlInt32 y)
{
return (x ^ y);
}
#endregion
#region Operators
// Compute Addition
public static SqlInt32 operator + (SqlInt32 x, SqlInt32 y)
{
checked {
return new SqlInt32 (x.Value + y.Value);
}
}
// Bitwise AND
public static SqlInt32 operator & (SqlInt32 x, SqlInt32 y)
{
return new SqlInt32 (x.Value & y.Value);
}
// Bitwise OR
public static SqlInt32 operator | (SqlInt32 x, SqlInt32 y)
{
checked {
return new SqlInt32 (x.Value | y.Value);
}
}
// Compute Division
public static SqlInt32 operator / (SqlInt32 x, SqlInt32 y)
{
checked {
return new SqlInt32 (x.Value / y.Value);
}
}
// Compare Equality
public static SqlBoolean operator == (SqlInt32 x, SqlInt32 y)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
else
return new SqlBoolean (x.Value == y.Value);
}
// Bitwise Exclusive-OR (XOR)
public static SqlInt32 operator ^ (SqlInt32 x, SqlInt32 y)
{
return new SqlInt32 (x.Value ^ y.Value);
}
// > Compare
public static SqlBoolean operator >(SqlInt32 x, SqlInt32 y)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
else
return new SqlBoolean (x.Value > y.Value);
}
// >= Compare
public static SqlBoolean operator >= (SqlInt32 x, SqlInt32 y)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
else
return new SqlBoolean (x.Value >= y.Value);
}
// != Inequality Compare
public static SqlBoolean operator != (SqlInt32 x, SqlInt32 y)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
else
return new SqlBoolean (x.Value != y.Value);
}
// < Compare
public static SqlBoolean operator < (SqlInt32 x, SqlInt32 y)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
else
return new SqlBoolean (x.Value < y.Value);
}
// <= Compare
public static SqlBoolean operator <= (SqlInt32 x, SqlInt32 y)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
else
return new SqlBoolean (x.Value <= y.Value);
}
// Compute Modulus
public static SqlInt32 operator % (SqlInt32 x, SqlInt32 y)
{
return new SqlInt32 (x.Value % y.Value);
}
// Compute Multiplication
public static SqlInt32 operator * (SqlInt32 x, SqlInt32 y)
{
checked {
return new SqlInt32 (x.Value * y.Value);
}
}
// Ones Complement
public static SqlInt32 operator ~ (SqlInt32 x)
{
return new SqlInt32 (~x.Value);
}
// Subtraction
public static SqlInt32 operator - (SqlInt32 x, SqlInt32 y)
{
checked {
return new SqlInt32 (x.Value - y.Value);
}
}
// Negates the Value
public static SqlInt32 operator - (SqlInt32 x)
{
return new SqlInt32 (-x.Value);
}
// Type Conversions
public static explicit operator SqlInt32 (SqlBoolean x)
{
if (x.IsNull)
return Null;
else
return new SqlInt32 ((int)x.ByteValue);
}
public static explicit operator SqlInt32 (SqlDecimal x)
{
checked {
if (x.IsNull)
return Null;
else
return new SqlInt32 ((int)x.Value);
}
}
public static explicit operator SqlInt32 (SqlDouble x)
{
checked {
if (x.IsNull)
return Null;
else
return new SqlInt32 ((int)x.Value);
}
}
public static explicit operator int (SqlInt32 x)
{
return x.Value;
}
public static explicit operator SqlInt32 (SqlInt64 x)
{
checked {
if (x.IsNull)
return Null;
else
return new SqlInt32 ((int)x.Value);
}
}
public static explicit operator SqlInt32(SqlMoney x)
{
checked {
if (x.IsNull)
return Null;
else
return new SqlInt32 ((int) Math.Round (x.Value));
}
}
public static explicit operator SqlInt32(SqlSingle x)
{
checked {
if (x.IsNull)
return Null;
else
return new SqlInt32 ((int)x.Value);
}
}
public static explicit operator SqlInt32(SqlString x)
{
checked {
return SqlInt32.Parse (x.Value);
}
}
public static implicit operator SqlInt32(int x)
{
return new SqlInt32 (x);
}
public static implicit operator SqlInt32(SqlByte x)
{
if (x.IsNull)
return Null;
else
return new SqlInt32 ((int)x.Value);
}
public static implicit operator SqlInt32(SqlInt16 x)
{
if (x.IsNull)
return Null;
else
return new SqlInt32 ((int)x.Value);
}
#endregion
}
}
| |
//
// IndexerClient.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Threading;
using Hyena;
using NDesk.DBus;
using org.freedesktop.DBus;
using Banshee.Collection.Indexer;
namespace Banshee.Collection.Indexer.RemoteHelper
{
public abstract class IndexerClient
{
private const string application_bus_name = "org.bansheeproject.Banshee";
private const string indexer_bus_name = "org.bansheeproject.CollectionIndexer";
private const string service_interface = "org.bansheeproject.CollectionIndexer.Service";
private static ObjectPath service_path = new ObjectPath ("/org/bansheeproject/Banshee/CollectionIndexerService");
private IBus session_bus;
private bool listening;
private ICollectionIndexerService service;
private bool cleanup_and_shutdown;
private bool index_when_collection_changed = true;
public void Start ()
{
ShowDebugMessages = true;
Debug ("Acquiring org.freedesktop.DBus session instance");
session_bus = Bus.Session.GetObject<IBus> ("org.freedesktop.DBus", new ObjectPath ("/org/freedesktop/DBus"));
session_bus.NameOwnerChanged += OnBusNameOwnerChanged;
if (Bus.Session.NameHasOwner (indexer_bus_name)) {
Debug ("{0} is already started", indexer_bus_name);
ConnectToIndexerService ();
} else {
Debug ("Starting {0}", indexer_bus_name);
Bus.Session.StartServiceByName (indexer_bus_name);
}
}
private void OnBusNameOwnerChanged (string name, string oldOwner, string newOwner)
{
if (name == indexer_bus_name) {
Debug ("NameOwnerChanged: {0}, '{1}' => '{2}'", name, oldOwner, newOwner);
if (service == null && !String.IsNullOrEmpty (newOwner)) {
ConnectToIndexerService ();
}
}
}
private void Index ()
{
if (HasCollectionChanged) {
ICollectionIndexer indexer = CreateIndexer ();
indexer.IndexingFinished += delegate { _UpdateIndex (indexer); };
indexer.Index ();
}
}
private void _UpdateIndex (ICollectionIndexer indexer)
{
ThreadPool.QueueUserWorkItem (delegate {
Debug ("Running indexer");
try {
UpdateIndex (indexer);
} catch (Exception e) {
Console.Error.WriteLine (e);
}
Debug ("Indexer finished");
indexer.Dispose ();
if (!ApplicationAvailable || !listening) {
DisconnectFromIndexerService ();
}
});
}
private void ConnectToIndexerService ()
{
DisconnectFromIndexerService ();
ResolveIndexerService ();
if (service == null) {
Log.Error ("Failed to connect to {0}, bailing.", service_interface);
return;
} else {
Debug ("Connected to {0}", service_interface);
}
service.CleanupAndShutdown += OnCleanupAndShutdown;
if (ApplicationAvailable) {
Debug ("Listening to service's CollectionChanged signal (full-app is running)");
listening = true;
service.CollectionChanged += OnCollectionChanged;
}
Index ();
}
private void DisconnectFromIndexerService ()
{
if (service == null) {
return;
}
Debug ("Disconnecting from service");
if (listening) {
try {
listening = false;
service.CollectionChanged -= OnCollectionChanged;
} catch (Exception e) {
Debug (e.ToString ());
}
}
try {
service.CleanupAndShutdown -= OnCleanupAndShutdown;
} catch (Exception e) {
Debug (e.ToString ());
}
try {
service.Shutdown ();
} catch (Exception e) {
Debug (e.ToString ());
}
ResetInternalState ();
}
private void ResetInternalState ()
{
if (service == null) {
return;
}
Debug ("Resetting internal state - service is no longer available or not needed");
service = null;
listening = false;
cleanup_and_shutdown = false;
ResetState ();
}
private void ResolveIndexerService ()
{
int attempts = 0;
while (attempts++ < 4) {
try {
Debug ("Resolving {0} (attempt {1})", service_interface, attempts);
service = Bus.Session.GetObject<ICollectionIndexerService> (indexer_bus_name, service_path);
service.Hello ();
return;
} catch {
service = null;
System.Threading.Thread.Sleep (2000);
}
}
}
private void OnCollectionChanged ()
{
if (IndexWhenCollectionChanged) {
Index ();
}
}
private void OnCleanupAndShutdown ()
{
cleanup_and_shutdown = true;
}
protected void Debug (string message, params object [] args)
{
Log.DebugFormat (message, args);
}
protected abstract bool HasCollectionChanged { get; }
protected abstract void UpdateIndex (ICollectionIndexer indexer);
protected abstract void ResetState ();
protected ICollectionIndexer CreateIndexer ()
{
ObjectPath object_path = service.CreateIndexer ();
Debug ("Creating an ICollectionIndexer ({0})", object_path);
return Bus.Session.GetObject<ICollectionIndexer> (indexer_bus_name, object_path);
}
public bool ShowDebugMessages {
get { return Log.Debugging; }
set { Log.Debugging = value; }
}
protected bool CleanupAndShutdown {
get { return cleanup_and_shutdown; }
}
public bool IndexWhenCollectionChanged {
get { return index_when_collection_changed; }
set { index_when_collection_changed = value; }
}
protected ICollectionIndexerService Service {
get { return service; }
}
protected bool ApplicationAvailable {
get { return Bus.Session.NameHasOwner (application_bus_name); }
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace Lucene.Net.Store
{
/// <summary>Abstract base class for input from a file in a {@link Directory}. A
/// random-access input stream. Used for all Lucene index input operations.
/// </summary>
/// <seealso cref="Directory">
/// </seealso>
public abstract class IndexInput : System.ICloneable
{
// used by ReadString()
private byte[] bytes;
// used by ReadModifiedUTF8String()
private char[] chars;
// true if using modified UTF-8 strings
private bool preUTF8Strings;
/// <summary>Reads and returns a single byte.</summary>
/// <seealso cref="IndexOutput.WriteByte(byte)">
/// </seealso>
public abstract byte ReadByte();
/// <summary>Reads a specified number of bytes into an array at the specified offset.</summary>
/// <param name="b">the array to read bytes into
/// </param>
/// <param name="offset">the offset in the array to start storing bytes
/// </param>
/// <param name="len">the number of bytes to read
/// </param>
/// <seealso cref="IndexOutput.WriteBytes(byte[],int)">
/// </seealso>
public abstract void ReadBytes(byte[] b, int offset, int len);
/// <summary>Reads a specified number of bytes into an array at the
/// specified offset with control over whether the read
/// should be buffered (callers who have their own buffer
/// should pass in "false" for useBuffer). Currently only
/// {@link BufferedIndexInput} respects this parameter.
/// </summary>
/// <param name="b">the array to read bytes into
/// </param>
/// <param name="offset">the offset in the array to start storing bytes
/// </param>
/// <param name="len">the number of bytes to read
/// </param>
/// <param name="useBuffer">set to false if the caller will handle
/// buffering.
/// </param>
/// <seealso cref="IndexOutput.WriteBytes(byte[],int)">
/// </seealso>
public virtual void ReadBytes(byte[] b, int offset, int len, bool useBuffer)
{
// Default to ignoring useBuffer entirely
ReadBytes(b, offset, len);
}
/// <summary>Reads four bytes and returns an int.</summary>
/// <seealso cref="IndexOutput.WriteInt(int)">
/// </seealso>
public virtual int ReadInt()
{
return ((ReadByte() & 0xFF) << 24) | ((ReadByte() & 0xFF) << 16) | ((ReadByte() & 0xFF) << 8) | (ReadByte() & 0xFF);
}
/// <summary>Reads an int stored in variable-length format. Reads between one and
/// five bytes. Smaller values take fewer bytes. Negative numbers are not
/// supported.
/// </summary>
/// <seealso cref="IndexOutput.WriteVInt(int)">
/// </seealso>
public virtual int ReadVInt()
{
byte b = ReadByte();
int i = b & 0x7F;
for (int shift = 7; (b & 0x80) != 0; shift += 7)
{
b = ReadByte();
i |= (b & 0x7F) << shift;
}
return i;
}
/// <summary>Reads eight bytes and returns a long.</summary>
/// <seealso cref="IndexOutput#WriteLong(long)">
/// </seealso>
public virtual long ReadLong()
{
return (((long) ReadInt()) << 32) | (ReadInt() & 0xFFFFFFFFL);
}
/// <summary>Reads a long stored in variable-length format. Reads between one and
/// nine bytes. Smaller values take fewer bytes. Negative numbers are not
/// supported.
/// </summary>
public virtual long ReadVLong()
{
byte b = ReadByte();
long i = b & 0x7F;
for (int shift = 7; (b & 0x80) != 0; shift += 7)
{
b = ReadByte();
i |= (b & 0x7FL) << shift;
}
return i;
}
/// <summary>
/// Set to read strings in the deprecated modified UTF-8 format
/// (length in Java chars and Java's modified UTF-8 encoding).
/// Used for pre-2.4.0 indexes. See JIRA LUCENE-510 for details.
/// </summary>
public void SetModifiedUTF8StringsMode()
{
preUTF8Strings = true;
}
/// <summary>Reads a string.</summary>
/// <seealso cref="IndexOutput.WriteString(String)">
/// </seealso>
public virtual string ReadString()
{
if (preUTF8Strings)
return ReadModifiedUTF8String();
int length = ReadVInt();
if (bytes == null || length > bytes.Length)
bytes = new byte[(int) (length*1.25)];
ReadBytes(bytes, 0, length);
return System.Text.Encoding.UTF8.GetString(bytes, 0, length);
}
public virtual string ReadModifiedUTF8String()
{
int length = ReadVInt();
if (chars == null || length > chars.Length)
chars = new char[length];
ReadChars(chars, 0, length);
return new String(chars, 0, length);
}
/// <summary>Reads Lucene's old "modified UTF-8" encoded characters into an array.</summary>
/// <param name="buffer">the array to read characters into
/// </param>
/// <param name="start">the offset in the array to start storing characters
/// </param>
/// <param name="length">the number of characters to read
/// </param>
/// <seealso cref="IndexOutput.WriteChars(String,int,int)">
/// </seealso>
[Obsolete("please use ReadString() or ReadBytes() instead")]
public virtual void ReadChars(char[] buffer, int start, int length)
{
int end = start + length;
for (int i = start; i < end; i++)
{
byte b = ReadByte();
if ((b & 0x80) == 0)
buffer[i] = (char) (b & 0x7F);
else if ((b & 0xE0) != 0xE0)
{
buffer[i] = (char) (((b & 0x1F) << 6) | (ReadByte() & 0x3F));
}
else
buffer[i] = (char) (((b & 0x0F) << 12) | ((ReadByte() & 0x3F) << 6) | (ReadByte() & 0x3F));
}
}
/// <summary> Expert
///
/// Similar to {@link #ReadChars(char[], int, int)} but does not do any conversion operations on the bytes it is reading in. It still
/// has to invoke {@link #ReadByte()} just as {@link #ReadChars(char[], int, int)} does, but it does not need a buffer to store anything
/// and it does not have to do any of the bitwise operations, since we don't actually care what is in the byte except to determine
/// how many more bytes to read
/// </summary>
/// <param name="length">The number of chars to read
/// </param>
[Obsolete("this method operates on old \"modified UTF-8\" encoded strings")]
public virtual void SkipChars(int length)
{
for (int i = 0; i < length; i++)
{
byte b = ReadByte();
if ((b & 0x80) == 0)
{
//do nothing, we only need one byte
}
else if ((b & 0xE0) != 0xE0)
{
ReadByte(); //read an additional byte
}
else
{
//read two additional bytes.
ReadByte();
ReadByte();
}
}
}
/// <summary>Closes the stream to futher operations. </summary>
public abstract void Close();
/// <summary>Returns the current position in this file, where the next read will
/// occur.
/// </summary>
/// <seealso cref="Seek(long)">
/// </seealso>
public abstract long GetFilePointer();
/// <summary>Sets current position in this file, where the next read will occur.</summary>
/// <seealso cref="GetFilePointer()">
/// </seealso>
public abstract void Seek(long pos);
/// <summary>The number of bytes in the file. </summary>
public abstract long Length();
/// <summary>Returns a clone of this stream.
///
/// <p>Clones of a stream access the same data, and are positioned at the same
/// point as the stream they were cloned from.
///
/// <p>Expert: Subclasses must ensure that clones may be positioned at
/// different points in the input from each other and from the stream they
/// were cloned from.
/// </summary>
public virtual object Clone()
{
IndexInput clone = null;
try
{
clone = (IndexInput) base.MemberwiseClone();
}
catch (System.Exception)
{
}
clone.bytes = null;
clone.chars = null;
return clone;
}
}
}
| |
using System;
using System.Text;
using Reinterpret.Net;
namespace Rs317.Sharp
{
public sealed class ItemDefinition
{
public static ItemDefinition getDefinition(int id)
{
for(int i = 0; i < 10; i++)
if(cache[i].id == id)
return cache[i];
cacheIndex = (cacheIndex + 1) % 10;
ItemDefinition definition = cache[cacheIndex];
stream.position = streamOffsets[id];
definition.id = id;
definition.setDefaults();
definition.readValues(stream);
if(definition.noteTemplateId != -1)
definition.toNote();
if(!membersWorld && definition.membersObject)
{
definition.name = "Members Object";
definition.description = "Login to a members' server to use this object.".Reinterpret(Encoding.ASCII);
definition.groundActions = null;
definition.actions = null;
definition.teamId = 0;
}
return definition;
}
public static Sprite getSprite(int itemId, int itemAmount, int type)
{
if(type == 0)
{
Sprite sprite = (Sprite)spriteCache.get(itemId);
if(sprite != null && sprite.maxHeight != itemAmount && sprite.maxHeight != -1)
{
sprite.unlink();
sprite = null;
}
if(sprite != null)
return sprite;
}
ItemDefinition definition = getDefinition(itemId);
if(definition.stackableIds == null)
itemAmount = -1;
if(itemAmount > 1)
{
int stackedId = -1;
for(int amount = 0; amount < 10; amount++)
if(itemAmount >= definition.stackableAmounts[amount] && definition.stackableAmounts[amount] != 0)
stackedId = definition.stackableIds[amount];
if(stackedId != -1)
definition = getDefinition(stackedId);
}
Model model = definition.getAmountModel(1);
if(model == null)
return null;
Sprite noteSprite = null;
if(definition.noteTemplateId != -1)
{
noteSprite = getSprite(definition.noteId, 10, -1);
if(noteSprite == null)
return null;
}
Sprite itemSprite = new Sprite(32, 32);
int textureCentreX = Rasterizer.centreX;
int textureCentreY = Rasterizer.centreY;
int[] lineOffsets = Rasterizer.lineOffsets;
int[] pixels = DrawingArea.pixels;
int width = DrawingArea.width;
int height = DrawingArea.height;
int topX = DrawingArea.topX;
int bottomX = DrawingArea.bottomX;
int topY = DrawingArea.topY;
int bottomY = DrawingArea.bottomY;
Rasterizer.textured = false;
DrawingArea.initDrawingArea(32, 32, itemSprite.pixels);
DrawingArea.drawFilledRectangle(0, 0, 32, 32, 0);
Rasterizer.setDefaultBounds();
int zoom = definition.modelZoom;
if(type == -1)
zoom = (int)(zoom * 1.5D);
if(type > 0)
zoom = (int)(zoom * 1.04D);
int l3 = Rasterizer.SINE[definition.modelRotationX] * zoom >> 16;
int i4 = Rasterizer.COSINE[definition.modelRotationX] * zoom >> 16;
model.renderSingle(definition.modelRotationY, definition.modelRotationZ, definition.modelRotationX,
definition.modelOffset1, l3 + model.modelHeight / 2 + definition.modelOffset2,
i4 + definition.modelOffset2);
for(int _x = 31; _x >= 0; _x--)
{
for(int _y = 31; _y >= 0; _y--)
if(itemSprite.pixels[_x + _y * 32] == 0)
if(_x > 0 && itemSprite.pixels[(_x - 1) + _y * 32] > 1)
itemSprite.pixels[_x + _y * 32] = 1;
else if(_y > 0 && itemSprite.pixels[_x + (_y - 1) * 32] > 1)
itemSprite.pixels[_x + _y * 32] = 1;
else if(_x < 31 && itemSprite.pixels[_x + 1 + _y * 32] > 1)
itemSprite.pixels[_x + _y * 32] = 1;
else if(_y < 31 && itemSprite.pixels[_x + (_y + 1) * 32] > 1)
itemSprite.pixels[_x + _y * 32] = 1;
}
if(type > 0)
{
for(int _x = 31; _x >= 0; _x--)
{
for(int _y = 31; _y >= 0; _y--)
if(itemSprite.pixels[_x + _y * 32] == 0)
if(_x > 0 && itemSprite.pixels[(_x - 1) + _y * 32] == 1)
itemSprite.pixels[_x + _y * 32] = type;
else if(_y > 0 && itemSprite.pixels[_x + (_y - 1) * 32] == 1)
itemSprite.pixels[_x + _y * 32] = type;
else if(_x < 31 && itemSprite.pixels[_x + 1 + _y * 32] == 1)
itemSprite.pixels[_x + _y * 32] = type;
else if(_y < 31 && itemSprite.pixels[_x + (_y + 1) * 32] == 1)
itemSprite.pixels[_x + _y * 32] = type;
}
}
else if(type == 0)
{
for(int _x = 31; _x >= 0; _x--)
{
for(int _y = 31; _y >= 0; _y--)
if(itemSprite.pixels[_x + _y * 32] == 0 && _x > 0 && _y > 0
&& itemSprite.pixels[(_x - 1) + (_y - 1) * 32] > 0)
itemSprite.pixels[_x + _y * 32] = 0x302020;
}
}
if(definition.noteTemplateId != -1)
{
int _maxWidth = noteSprite.maxWidth;
int _maxHeight = noteSprite.maxHeight;
noteSprite.maxWidth = 32;
noteSprite.maxHeight = 32;
noteSprite.drawImage(0, 0);
noteSprite.maxWidth = _maxWidth;
noteSprite.maxHeight = _maxHeight;
}
if(type == 0)
spriteCache.put(itemSprite, itemId);
DrawingArea.initDrawingArea(height, width, pixels);
DrawingArea.setDrawingArea(bottomY, topX, bottomX, topY);
Rasterizer.centreX = textureCentreX;
Rasterizer.centreY = textureCentreY;
Rasterizer.lineOffsets = lineOffsets;
Rasterizer.textured = true;
if(definition.stackable)
itemSprite.maxWidth = 33;
else
itemSprite.maxWidth = 32;
itemSprite.maxHeight = itemAmount;
return itemSprite;
}
public static void load(Archive streamLoader)
{
stream = new Default317Buffer(streamLoader.decompressFile("obj.dat"));
Default317Buffer index = new Default317Buffer(streamLoader.decompressFile("obj.idx"));
itemCount = index.getUnsignedLEShort();
streamOffsets = new int[itemCount];
int offset = 2;
for(int item = 0; item < itemCount; item++)
{
streamOffsets[item] = offset;
offset += index.getUnsignedLEShort();
}
cache = new ItemDefinition[10];
for(int definition = 0; definition < 10; definition++)
cache[definition] = new ItemDefinition();
}
public static void nullLoader()
{
modelCache = null;
spriteCache = null;
streamOffsets = null;
cache = null;
stream = null;
}
private byte equipModelTranslationFemale;
public int value;
private int[] modifiedModelColors;
public int id;
public static Cache spriteCache = new Cache(100);
public static Cache modelCache = new Cache(50);
private int[] originalModelColors;
public bool membersObject;
private int femaleEquipModelIdEmblem;
private int noteTemplateId;
private int femaleEquipModelIdSecondary;
private int maleEquipModelIdPrimary;
private int maleDialogueHatModelId;
private int modelScaleX;
public String[] groundActions;
private int modelOffset1;
public String name;
private static ItemDefinition[] cache;
private int femaleDialogueHatModelId;
private int modelId;
private int maleDialogueModelId;
public bool stackable;
public byte[] description;
private int noteId;
private static int cacheIndex;
public int modelZoom;
public static bool membersWorld = true;
private static Default317Buffer stream;
private int shadowModifier;
private int maleEquipModelIdEmblem;
private int maleEquipModelIdSecondary;
public String[] actions;
public int modelRotationX;
private int modelScaleZ;
private int modelScaleY;
private int[] stackableIds;
private int modelOffset2;
private static int[] streamOffsets;
private int lightModifier;
private int femaleDialogueModelId;
public int modelRotationY;
private int femaleEquipModelIdPrimary;
private int[] stackableAmounts;
public int teamId;
public static int itemCount;
private int modelRotationZ;
private byte equipModelTranslationMale;
private ItemDefinition()
{
id = -1;
}
public bool equipModelCached(int gender)
{
int equipModelIdPrimary = maleEquipModelIdPrimary;
int equipModelIdSecondary = maleEquipModelIdSecondary;
int equipModelIdEmblem = maleEquipModelIdEmblem;
if(gender == 1)
{
equipModelIdPrimary = femaleEquipModelIdPrimary;
equipModelIdSecondary = femaleEquipModelIdSecondary;
equipModelIdEmblem = femaleEquipModelIdEmblem;
}
if(equipModelIdPrimary == -1)
return true;
bool cached = true;
if(!Model.isCached(equipModelIdPrimary))
cached = false;
if(equipModelIdSecondary != -1 && !Model.isCached(equipModelIdSecondary))
cached = false;
if(equipModelIdEmblem != -1 && !Model.isCached(equipModelIdEmblem))
cached = false;
return cached;
}
public Model getAmountModel(int amount)
{
if(stackableIds != null && amount > 1)
{
int stackableId = -1;
for(int i = 0; i < 10; i++)
if(amount >= stackableAmounts[i] && stackableAmounts[i] != 0)
stackableId = stackableIds[i];
if(stackableId != -1)
return getDefinition(stackableId).getAmountModel(1);
}
Model stackedModel = (Model)modelCache.get(id);
if(stackedModel != null)
return stackedModel;
stackedModel = Model.getModel(modelId);
if(stackedModel == null)
return null;
if(modelScaleX != 128 || modelScaleY != 128 || modelScaleZ != 128)
stackedModel.scaleT(modelScaleX, modelScaleZ, modelScaleY);
if(modifiedModelColors != null)
{
for(int l = 0; l < modifiedModelColors.Length; l++)
stackedModel.recolour(modifiedModelColors[l], originalModelColors[l]);
}
stackedModel.applyLighting(64 + lightModifier, 768 + shadowModifier, -50, -10, -50, true);
stackedModel.singleTile = true;
modelCache.put(stackedModel, id);
return stackedModel;
}
public Model getDialogueModel(int gender)
{
int dialogueModelId = maleDialogueModelId;
int dialogueHatModelId = maleDialogueHatModelId;
if(gender == 1)
{
dialogueModelId = femaleDialogueModelId;
dialogueHatModelId = femaleDialogueHatModelId;
}
if(dialogueModelId == -1)
return null;
Model dialogueModel = Model.getModel(dialogueModelId);
if(dialogueHatModelId != -1)
{
Model dialogueHatModel = Model.getModel(dialogueHatModelId);
Model[] dialogueModels = { dialogueModel, dialogueHatModel };
dialogueModel = new Model(2, dialogueModels);
}
if(modifiedModelColors != null)
{
for(int c = 0; c < modifiedModelColors.Length; c++)
dialogueModel.recolour(modifiedModelColors[c], originalModelColors[c]);
}
return dialogueModel;
}
public Model getEquippedModel(int gender)
{
int equipModelIdPrimary = maleEquipModelIdPrimary;
int equipModelIdSecondary = maleEquipModelIdSecondary;
int equipModelIdEmblem = maleEquipModelIdEmblem;
if(gender == 1)
{
equipModelIdPrimary = femaleEquipModelIdPrimary;
equipModelIdSecondary = femaleEquipModelIdSecondary;
equipModelIdEmblem = femaleEquipModelIdEmblem;
}
if(equipModelIdPrimary == -1)
return null;
Model modelPrimary = Model.getModel(equipModelIdPrimary);
if(equipModelIdSecondary != -1)
if(equipModelIdEmblem != -1)
{
Model modelSecondary = Model.getModel(equipModelIdSecondary);
Model modelEmblem = Model.getModel(equipModelIdEmblem);
Model[] models = { modelPrimary, modelSecondary, modelEmblem };
modelPrimary = new Model(3, models);
}
else
{
Model modelSecondary = Model.getModel(equipModelIdSecondary);
Model[] models = { modelPrimary, modelSecondary };
modelPrimary = new Model(2, models);
}
if(gender == 0 && equipModelTranslationMale != 0)
modelPrimary.translate(0, equipModelTranslationMale, 0);
if(gender == 1 && equipModelTranslationFemale != 0)
modelPrimary.translate(0, equipModelTranslationFemale, 0);
if(modifiedModelColors != null)
{
for(int c = 0; c < modifiedModelColors.Length; c++)
modelPrimary.recolour(modifiedModelColors[c], originalModelColors[c]);
}
return modelPrimary;
}
public Model getInventoryModel(int amount)
{
if(stackableIds != null && amount > 1)
{
int stackableId = -1;
for(int i = 0; i < 10; i++)
if(amount >= stackableAmounts[i] && stackableAmounts[i] != 0)
stackableId = stackableIds[i];
if(stackableId != -1)
return getDefinition(stackableId).getInventoryModel(1);
}
Model stackedModel = Model.getModel(modelId);
if(stackedModel == null)
return null;
if(modifiedModelColors != null)
{
for(int c = 0; c < modifiedModelColors.Length; c++)
stackedModel.recolour(modifiedModelColors[c], originalModelColors[c]);
}
return stackedModel;
}
public bool isDialogueModelCached(int gender)
{
int dialogueModelId = maleDialogueModelId;
int dialogueHatModelId = maleDialogueHatModelId;
if(gender == 1)
{
dialogueModelId = femaleDialogueModelId;
dialogueHatModelId = femaleDialogueHatModelId;
}
if(dialogueModelId == -1)
return true;
bool cached = true;
if(!Model.isCached(dialogueModelId))
cached = false;
if(dialogueHatModelId != -1 && !Model.isCached(dialogueHatModelId))
cached = false;
return cached;
}
private void readValues(Default317Buffer stream)
{
do
{
int opcode = stream.getUnsignedByte();
if(opcode == 0)
return;
if(opcode == 1)
modelId = stream.getUnsignedLEShort();
else if(opcode == 2)
name = stream.getString();
else if(opcode == 3)
description = stream.readBytes();
else if(opcode == 4)
modelZoom = stream.getUnsignedLEShort();
else if(opcode == 5)
modelRotationX = stream.getUnsignedLEShort();
else if(opcode == 6)
modelRotationY = stream.getUnsignedLEShort();
else if(opcode == 7)
{
modelOffset1 = stream.getUnsignedLEShort();
if(modelOffset1 > 32767)
modelOffset1 -= 0x10000;
}
else if(opcode == 8)
{
modelOffset2 = stream.getUnsignedLEShort();
if(modelOffset2 > 32767)
modelOffset2 -= 0x10000;
}
else if(opcode == 10)
stream.getUnsignedLEShort();
else if(opcode == 11)
stackable = true;
else if(opcode == 12)
value = stream.getInt();
else if(opcode == 16)
membersObject = true;
else if(opcode == 23)
{
maleEquipModelIdPrimary = stream.getUnsignedLEShort();
equipModelTranslationMale = stream.get();
}
else if(opcode == 24)
maleEquipModelIdSecondary = stream.getUnsignedLEShort();
else if(opcode == 25)
{
femaleEquipModelIdPrimary = stream.getUnsignedLEShort();
equipModelTranslationFemale = stream.get();
}
else if(opcode == 26)
femaleEquipModelIdSecondary = stream.getUnsignedLEShort();
else if(opcode >= 30 && opcode < 35)
{
if(groundActions == null)
groundActions = new String[5];
groundActions[opcode - 30] = stream.getString();
if(groundActions[opcode - 30].Equals("hidden", StringComparison.InvariantCultureIgnoreCase))
groundActions[opcode - 30] = null;
}
else if(opcode >= 35 && opcode < 40)
{
if(actions == null)
actions = new String[5];
actions[opcode - 35] = stream.getString();
}
else if(opcode == 40)
{
int colourCount = stream.getUnsignedByte();
modifiedModelColors = new int[colourCount];
originalModelColors = new int[colourCount];
for(int c = 0; c < colourCount; c++)
{
modifiedModelColors[c] = stream.getUnsignedLEShort();
originalModelColors[c] = stream.getUnsignedLEShort();
}
}
else if(opcode == 78)
maleEquipModelIdEmblem = stream.getUnsignedLEShort();
else if(opcode == 79)
femaleEquipModelIdEmblem = stream.getUnsignedLEShort();
else if(opcode == 90)
maleDialogueModelId = stream.getUnsignedLEShort();
else if(opcode == 91)
femaleDialogueModelId = stream.getUnsignedLEShort();
else if(opcode == 92)
maleDialogueHatModelId = stream.getUnsignedLEShort();
else if(opcode == 93)
femaleDialogueHatModelId = stream.getUnsignedLEShort();
else if(opcode == 95)
modelRotationZ = stream.getUnsignedLEShort();
else if(opcode == 97)
noteId = stream.getUnsignedLEShort();
else if(opcode == 98)
noteTemplateId = stream.getUnsignedLEShort();
else if(opcode >= 100 && opcode < 110)
{
if(stackableIds == null)
{
stackableIds = new int[10];
stackableAmounts = new int[10];
}
stackableIds[opcode - 100] = stream.getUnsignedLEShort();
stackableAmounts[opcode - 100] = stream.getUnsignedLEShort();
}
else if(opcode == 110)
modelScaleX = stream.getUnsignedLEShort();
else if(opcode == 111)
modelScaleY = stream.getUnsignedLEShort();
else if(opcode == 112)
modelScaleZ = stream.getUnsignedLEShort();
else if(opcode == 113)
lightModifier = stream.get();
else if(opcode == 114)
shadowModifier = stream.get() * 5;
else if(opcode == 115)
teamId = stream.getUnsignedByte();
} while(true);
}
private void setDefaults()
{
modelId = 0;
name = null;
description = null;
modifiedModelColors = null;
originalModelColors = null;
modelZoom = 2000;
modelRotationX = 0;
modelRotationY = 0;
modelRotationZ = 0;
modelOffset1 = 0;
modelOffset2 = 0;
stackable = false;
value = 1;
membersObject = false;
groundActions = null;
actions = null;
maleEquipModelIdPrimary = -1;
maleEquipModelIdSecondary = -1;
equipModelTranslationMale = 0;
femaleEquipModelIdPrimary = -1;
femaleEquipModelIdSecondary = -1;
equipModelTranslationFemale = 0;
maleEquipModelIdEmblem = -1;
femaleEquipModelIdEmblem = -1;
maleDialogueModelId = -1;
maleDialogueHatModelId = -1;
femaleDialogueModelId = -1;
femaleDialogueHatModelId = -1;
stackableIds = null;
stackableAmounts = null;
noteId = -1;
noteTemplateId = -1;
modelScaleX = 128;
modelScaleY = 128;
modelScaleZ = 128;
lightModifier = 0;
shadowModifier = 0;
teamId = 0;
}
private void toNote()
{
ItemDefinition noteTemplateDefinition = getDefinition(noteTemplateId);
modelId = noteTemplateDefinition.modelId;
modelZoom = noteTemplateDefinition.modelZoom;
modelRotationX = noteTemplateDefinition.modelRotationX;
modelRotationY = noteTemplateDefinition.modelRotationY;
modelRotationZ = noteTemplateDefinition.modelRotationZ;
modelOffset1 = noteTemplateDefinition.modelOffset1;
modelOffset2 = noteTemplateDefinition.modelOffset2;
modifiedModelColors = noteTemplateDefinition.modifiedModelColors;
originalModelColors = noteTemplateDefinition.originalModelColors;
ItemDefinition noteDefinition = getDefinition(noteId);
name = noteDefinition.name;
membersObject = noteDefinition.membersObject;
value = noteDefinition.value;
String prefix = "a";
char firstCharacter = noteDefinition.name[0];
if(firstCharacter == 'A' || firstCharacter == 'E' || firstCharacter == 'I' || firstCharacter == 'O'
|| firstCharacter == 'U')
prefix = "an";
description = Encoding.ASCII.GetBytes($"Swap this note at any bank for {prefix} {noteDefinition.name}.");
stackable = true;
}
}
}
| |
//-----------------------------------------------------------------------------
//
// <copyright file="CompoundFileReference.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description:
// Implementation of the CompoundFileReference base class.
//
// History:
// 03/31/2003: BruceMac: Created (from ContainerReference.cs)
// 04/08/2003: BruceMac: Made into abstract base class.
// 05/20/2003: RogerCh: Ported to WCP tree. Split CompoundFileSubStreamReference.cs
// (2 classes) into individual files for ByteRange and Index
// reference.
// 08/11/2003: LGolding: Fix Bug 864168 (some of BruceMac's bug fixes were lost
// in port to WCP tree).
//
// Notes:
// Persistence of specific classes is mostly hard-coded in this base class because
// the persistence must follow a shared binary implementation with Office. It is
// also intentionally not polymorphic because we don't allow arbitrary subclasses
// to participate.
//-----------------------------------------------------------------------------
using System;
using System.Collections.Specialized; // for StringCollection class
using System.IO;
using System.Diagnostics; // for Debug.Assert
using System.Windows; // for SR error message lookup
using MS.Internal.WindowsBase;
namespace MS.Internal.IO.Packaging.CompoundFile
{
/// <summary>
/// Logical reference to a portion of a container
/// </summary>
/// <remarks>
/// Use this class to represent a logical reference to a portion of a container such as a stream
/// Note that a CompoundFileReference is not natively tied to any specific container. This lack of context allows
/// the developer freedom to create the reference in the absence of the container, or to have the reference
/// refer to any one of multiple containers having a similar format.
/// </remarks>
internal abstract class CompoundFileReference: IComparable
{
#region Enums
/// <summary>
/// Reference component types
/// </summary>
/// <remarks>
/// These are only used for serialization
/// </remarks>
private enum RefComponentType : int
{
/// <summary>
/// Stream component
/// </summary>
Stream = 0,
/// <summary>
/// Storage component
/// </summary>
Storage = 1,
};
#endregion
#region Abstracts
/// <summary>
/// Full name of the stream or storage this reference refers to (see StreamInfo and StorageInfo)
/// </summary>
abstract public string FullName {get;}
#endregion
#region IComparable
/// <summary>
/// This is not implemented - it exists as a reminder to authors of subclasses that they must implement this interface
/// </summary>
/// <param name="ob">ignored</param>
int IComparable.CompareTo(object ob)
{
// this must be implemented by our inheritors
Debug.Assert(false, "subclasses must override this method");
return 0;
}
#endregion
#region Operators
/// <summary>Compare for equality</summary>
/// <param name="o">the CompoundFileReference to compare to</param>
public override bool Equals(object o)
{
// this must be implemented by our inheritors
Debug.Assert(false, "subclasses must override this method");
return false;
}
/// <summary>Returns an integer suitable for including this object in a hash table</summary>
public override int GetHashCode()
{
// this must be implemented by our inheritors
Debug.Assert(false, "subclasses must override this method");
return 0;
}
#endregion
#region Persistence
/// <summary>Save to a stream</summary>
/// <param name="reference">reference to save</param>
/// <param name="writer">The BinaryWriter to persist this object to.
/// This method will alter the stream pointer of the underlying stream as a side effect.
/// Passing null simply calculates how many bytes would be written.</param>
/// <returns>number of bytes written including any padding</returns>
static internal int Save(CompoundFileReference reference, BinaryWriter writer)
{
int bytes = 0;
// NOTE: Our RefComponentType must be written by our caller
bool calcOnly = (writer == null);
// what are we dealing with here?
CompoundFileStreamReference streamReference = reference as CompoundFileStreamReference;
if ((streamReference == null) && (!(reference is CompoundFileStorageReference)))
throw new ArgumentException(SR.Get(SRID.UnknownReferenceSerialize), "reference");
// first parse the path into strings
string[] segments = ContainerUtilities.ConvertBackSlashPathToStringArrayPath(reference.FullName);
int entries = segments.Length;
// write the count
if (!calcOnly)
writer.Write( entries );
bytes += ContainerUtilities.Int32Size;
// write the segments - if we are dealing with a stream entry, don't write the last "segment"
// because it is in fact a stream name
for (int i = 0; i < segments.Length - (streamReference == null ? 0 : 1); i++)
{
if (!calcOnly)
{
writer.Write( (Int32)RefComponentType.Storage );
}
bytes += ContainerUtilities.Int32Size;
bytes += ContainerUtilities.WriteByteLengthPrefixedDWordPaddedUnicodeString(writer, segments[i]);
}
if (streamReference != null)
{
// we are responsible for the prefix
if (!calcOnly)
{
writer.Write( (Int32)RefComponentType.Stream );
}
bytes += ContainerUtilities.Int32Size;
// write the stream name
bytes += ContainerUtilities.WriteByteLengthPrefixedDWordPaddedUnicodeString(writer, segments[segments.Length - 1]);
}
return bytes;
}
/// <summary>
/// Deserialize from the given stream
/// </summary>
/// <param name="reader">the BinaryReader to deserialize from with the seek pointer at the beginning of the container reference</param>
/// <param name="bytesRead">bytes consumed from the stream</param>
/// <remarks>
/// Side effect of change the stream pointer
/// </remarks>
/// <exception cref="FileFormatException">Throws a FileFormatException if any formatting errors are encountered</exception>
internal static CompoundFileReference Load(BinaryReader reader, out int bytesRead)
{
ContainerUtilities.CheckAgainstNull( reader, "reader" );
bytesRead = 0; // running count of how much we've read - sanity check
// create the TypeMap
// reconstitute ourselves from the given BinaryReader
// in this version, the next Int32 is the number of entries
Int32 entryCount = reader.ReadInt32();
bytesRead += ContainerUtilities.Int32Size;
// EntryCount of zero indicates the root storage.
if (entryCount < 0)
throw new FileFormatException(
SR.Get(SRID.CFRCorrupt));
// need a temp collection because we don't know what we're dealing with until a non-storage component
// type is encountered
StringCollection storageList = null;
String streamName = null;
// loop through the entries - accumulating strings until we know what kind of object
// we ultimately need
int byteLength; // reusable
while (entryCount > 0)
{
// first Int32 tells us what kind of component this entry represents
RefComponentType refType = (RefComponentType)reader.ReadInt32();
bytesRead += ContainerUtilities.Int32Size;
switch (refType)
{
case RefComponentType.Storage:
{
if (streamName != null)
throw new FileFormatException(
SR.Get(SRID.CFRCorruptStgFollowStm));
if (storageList == null)
storageList = new StringCollection();
String str = ContainerUtilities.ReadByteLengthPrefixedDWordPaddedUnicodeString(reader, out byteLength);
bytesRead += byteLength;
storageList.Add(str);
} break;
case RefComponentType.Stream:
{
if (streamName != null)
throw new FileFormatException(
SR.Get(SRID.CFRCorruptMultiStream));
streamName = ContainerUtilities.ReadByteLengthPrefixedDWordPaddedUnicodeString(reader, out byteLength);
bytesRead += byteLength;
} break;
// we don't handle these types yet
default:
throw new FileFormatException(
SR.Get(SRID.UnknownReferenceComponentType));
}
--entryCount;
}
CompoundFileReference newRef = null;
// stream or storage?
if (streamName == null)
{
newRef = new CompoundFileStorageReference(
ContainerUtilities.ConvertStringArrayPathToBackSlashPath(storageList));
}
else
newRef = new CompoundFileStreamReference(
ContainerUtilities.ConvertStringArrayPathToBackSlashPath(storageList, streamName));
return newRef;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace System.Linq.Expressions
{
/// <summary>
/// Represents a constructor call that has a collection initializer.
/// </summary>
/// <remarks>
/// Use the <see cref="M:ListInit"/> factory methods to create a ListInitExpression.
/// The value of the NodeType property of a ListInitExpression is ListInit.
/// </remarks>
[DebuggerTypeProxy(typeof(Expression.ListInitExpressionProxy))]
public sealed class ListInitExpression : Expression
{
private readonly NewExpression _newExpression;
private readonly ReadOnlyCollection<ElementInit> _initializers;
internal ListInitExpression(NewExpression newExpression, ReadOnlyCollection<ElementInit> initializers)
{
_newExpression = newExpression;
_initializers = initializers;
}
/// <summary>
/// Returns the node type of this <see cref="Expression"/>. (Inherited from <see cref="Expression" />.)
/// </summary>
/// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
public sealed override ExpressionType NodeType
{
get { return ExpressionType.ListInit; }
}
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
/// </summary>
/// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
public sealed override Type Type
{
get { return _newExpression.Type; }
}
/// <summary>
/// Gets a value that indicates whether the expression tree node can be reduced.
/// </summary>
public override bool CanReduce
{
get
{
return true;
}
}
/// <summary>
/// Gets the expression that contains a call to the constructor of a collection type.
/// </summary>
public NewExpression NewExpression
{
get { return _newExpression; }
}
/// <summary>
/// Gets the element initializers that are used to initialize a collection.
/// </summary>
public ReadOnlyCollection<ElementInit> Initializers
{
get { return _initializers; }
}
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitListInit(this);
}
/// <summary>
/// Reduces the binary expression node to a simpler expression.
/// If CanReduce returns true, this should return a valid expression.
/// This method is allowed to return another node which itself
/// must be reduced.
/// </summary>
/// <returns>The reduced expression.</returns>
public override Expression Reduce()
{
return MemberInitExpression.ReduceListInit(_newExpression, _initializers, true);
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="newExpression">The <see cref="NewExpression" /> property of the result.</param>
/// <param name="initializers">The <see cref="Initializers" /> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public ListInitExpression Update(NewExpression newExpression, IEnumerable<ElementInit> initializers)
{
if (newExpression == NewExpression && initializers == Initializers)
{
return this;
}
return Expression.ListInit(newExpression, initializers);
}
}
public partial class Expression
{
/// <summary>
/// Creates a <see cref="ListInitExpression"/> that uses a method named "Add" to add elements to a collection.
/// </summary>
/// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param>
/// <param name="initializers">An array of <see cref="Expression"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param>
/// <returns>A <see cref="ListInitExpression"/> that has the <see cref="P:ListInitExpression.NodeType"/> property equal to ListInit and the <see cref="P:ListInitExpression.NewExpression"/> property set to the specified value.</returns>
public static ListInitExpression ListInit(NewExpression newExpression, params Expression[] initializers)
{
ContractUtils.RequiresNotNull(newExpression, "newExpression");
ContractUtils.RequiresNotNull(initializers, "initializers");
return ListInit(newExpression, initializers as IEnumerable<Expression>);
}
/// <summary>
/// Creates a <see cref="ListInitExpression"/> that uses a method named "Add" to add elements to a collection.
/// </summary>
/// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param>
/// <param name="initializers">An <see cref="IEnumerable{T}"/> that contains <see cref="M:ElementInit"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param>
/// <returns>A <see cref="ListInitExpression"/> that has the <see cref="P:ListInitExpression.NodeType"/> property equal to ListInit and the <see cref="P:ListInitExpression.NewExpression"/> property set to the specified value.</returns>
public static ListInitExpression ListInit(NewExpression newExpression, IEnumerable<Expression> initializers)
{
ContractUtils.RequiresNotNull(newExpression, "newExpression");
ContractUtils.RequiresNotNull(initializers, "initializers");
var initializerlist = initializers.ToReadOnly();
if (initializerlist.Count == 0)
{
throw Error.ListInitializerWithZeroMembers();
}
MethodInfo addMethod = FindMethod(newExpression.Type, "Add", null, new Expression[] { initializerlist[0] }, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
return ListInit(newExpression, addMethod, initializers);
}
/// <summary>
/// Creates a <see cref="ListInitExpression"/> that uses a specified method to add elements to a collection.
/// </summary>
/// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param>
/// <param name="addMethod">A <see cref="MethodInfo"/> that represents an instance method named "Add" (case insensitive), that adds an element to a collection. </param>
/// <param name="initializers">An array of <see cref="Expression"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param>
/// <returns>A <see cref="ListInitExpression"/> that has the <see cref="P:ListInitExpression.NodeType"/> property equal to ListInit and the <see cref="P:ListInitExpression.NewExpression"/> property set to the specified value.</returns>
public static ListInitExpression ListInit(NewExpression newExpression, MethodInfo addMethod, params Expression[] initializers)
{
if (addMethod == null)
{
return ListInit(newExpression, initializers as IEnumerable<Expression>);
}
ContractUtils.RequiresNotNull(newExpression, "newExpression");
ContractUtils.RequiresNotNull(initializers, "initializers");
return ListInit(newExpression, addMethod, initializers as IEnumerable<Expression>);
}
/// <summary>
/// Creates a <see cref="ListInitExpression"/> that uses a specified method to add elements to a collection.
/// </summary>
/// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param>
/// <param name="addMethod">A <see cref="MethodInfo"/> that represents an instance method named "Add" (case insensitive), that adds an element to a collection. </param>
/// <param name="initializers">An <see cref="IEnumerable{T}"/> that contains <see cref="Expression"/> objects to use to populate the Initializers collection.</param>
/// <returns>A <see cref="ListInitExpression"/> that has the <see cref="P:ListInitExpression.NodeType"/> property equal to ListInit and the <see cref="P:ListInitExpression.NewExpression"/> property set to the specified value.</returns>
public static ListInitExpression ListInit(NewExpression newExpression, MethodInfo addMethod, IEnumerable<Expression> initializers)
{
if (addMethod == null)
{
return ListInit(newExpression, initializers);
}
ContractUtils.RequiresNotNull(newExpression, "newExpression");
ContractUtils.RequiresNotNull(initializers, "initializers");
var initializerlist = initializers.ToReadOnly();
if (initializerlist.Count == 0)
{
throw Error.ListInitializerWithZeroMembers();
}
ElementInit[] initList = new ElementInit[initializerlist.Count];
for (int i = 0; i < initializerlist.Count; i++)
{
initList[i] = ElementInit(addMethod, initializerlist[i]);
}
return ListInit(newExpression, new TrueReadOnlyCollection<ElementInit>(initList));
}
/// <summary>
/// Creates a <see cref="ListInitExpression"/> that uses specified <see cref="M:ElementInit"/> objects to initialize a collection.
/// </summary>
/// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param>
/// <param name="initializers">An array that contains <see cref="M:ElementInit"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param>
/// <returns>
/// A <see cref="ListInitExpression"/> that has the <see cref="P:Expressions.NodeType"/> property equal to ListInit
/// and the <see cref="P:ListInitExpression.NewExpression"/> and <see cref="P:ListInitExpression.Initializers"/> properties set to the specified values.
/// </returns>
/// <remarks>
/// The <see cref="P:Expressions.Type"/> property of <paramref name="newExpression"/> must represent a type that implements <see cref="System.Collections.IEnumerable"/>.
/// The <see cref="P:Expressions.Type"/> property of the resulting <see cref="ListInitExpression"/> is equal to newExpression.Type.
/// </remarks>
public static ListInitExpression ListInit(NewExpression newExpression, params ElementInit[] initializers)
{
return ListInit(newExpression, (IEnumerable<ElementInit>)initializers);
}
/// <summary>
/// Creates a <see cref="ListInitExpression"/> that uses specified <see cref="M:ElementInit"/> objects to initialize a collection.
/// </summary>
/// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param>
/// <param name="initializers">An <see cref="IEnumerable{T}"/> that contains <see cref="M:ElementInit"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param>
/// <returns>An <see cref="IEnumerable{T}"/> that contains <see cref="M:ElementInit"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</returns>
/// <remarks>
/// The <see cref="P:Expressions.Type"/> property of <paramref name="newExpression"/> must represent a type that implements <see cref="System.Collections.IEnumerable"/>.
/// The <see cref="P:Expressions.Type"/> property of the resulting <see cref="ListInitExpression"/> is equal to newExpression.Type.
/// </remarks>
public static ListInitExpression ListInit(NewExpression newExpression, IEnumerable<ElementInit> initializers)
{
ContractUtils.RequiresNotNull(newExpression, "newExpression");
ContractUtils.RequiresNotNull(initializers, "initializers");
var initializerlist = initializers.ToReadOnly();
if (initializerlist.Count == 0)
{
throw Error.ListInitializerWithZeroMembers();
}
ValidateListInitArgs(newExpression.Type, initializerlist);
return new ListInitExpression(newExpression, initializerlist);
}
}
}
| |
/*
Copyright 2006 - 2010 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.IO;
using System.Xml;
using System.Text;
using OpenSource.UPnP;
using System.Collections;
using OpenSource.UPnP.AV;
namespace OpenSource.UPnP.AV.CdsMetadata
{
/// <summary>
/// This class is the general purpose class for getting
/// the strings for various element tag names and properties.
/// </summary>
public class Tags
{
/// <summary>
/// dublin core namespace value
/// </summary>
public const string XMLNSDC_VALUE = "http://purl.org/dc/elements/1.1/";
/// <summary>
/// upnp-av metadata namespace value
/// </summary>
public const string XMLNSUPNP_VALUE= "urn:schemas-upnp-org:metadata-1-0/upnp/";
/// <summary>
/// upnp-av subset of dublin-core namespace
/// </summary>
public const string XMLNSDIDL_VALUE= "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/";
/// <summary>
/// UPNP-AV defined abbreviation for dublin-core namespace is "dc"
/// </summary>
public const string XMLNS_DC = "xmlns:dc";
/// <summary>
/// UPNP-AV defined abbreviation for upnp-av metadata namespace is "upnp"
/// </summary>
public const string XMLNS_UPNP = "xmlns:upnp";
/// <summary>
/// XML namespace attribute name
/// </summary>
public const string XMLNS = "xmlns";
/// <summary>
/// A collection of all dublin-core element names without namespace.
/// </summary>
public ICollection DC { get { return m_DC; } }
/// <summary>
/// Collection of all upnp-av metadata element names without namespace.
/// </summary>
public ICollection UPNP { get { return m_UPNP; } }
/// <summary>
/// Collection of all DIDL-Lite element names without namespace.
/// </summary>
public ICollection DIDL { get { return m_DIDL; } }
/// <summary>
/// Collection of all attribute
/// names spanning all UPNP-AV/ContentDirectory namespaces,
/// without namespace.
/// </summary>
public ICollection ATTRIB { get { return m_ATTRIB; } }
/// <summary>
/// Enforce static instance.
/// </summary>
private Tags()
{
System.Array vals;
_DC dc = 0;
vals = Enum.GetValues(dc.GetType());
m_DC = new String[vals.Length];
for (int i=0; i < vals.Length; i++)
{
m_DC[i] = this[(_DC)vals.GetValue(i)];
}
_UPNP UPNP = 0;
vals = Enum.GetValues(UPNP.GetType());
m_UPNP = new String[vals.Length];
for (int i=0; i < vals.Length; i++)
{
m_UPNP[i] = this[(_UPNP)vals.GetValue(i)];
}
_DIDL DIDL = 0;
vals = Enum.GetValues(DIDL.GetType());
m_DIDL = new String[vals.Length];
for (int i=0; i < vals.Length; i++)
{
m_DIDL[i] = this[(_DIDL)vals.GetValue(i)];
}
_ATTRIB ATTRIB = 0;
vals = Enum.GetValues(ATTRIB.GetType());
m_ATTRIB = new String[vals.Length];
for (int i=0; i < vals.Length; i++)
{
m_ATTRIB[i] = this[(_ATTRIB)vals.GetValue(i)];
}
}
// public static string BuildXmlRepresentation(string baseUrl, ICollection entries)
// {
// return BuildXmlRepresentation("", new ArrayList(), entries);
// }
/// <summary>
/// the actual string values returned in DC
/// </summary>
private readonly string[] m_DC;
/// <summary>
/// actual string values in UPNP
/// </summary>
private readonly string[] m_UPNP;
/// <summary>
/// actual string values in DIDL
/// </summary>
private readonly string[] m_DIDL;
/// <summary>
/// actual string values in ATTRIB
/// </summary>
private readonly string[] m_ATTRIB;
/// <summary>
/// Allows easy retrieval of strings formatted both with
/// namespace and element name, given a value
/// from the <see cref="CommonPropertyNames"/>
/// enumerator.
/// </summary>
public string this[CommonPropertyNames tag]
{
get
{
StringBuilder sb = new StringBuilder(25);
string ns = "";
if (tag > CommonPropertyNames.DoNotUse)
{
ns = "dc:";
}
else if (tag < CommonPropertyNames.DoNotUse)
{
ns = "upnp:";
}
else
{
throw new Exception("Bad Evil. Improper value used to index Tags.");
}
if (tag == CommonPropertyNames.Class)
{
sb.AppendFormat("{1}{0}", "class", ns);
}
else
{
sb.AppendFormat("{1}{0}", tag.ToString(), ns);
}
return sb.ToString();
}
}
/// <summary>
/// Allows easy retrieval of strings formatted both with
/// namespace and element name, given a value
/// from the <see cref="_DC"/>
/// enumerator.
/// </summary>
public string this[_DC tag]
{
get
{
StringBuilder sb = new StringBuilder(25);
sb.AppendFormat("dc:{0}", tag.ToString());
return sb.ToString();
}
}
/// <summary>
/// Allows easy retrieval of strings formatted both with
/// namespace and element name, given a value
/// from the <see cref="_UPNP"/>
/// enumerator.
/// </summary>
public string this[_UPNP tag]
{
get
{
string str = tag.ToString();
if (tag == _UPNP.Class)
{
str = "class";
}
StringBuilder sb = new StringBuilder(25);
sb.AppendFormat("upnp:{0}", str);
return sb.ToString();
}
}
/// <summary>
/// Allows easy retrieval of strings form of an
/// <see cref="_ATTRIB"/>
/// value.
/// </summary>
public string this[_ATTRIB attrib]
{
get
{
StringBuilder sb = new StringBuilder(25);
sb.AppendFormat("{0}", attrib.ToString());
return sb.ToString();
}
}
/// <summary>
/// Allows easy retrieval of strings form of an
/// <see cref="_RESATTRIB"/>
/// value.
/// </summary>
public string this[_RESATTRIB attrib]
{
get
{
StringBuilder sb = new StringBuilder(25);
sb.AppendFormat("{0}", attrib.ToString());
return sb.ToString();
}
}
/// <summary>
/// Allows easy retrieval of DIDL-Lite element names given a value
/// from the <see cref="_DIDL"/>
/// enumerator.
/// </summary>
public string this[_DIDL tag]
{
get
{
string t;
if (tag == _DIDL.DIDL_Lite)
{
return "DIDL-Lite";
}
else
{
t = tag.ToString();
}
StringBuilder sb = new StringBuilder(25);
sb.AppendFormat("{0}", t);
sb[0] = char.ToLower(sb[0]);
return sb.ToString();
}
}
/// <summary>
/// The properties hashtable of a media object is not set.
/// </summary>
public class NullPropertiesException : Exception {}
/// <summary>
/// A media item improperly lacks a title.
/// </summary>
public class EmptyTitleException: Exception{}
/// <summary>
/// The one and only tags instance.
/// </summary>
private static Tags T = new Tags();
/// <summary>
/// Exposes a bunch of metadata properties that are attributes of elements
/// in their full name form, as used in ContentDirectory SearchCriteria
/// argument of Search action.
/// </summary>
public class PropertyAttributes
{
public const string item_parentID = "item@parentID";
public const string container_parentID = "container@parentID";
public const string container_childCount = "container@childCount";
public const string res_importUri = "res@importUri";
public const string res_size = "res@size";
public const string res_duration = "res@duration";
public const string res_bitrate = "res@bitrate";
public const string res_sampleFrequency = "res@sampleFrequency";
public const string res_bitsPerSample = "res@bitsPerSample";
public const string res_nrAudioChannels = "res@nrAudioChannels";
public const string res_resolution = "res@resolution";
public const string res_colorDepth = "res@colorDepth";
public const string res_protection = "res@protection";
public const string upnp_class = "upnp:class";
public const string upnp_className = "upnp:class@name";
public const string upnp_searchClass = "upnp:searchClass";
public const string upnp_searchClassName = "upnp:searchClass@name";
public const string upnp_searchClassIncludeDerived = "upnp:searchClass@includeDerived";
public const string upnp_createClass = "upnp:createClass";
public const string upnp_createClassName = "upnp:createClass@name";
public const string upnp_createClassIncludeDerived = "upnp:createClass@includeDerived";
public const string container_searchable = "container@searchable";
}
/// <summary>
/// Returns the static instance of Tags.
/// </summary>
/// <returns></returns>
public static Tags GetInstance()
{
return T;
}
}
}
| |
using System.Collections.Generic;
using System.Windows.Forms;
namespace eidss.avr.QueryBuilder
{
public class ChildQueryObjectList
{
private readonly List<QuerySearchObjectInfo> m_List;
private Control m_ParentControl;
private int m_Left;
private int m_Top;
private int m_Width = 464;
private int m_Height = 320;
private int m_TabIndex;
public ChildQueryObjectList()
{
m_List = new List<QuerySearchObjectInfo>();
m_ParentControl = null;
}
public ChildQueryObjectList(Control aParentControl)
{
m_List = new List<QuerySearchObjectInfo>();
m_ParentControl = aParentControl;
}
public ChildQueryObjectList(Control aParentControl, int aLeft, int aTop, int aWidth, int aHeight, int aTabIndex)
{
m_List = new List<QuerySearchObjectInfo>();
m_ParentControl = aParentControl;
m_Left = aLeft;
m_Top = aTop;
m_Width = aWidth;
m_Height = aHeight;
m_TabIndex = aTabIndex;
}
private void SetParentControl(Control ctrl)
{
foreach (var qso in m_List)
{
if ((m_ParentControl != null) && (m_ParentControl.Controls.Contains(qso)))
{
m_ParentControl.Controls.Remove(qso);
}
if (ctrl != null)
{
ctrl.Controls.Add(qso);
}
}
}
public Control ParentControl
{
get { return m_ParentControl; }
set
{
if (m_ParentControl == value)
{
return;
}
SetParentControl(value);
m_ParentControl = value;
}
}
private void SetLeft(int aLeft)
{
m_List.ForEach(qso => qso.Left = aLeft);
}
public int Left
{
get { return m_Left; }
set
{
if (m_Left == value)
{
return;
}
SetLeft(value);
m_Left = value;
}
}
private void SetTop(int aTop)
{
m_List.ForEach(qso => qso.Top = aTop);
}
public int Top
{
get { return m_Top; }
set
{
if (m_Top == value)
{
return;
}
SetTop(value);
m_Top = value;
}
}
private void SetWidth(int aWidth)
{
m_List.ForEach(qso => qso.Width = aWidth);
}
public int Width
{
get { return m_Width; }
set
{
if (m_Width == value)
{
return;
}
SetWidth(value);
m_Width = value;
}
}
private void SetHeight(int aHeight)
{
m_List.ForEach(qso => qso.Height = aHeight);
}
public int Height
{
get { return m_Height; }
set
{
if (m_Height == value)
{
return;
}
SetHeight(value);
m_Height = value;
}
}
private void SetTabIndex(int aTabIndex)
{
m_List.ForEach(qso => qso.TabIndex = aTabIndex);
}
public int TabIndex
{
get { return m_TabIndex; }
set
{
if (m_TabIndex == value)
{
return;
}
SetTabIndex(value);
m_TabIndex = value;
}
}
public int Count
{
get
{
if (m_List == null)
{
return 0;
}
return m_List.Count;
}
}
public QuerySearchObjectInfo Item(long aSearchObject)
{
return m_List.Find(qso => qso.SearchObject == aSearchObject);
}
public QuerySearchObjectInfo Item(int aOrder)
{
return m_List.Find(qso => qso.Order == aOrder);
}
public bool Contains(long aSearchObject)
{
return m_List.Exists(qso => qso.SearchObject == aSearchObject);
}
public bool Contains(QuerySearchObjectInfo qsoInfo)
{
return m_List.Contains(qsoInfo);
}
public QuerySearchObjectInfo Add(QuerySearchObjectInfo qsoInfo)
{
var qsoInfoEx = Item(qsoInfo.SearchObject);
if (qsoInfoEx != null)
{
return qsoInfoEx;
}
bool orderOk = (qsoInfo.Order > 0) && (qsoInfo.Order <= m_List.Count);
if (orderOk)
{
orderOk = false;
foreach (var qso in m_List)
{
if ((qsoInfo.Order == qso.Order))
orderOk = true;
if (orderOk)
qso.Order = qso.Order + 1;
}
}
if ((orderOk == false) && (qsoInfo.Order != m_List.Count + 1))
{
qsoInfo.Order = m_List.Count + 1;
}
qsoInfo.Visible = false;
if (m_ParentControl != null)
{
m_ParentControl.Controls.Add(qsoInfo);
}
//qsoInfo.Parent = m_ParentControl;
//qsoInfo.Left = m_Left;
//qsoInfo.Top = m_Top;
//qsoInfo.Width = m_Width;
//qsoInfo.Height = m_Height;
qsoInfo.TabIndex = m_TabIndex;
//qsoInfo.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom;
qsoInfo.Dock = DockStyle.Fill;
m_List.Add(qsoInfo);
//SetSearchObjectVisible(qsoInfo);
return qsoInfo;
}
public QuerySearchObjectInfo Add(long aSearchObject)
{
QuerySearchObjectInfo qsoInfo = Item(aSearchObject);
if (qsoInfo != null)
{
return qsoInfo;
}
qsoInfo = new QuerySearchObjectInfo(aSearchObject, m_List.Count + 1) { Name = string.Format("qso{0}", aSearchObject) };
return Add(qsoInfo);
}
public QuerySearchObjectInfo Add(long aSearchObject, int aOrder)
{
QuerySearchObjectInfo qsoInfo = Item(aSearchObject);
if (qsoInfo != null)
{
return qsoInfo;
}
qsoInfo = new QuerySearchObjectInfo(aSearchObject, aOrder) { Name = string.Format("qso{0}", aSearchObject) };
return Add(qsoInfo);
}
public void Remove(QuerySearchObjectInfo qsoInfo)
{
if (Contains(qsoInfo) == false)
{
return;
}
if (m_ParentControl != null)
{
m_ParentControl.Controls.Remove(qsoInfo);
qsoInfo.Parent = null;
}
foreach (var qso in m_List)
{
if ((qso.Order > qsoInfo.Order))
{
qso.Order = qso.Order - 1;
}
}
m_List.Remove(qsoInfo);
}
public void Remove(long aSearchObject)
{
if (Contains(aSearchObject) == false)
{
return;
}
QuerySearchObjectInfo qsoInfo = Item(aSearchObject);
Remove(qsoInfo);
}
public void Clear()
{
for (int i = m_List.Count - 1; i >= 0; i--)
{
Remove(m_List[i]);
}
}
public void SetSearchObjectVisible(QuerySearchObjectInfo qsoInfo)
{
if (Contains(qsoInfo) == false)
return;
m_List.ForEach(qso => qso.Visible = (qso == qsoInfo));
}
public void SetSearchObjectVisible(long aSearchObject)
{
if (Contains(aSearchObject) == false)
{
return;
}
QuerySearchObjectInfo qsoInfo = Item(aSearchObject);
SetSearchObjectVisible(qsoInfo);
}
public void SetAllSearchObjectsInVisible()
{
m_List.ForEach(qso => qso.Visible = false);
}
}
}
| |
/*
* 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.Threading;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.World
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "CloudModule")]
public class CloudModule : ICloudModule, INonSharedRegionModule
{
// private static readonly log4net.ILog m_log
// = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private uint m_frame = 0;
private int m_frameUpdateRate = 1000;
private Random m_rndnums;
private Scene m_scene = null;
private bool m_ready = false;
private bool m_enabled = false;
private float m_cloudDensity = 1.0F;
private float[] cloudCover = new float[16 * 16];
private int m_dataVersion;
private bool m_busy;
private object cloudlock = new object();
public void Initialise(IConfigSource config)
{
IConfig cloudConfig = config.Configs["Cloud"];
if (cloudConfig != null)
{
m_enabled = cloudConfig.GetBoolean("enabled", false);
m_cloudDensity = cloudConfig.GetFloat("density", 0.5F);
m_frameUpdateRate = cloudConfig.GetInt("cloud_update_rate", 1000);
}
}
public void AddRegion(Scene scene)
{
if (!m_enabled)
return;
m_scene = scene;
scene.RegisterModuleInterface<ICloudModule>(this);
int seed = Environment.TickCount;
seed += (int)(scene.RegionInfo.RegionLocX << 16);
seed += (int)(scene.RegionInfo.RegionLocY);
m_rndnums = new Random(seed);
GenerateCloudCover();
m_dataVersion = (int)m_scene.AllocateLocalId();
scene.EventManager.OnNewClient += CloudsToClient;
scene.EventManager.OnFrame += CloudUpdate;
m_ready = true;
}
public void RemoveRegion(Scene scene)
{
if (!m_enabled)
return;
m_ready = false;
// Remove our hooks
m_scene.EventManager.OnNewClient -= CloudsToClient;
m_scene.EventManager.OnFrame -= CloudUpdate;
m_scene.UnregisterModuleInterface<ICloudModule>(this);
m_scene = null;
}
public void RegionLoaded(Scene scene)
{
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return "CloudModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public float CloudCover(int x, int y, int z)
{
float cover = 0f;
x /= 16;
y /= 16;
if (x < 0) x = 0;
if (x > 15) x = 15;
if (y < 0) y = 0;
if (y > 15) y = 15;
if (cloudCover != null)
{
lock(cloudlock)
cover = cloudCover[y * 16 + x];
}
return cover;
}
private void UpdateCloudCover()
{
float[] newCover = new float[16 * 16];
int rowAbove = new int();
int rowBelow = new int();
int columnLeft = new int();
int columnRight = new int();
for (int x = 0; x < 16; x++)
{
if (x == 0)
{
columnRight = x + 1;
columnLeft = 15;
}
else if (x == 15)
{
columnRight = 0;
columnLeft = x - 1;
}
else
{
columnRight = x + 1;
columnLeft = x - 1;
}
for (int y = 0; y< 16; y++)
{
if (y == 0)
{
rowAbove = y + 1;
rowBelow = 15;
}
else if (y == 15)
{
rowAbove = 0;
rowBelow = y - 1;
}
else
{
rowAbove = y + 1;
rowBelow = y - 1;
}
float neighborAverage = (cloudCover[rowBelow * 16 + columnLeft] +
cloudCover[y * 16 + columnLeft] +
cloudCover[rowAbove * 16 + columnLeft] +
cloudCover[rowBelow * 16 + x] +
cloudCover[rowAbove * 16 + x] +
cloudCover[rowBelow * 16 + columnRight] +
cloudCover[y * 16 + columnRight] +
cloudCover[rowAbove * 16 + columnRight] +
cloudCover[y * 16 + x]) / 9;
newCover[y * 16 + x] = ((neighborAverage / m_cloudDensity) + 0.175f) % 1.0f;
newCover[y * 16 + x] *= m_cloudDensity;
}
}
Array.Copy(newCover, cloudCover, 16 * 16);
m_dataVersion++;
}
private void CloudUpdate()
{
if ((!m_ready || m_busy || m_cloudDensity == 0 ||
(m_frame++ % m_frameUpdateRate) != 0))
return;
if(Monitor.TryEnter(cloudlock))
{
m_busy = true;
Util.FireAndForget(delegate
{
try
{
lock(cloudlock)
{
UpdateCloudCover();
m_scene.ForEachClient(delegate(IClientAPI client)
{
client.SendCloudData(m_dataVersion, cloudCover);
});
}
}
finally
{
m_busy = false;
}
},
null, "CloudModuleUpdate");
Monitor.Exit(cloudlock);
}
}
public void CloudsToClient(IClientAPI client)
{
if (m_ready)
{
lock(cloudlock)
client.SendCloudData(m_dataVersion, cloudCover);
}
}
/// <summary>
/// Calculate the cloud cover over the region.
/// </summary>
private void GenerateCloudCover()
{
for (int y = 0; y < 16; y++)
{
for (int x = 0; x < 16; x++)
{
cloudCover[y * 16 + x] = (float)(m_rndnums.NextDouble()); // 0 to 1
cloudCover[y * 16 + x] *= m_cloudDensity;
}
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Utils;
using osu.Framework.Screens;
using osu.Framework.Testing;
using osu.Game.Configuration;
using osu.Game.Graphics.Containers;
using osu.Game.Overlays;
using osu.Game.Overlays.Notifications;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
using osu.Game.Screens.Play;
using osu.Game.Screens.Play.PlayerSettings;
using osu.Game.Utils;
using osuTK.Input;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestScenePlayerLoader : ScreenTestScene
{
private TestPlayerLoader loader;
private TestPlayer player;
private bool epilepsyWarning;
[Resolved]
private AudioManager audioManager { get; set; }
[Resolved]
private SessionStatics sessionStatics { get; set; }
[Cached]
private readonly NotificationOverlay notificationOverlay;
[Cached]
private readonly VolumeOverlay volumeOverlay;
[Cached(typeof(BatteryInfo))]
private readonly LocalBatteryInfo batteryInfo = new LocalBatteryInfo();
private readonly ChangelogOverlay changelogOverlay;
public TestScenePlayerLoader()
{
AddRange(new Drawable[]
{
notificationOverlay = new NotificationOverlay
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
},
volumeOverlay = new VolumeOverlay
{
Anchor = Anchor.TopLeft,
Origin = Anchor.TopLeft,
},
changelogOverlay = new ChangelogOverlay()
});
}
[SetUp]
public void Setup() => Schedule(() =>
{
player = null;
audioManager.Volume.SetDefault();
});
/// <summary>
/// Sets the input manager child to a new test player loader container instance.
/// </summary>
/// <param name="interactive">If the test player should behave like the production one.</param>
/// <param name="beforeLoadAction">An action to run before player load but after bindable leases are returned.</param>
private void resetPlayer(bool interactive, Action beforeLoadAction = null)
{
beforeLoadAction?.Invoke();
prepareBeatmap();
LoadScreen(loader = new TestPlayerLoader(() => player = new TestPlayer(interactive, interactive)));
}
private void prepareBeatmap()
{
var workingBeatmap = CreateWorkingBeatmap(new OsuRuleset().RulesetInfo);
workingBeatmap.BeatmapInfo.EpilepsyWarning = epilepsyWarning;
Beatmap.Value = workingBeatmap;
foreach (var mod in SelectedMods.Value.OfType<IApplicableToTrack>())
mod.ApplyToTrack(Beatmap.Value.Track);
}
[Test]
public void TestEarlyExitBeforePlayerConstruction()
{
AddStep("load dummy beatmap", () => resetPlayer(false, () => SelectedMods.Value = new[] { new OsuModNightcore() }));
AddUntilStep("wait for current", () => loader.IsCurrentScreen());
AddStep("exit loader", () => loader.Exit());
AddUntilStep("wait for not current", () => !loader.IsCurrentScreen());
AddAssert("player did not load", () => player == null);
AddUntilStep("player disposed", () => loader.DisposalTask == null);
AddAssert("mod rate still applied", () => Beatmap.Value.Track.Rate != 1);
}
/// <summary>
/// When <see cref="PlayerLoader"/> exits early, it has to wait for the player load task
/// to complete before running disposal on player. This previously caused an issue where mod
/// speed adjustments were undone too late, causing cross-screen pollution.
/// </summary>
[Test]
public void TestEarlyExitAfterPlayerConstruction()
{
AddStep("load dummy beatmap", () => resetPlayer(false, () => SelectedMods.Value = new[] { new OsuModNightcore() }));
AddUntilStep("wait for current", () => loader.IsCurrentScreen());
AddAssert("mod rate applied", () => Beatmap.Value.Track.Rate != 1);
AddUntilStep("wait for non-null player", () => player != null);
AddStep("exit loader", () => loader.Exit());
AddUntilStep("wait for not current", () => !loader.IsCurrentScreen());
AddAssert("player did not load", () => !player.IsLoaded);
AddUntilStep("player disposed", () => loader.DisposalTask?.IsCompleted == true);
AddAssert("mod rate still applied", () => Beatmap.Value.Track.Rate != 1);
}
[Test]
public void TestBlockLoadViaMouseMovement()
{
AddStep("load dummy beatmap", () => resetPlayer(false));
AddUntilStep("wait for current", () => loader.IsCurrentScreen());
AddUntilStep("wait for load ready", () =>
{
moveMouse();
return player?.LoadState == LoadState.Ready;
});
AddRepeatStep("move mouse", moveMouse, 20);
AddAssert("loader still active", () => loader.IsCurrentScreen());
AddUntilStep("loads after idle", () => !loader.IsCurrentScreen());
void moveMouse()
{
InputManager.MoveMouseTo(
loader.VisualSettings.ScreenSpaceDrawQuad.TopLeft
+ (loader.VisualSettings.ScreenSpaceDrawQuad.BottomRight - loader.VisualSettings.ScreenSpaceDrawQuad.TopLeft)
* RNG.NextSingle());
}
}
[Test]
public void TestBlockLoadViaFocus()
{
AddStep("load dummy beatmap", () => resetPlayer(false));
AddUntilStep("wait for current", () => loader.IsCurrentScreen());
AddStep("show focused overlay", () => changelogOverlay.Show());
AddUntilStep("overlay visible", () => changelogOverlay.IsPresent);
AddUntilStep("wait for load ready", () => player?.LoadState == LoadState.Ready);
AddRepeatStep("twiddle thumbs", () => { }, 20);
AddAssert("loader still active", () => loader.IsCurrentScreen());
AddStep("hide overlay", () => changelogOverlay.Hide());
AddUntilStep("loads after idle", () => !loader.IsCurrentScreen());
}
[Test]
public void TestLoadContinuation()
{
SlowLoadPlayer slowPlayer = null;
AddStep("load slow dummy beatmap", () =>
{
prepareBeatmap();
slowPlayer = new SlowLoadPlayer(false, false);
LoadScreen(loader = new TestPlayerLoader(() => slowPlayer));
});
AddStep("schedule slow load", () => Scheduler.AddDelayed(() => slowPlayer.AllowLoad.Set(), 5000));
AddUntilStep("wait for player to be current", () => slowPlayer.IsCurrentScreen());
}
[Test]
public void TestModReinstantiation()
{
TestMod gameMod = null;
TestMod playerMod1 = null;
TestMod playerMod2 = null;
AddStep("load player", () => { resetPlayer(true, () => SelectedMods.Value = new[] { gameMod = new TestMod() }); });
AddUntilStep("wait for loader to become current", () => loader.IsCurrentScreen());
AddStep("mouse in centre", () => InputManager.MoveMouseTo(loader.ScreenSpaceDrawQuad.Centre));
AddUntilStep("wait for player to be current", () => player.IsCurrentScreen());
AddStep("retrieve mods", () => playerMod1 = (TestMod)player.GameplayState.Mods.Single());
AddAssert("game mods not applied", () => gameMod.Applied == false);
AddAssert("player mods applied", () => playerMod1.Applied);
AddStep("restart player", () =>
{
var lastPlayer = player;
player = null;
lastPlayer.Restart();
});
AddUntilStep("wait for player to be current", () => player.IsCurrentScreen());
AddStep("retrieve mods", () => playerMod2 = (TestMod)player.GameplayState.Mods.Single());
AddAssert("game mods not applied", () => gameMod.Applied == false);
AddAssert("player has different mods", () => playerMod1 != playerMod2);
AddAssert("player mods applied", () => playerMod2.Applied);
}
[Test]
public void TestModDisplayChanges()
{
var testMod = new TestMod();
AddStep("load player", () => resetPlayer(true));
AddUntilStep("wait for loader to become current", () => loader.IsCurrentScreen());
AddStep("set test mod in loader", () => loader.Mods.Value = new[] { testMod });
AddAssert("test mod is displayed", () => (TestMod)loader.DisplayedMods.Single() == testMod);
}
[Test]
public void TestMutedNotificationMasterVolume()
{
addVolumeSteps("master volume", () => audioManager.Volume.Value = 0, () => audioManager.Volume.IsDefault);
}
[Test]
public void TestMutedNotificationTrackVolume()
{
addVolumeSteps("music volume", () => audioManager.VolumeTrack.Value = 0, () => audioManager.VolumeTrack.IsDefault);
}
[Test]
public void TestMutedNotificationMuteButton()
{
addVolumeSteps("mute button", () =>
{
// Importantly, in the case the volume is muted but the user has a volume level set, it should be retained.
audioManager.VolumeTrack.Value = 0.5f;
volumeOverlay.IsMuted.Value = true;
}, () => !volumeOverlay.IsMuted.Value && audioManager.VolumeTrack.Value == 0.5f);
}
/// <remarks>
/// Created for avoiding copy pasting code for the same steps.
/// </remarks>
/// <param name="volumeName">What part of the volume system is checked</param>
/// <param name="beforeLoad">The action to be invoked to set the volume before loading</param>
/// <param name="assert">The function to be invoked and checked</param>
private void addVolumeSteps(string volumeName, Action beforeLoad, Func<bool> assert)
{
AddStep("reset notification lock", () => sessionStatics.GetBindable<bool>(Static.MutedAudioNotificationShownOnce).Value = false);
AddStep("load player", () => resetPlayer(false, beforeLoad));
AddUntilStep("wait for player", () => player?.LoadState == LoadState.Ready);
AddAssert("check for notification", () => notificationOverlay.UnreadCount.Value == 1);
AddStep("click notification", () =>
{
var scrollContainer = (OsuScrollContainer)notificationOverlay.Children.Last();
var flowContainer = scrollContainer.Children.OfType<FillFlowContainer<NotificationSection>>().First();
var notification = flowContainer.First();
InputManager.MoveMouseTo(notification);
InputManager.Click(MouseButton.Left);
});
AddAssert("check " + volumeName, assert);
AddUntilStep("wait for player load", () => player.IsLoaded);
}
[TestCase(true)]
[TestCase(false)]
public void TestEpilepsyWarning(bool warning)
{
AddStep("change epilepsy warning", () => epilepsyWarning = warning);
AddStep("load dummy beatmap", () => resetPlayer(false));
AddUntilStep("wait for current", () => loader.IsCurrentScreen());
AddAssert($"epilepsy warning {(warning ? "present" : "absent")}", () => (getWarning() != null) == warning);
if (warning)
{
AddUntilStep("sound volume decreased", () => Beatmap.Value.Track.AggregateVolume.Value == 0.25);
AddUntilStep("sound volume restored", () => Beatmap.Value.Track.AggregateVolume.Value == 1);
}
}
[TestCase(false, 1.0, false)] // not charging, above cutoff --> no warning
[TestCase(true, 0.1, false)] // charging, below cutoff --> no warning
[TestCase(false, 0.25, true)] // not charging, at cutoff --> warning
public void TestLowBatteryNotification(bool isCharging, double chargeLevel, bool shouldWarn)
{
AddStep("reset notification lock", () => sessionStatics.GetBindable<bool>(Static.LowBatteryNotificationShownOnce).Value = false);
// set charge status and level
AddStep("load player", () => resetPlayer(false, () =>
{
batteryInfo.SetCharging(isCharging);
batteryInfo.SetChargeLevel(chargeLevel);
}));
AddUntilStep("wait for player", () => player?.LoadState == LoadState.Ready);
AddAssert($"notification {(shouldWarn ? "triggered" : "not triggered")}", () => notificationOverlay.UnreadCount.Value == (shouldWarn ? 1 : 0));
AddStep("click notification", () =>
{
var scrollContainer = (OsuScrollContainer)notificationOverlay.Children.Last();
var flowContainer = scrollContainer.Children.OfType<FillFlowContainer<NotificationSection>>().First();
var notification = flowContainer.First();
InputManager.MoveMouseTo(notification);
InputManager.Click(MouseButton.Left);
});
AddUntilStep("wait for player load", () => player.IsLoaded);
}
[Test]
public void TestEpilepsyWarningEarlyExit()
{
AddStep("set epilepsy warning", () => epilepsyWarning = true);
AddStep("load dummy beatmap", () => resetPlayer(false));
AddUntilStep("wait for current", () => loader.IsCurrentScreen());
AddUntilStep("wait for epilepsy warning", () => getWarning().Alpha > 0);
AddUntilStep("warning is shown", () => getWarning().State.Value == Visibility.Visible);
AddStep("exit early", () => loader.Exit());
AddUntilStep("warning is hidden", () => getWarning().State.Value == Visibility.Hidden);
AddUntilStep("sound volume restored", () => Beatmap.Value.Track.AggregateVolume.Value == 1);
}
private EpilepsyWarning getWarning() => loader.ChildrenOfType<EpilepsyWarning>().SingleOrDefault();
private class TestPlayerLoader : PlayerLoader
{
public new VisualSettings VisualSettings => base.VisualSettings;
public new Task DisposalTask => base.DisposalTask;
public IReadOnlyList<Mod> DisplayedMods => MetadataInfo.Mods.Value;
public TestPlayerLoader(Func<Player> createPlayer)
: base(createPlayer)
{
}
}
private class TestMod : Mod, IApplicableToScoreProcessor
{
public override string Name => string.Empty;
public override string Acronym => string.Empty;
public override double ScoreMultiplier => 1;
public override string Description => string.Empty;
public bool Applied { get; private set; }
public void ApplyToScoreProcessor(ScoreProcessor scoreProcessor)
{
Applied = true;
}
public ScoreRank AdjustRank(ScoreRank rank, double accuracy) => rank;
}
protected class SlowLoadPlayer : TestPlayer
{
public readonly ManualResetEventSlim AllowLoad = new ManualResetEventSlim(false);
public SlowLoadPlayer(bool allowPause = true, bool showResults = true)
: base(allowPause, showResults)
{
}
[BackgroundDependencyLoader]
private void load()
{
if (!AllowLoad.Wait(TimeSpan.FromSeconds(10)))
throw new TimeoutException();
}
}
/// <summary>
/// Mutable dummy BatteryInfo class for <see cref="TestScenePlayerLoader.TestLowBatteryNotification"/>
/// </summary>
/// <inheritdoc/>
private class LocalBatteryInfo : BatteryInfo
{
private bool isCharging = true;
private double chargeLevel = 1;
public override bool IsCharging => isCharging;
public override double ChargeLevel => chargeLevel;
public void SetCharging(bool value)
{
isCharging = value;
}
public void SetChargeLevel(double value)
{
chargeLevel = value;
}
}
}
}
| |
// Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using NodaTime.Text;
using NUnit.Framework;
using NodaTime.Test.Calendars;
namespace NodaTime.Test.Text
{
public class LocalDatePatternTest : PatternTestBase<LocalDate>
{
private static readonly LocalDate SampleLocalDate = new LocalDate(1976, 6, 19);
internal static readonly Data[] InvalidPatternData = {
new Data { Pattern = "", Message = TextErrorMessages.FormatStringEmpty },
new Data { Pattern = "!", Message = TextErrorMessages.UnknownStandardFormat, Parameters = {'!', typeof(LocalDate).FullName }},
new Data { Pattern = "%", Message = TextErrorMessages.UnknownStandardFormat, Parameters = { '%', typeof(LocalDate).FullName } },
new Data { Pattern = "\\", Message = TextErrorMessages.UnknownStandardFormat, Parameters = { '\\', typeof(LocalDate).FullName } },
new Data { Pattern = "%%", Message = TextErrorMessages.PercentDoubled },
new Data { Pattern = "%\\", Message = TextErrorMessages.EscapeAtEndOfString },
new Data { Pattern = "MMMMM", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'M', 4 } },
new Data { Pattern = "ddddd", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'd', 4 } },
new Data { Pattern = "M%", Message = TextErrorMessages.PercentAtEndOfString },
new Data { Pattern = "yyyyy", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'y', 4 } },
new Data { Pattern = "uuuuu", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'u', 4 } },
new Data { Pattern = "ggg", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'g', 2 } },
new Data { Pattern = "'qwe", Message = TextErrorMessages.MissingEndQuote, Parameters = { '\'' } },
new Data { Pattern = "'qwe\\", Message = TextErrorMessages.EscapeAtEndOfString },
new Data { Pattern = "'qwe\\'", Message = TextErrorMessages.MissingEndQuote, Parameters = { '\'' } },
// Note incorrect use of "u" (year) instead of "y" (year of era)
new Data { Pattern = "dd MM uuuu gg", Message = TextErrorMessages.EraWithoutYearOfEra },
// Era specifier and calendar specifier in the same pattern.
new Data { Pattern = "dd MM yyyy gg c", Message = TextErrorMessages.CalendarAndEra },
// Invalid patterns directly after the yyyy specifier. This will detect the issue early, but then
// continue and reject it in the normal path.
new Data { Pattern = "yyyy'", Message = TextErrorMessages.MissingEndQuote, Parameters = { '\'' } },
new Data { Pattern = "yyyy\\", Message = TextErrorMessages.EscapeAtEndOfString },
// Common typo, which is caught in 2.0...
new Data { Pattern = "yyyy-mm-dd", Message = TextErrorMessages.UnquotedLiteral, Parameters = { 'm' } },
// T isn't valid in a date pattern
new Data { Pattern = "yyyy-MM-ddT00:00:00", Message = TextErrorMessages.UnquotedLiteral, Parameters = { 'T' } },
// These became invalid in v2.0, when we decided that y and yyy weren't sensible.
new Data { Pattern = "y M d", Message = TextErrorMessages.InvalidRepeatCount, Parameters = { 'y', 1 } },
new Data { Pattern = "yyy M d", Message = TextErrorMessages.InvalidRepeatCount, Parameters = { 'y', 3 } },
};
internal static Data[] ParseFailureData = {
new Data { Pattern = "yyyy gg", Text = "2011 NodaEra", Message = TextErrorMessages.MismatchedText, Parameters = {'g'} },
new Data { Pattern = "yyyy uuuu gg", Text = "0010 0009 B.C.", Message = TextErrorMessages.InconsistentValues2, Parameters = {'g', 'u', typeof(LocalDate)} },
new Data { Pattern = "yyyy MM dd dddd", Text = "2011 10 09 Saturday", Message = TextErrorMessages.InconsistentDayOfWeekTextValue },
new Data { Pattern = "yyyy MM dd ddd", Text = "2011 10 09 Sat", Message = TextErrorMessages.InconsistentDayOfWeekTextValue },
new Data { Pattern = "yyyy MM dd MMMM", Text = "2011 10 09 January", Message = TextErrorMessages.InconsistentMonthTextValue },
new Data { Pattern = "yyyy MM dd ddd", Text = "2011 10 09 FooBar", Message = TextErrorMessages.MismatchedText, Parameters = {'d'} },
new Data { Pattern = "yyyy MM dd dddd", Text = "2011 10 09 FooBar", Message = TextErrorMessages.MismatchedText, Parameters = {'d'} },
new Data { Pattern = "yyyy/MM/dd", Text = "2011/02-29", Message = TextErrorMessages.DateSeparatorMismatch },
// Don't match a short name against a long pattern
new Data { Pattern = "yyyy MMMM dd", Text = "2011 Oct 09", Message = TextErrorMessages.MismatchedText, Parameters = {'M'} },
// Or vice versa... although this time we match the "Oct" and then fail as we're expecting a space
new Data { Pattern = "yyyy MMM dd", Text = "2011 October 09", Message = TextErrorMessages.MismatchedCharacter, Parameters = {' '}},
// Invalid month even when we've got genitive and non-genitive names to pick from
new Data(2011, 1, 3) { Pattern = "MMMM", Text = "BogusName", Culture = Cultures.GenitiveNameTestCulture, Message = TextErrorMessages.MismatchedText, Parameters = {'M'}},
// Invalid year, year-of-era, month, day
new Data { Pattern = "yyyy MM dd", Text = "0000 01 01", Message = TextErrorMessages.FieldValueOutOfRange, Parameters = { 0, 'y', typeof(LocalDate) } },
new Data { Pattern = "yyyy MM dd", Text = "2011 15 29", Message = TextErrorMessages.MonthOutOfRange, Parameters = { 15, 2011 } },
new Data { Pattern = "yyyy MM dd", Text = "2011 02 35", Message = TextErrorMessages.DayOfMonthOutOfRange, Parameters = { 35, 2, 2011 } },
// Year of era can't be negative...
new Data { Pattern = "yyyy MM dd", Text = "-15 01 01", Message = TextErrorMessages.UnexpectedNegative },
// Invalid leap years
new Data { Pattern = "yyyy MM dd", Text = "2011 02 29", Message = TextErrorMessages.DayOfMonthOutOfRange, Parameters = { 29, 2, 2011 } },
new Data { Pattern = "yyyy MM dd", Text = "1900 02 29", Message = TextErrorMessages.DayOfMonthOutOfRange, Parameters = { 29, 2, 1900 } },
// Year of era and two-digit year, but they don't match
new Data { Pattern = "uuuu yy", Text = "2011 10", Message = TextErrorMessages.InconsistentValues2, Parameters = { 'y', 'u', typeof(LocalDate) } },
// Invalid calendar name
new Data { Pattern = "c yyyy MM dd", Text = "2015 01 01", Message = TextErrorMessages.NoMatchingCalendarSystem },
// Invalid year
new Data { Template = new LocalDate(1, 1, 1, CalendarSystem.IslamicBcl), Pattern = "uuuu", Text = "9999", Message = TextErrorMessages.FieldValueOutOfRange, Parameters = { 9999, 'u', typeof(LocalDate) } },
new Data { Template = new LocalDate(1, 1, 1, CalendarSystem.IslamicBcl), Pattern = "yyyy", Text = "9999", Message = TextErrorMessages.YearOfEraOutOfRange, Parameters = { 9999, "EH", "Hijri" } },
// https://github.com/nodatime/nodatime/issues/414
new Data { Pattern = "yyyy-MM-dd", Text = "1984-00-15", Message = TextErrorMessages.FieldValueOutOfRange, Parameters = { 0, 'M', typeof(LocalDate) } },
new Data { Pattern = "M/d/yyyy", Text = "00/15/1984", Message = TextErrorMessages.FieldValueOutOfRange, Parameters = { 0, 'M', typeof(LocalDate) } },
// Calendar ID parsing is now ordinal, case-sensitive
new Data(2011, 10, 9) { Pattern = "yyyy MM dd c", Text = "2011 10 09 iso", Message = TextErrorMessages.NoMatchingCalendarSystem },
};
internal static Data[] ParseOnlyData = {
// Alternative era names
new Data(0, 10, 3) { Pattern = "yyyy MM dd gg", Text = "0001 10 03 BCE" },
// Valid leap years
new Data(2000, 2, 29) { Pattern = "yyyy MM dd", Text = "2000 02 29" },
new Data(2004, 2, 29) { Pattern = "yyyy MM dd", Text = "2004 02 29" },
// Month parsing should be case-insensitive
new Data(2011, 10, 3) { Pattern = "yyyy MMM dd", Text = "2011 OcT 03" },
new Data(2011, 10, 3) { Pattern = "yyyy MMMM dd", Text = "2011 OcToBeR 03" },
// Day-of-week parsing should be case-insensitive
new Data(2011, 10, 9) { Pattern = "yyyy MM dd ddd", Text = "2011 10 09 sUN" },
new Data(2011, 10, 9) { Pattern = "yyyy MM dd dddd", Text = "2011 10 09 SuNDaY" },
// Genitive name is an extension of the non-genitive name; parse longer first.
new Data(2011, 1, 10) { Pattern = "yyyy MMMM dd", Text = "2011 MonthName-Genitive 10", Culture = Cultures.GenitiveNameTestCultureWithLeadingNames },
new Data(2011, 1, 10) { Pattern = "yyyy MMMM dd", Text = "2011 MonthName 10", Culture = Cultures.GenitiveNameTestCultureWithLeadingNames },
new Data(2011, 1, 10) { Pattern = "yyyy MMM dd", Text = "2011 MN-Gen 10", Culture = Cultures.GenitiveNameTestCultureWithLeadingNames },
new Data(2011, 1, 10) { Pattern = "yyyy MMM dd", Text = "2011 MN 10", Culture = Cultures.GenitiveNameTestCultureWithLeadingNames },
};
internal static Data[] FormatOnlyData = {
// Would parse back to 2011
new Data(1811, 7, 3) { Pattern = "yy M d", Text = "11 7 3" },
// Tests for the documented 2-digit formatting of BC years
// (Less of an issue since yy became "year of era")
new Data(-94, 7, 3) { Pattern = "yy M d", Text = "95 7 3" },
new Data(-93, 7, 3) { Pattern = "yy M d", Text = "94 7 3" },
};
internal static Data[] FormatAndParseData = {
// Standard patterns
// Invariant culture uses the crazy MM/dd/yyyy format. Blech.
new Data(2011, 10, 20) { Pattern = "d", Text = "10/20/2011" },
new Data(2011, 10, 20) { Pattern = "D", Text = "Thursday, 20 October 2011" },
// ISO pattern uses a sensible format
new Data(2011, 10, 20) { StandardPattern = LocalDatePattern.Iso, Pattern = "R", Text = "2011-10-20" },
// Round trip with calendar system
new Data(2011, 10, 20, CalendarSystem.Coptic) { StandardPattern = LocalDatePattern.FullRoundtrip, Pattern = "r", Text = "2011-10-20 (Coptic)" },
// Custom patterns
new Data(2011, 10, 3) { Pattern = "yyyy/MM/dd", Text = "2011/10/03" },
new Data(2011, 10, 3) { Pattern = "yyyy/MM/dd", Text = "2011-10-03", Culture = Cultures.FrCa },
new Data(2011, 10, 3) { Pattern = "yyyyMMdd", Text = "20111003" },
new Data(2001, 7, 3) { Pattern = "yy M d", Text = "01 7 3" },
new Data(2011, 7, 3) { Pattern = "yy M d", Text = "11 7 3" },
new Data(2030, 7, 3) { Pattern = "yy M d", Text = "30 7 3" },
// Cutoff defaults to 30 (at the moment...)
new Data(1931, 7, 3) { Pattern = "yy M d", Text = "31 7 3" },
new Data(1976, 7, 3) { Pattern = "yy M d", Text = "76 7 3" },
// In the first century, we don't skip back a century for "high" two-digit year numbers.
new Data(25, 7, 3) { Pattern = "yy M d", Text = "25 7 3", Template = new LocalDate(50, 1, 1) },
new Data(35, 7, 3) { Pattern = "yy M d", Text = "35 7 3", Template = new LocalDate(50, 1, 1) },
new Data(2000, 10, 3) { Pattern = "MM/dd", Text = "10/03"},
new Data(1885, 10, 3) { Pattern = "MM/dd", Text = "10/03", Template = new LocalDate(1885, 10, 3) },
// When we parse in all of the below tests, we'll use the month and day-of-month if it's provided;
// the template value is specified to allow simple roundtripping. (Day of week doesn't affect what value is parsed; it just validates.)
// Non-genitive month name when there's no "day of month", even if there's a "day of week"
new Data(2011, 1, 3) { Pattern = "MMMM", Text = "FullNonGenName", Culture = Cultures.GenitiveNameTestCulture, Template = new LocalDate(2011, 5, 3)},
new Data(2011, 1, 3) { Pattern = "MMMM dddd", Text = "FullNonGenName Monday", Culture = Cultures.GenitiveNameTestCulture, Template = new LocalDate(2011, 5, 3) },
new Data(2011, 1, 3) { Pattern = "MMM", Text = "AbbrNonGenName", Culture = Cultures.GenitiveNameTestCulture, Template = new LocalDate(2011, 5, 3) },
new Data(2011, 1, 3) { Pattern = "MMM ddd", Text = "AbbrNonGenName Mon", Culture = Cultures.GenitiveNameTestCulture, Template = new LocalDate(2011, 5, 3) },
// Genitive month name when the pattern includes "day of month"
new Data(2011, 1, 3) { Pattern = "MMMM dd", Text = "FullGenName 03", Culture = Cultures.GenitiveNameTestCulture, Template = new LocalDate(2011, 5, 3) },
// TODO: Check whether or not this is actually appropriate
new Data(2011, 1, 3) { Pattern = "MMM dd", Text = "AbbrGenName 03", Culture = Cultures.GenitiveNameTestCulture, Template = new LocalDate(2011, 5, 3) },
// Era handling
new Data(2011, 1, 3) { Pattern = "yyyy MM dd gg", Text = "2011 01 03 A.D." },
new Data(2011, 1, 3) { Pattern = "uuuu yyyy MM dd gg", Text = "2011 2011 01 03 A.D." },
new Data(-1, 1, 3) { Pattern = "yyyy MM dd gg", Text = "0002 01 03 B.C." },
// Day of week handling
new Data(2011, 10, 9) { Pattern = "yyyy MM dd dddd", Text = "2011 10 09 Sunday" },
new Data(2011, 10, 9) { Pattern = "yyyy MM dd ddd", Text = "2011 10 09 Sun" },
// Month handling
new Data(2011, 10, 9) { Pattern = "yyyy MMMM dd", Text = "2011 October 09" },
new Data(2011, 10, 9) { Pattern = "yyyy MMM dd", Text = "2011 Oct 09" },
// Year and two-digit year-of-era in the same format. Note that the year
// gives the full year information, so we're not stuck in the 20th/21st century
new Data(1825, 10, 9) { Pattern = "uuuu yy MM/dd", Text = "1825 25 10/09" },
// Negative years
new Data(-43, 3, 15) { Pattern = "uuuu MM dd", Text = "-0043 03 15"},
// Calendar handling
new Data(2011, 10, 9) { Pattern = "c yyyy MM dd", Text = "ISO 2011 10 09" },
new Data(2011, 10, 9) { Pattern = "yyyy MM dd c", Text = "2011 10 09 ISO" },
new Data(2011, 10, 9, CalendarSystem.Coptic) { Pattern = "c uuuu MM dd", Text = "Coptic 2011 10 09" },
new Data(2011, 10, 9, CalendarSystem.Coptic) { Pattern = "uuuu MM dd c", Text = "2011 10 09 Coptic" },
new Data(180, 15, 19, CalendarSystem.Badi) { Pattern = "uuuu MM dd c", Text = "0180 15 19 Badi" },
// Awkward day-of-week handling
// December 14th 2012 was a Friday. Friday is "Foo" or "FooBar" in AwkwardDayOfWeekCulture.
new Data(2012, 12, 14) { Pattern = "ddd yyyy MM dd", Text = "Foo 2012 12 14", Culture = Cultures.AwkwardDayOfWeekCulture },
new Data(2012, 12, 14) { Pattern = "dddd yyyy MM dd", Text = "FooBar 2012 12 14", Culture = Cultures.AwkwardDayOfWeekCulture },
// December 13th 2012 was a Thursday. Friday is "FooBaz" or "FooBa" in AwkwardDayOfWeekCulture.
new Data(2012, 12, 13) { Pattern = "ddd yyyy MM dd", Text = "FooBaz 2012 12 13", Culture = Cultures.AwkwardDayOfWeekCulture },
new Data(2012, 12, 13) { Pattern = "dddd yyyy MM dd", Text = "FooBa 2012 12 13", Culture = Cultures.AwkwardDayOfWeekCulture },
// 3 digit year patterns (odd, but valid)
new Data(12, 1, 2) { Pattern = "uuu MM dd", Text = "012 01 02" },
new Data(-12, 1, 2) { Pattern = "uuu MM dd", Text = "-012 01 02" },
new Data(123, 1, 2) { Pattern = "uuu MM dd", Text = "123 01 02" },
new Data(-123, 1, 2) { Pattern = "uuu MM dd", Text = "-123 01 02" },
new Data(1234, 1, 2) { Pattern = "uuu MM dd", Text = "1234 01 02" },
new Data(-1234, 1, 2) { Pattern = "uuu MM dd", Text = "-1234 01 02" },
};
internal static IEnumerable<Data> ParseData = ParseOnlyData.Concat(FormatAndParseData);
internal static IEnumerable<Data> FormatData = FormatOnlyData.Concat(FormatAndParseData);
[Test]
[TestCaseSource(typeof(Cultures), nameof(Cultures.AllCultures))]
public void BclLongDatePatternGivesSameResultsInNoda(CultureInfo culture)
{
AssertBclNodaEquality(culture, culture.DateTimeFormat.LongDatePattern);
}
[Test]
[TestCaseSource(typeof(Cultures), nameof(Cultures.AllCultures))]
public void BclShortDatePatternGivesSameResultsInNoda(CultureInfo culture)
{
AssertBclNodaEquality(culture, culture.DateTimeFormat.ShortDatePattern);
}
[Test]
public void WithCalendar()
{
var pattern = LocalDatePattern.Iso.WithCalendar(CalendarSystem.Coptic);
var value = pattern.Parse("0284-08-29").Value;
Assert.AreEqual(new LocalDate(284, 8, 29, CalendarSystem.Coptic), value);
}
[Test]
public void CreateWithCurrentCulture()
{
var date = new LocalDate(2017, 8, 23);
using (CultureSaver.SetCultures(Cultures.FrFr))
{
var pattern = LocalDatePattern.CreateWithCurrentCulture("d");
Assert.AreEqual("23/08/2017", pattern.Format(date));
}
using (CultureSaver.SetCultures(Cultures.FrCa))
{
var pattern = LocalDatePattern.CreateWithCurrentCulture("d");
Assert.AreEqual("2017-08-23", pattern.Format(date));
}
}
[Test]
public void ParseNull() => AssertParseNull(LocalDatePattern.Iso);
private void AssertBclNodaEquality(CultureInfo culture, string patternText)
{
// The BCL never seems to use abbreviated month genitive names.
// I think it's reasonable that we do. Hmm.
// See https://github.com/nodatime/nodatime/issues/377
if (patternText.Contains("MMM") && !patternText.Contains("MMMM") &&
culture.DateTimeFormat.AbbreviatedMonthGenitiveNames[SampleLocalDate.Month - 1] != culture.DateTimeFormat.AbbreviatedMonthNames[SampleLocalDate.Month - 1])
{
return;
}
var pattern = LocalDatePattern.Create(patternText, culture);
var calendarSystem = BclCalendars.CalendarSystemForCalendar(culture.Calendar);
if (calendarSystem is null)
{
// We can't map this calendar system correctly yet; the test would be invalid.
return;
}
var sampleDateInCalendar = SampleLocalDate.WithCalendar(calendarSystem);
// To construct a DateTime, we need a time... let's give a non-midnight one to catch
// any unexpected uses of time within the date patterns.
DateTime sampleDateTime = (SampleLocalDate + new LocalTime(2, 3, 5)).ToDateTimeUnspecified();
Assert.AreEqual(sampleDateTime.ToString(patternText, culture), pattern.Format(sampleDateInCalendar));
}
public sealed class Data : PatternTestData<LocalDate>
{
// Default to the start of the year 2000.
protected override LocalDate DefaultTemplate => LocalDatePattern.DefaultTemplateValue;
/// <summary>
/// Initializes a new instance of the <see cref="Data" /> class.
/// </summary>
/// <param name="value">The value.</param>
public Data(LocalDate value) : base(value)
{
}
public Data(int year, int month, int day) : this(new LocalDate(year, month, day))
{
}
public Data(int year, int month, int day, CalendarSystem calendar)
: this(new LocalDate(year, month, day, calendar))
{
}
public Data() : this(LocalDatePattern.DefaultTemplateValue)
{
}
internal override IPattern<LocalDate> CreatePattern() =>
LocalDatePattern.CreateWithInvariantCulture(Pattern!)
.WithTemplateValue(Template)
.WithCulture(Culture);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="UndoableBase.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://www.lhotka.net/cslanet/
// </copyright>
// <summary>Implements n-level undo capabilities as</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.ComponentModel;
using Csla.Properties;
using Csla.Reflection;
using Csla.Serialization.Mobile;
using Csla.Serialization;
using System.Linq;
namespace Csla.Core
{
/// <summary>
/// Implements n-level undo capabilities as
/// described in Chapters 2 and 3.
/// </summary>
[Serializable()]
public abstract class UndoableBase : Csla.Core.BindableBase,
Csla.Core.IUndoableObject, IUseApplicationContext
{
// keep a stack of object state values.
[NotUndoable()]
private readonly Stack<byte[]> _stateStack = new();
[NotUndoable]
private bool _bindingEdit;
[NotUndoable]
private ApplicationContext _applicationContext;
ApplicationContext IUseApplicationContext.ApplicationContext { get => ApplicationContext; set => ApplicationContext = value; }
/// <summary>
/// Gets or sets a reference to the current ApplicationContext.
/// </summary>
protected ApplicationContext ApplicationContext
{
get => _applicationContext;
set
{
_applicationContext = value;
OnApplicationContextSet();
}
}
/// <summary>
/// Method invoked after ApplicationContext
/// is available.
/// </summary>
protected virtual void OnApplicationContextSet()
{ }
/// <summary>
/// Creates an instance of the type.
/// </summary>
protected UndoableBase()
{
}
/// <summary>
/// Gets or sets a value indicating whether n-level undo
/// was invoked through IEditableObject. FOR INTERNAL
/// CSLA .NET USE ONLY!
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
protected bool BindingEdit
{
get
{
return _bindingEdit;
}
set
{
_bindingEdit = value;
}
}
int IUndoableObject.EditLevel
{
get { return EditLevel; }
}
/// <summary>
/// Returns the current edit level of the object.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
protected int EditLevel
{
get { return _stateStack.Count; }
}
void IUndoableObject.CopyState(int parentEditLevel, bool parentBindingEdit)
{
if (!parentBindingEdit)
CopyState(parentEditLevel);
}
void IUndoableObject.UndoChanges(int parentEditLevel, bool parentBindingEdit)
{
if (!parentBindingEdit)
UndoChanges(parentEditLevel);
}
void IUndoableObject.AcceptChanges(int parentEditLevel, bool parentBindingEdit)
{
if (!parentBindingEdit)
AcceptChanges(parentEditLevel);
}
/// <summary>
/// This method is invoked before the CopyState
/// operation begins.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void CopyingState()
{
}
/// <summary>
/// This method is invoked after the CopyState
/// operation is complete.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void CopyStateComplete()
{
}
/// <summary>
/// Copies the state of the object and places the copy
/// onto the state stack.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
protected internal void CopyState(int parentEditLevel)
{
CopyingState();
Type currentType = this.GetType();
var state = new MobileDictionary<string, object>();
if (this.EditLevel + 1 > parentEditLevel)
throw new UndoException(string.Format(Resources.EditLevelMismatchException, "CopyState"), this.GetType().Name, null, this.EditLevel, parentEditLevel - 1);
do
{
var currentTypeName = currentType.FullName;
// get the list of fields in this type
List<DynamicMemberHandle> handlers =
UndoableHandler.GetCachedFieldHandlers(currentType);
foreach (var h in handlers)
{
var value = h.DynamicMemberGet(this);
var fieldName = GetFieldName(currentTypeName, h.MemberName);
if (typeof(IUndoableObject).IsAssignableFrom(h.MemberType))
{
if (value == null)
{
// variable has no value - store that fact
state.Add(fieldName, null);
}
else
{
// this is a child object, cascade the call
((IUndoableObject)value).CopyState(this.EditLevel + 1, BindingEdit);
}
}
else if (value is IMobileObject)
{
// this is a mobile object, store the serialized value
using MemoryStream buffer = new MemoryStream();
var formatter = SerializationFormatterFactory.GetFormatter(ApplicationContext);
formatter.Serialize(buffer, value);
state.Add(fieldName, buffer.ToArray());
}
else
{
// this is a normal field, simply trap the value
state.Add(fieldName, value);
}
}
currentType = currentType.BaseType;
} while (currentType != typeof(UndoableBase));
// serialize the state and stack it
using (MemoryStream buffer = new MemoryStream())
{
var formatter = SerializationFormatterFactory.GetFormatter(ApplicationContext);
formatter.Serialize(buffer, state);
_stateStack.Push(buffer.ToArray());
}
CopyStateComplete();
}
/// <summary>
/// This method is invoked before the UndoChanges
/// operation begins.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void UndoChangesComplete()
{
}
/// <summary>
/// This method is invoked after the UndoChanges
/// operation is complete.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void UndoingChanges()
{
}
/// <summary>
/// Restores the object's state to the most recently
/// copied values from the state stack.
/// </summary>
/// <remarks>
/// Restores the state of the object to its
/// previous value by taking the data out of
/// the stack and restoring it into the fields
/// of the object.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
protected internal void UndoChanges(int parentEditLevel)
{
UndoingChanges();
// if we are a child object we might be asked to
// undo below the level of stacked states,
// so just do nothing in that case
if (EditLevel > 0)
{
if (this.EditLevel - 1 != parentEditLevel)
throw new UndoException(string.Format(Resources.EditLevelMismatchException, "UndoChanges"), this.GetType().Name, null, this.EditLevel, parentEditLevel + 1);
MobileDictionary<string, object> state;
using (MemoryStream buffer = new MemoryStream(_stateStack.Pop()))
{
buffer.Position = 0;
var formatter = SerializationFormatterFactory.GetFormatter(ApplicationContext);
state = (MobileDictionary<string, object>)formatter.Deserialize(buffer);
}
Type currentType = this.GetType();
do
{
var currentTypeName = currentType.FullName;
// get the list of fields in this type
List<DynamicMemberHandle> handlers = UndoableHandler.GetCachedFieldHandlers(currentType);
foreach (var h in handlers)
{
// the field is undoable, so restore its value
var value = h.DynamicMemberGet(this);
var fieldName = GetFieldName(currentTypeName, h.MemberName);
if (typeof(IUndoableObject).IsAssignableFrom(h.MemberType))
{
// this is a child object
// see if the previous value was empty
//if (state.Contains(h.MemberName))
if (state.Contains(fieldName))
{
// previous value was empty - restore to empty
h.DynamicMemberSet(this, null);
}
else
{
// make sure the variable has a value
if (value != null)
{
// this is a child object, cascade the call.
((IUndoableObject)value).UndoChanges(this.EditLevel, BindingEdit);
}
}
}
else if (value is IMobileObject && state[fieldName] != null)
{
// this is a mobile object, deserialize the value
using MemoryStream buffer = new MemoryStream((byte[])state[fieldName]);
buffer.Position = 0;
var formatter = SerializationFormatterFactory.GetFormatter(ApplicationContext);
var obj = formatter.Deserialize(buffer);
h.DynamicMemberSet(this, obj);
}
else
{
// this is a regular field, restore its value
h.DynamicMemberSet(this, state[fieldName]);
}
}
currentType = currentType.BaseType;
} while (currentType != typeof(UndoableBase));
}
UndoChangesComplete();
}
/// <summary>
/// This method is invoked before the AcceptChanges
/// operation begins.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void AcceptingChanges()
{
}
/// <summary>
/// This method is invoked after the AcceptChanges
/// operation is complete.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void AcceptChangesComplete()
{
}
/// <summary>
/// Accepts any changes made to the object since the last
/// state copy was made.
/// </summary>
/// <remarks>
/// The most recent state copy is removed from the state
/// stack and discarded, thus committing any changes made
/// to the object's state.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
protected internal void AcceptChanges(int parentEditLevel)
{
AcceptingChanges();
if (this.EditLevel - 1 != parentEditLevel)
throw new UndoException(string.Format(Resources.EditLevelMismatchException, "AcceptChanges"), this.GetType().Name, null, this.EditLevel, parentEditLevel + 1);
if (EditLevel > 0)
{
_stateStack.Pop();
Type currentType = this.GetType();
do
{
// get the list of fields in this type
List<DynamicMemberHandle> handlers = UndoableHandler.GetCachedFieldHandlers(currentType);
foreach (var h in handlers)
{
// the field is undoable so see if it is a child object
if (typeof(Csla.Core.IUndoableObject).IsAssignableFrom(h.MemberType))
{
object value = h.DynamicMemberGet(this);
// make sure the variable has a value
if (value != null)
{
// it is a child object so cascade the call
((Core.IUndoableObject)value).AcceptChanges(this.EditLevel, BindingEdit);
}
}
}
currentType = currentType.BaseType;
} while (currentType != typeof(UndoableBase));
}
AcceptChangesComplete();
}
/// <summary>
/// Returns the full name of a field, including
/// the containing type name.
/// </summary>
/// <param name="typeName">Name of the containing type.</param>
/// <param name="memberName">Name of the member (field).</param>
private static string GetFieldName(string typeName, string memberName)
{
return typeName + "." + memberName;
}
internal static void ResetChildEditLevel(IUndoableObject child, int parentEditLevel, bool bindingEdit)
{
int targetLevel = parentEditLevel;
if (bindingEdit && targetLevel > 0 && child is not FieldManager.FieldDataManager)
targetLevel--;
// if item's edit level is too high,
// reduce it to match list
while (child.EditLevel > targetLevel)
child.AcceptChanges(targetLevel, false);
// if item's edit level is too low,
// increase it to match list
while (child.EditLevel < targetLevel)
child.CopyState(targetLevel, false);
}
/// <summary>
/// Override this method to insert your field values
/// into the MobileFormatter serialzation stream.
/// </summary>
/// <param name="info">
/// Object containing the data to serialize.
/// </param>
/// <param name="mode">
/// The StateMode indicating why this method was invoked.
/// </param>
protected override void OnGetState(SerializationInfo info, StateMode mode)
{
if (mode != StateMode.Undo)
{
info.AddValue("_bindingEdit", _bindingEdit);
if (_stateStack.Count > 0)
{
var stackArray = _stateStack.ToArray();
info.AddValue("_stateStack", stackArray);
}
}
base.OnGetState(info, mode);
}
/// <summary>
/// Override this method to retrieve your field values
/// from the MobileFormatter serialzation stream.
/// </summary>
/// <param name="info">
/// Object containing the data to serialize.
/// </param>
/// <param name="mode">
/// The StateMode indicating why this method was invoked.
/// </param>
protected override void OnSetState(SerializationInfo info, StateMode mode)
{
if (mode != StateMode.Undo)
{
_bindingEdit = info.GetValue<bool>("_bindingEdit");
if (info.Values.ContainsKey("_stateStack"))
{
var stackArray = info.GetValue<byte[][]>("_stateStack");
_stateStack.Clear();
foreach (var item in stackArray.Reverse())
_stateStack.Push(item);
}
}
base.OnSetState(info, mode);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using BackwardCompatibilityChecker.Introspection.Diff;
using Mono.Cecil;
using Mono.Collections.Generic;
namespace BackwardCompatibilityChecker.Introspection.Types
{
public static class Extensions
{
public static TypeDiff GetTypeByName(this HashSet<TypeDiff> set, string typeName)
{
TypeDiff lret = null;
foreach (TypeDiff type in set)
{
if (String.CompareOrdinal(type.ToString(), typeName) == 0)
{
lret = type;
break;
}
}
return lret;
}
public static FieldDefinition GetFieldByeName(this List<FieldDefinition> list, string fieldName)
{
return GetFieldByNameAndType(list, fieldName, null);
}
public static FieldDefinition GetFieldByNameAndType(this List<FieldDefinition> list, string fieldName, string fieldType)
{
FieldDefinition lret = null;
foreach (var field in list)
{
if (String.CompareOrdinal(field.Name, fieldName) == 0 )
{
if (!String.IsNullOrEmpty(fieldType) )
{
if (field.FieldType != null &&
field.FieldType.FullName == fieldType)
{
lret = field;
break;
}
}
else
{
lret = field;
break;
}
}
}
return lret;
}
public static EventDefinition GetEventByName(this List<EventDefinition> list, string evName)
{
return GetEventByNameAndType(list, evName, null);
}
public static EventDefinition GetEventByNameAndType(this List<EventDefinition> list, string evName, string type)
{
EventDefinition lret = null;
foreach (var ev in list)
{
if (ev.Name == evName)
{
if (type == null)
{
lret = ev;
}
else
{
lret = (ev.EventType.FullName == type) ? ev : null;
}
break;
}
}
return lret;
}
static void AddVisibility(StringBuilder sb, bool isPublic, bool isPrivate, bool isFamily, bool isAssembly, bool isProtectedInternal)
{
if (isPublic)
sb.Append("public ");
if (isPrivate)
sb.Append("private ");
if (isFamily)
sb.Append("protected ");
if (isAssembly)
sb.Append("internal ");
if (isProtectedInternal)
sb.Append("protected internal ");
}
public static string Print(this EventDefinition ev)
{
var sb = new StringBuilder();
MethodDefinition evMethod = ev.AddMethod;
AddVisibility(sb, evMethod.IsPublic, evMethod.IsPrivate, evMethod.IsFamily, evMethod.IsAssembly, evMethod.IsFamilyOrAssembly);
if (evMethod.IsVirtual)
sb.AppendFormat("{0} ", "virtual");
if (evMethod.IsStatic)
sb.AppendFormat("{0} ", "static");
sb.Append("event ");
string typeName;
if (ev.EventType is GenericInstanceType)
{
var genFieldType = (GenericInstanceType)ev.EventType;
var typeSb = new StringBuilder();
sb.Append(genFieldType.Name.Split(new[] { '`' })[0]);
PrintGenericArgumentCollection(typeSb, genFieldType.GenericArguments);
typeName = typeSb.ToString();
}
else
{
typeName = ev.EventType.FullName;
typeName = TypeMapper.FullToShort(typeName);
}
sb.Append(typeName);
sb.Append(" ");
sb.Append(ev.Name);
return sb.ToString();
}
public static string Print(this FieldDefinition field, FieldPrintOptions options)
{
var sb = new StringBuilder();
if( (options & FieldPrintOptions.Visibility ) == FieldPrintOptions.Visibility )
{
AddVisibility(sb, field.IsPublic, field.IsPrivate, field.IsFamily, field.IsAssembly, field.IsFamilyOrAssembly);
}
if( (options & FieldPrintOptions.Modifiers ) == FieldPrintOptions.Modifiers )
{
if (field.IsStatic && !field.HasConstant )
{
sb.Append("static ");
}
if (field.IsInitOnly)
{
sb.Append("readonly ");
}
if (field.HasConstant)
{
sb.Append("const ");
}
}
string typeName = "";
if( (options & FieldPrintOptions.SimpleType) == FieldPrintOptions.SimpleType )
{
var genType = field.FieldType as GenericInstanceType;
if (genType != null)
{
typeName = genType.Print();
}
else
{
typeName = field.FieldType.FullName;
typeName = TypeMapper.FullToShort(typeName);
}
}
sb.Append(typeName);
sb.AppendFormat(" {0}", field.Name);
if( ((options & FieldPrintOptions.Value) == FieldPrintOptions.Value) &&
field.HasConstant )
{
sb.AppendFormat(" - Value: {0}", field.Constant);
}
return sb.ToString();
}
static readonly char[] myGenericParamSep = { '`' };
static string RemoveGenericParameterCountFromName(string name)
{
return name.Split(myGenericParamSep)[0];
}
public static string Print(this GenericInstanceType type)
{
var sb = new StringBuilder();
sb.Append(RemoveGenericParameterCountFromName(type.Name));
PrintGenericArgumentCollection(sb, type.GenericArguments);
return sb.ToString();
}
public static string Print(this TypeDefinition type)
{
var sb = new StringBuilder();
if (type.IsPublic)
{
sb.Append("public ");
}
else
{
sb.Append("internal ");
}
if (type.IsInterface)
{
sb.Append("interface ");
}
else if (type.IsEnum)
{
sb.Append("enum ");
}
else if (type.IsValueType)
{
sb.Append("struct ");
}
else
{
sb.Append("class ");
}
if (type.DeclaringType != null)
{
sb.AppendFormat("{0}/", type.DeclaringType.FullName);
}
else
{
sb.Append(type.Namespace);
sb.Append(".");
}
sb.Append(type.Name.Split(new[] { '`' })[0]);
PrintGenericParameterCollection(sb, type.GenericParameters);
return sb.ToString();
}
/// <summary>
/// A type reference to a generic contains the concrete types to fully declare it.
/// Like List<string> where string is an argument to the generic type.
/// </summary>
/// <param name="sb"></param>
/// <param name="coll"></param>
static void PrintGenericArgumentCollection(StringBuilder sb, Collection<TypeReference> coll)
{
if (coll == null || coll.Count == 0)
return;
sb.Append("<");
for (int i = 0; i < coll.Count; i++)
{
TypeReference param = coll[i];
var generic = param as GenericInstanceType;
if (generic != null )
{
sb.Append(RemoveGenericParameterCountFromName(generic.Name));
PrintGenericArgumentCollection(sb, generic.GenericArguments);
}
else
{
sb.Append(TypeMapper.FullToShort(param.Name));
// Print recursive definition
if (i != coll.Count - 1)
{
sb.Append(",");
}
}
}
sb.Append(">");
}
/// <summary>
/// A type definition can contain generic parameters which are printed out here
/// </summary>
/// <param name="sb"></param>
/// <param name="coll"></param>
static void PrintGenericParameterCollection(StringBuilder sb, Collection<GenericParameter> coll)
{
if (coll == null || coll.Count == 0)
{
return;
}
sb.Append("<");
for (int i = 0; i < coll.Count; i++)
{
GenericParameter param = coll[i];
sb.Append(TypeMapper.FullToShort(param.Name));
// Print recursive definition
PrintGenericParameterCollection(sb, param.GenericParameters);
if (i != coll.Count - 1)
{
sb.Append(",");
}
}
sb.Append(">");
}
public static string Print(this MethodReference method, MethodPrintOption options)
{
var sb = new StringBuilder();
sb.AppendFormat("{0} {1} {2}",
method.DeclaringType.FullName,
method.MethodReturnType.ReturnType.Name,
method.Name);
PrintParameters(method.Parameters, sb, options);
return sb.ToString();
}
static void PrintParameters(Collection<ParameterDefinition> parameters, StringBuilder sb, MethodPrintOption options)
{
bool bPrintNames = ((options & MethodPrintOption.ParamNames) == MethodPrintOption.ParamNames);
sb.Append("(");
for (int i = 0; i < parameters.Count; i++)
{
ParameterDefinition parameter = parameters[i];
if (parameter.IsOut)
sb.Append("out ");
string paramType = null;
var generic = parameter.ParameterType as GenericInstanceType;
if (generic != null)
paramType = generic.Print();
if (paramType == null)
{
paramType = parameter.ParameterType.Name;
}
// Ref types seem not to be correctly parsed by mono cecil so we leave the & syntax
// inside it for the time beeing.
if (parameter.IsOut)
{
paramType = paramType.TrimEnd(new[] { '&' });
}
sb.Append(paramType);
if (bPrintNames)
{
sb.AppendFormat(" {0}", parameter.Name);
}
// parameter.Name
if (i != parameters.Count - 1)
{
sb.Append(",");
}
}
sb.Append(")");
}
public static string Print(this MethodDefinition method, MethodPrintOption options)
{
var sb = new StringBuilder();
bool bPrintAlias = ( (MethodPrintOption.ShortNames & MethodPrintOption.ShortNames) == MethodPrintOption.ShortNames);
if ((MethodPrintOption.Visiblity & options) == MethodPrintOption.Visiblity)
{
AddVisibility(sb, method.IsPublic, method.IsPrivate, method.IsFamily, method.IsAssembly, method.IsFamilyOrAssembly);
}
if( (MethodPrintOption.Modifier & options) == MethodPrintOption.Modifier)
{
if( method.IsVirtual && method.HasBody)
sb.AppendFormat("{0} ", "virtual");
if (method.IsStatic)
sb.AppendFormat("{0} ", "static");
}
if( (MethodPrintOption.ReturnType & options) == MethodPrintOption.ReturnType)
{
string retType = null;
if (bPrintAlias)
{
var generic = method.MethodReturnType.ReturnType as GenericInstanceType;
if (generic != null)
retType = generic.Print();
}
if( retType == null )
retType = TypeMapper.FullToShort(method.MethodReturnType.ReturnType.FullName);
sb.AppendFormat("{0} ", retType);
}
sb.Append(method.Name);
if( (options & MethodPrintOption.Parameters) == MethodPrintOption.Parameters )
{
PrintParameters(method.Parameters, sb, options);
}
return sb.ToString();
}
/// <summary>
/// Compares two TypeReferences by its Full Name and declaring assembly
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <returns>
/// <c>true</c> if the specified x is equal; otherwise, <c>false</c>.
/// </returns>
public static bool IsEqual(this TypeDefinition x, TypeDefinition y)
{
if (x == null && y == null)
return true;
if( (x == null) || (y == null) )
{
return false;
}
return x.FullName == y.FullName &&
x.Scope.IsEqual(y.Scope);
}
/*
static bool Contains(this InterfaceCollection interfaces, TypeReference itfTypeRef)
{
foreach (TypeReference typeRef in interfaces)
{
if (typeRef.IsEqual(itfTypeRef))
return true;
}
return false;
}
*/
/// <summary>
/// Check if two methods are equal with respect to name, return type, visibility and method modifiers.
/// </summary>
/// <param name="m1">The m1.</param>
/// <param name="m2">The m2.</param>
/// <returns></returns>
public static bool IsEqual(this MethodDefinition m1, MethodDefinition m2)
{
bool lret = false;
// check if function name, modifiers and paramters are still equal
if ( m1 != null &&
m1.Name == m2.Name &&
m1.MethodReturnType.ReturnType.FullName == m2.MethodReturnType.ReturnType.FullName &&
m1.Parameters.Count == m2.Parameters.Count &&
m1.IsPrivate == m2.IsPrivate &&
m1.IsPublic == m2.IsPublic &&
m1.IsFamily == m2.IsFamily &&
m1.IsAssembly == m2.IsAssembly &&
m1.IsFamilyOrAssembly == m2.IsFamilyOrAssembly &&
m1.IsVirtual == m2.IsVirtual &&
m1.IsStatic == m2.IsStatic &&
m1.GenericParameters.Count == m2.GenericParameters.Count
)
{
bool bParameterEqual = true;
// Check function parameter types if there has been any change
for (int i = 0; i < m1.Parameters.Count; i++)
{
ParameterDefinition pa = m1.Parameters[i];
ParameterDefinition pb = m2.Parameters[i];
if (pa.ParameterType.FullName != pb.ParameterType.FullName)
{
bParameterEqual = false;
}
}
lret = bParameterEqual;
}
return lret;
}
public static bool IsEqual(this EventDefinition e1, EventDefinition e2)
{
return e1.Name == e2.Name &&
e1.EventType.FullName == e2.EventType.FullName &&
e1.AddMethod.IsEqual(e2.AddMethod);
}
public static bool IsEqual(this MethodReference x, MethodReference y)
{
return x.IsEqual(y, true);
}
public static bool IsEqual(this MethodReference x, MethodReference y, bool bCompareGenericParameters)
{
if (x == null && y == null)
return true;
if( (x == null) || (y == null) )
{
return false;
}
bool lret = false;
if (x.Name == y.Name &&
x.DeclaringType.GetElementType().IsEqual(y.DeclaringType.GetElementType(), bCompareGenericParameters) &&
x.MethodReturnType.ReturnType.IsEqual(y.MethodReturnType.ReturnType, bCompareGenericParameters) &&
x.Parameters.IsEqual(y.Parameters, bCompareGenericParameters))
{
if (bCompareGenericParameters)
lret = x.GenericParameters.IsEqual(y.GenericParameters);
else
lret = true;
}
return lret;
}
public static bool IsEqual(this Collection<ParameterDefinition> x, Collection<ParameterDefinition> y)
{
return x.IsEqual(y, true);
}
public static bool IsEqual(this Collection<ParameterDefinition> x, Collection<ParameterDefinition> y, bool bCompareGenericParameters)
{
if (x == null && y == null)
return true;
if ((x == null) || (y == null))
{
return false;
}
if (x.Count != y.Count)
return false;
for (int i = 0; i < x.Count; i++)
{
ParameterDefinition p1 = x[i];
ParameterDefinition p2 = y[i];
if (!p1.ParameterType.IsEqual(p2.ParameterType, bCompareGenericParameters))
{
return false;
}
// There seems to be a bug in mono cecil. MethodReferences do not
// contain the IsIn/IsOut property data we would need to check if both methods
// have the same In/Out signature for this parameter.
if( p1.MetadataToken.RID == p2.MetadataToken.RID )
{
if( (p1.IsIn != p2.IsIn) || (p1.IsOut != p2.IsOut) )
{
return false;
}
}
}
return true;
}
static string ExractAssemblyNameFromScope(IMetadataScope x)
{
var aRef = x as AssemblyNameReference;
if (aRef != null)
return aRef.Name;
var aDef = x as AssemblyNameDefinition;
if( aDef != null )
return aDef.Name;
var aMod = x as ModuleDefinition;
if (aMod != null)
return aMod.Assembly.Name.Name;
// normally the module name has the dll name but
// this is not the case for mscorlib where CommonLanguageRuntime is inside it
var aModRef = x as ModuleReference;
if (aModRef != null)
return Path.GetFileNameWithoutExtension(aModRef.Name);
return x.Name;
}
public static bool IsEqual(this IMetadataScope x, IMetadataScope y)
{
if (x == null && y == null)
return true;
if ((x == null) || (y == null))
{
return false;
}
string xName = ExractAssemblyNameFromScope(x);
string yName = ExractAssemblyNameFromScope(y);
return xName == yName;
}
public static bool IsEqual(this TypeReference x, TypeReference y)
{
bool lret = x.IsEqual(y,true);
return lret;
}
public static bool IsEqual(this GenericInstanceType x, GenericInstanceType y)
{
if (x == null && y == null)
{
return true;
}
if ((x == null) || (y == null))
{
return false;
}
return x.GenericArguments.IsEqual(y.GenericArguments);
}
/// <summary>
/// Type names for generic in class instantiations beginn with ! to denote the number of
/// the generic argument of the enclosing class.
/// System.Collections.Generic.KeyValuePair`2<int32,float32>::.ctor(!0,!1)
/// where !0 and !1 are the position number of the generic type.
/// Method references to generic functions specify the type reference by two !! to number them
/// e.g. !!0 !!1
/// </summary>
/// <param name="n1"></param>
/// <param name="n2"></param>
/// <returns></returns>
static bool AreTypeNamesEqual(string n1, string n2)
{
if( n1 == n2 )
return true;
if( n1[0] == '!' ||
n2[0] == '!' )
return true;
return false;
}
public static void IsNotNull(this object value, Action acc)
{
if( value != null )
{
acc();
}
}
public static T IsNotNull<T>(this object value, Func<T> acc) where T : class
{
if (value != null)
{
return acc();
}
return null;
}
public static bool IsEqual(this TypeReference x, TypeReference y, bool bCompareGenericParameters)
{
if (x == null && y == null)
return true;
if (x == null || y == null)
{
return false;
}
bool lret = false;
TypeReference xDeclaring = x.DeclaringType;
TypeReference yDeclaring = y.DeclaringType;
xDeclaring.IsNotNull(() => xDeclaring = x.DeclaringType.GetElementType());
yDeclaring.IsNotNull(() => yDeclaring = y.DeclaringType.GetElementType());
// Generic parameters are passed as placeholder via method reference
// newobj instance void class [BaseLibraryV1]BaseLibrary.ApiChanges.PublicGenericClass`1<string>::.ctor(class [System.Core]System.Func`1<!0>)
if (AreTypeNamesEqual(x.Name,y.Name) &&
x.Namespace == y.Namespace &&
IsEqual(xDeclaring, yDeclaring, bCompareGenericParameters) &&
x.Scope.IsEqual(y.Scope) )
{
if (bCompareGenericParameters)
{
lret = x.GenericParameters.IsEqual(y.GenericParameters);
}
else
{
lret = true;
}
}
if (lret)
{
// Generics can have
var xGen = x as GenericInstanceType;
var yGen = y as GenericInstanceType;
if (xGen != null && yGen != null)
{
lret = xGen.IsEqual(yGen);
}
}
return lret;
}
public static bool IsEqual(this FieldDefinition f1, FieldDefinition f2)
{
return f1 != null &&
f1.IsPublic == f2.IsPublic &&
f1.IsFamilyOrAssembly == f2.IsFamilyOrAssembly &&
f1.IsFamily == f2.IsFamily &&
f1.IsAssembly == f2.IsAssembly &&
f1.IsPrivate == f2.IsPrivate &&
f1.IsStatic == f2.IsStatic &&
((f1.HasConstant && f2.HasConstant && f1.Constant == f2.Constant) || (!f1.HasConstant && !f2.HasConstant)) &&
f1.IsInitOnly == f2.IsInitOnly &&
f1.Name == f2.Name &&
f1.FieldType.FullName == f2.FieldType.FullName;
}
public static bool IsEqual(this Collection<TypeReference> genArgs1, Collection<TypeReference> genArgs2)
{
if (genArgs1 == null && genArgs2 == null)
{
return true;
}
if ((genArgs1 == null) || (genArgs2 == null))
{
return false;
}
if (genArgs1.Count != genArgs2.Count)
return false;
for (int i = 0; i < genArgs1.Count; i++)
{
TypeReference type1 = genArgs1[i];
TypeReference type2 = genArgs2[i];
if (!type1.IsEqual(type2))
{
return false;
}
}
return true;
}
public static bool IsEqual(this Collection<GenericParameter> collection1, Collection<GenericParameter> collection2)
{
if (collection1 == null && collection2 == null)
return true;
if( (collection1 == null) || (collection2 == null))
return false;
if( collection1.Count != collection2.Count )
return false;
bool lret = true;
for(int i=0;i<collection1.Count;i++)
{
GenericParameter param1 = collection1[i];
GenericParameter param2 = collection2[i];
if (param1.FullName != param2.FullName)
{
lret = false;
break;
}
}
return lret;
}
}
}
| |
// Copyright 2010 xUnit.BDDExtensions
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using Xunit.Internal;
namespace Xunit.Specs
{
public class Given_an_expression_which_points_to_a_controller_action_returning_an_action_result_when_trying_to_extract_the_name : ConcernOfMvcExpressionHelper
{
private string _result;
protected override void Because()
{
_result = MvcExpressionHelper.GetMemberName(GetExpression<TestClass, ActionResult>(c => c.Index()));
}
[Observation]
public void Should_be_able_to_extract_the_name_of_the_controller_action()
{
_result.ShouldBeEqualTo("Index");
}
}
public class Given_an_expression_which_points_to_a_parameterized_controller_action_returning_an_action_result_when_trying_to_extract_the_name : ConcernOfMvcExpressionHelper
{
private string _result;
protected override void Because()
{
_result = MvcExpressionHelper.GetMemberName(GetExpression<TestClass, ActionResult>(c => c.Index(3, 2, 1)));
}
[Observation]
public void Should_be_able_to_extract_the_name_of_the_controller_action()
{
_result.ShouldBeEqualTo("Index");
}
}
public class Given_an_expression_which_points_to_a_controller_comand_when_trying_to_extract_the_name : ConcernOfMvcExpressionHelper
{
private string _result;
protected override void Because()
{
_result = MvcExpressionHelper.GetMemberName(GetExpression<TestClass>(c => c.Create()));
}
[Observation]
public void Should_be_able_to_extract_the_name_of_the_controller_action()
{
_result.ShouldBeEqualTo("Create");
}
}
public class Given_an_expression_which_points_to_parameterized_controller_action_when_trying_to_extract_the_parameter_names : ConcernOfMvcExpressionHelper
{
private string[] _result;
protected override void Because()
{
_result = MvcExpressionHelper.GetParameterNames(GetExpression<TestClass, ActionResult>(c => c.Index(3, 2, 1)));
}
[Observation]
public void Should_be_able_to_extract_the_parameter_names_in_the_correct_order()
{
_result.ShouldOnlyContainInOrder("a", "b", "c");
}
}
public class Given_an_expression_which_points_to_a_controller_command_when_trying_to_extract_the_parameter_names : ConcernOfMvcExpressionHelper
{
private string[] _result;
protected override void Because()
{
_result = MvcExpressionHelper.GetParameterNames(GetExpression<TestClass, ActionResult>(c => c.Index()));
}
[Observation]
public void Should_return_an_empty_array()
{
_result.ShouldBeEmpty();
}
}
public class Given_an_expression_which_points_to_parameterized_controller_action_when_trying_to_extract_the_parameter_values : ConcernOfMvcExpressionHelper
{
private string[] _parameterNames;
private IEnumerable<object> _parameterValues;
protected override void EstablishContext()
{
_parameterNames = new[] { "a", "b", "c" };
}
protected override void Because()
{
_parameterValues = _parameterNames.Select(parameterName =>
MvcExpressionHelper.GetParameterValue(GetExpression<TestClass, ActionResult>(c => c.Index(3, 2, 1)),
parameterName));
}
[Observation]
public void Should_be_able_to_extract_each_parameter_value()
{
_parameterValues.ShouldOnlyContainInOrder(3,2,1);
}
}
public class Given_an_expression_which_points_to_controller_action_with_a_date_time_parameter_when_trying_to_extract_the_parameter_value : ConcernOfMvcExpressionHelper
{
private object _result1;
protected override void Because()
{
_result1 = MvcExpressionHelper.GetParameterValue(
GetExpression<TestClass>(c => c.Date(new DateTime(2010, 07, 05))),
"dateTime");
}
[Observation]
public void Should_be_able_to_extract_the_correct_date()
{
_result1.ShouldBeEqualTo(new DateTime(2010, 7, 5));
}
}
public class Given_an_expression_which_points_to_controller_action_with_parameters_of_a_reference_type_when_trying_to_extract_the_parameter_values : ConcernOfMvcExpressionHelper
{
private string[] _parameterNames;
private IEnumerable<object> _extractedParameters;
private TestClass _instance1;
private TestClass _instance2;
protected override void EstablishContext()
{
_instance1 = new TestClass {Vorname = "Eins", Nachname = "Zwei"};
_instance2 = new TestClass {Vorname = "Drei", Nachname = "Vier"};
_parameterNames = new[]
{
"param1",
"param2"
};
}
protected override void Because()
{
_extractedParameters = _parameterNames.Select(parameterName =>
MvcExpressionHelper.GetParameterValue(
GetExpression<TestClass>(c => c.Person(_instance1, _instance2)),
parameterName));
}
[Observation]
public void Should_able_to_extract_the_parameter_values()
{
_extractedParameters.ShouldOnlyContain(_instance1, _instance2);
}
}
[Concern(typeof (MvcExpressionHelper))]
public abstract class ConcernOfMvcExpressionHelper : StaticContextSpecification
{
protected static Expression GetExpression<T, TResult>(Expression<Func<T, TResult>> expression)
{
return expression;
}
protected static Expression GetExpression<T>(Expression<Action<T>> expression)
{
return expression;
}
}
internal class TestClass
{
public ActionResult Index()
{
throw new NotImplementedException();
}
public ActionResult Index(int a, int b, int c)
{
throw new NotImplementedException();
}
public void Create()
{
throw new NotImplementedException();
}
public void Date(DateTime dateTime)
{
throw new NotImplementedException();
}
public void Person(TestClass param1, TestClass param2)
{
throw new NotImplementedException();
}
public string Vorname { get; set; }
public string Nachname { get; set; }
}
}
| |
//---------------------------------------------------------------------
// This file is part of the CLR Managed Debugger (mdbg) Sample.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Part of managed wrappers for native debugging APIs.
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using Microsoft.Samples.Debugging.Native;
using Microsoft.Samples.Debugging.Native.Private;
namespace Microsoft.Samples.Debugging.Native
{
/// <summary>
/// Local Native Process being debugged
/// </summary>
public class NativeDbgProcess : IMemoryReader, IDisposable
{
#region Lifetime
internal NativeDbgProcess(int id)
{
m_id = id;
}
/// <summary>
/// Finalizer for NativeDbgProcess
/// </summary>
~NativeDbgProcess()
{
Dispose(false);
}
/// <summary>
/// Implementation of IDisposable.Dispose
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose worker
/// </summary>
/// <param name="disposing">true if releasing managed resources</param>
protected virtual void Dispose(bool disposing)
{
// if disposing == false, only cleanup native resources
// else clean up both managed + native resources.
//
// Native resources
//
if (m_handle != IntPtr.Zero)
{
NativeMethods.CloseHandle(m_handle);
m_handle = IntPtr.Zero;
}
if (disposing)
{
// remove all remaining modules
foreach (NativeDbgModule module in this.m_modules.Values)
{
module.CloseHandle();
}
m_modules.Clear();
}
}
#endregion Lifetime
int m_id;
/// <summary>
/// OS Process ID (pid)
/// </summary>
public int Id
{
get { return m_id; }
}
#region Process handle
/// <summary>
/// Post a request for the process terminate.
/// </summary>
/// <param name="exitCode">exit code to supply</param>
/// <remarks>
/// Terminate only posts a request to terminate. It makes no gaurantees when the process actually
/// terminates (or even that the termination actually succeed)
/// The debugger must still pump debug events even after Terminate is called.
/// Additional debug events may still be sent. This commonly includes Exit Thread events and
/// eventually an ExitProcess event.
/// It may include other events too. For example, on WinXp, if Terminate
/// is called at the CreateProcess event, the load dll event for ntdll is still dispatched.
/// </remarks>
public void TerminateProcess(int exitCode)
{
// Since process can exit asynchrously, it may already have exited when we called this.
// Ignore failures.
NativeMethods.TerminateProcess(m_handle, unchecked((uint)exitCode));
}
/// <summary>
/// Break into the debuggee.
/// </summary>
/// <remarks>This causes the debuggee to fire a debug event which the debugger will
/// then pickup via WaitForDebugEvent.</remarks>
public void Break()
{
bool fOk = NativeMethods.DebugBreakProcess(m_handle);
if (!fOk)
{
throw new InvalidOperationException("DebugBreak failed.");
}
}
/// <summary>
/// Determine if the process has really exited, by checking the process handle.
/// </summary>
/// <returns>true if process handle is signaled, else false</returns>
public bool IsExited()
{
// If process handle is nulled out, then it's exited.
if (m_handle == IntPtr.Zero)
{
return true;
}
// If the process handle is signaled, then the process has exited.
int ret = NativeMethods.WaitForSingleObject(m_handle, 0);
if (ret == 0) // WAIT_OBJECT_0
{
return true;
}
return false;
}
// We don't own this handle. We get it from CreateProcess debug event,
// and continuing ExitProcess debug event will call CloseHandle() on it.
// If the ExitProcess debug event is never called, then we'll Dispose it.
IntPtr m_handle;
// Expose the handle internally so that other things in the NativeDbgProcess tree can access it
// to use with the native win32 APIs.
internal IntPtr Handle
{
get { return m_handle; }
}
/// <summary>
/// Expose the raw handle. This is a dangerous this to do.
/// </summary>
public IntPtr UnsafeHandle
{
get { return m_handle; }
}
/// <summary>
/// Initialize handle to this process. This can be set during a CreateProcess debug event.
/// This object then gets ownership and must close it.
/// </summary>
/// <param name="handle">handle to process</param>
public void InitHandle(IntPtr handle)
{
m_handle = handle;
}
/// <summary>
/// Called when handling ExitProcess debug event. This does not CloseHandle()
/// </summary>
public void ClearHandle()
{
// ContinueDebugEvent on ExitProcess debug event will release this handle.
m_handle = IntPtr.Zero;
}
#endregion // Process handle
/// <summary>
/// Implement IMemoryReader.ReadMemory
/// </summary>
public void ReadMemory(IntPtr address, byte[] buffer)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
int lenRead;
UIntPtr len = new UIntPtr((uint)buffer.Length);
bool fReadOk = NativeMethods.ReadProcessMemory(m_handle, address, buffer, len, out lenRead);
if (!fReadOk || (lenRead != buffer.Length))
{
//throw new ReadMemoryFailureException(address, buffer.Length);
}
}
#region Loader Breakpoint
/// <summary>
/// Check if the event is the Loader Breakpoint, and if so, deal with it.
/// </summary>
/// <param name="nativeEvent">event</param>
/// <remarks>Loader breakpoint is generally the first breakpoint event</remarks>
public void HandleIfLoaderBreakpoint(NativeEvent nativeEvent, ref bool loaderBreakpointReceived)
{
// If it's already handled, nothing left to do
if (loaderBreakpointReceived)
{
return;
}
// On x86, x64, we can just clear the exception.
// This is even more complex on IA64, we have to actually skip it. IA64 is not yet implemented.
// Loader Breakpoint is an exception event
ExceptionNativeEvent e = nativeEvent as ExceptionNativeEvent;
if (e == null)
{
return;
}
// and it's a breakpoint
if (e.ExceptionCode != ExceptionCode.STATUS_BREAKPOINT)
{
return;
}
e.ContinueStatus = NativeMethods.ContinueStatus.DBG_CONTINUE;
loaderBreakpointReceived = true;
return;
}
bool m_fLoaderBreakpointReceived;
/// <summary>
/// Returns true if the loader breakpoint has been dispatched
/// Else returns false.
/// </summary>
public bool IsInitialized
{
get { return m_fLoaderBreakpointReceived; }
}
#endregion // Loader Breakpoint
#region Module support
// Debug events for module loads contain file handles that we need to remember and close.
Dictionary<IntPtr, NativeDbgModule> m_modules = new Dictionary<IntPtr, NativeDbgModule>();
/// <summary>
/// Lookup a module by base address
/// </summary>
/// <param name="baseAddress">base address for module to look for</param>
/// <returns>module with matching base address. Returns null on invalid address</returns>
/// <remarks>
/// Some WOW64 cases will produce unload events for which there are no matching load events.
/// </remarks>
public NativeDbgModule LookupModule(IntPtr baseAddress)
{
NativeDbgModule module;
if (m_modules.TryGetValue(baseAddress, out module))
{
return module;
}
return null;
}
/// <summary>
/// Find a module containing the address
/// </summary>
/// <param name="address">any address in the process</param>
/// <returns>NativeModule containing the address, or null if not in the native module list.</returns>
public NativeDbgModule FindModuleForAddress(IntPtr address)
{
foreach (NativeDbgModule module in this.m_modules.Values)
{
long start = module.BaseAddress.ToInt64();
int size = module.Size;
long end = start + size;
long test = address.ToInt64();
if (test >= start && test < end)
{
return module;
}
}
return null;
}
internal void AddModule(NativeDbgModule module)
{
Debug.Assert(!m_modules.ContainsKey(module.BaseAddress));
Debug.Assert(module.Process == this);
m_modules[module.BaseAddress] = module;
}
internal void RemoveModule(IntPtr baseAddress)
{
m_modules.Remove(baseAddress);
}
#endregion Module support
#region Context
/// <summary>
/// Retrieves the Thread Context of the thread that the event occured on.
/// </summary>
public INativeContext GetThreadContext(int threadId)
{
INativeContext context = NativeContextAllocator.Allocate();
GetThreadContext(threadId, context);
return context;
}
/// <summary>
/// copy the current context into the existing context buffer. Useful to avoid allocating a new context.
/// </summary>
/// <param name="threadId">thread ID in the current process</param>
/// <param name="context">already allocated context buffer</param>
public void GetThreadContext(int threadId, INativeContext context)
{
IntPtr hThread = IntPtr.Zero;
try
{
hThread = NativeMethods.OpenThread(ThreadAccess.THREAD_ALL_ACCESS, true, (uint)threadId);
using (IContextDirectAccessor w = context.OpenForDirectAccess())
{ // context buffer is now locked
NativeMethods.GetThreadContext(hThread, w.RawBuffer);
} // w is disposed, this unlocks the context buffer.
}
finally
{
if (hThread != IntPtr.Zero)
{
NativeMethods.CloseHandle(hThread);
}
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
namespace System.Reflection
{
internal sealed class RuntimeConstructorInfo : ConstructorInfo, IRuntimeMethodInfo
{
#region Private Data Members
private volatile RuntimeType m_declaringType;
private RuntimeTypeCache m_reflectedTypeCache;
private string? m_toString;
private ParameterInfo[]? m_parameters; // Created lazily when GetParameters() is called.
#pragma warning disable CA1823, 414
private object _empty1 = null!; // These empties are used to ensure that RuntimeConstructorInfo and RuntimeMethodInfo are have a layout which is sufficiently similar
private object _empty2 = null!;
private object _empty3 = null!;
#pragma warning restore CA1823, 414
private IntPtr m_handle;
private MethodAttributes m_methodAttributes;
private BindingFlags m_bindingFlags;
private volatile Signature? m_signature;
private INVOCATION_FLAGS m_invocationFlags;
internal INVOCATION_FLAGS InvocationFlags
{
get
{
if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0)
{
INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_IS_CTOR; // this is a given
Type? declaringType = DeclaringType;
//
// first take care of all the NO_INVOKE cases.
if (declaringType == typeof(void) ||
(declaringType != null && declaringType.ContainsGenericParameters) ||
((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs))
{
// We don't need other flags if this method cannot be invoked
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE;
}
else if (IsStatic || declaringType != null && declaringType.IsAbstract)
{
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_CTOR_INVOKE;
}
else
{
// Check for byref-like types
if (declaringType != null && declaringType.IsByRefLike)
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS;
// Check for attempt to create a delegate class.
if (typeof(Delegate).IsAssignableFrom(DeclaringType))
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR;
}
m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED;
}
return m_invocationFlags;
}
}
#endregion
#region Constructor
internal RuntimeConstructorInfo(
RuntimeMethodHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache,
MethodAttributes methodAttributes, BindingFlags bindingFlags)
{
m_bindingFlags = bindingFlags;
m_reflectedTypeCache = reflectedTypeCache;
m_declaringType = declaringType;
m_handle = handle.Value;
m_methodAttributes = methodAttributes;
}
#endregion
#region NonPublic Methods
RuntimeMethodHandleInternal IRuntimeMethodInfo.Value => new RuntimeMethodHandleInternal(m_handle);
internal override bool CacheEquals(object? o) =>
o is RuntimeConstructorInfo m && m.m_handle == m_handle;
private Signature Signature => m_signature ??= new Signature(this, m_declaringType);
private RuntimeType ReflectedTypeInternal => m_reflectedTypeCache.GetRuntimeType();
private void CheckConsistency(object? target)
{
if (target == null && IsStatic)
return;
if (!m_declaringType.IsInstanceOfType(target))
{
if (target == null)
throw new TargetException(SR.RFLCT_Targ_StatMethReqTarg);
throw new TargetException(SR.RFLCT_Targ_ITargMismatch);
}
}
internal BindingFlags BindingFlags => m_bindingFlags;
#endregion
#region Object Overrides
public override string ToString()
{
if (m_toString == null)
{
var sbName = new ValueStringBuilder(MethodNameBufferSize);
// "Void" really doesn't make sense here. But we'll keep it for compat reasons.
sbName.Append("Void ");
sbName.Append(Name);
sbName.Append('(');
AppendParameters(ref sbName, GetParameterTypes(), CallingConvention);
sbName.Append(')');
m_toString = sbName.ToString();
}
return m_toString;
}
#endregion
#region ICustomAttributeProvider
public override object[] GetCustomAttributes(bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, (typeof(object) as RuntimeType)!);
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
}
#endregion
#region MemberInfo Overrides
public override string Name => RuntimeMethodHandle.GetName(this);
public override MemberTypes MemberType => MemberTypes.Constructor;
public override Type? DeclaringType => m_reflectedTypeCache.IsGlobal ? null : m_declaringType;
public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) => HasSameMetadataDefinitionAsCore<RuntimeConstructorInfo>(other);
public override Type? ReflectedType => m_reflectedTypeCache.IsGlobal ? null : ReflectedTypeInternal;
public override int MetadataToken => RuntimeMethodHandle.GetMethodDef(this);
public override Module Module => GetRuntimeModule();
internal RuntimeType GetRuntimeType() { return m_declaringType; }
internal RuntimeModule GetRuntimeModule() { return RuntimeTypeHandle.GetModule(m_declaringType); }
internal RuntimeAssembly GetRuntimeAssembly() { return GetRuntimeModule().GetRuntimeAssembly(); }
#endregion
#region MethodBase Overrides
// This seems to always returns System.Void.
internal override Type GetReturnType() { return Signature.ReturnType; }
internal override ParameterInfo[] GetParametersNoCopy() =>
m_parameters ??= RuntimeParameterInfo.GetParameters(this, this, Signature);
public override ParameterInfo[] GetParameters()
{
ParameterInfo[] parameters = GetParametersNoCopy();
if (parameters.Length == 0)
return parameters;
ParameterInfo[] ret = new ParameterInfo[parameters.Length];
Array.Copy(parameters, ret, parameters.Length);
return ret;
}
public override MethodImplAttributes GetMethodImplementationFlags()
{
return RuntimeMethodHandle.GetImplAttributes(this);
}
public override RuntimeMethodHandle MethodHandle => new RuntimeMethodHandle(this);
public override MethodAttributes Attributes => m_methodAttributes;
public override CallingConventions CallingConvention => Signature.CallingConvention;
internal static void CheckCanCreateInstance(Type declaringType, bool isVarArg)
{
if (declaringType == null)
throw new ArgumentNullException(nameof(declaringType));
// ctor is declared on interface class
if (declaringType.IsInterface)
throw new MemberAccessException(
SR.Format(SR.Acc_CreateInterfaceEx, declaringType));
// ctor is on an abstract class
else if (declaringType.IsAbstract)
throw new MemberAccessException(
SR.Format(SR.Acc_CreateAbstEx, declaringType));
// ctor is on a class that contains stack pointers
else if (declaringType.GetRootElementType() == typeof(ArgIterator))
throw new NotSupportedException();
// ctor is vararg
else if (isVarArg)
throw new NotSupportedException();
// ctor is generic or on a generic class
else if (declaringType.ContainsGenericParameters)
{
throw new MemberAccessException(
SR.Format(SR.Acc_CreateGenericEx, declaringType));
}
// ctor is declared on System.Void
else if (declaringType == typeof(void))
throw new MemberAccessException(SR.Access_Void);
}
[DoesNotReturn]
internal void ThrowNoInvokeException()
{
CheckCanCreateInstance(DeclaringType!, (CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs);
// ctor is .cctor
if ((Attributes & MethodAttributes.Static) == MethodAttributes.Static)
throw new MemberAccessException(SR.Acc_NotClassInit);
throw new TargetException();
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override object? Invoke(
object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture)
{
INVOCATION_FLAGS invocationFlags = InvocationFlags;
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0)
ThrowNoInvokeException();
// check basic method consistency. This call will throw if there are problems in the target/method relationship
CheckConsistency(obj);
Signature sig = Signature;
// get the signature
int formalCount = sig.Arguments.Length;
int actualCount = (parameters != null) ? parameters.Length : 0;
if (formalCount != actualCount)
throw new TargetParameterCountException(SR.Arg_ParmCnt);
// if we are here we passed all the previous checks. Time to look at the arguments
bool wrapExceptions = (invokeAttr & BindingFlags.DoNotWrapExceptions) == 0;
if (actualCount > 0)
{
object[] arguments = CheckArguments(parameters!, binder, invokeAttr, culture, sig);
object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, sig, false, wrapExceptions);
// copy out. This should be made only if ByRef are present.
for (int index = 0; index < arguments.Length; index++)
parameters![index] = arguments[index];
return retValue;
}
return RuntimeMethodHandle.InvokeMethod(obj, null, sig, false, wrapExceptions);
}
public override MethodBody? GetMethodBody()
{
RuntimeMethodBody? mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal);
if (mb != null)
mb._methodBase = this;
return mb;
}
public override bool IsSecurityCritical => true;
public override bool IsSecuritySafeCritical => false;
public override bool IsSecurityTransparent => false;
public override bool ContainsGenericParameters => DeclaringType != null && DeclaringType.ContainsGenericParameters;
#endregion
#region ConstructorInfo Overrides
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override object Invoke(BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture)
{
INVOCATION_FLAGS invocationFlags = InvocationFlags;
if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS | INVOCATION_FLAGS.INVOCATION_FLAGS_NO_CTOR_INVOKE)) != 0)
ThrowNoInvokeException();
// get the signature
Signature sig = Signature;
int formalCount = sig.Arguments.Length;
int actualCount = (parameters != null) ? parameters.Length : 0;
if (formalCount != actualCount)
throw new TargetParameterCountException(SR.Arg_ParmCnt);
// We don't need to explicitly invoke the class constructor here,
// JIT/NGen will insert the call to .cctor in the instance ctor.
// if we are here we passed all the previous checks. Time to look at the arguments
bool wrapExceptions = (invokeAttr & BindingFlags.DoNotWrapExceptions) == 0;
if (actualCount > 0)
{
object[] arguments = CheckArguments(parameters!, binder, invokeAttr, culture, sig);
object retValue = RuntimeMethodHandle.InvokeMethod(null, arguments, sig, true, wrapExceptions);
// copy out. This should be made only if ByRef are present.
for (int index = 0; index < arguments.Length; index++)
parameters![index] = arguments[index];
return retValue;
}
return RuntimeMethodHandle.InvokeMethod(null, null, sig, true, wrapExceptions);
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lucene.Net.Search;
using Lucene.Net.Index;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Tokenattributes;
using Lucene.Net.Support;
using Lucene.Net.Util;
namespace Lucene.Net.Search
{
/// <summary>
/// Fuzzifies ALL terms provided as strings and then picks the best n differentiating terms.
/// In effect this mixes the behaviour of FuzzyQuery and MoreLikeThis but with special consideration
/// of fuzzy scoring factors.
/// This generally produces good results for queries where users may provide details in a number of
/// fields and have no knowledge of boolean query syntax and also want a degree of fuzzy matching and
/// a fast query.
///
/// For each source term the fuzzy variants are held in a BooleanQuery with no coord factor (because
/// we are not looking for matches on multiple variants in any one doc). Additionally, a specialized
/// TermQuery is used for variants and does not use that variant term's IDF because this would favour rarer
/// terms eg misspellings. Instead, all variants use the same IDF ranking (the one for the source query
/// term) and this is factored into the variant's boost. If the source query term does not exist in the
/// index the average IDF of the variants is used.
/// </summary>
public class FuzzyLikeThisQuery : Query
{
static Similarity sim = new DefaultSimilarity();
Query rewrittenQuery = null;
EquatableList<FieldVals> fieldVals = new EquatableList<FieldVals>();
Analyzer analyzer;
ScoreTermQueue q;
int MAX_VARIANTS_PER_TERM = 50;
bool ignoreTF = false;
private int maxNumTerms;
public override int GetHashCode()
{
int prime = 31;
int result = 1;
result = prime * result + ((analyzer == null) ? 0 : analyzer.GetHashCode());
result = prime * result
+ ((fieldVals == null) ? 0 : fieldVals.GetHashCode());
result = prime * result + (ignoreTF ? 1231 : 1237);
result = prime * result + maxNumTerms;
return result;
}
public override bool Equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (GetType() != obj.GetType())
return false;
FuzzyLikeThisQuery other = (FuzzyLikeThisQuery)obj;
if (analyzer == null)
{
if (other.analyzer != null)
return false;
}
else if (!analyzer.Equals(other.analyzer))
return false;
if (fieldVals == null)
{
if (other.fieldVals != null)
return false;
}
else if (!fieldVals.Equals(other.fieldVals))
return false;
if (ignoreTF != other.ignoreTF)
return false;
if (maxNumTerms != other.maxNumTerms)
return false;
return true;
}
/*
*
* <param name="maxNumTerms">The total number of terms clauses that will appear once rewritten as a BooleanQuery</param>
* <param name="analyzer"></param>
*/
public FuzzyLikeThisQuery(int maxNumTerms, Analyzer analyzer)
{
q = new ScoreTermQueue(maxNumTerms);
this.analyzer = analyzer;
this.maxNumTerms = maxNumTerms;
}
class FieldVals
{
internal String queryString;
internal String fieldName;
internal float minSimilarity;
internal int prefixLength;
public FieldVals(String name, float similarity, int length, String queryString)
{
fieldName = name;
minSimilarity = similarity;
prefixLength = length;
this.queryString = queryString;
}
public override int GetHashCode()
{
int prime = 31;
int result = 1;
result = prime * result
+ ((fieldName == null) ? 0 : fieldName.GetHashCode());
result = prime * result + BitConverter.ToInt32(BitConverter.GetBytes(minSimilarity),0);
result = prime * result + prefixLength;
result = prime * result
+ ((queryString == null) ? 0 : queryString.GetHashCode());
return result;
}
public override bool Equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (GetType() != obj.GetType())
return false;
FieldVals other = (FieldVals)obj;
if (fieldName == null)
{
if (other.fieldName != null)
return false;
}
else if (!fieldName.Equals(other.fieldName))
return false;
if (BitConverter.ToInt32(BitConverter.GetBytes(minSimilarity), 0) != BitConverter.ToInt32(BitConverter.GetBytes(other.minSimilarity), 0))
//if (Float.floatToIntBits(minSimilarity) != Float.floatToIntBits(other.minSimilarity))
return false;
if (prefixLength != other.prefixLength)
return false;
if (queryString == null)
{
if (other.queryString != null)
return false;
}
else if (!queryString.Equals(other.queryString))
return false;
return true;
}
}
/*
* <summary>Adds user input for "fuzzification" </summary>
* <param name="queryString">The string which will be parsed by the analyzer and for which fuzzy variants will be parsed</param>
* <param name="fieldName"></param>
* <param name="minSimilarity">The minimum similarity of the term variants (see FuzzyTermEnum)</param>
* <param name="prefixLength">Length of required common prefix on variant terms (see FuzzyTermEnum)</param>
*/
public void AddTerms(String queryString, String fieldName, float minSimilarity, int prefixLength)
{
fieldVals.Add(new FieldVals(fieldName, minSimilarity, prefixLength, queryString));
}
private void AddTerms(IndexReader reader, FieldVals f)
{
if (f.queryString == null) return;
TokenStream ts = analyzer.TokenStream(f.fieldName, new System.IO.StringReader(f.queryString));
ITermAttribute termAtt = ts.AddAttribute<ITermAttribute>();
int corpusNumDocs = reader.NumDocs();
Term internSavingTemplateTerm = new Term(f.fieldName); //optimization to avoid constructing new Term() objects
HashSet<string> processedTerms = new HashSet<string>();
while (ts.IncrementToken())
{
String term = termAtt.Term;
if (!processedTerms.Contains(term))
{
processedTerms.Add(term);
ScoreTermQueue variantsQ = new ScoreTermQueue(MAX_VARIANTS_PER_TERM); //maxNum variants considered for any one term
float minScore = 0;
Term startTerm = internSavingTemplateTerm.CreateTerm(term);
FuzzyTermEnum fe = new FuzzyTermEnum(reader, startTerm, f.minSimilarity, f.prefixLength);
TermEnum origEnum = reader.Terms(startTerm);
int df = 0;
if (startTerm.Equals(origEnum.Term))
{
df = origEnum.DocFreq(); //store the df so all variants use same idf
}
int numVariants = 0;
int totalVariantDocFreqs = 0;
do
{
Term possibleMatch = fe.Term;
if (possibleMatch != null)
{
numVariants++;
totalVariantDocFreqs += fe.DocFreq();
float score = fe.Difference();
if (variantsQ.Size() < MAX_VARIANTS_PER_TERM || score > minScore)
{
ScoreTerm st = new ScoreTerm(possibleMatch, score, startTerm);
variantsQ.InsertWithOverflow(st);
minScore = variantsQ.Top().Score; // maintain minScore
}
}
}
while (fe.Next());
if (numVariants > 0)
{
int avgDf = totalVariantDocFreqs / numVariants;
if (df == 0)//no direct match we can use as df for all variants
{
df = avgDf; //use avg df of all variants
}
// take the top variants (scored by edit distance) and reset the score
// to include an IDF factor then add to the global queue for ranking
// overall top query terms
int size = variantsQ.Size();
for (int i = 0; i < size; i++)
{
ScoreTerm st = variantsQ.Pop();
st.Score = (st.Score * st.Score) * sim.Idf(df, corpusNumDocs);
q.InsertWithOverflow(st);
}
}
}
}
}
public override Query Rewrite(IndexReader reader)
{
if (rewrittenQuery != null)
{
return rewrittenQuery;
}
//load up the list of possible terms
foreach (FieldVals f in fieldVals)
{
AddTerms(reader, f);
}
//clear the list of fields
fieldVals.Clear();
BooleanQuery bq = new BooleanQuery();
//create BooleanQueries to hold the variants for each token/field pair and ensure it
// has no coord factor
//Step 1: sort the termqueries by term/field
HashMap<Term, List<ScoreTerm>> variantQueries = new HashMap<Term, List<ScoreTerm>>();
int size = q.Size();
for (int i = 0; i < size; i++)
{
ScoreTerm st = q.Pop();
var l = variantQueries[st.fuzziedSourceTerm];
if (l == null)
{
l = new List<ScoreTerm>();
variantQueries.Add(st.fuzziedSourceTerm, l);
}
l.Add(st);
}
//Step 2: Organize the sorted termqueries into zero-coord scoring boolean queries
foreach(var variants in variantQueries.Values)
{
if (variants.Count == 1)
{
//optimize where only one selected variant
ScoreTerm st = variants[0];
TermQuery tq = new FuzzyTermQuery(st.Term, ignoreTF);
tq.Boost = st.Score; // set the boost to a mix of IDF and score
bq.Add(tq, Occur.SHOULD);
}
else
{
BooleanQuery termVariants = new BooleanQuery(true); //disable coord and IDF for these term variants
foreach(ScoreTerm st in variants)
{
TermQuery tq = new FuzzyTermQuery(st.Term, ignoreTF); // found a match
tq.Boost = st.Score; // set the boost using the ScoreTerm's score
termVariants.Add(tq, Occur.SHOULD); // add to query
}
bq.Add(termVariants, Occur.SHOULD); // add to query
}
}
//TODO possible alternative step 3 - organize above booleans into a new layer of field-based
// booleans with a minimum-should-match of NumFields-1?
bq.Boost = Boost;
this.rewrittenQuery = bq;
return bq;
}
//Holds info for a fuzzy term variant - initially score is set to edit distance (for ranking best
// term variants) then is reset with IDF for use in ranking against all other
// terms/fields
private class ScoreTerm
{
public Term Term { get; set; }
public float Score { get; set; }
internal Term fuzziedSourceTerm;
public ScoreTerm(Term term, float score, Term fuzziedSourceTerm)
{
this.Term = term;
this.Score = score;
this.fuzziedSourceTerm = fuzziedSourceTerm;
}
}
private class ScoreTermQueue : PriorityQueue<ScoreTerm>
{
public ScoreTermQueue(int size)
{
Initialize(size);
}
/* (non-Javadoc)
* <see cref="org.apache.lucene.util.PriorityQueue.lessThan(java.lang.Object, java.lang.Object)"/>
*/
public override bool LessThan(ScoreTerm termA, ScoreTerm termB)
{
if (termA.Score == termB.Score)
return termA.Term.CompareTo(termB.Term) > 0;
else
return termA.Score < termB.Score;
}
}
//overrides basic TermQuery to negate effects of IDF (idf is factored into boost of containing BooleanQuery)
private class FuzzyTermQuery : TermQuery
{
bool ignoreTF;
public FuzzyTermQuery(Term t, bool ignoreTF): base(t)
{
this.ignoreTF = ignoreTF;
}
public override Similarity GetSimilarity(Searcher searcher)
{
Similarity result = base.GetSimilarity(searcher);
result = new AnonymousSimilarityDelegator(this,result);
return result;
}
class AnonymousSimilarityDelegator : SimilarityDelegator
{
FuzzyTermQuery parent = null;
public AnonymousSimilarityDelegator(FuzzyTermQuery parent,Similarity result) : base(result)
{
this.parent = parent;
}
public override float Tf(float freq)
{
if (parent.ignoreTF)
{
return 1; //ignore tf
}
return base.Tf(freq);
}
public override float Idf(int docFreq, int numDocs)
{
//IDF is already factored into individual term boosts
return 1;
}
}
}
/* (non-Javadoc)
* <see cref="org.apache.lucene.search.Query.toString(java.lang.String)"/>
*/
public override String ToString(String field)
{
return null;
}
public bool IsIgnoreTF()
{
return ignoreTF;
}
public void SetIgnoreTF(bool ignoreTF)
{
this.ignoreTF = ignoreTF;
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Networking.Shared;
namespace Orleans.Runtime.Messaging
{
internal class Gateway
{
private readonly MessageCenter messageCenter;
private readonly GatewayClientCleanupAgent dropper;
// clients is the main authorative collection of all connected clients.
// Any client currently in the system appears in this collection.
// In addition, we use clientConnections collection for fast retrival of ClientState.
// Anything that appears in those 2 collections should also appear in the main clients collection.
private readonly ConcurrentDictionary<GrainId, ClientState> clients;
private readonly ConcurrentDictionary<GatewayInboundConnection, ClientState> clientConnections;
private readonly SiloAddress gatewayAddress;
private readonly GatewaySender sender;
private readonly ClientsReplyRoutingCache clientsReplyRoutingCache;
private ClientObserverRegistrar clientRegistrar;
private readonly object lockable;
private readonly ILogger logger;
private readonly ILoggerFactory loggerFactory;
private readonly SiloMessagingOptions messagingOptions;
public Gateway(
MessageCenter msgCtr,
ILocalSiloDetails siloDetails,
MessageFactory messageFactory,
ExecutorService executorService,
ILoggerFactory loggerFactory,
IOptions<SiloMessagingOptions> options)
{
this.messagingOptions = options.Value;
this.loggerFactory = loggerFactory;
messageCenter = msgCtr;
this.logger = this.loggerFactory.CreateLogger<Gateway>();
dropper = new GatewayClientCleanupAgent(this, executorService, loggerFactory, messagingOptions.ClientDropTimeout);
clients = new ConcurrentDictionary<GrainId, ClientState>();
clientConnections = new ConcurrentDictionary<GatewayInboundConnection, ClientState>();
clientsReplyRoutingCache = new ClientsReplyRoutingCache(messagingOptions.ResponseTimeout);
this.gatewayAddress = siloDetails.GatewayAddress;
this.sender = new GatewaySender(this, msgCtr, messageFactory, loggerFactory.CreateLogger<GatewaySender>());
lockable = new object();
}
internal void Start(ClientObserverRegistrar clientRegistrar)
{
this.clientRegistrar = clientRegistrar;
this.clientRegistrar.SetGateway(this);
dropper.Start();
}
internal void Stop()
{
dropper.Stop();
}
internal ICollection<GrainId> GetConnectedClients()
{
return clients.Keys;
}
internal void RecordOpenedConnection(GatewayInboundConnection connection, GrainId clientId)
{
lock (lockable)
{
logger.LogInformation((int)ErrorCode.GatewayClientOpenedSocket, "Recorded opened connection from endpoint {EndPoint}, client ID {ClientId}.", connection.RemoteEndpoint, clientId);
ClientState clientState;
if (clients.TryGetValue(clientId, out clientState))
{
var oldSocket = clientState.Connection;
if (oldSocket != null)
{
// The old socket will be closed by itself later.
clientConnections.TryRemove(oldSocket, out _);
}
}
else
{
clientState = new ClientState(clientId, messagingOptions.ClientDropTimeout);
clients[clientId] = clientState;
MessagingStatisticsGroup.ConnectedClientCount.Increment();
}
clientState.RecordConnection(connection);
clientConnections[connection] = clientState;
clientRegistrar.ClientAdded(clientId);
NetworkingStatisticsGroup.OnOpenedGatewayDuplexSocket();
}
}
internal void RecordClosedConnection(GatewayInboundConnection connection)
{
if (connection == null) return;
lock (lockable)
{
if (!clientConnections.TryGetValue(connection, out var clientState)) return;
clientConnections.TryRemove(connection, out _);
clientState.RecordDisconnection();
logger.LogInformation(
(int)ErrorCode.GatewayClientClosedSocket,
"Recorded closed socket from endpoint {Endpoint}, client ID {clientId}.",
connection.RemoteEndpoint?.ToString() ?? "null",
clientState.Id);
}
}
internal SiloAddress TryToReroute(Message msg)
{
// ** Special routing rule for system target here **
// When a client make a request/response to/from a SystemTarget, the TargetSilo can be set to either
// - the GatewayAddress of the target silo (for example, when the client want get the cluster typemap)
// - the "internal" Silo-to-Silo address, if the client want to send a message to a specific SystemTarget
// activation that is on a silo on which there is no gateway available (or if the client is not
// connected to that gateway)
// So, if the TargetGrain is a SystemTarget we always trust the value from Message.TargetSilo and forward
// it to this address...
// EXCEPT if the value is equal to the current GatewayAdress: in this case we will return
// null and the local dispatcher will forward the Message to a local SystemTarget activation
if (msg.TargetGrain.IsSystemTarget && !IsTargetingLocalGateway(msg.TargetSilo))
return msg.TargetSilo;
// for responses from ClientAddressableObject to ClientGrain try to use clientsReplyRoutingCache for sending replies directly back.
if (!msg.SendingGrain.IsClient || !msg.TargetGrain.IsClient) return null;
if (msg.Direction != Message.Directions.Response) return null;
SiloAddress gateway;
return clientsReplyRoutingCache.TryFindClientRoute(msg.TargetGrain, out gateway) ? gateway : null;
}
internal void DropDisconnectedClients()
{
lock (lockable)
{
List<ClientState> clientsToDrop = clients.Values.Where(cs => cs.ReadyToDrop()).ToList();
foreach (ClientState client in clientsToDrop)
DropClient(client);
}
}
internal void DropExpiredRoutingCachedEntries()
{
lock (lockable)
{
clientsReplyRoutingCache.DropExpiredEntries();
}
}
private bool IsTargetingLocalGateway(SiloAddress siloAddress)
{
// Special case if the address used by the client was loopback
return this.gatewayAddress.Matches(siloAddress)
|| (IPAddress.IsLoopback(siloAddress.Endpoint.Address)
&& siloAddress.Endpoint.Port == this.gatewayAddress.Endpoint.Port
&& siloAddress.Generation == this.gatewayAddress.Generation);
}
// This function is run under global lock
// There is NO need to acquire individual ClientState lock, since we only access client Id (immutable) and close an older socket.
private void DropClient(ClientState client)
{
logger.Info(ErrorCode.GatewayDroppingClient, "Dropping client {0}, {1} after disconnect with no reconnect",
client.Id, DateTime.UtcNow.Subtract(client.DisconnectedSince));
clients.TryRemove(client.Id, out _);
clientRegistrar.ClientDropped(client.Id);
GatewayInboundConnection oldConnection = client.Connection;
if (oldConnection != null)
{
// this will not happen, since we drop only already disconnected clients, for socket is already null. But leave this code just to be sure.
client.RecordDisconnection();
clientConnections.TryRemove(oldConnection, out _);
oldConnection.Close(new ConnectionAbortedException("Dropping client"));
}
MessagingStatisticsGroup.ConnectedClientCount.DecrementBy(1);
}
/// <summary>
/// See if this message is intended for a grain we're proxying, and queue it for delivery if so.
/// </summary>
/// <param name="msg"></param>
/// <returns>true if the message should be delivered to a proxied grain, false if not.</returns>
internal bool TryDeliverToProxy(Message msg)
{
// See if it's a grain we're proxying.
ClientState client;
// not taking global lock on the crytical path!
if (!clients.TryGetValue(msg.TargetGrain, out client))
return false;
// when this Gateway receives a message from client X to client addressale object Y
// it needs to record the original Gateway address through which this message came from (the address of the Gateway that X is connected to)
// it will use this Gateway to re-route the REPLY from Y back to X.
if (msg.SendingGrain.IsClient && msg.TargetGrain.IsClient)
{
clientsReplyRoutingCache.RecordClientRoute(msg.SendingGrain, msg.SendingSilo);
}
msg.TargetSilo = null;
// Override the SendingSilo only if the sending grain is not
// a system target
if (!msg.SendingGrain.IsSystemTarget)
msg.SendingSilo = gatewayAddress;
QueueRequest(client, msg);
return true;
}
private void QueueRequest(ClientState clientState, Message msg) => this.sender.Send(clientState, msg);
private class ClientState
{
private readonly TimeSpan clientDropTimeout;
internal Queue<Message> PendingToSend { get; private set; }
internal Queue<List<Message>> PendingBatchesToSend { get; private set; }
internal GatewayInboundConnection Connection { get; private set; }
internal DateTime DisconnectedSince { get; private set; }
internal GrainId Id { get; private set; }
internal bool IsConnected => this.Connection != null;
internal ClientState(GrainId id, TimeSpan clientDropTimeout)
{
Id = id;
this.clientDropTimeout = clientDropTimeout;
PendingToSend = new Queue<Message>();
PendingBatchesToSend = new Queue<List<Message>>();
}
internal void RecordDisconnection()
{
if (Connection == null) return;
DisconnectedSince = DateTime.UtcNow;
Connection = null;
NetworkingStatisticsGroup.OnClosedGatewayDuplexSocket();
}
internal void RecordConnection(GatewayInboundConnection connection)
{
Connection = connection;
DisconnectedSince = DateTime.MaxValue;
}
internal bool ReadyToDrop()
{
return !IsConnected &&
(DateTime.UtcNow.Subtract(DisconnectedSince) >= clientDropTimeout);
}
}
private class GatewayClientCleanupAgent : DedicatedAsynchAgent
{
private readonly Gateway gateway;
private readonly TimeSpan clientDropTimeout;
internal GatewayClientCleanupAgent(Gateway gateway, ExecutorService executorService, ILoggerFactory loggerFactory, TimeSpan clientDropTimeout)
:base(executorService, loggerFactory)
{
this.gateway = gateway;
this.clientDropTimeout = clientDropTimeout;
}
protected override void Run()
{
while (!Cts.IsCancellationRequested)
{
gateway.DropDisconnectedClients();
gateway.DropExpiredRoutingCachedEntries();
Thread.Sleep(clientDropTimeout);
}
}
}
// this cache is used to record the addresses of Gateways from which clients connected to.
// it is used to route replies to clients from client addressable objects
// without this cache this Gateway will not know how to route the reply back to the client
// (since clients are not registered in the directory and this Gateway may not be proxying for the client for whom the reply is destined).
private class ClientsReplyRoutingCache
{
// for every client: the Gateway to use to route repies back to it plus the last time that client connected via this Gateway.
private readonly ConcurrentDictionary<GrainId, Tuple<SiloAddress, DateTime>> clientRoutes;
private readonly TimeSpan TIME_BEFORE_ROUTE_CACHED_ENTRY_EXPIRES;
internal ClientsReplyRoutingCache(TimeSpan responseTimeout)
{
clientRoutes = new ConcurrentDictionary<GrainId, Tuple<SiloAddress, DateTime>>();
TIME_BEFORE_ROUTE_CACHED_ENTRY_EXPIRES = responseTimeout.Multiply(5);
}
internal void RecordClientRoute(GrainId client, SiloAddress gateway)
{
var now = DateTime.UtcNow;
clientRoutes.AddOrUpdate(client, new Tuple<SiloAddress, DateTime>(gateway, now), (k, v) => new Tuple<SiloAddress, DateTime>(gateway, now));
}
internal bool TryFindClientRoute(GrainId client, out SiloAddress gateway)
{
gateway = null;
Tuple<SiloAddress, DateTime> tuple;
bool ret = clientRoutes.TryGetValue(client, out tuple);
if (ret)
gateway = tuple.Item1;
return ret;
}
internal void DropExpiredEntries()
{
List<GrainId> clientsToDrop = clientRoutes.Where(route => Expired(route.Value.Item2)).Select(kv => kv.Key).ToList();
foreach (GrainId client in clientsToDrop)
{
Tuple<SiloAddress, DateTime> tuple;
clientRoutes.TryRemove(client, out tuple);
}
}
private bool Expired(DateTime lastUsed)
{
return DateTime.UtcNow.Subtract(lastUsed) >= TIME_BEFORE_ROUTE_CACHED_ENTRY_EXPIRES;
}
}
private sealed class GatewaySender
{
private readonly Gateway gateway;
private readonly MessageCenter messageCenter;
private readonly MessageFactory messageFactory;
private readonly ILogger<GatewaySender> log;
private readonly CounterStatistic gatewaySends;
internal GatewaySender(Gateway gateway, MessageCenter messageCenter, MessageFactory messageFactory, ILogger<GatewaySender> log)
{
this.gateway = gateway;
this.messageCenter = messageCenter;
this.messageFactory = messageFactory;
this.log = log;
this.gatewaySends = CounterStatistic.FindOrCreate(StatisticNames.GATEWAY_SENT);
}
public void Send(ClientState clientState, Message msg)
{
// This should never happen -- but make sure to handle it reasonably, just in case
if (clientState == null)
{
if (msg == null) return;
this.log.Info(ErrorCode.GatewayTryingToSendToUnrecognizedClient, "Trying to send a message {0} to an unrecognized client {1}", msg.ToString(), msg.TargetGrain);
MessagingStatisticsGroup.OnFailedSentMessage(msg);
// Message for unrecognized client -- reject it
if (msg.Direction == Message.Directions.Request)
{
MessagingStatisticsGroup.OnRejectedMessage(msg);
Message error = this.messageFactory.CreateRejectionResponse(
msg,
Message.RejectionTypes.Unrecoverable,
"Unknown client " + msg.TargetGrain);
messageCenter.SendMessage(error);
}
else
{
MessagingStatisticsGroup.OnDroppedSentMessage(msg);
}
return;
}
// if disconnected - queue for later.
if (!clientState.IsConnected)
{
if (msg == null) return;
if (this.log.IsEnabled(LogLevel.Trace)) this.log.Trace("Queued message {0} for client {1}", msg, msg.TargetGrain);
clientState.PendingToSend.Enqueue(msg);
return;
}
// if the queue is non empty - drain it first.
if (clientState.PendingToSend.Count > 0)
{
if (msg != null)
clientState.PendingToSend.Enqueue(msg);
// For now, drain in-line, although in the future this should happen in yet another asynch agent
Drain(clientState);
return;
}
// the queue was empty AND we are connected.
// If the request includes a message to send, send it (or enqueue it for later)
if (msg == null) return;
if (!Send(msg, clientState))
{
if (this.log.IsEnabled(LogLevel.Trace)) this.log.Trace("Queued message {0} for client {1}", msg, msg.TargetGrain);
clientState.PendingToSend.Enqueue(msg);
}
else
{
if (this.log.IsEnabled(LogLevel.Trace)) this.log.Trace("Sent message {0} to client {1}", msg, msg.TargetGrain);
}
}
private void Drain(ClientState clientState)
{
// For now, drain in-line, although in the future this should happen in yet another asynch agent
while (clientState.PendingToSend.Count > 0)
{
var m = clientState.PendingToSend.Peek();
if (Send(m, clientState))
{
if (this.log.IsEnabled(LogLevel.Trace)) this.log.Trace("Sent queued message {0} to client {1}", m, clientState.Id);
clientState.PendingToSend.Dequeue();
}
else
{
return;
}
}
}
private bool Send(Message msg, ClientState client)
{
try
{
client.Connection.Send(msg);
gatewaySends.Increment();
return true;
}
catch (Exception exception)
{
gateway.RecordClosedConnection(client.Connection);
client.Connection.Close(new ConnectionAbortedException("Exception posting a message to sender. See InnerException for details.", exception));
return false;
}
}
}
}
}
| |
/*
Copyright (C) 2013-2015 MetaMorph Software, Inc
Permission is hereby granted, free of charge, to any person obtaining a
copy of this data, including any software or models in source or binary
form, as well as any drawings, specifications, and documentation
(collectively "the Data"), to deal in the Data without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Data, and to
permit persons to whom the Data 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 Data.
THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
=======================
This version of the META tools is a fork of an original version produced
by Vanderbilt University's Institute for Software Integrated Systems (ISIS).
Their license statement:
Copyright (C) 2011-2014 Vanderbilt University
Developed with the sponsorship of the Defense Advanced Research Projects
Agency (DARPA) and delivered to the U.S. Government with Unlimited Rights
as defined in DFARS 252.227-7013.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this data, including any software or models in source or binary
form, as well as any drawings, specifications, and documentation
(collectively "the Data"), to deal in the Data without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Data, and to
permit persons to whom the Data 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 Data.
THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
using System.IO;
using GME.MGA;
namespace DynamicsTeamTest.Projects
{
public class RISimpleFormulaFixture : XmeImportFixture
{
protected override string xmeFilename
{
get { return Path.Combine("RISimpleFormula", "RISimpleFormula.xme"); }
}
}
public partial class RISimpleFormula : IUseFixture<RISimpleFormulaFixture>
{
internal string mgaFile { get { return this.fixture.mgaFile; } }
private RISimpleFormulaFixture fixture { get; set; }
public void SetFixture(RISimpleFormulaFixture data)
{
this.fixture = data;
}
//[Fact]
//[Trait("Model", "RISimpleFormula")]
//[Trait("ProjectImport/Open", "RISimpleFormula")]
//public void ProjectXmeImport()
//{
// Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
//}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("ProjectImport/Open", "RISimpleFormula")]
public void ProjectMgaOpen()
{
var mgaReference = "MGA=" + mgaFile;
MgaProject project = new MgaProject();
project.OpenEx(mgaReference, "CyPhyML", null);
project.Close(true);
Assert.True(File.Exists(mgaReference.Substring("MGA=".Length)));
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CyPhy2Modelica", "RISimpleFormula")]
public void Testing_RICircuit_CA()
{
string outputDir = "Testing_RICircuit_CA";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@RICircuit_CA|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CyPhy2Modelica", "RISimpleFormula")]
public void ValidParameterRanges_RICircuit_inf_and_minus_inf()
{
string outputDir = "ValidParameterRanges_RICircuit_inf_and_minus_inf";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@ValidParameterRanges|kind=Testing|relpos=0/@RICircuit_inf_and_minus_inf|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CyPhy2Modelica", "RISimpleFormula")]
public void ValidParameterRanges_RICircuit_minus_inf()
{
string outputDir = "ValidParameterRanges_RICircuit_minus_inf";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@ValidParameterRanges|kind=Testing|relpos=0/@RICircuit_minus_inf|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CyPhy2Modelica", "RISimpleFormula")]
public void ValidParameterRanges_RICircuit_inf()
{
string outputDir = "ValidParameterRanges_RICircuit_inf";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@ValidParameterRanges|kind=Testing|relpos=0/@RICircuit_inf|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CyPhy2Modelica", "RISimpleFormula")]
public void ValidParameterRanges_RICircuit_brackets1()
{
string outputDir = "ValidParameterRanges_RICircuit_brackets1";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@ValidParameterRanges|kind=Testing|relpos=0/@RICircuit_brackets1|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CyPhy2Modelica", "RISimpleFormula")]
public void ValidParameterRanges_RICircuit_brackets2()
{
string outputDir = "ValidParameterRanges_RICircuit_brackets2";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@ValidParameterRanges|kind=Testing|relpos=0/@RICircuit_brackets2|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CyPhy2Modelica", "RISimpleFormula")]
public void FailTests_RICircuit_GeoMean()
{
string outputDir = "FailTests_RICircuit_GeoMean";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@FailTests|kind=Testing|relpos=0/@RICircuit_GeoMean|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CheckerShouldFail", "RISimpleFormula")]
public void Fail_ParameterRanges_RICircuit_WrongSeparator()
{
string outputDir = "ParameterRanges_RICircuit_WrongSeparator";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@FailTests|kind=Testing|relpos=0/@ParameterRanges|kind=Testing|relpos=0/@RICircuit_WrongSeparator|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.False(result, "CyPhy2Modelica_v2 should have failed, but did not.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CheckerShouldFail", "RISimpleFormula")]
public void Fail_ParameterRanges_RICircuit_TooManySeparatedValues()
{
string outputDir = "ParameterRanges_RICircuit_TooManySeparatedValues";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@FailTests|kind=Testing|relpos=0/@ParameterRanges|kind=Testing|relpos=0/@RICircuit_TooManySeparatedValues|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.False(result, "CyPhy2Modelica_v2 should have failed, but did not.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CheckerShouldFail", "RISimpleFormula")]
public void Fail_ParameterRanges_RICircuit_misplaceBrackets()
{
string outputDir = "ParameterRanges_RICircuit_misplaceBrackets";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@FailTests|kind=Testing|relpos=0/@ParameterRanges|kind=Testing|relpos=0/@RICircuit_misplaceBrackets|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.False(result, "CyPhy2Modelica_v2 should have failed, but did not.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CheckerShouldFail", "RISimpleFormula")]
public void Fail_ParameterRanges_RICircuit_NoneRealInRange()
{
string outputDir = "ParameterRanges_RICircuit_NoneRealInRange";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@FailTests|kind=Testing|relpos=0/@ParameterRanges|kind=Testing|relpos=0/@RICircuit_NoneRealInRange|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.False(result, "CyPhy2Modelica_v2 should have failed, but did not.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CyPhy2Modelica", "RISimpleFormula")]
public void ValueFlows_RICircuit_IncomingParameterToProperty()
{
string outputDir = "ValueFlows_RICircuit_IncomingParameterToProperty";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@FailTests|kind=Testing|relpos=0/@ValueFlows|kind=Testing|relpos=0/@RICircuit_IncomingParameterToProperty|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CyPhy2Modelica", "RISimpleFormula")]
public void ValueFlows_RICircuit_CustomFormulaInParameterFlow()
{
string outputDir = "ValueFlows_RICircuit_CustomFormulaInParameterFlow";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@FailTests|kind=Testing|relpos=0/@ValueFlows|kind=Testing|relpos=0/@RICircuit_CustomFormulaInParameterFlow|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CyPhy2Modelica", "RISimpleFormula")]
public void ValueFlows_RICircuit_IncomingParameterToProperty1()
{
string outputDir = "ValueFlows_RICircuit_IncomingParameterToProperty1";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@FailTests|kind=Testing|relpos=0/@ValueFlows|kind=Testing|relpos=0/@RICircuit_IncomingParameterToProperty1|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CheckerShouldFail", "RISimpleFormula")]
public void Fail_ValueFlows_RICircuit_IncomingMetricToParameterAndProperties()
{
string outputDir = "ValueFlows_RICircuit_IncomingMetricToParameterAndProperties";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@FailTests|kind=Testing|relpos=0/@ValueFlows|kind=Testing|relpos=0/@RICircuit_IncomingMetricToParameterAndProperties|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.False(result, "CyPhy2Modelica_v2 should have failed, but did not.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CyPhy2Modelica", "RISimpleFormula")]
public void SimpleFormulas_RICircuit_CustomFormula()
{
string outputDir = "SimpleFormulas_RICircuit_CustomFormula";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@SimpleFormulas|kind=Testing|relpos=0/@RICircuit_CustomFormula|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CyPhy2Modelica", "RISimpleFormula")]
public void SimpleFormulas_RICircuit_ArithmeticMean()
{
string outputDir = "SimpleFormulas_RICircuit_ArithmeticMean";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@SimpleFormulas|kind=Testing|relpos=0/@RICircuit_ArithmeticMean|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CyPhy2Modelica", "RISimpleFormula")]
public void Multiplication_RICircuit_Product()
{
string outputDir = "Multiplication_RICircuit_Product";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@SimpleFormulas|kind=Testing|relpos=0/@Multiplication|kind=Testing|relpos=0/@RICircuit_Product|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CyPhy2Modelica", "RISimpleFormula")]
public void MinMax_RICircuit_Min()
{
string outputDir = "MinMax_RICircuit_Min";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@SimpleFormulas|kind=Testing|relpos=0/@MinMax|kind=Testing|relpos=0/@RICircuit_Min|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CyPhy2Modelica", "RISimpleFormula")]
public void MinMax_RICircuit_OneMin()
{
string outputDir = "MinMax_RICircuit_OneMin";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@SimpleFormulas|kind=Testing|relpos=0/@MinMax|kind=Testing|relpos=0/@RICircuit_OneMin|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CyPhy2Modelica", "RISimpleFormula")]
public void MinMax_RICircuit_Max()
{
string outputDir = "MinMax_RICircuit_Max";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@SimpleFormulas|kind=Testing|relpos=0/@MinMax|kind=Testing|relpos=0/@RICircuit_Max|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CyPhy2Modelica", "RISimpleFormula")]
public void Addition_RICircuit_TestBench()
{
string outputDir = "Addition_RICircuit_TestBench";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@SimpleFormulas|kind=Testing|relpos=0/@Addition|kind=Testing|relpos=0/@RICircuit_TestBench|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CyPhy2Modelica", "RISimpleFormula")]
public void Addition_RICircuit_NestedFormulas()
{
string outputDir = "Addition_RICircuit_NestedFormulas";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@SimpleFormulas|kind=Testing|relpos=0/@Addition|kind=Testing|relpos=0/@RICircuit_NestedFormulas|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CyPhy2Modelica", "RISimpleFormula")]
public void Addition_RICircuit_OutgoingParameters()
{
string outputDir = "Addition_RICircuit_OutgoingParameters";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@SimpleFormulas|kind=Testing|relpos=0/@Addition|kind=Testing|relpos=0/@RICircuit_OutgoingParameters|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CyPhy2Modelica", "RISimpleFormula")]
public void Addition_RICircuit_PassingBetweenComponents()
{
string outputDir = "Addition_RICircuit_PassingBetweenComponents";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@SimpleFormulas|kind=Testing|relpos=0/@Addition|kind=Testing|relpos=0/@RICircuit_PassingBetweenComponents|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("CyPhy2Modelica", "RISimpleFormula")]
public void Addition_RICircuit_TestBench_IntermediateParameter()
{
string outputDir = "Addition_RICircuit_TestBench_IntermediateParameter";
string testBenchPath = "/@Testing|kind=Testing|relpos=0/@SimpleFormulas|kind=Testing|relpos=0/@Addition|kind=Testing|relpos=0/@RICircuit_TestBench_IntermediateParameter|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "RISimpleFormula")]
[Trait("PCC", "RISimpleFormula")]
public void RI_PCC_CA()
{
string outputDir = "RI_PCC_CA";
string petExperimentPath = "/@Testing|kind=Testing|relpos=0/@PCC|kind=ParametricExplorationFolder|relpos=0/@RI_PCC_CA|kind=ParametricExploration|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhyPETRunner.Run(outputDir, mgaFile, petExperimentPath);
Assert.True(result, "CyPhyPET failed.");
}
}
}
| |
//
// AudioCdRipper.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Unix;
using Mono.Addins;
using Hyena.Jobs;
using Banshee.Base;
using Banshee.ServiceStack;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.MediaEngine;
namespace Banshee.AudioCd
{
public class AudioCdRipper : IDisposable
{
private static bool ripper_extension_queried = false;
private static TypeExtensionNode ripper_extension_node = null;
public static bool Supported {
get {
if (ripper_extension_queried) {
return ripper_extension_node != null;
}
ripper_extension_queried = true;
foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes (
"/Banshee/MediaEngine/AudioCdRipper")) {
ripper_extension_node = node;
break;
}
return ripper_extension_node != null;
}
}
public event EventHandler Finished;
// State that does real work
private IAudioCdRipper ripper;
private AudioCdSource source;
private UserJob user_job;
// State to process the rip operation
private Queue<AudioCdTrackInfo> queue = new Queue<AudioCdTrackInfo> ();
private TimeSpan ripped_duration;
private TimeSpan total_duration;
private int track_index;
// State to compute/display the rip speed (i.e. 24x)
private TimeSpan last_speed_poll_duration;
private DateTime last_speed_poll_time;
private double last_speed_poll_factor;
private string status;
public AudioCdRipper (AudioCdSource source)
{
if (ripper_extension_node != null) {
ripper = (IAudioCdRipper)ripper_extension_node.CreateInstance ();
ripper.TrackFinished += OnTrackFinished;
ripper.Progress += OnProgress;
ripper.Error += OnError;
} else {
throw new ApplicationException ("No AudioCdRipper extension is installed");
}
this.source = source;
}
public void Start ()
{
ResetState ();
foreach (AudioCdTrackInfo track in source.DiscModel) {
if (track.RipEnabled) {
total_duration += track.Duration;
queue.Enqueue (track);
}
}
if (queue.Count == 0) {
return;
}
source.LockAllTracks ();
user_job = new UserJob (Catalog.GetString ("Importing Audio CD"),
Catalog.GetString ("Initializing Drive"), "media-import-audio-cd");
user_job.CancelMessage = String.Format (Catalog.GetString (
"<i>{0}</i> is still being imported into the music library. Would you like to stop it?"
), GLib.Markup.EscapeText (source.DiscModel.Title));
user_job.SetResources (Resource.Cpu);
user_job.PriorityHints = PriorityHints.SpeedSensitive | PriorityHints.DataLossIfStopped;
user_job.CanCancel = true;
user_job.CancelRequested += OnCancelRequested;
user_job.Finished += OnFinished;
user_job.Register ();
if (source != null && source.DiscModel != null) {
if (!source.DiscModel.LockDoor ()) {
Hyena.Log.Warning ("Could not lock CD-ROM door", false);
}
}
ripper.Begin (source.DiscModel.Volume.DeviceNode, AudioCdService.ErrorCorrection.Get ());
RipNextTrack ();
}
public void Dispose ()
{
ResetState ();
if (source != null && source.DiscModel != null) {
source.DiscModel.UnlockDoor ();
}
if (ripper != null) {
ripper.Finish ();
ripper = null;
}
if (user_job != null) {
user_job.Finish ();
user_job = null;
}
}
private void ResetState ()
{
track_index = 0;
ripped_duration = TimeSpan.Zero;
total_duration = TimeSpan.Zero;
last_speed_poll_duration = TimeSpan.Zero;
last_speed_poll_time = DateTime.MinValue;
last_speed_poll_factor = 0;
status = null;
queue.Clear ();
}
private void RipNextTrack ()
{
if (queue.Count == 0) {
OnFinished ();
Dispose ();
return;
}
AudioCdTrackInfo track = queue.Dequeue ();
user_job.Title = String.Format (Catalog.GetString ("Importing {0} of {1}"),
++track_index, source.DiscModel.EnabledCount);
status = String.Format("{0} - {1}", track.ArtistName, track.TrackTitle);
user_job.Status = status;
SafeUri uri = new SafeUri (FileNamePattern.BuildFull (ServiceManager.SourceManager.MusicLibrary.BaseDirectory, track, null));
bool tagging_supported;
ripper.RipTrack (track.IndexOnDisc, track, uri, out tagging_supported);
}
#region Ripper Event Handlers
private void OnTrackFinished (object o, AudioCdRipperTrackFinishedArgs args)
{
if (user_job == null || ripper == null) {
return;
}
AudioCdTrackInfo track = (AudioCdTrackInfo)args.Track;
ripped_duration += track.Duration;
track.PrimarySource = ServiceManager.SourceManager.MusicLibrary;
track.Uri = args.Uri;
track.FileSize = Banshee.IO.File.GetSize (track.Uri);
track.FileModifiedStamp = Banshee.IO.File.GetModifiedTime (track.Uri);
track.LastSyncedStamp = DateTime.Now;
track.Save ();
source.UnlockTrack (track);
RipNextTrack ();
}
private void OnProgress (object o, AudioCdRipperProgressArgs args)
{
if (user_job == null) {
return;
}
TimeSpan total_ripped_duration = ripped_duration + args.EncodedTime;
user_job.Progress = total_ripped_duration.TotalMilliseconds / total_duration.TotalMilliseconds;
TimeSpan poll_diff = DateTime.Now - last_speed_poll_time;
double factor = 0;
if (poll_diff.TotalMilliseconds >= 1000) {
factor = ((total_ripped_duration - last_speed_poll_duration).TotalMilliseconds
* (poll_diff.TotalMilliseconds / 1000.0)) / 1000.0;
last_speed_poll_duration = total_ripped_duration;
last_speed_poll_time = DateTime.Now;
last_speed_poll_factor = factor > 1 ? factor : 0;
}
// Make sure the speed factor is between 1 and 200 to allow it to ramp and settle
user_job.Status = last_speed_poll_factor > 1 && last_speed_poll_factor <= 200
? String.Format ("{0} ({1:0.0}x)", status, last_speed_poll_factor)
: status;
}
private void OnError (object o, AudioCdRipperErrorArgs args)
{
Dispose ();
Hyena.Log.Error (Catalog.GetString ("Cannot Import CD"), args.Message, true);
}
#endregion
private void OnFinished ()
{
EventHandler handler = Finished;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
#region User Job Event Handlers
private void OnCancelRequested (object o, EventArgs args)
{
Dispose ();
}
private void OnFinished (object o, EventArgs args)
{
if (user_job != null) {
user_job.CancelRequested -= OnCancelRequested;
user_job.Finished -= OnFinished;
user_job = null;
}
source.UnlockAllTracks ();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Collections;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Globalization;
using System.Runtime.Serialization;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace System.Xml
{
internal static class XmlConverter
{
public const int MaxDateTimeChars = 64;
public const int MaxInt32Chars = 16;
public const int MaxInt64Chars = 32;
public const int MaxBoolChars = 5;
public const int MaxFloatChars = 16;
public const int MaxDoubleChars = 32;
public const int MaxDecimalChars = 40;
public const int MaxUInt64Chars = 32;
public const int MaxPrimitiveChars = MaxDateTimeChars;
private static UTF8Encoding s_utf8Encoding;
private static UnicodeEncoding s_unicodeEncoding;
private static Base64Encoding s_base64Encoding;
static public Base64Encoding Base64Encoding
{
get
{
if (s_base64Encoding == null)
s_base64Encoding = new Base64Encoding();
return s_base64Encoding;
}
}
private static UTF8Encoding UTF8Encoding
{
get
{
if (s_utf8Encoding == null)
s_utf8Encoding = new UTF8Encoding(false, true);
return s_utf8Encoding;
}
}
private static UnicodeEncoding UnicodeEncoding
{
get
{
if (s_unicodeEncoding == null)
s_unicodeEncoding = new UnicodeEncoding(false, false, true);
return s_unicodeEncoding;
}
}
static public bool ToBoolean(string value)
{
try
{
return XmlConvert.ToBoolean(value);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Boolean", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Boolean", exception));
}
}
static public bool ToBoolean(byte[] buffer, int offset, int count)
{
if (count == 1)
{
byte ch = buffer[offset];
if (ch == (byte)'1')
return true;
else if (ch == (byte)'0')
return false;
}
return ToBoolean(ToString(buffer, offset, count));
}
static public int ToInt32(string value)
{
try
{
return XmlConvert.ToInt32(value);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Int32", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Int32", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Int32", exception));
}
}
static public int ToInt32(byte[] buffer, int offset, int count)
{
int value;
if (TryParseInt32(buffer, offset, count, out value))
return value;
return ToInt32(ToString(buffer, offset, count));
}
static public Int64 ToInt64(string value)
{
try
{
return XmlConvert.ToInt64(value);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Int64", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Int64", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Int64", exception));
}
}
static public Int64 ToInt64(byte[] buffer, int offset, int count)
{
long value;
if (TryParseInt64(buffer, offset, count, out value))
return value;
return ToInt64(ToString(buffer, offset, count));
}
static public float ToSingle(string value)
{
try
{
return XmlConvert.ToSingle(value);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "float", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "float", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "float", exception));
}
}
static public float ToSingle(byte[] buffer, int offset, int count)
{
float value;
if (TryParseSingle(buffer, offset, count, out value))
return value;
return ToSingle(ToString(buffer, offset, count));
}
static public double ToDouble(string value)
{
try
{
return XmlConvert.ToDouble(value);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "double", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "double", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "double", exception));
}
}
static public double ToDouble(byte[] buffer, int offset, int count)
{
double value;
if (TryParseDouble(buffer, offset, count, out value))
return value;
return ToDouble(ToString(buffer, offset, count));
}
static public decimal ToDecimal(string value)
{
try
{
return XmlConvert.ToDecimal(value);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "decimal", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "decimal", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "decimal", exception));
}
}
static public decimal ToDecimal(byte[] buffer, int offset, int count)
{
return ToDecimal(ToString(buffer, offset, count));
}
static public DateTime ToDateTime(Int64 value)
{
try
{
return DateTime.FromBinary(value);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(ToString(value), "DateTime", exception));
}
}
static public DateTime ToDateTime(string value)
{
try
{
return XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.RoundtripKind);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "DateTime", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "DateTime", exception));
}
}
static public DateTime ToDateTime(byte[] buffer, int offset, int count)
{
DateTime value;
if (TryParseDateTime(buffer, offset, count, out value))
return value;
return ToDateTime(ToString(buffer, offset, count));
}
static public UniqueId ToUniqueId(string value)
{
try
{
return new UniqueId(Trim(value));
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "UniqueId", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "UniqueId", exception));
}
}
static public UniqueId ToUniqueId(byte[] buffer, int offset, int count)
{
return ToUniqueId(ToString(buffer, offset, count));
}
static public TimeSpan ToTimeSpan(string value)
{
try
{
return XmlConvert.ToTimeSpan(value);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "TimeSpan", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "TimeSpan", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "TimeSpan", exception));
}
}
static public TimeSpan ToTimeSpan(byte[] buffer, int offset, int count)
{
return ToTimeSpan(ToString(buffer, offset, count));
}
static public Guid ToGuid(string value)
{
try
{
return new Guid(Trim(value));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Guid", exception));
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Guid", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Guid", exception));
}
}
static public Guid ToGuid(byte[] buffer, int offset, int count)
{
return ToGuid(ToString(buffer, offset, count));
}
static public UInt64 ToUInt64(string value)
{
try
{
return ulong.Parse(value, NumberStyles.Any, NumberFormatInfo.InvariantInfo);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "UInt64", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "UInt64", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "UInt64", exception));
}
}
static public UInt64 ToUInt64(byte[] buffer, int offset, int count)
{
return ToUInt64(ToString(buffer, offset, count));
}
static public string ToString(byte[] buffer, int offset, int count)
{
try
{
return UTF8Encoding.GetString(buffer, offset, count);
}
catch (DecoderFallbackException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(buffer, offset, count, exception));
}
}
static public string ToStringUnicode(byte[] buffer, int offset, int count)
{
try
{
return UnicodeEncoding.GetString(buffer, offset, count);
}
catch (DecoderFallbackException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(buffer, offset, count, exception));
}
}
static public byte[] ToBytes(string value)
{
try
{
return UTF8Encoding.GetBytes(value);
}
catch (DecoderFallbackException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(value, exception));
}
}
static public int ToChars(byte[] buffer, int offset, int count, char[] chars, int charOffset)
{
try
{
return UTF8Encoding.GetChars(buffer, offset, count, chars, charOffset);
}
catch (DecoderFallbackException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(buffer, offset, count, exception));
}
}
static public string ToString(bool value) { return value ? "true" : "false"; }
static public string ToString(int value) { return XmlConvert.ToString(value); }
static public string ToString(Int64 value) { return XmlConvert.ToString(value); }
static public string ToString(float value) { return XmlConvert.ToString(value); }
static public string ToString(double value) { return XmlConvert.ToString(value); }
static public string ToString(decimal value) { return XmlConvert.ToString(value); }
static public string ToString(TimeSpan value) { return XmlConvert.ToString(value); }
static public string ToString(UniqueId value) { return value.ToString(); }
static public string ToString(Guid value) { return value.ToString(); }
static public string ToString(UInt64 value) { return value.ToString(NumberFormatInfo.InvariantInfo); }
static public string ToString(DateTime value)
{
byte[] dateChars = new byte[MaxDateTimeChars];
int count = ToChars(value, dateChars, 0);
return ToString(dateChars, 0, count);
}
private static string ToString(object value)
{
if (value is int)
return ToString((int)value);
else if (value is Int64)
return ToString((Int64)value);
else if (value is float)
return ToString((float)value);
else if (value is double)
return ToString((double)value);
else if (value is decimal)
return ToString((decimal)value);
else if (value is TimeSpan)
return ToString((TimeSpan)value);
else if (value is UniqueId)
return ToString((UniqueId)value);
else if (value is Guid)
return ToString((Guid)value);
else if (value is UInt64)
return ToString((UInt64)value);
else if (value is DateTime)
return ToString((DateTime)value);
else if (value is bool)
return ToString((bool)value);
else
return value.ToString();
}
static public string ToString(object[] objects)
{
if (objects.Length == 0)
return string.Empty;
string value = ToString(objects[0]);
if (objects.Length > 1)
{
StringBuilder sb = new StringBuilder(value);
for (int i = 1; i < objects.Length; i++)
{
sb.Append(' ');
sb.Append(ToString(objects[i]));
}
value = sb.ToString();
}
return value;
}
static public void ToQualifiedName(string qname, out string prefix, out string localName)
{
int index = qname.IndexOf(':');
if (index < 0)
{
prefix = string.Empty;
localName = Trim(qname);
}
else
{
if (index == qname.Length - 1)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.XmlInvalidQualifiedName, qname)));
prefix = Trim(qname.Substring(0, index));
localName = Trim(qname.Substring(index + 1));
}
}
private static bool TryParseInt32(byte[] chars, int offset, int count, out int result)
{
result = 0;
if (count == 0)
return false;
int value = 0;
int offsetMax = offset + count;
if (chars[offset] == '-')
{
if (count == 1)
return false;
for (int i = offset + 1; i < offsetMax; i++)
{
int digit = (chars[i] - '0');
if ((uint)digit > 9)
return false;
if (value < int.MinValue / 10)
return false;
value *= 10;
if (value < int.MinValue + digit)
return false;
value -= digit;
}
}
else
{
for (int i = offset; i < offsetMax; i++)
{
int digit = (chars[i] - '0');
if ((uint)digit > 9)
return false;
if (value > int.MaxValue / 10)
return false;
value *= 10;
if (value > int.MaxValue - digit)
return false;
value += digit;
}
}
result = value;
return true;
}
private static bool TryParseInt64(byte[] chars, int offset, int count, out long result)
{
result = 0;
if (count < 11)
{
int value;
if (!TryParseInt32(chars, offset, count, out value))
return false;
result = value;
return true;
}
else
{
long value = 0;
int offsetMax = offset + count;
if (chars[offset] == '-')
{
for (int i = offset + 1; i < offsetMax; i++)
{
int digit = (chars[i] - '0');
if ((uint)digit > 9)
return false;
if (value < long.MinValue / 10)
return false;
value *= 10;
if (value < long.MinValue + digit)
return false;
value -= digit;
}
}
else
{
for (int i = offset; i < offsetMax; i++)
{
int digit = (chars[i] - '0');
if ((uint)digit > 9)
return false;
if (value > long.MaxValue / 10)
return false;
value *= 10;
if (value > long.MaxValue - digit)
return false;
value += digit;
}
}
result = value;
return true;
}
}
private static bool TryParseSingle(byte[] chars, int offset, int count, out float result)
{
result = 0;
int offsetMax = offset + count;
bool negative = false;
if (offset < offsetMax && chars[offset] == '-')
{
negative = true;
offset++;
count--;
}
if (count < 1 || count > 10)
return false;
int value = 0;
int ch;
while (offset < offsetMax)
{
ch = (chars[offset] - '0');
if (ch == ('.' - '0'))
{
offset++;
int pow10 = 1;
while (offset < offsetMax)
{
ch = chars[offset] - '0';
if (((uint)ch) >= 10)
return false;
pow10 *= 10;
value = value * 10 + ch;
offset++;
}
// More than 8 characters (7 sig figs and a decimal) and int -> float conversion is lossy, so use double
if (count > 8)
{
result = (float)((double)value / (double)pow10);
}
else
{
result = (float)value / (float)pow10;
}
if (negative)
result = -result;
return true;
}
else if (((uint)ch) >= 10)
return false;
value = value * 10 + ch;
offset++;
}
// Ten digits w/out a decimal point might have overflowed the int
if (count == 10)
return false;
if (negative)
result = -value;
else
result = value;
return true;
}
private static bool TryParseDouble(byte[] chars, int offset, int count, out double result)
{
result = 0;
int offsetMax = offset + count;
bool negative = false;
if (offset < offsetMax && chars[offset] == '-')
{
negative = true;
offset++;
count--;
}
if (count < 1 || count > 10)
return false;
int value = 0;
int ch;
while (offset < offsetMax)
{
ch = (chars[offset] - '0');
if (ch == ('.' - '0'))
{
offset++;
int pow10 = 1;
while (offset < offsetMax)
{
ch = chars[offset] - '0';
if (((uint)ch) >= 10)
return false;
pow10 *= 10;
value = value * 10 + ch;
offset++;
}
if (negative)
result = -(double)value / pow10;
else
result = (double)value / pow10;
return true;
}
else if (((uint)ch) >= 10)
return false;
value = value * 10 + ch;
offset++;
}
// Ten digits w/out a decimal point might have overflowed the int
if (count == 10)
return false;
if (negative)
result = -value;
else
result = value;
return true;
}
static public int ToChars(int value, byte[] chars, int offset)
{
int count = ToCharsR(value, chars, offset + MaxInt32Chars);
Buffer.BlockCopy(chars, offset + MaxInt32Chars - count, chars, offset, count);
return count;
}
static public int ToChars(long value, byte[] chars, int offset)
{
int count = ToCharsR(value, chars, offset + MaxInt64Chars);
Buffer.BlockCopy(chars, offset + MaxInt64Chars - count, chars, offset, count);
return count;
}
static public int ToCharsR(long value, byte[] chars, int offset)
{
int count = 0;
if (value >= 0)
{
while (value > int.MaxValue)
{
long valueDiv10 = value / 10;
count++;
chars[--offset] = (byte)('0' + (int)(value - valueDiv10 * 10));
value = valueDiv10;
}
}
else
{
while (value < int.MinValue)
{
long valueDiv10 = value / 10;
count++;
chars[--offset] = (byte)('0' - (int)(value - valueDiv10 * 10));
value = valueDiv10;
}
}
Fx.Assert(value >= int.MinValue && value <= int.MaxValue, "");
return count + ToCharsR((int)value, chars, offset);
}
[SecuritySafeCritical]
private static unsafe bool IsNegativeZero(float value)
{
// Simple equals function will report that -0 is equal to +0, so compare bits instead
float negativeZero = -0e0F;
return (*(Int32*)&value == *(Int32*)&negativeZero);
}
[SecuritySafeCritical]
private static unsafe bool IsNegativeZero(double value)
{
// Simple equals function will report that -0 is equal to +0, so compare bits instead
double negativeZero = -0e0;
return (*(Int64*)&value == *(Int64*)&negativeZero);
}
private static int ToInfinity(bool isNegative, byte[] buffer, int offset)
{
if (isNegative)
{
buffer[offset + 0] = (byte)'-';
buffer[offset + 1] = (byte)'I';
buffer[offset + 2] = (byte)'N';
buffer[offset + 3] = (byte)'F';
return 4;
}
else
{
buffer[offset + 0] = (byte)'I';
buffer[offset + 1] = (byte)'N';
buffer[offset + 2] = (byte)'F';
return 3;
}
}
private static int ToZero(bool isNegative, byte[] buffer, int offset)
{
if (isNegative)
{
buffer[offset + 0] = (byte)'-';
buffer[offset + 1] = (byte)'0';
return 2;
}
else
{
buffer[offset] = (byte)'0';
return 1;
}
}
static public int ToChars(double value, byte[] buffer, int offset)
{
if (double.IsInfinity(value))
return ToInfinity(double.IsNegativeInfinity(value), buffer, offset);
if (value == 0.0)
return ToZero(IsNegativeZero(value), buffer, offset);
return ToAsciiChars(value.ToString("R", NumberFormatInfo.InvariantInfo), buffer, offset);
}
static public int ToChars(float value, byte[] buffer, int offset)
{
if (float.IsInfinity(value))
return ToInfinity(float.IsNegativeInfinity(value), buffer, offset);
if (value == 0.0)
return ToZero(IsNegativeZero(value), buffer, offset);
return ToAsciiChars(value.ToString("R", NumberFormatInfo.InvariantInfo), buffer, offset);
}
static public int ToChars(decimal value, byte[] buffer, int offset)
{
return ToAsciiChars(value.ToString(null, NumberFormatInfo.InvariantInfo), buffer, offset);
}
static public int ToChars(UInt64 value, byte[] buffer, int offset)
{
return ToAsciiChars(value.ToString(null, NumberFormatInfo.InvariantInfo), buffer, offset);
}
private static int ToAsciiChars(string s, byte[] buffer, int offset)
{
for (int i = 0; i < s.Length; i++)
{
Fx.Assert(s[i] < 128, "");
buffer[offset++] = (byte)s[i];
}
return s.Length;
}
static public int ToChars(bool value, byte[] buffer, int offset)
{
if (value)
{
buffer[offset + 0] = (byte)'t';
buffer[offset + 1] = (byte)'r';
buffer[offset + 2] = (byte)'u';
buffer[offset + 3] = (byte)'e';
return 4;
}
else
{
buffer[offset + 0] = (byte)'f';
buffer[offset + 1] = (byte)'a';
buffer[offset + 2] = (byte)'l';
buffer[offset + 3] = (byte)'s';
buffer[offset + 4] = (byte)'e';
return 5;
}
}
private static int ToInt32D2(byte[] chars, int offset)
{
byte ch1 = (byte)(chars[offset + 0] - '0');
byte ch2 = (byte)(chars[offset + 1] - '0');
if (ch1 > 9 || ch2 > 9)
return -1;
return 10 * ch1 + ch2;
}
private static int ToInt32D4(byte[] chars, int offset, int count)
{
return ToInt32D7(chars, offset, count);
}
private static int ToInt32D7(byte[] chars, int offset, int count)
{
int value = 0;
for (int i = 0; i < count; i++)
{
byte ch = (byte)(chars[offset + i] - '0');
if (ch > 9)
return -1;
value = value * 10 + ch;
}
return value;
}
private static bool TryParseDateTime(byte[] chars, int offset, int count, out DateTime result)
{
int offsetMax = offset + count;
result = DateTime.MaxValue;
if (count < 19)
return false;
// 1 2 3
// 012345678901234567890123456789012
// "yyyy-MM-ddTHH:mm:ss"
// "yyyy-MM-ddTHH:mm:ss.fffffff"
// "yyyy-MM-ddTHH:mm:ss.fffffffZ"
// "yyyy-MM-ddTHH:mm:ss.fffffff+xx:yy"
// "yyyy-MM-ddTHH:mm:ss.fffffff-xx:yy"
if (chars[offset + 4] != '-' || chars[offset + 7] != '-' || chars[offset + 10] != 'T' ||
chars[offset + 13] != ':' || chars[offset + 16] != ':')
return false;
int year = ToInt32D4(chars, offset + 0, 4);
int month = ToInt32D2(chars, offset + 5);
int day = ToInt32D2(chars, offset + 8);
int hour = ToInt32D2(chars, offset + 11);
int minute = ToInt32D2(chars, offset + 14);
int second = ToInt32D2(chars, offset + 17);
if ((year | month | day | hour | minute | second) < 0)
return false;
DateTimeKind kind = DateTimeKind.Unspecified;
offset += 19;
int ticks = 0;
if (offset < offsetMax && chars[offset] == '.')
{
offset++;
int digitOffset = offset;
while (offset < offsetMax)
{
byte ch = chars[offset];
if (ch < '0' || ch > '9')
break;
offset++;
}
int digitCount = offset - digitOffset;
if (digitCount < 1 || digitCount > 7)
return false;
ticks = ToInt32D7(chars, digitOffset, digitCount);
if (ticks < 0)
return false;
for (int i = digitCount; i < 7; ++i)
ticks *= 10;
}
bool isLocal = false;
int hourDelta = 0;
int minuteDelta = 0;
if (offset < offsetMax)
{
byte ch = chars[offset];
if (ch == 'Z')
{
offset++;
kind = DateTimeKind.Utc;
}
else if (ch == '+' || ch == '-')
{
offset++;
if (offset + 5 > offsetMax || chars[offset + 2] != ':')
return false;
kind = DateTimeKind.Utc;
isLocal = true;
hourDelta = ToInt32D2(chars, offset);
minuteDelta = ToInt32D2(chars, offset + 3);
if ((hourDelta | minuteDelta) < 0)
return false;
if (ch == '+')
{
hourDelta = -hourDelta;
minuteDelta = -minuteDelta;
}
offset += 5;
}
}
if (offset < offsetMax)
return false;
DateTime value;
try
{
value = new DateTime(year, month, day, hour, minute, second, kind);
}
catch (ArgumentException)
{
return false;
}
if (ticks > 0)
{
value = value.AddTicks(ticks);
}
if (isLocal)
{
try
{
TimeSpan ts = new TimeSpan(hourDelta, minuteDelta, 0);
if (hourDelta >= 0 && (value < DateTime.MaxValue - ts) ||
hourDelta < 0 && (value > DateTime.MinValue - ts))
{
value = value.Add(ts).ToLocalTime();
}
else
{
value = value.ToLocalTime().Add(ts);
}
}
catch (ArgumentOutOfRangeException) // Overflow
{
return false;
}
}
result = value;
return true;
}
// Works left from offset
static public int ToCharsR(int value, byte[] chars, int offset)
{
int count = 0;
if (value >= 0)
{
while (value >= 10)
{
int valueDiv10 = value / 10;
count++;
chars[--offset] = (byte)('0' + (value - valueDiv10 * 10));
value = valueDiv10;
}
chars[--offset] = (byte)('0' + value);
count++;
}
else
{
while (value <= -10)
{
int valueDiv10 = value / 10;
count++;
chars[--offset] = (byte)('0' - (value - valueDiv10 * 10));
value = valueDiv10;
}
chars[--offset] = (byte)('0' - value);
chars[--offset] = (byte)'-';
count += 2;
}
return count;
}
private static int ToCharsD2(int value, byte[] chars, int offset)
{
DiagnosticUtility.DebugAssert(value >= 0 && value < 100, "");
if (value < 10)
{
chars[offset + 0] = (byte)'0';
chars[offset + 1] = (byte)('0' + value);
}
else
{
int valueDiv10 = value / 10;
chars[offset + 0] = (byte)('0' + valueDiv10);
chars[offset + 1] = (byte)('0' + value - valueDiv10 * 10);
}
return 2;
}
private static int ToCharsD4(int value, byte[] chars, int offset)
{
DiagnosticUtility.DebugAssert(value >= 0 && value < 10000, "");
ToCharsD2(value / 100, chars, offset + 0);
ToCharsD2(value % 100, chars, offset + 2);
return 4;
}
private static int ToCharsD7(int value, byte[] chars, int offset)
{
DiagnosticUtility.DebugAssert(value >= 0 && value < 10000000, "");
int zeroCount = 7 - ToCharsR(value, chars, offset + 7);
for (int i = 0; i < zeroCount; i++)
chars[offset + i] = (byte)'0';
int count = 7;
while (count > 0 && chars[offset + count - 1] == '0')
count--;
return count;
}
static public int ToChars(DateTime value, byte[] chars, int offset)
{
const long TicksPerMillisecond = 10000;
const long TicksPerSecond = TicksPerMillisecond * 1000;
int offsetMin = offset;
// "yyyy-MM-ddTHH:mm:ss.fffffff";
offset += ToCharsD4(value.Year, chars, offset);
chars[offset++] = (byte)'-';
offset += ToCharsD2(value.Month, chars, offset);
chars[offset++] = (byte)'-';
offset += ToCharsD2(value.Day, chars, offset);
chars[offset++] = (byte)'T';
offset += ToCharsD2(value.Hour, chars, offset);
chars[offset++] = (byte)':';
offset += ToCharsD2(value.Minute, chars, offset);
chars[offset++] = (byte)':';
offset += ToCharsD2(value.Second, chars, offset);
int ms = (int)(value.Ticks % TicksPerSecond);
if (ms != 0)
{
chars[offset++] = (byte)'.';
offset += ToCharsD7(ms, chars, offset);
}
switch (value.Kind)
{
case DateTimeKind.Unspecified:
break;
case DateTimeKind.Local:
// +"zzzzzz";
TimeSpan ts = TimeZoneInfo.Local.GetUtcOffset(value);
if (ts.Ticks < 0)
chars[offset++] = (byte)'-';
else
chars[offset++] = (byte)'+';
offset += ToCharsD2(Math.Abs(ts.Hours), chars, offset);
chars[offset++] = (byte)':';
offset += ToCharsD2(Math.Abs(ts.Minutes), chars, offset);
break;
case DateTimeKind.Utc:
// +"Z"
chars[offset++] = (byte)'Z';
break;
default:
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException());
}
return offset - offsetMin;
}
static public bool IsWhitespace(string s)
{
for (int i = 0; i < s.Length; i++)
{
if (!IsWhitespace(s[i]))
return false;
}
return true;
}
static public bool IsWhitespace(char ch)
{
return (ch <= ' ' && (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'));
}
static public string StripWhitespace(string s)
{
int count = s.Length;
for (int i = 0; i < s.Length; i++)
{
if (IsWhitespace(s[i]))
{
count--;
}
}
if (count == s.Length)
return s;
char[] chars = new char[count];
count = 0;
for (int i = 0; i < s.Length; i++)
{
char ch = s[i];
if (!IsWhitespace(ch))
{
chars[count++] = ch;
}
}
return new string(chars);
}
private static string Trim(string s)
{
int i;
for (i = 0; i < s.Length && IsWhitespace(s[i]); i++)
;
int j;
for (j = s.Length; j > 0 && IsWhitespace(s[j - 1]); j--)
;
if (i == 0 && j == s.Length)
return s;
else if (j == 0)
return string.Empty;
else
return s.Substring(i, j - i);
}
}
}
| |
using System;
using NUnit.Framework;
using ServiceStack.Common.Tests.Models;
namespace ServiceStack.OrmLite.Tests
{
[TestFixture]
public class OrmLiteCreateTableWithNamigStrategyTests
: OrmLiteTestBase
{
[Test]
public void Can_create_TableWithNamigStrategy_table_prefix()
{
OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = new PrefixNamingStrategy
{
TablePrefix ="tab_",
ColumnPrefix = "col_",
};
using (var db = ConnectionString.OpenDbConnection())
using (var dbCmd = db.CreateCommand())
{
dbCmd.CreateTable<ModelWithOnlyStringFields>(true);
}
OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase();
}
[Test]
public void Can_create_TableWithNamigStrategy_table_lowered()
{
OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = new LowercaseNamingStrategy();
using (var db = ConnectionString.OpenDbConnection())
using (var dbCmd = db.CreateCommand())
{
dbCmd.CreateTable<ModelWithOnlyStringFields>(true);
}
OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase();
}
[Test]
public void Can_create_TableWithNamigStrategy_table_nameUnderscoreCoumpound()
{
OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = new UnderscoreSeparatedCompoundNamingStrategy();
using (var db = ConnectionString.OpenDbConnection())
using (var dbCmd = db.CreateCommand())
{
dbCmd.CreateTable<ModelWithOnlyStringFields>(true);
}
OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase();
}
[Test]
public void Can_get_data_from_TableWithNamigStrategy_with_GetById()
{
OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = new PrefixNamingStrategy
{
TablePrefix = "tab_",
ColumnPrefix = "col_",
};
using (var db = ConnectionString.OpenDbConnection())
using (var dbCmd = db.CreateCommand())
{
dbCmd.CreateTable<ModelWithOnlyStringFields>(true);
ModelWithOnlyStringFields m = new ModelWithOnlyStringFields() { Id= "999", AlbumId = "112", AlbumName="ElectroShip", Name = "MyNameIsBatman"};
dbCmd.Save<ModelWithOnlyStringFields>(m);
var modelFromDb = dbCmd.GetById<ModelWithOnlyStringFields>("999");
Assert.AreEqual(m.Name, modelFromDb.Name);
}
OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase();
}
[Test]
public void Can_get_data_from_TableWithNamigStrategy_with_query_by_example()
{
OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = new PrefixNamingStrategy
{
TablePrefix = "tab_",
ColumnPrefix = "col_",
};
using (var db = ConnectionString.OpenDbConnection())
using (var dbCmd = db.CreateCommand())
{
dbCmd.CreateTable<ModelWithOnlyStringFields>(true);
ModelWithOnlyStringFields m = new ModelWithOnlyStringFields() { Id = "998", AlbumId = "112", AlbumName = "ElectroShip", Name = "QueryByExample" };
dbCmd.Save<ModelWithOnlyStringFields>(m);
var modelFromDb = dbCmd.Where<ModelWithOnlyStringFields>(new { Name = "QueryByExample" })[0];
Assert.AreEqual(m.Name, modelFromDb.Name);
}
OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase();
}
[Test]
public void Can_get_data_from_TableWithNamigStrategy_AfterChangingNamingStrategy()
{
OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = new PrefixNamingStrategy
{
TablePrefix = "tab_",
ColumnPrefix = "col_",
};
using (var db = ConnectionString.OpenDbConnection())
using (var dbCmd = db.CreateCommand())
{
dbCmd.CreateTable<ModelWithOnlyStringFields>(true);
ModelWithOnlyStringFields m = new ModelWithOnlyStringFields() { Id = "998", AlbumId = "112", AlbumName = "ElectroShip", Name = "QueryByExample" };
dbCmd.Save<ModelWithOnlyStringFields>(m);
var modelFromDb = dbCmd.Where<ModelWithOnlyStringFields>(new { Name = "QueryByExample" })[0];
Assert.AreEqual(m.Name, modelFromDb.Name);
modelFromDb = dbCmd.GetById<ModelWithOnlyStringFields>("998");
Assert.AreEqual(m.Name, modelFromDb.Name);
}
OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase();
using (var db = ConnectionString.OpenDbConnection())
using (var dbCmd = db.CreateCommand())
{
dbCmd.CreateTable<ModelWithOnlyStringFields>(true);
ModelWithOnlyStringFields m = new ModelWithOnlyStringFields() { Id = "998", AlbumId = "112", AlbumName = "ElectroShip", Name = "QueryByExample" };
dbCmd.Save<ModelWithOnlyStringFields>(m);
var modelFromDb = dbCmd.Where<ModelWithOnlyStringFields>(new { Name = "QueryByExample" })[0];
Assert.AreEqual(m.Name, modelFromDb.Name);
modelFromDb = dbCmd.GetById<ModelWithOnlyStringFields>("998");
Assert.AreEqual(m.Name, modelFromDb.Name);
}
OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = new PrefixNamingStrategy
{
TablePrefix = "tab_",
ColumnPrefix = "col_",
};
using (var db = ConnectionString.OpenDbConnection())
using (var dbCmd = db.CreateCommand())
{
dbCmd.CreateTable<ModelWithOnlyStringFields>(true);
ModelWithOnlyStringFields m = new ModelWithOnlyStringFields() { Id = "998", AlbumId = "112", AlbumName = "ElectroShip", Name = "QueryByExample" };
dbCmd.Save<ModelWithOnlyStringFields>(m);
var modelFromDb = dbCmd.Where<ModelWithOnlyStringFields>(new { Name = "QueryByExample" })[0];
Assert.AreEqual(m.Name, modelFromDb.Name);
modelFromDb = dbCmd.GetById<ModelWithOnlyStringFields>("998");
Assert.AreEqual(m.Name, modelFromDb.Name);
}
OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase();
}
}
public class PrefixNamingStrategy : OrmLiteNamingStrategyBase
{
public string TablePrefix { get; set; }
public string ColumnPrefix { get; set; }
public override string GetTableName(string name)
{
return TablePrefix + name;
}
public override string GetColumnName(string name)
{
return ColumnPrefix + name;
}
}
public class LowercaseNamingStrategy : OrmLiteNamingStrategyBase
{
public override string GetTableName(string name)
{
return name.ToLower();
}
public override string GetColumnName(string name)
{
return name.ToLower();
}
}
public class UnderscoreSeparatedCompoundNamingStrategy : OrmLiteNamingStrategyBase
{
public override string GetTableName(string name)
{
return toUnderscoreSeparatedCompound(name);
}
public override string GetColumnName(string name)
{
return toUnderscoreSeparatedCompound(name);
}
string toUnderscoreSeparatedCompound(string name)
{
string r = char.ToLower(name[0]).ToString();
for (int i = 1; i < name.Length; i++)
{
char c = name[i];
if (char.IsUpper(name[i]))
{
r += "_";
r += char.ToLower(name[i]);
}
else
{
r += name[i];
}
}
return r;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reactive.Subjects;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Data;
using Avalonia.Logging;
using Avalonia.Platform;
using Avalonia.UnitTests;
using Moq;
using Xunit;
namespace Avalonia.Base.UnitTests
{
public class AvaloniaObjectTests_Direct
{
[Fact]
public void GetValue_Gets_Default_Value()
{
var target = new Class1();
Assert.Equal("initial", target.GetValue(Class1.FooProperty));
}
[Fact]
public void GetValue_Gets_Value_NonGeneric()
{
var target = new Class1();
Assert.Equal("initial", target.GetValue((AvaloniaProperty)Class1.FooProperty));
}
[Fact]
public void GetValue_On_Unregistered_Property_Throws_Exception()
{
var target = new Class2();
Assert.Throws<ArgumentException>(() => target.GetValue(Class1.BarProperty));
}
[Fact]
public void SetValue_Sets_Value()
{
var target = new Class1();
target.SetValue(Class1.FooProperty, "newvalue");
Assert.Equal("newvalue", target.Foo);
}
[Fact]
public void SetValue_Sets_Value_NonGeneric()
{
var target = new Class1();
target.SetValue((AvaloniaProperty)Class1.FooProperty, "newvalue");
Assert.Equal("newvalue", target.Foo);
}
[Fact]
public void SetValue_NonGeneric_Coerces_UnsetValue_To_Default_Value()
{
var target = new Class1();
target.SetValue((AvaloniaProperty)Class1.BazProperty, AvaloniaProperty.UnsetValue);
Assert.Equal(-1, target.Baz);
}
[Fact]
public void SetValue_Raises_PropertyChanged()
{
var target = new Class1();
bool raised = false;
target.PropertyChanged += (s, e) =>
raised = e.Property == Class1.FooProperty &&
(string)e.OldValue == "initial" &&
(string)e.NewValue == "newvalue" &&
e.Priority == BindingPriority.LocalValue;
target.SetValue(Class1.FooProperty, "newvalue");
Assert.True(raised);
}
[Fact]
public void SetValue_Raises_Changed()
{
var target = new Class1();
bool raised = false;
Class1.FooProperty.Changed.Subscribe(e =>
raised = e.Property == Class1.FooProperty &&
e.OldValue.GetValueOrDefault() == "initial" &&
e.NewValue.GetValueOrDefault() == "newvalue" &&
e.Priority == BindingPriority.LocalValue);
target.SetValue(Class1.FooProperty, "newvalue");
Assert.True(raised);
}
[Fact]
public void Setting_Object_Property_To_UnsetValue_Reverts_To_Default_Value()
{
Class1 target = new Class1();
target.SetValue(Class1.FrankProperty, "newvalue");
target.SetValue(Class1.FrankProperty, AvaloniaProperty.UnsetValue);
Assert.Equal("Kups", target.GetValue(Class1.FrankProperty));
}
[Fact]
public void Setting_Object_Property_To_DoNothing_Does_Nothing()
{
Class1 target = new Class1();
target.SetValue(Class1.FrankProperty, "newvalue");
target.SetValue(Class1.FrankProperty, BindingOperations.DoNothing);
Assert.Equal("newvalue", target.GetValue(Class1.FrankProperty));
}
[Fact]
public void Bind_Raises_PropertyChanged()
{
var target = new Class1();
var source = new Subject<BindingValue<string>>();
bool raised = false;
target.PropertyChanged += (s, e) =>
raised = e.Property == Class1.FooProperty &&
(string)e.OldValue == "initial" &&
(string)e.NewValue == "newvalue" &&
e.Priority == BindingPriority.LocalValue;
target.Bind(Class1.FooProperty, source);
source.OnNext("newvalue");
Assert.True(raised);
}
[Fact]
public void PropertyChanged_Not_Raised_When_Value_Unchanged()
{
var target = new Class1();
var source = new Subject<BindingValue<string>>();
var raised = 0;
target.PropertyChanged += (s, e) => ++raised;
target.Bind(Class1.FooProperty, source);
source.OnNext("newvalue");
source.OnNext("newvalue");
Assert.Equal(1, raised);
}
[Fact]
public void SetValue_On_Unregistered_Property_Throws_Exception()
{
var target = new Class2();
Assert.Throws<ArgumentException>(() => target.SetValue(Class1.BarProperty, "value"));
}
[Fact]
public void ClearValue_Restores_Default_value()
{
var target = new Class1();
Assert.Equal("initial", target.GetValue(Class1.FooProperty));
}
[Fact]
public void ClearValue_Raises_PropertyChanged()
{
Class1 target = new Class1();
var raised = 0;
target.SetValue(Class1.FooProperty, "newvalue");
target.PropertyChanged += (s, e) =>
{
Assert.Same(target, s);
Assert.Equal(BindingPriority.LocalValue, e.Priority);
Assert.Equal(Class1.FooProperty, e.Property);
Assert.Equal("newvalue", (string)e.OldValue);
Assert.Equal("unset", (string)e.NewValue);
++raised;
};
target.ClearValue(Class1.FooProperty);
Assert.Equal(1, raised);
}
[Fact]
public void GetObservable_Returns_Values()
{
var target = new Class1();
List<string> values = new List<string>();
target.GetObservable(Class1.FooProperty).Subscribe(x => values.Add(x));
target.Foo = "newvalue";
Assert.Equal(new[] { "initial", "newvalue" }, values);
}
[Fact]
public void Bind_Binds_Property_Value()
{
var target = new Class1();
var source = new Subject<string>();
var sub = target.Bind(Class1.FooProperty, source);
Assert.Equal("initial", target.Foo);
source.OnNext("first");
Assert.Equal("first", target.Foo);
source.OnNext("second");
Assert.Equal("second", target.Foo);
sub.Dispose();
source.OnNext("third");
Assert.Equal("second", target.Foo);
}
[Fact]
public void Bind_Binds_Property_Value_NonGeneric()
{
var target = new Class1();
var source = new Subject<string>();
var sub = target.Bind((AvaloniaProperty)Class1.FooProperty, source);
Assert.Equal("initial", target.Foo);
source.OnNext("first");
Assert.Equal("first", target.Foo);
source.OnNext("second");
Assert.Equal("second", target.Foo);
sub.Dispose();
source.OnNext("third");
Assert.Equal("second", target.Foo);
}
[Fact]
public void Bind_NonGeneric_Accepts_UnsetValue()
{
var target = new Class1();
var source = new Subject<object>();
var sub = target.Bind((AvaloniaProperty)Class1.BazProperty, source);
Assert.Equal(5, target.Baz);
source.OnNext(6);
Assert.Equal(6, target.Baz);
source.OnNext(AvaloniaProperty.UnsetValue);
Assert.Equal(-1, target.Baz);
}
[Fact]
public void Bind_Handles_Wrong_Type()
{
var target = new Class1();
var source = new Subject<object>();
var sub = target.Bind(Class1.FooProperty, source);
source.OnNext(45);
Assert.Equal("unset", target.Foo);
}
[Fact]
public void Bind_Handles_Wrong_Value_Type()
{
var target = new Class1();
var source = new Subject<object>();
var sub = target.Bind(Class1.BazProperty, source);
source.OnNext("foo");
Assert.Equal(-1, target.Baz);
}
[Fact]
public void ReadOnly_Property_Cannot_Be_Set()
{
var target = new Class1();
Assert.Throws<ArgumentException>(() =>
target.SetValue(Class1.BarProperty, "newvalue"));
}
[Fact]
public void ReadOnly_Property_Cannot_Be_Set_NonGeneric()
{
var target = new Class1();
Assert.Throws<ArgumentException>(() =>
target.SetValue((AvaloniaProperty)Class1.BarProperty, "newvalue"));
}
[Fact]
public void ReadOnly_Property_Cannot_Be_Bound()
{
var target = new Class1();
var source = new Subject<string>();
Assert.Throws<ArgumentException>(() =>
target.Bind(Class1.BarProperty, source));
}
[Fact]
public void ReadOnly_Property_Cannot_Be_Bound_NonGeneric()
{
var target = new Class1();
var source = new Subject<string>();
Assert.Throws<ArgumentException>(() =>
target.Bind(Class1.BarProperty, source));
}
[Fact]
public void GetValue_Gets_Value_On_AddOwnered_Property()
{
var target = new Class2();
Assert.Equal("initial2", target.GetValue(Class2.FooProperty));
}
[Fact]
public void GetValue_Gets_Value_On_AddOwnered_Property_Using_Original()
{
var target = new Class2();
Assert.Equal("initial2", target.GetValue(Class1.FooProperty));
}
[Fact]
public void GetValue_Gets_Value_On_AddOwnered_Property_Using_Original_NonGeneric()
{
var target = new Class2();
Assert.Equal("initial2", target.GetValue((AvaloniaProperty)Class1.FooProperty));
}
[Fact]
public void SetValue_Sets_Value_On_AddOwnered_Property_Using_Original()
{
var target = new Class2();
target.SetValue(Class1.FooProperty, "newvalue");
Assert.Equal("newvalue", target.Foo);
}
[Fact]
public void SetValue_Sets_Value_On_AddOwnered_Property_Using_Original_NonGeneric()
{
var target = new Class2();
target.SetValue((AvaloniaProperty)Class1.FooProperty, "newvalue");
Assert.Equal("newvalue", target.Foo);
}
[Fact]
public void UnsetValue_Is_Used_On_AddOwnered_Property()
{
var target = new Class2();
target.SetValue((AvaloniaProperty)Class1.FooProperty, AvaloniaProperty.UnsetValue);
Assert.Equal("unset", target.Foo);
}
[Fact]
public void Bind_Binds_AddOwnered_Property_Value()
{
var target = new Class2();
var source = new Subject<string>();
var sub = target.Bind(Class1.FooProperty, source);
Assert.Equal("initial2", target.Foo);
source.OnNext("first");
Assert.Equal("first", target.Foo);
source.OnNext("second");
Assert.Equal("second", target.Foo);
sub.Dispose();
source.OnNext("third");
Assert.Equal("second", target.Foo);
}
[Fact]
public void Bind_Binds_AddOwnered_Property_Value_NonGeneric()
{
var target = new Class2();
var source = new Subject<string>();
var sub = target.Bind((AvaloniaProperty)Class1.FooProperty, source);
Assert.Equal("initial2", target.Foo);
source.OnNext("first");
Assert.Equal("first", target.Foo);
source.OnNext("second");
Assert.Equal("second", target.Foo);
sub.Dispose();
source.OnNext("third");
Assert.Equal("second", target.Foo);
}
[Fact]
public void Binding_Error_Reverts_To_Default_Value()
{
var target = new Class1();
var source = new Subject<BindingValue<string>>();
target.Bind(Class1.FooProperty, source);
source.OnNext("initial");
source.OnNext(BindingValue<string>.BindingError(new InvalidOperationException("Foo")));
Assert.Equal("unset", target.GetValue(Class1.FooProperty));
}
[Fact]
public void Binding_Error_With_FallbackValue_Causes_Target_Update()
{
var target = new Class1();
var source = new Subject<BindingValue<string>>();
target.Bind(Class1.FooProperty, source);
source.OnNext("initial");
source.OnNext(BindingValue<string>.BindingError(new InvalidOperationException("Foo"), "bar"));
Assert.Equal("bar", target.GetValue(Class1.FooProperty));
}
[Fact]
public void DataValidationError_Does_Not_Cause_Target_Update()
{
var target = new Class1();
var source = new Subject<BindingValue<string>>();
target.Bind(Class1.FooProperty, source);
source.OnNext("initial");
source.OnNext(BindingValue<string>.DataValidationError(new InvalidOperationException("Foo")));
Assert.Equal("initial", target.GetValue(Class1.FooProperty));
}
[Fact]
public void DataValidationError_With_FallbackValue_Causes_Target_Update()
{
var target = new Class1();
var source = new Subject<BindingValue<string>>();
target.Bind(Class1.FooProperty, source);
source.OnNext("initial");
source.OnNext(BindingValue<string>.DataValidationError(new InvalidOperationException("Foo"), "bar"));
Assert.Equal("bar", target.GetValue(Class1.FooProperty));
}
[Fact]
public void BindingError_With_FallbackValue_Causes_Target_Update()
{
var target = new Class1();
var source = new Subject<BindingValue<string>>();
target.Bind(Class1.FooProperty, source);
source.OnNext("initial");
source.OnNext(BindingValue<string>.BindingError(new InvalidOperationException("Foo"), "fallback"));
Assert.Equal("fallback", target.GetValue(Class1.FooProperty));
}
[Fact]
public void Binding_To_Direct_Property_Logs_BindingError()
{
var target = new Class1();
var source = new Subject<BindingValue<string>>();
var called = false;
LogCallback checkLogMessage = (level, area, src, mt, pv) =>
{
if (level == LogEventLevel.Warning &&
area == LogArea.Binding &&
mt == "Error in binding to {Target}.{Property}: {Message}" &&
pv.Length == 3 &&
pv[0] is Class1 &&
object.ReferenceEquals(pv[1], Class1.FooProperty) &&
(string)pv[2] == "Binding Error Message")
{
called = true;
}
};
using (TestLogSink.Start(checkLogMessage))
{
target.Bind(Class1.FooProperty, source);
source.OnNext("baz");
source.OnNext(BindingValue<string>.BindingError(new InvalidOperationException("Binding Error Message")));
}
Assert.True(called);
}
[Fact]
public async Task Bind_Executes_On_UIThread()
{
var target = new Class1();
var source = new Subject<object>();
var currentThreadId = Thread.CurrentThread.ManagedThreadId;
var threadingInterfaceMock = new Mock<IPlatformThreadingInterface>();
threadingInterfaceMock.SetupGet(mock => mock.CurrentThreadIsLoopThread)
.Returns(() => Thread.CurrentThread.ManagedThreadId == currentThreadId);
var services = new TestServices(
threadingInterface: threadingInterfaceMock.Object);
using (UnitTestApplication.Start(services))
{
target.Bind(Class1.FooProperty, source);
await Task.Run(() => source.OnNext("foobar"));
}
}
[Fact]
public void AddOwner_Should_Inherit_DefaultBindingMode()
{
var foo = new DirectProperty<Class1, string>(
"foo",
o => "foo",
null,
new DirectPropertyMetadata<string>(defaultBindingMode: BindingMode.TwoWay));
var bar = foo.AddOwner<Class2>(o => "bar");
Assert.Equal(BindingMode.TwoWay, bar.GetMetadata<Class1>().DefaultBindingMode);
Assert.Equal(BindingMode.TwoWay, bar.GetMetadata<Class2>().DefaultBindingMode);
}
[Fact]
public void AddOwner_Can_Override_DefaultBindingMode()
{
var foo = new DirectProperty<Class1, string>(
"foo",
o => "foo",
null,
new DirectPropertyMetadata<string>(defaultBindingMode: BindingMode.TwoWay));
var bar = foo.AddOwner<Class2>(o => "bar", defaultBindingMode: BindingMode.OneWayToSource);
Assert.Equal(BindingMode.TwoWay, bar.GetMetadata<Class1>().DefaultBindingMode);
Assert.Equal(BindingMode.OneWayToSource, bar.GetMetadata<Class2>().DefaultBindingMode);
}
[Fact]
public void SetValue_Should_Not_Cause_StackOverflow_And_Have_Correct_Values()
{
var viewModel = new TestStackOverflowViewModel()
{
Value = 50
};
var target = new Class1();
target.Bind(Class1.DoubleValueProperty, new Binding("Value")
{
Mode = BindingMode.TwoWay,
Source = viewModel
});
var child = new Class1();
child[!!Class1.DoubleValueProperty] = target[!!Class1.DoubleValueProperty];
Assert.Equal(1, viewModel.SetterInvokedCount);
// Issues #855 and #824 were causing a StackOverflowException at this point.
target.DoubleValue = 51.001;
Assert.Equal(2, viewModel.SetterInvokedCount);
double expected = 51;
Assert.Equal(expected, viewModel.Value);
Assert.Equal(expected, target.DoubleValue);
Assert.Equal(expected, child.DoubleValue);
}
private class Class1 : AvaloniaObject
{
public static readonly DirectProperty<Class1, string> FooProperty =
AvaloniaProperty.RegisterDirect<Class1, string>(
nameof(Foo),
o => o.Foo,
(o, v) => o.Foo = v,
unsetValue: "unset");
public static readonly DirectProperty<Class1, string> BarProperty =
AvaloniaProperty.RegisterDirect<Class1, string>(nameof(Bar), o => o.Bar);
public static readonly DirectProperty<Class1, int> BazProperty =
AvaloniaProperty.RegisterDirect<Class1, int>(
nameof(Baz),
o => o.Baz,
(o, v) => o.Baz = v,
unsetValue: -1);
public static readonly DirectProperty<Class1, double> DoubleValueProperty =
AvaloniaProperty.RegisterDirect<Class1, double>(
nameof(DoubleValue),
o => o.DoubleValue,
(o, v) => o.DoubleValue = v);
public static readonly DirectProperty<Class1, object> FrankProperty =
AvaloniaProperty.RegisterDirect<Class1, object>(
nameof(Frank),
o => o.Frank,
(o, v) => o.Frank = v,
unsetValue: "Kups");
private string _foo = "initial";
private readonly string _bar = "bar";
private int _baz = 5;
private double _doubleValue;
private object _frank;
public string Foo
{
get { return _foo; }
set { SetAndRaise(FooProperty, ref _foo, value); }
}
public string Bar
{
get { return _bar; }
}
public int Baz
{
get { return _baz; }
set { SetAndRaise(BazProperty, ref _baz, value); }
}
public double DoubleValue
{
get { return _doubleValue; }
set { SetAndRaise(DoubleValueProperty, ref _doubleValue, value); }
}
public object Frank
{
get { return _frank; }
set { SetAndRaise(FrankProperty, ref _frank, value); }
}
}
private class Class2 : AvaloniaObject
{
public static readonly DirectProperty<Class2, string> FooProperty =
Class1.FooProperty.AddOwner<Class2>(o => o.Foo, (o, v) => o.Foo = v);
private string _foo = "initial2";
static Class2()
{
}
public string Foo
{
get { return _foo; }
set { SetAndRaise(FooProperty, ref _foo, value); }
}
}
private class TestStackOverflowViewModel : INotifyPropertyChanged
{
public int SetterInvokedCount { get; private set; }
public const int MaxInvokedCount = 1000;
private double _value;
public event PropertyChangedEventHandler PropertyChanged;
public double Value
{
get { return _value; }
set
{
if (_value != value)
{
SetterInvokedCount++;
if (SetterInvokedCount < MaxInvokedCount)
{
_value = (int)value;
if (_value > 75) _value = 75;
if (_value < 25) _value = 25;
}
else
{
_value = value;
}
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Value)));
}
}
}
}
}
}
| |
/////////////////////////////////////////////////////////////////////////////////
// Paint.NET Effect Plugin Name: Barcode //
// Author: Michael J. Sepcot //
// Version: 1.1.1 //
// Release Date: 19 March 2007 //
/////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using PaintDotNet.Effects;
namespace Barcode
{
public class BarcodeConfigDialog : PaintDotNet.Effects.EffectConfigDialog
{
private Button buttonOK;
private GroupBox groupBoxText;
private TextBox textBoxText;
private GroupBox groupBoxEncoding;
private ComboBox comboEncoding;
private Label labelVersion;
private Button buttonCancel;
public BarcodeConfigDialog()
{
InitializeComponent();
}
protected override void InitialInitToken()
{
theEffectToken = new BarcodeConfigToken("", Barcode.CODE_39);
}
protected override void InitTokenFromDialog()
{
((BarcodeConfigToken)EffectToken).TextToEncode = textBoxText.Text;
((BarcodeConfigToken)EffectToken).EncodingType = comboEncoding.SelectedIndex;
}
protected override void InitDialogFromToken(EffectConfigToken effectToken)
{
BarcodeConfigToken token = (BarcodeConfigToken)effectToken;
textBoxText.Text = token.TextToEncode;
comboEncoding.SelectedIndex = token.EncodingType;
}
private void InitializeComponent()
{
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonOK = new System.Windows.Forms.Button();
this.groupBoxText = new System.Windows.Forms.GroupBox();
this.textBoxText = new System.Windows.Forms.TextBox();
this.groupBoxEncoding = new System.Windows.Forms.GroupBox();
this.comboEncoding = new System.Windows.Forms.ComboBox();
this.labelVersion = new System.Windows.Forms.Label();
this.groupBoxText.SuspendLayout();
this.groupBoxEncoding.SuspendLayout();
this.SuspendLayout();
//
// buttonCancel
//
this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonCancel.Location = new System.Drawing.Point(182, 133);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(75, 23);
this.buttonCancel.TabIndex = 1;
this.buttonCancel.Text = "Cancel";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// buttonOK
//
this.buttonOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonOK.Location = new System.Drawing.Point(101, 133);
this.buttonOK.Name = "buttonOK";
this.buttonOK.Size = new System.Drawing.Size(75, 23);
this.buttonOK.TabIndex = 2;
this.buttonOK.Text = "OK";
this.buttonOK.UseVisualStyleBackColor = true;
this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click);
//
// groupBoxText
//
this.groupBoxText.Controls.Add(this.textBoxText);
this.groupBoxText.Location = new System.Drawing.Point(13, 13);
this.groupBoxText.Name = "groupBoxText";
this.groupBoxText.Size = new System.Drawing.Size(244, 50);
this.groupBoxText.TabIndex = 4;
this.groupBoxText.TabStop = false;
this.groupBoxText.Text = "Text To Encode";
//
// textBoxText
//
this.textBoxText.BackColor = System.Drawing.SystemColors.Window;
this.textBoxText.Location = new System.Drawing.Point(6, 19);
this.textBoxText.Name = "textBoxText";
this.textBoxText.Size = new System.Drawing.Size(232, 20);
this.textBoxText.TabIndex = 0;
this.textBoxText.TextChanged += new System.EventHandler(this.textBoxText_TextChanged);
//
// groupBoxEncoding
//
this.groupBoxEncoding.Controls.Add(this.comboEncoding);
this.groupBoxEncoding.Location = new System.Drawing.Point(13, 69);
this.groupBoxEncoding.Name = "groupBoxEncoding";
this.groupBoxEncoding.Size = new System.Drawing.Size(244, 50);
this.groupBoxEncoding.TabIndex = 5;
this.groupBoxEncoding.TabStop = false;
this.groupBoxEncoding.Text = "Encoding Method";
//
// comboEncoding
//
this.comboEncoding.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboEncoding.FormattingEnabled = true;
this.comboEncoding.Items.AddRange(new object[] {
"Code 39",
"Code 39 mod 43",
"Full ASCII Code 39",
"POSTNET"});
this.comboEncoding.Location = new System.Drawing.Point(7, 20);
this.comboEncoding.Name = "comboEncoding";
this.comboEncoding.Size = new System.Drawing.Size(231, 21);
this.comboEncoding.TabIndex = 0;
this.comboEncoding.SelectedIndexChanged += new System.EventHandler(this.comboEncoding_SelectedIndexChanged);
//
// labelVersion
//
this.labelVersion.AutoSize = true;
this.labelVersion.ForeColor = System.Drawing.Color.Gray;
this.labelVersion.Location = new System.Drawing.Point(13, 143);
this.labelVersion.Name = "labelVersion";
this.labelVersion.Size = new System.Drawing.Size(37, 13);
this.labelVersion.TabIndex = 6;
this.labelVersion.Text = "v1.1.1";
//
// BarcodeConfigDialog
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.ClientSize = new System.Drawing.Size(269, 168);
this.Controls.Add(this.labelVersion);
this.Controls.Add(this.groupBoxEncoding);
this.Controls.Add(this.groupBoxText);
this.Controls.Add(this.buttonOK);
this.Controls.Add(this.buttonCancel);
this.Location = new System.Drawing.Point(0, 0);
this.Name = "BarcodeConfigDialog";
this.Text = "Barcode";
this.Controls.SetChildIndex(this.buttonCancel, 0);
this.Controls.SetChildIndex(this.buttonOK, 0);
this.Controls.SetChildIndex(this.groupBoxText, 0);
this.Controls.SetChildIndex(this.groupBoxEncoding, 0);
this.Controls.SetChildIndex(this.labelVersion, 0);
this.groupBoxText.ResumeLayout(false);
this.groupBoxText.PerformLayout();
this.groupBoxEncoding.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
private void buttonOK_Click(object sender, EventArgs e)
{
FinishTokenUpdate();
DialogResult = DialogResult.OK;
this.Close();
}
private void buttonCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void textBoxText_TextChanged(object sender, EventArgs e)
{
if (Barcode.ValidateText(this.textBoxText.Text, this.comboEncoding.SelectedIndex))
{
this.textBoxText.BackColor = System.Drawing.SystemColors.Window;
}
else
{
this.textBoxText.BackColor = System.Drawing.Color.LightPink;
}
FinishTokenUpdate();
}
private void comboEncoding_SelectedIndexChanged(object sender, EventArgs e)
{
if (Barcode.ValidateText(this.textBoxText.Text, this.comboEncoding.SelectedIndex))
{
this.textBoxText.BackColor = System.Drawing.SystemColors.Window;
}
else
{
this.textBoxText.BackColor = System.Drawing.Color.LightPink;
}
FinishTokenUpdate();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
// Copyright (c) 2004 Mainsoft Co.
//
// 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 Xunit;
namespace System.Data.Tests
{
public class ForeignKeyConstraintTest2
{
[Fact]
public void Columns()
{
//int RowCount;
var ds = new DataSet();
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateChildDataTable();
ds.Tables.Add(dtParent);
ds.Tables.Add(dtChild);
ForeignKeyConstraint fc = null;
fc = new ForeignKeyConstraint(dtParent.Columns[0], dtChild.Columns[0]);
// Columns
Assert.Equal(dtChild.Columns[0], fc.Columns[0]);
// Columns count
Assert.Equal(1, fc.Columns.Length);
}
[Fact]
public void Equals()
{
var ds = new DataSet();
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateChildDataTable();
ds.Tables.Add(dtParent);
ds.Tables.Add(dtChild);
dtParent.PrimaryKey = new DataColumn[] { dtParent.Columns[0] };
ds.EnforceConstraints = true;
ForeignKeyConstraint fc1, fc2;
fc1 = new ForeignKeyConstraint(dtParent.Columns[0], dtChild.Columns[0]);
fc2 = new ForeignKeyConstraint(dtParent.Columns[0], dtChild.Columns[1]);
// different columnn
Assert.False(fc1.Equals(fc2));
//Two System.Data.ForeignKeyConstraint are equal if they constrain the same columns.
// same column
fc2 = new ForeignKeyConstraint(dtParent.Columns[0], dtChild.Columns[0]);
Assert.True(fc1.Equals(fc2));
}
[Fact]
public void RelatedColumns()
{
var ds = new DataSet();
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateChildDataTable();
ds.Tables.Add(dtParent);
ds.Tables.Add(dtChild);
ForeignKeyConstraint fc = null;
fc = new ForeignKeyConstraint(dtParent.Columns[0], dtChild.Columns[0]);
// RelatedColumns
Assert.Equal(new DataColumn[] { dtParent.Columns[0] }, fc.RelatedColumns);
}
[Fact]
public void RelatedTable()
{
var ds = new DataSet();
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateChildDataTable();
ds.Tables.Add(dtParent);
ds.Tables.Add(dtChild);
ForeignKeyConstraint fc = null;
fc = new ForeignKeyConstraint(dtParent.Columns[0], dtChild.Columns[0]);
// RelatedTable
Assert.Equal(dtParent, fc.RelatedTable);
}
[Fact]
public void Table()
{
var ds = new DataSet();
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateChildDataTable();
ds.Tables.Add(dtParent);
ds.Tables.Add(dtChild);
ForeignKeyConstraint fc = null;
fc = new ForeignKeyConstraint(dtParent.Columns[0], dtChild.Columns[0]);
// Table
Assert.Equal(dtChild, fc.Table);
}
[Fact]
public new void ToString()
{
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateChildDataTable();
ForeignKeyConstraint fc = null;
fc = new ForeignKeyConstraint(dtParent.Columns[0], dtChild.Columns[0]);
// ToString - default
Assert.Equal(string.Empty, fc.ToString());
fc = new ForeignKeyConstraint("myConstraint", dtParent.Columns[0], dtChild.Columns[0]);
// Tostring - Constraint name
Assert.Equal("myConstraint", fc.ToString());
}
[Fact]
public void acceptRejectRule()
{
DataSet ds = getNewDataSet();
ForeignKeyConstraint fc = new ForeignKeyConstraint(ds.Tables[0].Columns[0], ds.Tables[1].Columns[0]);
fc.AcceptRejectRule = AcceptRejectRule.Cascade;
ds.Tables[1].Constraints.Add(fc);
//Update the parent
ds.Tables[0].Rows[0]["ParentId"] = 777;
Assert.True(ds.Tables[1].Select("ParentId=777").Length > 0);
ds.Tables[0].RejectChanges();
Assert.Equal(0, ds.Tables[1].Select("ParentId=777").Length);
}
private DataSet getNewDataSet()
{
DataSet ds1 = new DataSet();
ds1.Tables.Add(DataProvider.CreateParentDataTable());
ds1.Tables.Add(DataProvider.CreateChildDataTable());
// ds1.Tables.Add(DataProvider.CreateChildDataTable());
ds1.Tables[0].PrimaryKey = new DataColumn[] { ds1.Tables[0].Columns[0] };
return ds1;
}
[Fact]
public void constraintName()
{
var ds = new DataSet();
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateChildDataTable();
ds.Tables.Add(dtParent);
ds.Tables.Add(dtChild);
ForeignKeyConstraint fc = null;
fc = new ForeignKeyConstraint(dtParent.Columns[0], dtChild.Columns[0]);
// default
Assert.Equal(string.Empty, fc.ConstraintName);
fc.ConstraintName = "myConstraint";
// set/get
Assert.Equal("myConstraint", fc.ConstraintName);
}
[Fact]
public void ctor_ParentColChildCol()
{
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateChildDataTable();
var ds = new DataSet();
ds.Tables.Add(dtChild);
ds.Tables.Add(dtParent);
ForeignKeyConstraint fc = null;
// Ctor ArgumentException
AssertExtensions.Throws<ArgumentException>(null, () =>
{
fc = new ForeignKeyConstraint(new DataColumn[] { dtParent.Columns[0] }, new DataColumn[] { dtChild.Columns[0], dtChild.Columns[1] });
});
fc = new ForeignKeyConstraint(new DataColumn[] { dtParent.Columns[0], dtParent.Columns[1] }, new DataColumn[] { dtChild.Columns[0], dtChild.Columns[2] });
// Add constraint to table - ArgumentException
AssertExtensions.Throws<ArgumentException>(null, () =>
{
dtChild.Constraints.Add(fc);
});
// Child Table Constraints Count - two columnns
Assert.Equal(0, dtChild.Constraints.Count);
// Parent Table Constraints Count - two columnns
Assert.Equal(1, dtParent.Constraints.Count);
// DataSet relations Count
Assert.Equal(0, ds.Relations.Count);
dtParent.Constraints.Clear();
dtChild.Constraints.Clear();
fc = new ForeignKeyConstraint(new DataColumn[] { dtParent.Columns[0] }, new DataColumn[] { dtChild.Columns[0] });
// Ctor
Assert.False(fc == null);
// Child Table Constraints Count
Assert.Equal(0, dtChild.Constraints.Count);
// Parent Table Constraints Count
Assert.Equal(0, dtParent.Constraints.Count);
// DataSet relations Count
Assert.Equal(0, ds.Relations.Count);
dtChild.Constraints.Add(fc);
// Child Table Constraints Count, Add
Assert.Equal(1, dtChild.Constraints.Count);
// Parent Table Constraints Count, Add
Assert.Equal(1, dtParent.Constraints.Count);
// DataSet relations Count, Add
Assert.Equal(0, ds.Relations.Count);
// Parent Table Constraints type
Assert.Equal(typeof(UniqueConstraint), dtParent.Constraints[0].GetType());
// Parent Table Constraints type
Assert.Equal(typeof(ForeignKeyConstraint), dtChild.Constraints[0].GetType());
// Parent Table Primary key
Assert.Equal(0, dtParent.PrimaryKey.Length);
dtChild.Constraints.Clear();
dtParent.Constraints.Clear();
ds.Relations.Add(new DataRelation("myRelation", dtParent.Columns[0], dtChild.Columns[0]));
// Relation - Child Table Constraints Count
Assert.Equal(1, dtChild.Constraints.Count);
// Relation - Parent Table Constraints Count
Assert.Equal(1, dtParent.Constraints.Count);
// Relation - Parent Table Constraints type
Assert.Equal(typeof(UniqueConstraint), dtParent.Constraints[0].GetType());
// Relation - Parent Table Constraints type
Assert.Equal(typeof(ForeignKeyConstraint), dtChild.Constraints[0].GetType());
// Relation - Parent Table Primary key
Assert.Equal(0, dtParent.PrimaryKey.Length);
}
[Fact]
public void ctor_NameParentColChildCol()
{
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateChildDataTable();
ForeignKeyConstraint fc = null;
fc = new ForeignKeyConstraint("myForeignKey", dtParent.Columns[0], dtChild.Columns[0]);
// Ctor
Assert.False(fc == null);
// Ctor - name
Assert.Equal("myForeignKey", fc.ConstraintName);
}
[Fact]
public void ctor_NameParentColsChildCols()
{
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateChildDataTable();
ForeignKeyConstraint fc = null;
fc = new ForeignKeyConstraint("myForeignKey", new DataColumn[] { dtParent.Columns[0] }, new DataColumn[] { dtChild.Columns[0] });
// Ctor
Assert.False(fc == null);
// Ctor - name
Assert.Equal("myForeignKey", fc.ConstraintName);
}
[Fact]
public void deleteRule()
{
var ds = new DataSet();
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateChildDataTable();
ds.Tables.Add(dtParent);
ds.Tables.Add(dtChild);
dtParent.PrimaryKey = new DataColumn[] { dtParent.Columns[0] };
ds.EnforceConstraints = true;
ForeignKeyConstraint fc = null;
fc = new ForeignKeyConstraint(dtParent.Columns[0], dtChild.Columns[0]);
//checking default
// Default
Assert.Equal(Rule.Cascade, fc.DeleteRule);
//checking set/get
foreach (Rule rule in Enum.GetValues(typeof(Rule)))
{
// Set/Get - rule
fc.DeleteRule = rule;
Assert.Equal(rule, fc.DeleteRule);
}
dtChild.Constraints.Add(fc);
//checking delete rule
// Rule = None, Delete Exception
fc.DeleteRule = Rule.None;
//Exception = "Cannot delete this row because constraints are enforced on relation Constraint1, and deleting this row will strand child rows."
Assert.Throws<InvalidConstraintException>(() =>
{
dtParent.Rows.Find(1).Delete();
});
// Rule = None, Delete succeed
fc.DeleteRule = Rule.None;
foreach (DataRow dr in dtChild.Select("ParentId = 1"))
dr.Delete();
dtParent.Rows.Find(1).Delete();
Assert.Equal(0, dtParent.Select("ParentId=1").Length);
// Rule = Cascade
fc.DeleteRule = Rule.Cascade;
dtParent.Rows.Find(2).Delete();
Assert.Equal(0, dtChild.Select("ParentId=2").Length);
// Rule = SetNull
DataSet ds1 = new DataSet();
ds1.Tables.Add(DataProvider.CreateParentDataTable());
ds1.Tables.Add(DataProvider.CreateChildDataTable());
ForeignKeyConstraint fc1 = new ForeignKeyConstraint(ds1.Tables[0].Columns[0], ds1.Tables[1].Columns[1]);
fc1.DeleteRule = Rule.SetNull;
ds1.Tables[1].Constraints.Add(fc1);
Assert.Equal(0, ds1.Tables[1].Select("ChildId is null").Length);
ds1.Tables[0].PrimaryKey = new DataColumn[] { ds1.Tables[0].Columns[0] };
ds1.Tables[0].Rows.Find(3).Delete();
ds1.Tables[0].AcceptChanges();
ds1.Tables[1].AcceptChanges();
DataRow[] arr = ds1.Tables[1].Select("ChildId is null");
/*foreach (DataRow dr in arr)
{
Assert.Null(dr["ChildId"]);
}*/
Assert.Equal(4, arr.Length);
// Rule = SetDefault
//fc.DeleteRule = Rule.SetDefault;
ds1 = new DataSet();
ds1.Tables.Add(DataProvider.CreateParentDataTable());
ds1.Tables.Add(DataProvider.CreateChildDataTable());
fc1 = new ForeignKeyConstraint(ds1.Tables[0].Columns[0], ds1.Tables[1].Columns[1]);
fc1.DeleteRule = Rule.SetDefault;
ds1.Tables[1].Constraints.Add(fc1);
ds1.Tables[1].Columns[1].DefaultValue = "777";
//Add new row --> in order to apply the forigen key rules
DataRow dr2 = ds1.Tables[0].NewRow();
dr2["ParentId"] = 777;
ds1.Tables[0].Rows.Add(dr2);
ds1.Tables[0].PrimaryKey = new DataColumn[] { ds1.Tables[0].Columns[0] };
ds1.Tables[0].Rows.Find(3).Delete();
Assert.Equal(4, ds1.Tables[1].Select("ChildId=777").Length);
}
[Fact]
public void extendedProperties()
{
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateParentDataTable();
ForeignKeyConstraint fc = null;
fc = new ForeignKeyConstraint(dtParent.Columns[0], dtChild.Columns[0]);
PropertyCollection pc = fc.ExtendedProperties;
// Checking ExtendedProperties default
Assert.True(fc != null);
// Checking ExtendedProperties count
Assert.Equal(0, pc.Count);
}
[Fact]
public void ctor_DclmDclm()
{
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateChildDataTable();
var ds = new DataSet();
ds.Tables.Add(dtChild);
ds.Tables.Add(dtParent);
ForeignKeyConstraint fc = null;
fc = new ForeignKeyConstraint(dtParent.Columns[0], dtChild.Columns[0]);
Assert.False(fc == null);
Assert.Equal(0, dtChild.Constraints.Count);
Assert.Equal(0, dtParent.Constraints.Count);
Assert.Equal(0, ds.Relations.Count);
dtChild.Constraints.Add(fc);
Assert.Equal(1, dtChild.Constraints.Count);
Assert.Equal(1, dtParent.Constraints.Count);
Assert.Equal(0, ds.Relations.Count);
Assert.Equal(typeof(UniqueConstraint), dtParent.Constraints[0].GetType());
Assert.Equal(typeof(ForeignKeyConstraint), dtChild.Constraints[0].GetType());
Assert.Equal(0, dtParent.PrimaryKey.Length);
dtChild.Constraints.Clear();
dtParent.Constraints.Clear();
ds.Relations.Add(new DataRelation("myRelation", dtParent.Columns[0], dtChild.Columns[0]));
Assert.Equal(1, dtChild.Constraints.Count);
Assert.Equal(1, dtParent.Constraints.Count);
Assert.Equal(typeof(UniqueConstraint), dtParent.Constraints[0].GetType());
Assert.Equal(typeof(ForeignKeyConstraint), dtChild.Constraints[0].GetType());
Assert.Equal(0, dtParent.PrimaryKey.Length);
}
[Fact]
public void ctor_DclmDclm1()
{
Assert.Throws<NullReferenceException>(() =>
{
ForeignKeyConstraint fc = new ForeignKeyConstraint(null, (DataColumn)null);
});
}
[Fact]
public void ctor_DclmDclm2()
{
AssertExtensions.Throws<ArgumentException>(null, () =>
{
var ds = new DataSet();
ds.Tables.Add(DataProvider.CreateParentDataTable());
ds.Tables.Add(DataProvider.CreateChildDataTable());
ds.Tables["Parent"].Columns["ParentId"].Expression = "2";
ForeignKeyConstraint fc = new ForeignKeyConstraint(ds.Tables[0].Columns[0], ds.Tables[1].Columns[0]);
});
}
[Fact]
public void ctor_DclmDclm3()
{
AssertExtensions.Throws<ArgumentException>(null, () =>
{
var ds = new DataSet();
ds.Tables.Add(DataProvider.CreateParentDataTable());
ds.Tables.Add(DataProvider.CreateChildDataTable());
ds.Tables["Child"].Columns["ParentId"].Expression = "2";
ForeignKeyConstraint fc = new ForeignKeyConstraint(ds.Tables[0].Columns[0], ds.Tables[1].Columns[0]);
});
}
[Fact]
public void UpdateRule1()
{
DataSet ds = GetNewDataSet();
ForeignKeyConstraint fc = new ForeignKeyConstraint(ds.Tables[0].Columns[0], ds.Tables[1].Columns[0]);
fc.UpdateRule = Rule.Cascade;
ds.Tables[1].Constraints.Add(fc);
//Changing parent row
ds.Tables[0].Rows.Find(1)["ParentId"] = 8;
ds.Tables[0].AcceptChanges();
ds.Tables[1].AcceptChanges();
//Checking the table
Assert.True(ds.Tables[1].Select("ParentId=8").Length > 0);
}
[Fact]
public void UpdateRule2()
{
Assert.Throws<ConstraintException>(() =>
{
DataSet ds = GetNewDataSet();
ds.Tables[0].PrimaryKey = null;
ForeignKeyConstraint fc = new ForeignKeyConstraint(ds.Tables[0].Columns[0], ds.Tables[1].Columns[0]);
fc.UpdateRule = Rule.None;
ds.Tables[1].Constraints.Add(fc);
//Changing parent row
ds.Tables[0].Rows[0]["ParentId"] = 5;
/*ds.Tables[0].AcceptChanges();
ds.Tables[1].AcceptChanges();
//Checking the table
Compare(ds.Tables[1].Select("ParentId=8").Length ,0);*/
});
}
[Fact]
public void UpdateRule3()
{
DataSet ds = GetNewDataSet();
ForeignKeyConstraint fc = new ForeignKeyConstraint(ds.Tables[0].Columns[0], ds.Tables[1].Columns[1]);
fc.UpdateRule = Rule.SetDefault;
ds.Tables[1].Constraints.Add(fc);
//Changing parent row
ds.Tables[1].Columns[1].DefaultValue = "777";
//Add new row --> in order to apply the forigen key rules
DataRow dr = ds.Tables[0].NewRow();
dr["ParentId"] = 777;
ds.Tables[0].Rows.Add(dr);
ds.Tables[0].Rows.Find(1)["ParentId"] = 8;
ds.Tables[0].AcceptChanges();
ds.Tables[1].AcceptChanges();
//Checking the table
Assert.True(ds.Tables[1].Select("ChildId=777").Length > 0);
}
[Fact]
public void UpdateRule4()
{
DataSet ds = GetNewDataSet();
ForeignKeyConstraint fc = new ForeignKeyConstraint(ds.Tables[0].Columns[0], ds.Tables[1].Columns[0]);
fc.UpdateRule = Rule.SetNull;
ds.Tables[1].Constraints.Add(fc);
//Changing parent row
ds.Tables[0].Rows.Find(1)["ParentId"] = 8;
ds.Tables[0].AcceptChanges();
ds.Tables[1].AcceptChanges();
//Checking the table
Assert.True(ds.Tables[1].Select("ParentId is null").Length > 0);
}
private DataSet GetNewDataSet()
{
DataSet ds1 = new DataSet();
ds1.Tables.Add(DataProvider.CreateParentDataTable());
ds1.Tables.Add(DataProvider.CreateChildDataTable());
ds1.Tables[0].PrimaryKey = new DataColumn[] { ds1.Tables[0].Columns[0] };
return ds1;
}
[Fact]
public void ForeignConstraint_DateTimeModeTest()
{
DataTable t1 = new DataTable("t1");
t1.Columns.Add("col", typeof(DateTime));
DataTable t2 = new DataTable("t2");
t2.Columns.Add("col", typeof(DateTime));
t2.Columns[0].DateTimeMode = DataSetDateTime.Unspecified;
// DataColumn type shud match, and no exception shud be raised
t2.Constraints.Add("fk", t1.Columns[0], t2.Columns[0]);
t2.Constraints.Clear();
t2.Columns[0].DateTimeMode = DataSetDateTime.Local;
try
{
// DataColumn type shud not match, and exception shud be raised
t2.Constraints.Add("fk", t1.Columns[0], t2.Columns[0]);
Assert.False(true);
}
catch (InvalidOperationException e) { }
}
[Fact]
public void ParentChildSameColumn()
{
DataTable dataTable = new DataTable("Menu");
DataColumn colID = dataTable.Columns.Add("ID", typeof(int));
DataColumn colCulture = dataTable.Columns.Add("Culture", typeof(string));
dataTable.Columns.Add("Name", typeof(string));
DataColumn colParentID = dataTable.Columns.Add("ParentID", typeof(int));
// table PK (ID, Culture)
dataTable.Constraints.Add(new UniqueConstraint(
"MenuPK",
new DataColumn[] { colID, colCulture },
true));
// add a FK referencing the same table: (ID, Culture) <- (ParentID, Culture)
ForeignKeyConstraint fkc = new ForeignKeyConstraint(
"MenuParentFK",
new DataColumn[] { colID, colCulture },
new DataColumn[] { colParentID, colCulture });
dataTable.Constraints.Add(fkc);
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the cloudformation-2010-05-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.CloudFormation.Model
{
/// <summary>
/// The StackEvent data type.
/// </summary>
public partial class StackEvent
{
private string _eventId;
private string _logicalResourceId;
private string _physicalResourceId;
private string _resourceProperties;
private ResourceStatus _resourceStatus;
private string _resourceStatusReason;
private string _resourceType;
private string _stackId;
private string _stackName;
private DateTime? _timestamp;
/// <summary>
/// Gets and sets the property EventId.
/// <para>
/// The unique ID of this event.
/// </para>
/// </summary>
public string EventId
{
get { return this._eventId; }
set { this._eventId = value; }
}
// Check to see if EventId property is set
internal bool IsSetEventId()
{
return this._eventId != null;
}
/// <summary>
/// Gets and sets the property LogicalResourceId.
/// <para>
/// The logical name of the resource specified in the template.
/// </para>
/// </summary>
public string LogicalResourceId
{
get { return this._logicalResourceId; }
set { this._logicalResourceId = value; }
}
// Check to see if LogicalResourceId property is set
internal bool IsSetLogicalResourceId()
{
return this._logicalResourceId != null;
}
/// <summary>
/// Gets and sets the property PhysicalResourceId.
/// <para>
/// The name or unique identifier associated with the physical instance of the resource.
/// </para>
/// </summary>
public string PhysicalResourceId
{
get { return this._physicalResourceId; }
set { this._physicalResourceId = value; }
}
// Check to see if PhysicalResourceId property is set
internal bool IsSetPhysicalResourceId()
{
return this._physicalResourceId != null;
}
/// <summary>
/// Gets and sets the property ResourceProperties.
/// <para>
/// BLOB of the properties used to create the resource.
/// </para>
/// </summary>
public string ResourceProperties
{
get { return this._resourceProperties; }
set { this._resourceProperties = value; }
}
// Check to see if ResourceProperties property is set
internal bool IsSetResourceProperties()
{
return this._resourceProperties != null;
}
/// <summary>
/// Gets and sets the property ResourceStatus.
/// <para>
/// Current status of the resource.
/// </para>
/// </summary>
public ResourceStatus ResourceStatus
{
get { return this._resourceStatus; }
set { this._resourceStatus = value; }
}
// Check to see if ResourceStatus property is set
internal bool IsSetResourceStatus()
{
return this._resourceStatus != null;
}
/// <summary>
/// Gets and sets the property ResourceStatusReason.
/// <para>
/// Success/failure message associated with the resource.
/// </para>
/// </summary>
public string ResourceStatusReason
{
get { return this._resourceStatusReason; }
set { this._resourceStatusReason = value; }
}
// Check to see if ResourceStatusReason property is set
internal bool IsSetResourceStatusReason()
{
return this._resourceStatusReason != null;
}
/// <summary>
/// Gets and sets the property ResourceType.
/// <para>
/// Type of resource. (For more information, go to <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html">
/// AWS Resource Types Reference</a> in the AWS CloudFormation User Guide.)
/// </para>
/// </summary>
public string ResourceType
{
get { return this._resourceType; }
set { this._resourceType = value; }
}
// Check to see if ResourceType property is set
internal bool IsSetResourceType()
{
return this._resourceType != null;
}
/// <summary>
/// Gets and sets the property StackId.
/// <para>
/// The unique ID name of the instance of the stack.
/// </para>
/// </summary>
public string StackId
{
get { return this._stackId; }
set { this._stackId = value; }
}
// Check to see if StackId property is set
internal bool IsSetStackId()
{
return this._stackId != null;
}
/// <summary>
/// Gets and sets the property StackName.
/// <para>
/// The name associated with a stack.
/// </para>
/// </summary>
public string StackName
{
get { return this._stackName; }
set { this._stackName = value; }
}
// Check to see if StackName property is set
internal bool IsSetStackName()
{
return this._stackName != null;
}
/// <summary>
/// Gets and sets the property Timestamp.
/// <para>
/// Time the status was updated.
/// </para>
/// </summary>
public DateTime Timestamp
{
get { return this._timestamp.GetValueOrDefault(); }
set { this._timestamp = value; }
}
// Check to see if Timestamp property is set
internal bool IsSetTimestamp()
{
return this._timestamp.HasValue;
}
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
namespace PCSComUtils.Common.DS
{
public class Sys_PeriodDS
{
public Sys_PeriodDS()
{
}
private const string THIS = "PCSComUtils.Common.DS.Sys_PeriodDS";
//**************************************************************************
/// <Description>
/// This method uses to add data to Sys_Period
/// </Description>
/// <Inputs>
/// Sys_PeriodVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Thursday, May 05, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
Sys_PeriodVO objObject = (Sys_PeriodVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql= "INSERT INTO Sys_Period("
+ Sys_PeriodTable.FROMDATE_FLD + ","
+ Sys_PeriodTable.TODATE_FLD + ","
+ Sys_PeriodTable.ACTIVATE_FLD + ")"
+ "VALUES(?,?,?)";
ocmdPCS.Parameters.Add(new OleDbParameter(Sys_PeriodTable.FROMDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[Sys_PeriodTable.FROMDATE_FLD].Value = objObject.FromDate;
ocmdPCS.Parameters.Add(new OleDbParameter(Sys_PeriodTable.TODATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[Sys_PeriodTable.TODATE_FLD].Value = objObject.ToDate;
ocmdPCS.Parameters.Add(new OleDbParameter(Sys_PeriodTable.ACTIVATE_FLD, OleDbType.Boolean));
ocmdPCS.Parameters[Sys_PeriodTable.ACTIVATE_FLD].Value = objObject.Activate;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public int AddAndReturnID(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".AddAndReturnID()";
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
Sys_PeriodVO objObject = (Sys_PeriodVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql= "INSERT INTO Sys_Period("
+ Sys_PeriodTable.FROMDATE_FLD + ","
+ Sys_PeriodTable.TODATE_FLD + ","
+ Sys_PeriodTable.ACTIVATE_FLD + ")"
+ "VALUES(?,?,?)"
+ "; SELECT @@IDENTITY as LatestID";
ocmdPCS.Parameters.Add(new OleDbParameter(Sys_PeriodTable.FROMDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[Sys_PeriodTable.FROMDATE_FLD].Value = objObject.FromDate;
ocmdPCS.Parameters.Add(new OleDbParameter(Sys_PeriodTable.TODATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[Sys_PeriodTable.TODATE_FLD].Value = objObject.ToDate;
ocmdPCS.Parameters.Add(new OleDbParameter(Sys_PeriodTable.ACTIVATE_FLD, OleDbType.Boolean));
ocmdPCS.Parameters[Sys_PeriodTable.ACTIVATE_FLD].Value = objObject.Activate;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
return Convert.ToInt32(ocmdPCS.ExecuteScalar());
}
catch(OleDbException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
else
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
else
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete data from Sys_Period
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(int pintID)
{
const string METHOD_NAME = THIS + ".Delete()";
string strSql = String.Empty;
strSql= "DELETE " + Sys_PeriodTable.TABLE_NAME + " WHERE " + "PeriodID" + "=" + pintID.ToString();
OleDbConnection oconPCS=null;
OleDbCommand ocmdPCS =null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from Sys_Period
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// Sys_PeriodVO
/// </Outputs>
/// <Returns>
/// Sys_PeriodVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Thursday, May 05, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ Sys_PeriodTable.PERIODID_FLD + ","
+ Sys_PeriodTable.FROMDATE_FLD + ","
+ Sys_PeriodTable.TODATE_FLD + ","
+ Sys_PeriodTable.ACTIVATE_FLD
+ " FROM " + Sys_PeriodTable.TABLE_NAME
+" WHERE " + Sys_PeriodTable.PERIODID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
Sys_PeriodVO objObject = new Sys_PeriodVO();
while (odrPCS.Read())
{
objObject.PeriodID = int.Parse(odrPCS[Sys_PeriodTable.PERIODID_FLD].ToString().Trim());
objObject.FromDate = DateTime.Parse(odrPCS[Sys_PeriodTable.FROMDATE_FLD].ToString().Trim());
objObject.ToDate = DateTime.Parse(odrPCS[Sys_PeriodTable.TODATE_FLD].ToString().Trim());
objObject.Activate = bool.Parse(odrPCS[Sys_PeriodTable.ACTIVATE_FLD].ToString().Trim());
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from Sys_Period
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// Sys_PeriodVO
/// </Outputs>
/// <Returns>
/// Sys_PeriodVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Thursday, May 05, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO()
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ Sys_PeriodTable.PERIODID_FLD + ","
+ Sys_PeriodTable.FROMDATE_FLD + ","
+ Sys_PeriodTable.TODATE_FLD + ","
+ Sys_PeriodTable.ACTIVATE_FLD
+ " FROM " + Sys_PeriodTable.TABLE_NAME
+" WHERE " + Sys_PeriodTable.ACTIVATE_FLD + "= 1";
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
Sys_PeriodVO objObject = new Sys_PeriodVO();
while (odrPCS.Read())
{
objObject.PeriodID = int.Parse(odrPCS[Sys_PeriodTable.PERIODID_FLD].ToString().Trim());
objObject.FromDate = DateTime.Parse(odrPCS[Sys_PeriodTable.FROMDATE_FLD].ToString().Trim());
objObject.ToDate = DateTime.Parse(odrPCS[Sys_PeriodTable.TODATE_FLD].ToString().Trim());
objObject.Activate = bool.Parse(odrPCS[Sys_PeriodTable.ACTIVATE_FLD].ToString().Trim());
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to change status of activate field in Sys_Period
/// </Description>
/// <Inputs>
/// Sys_PeriodVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void ChangeStatusOfActivate(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".ChangeStatusOfActivate()";
Sys_PeriodVO objObject = (Sys_PeriodVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql= "UPDATE Sys_Period SET "
+ Sys_PeriodTable.FROMDATE_FLD + "= ?" + ","
+ Sys_PeriodTable.TODATE_FLD + "= ?" + ","
+ Sys_PeriodTable.ACTIVATE_FLD + "= ?"
+" WHERE " + Sys_PeriodTable.PERIODID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(Sys_PeriodTable.FROMDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[Sys_PeriodTable.FROMDATE_FLD].Value = objObject.FromDate;
ocmdPCS.Parameters.Add(new OleDbParameter(Sys_PeriodTable.TODATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[Sys_PeriodTable.TODATE_FLD].Value = objObject.ToDate;
ocmdPCS.Parameters.Add(new OleDbParameter(Sys_PeriodTable.ACTIVATE_FLD, OleDbType.Boolean));
ocmdPCS.Parameters[Sys_PeriodTable.ACTIVATE_FLD].Value = objObject.Activate;
ocmdPCS.Parameters.Add(new OleDbParameter(Sys_PeriodTable.PERIODID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[Sys_PeriodTable.PERIODID_FLD].Value = objObject.PeriodID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update data to Sys_Period
/// </Description>
/// <Inputs>
/// Sys_PeriodVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
Sys_PeriodVO objObject = (Sys_PeriodVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql= "UPDATE Sys_Period SET "
+ Sys_PeriodTable.FROMDATE_FLD + "= ?" + ","
+ Sys_PeriodTable.TODATE_FLD + "= ?" + ","
+ Sys_PeriodTable.ACTIVATE_FLD + "= ?"
+" WHERE " + Sys_PeriodTable.PERIODID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(Sys_PeriodTable.FROMDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[Sys_PeriodTable.FROMDATE_FLD].Value = objObject.FromDate;
ocmdPCS.Parameters.Add(new OleDbParameter(Sys_PeriodTable.TODATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[Sys_PeriodTable.TODATE_FLD].Value = objObject.ToDate;
ocmdPCS.Parameters.Add(new OleDbParameter(Sys_PeriodTable.ACTIVATE_FLD, OleDbType.Boolean));
ocmdPCS.Parameters[Sys_PeriodTable.ACTIVATE_FLD].Value = objObject.Activate;
ocmdPCS.Parameters.Add(new OleDbParameter(Sys_PeriodTable.PERIODID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[Sys_PeriodTable.PERIODID_FLD].Value = objObject.PeriodID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from Sys_Period
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Thursday, May 05, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List()
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ Sys_PeriodTable.PERIODID_FLD + ","
+ Sys_PeriodTable.FROMDATE_FLD + ","
+ Sys_PeriodTable.TODATE_FLD + ","
+ Sys_PeriodTable.ACTIVATE_FLD
+ " FROM " + Sys_PeriodTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,Sys_PeriodTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update a DataSet
/// </Description>
/// <Inputs>
/// DataSet
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Thursday, May 05, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateDataSet(DataSet pData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS =null;
OleDbCommandBuilder odcbPCS ;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql= "SELECT "
+ Sys_PeriodTable.PERIODID_FLD + ","
+ Sys_PeriodTable.FROMDATE_FLD + ","
+ Sys_PeriodTable.TODATE_FLD + ","
+ Sys_PeriodTable.ACTIVATE_FLD
+ " FROM " + Sys_PeriodTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pData.EnforceConstraints = false;
odadPCS.Update(pData,Sys_PeriodTable.TABLE_NAME);
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public void ActiveNextPeriod(object pobjPeriod)
{
const string METHOD_NAME = THIS + ".ActiveNextPeriod()";
Sys_PeriodVO voPeriod = (Sys_PeriodVO)pobjPeriod;
DateTime dtmFromDate = voPeriod.FromDate.AddMonths(1);
dtmFromDate = new DateTime(dtmFromDate.Year, dtmFromDate.Month, dtmFromDate.Day);
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = "UPDATE Sys_Period SET Activate = 1"
+ " WHERE FromDate = ?";
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Parameters.Add(new OleDbParameter(Sys_PeriodTable.FROMDATE_FLD, OleDbType.Date)).Value = dtmFromDate;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
else
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
else
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public void CloseAllPeriod(object pobjPeriod)
{
const string METHOD_NAME = THIS + ".ActiveNextPeriod()";
Sys_PeriodVO voPeriod = (Sys_PeriodVO)pobjPeriod;
DateTime dtmFromDate = voPeriod.FromDate.Date;
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = "UPDATE Sys_Period SET Activate = 0"
+ " WHERE FromDate <> ?";
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Parameters.Add(new OleDbParameter(Sys_PeriodTable.FROMDATE_FLD, OleDbType.Date)).Value = dtmFromDate;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
else
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
else
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public bool IsPeriodOverlap(object pobjPeriod)
{
const string METHOD_NAME = THIS + ".IsPeriodOverlap()";
Sys_PeriodVO voPeriod = (Sys_PeriodVO)pobjPeriod;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = "SELECT Count(*) "
+ " FROM " + Sys_PeriodTable.TABLE_NAME
+ " WHERE (" + Sys_PeriodTable.PERIODID_FLD + " <> " + voPeriod.PeriodID + ") "
+ " AND ((" + Sys_PeriodTable.FROMDATE_FLD + " BETWEEN '" + voPeriod.FromDate.ToString("yyyy-MM-dd") + "' AND '" + voPeriod.ToDate.ToString("yyyy-MM-dd") + "')"
+ " OR (" + Sys_PeriodTable.TODATE_FLD + " BETWEEN '" + voPeriod.FromDate.ToString("yyyy-MM-dd") + "' AND '" + voPeriod.ToDate.ToString("yyyy-MM-dd") + "')"
+ " OR ('" + voPeriod.FromDate.ToString("yyyy-MM-dd") + "' BETWEEN " + Sys_PeriodTable.FROMDATE_FLD + " AND " + Sys_PeriodTable.TODATE_FLD + ")"
+ " OR ('" + voPeriod.ToDate.ToString("yyyy-MM-dd") + "' BETWEEN " + Sys_PeriodTable.FROMDATE_FLD + " AND " + Sys_PeriodTable.TODATE_FLD + "))";
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
object objReturn = ocmdPCS.ExecuteScalar();
if (objReturn == null)
{
return false;
}
else
{
if (int.Parse(objReturn.ToString()) > 0 )
{
return true;
}
else
{
return false;
}
}
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
}
}
| |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.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.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class GetDs3TargetFailuresSpectraS3Request : Ds3Request
{
private string _errorMessage;
public string ErrorMessage
{
get { return _errorMessage; }
set { WithErrorMessage(value); }
}
private bool? _lastPage;
public bool? LastPage
{
get { return _lastPage; }
set { WithLastPage(value); }
}
private int? _pageLength;
public int? PageLength
{
get { return _pageLength; }
set { WithPageLength(value); }
}
private int? _pageOffset;
public int? PageOffset
{
get { return _pageOffset; }
set { WithPageOffset(value); }
}
private string _pageStartMarker;
public string PageStartMarker
{
get { return _pageStartMarker; }
set { WithPageStartMarker(value); }
}
private string _targetId;
public string TargetId
{
get { return _targetId; }
set { WithTargetId(value); }
}
private TargetFailureType? _type;
public TargetFailureType? Type
{
get { return _type; }
set { WithType(value); }
}
public GetDs3TargetFailuresSpectraS3Request WithErrorMessage(string errorMessage)
{
this._errorMessage = errorMessage;
if (errorMessage != null)
{
this.QueryParams.Add("error_message", errorMessage);
}
else
{
this.QueryParams.Remove("error_message");
}
return this;
}
public GetDs3TargetFailuresSpectraS3Request WithLastPage(bool? lastPage)
{
this._lastPage = lastPage;
if (lastPage != null)
{
this.QueryParams.Add("last_page", lastPage.ToString());
}
else
{
this.QueryParams.Remove("last_page");
}
return this;
}
public GetDs3TargetFailuresSpectraS3Request WithPageLength(int? pageLength)
{
this._pageLength = pageLength;
if (pageLength != null)
{
this.QueryParams.Add("page_length", pageLength.ToString());
}
else
{
this.QueryParams.Remove("page_length");
}
return this;
}
public GetDs3TargetFailuresSpectraS3Request WithPageOffset(int? pageOffset)
{
this._pageOffset = pageOffset;
if (pageOffset != null)
{
this.QueryParams.Add("page_offset", pageOffset.ToString());
}
else
{
this.QueryParams.Remove("page_offset");
}
return this;
}
public GetDs3TargetFailuresSpectraS3Request WithPageStartMarker(Guid? pageStartMarker)
{
this._pageStartMarker = pageStartMarker.ToString();
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker.ToString());
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetDs3TargetFailuresSpectraS3Request WithPageStartMarker(string pageStartMarker)
{
this._pageStartMarker = pageStartMarker;
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker);
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetDs3TargetFailuresSpectraS3Request WithTargetId(Guid? targetId)
{
this._targetId = targetId.ToString();
if (targetId != null)
{
this.QueryParams.Add("target_id", targetId.ToString());
}
else
{
this.QueryParams.Remove("target_id");
}
return this;
}
public GetDs3TargetFailuresSpectraS3Request WithTargetId(string targetId)
{
this._targetId = targetId;
if (targetId != null)
{
this.QueryParams.Add("target_id", targetId);
}
else
{
this.QueryParams.Remove("target_id");
}
return this;
}
public GetDs3TargetFailuresSpectraS3Request WithType(TargetFailureType? type)
{
this._type = type;
if (type != null)
{
this.QueryParams.Add("type", type.ToString());
}
else
{
this.QueryParams.Remove("type");
}
return this;
}
public GetDs3TargetFailuresSpectraS3Request()
{
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.GET;
}
}
internal override string Path
{
get
{
return "/_rest_/ds3_target_failure";
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace WindowsAuthorizationService.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
#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.Diagnostics;
using Newtonsoft.Json.Utilities;
using System.Globalization;
#if HAVE_DYNAMIC
using System.Dynamic;
using System.Linq.Expressions;
#endif
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
namespace Newtonsoft.Json.Linq
{
/// <summary>
/// Represents a value in JSON (string, integer, date, etc).
/// </summary>
public partial class JValue : JToken, IEquatable<JValue>, IFormattable, IComparable, IComparable<JValue>
#if HAVE_ICONVERTIBLE
, IConvertible
#endif
{
private JTokenType _valueType;
private object _value;
internal JValue(object value, JTokenType type)
{
_value = value;
_valueType = type;
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class from another <see cref="JValue"/> object.
/// </summary>
/// <param name="other">A <see cref="JValue"/> object to copy from.</param>
public JValue(JValue other)
: this(other.Value, other.Type)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(long value)
: this(value, JTokenType.Integer)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(decimal value)
: this(value, JTokenType.Float)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(char value)
: this(value, JTokenType.String)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
[CLSCompliant(false)]
public JValue(ulong value)
: this(value, JTokenType.Integer)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(double value)
: this(value, JTokenType.Float)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(float value)
: this(value, JTokenType.Float)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(DateTime value)
: this(value, JTokenType.Date)
{
}
#if HAVE_DATE_TIME_OFFSET
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(DateTimeOffset value)
: this(value, JTokenType.Date)
{
}
#endif
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(bool value)
: this(value, JTokenType.Boolean)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(string value)
: this(value, JTokenType.String)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(Guid value)
: this(value, JTokenType.Guid)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(Uri value)
: this(value, (value != null) ? JTokenType.Uri : JTokenType.Null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(TimeSpan value)
: this(value, JTokenType.TimeSpan)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(object value)
: this(value, GetValueType(null, value))
{
}
internal override bool DeepEquals(JToken node)
{
JValue other = node as JValue;
if (other == null)
{
return false;
}
if (other == this)
{
return true;
}
return ValuesEquals(this, other);
}
/// <summary>
/// Gets a value indicating whether this token has child tokens.
/// </summary>
/// <value>
/// <c>true</c> if this token has child values; otherwise, <c>false</c>.
/// </value>
public override bool HasValues
{
get { return false; }
}
#if HAVE_BIG_INTEGER
private static int CompareBigInteger(BigInteger i1, object i2)
{
int result = i1.CompareTo(ConvertUtils.ToBigInteger(i2));
if (result != 0)
{
return result;
}
// converting a fractional number to a BigInteger will lose the fraction
// check for fraction if result is two numbers are equal
if (i2 is decimal)
{
decimal d = (decimal)i2;
return (0m).CompareTo(Math.Abs(d - Math.Truncate(d)));
}
else if (i2 is double || i2 is float)
{
double d = Convert.ToDouble(i2, CultureInfo.InvariantCulture);
return (0d).CompareTo(Math.Abs(d - Math.Truncate(d)));
}
return result;
}
#endif
internal static int Compare(JTokenType valueType, object objA, object objB)
{
if (objA == objB)
{
return 0;
}
if (objB == null)
{
return 1;
}
if (objA == null)
{
return -1;
}
switch (valueType)
{
case JTokenType.Integer:
#if HAVE_BIG_INTEGER
if (objA is BigInteger)
{
return CompareBigInteger((BigInteger)objA, objB);
}
if (objB is BigInteger)
{
return -CompareBigInteger((BigInteger)objB, objA);
}
#endif
if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
{
return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture));
}
else if (objA is float || objB is float || objA is double || objB is double)
{
return CompareFloat(objA, objB);
}
else
{
return Convert.ToInt64(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToInt64(objB, CultureInfo.InvariantCulture));
}
case JTokenType.Float:
#if HAVE_BIG_INTEGER
if (objA is BigInteger)
{
return CompareBigInteger((BigInteger)objA, objB);
}
if (objB is BigInteger)
{
return -CompareBigInteger((BigInteger)objB, objA);
}
#endif
if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
{
return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture));
}
return CompareFloat(objA, objB);
case JTokenType.Comment:
case JTokenType.String:
case JTokenType.Raw:
string s1 = Convert.ToString(objA, CultureInfo.InvariantCulture);
string s2 = Convert.ToString(objB, CultureInfo.InvariantCulture);
return string.CompareOrdinal(s1, s2);
case JTokenType.Boolean:
bool b1 = Convert.ToBoolean(objA, CultureInfo.InvariantCulture);
bool b2 = Convert.ToBoolean(objB, CultureInfo.InvariantCulture);
return b1.CompareTo(b2);
case JTokenType.Date:
#if HAVE_DATE_TIME_OFFSET
if (objA is DateTime)
{
#endif
DateTime date1 = (DateTime)objA;
DateTime date2;
#if HAVE_DATE_TIME_OFFSET
if (objB is DateTimeOffset)
{
date2 = ((DateTimeOffset)objB).DateTime;
}
else
#endif
{
date2 = Convert.ToDateTime(objB, CultureInfo.InvariantCulture);
}
return date1.CompareTo(date2);
#if HAVE_DATE_TIME_OFFSET
}
else
{
DateTimeOffset date1 = (DateTimeOffset)objA;
DateTimeOffset date2;
if (objB is DateTimeOffset)
{
date2 = (DateTimeOffset)objB;
}
else
{
date2 = new DateTimeOffset(Convert.ToDateTime(objB, CultureInfo.InvariantCulture));
}
return date1.CompareTo(date2);
}
#endif
case JTokenType.Bytes:
byte[] bytes2 = objB as byte[];
if (bytes2 == null)
{
throw new ArgumentException("Object must be of type byte[].");
}
byte[] bytes1 = objA as byte[];
Debug.Assert(bytes1 != null);
return MiscellaneousUtils.ByteArrayCompare(bytes1, bytes2);
case JTokenType.Guid:
if (!(objB is Guid))
{
throw new ArgumentException("Object must be of type Guid.");
}
Guid guid1 = (Guid)objA;
Guid guid2 = (Guid)objB;
return guid1.CompareTo(guid2);
case JTokenType.Uri:
Uri uri2 = objB as Uri;
if (uri2 == null)
{
throw new ArgumentException("Object must be of type Uri.");
}
Uri uri1 = (Uri)objA;
return Comparer<string>.Default.Compare(uri1.ToString(), uri2.ToString());
case JTokenType.TimeSpan:
if (!(objB is TimeSpan))
{
throw new ArgumentException("Object must be of type TimeSpan.");
}
TimeSpan ts1 = (TimeSpan)objA;
TimeSpan ts2 = (TimeSpan)objB;
return ts1.CompareTo(ts2);
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(valueType), valueType, "Unexpected value type: {0}".FormatWith(CultureInfo.InvariantCulture, valueType));
}
}
private static int CompareFloat(object objA, object objB)
{
double d1 = Convert.ToDouble(objA, CultureInfo.InvariantCulture);
double d2 = Convert.ToDouble(objB, CultureInfo.InvariantCulture);
// take into account possible floating point errors
if (MathUtils.ApproxEquals(d1, d2))
{
return 0;
}
return d1.CompareTo(d2);
}
#if HAVE_EXPRESSIONS
private static bool Operation(ExpressionType operation, object objA, object objB, out object result)
{
if (objA is string || objB is string)
{
if (operation == ExpressionType.Add || operation == ExpressionType.AddAssign)
{
result = objA?.ToString() + objB?.ToString();
return true;
}
}
#if HAVE_BIG_INTEGER
if (objA is BigInteger || objB is BigInteger)
{
if (objA == null || objB == null)
{
result = null;
return true;
}
// not that this will lose the fraction
// BigInteger doesn't have operators with non-integer types
BigInteger i1 = ConvertUtils.ToBigInteger(objA);
BigInteger i2 = ConvertUtils.ToBigInteger(objB);
switch (operation)
{
case ExpressionType.Add:
case ExpressionType.AddAssign:
result = i1 + i2;
return true;
case ExpressionType.Subtract:
case ExpressionType.SubtractAssign:
result = i1 - i2;
return true;
case ExpressionType.Multiply:
case ExpressionType.MultiplyAssign:
result = i1 * i2;
return true;
case ExpressionType.Divide:
case ExpressionType.DivideAssign:
result = i1 / i2;
return true;
}
}
else
#endif
if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
{
if (objA == null || objB == null)
{
result = null;
return true;
}
decimal d1 = Convert.ToDecimal(objA, CultureInfo.InvariantCulture);
decimal d2 = Convert.ToDecimal(objB, CultureInfo.InvariantCulture);
switch (operation)
{
case ExpressionType.Add:
case ExpressionType.AddAssign:
result = d1 + d2;
return true;
case ExpressionType.Subtract:
case ExpressionType.SubtractAssign:
result = d1 - d2;
return true;
case ExpressionType.Multiply:
case ExpressionType.MultiplyAssign:
result = d1 * d2;
return true;
case ExpressionType.Divide:
case ExpressionType.DivideAssign:
result = d1 / d2;
return true;
}
}
else if (objA is float || objB is float || objA is double || objB is double)
{
if (objA == null || objB == null)
{
result = null;
return true;
}
double d1 = Convert.ToDouble(objA, CultureInfo.InvariantCulture);
double d2 = Convert.ToDouble(objB, CultureInfo.InvariantCulture);
switch (operation)
{
case ExpressionType.Add:
case ExpressionType.AddAssign:
result = d1 + d2;
return true;
case ExpressionType.Subtract:
case ExpressionType.SubtractAssign:
result = d1 - d2;
return true;
case ExpressionType.Multiply:
case ExpressionType.MultiplyAssign:
result = d1 * d2;
return true;
case ExpressionType.Divide:
case ExpressionType.DivideAssign:
result = d1 / d2;
return true;
}
}
else if (objA is int || objA is uint || objA is long || objA is short || objA is ushort || objA is sbyte || objA is byte ||
objB is int || objB is uint || objB is long || objB is short || objB is ushort || objB is sbyte || objB is byte)
{
if (objA == null || objB == null)
{
result = null;
return true;
}
long l1 = Convert.ToInt64(objA, CultureInfo.InvariantCulture);
long l2 = Convert.ToInt64(objB, CultureInfo.InvariantCulture);
switch (operation)
{
case ExpressionType.Add:
case ExpressionType.AddAssign:
result = l1 + l2;
return true;
case ExpressionType.Subtract:
case ExpressionType.SubtractAssign:
result = l1 - l2;
return true;
case ExpressionType.Multiply:
case ExpressionType.MultiplyAssign:
result = l1 * l2;
return true;
case ExpressionType.Divide:
case ExpressionType.DivideAssign:
result = l1 / l2;
return true;
}
}
result = null;
return false;
}
#endif
internal override JToken CloneToken()
{
return new JValue(this);
}
/// <summary>
/// Creates a <see cref="JValue"/> comment with the given value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>A <see cref="JValue"/> comment with the given value.</returns>
public static JValue CreateComment(string value)
{
return new JValue(value, JTokenType.Comment);
}
/// <summary>
/// Creates a <see cref="JValue"/> string with the given value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>A <see cref="JValue"/> string with the given value.</returns>
public static JValue CreateString(string value)
{
return new JValue(value, JTokenType.String);
}
/// <summary>
/// Creates a <see cref="JValue"/> null value.
/// </summary>
/// <returns>A <see cref="JValue"/> null value.</returns>
public static JValue CreateNull()
{
return new JValue(null, JTokenType.Null);
}
/// <summary>
/// Creates a <see cref="JValue"/> undefined value.
/// </summary>
/// <returns>A <see cref="JValue"/> undefined value.</returns>
public static JValue CreateUndefined()
{
return new JValue(null, JTokenType.Undefined);
}
private static JTokenType GetValueType(JTokenType? current, object value)
{
if (value == null)
{
return JTokenType.Null;
}
#if HAVE_ADO_NET
else if (value == DBNull.Value)
{
return JTokenType.Null;
}
#endif
else if (value is string)
{
return GetStringValueType(current);
}
else if (value is long || value is int || value is short || value is sbyte
|| value is ulong || value is uint || value is ushort || value is byte)
{
return JTokenType.Integer;
}
else if (value is Enum)
{
return JTokenType.Integer;
}
#if HAVE_BIG_INTEGER
else if (value is BigInteger)
{
return JTokenType.Integer;
}
#endif
else if (value is double || value is float || value is decimal)
{
return JTokenType.Float;
}
else if (value is DateTime)
{
return JTokenType.Date;
}
#if HAVE_DATE_TIME_OFFSET
else if (value is DateTimeOffset)
{
return JTokenType.Date;
}
#endif
else if (value is byte[])
{
return JTokenType.Bytes;
}
else if (value is bool)
{
return JTokenType.Boolean;
}
else if (value is Guid)
{
return JTokenType.Guid;
}
else if (value is Uri)
{
return JTokenType.Uri;
}
else if (value is TimeSpan)
{
return JTokenType.TimeSpan;
}
throw new ArgumentException("Could not determine JSON object type for type {0}.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
}
private static JTokenType GetStringValueType(JTokenType? current)
{
if (current == null)
{
return JTokenType.String;
}
switch (current.GetValueOrDefault())
{
case JTokenType.Comment:
case JTokenType.String:
case JTokenType.Raw:
return current.GetValueOrDefault();
default:
return JTokenType.String;
}
}
/// <summary>
/// Gets the node type for this <see cref="JToken"/>.
/// </summary>
/// <value>The type.</value>
public override JTokenType Type
{
get { return _valueType; }
}
/// <summary>
/// Gets or sets the underlying token value.
/// </summary>
/// <value>The underlying token value.</value>
public object Value
{
get { return _value; }
set
{
Type currentType = _value?.GetType();
Type newType = value?.GetType();
if (currentType != newType)
{
_valueType = GetValueType(_valueType, value);
}
_value = value;
}
}
/// <summary>
/// Writes this token to a <see cref="JsonWriter"/>.
/// </summary>
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
/// <param name="converters">A collection of <see cref="JsonConverter"/>s which will be used when writing the token.</param>
public override void WriteTo(JsonWriter writer, params JsonConverter[] converters)
{
if (converters != null && converters.Length > 0 && _value != null)
{
JsonConverter matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType());
if (matchingConverter != null && matchingConverter.CanWrite)
{
matchingConverter.WriteJson(writer, _value, JsonSerializer.CreateDefault());
return;
}
}
switch (_valueType)
{
case JTokenType.Comment:
writer.WriteComment(_value?.ToString());
return;
case JTokenType.Raw:
writer.WriteRawValue(_value?.ToString());
return;
case JTokenType.Null:
writer.WriteNull();
return;
case JTokenType.Undefined:
writer.WriteUndefined();
return;
case JTokenType.Integer:
if (_value is int)
{
writer.WriteValue((int)_value);
}
else if (_value is long)
{
writer.WriteValue((long)_value);
}
else if (_value is ulong)
{
writer.WriteValue((ulong)_value);
}
#if HAVE_BIG_INTEGER
else if (_value is BigInteger)
{
writer.WriteValue((BigInteger)_value);
}
#endif
else
{
writer.WriteValue(Convert.ToInt64(_value, CultureInfo.InvariantCulture));
}
return;
case JTokenType.Float:
if (_value is decimal)
{
writer.WriteValue((decimal)_value);
}
else if (_value is double)
{
writer.WriteValue((double)_value);
}
else if (_value is float)
{
writer.WriteValue((float)_value);
}
else
{
writer.WriteValue(Convert.ToDouble(_value, CultureInfo.InvariantCulture));
}
return;
case JTokenType.String:
writer.WriteValue(_value?.ToString());
return;
case JTokenType.Boolean:
writer.WriteValue(Convert.ToBoolean(_value, CultureInfo.InvariantCulture));
return;
case JTokenType.Date:
#if HAVE_DATE_TIME_OFFSET
if (_value is DateTimeOffset)
{
writer.WriteValue((DateTimeOffset)_value);
}
else
#endif
{
writer.WriteValue(Convert.ToDateTime(_value, CultureInfo.InvariantCulture));
}
return;
case JTokenType.Bytes:
writer.WriteValue((byte[])_value);
return;
case JTokenType.Guid:
writer.WriteValue((_value != null) ? (Guid?)_value : null);
return;
case JTokenType.TimeSpan:
writer.WriteValue((_value != null) ? (TimeSpan?)_value : null);
return;
case JTokenType.Uri:
writer.WriteValue((Uri)_value);
return;
}
throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(Type), _valueType, "Unexpected token type.");
}
internal override int GetDeepHashCode()
{
int valueHashCode = (_value != null) ? _value.GetHashCode() : 0;
// GetHashCode on an enum boxes so cast to int
return ((int)_valueType).GetHashCode() ^ valueHashCode;
}
private static bool ValuesEquals(JValue v1, JValue v2)
{
return (v1 == v2 || (v1._valueType == v2._valueType && Compare(v1._valueType, v1._value, v2._value) == 0));
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <returns>
/// <c>true</c> if the current object is equal to the <paramref name="other"/> parameter; otherwise, <c>false</c>.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public bool Equals(JValue other)
{
if (other == null)
{
return false;
}
return ValuesEquals(this, other);
}
/// <summary>
/// Determines whether the specified <see cref="Object"/> is equal to the current <see cref="Object"/>.
/// </summary>
/// <param name="obj">The <see cref="Object"/> to compare with the current <see cref="Object"/>.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="Object"/> is equal to the current <see cref="Object"/>; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return Equals(obj as JValue);
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="Object"/>.
/// </returns>
public override int GetHashCode()
{
if (_value == null)
{
return 0;
}
return _value.GetHashCode();
}
/// <summary>
/// Returns a <see cref="String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="String"/> that represents this instance.
/// </returns>
public override string ToString()
{
if (_value == null)
{
return string.Empty;
}
return _value.ToString();
}
/// <summary>
/// Returns a <see cref="String"/> that represents this instance.
/// </summary>
/// <param name="format">The format.</param>
/// <returns>
/// A <see cref="String"/> that represents this instance.
/// </returns>
public string ToString(string format)
{
return ToString(format, CultureInfo.CurrentCulture);
}
/// <summary>
/// Returns a <see cref="String"/> that represents this instance.
/// </summary>
/// <param name="formatProvider">The format provider.</param>
/// <returns>
/// A <see cref="String"/> that represents this instance.
/// </returns>
public string ToString(IFormatProvider formatProvider)
{
return ToString(null, formatProvider);
}
/// <summary>
/// Returns a <see cref="String"/> that represents this instance.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="formatProvider">The format provider.</param>
/// <returns>
/// A <see cref="String"/> that represents this instance.
/// </returns>
public string ToString(string format, IFormatProvider formatProvider)
{
if (_value == null)
{
return string.Empty;
}
IFormattable formattable = _value as IFormattable;
if (formattable != null)
{
return formattable.ToString(format, formatProvider);
}
else
{
return _value.ToString();
}
}
#if HAVE_DYNAMIC
/// <summary>
/// Returns the <see cref="DynamicMetaObject"/> responsible for binding operations performed on this object.
/// </summary>
/// <param name="parameter">The expression tree representation of the runtime value.</param>
/// <returns>
/// The <see cref="DynamicMetaObject"/> to bind this object.
/// </returns>
protected override DynamicMetaObject GetMetaObject(Expression parameter)
{
return new DynamicProxyMetaObject<JValue>(parameter, this, new JValueDynamicProxy());
}
private class JValueDynamicProxy : DynamicProxy<JValue>
{
public override bool TryConvert(JValue instance, ConvertBinder binder, out object result)
{
if (binder.Type == typeof(JValue) || binder.Type == typeof(JToken))
{
result = instance;
return true;
}
object value = instance.Value;
if (value == null)
{
result = null;
return ReflectionUtils.IsNullable(binder.Type);
}
result = ConvertUtils.Convert(value, CultureInfo.InvariantCulture, binder.Type);
return true;
}
public override bool TryBinaryOperation(JValue instance, BinaryOperationBinder binder, object arg, out object result)
{
JValue value = arg as JValue;
object compareValue = value != null ? value.Value : arg;
switch (binder.Operation)
{
case ExpressionType.Equal:
result = (Compare(instance.Type, instance.Value, compareValue) == 0);
return true;
case ExpressionType.NotEqual:
result = (Compare(instance.Type, instance.Value, compareValue) != 0);
return true;
case ExpressionType.GreaterThan:
result = (Compare(instance.Type, instance.Value, compareValue) > 0);
return true;
case ExpressionType.GreaterThanOrEqual:
result = (Compare(instance.Type, instance.Value, compareValue) >= 0);
return true;
case ExpressionType.LessThan:
result = (Compare(instance.Type, instance.Value, compareValue) < 0);
return true;
case ExpressionType.LessThanOrEqual:
result = (Compare(instance.Type, instance.Value, compareValue) <= 0);
return true;
case ExpressionType.Add:
case ExpressionType.AddAssign:
case ExpressionType.Subtract:
case ExpressionType.SubtractAssign:
case ExpressionType.Multiply:
case ExpressionType.MultiplyAssign:
case ExpressionType.Divide:
case ExpressionType.DivideAssign:
if (Operation(binder.Operation, instance.Value, compareValue, out result))
{
result = new JValue(result);
return true;
}
break;
}
result = null;
return false;
}
}
#endif
int IComparable.CompareTo(object obj)
{
if (obj == null)
{
return 1;
}
JValue value = obj as JValue;
object otherValue = value != null ? value.Value : obj;
return Compare(_valueType, _value, otherValue);
}
/// <summary>
/// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.
/// </summary>
/// <param name="obj">An object to compare with this instance.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has these meanings:
/// Value
/// Meaning
/// Less than zero
/// This instance is less than <paramref name="obj"/>.
/// Zero
/// This instance is equal to <paramref name="obj"/>.
/// Greater than zero
/// This instance is greater than <paramref name="obj"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="obj"/> is not of the same type as this instance.
/// </exception>
public int CompareTo(JValue obj)
{
if (obj == null)
{
return 1;
}
return Compare(_valueType, _value, obj._value);
}
#if HAVE_ICONVERTIBLE
TypeCode IConvertible.GetTypeCode()
{
if (_value == null)
{
return TypeCode.Empty;
}
IConvertible convertable = _value as IConvertible;
if (convertable == null)
{
return TypeCode.Object;
}
return convertable.GetTypeCode();
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return (bool)this;
}
char IConvertible.ToChar(IFormatProvider provider)
{
return (char)this;
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return (sbyte)this;
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return (byte)this;
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return (short)this;
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return (ushort)this;
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return (int)this;
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return (uint)this;
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return (long)this;
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return (ulong)this;
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return (float)this;
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return (double)this;
}
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return (decimal)this;
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
return (DateTime)this;
}
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
return ToObject(conversionType);
}
#endif
}
}
| |
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 FSIX.Web.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ActionDescriptor.ReturnType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
using Xunit;
namespace BencodeLib.Test {
public class BencodeReaderTest {
[Fact]
[SuppressMessage("ReSharper", "PossibleNullReferenceException")]
public void Read_ValidSimpleDictionary() {
const string simpleDict = "d3:key5:value6:numKeyi42e4:listli10ei-1234e4:testee";
var reader = new BencodeReader(Encoding.ASCII.GetBytes(simpleDict));
var dict = reader.Read() as BencodeDictionary;
Assert.NotNull(dict);
Assert.Equal(3, dict.Count);
Assert.True(dict.ContainsKey("key"));
Assert.True(dict.ContainsKey("numKey"));
Assert.True(dict.ContainsKey("list"));
Assert.Equal("value", dict["key"] as BencodeByteString);
Assert.Equal(42, dict["numKey"] as BencodeInteger);
Assert.Equal(3, (dict["list"] as BencodeList).Count);
}
[Fact]
public void Read_InvalidDictionaryEnd() {
// This dictionary is missing the closing 'e'
const string test = "d3:key5:value";
var reader = new BencodeReader(Encoding.ASCII.GetBytes(test));
Assert.Throws(typeof(InvalidDataException), () => reader.Read());
}
[Fact]
public void Read_InvalidListEnd() {
const string test = "li1ei2ei3e";
var reader = new BencodeReader(Encoding.ASCII.GetBytes(test));
Assert.Throws(typeof(InvalidDataException), () => reader.Read());
}
[Fact]
public void Read_ValidInteger() {
const string test = "i123456e";
var reader = new BencodeReader(Encoding.ASCII.GetBytes(test));
var item = reader.Read();
Assert.IsType<BencodeInteger>(item);
var num = item as BencodeInteger;
Assert.Equal(123456, num);
}
[Fact]
public void Read_ValidNegativeInteger() {
const string test = "i-432e";
var reader = new BencodeReader(Encoding.ASCII.GetBytes(test));
var item = reader.Read();
Assert.IsType<BencodeInteger>(item);
var num = item as BencodeInteger;
Assert.Equal(-432, num);
}
[Fact]
public void Read_InvalidInteger() {
const string test = "iabce";
var reader = new BencodeReader(Encoding.ASCII.GetBytes(test));
Assert.Throws(typeof(FormatException), () => reader.Read());
}
[Fact]
public void Read_ValidWholeFile() {
byte[] rawData = {
0x64, 0x38, 0x3A, 0x61, 0x6E, 0x6E, 0x6F, 0x75, 0x6E, 0x63, 0x65, 0x33,
0x36, 0x3A, 0x68, 0x74, 0x74, 0x70, 0x3A, 0x2F, 0x2F, 0x62, 0x74, 0x31,
0x2E, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x2E, 0x6F, 0x72, 0x67,
0x3A, 0x36, 0x39, 0x36, 0x39, 0x2F, 0x61, 0x6E, 0x6E, 0x6F, 0x75, 0x6E,
0x63, 0x65, 0x31, 0x33, 0x3A, 0x61, 0x6E, 0x6E, 0x6F, 0x75, 0x6E, 0x63,
0x65, 0x2D, 0x6C, 0x69, 0x73, 0x74, 0x6C, 0x6C, 0x33, 0x36, 0x3A, 0x68,
0x74, 0x74, 0x70, 0x3A, 0x2F, 0x2F, 0x62, 0x74, 0x31, 0x2E, 0x61, 0x72,
0x63, 0x68, 0x69, 0x76, 0x65, 0x2E, 0x6F, 0x72, 0x67, 0x3A, 0x36, 0x39,
0x36, 0x39, 0x2F, 0x61, 0x6E, 0x6E, 0x6F, 0x75, 0x6E, 0x63, 0x65, 0x65,
0x6C, 0x33, 0x36, 0x3A, 0x68, 0x74, 0x74, 0x70, 0x3A, 0x2F, 0x2F, 0x62,
0x74, 0x32, 0x2E, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x2E, 0x6F,
0x72, 0x67, 0x3A, 0x36, 0x39, 0x36, 0x39, 0x2F, 0x61, 0x6E, 0x6E, 0x6F,
0x75, 0x6E, 0x63, 0x65, 0x65, 0x65, 0x37, 0x3A, 0x63, 0x6F, 0x6D, 0x6D,
0x65, 0x6E, 0x74, 0x37, 0x30, 0x32, 0x3A, 0x54, 0x68, 0x69, 0x73, 0x20,
0x63, 0x6F, 0x6E, 0x74, 0x65, 0x6E, 0x74, 0x20, 0x68, 0x6F, 0x73, 0x74,
0x65, 0x64, 0x20, 0x61, 0x74, 0x20, 0x74, 0x68, 0x65, 0x20, 0x49, 0x6E,
0x74, 0x65, 0x72, 0x6E, 0x65, 0x74, 0x20, 0x41, 0x72, 0x63, 0x68, 0x69,
0x76, 0x65, 0x20, 0x61, 0x74, 0x20, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3A,
0x2F, 0x2F, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x2E, 0x6F, 0x72,
0x67, 0x2F, 0x64, 0x65, 0x74, 0x61, 0x69, 0x6C, 0x73, 0x2F, 0x41, 0x64,
0x43, 0x6F, 0x75, 0x6E, 0x63, 0x69, 0x6C, 0x2D, 0x41, 0x64, 0x6F, 0x70,
0x74, 0x69, 0x6F, 0x6E, 0x2D, 0x44, 0x61, 0x6E, 0x67, 0x65, 0x72, 0x44,
0x61, 0x64, 0x2D, 0x33, 0x30, 0x5F, 0x43, 0x4C, 0x53, 0x44, 0x0A, 0x46,
0x69, 0x6C, 0x65, 0x73, 0x20, 0x6D, 0x61, 0x79, 0x20, 0x68, 0x61, 0x76,
0x65, 0x20, 0x63, 0x68, 0x61, 0x6E, 0x67, 0x65, 0x64, 0x2C, 0x20, 0x77,
0x68, 0x69, 0x63, 0x68, 0x20, 0x70, 0x72, 0x65, 0x76, 0x65, 0x6E, 0x74,
0x73, 0x20, 0x74, 0x6F, 0x72, 0x72, 0x65, 0x6E, 0x74, 0x73, 0x20, 0x66,
0x72, 0x6F, 0x6D, 0x20, 0x64, 0x6F, 0x77, 0x6E, 0x6C, 0x6F, 0x61, 0x64,
0x69, 0x6E, 0x67, 0x20, 0x63, 0x6F, 0x72, 0x72, 0x65, 0x63, 0x74, 0x6C,
0x79, 0x20, 0x6F, 0x72, 0x20, 0x63, 0x6F, 0x6D, 0x70, 0x6C, 0x65, 0x74,
0x65, 0x6C, 0x79, 0x3B, 0x20, 0x70, 0x6C, 0x65, 0x61, 0x73, 0x65, 0x20,
0x63, 0x68, 0x65, 0x63, 0x6B, 0x20, 0x66, 0x6F, 0x72, 0x20, 0x61, 0x6E,
0x20, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x20, 0x74, 0x6F, 0x72,
0x72, 0x65, 0x6E, 0x74, 0x20, 0x61, 0x74, 0x20, 0x68, 0x74, 0x74, 0x70,
0x73, 0x3A, 0x2F, 0x2F, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x2E,
0x6F, 0x72, 0x67, 0x2F, 0x64, 0x6F, 0x77, 0x6E, 0x6C, 0x6F, 0x61, 0x64,
0x2F, 0x41, 0x64, 0x43, 0x6F, 0x75, 0x6E, 0x63, 0x69, 0x6C, 0x2D, 0x41,
0x64, 0x6F, 0x70, 0x74, 0x69, 0x6F, 0x6E, 0x2D, 0x44, 0x61, 0x6E, 0x67,
0x65, 0x72, 0x44, 0x61, 0x64, 0x2D, 0x33, 0x30, 0x5F, 0x43, 0x4C, 0x53,
0x44, 0x2F, 0x41, 0x64, 0x43, 0x6F, 0x75, 0x6E, 0x63, 0x69, 0x6C, 0x2D,
0x41, 0x64, 0x6F, 0x70, 0x74, 0x69, 0x6F, 0x6E, 0x2D, 0x44, 0x61, 0x6E,
0x67, 0x65, 0x72, 0x44, 0x61, 0x64, 0x2D, 0x33, 0x30, 0x5F, 0x43, 0x4C,
0x53, 0x44, 0x5F, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x2E, 0x74,
0x6F, 0x72, 0x72, 0x65, 0x6E, 0x74, 0x0A, 0x4E, 0x6F, 0x74, 0x65, 0x3A,
0x20, 0x72, 0x65, 0x74, 0x72, 0x69, 0x65, 0x76, 0x61, 0x6C, 0x20, 0x75,
0x73, 0x75, 0x61, 0x6C, 0x6C, 0x79, 0x20, 0x72, 0x65, 0x71, 0x75, 0x69,
0x72, 0x65, 0x73, 0x20, 0x61, 0x20, 0x63, 0x6C, 0x69, 0x65, 0x6E, 0x74,
0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x73, 0x75, 0x70, 0x70, 0x6F, 0x72,
0x74, 0x73, 0x20, 0x77, 0x65, 0x62, 0x73, 0x65, 0x65, 0x64, 0x69, 0x6E,
0x67, 0x20, 0x28, 0x47, 0x65, 0x74, 0x52, 0x69, 0x67, 0x68, 0x74, 0x20,
0x73, 0x74, 0x79, 0x6C, 0x65, 0x29, 0x2E, 0x0A, 0x4E, 0x6F, 0x74, 0x65,
0x3A, 0x20, 0x6D, 0x61, 0x6E, 0x79, 0x20, 0x49, 0x6E, 0x74, 0x65, 0x72,
0x6E, 0x65, 0x74, 0x20, 0x41, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x20,
0x74, 0x6F, 0x72, 0x72, 0x65, 0x6E, 0x74, 0x73, 0x20, 0x63, 0x6F, 0x6E,
0x74, 0x61, 0x69, 0x6E, 0x20, 0x61, 0x20, 0x27, 0x70, 0x61, 0x64, 0x20,
0x66, 0x69, 0x6C, 0x65, 0x27, 0x20, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74,
0x6F, 0x72, 0x79, 0x2E, 0x20, 0x54, 0x68, 0x69, 0x73, 0x20, 0x64, 0x69,
0x72, 0x65, 0x63, 0x74, 0x6F, 0x72, 0x79, 0x20, 0x61, 0x6E, 0x64, 0x20,
0x74, 0x68, 0x65, 0x20, 0x66, 0x69, 0x6C, 0x65, 0x73, 0x20, 0x77, 0x69,
0x74, 0x68, 0x69, 0x6E, 0x20, 0x69, 0x74, 0x20, 0x6D, 0x61, 0x79, 0x20,
0x62, 0x65, 0x20, 0x65, 0x72, 0x61, 0x73, 0x65, 0x64, 0x20, 0x6F, 0x6E,
0x63, 0x65, 0x20, 0x72, 0x65, 0x74, 0x72, 0x69, 0x65, 0x76, 0x61, 0x6C,
0x20, 0x63, 0x6F, 0x6D, 0x70, 0x6C, 0x65, 0x74, 0x65, 0x73, 0x2E, 0x0A,
0x4E, 0x6F, 0x74, 0x65, 0x3A, 0x20, 0x74, 0x68, 0x65, 0x20, 0x66, 0x69,
0x6C, 0x65, 0x20, 0x41, 0x64, 0x43, 0x6F, 0x75, 0x6E, 0x63, 0x69, 0x6C,
0x2D, 0x41, 0x64, 0x6F, 0x70, 0x74, 0x69, 0x6F, 0x6E, 0x2D, 0x44, 0x61,
0x6E, 0x67, 0x65, 0x72, 0x44, 0x61, 0x64, 0x2D, 0x33, 0x30, 0x5F, 0x43,
0x4C, 0x53, 0x44, 0x5F, 0x6D, 0x65, 0x74, 0x61, 0x2E, 0x78, 0x6D, 0x6C,
0x20, 0x63, 0x6F, 0x6E, 0x74, 0x61, 0x69, 0x6E, 0x73, 0x20, 0x6D, 0x65,
0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x20, 0x61, 0x62, 0x6F, 0x75, 0x74,
0x20, 0x74, 0x68, 0x69, 0x73, 0x20, 0x74, 0x6F, 0x72, 0x72, 0x65, 0x6E,
0x74, 0x27, 0x73, 0x20, 0x63, 0x6F, 0x6E, 0x74, 0x65, 0x6E, 0x74, 0x73,
0x2E, 0x31, 0x30, 0x3A, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x20,
0x62, 0x79, 0x31, 0x35, 0x3A, 0x69, 0x61, 0x5F, 0x6D, 0x61, 0x6B, 0x65,
0x5F, 0x74, 0x6F, 0x72, 0x72, 0x65, 0x6E, 0x74, 0x31, 0x33, 0x3A, 0x63,
0x72, 0x65, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x20, 0x64, 0x61, 0x74, 0x65,
0x69, 0x31, 0x34, 0x38, 0x32, 0x34, 0x34, 0x30, 0x37, 0x33, 0x34, 0x65,
0x34, 0x3A, 0x69, 0x6E, 0x66, 0x6F, 0x64, 0x31, 0x31, 0x3A, 0x63, 0x6F,
0x6C, 0x6C, 0x65, 0x63, 0x74, 0x69, 0x6F, 0x6E, 0x73, 0x6C, 0x34, 0x38,
0x3A, 0x6F, 0x72, 0x67, 0x2E, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65,
0x2E, 0x41, 0x64, 0x43, 0x6F, 0x75, 0x6E, 0x63, 0x69, 0x6C, 0x2D, 0x41,
0x64, 0x6F, 0x70, 0x74, 0x69, 0x6F, 0x6E, 0x2D, 0x44, 0x61, 0x6E, 0x67,
0x65, 0x72, 0x44, 0x61, 0x64, 0x2D, 0x33, 0x30, 0x5F, 0x43, 0x4C, 0x53,
0x44, 0x65, 0x35, 0x3A, 0x66, 0x69, 0x6C, 0x65, 0x73, 0x6C, 0x64, 0x35,
0x3A, 0x63, 0x72, 0x63, 0x33, 0x32, 0x38, 0x3A, 0x36, 0x32, 0x35, 0x65,
0x35, 0x38, 0x66, 0x30, 0x36, 0x3A, 0x6C, 0x65, 0x6E, 0x67, 0x74, 0x68,
0x69, 0x39, 0x32, 0x31, 0x36, 0x65, 0x33, 0x3A, 0x6D, 0x64, 0x35, 0x33,
0x32, 0x3A, 0x34, 0x63, 0x31, 0x37, 0x39, 0x35, 0x64, 0x62, 0x34, 0x39,
0x63, 0x35, 0x62, 0x63, 0x33, 0x32, 0x37, 0x36, 0x31, 0x37, 0x32, 0x30,
0x30, 0x34, 0x61, 0x35, 0x30, 0x66, 0x63, 0x66, 0x34, 0x65, 0x35, 0x3A,
0x6D, 0x74, 0x69, 0x6D, 0x65, 0x31, 0x30, 0x3A, 0x31, 0x34, 0x37, 0x31,
0x32, 0x32, 0x34, 0x32, 0x37, 0x34, 0x34, 0x3A, 0x70, 0x61, 0x74, 0x68,
0x6C, 0x34, 0x38, 0x3A, 0x41, 0x64, 0x43, 0x6F, 0x75, 0x6E, 0x63, 0x69,
0x6C, 0x2D, 0x41, 0x64, 0x6F, 0x70, 0x74, 0x69, 0x6F, 0x6E, 0x2D, 0x44,
0x61, 0x6E, 0x67, 0x65, 0x72, 0x44, 0x61, 0x64, 0x2D, 0x33, 0x30, 0x5F,
0x43, 0x4C, 0x53, 0x44, 0x5F, 0x6D, 0x65, 0x74, 0x61, 0x2E, 0x73, 0x71,
0x6C, 0x69, 0x74, 0x65, 0x65, 0x34, 0x3A, 0x73, 0x68, 0x61, 0x31, 0x34,
0x30, 0x3A, 0x31, 0x36, 0x32, 0x66, 0x32, 0x38, 0x34, 0x61, 0x63, 0x65,
0x61, 0x31, 0x36, 0x35, 0x34, 0x66, 0x62, 0x62, 0x63, 0x31, 0x65, 0x32,
0x36, 0x33, 0x64, 0x62, 0x35, 0x31, 0x30, 0x35, 0x66, 0x37, 0x30, 0x34,
0x31, 0x32, 0x34, 0x30, 0x37, 0x61, 0x65, 0x64, 0x35, 0x3A, 0x63, 0x72,
0x63, 0x33, 0x32, 0x38, 0x3A, 0x35, 0x31, 0x38, 0x39, 0x61, 0x39, 0x62,
0x61, 0x36, 0x3A, 0x6C, 0x65, 0x6E, 0x67, 0x74, 0x68, 0x69, 0x31, 0x32,
0x36, 0x39, 0x65, 0x33, 0x3A, 0x6D, 0x64, 0x35, 0x33, 0x32, 0x3A, 0x63,
0x35, 0x62, 0x37, 0x61, 0x61, 0x62, 0x33, 0x31, 0x34, 0x32, 0x35, 0x62,
0x38, 0x66, 0x30, 0x63, 0x32, 0x39, 0x35, 0x31, 0x65, 0x65, 0x33, 0x33,
0x36, 0x66, 0x35, 0x30, 0x61, 0x33, 0x32, 0x35, 0x3A, 0x6D, 0x74, 0x69,
0x6D, 0x65, 0x31, 0x30, 0x3A, 0x31, 0x34, 0x38, 0x32, 0x34, 0x34, 0x30,
0x37, 0x33, 0x32, 0x34, 0x3A, 0x70, 0x61, 0x74, 0x68, 0x6C, 0x34, 0x35,
0x3A, 0x41, 0x64, 0x43, 0x6F, 0x75, 0x6E, 0x63, 0x69, 0x6C, 0x2D, 0x41,
0x64, 0x6F, 0x70, 0x74, 0x69, 0x6F, 0x6E, 0x2D, 0x44, 0x61, 0x6E, 0x67,
0x65, 0x72, 0x44, 0x61, 0x64, 0x2D, 0x33, 0x30, 0x5F, 0x43, 0x4C, 0x53,
0x44, 0x5F, 0x6D, 0x65, 0x74, 0x61, 0x2E, 0x78, 0x6D, 0x6C, 0x65, 0x34,
0x3A, 0x73, 0x68, 0x61, 0x31, 0x34, 0x30, 0x3A, 0x36, 0x37, 0x64, 0x31,
0x65, 0x34, 0x31, 0x61, 0x66, 0x66, 0x63, 0x65, 0x62, 0x39, 0x38, 0x32,
0x64, 0x33, 0x32, 0x66, 0x36, 0x38, 0x33, 0x64, 0x39, 0x35, 0x33, 0x33,
0x33, 0x61, 0x33, 0x35, 0x66, 0x36, 0x33, 0x37, 0x31, 0x63, 0x65, 0x64,
0x65, 0x65, 0x34, 0x3A, 0x6E, 0x61, 0x6D, 0x65, 0x33, 0x36, 0x3A, 0x41,
0x64, 0x43, 0x6F, 0x75, 0x6E, 0x63, 0x69, 0x6C, 0x2D, 0x41, 0x64, 0x6F,
0x70, 0x74, 0x69, 0x6F, 0x6E, 0x2D, 0x44, 0x61, 0x6E, 0x67, 0x65, 0x72,
0x44, 0x61, 0x64, 0x2D, 0x33, 0x30, 0x5F, 0x43, 0x4C, 0x53, 0x44, 0x31,
0x32, 0x3A, 0x70, 0x69, 0x65, 0x63, 0x65, 0x20, 0x6C, 0x65, 0x6E, 0x67,
0x74, 0x68, 0x69, 0x35, 0x32, 0x34, 0x32, 0x38, 0x38, 0x65, 0x36, 0x3A,
0x70, 0x69, 0x65, 0x63, 0x65, 0x73, 0x32, 0x30, 0x3A, 0x83, 0x72, 0x53,
0x2D, 0x36, 0x11, 0x50, 0xA8, 0x68, 0x52, 0x0E, 0xC8, 0x2E, 0x0F, 0x0C,
0x1C, 0x6B, 0xE2, 0x46, 0xEC, 0x65, 0x36, 0x3A, 0x6C, 0x6F, 0x63, 0x61,
0x6C, 0x65, 0x32, 0x3A, 0x65, 0x6E, 0x35, 0x3A, 0x74, 0x69, 0x74, 0x6C,
0x65, 0x33, 0x36, 0x3A, 0x41, 0x64, 0x43, 0x6F, 0x75, 0x6E, 0x63, 0x69,
0x6C, 0x2D, 0x41, 0x64, 0x6F, 0x70, 0x74, 0x69, 0x6F, 0x6E, 0x2D, 0x44,
0x61, 0x6E, 0x67, 0x65, 0x72, 0x44, 0x61, 0x64, 0x2D, 0x33, 0x30, 0x5F,
0x43, 0x4C, 0x53, 0x44, 0x38, 0x3A, 0x75, 0x72, 0x6C, 0x2D, 0x6C, 0x69,
0x73, 0x74, 0x6C, 0x32, 0x39, 0x3A, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3A,
0x2F, 0x2F, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x2E, 0x6F, 0x72,
0x67, 0x2F, 0x64, 0x6F, 0x77, 0x6E, 0x6C, 0x6F, 0x61, 0x64, 0x2F, 0x34,
0x30, 0x3A, 0x68, 0x74, 0x74, 0x70, 0x3A, 0x2F, 0x2F, 0x69, 0x61, 0x36,
0x30, 0x31, 0x32, 0x30, 0x31, 0x2E, 0x75, 0x73, 0x2E, 0x61, 0x72, 0x63,
0x68, 0x69, 0x76, 0x65, 0x2E, 0x6F, 0x72, 0x67, 0x2F, 0x32, 0x30, 0x2F,
0x69, 0x74, 0x65, 0x6D, 0x73, 0x2F, 0x34, 0x30, 0x3A, 0x68, 0x74, 0x74,
0x70, 0x3A, 0x2F, 0x2F, 0x69, 0x61, 0x38, 0x30, 0x31, 0x32, 0x30, 0x31,
0x2E, 0x75, 0x73, 0x2E, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x2E,
0x6F, 0x72, 0x67, 0x2F, 0x32, 0x30, 0x2F, 0x69, 0x74, 0x65, 0x6D, 0x73,
0x2F, 0x65, 0x65
};
var reader = new BencodeReader(rawData);
var item = reader.Read() as BencodeDictionary;
var rootKeys = new List<string> {
"announce", "announce-list", "comment",
"created by", "creation date", "info",
"locale", "title", "url-list"
};
// TODO: Test more included values
Assert.NotNull(item);
Assert.Equal(9, item.Count);
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
Assert.All(item, kvp => rootKeys.Contains(kvp.Key));
}
[Fact]
public void Read_InvalidSimpleDictionary() {
const string data = "di42e5:valuee";
var reader = new BencodeReader(Encoding.ASCII.GetBytes(data));
Assert.Throws(typeof(InvalidDataException), () => reader.Read());
}
[Fact]
public void Read_NegativeBytestringLength() {
// Byte string length can be 0, but not negative
const string data = "-5:bytestr";
var reader = new BencodeReader(Encoding.ASCII.GetBytes(data));
Assert.Throws(typeof(InvalidDataException), () => reader.Read());
}
[Fact]
public void Read_ZeroBytestringLength() {
const string data = "0:";
var reader = new BencodeReader(Encoding.ASCII.GetBytes(data));
var str = reader.Read() as BencodeByteString;
Assert.Equal(string.Empty, str);
}
[Fact]
public void Read_EmptyList() {
const string data = "le";
var reader = new BencodeReader(Encoding.ASCII.GetBytes(data));
var list = reader.Read() as BencodeList;
Assert.NotNull(list);
Assert.Equal(0, list.Count);
}
[Fact]
public void Read_EmptyDictionary() {
const string data = "de";
var reader = new BencodeReader(Encoding.ASCII.GetBytes(data));
var dict = reader.Read() as BencodeDictionary;
Assert.NotNull(dict);
Assert.Equal(0, dict.Count);
}
}
}
| |
// <copyright file="GPGSAndroidSetupUI.cs" company="Google Inc.">
// Copyright (C) Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
namespace GooglePlayGames
{
using System.IO;
using System.Collections;
using System.Xml;
using UnityEngine;
using UnityEditor;
public class GPGSAndroidSetupUI : EditorWindow
{
private string mConfigData = string.Empty;
private string mClassName = "GooglePlayGames.GPGSIds";
private Vector2 scroll;
private string mWebClientId = string.Empty;
[MenuItem("Window/Google Play Games/Setup/Android setup...", false, 1)]
public static void MenuItemFileGPGSAndroidSetup()
{
EditorWindow window = EditorWindow.GetWindow(
typeof(GPGSAndroidSetupUI), true, GPGSStrings.AndroidSetup.Title);
window.minSize = new Vector2(500, 400);
}
public void OnEnable()
{
mClassName = GPGSProjectSettings.Instance.Get(GPGSUtil.CLASSNAMEKEY);
mConfigData = GPGSProjectSettings.Instance.Get(GPGSUtil.ANDROIDRESOURCEKEY);
mWebClientId = GPGSProjectSettings.Instance.Get(GPGSUtil.WEBCLIENTIDKEY);
}
public void OnGUI()
{
GUI.skin.label.wordWrap = true;
GUILayout.BeginVertical();
GUILayout.Space(10);
GUILayout.Label(GPGSStrings.AndroidSetup.Blurb);
GUILayout.Label("Constants class name", EditorStyles.boldLabel);
GUILayout.Label("Enter the fully qualified name of the class to create containing the constants");
GUILayout.Space(10);
mClassName = EditorGUILayout.TextField("Constants class name",
mClassName,GUILayout.Width(480));
GUILayout.Label("Resources Definition", EditorStyles.boldLabel);
GUILayout.Label("Paste in the Android Resources from the Play Console");
GUILayout.Space(10);
scroll = GUILayout.BeginScrollView(scroll);
mConfigData = EditorGUILayout.TextArea(mConfigData,
GUILayout.Width(475), GUILayout.Height(Screen.height));
GUILayout.EndScrollView();
GUILayout.Space(10);
// Client ID field
GUILayout.Label(GPGSStrings.Setup.WebClientIdTitle, EditorStyles.boldLabel);
GUILayout.Label(GPGSStrings.AndroidSetup.WebClientIdBlurb);
mWebClientId = EditorGUILayout.TextField(GPGSStrings.Setup.ClientId,
mWebClientId, GUILayout.Width(450));
GUILayout.Space(10);
GUILayout.FlexibleSpace();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button(GPGSStrings.Setup.SetupButton,
GUILayout.Width(100)))
{
DoSetup();
}
if (GUILayout.Button("Cancel",GUILayout.Width(100)))
{
this.Close();
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.Space(20);
GUILayout.EndVertical();
}
public void DoSetup()
{
if (PerformSetup(mWebClientId, mClassName, mConfigData, null))
{
EditorUtility.DisplayDialog(GPGSStrings.Success,
GPGSStrings.AndroidSetup.SetupComplete, GPGSStrings.Ok);
this.Close();
}
else
{
GPGSUtil.Alert(GPGSStrings.Error,
"Invalid or missing XML resource data. Make sure the data is" +
" valid and contains the app_id element");
}
}
private static bool ParseResources(string className, string res)
{
XmlTextReader reader = new XmlTextReader(new StringReader(res));
bool inResource = false;
string lastProp = null;
Hashtable resourceKeys = new Hashtable();
string appId = null;
while (reader.Read())
{
if (reader.Name == "resources")
{
inResource = true;
}
if (inResource && reader.Name == "string")
{
lastProp = reader.GetAttribute("name");
}
else if (inResource && !string.IsNullOrEmpty(lastProp))
{
if (reader.HasValue)
{
if (lastProp == "app_id")
{
appId = reader.Value;
GPGSProjectSettings.Instance.Set(GPGSUtil.APPIDKEY, appId);
}
else
{
resourceKeys[lastProp] = reader.Value;
}
lastProp = null;
}
}
}
reader.Close();
if (resourceKeys.Count > 0)
{
GPGSUtil.WriteResourceIds(className, resourceKeys);
}
return appId != null;
}
/// <summary>
/// Performs setup using the Android resources downloaded XML file
/// from the play console.
/// </summary>
/// <returns><c>true</c>, if setup was performed, <c>false</c> otherwise.</returns>
/// <param name="className">Fully qualified class name for the resource Ids.</param>
/// <param name="resourceXmlData">Resource xml data.</param>
/// <param name="nearbySvcId">Nearby svc identifier.</param>
public static bool PerformSetup(string clientId, string className, string resourceXmlData, string nearbySvcId)
{
if (string.IsNullOrEmpty(resourceXmlData) &&
!string.IsNullOrEmpty(nearbySvcId))
{
return PerformSetup(clientId,
GPGSProjectSettings.Instance.Get(GPGSUtil.APPIDKEY), nearbySvcId);
}
if (ParseResources(className, resourceXmlData))
{
GPGSProjectSettings.Instance.Set(GPGSUtil.CLASSNAMEKEY, className);
GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDRESOURCEKEY, resourceXmlData);
return PerformSetup(clientId,
GPGSProjectSettings.Instance.Get(GPGSUtil.APPIDKEY), nearbySvcId);
}
return false;
}
/// <summary>
/// Provide static access to setup for facilitating automated builds.
/// </summary>
/// <param name="webClientId">The oauth2 client id for the game. This is only
/// needed if the ID Token or access token are needed.</param>
/// <param name="appId">App identifier.</param>
/// <param name="nearbySvcId">Optional nearby connection serviceId</param>
public static bool PerformSetup(string webClientId, string appId, string nearbySvcId)
{
bool needTokenPermissions = false;
if( !string.IsNullOrEmpty(webClientId) )
{
if (!GPGSUtil.LooksLikeValidClientId(webClientId))
{
GPGSUtil.Alert(GPGSStrings.Setup.ClientIdError);
return false;
}
string serverAppId = webClientId.Split('-')[0];
if (!serverAppId.Equals(appId)) {
GPGSUtil.Alert(GPGSStrings.Setup.AppIdMismatch);
return false;
}
needTokenPermissions = true;
}
else
{
needTokenPermissions = false;
}
// check for valid app id
if (!GPGSUtil.LooksLikeValidAppId(appId) && string.IsNullOrEmpty(nearbySvcId))
{
GPGSUtil.Alert(GPGSStrings.Setup.AppIdError);
return false;
}
if (nearbySvcId != null)
{
if (!NearbyConnectionUI.PerformSetup(nearbySvcId, true))
{
return false;
}
}
GPGSProjectSettings.Instance.Set(GPGSUtil.APPIDKEY, appId);
GPGSProjectSettings.Instance.Set(GPGSUtil.WEBCLIENTIDKEY, webClientId);
GPGSProjectSettings.Instance.Save();
GPGSUtil.UpdateGameInfo();
// check that Android SDK is there
if (!GPGSUtil.HasAndroidSdk())
{
Debug.LogError("Android SDK not found.");
EditorUtility.DisplayDialog(GPGSStrings.AndroidSetup.SdkNotFound,
GPGSStrings.AndroidSetup.SdkNotFoundBlurb, GPGSStrings.Ok);
return false;
}
GPGSUtil.CopySupportLibs();
// Generate AndroidManifest.xml
GPGSUtil.GenerateAndroidManifest(needTokenPermissions);
// refresh assets, and we're done
AssetDatabase.Refresh();
GPGSProjectSettings.Instance.Set("android.SetupDone", true);
GPGSProjectSettings.Instance.Save();
return true;
}
}
}
| |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using System.Diagnostics;
using Org.BouncyCastle.Math.Raw;
namespace Org.BouncyCastle.Math.EC.Custom.Sec
{
internal class SecT163Field
{
private const ulong M35 = ulong.MaxValue >> 29;
private const ulong M55 = ulong.MaxValue >> 9;
public static void Add(ulong[] x, ulong[] y, ulong[] z)
{
z[0] = x[0] ^ y[0];
z[1] = x[1] ^ y[1];
z[2] = x[2] ^ y[2];
}
public static void AddExt(ulong[] xx, ulong[] yy, ulong[] zz)
{
zz[0] = xx[0] ^ yy[0];
zz[1] = xx[1] ^ yy[1];
zz[2] = xx[2] ^ yy[2];
zz[3] = xx[3] ^ yy[3];
zz[4] = xx[4] ^ yy[4];
zz[5] = xx[5] ^ yy[5];
}
public static void AddOne(ulong[] x, ulong[] z)
{
z[0] = x[0] ^ 1UL;
z[1] = x[1];
z[2] = x[2];
}
public static ulong[] FromBigInteger(BigInteger x)
{
ulong[] z = Nat192.FromBigInteger64(x);
Reduce29(z, 0);
return z;
}
public static void Multiply(ulong[] x, ulong[] y, ulong[] z)
{
ulong[] tt = Nat192.CreateExt64();
ImplMultiply(x, y, tt);
Reduce(tt, z);
}
public static void MultiplyAddToExt(ulong[] x, ulong[] y, ulong[] zz)
{
ulong[] tt = Nat192.CreateExt64();
ImplMultiply(x, y, tt);
AddExt(zz, tt, zz);
}
public static void Reduce(ulong[] xx, ulong[] z)
{
ulong x0 = xx[0], x1 = xx[1], x2 = xx[2], x3 = xx[3], x4 = xx[4], x5 = xx[5];
x2 ^= (x5 << 29) ^ (x5 << 32) ^ (x5 << 35) ^ (x5 << 36);
x3 ^= (x5 >> 35) ^ (x5 >> 32) ^ (x5 >> 29) ^ (x5 >> 28);
x1 ^= (x4 << 29) ^ (x4 << 32) ^ (x4 << 35) ^ (x4 << 36);
x2 ^= (x4 >> 35) ^ (x4 >> 32) ^ (x4 >> 29) ^ (x4 >> 28);
x0 ^= (x3 << 29) ^ (x3 << 32) ^ (x3 << 35) ^ (x3 << 36);
x1 ^= (x3 >> 35) ^ (x3 >> 32) ^ (x3 >> 29) ^ (x3 >> 28);
ulong t = x2 >> 35;
z[0] = x0 ^ t ^ (t << 3) ^ (t << 6) ^ (t << 7);
z[1] = x1;
z[2] = x2 & M35;
}
public static void Reduce29(ulong[] z, int zOff)
{
ulong z2 = z[zOff + 2], t = z2 >> 35;
z[zOff ] ^= t ^ (t << 3) ^ (t << 6) ^ (t << 7);
z[zOff + 2] = z2 & M35;
}
public static void Square(ulong[] x, ulong[] z)
{
ulong[] tt = Nat192.CreateExt64();
ImplSquare(x, tt);
Reduce(tt, z);
}
public static void SquareAddToExt(ulong[] x, ulong[] zz)
{
ulong[] tt = Nat192.CreateExt64();
ImplSquare(x, tt);
AddExt(zz, tt, zz);
}
public static void SquareN(ulong[] x, int n, ulong[] z)
{
Debug.Assert(n > 0);
ulong[] tt = Nat192.CreateExt64();
ImplSquare(x, tt);
Reduce(tt, z);
while (--n > 0)
{
ImplSquare(z, tt);
Reduce(tt, z);
}
}
protected static void ImplCompactExt(ulong[] zz)
{
ulong z0 = zz[0], z1 = zz[1], z2 = zz[2], z3 = zz[3], z4 = zz[4], z5 = zz[5];
zz[0] = z0 ^ (z1 << 55);
zz[1] = (z1 >> 9) ^ (z2 << 46);
zz[2] = (z2 >> 18) ^ (z3 << 37);
zz[3] = (z3 >> 27) ^ (z4 << 28);
zz[4] = (z4 >> 36) ^ (z5 << 19);
zz[5] = (z5 >> 45);
}
protected static void ImplMultiply(ulong[] x, ulong[] y, ulong[] zz)
{
/*
* "Five-way recursion" as described in "Batch binary Edwards", Daniel J. Bernstein.
*/
ulong f0 = x[0], f1 = x[1], f2 = x[2];
f2 = ((f1 >> 46) ^ (f2 << 18));
f1 = ((f0 >> 55) ^ (f1 << 9)) & M55;
f0 &= M55;
ulong g0 = y[0], g1 = y[1], g2 = y[2];
g2 = ((g1 >> 46) ^ (g2 << 18));
g1 = ((g0 >> 55) ^ (g1 << 9)) & M55;
g0 &= M55;
ulong[] H = new ulong[10];
ImplMulw(f0, g0, H, 0); // H(0) 55/54 bits
ImplMulw(f2, g2, H, 2); // H(INF) 55/50 bits
ulong t0 = f0 ^ f1 ^ f2;
ulong t1 = g0 ^ g1 ^ g2;
ImplMulw(t0, t1, H, 4); // H(1) 55/54 bits
ulong t2 = (f1 << 1) ^ (f2 << 2);
ulong t3 = (g1 << 1) ^ (g2 << 2);
ImplMulw(f0 ^ t2, g0 ^ t3, H, 6); // H(t) 55/56 bits
ImplMulw(t0 ^ t2, t1 ^ t3, H, 8); // H(t + 1) 55/56 bits
ulong t4 = H[6] ^ H[8];
ulong t5 = H[7] ^ H[9];
Debug.Assert(t5 >> 55 == 0);
// Calculate V
ulong v0 = (t4 << 1) ^ H[6];
ulong v1 = t4 ^ (t5 << 1) ^ H[7];
ulong v2 = t5;
// Calculate U
ulong u0 = H[0];
ulong u1 = H[1] ^ H[0] ^ H[4];
ulong u2 = H[1] ^ H[5];
// Calculate W
ulong w0 = u0 ^ v0 ^ (H[2] << 4) ^ (H[2] << 1);
ulong w1 = u1 ^ v1 ^ (H[3] << 4) ^ (H[3] << 1);
ulong w2 = u2 ^ v2;
// Propagate carries
w1 ^= (w0 >> 55); w0 &= M55;
w2 ^= (w1 >> 55); w1 &= M55;
Debug.Assert((w0 & 1UL) == 0UL);
// Divide W by t
w0 = (w0 >> 1) ^ ((w1 & 1UL) << 54);
w1 = (w1 >> 1) ^ ((w2 & 1UL) << 54);
w2 = (w2 >> 1);
// Divide W by (t + 1)
w0 ^= (w0 << 1);
w0 ^= (w0 << 2);
w0 ^= (w0 << 4);
w0 ^= (w0 << 8);
w0 ^= (w0 << 16);
w0 ^= (w0 << 32);
w0 &= M55; w1 ^= (w0 >> 54);
w1 ^= (w1 << 1);
w1 ^= (w1 << 2);
w1 ^= (w1 << 4);
w1 ^= (w1 << 8);
w1 ^= (w1 << 16);
w1 ^= (w1 << 32);
w1 &= M55; w2 ^= (w1 >> 54);
w2 ^= (w2 << 1);
w2 ^= (w2 << 2);
w2 ^= (w2 << 4);
w2 ^= (w2 << 8);
w2 ^= (w2 << 16);
w2 ^= (w2 << 32);
Debug.Assert(w2 >> 52 == 0);
zz[0] = u0;
zz[1] = u1 ^ w0 ^ H[2];
zz[2] = u2 ^ w1 ^ w0 ^ H[3];
zz[3] = w2 ^ w1;
zz[4] = w2 ^ H[2];
zz[5] = H[3];
ImplCompactExt(zz);
}
protected static void ImplMulw(ulong x, ulong y, ulong[] z, int zOff)
{
Debug.Assert(x >> 56 == 0);
Debug.Assert(y >> 56 == 0);
ulong[] u = new ulong[8];
// u[0] = 0;
u[1] = y;
u[2] = u[1] << 1;
u[3] = u[2] ^ y;
u[4] = u[2] << 1;
u[5] = u[4] ^ y;
u[6] = u[3] << 1;
u[7] = u[6] ^ y;
uint j = (uint)x;
ulong g, h = 0, l = u[j & 3];
int k = 47;
do
{
j = (uint)(x >> k);
g = u[j & 7]
^ u[(j >> 3) & 7] << 3
^ u[(j >> 6) & 7] << 6;
l ^= (g << k);
h ^= (g >> -k);
}
while ((k -= 9) > 0);
Debug.Assert(h >> 47 == 0);
z[zOff ] = l & M55;
z[zOff + 1] = (l >> 55) ^ (h << 9);
}
protected static void ImplSquare(ulong[] x, ulong[] zz)
{
Interleave.Expand64To128(x[0], zz, 0);
Interleave.Expand64To128(x[1], zz, 2);
ulong x2 = x[2];
zz[4] = Interleave.Expand32to64((uint)x2);
zz[5] = Interleave.Expand8to16((uint)(x2 >> 32));
}
}
}
#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.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Tests
{
public static class StackTests
{
[Fact]
public static void Ctor_Empty()
{
var stack = new Stack();
Assert.Equal(0, stack.Count);
Assert.False(stack.IsSynchronized);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
[InlineData(1000)]
public static void Ctor_Int(int initialCapacity)
{
var stack = new Stack(initialCapacity);
Assert.Equal(0, stack.Count);
Assert.False(stack.IsSynchronized);
}
[Fact]
public static void Ctor_Int_NegativeInitialCapacity_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("initialCapacity", () => new Stack(-1)); // InitialCapacity < 0
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
[InlineData(1000)]
[InlineData(10000)]
public static void Ctor_ICollection(int count)
{
var array = new object[count];
for (int i = 0; i < count; i++)
{
array[i] = i;
}
var stack = new Stack(array);
Assert.Equal(count, stack.Count);
Assert.False(stack.IsSynchronized);
for (int i = 0; i < count; i++)
{
Assert.Equal(count - i - 1, stack.Pop());
}
}
[Fact]
public static void Ctor_ICollection_NullCollection_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("col", () => new Stack(null)); // Collection is null
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public static void DebuggerAttribute()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(new Stack());
var stack = new Stack();
stack.Push("a");
stack.Push(1);
stack.Push("b");
stack.Push(2);
DebuggerAttributeInfo debuggerAttribute = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(stack);
PropertyInfo infoProperty = debuggerAttribute.Properties.Single(property => property.Name == "Items");
object[] items = (object[])infoProperty.GetValue(debuggerAttribute.Instance);
Assert.Equal(stack.ToArray(), items);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public static void DebuggerAttribute_NullStack_ThrowsArgumentNullException()
{
bool threwNull = false;
try
{
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(Stack), null);
}
catch (TargetInvocationException ex)
{
threwNull = ex.InnerException is ArgumentNullException;
}
Assert.True(threwNull);
}
[Fact]
public static void Clear()
{
Stack stack1 = Helpers.CreateIntStack(100);
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
stack2.Clear();
Assert.Equal(0, stack2.Count);
stack2.Clear();
Assert.Equal(0, stack2.Count);
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void Clone(int count)
{
Stack stack1 = Helpers.CreateIntStack(count);
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
Stack stackClone = (Stack)stack2.Clone();
Assert.Equal(stack2.Count, stackClone.Count);
Assert.Equal(stack2.IsSynchronized, stackClone.IsSynchronized);
for (int i = 0; i < stackClone.Count; i++)
{
Assert.Equal(stack2.Pop(), stackClone.Pop());
}
});
}
[Fact]
public static void Clone_IsShallowCopy()
{
var stack1 = new Stack();
stack1.Push(new Foo(10));
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
Stack stackClone = (Stack)stack2.Clone();
Foo a1 = (Foo)stack2.Pop();
a1.IntValue = 50;
Foo a2 = (Foo)stackClone.Pop();
Assert.Equal(50, a1.IntValue);
});
}
[Fact]
public static void Contains()
{
Stack stack1 = Helpers.CreateIntStack(100);
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
for (int i = 0; i < stack2.Count; i++)
{
Assert.True(stack2.Contains(i));
}
Assert.False(stack2.Contains(101));
Assert.False(stack2.Contains("hello"));
Assert.False(stack2.Contains(null));
stack2.Push(null);
Assert.True(stack2.Contains(null));
Assert.False(stack2.Contains(-1)); // We have a null item in the list, so the algorithm may use a different branch
});
}
[Theory]
[InlineData(0, 0)]
[InlineData(1, 0)]
[InlineData(10, 0)]
[InlineData(100, 0)]
[InlineData(1000, 0)]
[InlineData(10, 5)]
[InlineData(100, 50)]
[InlineData(1000, 500)]
public static void CopyTo_ObjectArray(int count, int index)
{
Stack stack1 = Helpers.CreateIntStack(count);
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
object[] oArray = new object[index + count];
stack2.CopyTo(oArray, index);
Assert.Equal(index + count, oArray.Length);
for (int i = index; i < count; i++)
{
Assert.Equal(stack2.Pop(), oArray[i]);
}
});
}
[Theory]
[InlineData(0, 0)]
[InlineData(1, 0)]
[InlineData(10, 0)]
[InlineData(100, 0)]
[InlineData(1000, 0)]
[InlineData(10, 5)]
[InlineData(100, 50)]
[InlineData(1000, 500)]
public static void CopyTo_IntArray(int count, int index)
{
Stack stack1 = Helpers.CreateIntStack(count);
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
int[] iArray = new int[index + count];
stack2.CopyTo(iArray, index);
Assert.Equal(index + count, iArray.Length);
for (int i = index; i < count; i++)
{
Assert.Equal(stack2.Pop(), iArray[i]);
}
});
}
[Fact]
public static void CopyTo_Invalid()
{
Stack stack1 = Helpers.CreateIntStack(100);
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
AssertExtensions.Throws<ArgumentNullException>("array", () => stack2.CopyTo(null, 0)); // Array is null
Assert.Throws<ArgumentException>(() => stack2.CopyTo(new object[10, 10], 0)); // Array is multidimensional
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => stack2.CopyTo(new object[100], -1)); // Index < 0
Assert.Throws<ArgumentException>(null, () => stack2.CopyTo(new object[0], 0)); // Index >= array.Count
Assert.Throws<ArgumentException>(null, () => stack2.CopyTo(new object[100], 1)); // Index + array.Count > stack.Count
Assert.Throws<ArgumentException>(null, () => stack2.CopyTo(new object[150], 51)); // Index + array.Count > stack.Count
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void GetEnumerator(int count)
{
Stack stack1 = Helpers.CreateIntStack(count);
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
Assert.NotSame(stack2.GetEnumerator(), stack2.GetEnumerator());
IEnumerator enumerator = stack2.GetEnumerator();
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator.MoveNext())
{
counter++;
Assert.NotNull(enumerator.Current);
}
Assert.Equal(count, counter);
enumerator.Reset();
}
});
}
[Fact]
public static void GetEnumerator_StartOfEnumeration_Clone()
{
Stack stack = Helpers.CreateIntStack(10);
IEnumerator enumerator = stack.GetEnumerator();
ICloneable cloneableEnumerator = (ICloneable)enumerator;
IEnumerator clonedEnumerator = (IEnumerator)cloneableEnumerator.Clone();
Assert.NotSame(enumerator, clonedEnumerator);
// Cloned and original enumerators should enumerate separately.
Assert.True(enumerator.MoveNext());
Assert.Equal(stack.Count - 1, enumerator.Current);
Assert.Throws<InvalidOperationException>(() => clonedEnumerator.Current);
Assert.True(clonedEnumerator.MoveNext());
Assert.Equal(stack.Count - 1, enumerator.Current);
Assert.Equal(stack.Count - 1, clonedEnumerator.Current);
// Cloned and original enumerators should enumerate in the same sequence.
for (int i = 1; i < stack.Count; i++)
{
Assert.True(enumerator.MoveNext());
Assert.NotEqual(enumerator.Current, clonedEnumerator.Current);
Assert.True(clonedEnumerator.MoveNext());
Assert.Equal(enumerator.Current, clonedEnumerator.Current);
}
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Equal(0, clonedEnumerator.Current);
Assert.False(clonedEnumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => clonedEnumerator.Current);
}
[Fact]
public static void GetEnumerator_InMiddleOfEnumeration_Clone()
{
Stack stack = Helpers.CreateIntStack(10);
IEnumerator enumerator = stack.GetEnumerator();
enumerator.MoveNext();
ICloneable cloneableEnumerator = (ICloneable)enumerator;
// Cloned and original enumerators should start at the same spot, even
// if the original is in the middle of enumeration.
IEnumerator clonedEnumerator = (IEnumerator)cloneableEnumerator.Clone();
Assert.Equal(enumerator.Current, clonedEnumerator.Current);
for (int i = 0; i < stack.Count - 1; i++)
{
Assert.True(clonedEnumerator.MoveNext());
}
Assert.False(clonedEnumerator.MoveNext());
}
[Fact]
public static void GetEnumerator_Invalid()
{
Stack stack1 = Helpers.CreateIntStack(100);
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
IEnumerator enumerator = stack2.GetEnumerator();
// Index < 0
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Index > dictionary.Count
while (enumerator.MoveNext()) ;
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current throws after resetting
enumerator.Reset();
Assert.True(enumerator.MoveNext());
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// MoveNext and Reset throws after stack is modified, but current doesn't
enumerator = stack2.GetEnumerator();
enumerator.MoveNext();
stack2.Push("hi");
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
Assert.NotNull(enumerator.Current);
enumerator = stack2.GetEnumerator();
enumerator.MoveNext();
stack2.Pop();
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
Assert.NotNull(enumerator.Current);
});
}
[Fact]
public static void Peek()
{
int count = 100;
Stack stack1 = Helpers.CreateIntStack(count);
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
for (int i = 0; i < count; i++)
{
int peek1 = (int)stack2.Peek();
int peek2 = (int)stack2.Peek();
Assert.Equal(peek1, peek2);
Assert.Equal(stack2.Pop(), peek1);
Assert.Equal(count - i - 1, peek1);
}
});
}
[Fact]
public static void Peek_EmptyStack_ThrowsInvalidOperationException()
{
var stack1 = new Stack();
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
Assert.Throws<InvalidOperationException>(() => stack2.Peek()); // Empty stack
for (int i = 0; i < 1000; i++)
{
stack2.Push(i);
}
for (int i = 0; i < 1000; i++)
{
stack2.Pop();
}
Assert.Throws<InvalidOperationException>(() => stack2.Peek()); // Empty stack
});
}
[Theory]
[InlineData(1, 1)]
[InlineData(10, 10)]
[InlineData(100, 100)]
[InlineData(1000, 1000)]
[InlineData(10, 5)]
[InlineData(100, 50)]
[InlineData(1000, 500)]
public static void Pop(int pushCount, int popCount)
{
Stack stack1 = Helpers.CreateIntStack(pushCount);
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
for (int i = 0; i < popCount; i++)
{
Assert.Equal(pushCount - i - 1, stack2.Pop());
Assert.Equal(pushCount - i - 1, stack2.Count);
}
Assert.Equal(pushCount - popCount, stack2.Count);
});
}
[Fact]
public static void Pop_Null()
{
var stack1 = new Stack();
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
stack2.Push(null);
stack2.Push(-1);
stack2.Push(null);
Assert.Equal(null, stack2.Pop());
Assert.Equal(-1, stack2.Pop());
Assert.Equal(null, stack2.Pop());
});
}
[Fact]
public static void Pop_EmptyStack_ThrowsInvalidOperationException()
{
var stack1 = new Stack();
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
Assert.Throws<InvalidOperationException>(() => stack2.Pop()); // Empty stack
});
}
[Theory]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
[InlineData(1000)]
public static void Push(int count)
{
var stack1 = new Stack();
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
for (int i = 0; i < count; i++)
{
stack2.Push(i);
Assert.Equal(i + 1, stack2.Count);
}
Assert.Equal(count, stack2.Count);
});
}
[Fact]
public static void Push_Null()
{
var stack1 = new Stack();
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
stack2.Push(null);
stack2.Push(-1);
stack2.Push(null);
Assert.True(stack2.Contains(null));
Assert.True(stack2.Contains(-1));
});
}
[Fact]
public static void Synchronized_IsSynchronized()
{
Stack stack = Stack.Synchronized(new Stack());
Assert.True(stack.IsSynchronized);
}
[Fact]
public static void Synchronized_NullStack_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("stack", () => Stack.Synchronized(null)); // Stack is null
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void ToArray(int count)
{
Stack stack1 = Helpers.CreateIntStack(count);
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
object[] array = stack2.ToArray();
Assert.Equal(stack2.Count, array.Length);
for (int i = 0; i < array.Length; i++)
{
Assert.Equal(stack2.Pop(), array[i]);
}
});
}
private class Foo
{
public Foo(int intValue)
{
IntValue = intValue;
}
public int IntValue { get; set; }
}
}
public class Stack_SyncRootTests
{
private Stack _stackDaughter;
private Stack _stackGrandDaughter;
private const int NumberOfElements = 100;
[Fact]
public void GetSyncRootBasic()
{
// Testing SyncRoot is not as simple as its implementation looks like. This is the working
// scenario we have in mind.
// 1) Create your Down to earth mother Stack
// 2) Get a Fixed 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 stackMother = new Stack();
for (int i = 0; i < NumberOfElements; i++)
{
stackMother.Push(i);
}
Assert.Equal(typeof(object), stackMother.SyncRoot.GetType());
Stack stackSon = Stack.Synchronized(stackMother);
_stackGrandDaughter = Stack.Synchronized(stackSon);
_stackDaughter = Stack.Synchronized(stackMother);
Assert.Equal(stackSon.SyncRoot, stackMother.SyncRoot);
Assert.Equal(_stackGrandDaughter.SyncRoot, stackMother.SyncRoot);
Assert.Equal(_stackDaughter.SyncRoot, stackMother.SyncRoot);
Assert.Equal(stackSon.SyncRoot, stackMother.SyncRoot);
// We are going to rumble with the Stacks with 2 threads
Action ts1 = SortElements;
Action ts2 = ReverseElements;
var tasks = new Task[4];
for (int iThreads = 0; iThreads < tasks.Length; iThreads += 2)
{
tasks[iThreads] = Task.Run(ts1);
tasks[iThreads + 1] = Task.Run(ts2);
}
Task.WaitAll(tasks);
}
private void SortElements()
{
_stackGrandDaughter.Clear();
for (int i = 0; i < NumberOfElements; i++)
{
_stackGrandDaughter.Push(i);
}
}
private void ReverseElements()
{
_stackDaughter.Clear();
for (int i = 0; i < NumberOfElements; i++)
{
_stackDaughter.Push(i);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace MaterialDesignThemes.Wpf
{
[TemplateVisualState(GroupName = TemplateAllDrawersGroupName, Name = TemplateAllDrawersAllClosedStateName)]
[TemplateVisualState(GroupName = TemplateAllDrawersGroupName, Name = TemplateAllDrawersAnyOpenStateName)]
[TemplateVisualState(GroupName = TemplateLeftDrawerGroupName, Name = TemplateLeftClosedStateName)]
[TemplateVisualState(GroupName = TemplateLeftDrawerGroupName, Name = TemplateLeftOpenStateName)]
[TemplateVisualState(GroupName = TemplateTopDrawerGroupName, Name = TemplateTopClosedStateName)]
[TemplateVisualState(GroupName = TemplateTopDrawerGroupName, Name = TemplateTopOpenStateName)]
[TemplateVisualState(GroupName = TemplateRightDrawerGroupName, Name = TemplateRightClosedStateName)]
[TemplateVisualState(GroupName = TemplateRightDrawerGroupName, Name = TemplateRightOpenStateName)]
[TemplateVisualState(GroupName = TemplateBottomDrawerGroupName, Name = TemplateBottomClosedStateName)]
[TemplateVisualState(GroupName = TemplateBottomDrawerGroupName, Name = TemplateBottomOpenStateName)]
[TemplatePart(Name = TemplateContentCoverPartName, Type = typeof(FrameworkElement))]
[TemplatePart(Name = TemplateLeftDrawerPartName, Type = typeof(FrameworkElement))]
[TemplatePart(Name = TemplateTopDrawerPartName, Type = typeof(FrameworkElement))]
[TemplatePart(Name = TemplateRightDrawerPartName, Type = typeof(FrameworkElement))]
[TemplatePart(Name = TemplateBottomDrawerPartName, Type = typeof(FrameworkElement))]
public class DrawerHost : ContentControl
{
public const string TemplateAllDrawersGroupName = "AllDrawers";
public const string TemplateAllDrawersAllClosedStateName = "AllClosed";
public const string TemplateAllDrawersAnyOpenStateName = "AnyOpen";
public const string TemplateLeftDrawerGroupName = "LeftDrawer";
public const string TemplateLeftClosedStateName = "LeftDrawerClosed";
public const string TemplateLeftOpenStateName = "LeftDrawerOpen";
public const string TemplateTopDrawerGroupName = "TopDrawer";
public const string TemplateTopClosedStateName = "TopDrawerClosed";
public const string TemplateTopOpenStateName = "TopDrawerOpen";
public const string TemplateRightDrawerGroupName = "RightDrawer";
public const string TemplateRightClosedStateName = "RightDrawerClosed";
public const string TemplateRightOpenStateName = "RightDrawerOpen";
public const string TemplateBottomDrawerGroupName = "BottomDrawer";
public const string TemplateBottomClosedStateName = "BottomDrawerClosed";
public const string TemplateBottomOpenStateName = "BottomDrawerOpen";
public const string TemplateContentCoverPartName = "PART_ContentCover";
public const string TemplateLeftDrawerPartName = "PART_LeftDrawer";
public const string TemplateTopDrawerPartName = "PART_TopDrawer";
public const string TemplateRightDrawerPartName = "PART_RightDrawer";
public const string TemplateBottomDrawerPartName = "PART_BottomDrawer";
public static readonly RoutedCommand OpenDrawerCommand = new();
public static readonly RoutedCommand CloseDrawerCommand = new();
private FrameworkElement? _templateContentCoverElement;
private FrameworkElement? _leftDrawerElement;
private FrameworkElement? _topDrawerElement;
private FrameworkElement? _rightDrawerElement;
private FrameworkElement? _bottomDrawerElement;
private bool _lockZIndexes;
private readonly IDictionary<DependencyProperty, DependencyPropertyKey> _zIndexPropertyLookup = new Dictionary<DependencyProperty, DependencyPropertyKey>
{
{ IsLeftDrawerOpenProperty, LeftDrawerZIndexPropertyKey },
{ IsTopDrawerOpenProperty, TopDrawerZIndexPropertyKey },
{ IsRightDrawerOpenProperty, RightDrawerZIndexPropertyKey },
{ IsBottomDrawerOpenProperty, BottomDrawerZIndexPropertyKey }
};
static DrawerHost()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(DrawerHost), new FrameworkPropertyMetadata(typeof(DrawerHost)));
}
public DrawerHost()
{
CommandBindings.Add(new CommandBinding(OpenDrawerCommand, OpenDrawerHandler));
CommandBindings.Add(new CommandBinding(CloseDrawerCommand, CloseDrawerHandler));
}
public static readonly DependencyProperty OverlayBackgroundProperty = DependencyProperty.Register(
nameof(OverlayBackground), typeof(Brush), typeof(DrawerHost), new PropertyMetadata(default(Brush)));
public Brush? OverlayBackground
{
get => (Brush?)GetValue(OverlayBackgroundProperty);
set => SetValue(OverlayBackgroundProperty, value);
}
public DrawerHostOpenMode OpenMode
{
get => (DrawerHostOpenMode)GetValue(OpenModeProperty);
set => SetValue(OpenModeProperty, value);
}
public static readonly DependencyProperty OpenModeProperty =
DependencyProperty.Register("OpenMode", typeof(DrawerHostOpenMode), typeof(DrawerHost), new PropertyMetadata(DrawerHostOpenMode.Default));
#region top drawer
public static readonly DependencyProperty TopDrawerContentProperty = DependencyProperty.Register(
nameof(TopDrawerContent), typeof(object), typeof(DrawerHost), new PropertyMetadata(default(object)));
public object? TopDrawerContent
{
get => GetValue(TopDrawerContentProperty);
set => SetValue(TopDrawerContentProperty, value);
}
public static readonly DependencyProperty TopDrawerContentTemplateProperty = DependencyProperty.Register(
nameof(TopDrawerContentTemplate), typeof(DataTemplate), typeof(DrawerHost), new PropertyMetadata(default(DataTemplate)));
public DataTemplate? TopDrawerContentTemplate
{
get => (DataTemplate?)GetValue(TopDrawerContentTemplateProperty);
set => SetValue(TopDrawerContentTemplateProperty, value);
}
public static readonly DependencyProperty TopDrawerContentTemplateSelectorProperty = DependencyProperty.Register(
nameof(TopDrawerContentTemplateSelector), typeof(DataTemplateSelector), typeof(DrawerHost), new PropertyMetadata(default(DataTemplateSelector)));
public DataTemplateSelector? TopDrawerContentTemplateSelector
{
get => (DataTemplateSelector?)GetValue(TopDrawerContentTemplateSelectorProperty);
set => SetValue(TopDrawerContentTemplateSelectorProperty, value);
}
public static readonly DependencyProperty TopDrawerContentStringFormatProperty = DependencyProperty.Register(
nameof(TopDrawerContentStringFormat), typeof(string), typeof(DrawerHost), new PropertyMetadata(default(string)));
public string? TopDrawerContentStringFormat
{
get => (string?)GetValue(TopDrawerContentStringFormatProperty);
set => SetValue(TopDrawerContentStringFormatProperty, value);
}
public static readonly DependencyProperty TopDrawerBackgroundProperty = DependencyProperty.Register(
nameof(TopDrawerBackground), typeof(Brush), typeof(DrawerHost), new PropertyMetadata(default(Brush)));
public Brush? TopDrawerBackground
{
get => (Brush?)GetValue(TopDrawerBackgroundProperty);
set => SetValue(TopDrawerBackgroundProperty, value);
}
public static readonly DependencyProperty IsTopDrawerOpenProperty = DependencyProperty.Register(
nameof(IsTopDrawerOpen), typeof(bool), typeof(DrawerHost), new FrameworkPropertyMetadata(default(bool), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, IsTopDrawerOpenPropertyChangedCallback));
public bool IsTopDrawerOpen
{
get => (bool)GetValue(IsTopDrawerOpenProperty);
set => SetValue(IsTopDrawerOpenProperty, value);
}
private static readonly DependencyPropertyKey TopDrawerZIndexPropertyKey =
DependencyProperty.RegisterReadOnly(
"TopDrawerZIndex", typeof(int), typeof(DrawerHost),
new PropertyMetadata(4));
public static readonly DependencyProperty TopDrawerZIndexProperty = TopDrawerZIndexPropertyKey.DependencyProperty;
public int TopDrawerZIndex
{
get => (int)GetValue(TopDrawerZIndexProperty);
private set => SetValue(TopDrawerZIndexPropertyKey, value);
}
public static readonly DependencyProperty TopDrawerCloseOnClickAwayProperty = DependencyProperty.Register(
nameof(TopDrawerCloseOnClickAway), typeof(bool), typeof(DrawerHost), new PropertyMetadata(true));
public bool TopDrawerCloseOnClickAway
{
get => (bool)GetValue(TopDrawerCloseOnClickAwayProperty);
set => SetValue(TopDrawerCloseOnClickAwayProperty, value);
}
public static readonly DependencyProperty TopDrawerCornerRadiusProperty = DependencyProperty.Register(
nameof(TopDrawerCornerRadius), typeof(CornerRadius), typeof(DrawerHost), new PropertyMetadata(default(CornerRadius)));
public CornerRadius? TopDrawerCornerRadius
{
get => (CornerRadius?)GetValue(TopDrawerCornerRadiusProperty);
set => SetValue(TopDrawerCornerRadiusProperty, value);
}
#endregion
#region left drawer
public static readonly DependencyProperty LeftDrawerContentProperty = DependencyProperty.Register(
nameof(LeftDrawerContent), typeof(object), typeof(DrawerHost), new PropertyMetadata(default(object)));
public object? LeftDrawerContent
{
get => GetValue(LeftDrawerContentProperty);
set => SetValue(LeftDrawerContentProperty, value);
}
public static readonly DependencyProperty LeftDrawerContentTemplateProperty = DependencyProperty.Register(
nameof(LeftDrawerContentTemplate), typeof(DataTemplate), typeof(DrawerHost), new PropertyMetadata(default(DataTemplate)));
public DataTemplate? LeftDrawerContentTemplate
{
get => (DataTemplate?)GetValue(LeftDrawerContentTemplateProperty);
set => SetValue(LeftDrawerContentTemplateProperty, value);
}
public static readonly DependencyProperty LeftDrawerContentTemplateSelectorProperty = DependencyProperty.Register(
nameof(LeftDrawerContentTemplateSelector), typeof(DataTemplateSelector), typeof(DrawerHost), new PropertyMetadata(default(DataTemplateSelector)));
public DataTemplateSelector? LeftDrawerContentTemplateSelector
{
get => (DataTemplateSelector?)GetValue(LeftDrawerContentTemplateSelectorProperty);
set => SetValue(LeftDrawerContentTemplateSelectorProperty, value);
}
public static readonly DependencyProperty LeftDrawerContentStringFormatProperty = DependencyProperty.Register(
nameof(LeftDrawerContentStringFormat), typeof(string), typeof(DrawerHost), new PropertyMetadata(default(string)));
public string? LeftDrawerContentStringFormat
{
get => (string?)GetValue(LeftDrawerContentStringFormatProperty);
set => SetValue(LeftDrawerContentStringFormatProperty, value);
}
public static readonly DependencyProperty LeftDrawerBackgroundProperty = DependencyProperty.Register(
nameof(LeftDrawerBackground), typeof(Brush), typeof(DrawerHost), new PropertyMetadata(default(Brush)));
public Brush? LeftDrawerBackground
{
get => (Brush?)GetValue(LeftDrawerBackgroundProperty);
set => SetValue(LeftDrawerBackgroundProperty, value);
}
public static readonly DependencyProperty IsLeftDrawerOpenProperty = DependencyProperty.Register(
nameof(IsLeftDrawerOpen), typeof(bool), typeof(DrawerHost), new FrameworkPropertyMetadata(default(bool), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, IsLeftDrawerOpenPropertyChangedCallback));
public bool IsLeftDrawerOpen
{
get => (bool)GetValue(IsLeftDrawerOpenProperty);
set => SetValue(IsLeftDrawerOpenProperty, value);
}
private static readonly DependencyPropertyKey LeftDrawerZIndexPropertyKey =
DependencyProperty.RegisterReadOnly(
"LeftDrawerZIndex", typeof(int), typeof(DrawerHost),
new PropertyMetadata(2));
public static readonly DependencyProperty LeftDrawerZIndexProperty = LeftDrawerZIndexPropertyKey.DependencyProperty;
public int LeftDrawerZIndex
{
get => (int)GetValue(LeftDrawerZIndexProperty);
private set => SetValue(LeftDrawerZIndexPropertyKey, value);
}
public static readonly DependencyProperty LeftDrawerCloseOnClickAwayProperty = DependencyProperty.Register(
nameof(LeftDrawerCloseOnClickAway), typeof(bool), typeof(DrawerHost), new PropertyMetadata(true));
public bool LeftDrawerCloseOnClickAway
{
get => (bool)GetValue(LeftDrawerCloseOnClickAwayProperty);
set => SetValue(LeftDrawerCloseOnClickAwayProperty, value);
}
public static readonly DependencyProperty LeftDrawerCornerRadiusProperty = DependencyProperty.Register(
nameof(LeftDrawerCornerRadius), typeof(CornerRadius), typeof(DrawerHost), new PropertyMetadata(default(CornerRadius)));
public CornerRadius? LeftDrawerCornerRadius
{
get => (CornerRadius?)GetValue(LeftDrawerCornerRadiusProperty);
set => SetValue(LeftDrawerCornerRadiusProperty, value);
}
#endregion
#region right drawer
public static readonly DependencyProperty RightDrawerContentProperty = DependencyProperty.Register(
nameof(RightDrawerContent), typeof(object), typeof(DrawerHost), new PropertyMetadata(default(object)));
public object? RightDrawerContent
{
get => GetValue(RightDrawerContentProperty);
set => SetValue(RightDrawerContentProperty, value);
}
public static readonly DependencyProperty RightDrawerContentTemplateProperty = DependencyProperty.Register(
nameof(RightDrawerContentTemplate), typeof(DataTemplate), typeof(DrawerHost), new PropertyMetadata(default(DataTemplate)));
public DataTemplate? RightDrawerContentTemplate
{
get => (DataTemplate?)GetValue(RightDrawerContentTemplateProperty);
set => SetValue(RightDrawerContentTemplateProperty, value);
}
public static readonly DependencyProperty RightDrawerContentTemplateSelectorProperty = DependencyProperty.Register(
nameof(RightDrawerContentTemplateSelector), typeof(DataTemplateSelector), typeof(DrawerHost), new PropertyMetadata(default(DataTemplateSelector)));
public DataTemplateSelector? RightDrawerContentTemplateSelector
{
get => (DataTemplateSelector?)GetValue(RightDrawerContentTemplateSelectorProperty);
set => SetValue(RightDrawerContentTemplateSelectorProperty, value);
}
public static readonly DependencyProperty RightDrawerContentStringFormatProperty = DependencyProperty.Register(
nameof(RightDrawerContentStringFormat), typeof(string), typeof(DrawerHost), new PropertyMetadata(default(string)));
public string? RightDrawerContentStringFormat
{
get => (string?)GetValue(RightDrawerContentStringFormatProperty);
set => SetValue(RightDrawerContentStringFormatProperty, value);
}
public static readonly DependencyProperty RightDrawerBackgroundProperty = DependencyProperty.Register(
nameof(RightDrawerBackground), typeof(Brush), typeof(DrawerHost), new PropertyMetadata(default(Brush)));
public Brush? RightDrawerBackground
{
get => (Brush?)GetValue(RightDrawerBackgroundProperty);
set => SetValue(RightDrawerBackgroundProperty, value);
}
public static readonly DependencyProperty IsRightDrawerOpenProperty = DependencyProperty.Register(
nameof(IsRightDrawerOpen), typeof(bool), typeof(DrawerHost), new FrameworkPropertyMetadata(default(bool), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, IsRightDrawerOpenPropertyChangedCallback));
public bool IsRightDrawerOpen
{
get => (bool)GetValue(IsRightDrawerOpenProperty);
set => SetValue(IsRightDrawerOpenProperty, value);
}
private static readonly DependencyPropertyKey RightDrawerZIndexPropertyKey =
DependencyProperty.RegisterReadOnly(
"RightDrawerZIndex", typeof(int), typeof(DrawerHost),
new PropertyMetadata(1));
public static readonly DependencyProperty RightDrawerZIndexProperty = RightDrawerZIndexPropertyKey.DependencyProperty;
public int RightDrawerZIndex
{
get => (int)GetValue(RightDrawerZIndexProperty);
private set => SetValue(RightDrawerZIndexPropertyKey, value);
}
public static readonly DependencyProperty RightDrawerCloseOnClickAwayProperty = DependencyProperty.Register(
nameof(RightDrawerCloseOnClickAway), typeof(bool), typeof(DrawerHost), new PropertyMetadata(true));
public bool RightDrawerCloseOnClickAway
{
get => (bool)GetValue(RightDrawerCloseOnClickAwayProperty);
set => SetValue(RightDrawerCloseOnClickAwayProperty, value);
}
public static readonly DependencyProperty RightDrawerCornerRadiusProperty = DependencyProperty.Register(
nameof(RightDrawerCornerRadius), typeof(CornerRadius), typeof(DrawerHost), new PropertyMetadata(default(CornerRadius)));
public CornerRadius? RightDrawerCornerRadius
{
get => (CornerRadius?)GetValue(RightDrawerCornerRadiusProperty);
set => SetValue(RightDrawerCornerRadiusProperty, value);
}
#endregion
#region bottom drawer
public static readonly DependencyProperty BottomDrawerContentProperty = DependencyProperty.Register(
nameof(BottomDrawerContent), typeof(object), typeof(DrawerHost), new PropertyMetadata(default(object)));
public object? BottomDrawerContent
{
get => GetValue(BottomDrawerContentProperty);
set => SetValue(BottomDrawerContentProperty, value);
}
public static readonly DependencyProperty BottomDrawerContentTemplateProperty = DependencyProperty.Register(
nameof(BottomDrawerContentTemplate), typeof(DataTemplate), typeof(DrawerHost), new PropertyMetadata(default(DataTemplate)));
public DataTemplate? BottomDrawerContentTemplate
{
get => (DataTemplate?)GetValue(BottomDrawerContentTemplateProperty);
set => SetValue(BottomDrawerContentTemplateProperty, value);
}
public static readonly DependencyProperty BottomDrawerContentTemplateSelectorProperty = DependencyProperty.Register(
nameof(BottomDrawerContentTemplateSelector), typeof(DataTemplateSelector), typeof(DrawerHost), new PropertyMetadata(default(DataTemplateSelector)));
public DataTemplateSelector? BottomDrawerContentTemplateSelector
{
get => (DataTemplateSelector?)GetValue(BottomDrawerContentTemplateSelectorProperty);
set => SetValue(BottomDrawerContentTemplateSelectorProperty, value);
}
public static readonly DependencyProperty BottomDrawerContentStringFormatProperty = DependencyProperty.Register(
nameof(BottomDrawerContentStringFormat), typeof(string), typeof(DrawerHost), new PropertyMetadata(default(string)));
public string? BottomDrawerContentStringFormat
{
get => (string?)GetValue(BottomDrawerContentStringFormatProperty);
set => SetValue(BottomDrawerContentStringFormatProperty, value);
}
public static readonly DependencyProperty BottomDrawerBackgroundProperty = DependencyProperty.Register(
nameof(BottomDrawerBackground), typeof(Brush), typeof(DrawerHost), new PropertyMetadata(default(Brush)));
public Brush? BottomDrawerBackground
{
get => (Brush?)GetValue(BottomDrawerBackgroundProperty);
set => SetValue(BottomDrawerBackgroundProperty, value);
}
public static readonly DependencyProperty IsBottomDrawerOpenProperty = DependencyProperty.Register(
nameof(IsBottomDrawerOpen), typeof(bool), typeof(DrawerHost), new FrameworkPropertyMetadata(default(bool), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, IsBottomDrawerOpenPropertyChangedCallback));
public bool IsBottomDrawerOpen
{
get => (bool)GetValue(IsBottomDrawerOpenProperty);
set => SetValue(IsBottomDrawerOpenProperty, value);
}
private static readonly DependencyPropertyKey BottomDrawerZIndexPropertyKey =
DependencyProperty.RegisterReadOnly(
"BottomDrawerZIndex", typeof(int), typeof(DrawerHost),
new PropertyMetadata(3));
public static readonly DependencyProperty BottomDrawerZIndexProperty = BottomDrawerZIndexPropertyKey.DependencyProperty;
public int BottomDrawerZIndex
{
get => (int)GetValue(BottomDrawerZIndexProperty);
private set => SetValue(BottomDrawerZIndexPropertyKey, value);
}
public static readonly DependencyProperty BottomDrawerCloseOnClickAwayProperty = DependencyProperty.Register(
nameof(BottomDrawerCloseOnClickAway), typeof(bool), typeof(DrawerHost), new PropertyMetadata(true));
public bool BottomDrawerCloseOnClickAway
{
get => (bool)GetValue(BottomDrawerCloseOnClickAwayProperty);
set => SetValue(BottomDrawerCloseOnClickAwayProperty, value);
}
public static readonly DependencyProperty BottomDrawerCornerRadiusProperty = DependencyProperty.Register(
nameof(BottomDrawerCornerRadius), typeof(CornerRadius), typeof(DrawerHost), new PropertyMetadata(default(CornerRadius)));
public CornerRadius? BottomDrawerCornerRadius
{
get => (CornerRadius?)GetValue(BottomDrawerCornerRadiusProperty);
set => SetValue(BottomDrawerCornerRadiusProperty, value);
}
#endregion
#region open drawer events/callbacks
public static readonly RoutedEvent DrawerOpenedEvent =
EventManager.RegisterRoutedEvent(
"DrawerOpened",
RoutingStrategy.Bubble,
typeof(EventHandler<DrawerOpenedEventArgs>),
typeof(DrawerHost));
/// <summary>
/// Raised when a drawer is opened.
/// </summary>
public event EventHandler<DrawerOpenedEventArgs> DrawerOpened
{
add { AddHandler(DrawerOpenedEvent, value); }
remove { RemoveHandler(DrawerOpenedEvent, value); }
}
protected void OnDrawerOpened(DrawerOpenedEventArgs eventArgs) => RaiseEvent(eventArgs);
#endregion
#region close drawer events/callbacks
public static readonly RoutedEvent DrawerClosingEvent =
EventManager.RegisterRoutedEvent(
"DrawerClosing",
RoutingStrategy.Bubble,
typeof(EventHandler<DrawerClosingEventArgs>),
typeof(DrawerHost));
/// <summary>
/// Raised when a drawer is closing.
/// </summary>
public event EventHandler<DrawerClosingEventArgs> DrawerClosing
{
add { AddHandler(DrawerClosingEvent, value); }
remove { RemoveHandler(DrawerClosingEvent, value); }
}
protected void OnDrawerClosing(DrawerClosingEventArgs eventArgs) => RaiseEvent(eventArgs);
#endregion
public override void OnApplyTemplate()
{
if (_templateContentCoverElement != null)
_templateContentCoverElement.PreviewMouseLeftButtonUp += TemplateContentCoverElementOnPreviewMouseLeftButtonUp;
WireDrawer(_leftDrawerElement, true);
WireDrawer(_topDrawerElement, true);
WireDrawer(_rightDrawerElement, true);
WireDrawer(_bottomDrawerElement, true);
base.OnApplyTemplate();
_templateContentCoverElement = GetTemplateChild(TemplateContentCoverPartName) as FrameworkElement;
if (_templateContentCoverElement != null)
_templateContentCoverElement.PreviewMouseLeftButtonUp += TemplateContentCoverElementOnPreviewMouseLeftButtonUp;
_leftDrawerElement = WireDrawer(GetTemplateChild(TemplateLeftDrawerPartName) as FrameworkElement, false);
_topDrawerElement = WireDrawer(GetTemplateChild(TemplateTopDrawerPartName) as FrameworkElement, false);
_rightDrawerElement = WireDrawer(GetTemplateChild(TemplateRightDrawerPartName) as FrameworkElement, false);
_bottomDrawerElement = WireDrawer(GetTemplateChild(TemplateBottomDrawerPartName) as FrameworkElement, false);
UpdateVisualStates(false);
}
private FrameworkElement? WireDrawer(FrameworkElement? drawerElement, bool unwire)
{
if (drawerElement is null) return null;
if (unwire)
{
drawerElement.GotFocus -= DrawerElement_GotFocus;
drawerElement.MouseDown -= DrawerElement_MouseDown;
return drawerElement;
}
drawerElement.GotFocus += DrawerElement_GotFocus;
drawerElement.MouseDown += DrawerElement_MouseDown;
return drawerElement;
}
private void DrawerElement_MouseDown(object sender, MouseButtonEventArgs e) => ReactToFocus(sender);
private void DrawerElement_GotFocus(object sender, RoutedEventArgs e) => ReactToFocus(sender);
private void ReactToFocus(object sender)
{
if (sender == _leftDrawerElement)
PrepareZIndexes(LeftDrawerZIndexPropertyKey);
else if (sender == _topDrawerElement)
PrepareZIndexes(TopDrawerZIndexPropertyKey);
else if (sender == _rightDrawerElement)
PrepareZIndexes(RightDrawerZIndexPropertyKey);
else if (sender == _bottomDrawerElement)
PrepareZIndexes(BottomDrawerZIndexPropertyKey);
}
private void TemplateContentCoverElementOnPreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
if (LeftDrawerCloseOnClickAway)
SetCurrentValue(IsLeftDrawerOpenProperty, false);
if (RightDrawerCloseOnClickAway)
SetCurrentValue(IsRightDrawerOpenProperty, false);
if (TopDrawerCloseOnClickAway)
SetCurrentValue(IsTopDrawerOpenProperty, false);
if (BottomDrawerCloseOnClickAway)
SetCurrentValue(IsBottomDrawerOpenProperty, false);
}
private void UpdateVisualStates(bool? useTransitions = null)
{
var anyOpen = IsTopDrawerOpen || IsLeftDrawerOpen || IsBottomDrawerOpen || IsRightDrawerOpen;
VisualStateManager.GoToState(this,
!anyOpen ? TemplateAllDrawersAllClosedStateName : TemplateAllDrawersAnyOpenStateName, useTransitions ?? !TransitionAssist.GetDisableTransitions(this));
VisualStateManager.GoToState(this,
IsLeftDrawerOpen ? TemplateLeftOpenStateName : TemplateLeftClosedStateName, useTransitions ?? !TransitionAssist.GetDisableTransitions(this));
VisualStateManager.GoToState(this,
IsTopDrawerOpen ? TemplateTopOpenStateName : TemplateTopClosedStateName, useTransitions ?? !TransitionAssist.GetDisableTransitions(this));
VisualStateManager.GoToState(this,
IsRightDrawerOpen ? TemplateRightOpenStateName : TemplateRightClosedStateName, useTransitions ?? !TransitionAssist.GetDisableTransitions(this));
VisualStateManager.GoToState(this,
IsBottomDrawerOpen ? TemplateBottomOpenStateName : TemplateBottomClosedStateName, useTransitions ?? !TransitionAssist.GetDisableTransitions(this));
}
private static void IsTopDrawerOpenPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
=> IsDrawerOpenPropertyChanged(dependencyObject, dependencyPropertyChangedEventArgs, Dock.Top);
private static void IsLeftDrawerOpenPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
=> IsDrawerOpenPropertyChanged(dependencyObject, dependencyPropertyChangedEventArgs, Dock.Left);
private static void IsRightDrawerOpenPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
=> IsDrawerOpenPropertyChanged(dependencyObject, dependencyPropertyChangedEventArgs, Dock.Right);
private static void IsBottomDrawerOpenPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
=> IsDrawerOpenPropertyChanged(dependencyObject, dependencyPropertyChangedEventArgs, Dock.Bottom);
private static void IsDrawerOpenPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs, Dock dock)
{
var drawerHost = (DrawerHost)dependencyObject;
if (!drawerHost._lockZIndexes && (bool)dependencyPropertyChangedEventArgs.NewValue)
drawerHost.PrepareZIndexes(drawerHost._zIndexPropertyLookup[dependencyPropertyChangedEventArgs.Property]);
drawerHost.UpdateVisualStates();
if ((bool)dependencyPropertyChangedEventArgs.NewValue)
{
RaiseDrawerOpened(drawerHost, dock);
}
}
private static void RaiseDrawerOpened(DrawerHost drawerHost, Dock dock)
{
//multiple ways of calling back that the drawer has opened:
// * routed event
var drawerOpenedEventArgs = new DrawerOpenedEventArgs(dock, DrawerOpenedEvent);
drawerHost.OnDrawerOpened(drawerOpenedEventArgs);
}
private void PrepareZIndexes(DependencyPropertyKey zIndexDependencyPropertyKey)
{
var newOrder = new[] { zIndexDependencyPropertyKey }
.Concat(_zIndexPropertyLookup.Values.Except(new[] { zIndexDependencyPropertyKey })
.OrderByDescending(dpk => (int)GetValue(dpk.DependencyProperty)))
.Reverse()
.Select((dpk, idx) => new { dpk, idx });
foreach (var a in newOrder)
SetValue(a.dpk, a.idx);
}
private void CloseDrawerHandler(object sender, ExecutedRoutedEventArgs executedRoutedEventArgs)
{
if (executedRoutedEventArgs.Handled) return;
if (executedRoutedEventArgs.Parameter is Dock dock)
{
var drawerClosingEventArgs = new DrawerClosingEventArgs(dock, DrawerClosingEvent);
//multiple ways of calling back that the drawer is closing:
// * routed event
OnDrawerClosing(drawerClosingEventArgs);
if (drawerClosingEventArgs.IsCancelled)
{
return;
}
}
SetOpenFlag(executedRoutedEventArgs, false);
executedRoutedEventArgs.Handled = true;
}
private void OpenDrawerHandler(object sender, ExecutedRoutedEventArgs executedRoutedEventArgs)
{
if (executedRoutedEventArgs.Handled) return;
SetOpenFlag(executedRoutedEventArgs, true);
executedRoutedEventArgs.Handled = true;
}
private void SetOpenFlag(ExecutedRoutedEventArgs executedRoutedEventArgs, bool value)
{
if (executedRoutedEventArgs.Parameter is Dock dock)
{
switch (dock)
{
case Dock.Left:
SetCurrentValue(IsLeftDrawerOpenProperty, value);
break;
case Dock.Top:
SetCurrentValue(IsTopDrawerOpenProperty, value);
break;
case Dock.Right:
SetCurrentValue(IsRightDrawerOpenProperty, value);
break;
case Dock.Bottom:
SetCurrentValue(IsBottomDrawerOpenProperty, value);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
else
{
try
{
_lockZIndexes = true;
SetCurrentValue(IsLeftDrawerOpenProperty, value);
SetCurrentValue(IsTopDrawerOpenProperty, value);
SetCurrentValue(IsRightDrawerOpenProperty, value);
SetCurrentValue(IsBottomDrawerOpenProperty, value);
}
finally
{
_lockZIndexes = false;
}
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.AutoML.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedPredictionServiceClientTest
{
[xunit::FactAttribute]
public void PredictRequestObject()
{
moq::Mock<PredictionService.PredictionServiceClient> mockGrpcClient = new moq::Mock<PredictionService.PredictionServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
PredictRequest request = new PredictRequest
{
ModelName = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]"),
Payload = new ExamplePayload(),
Params =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
PredictResponse expectedResponse = new PredictResponse
{
Payload =
{
new AnnotationPayload(),
},
Metadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
PreprocessedInput = new ExamplePayload(),
};
mockGrpcClient.Setup(x => x.Predict(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
PredictionServiceClient client = new PredictionServiceClientImpl(mockGrpcClient.Object, null);
PredictResponse response = client.Predict(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task PredictRequestObjectAsync()
{
moq::Mock<PredictionService.PredictionServiceClient> mockGrpcClient = new moq::Mock<PredictionService.PredictionServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
PredictRequest request = new PredictRequest
{
ModelName = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]"),
Payload = new ExamplePayload(),
Params =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
PredictResponse expectedResponse = new PredictResponse
{
Payload =
{
new AnnotationPayload(),
},
Metadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
PreprocessedInput = new ExamplePayload(),
};
mockGrpcClient.Setup(x => x.PredictAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PredictResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
PredictionServiceClient client = new PredictionServiceClientImpl(mockGrpcClient.Object, null);
PredictResponse responseCallSettings = await client.PredictAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PredictResponse responseCancellationToken = await client.PredictAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Predict()
{
moq::Mock<PredictionService.PredictionServiceClient> mockGrpcClient = new moq::Mock<PredictionService.PredictionServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
PredictRequest request = new PredictRequest
{
ModelName = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]"),
Payload = new ExamplePayload(),
Params =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
PredictResponse expectedResponse = new PredictResponse
{
Payload =
{
new AnnotationPayload(),
},
Metadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
PreprocessedInput = new ExamplePayload(),
};
mockGrpcClient.Setup(x => x.Predict(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
PredictionServiceClient client = new PredictionServiceClientImpl(mockGrpcClient.Object, null);
PredictResponse response = client.Predict(request.Name, request.Payload, request.Params);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task PredictAsync()
{
moq::Mock<PredictionService.PredictionServiceClient> mockGrpcClient = new moq::Mock<PredictionService.PredictionServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
PredictRequest request = new PredictRequest
{
ModelName = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]"),
Payload = new ExamplePayload(),
Params =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
PredictResponse expectedResponse = new PredictResponse
{
Payload =
{
new AnnotationPayload(),
},
Metadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
PreprocessedInput = new ExamplePayload(),
};
mockGrpcClient.Setup(x => x.PredictAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PredictResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
PredictionServiceClient client = new PredictionServiceClientImpl(mockGrpcClient.Object, null);
PredictResponse responseCallSettings = await client.PredictAsync(request.Name, request.Payload, request.Params, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PredictResponse responseCancellationToken = await client.PredictAsync(request.Name, request.Payload, request.Params, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void PredictResourceNames()
{
moq::Mock<PredictionService.PredictionServiceClient> mockGrpcClient = new moq::Mock<PredictionService.PredictionServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
PredictRequest request = new PredictRequest
{
ModelName = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]"),
Payload = new ExamplePayload(),
Params =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
PredictResponse expectedResponse = new PredictResponse
{
Payload =
{
new AnnotationPayload(),
},
Metadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
PreprocessedInput = new ExamplePayload(),
};
mockGrpcClient.Setup(x => x.Predict(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
PredictionServiceClient client = new PredictionServiceClientImpl(mockGrpcClient.Object, null);
PredictResponse response = client.Predict(request.ModelName, request.Payload, request.Params);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task PredictResourceNamesAsync()
{
moq::Mock<PredictionService.PredictionServiceClient> mockGrpcClient = new moq::Mock<PredictionService.PredictionServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
PredictRequest request = new PredictRequest
{
ModelName = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]"),
Payload = new ExamplePayload(),
Params =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
PredictResponse expectedResponse = new PredictResponse
{
Payload =
{
new AnnotationPayload(),
},
Metadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
PreprocessedInput = new ExamplePayload(),
};
mockGrpcClient.Setup(x => x.PredictAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PredictResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
PredictionServiceClient client = new PredictionServiceClientImpl(mockGrpcClient.Object, null);
PredictResponse responseCallSettings = await client.PredictAsync(request.ModelName, request.Payload, request.Params, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PredictResponse responseCancellationToken = await client.PredictAsync(request.ModelName, request.Payload, request.Params, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using JetBrains.Annotations;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Queries;
using JsonApiDotNetCore.Queries.Internal;
using JsonApiDotNetCore.QueryStrings;
using JsonApiDotNetCore.Resources;
using JsonApiDotNetCore.Resources.Annotations;
using JsonApiDotNetCore.Serialization.Objects;
namespace JsonApiDotNetCore.Serialization.Building
{
[PublicAPI]
public class IncludedResourceObjectBuilder : ResourceObjectBuilder, IIncludedResourceObjectBuilder
{
private readonly HashSet<ResourceObject> _included;
private readonly IFieldsToSerialize _fieldsToSerialize;
private readonly ILinkBuilder _linkBuilder;
private readonly IResourceDefinitionAccessor _resourceDefinitionAccessor;
private readonly IRequestQueryStringAccessor _queryStringAccessor;
private readonly SparseFieldSetCache _sparseFieldSetCache;
public IncludedResourceObjectBuilder(IFieldsToSerialize fieldsToSerialize, ILinkBuilder linkBuilder, IResourceGraph resourceGraph,
IEnumerable<IQueryConstraintProvider> constraintProviders, IResourceDefinitionAccessor resourceDefinitionAccessor,
IRequestQueryStringAccessor queryStringAccessor, IJsonApiOptions options)
: base(resourceGraph, options)
{
ArgumentGuard.NotNull(fieldsToSerialize, nameof(fieldsToSerialize));
ArgumentGuard.NotNull(linkBuilder, nameof(linkBuilder));
ArgumentGuard.NotNull(constraintProviders, nameof(constraintProviders));
ArgumentGuard.NotNull(resourceDefinitionAccessor, nameof(resourceDefinitionAccessor));
ArgumentGuard.NotNull(queryStringAccessor, nameof(queryStringAccessor));
_included = new HashSet<ResourceObject>(ResourceIdentityComparer.Instance);
_fieldsToSerialize = fieldsToSerialize;
_linkBuilder = linkBuilder;
_resourceDefinitionAccessor = resourceDefinitionAccessor;
_queryStringAccessor = queryStringAccessor;
_sparseFieldSetCache = new SparseFieldSetCache(constraintProviders, resourceDefinitionAccessor);
}
/// <inheritdoc />
public IList<ResourceObject> Build()
{
if (_included.Any())
{
// Cleans relationship dictionaries and adds links of resources.
foreach (ResourceObject resourceObject in _included)
{
if (resourceObject.Relationships != null)
{
UpdateRelationships(resourceObject);
}
resourceObject.Links = _linkBuilder.GetResourceLinks(resourceObject.Type, resourceObject.Id);
}
return _included.ToArray();
}
return _queryStringAccessor.Query.ContainsKey("include") ? Array.Empty<ResourceObject>() : null;
}
private void UpdateRelationships(ResourceObject resourceObject)
{
foreach (string relationshipName in resourceObject.Relationships.Keys)
{
ResourceContext resourceContext = ResourceGraph.GetResourceContext(resourceObject.Type);
RelationshipAttribute relationship = resourceContext.GetRelationshipByPublicName(relationshipName);
if (!IsRelationshipInSparseFieldSet(relationship))
{
resourceObject.Relationships.Remove(relationshipName);
}
}
resourceObject.Relationships = PruneRelationshipObjects(resourceObject);
}
private static IDictionary<string, RelationshipObject> PruneRelationshipObjects(ResourceObject resourceObject)
{
Dictionary<string, RelationshipObject> pruned = resourceObject.Relationships.Where(pair => pair.Value.Data.IsAssigned || pair.Value.Links != null)
.ToDictionary(pair => pair.Key, pair => pair.Value);
return !pruned.Any() ? null : pruned;
}
private bool IsRelationshipInSparseFieldSet(RelationshipAttribute relationship)
{
ResourceContext resourceContext = ResourceGraph.GetResourceContext(relationship.LeftType);
IImmutableSet<ResourceFieldAttribute> fieldSet = _sparseFieldSetCache.GetSparseFieldSetForSerializer(resourceContext);
return fieldSet.Contains(relationship);
}
/// <inheritdoc />
public override ResourceObject Build(IIdentifiable resource, IReadOnlyCollection<AttrAttribute> attributes = null,
IReadOnlyCollection<RelationshipAttribute> relationships = null)
{
ResourceObject resourceObject = base.Build(resource, attributes, relationships);
resourceObject.Meta = _resourceDefinitionAccessor.GetMeta(resource.GetType(), resource);
return resourceObject;
}
/// <inheritdoc />
public void IncludeRelationshipChain(IReadOnlyCollection<RelationshipAttribute> inclusionChain, IIdentifiable rootResource)
{
ArgumentGuard.NotNull(inclusionChain, nameof(inclusionChain));
ArgumentGuard.NotNull(rootResource, nameof(rootResource));
// We don't have to build a resource object for the root resource because
// this one is already encoded in the documents primary data, so we process the chain
// starting from the first related resource.
RelationshipAttribute relationship = inclusionChain.First();
IList<RelationshipAttribute> chainRemainder = ShiftChain(inclusionChain);
object related = relationship.GetValue(rootResource);
ProcessChain(related, chainRemainder);
}
private void ProcessChain(object related, IList<RelationshipAttribute> inclusionChain)
{
if (related is IEnumerable children)
{
foreach (IIdentifiable child in children)
{
ProcessRelationship(child, inclusionChain);
}
}
else
{
ProcessRelationship((IIdentifiable)related, inclusionChain);
}
}
private void ProcessRelationship(IIdentifiable parent, IList<RelationshipAttribute> inclusionChain)
{
if (parent == null)
{
return;
}
ResourceObject resourceObject = TryGetBuiltResourceObjectFor(parent);
if (resourceObject == null)
{
_resourceDefinitionAccessor.OnSerialize(parent);
resourceObject = BuildCachedResourceObjectFor(parent);
}
if (!inclusionChain.Any())
{
return;
}
RelationshipAttribute nextRelationship = inclusionChain.First();
List<RelationshipAttribute> chainRemainder = inclusionChain.ToList();
chainRemainder.RemoveAt(0);
string nextRelationshipName = nextRelationship.PublicName;
IDictionary<string, RelationshipObject> relationshipsObject = resourceObject.Relationships;
if (!relationshipsObject.TryGetValue(nextRelationshipName, out RelationshipObject relationshipObject))
{
relationshipObject = GetRelationshipData(nextRelationship, parent);
relationshipsObject[nextRelationshipName] = relationshipObject;
}
relationshipObject.Data = GetRelatedResourceLinkage(nextRelationship, parent);
if (relationshipObject.Data.IsAssigned && relationshipObject.Data.Value != null)
{
// if the relationship is set, continue parsing the chain.
object related = nextRelationship.GetValue(parent);
ProcessChain(related, chainRemainder);
}
}
private IList<RelationshipAttribute> ShiftChain(IReadOnlyCollection<RelationshipAttribute> chain)
{
List<RelationshipAttribute> chainRemainder = chain.ToList();
chainRemainder.RemoveAt(0);
return chainRemainder;
}
/// <summary>
/// We only need an empty relationship object here. It will be populated in the ProcessRelationships method.
/// </summary>
protected override RelationshipObject GetRelationshipData(RelationshipAttribute relationship, IIdentifiable resource)
{
ArgumentGuard.NotNull(relationship, nameof(relationship));
ArgumentGuard.NotNull(resource, nameof(resource));
return new RelationshipObject
{
Links = _linkBuilder.GetRelationshipLinks(relationship, resource)
};
}
private ResourceObject TryGetBuiltResourceObjectFor(IIdentifiable resource)
{
Type resourceType = resource.GetType();
ResourceContext resourceContext = ResourceGraph.GetResourceContext(resourceType);
return _included.SingleOrDefault(resourceObject => resourceObject.Type == resourceContext.PublicName && resourceObject.Id == resource.StringId);
}
private ResourceObject BuildCachedResourceObjectFor(IIdentifiable resource)
{
Type resourceType = resource.GetType();
IReadOnlyCollection<AttrAttribute> attributes = _fieldsToSerialize.GetAttributes(resourceType);
IReadOnlyCollection<RelationshipAttribute> relationships = _fieldsToSerialize.GetRelationships(resourceType);
ResourceObject resourceObject = Build(resource, attributes, relationships);
_included.Add(resourceObject);
return resourceObject;
}
}
}
| |
#region License
// Copyright (c) K2 Workflow (SourceCode Technology Holdings Inc.). All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
#endregion
using Moq;
using SourceCode.Chasm.IO;
using SourceCode.Chasm.Tests.Helpers;
using SourceCode.Chasm.Tests.TestObjects;
using SourceCode.Clay.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO.Compression;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace SourceCode.Chasm.Tests.IO
{
public static class ChasmRepositoryTreeTests
{
#region Methods
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(ChasmRepositoryTree_ReadTreeAsync_Branch_CommitRefName))]
public static async Task ChasmRepositoryTree_ReadTreeAsync_Branch_CommitRefName()
{
// Arrange
var mockChasmSerializer = new Mock<RandomChasmSerializer>();
var mockChasmRepository = new Mock<ChasmRepository>(mockChasmSerializer.Object, CompressionLevel.NoCompression, 5)
{
CallBase = true
};
mockChasmRepository.Setup(i => i.ReadCommitRefAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(async () =>
{
await Task.Yield();
return CommitRefTestObject.Random;
});
// Action
var actual = await mockChasmRepository.Object.ReadTreeAsync(RandomHelper.String, CommitRefTestObject.Random.Branch, TestValues.CancellationToken);
// Assert
Assert.Equal(default, actual);
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(ChasmRepositoryTree_ReadTreeAsync_Branch_CommitRefName_Empty))]
public static void ChasmRepositoryTree_ReadTreeAsync_Branch_CommitRefName_Empty()
{
// Arrange
var mockChasmSerializer = new Mock<IChasmSerializer>();
var mockChasmRepository = new Mock<ChasmRepository>(mockChasmSerializer.Object, CompressionLevel.NoCompression, 5)
{
CallBase = true
};
// Action
var actual = Assert.ThrowsAsync<ArgumentNullException>(async () => await mockChasmRepository.Object.ReadTreeAsync(RandomHelper.String, default, TestValues.CancellationToken));
// Assert
Assert.Contains("commitRefName", actual.Result.Message);
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(ChasmRepositoryTree_ReadTreeAsync_Branch_CommitRefName_EmptyBuffer))]
public static async Task ChasmRepositoryTree_ReadTreeAsync_Branch_CommitRefName_EmptyBuffer()
{
// Arrange
var mockChasmSerializer = new Mock<IChasmSerializer>();
var mockChasmRepository = new Mock<ChasmRepository>(mockChasmSerializer.Object, CompressionLevel.NoCompression, 5)
{
CallBase = true
};
// Action
var actual = await mockChasmRepository.Object.ReadTreeAsync(RandomHelper.String, CommitRefTestObject.Random.Branch, TestValues.CancellationToken);
// Assert
Assert.Equal(default, actual);
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(ChasmRepositoryTree_ReadTreeAsync_Branch_Empty))]
public static void ChasmRepositoryTree_ReadTreeAsync_Branch_Empty()
{
// Arrange
var mockChasmSerializer = new Mock<IChasmSerializer>();
var mockChasmRepository = new Mock<ChasmRepository>(mockChasmSerializer.Object, CompressionLevel.NoCompression, 5)
{
CallBase = true
};
// Action
var actual = Assert.ThrowsAsync<ArgumentNullException>(async () => await mockChasmRepository.Object.ReadTreeAsync(default, CommitRefTestObject.Random.Branch, TestValues.CancellationToken));
// Assert
Assert.Contains("branch", actual.Result.Message);
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(ChasmRepositoryTree_ReadTreeAsync_CommitId))]
public static async Task ChasmRepositoryTree_ReadTreeAsync_CommitId()
{
// Arrange
var mockChasmSerializer = new Mock<RandomChasmSerializer>();
var mockChasmRepository = new Mock<ChasmRepository>(mockChasmSerializer.Object, CompressionLevel.NoCompression, 5)
{
CallBase = true
};
mockChasmRepository.Setup(i => i.ReadObjectAsync(It.IsAny<Sha1>(), It.IsAny<CancellationToken>()))
.Returns(async () =>
{
await Task.Yield();
return TestValues.ReadOnlyMemory;
});
// Action
var actual = await mockChasmRepository.Object.ReadTreeAsync(CommitIdTestObject.Random, TestValues.CancellationToken);
// Assert
Assert.Equal(TreeNodeMap.Empty, actual);
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(ChasmRepositoryTree_ReadTreeAsync_CommitId_EmptyBuffer))]
public static async Task ChasmRepositoryTree_ReadTreeAsync_CommitId_EmptyBuffer()
{
// Arrange
var mockChasmSerializer = new Mock<IChasmSerializer>();
var mockChasmRepository = new Mock<ChasmRepository>(mockChasmSerializer.Object, CompressionLevel.NoCompression, 5)
{
CallBase = true
};
// Action
var actual = await mockChasmRepository.Object.ReadTreeAsync(CommitIdTestObject.Random, TestValues.CancellationToken);
// Assert
Assert.Equal(default, actual);
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(ChasmRepositoryTree_ReadTreeAsync_TreeId))]
public static async Task ChasmRepositoryTree_ReadTreeAsync_TreeId()
{
// Arrange
var mockChasmSerializer = new Mock<RandomChasmSerializer>();
var mockChasmRepository = new Mock<ChasmRepository>(mockChasmSerializer.Object, CompressionLevel.NoCompression, 5)
{
CallBase = true
};
mockChasmRepository.Setup(i => i.ReadObjectAsync(It.IsAny<Sha1>(), It.IsAny<CancellationToken>()))
.Returns(async () =>
{
await Task.Yield();
return TestValues.ReadOnlyMemory;
});
// Action
var actual = await mockChasmRepository.Object.ReadTreeAsync(TreeIdTestObject.Random, TestValues.CancellationToken);
// Assert
Assert.Equal(TreeNodeMap.Empty, actual);
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(ChasmRepositoryTree_ReadTreeAsync_TreeId_EmptyBuffer))]
public static async Task ChasmRepositoryTree_ReadTreeAsync_TreeId_EmptyBuffer()
{
// Arrange
var mockChasmSerializer = new Mock<IChasmSerializer>();
var mockChasmRepository = new Mock<ChasmRepository>(mockChasmSerializer.Object, CompressionLevel.NoCompression, 5)
{
CallBase = true
};
// Action
var actual = await mockChasmRepository.Object.ReadTreeAsync(TreeIdTestObject.Random, TestValues.CancellationToken);
// Assert
Assert.Equal(default, actual);
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(ChasmRepositoryTree_ReadTreeBatchAsync_TreeIds))]
public static async Task ChasmRepositoryTree_ReadTreeBatchAsync_TreeIds()
{
// Arrange
var mockChasmSerializer = new Mock<IChasmSerializer>();
var mockChasmRepository = new Mock<ChasmRepository>(mockChasmSerializer.Object, CompressionLevel.NoCompression, 5)
{
CallBase = true
};
mockChasmRepository.Setup(i => i.ReadObjectBatchAsync(It.IsAny<IEnumerable<Sha1>>(), It.IsAny<CancellationToken>()))
.Returns<IEnumerable<Sha1>, CancellationToken>(async (objectIds, parallelOptions) =>
{
await Task.Yield();
var dictionary = new Dictionary<Sha1, ReadOnlyMemory<byte>>();
foreach (var objectId in objectIds)
{
dictionary.Add(objectId, TestValues.ReadOnlyMemory);
}
return new ReadOnlyDictionary<Sha1, ReadOnlyMemory<byte>>(dictionary);
});
// Action
var actual = await mockChasmRepository.Object.ReadTreeBatchAsync(new TreeId[] { TreeIdTestObject.Random }, TestValues.ParallelOptions.CancellationToken);
// Assert
Assert.Equal(1, actual.Count);
Assert.Equal(TreeNodeMap.Empty, actual.Values.FirstOrDefault());
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(ChasmRepositoryTree_ReadTreeBatchAsync_TreeIds_Empty))]
public static async Task ChasmRepositoryTree_ReadTreeBatchAsync_TreeIds_Empty()
{
// Arrange
var mockChasmSerializer = new Mock<IChasmSerializer>();
var mockChasmRepository = new Mock<ChasmRepository>(mockChasmSerializer.Object, CompressionLevel.NoCompression, 5)
{
CallBase = true
};
// Action
var actual = await mockChasmRepository.Object.ReadTreeBatchAsync(null, TestValues.ParallelOptions.CancellationToken);
// Assert
Assert.Equal(ReadOnlyDictionary.Empty<TreeId, TreeNodeMap>(), actual);
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(ChasmRepositoryTree_ReadTreeBatchAsync_TreeIds_EmptyBuffer))]
public static async Task ChasmRepositoryTree_ReadTreeBatchAsync_TreeIds_EmptyBuffer()
{
// Arrange
var mockChasmSerializer = new Mock<IChasmSerializer>();
var mockChasmRepository = new Mock<ChasmRepository>(mockChasmSerializer.Object, CompressionLevel.NoCompression, 5)
{
CallBase = true
};
mockChasmRepository.Setup(i => i.ReadObjectBatchAsync(It.IsAny<IEnumerable<Sha1>>(), It.IsAny<CancellationToken>()))
.Returns(async () =>
{
await Task.Yield();
return ReadOnlyDictionary.Empty<Sha1, ReadOnlyMemory<byte>>();
});
// Action
var actual = await mockChasmRepository.Object.ReadTreeBatchAsync(new TreeId[] { TreeIdTestObject.Random }, TestValues.ParallelOptions.CancellationToken);
// Assert
Assert.Equal(ReadOnlyDictionary.Empty<TreeId, TreeNodeMap>(), actual);
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(ChasmRepositoryTree_WriteTreeAsync_Tree))]
public static async Task ChasmRepositoryTree_WriteTreeAsync_CommitIds()
{
// Arrange
var parents = new List<CommitId> { CommitIdTestObject.Random };
var mockChasmSerializer = new Mock<IChasmSerializer>();
var mockChasmRepository = new Mock<ChasmRepository>(mockChasmSerializer.Object, CompressionLevel.NoCompression, 5)
{
CallBase = true
};
// Action
var actual = await mockChasmRepository.Object.WriteTreeAsync(parents, TreeNodeMapTestObject.Random, AuditTestObject.Random, AuditTestObject.Random, RandomHelper.String, TestValues.CancellationToken);
// Assert
Assert.Equal(new CommitId(), actual);
mockChasmRepository.Verify(i => i.WriteTreeAsync(It.IsAny<TreeNodeMap>(), It.IsAny<CancellationToken>()));
mockChasmRepository.Verify(i => i.WriteCommitAsync(It.IsAny<Commit>(), It.IsAny<CancellationToken>()));
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(ChasmRepositoryTree_WriteTreeAsync_Tree))]
public static async Task ChasmRepositoryTree_WriteTreeAsync_Tree()
{
// Arrange
var mockChasmSerializer = new Mock<IChasmSerializer>();
var mockChasmRepository = new Mock<ChasmRepository>(mockChasmSerializer.Object, CompressionLevel.NoCompression, 5)
{
CallBase = true
};
// Action
var actual = await mockChasmRepository.Object.WriteTreeAsync(TreeNodeMap.Empty, TestValues.CancellationToken);
// Assert
Assert.Equal(new TreeId(), actual);
mockChasmRepository.Verify(i => i.WriteObjectAsync(It.IsAny<Sha1>(), It.IsAny<ArraySegment<byte>>(), It.IsAny<bool>(), It.IsAny<CancellationToken>()));
}
#endregion
}
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || UNITY_WP8
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Utilities;
using System.Globalization;
namespace Newtonsoft.Json.Linq
{
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only access to serialized Json data.
/// </summary>
public class JTokenReader : JsonReader, IJsonLineInfo
{
private readonly JToken _root;
private JToken _parent;
private JToken _current;
/// <summary>
/// Initializes a new instance of the <see cref="JTokenReader"/> class.
/// </summary>
/// <param name="token">The token to read from.</param>
public JTokenReader(JToken token)
{
ValidationUtils.ArgumentNotNull(token, "token");
_root = token;
_current = token;
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="T:Byte[]"/>.
/// </summary>
/// <returns>
/// A <see cref="T:Byte[]"/> or a null reference if the next JSON token is null.
/// </returns>
public override byte[] ReadAsBytes()
{
Read();
// attempt to convert possible base 64 string to bytes
if (TokenType == JsonToken.String)
{
string s = (string) Value;
byte[] data = (s.Length == 0) ? new byte[0] : Convert.FromBase64String(s);
SetToken(JsonToken.Bytes, data);
}
if (TokenType == JsonToken.Null)
return null;
if (TokenType == JsonToken.Bytes)
return (byte[])Value;
throw new JsonReaderException("Error reading bytes. Expected bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Decimal}"/>.</returns>
public override decimal? ReadAsDecimal()
{
Read();
if (TokenType == JsonToken.Null)
return null;
if (TokenType == JsonToken.Integer || TokenType == JsonToken.Float)
{
SetToken(JsonToken.Float, Convert.ToDecimal(Value, CultureInfo.InvariantCulture));
return (decimal) Value;
}
throw new JsonReaderException("Error reading decimal. Expected a number but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{DateTimeOffset}"/>.</returns>
public override DateTimeOffset? ReadAsDateTimeOffset()
{
Read();
if (TokenType == JsonToken.Null)
return null;
if (TokenType == JsonToken.Date)
{
SetToken(JsonToken.Date, new DateTimeOffset((DateTime)Value));
return (DateTimeOffset)Value;
}
throw new JsonReaderException("Error reading date. Expected bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
/// <summary>
/// Reads the next JSON token from the stream.
/// </summary>
/// <returns>
/// true if the next token was read successfully; false if there are no more tokens to read.
/// </returns>
public override bool Read()
{
if (CurrentState != State.Start)
{
JContainer container = _current as JContainer;
if (container != null && _parent != container)
return ReadInto(container);
else
return ReadOver(_current);
}
SetToken(_current);
return true;
}
private bool ReadOver(JToken t)
{
if (t == _root)
return ReadToEnd();
JToken next = t.Next;
if ((next == null || next == t) || t == t.Parent.Last)
{
if (t.Parent == null)
return ReadToEnd();
return SetEnd(t.Parent);
}
else
{
_current = next;
SetToken(_current);
return true;
}
}
private bool ReadToEnd()
{
//CurrentState = State.Finished;
return false;
}
private bool IsEndElement
{
get { return (_current == _parent); }
}
private JsonToken? GetEndToken(JContainer c)
{
switch (c.Type)
{
case JTokenType.Object:
return JsonToken.EndObject;
case JTokenType.Array:
return JsonToken.EndArray;
case JTokenType.Constructor:
return JsonToken.EndConstructor;
case JTokenType.Property:
return null;
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException("Type", c.Type, "Unexpected JContainer type.");
}
}
private bool ReadInto(JContainer c)
{
JToken firstChild = c.First;
if (firstChild == null)
{
return SetEnd(c);
}
else
{
SetToken(firstChild);
_current = firstChild;
_parent = c;
return true;
}
}
private bool SetEnd(JContainer c)
{
JsonToken? endToken = GetEndToken(c);
if (endToken != null)
{
SetToken(endToken.Value);
_current = c;
_parent = c;
return true;
}
else
{
return ReadOver(c);
}
}
private void SetToken(JToken token)
{
switch (token.Type)
{
case JTokenType.Object:
SetToken(JsonToken.StartObject);
break;
case JTokenType.Array:
SetToken(JsonToken.StartArray);
break;
case JTokenType.Constructor:
SetToken(JsonToken.StartConstructor);
break;
case JTokenType.Property:
SetToken(JsonToken.PropertyName, ((JProperty)token).Name);
break;
case JTokenType.Comment:
SetToken(JsonToken.Comment, ((JValue)token).Value);
break;
case JTokenType.Integer:
SetToken(JsonToken.Integer, ((JValue)token).Value);
break;
case JTokenType.Float:
SetToken(JsonToken.Float, ((JValue)token).Value);
break;
case JTokenType.String:
SetToken(JsonToken.String, ((JValue)token).Value);
break;
case JTokenType.Boolean:
SetToken(JsonToken.Boolean, ((JValue)token).Value);
break;
case JTokenType.Null:
SetToken(JsonToken.Null, ((JValue)token).Value);
break;
case JTokenType.Undefined:
SetToken(JsonToken.Undefined, ((JValue)token).Value);
break;
case JTokenType.Date:
SetToken(JsonToken.Date, ((JValue)token).Value);
break;
case JTokenType.Raw:
SetToken(JsonToken.Raw, ((JValue)token).Value);
break;
case JTokenType.Bytes:
SetToken(JsonToken.Bytes, ((JValue)token).Value);
break;
case JTokenType.Guid:
SetToken(JsonToken.String, SafeToString(((JValue)token).Value));
break;
case JTokenType.Uri:
SetToken(JsonToken.String, SafeToString(((JValue)token).Value));
break;
case JTokenType.TimeSpan:
SetToken(JsonToken.String, SafeToString(((JValue)token).Value));
break;
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException("Type", token.Type, "Unexpected JTokenType.");
}
}
private string SafeToString(object value)
{
return (value != null) ? value.ToString() : null;
}
bool IJsonLineInfo.HasLineInfo()
{
if (CurrentState == State.Start)
return false;
IJsonLineInfo info = IsEndElement ? null : _current;
return (info != null && info.HasLineInfo());
}
int IJsonLineInfo.LineNumber
{
get
{
if (CurrentState == State.Start)
return 0;
IJsonLineInfo info = IsEndElement ? null : _current;
if (info != null)
return info.LineNumber;
return 0;
}
}
int IJsonLineInfo.LinePosition
{
get
{
if (CurrentState == State.Start)
return 0;
IJsonLineInfo info = IsEndElement ? null : _current;
if (info != null)
return info.LinePosition;
return 0;
}
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.OS;
using Android.Support.V7.App;
using Android.Views;
using Android.Widget;
using Newtonsoft.Json.Linq;
using AlertDialog = Android.Support.V7.App.AlertDialog;
using Path = System.IO.Path;
using Uri = Android.Net.Uri;
using VKontakte;
using VKontakte.API;
using VKontakte.API.Methods;
using VKontakte.API.Models;
using VKontakte.API.Photos;
using VKontakte.Payments;
using VKontakte.Dialogs;
namespace VKontakteSampleAndroid
{
[Activity (Label = "VKontakte Tests")]
public class TestActivity : AppCompatActivity
{
private const int OwnerId = 336001037;
private const int AlbumId = 224233810;
private const string WallPostId = "336001037_5";
private const string PhotoId = "photo336001037_390461056";
protected override async void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
SetContentView (Resource.Layout.activity_test);
if (SupportActionBar != null) {
SupportActionBar.SetDisplayHomeAsUpEnabled (true);
}
if (savedInstanceState == null) {
SupportFragmentManager
.BeginTransaction ()
.Add (Resource.Id.container, new PlaceholderFragment ())
.Commit ();
}
var userIsVk = await VKSdk.RequestUserStateAsync (this);
Toast.MakeText (this, userIsVk ? "user is vk's" : "user is not vk's", ToastLength.Short).Show ();
}
public override bool OnOptionsItemSelected (IMenuItem item)
{
if (item.ItemId == Android.Resource.Id.Home) {
Finish ();
return true;
}
return base.OnOptionsItemSelected (item);
}
/// <summary>
/// A placeholder fragment containing a simple view.
/// </summary>
public class PlaceholderFragment : Android.Support.V4.App.Fragment
{
public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = inflater.Inflate (Resource.Layout.fragment_test, container, false);
view.FindViewById (Resource.Id.test_send_request).Click += SendRequest;
view.FindViewById (Resource.Id.users_get).Click += GetUsers;
view.FindViewById (Resource.Id.friends_get).Click += GetFriends;
view.FindViewById (Resource.Id.messages_get).Click += GetMessages;
view.FindViewById (Resource.Id.dialogs_get).Click += GetDialogs;
view.FindViewById (Resource.Id.captcha_force).Click += Captcha;
view.FindViewById (Resource.Id.upload_photo).Click += UploadSinglePhoto;
view.FindViewById (Resource.Id.wall_post).Click += WallPost;
view.FindViewById (Resource.Id.wall_getById).Click += GetWallPost;
view.FindViewById (Resource.Id.test_validation).Click += Validation;
view.FindViewById (Resource.Id.test_share).Click += Share;
view.FindViewById (Resource.Id.upload_photo_to_wall).Click += UploadSinglePhotoToWall;
view.FindViewById (Resource.Id.upload_doc).Click += UploadDoc;
view.FindViewById (Resource.Id.upload_several_photos_to_wall).Click += UploadMultiplePhotosToWall;
return view;
}
// text cases
private void GetFriends (object sender, EventArgs e)
{
var request = VKApi.Friends.Get (new VKParameters (new Dictionary<string, Java.Lang.Object> {
{ VKApiConst.Fields, "id,first_name,last_name,sex,bdate,city" }
}));
StartApiCall (request);
}
private void GetUsers (object sender, EventArgs e)
{
var request = VKApi.Users.Get (new VKParameters (new Dictionary<string, Java.Lang.Object> { {
VKApiConst.Fields,
"id,first_name,last_name,sex,bdate,city,country,photo_50,photo_100,photo_200_orig,photo_200,photo_400_orig,photo_max,photo_max_orig,online,online_mobile,lists,domain,has_mobile,contacts,connections,site,education,universities,schools,can_post,can_see_all_posts,can_see_audio,can_write_private_message,status,last_seen,common_count,relation,relatives,counters"
}
}));
request.Secure = false;
request.UseSystemLanguage = false;
StartApiCall (request);
}
private void SendRequest (object sender, EventArgs e)
{
MakeRequest ();
}
private void GetDialogs (object sender, EventArgs e)
{
var request = VKApi.Messages.GetDialogs ();
StartApiCall (request);
}
private void GetMessages (object sender, EventArgs e)
{
var request = VKApi.Messages.Get ();
StartApiCall (request);
}
private void Captcha (object sender, EventArgs e)
{
var request = new VKApiCaptcha ().Force ();
StartApiCall (request);
}
private async void UploadSinglePhoto (object sender, EventArgs e)
{
var photo = GetPhoto ();
var request = VKApi.UploadAlbumPhotoRequest (new VKUploadImage (photo, VKImageParameters.PngImage ()), AlbumId, OwnerId);
try {
var response = await request.ExecuteAsync ();
RecycleBitmap (photo);
var photoArray = (VKPhotoArray)response.ParsedModel;
var uri = string.Format ("https://vk.com/photo{0}_{1}", OwnerId, photoArray [0].id);
var i = new Intent (Intent.ActionView, Uri.Parse (uri));
StartActivity (i);
} catch (VKException ex) {
ShowError (ex.Error);
}
}
private void WallPost (object sender, EventArgs e)
{
MakePost ("Hello, friends! (From Xamarin.Android)");
}
private void GetWallPost (object sender, EventArgs e)
{
var request = VKApi.Wall.GetById (VKParameters.From (VKApiConst.Posts, WallPostId));
StartApiCall (request);
}
private void Validation (object sender, EventArgs e)
{
var request = new VKRequest ("account.testValidation");
StartApiCall (request);
}
private void Share (object sender, EventArgs e)
{
var photo = GetPhoto ();
new VKShareDialog ()
.SetText ("I created this post with VK Xamarin.Android SDK\nSee additional information below\n#vksdk #xamarin #componentstore")
.SetUploadedPhotos (new VKPhotoArray {
new VKApiPhoto (PhotoId)
})
.SetAttachmentImages (new [] {
new VKUploadImage (photo, VKImageParameters.PngImage ())
})
.SetAttachmentLink ("VK Android SDK information", "https://vk.com/dev/android_sdk")
.SetShareDialogListener (
postId => {
RecycleBitmap (photo);
},
() => {
RecycleBitmap (photo);
},
error => {
RecycleBitmap (photo);
})
.Show (Activity.SupportFragmentManager, "VK_SHARE_DIALOG");
}
private async void UploadSinglePhotoToWall (object sender, EventArgs e)
{
var photo = GetPhoto ();
var request = VKApi.UploadWallPhotoRequest (new VKUploadImage (photo, VKImageParameters.JpgImage (0.9f)), 0, OwnerId);
try {
var response = await request.ExecuteAsync ();
RecycleBitmap (photo);
var photoModel = ((VKPhotoArray)response.ParsedModel) [0];
MakePost ("Photos from Xamarin.Android!", new VKAttachments (photoModel));
} catch (VKException ex) {
ShowError (ex.Error);
}
}
private void UploadDoc (object sender, EventArgs e)
{
var request = VKApi.Docs.UploadDocRequest (GetFile ());
StartApiCall (request);
}
private async void UploadMultiplePhotosToWall (object sender, EventArgs e)
{
var photo = GetPhoto ();
var request1 = VKApi.UploadWallPhotoRequest (new VKUploadImage (photo, VKImageParameters.JpgImage (0.9f)), 0, OwnerId);
var request2 = VKApi.UploadWallPhotoRequest (new VKUploadImage (photo, VKImageParameters.JpgImage (0.5f)), 0, OwnerId);
var request3 = VKApi.UploadWallPhotoRequest (new VKUploadImage (photo, VKImageParameters.JpgImage (0.1f)), 0, OwnerId);
var request4 = VKApi.UploadWallPhotoRequest (new VKUploadImage (photo, VKImageParameters.PngImage ()), 0, OwnerId);
var batch = new VKBatchRequest (request1, request2, request3, request4);
var responses = await batch.ExecuteAsync ();
try {
RecycleBitmap (photo);
var resp = responses.Select (r => ((VKPhotoArray)r.ParsedModel) [0]);
var attachments = new VKAttachments ();
attachments.AddRange (resp);
MakePost ("I just uploaded multiple files from the VK Xamarin.Android SDK!", attachments);
} catch (VKException ex) {
ShowError (ex.Error);
}
}
// utillities
private void StartApiCall (VKRequest request)
{
var i = new Intent (Activity, typeof(ApiCallActivity));
i.PutExtra ("request", request.RegisterObject ());
StartActivity (i);
}
private void ShowError (VKError error)
{
new AlertDialog.Builder (Activity)
.SetMessage (error.ToString ())
.SetPositiveButton ("OK", delegate {
})
.Show ();
if (error.HttpError != null) {
Console.WriteLine ("Error in request or upload: " + error.HttpError);
}
}
private Bitmap GetPhoto ()
{
try {
return BitmapFactory.DecodeStream (Activity.Assets.Open ("android.jpg"));
} catch (Exception ex) {
Console.WriteLine (ex);
return null;
}
}
private void RecycleBitmap (Bitmap bitmap)
{
if (bitmap != null) {
bitmap.Recycle ();
bitmap.Dispose ();
}
}
private Java.IO.File GetFile ()
{
try {
var filename = "android.jpg";
var path = Path.Combine (Activity.CacheDir.AbsolutePath, filename);
using (var inputStream = Activity.Assets.Open (filename))
using (var outputStream = File.Open (path, FileMode.Create)) {
inputStream.CopyTo (outputStream);
}
return new Java.IO.File (path);
} catch (Exception ex) {
Console.WriteLine (ex);
}
return null;
}
private async void MakeRequest ()
{
var request = new VKRequest ("apps.getFriendsList", new VKParameters (new Dictionary<string, Java.Lang.Object> {
{ VKApiConst.Extended, 1 },
{ "type", "request" }
}));
var response = await request.ExecuteAsync ();
var context = Context;
if (context == null || !IsAdded) {
return;
}
try {
var json = JObject.Parse (response.Json.ToString ());
var jsonArray = (JArray)json ["response"]["items"];
var ids = jsonArray.Select (user => (int)user ["id"]).ToArray ();
var users = jsonArray.Select (j => string.Format ("{0} {1}", j ["first_name"], j ["last_name"])).ToArray ();
new AlertDialog.Builder (context)
.SetTitle (Resource.String.send_request_title)
.SetItems (users, (sender, e) => {
var parameters = new VKParameters (new Dictionary<string, Java.Lang.Object> {
{ VKApiConst.UserId, ids [e.Which] },
{ "type", "request" }
});
StartApiCall (new VKRequest ("apps.sendRequest", parameters));
})
.Create ()
.Show ();
} catch (Exception ex) {
Console.WriteLine (ex);
}
}
private async void MakePost (string message, VKAttachments attachments = null)
{
var post = VKApi.Wall.Post (new VKParameters (new Dictionary<string, Java.Lang.Object> {
{ VKApiConst.OwnerId, OwnerId },
{ VKApiConst.Attachments, attachments ?? new VKAttachments () },
{ VKApiConst.Message, message }
}));
post.SetModelClass<VKWallPostResult> ();
try {
var response = await post.ExecuteAsync ();
if (IsAdded) {
var result = (VKWallPostResult)response.ParsedModel;
var uri = string.Format ("https://vk.com/wall{0}_{1}", OwnerId, result.post_id);
var i = new Intent (Intent.ActionView, Uri.Parse (uri));
StartActivity (i);
}
} catch (VKException ex) {
ShowError (ex.Error);
}
}
}
}
}
| |
#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.Xml;
using System.Threading;
using System.Collections.Specialized;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace System.Web
{
/// <summary>
/// HttpError
/// </summary>
public class HttpError
{
/// <summary>
/// Initializes a new instance of the <see cref="HttpError"/> class from a given <see cref="Exception"/> instance and
/// <see cref="System.Web.HttpContext"/> instance representing the HTTP context during the exception.
/// </summary>
/// <param name="e">The e.</param>
/// <param name="httpContext">The HTTP context.</param>
public HttpError(Exception e, HttpContext httpContext)
{
if (e == null)
throw new ArgumentNullException("e");
Exception = e;
// load the basic information.
var baseException = e.GetBaseException();
HostName = Environment.MachineName;
TypeName = baseException.GetType().FullName;
Message = baseException.Message;
Source = baseException.Source;
Detail = e.ToString();
UserName = (Thread.CurrentPrincipal.Identity.Name ?? string.Empty);
Date = DateTime.Now;
// if this is an http exception, then get the status code and detailed html message provided by the host.
var httpException = (e as HttpException);
if (httpException != null)
{
StatusId = httpException.GetHttpCode();
HtmlErrorMessage = (httpException.GetHtmlErrorMessage() ?? string.Empty);
}
// if the http context is available, then capture the collections that represent the state request.
if (httpContext != null)
{
var httpRequest = httpContext.Request;
ServerVariable = httpRequest.ServerVariables;
QueryString = httpRequest.QueryString;
Form = httpRequest.Form;
Cookie = httpRequest.Cookies;
}
}
/// <summary>
/// Gets or sets the name of application in which this error occurred.
/// </summary>
/// <value>
/// The name of the application.
/// </value>
public string ApplicationName { get; set; }
/// <summary>
/// Gets a collection representing the client cookies captured as part of diagnostic data for the error.
/// </summary>
/// <value>
/// The cookie.
/// </value>
public HttpCookieCollection Cookie { get; private set; }
/// <summary>
/// Gets or sets the date and time (in local time) at which the error occurred.
/// </summary>
/// <value>
/// The date.
/// </value>
public DateTime Date { get; set; }
/// <summary>
/// Gets or sets a detailed text describing the error, such as a stack trace.
/// </summary>
/// <value>
/// The detail.
/// </value>
public string Detail { get; set; }
/// <summary>
/// Gets the exception.
/// </summary>
public Exception Exception { get; private set; }
/// <summary>
/// Gets a collection representing the form variables captured as part of diagnostic data for the error.
/// </summary>
/// <value>
/// The form.
/// </value>
public NameValueCollection Form { get; set; }
/// <summary>
/// Gets or sets name of host machine where this error occurred.
/// </summary>
/// <value>
/// The name of the host.
/// </value>
public string HostName { get; set; }
/// <summary>
/// Gets or sets the HTML message generated by the web host (ASP.NET) for the given error.
/// </summary>
/// <value>
/// The HTML error message.
/// </value>
public string HtmlErrorMessage { get; set; }
/// <summary>
/// Gets or sets a brief text describing the error.
/// </summary>
/// <value>
/// The message.
/// </value>
public string Message { get; set; }
/// <summary>
/// Gets a collection representing the Web query string variables captured as part of diagnostic data for the error.
/// </summary>
/// <value>
/// The query string.
/// </value>
public NameValueCollection QueryString { get; private set; }
/// <summary>
/// Gets a collection representing the Web server variables captured as part of diagnostic data for the error.
/// </summary>
/// <value>
/// The server variable.
/// </value>
public NameValueCollection ServerVariable { get; private set; }
/// <summary>
/// Gets or sets the source that is the cause of the error.
/// </summary>
/// <value>
/// The source.
/// </value>
public string Source { get; set; }
/// <summary>
/// Gets or sets the HTTP status code of the output returned to the client for the error.
/// </summary>
/// <value>
/// The status id.
/// </value>
/// <remarks>
/// For cases where this value cannot always be reliably determined, the value may be reported as zero.
/// </remarks>
public int StatusId { get; set; }
/// <summary>
/// Returns the value of the <see cref="Message"/> property.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override string ToString() { return Message; }
/// <summary>
/// Get or sets the type, class or category of the error.
/// </summary>
/// <value>
/// The type.
/// </value>
public string TypeName { get; set; }
/// <summary>
/// Gets or sets the user logged into the application at the time of the error.
/// </summary>
/// <value>
/// The name of the user.
/// </value>
public string UserName { get; set; }
#region ToXml
/// <summary>
/// Writes the error data to its XML representation.
/// </summary>
/// <param name="w">The w.</param>
public void ToXml(XmlWriter w)
{
if (w == null)
throw new ArgumentNullException("w");
if (w.WriteState != WriteState.Element)
throw new ArgumentOutOfRangeException("w");
// write out the basic typed information in attributes followed by collections as inner elements.
WriteXmlAttribute(w);
WriteInnerXml(w);
}
/// <summary>
/// Writes the error data that belongs in XML attributes.
/// </summary>
/// <param name="w">The w.</param>
protected void WriteXmlAttribute(XmlWriter w)
{
if (w == null)
throw new ArgumentNullException("w");
w.WriteAttributeStringIf("applicationName", ApplicationName);
w.WriteAttributeStringIf("hostName", HostName);
w.WriteAttributeStringIf("typeName", TypeName);
w.WriteAttributeStringIf("source", Source);
w.WriteAttributeStringIf("userName", UserName);
if (Date != DateTime.MinValue)
w.WriteAttributeString("date", XmlConvert.ToString(Date, XmlDateTimeSerializationMode.Local));
if (StatusId != 0)
w.WriteAttributeString("statusId", XmlConvert.ToString(StatusId));
}
/// <summary>
/// Writes the error data that belongs in child nodes.
/// </summary>
/// <param name="w">The w.</param>
protected void WriteInnerXml(System.Xml.XmlWriter w)
{
if (w == null)
throw new ArgumentNullException("w");
// message + detail
if (!string.IsNullOrEmpty(Message) || !string.IsNullOrEmpty(Detail))
{
w.WriteStartElement("message");
w.WriteAttributeStringIf("text", Message);
if (!string.IsNullOrEmpty(Detail))
w.WriteCData(Detail);
w.WriteEndElement();
}
// htmlErrorMessage
if (!string.IsNullOrEmpty(HtmlErrorMessage))
{
w.WriteStartElement("htmlErrorMessage");
w.WriteCData(HtmlErrorMessage);
w.WriteEndElement();
}
// collections
w.WriteCollectionIf("serverVariables", new HttpValuesCollection(ServerVariable));
w.WriteCollectionIf("queryString", new HttpValuesCollection(QueryString));
w.WriteCollectionIf("form", new HttpValuesCollection(Form));
w.WriteCollectionIf("cookies", new HttpValuesCollection(Cookie));
}
#endregion
#region HttpValuesCollection
/// <summary>
/// A name-values collection implementation suitable for web-based collections (like server variables, query strings, forms and cookies) that can also be written and read as XML.
/// </summary>
private sealed class HttpValuesCollection : NameValueCollection, IXmlSerializable
{
/// <summary>
/// Initializes a new instance of the <see cref="HttpValuesCollection"/> class.
/// </summary>
/// <param name="collection">The collection.</param>
public HttpValuesCollection(NameValueCollection collection)
: base(collection) { }
/// <summary>
/// Initializes a new instance of the <see cref="HttpValuesCollection"/> class.
/// </summary>
/// <param name="collection">The collection.</param>
public HttpValuesCollection(HttpCookieCollection collection)
: base(collection != null ? collection.Count : 0)
{
if (collection != null && collection.Count > 0)
for (int index = 0; index < collection.Count; index++)
{
var cookie = collection[index];
// note: we drop the path and domain properties of the cookie for sake of simplicity.
Add(cookie.Name, cookie.Value);
}
}
/// <summary>
/// Gets the schema.
/// </summary>
/// <returns></returns>
public XmlSchema GetSchema() { return null; }
/// <summary>
/// Reads the XML.
/// </summary>
/// <param name="r">The r.</param>
public void ReadXml(XmlReader r)
{
if (r == null)
throw new ArgumentNullException("r");
if (IsReadOnly)
throw new InvalidOperationException("Object is read-only.");
r.Read();
// add entries into the collection as <item> elements with child <value> elements are found.
while (r.IsStartElement("item"))
{
var name = r.GetAttribute("name");
var isEmptyElement = r.IsEmptyElement;
// <item>
r.Read();
if (!isEmptyElement)
{
// <value ...>
while (r.IsStartElement("value"))
{
Add(name, r.GetAttribute("text"));
r.Read();
}
// </item>
r.ReadEndElement();
}
else
Add(name, null);
}
r.ReadEndElement();
}
/// <summary>
/// Writes the XML.
/// </summary>
/// <param name="w">The w.</param>
/// Write out a named multi-value collection as follows (example here is the ServerVariables collection):
/// <item name="HTTP_URL">
/// <value string="/myapp/somewhere/page.aspx"/>
/// </item>
/// <item name="QUERY_STRING">
/// <value string="a=1&b=2"/>
/// </item>
/// ...
public void WriteXml(XmlWriter w)
{
if (w == null)
throw new ArgumentNullException("w");
if (Count == 0)
return;
foreach (string key in Keys)
{
w.WriteStartElement("item");
w.WriteAttributeString("name", key);
var values = GetValues(key);
if (values != null)
foreach (string value in values)
{
w.WriteStartElement("value");
w.WriteAttributeString("text", value);
w.WriteEndElement();
}
w.WriteEndElement();
}
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.CSharp.RuntimeBinder.Errors;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
[Flags]
internal enum MemLookFlags : uint
{
None = 0,
Ctor = EXPRFLAG.EXF_CTOR,
NewObj = EXPRFLAG.EXF_NEWOBJCALL,
Operator = EXPRFLAG.EXF_OPERATOR,
Indexer = EXPRFLAG.EXF_INDEXER,
UserCallable = EXPRFLAG.EXF_USERCALLABLE,
BaseCall = EXPRFLAG.EXF_BASECALL,
// All EXF flags are < 0x01000000
MustBeInvocable = 0x20000000,
All = Ctor | NewObj | Operator | Indexer | UserCallable | BaseCall | MustBeInvocable
}
/////////////////////////////////////////////////////////////////////////////////
// MemberLookup class handles looking for a member within a type and its
// base types. This only handles AGGTYPESYMs and TYVARSYMs.
//
// Lookup must be called before any other methods.
internal sealed class MemberLookup
{
// The inputs to Lookup.
private CType _typeSrc;
private CType _typeQual;
private ParentSymbol _symWhere;
private Name _name;
private int _arity;
private MemLookFlags _flags;
// For maintaining the type array. We throw the first 8 or so here.
private readonly List<AggregateType> _rgtypeStart;
// Results of the lookup.
private List<AggregateType> _prgtype;
private int _csym; // Number of syms found.
private readonly SymWithType _swtFirst; // The first symbol found.
private readonly List<MethPropWithType> _methPropWithTypeList; // When we look up methods, we want to keep the list of all candidate methods given a particular name.
// These are for error reporting.
private readonly SymWithType _swtAmbig; // An ambiguous symbol.
private readonly SymWithType _swtInaccess; // An inaccessible symbol.
private readonly SymWithType _swtBad; // If we're looking for a constructor or indexer, this matched on name, but isn't the right thing.
private readonly SymWithType _swtBogus; // A bogus member - such as an indexed property.
private readonly SymWithType _swtBadArity; // An symbol with the wrong arity.
private bool _fMulti; // Whether symFirst is of a kind for which we collect multiples (methods and indexers).
/***************************************************************************************************
Another match was found. Increment the count of syms and add the type to our list if it's not
already there.
***************************************************************************************************/
private void RecordType(AggregateType type, Symbol sym)
{
Debug.Assert(type != null && sym != null);
if (!_prgtype.Contains(type))
{
_prgtype.Add(type);
}
// Now record the sym....
_csym++;
// If it is first, record it.
if (_swtFirst == null)
{
_swtFirst.Set(sym, type);
Debug.Assert(_csym == 1);
Debug.Assert(_prgtype[0] == type);
_fMulti = sym is MethodSymbol || sym is IndexerSymbol;
}
}
/******************************************************************************
Search just the given type (not any bases). Returns true iff it finds
something (which will have been recorded by RecordType).
pfHideByName is set to true iff something was found that hides all
members of base types (eg, a hidebyname method).
******************************************************************************/
private bool SearchSingleType(AggregateType typeCur, out bool pfHideByName)
{
bool fFoundSome = false;
pfHideByName = false;
// Make sure this type is accessible. It may not be due to private inheritance
// or friend assemblies.
bool fInaccess = !CSemanticChecker.CheckTypeAccess(typeCur, _symWhere);
if (fInaccess && (_csym != 0 || _swtInaccess != null))
return false;
// Loop through symbols.
Symbol symCur;
for (symCur = SymbolLoader.LookupAggMember(_name, typeCur.OwningAggregate, symbmask_t.MASK_Member);
symCur != null;
symCur = symCur.LookupNext(symbmask_t.MASK_Member))
{
Debug.Assert(!(symCur is AggregateSymbol));
// Check for arity.
// For non-zero arity, only methods of the correct arity are considered.
// For zero arity, don't filter out any methods since we do type argument
// inferencing.
// All others are only considered when arity is zero.
if (_arity > 0 && (!(symCur is MethodSymbol curMeth) || curMeth.typeVars.Count != _arity))
{
if (!_swtBadArity)
{
_swtBadArity.Set(symCur, typeCur);
}
continue;
}
// Check for user callability.
if (symCur.IsOverride() && !symCur.IsHideByName())
{
continue;
}
MethodOrPropertySymbol methProp = symCur as MethodOrPropertySymbol;
MethodSymbol meth = symCur as MethodSymbol;
if (methProp != null && (_flags & MemLookFlags.UserCallable) != 0 && !methProp.isUserCallable())
{
// If its an indexed property method symbol, let it through.
// This is too liberal, but maintained for compatibility.
if (meth == null ||
!meth.isPropertyAccessor() ||
(!symCur.name.Text.StartsWith("set_", StringComparison.Ordinal) || meth.Params.Count <= 1) &&
(!symCur.name.Text.StartsWith("get_", StringComparison.Ordinal) || meth.Params.Count <= 0))
{
if (!_swtInaccess)
{
_swtInaccess.Set(symCur, typeCur);
}
continue;
}
}
if (fInaccess || !CSemanticChecker.CheckAccess(symCur, typeCur, _symWhere, _typeQual))
{
// Not accessible so get the next sym.
if (!_swtInaccess)
{
_swtInaccess.Set(symCur, typeCur);
}
if (fInaccess)
{
return false;
}
continue;
}
PropertySymbol prop = symCur as PropertySymbol;
// Make sure that whether we're seeing a ctor, operator, or indexer is consistent with the flags.
if (((_flags & MemLookFlags.Ctor) == 0) != (meth == null || !meth.IsConstructor()) ||
((_flags & MemLookFlags.Operator) == 0) != (meth == null || !meth.isOperator) ||
((_flags & MemLookFlags.Indexer) == 0) != !(prop is IndexerSymbol))
{
if (!_swtBad)
{
_swtBad.Set(symCur, typeCur);
}
continue;
}
// We can't call CheckBogus on methods or indexers because if the method has the wrong
// number of parameters people don't think they should have to /r the assemblies containing
// the parameter types and they complain about the resulting CS0012 errors.
if (!(symCur is MethodSymbol) && (_flags & MemLookFlags.Indexer) == 0 && CSemanticChecker.CheckBogus(symCur))
{
// A bogus member - we can't use these, so only record them for error reporting.
if (!_swtBogus)
{
_swtBogus.Set(symCur, typeCur);
}
continue;
}
// if we are in a calling context then we should only find a property if it is delegate valued
if ((_flags & MemLookFlags.MustBeInvocable) != 0)
{
if ((symCur is FieldSymbol field && !IsDelegateType(field.GetType(), typeCur) && !IsDynamicMember(symCur)) ||
(prop != null && !IsDelegateType(prop.RetType, typeCur) && !IsDynamicMember(symCur)))
{
if (!_swtBad)
{
_swtBad.Set(symCur, typeCur);
}
continue;
}
}
if (methProp != null)
{
MethPropWithType mwpInsert = new MethPropWithType(methProp, typeCur);
_methPropWithTypeList.Add(mwpInsert);
}
// We have a visible symbol.
fFoundSome = true;
if (_swtFirst)
{
if (!typeCur.IsInterfaceType)
{
// Non-interface case.
Debug.Assert(_fMulti || typeCur == _prgtype[0]);
if (!_fMulti)
{
if (_swtFirst.Sym is FieldSymbol && symCur is EventSymbol
// The isEvent bit is only set on symbols which come from source...
// This is not a problem for the compiler because the field is only
// accessible in the scope in which it is declared,
// but in the EE we ignore accessibility...
&& _swtFirst.Field().isEvent
)
{
// m_swtFirst is just the field behind the event symCur so ignore symCur.
continue;
}
else if (_swtFirst.Sym is FieldSymbol && symCur is EventSymbol)
{
// symCur is the matching event.
continue;
}
goto LAmbig;
}
if (_swtFirst.Sym.getKind() != symCur.getKind())
{
if (typeCur == _prgtype[0])
goto LAmbig;
// This one is hidden by the first one. This one also hides any more in base types.
pfHideByName = true;
continue;
}
}
// Interface case.
// m_fMulti : n n n y y y y y
// same-kind : * * * y n n n n
// fDiffHidden: * * * * y n n n
// meth : * * * * * y n * can n happen? just in case, we better handle it....
// hack : n * y * * y * n
// meth-2 : * n y * * * * *
// res : A A S R H H A A
else if (!_fMulti)
{
// Give method groups priority.
if (!(symCur is MethodSymbol))
goto LAmbig;
// Erase previous results so we'll record this method as the first.
_prgtype = new List<AggregateType>();
_csym = 0;
_swtFirst.Clear();
_swtAmbig.Clear();
}
else if (_swtFirst.Sym.getKind() != symCur.getKind())
{
if (!typeCur.DiffHidden)
{
// Give method groups priority.
if (!(_swtFirst.Sym is MethodSymbol))
goto LAmbig;
}
// This one is hidden by another. This one also hides any more in base types.
pfHideByName = true;
continue;
}
}
RecordType(typeCur, symCur);
if (methProp != null && methProp.isHideByName)
pfHideByName = true;
// We've found a symbol in this type but need to make sure there aren't any conflicting
// syms here, so keep searching the type.
}
Debug.Assert(!fInaccess || !fFoundSome);
return fFoundSome;
LAmbig:
// Ambiguous!
if (!_swtAmbig)
_swtAmbig.Set(symCur, typeCur);
pfHideByName = true;
return true;
}
private static bool IsDynamicMember(Symbol sym)
{
System.Runtime.CompilerServices.DynamicAttribute da = null;
if (sym is FieldSymbol field)
{
if (!field.getType().IsPredefType(PredefinedType.PT_OBJECT))
{
return false;
}
var o = field.AssociatedFieldInfo.GetCustomAttributes(typeof(System.Runtime.CompilerServices.DynamicAttribute), false).ToArray();
if (o.Length == 1)
{
da = o[0] as System.Runtime.CompilerServices.DynamicAttribute;
}
}
else
{
Debug.Assert(sym is PropertySymbol);
PropertySymbol prop = (PropertySymbol)sym;
if (!prop.getType().IsPredefType(PredefinedType.PT_OBJECT))
{
return false;
}
var o = prop.AssociatedPropertyInfo.GetCustomAttributes(typeof(System.Runtime.CompilerServices.DynamicAttribute), false).ToArray();
if (o.Length == 1)
{
da = o[0] as System.Runtime.CompilerServices.DynamicAttribute;
}
}
if (da == null)
{
return false;
}
return (da.TransformFlags.Count == 0 || (da.TransformFlags.Count == 1 && da.TransformFlags[0]));
}
/******************************************************************************
Lookup in a class and its bases (until *ptypeEnd is hit).
ptypeEnd [in/out] - *ptypeEnd should be either null or object. If we find
something here that would hide members of object, this sets *ptypeEnd
to null.
Returns true when searching should continue to the interfaces.
******************************************************************************/
private bool LookupInClass(AggregateType typeStart, ref AggregateType ptypeEnd)
{
Debug.Assert(!_swtFirst || _fMulti);
Debug.Assert(typeStart != null && !typeStart.IsInterfaceType && (ptypeEnd == null || typeStart != ptypeEnd));
AggregateType typeEnd = ptypeEnd;
AggregateType typeCur;
// Loop through types. Loop until we hit typeEnd (object or null).
for (typeCur = typeStart; typeCur != typeEnd && typeCur != null; typeCur = typeCur.BaseClass)
{
Debug.Assert(!typeCur.IsInterfaceType);
SearchSingleType(typeCur, out bool fHideByName);
if (_swtFirst && !_fMulti)
{
// Everything below this type and in interfaces is hidden.
return false;
}
if (fHideByName)
{
// This hides everything below it and in object, but not in the interfaces!
ptypeEnd = null;
// Return true to indicate that it's ok to search additional types.
return true;
}
if ((_flags & MemLookFlags.Ctor) != 0)
{
// If we're looking for a constructor, don't check base classes or interfaces.
return false;
}
}
Debug.Assert(typeCur == typeEnd);
return true;
}
/******************************************************************************
Returns true if searching should continue to object.
******************************************************************************/
private bool LookupInInterfaces(AggregateType typeStart, TypeArray types)
{
Debug.Assert(!_swtFirst || _fMulti);
Debug.Assert(typeStart == null || typeStart.IsInterfaceType);
Debug.Assert(typeStart != null || types.Count != 0);
// Clear all the hidden flags. Anything found in a class hides any other
// kind of member in all the interfaces.
if (typeStart != null)
{
typeStart.AllHidden = false;
typeStart.DiffHidden = (_swtFirst != null);
}
for (int i = 0; i < types.Count; i++)
{
AggregateType type = (AggregateType)types[i];
Debug.Assert(type.IsInterfaceType);
type.AllHidden = false;
type.DiffHidden = !!_swtFirst;
}
bool fHideObject = false;
AggregateType typeCur = typeStart;
int itypeNext = 0;
if (typeCur == null)
{
typeCur = (AggregateType)types[itypeNext++];
}
Debug.Assert(typeCur != null);
// Loop through the interfaces.
for (; ;)
{
Debug.Assert(typeCur != null && typeCur.IsInterfaceType);
if (!typeCur.AllHidden && SearchSingleType(typeCur, out bool fHideByName))
{
fHideByName |= !_fMulti;
// Mark base interfaces appropriately.
foreach (AggregateType type in typeCur.IfacesAll.Items)
{
Debug.Assert(type.IsInterfaceType);
if (fHideByName)
{
type.AllHidden = true;
}
type.DiffHidden = true;
}
// If we hide all base types, that includes object!
if (fHideByName)
{
fHideObject = true;
}
}
if (itypeNext >= types.Count)
{
return !fHideObject;
}
// Substitution has already been done.
typeCur = types[itypeNext++] as AggregateType;
}
}
private static RuntimeBinderException ReportBogus(SymWithType swt)
{
Debug.Assert(CSemanticChecker.CheckBogus(swt.Sym));
MethodSymbol meth1 = swt.Prop().GetterMethod;
MethodSymbol meth2 = swt.Prop().SetterMethod;
Debug.Assert((meth1 ?? meth2) != null);
return meth1 == null | meth2 == null
? ErrorHandling.Error(
ErrorCode.ERR_BindToBogusProp1, swt.Sym.name, new SymWithType(meth1 ?? meth2, swt.GetType()),
new ErrArgRefOnly(swt.Sym))
: ErrorHandling.Error(
ErrorCode.ERR_BindToBogusProp2, swt.Sym.name, new SymWithType(meth1, swt.GetType()),
new SymWithType(meth2, swt.GetType()), new ErrArgRefOnly(swt.Sym));
}
private static bool IsDelegateType(CType pSrcType, AggregateType pAggType) =>
TypeManager.SubstType(pSrcType, pAggType, pAggType.TypeArgsAll).IsDelegateType;
/////////////////////////////////////////////////////////////////////////////////
// Public methods.
public MemberLookup()
{
_methPropWithTypeList = new List<MethPropWithType>();
_rgtypeStart = new List<AggregateType>();
_swtFirst = new SymWithType();
_swtAmbig = new SymWithType();
_swtInaccess = new SymWithType();
_swtBad = new SymWithType();
_swtBogus = new SymWithType();
_swtBadArity = new SymWithType();
}
/***************************************************************************************************
Lookup must be called before anything else can be called.
typeSrc - Must be an AggregateType or TypeParameterType.
obj - the expression through which the member is being accessed. This is used for accessibility
of protected members and for constructing a MEMGRP from the results of the lookup.
It is legal for obj to be an EK_CLASS, in which case it may be used for accessibility, but
will not be used for MEMGRP construction.
symWhere - the symbol from with the name is being accessed (for checking accessibility).
name - the name to look for.
arity - the number of type args specified. Only members that support this arity are found.
Note that when arity is zero, all methods are considered since we do type argument
inferencing.
flags - See MemLookFlags.
TypeVarsAllowed only applies to the most derived type (not base types).
***************************************************************************************************/
public bool Lookup(CType typeSrc, Expr obj, ParentSymbol symWhere, Name name, int arity, MemLookFlags flags)
{
Debug.Assert((flags & ~MemLookFlags.All) == 0);
Debug.Assert(obj == null || obj.Type != null);
Debug.Assert(typeSrc is AggregateType);
_prgtype = _rgtypeStart;
// Save the inputs for error handling, etc.
_typeSrc = typeSrc;
_symWhere = symWhere;
_name = name;
_arity = arity;
_flags = flags;
_typeQual = (_flags & MemLookFlags.Ctor) != 0 ? _typeSrc : obj?.Type;
// Determine what to search.
AggregateType typeCls1;
AggregateType typeIface;
TypeArray ifaces;
if (typeSrc.IsInterfaceType)
{
Debug.Assert((_flags & (MemLookFlags.Ctor | MemLookFlags.NewObj | MemLookFlags.Operator | MemLookFlags.BaseCall)) == 0);
typeCls1 = null;
typeIface = (AggregateType)typeSrc;
ifaces = typeIface.IfacesAll;
}
else
{
typeCls1 = (AggregateType)typeSrc;
typeIface = null;
ifaces = typeCls1.IsWindowsRuntimeType ? typeCls1.WinRTCollectionIfacesAll : TypeArray.Empty;
}
AggregateType typeCls2 = typeIface != null || ifaces.Count > 0
? SymbolLoader.GetPredefindType(PredefinedType.PT_OBJECT)
: null;
// Search the class first (except possibly object).
if (typeCls1 == null || LookupInClass(typeCls1, ref typeCls2))
{
// Search the interfaces.
if ((typeIface != null || ifaces.Count > 0) && LookupInInterfaces(typeIface, ifaces) && typeCls2 != null)
{
// Search object last.
Debug.Assert(typeCls2 != null && typeCls2.IsPredefType(PredefinedType.PT_OBJECT));
AggregateType result = null;
LookupInClass(typeCls2, ref result);
}
}
return !FError();
}
// Whether there were errors.
private bool FError()
{
return !_swtFirst || _swtAmbig;
}
// The first symbol found.
public SymWithType SwtFirst()
{
return _swtFirst;
}
/******************************************************************************
Reports errors. Only call this if FError() is true.
******************************************************************************/
public Exception ReportErrors()
{
Debug.Assert(FError());
// Report error.
// NOTE: If the definition of FError changes, this code will need to change.
Debug.Assert(!_swtFirst || _swtAmbig);
if (_swtFirst)
{
// Ambiguous lookup.
return ErrorHandling.Error(ErrorCode.ERR_AmbigMember, _swtFirst, _swtAmbig);
}
if (_swtInaccess)
{
return !_swtInaccess.Sym.isUserCallable() && ((_flags & MemLookFlags.UserCallable) != 0)
? ErrorHandling.Error(ErrorCode.ERR_CantCallSpecialMethod, _swtInaccess)
: CSemanticChecker.ReportAccessError(_swtInaccess, _symWhere, _typeQual);
}
if ((_flags & MemLookFlags.Ctor) != 0)
{
Debug.Assert(_typeSrc is AggregateType);
return _arity > 0
? ErrorHandling.Error(ErrorCode.ERR_BadCtorArgCount, ((AggregateType)_typeSrc).OwningAggregate, _arity)
: ErrorHandling.Error(ErrorCode.ERR_NoConstructors, ((AggregateType)_typeSrc).OwningAggregate);
}
if ((_flags & MemLookFlags.Operator) != 0)
{
return ErrorHandling.Error(ErrorCode.ERR_NoSuchMember, _typeSrc, _name);
}
if ((_flags & MemLookFlags.Indexer) != 0)
{
return ErrorHandling.Error(ErrorCode.ERR_BadIndexLHS, _typeSrc);
}
if (_swtBad)
{
return ErrorHandling.Error((_flags & MemLookFlags.MustBeInvocable) != 0 ? ErrorCode.ERR_NonInvocableMemberCalled : ErrorCode.ERR_CantCallSpecialMethod, _swtBad);
}
if (_swtBogus)
{
return ReportBogus(_swtBogus);
}
if (_swtBadArity)
{
Debug.Assert(_arity != 0);
Debug.Assert(!(_swtBadArity.Sym is AggregateSymbol));
if (_swtBadArity.Sym is MethodSymbol badMeth)
{
int cvar = badMeth.typeVars.Count;
return ErrorHandling.Error(cvar > 0 ? ErrorCode.ERR_BadArity : ErrorCode.ERR_HasNoTypeVars, _swtBadArity, new ErrArgSymKind(_swtBadArity.Sym), cvar);
}
return ErrorHandling.Error(ErrorCode.ERR_TypeArgsNotAllowed, _swtBadArity, new ErrArgSymKind(_swtBadArity.Sym));
}
return ErrorHandling.Error(ErrorCode.ERR_NoSuchMember, _typeSrc, _name);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="BuildableExpectation.cs" company="NMock2">
//
// http://www.sourceforge.net/projects/NMock2
//
// 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>
//-----------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NMocha.Monitoring;
using NMock2;
using NMock2.Matchers;
using NMock2.Monitoring;
namespace NMocha.Internal {
public class InvocationExpectation : IExpectation {
private readonly Cardinality cardinality;
private readonly ArrayList actions = new ArrayList();
private readonly ArrayList extraMatchers = new ArrayList();
private readonly List<IOrderingConstraint> orderingConstraints = new List<IOrderingConstraint>();
private readonly List<ISideEffect> sideEffects = new List<ISideEffect>();
private Matcher argumentsMatcher = new AlwaysMatcher(true, "(any arguments)");
private int callCount;
private string expectationComment;
private Matcher genericMethodTypeMatcher = new AlwaysMatcher(true, string.Empty);
private Matcher methodMatcher = new AlwaysMatcher(true, "<any method>");
private string methodSeparator = ".";
private IMockObject receiver;
public InvocationExpectation(Cardinality cardinality) {
this.cardinality = cardinality;
}
public IMockObject Receiver {
get { return receiver; }
set { receiver = value; }
}
public Matcher MethodMatcher {
get { return methodMatcher; }
set { methodMatcher = value; }
}
public Matcher GenericMethodTypeMatcher {
get { return genericMethodTypeMatcher; }
set { genericMethodTypeMatcher = value; }
}
public Matcher ArgumentsMatcher {
get { return argumentsMatcher; }
set { argumentsMatcher = value; }
}
#region IExpectation Members
public bool IsActive {
get { return cardinality.AllowsMoreInvocations(callCount); }
}
public bool HasBeenMet {
get { return cardinality.IsSatisfied(callCount); }
}
public bool Matches(Invocation invocation) {
return IsActive
&& receiver == invocation.Receiver
&& methodMatcher.Matches(invocation.Method)
&& argumentsMatcher.Matches(invocation)
&& ExtraMatchersMatch(invocation)
&& GenericMethodTypeMatcher.Matches(invocation)
&& IsInCorrectOrder();
}
public bool MatchesIgnoringIsActive(Invocation invocation) {
return receiver == invocation.Receiver
&& methodMatcher.Matches(invocation.Method)
&& argumentsMatcher.Matches(invocation)
&& ExtraMatchersMatch(invocation)
&& GenericMethodTypeMatcher.Matches(invocation);
}
public void Perform(Invocation invocation) {
callCount++;
foreach (IAction action in actions)
{
action.Invoke(invocation);
}
sideEffects.ForEach(sideEffect => sideEffect.Apply());
}
public void DescribeActiveExpectationsTo(IDescription writer) {
if (IsActive)
{
DescribeTo(writer);
}
}
public void DescribeUnmetExpectationsTo(IDescription writer) {
DescribeTo(writer);
}
#endregion
public void AddInvocationMatcher(Matcher matcher) {
extraMatchers.Add(matcher);
}
public void AddAction(IAction action) {
actions.Add(action);
}
public void AddComment(string comment) {
expectationComment = comment;
}
private bool IsInCorrectOrder() {
return orderingConstraints.All(orderConstraint => orderConstraint.AllowsInvocationNow());
}
public void DescribeAsIndexer() {
methodSeparator = string.Empty;
}
private bool ExtraMatchersMatch(Invocation invocation) {
return extraMatchers.Cast<Matcher>().All(matcher => matcher.Matches(invocation));
}
private void DescribeTo(IDescription writer) {
DescribeMethod(writer);
argumentsMatcher.DescribeOn(writer);
foreach (Matcher extraMatcher in extraMatchers)
{
writer.AppendText(", ");
extraMatcher.DescribeOn(writer);
}
if (actions.Count > 0)
{
writer.AppendText(", will ");
((IAction) actions[0]).DescribeOn(writer);
for (int i = 1; i < actions.Count; i++)
{
writer.AppendText(", ");
((IAction) actions[i]).DescribeOn(writer);
}
}
DescribeOrderingConstraintsOn(writer);
sideEffects.ForEach(sideEffect => sideEffect.DescribeOn(writer));
if (!string.IsNullOrEmpty(expectationComment))
{
writer.AppendText(" Comment: ")
.AppendText(expectationComment);
}
}
private void DescribeMethod(IDescription description) {
cardinality.DescribeOn(description);
DescribeInvocationCount(description, callCount);
description.AppendText(": ")
.AppendText(receiver.MockName)
.AppendText(methodSeparator);
methodMatcher.DescribeOn(description);
genericMethodTypeMatcher.DescribeOn(description);
}
private void DescribeInvocationCount(IDescription description, int count) {
if(cardinality.Equals(Cardinality.Never())) return;
description.AppendText(", ");
if (count == 0 )
{
description.AppendText("never invoked");
}
else
{
description.AppendText("already invoked ");
description.AppendText(count.ToString());
description.AppendText(" time");
if (count != 1)
{
description.AppendText("s");
}
}
}
private void DescribeOrderingConstraintsOn(IDescription writer) {
if (!orderingConstraints.Any()) return;
writer.AppendText(" ");
orderingConstraints.ForEach(constraint => constraint.DescribeOn(writer));
}
public void AddOrderingConstraint(IOrderingConstraint orderingConstraint) {
orderingConstraints.Add(orderingConstraint);
}
public void AddSideEffect(ISideEffect sideEffect) {
sideEffects.Add(sideEffect);
}
}
public interface ISideEffect : ISelfDescribing {
void Apply();
}
}
| |
/*
Small JSON parser implementation for .NET 3.0 or later
Copyright (c) 2014, Takashi Kawasaki
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace SimpleJsonParser
{
public class JsonParser
{
public static object Parse(TextReader jsonReader)
{
var p = new JsonParser(jsonReader);
return p.Parse();
}
public static object Parse(string json)
{
return Parse(new StringReader(json));
}
public static object Parse(Stream json)
{
return Parse(new StreamReader(json));
}
public static object ParseFile(string jsonFile, Encoding encoding)
{
using (var sr = new StreamReader(File.OpenRead(jsonFile), encoding))
return Parse(sr);
}
/// <summary>
/// Get the object on the specified path.
/// Please note that array index starts with 0.
/// </summary>
/// <typeparam name="T">Type of the object.</typeparam>
/// <param name="obj">Parsed JSON object.</param>
/// <param name="path">Object path in the JSON object.</param>
/// <param name="defValue">The default value for not found case.</param>
/// <returns>The object. If the object is found but the type is different, the <paramref name="defValue"/> is returned.</returns>
public static T JsonWalk<T>(object obj, string path, T defValue)
{
return JsonWalk<T>(obj, defValue, path.Split('/'), 0);
}
public static T JsonWalk<T>(object obj, T defValue, string[] path, int index)
{
if (index > path.Length)
{
return defValue;
}
else if (index == path.Length)
{
if (obj is T)
return (T)obj;
return defValue;
}
else
{
int arrIndex;
if (int.TryParse(path[index], out arrIndex))
{
var arr = obj as object[];
if (arr != null)
return JsonWalk<T>(arr[arrIndex], defValue, path, ++index);
}
var dict = obj as Dictionary<string, object>;
if (dict == null)
return defValue;
object v;
if (!dict.TryGetValue(path[index], out v))
return defValue;
return JsonWalk<T>(v, defValue, path, ++index);
}
}
private JsonParser(TextReader sr)
{
reader = sr;
}
TextReader reader;
const int NoChar = -1;
string fileName = "unknown.json";
int lastReadChar = NoChar;
int backingChar = NoChar;
int line = 1;
int column = 0;
int readChar()
{
column++;
if (backingChar != NoChar)
{
var c = lastReadChar = backingChar;
backingChar = NoChar;
return c;
}
else
{
var c = reader.Read();
lastReadChar = c;
return c;
}
}
void unreadChar(int c)
{
if (backingChar != NoChar)
throw new InvalidOperationException("Duplicate unread of character.");
backingChar = c;
column--;
}
void unreadChar()
{
unreadChar(lastReadChar);
lastReadChar = NoChar;
}
object Parse()
{
var contexts = new Stack<object>();
var sb = new StringBuilder();
object obj = null;
var keys = new Stack<string>();
while (true)
{
var c = readChar();
if (c == '"')
{
if (obj != null || sb.Length > 0)
throw dataException("Unexpected '\"'.");
obj = readString();
}
else if (c == '[')
{
if (obj != null || sb.Length > 0)
throw dataException("Unexpected '['.");
contexts.Push(new List<object>());
}
else if (c == '{')
{
if (obj != null || sb.Length > 0)
throw dataException("Unexpected '{'.");
contexts.Push(new Dictionary<string, object>());
}
else if (c == ',')
{
if (obj == null && sb.Length == 0)
throw dataException("Unexpected ','.");
obj = obj ?? parseString(sb.ToString());
var container = contexts.Count > 0 ? contexts.Peek() : null;
var list = container as List<object>;
if (list != null)
{
list.Add(transform(obj));
obj = null;
sb = new StringBuilder();
continue;
}
var dict = container as Dictionary<string, object>;
if (dict != null)
{
if (keys.Count == 0)
throw dataException("Unexpected ','.");
dict.Add(keys.Pop(), transform(obj));
obj = null;
sb = new StringBuilder();
continue;
}
throw dataException("Unexpected ','.");
}
else if (c == ':')
{
var key = obj as string;
if (key == null || sb.Length > 0)
throw dataException("Unexpected ':'.");
obj = null;
keys.Push(key);
}
else if (c == ']')
{
var arr = contexts.Count > 0 ? contexts.Pop() as List<object> : null;
if (arr == null)
throw dataException("Unexpected ']'.");
if (obj != null || sb.Length > 0)
arr.Add(transform(obj ?? parseString(sb.ToString())));
if (contexts.Count == 0)
return arr.ToArray();
obj = arr.ToArray();
sb = new StringBuilder();
}
else if (c == '}')
{
var dict = contexts.Count > 0 ? contexts.Pop() as Dictionary<string, object> : null;
if (dict == null)
throw dataException("Unmatched '}'.");
if (obj != null || sb.Length > 0)
{
if (keys.Count == 0)
throw dataException("Unexpected '}'.");
dict.Add(keys.Pop(), transform(obj ?? parseString(sb.ToString())));
obj = null;
sb = new StringBuilder();
}
if (contexts.Count == 0)
return dict;
else
obj = dict;
}
else if (c == NoChar || " \t\r\n".IndexOf((char)c) >= 0)
{
if (sb.Length > 0)
{
if (obj != null)
throw dataException(string.Format("Unexpected literal '{0}'.", sb.ToString()));
obj = parseString(sb.ToString());
sb = new StringBuilder();
}
if (c == NoChar)
{
return obj;
}
else if (c == '\r')
{
if (readChar() != '\n')
unreadChar();
line++;
column = 0;
}
else if (c == '\n')
{
line++;
column = 0;
}
}
else
{
sb.Append((char)c);
}
}
}
class Null
{
public static readonly Null _null = new Null();
private Null() { }
};
object transform(object obj)
{
if (obj is Null)
return null;
return obj;
}
object parseString(string s)
{
if (s == "true")
return true;
if (s == "false")
return false;
if (s == "null")
return Null._null;
int v;
if (int.TryParse(s, out v))
return v;
return double.Parse(s);
}
string readString()
{
var sb = new StringBuilder();
for (; ; )
{
var c = readChar();
switch (c)
{
case NoChar:
throw dataException("string sequence does not terminated correctly.");
case '"':
return sb.ToString();
case '\\':
switch (c = readChar())
{
case '"': sb.Append('"'); break;
case '\\': sb.Append('\\'); break;
case '/': sb.Append('/'); break;
case 'b': sb.Append('\b'); break;
case 'f': sb.Append('\f'); break;
case 'n': sb.Append('\n'); break;
case 'r': sb.Append('\r'); break;
case 't': sb.Append('\t'); break;
case 'u':
{
var sbHex4 = new StringBuilder(4);
sbHex4.Append((char)readChar());
sbHex4.Append((char)readChar());
sbHex4.Append((char)readChar());
sbHex4.Append((char)readChar());
sb.Append((char)int.Parse(sbHex4.ToString(), System.Globalization.NumberStyles.AllowHexSpecifier));
break;
}
default:
throw dataException(string.Format("Invalid escape sequence \\{0}", (char)c));
}
break;
default:
sb.Append((char)c);
break;
}
}
}
Exception dataException(string errorMessage)
{
return new Exception(string.Format("{0}({1},{2}): {3}", fileName, line, column, errorMessage));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using System.Reflection;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Reflection.Runtime.Assemblies;
using Internal.LowLevelLinq;
using Internal.Reflection.Core;
using Internal.Runtime.Augments;
using Internal.Metadata.NativeFormat;
using NativeFormatAssemblyFlags = global::Internal.Metadata.NativeFormat.AssemblyFlags;
namespace System.Reflection.Runtime.General
{
//
// Collect various metadata reading tasks for better chunking...
//
internal static class NativeFormatMetadataReaderExtensions
{
public static bool StringOrNullEquals(this ConstantStringValueHandle handle, String valueOrNull, MetadataReader reader)
{
if (valueOrNull == null)
return handle.IsNull(reader);
if (handle.IsNull(reader))
return false;
return handle.StringEquals(valueOrNull, reader);
}
// Needed for RuntimeMappingTable access
public static int AsInt(this TypeDefinitionHandle typeDefinitionHandle)
{
unsafe
{
return *(int*)&typeDefinitionHandle;
}
}
public static TypeDefinitionHandle AsTypeDefinitionHandle(this int i)
{
unsafe
{
return *(TypeDefinitionHandle*)&i;
}
}
public static int AsInt(this MethodHandle methodHandle)
{
unsafe
{
return *(int*)&methodHandle;
}
}
public static MethodHandle AsMethodHandle(this int i)
{
unsafe
{
return *(MethodHandle*)&i;
}
}
public static int AsInt(this FieldHandle fieldHandle)
{
unsafe
{
return *(int*)&fieldHandle;
}
}
public static FieldHandle AsFieldHandle(this int i)
{
unsafe
{
return *(FieldHandle*)&i;
}
}
public static bool IsNamespaceDefinitionHandle(this Handle handle, MetadataReader reader)
{
HandleType handleType = handle.HandleType;
return handleType == HandleType.NamespaceDefinition;
}
public static bool IsNamespaceReferenceHandle(this Handle handle, MetadataReader reader)
{
HandleType handleType = handle.HandleType;
return handleType == HandleType.NamespaceReference;
}
// Conversion where a invalid handle type indicates bad metadata rather a mistake by the caller.
public static ScopeReferenceHandle ToExpectedScopeReferenceHandle(this Handle handle, MetadataReader reader)
{
try
{
return handle.ToScopeReferenceHandle(reader);
}
catch (ArgumentException)
{
throw new BadImageFormatException();
}
}
// Conversion where a invalid handle type indicates bad metadata rather a mistake by the caller.
public static NamespaceReferenceHandle ToExpectedNamespaceReferenceHandle(this Handle handle, MetadataReader reader)
{
try
{
return handle.ToNamespaceReferenceHandle(reader);
}
catch (ArgumentException)
{
throw new BadImageFormatException();
}
}
// Conversion where a invalid handle type indicates bad metadata rather a mistake by the caller.
public static TypeDefinitionHandle ToExpectedTypeDefinitionHandle(this Handle handle, MetadataReader reader)
{
try
{
return handle.ToTypeDefinitionHandle(reader);
}
catch (ArgumentException)
{
throw new BadImageFormatException();
}
}
// Return any custom modifiers modifying the passed-in type and whose required/optional bit matches the passed in boolean.
// Because this is intended to service the GetCustomModifiers() apis, this helper will always return a freshly allocated array
// safe for returning to api callers.
public static Type[] GetCustomModifiers(this Handle handle, MetadataReader reader, TypeContext typeContext, bool optional)
{
HandleType handleType = handle.HandleType;
Debug.Assert(handleType == HandleType.TypeDefinition || handleType == HandleType.TypeReference || handleType == HandleType.TypeSpecification || handleType == HandleType.ModifiedType);
if (handleType != HandleType.ModifiedType)
return Array.Empty<Type>();
LowLevelList<Type> customModifiers = new LowLevelList<Type>();
do
{
ModifiedType modifiedType = handle.ToModifiedTypeHandle(reader).GetModifiedType(reader);
if (optional == modifiedType.IsOptional)
{
Type customModifier = modifiedType.ModifierType.Resolve(reader, typeContext);
customModifiers.Add(customModifier);
}
handle = modifiedType.Type;
handleType = handle.HandleType;
}
while (handleType == HandleType.ModifiedType);
return customModifiers.ToArray();
}
public static MethodSignature ParseMethodSignature(this Handle handle, MetadataReader reader)
{
return handle.ToMethodSignatureHandle(reader).GetMethodSignature(reader);
}
public static FieldSignature ParseFieldSignature(this Handle handle, MetadataReader reader)
{
return handle.ToFieldSignatureHandle(reader).GetFieldSignature(reader);
}
public static PropertySignature ParsePropertySignature(this Handle handle, MetadataReader reader)
{
return handle.ToPropertySignatureHandle(reader).GetPropertySignature(reader);
}
//
// Used to split methods between DeclaredMethods and DeclaredConstructors.
//
public static bool IsConstructor(this MethodHandle methodHandle, MetadataReader reader)
{
Method method = methodHandle.GetMethod(reader);
return IsConstructor(ref method, reader);
}
// This is specially designed for a hot path so we make some compromises in the signature:
//
// - "method" is passed by reference even though no side-effects are intended.
//
public static bool IsConstructor(ref Method method, MetadataReader reader)
{
if ((method.Flags & (MethodAttributes.RTSpecialName | MethodAttributes.SpecialName)) != (MethodAttributes.RTSpecialName | MethodAttributes.SpecialName))
return false;
ConstantStringValueHandle nameHandle = method.Name;
return nameHandle.StringEquals(ConstructorInfo.ConstructorName, reader) || nameHandle.StringEquals(ConstructorInfo.TypeConstructorName, reader);
}
private static Exception ParseBoxedEnumConstantValue(this ConstantBoxedEnumValueHandle handle, MetadataReader reader, out Object value)
{
ConstantBoxedEnumValue record = handle.GetConstantBoxedEnumValue(reader);
Exception exception = null;
Type enumType = record.Type.TryResolve(reader, new TypeContext(null, null), ref exception);
if (enumType == null)
{
value = null;
return exception;
}
if (!enumType.IsEnum)
throw new BadImageFormatException();
Type underlyingType = Enum.GetUnderlyingType(enumType);
// Now box the value as the specified enum type.
unsafe
{
switch (record.Value.HandleType)
{
case HandleType.ConstantByteValue:
{
if (underlyingType != CommonRuntimeTypes.Byte)
throw new BadImageFormatException();
byte v = record.Value.ToConstantByteValueHandle(reader).GetConstantByteValue(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantSByteValue:
{
if (underlyingType != CommonRuntimeTypes.SByte)
throw new BadImageFormatException();
sbyte v = record.Value.ToConstantSByteValueHandle(reader).GetConstantSByteValue(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantInt16Value:
{
if (underlyingType != CommonRuntimeTypes.Int16)
throw new BadImageFormatException();
short v = record.Value.ToConstantInt16ValueHandle(reader).GetConstantInt16Value(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantUInt16Value:
{
if (underlyingType != CommonRuntimeTypes.UInt16)
throw new BadImageFormatException();
ushort v = record.Value.ToConstantUInt16ValueHandle(reader).GetConstantUInt16Value(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantInt32Value:
{
if (underlyingType != CommonRuntimeTypes.Int32)
throw new BadImageFormatException();
int v = record.Value.ToConstantInt32ValueHandle(reader).GetConstantInt32Value(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantUInt32Value:
{
if (underlyingType != CommonRuntimeTypes.UInt32)
throw new BadImageFormatException();
uint v = record.Value.ToConstantUInt32ValueHandle(reader).GetConstantUInt32Value(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantInt64Value:
{
if (underlyingType != CommonRuntimeTypes.Int64)
throw new BadImageFormatException();
long v = record.Value.ToConstantInt64ValueHandle(reader).GetConstantInt64Value(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantUInt64Value:
{
if (underlyingType != CommonRuntimeTypes.UInt64)
throw new BadImageFormatException();
ulong v = record.Value.ToConstantUInt64ValueHandle(reader).GetConstantUInt64Value(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
default:
throw new BadImageFormatException();
}
}
}
public static Object ParseConstantValue(this Handle handle, MetadataReader reader)
{
Object value;
Exception exception = handle.TryParseConstantValue(reader, out value);
if (exception != null)
throw exception;
return value;
}
public static Exception TryParseConstantValue(this Handle handle, MetadataReader reader, out Object value)
{
HandleType handleType = handle.HandleType;
switch (handleType)
{
case HandleType.ConstantBooleanValue:
value = handle.ToConstantBooleanValueHandle(reader).GetConstantBooleanValue(reader).Value;
return null;
case HandleType.ConstantStringValue:
value = handle.ToConstantStringValueHandle(reader).GetConstantStringValue(reader).Value;
return null;
case HandleType.ConstantCharValue:
value = handle.ToConstantCharValueHandle(reader).GetConstantCharValue(reader).Value;
return null;
case HandleType.ConstantByteValue:
value = handle.ToConstantByteValueHandle(reader).GetConstantByteValue(reader).Value;
return null;
case HandleType.ConstantSByteValue:
value = handle.ToConstantSByteValueHandle(reader).GetConstantSByteValue(reader).Value;
return null;
case HandleType.ConstantInt16Value:
value = handle.ToConstantInt16ValueHandle(reader).GetConstantInt16Value(reader).Value;
return null;
case HandleType.ConstantUInt16Value:
value = handle.ToConstantUInt16ValueHandle(reader).GetConstantUInt16Value(reader).Value;
return null;
case HandleType.ConstantInt32Value:
value = handle.ToConstantInt32ValueHandle(reader).GetConstantInt32Value(reader).Value;
return null;
case HandleType.ConstantUInt32Value:
value = handle.ToConstantUInt32ValueHandle(reader).GetConstantUInt32Value(reader).Value;
return null;
case HandleType.ConstantInt64Value:
value = handle.ToConstantInt64ValueHandle(reader).GetConstantInt64Value(reader).Value;
return null;
case HandleType.ConstantUInt64Value:
value = handle.ToConstantUInt64ValueHandle(reader).GetConstantUInt64Value(reader).Value;
return null;
case HandleType.ConstantSingleValue:
value = handle.ToConstantSingleValueHandle(reader).GetConstantSingleValue(reader).Value;
return null;
case HandleType.ConstantDoubleValue:
value = handle.ToConstantDoubleValueHandle(reader).GetConstantDoubleValue(reader).Value;
return null;
case HandleType.TypeDefinition:
case HandleType.TypeReference:
case HandleType.TypeSpecification:
{
Exception exception = null;
Type type = handle.TryResolve(reader, new TypeContext(null, null), ref exception);
value = type;
return (value == null) ? exception : null;
}
case HandleType.ConstantReferenceValue:
value = null;
return null;
case HandleType.ConstantBoxedEnumValue:
{
return handle.ToConstantBoxedEnumValueHandle(reader).ParseBoxedEnumConstantValue(reader, out value);
}
default:
{
Exception exception;
value = handle.TryParseConstantArray(reader, out exception);
if (value == null)
return exception;
return null;
}
}
}
private static Array TryParseConstantArray(this Handle handle, MetadataReader reader, out Exception exception)
{
exception = null;
HandleType handleType = handle.HandleType;
switch (handleType)
{
case HandleType.ConstantBooleanArray:
return handle.ToConstantBooleanArrayHandle(reader).GetConstantBooleanArray(reader).Value.ReadOnlyCollectionToArray();
case HandleType.ConstantCharArray:
return handle.ToConstantCharArrayHandle(reader).GetConstantCharArray(reader).Value.ReadOnlyCollectionToArray();
case HandleType.ConstantByteArray:
return handle.ToConstantByteArrayHandle(reader).GetConstantByteArray(reader).Value.ReadOnlyCollectionToArray();
case HandleType.ConstantSByteArray:
return handle.ToConstantSByteArrayHandle(reader).GetConstantSByteArray(reader).Value.ReadOnlyCollectionToArray();
case HandleType.ConstantInt16Array:
return handle.ToConstantInt16ArrayHandle(reader).GetConstantInt16Array(reader).Value.ReadOnlyCollectionToArray();
case HandleType.ConstantUInt16Array:
return handle.ToConstantUInt16ArrayHandle(reader).GetConstantUInt16Array(reader).Value.ReadOnlyCollectionToArray();
case HandleType.ConstantInt32Array:
return handle.ToConstantInt32ArrayHandle(reader).GetConstantInt32Array(reader).Value.ReadOnlyCollectionToArray();
case HandleType.ConstantUInt32Array:
return handle.ToConstantUInt32ArrayHandle(reader).GetConstantUInt32Array(reader).Value.ReadOnlyCollectionToArray();
case HandleType.ConstantInt64Array:
return handle.ToConstantInt64ArrayHandle(reader).GetConstantInt64Array(reader).Value.ReadOnlyCollectionToArray();
case HandleType.ConstantUInt64Array:
return handle.ToConstantUInt64ArrayHandle(reader).GetConstantUInt64Array(reader).Value.ReadOnlyCollectionToArray();
case HandleType.ConstantSingleArray:
return handle.ToConstantSingleArrayHandle(reader).GetConstantSingleArray(reader).Value.ReadOnlyCollectionToArray();
case HandleType.ConstantDoubleArray:
return handle.ToConstantDoubleArrayHandle(reader).GetConstantDoubleArray(reader).Value.ReadOnlyCollectionToArray();
case HandleType.ConstantEnumArray:
return TryParseConstantEnumArray(handle.ToConstantEnumArrayHandle(reader), reader, out exception);
case HandleType.ConstantStringArray:
{
Handle[] constantHandles = handle.ToConstantStringArrayHandle(reader).GetConstantStringArray(reader).Value.ToArray();
string[] elements = new string[constantHandles.Length];
for (int i = 0; i < constantHandles.Length; i++)
{
object elementValue;
exception = constantHandles[i].TryParseConstantValue(reader, out elementValue);
if (exception != null)
return null;
elements[i] = (string)elementValue;
}
return elements;
}
case HandleType.ConstantHandleArray:
{
Handle[] constantHandles = handle.ToConstantHandleArrayHandle(reader).GetConstantHandleArray(reader).Value.ToArray();
object[] elements = new object[constantHandles.Length];
for (int i = 0; i < constantHandles.Length; i++)
{
exception = constantHandles[i].TryParseConstantValue(reader, out elements[i]);
if (exception != null)
return null;
}
return elements;
}
default:
throw new BadImageFormatException();
}
}
private static Array TryParseConstantEnumArray(this ConstantEnumArrayHandle handle, MetadataReader reader, out Exception exception)
{
exception = null;
ConstantEnumArray enumArray = handle.GetConstantEnumArray(reader);
Type elementType = enumArray.ElementType.TryResolve(reader, new TypeContext(null, null), ref exception);
if (exception != null)
return null;
switch (enumArray.Value.HandleType)
{
case HandleType.ConstantByteArray:
return enumArray.Value.ToConstantByteArrayHandle(reader).GetConstantByteArray(reader).Value.ReadOnlyCollectionToEnumArray(elementType);
case HandleType.ConstantSByteArray:
return enumArray.Value.ToConstantSByteArrayHandle(reader).GetConstantSByteArray(reader).Value.ReadOnlyCollectionToEnumArray(elementType);
case HandleType.ConstantInt16Array:
return enumArray.Value.ToConstantInt16ArrayHandle(reader).GetConstantInt16Array(reader).Value.ReadOnlyCollectionToEnumArray(elementType);
case HandleType.ConstantUInt16Array:
return enumArray.Value.ToConstantUInt16ArrayHandle(reader).GetConstantUInt16Array(reader).Value.ReadOnlyCollectionToEnumArray(elementType);
case HandleType.ConstantInt32Array:
return enumArray.Value.ToConstantInt32ArrayHandle(reader).GetConstantInt32Array(reader).Value.ReadOnlyCollectionToEnumArray(elementType);
case HandleType.ConstantUInt32Array:
return enumArray.Value.ToConstantUInt32ArrayHandle(reader).GetConstantUInt32Array(reader).Value.ReadOnlyCollectionToEnumArray(elementType);
case HandleType.ConstantInt64Array:
return enumArray.Value.ToConstantInt64ArrayHandle(reader).GetConstantInt64Array(reader).Value.ReadOnlyCollectionToEnumArray(elementType);
case HandleType.ConstantUInt64Array:
return enumArray.Value.ToConstantUInt64ArrayHandle(reader).GetConstantUInt64Array(reader).Value.ReadOnlyCollectionToEnumArray(elementType);
default:
throw new BadImageFormatException();
}
}
public static Handle GetAttributeTypeHandle(this CustomAttribute customAttribute,
MetadataReader reader)
{
HandleType constructorHandleType = customAttribute.Constructor.HandleType;
if (constructorHandleType == HandleType.QualifiedMethod)
return customAttribute.Constructor.ToQualifiedMethodHandle(reader).GetQualifiedMethod(reader).EnclosingType;
else if (constructorHandleType == HandleType.MemberReference)
return customAttribute.Constructor.ToMemberReferenceHandle(reader).GetMemberReference(reader).Parent;
else
throw new BadImageFormatException();
}
//
// Lightweight check to see if a custom attribute's is of a well-known type.
//
// This check performs without instantating the Type object and bloating memory usage. On the flip side,
// it doesn't check on whether the type is defined in a paricular assembly. The desktop CLR typically doesn't
// check this either so this is useful from a compat persective as well.
//
public static bool IsCustomAttributeOfType(this CustomAttributeHandle customAttributeHandle,
MetadataReader reader,
String ns,
String name)
{
String[] namespaceParts = ns.Split('.');
Handle typeHandle = customAttributeHandle.GetCustomAttribute(reader).GetAttributeTypeHandle(reader);
HandleType handleType = typeHandle.HandleType;
if (handleType == HandleType.TypeDefinition)
{
TypeDefinition typeDefinition = typeHandle.ToTypeDefinitionHandle(reader).GetTypeDefinition(reader);
if (!typeDefinition.Name.StringEquals(name, reader))
return false;
NamespaceDefinitionHandle nsHandle = typeDefinition.NamespaceDefinition;
int idx = namespaceParts.Length;
while (idx-- != 0)
{
String namespacePart = namespaceParts[idx];
NamespaceDefinition namespaceDefinition = nsHandle.GetNamespaceDefinition(reader);
if (!namespaceDefinition.Name.StringOrNullEquals(namespacePart, reader))
return false;
if (!namespaceDefinition.ParentScopeOrNamespace.IsNamespaceDefinitionHandle(reader))
return false;
nsHandle = namespaceDefinition.ParentScopeOrNamespace.ToNamespaceDefinitionHandle(reader);
}
if (!nsHandle.GetNamespaceDefinition(reader).Name.StringOrNullEquals(null, reader))
return false;
return true;
}
else if (handleType == HandleType.TypeReference)
{
TypeReference typeReference = typeHandle.ToTypeReferenceHandle(reader).GetTypeReference(reader);
if (!typeReference.TypeName.StringEquals(name, reader))
return false;
if (!typeReference.ParentNamespaceOrType.IsNamespaceReferenceHandle(reader))
return false;
NamespaceReferenceHandle nsHandle = typeReference.ParentNamespaceOrType.ToNamespaceReferenceHandle(reader);
int idx = namespaceParts.Length;
while (idx-- != 0)
{
String namespacePart = namespaceParts[idx];
NamespaceReference namespaceReference = nsHandle.GetNamespaceReference(reader);
if (!namespaceReference.Name.StringOrNullEquals(namespacePart, reader))
return false;
if (!namespaceReference.ParentScopeOrNamespace.IsNamespaceReferenceHandle(reader))
return false;
nsHandle = namespaceReference.ParentScopeOrNamespace.ToNamespaceReferenceHandle(reader);
}
if (!nsHandle.GetNamespaceReference(reader).Name.StringOrNullEquals(null, reader))
return false;
return true;
}
else
throw new NotSupportedException();
}
public static String ToNamespaceName(this NamespaceDefinitionHandle namespaceDefinitionHandle, MetadataReader reader)
{
String ns = "";
for (;;)
{
NamespaceDefinition currentNamespaceDefinition = namespaceDefinitionHandle.GetNamespaceDefinition(reader);
String name = currentNamespaceDefinition.Name.GetStringOrNull(reader);
if (name != null)
{
if (ns.Length != 0)
ns = "." + ns;
ns = name + ns;
}
Handle nextHandle = currentNamespaceDefinition.ParentScopeOrNamespace;
HandleType handleType = nextHandle.HandleType;
if (handleType == HandleType.ScopeDefinition)
break;
if (handleType == HandleType.NamespaceDefinition)
{
namespaceDefinitionHandle = nextHandle.ToNamespaceDefinitionHandle(reader);
continue;
}
throw new BadImageFormatException(SR.Bif_InvalidMetadata);
}
return ns;
}
public static IEnumerable<NamespaceDefinitionHandle> GetTransitiveNamespaces(this MetadataReader reader, IEnumerable<NamespaceDefinitionHandle> namespaceHandles)
{
foreach (NamespaceDefinitionHandle namespaceHandle in namespaceHandles)
{
yield return namespaceHandle;
NamespaceDefinition namespaceDefinition = namespaceHandle.GetNamespaceDefinition(reader);
foreach (NamespaceDefinitionHandle childNamespaceHandle in GetTransitiveNamespaces(reader, namespaceDefinition.NamespaceDefinitions))
yield return childNamespaceHandle;
}
}
public static IEnumerable<TypeDefinitionHandle> GetTopLevelTypes(this MetadataReader reader, IEnumerable<NamespaceDefinitionHandle> namespaceHandles)
{
foreach (NamespaceDefinitionHandle namespaceHandle in namespaceHandles)
{
NamespaceDefinition namespaceDefinition = namespaceHandle.GetNamespaceDefinition(reader);
foreach (TypeDefinitionHandle typeDefinitionHandle in namespaceDefinition.TypeDefinitions)
{
yield return typeDefinitionHandle;
}
}
}
public static IEnumerable<TypeDefinitionHandle> GetTransitiveTypes(this MetadataReader reader, IEnumerable<TypeDefinitionHandle> typeDefinitionHandles, bool publicOnly)
{
foreach (TypeDefinitionHandle typeDefinitionHandle in typeDefinitionHandles)
{
TypeDefinition typeDefinition = typeDefinitionHandle.GetTypeDefinition(reader);
if (publicOnly)
{
TypeAttributes visibility = typeDefinition.Flags & TypeAttributes.VisibilityMask;
if (visibility != TypeAttributes.Public && visibility != TypeAttributes.NestedPublic)
continue;
}
yield return typeDefinitionHandle;
foreach (TypeDefinitionHandle nestedTypeDefinitionHandle in GetTransitiveTypes(reader, typeDefinition.NestedTypes, publicOnly))
yield return nestedTypeDefinitionHandle;
}
}
/// <summary>
/// Reverse len characters in a StringBuilder starting at offset index
/// </summary>
private static void ReverseStringInStringBuilder(StringBuilder builder, int index, int len)
{
int back = index + len - 1;
int front = index;
while (front < back)
{
char temp = builder[front];
builder[front] = builder[back];
builder[back] = temp;
front++;
back--;
}
}
public static string ToFullyQualifiedTypeName(this NamespaceReferenceHandle namespaceReferenceHandle, string typeName, MetadataReader reader)
{
StringBuilder fullName = new StringBuilder(64);
NamespaceReference namespaceReference;
for (;;)
{
namespaceReference = namespaceReferenceHandle.GetNamespaceReference(reader);
String namespacePart = namespaceReference.Name.GetStringOrNull(reader);
if (namespacePart == null)
break;
fullName.Append('.');
int index = fullName.Length;
fullName.Append(namespacePart);
ReverseStringInStringBuilder(fullName, index, namespacePart.Length);
namespaceReferenceHandle = namespaceReference.ParentScopeOrNamespace.ToExpectedNamespaceReferenceHandle(reader);
}
ReverseStringInStringBuilder(fullName, 0, fullName.Length);
fullName.Append(typeName);
return fullName.ToString();
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Activities.Presentation.FreeFormEditing
{
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using System.Activities.Presentation;
using System.Activities.Presentation.View;
using System.Activities.Presentation.Internal.PropertyEditing;
using System.Runtime;
using System.Linq;
using System.Activities.Presentation.Model;
internal class FreeFormPanel : Panel
{
public static readonly DependencyProperty ChildSizeProperty = DependencyProperty.RegisterAttached("ChildSize", typeof(Size), typeof(FreeFormPanel), new FrameworkPropertyMetadata());
public static readonly DependencyProperty LocationProperty = DependencyProperty.RegisterAttached("Location", typeof(Point), typeof(FreeFormPanel), new FrameworkPropertyMetadata(new Point(-1, -1)));
public static readonly DependencyProperty RequiredWidthProperty = DependencyProperty.Register("RequiredWidth", typeof(Double), typeof(FreeFormPanel), new FrameworkPropertyMetadata(double.NaN));
public static readonly DependencyProperty RequiredHeightProperty = DependencyProperty.Register("RequiredHeight", typeof(Double), typeof(FreeFormPanel), new FrameworkPropertyMetadata(double.NaN));
public static readonly DependencyProperty DestinationConnectionPointProperty = DependencyProperty.RegisterAttached("DestinationConnectionPoint", typeof(ConnectionPoint), typeof(FreeFormPanel), new FrameworkPropertyMetadata());
public static readonly DependencyProperty SourceConnectionPointProperty = DependencyProperty.RegisterAttached("SourceConnectionPoint", typeof(ConnectionPoint), typeof(FreeFormPanel), new FrameworkPropertyMetadata());
public static readonly DependencyProperty DisabledProperty = DependencyProperty.Register("Disabled", typeof(bool), typeof(FreeFormPanel), new UIPropertyMetadata(false));
public static readonly DependencyProperty AutoConnectContainerProperty = DependencyProperty.Register("AutoConnectContainer", typeof(IAutoConnectContainer), typeof(FreeFormPanel), new UIPropertyMetadata(null));
public const double ConnectorEditorOpacity = 1.0;
public const double ConnectorEditorThickness = 1.5;
public const double LeftStackingMargin = 50;
public const double TopStackingMargin = 80;
public const double VerticalStackingDistance = 50;
public const double GridSize = 10;
public ConnectorEditor connectorEditor;
double lastYPosition;
bool measureConnectors = false;
bool measureConnectorsPosted = false;
AutoConnectHelper autoConnectHelper = null;
DesignerConfigurationService designerConfigurationService = null;
public FreeFormPanel()
{
connectorEditor = null;
this.autoConnectHelper = new AutoConnectHelper(this);
lastYPosition = FreeFormPanel.TopStackingMargin;
this.Unloaded += (sender, e) =>
{
this.RemoveConnectorEditor();
};
}
public event LocationChangedEventHandler LocationChanged;
public event ConnectorMovedEventHandler ConnectorMoved;
public event RequiredSizeChangedEventHandler RequiredSizeChanged;
public static Size GetChildSize(DependencyObject obj)
{
return (Size)obj.GetValue(FreeFormPanel.ChildSizeProperty);
}
public static void SetChildSize(DependencyObject obj, Size size)
{
obj.SetValue(FreeFormPanel.ChildSizeProperty, size);
}
public double RequiredHeight
{
get { return (double)GetValue(FreeFormPanel.RequiredHeightProperty); }
private set { SetValue(FreeFormPanel.RequiredHeightProperty, value); }
}
public double RequiredWidth
{
get { return (double)GetValue(FreeFormPanel.RequiredWidthProperty); }
private set { SetValue(FreeFormPanel.RequiredWidthProperty, value); }
}
public bool Disabled
{
get { return (bool)GetValue(DisabledProperty); }
set { SetValue(DisabledProperty, value); }
}
public IAutoConnectContainer AutoConnectContainer
{
get { return (IAutoConnectContainer)GetValue(AutoConnectContainerProperty); }
set { SetValue(AutoConnectContainerProperty, value); }
}
public static Vector CalculateMovement(Key key, bool isRightToLeft)
{
Vector moveDir;
switch (key)
{
case Key.Down:
moveDir = new Vector(0, FreeFormPanel.GridSize);
break;
case Key.Up:
moveDir = new Vector(0, -FreeFormPanel.GridSize);
break;
case Key.Right:
moveDir = new Vector(FreeFormPanel.GridSize, 0);
break;
case Key.Left:
moveDir = new Vector(-FreeFormPanel.GridSize, 0);
break;
default:
Fx.Assert(false, "Invalid case");
moveDir = new Vector(0, 0);
break;
}
if (isRightToLeft)
{
moveDir.X = -moveDir.X;
}
return moveDir;
}
public static double ZeroIfNegative(double val)
{
return val.IsNoGreaterThan(0) ? 0 : val;
}
internal UIElement CurrentAutoConnectTarget
{
get
{
return this.autoConnectHelper.CurrentTarget;
}
}
internal Connector CurrentAutoSplitTarget
{
get;
set;
}
bool AutoConnectEnabled
{
get
{
if (this.designerConfigurationService == null)
{
DesignerView view = VisualTreeUtils.FindVisualAncestor<DesignerView>(this);
if (view != null)
{
this.designerConfigurationService = view.Context.Services.GetService<DesignerConfigurationService>();
return this.designerConfigurationService.AutoConnectEnabled;
}
else
{
return false;
}
}
else
{
return this.designerConfigurationService.AutoConnectEnabled;
}
}
}
public static ConnectionPoint GetDestinationConnectionPoint(DependencyObject obj)
{
return (ConnectionPoint)obj.GetValue(FreeFormPanel.DestinationConnectionPointProperty);
}
public static void SetDestinationConnectionPoint(DependencyObject obj, ConnectionPoint connectionPoint)
{
obj.SetValue(FreeFormPanel.DestinationConnectionPointProperty, connectionPoint);
}
public static ConnectionPoint GetSourceConnectionPoint(DependencyObject obj)
{
return (ConnectionPoint)obj.GetValue(FreeFormPanel.SourceConnectionPointProperty);
}
public static void SetSourceConnectionPoint(DependencyObject obj, ConnectionPoint connectionPoint)
{
obj.SetValue(FreeFormPanel.SourceConnectionPointProperty, connectionPoint);
}
public static Point GetLocation(DependencyObject obj)
{
return (Point)obj.GetValue(FreeFormPanel.LocationProperty);
}
public static void SetLocation(DependencyObject obj, Point point)
{
obj.SetValue(FreeFormPanel.LocationProperty, point);
}
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
this.SnapsToDevicePixels = true;
this.AllowDrop = true;
}
internal void RemoveAutoConnectAdorner()
{
this.autoConnectHelper.RemoveDropTargets();
}
internal List<DependencyObject> GetChildShapes(DependencyObject excluded)
{
List<DependencyObject> children = new List<DependencyObject>();
foreach (UIElement element in this.Children)
{
if (element is Connector)
{
continue;
}
if (object.Equals(element, excluded))
{
continue;
}
else if (element is VirtualizedContainerService.VirtualizingContainer)
{
if (object.Equals(excluded, ((VirtualizedContainerService.VirtualizingContainer)element).Child))
{
continue;
}
}
children.Add(element);
}
return children;
}
protected override void OnPreviewDragOver(DragEventArgs e)
{
if (this.IsOutmostPanel())
{
if (this.AutoConnectEnabled && DragDropHelper.GetDraggedObjectCount(e) == 1)
{
this.autoConnectHelper.OnPreviewDragOverPanel(e);
}
}
base.OnPreviewDragOver(e);
}
public void UpdateConnectorPoints(Connector connector, List<Point> points)
{
PointCollection pointCollection = new PointCollection();
foreach (Point point in points)
{
pointCollection.Add(new Point(point.X < 0 ? 0 : point.X, point.Y < 0 ? 0 : point.Y));
}
connector.Points = pointCollection;
OnLocationChanged(connector, null);
}
static public List<Point> GetEdgeRelativeToOutmostPanel(ConnectionPoint connectionPoint)
{
return connectionPoint.Edge;
}
static public Point GetLocationRelativeToOutmostPanel(ConnectionPoint connectionPoint)
{
return connectionPoint.Location;
}
public Point GetLocationRelativeToOutmostPanel(Point location)
{
return this.TranslatePoint(location, this.GetOutmostPanel());
}
FreeFormPanel GetOutmostPanel()
{
DependencyObject obj = this;
do
{
obj = VisualTreeHelper.GetParent(obj);
}
while (obj != null && !typeof(INestedFreeFormPanelContainer).IsAssignableFrom(obj.GetType()));
if (obj != null)
{
INestedFreeFormPanelContainer container = (INestedFreeFormPanelContainer)obj;
if (container.GetChildFreeFormPanel() == this)
{
return container.GetOutmostFreeFormPanel();
}
}
return this;
}
internal bool IsOutmostPanel()
{
return this == this.GetOutmostPanel();
}
internal static ConnectionPoint ConnectionPointHitTest(Point hitPoint, ConnectionPointsAdorner adorner)
{
FreeFormPanel panel = VisualTreeUtils.FindVisualAncestor<FreeFormPanel>(adorner.AdornedElement);
return ConnectionPointHitTest(hitPoint, adorner.ConnectionPoints, panel);
}
internal static ConnectionPoint ConnectionPointHitTest(Point hitPoint, List<ConnectionPoint> connectionPoints, FreeFormPanel panel)
{
ConnectionPoint hitConnectionPoint = null;
FreeFormPanel outmost = panel.GetOutmostPanel();
foreach (ConnectionPoint connPoint in connectionPoints)
{
if (connPoint != null && connPoint.IsEnabled)
{
if (new Rect(panel.TranslatePoint(connPoint.Location, outmost) + connPoint.HitTestOffset, connPoint.HitTestSize).Contains(hitPoint))
{
hitConnectionPoint = connPoint;
break;
}
}
}
return hitConnectionPoint;
}
protected override Size ArrangeOverride(Size finalSize)
{
double height = 0;
double width = 0;
for (int i = 0; i < Children.Count; i++)
{
Point pt = new Point(0, 0);
Size size = Children[i].DesiredSize;
if (Children[i].GetType() == typeof(Connector))
{
((UIElement)Children[i]).Arrange(new Rect(pt, size));
}
else
{
pt = FreeFormPanel.GetLocation(Children[i]);
((UIElement)Children[i]).Arrange(new Rect(pt, size));
}
if (width < (size.Width + pt.X))
{
width = size.Width + pt.X;
}
if (height < (size.Height + pt.Y))
{
height = size.Height + pt.Y;
}
}
width = (width < this.MinWidth) ? this.MinWidth : width;
width = (width < this.Width) ? (this.Width < Double.MaxValue ? this.Width : width) : width;
height = (height < this.MinHeight) ? this.MinHeight : height;
height = (height < this.Height) ? (this.Height < Double.MaxValue ? this.Height : height) : height;
return new Size(width, height);
}
protected override Size MeasureOverride(Size availableSize)
{
bool isOutmostPanel = this.IsOutmostPanel();
base.MeasureOverride(availableSize);
double height;
double width;
this.MeasureChildren(out height, out width);
if (this.RequiredSizeChanged != null)
{
this.RequiredSizeChanged(this, new RequiredSizeChangedEventArgs(new Size(width, height)));
}
this.RequiredWidth = width;
this.RequiredHeight = height;
if (isOutmostPanel)
{
Action MeasureConnectors = () =>
{
//This action will execute at Input priority.
//Enabling measuring on Connectors and forcing a MeasureOverride by calling InvalidateMeasure.
this.measureConnectors = true;
this.InvalidateMeasure();
};
if (!measureConnectorsPosted)
{
this.Dispatcher.BeginInvoke(DispatcherPriority.Input, MeasureConnectors);
measureConnectorsPosted = true;
}
if (measureConnectors)
{
measureConnectors = false;
measureConnectorsPosted = false;
}
}
width = (width < this.Width) ? (this.Width < Double.MaxValue ? this.Width : width) : width;
height = (height < this.Height) ? (this.Height < Double.MaxValue ? this.Height : height) : height;
return new Size(width, height);
}
private void MeasureChildren(out double height, out double width)
{
height = 0;
width = 0;
Point pt = new Point(0, 0);
bool isOutmostPanel = this.IsOutmostPanel();
foreach (UIElement child in Children)
{
Connector connectorChild = child as Connector;
if (connectorChild != null && isOutmostPanel)
{
pt = new Point(0, 0);
if (measureConnectors)
{
Point srcPoint = FreeFormPanel.GetLocationRelativeToOutmostPanel(FreeFormPanel.GetSourceConnectionPoint(connectorChild));
Point destPoint = FreeFormPanel.GetLocationRelativeToOutmostPanel(FreeFormPanel.GetDestinationConnectionPoint(connectorChild));
if (connectorChild.Points.Count == 0 || !this.Disabled &&
((DesignerGeometryHelper.ManhattanDistanceBetweenPoints(connectorChild.Points[0], srcPoint) > ConnectorRouter.EndPointTolerance)
|| (DesignerGeometryHelper.ManhattanDistanceBetweenPoints(connectorChild.Points[connectorChild.Points.Count - 1], destPoint) > ConnectorRouter.EndPointTolerance)))
{
connectorChild.Points = new PointCollection();
RoutePolyLine(connectorChild);
}
connectorChild.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
}
else
{
continue;
}
}
else //Measure non-connector elements.
{
child.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
if (!child.DesiredSize.Equals(((Size)FreeFormPanel.GetChildSize(child))))
{
FreeFormPanel.SetChildSize(child, child.DesiredSize);
}
pt = FreeFormPanel.GetLocation(child);
if (!IsLocationValid(pt))
{
pt = new Point(LeftStackingMargin, lastYPosition);
OnLocationChanged(child, new LocationChangedEventArgs(pt));
FreeFormPanel.SetLocation(child, pt);
lastYPosition += child.DesiredSize.Height + VerticalStackingDistance;
}
}
if (height < child.DesiredSize.Height + pt.Y)
{
height = child.DesiredSize.Height + pt.Y;
}
if (width < child.DesiredSize.Width + pt.X)
{
width = child.DesiredSize.Width + pt.X;
}
}
width = (width < this.MinWidth) ? this.MinWidth : width;
height = (height < this.MinHeight) ? this.MinHeight : height;
}
static bool IsLocationValid(Point location)
{
return location.X >= 0 && location.Y >= 0;
}
void OnLocationChanged(Object sender, LocationChangedEventArgs e)
{
if (LocationChanged != null)
{
LocationChanged(sender, e);
}
}
protected override void OnMouseLeave(MouseEventArgs e)
{
if (e != null && !this.Disabled && this.IsOutmostPanel())
{
if (connectorEditor != null && connectorEditor.BeingEdited
&& Mouse.DirectlyOver != null
&& !(Mouse.DirectlyOver is ConnectionPointsAdorner))
{
SaveConnectorEditor(e.GetPosition(this));
}
}
base.OnMouseLeave(e);
}
protected override void OnMouseMove(System.Windows.Input.MouseEventArgs e)
{
if (e != null && !this.Disabled && this.IsOutmostPanel())
{
if (this.AutoConnectEnabled)
{
this.RemoveAutoConnectAdorner();
}
if (e.LeftButton == MouseButtonState.Pressed)
{
if (connectorEditor != null && connectorEditor.BeingEdited)
{
AutoScrollHelper.AutoScroll(e, this, 1);
connectorEditor.Update(e.GetPosition(this));
e.Handled = true;
}
}
}
base.OnMouseMove(e);
}
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
{
if (e != null && !this.Disabled && this.IsOutmostPanel())
{
if (connectorEditor != null && connectorEditor.BeingEdited)
{
SaveConnectorEditor(e.GetPosition(this));
}
}
base.OnMouseLeftButtonUp(e);
}
public void RemoveConnectorEditor()
{
if (connectorEditor != null)
{
connectorEditor.Remove();
connectorEditor = null;
}
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e != null && !this.Disabled && this.IsOutmostPanel())
{
if (connectorEditor != null && connectorEditor.BeingEdited)
{
if (e.Key == Key.Escape)
{
//If escape key is hit while dragging a connector, end dragging.
Connector affectedConnector = connectorEditor.Connector;
RemoveConnectorEditor();
this.connectorEditor = new ConnectorEditor(this, affectedConnector);
}
// Ignore all other Keyboard input when rerouting connector
e.Handled = true;
}
}
base.OnKeyDown(e);
}
static bool ShouldCreateNewConnectorEditor(MouseButtonEventArgs e)
{
Connector connector = e.Source as Connector;
// Don't create new connector editor when clicking on the start dot.
if (connector == null || (connector.StartDot != null && connector.StartDot.IsAncestorOf(e.MouseDevice.DirectlyOver as DependencyObject)))
{
return false;
}
return true;
}
protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
{
if (e != null && !this.Disabled && this.IsOutmostPanel() && e.ClickCount == 1)
{
//If one of the edit points is clicked, update the connector editor.
if ((connectorEditor != null) && connectorEditor.EditPointsHitTest(e.GetPosition(this)))
{
connectorEditor.Update(e.GetPosition(this));
e.Handled = true;
}
else if (ShouldCreateNewConnectorEditor(e))
{
CreateNewConnectorEditor(e);
}
}
base.OnPreviewMouseLeftButtonDown(e);
}
void CreateNewConnectorEditor(MouseButtonEventArgs e)
{
if (connectorEditor == null || !e.Source.Equals(connectorEditor.Connector))
{
//If user clicks anywhere other than the connector editor, destroy it.
RemoveConnectorEditor();
if (typeof(Connector).IsAssignableFrom(e.Source.GetType()))
{
this.connectorEditor = new ConnectorEditor(this, e.Source as Connector);
}
}
}
//Calls the Line routing algorithm and populates the points collection of the connector.
void RoutePolyLine(Connector connector)
{
Point[] pts = ConnectorRouter.Route(this, FreeFormPanel.GetSourceConnectionPoint(connector), FreeFormPanel.GetDestinationConnectionPoint(connector));
List<Point> points = new List<Point>(pts);
if (pts != null)
{
UpdateConnectorPoints(connector, points);
}
}
//Connector editing is complete, save the final connectorEditor state into the connector.
void SaveConnectorEditor(Point pt)
{
bool isConnectionEndPointMoved = !connectorEditor.Persist(pt);
if (this.ConnectorMoved != null)
{
Connector connector = this.connectorEditor.Connector;
List<Point> points = this.connectorEditor.ConnectorEditorLocation;
ConnectorMoved(connector, new ConnectorMovedEventArgs(points));
}
if (isConnectionEndPointMoved)
{
//Persist will return false, when the ConnectionEndPoint has been moved.
RemoveConnectorEditor();
}
else
{
this.InvalidateMeasure();
}
}
}
}
| |
// 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 Xunit;
namespace System.PrivateUri.Tests
{
public static class UriTests
{
public static IEnumerable<object[]> Uri_TestData
{
get
{
if (PlatformDetection.IsWindows)
{
yield return new object[] { @"file:///path1\path2/path3\path4", @"/path1/path2/path3/path4", @"/path1/path2/path3/path4", @"file:///path1/path2/path3/path4", "" };
yield return new object[] { @"file:///path1%5Cpath2\path3", @"/path1/path2/path3", @"/path1/path2/path3", @"file:///path1/path2/path3", ""};
yield return new object[] { @"file://localhost/path1\path2/path3\path4\", @"/path1/path2/path3/path4/", @"\\localhost\path1\path2\path3\path4\", @"file://localhost/path1/path2/path3/path4/", "localhost"};
yield return new object[] { @"file://randomhost/path1%5Cpath2\path3", @"/path1/path2/path3", @"\\randomhost\path1\path2\path3", @"file://randomhost/path1/path2/path3", "randomhost"};
}
else
{
yield return new object[] { @"file:///path1\path2/path3\path4", @"/path1\path2/path3\path4", @"/path1\path2/path3\path4", @"file:///path1\path2/path3\path4", "" };
yield return new object[] { @"file:///path1%5Cpath2\path3", @"/path1%5Cpath2%5Cpath3", @"/path1\path2\path3", @"file:///path1%5Cpath2%5Cpath3", ""};
yield return new object[] { @"file://localhost/path1\path2/path3\path4\", @"/path1\path2/path3\path4\", @"\\localhost\path1\path2\path3\path4\", @"file://localhost/path1\path2/path3\path4\", "localhost"};
yield return new object[] { @"file://randomhost/path1%5Cpath2\path3", @"/path1%5Cpath2%5Cpath3", @"\\randomhost\path1\path2\path3", @"file://randomhost/path1%5Cpath2%5Cpath3", "randomhost"};
}
}
}
[Theory]
[MemberData(nameof(Uri_TestData))]
public static void TestCtor_BackwardSlashInPath(string uri, string expectedAbsolutePath, string expectedLocalPath, string expectedAbsoluteUri, string expectedHost)
{
Uri actualUri = new Uri(uri);
Assert.Equal(expectedAbsolutePath, actualUri.AbsolutePath);
Assert.Equal(expectedLocalPath, actualUri.LocalPath);
Assert.Equal(expectedAbsoluteUri, actualUri.AbsoluteUri);
Assert.Equal(expectedHost, actualUri.Host);
}
[Fact]
public static void TestCtor_String()
{
Uri uri = new Uri(@"http://foo/bar/baz#frag");
int i;
String s;
bool b;
UriHostNameType uriHostNameType;
String[] ss;
s = uri.ToString();
Assert.Equal(s, @"http://foo/bar/baz#frag");
s = uri.AbsolutePath;
Assert.Equal<String>(s, @"/bar/baz");
s = uri.AbsoluteUri;
Assert.Equal<String>(s, @"http://foo/bar/baz#frag");
s = uri.Authority;
Assert.Equal<String>(s, @"foo");
s = uri.DnsSafeHost;
Assert.Equal<String>(s, @"foo");
s = uri.Fragment;
Assert.Equal<String>(s, @"#frag");
s = uri.Host;
Assert.Equal<String>(s, @"foo");
uriHostNameType = uri.HostNameType;
Assert.Equal<UriHostNameType>(uriHostNameType, UriHostNameType.Dns);
b = uri.IsAbsoluteUri;
Assert.True(b);
b = uri.IsDefaultPort;
Assert.True(b);
b = uri.IsFile;
Assert.False(b);
b = uri.IsLoopback;
Assert.False(b);
b = uri.IsUnc;
Assert.False(b);
s = uri.LocalPath;
Assert.Equal<String>(s, @"/bar/baz");
s = uri.OriginalString;
Assert.Equal<String>(s, @"http://foo/bar/baz#frag");
s = uri.PathAndQuery;
Assert.Equal<String>(s, @"/bar/baz");
i = uri.Port;
Assert.Equal<int>(i, 80);
s = uri.Query;
Assert.Equal<String>(s, @"");
s = uri.Scheme;
Assert.Equal<String>(s, @"http");
ss = uri.Segments;
Assert.Equal<int>(ss.Length, 3);
Assert.Equal<String>(ss[0], @"/");
Assert.Equal<String>(ss[1], @"bar/");
Assert.Equal<String>(ss[2], @"baz");
b = uri.UserEscaped;
Assert.False(b);
s = uri.UserInfo;
Assert.Equal<String>(s, @"");
}
[Fact]
public static void TestCtor_Uri_String()
{
Uri uri;
uri = new Uri(@"http://www.contoso.com/");
uri = new Uri(uri, "catalog/shownew.htm?date=today");
int i;
String s;
bool b;
UriHostNameType uriHostNameType;
String[] ss;
s = uri.ToString();
Assert.Equal(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.AbsolutePath;
Assert.Equal<String>(s, @"/catalog/shownew.htm");
s = uri.AbsoluteUri;
Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.Authority;
Assert.Equal<String>(s, @"www.contoso.com");
s = uri.DnsSafeHost;
Assert.Equal<String>(s, @"www.contoso.com");
s = uri.Fragment;
Assert.Equal<String>(s, @"");
s = uri.Host;
Assert.Equal<String>(s, @"www.contoso.com");
uriHostNameType = uri.HostNameType;
Assert.Equal<UriHostNameType>(uriHostNameType, UriHostNameType.Dns);
b = uri.IsAbsoluteUri;
Assert.True(b);
b = uri.IsDefaultPort;
Assert.True(b);
b = uri.IsFile;
Assert.False(b);
b = uri.IsLoopback;
Assert.False(b);
b = uri.IsUnc;
Assert.False(b);
s = uri.LocalPath;
Assert.Equal<String>(s, @"/catalog/shownew.htm");
s = uri.OriginalString;
Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.PathAndQuery;
Assert.Equal<String>(s, @"/catalog/shownew.htm?date=today");
i = uri.Port;
Assert.Equal<int>(i, 80);
s = uri.Query;
Assert.Equal<String>(s, @"?date=today");
s = uri.Scheme;
Assert.Equal<String>(s, @"http");
ss = uri.Segments;
Assert.Equal<int>(ss.Length, 3);
Assert.Equal<String>(ss[0], @"/");
Assert.Equal<String>(ss[1], @"catalog/");
Assert.Equal<String>(ss[2], @"shownew.htm");
b = uri.UserEscaped;
Assert.False(b);
s = uri.UserInfo;
Assert.Equal<String>(s, @"");
}
[Fact]
public static void TestCtor_String_UriKind()
{
Uri uri = new Uri("catalog/shownew.htm?date=today", UriKind.Relative);
String s;
bool b;
s = uri.ToString();
Assert.Equal(s, @"catalog/shownew.htm?date=today");
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.AbsolutePath; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.AbsoluteUri; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Authority; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.DnsSafeHost; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Fragment; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Host; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.HostNameType; });
Assert.False(uri.IsAbsoluteUri);
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.IsDefaultPort; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.IsFile; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.IsLoopback; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.IsUnc; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.LocalPath; });
s = uri.OriginalString;
Assert.Equal<String>(s, @"catalog/shownew.htm?date=today");
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.PathAndQuery; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Port; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Query; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Scheme; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Segments; });
b = uri.UserEscaped;
Assert.False(b);
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.UserInfo; });
}
[Fact]
public static void TestCtor_Uri_Uri()
{
Uri absoluteUri = new Uri("http://www.contoso.com/");
// Create a relative Uri from a string. allowRelative = true to allow for
// creating a relative Uri.
Uri relativeUri = new Uri("/catalog/shownew.htm?date=today", UriKind.Relative);
// Create a new Uri from an absolute Uri and a relative Uri.
Uri uri = new Uri(absoluteUri, relativeUri);
int i;
String s;
bool b;
UriHostNameType uriHostNameType;
String[] ss;
s = uri.ToString();
Assert.Equal(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.AbsolutePath;
Assert.Equal<String>(s, @"/catalog/shownew.htm");
s = uri.AbsoluteUri;
Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.Authority;
Assert.Equal<String>(s, @"www.contoso.com");
s = uri.DnsSafeHost;
Assert.Equal<String>(s, @"www.contoso.com");
s = uri.Fragment;
Assert.Equal<String>(s, @"");
s = uri.Host;
Assert.Equal<String>(s, @"www.contoso.com");
uriHostNameType = uri.HostNameType;
Assert.Equal<UriHostNameType>(uriHostNameType, UriHostNameType.Dns);
b = uri.IsAbsoluteUri;
Assert.True(b);
b = uri.IsDefaultPort;
Assert.True(b);
b = uri.IsFile;
Assert.False(b);
b = uri.IsLoopback;
Assert.False(b);
b = uri.IsUnc;
Assert.False(b);
s = uri.LocalPath;
Assert.Equal<String>(s, @"/catalog/shownew.htm");
s = uri.OriginalString;
Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.PathAndQuery;
Assert.Equal<String>(s, @"/catalog/shownew.htm?date=today");
i = uri.Port;
Assert.Equal<int>(i, 80);
s = uri.Query;
Assert.Equal<String>(s, @"?date=today");
s = uri.Scheme;
Assert.Equal<String>(s, @"http");
ss = uri.Segments;
Assert.Equal<int>(ss.Length, 3);
Assert.Equal<String>(ss[0], @"/");
Assert.Equal<String>(ss[1], @"catalog/");
Assert.Equal<String>(ss[2], @"shownew.htm");
b = uri.UserEscaped;
Assert.False(b);
s = uri.UserInfo;
Assert.Equal<String>(s, @"");
}
[Fact]
public static void TestTryCreate_String_UriKind()
{
Uri uri;
bool b = Uri.TryCreate("http://www.contoso.com/catalog/shownew.htm?date=today", UriKind.Absolute, out uri);
Assert.True(b);
int i;
String s;
UriHostNameType uriHostNameType;
String[] ss;
s = uri.ToString();
Assert.Equal(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.AbsolutePath;
Assert.Equal<String>(s, @"/catalog/shownew.htm");
s = uri.AbsoluteUri;
Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.Authority;
Assert.Equal<String>(s, @"www.contoso.com");
s = uri.DnsSafeHost;
Assert.Equal<String>(s, @"www.contoso.com");
s = uri.Fragment;
Assert.Equal<String>(s, @"");
s = uri.Host;
Assert.Equal<String>(s, @"www.contoso.com");
uriHostNameType = uri.HostNameType;
Assert.Equal<UriHostNameType>(uriHostNameType, UriHostNameType.Dns);
b = uri.IsAbsoluteUri;
Assert.True(b);
b = uri.IsDefaultPort;
Assert.True(b);
b = uri.IsFile;
Assert.False(b);
b = uri.IsLoopback;
Assert.False(b);
b = uri.IsUnc;
Assert.False(b);
s = uri.LocalPath;
Assert.Equal<String>(s, @"/catalog/shownew.htm");
s = uri.OriginalString;
Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.PathAndQuery;
Assert.Equal<String>(s, @"/catalog/shownew.htm?date=today");
i = uri.Port;
Assert.Equal<int>(i, 80);
s = uri.Query;
Assert.Equal<String>(s, @"?date=today");
s = uri.Scheme;
Assert.Equal<String>(s, @"http");
ss = uri.Segments;
Assert.Equal<int>(ss.Length, 3);
Assert.Equal<String>(ss[0], @"/");
Assert.Equal<String>(ss[1], @"catalog/");
Assert.Equal<String>(ss[2], @"shownew.htm");
b = uri.UserEscaped;
Assert.False(b);
s = uri.UserInfo;
Assert.Equal<String>(s, @"");
}
[Fact]
public static void TestTryCreate_Uri_String()
{
Uri uri;
Uri baseUri = new Uri("http://www.contoso.com/", UriKind.Absolute);
bool b = Uri.TryCreate(baseUri, "catalog/shownew.htm?date=today", out uri);
Assert.True(b);
int i;
String s;
UriHostNameType uriHostNameType;
String[] ss;
s = uri.ToString();
Assert.Equal(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.AbsolutePath;
Assert.Equal<String>(s, @"/catalog/shownew.htm");
s = uri.AbsoluteUri;
Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.Authority;
Assert.Equal<String>(s, @"www.contoso.com");
s = uri.DnsSafeHost;
Assert.Equal<String>(s, @"www.contoso.com");
s = uri.Fragment;
Assert.Equal<String>(s, @"");
s = uri.Host;
Assert.Equal<String>(s, @"www.contoso.com");
uriHostNameType = uri.HostNameType;
Assert.Equal<UriHostNameType>(uriHostNameType, UriHostNameType.Dns);
b = uri.IsAbsoluteUri;
Assert.True(b);
b = uri.IsDefaultPort;
Assert.True(b);
b = uri.IsFile;
Assert.False(b);
b = uri.IsLoopback;
Assert.False(b);
b = uri.IsUnc;
Assert.False(b);
s = uri.LocalPath;
Assert.Equal<String>(s, @"/catalog/shownew.htm");
s = uri.OriginalString;
Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.PathAndQuery;
Assert.Equal<String>(s, @"/catalog/shownew.htm?date=today");
i = uri.Port;
Assert.Equal<int>(i, 80);
s = uri.Query;
Assert.Equal<String>(s, @"?date=today");
s = uri.Scheme;
Assert.Equal<String>(s, @"http");
ss = uri.Segments;
Assert.Equal<int>(ss.Length, 3);
Assert.Equal<String>(ss[0], @"/");
Assert.Equal<String>(ss[1], @"catalog/");
Assert.Equal<String>(ss[2], @"shownew.htm");
b = uri.UserEscaped;
Assert.False(b);
s = uri.UserInfo;
Assert.Equal<String>(s, @"");
}
[Fact]
public static void TestTryCreate_Uri_Uri()
{
Uri uri;
Uri baseUri = new Uri("http://www.contoso.com/", UriKind.Absolute);
Uri relativeUri = new Uri("catalog/shownew.htm?date=today", UriKind.Relative);
bool b = Uri.TryCreate(baseUri, relativeUri, out uri);
Assert.True(b);
int i;
String s;
UriHostNameType uriHostNameType;
String[] ss;
s = uri.ToString();
Assert.Equal(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.AbsolutePath;
Assert.Equal<String>(s, @"/catalog/shownew.htm");
s = uri.AbsoluteUri;
Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.Authority;
Assert.Equal<String>(s, @"www.contoso.com");
s = uri.DnsSafeHost;
Assert.Equal<String>(s, @"www.contoso.com");
s = uri.Fragment;
Assert.Equal<String>(s, @"");
s = uri.Host;
Assert.Equal<String>(s, @"www.contoso.com");
uriHostNameType = uri.HostNameType;
Assert.Equal<UriHostNameType>(uriHostNameType, UriHostNameType.Dns);
b = uri.IsAbsoluteUri;
Assert.True(b);
b = uri.IsDefaultPort;
Assert.True(b);
b = uri.IsFile;
Assert.False(b);
b = uri.IsLoopback;
Assert.False(b);
b = uri.IsUnc;
Assert.False(b);
s = uri.LocalPath;
Assert.Equal<String>(s, @"/catalog/shownew.htm");
s = uri.OriginalString;
Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.PathAndQuery;
Assert.Equal<String>(s, @"/catalog/shownew.htm?date=today");
i = uri.Port;
Assert.Equal<int>(i, 80);
s = uri.Query;
Assert.Equal<String>(s, @"?date=today");
s = uri.Scheme;
Assert.Equal<String>(s, @"http");
ss = uri.Segments;
Assert.Equal<int>(ss.Length, 3);
Assert.Equal<String>(ss[0], @"/");
Assert.Equal<String>(ss[1], @"catalog/");
Assert.Equal<String>(ss[2], @"shownew.htm");
b = uri.UserEscaped;
Assert.False(b);
s = uri.UserInfo;
Assert.Equal<String>(s, @"");
}
[Fact]
public static void TestMakeRelative()
{
// Create a base Uri.
Uri address1 = new Uri("http://www.contoso.com/");
// Create a new Uri from a string.
Uri address2 = new Uri("http://www.contoso.com/index.htm?date=today");
// Determine the relative Uri.
Uri uri = address1.MakeRelativeUri(address2);
String s;
bool b;
s = uri.ToString();
Assert.Equal(s, @"index.htm?date=today");
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.AbsolutePath; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.AbsoluteUri; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Authority; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.DnsSafeHost; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Fragment; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Host; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.HostNameType; });
b = uri.IsAbsoluteUri;
Assert.False(b);
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.IsDefaultPort; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.IsFile; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.IsLoopback; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.IsUnc; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.LocalPath; });
s = uri.OriginalString;
Assert.Equal<String>(s, @"index.htm?date=today");
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.PathAndQuery; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Port; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Query; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Scheme; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Segments; });
b = uri.UserEscaped;
Assert.False(b);
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.UserInfo; });
}
[Fact]
public static void TestCheckHostName()
{
UriHostNameType u;
u = Uri.CheckHostName("www.contoso.com");
Assert.Equal(u, UriHostNameType.Dns);
u = Uri.CheckHostName("1.2.3.4");
Assert.Equal(u, UriHostNameType.IPv4);
u = Uri.CheckHostName(null);
Assert.Equal(u, UriHostNameType.Unknown);
u = Uri.CheckHostName("!@*(@#&*#$&*#");
Assert.Equal(u, UriHostNameType.Unknown);
}
[Fact]
public static void TestCheckSchemeName()
{
bool b;
b = Uri.CheckSchemeName("http");
Assert.True(b);
b = Uri.CheckSchemeName(null);
Assert.False(b);
b = Uri.CheckSchemeName("!");
Assert.False(b);
}
[Fact]
public static void TestIsBaseOf()
{
bool b;
Uri uri, uri2;
uri = new Uri("http://host/path/path/file?query");
uri2 = new Uri(@"http://host/path/path/file/");
b = uri.IsBaseOf(uri2);
Assert.True(b);
uri2 = new Uri(@"http://host/path/path/#fragment");
b = uri.IsBaseOf(uri2);
Assert.True(b);
uri2 = new Uri("http://host/path/path/MoreDir/\"");
b = uri.IsBaseOf(uri2);
Assert.True(b);
uri2 = new Uri(@"http://host/path/path/OtherFile?Query");
b = uri.IsBaseOf(uri2);
Assert.True(b);
uri2 = new Uri(@"http://host/path/path/");
b = uri.IsBaseOf(uri2);
Assert.True(b);
uri2 = new Uri(@"http://host/path/path/file");
b = uri.IsBaseOf(uri2);
Assert.True(b);
uri2 = new Uri(@"http://host/path/path");
b = uri.IsBaseOf(uri2);
Assert.False(b);
uri2 = new Uri(@"http://host/path/path?query");
b = uri.IsBaseOf(uri2);
Assert.False(b);
uri2 = new Uri(@"http://host/path/path#Fragment");
b = uri.IsBaseOf(uri2);
Assert.False(b);
uri2 = new Uri(@"http://host/path/path2/");
b = uri.IsBaseOf(uri2);
Assert.False(b);
uri2 = new Uri(@"http://host/path/path2/MoreDir");
b = uri.IsBaseOf(uri2);
Assert.False(b);
uri2 = new Uri(@"http://host/path/File");
b = uri.IsBaseOf(uri2);
Assert.False(b);
}
[Fact]
public static void TestIsWellFormedOriginalString()
{
Uri uri;
bool b;
uri = new Uri("http://www.contoso.com/path?name");
b = uri.IsWellFormedOriginalString();
Assert.True(b);
uri = new Uri("http://www.contoso.com/path???/file name");
b = uri.IsWellFormedOriginalString();
Assert.False(b);
uri = new Uri(@"c:\\directory\filename");
b = uri.IsWellFormedOriginalString();
Assert.False(b);
uri = new Uri(@"file://c:/directory/filename");
b = uri.IsWellFormedOriginalString();
Assert.False(b);
uri = new Uri(@"http:\\host/path/file");
b = uri.IsWellFormedOriginalString();
Assert.False(b);
}
[Fact]
public static void TestIsWellFormedUriString()
{
bool b;
b = Uri.IsWellFormedUriString("http://www.contoso.com/path?name", UriKind.RelativeOrAbsolute);
Assert.True(b);
b = Uri.IsWellFormedUriString("http://www.contoso.com/path???/file name", UriKind.RelativeOrAbsolute);
Assert.False(b);
b = Uri.IsWellFormedUriString(@"c:\\directory\filename", UriKind.RelativeOrAbsolute);
Assert.False(b);
b = Uri.IsWellFormedUriString(@"file://c:/directory/filename", UriKind.RelativeOrAbsolute);
Assert.False(b);
b = Uri.IsWellFormedUriString(@"http:\\host/path/file", UriKind.RelativeOrAbsolute);
Assert.False(b);
}
[Fact]
public static void TestCompare()
{
Uri uri1 = new Uri("http://www.contoso.com/path?name#frag");
Uri uri2 = new Uri("http://www.contosooo.com/path?name#slag");
Uri uri2a = new Uri("http://www.contosooo.com/path?name#slag");
int i;
i = Uri.Compare(uri1, uri2, UriComponents.AbsoluteUri, UriFormat.UriEscaped, StringComparison.CurrentCulture);
Assert.Equal(i, -1);
i = Uri.Compare(uri1, uri2, UriComponents.Query, UriFormat.UriEscaped, StringComparison.CurrentCulture);
Assert.Equal(i, 0);
i = Uri.Compare(uri1, uri2, UriComponents.Query | UriComponents.Fragment, UriFormat.UriEscaped, StringComparison.CurrentCulture);
Assert.Equal(i, -1);
bool b;
b = uri1.Equals(uri2);
Assert.False(b);
b = uri1 == uri2;
Assert.False(b);
b = uri1 != uri2;
Assert.True(b);
b = uri2.Equals(uri2a);
Assert.True(b);
b = uri2 == uri2a;
Assert.True(b);
b = uri2 != uri2a;
Assert.False(b);
int h2 = uri2.GetHashCode();
int h2a = uri2a.GetHashCode();
Assert.Equal(h2, h2a);
}
[Fact]
public static void TestEscapeDataString()
{
String s;
s = Uri.EscapeDataString("Hello");
Assert.Equal(s, "Hello");
s = Uri.EscapeDataString(@"He\l/lo");
Assert.Equal(s, "He%5Cl%2Flo");
}
[Fact]
public static void TestUnescapeDataString()
{
String s;
s = Uri.UnescapeDataString("Hello");
Assert.Equal(s, "Hello");
s = Uri.UnescapeDataString("He%5Cl%2Flo");
Assert.Equal(s, @"He\l/lo");
}
[Fact]
public static void TestEscapeUriString()
{
String s;
s = Uri.EscapeUriString("Hello");
Assert.Equal(s, "Hello");
s = Uri.EscapeUriString(@"He\l/lo");
Assert.Equal(s, @"He%5Cl/lo");
}
[Fact]
public static void TestGetComponentParts()
{
Uri uri = new Uri("http://www.contoso.com/path?name#frag");
String s;
s = uri.GetComponents(UriComponents.Fragment, UriFormat.UriEscaped);
Assert.Equal(s, "frag");
s = uri.GetComponents(UriComponents.Host, UriFormat.UriEscaped);
Assert.Equal(s, "www.contoso.com");
}
}
}
| |
/*
* 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.Net;
using System.Reflection;
using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Services.Connectors.Friends;
using OpenSim.Services.Connectors.Hypergrid;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Server.Base;
using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
using OpenMetaverse;
using log4net;
using Nini.Config;
namespace OpenSim.Services.HypergridService
{
/// <summary>
/// This service is for HG1.5 only, to make up for the fact that clients don't
/// keep any private information in themselves, and that their 'home service'
/// needs to do it for them.
/// Once we have better clients, this shouldn't be needed.
/// </summary>
public class UserAgentService : UserAgentServiceBase, IUserAgentService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
// This will need to go into a DB table
//static Dictionary<UUID, TravelingAgentInfo> m_Database = new Dictionary<UUID, TravelingAgentInfo>();
static bool m_Initialized = false;
protected static IGridUserService m_GridUserService;
protected static IGridService m_GridService;
protected static GatekeeperServiceConnector m_GatekeeperConnector;
protected static IGatekeeperService m_GatekeeperService;
protected static IFriendsService m_FriendsService;
protected static IPresenceService m_PresenceService;
protected static IUserAccountService m_UserAccountService;
protected static IFriendsSimConnector m_FriendsLocalSimConnector; // standalone, points to HGFriendsModule
protected static FriendsSimConnector m_FriendsSimConnector; // grid
protected static string m_GridName;
protected static int m_LevelOutsideContacts;
protected static bool m_BypassClientVerification;
private static Dictionary<int, bool> m_ForeignTripsAllowed = new Dictionary<int, bool>();
private static Dictionary<int, List<string>> m_TripsAllowedExceptions = new Dictionary<int, List<string>>();
private static Dictionary<int, List<string>> m_TripsDisallowedExceptions = new Dictionary<int, List<string>>();
public UserAgentService(IConfigSource config) : this(config, null)
{
}
public UserAgentService(IConfigSource config, IFriendsSimConnector friendsConnector)
: base(config)
{
// Let's set this always, because we don't know the sequence
// of instantiations
if (friendsConnector != null)
m_FriendsLocalSimConnector = friendsConnector;
if (!m_Initialized)
{
m_Initialized = true;
m_log.DebugFormat("[HOME USERS SECURITY]: Starting...");
m_FriendsSimConnector = new FriendsSimConnector();
IConfig serverConfig = config.Configs["UserAgentService"];
if (serverConfig == null)
throw new Exception(String.Format("No section UserAgentService in config file"));
string gridService = serverConfig.GetString("GridService", String.Empty);
string gridUserService = serverConfig.GetString("GridUserService", String.Empty);
string gatekeeperService = serverConfig.GetString("GatekeeperService", String.Empty);
string friendsService = serverConfig.GetString("FriendsService", String.Empty);
string presenceService = serverConfig.GetString("PresenceService", String.Empty);
string userAccountService = serverConfig.GetString("UserAccountService", String.Empty);
m_BypassClientVerification = serverConfig.GetBoolean("BypassClientVerification", false);
if (gridService == string.Empty || gridUserService == string.Empty || gatekeeperService == string.Empty)
throw new Exception(String.Format("Incomplete specifications, UserAgent Service cannot function."));
Object[] args = new Object[] { config };
m_GridService = ServerUtils.LoadPlugin<IGridService>(gridService, args);
m_GridUserService = ServerUtils.LoadPlugin<IGridUserService>(gridUserService, args);
m_GatekeeperConnector = new GatekeeperServiceConnector();
m_GatekeeperService = ServerUtils.LoadPlugin<IGatekeeperService>(gatekeeperService, args);
m_FriendsService = ServerUtils.LoadPlugin<IFriendsService>(friendsService, args);
m_PresenceService = ServerUtils.LoadPlugin<IPresenceService>(presenceService, args);
m_UserAccountService = ServerUtils.LoadPlugin<IUserAccountService>(userAccountService, args);
m_LevelOutsideContacts = serverConfig.GetInt("LevelOutsideContacts", 0);
LoadTripPermissionsFromConfig(serverConfig, "ForeignTripsAllowed");
LoadDomainExceptionsFromConfig(serverConfig, "AllowExcept", m_TripsAllowedExceptions);
LoadDomainExceptionsFromConfig(serverConfig, "DisallowExcept", m_TripsDisallowedExceptions);
m_GridName = Util.GetConfigVarFromSections<string>(config, "GatekeeperURI",
new string[] { "Startup", "Hypergrid", "UserAgentService" }, String.Empty);
if (string.IsNullOrEmpty(m_GridName)) // Legacy. Remove soon.
{
m_GridName = serverConfig.GetString("ExternalName", string.Empty);
if (m_GridName == string.Empty)
{
serverConfig = config.Configs["GatekeeperService"];
m_GridName = serverConfig.GetString("ExternalName", string.Empty);
}
}
if (!m_GridName.EndsWith("/"))
m_GridName = m_GridName + "/";
// Finally some cleanup
m_Database.DeleteOld();
}
}
protected void LoadTripPermissionsFromConfig(IConfig config, string variable)
{
foreach (string keyName in config.GetKeys())
{
if (keyName.StartsWith(variable + "_Level_"))
{
int level = 0;
if (Int32.TryParse(keyName.Replace(variable + "_Level_", ""), out level))
m_ForeignTripsAllowed.Add(level, config.GetBoolean(keyName, true));
}
}
}
protected void LoadDomainExceptionsFromConfig(IConfig config, string variable, Dictionary<int, List<string>> exceptions)
{
foreach (string keyName in config.GetKeys())
{
if (keyName.StartsWith(variable + "_Level_"))
{
int level = 0;
if (Int32.TryParse(keyName.Replace(variable + "_Level_", ""), out level) && !exceptions.ContainsKey(level))
{
exceptions.Add(level, new List<string>());
string value = config.GetString(keyName, string.Empty);
string[] parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in parts)
exceptions[level].Add(s.Trim());
}
}
}
}
public GridRegion GetHomeRegion(UUID userID, out Vector3 position, out Vector3 lookAt)
{
position = new Vector3(128, 128, 0); lookAt = Vector3.UnitY;
m_log.DebugFormat("[USER AGENT SERVICE]: Request to get home region of user {0}", userID);
GridRegion home = null;
GridUserInfo uinfo = m_GridUserService.GetGridUserInfo(userID.ToString());
if (uinfo != null)
{
if (uinfo.HomeRegionID != UUID.Zero)
{
home = m_GridService.GetRegionByUUID(UUID.Zero, uinfo.HomeRegionID);
position = uinfo.HomePosition;
lookAt = uinfo.HomeLookAt;
}
if (home == null)
{
List<GridRegion> defs = m_GridService.GetDefaultRegions(UUID.Zero);
if (defs != null && defs.Count > 0)
home = defs[0];
}
}
return home;
}
public bool LoginAgentToGrid(AgentCircuitData agentCircuit, GridRegion gatekeeper, GridRegion finalDestination, bool fromLogin, out string reason)
{
m_log.DebugFormat("[USER AGENT SERVICE]: Request to login user {0} {1} (@{2}) to grid {3}",
agentCircuit.firstname, agentCircuit.lastname, (fromLogin ? agentCircuit.IPAddress : "stored IP"), gatekeeper.ServerURI);
string gridName = gatekeeper.ServerURI;
UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, agentCircuit.AgentID);
if (account == null)
{
m_log.WarnFormat("[USER AGENT SERVICE]: Someone attempted to lauch a foreign user from here {0} {1}", agentCircuit.firstname, agentCircuit.lastname);
reason = "Forbidden to launch your agents from here";
return false;
}
// Is this user allowed to go there?
if (m_GridName != gridName)
{
if (m_ForeignTripsAllowed.ContainsKey(account.UserLevel))
{
bool allowed = m_ForeignTripsAllowed[account.UserLevel];
if (m_ForeignTripsAllowed[account.UserLevel] && IsException(gridName, account.UserLevel, m_TripsAllowedExceptions))
allowed = false;
if (!m_ForeignTripsAllowed[account.UserLevel] && IsException(gridName, account.UserLevel, m_TripsDisallowedExceptions))
allowed = true;
if (!allowed)
{
reason = "Your world does not allow you to visit the destination";
m_log.InfoFormat("[USER AGENT SERVICE]: Agents not permitted to visit {0}. Refusing service.", gridName);
return false;
}
}
}
// Take the IP address + port of the gatekeeper (reg) plus the info of finalDestination
GridRegion region = new GridRegion(gatekeeper);
region.ServerURI = gatekeeper.ServerURI;
region.ExternalHostName = finalDestination.ExternalHostName;
region.InternalEndPoint = finalDestination.InternalEndPoint;
region.RegionName = finalDestination.RegionName;
region.RegionID = finalDestination.RegionID;
region.RegionLocX = finalDestination.RegionLocX;
region.RegionLocY = finalDestination.RegionLocY;
// Generate a new service session
agentCircuit.ServiceSessionID = region.ServerURI + ";" + UUID.Random();
TravelingAgentInfo old = null;
TravelingAgentInfo travel = CreateTravelInfo(agentCircuit, region, fromLogin, out old);
bool success = false;
string myExternalIP = string.Empty;
m_log.DebugFormat("[USER AGENT SERVICE]: this grid: {0}, desired grid: {1}, desired region: {2}", m_GridName, gridName, region.RegionID);
if (m_GridName == gridName)
success = m_GatekeeperService.LoginAgent(agentCircuit, finalDestination, out reason);
else
{
success = m_GatekeeperConnector.CreateAgent(region, agentCircuit, (uint)Constants.TeleportFlags.ViaLogin, out myExternalIP, out reason);
if (success)
// Report them as nowhere
m_PresenceService.ReportAgent(agentCircuit.SessionID, UUID.Zero);
}
if (!success)
{
m_log.DebugFormat("[USER AGENT SERVICE]: Unable to login user {0} {1} to grid {2}, reason: {3}",
agentCircuit.firstname, agentCircuit.lastname, region.ServerURI, reason);
if (old != null)
StoreTravelInfo(old);
else
m_Database.Delete(agentCircuit.SessionID);
return false;
}
// Everything is ok
// Update the perceived IP Address of our grid
m_log.DebugFormat("[USER AGENT SERVICE]: Gatekeeper sees me as {0}", myExternalIP);
travel.MyIpAddress = myExternalIP;
StoreTravelInfo(travel);
return true;
}
public bool LoginAgentToGrid(AgentCircuitData agentCircuit, GridRegion gatekeeper, GridRegion finalDestination, out string reason)
{
reason = string.Empty;
return LoginAgentToGrid(agentCircuit, gatekeeper, finalDestination, false, out reason);
}
TravelingAgentInfo CreateTravelInfo(AgentCircuitData agentCircuit, GridRegion region, bool fromLogin, out TravelingAgentInfo existing)
{
HGTravelingData hgt = m_Database.Get(agentCircuit.SessionID);
existing = null;
if (hgt != null)
{
// Very important! Override whatever this agent comes with.
// UserAgentService always sets the IP for every new agent
// with the original IP address.
existing = new TravelingAgentInfo(hgt);
agentCircuit.IPAddress = existing.ClientIPAddress;
}
TravelingAgentInfo travel = new TravelingAgentInfo(existing);
travel.SessionID = agentCircuit.SessionID;
travel.UserID = agentCircuit.AgentID;
travel.GridExternalName = region.ServerURI;
travel.ServiceToken = agentCircuit.ServiceSessionID;
if (fromLogin)
travel.ClientIPAddress = agentCircuit.IPAddress;
StoreTravelInfo(travel);
return travel;
}
public void LogoutAgent(UUID userID, UUID sessionID)
{
m_log.DebugFormat("[USER AGENT SERVICE]: User {0} logged out", userID);
m_Database.Delete(sessionID);
GridUserInfo guinfo = m_GridUserService.GetGridUserInfo(userID.ToString());
if (guinfo != null)
m_GridUserService.LoggedOut(userID.ToString(), sessionID, guinfo.LastRegionID, guinfo.LastPosition, guinfo.LastLookAt);
}
// We need to prevent foreign users with the same UUID as a local user
public bool IsAgentComingHome(UUID sessionID, string thisGridExternalName)
{
HGTravelingData hgt = m_Database.Get(sessionID);
if (hgt == null)
return false;
TravelingAgentInfo travel = new TravelingAgentInfo(hgt);
return travel.GridExternalName.ToLower() == thisGridExternalName.ToLower();
}
public bool VerifyClient(UUID sessionID, string reportedIP)
{
if (m_BypassClientVerification)
return true;
m_log.DebugFormat("[USER AGENT SERVICE]: Verifying Client session {0} with reported IP {1}.",
sessionID, reportedIP);
HGTravelingData hgt = m_Database.Get(sessionID);
if (hgt == null)
return false;
TravelingAgentInfo travel = new TravelingAgentInfo(hgt);
bool result = travel.ClientIPAddress == reportedIP || travel.MyIpAddress == reportedIP; // NATed
m_log.DebugFormat("[USER AGENT SERVICE]: Comparing {0} with login IP {1} and MyIP {1}; result is {3}",
reportedIP, travel.ClientIPAddress, travel.MyIpAddress, result);
return result;
}
public bool VerifyAgent(UUID sessionID, string token)
{
HGTravelingData hgt = m_Database.Get(sessionID);
if (hgt == null)
{
m_log.DebugFormat("[USER AGENT SERVICE]: Token verification for session {0}: no such session", sessionID);
return false;
}
TravelingAgentInfo travel = new TravelingAgentInfo(hgt);
m_log.DebugFormat("[USER AGENT SERVICE]: Verifying agent token {0} against {1}", token, travel.ServiceToken);
return travel.ServiceToken == token;
}
[Obsolete]
public List<UUID> StatusNotification(List<string> friends, UUID foreignUserID, bool online)
{
if (m_FriendsService == null || m_PresenceService == null)
{
m_log.WarnFormat("[USER AGENT SERVICE]: Unable to perform status notifications because friends or presence services are missing");
return new List<UUID>();
}
List<UUID> localFriendsOnline = new List<UUID>();
m_log.DebugFormat("[USER AGENT SERVICE]: Status notification: foreign user {0} wants to notify {1} local friends", foreignUserID, friends.Count);
// First, let's double check that the reported friends are, indeed, friends of that user
// And let's check that the secret matches
List<string> usersToBeNotified = new List<string>();
foreach (string uui in friends)
{
UUID localUserID;
string secret = string.Empty, tmp = string.Empty;
if (Util.ParseUniversalUserIdentifier(uui, out localUserID, out tmp, out tmp, out tmp, out secret))
{
FriendInfo[] friendInfos = m_FriendsService.GetFriends(localUserID);
foreach (FriendInfo finfo in friendInfos)
{
if (finfo.Friend.StartsWith(foreignUserID.ToString()) && finfo.Friend.EndsWith(secret))
{
// great!
usersToBeNotified.Add(localUserID.ToString());
}
}
}
}
// Now, let's send the notifications
m_log.DebugFormat("[USER AGENT SERVICE]: Status notification: user has {0} local friends", usersToBeNotified.Count);
// First, let's send notifications to local users who are online in the home grid
PresenceInfo[] friendSessions = m_PresenceService.GetAgents(usersToBeNotified.ToArray());
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = null;
foreach (PresenceInfo pinfo in friendSessions)
if (pinfo.RegionID != UUID.Zero) // let's guard against traveling agents
{
friendSession = pinfo;
break;
}
if (friendSession != null)
{
ForwardStatusNotificationToSim(friendSession.RegionID, foreignUserID, friendSession.UserID, online);
usersToBeNotified.Remove(friendSession.UserID.ToString());
UUID id;
if (UUID.TryParse(friendSession.UserID, out id))
localFriendsOnline.Add(id);
}
}
//// Lastly, let's notify the rest who may be online somewhere else
//foreach (string user in usersToBeNotified)
//{
// UUID id = new UUID(user);
// if (m_Database.ContainsKey(id) && m_Database[id].GridExternalName != m_GridName)
// {
// string url = m_Database[id].GridExternalName;
// // forward
// m_log.WarnFormat("[USER AGENT SERVICE]: User {0} is visiting {1}. HG Status notifications still not implemented.", user, url);
// }
//}
// and finally, let's send the online friends
if (online)
{
return localFriendsOnline;
}
else
return new List<UUID>();
}
[Obsolete]
protected void ForwardStatusNotificationToSim(UUID regionID, UUID foreignUserID, string user, bool online)
{
UUID userID;
if (UUID.TryParse(user, out userID))
{
if (m_FriendsLocalSimConnector != null)
{
m_log.DebugFormat("[USER AGENT SERVICE]: Local Notify, user {0} is {1}", foreignUserID, (online ? "online" : "offline"));
m_FriendsLocalSimConnector.StatusNotify(foreignUserID, userID, online);
}
else
{
GridRegion region = m_GridService.GetRegionByUUID(UUID.Zero /* !!! */, regionID);
if (region != null)
{
m_log.DebugFormat("[USER AGENT SERVICE]: Remote Notify to region {0}, user {1} is {2}", region.RegionName, foreignUserID, (online ? "online" : "offline"));
m_FriendsSimConnector.StatusNotify(region, foreignUserID, userID.ToString(), online);
}
}
}
}
public List<UUID> GetOnlineFriends(UUID foreignUserID, List<string> friends)
{
List<UUID> online = new List<UUID>();
if (m_FriendsService == null || m_PresenceService == null)
{
m_log.WarnFormat("[USER AGENT SERVICE]: Unable to get online friends because friends or presence services are missing");
return online;
}
m_log.DebugFormat("[USER AGENT SERVICE]: Foreign user {0} wants to know status of {1} local friends", foreignUserID, friends.Count);
// First, let's double check that the reported friends are, indeed, friends of that user
// And let's check that the secret matches and the rights
List<string> usersToBeNotified = new List<string>();
foreach (string uui in friends)
{
UUID localUserID;
string secret = string.Empty, tmp = string.Empty;
if (Util.ParseUniversalUserIdentifier(uui, out localUserID, out tmp, out tmp, out tmp, out secret))
{
FriendInfo[] friendInfos = m_FriendsService.GetFriends(localUserID);
foreach (FriendInfo finfo in friendInfos)
{
if (finfo.Friend.StartsWith(foreignUserID.ToString()) && finfo.Friend.EndsWith(secret) &&
(finfo.TheirFlags & (int)FriendRights.CanSeeOnline) != 0 && (finfo.TheirFlags != -1))
{
// great!
usersToBeNotified.Add(localUserID.ToString());
}
}
}
}
// Now, let's find out their status
m_log.DebugFormat("[USER AGENT SERVICE]: GetOnlineFriends: user has {0} local friends with status rights", usersToBeNotified.Count);
// First, let's send notifications to local users who are online in the home grid
PresenceInfo[] friendSessions = m_PresenceService.GetAgents(usersToBeNotified.ToArray());
if (friendSessions != null && friendSessions.Length > 0)
{
foreach (PresenceInfo pi in friendSessions)
{
UUID presenceID;
if (UUID.TryParse(pi.UserID, out presenceID))
online.Add(presenceID);
}
}
return online;
}
public Dictionary<string, object> GetUserInfo(UUID userID)
{
Dictionary<string, object> info = new Dictionary<string, object>();
if (m_UserAccountService == null)
{
m_log.WarnFormat("[USER AGENT SERVICE]: Unable to get user flags because user account service is missing");
info["result"] = "fail";
info["message"] = "UserAccountService is missing!";
return info;
}
UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero /*!!!*/, userID);
if (account != null)
{
info.Add("user_flags", (object)account.UserFlags);
info.Add("user_created", (object)account.Created);
info.Add("user_title", (object)account.UserTitle);
info.Add("result", "success");
}
return info;
}
public Dictionary<string, object> GetServerURLs(UUID userID)
{
if (m_UserAccountService == null)
{
m_log.WarnFormat("[USER AGENT SERVICE]: Unable to get server URLs because user account service is missing");
return new Dictionary<string, object>();
}
UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero /*!!!*/, userID);
if (account != null)
return account.ServiceURLs;
return new Dictionary<string, object>();
}
public string LocateUser(UUID userID)
{
HGTravelingData[] hgts = m_Database.GetSessions(userID);
if (hgts == null)
return string.Empty;
foreach (HGTravelingData t in hgts)
if (t.Data.ContainsKey("GridExternalName") && !m_GridName.Equals(t.Data["GridExternalName"]))
return t.Data["GridExternalName"];
return string.Empty;
}
public string GetUUI(UUID userID, UUID targetUserID)
{
// Let's see if it's a local user
UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, targetUserID);
if (account != null)
return targetUserID.ToString() + ";" + m_GridName + ";" + account.FirstName + " " + account.LastName ;
// Let's try the list of friends
FriendInfo[] friends = m_FriendsService.GetFriends(userID);
if (friends != null && friends.Length > 0)
{
foreach (FriendInfo f in friends)
if (f.Friend.StartsWith(targetUserID.ToString()))
{
// Let's remove the secret
UUID id; string tmp = string.Empty, secret = string.Empty;
if (Util.ParseUniversalUserIdentifier(f.Friend, out id, out tmp, out tmp, out tmp, out secret))
return f.Friend.Replace(secret, "0");
}
}
return string.Empty;
}
public UUID GetUUID(String first, String last)
{
// Let's see if it's a local user
UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, first, last);
if (account != null)
{
// check user level
if (account.UserLevel < m_LevelOutsideContacts)
return UUID.Zero;
else
return account.PrincipalID;
}
else
return UUID.Zero;
}
#region Misc
private bool IsException(string dest, int level, Dictionary<int, List<string>> exceptions)
{
if (!exceptions.ContainsKey(level))
return false;
bool exception = false;
if (exceptions[level].Count > 0) // we have exceptions
{
string destination = dest;
if (!destination.EndsWith("/"))
destination += "/";
if (exceptions[level].Find(delegate(string s)
{
if (!s.EndsWith("/"))
s += "/";
return s == destination;
}) != null)
exception = true;
}
return exception;
}
private void StoreTravelInfo(TravelingAgentInfo travel)
{
if (travel == null)
return;
HGTravelingData hgt = new HGTravelingData();
hgt.SessionID = travel.SessionID;
hgt.UserID = travel.UserID;
hgt.Data = new Dictionary<string, string>();
hgt.Data["GridExternalName"] = travel.GridExternalName;
hgt.Data["ServiceToken"] = travel.ServiceToken;
hgt.Data["ClientIPAddress"] = travel.ClientIPAddress;
hgt.Data["MyIPAddress"] = travel.MyIpAddress;
m_Database.Store(hgt);
}
#endregion
}
class TravelingAgentInfo
{
public UUID SessionID;
public UUID UserID;
public string GridExternalName = string.Empty;
public string ServiceToken = string.Empty;
public string ClientIPAddress = string.Empty; // as seen from this user agent service
public string MyIpAddress = string.Empty; // the user agent service's external IP, as seen from the next gatekeeper
public TravelingAgentInfo(HGTravelingData t)
{
if (t.Data != null)
{
SessionID = new UUID(t.SessionID);
UserID = new UUID(t.UserID);
GridExternalName = t.Data["GridExternalName"];
ServiceToken = t.Data["ServiceToken"];
ClientIPAddress = t.Data["ClientIPAddress"];
MyIpAddress = t.Data["MyIPAddress"];
}
}
public TravelingAgentInfo(TravelingAgentInfo old)
{
if (old != null)
{
SessionID = old.SessionID;
UserID = old.UserID;
GridExternalName = old.GridExternalName;
ServiceToken = old.ServiceToken;
ClientIPAddress = old.ClientIPAddress;
MyIpAddress = old.MyIpAddress;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine.Rendering;
using UnityEngine.Serialization;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
public enum ShadowMapType
{
CascadedDirectional,
PunctualAtlas,
AreaLightAtlas
}
[GenerateHLSL]
public struct HDShadowData
{
public Vector3 rot0;
public Vector3 rot1;
public Vector3 rot2;
public Vector3 pos;
public Vector4 proj;
public Vector2 atlasOffset;
public float edgeTolerance;
public int flags;
public Vector4 zBufferParam;
public Vector4 shadowMapSize;
public Vector4 viewBias;
public Vector3 normalBias;
public float _padding;
public Vector4 shadowFilterParams0;
public Matrix4x4 shadowToWorld;
}
// We use a different structure for directional light because these is a lot of data there
// and it will add too much useless stuff for other lights
// Note: In order to support HLSL array generation, we need to use fixed arrays and so a unsafe context for this struct
[GenerateHLSL]
public unsafe struct HDDirectionalShadowData
{
// We can't use Vector4 here because the vector4[] makes this struct non blittable
[HLSLArray(4, typeof(Vector4))]
public fixed float sphereCascades[4 * 4];
public Vector4 cascadeDirection;
[HLSLArray(4, typeof(float))]
public fixed float cascadeBorders[4];
}
[GenerateHLSL]
public enum HDShadowFlag
{
SampleBiasScale = (1 << 0),
EdgeLeakFixup = (1 << 1),
EdgeToleranceNormal = (1 << 2),
}
public class HDShadowRequest
{
public Matrix4x4 view;
// Use the y flipped device projection matrix as light projection matrix
public Matrix4x4 deviceProjectionYFlip;
public Matrix4x4 deviceProjection;
public Matrix4x4 shadowToWorld;
public Vector3 position;
public Vector4 zBufferParam;
// Warning: this field is updated by ProcessShadowRequests and is invalid before
public Rect atlasViewport;
public bool zClip;
public Vector4[] frustumPlanes;
// Store the final shadow indice in the shadow data array
// Warning: the index is computed during ProcessShadowRequest and so is invalid before calling this function
public int shadowIndex;
public int lightType;
// Determine in which atlas the shadow will be rendered
public ShadowMapType shadowMapType = ShadowMapType.PunctualAtlas;
// TODO: Remove these field once scriptable culling is here (currently required by ScriptableRenderContext.DrawShadows)
public int lightIndex;
public ShadowSplitData splitData;
// end
public Vector4 viewBias;
public Vector3 normalBias;
public float edgeTolerance;
public int flags;
// PCSS parameters
public float shadowSoftness;
public int blockerSampleCount;
public int filterSampleCount;
public float minFilterSize;
// IMS parameters
public float kernelSize;
public float lightAngle;
public float maxDepthBias;
public Vector4 evsmParams;
}
public enum HDShadowQuality
{
Low = 0,
Medium = 1,
High = 2,
VeryHigh = 3,
}
public enum DirectionalShadowAlgorithm
{
PCF5x5,
PCF7x7,
PCSS,
IMS
}
[Serializable]
public struct HDShadowInitParameters
{
[Serializable]
public struct HDShadowAtlasInitParams
{
public int shadowAtlasResolution;
public DepthBits shadowAtlasDepthBits;
public bool useDynamicViewportRescale;
public static HDShadowAtlasInitParams GetDefault()
{
return new HDShadowAtlasInitParams()
{
shadowAtlasResolution = k_DefaultShadowAtlasResolution,
shadowAtlasDepthBits = k_DefaultShadowMapDepthBits,
useDynamicViewportRescale = true
};
}
}
/// <summary>Default HDShadowInitParameters</summary>
public static readonly HDShadowInitParameters @default = new HDShadowInitParameters()
{
maxShadowRequests = k_DefaultMaxShadowRequests,
directionalShadowsDepthBits = k_DefaultShadowMapDepthBits,
punctualLightShadowAtlas = HDShadowAtlasInitParams.GetDefault(),
areaLightShadowAtlas = HDShadowAtlasInitParams.GetDefault(),
shadowQuality = HDShadowQuality.Low
};
public const int k_DefaultShadowAtlasResolution = 4096;
public const int k_DefaultMaxShadowRequests = 128;
public const DepthBits k_DefaultShadowMapDepthBits = DepthBits.Depth32;
public int maxShadowRequests;
public DepthBits directionalShadowsDepthBits;
public HDShadowQuality shadowQuality;
public HDShadowAtlasInitParams punctualLightShadowAtlas;
public HDShadowAtlasInitParams areaLightShadowAtlas;
}
public class HDShadowResolutionRequest
{
public Rect atlasViewport;
public Vector2 resolution;
public ShadowMapType shadowMapType;
}
public class HDShadowManager : IDisposable
{
public const int k_DirectionalShadowCascadeCount = 4;
List<HDShadowData> m_ShadowDatas = new List<HDShadowData>();
HDShadowRequest[] m_ShadowRequests;
List<HDShadowResolutionRequest> m_ShadowResolutionRequests = new List<HDShadowResolutionRequest>();
HDDirectionalShadowData m_DirectionalShadowData;
// Structured buffer of shadow datas
ComputeBuffer m_ShadowDataBuffer;
ComputeBuffer m_DirectionalShadowDataBuffer;
// The two shadowmaps atlases we uses, one for directional cascade (without resize) and the second for the rest of the shadows
HDShadowAtlas m_CascadeAtlas;
HDShadowAtlas m_Atlas;
HDShadowAtlas m_AreaLightShadowAtlas;
int m_MaxShadowRequests;
int m_ShadowRequestCount;
int m_CascadeCount;
public HDShadowManager(RenderPipelineResources renderPipelineResources, DepthBits directionalShadowDepthBits,
HDShadowInitParameters.HDShadowAtlasInitParams punctualLightAtlasInfo, HDShadowInitParameters.HDShadowAtlasInitParams areaLightAtlasInfo, int maxShadowRequests, Shader clearShader)
{
Material clearMaterial = CoreUtils.CreateEngineMaterial(clearShader);
// Prevent the list from resizing their internal container when we add shadow requests
m_ShadowDatas.Capacity = maxShadowRequests;
m_ShadowResolutionRequests.Capacity = maxShadowRequests;
m_ShadowRequests = new HDShadowRequest[maxShadowRequests];
// The cascade atlas will be allocated only if there is a directional light
m_Atlas = new HDShadowAtlas(renderPipelineResources, punctualLightAtlasInfo.shadowAtlasResolution, punctualLightAtlasInfo.shadowAtlasResolution, HDShaderIDs._ShadowAtlasSize, clearMaterial, false, depthBufferBits: punctualLightAtlasInfo.shadowAtlasDepthBits, name: "Shadow Map Atlas");
// Cascade atlas render texture will only be allocated if there is a shadow casting directional light
bool useMomentShadows = GetDirectionalShadowAlgorithm() == DirectionalShadowAlgorithm.IMS;
m_CascadeAtlas = new HDShadowAtlas(renderPipelineResources, 1, 1, HDShaderIDs._CascadeShadowAtlasSize, clearMaterial, useMomentShadows, depthBufferBits: directionalShadowDepthBits, name: "Cascade Shadow Map Atlas");
m_AreaLightShadowAtlas = new HDShadowAtlas(renderPipelineResources, areaLightAtlasInfo.shadowAtlasResolution, areaLightAtlasInfo.shadowAtlasResolution, HDShaderIDs._AreaShadowAtlasSize, clearMaterial, false, BlurredEVSM: true, depthBufferBits: areaLightAtlasInfo.shadowAtlasDepthBits, name: "Area Light Shadow Map Atlas");
m_ShadowDataBuffer = new ComputeBuffer(maxShadowRequests, System.Runtime.InteropServices.Marshal.SizeOf(typeof(HDShadowData)));
m_DirectionalShadowDataBuffer = new ComputeBuffer(1, System.Runtime.InteropServices.Marshal.SizeOf(typeof(HDDirectionalShadowData)));
m_MaxShadowRequests = maxShadowRequests;
}
public static DirectionalShadowAlgorithm GetDirectionalShadowAlgorithm()
{
var hdAsset = (GraphicsSettings.renderPipelineAsset as HDRenderPipelineAsset);
switch (hdAsset.currentPlatformRenderPipelineSettings.hdShadowInitParams.shadowQuality)
{
case HDShadowQuality.Low:
{
return DirectionalShadowAlgorithm.PCF5x5;
}
case HDShadowQuality.Medium:
{
return DirectionalShadowAlgorithm.PCF7x7;
}
case HDShadowQuality.High:
{
return DirectionalShadowAlgorithm.PCSS;
}
case HDShadowQuality.VeryHigh:
{
return DirectionalShadowAlgorithm.IMS;
}
};
return DirectionalShadowAlgorithm.PCF5x5;
}
public void UpdateDirectionalShadowResolution(int resolution, int cascadeCount)
{
Vector2Int atlasResolution = new Vector2Int(resolution, resolution);
if (cascadeCount > 1)
atlasResolution.x *= 2;
if (cascadeCount > 2)
atlasResolution.y *= 2;
m_CascadeAtlas.UpdateSize(atlasResolution);
}
public int ReserveShadowResolutions(Vector2 resolution, ShadowMapType shadowMapType)
{
if (m_ShadowRequestCount >= m_MaxShadowRequests)
{
Debug.LogWarning("Max shadow requests count reached, dropping all exceeding requests. You can increase this limit by changing the max requests in the HDRP asset");
return -1;
}
HDShadowResolutionRequest resolutionRequest = new HDShadowResolutionRequest{
resolution = resolution,
shadowMapType = shadowMapType,
};
switch (shadowMapType)
{
case ShadowMapType.PunctualAtlas:
m_Atlas.ReserveResolution(resolutionRequest);
break;
case ShadowMapType.AreaLightAtlas:
m_AreaLightShadowAtlas.ReserveResolution(resolutionRequest);
break;
case ShadowMapType.CascadedDirectional:
m_CascadeAtlas.ReserveResolution(resolutionRequest);
break;
}
m_ShadowResolutionRequests.Add(resolutionRequest);
m_ShadowRequestCount = m_ShadowResolutionRequests.Count;
return m_ShadowResolutionRequests.Count - 1;
}
public Vector2 GetReservedResolution(int index)
{
if (index < 0 || index >= m_ShadowRequestCount)
return Vector2.zero;
return m_ShadowResolutionRequests[index].resolution;
}
public void UpdateShadowRequest(int index, HDShadowRequest shadowRequest)
{
if (index >= m_ShadowRequestCount)
return;
shadowRequest.atlasViewport = m_ShadowResolutionRequests[index].atlasViewport;
m_ShadowRequests[index] = shadowRequest;
switch (shadowRequest.shadowMapType)
{
case ShadowMapType.PunctualAtlas:
{
m_Atlas.AddShadowRequest(shadowRequest);
break;
}
case ShadowMapType.CascadedDirectional:
{
m_CascadeAtlas.AddShadowRequest(shadowRequest);
break;
}
case ShadowMapType.AreaLightAtlas:
{
m_AreaLightShadowAtlas.AddShadowRequest(shadowRequest);
break;
}
};
}
public void UpdateCascade(int cascadeIndex, Vector4 cullingSphere, float border)
{
if (cullingSphere.w != float.NegativeInfinity)
{
cullingSphere.w *= cullingSphere.w;
}
m_CascadeCount = Mathf.Max(m_CascadeCount, cascadeIndex);
unsafe
{
fixed (float * sphereCascadesBuffer = m_DirectionalShadowData.sphereCascades)
((Vector4 *)sphereCascadesBuffer)[cascadeIndex] = cullingSphere;
fixed (float * cascadeBorders = m_DirectionalShadowData.cascadeBorders)
cascadeBorders[cascadeIndex] = border;
}
}
HDShadowData CreateShadowData(HDShadowRequest shadowRequest, HDShadowAtlas atlas)
{
HDShadowData data = new HDShadowData();
var devProj = shadowRequest.deviceProjection;
var view = shadowRequest.view;
data.proj = new Vector4(devProj.m00, devProj.m11, devProj.m22, devProj.m23);
data.pos = shadowRequest.position;
data.rot0 = new Vector3(view.m00, view.m01, view.m02);
data.rot1 = new Vector3(view.m10, view.m11, view.m12);
data.rot2 = new Vector3(view.m20, view.m21, view.m22);
data.shadowToWorld = shadowRequest.shadowToWorld;
// Compute the scale and offset (between 0 and 1) for the atlas coordinates
float rWidth = 1.0f / atlas.width;
float rHeight = 1.0f / atlas.height;
data.atlasOffset = Vector2.Scale(new Vector2(rWidth, rHeight), new Vector2(shadowRequest.atlasViewport.x, shadowRequest.atlasViewport.y));
data.shadowMapSize = new Vector4(shadowRequest.atlasViewport.width, shadowRequest.atlasViewport.height, 1.0f / shadowRequest.atlasViewport.width, 1.0f / shadowRequest.atlasViewport.height);
data.viewBias = shadowRequest.viewBias;
data.normalBias = shadowRequest.normalBias;
data.flags = shadowRequest.flags;
data.edgeTolerance = shadowRequest.edgeTolerance;
data.shadowFilterParams0.x = shadowRequest.shadowSoftness;
data.shadowFilterParams0.y = HDShadowUtils.Asfloat(shadowRequest.blockerSampleCount);
data.shadowFilterParams0.z = HDShadowUtils.Asfloat(shadowRequest.filterSampleCount);
data.shadowFilterParams0.w = shadowRequest.minFilterSize;
var hdAsset = (GraphicsSettings.renderPipelineAsset as HDRenderPipelineAsset);
if (hdAsset.currentPlatformRenderPipelineSettings.hdShadowInitParams.shadowQuality == HDShadowQuality.VeryHigh && shadowRequest.lightType == (int)LightType.Directional)
{
data.shadowFilterParams0.x = shadowRequest.kernelSize;
data.shadowFilterParams0.y = shadowRequest.lightAngle;
data.shadowFilterParams0.z = shadowRequest.maxDepthBias;
}
if (atlas.HasBlurredEVSM())
{
data.shadowFilterParams0 = shadowRequest.evsmParams;
}
return data;
}
unsafe Vector4 GetCascadeSphereAtIndex(int index)
{
fixed (float * sphereCascadesBuffer = m_DirectionalShadowData.sphereCascades)
{
return ((Vector4 *)sphereCascadesBuffer)[index];
}
}
public void UpdateCullingParameters(ref ScriptableCullingParameters cullingParams)
{
cullingParams.shadowDistance = Mathf.Min(VolumeManager.instance.stack.GetComponent<HDShadowSettings>().maxShadowDistance.value, cullingParams.shadowDistance);
}
public void LayoutShadowMaps(LightingDebugSettings lightingDebugSettings)
{
m_Atlas.UpdateDebugSettings(lightingDebugSettings);
if (m_CascadeAtlas != null)
m_CascadeAtlas.UpdateDebugSettings(lightingDebugSettings);
m_AreaLightShadowAtlas.UpdateDebugSettings(lightingDebugSettings);
if (lightingDebugSettings.shadowResolutionScaleFactor != 1.0f)
{
foreach (var shadowResolutionRequest in m_ShadowResolutionRequests)
{
// We don't rescale the directional shadows with the global shadow scale factor
// because there is no dynamic atlas rescale when it overflow.
if (shadowResolutionRequest.shadowMapType != ShadowMapType.CascadedDirectional)
shadowResolutionRequest.resolution *= lightingDebugSettings.shadowResolutionScaleFactor;
}
}
// Assign a position to all the shadows in the atlas, and scale shadows if needed
if (m_CascadeAtlas != null && !m_CascadeAtlas.Layout(false))
Debug.LogError("Cascade Shadow atlasing has failed, only one directional light can cast shadows at a time");
m_Atlas.Layout();
m_AreaLightShadowAtlas.Layout();
}
unsafe public void PrepareGPUShadowDatas(CullingResults cullResults, Camera camera)
{
int shadowIndex = 0;
m_ShadowDatas.Clear();
// Create all HDShadowDatas and update them with shadow request datas
for (int i = 0; i < m_ShadowRequestCount; i++)
{
HDShadowAtlas atlas = m_Atlas;
if (m_ShadowRequests[i].shadowMapType == ShadowMapType.CascadedDirectional)
{
atlas = m_CascadeAtlas;
}
else if (m_ShadowRequests[i].shadowMapType == ShadowMapType.AreaLightAtlas)
{
atlas = m_AreaLightShadowAtlas;
}
m_ShadowDatas.Add(CreateShadowData(m_ShadowRequests[i], atlas));
m_ShadowRequests[i].shadowIndex = shadowIndex++;
}
int first = k_DirectionalShadowCascadeCount, second = k_DirectionalShadowCascadeCount;
fixed (float *sphereBuffer = m_DirectionalShadowData.sphereCascades)
{
Vector4 * sphere = (Vector4 *)sphereBuffer;
for (int i = 0; i < k_DirectionalShadowCascadeCount; i++)
{
first = (first == k_DirectionalShadowCascadeCount && sphere[i].w > 0.0f) ? i : first;
second = ((second == k_DirectionalShadowCascadeCount || second == first) && sphere[i].w > 0.0f) ? i : second;
}
}
// Update directional datas:
if (second != k_DirectionalShadowCascadeCount)
m_DirectionalShadowData.cascadeDirection = (GetCascadeSphereAtIndex(second) - GetCascadeSphereAtIndex(first)).normalized;
else
m_DirectionalShadowData.cascadeDirection = Vector4.zero;
m_DirectionalShadowData.cascadeDirection.w = VolumeManager.instance.stack.GetComponent<HDShadowSettings>().cascadeShadowSplitCount.value;
}
public void RenderShadows(ScriptableRenderContext renderContext, CommandBuffer cmd, CullingResults cullResults, HDCamera hdCamera)
{
// Avoid to do any commands if there is no shadow to draw
if (m_ShadowRequestCount == 0)
return ;
// TODO remove DrawShadowSettings, lightIndex and splitData when scriptable culling is available
ShadowDrawingSettings dss = new ShadowDrawingSettings(cullResults, 0);
dss.useRenderingLayerMaskTest = hdCamera.frameSettings.IsEnabled(FrameSettingsField.LightLayers);
// Clear atlas render targets and draw shadows
using (new ProfilingSample(cmd, "Punctual Lights Shadows rendering", CustomSamplerId.RenderShadows.GetSampler()))
{
m_Atlas.RenderShadows(renderContext, cmd, dss);
}
using (new ProfilingSample(cmd, "Directional Light Shadows rendering", CustomSamplerId.RenderShadows.GetSampler()))
{
m_CascadeAtlas.RenderShadows(renderContext, cmd, dss);
}
using (new ProfilingSample(cmd, "Area Light Shadows rendering", CustomSamplerId.RenderShadows.GetSampler()))
{
m_AreaLightShadowAtlas.RenderShadows(renderContext, cmd, dss);
if (m_AreaLightShadowAtlas.HasBlurredEVSM())
{
m_AreaLightShadowAtlas.AreaShadowBlurMoments(cmd, hdCamera);
}
}
// If the shadow algorithm is the improved moment shadow
if (GetDirectionalShadowAlgorithm() == DirectionalShadowAlgorithm.IMS)
{
m_CascadeAtlas.ComputeMomentShadows(cmd, hdCamera);
}
}
public void SyncData()
{
// Avoid to upload datas which will not be used
if (m_ShadowRequestCount == 0)
return;
// Upload the shadow buffers to GPU
m_ShadowDataBuffer.SetData(m_ShadowDatas);
m_DirectionalShadowDataBuffer.SetData(new HDDirectionalShadowData[]{ m_DirectionalShadowData });
}
public void BindResources(CommandBuffer cmd)
{
// This code must be in sync with HDShadowContext.hlsl
cmd.SetGlobalBuffer(HDShaderIDs._HDShadowDatas, m_ShadowDataBuffer);
cmd.SetGlobalBuffer(HDShaderIDs._HDDirectionalShadowData, m_DirectionalShadowDataBuffer);
cmd.SetGlobalTexture(HDShaderIDs._ShadowmapAtlas, m_Atlas.identifier);
cmd.SetGlobalTexture(HDShaderIDs._ShadowmapCascadeAtlas, m_CascadeAtlas.identifier);
cmd.SetGlobalTexture(HDShaderIDs._AreaLightShadowmapAtlas, m_AreaLightShadowAtlas.identifier);
if (m_AreaLightShadowAtlas.HasBlurredEVSM())
{
cmd.SetGlobalTexture(HDShaderIDs._AreaShadowmapMomentAtlas, m_AreaLightShadowAtlas.GetMomentRT());
}
cmd.SetGlobalInt(HDShaderIDs._CascadeShadowCount, m_CascadeCount + 1);
}
public int GetShadowRequestCount()
{
return m_ShadowRequestCount;
}
public void Clear()
{
// Clear the shadows atlas infos and requests
m_Atlas.Clear();
m_CascadeAtlas.Clear();
m_AreaLightShadowAtlas.Clear();
m_ShadowResolutionRequests.Clear();
m_ShadowRequestCount = 0;
m_CascadeCount = 0;
}
// Warning: must be called after ProcessShadowRequests and RenderShadows to have valid informations
public void DisplayShadowAtlas(CommandBuffer cmd, Material debugMaterial, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue)
{
m_Atlas.DisplayAtlas(cmd, debugMaterial, new Rect(0, 0, m_Atlas.width, m_Atlas.height), screenX, screenY, screenSizeX, screenSizeY, minValue, maxValue);
}
// Warning: must be called after ProcessShadowRequests and RenderShadows to have valid informations
public void DisplayShadowCascadeAtlas(CommandBuffer cmd, Material debugMaterial, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue)
{
m_CascadeAtlas.DisplayAtlas(cmd, debugMaterial, new Rect(0, 0, m_CascadeAtlas.width, m_CascadeAtlas.height), screenX, screenY, screenSizeX, screenSizeY, minValue, maxValue);
}
// Warning: must be called after ProcessShadowRequests and RenderShadows to have valid informations
public void DisplayAreaLightShadowAtlas(CommandBuffer cmd, Material debugMaterial, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue)
{
m_AreaLightShadowAtlas.DisplayAtlas(cmd, debugMaterial, new Rect(0, 0, m_AreaLightShadowAtlas.width, m_AreaLightShadowAtlas.height), screenX, screenY, screenSizeX, screenSizeY, minValue, maxValue);
}
// Warning: must be called after ProcessShadowRequests and RenderShadows to have valid informations
public void DisplayShadowMap(int shadowIndex, CommandBuffer cmd, Material debugMaterial, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue)
{
if (shadowIndex >= m_ShadowRequestCount)
return;
HDShadowRequest shadowRequest = m_ShadowRequests[shadowIndex];
switch (shadowRequest.shadowMapType)
{
case ShadowMapType.PunctualAtlas:
{
m_Atlas.DisplayAtlas(cmd, debugMaterial, shadowRequest.atlasViewport, screenX, screenY, screenSizeX, screenSizeY, minValue, maxValue);
break;
}
case ShadowMapType.CascadedDirectional:
{
m_CascadeAtlas.DisplayAtlas(cmd, debugMaterial, shadowRequest.atlasViewport, screenX, screenY, screenSizeX, screenSizeY, minValue, maxValue);
break;
}
case ShadowMapType.AreaLightAtlas:
{
m_AreaLightShadowAtlas.DisplayAtlas(cmd, debugMaterial, shadowRequest.atlasViewport, screenX, screenY, screenSizeX, screenSizeY, minValue, maxValue);
break;
}
};
}
public void Dispose()
{
m_ShadowDataBuffer.Dispose();
m_DirectionalShadowDataBuffer.Dispose();
m_Atlas.Release();
m_AreaLightShadowAtlas.Release();
m_CascadeAtlas.Release();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Abp.Application.Features;
using Abp.Authorization.Roles;
using Abp.Configuration;
using Abp.Configuration.Startup;
using Abp.Domain.Repositories;
using Abp.Domain.Services;
using Abp.Domain.Uow;
using Abp.IdentityFramework;
using Abp.Localization;
using Abp.MultiTenancy;
using Abp.Organizations;
using Abp.Runtime.Caching;
using Abp.Runtime.Security;
using Abp.Runtime.Session;
using Abp.Zero;
using Abp.Zero.Configuration;
using Microsoft.AspNet.Identity;
namespace Abp.Authorization.Users
{
/// <summary>
/// Extends <see cref="UserManager{TUser,TKey}"/> of ASP.NET Identity Framework.
/// </summary>
public abstract class AbpUserManager<TRole, TUser>
: UserManager<TUser, long>,
IDomainService
where TRole : AbpRole<TUser>, new()
where TUser : AbpUser<TUser>
{
protected IUserPermissionStore<TUser> UserPermissionStore
{
get
{
if (!(Store is IUserPermissionStore<TUser>))
{
throw new AbpException("Store is not IUserPermissionStore");
}
return Store as IUserPermissionStore<TUser>;
}
}
public ILocalizationManager LocalizationManager { get; }
protected string LocalizationSourceName { get; set; }
public IAbpSession AbpSession { get; set; }
public FeatureDependencyContext FeatureDependencyContext { get; set; }
protected AbpRoleManager<TRole, TUser> RoleManager { get; }
public AbpUserStore<TRole, TUser> AbpStore { get; }
public IMultiTenancyConfig MultiTenancy { get; set; }
private readonly IPermissionManager _permissionManager;
private readonly IUnitOfWorkManager _unitOfWorkManager;
private readonly ICacheManager _cacheManager;
private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository;
private readonly IRepository<UserOrganizationUnit, long> _userOrganizationUnitRepository;
private readonly IOrganizationUnitSettings _organizationUnitSettings;
private readonly ISettingManager _settingManager;
protected AbpUserManager(
AbpUserStore<TRole, TUser> userStore,
AbpRoleManager<TRole, TUser> roleManager,
IPermissionManager permissionManager,
IUnitOfWorkManager unitOfWorkManager,
ICacheManager cacheManager,
IRepository<OrganizationUnit, long> organizationUnitRepository,
IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository,
IOrganizationUnitSettings organizationUnitSettings,
ILocalizationManager localizationManager,
IdentityEmailMessageService emailService,
ISettingManager settingManager,
IUserTokenProviderAccessor userTokenProviderAccessor)
: base(userStore)
{
AbpStore = userStore;
RoleManager = roleManager;
LocalizationManager = localizationManager;
LocalizationSourceName = AbpZeroConsts.LocalizationSourceName;
_settingManager = settingManager;
_permissionManager = permissionManager;
_unitOfWorkManager = unitOfWorkManager;
_cacheManager = cacheManager;
_organizationUnitRepository = organizationUnitRepository;
_userOrganizationUnitRepository = userOrganizationUnitRepository;
_organizationUnitSettings = organizationUnitSettings;
AbpSession = NullAbpSession.Instance;
UserLockoutEnabledByDefault = true;
DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
MaxFailedAccessAttemptsBeforeLockout = 5;
EmailService = emailService;
UserTokenProvider = userTokenProviderAccessor.GetUserTokenProviderOrNull<TUser>();
}
public override async Task<IdentityResult> CreateAsync(TUser user)
{
user.SetNormalizedNames();
var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress);
if (!result.Succeeded)
{
return result;
}
var tenantId = GetCurrentTenantId();
if (tenantId.HasValue && !user.TenantId.HasValue)
{
user.TenantId = tenantId.Value;
}
InitializeLockoutSettings(user.TenantId);
return await base.CreateAsync(user);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="userId">User id</param>
/// <param name="permissionName">Permission name</param>
public virtual async Task<bool> IsGrantedAsync(long userId, string permissionName)
{
return await IsGrantedAsync(
userId,
_permissionManager.GetPermission(permissionName)
);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="userId">User id</param>
/// <param name="permissionName">Permission name</param>
public virtual bool IsGranted(long userId, string permissionName)
{
return IsGranted(
userId,
_permissionManager.GetPermission(permissionName)
);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual Task<bool> IsGrantedAsync(TUser user, Permission permission)
{
return IsGrantedAsync(user.Id, permission);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual bool IsGranted(TUser user, Permission permission)
{
return IsGranted(user.Id, permission);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="userId">User id</param>
/// <param name="permission">Permission</param>
public virtual async Task<bool> IsGrantedAsync(long userId, Permission permission)
{
//Check for multi-tenancy side
if (!permission.MultiTenancySides.HasFlag(GetCurrentMultiTenancySide()))
{
return false;
}
//Check for depended features
if (permission.FeatureDependency != null && GetCurrentMultiTenancySide() == MultiTenancySides.Tenant)
{
FeatureDependencyContext.TenantId = GetCurrentTenantId();
if (!await permission.FeatureDependency.IsSatisfiedAsync(FeatureDependencyContext))
{
return false;
}
}
//Get cached user permissions
var cacheItem = await GetUserPermissionCacheItemAsync(userId);
if (cacheItem == null)
{
return false;
}
//Check for user-specific value
if (cacheItem.GrantedPermissions.Contains(permission.Name))
{
return true;
}
if (cacheItem.ProhibitedPermissions.Contains(permission.Name))
{
return false;
}
//Check for roles
foreach (var roleId in cacheItem.RoleIds)
{
if (await RoleManager.IsGrantedAsync(roleId, permission))
{
return true;
}
}
return false;
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="userId">User id</param>
/// <param name="permission">Permission</param>
public virtual bool IsGranted(long userId, Permission permission)
{
//Check for multi-tenancy side
if (!permission.MultiTenancySides.HasFlag(GetCurrentMultiTenancySide()))
{
return false;
}
//Check for depended features
if (permission.FeatureDependency != null && GetCurrentMultiTenancySide() == MultiTenancySides.Tenant)
{
FeatureDependencyContext.TenantId = GetCurrentTenantId();
if (!permission.FeatureDependency.IsSatisfied(FeatureDependencyContext))
{
return false;
}
}
//Get cached user permissions
var cacheItem = GetUserPermissionCacheItem(userId);
if (cacheItem == null)
{
return false;
}
//Check for user-specific value
if (cacheItem.GrantedPermissions.Contains(permission.Name))
{
return true;
}
if (cacheItem.ProhibitedPermissions.Contains(permission.Name))
{
return false;
}
//Check for roles
foreach (var roleId in cacheItem.RoleIds)
{
if (RoleManager.IsGranted(roleId, permission))
{
return true;
}
}
return false;
}
/// <summary>
/// Gets granted permissions for a user.
/// </summary>
/// <param name="user">Role</param>
/// <returns>List of granted permissions</returns>
public virtual async Task<IReadOnlyList<Permission>> GetGrantedPermissionsAsync(TUser user)
{
var permissionList = new List<Permission>();
foreach (var permission in _permissionManager.GetAllPermissions())
{
if (await IsGrantedAsync(user.Id, permission))
{
permissionList.Add(permission);
}
}
return permissionList;
}
/// <summary>
/// Sets all granted permissions of a user at once.
/// Prohibits all other permissions.
/// </summary>
/// <param name="user">The user</param>
/// <param name="permissions">Permissions</param>
public virtual async Task SetGrantedPermissionsAsync(TUser user, IEnumerable<Permission> permissions)
{
var oldPermissions = await GetGrantedPermissionsAsync(user);
var newPermissions = permissions.ToArray();
foreach (var permission in oldPermissions.Where(p => !newPermissions.Contains(p)))
{
await ProhibitPermissionAsync(user, permission);
}
foreach (var permission in newPermissions.Where(p => !oldPermissions.Contains(p)))
{
await GrantPermissionAsync(user, permission);
}
}
/// <summary>
/// Prohibits all permissions for a user.
/// </summary>
/// <param name="user">User</param>
public async Task ProhibitAllPermissionsAsync(TUser user)
{
foreach (var permission in _permissionManager.GetAllPermissions())
{
await ProhibitPermissionAsync(user, permission);
}
}
/// <summary>
/// Resets all permission settings for a user.
/// It removes all permission settings for the user.
/// User will have permissions according to his roles.
/// This method does not prohibit all permissions.
/// For that, use <see cref="ProhibitAllPermissionsAsync"/>.
/// </summary>
/// <param name="user">User</param>
public async Task ResetAllPermissionsAsync(TUser user)
{
await UserPermissionStore.RemoveAllPermissionSettingsAsync(user);
}
/// <summary>
/// Grants a permission for a user if not already granted.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual async Task GrantPermissionAsync(TUser user, Permission permission)
{
await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, false));
if (await IsGrantedAsync(user.Id, permission))
{
return;
}
await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, true));
}
/// <summary>
/// Prohibits a permission for a user if it's granted.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual async Task ProhibitPermissionAsync(TUser user, Permission permission)
{
await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, true));
if (!await IsGrantedAsync(user.Id, permission))
{
return;
}
await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, false));
}
public virtual async Task<TUser> FindByNameOrEmailAsync(string userNameOrEmailAddress)
{
return await AbpStore.FindByNameOrEmailAsync(userNameOrEmailAddress);
}
public virtual Task<List<TUser>> FindAllAsync(UserLoginInfo login)
{
return AbpStore.FindAllAsync(login);
}
/// <summary>
/// Gets a user by given id.
/// Throws exception if no user found with given id.
/// </summary>
/// <param name="userId">User id</param>
/// <returns>User</returns>
/// <exception cref="AbpException">Throws exception if no user found with given id</exception>
public virtual async Task<TUser> GetUserByIdAsync(long userId)
{
var user = await FindByIdAsync(userId);
if (user == null)
{
throw new AbpException("There is no user with id: " + userId);
}
return user;
}
/// <summary>
/// Gets a user by given id.
/// Throws exception if no user found with given id.
/// </summary>
/// <param name="userId">User id</param>
/// <returns>User</returns>
/// <exception cref="AbpException">Throws exception if no user found with given id</exception>
public virtual TUser GetUserById(long userId)
{
var user = AbpStore.FindById(userId);
if (user == null)
{
throw new AbpException("There is no user with id: " + userId);
}
return user;
}
public async override Task<ClaimsIdentity> CreateIdentityAsync(TUser user, string authenticationType)
{
var identity = await base.CreateIdentityAsync(user, authenticationType);
if (user.TenantId.HasValue)
{
identity.AddClaim(new Claim(AbpClaimTypes.TenantId, user.TenantId.Value.ToString(CultureInfo.InvariantCulture)));
}
return identity;
}
public override async Task<IdentityResult> UpdateAsync(TUser user)
{
user.SetNormalizedNames();
var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress);
if (!result.Succeeded)
{
return result;
}
//Admin user's username can not be changed!
if (user.UserName != AbpUser<TUser>.AdminUserName)
{
if ((await GetOldUserNameAsync(user.Id)) == AbpUser<TUser>.AdminUserName)
{
return AbpIdentityResult.Failed(string.Format(L("CanNotRenameAdminUser"), AbpUser<TUser>.AdminUserName));
}
}
return await base.UpdateAsync(user);
}
public override async Task<IdentityResult> DeleteAsync(TUser user)
{
if (user.UserName == AbpUser<TUser>.AdminUserName)
{
return AbpIdentityResult.Failed(string.Format(L("CanNotDeleteAdminUser"), AbpUser<TUser>.AdminUserName));
}
return await base.DeleteAsync(user);
}
public virtual async Task<IdentityResult> ChangePasswordAsync(TUser user, string newPassword)
{
var result = await PasswordValidator.ValidateAsync(newPassword);
if (!result.Succeeded)
{
return result;
}
await AbpStore.SetPasswordHashAsync(user, PasswordHasher.HashPassword(newPassword));
await UpdateSecurityStampAsync(user.Id);
return IdentityResult.Success;
}
public virtual async Task<IdentityResult> CheckDuplicateUsernameOrEmailAddressAsync(long? expectedUserId, string userName, string emailAddress)
{
var user = (await FindByNameAsync(userName));
if (user != null && user.Id != expectedUserId)
{
return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateUserName"), userName));
}
user = (await FindByEmailAsync(emailAddress));
if (user != null && user.Id != expectedUserId)
{
return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateEmail"), emailAddress));
}
return IdentityResult.Success;
}
public virtual async Task<IdentityResult> SetRoles(TUser user, string[] roleNames)
{
//Remove from removed roles
foreach (var userRole in user.Roles.ToList())
{
var role = await RoleManager.FindByIdAsync(userRole.RoleId);
if (roleNames.All(roleName => role.Name != roleName))
{
var result = await RemoveFromRoleAsync(user.Id, role.Name);
if (!result.Succeeded)
{
return result;
}
}
}
//Add to added roles
foreach (var roleName in roleNames)
{
var role = await RoleManager.GetRoleByNameAsync(roleName);
if (user.Roles.All(ur => ur.RoleId != role.Id))
{
var result = await AddToRoleAsync(user.Id, roleName);
if (!result.Succeeded)
{
return result;
}
}
}
return IdentityResult.Success;
}
public virtual async Task<bool> IsInOrganizationUnitAsync(long userId, long ouId)
{
return await IsInOrganizationUnitAsync(
await GetUserByIdAsync(userId),
await _organizationUnitRepository.GetAsync(ouId)
);
}
public virtual async Task<bool> IsInOrganizationUnitAsync(TUser user, OrganizationUnit ou)
{
return await _userOrganizationUnitRepository.CountAsync(uou =>
uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id
) > 0;
}
public virtual async Task AddToOrganizationUnitAsync(long userId, long ouId)
{
await AddToOrganizationUnitAsync(
await GetUserByIdAsync(userId),
await _organizationUnitRepository.GetAsync(ouId)
);
}
public virtual async Task AddToOrganizationUnitAsync(TUser user, OrganizationUnit ou)
{
var currentOus = await GetOrganizationUnitsAsync(user);
if (currentOus.Any(cou => cou.Id == ou.Id))
{
return;
}
await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, currentOus.Count + 1);
await _userOrganizationUnitRepository.InsertAsync(new UserOrganizationUnit(user.TenantId, user.Id, ou.Id));
}
public virtual async Task RemoveFromOrganizationUnitAsync(long userId, long ouId)
{
await RemoveFromOrganizationUnitAsync(
await GetUserByIdAsync(userId),
await _organizationUnitRepository.GetAsync(ouId)
);
}
public virtual async Task RemoveFromOrganizationUnitAsync(TUser user, OrganizationUnit ou)
{
await _userOrganizationUnitRepository.DeleteAsync(uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id);
}
public virtual async Task SetOrganizationUnitsAsync(long userId, params long[] organizationUnitIds)
{
await SetOrganizationUnitsAsync(
await GetUserByIdAsync(userId),
organizationUnitIds
);
}
private async Task CheckMaxUserOrganizationUnitMembershipCountAsync(int? tenantId, int requestedCount)
{
var maxCount = await _organizationUnitSettings.GetMaxUserMembershipCountAsync(tenantId);
if (requestedCount > maxCount)
{
throw new AbpException(string.Format("Can not set more than {0} organization unit for a user!", maxCount));
}
}
[UnitOfWork]
public virtual async Task SetOrganizationUnitsAsync(TUser user, params long[] organizationUnitIds)
{
if (organizationUnitIds == null)
{
organizationUnitIds = new long[0];
}
await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, organizationUnitIds.Length);
var currentOus = await GetOrganizationUnitsAsync(user);
//Remove from removed OUs
foreach (var currentOu in currentOus)
{
if (!organizationUnitIds.Contains(currentOu.Id))
{
await RemoveFromOrganizationUnitAsync(user, currentOu);
}
}
await _unitOfWorkManager.Current.SaveChangesAsync();
//Add to added OUs
foreach (var organizationUnitId in organizationUnitIds)
{
if (currentOus.All(ou => ou.Id != organizationUnitId))
{
await AddToOrganizationUnitAsync(
user,
await _organizationUnitRepository.GetAsync(organizationUnitId)
);
}
}
}
[UnitOfWork]
public virtual Task<List<OrganizationUnit>> GetOrganizationUnitsAsync(TUser user)
{
var query = from uou in _userOrganizationUnitRepository.GetAll()
join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id
where uou.UserId == user.Id
select ou;
return Task.FromResult(query.ToList());
}
[UnitOfWork]
public virtual Task<List<TUser>> GetUsersInOrganizationUnit(OrganizationUnit organizationUnit, bool includeChildren = false)
{
if (!includeChildren)
{
var query = from uou in _userOrganizationUnitRepository.GetAll()
join user in AbpStore.Users on uou.UserId equals user.Id
where uou.OrganizationUnitId == organizationUnit.Id
select user;
return Task.FromResult(query.ToList());
}
else
{
var query = from uou in _userOrganizationUnitRepository.GetAll()
join user in AbpStore.Users on uou.UserId equals user.Id
join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id
where ou.Code.StartsWith(organizationUnit.Code)
select user;
return Task.FromResult(query.ToList());
}
}
public virtual void RegisterTwoFactorProviders(int? tenantId)
{
TwoFactorProviders.Clear();
if (!IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEnabled, tenantId))
{
return;
}
if (EmailService != null &&
IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEmailProviderEnabled, tenantId))
{
RegisterTwoFactorProvider(
L("Email"),
new EmailTokenProvider<TUser, long>
{
Subject = L("EmailSecurityCodeSubject"),
BodyFormat = L("EmailSecurityCodeBody")
}
);
}
if (SmsService != null &&
IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsSmsProviderEnabled, tenantId))
{
RegisterTwoFactorProvider(
L("Sms"),
new PhoneNumberTokenProvider<TUser, long>
{
MessageFormat = L("SmsSecurityCodeMessage")
}
);
}
}
public virtual void InitializeLockoutSettings(int? tenantId)
{
UserLockoutEnabledByDefault = IsTrue(AbpZeroSettingNames.UserManagement.UserLockOut.IsEnabled, tenantId);
DefaultAccountLockoutTimeSpan = TimeSpan.FromSeconds(GetSettingValue<int>(AbpZeroSettingNames.UserManagement.UserLockOut.DefaultAccountLockoutSeconds, tenantId));
MaxFailedAccessAttemptsBeforeLockout = GetSettingValue<int>(AbpZeroSettingNames.UserManagement.UserLockOut.MaxFailedAccessAttemptsBeforeLockout, tenantId);
}
public override async Task<IList<string>> GetValidTwoFactorProvidersAsync(long userId)
{
var user = await GetUserByIdAsync(userId);
RegisterTwoFactorProviders(user.TenantId);
return await base.GetValidTwoFactorProvidersAsync(userId);
}
public override async Task<IdentityResult> NotifyTwoFactorTokenAsync(long userId, string twoFactorProvider, string token)
{
var user = await GetUserByIdAsync(userId);
RegisterTwoFactorProviders(user.TenantId);
return await base.NotifyTwoFactorTokenAsync(userId, twoFactorProvider, token);
}
public override async Task<string> GenerateTwoFactorTokenAsync(long userId, string twoFactorProvider)
{
var user = await GetUserByIdAsync(userId);
RegisterTwoFactorProviders(user.TenantId);
return await base.GenerateTwoFactorTokenAsync(userId, twoFactorProvider);
}
public override async Task<bool> VerifyTwoFactorTokenAsync(long userId, string twoFactorProvider, string token)
{
var user = await GetUserByIdAsync(userId);
RegisterTwoFactorProviders(user.TenantId);
return await base.VerifyTwoFactorTokenAsync(userId, twoFactorProvider, token);
}
protected virtual Task<string> GetOldUserNameAsync(long userId)
{
return AbpStore.GetUserNameFromDatabaseAsync(userId);
}
private async Task<UserPermissionCacheItem> GetUserPermissionCacheItemAsync(long userId)
{
var cacheKey = userId + "@" + (GetCurrentTenantId() ?? 0);
return await _cacheManager.GetUserPermissionCache().GetAsync(cacheKey, async () =>
{
var user = await FindByIdAsync(userId);
if (user == null)
{
return null;
}
var newCacheItem = new UserPermissionCacheItem(userId);
foreach (var roleName in await GetRolesAsync(userId))
{
newCacheItem.RoleIds.Add((await RoleManager.GetRoleByNameAsync(roleName)).Id);
}
foreach (var permissionInfo in await UserPermissionStore.GetPermissionsAsync(userId))
{
if (permissionInfo.IsGranted)
{
newCacheItem.GrantedPermissions.Add(permissionInfo.Name);
}
else
{
newCacheItem.ProhibitedPermissions.Add(permissionInfo.Name);
}
}
return newCacheItem;
});
}
private UserPermissionCacheItem GetUserPermissionCacheItem(long userId)
{
var cacheKey = userId + "@" + (GetCurrentTenantId() ?? 0);
return _cacheManager.GetUserPermissionCache().Get(cacheKey, () =>
{
var user = AbpStore.FindById(userId);
if (user == null)
{
return null;
}
var newCacheItem = new UserPermissionCacheItem(userId);
foreach (var roleName in AbpStore.GetRoles(userId))
{
newCacheItem.RoleIds.Add((RoleManager.GetRoleByName(roleName)).Id);
}
foreach (var permissionInfo in UserPermissionStore.GetPermissions(userId))
{
if (permissionInfo.IsGranted)
{
newCacheItem.GrantedPermissions.Add(permissionInfo.Name);
}
else
{
newCacheItem.ProhibitedPermissions.Add(permissionInfo.Name);
}
}
return newCacheItem;
});
}
private bool IsTrue(string settingName, int? tenantId)
{
return GetSettingValue<bool>(settingName, tenantId);
}
private T GetSettingValue<T>(string settingName, int? tenantId) where T : struct
{
return tenantId == null
? _settingManager.GetSettingValueForApplication<T>(settingName)
: _settingManager.GetSettingValueForTenant<T>(settingName, tenantId.Value);
}
protected virtual string L(string name)
{
return LocalizationManager.GetString(LocalizationSourceName, name);
}
protected virtual string L(string name, CultureInfo cultureInfo)
{
return LocalizationManager.GetString(LocalizationSourceName, name, cultureInfo);
}
private int? GetCurrentTenantId()
{
if (_unitOfWorkManager.Current != null)
{
return _unitOfWorkManager.Current.GetTenantId();
}
return AbpSession.TenantId;
}
private MultiTenancySides GetCurrentMultiTenancySide()
{
if (_unitOfWorkManager.Current != null)
{
return MultiTenancy.IsEnabled && !_unitOfWorkManager.Current.GetTenantId().HasValue
? MultiTenancySides.Host
: MultiTenancySides.Tenant;
}
return AbpSession.MultiTenancySide;
}
public bool IsLockedOut(long userId)
{
var user = AbpStore.FindById(userId);
if (user == null)
{
throw new AbpException("There is no user with id: " + userId);
}
var lockoutEndDateUtc = AbpStore.GetLockoutEndDate(user);
return lockoutEndDateUtc > DateTimeOffset.UtcNow;
}
public bool IsLockedOut(TUser user)
{
var lockoutEndDateUtc = AbpStore.GetLockoutEndDate(user);
return lockoutEndDateUtc > DateTimeOffset.UtcNow;
}
public void ResetAccessFailedCount(TUser user)
{
AbpStore.ResetAccessFailedCountAsync(user);
}
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using System;
using System.Threading;
using Alachisoft.NCache.Common.Enum;
namespace Alachisoft.NCache.Common.DataStructures
{
/// <summary> Elements are added at the tail and removed from the head. Class is thread-safe in that
/// 1 producer and 1 consumer may add/remove elements concurrently. The class is not
/// explicitely designed for multiple producers or consumers.
/// </summary>
/// <author>
/// </author>
public class Queue
{
protected System.Collections.Queue[] _queues = new System.Collections.Queue[3];
/*flag to determine the state of the queue*/
protected bool closed = false;
/*current size of the queue*/
protected int size = 0;
/* Lock object for synchronization. Is notified when element is added */
protected object mutex = new object();
/// <summary>Lock object for syncing on removes. It is notified when an object is removed </summary>
// Object remove_mutex=new Object();
/*the number of end markers that have been added*/
protected int num_markers = 0;
/// <summary> if the queue closes during the runtime
/// an endMarker object is added to the end of the queue to indicate that
/// the queue will close automatically when the end marker is encountered
/// This allows for a "soft" close.
/// </summary>
/// <seealso cref="Queue#close">
/// </seealso>
protected static readonly object endMarker = new object();
/// <summary> creates an empty queue</summary>
public Queue()
{
_queues[(int)Priority.High] = new System.Collections.Queue(11, 1.0f);
_queues[(int)Priority.Normal] = new System.Collections.Queue(11, 1.0f);
_queues[(int)Priority.Low] = new System.Collections.Queue(11, 1.0f);
}
/// <summary>
/// Number of Objects in the queue
/// </summary>
public int Count
{
get { return size - num_markers; }
}
/// <summary> returns true if the Queue has been closed
/// however, this method will return false if the queue has been closed
/// using the close(true) method and the last element has yet not been received.
/// </summary>
/// <returns> true if the queue has been closed
/// </returns>
public bool Closed
{
get { return closed; }
}
/// <summary> adds an object to the tail of this queue
/// If the queue has been closed with close(true) no exception will be
/// thrown if the queue has not been flushed yet.
/// </summary>
/// <param name="obj">- the object to be added to the queue
/// </param>
/// <exception cref=""> QueueClosedException exception if closed() returns true
/// </exception>
public void add(object obj)
{
add(obj, Priority.Normal);
}
/// <summary> adds an object to the tail of this queue
/// If the queue has been closed with close(true) no exception will be
/// thrown if the queue has not been flushed yet.
/// </summary>
/// <param name="obj">- the object to be added to the queue
/// </param>
/// <param name="priority">- the priority of the object
/// </param>
/// <exception cref=""> QueueClosedException exception if closed() returns true
/// </exception>
public void add(object obj, Priority priority)
{
if (obj == null)
{
return;
}
if (priority == Priority.Critical)
priority = Priority.High;
lock (mutex)
{
if (closed)
throw new QueueClosedException();
if (this.num_markers > 0)
throw new QueueClosedException("Queue.add(): queue has been closed. You can not add more elements. " + "Waiting for removal of remaining elements.");
_queues[(int)priority].Enqueue(obj);
size++;
Monitor.PulseAll(mutex);
}
}
/// <summary> Removes 1 element from head or <B>blocks</B>
/// until next element has been added or until queue has been closed
/// </summary>
/// <returns> the first element to be taken of the queue
/// </returns>
public object remove()
{
object retval = null;
try
{
retval = remove(Timeout.Infinite);
}
catch (Runtime.Exceptions.TimeoutException)
{
}
return retval;
}
/// <summary> Removes 1 element from the head.
/// If the queue is empty the operation will wait for timeout ms.
/// if no object is added during the timeout time, a Timout exception is thrown
/// </summary>
/// <param name="timeout">- the number of milli seconds this operation will wait before it times out
/// </param>
/// <returns> the first object in the queue
/// </returns>
public object remove(long timeout)
{
object retval = null;
/*lock the queue*/
lock (mutex)
{
/*if the queue size is zero, we want to wait until a new object is added*/
if (size == 0)
{
if (closed) throw new QueueClosedException();
/*release the add_mutex lock and wait no more than timeout ms*/
if (!Monitor.Wait(mutex, (int)timeout))
{
throw new Runtime.Exceptions.TimeoutException();
}
}
/*check to see if the object closed*/
if (closed) throw new QueueClosedException();
/*get the next value*/
retval = RemoveItemFromQueue();
/*if we reached an end marker we are going to close the queue*/
if (retval == endMarker)
{
close(false);
throw new QueueClosedException();
}
/*at this point we actually did receive a value from the queue, return it*/
return retval;
}
}
protected virtual Object RemoveItemFromQueue()
{
Object retval = null;
if (_queues[(int)Priority.High].Count > 0)
retval = removeInternal(_queues[(int)Priority.High]);
else if (_queues[(int)Priority.Normal].Count > 0)
retval = removeInternal(_queues[(int)Priority.Normal]);
else if (_queues[(int)Priority.Low].Count > 0)
retval = removeInternal(_queues[(int)Priority.Low]);
return retval;
}
/// <summary> returns the first object on the queue, without removing it.
/// If the queue is empty this object blocks until the first queue object has
/// been added
/// </summary>
/// <returns> the first object on the queue
/// </returns>
public object peek()
{
object retval = null;
bool success;
retval = peek(Timeout.Infinite, out success);
return retval;
}
/// <summary> returns the first object on the queue, without removing it.
/// If the queue is empty this object blocks until the first queue object has
/// been added or the operation times out
/// </summary>
/// <param name="timeout">how long in milli seconds will this operation wait for an object to be added to the queue
/// before it times out
/// </param>
/// <param name="error">this param is set to false if timeout occurs</param>
/// <returns> the first object on the queue
/// </returns>
public object peek(long timeout, out bool success)
{
object retval = null;
success = true;
lock (mutex)
{
if (size == 0)
{
if (closed)
throw new QueueClosedException();
if (!Monitor.Wait(mutex, (int)timeout))
{
success = false;
return null;
}
}
if (closed)
throw new QueueClosedException();
retval = peekInternal();
if (retval == endMarker)
{
close(false);
throw new QueueClosedException();
}
}
return retval;
}
private object peekInternal()
{
object retval = null;
if (_queues[(int)Priority.High].Count > 0)
retval = _queues[(int)Priority.High].Peek();
else if (_queues[(int)Priority.Normal].Count > 0)
retval = _queues[(int)Priority.Normal].Peek();
else if (_queues[(int)Priority.Low].Count > 0)
retval = _queues[(int)Priority.Low].Peek();
return retval;
}
/// <summary>Marks the queues as closed. When an <code>add</code> or <code>remove</code> operation is
/// attempted on a closed queue, an exception is thrown.
/// </summary>
/// <param name="flush_entries">When true, a end-of-entries marker is added to the end of the queue.
/// Entries may be added and removed, but when the end-of-entries marker
/// is encountered, the queue is marked as closed. This allows to flush
/// pending messages before closing the queue.
/// </param>
public virtual void close(bool flush_entries)
{
lock (mutex)
{
if (flush_entries)
{
try
{
add(endMarker, Priority.Low);
num_markers++;
}
catch (QueueClosedException ex)
{
}
return;
}
closed = true;
Monitor.PulseAll(mutex);
}
}
/// <summary> resets the queue.
/// This operation removes all the objects in the queue and marks the queue open
/// </summary>
public virtual void reset()
{
lock (mutex)
{
num_markers = 0;
if (!closed) close(false);
size = 0;
_queues[(int)Priority.High].Clear();
_queues[(int)Priority.Normal].Clear();
_queues[(int)Priority.Low].Clear();
closed = false;
Monitor.PulseAll(mutex);
}
}
/// <summary> prints the size of the queue</summary>
public override string ToString()
{
return "Queue (" + Count + ") messages";
}
/* ------------------------------------- Private Methods ----------------------------------- */
/// <summary> Removes the first element. Returns null if no elements in queue.
/// Always called with add_mutex locked (we don't have to lock add_mutex ourselves)
/// </summary>
protected object removeInternal(System.Collections.Queue queue)
{
object obj = null;
lock (mutex)
{
int count = queue.Count;
if (count > 0)
{
obj = queue.Dequeue();
}
else
{
return null;
}
size--;
if (size < 0)
size = 0;
if (peekInternal() == endMarker)
closed = true;
}
return obj;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//------------------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
namespace System.Data.Common
{
internal class DbConnectionOptions
{
// instances of this class are intended to be immutable, i.e readonly
// used by pooling classes so it is much easier to verify correctness
// when not worried about the class being modified during execution
#if DEBUG
/*private const string ConnectionStringPatternV1 =
"[\\s;]*"
+"(?<key>([^=\\s]|\\s+[^=\\s]|\\s+==|==)+)"
+ "\\s*=(?!=)\\s*"
+"(?<value>("
+ "(" + "\"" + "([^\"]|\"\")*" + "\"" + ")"
+ "|"
+ "(" + "'" + "([^']|'')*" + "'" + ")"
+ "|"
+ "(" + "(?![\"'])" + "([^\\s;]|\\s+[^\\s;])*" + "(?<![\"'])" + ")"
+ "))"
+ "[\\s;]*"
;*/
private const string ConnectionStringPattern = // may not contain embedded null except trailing last value
"([\\s;]*" // leading whitespace and extra semicolons
+ "(?![\\s;])" // key does not start with space or semicolon
+ "(?<key>([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}]|\\s+==|==)+)" // allow any visible character for keyname except '=' which must quoted as '=='
+ "\\s*=(?!=)\\s*" // the equal sign divides the key and value parts
+ "(?<value>"
+ "(\"([^\"\u0000]|\"\")*\")" // double quoted string, " must be quoted as ""
+ "|"
+ "('([^'\u0000]|'')*')" // single quoted string, ' must be quoted as ''
+ "|"
+ "((?![\"'\\s])" // unquoted value must not start with " or ' or space, would also like = but too late to change
+ "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" // control characters must be quoted
+ "(?<![\"']))" // unquoted value must not stop with " or '
+ ")(\\s*)(;|[\u0000\\s]*$)" // whitespace after value up to semicolon or end-of-line
+ ")*" // repeat the key-value pair
+ "[\\s;]*[\u0000\\s]*" // trailing whitespace/semicolons (DataSourceLocator), embedded nulls are allowed only in the end
;
private static readonly Regex s_connectionStringRegex = new Regex(ConnectionStringPattern, RegexOptions.ExplicitCapture | RegexOptions.Compiled);
#endif
private const string ConnectionStringValidKeyPattern = "^(?![;\\s])[^\\p{Cc}]+(?<!\\s)$"; // key not allowed to start with semi-colon or space or contain non-visible characters or end with space
private const string ConnectionStringValidValuePattern = "^[^\u0000]*$"; // value not allowed to contain embedded null
private static readonly Regex s_connectionStringValidKeyRegex = new Regex(ConnectionStringValidKeyPattern, RegexOptions.Compiled);
private static readonly Regex s_connectionStringValidValueRegex = new Regex(ConnectionStringValidValuePattern, RegexOptions.Compiled);
// connection string common keywords
private static class KEY
{
internal const string Integrated_Security = "integrated security";
internal const string Password = "password";
internal const string Persist_Security_Info = "persist security info";
};
// known connection string common synonyms
private static class SYNONYM
{
internal const string Pwd = "pwd";
};
private readonly string _usersConnectionString;
private readonly Dictionary<string, string> _parsetable;
internal readonly NameValuePair KeyChain;
internal readonly bool HasPasswordKeyword;
public DbConnectionOptions(string connectionString, Dictionary<string, string> synonyms)
{
_parsetable = new Dictionary<string, string>();
_usersConnectionString = ((null != connectionString) ? connectionString : "");
// first pass on parsing, initial syntax check
if (0 < _usersConnectionString.Length)
{
KeyChain = ParseInternal(_parsetable, _usersConnectionString, true, synonyms);
HasPasswordKeyword = (_parsetable.ContainsKey(KEY.Password) || _parsetable.ContainsKey(SYNONYM.Pwd));
}
}
protected DbConnectionOptions(DbConnectionOptions connectionOptions)
{ // Clone used by SqlConnectionString
_usersConnectionString = connectionOptions._usersConnectionString;
HasPasswordKeyword = connectionOptions.HasPasswordKeyword;
_parsetable = connectionOptions._parsetable;
KeyChain = connectionOptions.KeyChain;
}
public string UsersConnectionString(bool hidePassword)
{
return UsersConnectionString(hidePassword, false);
}
private string UsersConnectionString(bool hidePassword, bool forceHidePassword)
{
string connectionString = _usersConnectionString;
if (HasPasswordKeyword && (forceHidePassword || (hidePassword && !HasPersistablePassword)))
{
ReplacePasswordPwd(out connectionString, false);
}
return ((null != connectionString) ? connectionString : "");
}
internal bool HasPersistablePassword
{
get
{
if (HasPasswordKeyword)
{
return ConvertValueToBoolean(KEY.Persist_Security_Info, false);
}
return true; // no password means persistable password so we don't have to munge
}
}
public bool IsEmpty
{
get { return (null == KeyChain); }
}
internal bool TryGetParsetableValue(string key, out string value) => _parsetable.TryGetValue(key, out value);
public bool ConvertValueToBoolean(string keyName, bool defaultValue)
{
string value;
return _parsetable.TryGetValue(keyName, out value) ?
ConvertValueToBooleanInternal(keyName, value) :
defaultValue;
}
internal static bool ConvertValueToBooleanInternal(string keyName, string stringValue)
{
if (CompareInsensitiveInvariant(stringValue, "true") || CompareInsensitiveInvariant(stringValue, "yes"))
return true;
else if (CompareInsensitiveInvariant(stringValue, "false") || CompareInsensitiveInvariant(stringValue, "no"))
return false;
else
{
string tmp = stringValue.Trim(); // Remove leading & trailing whitespace.
if (CompareInsensitiveInvariant(tmp, "true") || CompareInsensitiveInvariant(tmp, "yes"))
return true;
else if (CompareInsensitiveInvariant(tmp, "false") || CompareInsensitiveInvariant(tmp, "no"))
return false;
else
{
throw ADP.InvalidConnectionOptionValue(keyName);
}
}
}
// same as Boolean, but with SSPI thrown in as valid yes
public bool ConvertValueToIntegratedSecurity()
{
string value;
return _parsetable.TryGetValue(KEY.Integrated_Security, out value) ?
ConvertValueToIntegratedSecurityInternal(value) :
false;
}
internal bool ConvertValueToIntegratedSecurityInternal(string stringValue)
{
if (CompareInsensitiveInvariant(stringValue, "sspi") || CompareInsensitiveInvariant(stringValue, "true") || CompareInsensitiveInvariant(stringValue, "yes"))
return true;
else if (CompareInsensitiveInvariant(stringValue, "false") || CompareInsensitiveInvariant(stringValue, "no"))
return false;
else
{
string tmp = stringValue.Trim(); // Remove leading & trailing whitespace.
if (CompareInsensitiveInvariant(tmp, "sspi") || CompareInsensitiveInvariant(tmp, "true") || CompareInsensitiveInvariant(tmp, "yes"))
return true;
else if (CompareInsensitiveInvariant(tmp, "false") || CompareInsensitiveInvariant(tmp, "no"))
return false;
else
{
throw ADP.InvalidConnectionOptionValue(KEY.Integrated_Security);
}
}
}
public int ConvertValueToInt32(string keyName, int defaultValue)
{
string value;
return _parsetable.TryGetValue(keyName, out value) ?
ConvertToInt32Internal(keyName, value) :
defaultValue;
}
internal static int ConvertToInt32Internal(string keyname, string stringValue)
{
try
{
return System.Int32.Parse(stringValue, System.Globalization.NumberStyles.Integer, CultureInfo.InvariantCulture);
}
catch (FormatException e)
{
throw ADP.InvalidConnectionOptionValue(keyname, e);
}
catch (OverflowException e)
{
throw ADP.InvalidConnectionOptionValue(keyname, e);
}
}
public string ConvertValueToString(string keyName, string defaultValue)
{
string value;
return _parsetable.TryGetValue(keyName, out value) && value != null ? value : defaultValue;
}
private static bool CompareInsensitiveInvariant(string strvalue, string strconst)
{
return (0 == StringComparer.OrdinalIgnoreCase.Compare(strvalue, strconst));
}
public bool ContainsKey(string keyword)
{
return _parsetable.ContainsKey(keyword);
}
#if DEBUG
[System.Diagnostics.Conditional("DEBUG")]
private static void DebugTraceKeyValuePair(string keyname, string keyvalue, Dictionary<string, string> synonyms)
{
}
#endif
private static string GetKeyName(StringBuilder buffer)
{
int count = buffer.Length;
while ((0 < count) && Char.IsWhiteSpace(buffer[count - 1]))
{
count--; // trailing whitespace
}
return buffer.ToString(0, count).ToLowerInvariant();
}
private static string GetKeyValue(StringBuilder buffer, bool trimWhitespace)
{
int count = buffer.Length;
int index = 0;
if (trimWhitespace)
{
while ((index < count) && Char.IsWhiteSpace(buffer[index]))
{
index++; // leading whitespace
}
while ((0 < count) && Char.IsWhiteSpace(buffer[count - 1]))
{
count--; // trailing whitespace
}
}
return buffer.ToString(index, count - index);
}
// transition states used for parsing
private enum ParserState
{
NothingYet = 1, //start point
Key,
KeyEqual,
KeyEnd,
UnquotedValue,
DoubleQuoteValue,
DoubleQuoteValueQuote,
SingleQuoteValue,
SingleQuoteValueQuote,
BraceQuoteValue,
BraceQuoteValueQuote,
QuotedValueEnd,
NullTermination,
};
internal static int GetKeyValuePair(string connectionString, int currentPosition, StringBuilder buffer, out string keyname, out string keyvalue)
{
int startposition = currentPosition;
buffer.Length = 0;
keyname = null;
keyvalue = null;
char currentChar = '\0';
ParserState parserState = ParserState.NothingYet;
int length = connectionString.Length;
for (; currentPosition < length; ++currentPosition)
{
currentChar = connectionString[currentPosition];
switch (parserState)
{
case ParserState.NothingYet: // [\\s;]*
if ((';' == currentChar) || Char.IsWhiteSpace(currentChar))
{
continue;
}
if ('\0' == currentChar) { parserState = ParserState.NullTermination; continue; }
if (Char.IsControl(currentChar)) { throw ADP.ConnectionStringSyntax(startposition); }
startposition = currentPosition;
if ('=' != currentChar)
{
parserState = ParserState.Key;
break;
}
else
{
parserState = ParserState.KeyEqual;
continue;
}
case ParserState.Key: // (?<key>([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}]|\\s+==|==)+)
if ('=' == currentChar) { parserState = ParserState.KeyEqual; continue; }
if (Char.IsWhiteSpace(currentChar)) { break; }
if (Char.IsControl(currentChar)) { throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.KeyEqual: // \\s*=(?!=)\\s*
if ('=' == currentChar) { parserState = ParserState.Key; break; }
keyname = GetKeyName(buffer);
if (string.IsNullOrEmpty(keyname)) { throw ADP.ConnectionStringSyntax(startposition); }
buffer.Length = 0;
parserState = ParserState.KeyEnd;
goto case ParserState.KeyEnd;
case ParserState.KeyEnd:
if (Char.IsWhiteSpace(currentChar)) { continue; }
{
if ('\'' == currentChar) { parserState = ParserState.SingleQuoteValue; continue; }
if ('"' == currentChar) { parserState = ParserState.DoubleQuoteValue; continue; }
}
if (';' == currentChar) { goto ParserExit; }
if ('\0' == currentChar) { goto ParserExit; }
if (Char.IsControl(currentChar)) { throw ADP.ConnectionStringSyntax(startposition); }
parserState = ParserState.UnquotedValue;
break;
case ParserState.UnquotedValue: // "((?![\"'\\s])" + "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" + "(?<![\"']))"
if (Char.IsWhiteSpace(currentChar)) { break; }
if (Char.IsControl(currentChar) || ';' == currentChar) { goto ParserExit; }
break;
case ParserState.DoubleQuoteValue: // "(\"([^\"\u0000]|\"\")*\")"
if ('"' == currentChar) { parserState = ParserState.DoubleQuoteValueQuote; continue; }
if ('\0' == currentChar) { throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.DoubleQuoteValueQuote:
if ('"' == currentChar) { parserState = ParserState.DoubleQuoteValue; break; }
keyvalue = GetKeyValue(buffer, false);
parserState = ParserState.QuotedValueEnd;
goto case ParserState.QuotedValueEnd;
case ParserState.SingleQuoteValue: // "('([^'\u0000]|'')*')"
if ('\'' == currentChar) { parserState = ParserState.SingleQuoteValueQuote; continue; }
if ('\0' == currentChar) { throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.SingleQuoteValueQuote:
if ('\'' == currentChar) { parserState = ParserState.SingleQuoteValue; break; }
keyvalue = GetKeyValue(buffer, false);
parserState = ParserState.QuotedValueEnd;
goto case ParserState.QuotedValueEnd;
case ParserState.BraceQuoteValue: // "(\\{([^\\}\u0000]|\\}\\})*\\})"
if ('}' == currentChar) { parserState = ParserState.BraceQuoteValueQuote; break; }
if ('\0' == currentChar) { throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.BraceQuoteValueQuote:
if ('}' == currentChar) { parserState = ParserState.BraceQuoteValue; break; }
keyvalue = GetKeyValue(buffer, false);
parserState = ParserState.QuotedValueEnd;
goto case ParserState.QuotedValueEnd;
case ParserState.QuotedValueEnd:
if (Char.IsWhiteSpace(currentChar)) { continue; }
if (';' == currentChar) { goto ParserExit; }
if ('\0' == currentChar) { parserState = ParserState.NullTermination; continue; }
throw ADP.ConnectionStringSyntax(startposition); // unbalanced single quote
case ParserState.NullTermination: // [\\s;\u0000]*
if ('\0' == currentChar) { continue; }
if (Char.IsWhiteSpace(currentChar)) { continue; }
throw ADP.ConnectionStringSyntax(currentPosition);
default:
throw ADP.InternalError(ADP.InternalErrorCode.InvalidParserState1);
}
buffer.Append(currentChar);
}
ParserExit:
switch (parserState)
{
case ParserState.Key:
case ParserState.DoubleQuoteValue:
case ParserState.SingleQuoteValue:
case ParserState.BraceQuoteValue:
// keyword not found/unbalanced double/single quote
throw ADP.ConnectionStringSyntax(startposition);
case ParserState.KeyEqual:
// equal sign at end of line
keyname = GetKeyName(buffer);
if (string.IsNullOrEmpty(keyname)) { throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.UnquotedValue:
// unquoted value at end of line
keyvalue = GetKeyValue(buffer, true);
char tmpChar = keyvalue[keyvalue.Length - 1];
if (('\'' == tmpChar) || ('"' == tmpChar))
{
throw ADP.ConnectionStringSyntax(startposition); // unquoted value must not end in quote, except for odbc
}
break;
case ParserState.DoubleQuoteValueQuote:
case ParserState.SingleQuoteValueQuote:
case ParserState.BraceQuoteValueQuote:
case ParserState.QuotedValueEnd:
// quoted value at end of line
keyvalue = GetKeyValue(buffer, false);
break;
case ParserState.NothingYet:
case ParserState.KeyEnd:
case ParserState.NullTermination:
// do nothing
break;
default:
throw ADP.InternalError(ADP.InternalErrorCode.InvalidParserState2);
}
if ((';' == currentChar) && (currentPosition < connectionString.Length))
{
currentPosition++;
}
return currentPosition;
}
private static bool IsValueValidInternal(string keyvalue)
{
if (null != keyvalue)
{
#if DEBUG
bool compValue = s_connectionStringValidValueRegex.IsMatch(keyvalue);
Debug.Assert((-1 == keyvalue.IndexOf('\u0000')) == compValue, "IsValueValid mismatch with regex");
#endif
return (-1 == keyvalue.IndexOf('\u0000'));
}
return true;
}
private static bool IsKeyNameValid(string keyname)
{
if (null != keyname)
{
#if DEBUG
bool compValue = s_connectionStringValidKeyRegex.IsMatch(keyname);
Debug.Assert(((0 < keyname.Length) && (';' != keyname[0]) && !Char.IsWhiteSpace(keyname[0]) && (-1 == keyname.IndexOf('\u0000'))) == compValue, "IsValueValid mismatch with regex");
#endif
return ((0 < keyname.Length) && (';' != keyname[0]) && !Char.IsWhiteSpace(keyname[0]) && (-1 == keyname.IndexOf('\u0000')));
}
return false;
}
#if DEBUG
private static Dictionary<string, string> SplitConnectionString(string connectionString, Dictionary<string, string> synonyms)
{
var parsetable = new Dictionary<string, string>();
Regex parser = s_connectionStringRegex;
const int KeyIndex = 1, ValueIndex = 2;
Debug.Assert(KeyIndex == parser.GroupNumberFromName("key"), "wrong key index");
Debug.Assert(ValueIndex == parser.GroupNumberFromName("value"), "wrong value index");
if (null != connectionString)
{
Match match = parser.Match(connectionString);
if (!match.Success || (match.Length != connectionString.Length))
{
throw ADP.ConnectionStringSyntax(match.Length);
}
int indexValue = 0;
CaptureCollection keyvalues = match.Groups[ValueIndex].Captures;
foreach (Capture keypair in match.Groups[KeyIndex].Captures)
{
string keyname = keypair.Value.Replace("==", "=").ToLowerInvariant();
string keyvalue = keyvalues[indexValue++].Value;
if (0 < keyvalue.Length)
{
{
switch (keyvalue[0])
{
case '\"':
keyvalue = keyvalue.Substring(1, keyvalue.Length - 2).Replace("\"\"", "\"");
break;
case '\'':
keyvalue = keyvalue.Substring(1, keyvalue.Length - 2).Replace("\'\'", "\'");
break;
default:
break;
}
}
}
else
{
keyvalue = null;
}
DebugTraceKeyValuePair(keyname, keyvalue, synonyms);
string synonym;
string realkeyname = null != synonyms ?
(synonyms.TryGetValue(keyname, out synonym) ? synonym : null) :
keyname;
if (!IsKeyNameValid(realkeyname))
{
throw ADP.KeywordNotSupported(keyname);
}
else
{
parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first)
}
}
}
return parsetable;
}
private static void ParseComparison(Dictionary<string, string> parsetable, string connectionString, Dictionary<string, string> synonyms, Exception e)
{
try
{
Dictionary<string, string> parsedvalues = SplitConnectionString(connectionString, synonyms);
foreach (KeyValuePair<string, string> pair in parsedvalues)
{
string keyname = pair.Key;
string value1 = pair.Value;
string value2;
bool parsetableContainsKey = parsetable.TryGetValue(keyname, out value2);
Debug.Assert(parsetableContainsKey, $"{nameof(ParseInternal)} code vs. regex mismatch keyname <{keyname}>");
Debug.Assert(value1 == value2, $"{nameof(ParseInternal)} code vs. regex mismatch keyvalue <{value1}> <{value2}>");
}
}
catch (ArgumentException f)
{
if (null != e)
{
string msg1 = e.Message;
string msg2 = f.Message;
const string KeywordNotSupportedMessagePrefix = "Keyword not supported:";
const string WrongFormatMessagePrefix = "Format of the initialization string";
bool isEquivalent = (msg1 == msg2);
if (!isEquivalent)
{
// We also accept cases were Regex parser (debug only) reports "wrong format" and
// retail parsing code reports format exception in different location or "keyword not supported"
if (msg2.StartsWith(WrongFormatMessagePrefix, StringComparison.Ordinal))
{
if (msg1.StartsWith(KeywordNotSupportedMessagePrefix, StringComparison.Ordinal) || msg1.StartsWith(WrongFormatMessagePrefix, StringComparison.Ordinal))
{
isEquivalent = true;
}
}
}
Debug.Assert(isEquivalent, "ParseInternal code vs regex message mismatch: <" + msg1 + "> <" + msg2 + ">");
}
else
{
Debug.Assert(false, "ParseInternal code vs regex throw mismatch " + f.Message);
}
e = null;
}
if (null != e)
{
Debug.Assert(false, "ParseInternal code threw exception vs regex mismatch");
}
}
#endif
private static NameValuePair ParseInternal(Dictionary<string, string> parsetable, string connectionString, bool buildChain, Dictionary<string, string> synonyms)
{
Debug.Assert(null != connectionString, "null connectionstring");
StringBuilder buffer = new StringBuilder();
NameValuePair localKeychain = null, keychain = null;
#if DEBUG
try
{
#endif
int nextStartPosition = 0;
int endPosition = connectionString.Length;
while (nextStartPosition < endPosition)
{
int startPosition = nextStartPosition;
string keyname, keyvalue;
nextStartPosition = GetKeyValuePair(connectionString, startPosition, buffer, out keyname, out keyvalue);
if (string.IsNullOrEmpty(keyname))
{
// if (nextStartPosition != endPosition) { throw; }
break;
}
#if DEBUG
DebugTraceKeyValuePair(keyname, keyvalue, synonyms);
Debug.Assert(IsKeyNameValid(keyname), "ParseFailure, invalid keyname");
Debug.Assert(IsValueValidInternal(keyvalue), "parse failure, invalid keyvalue");
#endif
string synonym;
string realkeyname = null != synonyms ?
(synonyms.TryGetValue(keyname, out synonym) ? synonym : null) :
keyname;
if (!IsKeyNameValid(realkeyname))
{
throw ADP.KeywordNotSupported(keyname);
}
else
{
parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first)
}
if (null != localKeychain)
{
localKeychain = localKeychain.Next = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition);
}
else if (buildChain)
{ // first time only - don't contain modified chain from UDL file
keychain = localKeychain = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition);
}
}
#if DEBUG
}
catch (ArgumentException e)
{
ParseComparison(parsetable, connectionString, synonyms, e);
throw;
}
ParseComparison(parsetable, connectionString, synonyms, null);
#endif
return keychain;
}
internal NameValuePair ReplacePasswordPwd(out string constr, bool fakePassword)
{
bool expanded = false;
int copyPosition = 0;
NameValuePair head = null, tail = null, next = null;
StringBuilder builder = new StringBuilder(_usersConnectionString.Length);
for (NameValuePair current = KeyChain; null != current; current = current.Next)
{
if ((KEY.Password != current.Name) && (SYNONYM.Pwd != current.Name))
{
builder.Append(_usersConnectionString, copyPosition, current.Length);
if (fakePassword)
{
next = new NameValuePair(current.Name, current.Value, current.Length);
}
}
else if (fakePassword)
{ // replace user password/pwd value with *
const string equalstar = "=*;";
builder.Append(current.Name).Append(equalstar);
next = new NameValuePair(current.Name, "*", current.Name.Length + equalstar.Length);
expanded = true;
}
else
{ // drop the password/pwd completely in returning for user
expanded = true;
}
if (fakePassword)
{
if (null != tail)
{
tail = tail.Next = next;
}
else
{
tail = head = next;
}
}
copyPosition += current.Length;
}
Debug.Assert(expanded, "password/pwd was not removed");
constr = builder.ToString();
return head;
}
}
}
| |
using EncompassRest.Loans.Enums;
using EncompassRest.Schema;
namespace EncompassRest.Loans
{
/// <summary>
/// FreddieMac
/// </summary>
public sealed partial class FreddieMac : DirtyExtensibleObject, IIdentifiable
{
private DirtyValue<StringEnumValue<AffordableProduct>>? _affordableProduct;
private DirtyValue<decimal?>? _alimonyAsIncomeReduction;
private DirtyValue<decimal?>? _allMonthlyPayments;
private DirtyValue<bool?>? _allowsNegativeAmortizationIndicator;
private DirtyValue<string?>? _amountOfFinancedMI;
private DirtyValue<string?>? _aPNCity;
private DirtyValue<bool?>? _armsLengthTransactionIndicator;
private DirtyValue<bool?>? _borrowerQualifiesAsVeteranIndicator;
private DirtyValue<string?>? _brokerOriginated;
private DirtyValue<StringEnumValue<BuydownContributor>>? _buydownContributor;
private DirtyValue<StringEnumValue<CondoClass>>? _condoClass;
private DirtyValue<decimal?>? _convertibleFeeAmount;
private DirtyValue<decimal?>? _convertibleFeePercent;
private DirtyValue<decimal?>? _convertibleMaxRateAdjPercent;
private DirtyValue<decimal?>? _convertibleMinRateAdjPercent;
private DirtyValue<string?>? _correspondentAssignmentID;
private DirtyValue<string?>? _county;
private DirtyValue<StringEnumValue<CreditReportCompany>>? _creditReportCompany;
private DirtyValue<decimal?>? _financingConcessions;
private DirtyValue<string?>? _freddieFiel11;
private DirtyValue<string?>? _freddieFiel12;
private DirtyValue<string?>? _freddieFiel13;
private DirtyValue<string?>? _freddieFiel14;
private DirtyValue<string?>? _freddieFiel15;
private DirtyValue<string?>? _freddieField3;
private DirtyValue<string?>? _freddieField7;
private DirtyValue<string?>? _freddieMacAppraisalHybrid;
private DirtyValue<string?>? _freddieMacOwnedMessage;
private DirtyValue<string?>? _hELOCActualBalance;
private DirtyValue<string?>? _hELOCCreditLimit;
private DirtyValue<string?>? _id;
private DirtyValue<string?>? _lenderAltPhone;
private DirtyValue<string?>? _lenderRegistration;
private DirtyValue<string?>? _loanProspectorID;
private DirtyValue<StringEnumValue<LoanToConduitCode>>? _loanToConduitCode;
private DirtyValue<string?>? _longLegalDescription;
private DirtyValue<StringEnumValue<LossCoverage>>? _lossCoverage;
private DirtyValue<string?>? _lPKeyNumber;
private DirtyValue<StringEnumValue<MIRefundOption>>? _mIRefundOption;
private DirtyValue<StringEnumValue<MortgageInsuranceCompany>>? _mortgageInsuranceCompany;
private DirtyValue<decimal?>? _netPurchasePrice;
private DirtyValue<StringEnumValue<NewConstructionType>>? _newConstructionType;
private DirtyValue<StringEnumValue<NoAppraisalMAF>>? _noAppraisalMAF;
private DirtyValue<decimal?>? _nonOccupantNonHousingDebt;
private DirtyValue<decimal?>? _nonOccupantPresentHE;
private DirtyValue<bool?>? _orderCreditEvaluationIndicator;
private DirtyValue<bool?>? _orderMergedCreditReportIndicator;
private DirtyValue<StringEnumValue<OrderMortgageInsurance>>? _orderMortgageInsurance;
private DirtyValue<bool?>? _orderRiskGradeEvaluationIndicator;
private DirtyValue<decimal?>? _originalIntRate;
private DirtyValue<string?>? _originateID;
private DirtyValue<StringEnumValue<PaymentFrequency>>? _paymentFrequency;
private DirtyValue<StringEnumValue<PaymentOption>>? _paymentOption;
private DirtyValue<decimal?>? _personIncomeForSelfEmployment1;
private DirtyValue<decimal?>? _personIncomeForSelfEmployment2;
private DirtyValue<int?>? _personPercentOfBusinessOwned1;
private DirtyValue<int?>? _personPercentOfBusinessOwned2;
private DirtyValue<StringEnumValue<PremiumSource>>? _premiumSource;
private DirtyValue<decimal?>? _presentHousingExpense;
private DirtyValue<StringEnumValue<ProcessingPoint>>? _processingPoint;
private DirtyValue<StringEnumValue<FreddieMacPropertyType>>? _propertyType;
private DirtyValue<StringEnumValue<FreddieMacPurposeOfLoan>>? _purposeOfLoan;
private DirtyValue<StringEnumValue<RenewalOption>>? _renewalOption;
private DirtyValue<StringEnumValue<RenewalType>>? _renewalType;
private DirtyValue<StringEnumValue<RequiredDocumentType>>? _requiredDocumentType;
private DirtyValue<decimal?>? _reserves;
private DirtyValue<bool?>? _retailLoanIndicator;
private DirtyValue<StringEnumValue<FreddieMacRiskClass>>? _riskClass;
private DirtyValue<StringEnumValue<RiskGradeEvaluationType>>? _riskGradeEvaluationType;
private DirtyValue<decimal?>? _salesConcessions;
private DirtyValue<StringEnumValue<SecondaryFinancingType>>? _secondaryFinancingType;
private DirtyValue<bool?>? _secondTrustRefiIndicator;
private DirtyValue<decimal?>? _simulatedPITI;
private DirtyValue<string?>? _sizeOfHousehold;
private DirtyValue<string?>? _specialInstruction1;
private DirtyValue<string?>? _specialInstruction2;
private DirtyValue<string?>? _specialInstruction3;
private DirtyValue<string?>? _specialInstruction4;
private DirtyValue<string?>? _specialInstruction5;
private DirtyValue<string?>? _state;
private DirtyValue<bool?>? _transferLoanToConduitIndicator;
private DirtyValue<StringEnumValue<YearsOfCoverage>>? _yearsOfCoverage;
/// <summary>
/// Freddie Mac Lender Affordable Product [CASASRN.X114]
/// </summary>
public StringEnumValue<AffordableProduct> AffordableProduct { get => _affordableProduct; set => SetField(ref _affordableProduct, value); }
/// <summary>
/// Freddie Mac FHA/VA Alimony as Inc Reduc [CASASRN.X159]
/// </summary>
public decimal? AlimonyAsIncomeReduction { get => _alimonyAsIncomeReduction; set => SetField(ref _alimonyAsIncomeReduction, value); }
/// <summary>
/// Freddie Mac Total All Mo Pymts [CASASRN.X99]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? AllMonthlyPayments { get => _allMonthlyPayments; set => SetField(ref _allMonthlyPayments, value); }
/// <summary>
/// Freddie Mac Lender Allows Neg Amort [CASASRN.X85]
/// </summary>
[LoanFieldProperty(OptionsJson = "{\"Y\":\"Allows Negative Amortization\"}")]
public bool? AllowsNegativeAmortizationIndicator { get => _allowsNegativeAmortizationIndicator; set => SetField(ref _allowsNegativeAmortizationIndicator, value); }
/// <summary>
/// Freddie Mac Amt Financed MI [CASASRN.X169]
/// </summary>
public string? AmountOfFinancedMI { get => _amountOfFinancedMI; set => SetField(ref _amountOfFinancedMI, value); }
/// <summary>
/// Freddie Mac Lender APN City [CASASRN.X17]
/// </summary>
public string? APNCity { get => _aPNCity; set => SetField(ref _aPNCity, value); }
/// <summary>
/// Freddie Mac Lender Arms-Length Trans [CASASRN.X81]
/// </summary>
[LoanFieldProperty(OptionsJson = "{\"Y\":\"Arms-Length Transaction\"}")]
public bool? ArmsLengthTransactionIndicator { get => _armsLengthTransactionIndicator; set => SetField(ref _armsLengthTransactionIndicator, value); }
/// <summary>
/// Borr Qualifies as Veteran [156]
/// </summary>
[LoanFieldProperty(OptionsJson = "{\"Y\":\"One or more borrowers qualifies as a veteran\"}")]
public bool? BorrowerQualifiesAsVeteranIndicator { get => _borrowerQualifiesAsVeteranIndicator; set => SetField(ref _borrowerQualifiesAsVeteranIndicator, value); }
/// <summary>
/// Freddie Mac Broker Originated [CASASRN.X165]
/// </summary>
public string? BrokerOriginated { get => _brokerOriginated; set => SetField(ref _brokerOriginated, value); }
/// <summary>
/// Freddie Mac Buydown Contributor [CASASRN.X141]
/// </summary>
public StringEnumValue<BuydownContributor> BuydownContributor { get => _buydownContributor; set => SetField(ref _buydownContributor, value); }
/// <summary>
/// Freddie Mac Lender Condo Class [CASASRN.X84]
/// </summary>
public StringEnumValue<CondoClass> CondoClass { get => _condoClass; set => SetField(ref _condoClass, value); }
/// <summary>
/// Conversion Option Fee Amount [CnvrOpt.FeeAmt]
/// </summary>
public decimal? ConvertibleFeeAmount { get => _convertibleFeeAmount; set => SetField(ref _convertibleFeeAmount, value); }
/// <summary>
/// Conversion Option Fee Percent [CnvrOpt.FeePct]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)]
public decimal? ConvertibleFeePercent { get => _convertibleFeePercent; set => SetField(ref _convertibleFeePercent, value); }
/// <summary>
/// Conversion Option Max. Rate Adj. [CnvrOpt.MaxRateAdj]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)]
public decimal? ConvertibleMaxRateAdjPercent { get => _convertibleMaxRateAdjPercent; set => SetField(ref _convertibleMaxRateAdjPercent, value); }
/// <summary>
/// Conversion Option Min. Rate Adj. [CnvrOpt.MinRateAdj]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)]
public decimal? ConvertibleMinRateAdjPercent { get => _convertibleMinRateAdjPercent; set => SetField(ref _convertibleMinRateAdjPercent, value); }
/// <summary>
/// Freddie Mac Correspondent Assignment Center ID [CASASRN.X203]
/// </summary>
public string? CorrespondentAssignmentID { get => _correspondentAssignmentID; set => SetField(ref _correspondentAssignmentID, value); }
/// <summary>
/// Freddie Mac Lender County [977]
/// </summary>
public string? County { get => _county; set => SetField(ref _county, value); }
/// <summary>
/// Freddie Mac Merged Credit Rpt Source [CASASRN.X2]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public StringEnumValue<CreditReportCompany> CreditReportCompany { get => _creditReportCompany; set => SetField(ref _creditReportCompany, value); }
/// <summary>
/// Freddie Mac Financing Concessions [CASASRN.X20]
/// </summary>
public decimal? FinancingConcessions { get => _financingConcessions; set => SetField(ref _financingConcessions, value); }
/// <summary>
/// Freddie Mac AccountChek Asset ID (Bor) [CASASRN.X31]
/// </summary>
public string? FreddieFiel11 { get => _freddieFiel11; set => SetField(ref _freddieFiel11, value); }
/// <summary>
/// Freddie Mac AccountChek Asset ID (CoBor) [CASASRN.X32]
/// </summary>
public string? FreddieFiel12 { get => _freddieFiel12; set => SetField(ref _freddieFiel12, value); }
/// <summary>
/// Freddie Mac Freddie Field 13 [CASASRN.X33]
/// </summary>
public string? FreddieFiel13 { get => _freddieFiel13; set => SetField(ref _freddieFiel13, value); }
/// <summary>
/// Freddie Mac Risk Class [CASASRN.X34]
/// </summary>
public string? FreddieFiel14 { get => _freddieFiel14; set => SetField(ref _freddieFiel14, value); }
/// <summary>
/// Correspondent Assignment Name [CASASRN.X35]
/// </summary>
public string? FreddieFiel15 { get => _freddieFiel15; set => SetField(ref _freddieFiel15, value); }
/// <summary>
/// Freddie Mac Freddie Field 3 [CASASRN.X162]
/// </summary>
public string? FreddieField3 { get => _freddieField3; set => SetField(ref _freddieField3, value); }
/// <summary>
/// LoanBeam [CASASRN.X166]
/// </summary>
public string? FreddieField7 { get => _freddieField7; set => SetField(ref _freddieField7, value); }
/// <summary>
/// Freddie Mac Appraisal Hybrid [CASASRN.X205]
/// </summary>
public string? FreddieMacAppraisalHybrid { get => _freddieMacAppraisalHybrid; set => SetField(ref _freddieMacAppraisalHybrid, value); }
/// <summary>
/// Freddie Mac Owned Message [CASASRN.X204]
/// </summary>
public string? FreddieMacOwnedMessage { get => _freddieMacOwnedMessage; set => SetField(ref _freddieMacOwnedMessage, value); }
/// <summary>
/// Freddie Mac HELOC Actual Bal [CASASRN.X167]
/// </summary>
public string? HELOCActualBalance { get => _hELOCActualBalance; set => SetField(ref _hELOCActualBalance, value); }
/// <summary>
/// Freddie Mac HELOC Credit Limit [CASASRN.X168]
/// </summary>
public string? HELOCCreditLimit { get => _hELOCCreditLimit; set => SetField(ref _hELOCCreditLimit, value); }
/// <summary>
/// FreddieMac Id
/// </summary>
public string? Id { get => _id; set => SetField(ref _id, value); }
/// <summary>
/// Freddie Mac Lender Alt Phone [CASASRN.X80]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.PHONE)]
public string? LenderAltPhone { get => _lenderAltPhone; set => SetField(ref _lenderAltPhone, value); }
/// <summary>
/// Freddie Mac Lender Registration # [CASASRN.X161]
/// </summary>
public string? LenderRegistration { get => _lenderRegistration; set => SetField(ref _lenderRegistration, value); }
/// <summary>
/// Freddie Mac Loan Prospector ID [CASASRN.X200]
/// </summary>
public string? LoanProspectorID { get => _loanProspectorID; set => SetField(ref _loanProspectorID, value); }
/// <summary>
/// Freddie Mac Conduit [CASASRN.X106]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public StringEnumValue<LoanToConduitCode> LoanToConduitCode { get => _loanToConduitCode; set => SetField(ref _loanToConduitCode, value); }
/// <summary>
/// Freddie Mac Long Legal Descr [CASASRN.X41]
/// </summary>
public string? LongLegalDescription { get => _longLegalDescription; set => SetField(ref _longLegalDescription, value); }
/// <summary>
/// Freddie Mac Loss Coverage Est [CASASRN.X160]
/// </summary>
public StringEnumValue<LossCoverage> LossCoverage { get => _lossCoverage; set => SetField(ref _lossCoverage, value); }
/// <summary>
/// Freddie Mac LP Key # [CASASRN.X13]
/// </summary>
public string? LPKeyNumber { get => _lPKeyNumber; set => SetField(ref _lPKeyNumber, value); }
/// <summary>
/// Freddie Mac MI Refundable Option [CASASRN.X146]
/// </summary>
public StringEnumValue<MIRefundOption> MIRefundOption { get => _mIRefundOption; set => SetField(ref _mIRefundOption, value); }
/// <summary>
/// Freddie Mac MI Souce [CASASRN.X3]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public StringEnumValue<MortgageInsuranceCompany> MortgageInsuranceCompany { get => _mortgageInsuranceCompany; set => SetField(ref _mortgageInsuranceCompany, value); }
/// <summary>
/// Freddie Mac Lender Net Purch Price [CASASRN.X109]
/// </summary>
public decimal? NetPurchasePrice { get => _netPurchasePrice; set => SetField(ref _netPurchasePrice, value); }
/// <summary>
/// Freddie Mac New Construction Type [CASASRN.X197]
/// </summary>
public StringEnumValue<NewConstructionType> NewConstructionType { get => _newConstructionType; set => SetField(ref _newConstructionType, value); }
/// <summary>
/// Freddie Mac No-Appraisal MAF [CASASRN.X164]
/// </summary>
public StringEnumValue<NoAppraisalMAF> NoAppraisalMAF { get => _noAppraisalMAF; set => SetField(ref _noAppraisalMAF, value); }
/// <summary>
/// Freddie Mac Total Debt [CASASRN.X174]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? NonOccupantNonHousingDebt { get => _nonOccupantNonHousingDebt; set => SetField(ref _nonOccupantNonHousingDebt, value); }
/// <summary>
/// Freddie Mac Total Non-Occ Pres Housing Exp [CASASRN.X131]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? NonOccupantPresentHE { get => _nonOccupantPresentHE; set => SetField(ref _nonOccupantPresentHE, value); }
/// <summary>
/// Freddie Mac Order Credit [CASASRN.X1]
/// </summary>
[LoanFieldProperty(ReadOnly = true, OptionsJson = "{\"Y\":\"Order Credit Evaluation\"}")]
public bool? OrderCreditEvaluationIndicator { get => _orderCreditEvaluationIndicator; set => SetField(ref _orderCreditEvaluationIndicator, value); }
/// <summary>
/// Freddie Mac Order Merged Credit Rpt [CASASRN.X88]
/// </summary>
[LoanFieldProperty(ReadOnly = true, OptionsJson = "{\"Y\":\"Order Merged Credit Report\"}")]
public bool? OrderMergedCreditReportIndicator { get => _orderMergedCreditReportIndicator; set => SetField(ref _orderMergedCreditReportIndicator, value); }
/// <summary>
/// Freddie Mac Order MI [CASASRN.X89]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public StringEnumValue<OrderMortgageInsurance> OrderMortgageInsurance { get => _orderMortgageInsurance; set => SetField(ref _orderMortgageInsurance, value); }
/// <summary>
/// Freddie Mac Order Risk Grade Eval [CASASRN.X4]
/// </summary>
[LoanFieldProperty(ReadOnly = true, OptionsJson = "{\"Y\":\"Order Risk Grade Evaluation\"}")]
public bool? OrderRiskGradeEvaluationIndicator { get => _orderRiskGradeEvaluationIndicator; set => SetField(ref _orderRiskGradeEvaluationIndicator, value); }
/// <summary>
/// Freddie Mac Lender Orig Interest Rate [CASASRN.X142]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)]
public decimal? OriginalIntRate { get => _originalIntRate; set => SetField(ref _originalIntRate, value); }
/// <summary>
/// Freddie Mac FHA/VA Originate ID [CASASRN.X27]
/// </summary>
public string? OriginateID { get => _originateID; set => SetField(ref _originateID, value); }
/// <summary>
/// Freddie Mac MI Pymt Frequency [CASASRN.X154]
/// </summary>
public StringEnumValue<PaymentFrequency> PaymentFrequency { get => _paymentFrequency; set => SetField(ref _paymentFrequency, value); }
/// <summary>
/// Freddie Mac MI Pymt Option [CASASRN.X152]
/// </summary>
public StringEnumValue<PaymentOption> PaymentOption { get => _paymentOption; set => SetField(ref _paymentOption, value); }
/// <summary>
/// Freddie Mac Borr Income from Self Emp [CASASRN.X178]
/// </summary>
public decimal? PersonIncomeForSelfEmployment1 { get => _personIncomeForSelfEmployment1; set => SetField(ref _personIncomeForSelfEmployment1, value); }
/// <summary>
/// Freddie Mac Co-Borr Income from Self Emp [CASASRN.X179]
/// </summary>
public decimal? PersonIncomeForSelfEmployment2 { get => _personIncomeForSelfEmployment2; set => SetField(ref _personIncomeForSelfEmployment2, value); }
/// <summary>
/// Freddie Mac Borr % of Business Owned [CASASRN.X176]
/// </summary>
public int? PersonPercentOfBusinessOwned1 { get => _personPercentOfBusinessOwned1; set => SetField(ref _personPercentOfBusinessOwned1, value); }
/// <summary>
/// Freddie Mac Co-Borr % of Business Owned [CASASRN.X177]
/// </summary>
public int? PersonPercentOfBusinessOwned2 { get => _personPercentOfBusinessOwned2; set => SetField(ref _personPercentOfBusinessOwned2, value); }
/// <summary>
/// Freddie Mac MI Premium Source [CASASRN.X158]
/// </summary>
public StringEnumValue<PremiumSource> PremiumSource { get => _premiumSource; set => SetField(ref _premiumSource, value); }
/// <summary>
/// Freddie Mac Total Present Housing Expense [CASASRN.X16]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? PresentHousingExpense { get => _presentHousingExpense; set => SetField(ref _presentHousingExpense, value); }
/// <summary>
/// Freddie Mac Lender Processing Point [CASASRN.X107]
/// </summary>
public StringEnumValue<ProcessingPoint> ProcessingPoint { get => _processingPoint; set => SetField(ref _processingPoint, value); }
/// <summary>
/// Freddie Mac Lender Property Type [CASASRN.X14]
/// </summary>
public StringEnumValue<FreddieMacPropertyType> PropertyType { get => _propertyType; set => SetField(ref _propertyType, value); }
/// <summary>
/// Freddie Mac Lender Loan Purpose [CASASRN.X29]
/// </summary>
public StringEnumValue<FreddieMacPurposeOfLoan> PurposeOfLoan { get => _purposeOfLoan; set => SetField(ref _purposeOfLoan, value); }
/// <summary>
/// Freddie Mac MI Renewal Option [CASASRN.X150]
/// </summary>
public StringEnumValue<RenewalOption> RenewalOption { get => _renewalOption; set => SetField(ref _renewalOption, value); }
/// <summary>
/// Freddie Mac MI Renewal Type [CASASRN.X148]
/// </summary>
public StringEnumValue<RenewalType> RenewalType { get => _renewalType; set => SetField(ref _renewalType, value); }
/// <summary>
/// Freddie Mac Lender Requiredd Doc Type [CASASRN.X144]
/// </summary>
public StringEnumValue<RequiredDocumentType> RequiredDocumentType { get => _requiredDocumentType; set => SetField(ref _requiredDocumentType, value); }
/// <summary>
/// Freddie Mac Total Reserves [CASASRN.X78]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? Reserves { get => _reserves; set => SetField(ref _reserves, value); }
/// <summary>
/// Freddie Mac Lender Retail Loan [CASASRN.X77]
/// </summary>
[LoanFieldProperty(OptionsJson = "{\"Y\":\"Retail loan\"}")]
public bool? RetailLoanIndicator { get => _retailLoanIndicator; set => SetField(ref _retailLoanIndicator, value); }
/// <summary>
/// Freddie Mac Risk Class [CASASRN.X98]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public StringEnumValue<FreddieMacRiskClass> RiskClass { get => _riskClass; set => SetField(ref _riskClass, value); }
/// <summary>
/// Freddie Mac Order Risk Grade Eval Source [CASASRN.X173]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public StringEnumValue<RiskGradeEvaluationType> RiskGradeEvaluationType { get => _riskGradeEvaluationType; set => SetField(ref _riskGradeEvaluationType, value); }
/// <summary>
/// Freddie Mac Lender Sales Concessions [CASASRN.X19]
/// </summary>
public decimal? SalesConcessions { get => _salesConcessions; set => SetField(ref _salesConcessions, value); }
/// <summary>
/// Freddie Mac Lender Secondary Finance [CASASRN.X112]
/// </summary>
public StringEnumValue<SecondaryFinancingType> SecondaryFinancingType { get => _secondaryFinancingType; set => SetField(ref _secondaryFinancingType, value); }
/// <summary>
/// Freddie Mac Lender 2nd Trust Pd on Closing [CASASRN.X30]
/// </summary>
[LoanFieldProperty(OptionsJson = "{\"Y\":\"Second Trust Paid on closing\"}")]
public bool? SecondTrustRefiIndicator { get => _secondTrustRefiIndicator; set => SetField(ref _secondTrustRefiIndicator, value); }
/// <summary>
/// Freddie Mac Lender Simulated PITI [CASASRN.X15]
/// </summary>
public decimal? SimulatedPITI { get => _simulatedPITI; set => SetField(ref _simulatedPITI, value); }
/// <summary>
/// Freddie Mac FHA/VA Info Houshld Size [CASASRN.X145]
/// </summary>
public string? SizeOfHousehold { get => _sizeOfHousehold; set => SetField(ref _sizeOfHousehold, value); }
/// <summary>
/// Freddie Mac Special Instructions 1 [CASASRN.X100]
/// </summary>
public string? SpecialInstruction1 { get => _specialInstruction1; set => SetField(ref _specialInstruction1, value); }
/// <summary>
/// Freddie Mac Special Instructions 2 [CASASRN.X101]
/// </summary>
public string? SpecialInstruction2 { get => _specialInstruction2; set => SetField(ref _specialInstruction2, value); }
/// <summary>
/// Freddie Mac Special Instructions 3 [CASASRN.X102]
/// </summary>
public string? SpecialInstruction3 { get => _specialInstruction3; set => SetField(ref _specialInstruction3, value); }
/// <summary>
/// Freddie Mac Special Instructions 4 [CASASRN.X103]
/// </summary>
public string? SpecialInstruction4 { get => _specialInstruction4; set => SetField(ref _specialInstruction4, value); }
/// <summary>
/// Freddie Mac Special Instructions 5 [CASASRN.X104]
/// </summary>
public string? SpecialInstruction5 { get => _specialInstruction5; set => SetField(ref _specialInstruction5, value); }
/// <summary>
/// Freddie Mac Lender APN State [CASASRN.X18]
/// </summary>
public string? State { get => _state; set => SetField(ref _state, value); }
/// <summary>
/// Freddie Mac Transfer Loan to Conduit [CASASRN.X10]
/// </summary>
[LoanFieldProperty(ReadOnly = true, OptionsJson = "{\"Y\":\"Transfer Loan to Conduit\"}")]
public bool? TransferLoanToConduitIndicator { get => _transferLoanToConduitIndicator; set => SetField(ref _transferLoanToConduitIndicator, value); }
/// <summary>
/// Freddie Mac MI Yrs Coverage [CASASRN.X156]
/// </summary>
public StringEnumValue<YearsOfCoverage> YearsOfCoverage { get => _yearsOfCoverage; set => SetField(ref _yearsOfCoverage, value); }
}
}
| |
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Worker;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Xunit;
using System.Threading;
using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines;
namespace Microsoft.VisualStudio.Services.Agent.Tests.Worker
{
public sealed class JobExtensionL0
{
private class TestJobExtension : JobExtension
{
public override HostTypes HostType => HostTypes.None;
public override Type ExtensionType => typeof(IJobExtension);
public override void ConvertLocalPath(IExecutionContext context, string localPath, out string repoName, out string sourcePath)
{
repoName = "";
sourcePath = "";
}
public override IStep GetExtensionPostJobStep(IExecutionContext jobContext)
{
return null;
}
public override IStep GetExtensionPreJobStep(IExecutionContext jobContext)
{
return null;
}
public override string GetRootedPath(IExecutionContext context, string path)
{
return path;
}
public override void InitializeJobExtension(IExecutionContext context, IList<Pipelines.JobStep> steps, Pipelines.WorkspaceOptions workspace)
{
return;
}
}
private IExecutionContext _jobEc;
private JobInitializeResult _initResult = new JobInitializeResult();
private Pipelines.AgentJobRequestMessage _message;
private Mock<ITaskManager> _taskManager;
private Mock<IJobServerQueue> _jobServerQueue;
private Mock<IVstsAgentWebProxy> _proxy;
private Mock<IAgentCertificateManager> _cert;
private Mock<IConfigurationStore> _config;
private Mock<IPagingLogger> _logger;
private Mock<IExpressionManager> _express;
private Mock<IContainerOperationProvider> _containerProvider;
private CancellationTokenSource _tokenSource;
private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
{
var hc = new TestHostContext(this, testName);
_jobEc = new Agent.Worker.ExecutionContext();
_taskManager = new Mock<ITaskManager>();
_jobServerQueue = new Mock<IJobServerQueue>();
_config = new Mock<IConfigurationStore>();
_logger = new Mock<IPagingLogger>();
_proxy = new Mock<IVstsAgentWebProxy>();
_cert = new Mock<IAgentCertificateManager>();
_express = new Mock<IExpressionManager>();
_containerProvider = new Mock<IContainerOperationProvider>();
TaskRunner step1 = new TaskRunner();
TaskRunner step2 = new TaskRunner();
TaskRunner step3 = new TaskRunner();
TaskRunner step4 = new TaskRunner();
TaskRunner step5 = new TaskRunner();
TaskRunner step6 = new TaskRunner();
TaskRunner step7 = new TaskRunner();
TaskRunner step8 = new TaskRunner();
TaskRunner step9 = new TaskRunner();
TaskRunner step10 = new TaskRunner();
TaskRunner step11 = new TaskRunner();
TaskRunner step12 = new TaskRunner();
_logger.Setup(x => x.Setup(It.IsAny<Guid>(), It.IsAny<Guid>()));
var settings = new AgentSettings
{
AgentId = 1,
AgentName = "agent1",
ServerUrl = "https://test.visualstudio.com",
WorkFolder = "_work",
};
_config.Setup(x => x.GetSettings())
.Returns(settings);
_proxy.Setup(x => x.ProxyAddress)
.Returns(string.Empty);
if (_tokenSource != null)
{
_tokenSource.Dispose();
_tokenSource = null;
}
_tokenSource = new CancellationTokenSource();
TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
TimelineReference timeline = new Timeline(Guid.NewGuid());
JobEnvironment environment = new JobEnvironment();
environment.Variables[Constants.Variables.System.Culture] = "en-US";
environment.SystemConnection = new ServiceEndpoint()
{
Name = WellKnownServiceEndpointNames.SystemVssConnection,
Url = new Uri("https://test.visualstudio.com"),
Authorization = new EndpointAuthorization()
{
Scheme = "Test",
}
};
environment.SystemConnection.Authorization.Parameters["AccessToken"] = "token";
List<TaskInstance> tasks = new List<TaskInstance>()
{
new TaskInstance()
{
InstanceId = Guid.NewGuid(),
DisplayName = "task1",
},
new TaskInstance()
{
InstanceId = Guid.NewGuid(),
DisplayName = "task2",
},
new TaskInstance()
{
InstanceId = Guid.NewGuid(),
DisplayName = "task3",
},
new TaskInstance()
{
InstanceId = Guid.NewGuid(),
DisplayName = "task4",
},
new TaskInstance()
{
InstanceId = Guid.NewGuid(),
DisplayName = "task5",
},
new TaskInstance()
{
InstanceId = Guid.NewGuid(),
DisplayName = "task6",
},
new TaskInstance()
{
InstanceId = Guid.NewGuid(),
DisplayName = "task7",
},
};
Guid JobId = Guid.NewGuid();
_message = Pipelines.AgentJobRequestMessageUtil.Convert(new AgentJobRequestMessage(plan, timeline, JobId, testName, testName, environment, tasks));
_initResult.PreJobSteps.Clear();
_initResult.JobSteps.Clear();
_initResult.PostJobStep.Clear();
_taskManager.Setup(x => x.DownloadAsync(It.IsAny<IExecutionContext>(), It.IsAny<IEnumerable<Pipelines.TaskStep>>()))
.Returns(Task.CompletedTask);
_taskManager.Setup(x => x.Load(It.Is<Pipelines.TaskStep>(t => t.DisplayName == "task1")))
.Returns(new Definition()
{
Data = new DefinitionData()
{
PreJobExecution = null,
Execution = new ExecutionData(),
PostJobExecution = null,
},
});
_taskManager.Setup(x => x.Load(It.Is<Pipelines.TaskStep>(t => t.DisplayName == "task2")))
.Returns(new Definition()
{
Data = new DefinitionData()
{
PreJobExecution = new ExecutionData(),
Execution = new ExecutionData(),
PostJobExecution = new ExecutionData(),
},
});
_taskManager.Setup(x => x.Load(It.Is<Pipelines.TaskStep>(t => t.DisplayName == "task3")))
.Returns(new Definition()
{
Data = new DefinitionData()
{
PreJobExecution = new ExecutionData(),
Execution = null,
PostJobExecution = new ExecutionData(),
},
});
_taskManager.Setup(x => x.Load(It.Is<Pipelines.TaskStep>(t => t.DisplayName == "task4")))
.Returns(new Definition()
{
Data = new DefinitionData()
{
PreJobExecution = new ExecutionData(),
Execution = null,
PostJobExecution = null,
},
});
_taskManager.Setup(x => x.Load(It.Is<Pipelines.TaskStep>(t => t.DisplayName == "task5")))
.Returns(new Definition()
{
Data = new DefinitionData()
{
PreJobExecution = null,
Execution = null,
PostJobExecution = new ExecutionData(),
},
});
_taskManager.Setup(x => x.Load(It.Is<Pipelines.TaskStep>(t => t.DisplayName == "task6")))
.Returns(new Definition()
{
Data = new DefinitionData()
{
PreJobExecution = new ExecutionData(),
Execution = new ExecutionData(),
PostJobExecution = null,
},
});
_taskManager.Setup(x => x.Load(It.Is<Pipelines.TaskStep>(t => t.DisplayName == "task7")))
.Returns(new Definition()
{
Data = new DefinitionData()
{
PreJobExecution = null,
Execution = new ExecutionData(),
PostJobExecution = new ExecutionData(),
},
});
hc.SetSingleton(_taskManager.Object);
hc.SetSingleton(_config.Object);
hc.SetSingleton(_jobServerQueue.Object);
hc.SetSingleton(_proxy.Object);
hc.SetSingleton(_cert.Object);
hc.SetSingleton(_express.Object);
hc.SetSingleton(_containerProvider.Object);
hc.EnqueueInstance<IPagingLogger>(_logger.Object); // jobcontext logger
hc.EnqueueInstance<IPagingLogger>(_logger.Object); // init step logger
hc.EnqueueInstance<IPagingLogger>(_logger.Object); // step 1
hc.EnqueueInstance<IPagingLogger>(_logger.Object);
hc.EnqueueInstance<IPagingLogger>(_logger.Object);
hc.EnqueueInstance<IPagingLogger>(_logger.Object);
hc.EnqueueInstance<IPagingLogger>(_logger.Object);
hc.EnqueueInstance<IPagingLogger>(_logger.Object);
hc.EnqueueInstance<IPagingLogger>(_logger.Object);
hc.EnqueueInstance<IPagingLogger>(_logger.Object);
hc.EnqueueInstance<IPagingLogger>(_logger.Object);
hc.EnqueueInstance<IPagingLogger>(_logger.Object);
hc.EnqueueInstance<IPagingLogger>(_logger.Object);
hc.EnqueueInstance<IPagingLogger>(_logger.Object); // step 12
hc.EnqueueInstance<ITaskRunner>(step1);
hc.EnqueueInstance<ITaskRunner>(step2);
hc.EnqueueInstance<ITaskRunner>(step3);
hc.EnqueueInstance<ITaskRunner>(step4);
hc.EnqueueInstance<ITaskRunner>(step5);
hc.EnqueueInstance<ITaskRunner>(step6);
hc.EnqueueInstance<ITaskRunner>(step7);
hc.EnqueueInstance<ITaskRunner>(step8);
hc.EnqueueInstance<ITaskRunner>(step9);
hc.EnqueueInstance<ITaskRunner>(step10);
hc.EnqueueInstance<ITaskRunner>(step11);
hc.EnqueueInstance<ITaskRunner>(step12);
_jobEc.Initialize(hc);
_jobEc.InitializeJob(_message, _tokenSource.Token);
return hc;
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task JobExtensioBuildStepsList()
{
using (TestHostContext hc = CreateTestContext())
{
TestJobExtension testExtension = new TestJobExtension();
testExtension.Initialize(hc);
JobInitializeResult result = await testExtension.InitializeJob(_jobEc, _message);
var trace = hc.GetTrace();
trace.Info(string.Join(", ", result.PreJobSteps.Select(x => x.DisplayName)));
trace.Info(string.Join(", ", result.JobSteps.Select(x => x.DisplayName)));
trace.Info(string.Join(", ", result.PostJobStep.Select(x => x.DisplayName)));
Assert.Equal(4, result.PreJobSteps.Count);
Assert.Equal(4, result.JobSteps.Count);
Assert.Equal(4, result.PostJobStep.Count);
Assert.Equal("task2", result.PreJobSteps[0].DisplayName);
Assert.Equal("task3", result.PreJobSteps[1].DisplayName);
Assert.Equal("task4", result.PreJobSteps[2].DisplayName);
Assert.Equal("task6", result.PreJobSteps[3].DisplayName);
Assert.Equal("task1", result.JobSteps[0].DisplayName);
Assert.Equal("task2", result.JobSteps[1].DisplayName);
Assert.Equal("task6", result.JobSteps[2].DisplayName);
Assert.Equal("task7", result.JobSteps[3].DisplayName);
Assert.Equal("task7", result.PostJobStep[0].DisplayName);
Assert.Equal("task5", result.PostJobStep[1].DisplayName);
Assert.Equal("task3", result.PostJobStep[2].DisplayName);
Assert.Equal("task2", result.PostJobStep[3].DisplayName);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task JobExtensionIntraTaskState()
{
using (TestHostContext hc = CreateTestContext())
{
TestJobExtension testExtension = new TestJobExtension();
testExtension.Initialize(hc);
JobInitializeResult result = await testExtension.InitializeJob(_jobEc, _message);
var trace = hc.GetTrace();
trace.Info(string.Join(", ", result.PreJobSteps.Select(x => x.DisplayName)));
trace.Info(string.Join(", ", result.JobSteps.Select(x => x.DisplayName)));
trace.Info(string.Join(", ", result.PostJobStep.Select(x => x.DisplayName)));
Assert.Equal(4, result.PreJobSteps.Count);
Assert.Equal(4, result.JobSteps.Count);
Assert.Equal(4, result.PostJobStep.Count);
result.PreJobSteps[0].ExecutionContext.TaskVariables.Set("state1", "value1", false);
Assert.Equal("value1", result.JobSteps[1].ExecutionContext.TaskVariables.Get("state1"));
Assert.Equal("value1", result.PostJobStep[3].ExecutionContext.TaskVariables.Get("state1"));
Assert.Null(result.JobSteps[0].ExecutionContext.TaskVariables.Get("state1"));
Assert.Null(result.PreJobSteps[1].ExecutionContext.TaskVariables.Get("state1"));
Assert.Null(result.PreJobSteps[2].ExecutionContext.TaskVariables.Get("state1"));
Assert.Null(result.PostJobStep[2].ExecutionContext.TaskVariables.Get("state1"));
Assert.Null(result.JobSteps[2].ExecutionContext.TaskVariables.Get("state1"));
Assert.Null(result.JobSteps[3].ExecutionContext.TaskVariables.Get("state1"));
}
}
#if OS_WINDOWS
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task JobExtensionManagementScriptStep()
{
using (TestHostContext hc = CreateTestContext())
{
hc.EnqueueInstance<IPagingLogger>(_logger.Object);
hc.EnqueueInstance<IPagingLogger>(_logger.Object);
Environment.SetEnvironmentVariable("VSTS_AGENT_INIT_INTERNAL_TEMP_HACK", "C:\\init.ps1");
Environment.SetEnvironmentVariable("VSTS_AGENT_CLEANUP_INTERNAL_TEMP_HACK", "C:\\clenup.ps1");
try
{
TestJobExtension testExtension = new TestJobExtension();
testExtension.Initialize(hc);
JobInitializeResult result = await testExtension.InitializeJob(_jobEc, _message);
var trace = hc.GetTrace();
trace.Info(string.Join(", ", result.PreJobSteps.Select(x => x.DisplayName)));
trace.Info(string.Join(", ", result.JobSteps.Select(x => x.DisplayName)));
trace.Info(string.Join(", ", result.PostJobStep.Select(x => x.DisplayName)));
Assert.Equal(5, result.PreJobSteps.Count);
Assert.Equal(4, result.JobSteps.Count);
Assert.Equal(5, result.PostJobStep.Count);
Assert.True(result.PreJobSteps[0] is ManagementScriptStep);
Assert.True(result.PostJobStep[4] is ManagementScriptStep);
Assert.Equal(result.PreJobSteps[0].DisplayName, "Agent Initialization");
Assert.Equal(result.PostJobStep[4].DisplayName, "Agent Cleanup");
}
finally
{
Environment.SetEnvironmentVariable("VSTS_AGENT_INIT_INTERNAL_TEMP_HACK", "");
Environment.SetEnvironmentVariable("VSTS_AGENT_CLEANUP_INTERNAL_TEMP_HACK", "");
}
}
}
#endif
}
}
| |
//-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
// Vector Light State
new GFXStateBlockData( AL_VectorLightState )
{
blendDefined = true;
blendEnable = true;
blendSrc = GFXBlendOne;
blendDest = GFXBlendOne;
blendOp = GFXBlendOpAdd;
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampPoint; // G-buffer
samplerStates[1] = SamplerClampPoint; // Shadow Map (Do not change this to linear, as all cards can not filter equally.)
samplerStates[2] = SamplerClampLinear; // SSAO Mask
samplerStates[3] = SamplerWrapPoint; // Random Direction Map
cullDefined = true;
cullMode = GFXCullNone;
stencilDefined = true;
stencilEnable = true;
stencilFailOp = GFXStencilOpKeep;
stencilZFailOp = GFXStencilOpKeep;
stencilPassOp = GFXStencilOpKeep;
stencilFunc = GFXCmpLess;
stencilRef = 0;
};
// Vector Light Material
new ShaderData( AL_VectorLightShader )
{
DXVertexShaderFile = "shaders/common/lighting/advanced/farFrustumQuadV.hlsl";
DXPixelShaderFile = "shaders/common/lighting/advanced/vectorLightP.hlsl";
OGLVertexShaderFile = "shaders/common/lighting/advanced/gl/farFrustumQuadV.glsl";
OGLPixelShaderFile = "shaders/common/lighting/advanced/gl/vectorLightP.glsl";
pixVersion = 3.0;
};
new CustomMaterial( AL_VectorLightMaterial )
{
shader = AL_VectorLightShader;
stateBlock = AL_VectorLightState;
sampler["prePassBuffer"] = "#prepass";
sampler["ShadowMap"] = "$dynamiclight";
sampler["ssaoMask"] = "#ssaoMask";
target = "lightinfo";
pixVersion = 3.0;
};
//------------------------------------------------------------------------------
// Convex-geometry light states
new GFXStateBlockData( AL_ConvexLightState )
{
blendDefined = true;
blendEnable = true;
blendSrc = GFXBlendOne;
blendDest = GFXBlendOne;
blendOp = GFXBlendOpAdd;
zDefined = true;
zEnable = true;
zWriteEnable = false;
zFunc = GFXCmpGreaterEqual;
samplersDefined = true;
samplerStates[0] = SamplerClampPoint; // G-buffer
samplerStates[1] = SamplerClampPoint; // Shadow Map (Do not use linear, these are perspective projections)
samplerStates[2] = SamplerClampLinear; // Cookie Map
samplerStates[3] = SamplerWrapPoint; // Random Direction Map
cullDefined = true;
cullMode = GFXCullCW;
stencilDefined = true;
stencilEnable = true;
stencilFailOp = GFXStencilOpKeep;
stencilZFailOp = GFXStencilOpKeep;
stencilPassOp = GFXStencilOpKeep;
stencilFunc = GFXCmpLess;
stencilRef = 0;
};
// Point Light Material
new ShaderData( AL_PointLightShader )
{
DXVertexShaderFile = "shaders/common/lighting/advanced/convexGeometryV.hlsl";
DXPixelShaderFile = "shaders/common/lighting/advanced/pointLightP.hlsl";
OGLVertexShaderFile = "shaders/common/lighting/advanced/gl/convexGeometryV.glsl";
OGLPixelShaderFile = "shaders/common/lighting/advanced/gl/pointLightP.glsl";
pixVersion = 3.0;
};
new CustomMaterial( AL_PointLightMaterial )
{
shader = AL_PointLightShader;
stateBlock = AL_ConvexLightState;
sampler["prePassBuffer"] = "#prepass";
sampler["shadowMap"] = "$dynamiclight";
sampler["cookieTex"] = "$dynamiclightmask";
target = "lightinfo";
pixVersion = 3.0;
};
// Spot Light Material
new ShaderData( AL_SpotLightShader )
{
DXVertexShaderFile = "shaders/common/lighting/advanced/convexGeometryV.hlsl";
DXPixelShaderFile = "shaders/common/lighting/advanced/spotLightP.hlsl";
OGLVertexShaderFile = "shaders/common/lighting/advanced/gl/convexGeometryV.glsl";
OGLPixelShaderFile = "shaders/common/lighting/advanced/gl/spotLightP.glsl";
pixVersion = 3.0;
};
new CustomMaterial( AL_SpotLightMaterial )
{
shader = AL_SpotLightShader;
stateBlock = AL_ConvexLightState;
sampler["prePassBuffer"] = "#prepass";
sampler["shadowMap"] = "$dynamiclight";
sampler["cookieTex"] = "$dynamiclightmask";
target = "lightinfo";
pixVersion = 3.0;
};
/// This material is used for generating prepass
/// materials for objects that do not have materials.
new Material( AL_DefaultPrePassMaterial )
{
// We need something in the first pass else it
// won't create a proper material instance.
//
// We use color here because some objects may not
// have texture coords in their vertex format...
// for example like terrain.
//
diffuseColor[0] = "1 1 1 1";
};
/// This material is used for generating shadow
/// materials for objects that do not have materials.
new Material( AL_DefaultShadowMaterial )
{
// We need something in the first pass else it
// won't create a proper material instance.
//
// We use color here because some objects may not
// have texture coords in their vertex format...
// for example like terrain.
//
diffuseColor[0] = "1 1 1 1";
// This is here mostly for terrain which uses
// this material to create its shadow material.
//
// At sunset/sunrise the sun is looking thru
// backsides of the terrain which often are not
// closed. By changing the material to be double
// sided we avoid holes in the shadowed geometry.
//
doubleSided = true;
};
// Particle System Point Light Material
new ShaderData( AL_ParticlePointLightShader )
{
DXVertexShaderFile = "shaders/common/lighting/advanced/particlePointLightV.hlsl";
DXPixelShaderFile = "shaders/common/lighting/advanced/particlePointLightP.hlsl";
OGLVertexShaderFile = "shaders/common/lighting/advanced/gl/convexGeometryV.glsl";
OGLPixelShaderFile = "shaders/common/lighting/advanced/gl/pointLightP.glsl";
pixVersion = 3.0;
};
new CustomMaterial( AL_ParticlePointLightMaterial )
{
shader = AL_ParticlePointLightShader;
stateBlock = AL_ConvexLightState;
sampler["prePassBuffer"] = "#prepass";
target = "lightinfo";
pixVersion = 3.0;
};
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using System.Threading;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.Events;
using osu.Framework.Input.States;
using osu.Framework.Platform;
using osu.Framework.Screens;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Scoring;
using osu.Game.Screens;
using osu.Game.Screens.Backgrounds;
using osu.Game.Screens.Play;
using osu.Game.Screens.Play.PlayerSettings;
using osu.Game.Screens.Ranking;
using osu.Game.Screens.Select;
using osu.Game.Tests.Beatmaps;
using osu.Game.Tests.Resources;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.Background
{
[TestFixture]
public class TestSceneUserDimBackgrounds : OsuManualInputManagerTestScene
{
private DummySongSelect songSelect;
private TestPlayerLoader playerLoader;
private LoadBlockingTestPlayer player;
private BeatmapManager manager;
private RulesetStore rulesets;
[BackgroundDependencyLoader]
private void load(GameHost host, AudioManager audio)
{
Dependencies.Cache(rulesets = new RulesetStore(ContextFactory));
Dependencies.Cache(manager = new BeatmapManager(LocalStorage, ContextFactory, rulesets, null, audio, Resources, host, Beatmap.Default));
Dependencies.Cache(new OsuConfigManager(LocalStorage));
manager.Import(TestResources.GetQuickTestBeatmapForImport()).Wait();
Beatmap.SetDefault();
}
[SetUp]
public virtual void SetUp() => Schedule(() =>
{
var stack = new OsuScreenStack { RelativeSizeAxes = Axes.Both };
Child = stack;
stack.Push(songSelect = new DummySongSelect());
});
/// <summary>
/// User settings should always be ignored on song select screen.
/// </summary>
[Test]
public void TestUserSettingsIgnoredOnSongSelect()
{
setupUserSettings();
AddUntilStep("Screen is undimmed", () => songSelect.IsBackgroundUndimmed());
AddUntilStep("Screen using background blur", () => songSelect.IsBackgroundBlur());
performFullSetup();
AddStep("Exit to song select", () => player.Exit());
AddUntilStep("Screen is undimmed", () => songSelect.IsBackgroundUndimmed());
AddUntilStep("Screen using background blur", () => songSelect.IsBackgroundBlur());
}
/// <summary>
/// Check if <see cref="PlayerLoader"/> properly triggers the visual settings preview when a user hovers over the visual settings panel.
/// </summary>
[Test]
public void TestPlayerLoaderSettingsHover()
{
setupUserSettings();
AddStep("Start player loader", () => songSelect.Push(playerLoader = new TestPlayerLoader(player = new LoadBlockingTestPlayer { BlockLoad = true })));
AddUntilStep("Wait for Player Loader to load", () => playerLoader?.IsLoaded ?? false);
AddAssert("Background retained from song select", () => songSelect.IsBackgroundCurrent());
AddStep("Trigger background preview", () =>
{
InputManager.MoveMouseTo(playerLoader.ScreenPos);
InputManager.MoveMouseTo(playerLoader.VisualSettingsPos);
});
AddUntilStep("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied());
AddStep("Stop background preview", () => InputManager.MoveMouseTo(playerLoader.ScreenPos));
AddUntilStep("Screen is undimmed and user blur removed", () => songSelect.IsBackgroundUndimmed() && songSelect.CheckBackgroundBlur(playerLoader.ExpectedBackgroundBlur));
}
/// <summary>
/// In the case of a user triggering the dim preview the instant player gets loaded, then moving the cursor off of the visual settings:
/// The OnHover of PlayerLoader will trigger, which could potentially cause visual settings to be unapplied unless checked for in PlayerLoader.
/// We need to check that in this scenario, the dim and blur is still properly applied after entering player.
/// </summary>
[Test]
public void TestPlayerLoaderTransition()
{
performFullSetup();
AddStep("Trigger hover event", () => playerLoader.TriggerOnHover());
AddAssert("Background retained from song select", () => songSelect.IsBackgroundCurrent());
AddUntilStep("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied());
}
/// <summary>
/// Make sure the background is fully invisible (Alpha == 0) when the background should be disabled by the storyboard.
/// </summary>
[Test]
public void TestStoryboardBackgroundVisibility()
{
performFullSetup();
AddAssert("Background retained from song select", () => songSelect.IsBackgroundCurrent());
createFakeStoryboard();
AddStep("Enable Storyboard", () =>
{
player.ReplacesBackground.Value = true;
player.StoryboardEnabled.Value = true;
});
AddUntilStep("Background is invisible, storyboard is visible", () => songSelect.IsBackgroundInvisible() && player.IsStoryboardVisible);
AddStep("Disable Storyboard", () =>
{
player.ReplacesBackground.Value = false;
player.StoryboardEnabled.Value = false;
});
AddUntilStep("Background is visible, storyboard is invisible", () => songSelect.IsBackgroundVisible() && !player.IsStoryboardVisible);
}
/// <summary>
/// When exiting player, the screen that it suspends/exits to needs to have a fully visible (Alpha == 1) background.
/// </summary>
[Test]
public void TestStoryboardTransition()
{
performFullSetup();
createFakeStoryboard();
AddStep("Exit to song select", () => player.Exit());
AddUntilStep("Background is visible", () => songSelect.IsBackgroundVisible());
}
/// <summary>
/// Ensure <see cref="UserDimContainer"/> is properly accepting user-defined visual changes for a background.
/// </summary>
[Test]
public void TestDisableUserDimBackground()
{
performFullSetup();
AddUntilStep("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied());
AddStep("Disable user dim", () => songSelect.IgnoreUserSettings.Value = true);
AddUntilStep("Screen is undimmed and user blur removed", () => songSelect.IsBackgroundUndimmed() && songSelect.IsUserBlurDisabled());
AddStep("Enable user dim", () => songSelect.IgnoreUserSettings.Value = false);
AddUntilStep("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied());
}
/// <summary>
/// Ensure <see cref="UserDimContainer"/> is properly accepting user-defined visual changes for a storyboard.
/// </summary>
[Test]
public void TestDisableUserDimStoryboard()
{
performFullSetup();
createFakeStoryboard();
AddStep("Enable Storyboard", () =>
{
player.ReplacesBackground.Value = true;
player.StoryboardEnabled.Value = true;
});
AddStep("Enable user dim", () => player.DimmableStoryboard.IgnoreUserSettings.Value = false);
AddStep("Set dim level to 1", () => songSelect.DimLevel.Value = 1f);
AddUntilStep("Storyboard is invisible", () => !player.IsStoryboardVisible);
AddStep("Disable user dim", () => player.DimmableStoryboard.IgnoreUserSettings.Value = true);
AddUntilStep("Storyboard is visible", () => player.IsStoryboardVisible);
}
[Test]
public void TestStoryboardIgnoreUserSettings()
{
performFullSetup();
createFakeStoryboard();
AddStep("Enable replacing background", () => player.ReplacesBackground.Value = true);
AddUntilStep("Storyboard is invisible", () => !player.IsStoryboardVisible);
AddUntilStep("Background is visible", () => songSelect.IsBackgroundVisible());
AddStep("Ignore user settings", () =>
{
player.ApplyToBackground(b => b.IgnoreUserSettings.Value = true);
player.DimmableStoryboard.IgnoreUserSettings.Value = true;
});
AddUntilStep("Storyboard is visible", () => player.IsStoryboardVisible);
AddUntilStep("Background is invisible", () => songSelect.IsBackgroundInvisible());
AddStep("Disable background replacement", () => player.ReplacesBackground.Value = false);
AddUntilStep("Storyboard is visible", () => player.IsStoryboardVisible);
AddUntilStep("Background is visible", () => songSelect.IsBackgroundVisible());
}
/// <summary>
/// Check if the visual settings container retains dim and blur when pausing
/// </summary>
[Test]
public void TestPause()
{
performFullSetup(true);
AddStep("Pause", () => player.Pause());
AddUntilStep("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied());
AddStep("Unpause", () => player.Resume());
AddUntilStep("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied());
}
/// <summary>
/// Check if the visual settings container removes user dim when suspending <see cref="Player"/> for <see cref="ResultsScreen"/>
/// </summary>
[Test]
public void TestTransition()
{
performFullSetup();
FadeAccessibleResults results = null;
AddStep("Transition to Results", () => player.Push(results = new FadeAccessibleResults(new ScoreInfo
{
User = new APIUser { Username = "osu!" },
BeatmapInfo = new TestBeatmap(Ruleset.Value).BeatmapInfo,
Ruleset = Ruleset.Value,
})));
AddUntilStep("Wait for results is current", () => results.IsCurrentScreen());
AddUntilStep("Screen is undimmed, original background retained", () =>
songSelect.IsBackgroundUndimmed() && songSelect.IsBackgroundCurrent() && songSelect.CheckBackgroundBlur(results.ExpectedBackgroundBlur));
}
/// <summary>
/// Check if hovering on the visual settings dialogue after resuming from player still previews the background dim.
/// </summary>
[Test]
public void TestResumeFromPlayer()
{
performFullSetup();
AddStep("Move mouse to Visual Settings", () => InputManager.MoveMouseTo(playerLoader.VisualSettingsPos));
AddStep("Resume PlayerLoader", () => player.Restart());
AddUntilStep("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied());
AddStep("Move mouse to center of screen", () => InputManager.MoveMouseTo(playerLoader.ScreenPos));
AddUntilStep("Screen is undimmed and user blur removed", () => songSelect.IsBackgroundUndimmed() && songSelect.CheckBackgroundBlur(playerLoader.ExpectedBackgroundBlur));
}
private void createFakeStoryboard() => AddStep("Create storyboard", () =>
{
player.StoryboardEnabled.Value = false;
player.ReplacesBackground.Value = false;
player.DimmableStoryboard.Add(new OsuSpriteText
{
Size = new Vector2(500, 50),
Alpha = 1,
Colour = Color4.White,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Text = "THIS IS A STORYBOARD",
Font = new FontUsage(size: 50)
});
});
private void performFullSetup(bool allowPause = false)
{
setupUserSettings();
AddStep("Start player loader", () => songSelect.Push(playerLoader = new TestPlayerLoader(player = new LoadBlockingTestPlayer(allowPause))));
AddUntilStep("Wait for Player Loader to load", () => playerLoader.IsLoaded);
AddStep("Move mouse to center of screen", () => InputManager.MoveMouseTo(playerLoader.ScreenPos));
AddUntilStep("Wait for player to load", () => player.IsLoaded);
}
private void setupUserSettings()
{
AddUntilStep("Song select is current", () => songSelect.IsCurrentScreen());
AddUntilStep("Song select has selection", () => songSelect.Carousel?.SelectedBeatmapInfo != null);
AddStep("Set default user settings", () =>
{
SelectedMods.Value = SelectedMods.Value.Concat(new[] { new OsuModNoFail() }).ToArray();
songSelect.DimLevel.Value = 0.7f;
songSelect.BlurLevel.Value = 0.4f;
});
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
rulesets?.Dispose();
}
private class DummySongSelect : PlaySongSelect
{
private FadeAccessibleBackground background;
protected override BackgroundScreen CreateBackground()
{
background = new FadeAccessibleBackground(Beatmap.Value);
IgnoreUserSettings.BindTo(background.IgnoreUserSettings);
return background;
}
public readonly Bindable<bool> IgnoreUserSettings = new Bindable<bool>();
public readonly Bindable<double> DimLevel = new BindableDouble();
public readonly Bindable<double> BlurLevel = new BindableDouble();
public new BeatmapCarousel Carousel => base.Carousel;
[BackgroundDependencyLoader]
private void load(OsuConfigManager config)
{
config.BindWith(OsuSetting.DimLevel, DimLevel);
config.BindWith(OsuSetting.BlurLevel, BlurLevel);
}
public bool IsBackgroundDimmed() => background.CurrentColour == OsuColour.Gray(1f - background.CurrentDim);
public bool IsBackgroundUndimmed() => background.CurrentColour == Color4.White;
public bool IsUserBlurApplied() => background.CurrentBlur == new Vector2((float)BlurLevel.Value * BackgroundScreenBeatmap.USER_BLUR_FACTOR);
public bool IsUserBlurDisabled() => background.CurrentBlur == new Vector2(0);
public bool IsBackgroundInvisible() => background.CurrentAlpha == 0;
public bool IsBackgroundVisible() => background.CurrentAlpha == 1;
public bool IsBackgroundBlur() => background.CurrentBlur == new Vector2(BACKGROUND_BLUR);
public bool CheckBackgroundBlur(Vector2 expected) => background.CurrentBlur == expected;
/// <summary>
/// Make sure every time a screen gets pushed, the background doesn't get replaced
/// </summary>
/// <returns>Whether or not the original background (The one created in DummySongSelect) is still the current background</returns>
public bool IsBackgroundCurrent() => background?.IsCurrentScreen() == true;
}
private class FadeAccessibleResults : ResultsScreen
{
public FadeAccessibleResults(ScoreInfo score)
: base(score, true)
{
}
protected override BackgroundScreen CreateBackground() => new FadeAccessibleBackground(Beatmap.Value);
public Vector2 ExpectedBackgroundBlur => new Vector2(BACKGROUND_BLUR);
}
private class LoadBlockingTestPlayer : TestPlayer
{
protected override BackgroundScreen CreateBackground() =>
new FadeAccessibleBackground(Beatmap.Value);
public override void OnEntering(IScreen last)
{
base.OnEntering(last);
ApplyToBackground(b => ReplacesBackground.BindTo(b.StoryboardReplacesBackground));
}
public new DimmableStoryboard DimmableStoryboard => base.DimmableStoryboard;
// Whether or not the player should be allowed to load.
public bool BlockLoad;
public Bindable<bool> StoryboardEnabled;
public readonly Bindable<bool> ReplacesBackground = new Bindable<bool>();
public readonly Bindable<bool> IsPaused = new Bindable<bool>();
public LoadBlockingTestPlayer(bool allowPause = true)
: base(allowPause)
{
}
public bool IsStoryboardVisible => DimmableStoryboard.ContentDisplayed;
[BackgroundDependencyLoader]
private void load(OsuConfigManager config, CancellationToken token)
{
while (BlockLoad && !token.IsCancellationRequested)
Thread.Sleep(1);
StoryboardEnabled = config.GetBindable<bool>(OsuSetting.ShowStoryboard);
DrawableRuleset.IsPaused.BindTo(IsPaused);
}
}
private class TestPlayerLoader : PlayerLoader
{
private FadeAccessibleBackground background;
public VisualSettings VisualSettingsPos => VisualSettings;
public BackgroundScreen ScreenPos => background;
public TestPlayerLoader(Player player)
: base(() => player)
{
}
public void TriggerOnHover() => OnHover(new HoverEvent(new InputState()));
public Vector2 ExpectedBackgroundBlur => new Vector2(BACKGROUND_BLUR);
protected override BackgroundScreen CreateBackground() => background = new FadeAccessibleBackground(Beatmap.Value);
}
private class FadeAccessibleBackground : BackgroundScreenBeatmap
{
protected override DimmableBackground CreateFadeContainer() => dimmable = new TestDimmableBackground { RelativeSizeAxes = Axes.Both };
public Color4 CurrentColour => dimmable.CurrentColour;
public float CurrentAlpha => dimmable.CurrentAlpha;
public float CurrentDim => dimmable.DimLevel;
public Vector2 CurrentBlur => Background?.BlurSigma ?? Vector2.Zero;
private TestDimmableBackground dimmable;
public FadeAccessibleBackground(WorkingBeatmap beatmap)
: base(beatmap)
{
}
}
private class TestDimmableBackground : BackgroundScreenBeatmap.DimmableBackground
{
public Color4 CurrentColour => Content.Colour;
public float CurrentAlpha => Content.Alpha;
public new float DimLevel => base.DimLevel;
}
}
}
| |
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using ToolKit.Syslog;
using Xunit;
namespace UnitTests.Syslog
{
[SuppressMessage(
"StyleCop.CSharp.DocumentationRules",
"SA1600:ElementsMustBeDocumented",
Justification = "Test Suites do not need XML Documentation.")]
public class SyslogClientTests
{
private static Random random = new Random();
[Fact]
public void IncludeProcessInfo_Should_AcceptSettingToFalse()
{
// Arrange
var client = new SyslogClient();
// Act
client.IncludeProcessInfo = false;
// Assert
Assert.False(client.IncludeProcessInfo);
}
[Fact]
public void IncludeProcessInfo_Should_HaveDefaultValue()
{
// Arrange & Act
var client = new SyslogClient();
// Assert
Assert.True(client.IncludeProcessInfo);
}
[Fact]
public void Port_Should_AcceptProperPortNumbers()
{
// Arrange
var client = new SyslogClient();
// Act
client.Port = 8514;
// Assert
Assert.Equal(8514, client.Port);
}
[Fact]
public void Port_Should_HaveDefaultValue()
{
// Arrange & Act
var client = new SyslogClient();
// Assert
Assert.Equal(514, client.Port);
}
[Fact]
public void Port_Should_HaveProvidedValue()
{
// Arrange & Act
var client = new SyslogClient("syslog.contoso.com", 8514);
// Assert
Assert.Equal(8514, client.Port);
}
[Fact]
public void Port_Should_ThrowArgumentOutOfRangeException_When_AttemptingToSetTo65536()
{
// Arrange
var client = new SyslogClient();
// Act & Assert
Assert.Throws<ArgumentOutOfRangeException>(() => client.Port = 65536);
}
[Fact]
public void Port_Should_ThrowArgumentOutOfRangeException_When_AttemptingToSetToNegative()
{
// Arrange
var client = new SyslogClient();
// Act & Assert
Assert.Throws<ArgumentOutOfRangeException>(() => client.Port = -1);
}
[Fact]
public void Send_Should_CommunicateCorrectly_When_NotIncludingProcessInfo()
{
// Arrange
var expected = @"\<\d+\>\S{3}\s\d+\s\d+\:\d+\:\d+\s\S+\s[^\[]+$";
var port = random.Next(49152, 65535);
var client = new SyslogClient()
{
Port = port,
IncludeProcessInfo = false
};
var message = new Message("Unit Test Are Awesome!");
var server = new MockUdpServer(port);
// Act
client.Send(message);
while (!server.Done)
{
Thread.Sleep(100); // Multi-threaded programming will bite you!
}
// Assert
Assert.Matches(expected, server.MessageRecieved);
}
[Fact]
public void Send_Should_CommunicateCorrectlyOverTcp()
{
// Arrange
var expected = @"\<\d+\>\S{3}\s\d+\s\d+\:\d+\:\d+\s\S+\s\S+\[\d+\]\:\s.*";
var port = random.Next(49152, 65535);
var client = new SyslogClient()
{
Port = port
}.UseTcp();
var message = new Message("Unit Test Are Awesome!");
var server = new MockTcpServer(port);
// Act
client.Send(message);
while (!server.Done)
{
Thread.Sleep(100); // Multi-threaded programming will bite you!
}
// Assert
Assert.Matches(expected, server.MessageRecieved);
}
[Fact]
public void Send_Should_CommunicateCorrectlyOverUdp()
{
// Arrange
var expected = @"\<\d+\>\S{3}\s\d+\s\d+\:\d+\:\d+\s\S+\s\S+\[\d+\]\:\s.*";
var port = random.Next(49152, 65535);
var client = new SyslogClient()
{
Port = port
}.UseUdp();
var message = new Message("Unit Test Are Awesome!");
var server = new MockUdpServer(port);
// Act
client.Send(message);
while (!server.Done)
{
Thread.Sleep(100); // Multi-threaded programming will bite you!
}
// Assert
Assert.Matches(expected, server.MessageRecieved);
}
[Fact]
public void Server_Should_AcceptProperServerName()
{
// Arrange
var client = new SyslogClient();
// Act
client.Server = "syslogserver.contoso.com";
// Assert
Assert.Equal("syslogserver.contoso.com", client.Server);
}
[Fact]
public void Server_Should_HaveDefaultValue()
{
// Arrange
var client = new SyslogClient();
// Act & Assert
Assert.Equal("127.0.0.1", client.Server);
}
[Fact]
public void Server_Should_HaveProvidedValue()
{
// Arrange
var client = new SyslogClient("syslogserver.contoso.com");
// Act & Assert
Assert.Equal("syslogserver.contoso.com", client.Server);
}
[Fact]
public void Server_Should_ThrowArgumentException_When_AttemptingToSetToEmptyString()
{
// Arrange
var client = new SyslogClient();
// Act & Assert
Assert.Throws<ArgumentException>(() => client.Server = string.Empty);
}
[Fact]
public void Server_Should_ThrowArgumentNullException_When_AttemptingToSetToNull()
{
// Arrange
var client = new SyslogClient();
// Act & Assert
Assert.Throws<ArgumentNullException>(() => client.Server = null);
}
[Fact]
public void TruncateTagIfNeeded_Should_TruncateWhenProcessNameTooLong()
{
// Arrange
const string expected = "12345678901234567890123456[5434]: ";
const string tag = "12345678901234567890123456789012345";
const string id = "[5434]";
// Act
var actual = SyslogClient.TruncateTagIfNeeded(tag, id);
// Assert
Assert.Equal(expected, actual);
}
private class MockTcpServer
{
private readonly TcpListener _server;
public MockTcpServer(int port)
{
_server = new TcpListener(IPAddress.Loopback, port);
_server.Start();
_server.BeginAcceptTcpClient(Listen, _server);
}
public bool Done { get; set; }
public string MessageRecieved { get; set; }
private void Listen(IAsyncResult result)
{
var client = _server.EndAcceptTcpClient(result);
var stream = client.GetStream();
using (var reader = new StreamReader(stream, Encoding.ASCII))
{
MessageRecieved = reader.ReadToEnd();
}
Done = true;
}
}
private class MockUdpServer
{
private readonly UdpClient _server;
private IPEndPoint _endpoint;
public MockUdpServer(int port)
{
_endpoint = new IPEndPoint(IPAddress.Loopback, port);
_server = new UdpClient(_endpoint);
_server.BeginReceive(Listen, _server);
}
public bool Done { get; set; }
public string MessageRecieved { get; set; }
private void Listen(IAsyncResult result)
{
var message = _server.EndReceive(result, ref _endpoint);
MessageRecieved = Encoding.ASCII.GetString(message).Trim('\0').Trim('\n');
Done = true;
}
}
}
}
| |
// Copyright (c) 2017 Andrew Vardeman. Published under the MIT license.
// See license.txt in the FileSharper distribution or repository for the
// full text of the license.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
namespace FileSharperCore
{
public class SharperEngine
{
public RunInfo RunInfo { get; set; }
public IFileSource FileSource { get; set; }
public ICondition Condition { get; set; }
public IFieldSource[] FieldSources { get; set; }
public IProcessor[] TestedProcessors { get; set; }
public IProcessor[] MatchedProcessors { get; set; }
public Timer Timer { get; set; }
public int MaxToMatch { get; set; }
public bool StopRequested
{
get
{
lock (m_Mutex)
{
if (RunInfo == null)
{
return false;
}
return RunInfo.StopRequested;
}
}
}
private object m_Mutex = new object();
public SharperEngine(IFileSource fileSource, ICondition condition, IFieldSource[] fieldSources,
IProcessor[] testedProcessors, IProcessor[] matchedProcessors, int maxToMatch)
{
FileSource = fileSource;
Condition = condition;
FieldSources = fieldSources;
TestedProcessors = testedProcessors;
MatchedProcessors = matchedProcessors;
MaxToMatch = maxToMatch;
}
public void Run(CancellationToken token, IProgress<string> fileSourceProgress,
IProgress<IEnumerable<FileProgressInfo>> testedProgress,
IProgress<IEnumerable<FileProgressInfo>> matchedProgress,
IProgress<IEnumerable<ExceptionInfo>> exceptionProgress,
IProgress<bool> completeProgress, TimeSpan reportInterval)
{
int numMatched = 0;
DateTime lastExceptionReportTime = DateTime.Now;
DateTime lastTestedReportTime = DateTime.Now;
DateTime lastMatchedReportTime = DateTime.Now;
try
{
if (fileSourceProgress == null)
{
fileSourceProgress = new Progress<string>(x => { });
}
if (testedProgress == null)
{
testedProgress = new Progress<IEnumerable<FileProgressInfo>>(x => { });
}
if (matchedProgress == null)
{
matchedProgress = new Progress<IEnumerable<FileProgressInfo>>(x => { });
}
if (exceptionProgress == null)
{
exceptionProgress = new Progress<IEnumerable<ExceptionInfo>>(x => { });
}
if (completeProgress == null)
{
completeProgress = new Progress<bool>(x => { });
}
lock (m_Mutex)
{
RunInfo = new RunInfo(FileSource, Condition, FieldSources, TestedProcessors,
MatchedProcessors, MaxToMatch, token, fileSourceProgress, testedProgress,
matchedProgress, exceptionProgress, completeProgress);
TimeSpan interval = TimeSpan.FromMilliseconds(100);
Timer = new Timer(state => {
ReportFilesAndExceptions();
if (StopRequested)
{
Timer.Dispose();
}
}, null, interval, interval);
}
token.ThrowIfCancellationRequested();
FileSource.Init(RunInfo);
token.ThrowIfCancellationRequested();
Condition.Init(RunInfo);
token.ThrowIfCancellationRequested();
foreach (IFieldSource fieldSource in FieldSources)
{
token.ThrowIfCancellationRequested();
fieldSource.Init(RunInfo);
}
foreach (IProcessor processor in TestedProcessors)
{
token.ThrowIfCancellationRequested();
processor.Init(RunInfo);
}
foreach (IProcessor processor in MatchedProcessors)
{
token.ThrowIfCancellationRequested();
processor.Init(RunInfo);
}
}
catch (OperationCanceledException ex)
{
Cleanup(exceptionProgress);
throw ex;
}
catch(Exception ex)
{
Cleanup(exceptionProgress);
RunInfo.ExceptionInfos.Enqueue(new ExceptionInfo(ex));
ReportFilesAndExceptions();
completeProgress?.Report(false);
return;
}
try
{
foreach (FileInfo file in FileSource.Files)
{
token.ThrowIfCancellationRequested();
try
{
Dictionary<Type, IFileCache> caches = new Dictionary<Type, IFileCache>();
List<string> values = new List<string>();
MatchResult result = null;
MatchResultType matchResultType = MatchResultType.NotApplicable;
if (!file.Exists)
{
continue;
}
try
{
GetFileCaches(Condition, FieldSources, file, caches, exceptionProgress);
try
{
result = Condition.Matches(file, caches, token);
if (result?.Values != null)
{
values.AddRange(result.Values);
}
matchResultType = result == null ? MatchResultType.NotApplicable : result.Type;
}
catch (Exception ex) when (!(ex is OperationCanceledException))
{
RunInfo.ExceptionInfos.Enqueue(new ExceptionInfo(ex, file));
}
if (result != null)
{
foreach (IFieldSource fieldSource in FieldSources)
{
if (fieldSource != null)
{
try
{
string[] vals = fieldSource.GetValues(file, caches, token);
if (vals != null)
{
values.AddRange(vals);
}
}
catch (Exception ex) when (!(ex is OperationCanceledException))
{
RunInfo.ExceptionInfos.Enqueue(new ExceptionInfo(ex, file));
}
}
}
string[] allValues = values.ToArray();
RunInfo.TestedFileProgressInfos.Enqueue(new FileProgressInfo(file, result.Type, allValues));
RunProcessors(TestedProcessors, file, matchResultType, allValues);
if (result.Type == MatchResultType.Yes)
{
RunInfo.MatchedFileProgressInfos.Enqueue(new FileProgressInfo(file, result.Type, allValues));
RunProcessors(MatchedProcessors, file, matchResultType, allValues);
numMatched++;
}
}
}
finally
{
DisposeFileCaches(caches, RunInfo.ExceptionInfos);
}
}
catch (Exception ex) when (!(ex is OperationCanceledException))
{
RunInfo.ExceptionInfos.Enqueue(new ExceptionInfo(ex, file));
}
if (RunInfo.StopRequested || numMatched == MaxToMatch)
{
break;
}
}
AggregateProcessors(TestedProcessors);
AggregateProcessors(MatchedProcessors);
}
catch (Exception ex) when (!(ex is OperationCanceledException))
{
RunInfo.ExceptionInfos.Enqueue(new ExceptionInfo(ex));
}
finally
{
Cleanup(exceptionProgress);
}
ReportFilesAndExceptions();
completeProgress?.Report(false);
}
private void RunProcessors(IProcessor[] processors, FileInfo file,
MatchResultType matchResultType, string[] values)
{
FileInfo[] lastOutputs = new FileInfo[0];
foreach (IProcessor processor in processors)
{
RunInfo.CancellationToken.ThrowIfCancellationRequested();
try
{
ProcessInput whatToProcess = (processor.InputFileSource == InputFileSource.OriginalFile ?
ProcessInput.OriginalFile : ProcessInput.GeneratedFiles);
ProcessingResult result = processor?.Process(file, matchResultType, values,
lastOutputs ?? new FileInfo[0], whatToProcess, RunInfo.CancellationToken);
FileInfo[] outputFiles = result == null ? new FileInfo[0] : result.OutputFiles;
lastOutputs = outputFiles == null ? new FileInfo[0] : outputFiles;
}
catch (Exception ex) when (!(ex is OperationCanceledException))
{
lastOutputs = new FileInfo[0];
RunInfo.ExceptionInfos.Enqueue(new ExceptionInfo(ex, file));
}
}
}
private void AggregateProcessors(IProcessor[] processors)
{
foreach (IProcessor processor in processors)
{
RunInfo.CancellationToken.ThrowIfCancellationRequested();
try
{
processor?.ProcessAggregated(RunInfo.CancellationToken);
}
catch (Exception ex) when (!(ex is OperationCanceledException))
{
RunInfo.ExceptionInfos.Enqueue(new ExceptionInfo(ex, null));
}
}
}
private T[] DequeueToArray<T>(ConcurrentQueue<T> queue)
{
List<T> tmp = new List<T>();
T item;
while (queue.TryDequeue(out item))
{
tmp.Add(item);
}
return tmp.ToArray();
}
private void GetFileCaches(ICondition condition, IFieldSource[] fieldSources, FileInfo file,
Dictionary<Type, IFileCache> cacheLookup, IProgress<IEnumerable<ExceptionInfo>> exceptionProgress)
{
List<Type> cacheTypes = new List<Type>();
cacheTypes.AddRange(condition.CacheTypes);
foreach (IFieldSource fieldSource in fieldSources)
{
cacheTypes.AddRange(fieldSource.CacheTypes);
}
List<ExceptionInfo> exinfos = new List<ExceptionInfo>();
foreach (Type type in cacheTypes)
{
Type[] interfaces = type.GetInterfaces();
if (type == null || !interfaces.Contains(typeof(IFileCache)))
{
continue;
}
try
{
if (!cacheLookup.ContainsKey(type))
{
IFileCache cache = (IFileCache)Activator.CreateInstance(type);
cache.Load(file);
cacheLookup[type] = cache;
}
}
catch (Exception ex) when (!(ex is OperationCanceledException))
{
RunInfo.ExceptionInfos.Enqueue(new ExceptionInfo(ex, file));
}
}
}
private void ReportFilesAndExceptions()
{
lock (m_Mutex)
{
RunInfo.TestedProgress.Report(DequeueToArray(RunInfo.TestedFileProgressInfos));
RunInfo.MatchedProgress.Report(DequeueToArray(RunInfo.MatchedFileProgressInfos));
RunInfo.ExceptionProgress.Report(DequeueToArray(RunInfo.ExceptionInfos));
}
}
private void DisposeFileCaches(Dictionary<Type, IFileCache> cacheLookup, ConcurrentQueue<ExceptionInfo> exceptionInfos)
{
OperationCanceledException canceledException = null;
foreach (IFileCache cache in cacheLookup.Values)
{
try
{
cache?.Dispose();
}
catch (OperationCanceledException ex)
{
canceledException = ex;
}
catch (Exception ex)
{
exceptionInfos.Enqueue(new ExceptionInfo(ex));
}
}
if (canceledException != null)
{
throw canceledException;
}
}
private void Cleanup(IProgress<IEnumerable<ExceptionInfo>> exceptionProgress)
{
List<ExceptionInfo> exinfos = new List<ExceptionInfo>();
try
{
FileSource?.Cleanup();
}
catch (Exception ex)
{
RunInfo.ExceptionInfos.Enqueue(new ExceptionInfo(ex));
}
try
{
Condition?.Cleanup();
}
catch (Exception ex)
{
RunInfo.ExceptionInfos.Enqueue(new ExceptionInfo(ex));
}
foreach (IFieldSource fieldSource in FieldSources)
{
try
{
fieldSource?.Cleanup();
}
catch (Exception ex)
{
RunInfo.ExceptionInfos.Enqueue(new ExceptionInfo(ex));
}
}
foreach (IProcessor processor in TestedProcessors)
{
try
{
processor?.Cleanup();
}
catch (Exception ex)
{
RunInfo.ExceptionInfos.Enqueue(new ExceptionInfo(ex));
}
}
foreach (IProcessor processor in MatchedProcessors)
{
try
{
processor?.Cleanup();
}
catch (Exception ex)
{
RunInfo.ExceptionInfos.Enqueue(new ExceptionInfo(ex));
}
}
ReportFilesAndExceptions();
}
public void RequestStop()
{
lock (m_Mutex)
{
RunInfo runInfo = RunInfo;
if (runInfo != null)
{
runInfo.RequestStop();
}
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.CodeGeneration.IR.Transformations
{
using System;
using System.Collections.Generic;
using Microsoft.Zelig.Runtime.TypeSystem;
public static class StaticSingleAssignmentForm
{
//
// State
//
//
// Constructor Methods
//
//
// Helper Methods
//
public static bool ShouldTransformInto( ControlFlowGraphStateForCodeTransformation cfg )
{
return ComputeCandidatesForTransformIntoSSA( cfg ) != null;
}
//--//
public static void RemovePiOperators( ControlFlowGraphStateForCodeTransformation cfg )
{
cfg.TraceToFile( "RemovePiOperators-Pre" );
foreach(var op in cfg.FilterOperators< PiOperator >())
{
var opNew = SingleAssignmentOperator.New( op.DebugInfo, op.FirstResult, op.FirstArgument );
op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default );
}
cfg.TraceToFile( "RemovePiOperators-Post" );
}
public static void InsertPiOperators( ControlFlowGraphStateForCodeTransformation cfg )
{
cfg.TraceToFile( "InsertPiOperators-Pre" );
TypeSystemForCodeTransformation ts = cfg.TypeSystem;
foreach(var op in cfg.FilterOperators< ConditionCodeConditionalControlOperator >())
{
InsertPiOperators( ts, op );
}
cfg.TraceToFile( "InsertPiOperators-Post" );
}
private static void InsertPiOperators( TypeSystemForCodeTransformation ts ,
ConditionCodeConditionalControlOperator flowOp )
{
PiOperator.Relation relation = PiOperator.ConvertRelation( flowOp.Condition );
if(relation != PiOperator.Relation.Invalid)
{
CompareOperator cmpOp = flowOp.GetPreviousOperator() as CompareOperator;
if(cmpOp != null && cmpOp.FirstResult == flowOp.FirstArgument)
{
Expression exLeft = cmpOp.FirstArgument;
Expression exRight = cmpOp.SecondArgument;
//
// Generate the constraints for the "comparison is true" branch.
//
AddPiOperator( flowOp, flowOp.TargetBranchTaken, exLeft , exLeft, exRight, relation );
AddPiOperator( flowOp, flowOp.TargetBranchTaken, exRight, exLeft, exRight, relation );
//
// Generate the constraints for the "comparison is false" branch.
//
relation = PiOperator.NegateRelation( relation );
AddPiOperator( flowOp, flowOp.TargetBranchNotTaken, exLeft , exLeft, exRight, relation );
AddPiOperator( flowOp, flowOp.TargetBranchNotTaken, exRight, exLeft, exRight, relation );
}
}
}
private static void AddPiOperator( Operator opSrc ,
BasicBlock bbDst ,
Expression ex ,
Expression cmpLeft ,
Expression cmpRight ,
PiOperator.Relation cmpRelation )
{
VariableExpression var = ex as VariableExpression;
if(var != null)
{
//
// Make sure that we put the Pi operator in a basic block immediately dominated by the location of the comparison.
//
if(bbDst.Predecessors.Length > 1)
{
bbDst = opSrc.BasicBlock.InsertNewSuccessor( bbDst );
}
var opDst = FirstOperatorAfterPiOperators( bbDst, var );
if(opDst != null)
{
PiOperator opNew = PiOperator.New( opSrc.DebugInfo, var, var, cmpLeft, cmpRight, cmpRelation );
opDst.AddOperatorBefore( opNew );
}
}
}
private static Operator FirstOperatorAfterPiOperators( BasicBlock bb ,
VariableExpression var )
{
foreach(Operator op in bb.Operators)
{
if(var == null)
{
return op;
}
var pi = op as PiOperator;
if(pi == null)
{
return op;
}
if(pi.FirstArgument == var)
{
var = null; // Return the next operator.
}
}
throw TypeConsistencyErrorException.Create( "Cannot find non-PI operator in {0}", bb );
}
//--//
private static bool[] ComputeCandidatesForTransformIntoSSA( ControlFlowGraphStateForCodeTransformation cfg )
{
using(new PerformanceCounters.ContextualTiming( cfg, "ComputeCandidatesForTransformIntoSSA" ))
{
Operator[][] defChains = cfg.DataFlow_DefinitionChains;
BitVector[] liveness = cfg.DataFlow_LivenessAtBasicBlockEntry;
int varNum = defChains.Length;
//
// Are we already in SSA form?
//
// We need to convert into SSA form only if:
// 1) A variable is defined twice or more.
// 2) A variable is defined once and it's an argument.
//
bool[] candidate = new bool[varNum];
bool fShouldProcess = false;
for(int varIdx = 0; varIdx < varNum; varIdx++)
{
Operator[] defs = defChains[varIdx];
if(defs.Length > 1)
{
candidate[varIdx] = true;
fShouldProcess = true;
}
}
return fShouldProcess ? candidate : null;
}
}
public static bool ConvertInto( ControlFlowGraphStateForCodeTransformation cfg )
{
using(new PerformanceCounters.ContextualTiming( cfg, "ConvertIntoSSA" ))
{
cfg.TraceToFile( "ConvertInto-Pre" );
//
// To properly capture the dependencies between variables and exception handlers,
// we need to create a basic block boundary at each exception site.
//
SplitBasicBlocksAtExceptionSites.Execute( cfg );
using(cfg.GroupLock( cfg.LockSpanningTree () ,
cfg.LockUseDefinitionChains() ,
cfg.LockLiveness () ))
{
bool[] candidate = ComputeCandidatesForTransformIntoSSA( cfg );
if(candidate == null)
{
return false;
}
cfg.TraceToFile( "ConvertInto-Entry" );
using(cfg.LockDominance())
{
VariableExpression[] variables = cfg.DataFlow_SpanningTree_Variables;
Operator[][] defChains = cfg.DataFlow_DefinitionChains;
BitVector[] liveness = cfg.DataFlow_LivenessAtBasicBlockEntry;
int varNum = variables.Length;
GrowOnlySet< Operator > newPhis = SetFactory.NewWithReferenceEquality< Operator >();
//
// Compute Iterated Dominance Frontier for each variable assigned.
//
BasicBlock[] basicBlocks = cfg.DataFlow_SpanningTree_BasicBlocks;
BasicBlock[] immediateDominators = cfg.DataFlow_ImmediateDominators;
BitVector[] dominanceFrontier = cfg.DataFlow_DominanceFrontier;
int bbNum = basicBlocks.Length;
Operator[] phiInsertionOps = new Operator[bbNum];
//
// Insert Phi-operators.
//
BitVector vec = new BitVector( bbNum );
BitVector vecDF_N = new BitVector( bbNum );
BitVector vecDF_Nplus1 = new BitVector( bbNum );
for(int varIdx = 0; varIdx < varNum; varIdx++)
{
if(candidate[varIdx])
{
VariableExpression var = variables[varIdx];
Operator[] defs = defChains[varIdx];
vec.ClearAll();
//
// Build S
//
foreach(Operator op in defs)
{
vec.Set( op.BasicBlock.SpanningTreeIndex );
}
if(vec.Cardinality > 1)
{
//
// Compute DF^1(S)
//
vecDF_N.ClearAll();
foreach(int bbIdx in vec)
{
vecDF_N.OrInPlace( dominanceFrontier[bbIdx] );
}
//
// Build DF+(S), by computing DF^(N+1)(S) = DF(S union DF^N(S)).
//
while(true)
{
vecDF_Nplus1.ClearAll();
//
// DF(S)
//
foreach(int bbIdx in vec)
{
vecDF_Nplus1.OrInPlace( dominanceFrontier[bbIdx] );
}
//
// DF(DF^N(S))
//
foreach(int bbIdx in vecDF_N)
{
vecDF_Nplus1.OrInPlace( dominanceFrontier[bbIdx] );
}
if(vecDF_Nplus1 == vecDF_N)
{
break;
}
vecDF_N.Assign( vecDF_Nplus1 );
}
//
// For each node in DF+(S), where <var> is live at entry, add a phi operator.
//
foreach(int bbIdx in vecDF_N)
{
if(liveness[bbIdx][varIdx])
{
PhiOperator phiOp = PhiOperator.New( null, var );
newPhis.Insert( phiOp );
var phiInsertionOp = phiInsertionOps[bbIdx];
if(phiInsertionOp == null)
{
phiInsertionOp = basicBlocks[bbIdx].GetFirstDifferentOperator( typeof(PhiOperator) );
phiInsertionOps[bbIdx] = phiInsertionOp;
}
phiInsertionOp.AddOperatorBefore( phiOp );
}
}
}
}
}
//
// Rename variables.
//
using(new PerformanceCounters.ContextualTiming( cfg, "ProcessInDominatorTreeOrder" ))
{
ProcessInDominatorTreeOrder( cfg, basicBlocks, immediateDominators, variables, candidate, newPhis );
}
}
}
#if DEBUG
foreach(Operator[] defChainPost in cfg.DataFlow_DefinitionChains)
{
CHECKS.ASSERT( defChainPost.Length <= 1, "Found a variable still defined multiple times after SSA conversion" );
}
#endif
cfg.TraceToFile( "ConvertInto-Post" );
PurgeUselessPhiOperators( cfg );
cfg.TraceToFile( "ConvertInto-PostPurge" );
while(Transformations.SimplifyConditionCodeChecks.Execute( cfg ))
{
Transformations.RemoveDeadCode.Execute( cfg, false );
}
while(Transformations.CommonMethodRedundancyElimination.Execute( cfg ))
{
}
cfg.DropDeadVariables();
cfg.TraceToFile( "ConvertInto-Done" );
return true;
}
}
private static void PurgeUselessPhiOperators( ControlFlowGraphStateForCodeTransformation cfg )
{
Operator[] operators = cfg.DataFlow_SpanningTree_Operators;
VariableExpression[] variables = cfg.DataFlow_SpanningTree_Variables;
VariableExpression[] variablesMap = new VariableExpression[variables.Length];
bool fLoop = true;
bool fGot = false;
//
// In 'variablesMap', collect all the variables that are assigned through an identity phi operator.
//
while(fLoop)
{
fLoop = false;
foreach(Operator op in operators)
{
if(op is PhiOperator)
{
VariableExpression lhs = op.FirstResult;
if(variablesMap[lhs.SpanningTreeIndex] == null)
{
VariableExpression var = null;
foreach(Expression ex in op.Arguments)
{
VariableExpression rhs = ex as VariableExpression;
if(rhs != null)
{
VariableExpression rhsMapped = variablesMap[rhs.SpanningTreeIndex];
if(rhsMapped != null)
{
rhs = rhsMapped;
}
if(var == null)
{
var = rhs;
}
else if(var != rhs)
{
var = null;
break;
}
}
}
if(var != null)
{
//
// If other variables were mapped to 'lhs', update the mapping.
//
for(int varIdx = variablesMap.Length; --varIdx >= 0;)
{
if(variablesMap[varIdx] == lhs)
{
variablesMap[varIdx] = var;
}
}
variablesMap[lhs.SpanningTreeIndex] = var;
fLoop = true;
fGot = true;
}
}
}
}
}
if(fGot)
{
//
// We found some nilpotent phi operators, let's get rid of them.
// This reduces the number of variables we need to track.
//
foreach(Operator op in operators)
{
if(op is PhiOperator)
{
VariableExpression lhs = op.FirstResult;
if(lhs != null && variablesMap[lhs.SpanningTreeIndex] != null)
{
op.Delete();
}
else
{
foreach(Expression ex in op.Arguments)
{
var rhs = ex as VariableExpression;
if(rhs != null)
{
VariableExpression rhsMapped = variablesMap[rhs.SpanningTreeIndex];
if(rhsMapped != null)
{
op.SubstituteUsage( rhs, rhsMapped );
}
}
}
}
}
}
}
}
//--//
internal class BasicBlockState
{
//
// State
//
internal BasicBlock m_bb;
internal BasicBlockEdge[] m_successors;
internal PhiVariableExpression[] m_stackAtExit;
//
// Constructor Methods
//
internal BasicBlockState( BasicBlock bb )
{
m_bb = bb;
m_successors = bb.Successors;
}
}
private static void ProcessInDominatorTreeOrder( ControlFlowGraphStateForCodeTransformation cfg ,
BasicBlock[] basicBlocks ,
BasicBlock[] immediateDominators ,
VariableExpression[] variables ,
bool[] candidate ,
GrowOnlySet< Operator > newPhis )
{
int bbNum = basicBlocks.Length;
int varNum = variables .Length;
BasicBlockState[] bbStates = new BasicBlockState[bbNum];
Stack< BasicBlockState > pending = new Stack< BasicBlockState >( bbNum + 2 );
PhiVariableExpression[] stack = new PhiVariableExpression[varNum];
int [] renameHistory = new int [varNum];
int renameHistoryKey = 1;
//
// Process from the end of the spanning tree, so that the entry basic block will be at the top of the stack.
//
for(int idx = bbNum; --idx >= 0; )
{
BasicBlockState bbs = new BasicBlockState( basicBlocks[idx] );
bbStates[idx] = bbs;
pending.Push( bbs );
}
//
// Walk through the basic blocks, in dominator order, and update all the variables with corresponding phi versions.
//
while(pending.Count > 0)
{
BasicBlockState bbs = pending.Pop();
BasicBlock bb = bbs.m_bb;
int idx = bb.SpanningTreeIndex;
if(bbs.m_stackAtExit != null)
{
//
// Already processed.
//
continue;
}
PhiVariableExpression[] localStack;
BasicBlockState bbsIDOM = bbStates[immediateDominators[idx].SpanningTreeIndex] ;
if(bbsIDOM == bbs)
{
//
// This is an entry node, so we should use the initial state of the variable stack.
//
localStack = ArrayUtility.CopyNotNullArray( stack );
}
else if(bbsIDOM.m_stackAtExit != null)
{
//
// Use the state of the variable stack at the exit of the dominator basic block as our input.
//
localStack = ArrayUtility.CopyNotNullArray( bbsIDOM.m_stackAtExit );
}
else
{
//
// Process the immediate dominator before the current basic block.
//
pending.Push( bbs );
pending.Push( bbsIDOM );
continue;
}
//
// Rename all the variables.
//
var entryStack = ArrayUtility.CopyNotNullArray( localStack );
foreach(Operator op in bb.Operators)
{
foreach(var an in op.FilterAnnotations< PreInvalidationAnnotation>())
{
CreateNewVariable( cfg, variables, localStack, candidate, renameHistory, renameHistoryKey, an.Target );
}
renameHistoryKey++;
foreach(var an in op.FilterAnnotations< PreInvalidationAnnotation>())
{
SubstituteDefinition( localStack, candidate, op, an );
}
//--//
SubstituteUsage( localStack, entryStack, candidate, op );
//--//
foreach(var an in op.FilterAnnotations< PostInvalidationAnnotation>())
{
CreateNewVariable( cfg, variables, localStack, candidate, renameHistory, renameHistoryKey, an.Target );
}
renameHistoryKey++;
foreach(var an in op.FilterAnnotations< PostInvalidationAnnotation>())
{
SubstituteDefinition( localStack, candidate, op, an );
}
//--//
foreach(var lhs in op.Results)
{
CreateNewVariable( cfg, variables, localStack, candidate, renameHistory, renameHistoryKey, lhs );
}
renameHistoryKey++;
SubstituteDefinition( localStack, candidate, op );
}
bbs.m_stackAtExit = localStack;
//
// Queue successors for processing.
//
foreach(BasicBlockEdge edge in bbs.m_successors)
{
BasicBlockState bbsNext = bbStates[edge.Successor.SpanningTreeIndex];
if(bbsNext.m_stackAtExit == null)
{
pending.Push( bbsNext );
}
}
}
//
// Now that all the variables have been updated, we can fill the phi operators.
//
foreach(BasicBlockState bbs in bbStates)
{
foreach(BasicBlockEdge edge in bbs.m_successors)
{
BasicBlock bbNext = edge.Successor;
foreach(Operator op in bbNext.Operators)
{
PhiOperator phiOp = op as PhiOperator;
if(phiOp != null && newPhis.Contains( phiOp ))
{
PhiVariableExpression phiVar = (PhiVariableExpression)phiOp.FirstResult;
VariableExpression var = phiVar.Target;
VariableExpression input = bbs.m_stackAtExit[var.SpanningTreeIndex];
///
/// TODO: Verify that this is the correct thing to do. For exception handlers
/// the variables of the outer scope are set to NULL for the current bbs.m_stackAtExit
/// This code gets the variable in the target basic blocks m_stackAtExit
///
if(input == null)
{
input = bbStates[bbNext.SpanningTreeIndex].m_stackAtExit[var.SpanningTreeIndex];
}
CHECKS.ASSERT( input != null, "Inputs to the phi operator have to be defined in method '{0}':\r\n {1}", op.BasicBlock.Owner.Method.ToShortString(), phiOp );
phiOp.AddEffect( input, bbs.m_bb );
}
}
}
}
}
private static void CreateNewVariable( ControlFlowGraphStateForCodeTransformation cfg ,
VariableExpression[] variables ,
PhiVariableExpression[] localStack ,
bool[] candidate ,
int[] renameHistory ,
int renameHistoryKey ,
VariableExpression lhs )
{
int varIdx = lhs.SpanningTreeIndex;
if(candidate[varIdx] && renameHistory[varIdx] != renameHistoryKey)
{
PhiVariableExpression phiVar = cfg.AllocatePhiVariable( lhs );
localStack [varIdx] = phiVar;
renameHistory[varIdx] = renameHistoryKey;
PhysicalRegisterExpression reg = lhs.AliasedVariable as PhysicalRegisterExpression;
if(reg != null)
{
//
// Create a new phi variables for all the various typed versions of this physical register.
//
foreach(VariableExpression reg2 in variables)
{
int regIdx = reg2.SpanningTreeIndex;
if(localStack[regIdx] == null && renameHistory[regIdx] != renameHistoryKey && reg.IsTheSamePhysicalEntity( reg2.AliasedVariable ))
{
localStack [regIdx] = cfg.AllocatePhiVariable( reg2 );
renameHistory[regIdx] = renameHistoryKey;
}
}
}
}
}
private static void SubstituteDefinition( PhiVariableExpression[] localStack ,
bool[] candidate ,
Operator op ,
InvalidationAnnotation an )
{
var lhs = an.Target;
int varIdx = lhs.SpanningTreeIndex;
if(candidate[varIdx])
{
var newVar = localStack[varIdx];
InvalidationAnnotation anNew;
if(an is PreInvalidationAnnotation)
{
anNew = PreInvalidationAnnotation.Create( null, newVar );
}
else
{
anNew = PostInvalidationAnnotation.Create( null, newVar );
}
op.SubstituteAnnotation( an, anNew );
}
}
private static void SubstituteDefinition( PhiVariableExpression[] localStack ,
bool[] candidate ,
Operator op )
{
foreach(var lhs in op.Results)
{
int varIdx = lhs.SpanningTreeIndex;
if(candidate[varIdx])
{
op.SubstituteDefinition( lhs, localStack[varIdx] );
}
}
}
private static void SubstituteUsage( PhiVariableExpression[] localStack ,
PhiVariableExpression[] entryStack ,
bool[] candidate ,
Operator op )
{
foreach(Expression rhs in op.Arguments)
{
VariableExpression var = rhs as VariableExpression;
if(var != null)
{
int varIdx = var.SpanningTreeIndex;
if(candidate[varIdx])
{
//
// If a variable is an argument, it won't be defined on any path from entry,
// so its lot in localStack will be empty. It's OK, just use the original value.
//
PhiVariableExpression phiVar;
//
// Phi and Pi operators are parallel operators.
// That's equivalent to using the state of the variables at the entry of the basic block.
//
if(op is PhiOperator ||
op is PiOperator )
{
phiVar = entryStack[varIdx];
}
else
{
phiVar = localStack[varIdx];
}
CHECKS.ASSERT( phiVar != null, "Found use of phi-candidate variable that is not reachable by any of its definitions: {0}", op );
op.SubstituteUsage( var, phiVar );
}
}
}
}
//--//--//--//--//--//--//--//--//--//--//
public static bool ConvertOut( ControlFlowGraphStateForCodeTransformation cfg ,
bool fAllowPseudoReg )
{
using(new PerformanceCounters.ContextualTiming( cfg, "ConvertOutSSA" ))
{
bool fShouldProcess = false;
//
// First of all, are we still in SSA form?
// Look for any PhiOperators or PhiVariable.
//
foreach(Operator op in cfg.DataFlow_SpanningTree_Operators)
{
if(op is PhiOperator ||
op is PiOperator )
{
fShouldProcess = true;
break;
}
}
if(fShouldProcess == false)
{
foreach(VariableExpression var in cfg.DataFlow_SpanningTree_Variables)
{
if(var is PhiVariableExpression)
{
fShouldProcess = true;
break;
}
}
}
if(fShouldProcess)
{
cfg.TraceToFile( "ConvertOut-Pre" );
RemovePiOperators ( cfg );
ConvertPhiOperatorsIntoCopies ( cfg );
ConvertPhiVariablesIntoNormalVariables( cfg, fAllowPseudoReg );
cfg.TraceToFile( "ConvertOut-Post" );
while(Transformations.CommonMethodRedundancyElimination.Execute( cfg ))
{
}
cfg.DropDeadVariables();
cfg.TraceToFile( "ConvertOut-Done" );
}
return fShouldProcess;
}
}
//--//
internal class InsertionState
{
//
// State
//
internal BasicBlock m_basicBlockSource;
internal BasicBlock m_basicBlockTarget;
internal BasicBlock m_basicBlockInserted;
internal List< SingleAssignmentOperator > m_assignments;
//
// Constructor Methods
//
internal InsertionState( BasicBlock bbSource ,
BasicBlock bbTarget )
{
m_basicBlockSource = bbSource;
m_basicBlockTarget = bbTarget;
m_assignments = new List< SingleAssignmentOperator >();
}
internal void AllocateBasicBlock()
{
m_basicBlockInserted = m_basicBlockSource.InsertNewSuccessor( m_basicBlockTarget );
}
internal void Add( Microsoft.Zelig.Debugging.DebugInfo debugInfo ,
VariableExpression targetVar ,
Expression sourceEx )
{
m_assignments.Add( SingleAssignmentOperator.New( debugInfo, targetVar, sourceEx ) );
}
internal void ScheduleCopies( ControlFlowGraphStateForCodeTransformation cfg )
{
//
// First, get rid of non-interfering copies.
//
while(true)
{
InsertNonInterferingCopies();
bool fDone = true;
for(int pos = 0; pos < m_assignments.Count; pos++)
{
SingleAssignmentOperator op = m_assignments[pos];
if(op != null)
{
//
// At this point, only items in a cyclic graph are left.
//
// To break the loop, we have to:
// 1) create a temporary,
// 2) copy the source value into it,
// 3) remove the original copy from the set,
// 4) schedule all the other copies,
// 5) insert back the assignment to the original destination, now from the temporary.
//
VariableExpression destinationVar = op.FirstResult;
VariableExpression sourceVar = (VariableExpression)op.FirstArgument;
VariableExpression tmp = AllocateTemporary( cfg, sourceVar.AliasedVariable );
m_basicBlockInserted.AddOperator( SingleAssignmentOperator.New( op.DebugInfo, tmp, sourceVar ) );
m_assignments[pos] = null;
InsertNonInterferingCopies();
CHECKS.ASSERT( IsUsedByAnotherCopy( op, destinationVar ) == false, "Oops" );
m_assignments[pos] = SingleAssignmentOperator.New( op.DebugInfo, destinationVar, tmp );
fDone = false; // One less candidate, try looping again.
break;
}
}
if(fDone)
{
break;
}
}
}
//--//
private VariableExpression AllocateTemporary( ControlFlowGraphStateForCodeTransformation cfg ,
VariableExpression var )
{
if(var is PhysicalRegisterExpression)
{
PhysicalRegisterExpression regVar = (PhysicalRegisterExpression)var;
Abstractions.RegisterDescriptor regDesc = cfg.TypeSystem.PlatformAbstraction.GetScratchRegister();
var = cfg.AllocateTypedPhysicalRegister( regVar.Type, regDesc, regVar.DebugName, regVar.SourceVariable, regVar.SourceOffset );
}
return cfg.AllocatePhiVariable( var );
}
private void InsertNonInterferingCopies()
{
while(true)
{
bool fDone = true;
for(int pos = 0; pos < m_assignments.Count; pos++)
{
SingleAssignmentOperator op = m_assignments[pos];
if(op != null)
{
if(IsUsedByAnotherCopy( op, op.FirstResult ) == false)
{
m_basicBlockInserted.AddOperator( op );
m_assignments[pos] = null;
fDone = false; // One less candidate, try looping again.
}
}
}
if(fDone)
{
break;
}
}
}
private bool IsUsedByAnotherCopy( SingleAssignmentOperator opSrc ,
VariableExpression var )
{
for(int pos = 0; pos < m_assignments.Count; pos++)
{
var op = m_assignments[pos];
if(op != null && op != opSrc) // Skip source operator.
{
if(var.IsTheSamePhysicalEntity( op.FirstArgument ))
{
return true;
}
}
}
return false;
}
}
private static void ConvertPhiOperatorsIntoCopies( ControlFlowGraphStateForCodeTransformation cfg )
{
List< InsertionState > insertionPoints = new List< InsertionState >();
//
// Build the table with all the copy operations that have to be scheduled.
//
foreach(var phiOp in cfg.FilterOperators< PhiOperator >())
{
Expression[] rhs = phiOp.Arguments;
BasicBlock[] origins = phiOp.Origins;
BasicBlock target = phiOp.BasicBlock;
VariableExpression targetVar = phiOp.FirstResult;
for(int pos = 0; pos < origins.Length; pos++)
{
Expression sourceEx = rhs [pos];
BasicBlock source = origins[pos];
InsertionState insertionPoint = null;
foreach(InsertionState insertionPoint2 in insertionPoints)
{
if(insertionPoint2.m_basicBlockSource == source &&
insertionPoint2.m_basicBlockTarget == target )
{
insertionPoint = insertionPoint2;
break;
}
}
if(insertionPoint == null)
{
insertionPoint = new InsertionState( source, target );
insertionPoints.Add( insertionPoint );
}
insertionPoint.Add( phiOp.DebugInfo, targetVar, sourceEx );
}
phiOp.Delete();
}
//
// Create a new basic block and redirect the source to it.
//
foreach(InsertionState insertionPoint in insertionPoints)
{
insertionPoint.AllocateBasicBlock();
}
foreach(InsertionState insertionPoint in insertionPoints)
{
insertionPoint.ScheduleCopies( cfg );
}
}
//--//
internal class VariableState
{
//
// State
//
internal int m_index;
internal VariableExpression.Property m_properties;
internal PhiVariableExpression[] m_phiVariables;
internal VariableExpression m_mappedTo;
internal Operator[] m_definitions;
internal BitVector m_livenessMap;
//
// Constructor Methods
//
internal VariableState( int index )
{
m_index = index;
m_phiVariables = PhiVariableExpression.SharedEmptyArray;
}
internal static VariableState Create( GrowOnlyHashTable< VariableExpression, VariableState > lookup ,
VariableExpression var )
{
VariableState res;
if(lookup.TryGetValue( var, out res ) == false)
{
res = new VariableState( var.SpanningTreeIndex );
lookup[var] = res;
}
return res;
}
internal bool IsThereInterference( GrowOnlyHashTable< VariableExpression, VariableState > lookup ,
BitVector tmp ,
PhiVariableExpression phiTarget ,
PhiVariableExpression[] phis )
{
//
// We have to find out if there's any overlap in the liveness of different phi variables.
// If there isn't, we can directly convert them back to registers.
// Otherwise we need to add extra assignments.
//
foreach(PhiVariableExpression phi in phis)
{
if(phi != phiTarget)
{
tmp.And( m_livenessMap, lookup[phi].m_livenessMap );
if(tmp.Cardinality != 0)
{
return true;
}
}
}
return false;
}
}
private static void ConvertPhiVariablesIntoNormalVariables( ControlFlowGraphStateForCodeTransformation cfg ,
bool fAllowPseudoReg )
{
VariableExpression[] variables = cfg.DataFlow_SpanningTree_Variables;
VariableExpression.Property[] varProps = cfg.DataFlow_PropertiesOfVariables;
Operator[][] defChains = cfg.DataFlow_DefinitionChains;
BitVector[] variableLivenessMap = cfg.DataFlow_VariableLivenessMap;
GrowOnlyHashTable< VariableExpression, VariableState > lookup = HashTableFactory.NewWithReferenceEquality< VariableExpression, VariableState >();
//
// Collect all redefinitions of variables.
//
foreach(VariableExpression var in variables)
{
VariableState vs;
PhiVariableExpression phiVar = var as PhiVariableExpression;
if(phiVar != null)
{
vs = VariableState.Create( lookup, phiVar.AliasedVariable );
vs.m_phiVariables = ArrayUtility.AppendToNotNullArray( vs.m_phiVariables, phiVar );
}
//--//
vs = VariableState.Create( lookup, var );
int idx = var.SpanningTreeIndex;
vs.m_properties = varProps [idx];
vs.m_livenessMap = variableLivenessMap[idx];
vs.m_definitions = defChains [idx];
}
//
// Keep track of all the substitutions.
//
// Then go through the Subroutines and Invalidate operators and
// update the values back to PhysicalRegister and StackLocations.
// If needed, add assignment operators in front of subroutine calls.
//
foreach(VariableExpression var in lookup.Keys)
{
VariableState vs = lookup[var];
PhiVariableExpression[] phis = vs.m_phiVariables;
if(phis.Length == 1)
{
//
// Simple case, only one definition, substitute back for the original variable.
//
lookup[ phis[0] ].m_mappedTo = var;
}
else
{
VariableExpression.DebugInfo debugInfo = var.AliasedVariable.DebugName;
BitVector tmp = new BitVector();
foreach(PhiVariableExpression phi in phis)
{
VariableState vsPhi = lookup[phi];
VariableExpression newVar = null;
if(var is PhysicalRegisterExpression)
{
//
// We have to find out if there's any overlap in the liveness of different phi variables.
// If there isn't, we can directly convert them back to registers.
// Otherwise we need to add extra assignments.
//
if(vsPhi.IsThereInterference( lookup, tmp, phi, phis ) == false)
{
newVar = var;
}
else if(vsPhi.m_definitions.Length == 1 && vsPhi.m_definitions[0] is InitialValueOperator)
{
//
// This is an argument. Keep it as is.
//
newVar = var;
}
else
{
//
// There's some aliasing problem with this register.
// Create a new temporary, add an assignment at the original definition site and propagate that value.
//
if(fAllowPseudoReg)
{
newVar = cfg.AllocatePseudoRegister( var.Type, debugInfo );
}
else
{
newVar = var;
}
}
}
else if(var is ConditionCodeExpression)
{
CHECKS.ASSERT( (vsPhi.m_properties & VariableExpression.Property.AddressTaken) == 0, "Cannot take address of condition code: {0}", phi );
//
// We have to find out if there's any overlap in the liveness of different phi variables.
// If there isn't, we can directly convert them back to registers.
// Otherwise we need to add extra assignments.
//
if(vsPhi.IsThereInterference( lookup, tmp, phi, phis ) == false)
{
newVar = var;
}
else if(vsPhi.m_definitions.Length == 1 && vsPhi.m_definitions[0] is InitialValueOperator)
{
//
// This is an argument. Keep it as is.
//
newVar = var;
}
else
{
//
// There's some aliasing problem with this register.
// Create a new temporary, add an assignment at the original definition site and propagate that value.
//
if(fAllowPseudoReg)
{
newVar = cfg.AllocatePseudoRegister( var.Type, debugInfo );
}
else
{
newVar = var;
}
}
}
else if(var is StackLocationExpression)
{
StackLocationExpression stack = (StackLocationExpression)var;
if(vsPhi.IsThereInterference( lookup, tmp, phi, phis ) == false)
{
newVar = var;
}
else if(vsPhi.m_definitions.Length == 1 && vsPhi.m_definitions[0] is InitialValueOperator)
{
//
// This is an argument. Keep it as is.
//
newVar = var;
}
else
{
//
// There's some aliasing problem with this stack location.
// Create a new temporary, add an assignment at the original definition site and propagate that value.
//
if((vsPhi.m_properties & VariableExpression.Property.AddressTaken) != 0)
{
newVar = cfg.AllocateLocalStackLocation( stack.Type, debugInfo, stack.SourceVariable, stack.SourceOffset );
}
else
{
if(fAllowPseudoReg)
{
newVar = cfg.AllocatePseudoRegister( stack.Type, debugInfo, stack.SourceVariable, stack.SourceOffset );
}
else
{
newVar = var;
}
}
}
}
else if(var is PseudoRegisterExpression)
{
PseudoRegisterExpression pseudo = (PseudoRegisterExpression)var;
if((vsPhi.m_properties & VariableExpression.Property.AddressTaken) != 0)
{
newVar = cfg.AllocateLocalStackLocation( pseudo.Type, debugInfo, pseudo.SourceVariable, pseudo.SourceOffset );
}
else
{
if(fAllowPseudoReg)
{
newVar = cfg.AllocatePseudoRegister( pseudo.Type, debugInfo, pseudo.SourceVariable, pseudo.SourceOffset );
}
else
{
throw TypeConsistencyErrorException.Create( "Expecting a physical expression instead of {0}", var );
}
}
}
else
{
//
// WARNING: Convert to or from SSA before mapping to machine words is untested...
//
if(var is TemporaryVariableExpression)
{
newVar = cfg.AllocateTemporary( var.Type, debugInfo );
}
else
{
newVar = cfg.AllocateLocal( var.Type, debugInfo );
}
}
vsPhi.m_mappedTo = newVar;
}
}
}
foreach(Operator op in cfg.DataFlow_SpanningTree_Operators)
{
SubstitutePhiVariables( op, lookup );
}
}
private static void SubstitutePhiVariables( Operator op ,
GrowOnlyHashTable< VariableExpression, VariableState > lookup )
{
bool fCall = (op is SubroutineOperator);
foreach(var an in op.FilterAnnotations< PreInvalidationAnnotation >())
{
var var = an.Target;
var newVar = FindSubstituteForPhiVariable( lookup, var );
if(newVar != null)
{
VariableExpression origVar = var.AliasedVariable;
newVar = AdjustForCallingConvention( origVar, newVar );
if(newVar != origVar)
{
op.AddOperatorBefore( SingleAssignmentOperator.New( op.DebugInfo, origVar, newVar ) );
}
var anNew = PreInvalidationAnnotation.Create( null, origVar );
op.SubstituteAnnotation( an, anNew );
}
}
foreach(Expression ex in op.Arguments)
{
var var = ex as VariableExpression;
if(var != null)
{
var newVar = FindSubstituteForPhiVariable( lookup, var );
if(newVar != null)
{
if(fCall)
{
VariableExpression origVar = var.AliasedVariable;
newVar = AdjustForCallingConvention( origVar, newVar );
if(newVar != origVar)
{
op.AddOperatorBefore( SingleAssignmentOperator.New( op.DebugInfo, origVar, newVar ) );
}
op.SubstituteUsage( var, origVar );
}
else
{
op.SubstituteUsage( var, newVar );
}
}
}
}
foreach(var an in op.FilterAnnotations< PostInvalidationAnnotation >())
{
var var = an.Target;
var newVar = FindSubstituteForPhiVariable( lookup, var );
if(newVar != null)
{
VariableExpression origVar = var.AliasedVariable;
newVar = AdjustForCallingConvention( origVar, newVar );
if(newVar != origVar)
{
op.AddOperatorAfter( SingleAssignmentOperator.New( op.DebugInfo, newVar, origVar ) );
}
var anNew = PostInvalidationAnnotation.Create( null, origVar );
op.SubstituteAnnotation( an, anNew );
}
}
foreach(var var in op.Results)
{
var newVar = FindSubstituteForPhiVariable( lookup, var );
if(newVar != null)
{
op.SubstituteDefinition( var, newVar );
}
}
}
private static VariableExpression FindSubstituteForPhiVariable( GrowOnlyHashTable< VariableExpression, VariableState > lookup ,
VariableExpression var )
{
VariableState vs;
if(lookup.TryGetValue( var, out vs ))
{
return vs.m_mappedTo;
}
return null;
}
private static VariableExpression AdjustForCallingConvention( VariableExpression origVar ,
VariableExpression newVar )
{
if(origVar is PhysicalRegisterExpression)
{
return origVar;
}
else if(origVar is ConditionCodeExpression)
{
return origVar;
}
else if(origVar is StackLocationExpression)
{
StackLocationExpression stack = (StackLocationExpression)origVar;
if(stack.StackPlacement == StackLocationExpression.Placement.Out)
{
return stack;
}
}
return newVar;
}
//
// Access Methods
//
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Timer.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Timers {
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.ComponentModel;
using System.ComponentModel.Design;
using System;
using System.Runtime.Versioning;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
/// <devdoc>
/// <para>Handles recurring events in an application.</para>
/// </devdoc>
[
DefaultProperty("Interval"),
DefaultEvent("Elapsed"),
HostProtection(Synchronization=true, ExternalThreading=true)
]
public class Timer : Component, ISupportInitialize {
private double interval;
private bool enabled;
private bool initializing;
private bool delayedEnable;
private ElapsedEventHandler onIntervalElapsed;
private bool autoReset;
private ISynchronizeInvoke synchronizingObject;
private bool disposed;
private System.Threading.Timer timer;
private TimerCallback callback;
private Object cookie;
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Timers.Timer'/> class, with the properties
/// set to initial values.</para>
/// </devdoc>
public Timer()
: base() {
interval = 100;
enabled = false;
autoReset = true;
initializing = false;
delayedEnable = false;
callback = new TimerCallback(this.MyTimerCallback);
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Timers.Timer'/> class, setting the <see cref='System.Timers.Timer.Interval'/> property to the specified period.
/// </para>
/// </devdoc>
public Timer(double interval)
: this() {
if (interval <= 0)
throw new ArgumentException(SR.GetString(SR.InvalidParameter, "interval", interval));
double roundedInterval = Math.Ceiling(interval);
if (roundedInterval > Int32.MaxValue || roundedInterval <= 0) {
throw new ArgumentException(SR.GetString(SR.InvalidParameter, "interval", interval));
}
this.interval = (int) roundedInterval;
}
/// <devdoc>
/// <para>Gets or sets a value indicating whether the Timer raises the Tick event each time the specified
/// Interval has elapsed,
/// when Enabled is set to true.</para>
/// </devdoc>
[Category("Behavior"), TimersDescription(SR.TimerAutoReset), DefaultValue(true)]
public bool AutoReset {
get {
return this.autoReset;
}
set {
if (DesignMode)
this.autoReset = value;
else if (this.autoReset != value) {
this.autoReset = value;
if( timer != null) {
UpdateTimer();
}
}
}
}
/// <devdoc>
/// <para>Gets or sets a value indicating whether the <see cref='System.Timers.Timer'/>
/// is able
/// to raise events at a defined interval.</para>
/// </devdoc>
//[....] - The default value by design is false, don't change it.
[Category("Behavior"), TimersDescription(SR.TimerEnabled), DefaultValue(false)]
public bool Enabled {
get {
return this.enabled;
}
set {
if (DesignMode) {
this.delayedEnable = value;
this.enabled = value;
}
else if (initializing)
this.delayedEnable = value;
else if (enabled != value) {
if (!value) {
if( timer != null) {
cookie = null;
timer.Dispose();
timer = null;
}
enabled = value;
}
else {
enabled = value;
if( timer == null) {
if (disposed) {
throw new ObjectDisposedException(GetType().Name);
}
int i = (int)Math.Ceiling(interval);
cookie = new Object();
timer = new System.Threading.Timer(callback, cookie, i, autoReset? i:Timeout.Infinite);
}
else {
UpdateTimer();
}
}
}
}
}
private void UpdateTimer() {
int i = (int)Math.Ceiling(interval);
timer.Change(i, autoReset? i :Timeout.Infinite );
}
/// <devdoc>
/// <para>Gets or
/// sets the interval on which
/// to raise events.</para>
/// </devdoc>
[Category("Behavior"), TimersDescription(SR.TimerInterval), DefaultValue(100d), SettingsBindable(true)]
public double Interval {
get {
return this.interval;
}
set {
if (value <= 0)
throw new ArgumentException(SR.GetString(SR.TimerInvalidInterval, value, 0));
interval = value;
if (timer != null) {
UpdateTimer();
}
}
}
/// <devdoc>
/// <para>Occurs when the <see cref='System.Timers.Timer.Interval'/> has
/// elapsed.</para>
/// </devdoc>
[Category("Behavior"), TimersDescription(SR.TimerIntervalElapsed)]
public event ElapsedEventHandler Elapsed {
add {
onIntervalElapsed += value;
}
remove {
onIntervalElapsed -= value;
}
}
/// <devdoc>
/// <para>
/// Sets the enable property in design mode to true by default.
/// </para>
/// </devdoc>
/// <internalonly/>
public override ISite Site {
set {
base.Site = value;
if (this.DesignMode)
this.enabled= true;
}
get {
return base.Site;
}
}
/// <devdoc>
/// <para>Gets or sets the object used to marshal event-handler calls that are issued when
/// an interval has elapsed.</para>
/// </devdoc>
[
Browsable(false),
DefaultValue(null),
TimersDescription(SR.TimerSynchronizingObject)
]
public ISynchronizeInvoke SynchronizingObject {
get {
if (this.synchronizingObject == null && DesignMode) {
IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost));
if (host != null) {
object baseComponent = host.RootComponent;
if (baseComponent != null && baseComponent is ISynchronizeInvoke)
this.synchronizingObject = (ISynchronizeInvoke)baseComponent;
}
}
return this.synchronizingObject;
}
set {
this.synchronizingObject = value;
}
}
/// <devdoc>
/// <para>
/// Notifies
/// the object that initialization is beginning and tells it to stand by.
/// </para>
/// </devdoc>
public void BeginInit() {
this.Close();
this.initializing = true;
}
/// <devdoc>
/// <para>Disposes of the resources (other than memory) used by
/// the <see cref='System.Timers.Timer'/>.</para>
/// </devdoc>
public void Close() {
initializing = false;
delayedEnable = false;
enabled = false;
if (timer != null ) {
timer.Dispose();
timer = null;
}
}
/// <internalonly/>
/// <devdoc>
/// </devdoc>
protected override void Dispose(bool disposing) {
Close();
this.disposed = true;
base.Dispose(disposing);
}
/// <devdoc>
/// <para>
/// Notifies the object that initialization is complete.
/// </para>
/// </devdoc>
public void EndInit() {
this.initializing = false;
this.Enabled = this.delayedEnable;
}
/// <devdoc>
/// <para>Starts the timing by setting <see cref='System.Timers.Timer.Enabled'/> to <see langword='true'/>.</para>
/// </devdoc>
public void Start() {
Enabled = true;
}
/// <devdoc>
/// <para>
/// Stops the timing by setting <see cref='System.Timers.Timer.Enabled'/> to <see langword='false'/>.
/// </para>
/// </devdoc>
public void Stop() {
Enabled = false;
}
private void MyTimerCallback(object state) {
// System.Threading.Timer will not cancel the work item queued before the timer is stopped.
// We don't want to handle the callback after a timer is stopped.
if( state != cookie) {
return;
}
if (!this.autoReset) {
enabled = false;
}
FILE_TIME filetime = new FILE_TIME();
GetSystemTimeAsFileTime(ref filetime);
ElapsedEventArgs elapsedEventArgs = new ElapsedEventArgs(filetime.ftTimeLow, filetime.ftTimeHigh);
try {
// To avoid ---- between remove handler and raising the event
ElapsedEventHandler intervalElapsed = this.onIntervalElapsed;
if (intervalElapsed != null) {
if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired)
this.SynchronizingObject.BeginInvoke(intervalElapsed, new object[]{this, elapsedEventArgs});
else
intervalElapsed(this, elapsedEventArgs);
}
}
catch {
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct FILE_TIME {
internal int ftTimeLow;
internal int ftTimeHigh;
}
[ResourceExposure(ResourceScope.None)]
[DllImport(ExternDll.Kernel32), SuppressUnmanagedCodeSecurityAttribute()]
internal static extern void GetSystemTimeAsFileTime(ref FILE_TIME lpSystemTimeAsFileTime);
}
}
| |
using System;
using System.Data;
using System.IO;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using System.Xml;
namespace DbInitToy
{
class Program
{
const string ErrorXmlCannotLoad = "The specified xml setting file cannot be loaded";
const string ErrorXmlNotValid = "The specifiled xml setting file is not an valid DbInitToy setting file";
static void ShowColorfulMsg(string msg, ConsoleColor foreColor, ConsoleColor bgColor)
{
ConsoleColor fcolor = Console.ForegroundColor;
ConsoleColor bcolor = Console.BackgroundColor;
Console.ForegroundColor = foreColor;
Console.BackgroundColor = bgColor;
Console.WriteLine(msg);
Console.ForegroundColor = fcolor;
Console.BackgroundColor = bcolor;
}
static void ShowColorfulMsg(string msg, ConsoleColor foreColor)
{
ConsoleColor old = Console.ForegroundColor;
Console.ForegroundColor = foreColor;
Console.WriteLine(msg);
Console.ForegroundColor = old;
}
static void ShowError(string msg)
{
ShowColorfulMsg(msg, ConsoleColor.Red);
}
static void ShowSuccess(string msg)
{
ShowColorfulMsg(msg, ConsoleColor.Green);
}
static void ShowNotValidError(string custMsg, string innerMsg, string file)
{
string format = "Error: {0}{1}{2}.{1}File: {3}";
ShowError(string.Format(format, innerMsg, Environment.NewLine, custMsg, file));
}
static void ParseSettingFile(string file, out string conn, out List<SqlScriptFileInfo> list)
{
conn = null;
list = null;
Console.Write("Parsing xml setting file: ");
ShowColorfulMsg(file, ConsoleColor.Cyan);
if (string.IsNullOrEmpty(file) || !Path.IsPathRooted(file))
{
ShowError("Invalid file name!");
return;
}
XmlDocument doc = new XmlDocument();
try
{
doc.Load(file);
}
catch (Exception ex)
{
ShowNotValidError(ErrorXmlCannotLoad, ex.Message, file);
}
XmlElement root = doc.DocumentElement;
if (null == root || "Script" != root.Name || null == root.Attributes["ConnectionString"])
{
ShowNotValidError(ErrorXmlNotValid, "Could not find the specified attributes.", file);
return;
}
conn = root.Attributes["ConnectionString"].Value;
list = new List<SqlScriptFileInfo>(root.ChildNodes.Count);
foreach (XmlNode node in root.ChildNodes)
{
try
{
list.Add(ParseXmlNode(node));
}
catch (Exception ex)
{
ShowNotValidError(ErrorXmlNotValid, ex.Message, file);
}
}
ShowSuccess("The file is valid." + Environment.NewLine);
}
static SqlScriptFileInfo ParseXmlNode(XmlNode node)
{
if ("File" != node.Name || null == node.Attributes["path"])
return null;
XmlAttribute att = node.Attributes["path"];
return new SqlScriptFileInfo(att.Value);
}
static void Execute(string[] xmlFiles)
{
foreach (string file in xmlFiles)
{
List<SqlScriptFileInfo> list;
string connstr;
ParseSettingFile(file, out connstr, out list);
if (null == connstr || null == list || 0 == list.Count)
return;
using (SqlConnection conn = new SqlConnection(connstr))
{
Console.WriteLine("Opening database connection...");
ShowColorfulMsg("\tConnection string: " + connstr, ConsoleColor.Cyan);
try
{
conn.Open();
ShowSuccess("Connection opened successfully.");
}
catch (Exception ex)
{
ShowError("Error: " + ex.Message);
continue;
}
Console.WriteLine();
foreach (SqlScriptFileInfo info in list)
{
if (null == info)
continue;
using (SqlCommand cmd = new SqlCommand(info.SqlString, conn))
{
Console.Write("Executing {0}... ", info.FilePath);
try
{
int rowsAffected = cmd.ExecuteNonQuery();
ShowSuccess("Success.");
}
catch (Exception ex)
{
ShowError(" Error: " + ex.Message);
continue;
}
}
}
Console.WriteLine("{0}Execution complete.{0}", Environment.NewLine);
}
}
}
//DbInitToy xmlfile.xml
static void Main(string[] args)
{
ConsoleColor fcolor = Console.ForegroundColor;
ConsoleColor bcolor = Console.BackgroundColor;
string[] xmlFile = GetXmlSettingFile(args);
ListFiles(xmlFile);
if (Console.ReadKey().Key == ConsoleKey.Y)
{
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.White;
Console.BackgroundColor = ConsoleColor.Black;
Execute(xmlFile);
}
Console.ForegroundColor = fcolor;
Console.BackgroundColor = bcolor;
}
static string[] GetXmlSettingFile(string[] args)
{
string[] xmlFile = 0 == args.Length ? Directory.GetFiles(Environment.CurrentDirectory, "*.xml") : args;
if (0 == xmlFile.Length)
{
ShowError(@"Could not find the xml setting file in this directory.
Either you can specify which xml setting file to use, e.g. 'DbInitToy xmlfile.xml, xmlfile2.xml',
or put the xml setting files in the directory.");
Environment.Exit(-1);
}
return xmlFile;
}
static void ListFiles(string[] xmlFile)
{
if (1 == xmlFile.Length)
{
Console.WriteLine("Found file:{0}\t{1}", Environment.NewLine, xmlFile[0]);
}
else
{
Console.WriteLine("Found files: ");
for (int i = 0; i < xmlFile.Length; i++)
{
Console.WriteLine("\t{0}. {1}", i, xmlFile[i]);
}
}
Console.WriteLine();
Console.Write("Execute? (y/n): ");
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Xml;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Designer.Interfaces;
using Microsoft.VisualStudio.Shell;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
using IServiceProvider = System.IServiceProvider;
using ShellConstants = Microsoft.VisualStudio.Shell.Interop.Constants;
using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.VisualStudio.FSharp.ProjectSystem
{
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct _DROPFILES
{
public Int32 pFiles;
public Int32 X;
public Int32 Y;
public Int32 fNC;
public Int32 fWide;
}
/// <summary>
/// Defines possible types of output that can produced by a language project
/// </summary>
[PropertyPageTypeConverterAttribute(typeof(OutputTypeConverter))]
public enum OutputType
{
/// <summary>
/// The output type is a windows executable.
/// </summary>
WinExe,
/// <summary>
/// The output type is an executable.
/// </summary>
Exe,
/// <summary>
/// The output type is a class library.
/// </summary>
Library
}
/// <summary>
/// Debug values used by DebugModeConverter.
/// </summary>
[PropertyPageTypeConverterAttribute(typeof(DebugModeConverter))]
public enum DebugMode
{
Project,
Program,
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URL")]
URL
}
[PropertyPageTypeConverterAttribute(typeof(CopyToOutputDirectoryConverter))]
public enum CopyToOutputDirectory
{
DoNotCopy,
Always,
PreserveNewest,
}
/// <summary>
/// Defines the version of the CLR that is appropriate to the project.
/// </summary>
[PropertyPageTypeConverterAttribute(typeof(PlatformTypeConverter))]
public enum PlatformType
{
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "not")]
notSpecified,
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "v")]
v1,
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "v")]
v11,
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "v")]
v2,
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "cli")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "cli")]
cli1
}
/// <summary>
/// Defines the currect state of a property page.
/// </summary>
[Flags]
internal enum PropPageStatus
{
Dirty = 0x1,
Validate = 0x2,
Clean = 0x4
}
[Flags]
[SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")]
internal enum ModuleKindFlags
{
ConsoleApplication,
WindowsApplication,
DynamicallyLinkedLibrary,
ManifestResourceFile,
UnmanagedDynamicallyLinkedLibrary
}
/// <summary>
/// Defines the status of the command being queried
/// </summary>
[Flags]
[SuppressMessage("Microsoft.Naming", "CA1714:FlagsEnumsShouldHavePluralNames")]
[SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")]
internal enum QueryStatusResult
{
/// <summary>
/// The command is not supported.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "NOTSUPPORTED")]
NOTSUPPORTED = 0,
/// <summary>
/// The command is supported
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SUPPORTED")]
SUPPORTED = 1,
/// <summary>
/// The command is enabled
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ENABLED")]
ENABLED = 2,
/// <summary>
/// The command is toggled on
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "LATCHED")]
LATCHED = 4,
/// <summary>
/// The command is toggled off (the opposite of LATCHED).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "NINCHED")]
NINCHED = 8,
/// <summary>
/// The command is invisible.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "INVISIBLE")]
INVISIBLE = 16
}
/// <summary>
/// Defines the type of item to be added to the hierarchy.
/// </summary>
internal enum HierarchyAddType
{
AddNewItem,
AddExistingItem
}
/// <summary>
/// Defines the component from which a command was issued.
/// </summary>
internal enum CommandOrigin
{
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ui")]
UiHierarchy,
OleCommandTarget
}
/// <summary>
/// Defines the current status of the build process.
/// </summary>
internal enum MSBuildResult
{
/// <summary>
/// The build is currently suspended.
/// </summary>
Suspended,
/// <summary>
/// The build has been restarted.
/// </summary>
Resumed,
/// <summary>
/// The build failed.
/// </summary>
Failed,
/// <summary>
/// The build was successful.
/// </summary>
Successful,
}
/// <summary>
/// Defines the type of action to be taken in showing the window frame.
/// </summary>
internal enum WindowFrameShowAction
{
DontShow,
Show,
ShowNoActivate,
Hide,
}
/// <summary>
/// Defines drop types
/// </summary>
internal enum DropDataType
{
None,
Shell,
VsStg,
VsRef
}
/// <summary>
/// Used by the hierarchy node to decide which element to redraw.
/// </summary>
[Flags]
[SuppressMessage("Microsoft.Naming", "CA1714:FlagsEnumsShouldHavePluralNames")]
internal enum UIHierarchyElement
{
None = 0,
/// <summary>
/// This will be translated to VSHPROPID_IconIndex
/// </summary>
Icon = 1,
/// <summary>
/// This will be translated to VSHPROPID_StateIconIndex
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Scc")]
SccState = 2,
/// <summary>
/// This will be translated to VSHPROPID_Caption
/// </summary>
Caption = 4
}
/// <summary>
/// Defines the global propeties used by the msbuild project.
/// </summary>
internal enum GlobalProperty
{
/// <summary>
/// Property specifying that we are building inside VS.
/// </summary>
BuildingInsideVisualStudio,
/// <summary>
/// The VS installation directory. This is the same as the $(DevEnvDir) macro.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Env")]
DevEnvDir,
/// <summary>
/// The name of the solution the project is created. This is the same as the $(SolutionName) macro.
/// </summary>
SolutionName,
/// <summary>
/// The file name of the solution. This is the same as $(SolutionFileName) macro.
/// </summary>
SolutionFileName,
/// <summary>
/// The full path of the solution. This is the same as the $(SolutionPath) macro.
/// </summary>
SolutionPath,
/// <summary>
/// The directory of the solution. This is the same as the $(SolutionDir) macro.
/// </summary>
SolutionDir,
/// <summary>
/// The extension of teh directory. This is the same as the $(SolutionExt) macro.
/// </summary>
SolutionExt,
/// <summary>
/// The fxcop installation directory.
/// </summary>
FxCopDir,
/// <summary>
/// The ResolvedNonMSBuildProjectOutputs msbuild property
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "VSIDE")]
VSIDEResolvedNonMSBuildProjectOutputs,
/// <summary>
/// The Configuartion property.
/// </summary>
Configuration,
/// <summary>
/// The platform property.
/// </summary>
Platform,
/// <summary>
/// The RunCodeAnalysisOnce property
/// </summary>
RunCodeAnalysisOnce,
/// <summary>
/// The VisualStudioStyleErrors property. We use this to determine correct error spans for build errors.
/// </summary>
VisualStudioStyleErrors,
/// <summary>
/// The SqmSessionGuid property
/// </summary>
SqmSessionGuid
}
public class AfterProjectFileOpenedEventArgs : EventArgs
{
private bool added;
/// <summary>
/// True if the project is added to the solution after the solution is opened. false if the project is added to the solution while the solution is being opened.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public bool Added
{
get { return this.added; }
}
public AfterProjectFileOpenedEventArgs(bool added)
{
this.added = added;
}
}
public class BeforeProjectFileClosedEventArgs : EventArgs
{
private bool removed;
/// <summary>
/// true if the project was removed from the solution before the solution was closed. false if the project was removed from the solution while the solution was being closed.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public bool Removed
{
get { return this.removed; }
}
public BeforeProjectFileClosedEventArgs(bool removed)
{
this.removed = removed;
}
}
/// <summary>
/// This class is used for the events raised by a HierarchyNode object.
/// </summary>
internal class HierarchyNodeEventArgs : EventArgs
{
private HierarchyNode child;
public HierarchyNodeEventArgs(HierarchyNode child)
{
this.child = child;
}
public HierarchyNode Child
{
get { return this.child; }
}
}
/// <summary>
/// Event args class for triggering file change event arguments.
/// </summary>
internal class FileChangedOnDiskEventArgs : EventArgs
{
/// <summary>
/// File name that was changed on disk.
/// </summary>
private string fileName;
/// <summary>
/// The item ide of the file that has changed.
/// </summary>
private uint itemID;
/// <summary>
/// The reason the file has changed on disk.
/// </summary>
private _VSFILECHANGEFLAGS fileChangeFlag;
/// <summary>
/// Constructs a new event args.
/// </summary>
/// <param name="fileName">File name that was changed on disk.</param>
/// <param name="id">The item id of the file that was changed on disk.</param>
public FileChangedOnDiskEventArgs(string fileName, uint id, _VSFILECHANGEFLAGS flag)
{
this.fileName = fileName;
this.itemID = id;
this.fileChangeFlag = flag;
}
/// <summary>
/// Gets the file name that was changed on disk.
/// </summary>
/// <value>The file that was changed on disk.</value>
public string FileName
{
get
{
return this.fileName;
}
}
/// <summary>
/// Gets item id of the file that has changed
/// </summary>
/// <value>The file that was changed on disk.</value>
public uint ItemID
{
get
{
return this.itemID;
}
}
/// <summary>
/// The reason while the file has chnaged on disk.
/// </summary>
/// <value>The reason while the file has chnaged on disk.</value>
public _VSFILECHANGEFLAGS FileChangeFlag
{
get
{
return this.fileChangeFlag;
}
}
}
/// <summary>
/// Defines the event args for the active configuration chnage event.
/// </summary>
internal class ActiveConfigurationChangedEventArgs : EventArgs
{
/// <summary>
/// The hierarchy whose configuration has changed
/// </summary>
private IVsHierarchy hierarchy;
/// <summary>
/// Constructs a new event args.
/// </summary>
/// <param name="hierarchy">The hierarchy that has changed its configuration.</param>
public ActiveConfigurationChangedEventArgs(IVsHierarchy hierarchy)
{
this.hierarchy = hierarchy;
}
/// <summary>
/// The hierarchy whose configuration has changed
/// </summary>
public IVsHierarchy Hierarchy
{
get
{
return this.hierarchy;
}
}
}
/// <summary>
/// Argument of the event raised when a project property is changed.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
internal class ProjectPropertyChangedArgs : EventArgs
{
private string propertyName;
private string oldValue;
private string newValue;
public ProjectPropertyChangedArgs(string propertyName, string oldValue, string newValue)
{
this.propertyName = propertyName;
this.oldValue = oldValue;
this.newValue = newValue;
}
public string NewValue
{
get { return newValue; }
}
public string OldValue
{
get { return oldValue; }
}
public string PropertyName
{
get { return propertyName; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Cci;
using Microsoft.Cci.Extensions;
using Microsoft.Cci.Filters;
using Microsoft.Cci.Writers;
using Microsoft.Cci.Writers.Syntax;
using Microsoft.Fx.CommandLine;
namespace GenAPI
{
internal class Program
{
private static int Main(string[] args)
{
ParseCommandLine(args);
HostEnvironment host = new HostEnvironment();
host.UnableToResolve += host_UnableToResolve;
host.UnifyToLibPath = true;
if (!string.IsNullOrWhiteSpace(s_libPath))
host.AddLibPaths(HostEnvironment.SplitPaths(s_libPath));
IEnumerable<IAssembly> assemblies = host.LoadAssemblies(HostEnvironment.SplitPaths(s_assembly));
if (!assemblies.Any())
{
Console.WriteLine("ERROR: Failed to load any assemblies from '{0}'", s_assembly);
return 1;
}
using (TextWriter output = GetOutput())
using (IStyleSyntaxWriter syntaxWriter = GetSyntaxWriter(output))
{
if (!String.IsNullOrEmpty(s_headerFile))
{
if (!File.Exists(s_headerFile))
{
Console.WriteLine("ERROR: header file '{0}' does not exist", s_headerFile);
return 1;
}
using (TextReader headerText = File.OpenText(s_headerFile))
{
output.Write(headerText.ReadToEnd());
}
}
ICciWriter writer = GetWriter(output, syntaxWriter);
writer.WriteAssemblies(assemblies);
}
return 0;
}
private static void host_UnableToResolve(object sender, UnresolvedReference<IUnit, AssemblyIdentity> e)
{
Console.WriteLine("Unable to resolve assembly '{0}' referenced by '{1}'.", e.Unresolved.ToString(), e.Referrer.ToString());
}
private static TextWriter GetOutput()
{
// If this is a null, empty, whitespace, or a directory use console
if (string.IsNullOrWhiteSpace(s_out) || Directory.Exists(s_out))
return Console.Out;
return File.CreateText(s_out);
}
private static ICciWriter GetWriter(TextWriter output, IStyleSyntaxWriter syntaxWriter)
{
ICciFilter filter = GetFilter();
switch (s_writer)
{
case WriterType.DocIds:
return new DocumentIdWriter(output, filter);
case WriterType.TypeForwards:
return new TypeForwardWriter(output, filter);
case WriterType.TypeList:
return new TypeListWriter(syntaxWriter, filter);
default:
case WriterType.CSDecl:
{
CSharpWriter writer = new CSharpWriter(syntaxWriter, filter, s_apiOnly);
writer.IncludeSpaceBetweenMemberGroups = writer.IncludeMemberGroupHeadings = s_memberHeadings;
writer.HighlightBaseMembers = s_hightlightBaseMembers;
writer.HighlightInterfaceMembers = s_hightlightInterfaceMembers;
writer.PutBraceOnNewLine = true;
writer.ThrowPlatformNotSupportedForCompilation = s_throw;
return writer;
}
}
}
private static ICciFilter GetFilter()
{
ICciFilter includeFilter = null;
if (string.IsNullOrWhiteSpace(s_apiList))
{
if (s_all)
{
includeFilter = new IncludeAllFilter();
}
else
{
includeFilter = new PublicOnlyCciFilter(excludeAttributes: s_apiOnly);
}
}
else
{
includeFilter = new DocIdIncludeListFilter(s_apiList);
}
if (!string.IsNullOrWhiteSpace(s_excludeApiList))
{
includeFilter = new IntersectionFilter(includeFilter, new DocIdExcludeListFilter(s_excludeApiList));
}
return includeFilter;
}
private static IStyleSyntaxWriter GetSyntaxWriter(TextWriter output)
{
if (s_writer != WriterType.CSDecl && s_writer != WriterType.TypeList)
return null;
switch (s_syntaxWriter)
{
case SyntaxWriterType.Xml:
return new OpenXmlSyntaxWriter(output);
case SyntaxWriterType.Html:
return new HtmlSyntaxWriter(output);
case SyntaxWriterType.Text:
default:
return new TextSyntaxWriter(output) { SpacesInIndent = 4 };
}
}
private enum WriterType
{
CSDecl,
DocIds,
TypeForwards,
TypeList,
}
private enum SyntaxWriterType
{
Text,
Html,
Xml
}
private static string s_assembly;
private static WriterType s_writer = WriterType.CSDecl;
private static SyntaxWriterType s_syntaxWriter = SyntaxWriterType.Text;
private static string s_apiList;
private static string s_excludeApiList;
private static string s_headerFile;
private static string s_out;
private static string s_libPath;
private static bool s_apiOnly;
private static bool s_memberHeadings;
private static bool s_hightlightBaseMembers;
private static bool s_hightlightInterfaceMembers;
private static bool s_all;
private static bool s_throw;
private static void ParseCommandLine(string[] args)
{
CommandLineParser.ParseForConsoleApplication((parser) =>
{
parser.DefineOptionalQualifier("libPath", ref s_libPath, "Delimited (',' or ';') set of paths to use for resolving assembly references");
parser.DefineAliases("apiList", "al");
parser.DefineOptionalQualifier("apiList", ref s_apiList, "(-al) Specify a api list in the DocId format of which APIs to include.");
parser.DefineAliases("excludeApiList", "xal");
parser.DefineOptionalQualifier("excludeApiList", ref s_excludeApiList, "(-xal) Specify a api list in the DocId format of which APIs to exclude.");
parser.DefineAliases("writer", "w");
parser.DefineOptionalQualifier<WriterType>("writer", ref s_writer, "(-w) Specify the writer type to use.");
parser.DefineAliases("syntax", "s");
parser.DefineOptionalQualifier<SyntaxWriterType>("syntax", ref s_syntaxWriter, "(-s) Specific the syntax writer type. Only used if the writer is CSDecl");
parser.DefineOptionalQualifier("out", ref s_out, "Output path. Default is the console.");
parser.DefineAliases("headerFile", "h");
parser.DefineOptionalQualifier("headerFile", ref s_headerFile, "(-h) Specify a file with header content to prepend to output.");
parser.DefineAliases("apiOnly", "api");
parser.DefineOptionalQualifier("apiOnly", ref s_apiOnly, "(-api) [CSDecl] Include only API's not CS code that compiles.");
parser.DefineOptionalQualifier("all", ref s_all, "Include all API's not just public APIs. Default is public only.");
parser.DefineAliases("memberHeadings", "mh");
parser.DefineOptionalQualifier("memberHeadings", ref s_memberHeadings, "(-mh) [CSDecl] Include member headings for each type of member.");
parser.DefineAliases("hightlightBaseMembers", "hbm");
parser.DefineOptionalQualifier("hightlightBaseMembers", ref s_hightlightBaseMembers, "(-hbm) [CSDecl] Highlight overridden base members.");
parser.DefineAliases("hightlightInterfaceMembers", "him");
parser.DefineOptionalQualifier("hightlightInterfaceMembers", ref s_hightlightInterfaceMembers, "(-him) [CSDecl] Highlight interface implementation members.");
parser.DefineAliases("throw", "t");
parser.DefineOptionalQualifier("throw", ref s_throw, "(-t) Method bodies should throw PlatformNotSupportedException.");
parser.DefineQualifier("assembly", ref s_assembly, "Path for an specific assembly or a directory to get all assemblies.");
}, args);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.SignalR.Internal;
using Microsoft.AspNetCore.SignalR.Protocol;
using Microsoft.AspNetCore.SignalR.StackExchangeRedis.Internal;
using Microsoft.AspNetCore.SignalR.Tests;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Xunit;
namespace Microsoft.AspNetCore.SignalR.StackExchangeRedis.Tests
{
public class RedisProtocolTests
{
private static readonly Dictionary<string, ProtocolTestData<int>> _ackTestData = new[]
{
CreateTestData("Zero", 0, 0x91, 0x00),
CreateTestData("Fixnum", 42, 0x91, 0x2A),
CreateTestData("Uint8", 180, 0x91, 0xCC, 0xB4),
CreateTestData("Uint16", 384, 0x91, 0xCD, 0x01, 0x80),
CreateTestData("Uint32", 70_000, 0x91, 0xCE, 0x00, 0x01, 0x11, 0x70),
}.ToDictionary(t => t.Name);
public static IEnumerable<object[]> AckTestData = _ackTestData.Keys.Select(k => new object[] { k });
[Theory]
[MemberData(nameof(AckTestData))]
public void ParseAck(string testName)
{
var testData = _ackTestData[testName];
var protocol = new RedisProtocol(CreateHubMessageSerializer(new List<IHubProtocol>()));
var decoded = protocol.ReadAck(testData.Encoded);
Assert.Equal(testData.Decoded, decoded);
}
[Theory]
[MemberData(nameof(AckTestData))]
public void WriteAck(string testName)
{
var testData = _ackTestData[testName];
var protocol = new RedisProtocol(CreateHubMessageSerializer(new List<IHubProtocol>()));
var encoded = protocol.WriteAck(testData.Decoded);
Assert.Equal(testData.Encoded, encoded);
}
private static readonly Dictionary<string, ProtocolTestData<RedisGroupCommand>> _groupCommandTestData = new[]
{
CreateTestData("GroupAdd", new RedisGroupCommand(42, "S", GroupAction.Add, "G", "C" ), 0x95, 0x2A, 0xA1, (byte)'S', 0x01, 0xA1, (byte)'G', 0xA1, (byte)'C'),
CreateTestData("GroupRemove", new RedisGroupCommand(42, "S", GroupAction.Remove, "G", "C" ), 0x95, 0x2A, 0xA1, (byte)'S', 0x02, 0xA1, (byte)'G', 0xA1, (byte)'C'),
}.ToDictionary(t => t.Name);
public static IEnumerable<object[]> GroupCommandTestData = _groupCommandTestData.Keys.Select(k => new object[] { k });
[Theory]
[MemberData(nameof(GroupCommandTestData))]
public void ParseGroupCommand(string testName)
{
var testData = _groupCommandTestData[testName];
var protocol = new RedisProtocol(CreateHubMessageSerializer(new List<IHubProtocol>()));
var decoded = protocol.ReadGroupCommand(testData.Encoded);
Assert.Equal(testData.Decoded.Id, decoded.Id);
Assert.Equal(testData.Decoded.ServerName, decoded.ServerName);
Assert.Equal(testData.Decoded.Action, decoded.Action);
Assert.Equal(testData.Decoded.GroupName, decoded.GroupName);
Assert.Equal(testData.Decoded.ConnectionId, decoded.ConnectionId);
}
[Theory]
[MemberData(nameof(GroupCommandTestData))]
public void WriteGroupCommand(string testName)
{
var testData = _groupCommandTestData[testName];
var protocol = new RedisProtocol(CreateHubMessageSerializer(new List<IHubProtocol>()));
var encoded = protocol.WriteGroupCommand(testData.Decoded);
Assert.Equal(testData.Encoded, encoded);
}
// The actual invocation message doesn't matter
private static readonly InvocationMessage _testMessage = new InvocationMessage("target", Array.Empty<object>());
// We use a func so we are guaranteed to get a new SerializedHubMessage for each test
private static readonly Dictionary<string, ProtocolTestData<Func<RedisInvocation>>> _invocationTestData = new[]
{
CreateTestData<Func<RedisInvocation>>(
"NoExcludedIds",
() => new RedisInvocation(new SerializedHubMessage(_testMessage), null),
0x92,
0x90,
0x82,
0xA2, (byte)'p', (byte)'1',
0xC4, 0x01, 0x2A,
0xA2, (byte)'p', (byte)'2',
0xC4, 0x01, 0x2A),
CreateTestData<Func<RedisInvocation>>(
"OneExcludedId",
() => new RedisInvocation(new SerializedHubMessage(_testMessage), new [] { "a" }),
0x92,
0x91,
0xA1, (byte)'a',
0x82,
0xA2, (byte)'p', (byte)'1',
0xC4, 0x01, 0x2A,
0xA2, (byte)'p', (byte)'2',
0xC4, 0x01, 0x2A),
CreateTestData<Func<RedisInvocation>>(
"ManyExcludedIds",
() => new RedisInvocation(new SerializedHubMessage(_testMessage), new [] { "a", "b", "c", "d", "e", "f" }),
0x92,
0x96,
0xA1, (byte)'a',
0xA1, (byte)'b',
0xA1, (byte)'c',
0xA1, (byte)'d',
0xA1, (byte)'e',
0xA1, (byte)'f',
0x82,
0xA2, (byte)'p', (byte)'1',
0xC4, 0x01, 0x2A,
0xA2, (byte)'p', (byte)'2',
0xC4, 0x01, 0x2A),
}.ToDictionary(t => t.Name);
public static IEnumerable<object[]> InvocationTestData = _invocationTestData.Keys.Select(k => new object[] { k });
[Theory]
[MemberData(nameof(InvocationTestData))]
public void ParseInvocation(string testName)
{
var testData = _invocationTestData[testName];
var hubProtocols = new[] { new DummyHubProtocol("p1"), new DummyHubProtocol("p2") };
var protocol = new RedisProtocol(CreateHubMessageSerializer(hubProtocols.Cast<IHubProtocol>().ToList()));
var expected = testData.Decoded();
var decoded = protocol.ReadInvocation(testData.Encoded);
Assert.Equal(expected.ExcludedConnectionIds, decoded.ExcludedConnectionIds);
// Verify the deserialized object has the necessary serialized forms
foreach (var hubProtocol in hubProtocols)
{
Assert.Equal(
expected.Message.GetSerializedMessage(hubProtocol).ToArray(),
decoded.Message.GetSerializedMessage(hubProtocol).ToArray());
var writtenMessages = hubProtocol.GetWrittenMessages();
Assert.Collection(writtenMessages,
actualMessage =>
{
var invocation = Assert.IsType<InvocationMessage>(actualMessage);
Assert.Same(_testMessage.Target, invocation.Target);
Assert.Same(_testMessage.Arguments, invocation.Arguments);
});
}
}
[Theory]
[MemberData(nameof(InvocationTestData))]
public void WriteInvocation(string testName)
{
var testData = _invocationTestData[testName];
var protocol = new RedisProtocol(CreateHubMessageSerializer(new List<IHubProtocol>() { new DummyHubProtocol("p1"), new DummyHubProtocol("p2") }));
// Actual invocation doesn't matter because we're using a dummy hub protocol.
// But the dummy protocol will check that we gave it the test message to make sure everything flows through properly.
var expected = testData.Decoded();
var encoded = protocol.WriteInvocation(_testMessage.Target, _testMessage.Arguments, expected.ExcludedConnectionIds);
Assert.Equal(testData.Encoded, encoded);
}
[Theory]
[MemberData(nameof(InvocationTestData))]
public void WriteInvocationWithHubMessageSerializer(string testName)
{
var testData = _invocationTestData[testName];
var hubMessageSerializer = CreateHubMessageSerializer(new List<IHubProtocol>() { new DummyHubProtocol("p1"), new DummyHubProtocol("p2") });
var protocol = new RedisProtocol(hubMessageSerializer);
// Actual invocation doesn't matter because we're using a dummy hub protocol.
// But the dummy protocol will check that we gave it the test message to make sure everything flows through properly.
var expected = testData.Decoded();
var encoded = protocol.WriteInvocation(_testMessage.Target, _testMessage.Arguments, expected.ExcludedConnectionIds);
Assert.Equal(testData.Encoded, encoded);
}
// Create ProtocolTestData<T> using the Power of Type Inference(TM).
private static ProtocolTestData<T> CreateTestData<T>(string name, T decoded, params byte[] encoded)
=> new ProtocolTestData<T>(name, decoded, encoded);
public class ProtocolTestData<T>
{
public string Name { get; }
public T Decoded { get; }
public byte[] Encoded { get; }
public ProtocolTestData(string name, T decoded, byte[] encoded)
{
Name = name;
Decoded = decoded;
Encoded = encoded;
}
}
private DefaultHubMessageSerializer CreateHubMessageSerializer(List<IHubProtocol> protocols)
{
var protocolResolver = new DefaultHubProtocolResolver(protocols, NullLogger<DefaultHubProtocolResolver>.Instance);
return new DefaultHubMessageSerializer(protocolResolver, protocols.ConvertAll(p => p.Name), hubSupportedProtocols: null);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.