context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
/*
Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft
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 SCG = System.Collections.Generic;
namespace RazorDBx.C5
{
/// <summary>
/// An entry in a dictionary from K to V.
/// </summary>
public struct KeyValuePair<K, V> : IEquatable<KeyValuePair<K, V>>, IShowable
{
/// <summary>
/// The key field of the entry
/// </summary>
public K Key;
/// <summary>
/// The value field of the entry
/// </summary>
public V Value;
/// <summary>
/// Create an entry with specified key and value
/// </summary>
/// <param name="key">The key</param>
/// <param name="value">The value</param>
public KeyValuePair(K key, V value) { Key = key; Value = value; }
/// <summary>
/// Create an entry with a specified key. The value will be the default value of type <code>V</code>.
/// </summary>
/// <param name="key">The key</param>
public KeyValuePair(K key) { Key = key; Value = default(V); }
/// <summary>
/// Pretty print an entry
/// </summary>
/// <returns>(key, value)</returns>
public override string ToString() { return "(" + Key + ", " + Value + ")"; }
/// <summary>
/// Check equality of entries.
/// </summary>
/// <param name="obj">The other object</param>
/// <returns>True if obj is an entry of the same type and has the same key and value</returns>
public override bool Equals(object obj)
{
if (!(obj is KeyValuePair<K, V>))
return false;
KeyValuePair<K, V> other = (KeyValuePair<K, V>)obj;
return Equals(other);
}
/// <summary>
/// Get the hash code of the pair.
/// </summary>
/// <returns>The hash code</returns>
public override int GetHashCode() { return EqualityComparer<K>.Default.GetHashCode(Key) + 13984681 * EqualityComparer<V>.Default.GetHashCode(Value); }
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(KeyValuePair<K, V> other)
{
return EqualityComparer<K>.Default.Equals(Key, other.Key) && EqualityComparer<V>.Default.Equals(Value, other.Value);
}
/// <summary>
///
/// </summary>
/// <param name="pair1"></param>
/// <param name="pair2"></param>
/// <returns></returns>
public static bool operator ==(KeyValuePair<K, V> pair1, KeyValuePair<K, V> pair2) { return pair1.Equals(pair2); }
/// <summary>
///
/// </summary>
/// <param name="pair1"></param>
/// <param name="pair2"></param>
/// <returns></returns>
public static bool operator !=(KeyValuePair<K, V> pair1, KeyValuePair<K, V> pair2) { return !pair1.Equals(pair2); }
#region IShowable Members
/// <summary>
///
/// </summary>
/// <param name="stringbuilder"></param>
/// <param name="formatProvider"></param>
/// <param name="rest"></param>
/// <returns></returns>
public bool Show(System.Text.StringBuilder stringbuilder, ref int rest, IFormatProvider formatProvider)
{
if (rest < 0)
return false;
if (!Showing.Show(Key, stringbuilder, ref rest, formatProvider))
return false;
stringbuilder.Append(" => ");
rest -= 4;
if (!Showing.Show(Value, stringbuilder, ref rest, formatProvider))
return false;
return rest >= 0;
}
#endregion
#region IFormattable Members
/// <summary>
///
/// </summary>
/// <param name="format"></param>
/// <param name="formatProvider"></param>
/// <returns></returns>
public string ToString(string format, IFormatProvider formatProvider)
{
return Showing.ShowString(this, format, formatProvider);
}
#endregion
}
/// <summary>
/// Default comparer for dictionary entries in a sorted dictionary.
/// Entry comparisons only look at keys and uses an externally defined comparer for that.
/// </summary>
public class KeyValuePairComparer<K, V> : SCG.IComparer<KeyValuePair<K, V>>
{
SCG.IComparer<K> comparer;
/// <summary>
/// Create an entry comparer for a item comparer of the keys
/// </summary>
/// <param name="comparer">Comparer of keys</param>
public KeyValuePairComparer(SCG.IComparer<K> comparer)
{
if (comparer == null)
throw new NullReferenceException();
this.comparer = comparer;
}
/// <summary>
/// Compare two entries
/// </summary>
/// <param name="entry1">First entry</param>
/// <param name="entry2">Second entry</param>
/// <returns>The result of comparing the keys</returns>
public int Compare(KeyValuePair<K, V> entry1, KeyValuePair<K, V> entry2)
{
return comparer.Compare(entry1.Key, entry2.Key);
}
}
/// <summary>
/// Default equalityComparer for dictionary entries.
/// Operations only look at keys and uses an externaly defined equalityComparer for that.
/// </summary>
public sealed class KeyValuePairEqualityComparer<K, V> : SCG.IEqualityComparer<KeyValuePair<K, V>>
{
SCG.IEqualityComparer<K> keyequalityComparer;
/// <summary>
/// Create an entry equalityComparer using the default equalityComparer for keys
/// </summary>
public KeyValuePairEqualityComparer() { keyequalityComparer = EqualityComparer<K>.Default; }
/// <summary>
/// Create an entry equalityComparer from a specified item equalityComparer for the keys
/// </summary>
/// <param name="keyequalityComparer">The key equalitySCG.Comparer</param>
public KeyValuePairEqualityComparer(SCG.IEqualityComparer<K> keyequalityComparer)
{
if (keyequalityComparer == null)
throw new NullReferenceException("Key equality comparer cannot be null");
this.keyequalityComparer = keyequalityComparer;
}
/// <summary>
/// Get the hash code of the entry
/// </summary>
/// <param name="entry">The entry</param>
/// <returns>The hash code of the key</returns>
public int GetHashCode(KeyValuePair<K, V> entry) { return keyequalityComparer.GetHashCode(entry.Key); }
/// <summary>
/// Test two entries for equality
/// </summary>
/// <param name="entry1">First entry</param>
/// <param name="entry2">Second entry</param>
/// <returns>True if keys are equal</returns>
public bool Equals(KeyValuePair<K, V> entry1, KeyValuePair<K, V> entry2)
{
return keyequalityComparer.Equals(entry1.Key, entry2.Key);
}
}
/// <summary>
/// A base class for implementing a dictionary based on a set collection implementation.
/// <i>See the source code for <see cref="T:C5.HashDictionary`2"/> for an example</i>
///
/// </summary>
public abstract class DictionaryBase<K, V> : CollectionValueBase<KeyValuePair<K, V>>, IDictionary<K, V>
{
/// <summary>
/// The set collection of entries underlying this dictionary implementation
/// </summary>
protected ICollection<KeyValuePair<K, V>> pairs;
SCG.IEqualityComparer<K> keyequalityComparer;
#region Events
ProxyEventBlock<KeyValuePair<K, V>> eventBlock;
/// <summary>
/// The change event. Will be raised for every change operation on the collection.
/// </summary>
public override event CollectionChangedHandler<KeyValuePair<K, V>> CollectionChanged
{
add { (eventBlock ?? (eventBlock = new ProxyEventBlock<KeyValuePair<K, V>>(this, pairs))).CollectionChanged += value; }
remove { if (eventBlock != null) eventBlock.CollectionChanged -= value; }
}
/// <summary>
/// The change event. Will be raised for every change operation on the collection.
/// </summary>
public override event CollectionClearedHandler<KeyValuePair<K, V>> CollectionCleared
{
add { (eventBlock ?? (eventBlock = new ProxyEventBlock<KeyValuePair<K, V>>(this, pairs))).CollectionCleared += value; }
remove { if (eventBlock != null) eventBlock.CollectionCleared -= value; }
}
/// <summary>
/// The item added event. Will be raised for every individual addition to the collection.
/// </summary>
public override event ItemsAddedHandler<KeyValuePair<K, V>> ItemsAdded
{
add { (eventBlock ?? (eventBlock = new ProxyEventBlock<KeyValuePair<K, V>>(this, pairs))).ItemsAdded += value; }
remove { if (eventBlock != null) eventBlock.ItemsAdded -= value; }
}
/// <summary>
/// The item added event. Will be raised for every individual removal from the collection.
/// </summary>
public override event ItemsRemovedHandler<KeyValuePair<K, V>> ItemsRemoved
{
add { (eventBlock ?? (eventBlock = new ProxyEventBlock<KeyValuePair<K, V>>(this, pairs))).ItemsRemoved += value; }
remove { if (eventBlock != null) eventBlock.ItemsRemoved -= value; }
}
/// <summary>
///
/// </summary>
public override EventTypeEnum ListenableEvents
{
get
{
return EventTypeEnum.Basic;
}
}
/// <summary>
///
/// </summary>
public override EventTypeEnum ActiveEvents
{
get
{
return pairs.ActiveEvents;
}
}
#endregion
/// <summary>
///
/// </summary>
/// <param name="keyequalityComparer"></param>
protected DictionaryBase(SCG.IEqualityComparer<K> keyequalityComparer)
{
if (keyequalityComparer == null)
throw new NullReferenceException("Key equality comparer cannot be null");
this.keyequalityComparer = keyequalityComparer;
}
#region IDictionary<K,V> Members
/// <summary>
///
/// </summary>
/// <value></value>
public virtual SCG.IEqualityComparer<K> EqualityComparer { get { return keyequalityComparer; } }
/// <summary>
/// Add a new (key, value) pair (a mapping) to the dictionary.
/// </summary>
/// <exception cref="DuplicateNotAllowedException"> if there already is an entry with the same key. </exception>
/// <param name="key">Key to add</param>
/// <param name="value">Value to add</param>
public virtual void Add(K key, V value)
{
KeyValuePair<K, V> p = new KeyValuePair<K, V>(key, value);
if (!pairs.Add(p))
throw new DuplicateNotAllowedException("Key being added: '" + key + "'");
}
/// <summary>
/// Add the entries from a collection of <see cref="T:C5.KeyValuePair`2"/> pairs to this dictionary.
/// <para><b>TODO: add restrictions L:K and W:V when the .Net SDK allows it </b></para>
/// </summary>
/// <exception cref="DuplicateNotAllowedException">
/// If the input contains duplicate keys or a key already present in this dictionary.</exception>
/// <param name="entries"></param>
public virtual void AddAll<L, W>(SCG.IEnumerable<KeyValuePair<L, W>> entries)
where L : K
where W : V
{
foreach (KeyValuePair<L, W> pair in entries)
{
KeyValuePair<K, V> p = new KeyValuePair<K, V>(pair.Key, pair.Value);
if (!pairs.Add(p))
throw new DuplicateNotAllowedException("Key being added: '" + pair.Key + "'");
}
}
/// <summary>
/// Remove an entry with a given key from the dictionary
/// </summary>
/// <param name="key">The key of the entry to remove</param>
/// <returns>True if an entry was found (and removed)</returns>
public virtual bool Remove(K key)
{
KeyValuePair<K, V> p = new KeyValuePair<K, V>(key);
return pairs.Remove(p);
}
/// <summary>
/// Remove an entry with a given key from the dictionary and report its value.
/// </summary>
/// <param name="key">The key of the entry to remove</param>
/// <param name="value">On exit, the value of the removed entry</param>
/// <returns>True if an entry was found (and removed)</returns>
public virtual bool Remove(K key, out V value)
{
KeyValuePair<K, V> p = new KeyValuePair<K, V>(key);
if (pairs.Remove(p, out p))
{
value = p.Value;
return true;
}
else
{
value = default(V);
return false;
}
}
/// <summary>
/// Remove all entries from the dictionary
/// </summary>
public virtual void Clear() { pairs.Clear(); }
/// <summary>
///
/// </summary>
/// <value></value>
public virtual Speed ContainsSpeed { get { return pairs.ContainsSpeed; } }
/// <summary>
/// Check if there is an entry with a specified key
/// </summary>
/// <param name="key">The key to look for</param>
/// <returns>True if key was found</returns>
public virtual bool Contains(K key)
{
KeyValuePair<K, V> p = new KeyValuePair<K, V>(key);
return pairs.Contains(p);
}
class LiftedEnumerable<H> : SCG.IEnumerable<KeyValuePair<K, V>> where H : K
{
SCG.IEnumerable<H> keys;
public LiftedEnumerable(SCG.IEnumerable<H> keys) { this.keys = keys; }
public SCG.IEnumerator<KeyValuePair<K, V>> GetEnumerator() { foreach (H key in keys) yield return new KeyValuePair<K, V>(key); }
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
#endregion
}
/// <summary>
///
/// </summary>
/// <param name="keys"></param>
/// <returns></returns>
public virtual bool ContainsAll<H>(SCG.IEnumerable<H> keys) where H : K
{
return pairs.ContainsAll(new LiftedEnumerable<H>(keys));
}
/// <summary>
/// Check if there is an entry with a specified key and report the corresponding
/// value if found. This can be seen as a safe form of "val = this[key]".
/// </summary>
/// <param name="key">The key to look for</param>
/// <param name="value">On exit, the value of the entry</param>
/// <returns>True if key was found</returns>
public virtual bool Find(ref K key, out V value)
{
KeyValuePair<K, V> p = new KeyValuePair<K, V>(key);
if (pairs.Find(ref p))
{
key = p.Key;
value = p.Value;
return true;
}
else
{
value = default(V);
return false;
}
}
/// <summary>
/// Look for a specific key in the dictionary and if found replace the value with a new one.
/// This can be seen as a non-adding version of "this[key] = val".
/// </summary>
/// <param name="key">The key to look for</param>
/// <param name="value">The new value</param>
/// <returns>True if key was found</returns>
public virtual bool Update(K key, V value)
{
KeyValuePair<K, V> p = new KeyValuePair<K, V>(key, value);
return pairs.Update(p);
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="oldvalue"></param>
/// <returns></returns>
public virtual bool Update(K key, V value, out V oldvalue)
{
KeyValuePair<K, V> p = new KeyValuePair<K, V>(key, value);
bool retval = pairs.Update(p, out p);
oldvalue = p.Value;
return retval;
}
/// <summary>
/// Look for a specific key in the dictionary. If found, report the corresponding value,
/// else add an entry with the key and the supplied value.
/// </summary>
/// <param name="key">On entry the key to look for</param>
/// <param name="value">On entry the value to add if the key is not found.
/// On exit the value found if any.</param>
/// <returns>True if key was found</returns>
public virtual bool FindOrAdd(K key, ref V value)
{
KeyValuePair<K, V> p = new KeyValuePair<K, V>(key, value);
if (!pairs.FindOrAdd(ref p))
return false;
else
{
value = p.Value;
//key = p.key;
return true;
}
}
/// <summary>
/// Update value in dictionary corresponding to key if found, else add new entry.
/// More general than "this[key] = val;" by reporting if key was found.
/// </summary>
/// <param name="key">The key to look for</param>
/// <param name="value">The value to add or replace with.</param>
/// <returns>True if entry was updated.</returns>
public virtual bool UpdateOrAdd(K key, V value)
{
return pairs.UpdateOrAdd(new KeyValuePair<K, V>(key, value));
}
/// <summary>
/// Update value in dictionary corresponding to key if found, else add new entry.
/// More general than "this[key] = val;" by reporting if key was found and the old value if any.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="oldvalue"></param>
/// <returns></returns>
public virtual bool UpdateOrAdd(K key, V value, out V oldvalue)
{
KeyValuePair<K, V> p = new KeyValuePair<K, V>(key, value);
bool retval = pairs.UpdateOrAdd(p, out p);
oldvalue = p.Value;
return retval;
}
#region Keys,Values support classes
internal class ValuesCollection : CollectionValueBase<V>, ICollectionValue<V>
{
ICollection<KeyValuePair<K, V>> pairs;
internal ValuesCollection(ICollection<KeyValuePair<K, V>> pairs)
{ this.pairs = pairs; }
public override V Choose() { return pairs.Choose().Value; }
public override SCG.IEnumerator<V> GetEnumerator()
{
//Updatecheck is performed by the pairs enumerator
foreach (KeyValuePair<K, V> p in pairs)
yield return p.Value;
}
public override bool IsEmpty { get { return pairs.IsEmpty; } }
public override int Count { get { return pairs.Count; } }
public override Speed CountSpeed { get { return Speed.Constant; } }
}
internal class KeysCollection : CollectionValueBase<K>, ICollectionValue<K>
{
ICollection<KeyValuePair<K, V>> pairs;
internal KeysCollection(ICollection<KeyValuePair<K, V>> pairs)
{ this.pairs = pairs; }
public override K Choose() { return pairs.Choose().Key; }
public override SCG.IEnumerator<K> GetEnumerator()
{
foreach (KeyValuePair<K, V> p in pairs)
yield return p.Key;
}
public override bool IsEmpty { get { return pairs.IsEmpty; } }
public override int Count { get { return pairs.Count; } }
public override Speed CountSpeed { get { return pairs.CountSpeed; } }
}
#endregion
/// <summary>
///
/// </summary>
/// <value>A collection containg the all the keys of the dictionary</value>
public virtual ICollectionValue<K> Keys { get { return new KeysCollection(pairs); } }
/// <summary>
///
/// </summary>
/// <value>A collection containing all the values of the dictionary</value>
public virtual ICollectionValue<V> Values { get { return new ValuesCollection(pairs); } }
/// <summary>
///
/// </summary>
public virtual Func<K, V> Func { get { return delegate(K k) { return this[k]; }; } }
/// <summary>
/// Indexer by key for dictionary.
/// <para>The get method will throw an exception if no entry is found. </para>
/// <para>The set method behaves like <see cref="M:C5.DictionaryBase`2.UpdateOrAdd(`0,`1)"/>.</para>
/// </summary>
/// <exception cref="NoSuchItemException"> On get if no entry is found. </exception>
/// <value>The value corresponding to the key</value>
public virtual V this[K key]
{
get
{
KeyValuePair<K, V> p = new KeyValuePair<K, V>(key);
if (pairs.Find(ref p))
return p.Value;
else
throw new NoSuchItemException("Key '" + key.ToString() + "' not present in Dictionary");
}
set
{ pairs.UpdateOrAdd(new KeyValuePair<K, V>(key, value)); }
}
/// <summary>
///
/// </summary>
/// <value>True if dictionary is read only</value>
public virtual bool IsReadOnly { get { return pairs.IsReadOnly; } }
/// <summary>
/// Check the integrity of the internal data structures of this dictionary.
/// </summary>
/// <returns>True if check does not fail.</returns>
public virtual bool Check() { return pairs.Check(); }
#endregion
#region ICollectionValue<KeyValuePair<K,V>> Members
/// <summary>
///
/// </summary>
/// <value>True if this collection is empty.</value>
public override bool IsEmpty { get { return pairs.IsEmpty; } }
/// <summary>
///
/// </summary>
/// <value>The number of entrues in the dictionary</value>
public override int Count { get { return pairs.Count; } }
/// <summary>
///
/// </summary>
/// <value>The number of entrues in the dictionary</value>
public override Speed CountSpeed { get { return pairs.CountSpeed; } }
/// <summary>
/// Choose some entry in this Dictionary.
/// </summary>
/// <exception cref="NoSuchItemException">if collection is empty.</exception>
/// <returns></returns>
public override KeyValuePair<K, V> Choose() { return pairs.Choose(); }
/// <summary>
/// Create an enumerator for the collection of entries of the dictionary
/// </summary>
/// <returns>The enumerator</returns>
public override SCG.IEnumerator<KeyValuePair<K, V>> GetEnumerator()
{
return pairs.GetEnumerator(); ;
}
#endregion
/// <summary>
///
/// </summary>
/// <param name="stringbuilder"></param>
/// <param name="rest"></param>
/// <param name="formatProvider"></param>
/// <returns></returns>
public override bool Show(System.Text.StringBuilder stringbuilder, ref int rest, IFormatProvider formatProvider)
{
return Showing.ShowDictionary<K, V>(this, stringbuilder, ref rest, formatProvider);
}
}
/// <summary>
/// A base class for implementing a sorted dictionary based on a sorted set collection implementation.
/// <i>See the source code for <see cref="T:C5.TreeDictionary`2"/> for an example</i>
///
/// </summary>
public abstract class SortedDictionaryBase<K, V> : DictionaryBase<K, V>, ISortedDictionary<K, V>
{
#region Fields
/// <summary>
///
/// </summary>
protected ISorted<KeyValuePair<K, V>> sortedpairs;
SCG.IComparer<K> keycomparer;
/// <summary>
///
/// </summary>
/// <param name="keycomparer"></param>
/// <param name="keyequalityComparer"></param>
protected SortedDictionaryBase(SCG.IComparer<K> keycomparer, SCG.IEqualityComparer<K> keyequalityComparer) : base(keyequalityComparer) { this.keycomparer = keycomparer; }
#endregion
#region ISortedDictionary<K,V> Members
/// <summary>
/// The key comparer used by this dictionary.
/// </summary>
/// <value></value>
public SCG.IComparer<K> Comparer { get { return keycomparer; } }
/// <summary>
///
/// </summary>
/// <value></value>
public new ISorted<K> Keys { get { return new SortedKeysCollection(this, sortedpairs, keycomparer, EqualityComparer); } }
/// <summary>
/// Find the entry in the dictionary whose key is the
/// predecessor of the specified key.
/// </summary>
/// <param name="key">The key</param>
/// <param name="res">The predecessor, if any</param>
/// <returns>True if key has a predecessor</returns>
public bool TryPredecessor(K key, out KeyValuePair<K, V> res)
{
return sortedpairs.TryPredecessor(new KeyValuePair<K, V>(key), out res);
}
/// <summary>
/// Find the entry in the dictionary whose key is the
/// successor of the specified key.
/// </summary>
/// <param name="key">The key</param>
/// <param name="res">The successor, if any</param>
/// <returns>True if the key has a successor</returns>
public bool TrySuccessor(K key, out KeyValuePair<K, V> res)
{
return sortedpairs.TrySuccessor(new KeyValuePair<K, V>(key), out res);
}
/// <summary>
/// Find the entry in the dictionary whose key is the
/// weak predecessor of the specified key.
/// </summary>
/// <param name="key">The key</param>
/// <param name="res">The predecessor, if any</param>
/// <returns>True if key has a weak predecessor</returns>
public bool TryWeakPredecessor(K key, out KeyValuePair<K, V> res)
{
return sortedpairs.TryWeakPredecessor(new KeyValuePair<K, V>(key), out res);
}
/// <summary>
/// Find the entry in the dictionary whose key is the
/// weak successor of the specified key.
/// </summary>
/// <param name="key">The key</param>
/// <param name="res">The weak successor, if any</param>
/// <returns>True if the key has a weak successor</returns>
public bool TryWeakSuccessor(K key, out KeyValuePair<K, V> res)
{
return sortedpairs.TryWeakSuccessor(new KeyValuePair<K, V>(key), out res);
}
/// <summary>
/// Get the entry in the dictionary whose key is the
/// predecessor of the specified key.
/// </summary>
/// <exception cref="NoSuchItemException"></exception>
/// <param name="key">The key</param>
/// <returns>The entry</returns>
public KeyValuePair<K, V> Predecessor(K key)
{
return sortedpairs.Predecessor(new KeyValuePair<K, V>(key));
}
/// <summary>
/// Get the entry in the dictionary whose key is the
/// successor of the specified key.
/// </summary>
/// <exception cref="NoSuchItemException"></exception>
/// <param name="key">The key</param>
/// <returns>The entry</returns>
public KeyValuePair<K, V> Successor(K key)
{
return sortedpairs.Successor(new KeyValuePair<K, V>(key));
}
/// <summary>
/// Get the entry in the dictionary whose key is the
/// weak predecessor of the specified key.
/// </summary>
/// <exception cref="NoSuchItemException"></exception>
/// <param name="key">The key</param>
/// <returns>The entry</returns>
public KeyValuePair<K, V> WeakPredecessor(K key)
{
return sortedpairs.WeakPredecessor(new KeyValuePair<K, V>(key));
}
/// <summary>
/// Get the entry in the dictionary whose key is the
/// weak successor of the specified key.
/// </summary>
/// <exception cref="NoSuchItemException"></exception>
/// <param name="key">The key</param>
/// <returns>The entry</returns>
public KeyValuePair<K, V> WeakSuccessor(K key)
{
return sortedpairs.WeakSuccessor(new KeyValuePair<K, V>(key));
}
#endregion
#region ISortedDictionary<K,V> Members
/// <summary>
///
/// </summary>
/// <returns></returns>
public KeyValuePair<K, V> FindMin()
{
return sortedpairs.FindMin();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public KeyValuePair<K, V> DeleteMin()
{
return sortedpairs.DeleteMin();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public KeyValuePair<K, V> FindMax()
{
return sortedpairs.FindMax();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public KeyValuePair<K, V> DeleteMax()
{
return sortedpairs.DeleteMax();
}
/// <summary>
///
/// </summary>
/// <param name="cutter"></param>
/// <param name="lowEntry"></param>
/// <param name="lowIsValid"></param>
/// <param name="highEntry"></param>
/// <param name="highIsValid"></param>
/// <returns></returns>
public bool Cut(IComparable<K> cutter, out KeyValuePair<K, V> lowEntry, out bool lowIsValid, out KeyValuePair<K, V> highEntry, out bool highIsValid)
{
return sortedpairs.Cut(new KeyValuePairComparable(cutter), out lowEntry, out lowIsValid, out highEntry, out highIsValid);
}
/// <summary>
///
/// </summary>
/// <param name="bot"></param>
/// <returns></returns>
public IDirectedEnumerable<KeyValuePair<K, V>> RangeFrom(K bot)
{
return sortedpairs.RangeFrom(new KeyValuePair<K, V>(bot));
}
/// <summary>
///
/// </summary>
/// <param name="bot"></param>
/// <param name="top"></param>
/// <returns></returns>
public IDirectedEnumerable<KeyValuePair<K, V>> RangeFromTo(K bot, K top)
{
return sortedpairs.RangeFromTo(new KeyValuePair<K, V>(bot), new KeyValuePair<K, V>(top));
}
/// <summary>
///
/// </summary>
/// <param name="top"></param>
/// <returns></returns>
public IDirectedEnumerable<KeyValuePair<K, V>> RangeTo(K top)
{
return sortedpairs.RangeTo(new KeyValuePair<K, V>(top));
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IDirectedCollectionValue<KeyValuePair<K, V>> RangeAll()
{
return sortedpairs.RangeAll();
}
/// <summary>
///
/// </summary>
/// <param name="items"></param>
public void AddSorted(SCG.IEnumerable<KeyValuePair<K, V>> items)
{
sortedpairs.AddSorted(items);
}
/// <summary>
///
/// </summary>
/// <param name="lowKey"></param>
public void RemoveRangeFrom(K lowKey)
{
sortedpairs.RemoveRangeFrom(new KeyValuePair<K, V>(lowKey));
}
/// <summary>
///
/// </summary>
/// <param name="lowKey"></param>
/// <param name="highKey"></param>
public void RemoveRangeFromTo(K lowKey, K highKey)
{
sortedpairs.RemoveRangeFromTo(new KeyValuePair<K, V>(lowKey), new KeyValuePair<K, V>(highKey));
}
/// <summary>
///
/// </summary>
/// <param name="highKey"></param>
public void RemoveRangeTo(K highKey)
{
sortedpairs.RemoveRangeTo(new KeyValuePair<K, V>(highKey));
}
#endregion
class KeyValuePairComparable : IComparable<KeyValuePair<K, V>>
{
IComparable<K> cutter;
internal KeyValuePairComparable(IComparable<K> cutter) { this.cutter = cutter; }
public int CompareTo(KeyValuePair<K, V> other) { return cutter.CompareTo(other.Key); }
public bool Equals(KeyValuePair<K, V> other) { return cutter.Equals(other.Key); }
}
class ProjectedDirectedEnumerable : MappedDirectedEnumerable<KeyValuePair<K, V>, K>
{
public ProjectedDirectedEnumerable(IDirectedEnumerable<KeyValuePair<K, V>> directedpairs) : base(directedpairs) { }
public override K Map(KeyValuePair<K, V> pair) { return pair.Key; }
}
class ProjectedDirectedCollectionValue : MappedDirectedCollectionValue<KeyValuePair<K, V>, K>
{
public ProjectedDirectedCollectionValue(IDirectedCollectionValue<KeyValuePair<K, V>> directedpairs) : base(directedpairs) { }
public override K Map(KeyValuePair<K, V> pair) { return pair.Key; }
}
class SortedKeysCollection : SequencedBase<K>, ISorted<K>
{
ISortedDictionary<K, V> sorteddict;
//TODO: eliminate this. Only problem is the Find method because we lack method on dictionary that also
// returns the actual key.
ISorted<KeyValuePair<K, V>> sortedpairs;
SCG.IComparer<K> comparer;
internal SortedKeysCollection(ISortedDictionary<K, V> sorteddict, ISorted<KeyValuePair<K, V>> sortedpairs, SCG.IComparer<K> comparer, SCG.IEqualityComparer<K> itemequalityComparer)
: base(itemequalityComparer)
{
this.sorteddict = sorteddict;
this.sortedpairs = sortedpairs;
this.comparer = comparer;
}
public override K Choose() { return sorteddict.Choose().Key; }
public override SCG.IEnumerator<K> GetEnumerator()
{
foreach (KeyValuePair<K, V> p in sorteddict)
yield return p.Key;
}
public override bool IsEmpty { get { return sorteddict.IsEmpty; } }
public override int Count { get { return sorteddict.Count; } }
public override Speed CountSpeed { get { return sorteddict.CountSpeed; } }
#region ISorted<K> Members
public K FindMin() { return sorteddict.FindMin().Key; }
public K DeleteMin() { throw new ReadOnlyCollectionException(); }
public K FindMax() { return sorteddict.FindMax().Key; }
public K DeleteMax() { throw new ReadOnlyCollectionException(); }
public SCG.IComparer<K> Comparer { get { return comparer; } }
public bool TryPredecessor(K item, out K res)
{
KeyValuePair<K, V> pRes;
bool success = sorteddict.TryPredecessor(item, out pRes);
res = pRes.Key;
return success;
}
public bool TrySuccessor(K item, out K res)
{
KeyValuePair<K, V> pRes;
bool success = sorteddict.TrySuccessor(item, out pRes);
res = pRes.Key;
return success;
}
public bool TryWeakPredecessor(K item, out K res)
{
KeyValuePair<K, V> pRes;
bool success = sorteddict.TryWeakPredecessor(item, out pRes);
res = pRes.Key;
return success;
}
public bool TryWeakSuccessor(K item, out K res)
{
KeyValuePair<K, V> pRes;
bool success = sorteddict.TryWeakSuccessor(item, out pRes);
res = pRes.Key;
return success;
}
public K Predecessor(K item) { return sorteddict.Predecessor(item).Key; }
public K Successor(K item) { return sorteddict.Successor(item).Key; }
public K WeakPredecessor(K item) { return sorteddict.WeakPredecessor(item).Key; }
public K WeakSuccessor(K item) { return sorteddict.WeakSuccessor(item).Key; }
public bool Cut(IComparable<K> c, out K low, out bool lowIsValid, out K high, out bool highIsValid)
{
KeyValuePair<K, V> lowpair, highpair;
bool retval = sorteddict.Cut(c, out lowpair, out lowIsValid, out highpair, out highIsValid);
low = lowpair.Key;
high = highpair.Key;
return retval;
}
public IDirectedEnumerable<K> RangeFrom(K bot)
{
return new ProjectedDirectedEnumerable(sorteddict.RangeFrom(bot));
}
public IDirectedEnumerable<K> RangeFromTo(K bot, K top)
{
return new ProjectedDirectedEnumerable(sorteddict.RangeFromTo(bot, top));
}
public IDirectedEnumerable<K> RangeTo(K top)
{
return new ProjectedDirectedEnumerable(sorteddict.RangeTo(top));
}
public IDirectedCollectionValue<K> RangeAll()
{
return new ProjectedDirectedCollectionValue(sorteddict.RangeAll());
}
public void AddSorted(SCG.IEnumerable<K> items) { throw new ReadOnlyCollectionException(); }
public void RemoveRangeFrom(K low) { throw new ReadOnlyCollectionException(); }
public void RemoveRangeFromTo(K low, K hi) { throw new ReadOnlyCollectionException(); }
public void RemoveRangeTo(K hi) { throw new ReadOnlyCollectionException(); }
#endregion
#region ICollection<K> Members
public Speed ContainsSpeed { get { return sorteddict.ContainsSpeed; } }
public bool Contains(K key) { return sorteddict.Contains(key); ; }
public int ContainsCount(K item) { return sorteddict.Contains(item) ? 1 : 0; }
/// <summary>
///
/// </summary>
/// <returns></returns>
public virtual ICollectionValue<K> UniqueItems()
{
return this;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public virtual ICollectionValue<KeyValuePair<K, int>> ItemMultiplicities()
{
return new MultiplicityOne<K>(this);
}
public bool ContainsAll(SCG.IEnumerable<K> items)
{
//TODO: optimize?
foreach (K item in items)
if (!sorteddict.Contains(item))
return false;
return true;
}
public bool Find(ref K item)
{
KeyValuePair<K, V> p = new KeyValuePair<K, V>(item);
bool retval = sortedpairs.Find(ref p);
item = p.Key;
return retval;
}
public bool FindOrAdd(ref K item) { throw new ReadOnlyCollectionException(); }
public bool Update(K item) { throw new ReadOnlyCollectionException(); }
public bool Update(K item, out K olditem) { throw new ReadOnlyCollectionException(); }
public bool UpdateOrAdd(K item) { throw new ReadOnlyCollectionException(); }
public bool UpdateOrAdd(K item, out K olditem) { throw new ReadOnlyCollectionException(); }
public bool Remove(K item) { throw new ReadOnlyCollectionException(); }
public bool Remove(K item, out K removeditem) { throw new ReadOnlyCollectionException(); }
public void RemoveAllCopies(K item) { throw new ReadOnlyCollectionException(); }
public void RemoveAll(SCG.IEnumerable<K> items) { throw new ReadOnlyCollectionException(); }
public void Clear() { throw new ReadOnlyCollectionException(); }
public void RetainAll(SCG.IEnumerable<K> items) { throw new ReadOnlyCollectionException(); }
#endregion
#region IExtensible<K> Members
public override bool IsReadOnly { get { return true; } }
public bool AllowsDuplicates { get { return false; } }
public bool DuplicatesByCounting { get { return true; } }
public bool Add(K item) { throw new ReadOnlyCollectionException(); }
void SCG.ICollection<K>.Add(K item) { throw new ReadOnlyCollectionException(); }
public void AddAll(System.Collections.Generic.IEnumerable<K> items) { throw new ReadOnlyCollectionException(); }
public bool Check() { return sorteddict.Check(); }
#endregion
#region IDirectedCollectionValue<K> Members
public override IDirectedCollectionValue<K> Backwards()
{
return RangeAll().Backwards();
}
#endregion
#region IDirectedEnumerable<K> Members
IDirectedEnumerable<K> IDirectedEnumerable<K>.Backwards() { return Backwards(); }
#endregion
}
/// <summary>
///
/// </summary>
/// <param name="stringbuilder"></param>
/// <param name="rest"></param>
/// <param name="formatProvider"></param>
/// <returns></returns>
public override bool Show(System.Text.StringBuilder stringbuilder, ref int rest, IFormatProvider formatProvider)
{
return Showing.ShowDictionary<K, V>(this, stringbuilder, ref rest, formatProvider);
}
}
class SortedArrayDictionary<K, V> : SortedDictionaryBase<K, V>
{
#region Constructors
public SortedArrayDictionary() : this(SCG.Comparer<K>.Default, EqualityComparer<K>.Default) { }
/// <summary>
/// Create a red-black tree dictionary using an external comparer for keys.
/// </summary>
/// <param name="comparer">The external comparer</param>
public SortedArrayDictionary(SCG.IComparer<K> comparer) : this(comparer, new ComparerZeroHashCodeEqualityComparer<K>(comparer)) { }
/// <summary>
///
/// </summary>
/// <param name="comparer"></param>
/// <param name="equalityComparer"></param>
public SortedArrayDictionary(SCG.IComparer<K> comparer, SCG.IEqualityComparer<K> equalityComparer)
: base(comparer, equalityComparer)
{
pairs = sortedpairs = new SortedArray<KeyValuePair<K, V>>(new KeyValuePairComparer<K, V>(comparer));
}
/// <summary>
///
/// </summary>
/// <param name="comparer"></param>
/// <param name="equalityComparer"></param>
/// <param name="capacity"></param>
public SortedArrayDictionary(int capacity, SCG.IComparer<K> comparer, SCG.IEqualityComparer<K> equalityComparer)
: base(comparer, equalityComparer)
{
pairs = sortedpairs = new SortedArray<KeyValuePair<K, V>>(capacity, new KeyValuePairComparer<K, V>(comparer));
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.StreamAnalytics;
using Microsoft.Azure.Management.StreamAnalytics.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.StreamAnalytics
{
public partial class StreamAnalyticsManagementClient : ServiceClient<StreamAnalyticsManagementClient>, IStreamAnalyticsManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// The URI used as the base for all Service Management requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
set { this._baseUri = value; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// When you create a Windows Azure subscription, it is uniquely
/// identified by a subscription ID. The subscription ID forms part of
/// the URI for every call that you make to the Service Management
/// API. The Windows Azure Service ManagementAPI use mutual
/// authentication of management certificates over SSL to ensure that
/// a request made to the service is secure. No anonymous requests are
/// allowed.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
set { this._credentials = value; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IFunctionOperations _functions;
/// <summary>
/// Operations for managing the function(s) of the stream analytics job.
/// </summary>
public virtual IFunctionOperations Functions
{
get { return this._functions; }
}
private IInputOperations _inputs;
/// <summary>
/// Operations for managing the input(s) of the stream analytics job.
/// </summary>
public virtual IInputOperations Inputs
{
get { return this._inputs; }
}
private IJobOperations _streamingJobs;
/// <summary>
/// Operations for managing the stream analytics job.
/// </summary>
public virtual IJobOperations StreamingJobs
{
get { return this._streamingJobs; }
}
private IOutputOperations _outputs;
/// <summary>
/// Operations for managing the output(s) of the stream analytics job.
/// </summary>
public virtual IOutputOperations Outputs
{
get { return this._outputs; }
}
private ISubscriptionOperations _subscriptions;
/// <summary>
/// Operations for Azure Stream Analytics subscription information.
/// </summary>
public virtual ISubscriptionOperations Subscriptions
{
get { return this._subscriptions; }
}
private ITransformationOperations _transformations;
/// <summary>
/// Operations for managing the transformation definition of the stream
/// analytics job.
/// </summary>
public virtual ITransformationOperations Transformations
{
get { return this._transformations; }
}
/// <summary>
/// Initializes a new instance of the StreamAnalyticsManagementClient
/// class.
/// </summary>
public StreamAnalyticsManagementClient()
: base()
{
this._functions = new FunctionOperations(this);
this._inputs = new InputOperations(this);
this._streamingJobs = new JobOperations(this);
this._outputs = new OutputOperations(this);
this._subscriptions = new SubscriptionOperations(this);
this._transformations = new TransformationOperations(this);
this._apiVersion = "2015-10-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(60);
}
/// <summary>
/// Initializes a new instance of the StreamAnalyticsManagementClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. When you create a Windows Azure subscription, it is
/// uniquely identified by a subscription ID. The subscription ID
/// forms part of the URI for every call that you make to the Service
/// Management API. The Windows Azure Service ManagementAPI use mutual
/// authentication of management certificates over SSL to ensure that
/// a request made to the service is secure. No anonymous requests are
/// allowed.
/// </param>
/// <param name='baseUri'>
/// Optional. The URI used as the base for all Service Management
/// requests.
/// </param>
public StreamAnalyticsManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the StreamAnalyticsManagementClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. When you create a Windows Azure subscription, it is
/// uniquely identified by a subscription ID. The subscription ID
/// forms part of the URI for every call that you make to the Service
/// Management API. The Windows Azure Service ManagementAPI use mutual
/// authentication of management certificates over SSL to ensure that
/// a request made to the service is secure. No anonymous requests are
/// allowed.
/// </param>
public StreamAnalyticsManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the StreamAnalyticsManagementClient
/// class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public StreamAnalyticsManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._functions = new FunctionOperations(this);
this._inputs = new InputOperations(this);
this._streamingJobs = new JobOperations(this);
this._outputs = new OutputOperations(this);
this._subscriptions = new SubscriptionOperations(this);
this._transformations = new TransformationOperations(this);
this._apiVersion = "2015-10-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(60);
}
/// <summary>
/// Initializes a new instance of the StreamAnalyticsManagementClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. When you create a Windows Azure subscription, it is
/// uniquely identified by a subscription ID. The subscription ID
/// forms part of the URI for every call that you make to the Service
/// Management API. The Windows Azure Service ManagementAPI use mutual
/// authentication of management certificates over SSL to ensure that
/// a request made to the service is secure. No anonymous requests are
/// allowed.
/// </param>
/// <param name='baseUri'>
/// Optional. The URI used as the base for all Service Management
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public StreamAnalyticsManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the StreamAnalyticsManagementClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. When you create a Windows Azure subscription, it is
/// uniquely identified by a subscription ID. The subscription ID
/// forms part of the URI for every call that you make to the Service
/// Management API. The Windows Azure Service ManagementAPI use mutual
/// authentication of management certificates over SSL to ensure that
/// a request made to the service is secure. No anonymous requests are
/// allowed.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public StreamAnalyticsManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// StreamAnalyticsManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of StreamAnalyticsManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<StreamAnalyticsManagementClient> client)
{
base.Clone(client);
if (client is StreamAnalyticsManagementClient)
{
StreamAnalyticsManagementClient clonedClient = ((StreamAnalyticsManagementClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResponse> GetLongRunningOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
{
// Validate
if (operationStatusLink == null)
{
throw new ArgumentNullException("operationStatusLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("operationStatusLink", operationStatusLink);
TracingAdapter.Enter(invocationId, this, "GetLongRunningOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + operationStatusLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent && statusCode != HttpStatusCode.NotFound && statusCode != HttpStatusCode.Conflict && statusCode != HttpStatusCode.PreconditionFailed)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LongRunningOperationResponse result = null;
// Deserialize Response
result = new LongRunningOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.NotFound)
{
result.Status = OperationStatus.Failed;
}
if (statusCode == HttpStatusCode.PreconditionFailed)
{
result.Status = OperationStatus.Failed;
}
if (statusCode == HttpStatusCode.Conflict)
{
result.Status = OperationStatus.Failed;
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
if (statusCode == HttpStatusCode.NoContent)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The test result of the input or output data source.
/// </returns>
public async Task<ResourceTestConnectionResponse> GetTestConnectionStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
{
// Validate
if (operationStatusLink == null)
{
throw new ArgumentNullException("operationStatusLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("operationStatusLink", operationStatusLink);
TracingAdapter.Enter(invocationId, this, "GetTestConnectionStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + operationStatusLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent && statusCode != HttpStatusCode.BadRequest)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ResourceTestConnectionResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted || statusCode == HttpStatusCode.NoContent || statusCode == HttpStatusCode.BadRequest)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ResourceTestConnectionResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken statusValue = responseDoc["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
string statusInstance = ((string)statusValue);
result.ResourceTestStatus = statusInstance;
}
JToken errorValue = responseDoc["error"];
if (errorValue != null && errorValue.Type != JTokenType.Null)
{
ErrorResponse errorInstance = new ErrorResponse();
result.Error = errorInstance;
JToken codeValue = errorValue["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = errorValue["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
JToken detailsValue = errorValue["details"];
if (detailsValue != null && detailsValue.Type != JTokenType.Null)
{
ErrorDetailsResponse detailsInstance = new ErrorDetailsResponse();
errorInstance.Details = detailsInstance;
JToken codeValue2 = detailsValue["code"];
if (codeValue2 != null && codeValue2.Type != JTokenType.Null)
{
string codeInstance2 = ((string)codeValue2);
detailsInstance.Code = codeInstance2;
}
JToken messageValue2 = detailsValue["message"];
if (messageValue2 != null && messageValue2.Type != JTokenType.Null)
{
string messageInstance2 = ((string)messageValue2);
detailsInstance.Message = messageInstance2;
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.NotFound)
{
result.Status = OperationStatus.Failed;
}
if (statusCode == HttpStatusCode.BadRequest)
{
result.Status = OperationStatus.Failed;
}
if (result.ResourceTestStatus == ResourceTestStatus.TestFailed)
{
result.Status = OperationStatus.Failed;
}
if (result.ResourceTestStatus == ResourceTestStatus.TestSucceeded)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/*
* Copyright 2014 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;
using System.Runtime.InteropServices;
using System.IO;
using System.Linq;
using UnityEngine;
using System.Reflection;
namespace Tango
{
public delegate void PermissionsEvent(bool permissionsGranted);
/// <summary>
/// Entry point of Tango applications, maintain the application handler.
/// </summary>
public class TangoApplication : MonoBehaviour
{
///<summary>
/// Permission types used by Tango applications.
/// </summary>
[Flags]
private enum PermissionsTypes
{
// All entries must be a power of two for
// use in a bit field as flags.
NONE = 0,
MOTION_TRACKING = 0x1,
AREA_LEARNING = 0x2,
}
public bool m_enableMotionTracking = true;
public bool m_enableDepth = true;
public bool m_enableVideoOverlay = false;
public bool m_motionTrackingAutoReset = true;
public bool m_enableAreaLearning = false;
public bool m_enableUXLibrary = true;
public bool m_drawDefaultUXExceptions = true;
public bool m_useExperimentalVideoOverlay = true;
public bool m_useExperimentalADF = false;
public bool m_useLowLatencyIMUIntegration = true;
private static string m_tangoServiceVersion = string.Empty;
private const string CLASS_NAME = "TangoApplication";
private const string ANDROID_PRO_LABEL_TEXT = "<size=30>Tango plugin requires Unity Android Pro!</size>";
private const float ANDROID_PRO_LABEL_PERCENT_X = 0.5f;
private const float ANDROID_PRO_LABEL_PERCENT_Y = 0.5f;
private const float ANDROID_PRO_LABEL_WIDTH = 200.0f;
private const float ANDROID_PRO_LABEL_HEIGHT = 200.0f;
private const string DEFAULT_AREA_DESCRIPTION = "/sdcard/defaultArea";
private const string MOTION_TRACKING_LOG_PREFIX = "Motion tracking mode : ";
private const int MINIMUM_API_VERSION = 1978;
private event PermissionsEvent m_permissionEvent;
private PermissionsTypes m_requiredPermissions = 0;
private static bool m_isValidTangoAPIVersion = false;
private static bool m_hasVersionBeenChecked = false;
private DepthProvider m_depthProvider;
private IntPtr m_callbackContext = IntPtr.Zero;
private bool m_isServiceConnected = false;
private bool m_shouldReconnectService = false;
private bool m_isDisconnecting = false;
private bool m_sendPermissions = false;
private bool m_permissionsSuccessful = false;
private PoseListener m_poseListener;
private DepthListener m_depthListener;
private VideoOverlayListener m_videoOverlayListener;
private TangoEventListener m_tangoEventListener;
private YUVTexture m_yuvTexture;
/// <summary>
/// Gets the video overlay texture.
/// </summary>
/// <returns>The video overlay texture.</returns>
public YUVTexture GetVideoOverlayTextureYUV()
{
return m_yuvTexture;
}
/// <summary>
/// Gets the tango service version.
/// </summary>
/// <returns>The tango service version.</returns>
public static string GetTangoServiceVersion()
{
if (m_tangoServiceVersion == string.Empty)
{
m_tangoServiceVersion = AndroidHelper.GetVersionName("com.projecttango.tango");
}
return m_tangoServiceVersion;
}
/// <summary>
/// Register the specified tangoObject.
/// </summary>
/// <param name="tangoObject">Tango object.</param>
public void Register(System.Object tangoObject)
{
if (m_enableMotionTracking)
{
ITangoPose poseHandler = tangoObject as ITangoPose;
if (poseHandler != null)
{
RegisterOnTangoPoseEvent(poseHandler.OnTangoPoseAvailable);
}
}
if (m_enableDepth)
{
ITangoDepth depthHandler = tangoObject as ITangoDepth;
if (depthHandler != null)
{
RegisterOnTangoDepthEvent(depthHandler.OnTangoDepthAvailable);
}
}
if (m_enableVideoOverlay)
{
if (m_useExperimentalVideoOverlay)
{
IExperimentalTangoVideoOverlay videoOverlayHandler = tangoObject as IExperimentalTangoVideoOverlay;
if (videoOverlayHandler != null)
{
RegisterOnExperimentalTangoVideoOverlay(videoOverlayHandler.OnExperimentalTangoImageAvailable);
}
}
else
{
ITangoVideoOverlay videoOverlayHandler = tangoObject as ITangoVideoOverlay;
if (videoOverlayHandler != null)
{
RegisterOnTangoVideoOverlay(videoOverlayHandler.OnTangoImageAvailableEventHandler);
}
}
}
if(m_enableUXLibrary)
{
ITangoUX tangoUX = tangoObject as ITangoUX;
if(tangoUX != null)
{
UxExceptionListener.GetInstance.RegisterOnMovingTooFast(tangoUX.onMovingTooFastEventHandler);
UxExceptionListener.GetInstance.RegisterOnMotionTrackingInvalid(tangoUX.onMotionTrackingInvalidEventHandler);
UxExceptionListener.GetInstance.RegisterOnLyingOnSurface(tangoUX.onLyingOnSurfaceEventHandler);
UxExceptionListener.GetInstance.RegisterOnCameraOverExposed(tangoUX.onCameraOverExposedEventHandler);
UxExceptionListener.GetInstance.RegisterOnCamerUnderExposed(tangoUX.onCameraUnderExposedEventHandler);
UxExceptionListener.GetInstance.RegisterOnTangoServiceNotResponding(tangoUX.onTangoServiceNotRespondingEventHandler);
UxExceptionListener.GetInstance.RegisterOnTooFewFeatures(tangoUX.onTooFewFeaturesEventHandler);
UxExceptionListener.GetInstance.RegisterOnTooFewPoints(tangoUX.onTooFewPointsEventHandler);
UxExceptionListener.GetInstance.RegisterOnVersionUpdateNeeded(tangoUX.onVersionUpdateNeededEventHandler);
UxExceptionListener.GetInstance.RegisterOnIncompatibleVMFound(tangoUX.onIncompatibleVMFoundEventHandler);
}
}
}
/// <summary>
/// Unregister the specified tangoObject.
/// </summary>
/// <param name="tangoObject">Tango object.</param>
public void Unregister(System.Object tangoObject)
{
if (m_enableMotionTracking)
{
ITangoPose poseHandler = tangoObject as ITangoPose;
if (poseHandler != null)
{
UnregisterOnTangoPoseEvent(poseHandler.OnTangoPoseAvailable);
}
}
if (m_enableDepth)
{
ITangoDepth depthHandler = tangoObject as ITangoDepth;
if (depthHandler != null)
{
UnregisterOnTangoDepthEvent(depthHandler.OnTangoDepthAvailable);
}
}
if (m_enableVideoOverlay)
{
if (m_useExperimentalVideoOverlay)
{
IExperimentalTangoVideoOverlay videoOverlayHandler = tangoObject as IExperimentalTangoVideoOverlay;
if (videoOverlayHandler != null)
{
UnregisterOnExperimentalTangoVideoOverlay(videoOverlayHandler.OnExperimentalTangoImageAvailable);
}
} else
{
ITangoVideoOverlay videoOverlayHandler = tangoObject as ITangoVideoOverlay;
if (videoOverlayHandler != null)
{
UnregisterOnTangoVideoOverlay(videoOverlayHandler.OnTangoImageAvailableEventHandler);
}
}
}
if(m_enableUXLibrary)
{
ITangoUX tangoUX = tangoObject as ITangoUX;
if(tangoUX != null)
{
UxExceptionListener.GetInstance.UnregisterOnMovingTooFast(tangoUX.onMovingTooFastEventHandler);
UxExceptionListener.GetInstance.UnregisterOnMotionTrackingInvalid(tangoUX.onMotionTrackingInvalidEventHandler);
UxExceptionListener.GetInstance.UnregisterOnLyingOnSurface(tangoUX.onLyingOnSurfaceEventHandler);
UxExceptionListener.GetInstance.UnregisterOnCameraOverExposed(tangoUX.onCameraOverExposedEventHandler);
UxExceptionListener.GetInstance.UnregisterOnCamerUnderExposed(tangoUX.onCameraUnderExposedEventHandler);
UxExceptionListener.GetInstance.UnregisterOnTangoServiceNotResponding(tangoUX.onTangoServiceNotRespondingEventHandler);
UxExceptionListener.GetInstance.UnregisterOnTooFewFeatures(tangoUX.onTooFewFeaturesEventHandler);
UxExceptionListener.GetInstance.UnregisterOnTooFewPoints(tangoUX.onTooFewPointsEventHandler);
UxExceptionListener.GetInstance.UnregisterOnVersionUpdateNeeded(tangoUX.onVersionUpdateNeededEventHandler);
UxExceptionListener.GetInstance.UnregisterOnIncompatibleVMFound(tangoUX.onIncompatibleVMFoundEventHandler);
}
}
}
/// <summary>
/// Registers the on tango pose event.
/// </summary>
/// <param name="handler">Handler.</param>
public void RegisterOnTangoPoseEvent(OnTangoPoseAvailableEventHandler handler)
{
if (m_poseListener != null)
{
m_poseListener.RegisterTangoPoseAvailable(handler);
}
}
/// <summary>
/// Registers the on tango depth event.
/// </summary>
/// <param name="handler">Handler.</param>
public void RegisterOnTangoDepthEvent(OnTangoDepthAvailableEventHandler handler)
{
if (m_depthListener != null)
{
m_depthListener.RegisterOnTangoDepthAvailable(handler);
}
}
/// <summary>
/// Registers the on tango event.
/// </summary>
/// <param name="handler">Handler.</param>
public void RegisterOnTangoEvent(OnTangoEventAvailableEventHandler handler)
{
if (m_tangoEventListener != null)
{
m_tangoEventListener.RegisterOnTangoEventAvailable(handler);
}
}
/// <summary>
/// Registers the on tango video overlay.
/// </summary>
/// <param name="handler">Handler.</param>
public void RegisterOnTangoVideoOverlay(OnTangoImageAvailableEventHandler handler)
{
if (m_videoOverlayListener != null)
{
m_videoOverlayListener.RegisterOnTangoImageAvailable(handler);
}
}
/// <summary>
/// Registers the on experimental tango video overlay.
/// </summary>
/// <param name="handler">Handler.</param>
public void RegisterOnExperimentalTangoVideoOverlay(OnExperimentalTangoImageAvailableEventHandler handler)
{
if (m_videoOverlayListener != null)
{
m_videoOverlayListener.RegisterOnExperimentalTangoImageAvailable(handler);
}
}
/// <summary>
/// Determines if has requested permissions.
/// </summary>
/// <returns><c>true</c> if has requested permissions; otherwise, <c>false</c>.</returns>
public bool HasRequestedPermissions()
{
return (m_requiredPermissions == PermissionsTypes.NONE);
}
/// <summary>
/// Registers the permissions callback.
/// </summary>
/// <param name="permissionsEventHandler">Permissions event handler.</param>
public void RegisterPermissionsCallback(PermissionsEvent permissionsEventHandler)
{
if (permissionsEventHandler != null)
{
m_permissionEvent += permissionsEventHandler;
}
}
/// <summary>
/// Unregisters the on tango pose event.
/// </summary>
/// <param name="handler">Handler.</param>
public void UnregisterOnTangoPoseEvent(OnTangoPoseAvailableEventHandler handler)
{
if (m_poseListener != null)
{
m_poseListener.UnregisterTangoPoseAvailable(handler);
}
}
/// <summary>
/// Unregisters the on tango depth event.
/// </summary>
/// <param name="handler">Handler.</param>
public void UnregisterOnTangoDepthEvent(OnTangoDepthAvailableEventHandler handler)
{
if (m_depthListener != null)
{
m_depthListener.UnregisterOnTangoDepthAvailable(handler);
}
}
/// <summary>
/// Unregisters the on tango event.
/// </summary>
/// <param name="handler">Handler.</param>
public void UnregisterOnTangoEvent(OnTangoEventAvailableEventHandler handler)
{
if (m_tangoEventListener != null)
{
m_tangoEventListener.UnregisterOnTangoEventAvailable(handler);
}
}
/// <summary>
/// Unregisters the on tango video overlay.
/// </summary>
/// <param name="handler">Handler.</param>
public void UnregisterOnTangoVideoOverlay(OnTangoImageAvailableEventHandler handler)
{
if (m_videoOverlayListener != null)
{
m_videoOverlayListener.UnregisterOnTangoImageAvailable(handler);
}
}
/// <summary>
/// Unregisters the on experimental tango video overlay.
/// </summary>
/// <param name="handler">Handler.</param>
public void UnregisterOnExperimentalTangoVideoOverlay(OnExperimentalTangoImageAvailableEventHandler handler)
{
if (m_videoOverlayListener != null)
{
m_videoOverlayListener.UnregisterOnExperimentalTangoImageAvailable(handler);
}
}
/// <summary>
/// Removes the permissions callback.
/// </summary>
/// <param name="permissionsEventHandler">Permissions event handler.</param>
public void RemovePermissionsCallback(PermissionsEvent permissionsEventHandler)
{
if (permissionsEventHandler != null)
{
m_permissionEvent -= permissionsEventHandler;
}
}
/// <summary>
/// Requests the necessary permissions for Tango functionality.
/// </summary>
public void RequestNecessaryPermissionsAndConnect()
{
_ResetPermissionsFlags();
_RequestNextPermission();
}
/// <summary>
/// Initialize Tango Service and Config.
/// </summary>
public void InitApplication()
{
Debug.Log("-----------------------------------Initializing Tango");
_TangoInitialize();
TangoConfig.InitConfig(TangoEnums.TangoConfigType.TANGO_CONFIG_DEFAULT);
if(m_enableVideoOverlay && m_useExperimentalVideoOverlay)
{
int yTextureWidth = 0;
int yTextureHeight = 0;
int uvTextureWidth = 0;
int uvTextureHeight = 0;
TangoConfig.GetInt32(TangoConfig.Keys.EXPERIMENTAL_Y_TEXTURE_WIDTH, ref yTextureWidth);
TangoConfig.GetInt32(TangoConfig.Keys.EXPERIMENTAL_Y_TEXTURE_HEIGHT, ref yTextureHeight);
TangoConfig.GetInt32(TangoConfig.Keys.EXPERIMENTAL_UV_TEXTURE_WIDTH, ref uvTextureWidth);
TangoConfig.GetInt32(TangoConfig.Keys.EXPERIMENTAL_UV_TEXTURE_HEIGHT, ref uvTextureHeight);
if(yTextureWidth == 0 ||
yTextureHeight == 0 ||
uvTextureWidth == 0 ||
uvTextureHeight == 0)
{
Debug.Log("Video overlay texture sizes were not set properly");
}
m_yuvTexture.ResizeAll(yTextureWidth, yTextureHeight, uvTextureWidth, uvTextureHeight);
}
}
/// <summary>
/// Initialize the providers.
/// </summary>
/// <param name="UUID"> UUID to be loaded, if any.</param>
public void InitProviders(string UUID)
{
_InitializeMotionTracking(UUID);
_InitializeDepth();
//_InitializeOverlay();
_SetEventCallbacks();
}
/// <summary>
/// Connects to Tango Service.
/// </summary>
public void ConnectToService()
{
Debug.Log("TangoApplication.ConnectToService()");
_TangoConnect();
}
/// <summary>
/// Shutdown this instance.
/// </summary>
public void Shutdown()
{
Debug.Log("Tango Shutdown");
TangoConfig.Free();
_TangoDisconnect();
}
/// <summary>
/// Helper method that will resume the tango services on App Resume.
/// Locks the config again and connects the service.
/// </summary>
private void _ResumeTangoServices()
{
RequestNecessaryPermissionsAndConnect();
}
/// <summary>
/// Helper method that will suspend the tango services on App Suspend.
/// Unlocks the tango config and disconnects the service.
/// </summary>
private void _SuspendTangoServices()
{
Debug.Log("Suspending Tango Service");
_TangoDisconnect();
}
/// <summary>
/// Set callbacks on all PoseListener objects.
/// </summary>
/// <param name="framePairs">Frame pairs.</param>
private void _SetMotionTrackingCallbacks(TangoCoordinateFramePair[] framePairs)
{
if (m_poseListener != null)
{
m_poseListener.AutoReset = m_motionTrackingAutoReset;
m_poseListener.SetCallback(framePairs);
}
}
/// <summary>
/// Set callbacks for all DepthListener objects.
/// </summary>
private void _SetDepthCallbacks()
{
if (m_depthListener != null)
{
m_depthListener.SetCallback();
}
}
/// <summary>
/// Set callbacks for all TangoEventListener objects.
/// </summary>
private void _SetEventCallbacks()
{
if (m_tangoEventListener != null)
{
m_tangoEventListener.SetCallback();
}
}
/// <summary>
/// Set callbacks for all VideoOverlayListener objects.
/// </summary>
private void _SetVideoOverlayCallbacks()
{
if (m_videoOverlayListener != null)
{
m_videoOverlayListener.SetCallback(TangoEnums.TangoCameraId.TANGO_CAMERA_COLOR, m_useExperimentalVideoOverlay, m_yuvTexture);
}
}
/// <summary>
/// Initialize motion tracking.
/// </summary>
private void _InitializeMotionTracking(string UUID)
{
System.Collections.Generic.List<TangoCoordinateFramePair> framePairs = new System.Collections.Generic.List<TangoCoordinateFramePair>();
if (TangoConfig.SetBool(TangoConfig.Keys.ENABLE_MOTION_TRACKING_BOOL, m_enableMotionTracking) && m_enableMotionTracking)
{
TangoCoordinateFramePair motionTracking;
motionTracking.baseFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_START_OF_SERVICE;
motionTracking.targetFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_DEVICE;
framePairs.Add(motionTracking);
if (TangoConfig.SetBool(TangoConfig.Keys.ENABLE_AREA_LEARNING_BOOL, m_enableAreaLearning) && m_enableAreaLearning)
{
Debug.Log("Area Learning is enabled.");
if (!string.IsNullOrEmpty(UUID))
{
TangoConfig.SetBool("config_experimental_high_accuracy_small_scale_adf", m_useExperimentalADF);
TangoConfig.SetString(TangoConfig.Keys.LOAD_AREA_DESCRIPTION_UUID_STRING, UUID);
}
TangoCoordinateFramePair areaDescription;
areaDescription.baseFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_AREA_DESCRIPTION;
areaDescription.targetFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_DEVICE;
TangoCoordinateFramePair startToADF;
startToADF.baseFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_AREA_DESCRIPTION;
startToADF.targetFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_START_OF_SERVICE;
framePairs.Add(areaDescription);
framePairs.Add(startToADF);
}
}
if (framePairs.Count > 0)
{
_SetMotionTrackingCallbacks(framePairs.ToArray());
}
TangoConfig.SetBool(TangoConfig.Keys.ENABLE_LOW_LATENCY_IMU_INTEGRATION, m_useLowLatencyIMUIntegration);
TangoConfig.SetBool(TangoConfig.Keys.ENABLE_MOTION_TRACKING_AUTO_RECOVERY_BOOL, m_motionTrackingAutoReset);
}
/// <summary>
/// Initialize depth perception.
/// </summary>
private void _InitializeDepth()
{
if (TangoConfig.SetBool(TangoConfig.Keys.ENABLE_DEPTH_PERCEPTION_BOOL, m_enableDepth) && m_enableDepth)
{
_SetDepthCallbacks();
}
}
/// <summary>
/// Initialize the RGB overlay.
/// </summary>
private void _InitializeOverlay()
{
_SetVideoOverlayCallbacks();
}
/// <summary>
/// Initialize the Tango Service.
/// </summary>
private void _TangoInitialize()
{
if (_IsValidTangoAPIVersion())
{
int status = TangoServiceAPI.TangoService_initialize(IntPtr.Zero, IntPtr.Zero);
if (status != Common.ErrorType.TANGO_SUCCESS)
{
Debug.Log("-------------------Tango initialize status : " + status);
Debug.Log(CLASS_NAME + ".Initialize() The service has not been initialized!");
} else
{
Debug.Log(CLASS_NAME + ".Initialize() Tango was initialized!");
}
} else
{
Debug.Log(CLASS_NAME + ".Initialize() Invalid API version. please update to minimul API version.");
}
}
/// <summary>
/// Connect to the Tango Service.
/// </summary>
private void _TangoConnect()
{
if (!m_isServiceConnected)
{
m_isServiceConnected = true;
AndroidHelper.PerformanceLog("Unity _TangoConnect start");
if (TangoServiceAPI.TangoService_connect(m_callbackContext, TangoConfig.GetConfig()) != Common.ErrorType.TANGO_SUCCESS)
{
Debug.Log(CLASS_NAME + ".Connect() Could not connect to the Tango Service!");
} else
{
AndroidHelper.PerformanceLog("Unity _TangoConnect end");
Debug.Log(CLASS_NAME + ".Connect() Tango client connected to service!");
if (m_enableUXLibrary)
{
AndroidHelper.StartTangoUX();
}
}
}
}
/// <summary>
/// Disconnect from the Tango Service.
/// </summary>
private void _TangoDisconnect()
{
Debug.Log(CLASS_NAME + ".Disconnect() Disconnecting from the Tango Service");
m_isDisconnecting = true;
m_isServiceConnected = false;
if (TangoServiceAPI.TangoService_disconnect() != Common.ErrorType.TANGO_SUCCESS)
{
Debug.Log(CLASS_NAME + ".Disconnect() Could not disconnect from the Tango Service!");
m_isDisconnecting = false;
} else
{
Debug.Log(CLASS_NAME + ".Disconnect() Tango client disconnected from service!");
m_isDisconnecting = false;
if (m_enableUXLibrary)
{
AndroidHelper.StopTangoUX();
}
}
}
/// <summary>
/// Checks to see if the current Tango Service is supported.
/// </summary>
/// <returns><c>true</c>, if is valid tango API version is greater
/// than or equal to the minimum supported version, <c>false</c> otherwise.</returns>
private bool _IsValidTangoAPIVersion()
{
if (!m_hasVersionBeenChecked)
{
int versionCode = _GetTangoAPIVersion();
if (versionCode < 0)
{
m_isValidTangoAPIVersion = false;
} else
{
m_isValidTangoAPIVersion = (versionCode >= MINIMUM_API_VERSION);
}
m_hasVersionBeenChecked = true;
}
return m_isValidTangoAPIVersion;
}
/// <summary>
/// Gets the get tango API version code.
/// </summary>
/// <returns>The get tango API version code.</returns>
private static int _GetTangoAPIVersion()
{
return AndroidHelper.GetVersionCode("com.projecttango.tango");
}
/// <summary>
/// Android on pause.
/// </summary>
private void _androidOnPause()
{
if (m_isServiceConnected && m_requiredPermissions == PermissionsTypes.NONE)
{
Debug.Log("Pausing services");
m_shouldReconnectService = true;
_SuspendTangoServices();
}
Debug.Log("androidOnPause done");
}
/// <summary>
/// Android on resume.
/// </summary>
private void _androidOnResume()
{
if (m_shouldReconnectService)
{
Debug.Log("Resuming services");
m_shouldReconnectService = false;
_ResumeTangoServices();
}
Debug.Log("androidOnResume done");
}
/// <summary>
/// EventHandler for Android's on activity result.
/// </summary>
/// <param name="requestCode">Request code.</param>
/// <param name="resultCode">Result code.</param>
/// <param name="data">Data.</param>
private void _androidOnActivityResult(int requestCode, int resultCode, AndroidJavaObject data)
{
Debug.Log("Activity returned result code : " + resultCode);
switch (requestCode)
{
case Common.TANGO_MOTION_TRACKING_PERMISSIONS_REQUEST_CODE:
{
if (resultCode == (int)Common.AndroidResult.SUCCESS)
{
_FlipBitAndCheckPermissions(PermissionsTypes.MOTION_TRACKING);
} else
{
_PermissionWasDenied();
}
break;
}
case Common.TANGO_ADF_LOAD_SAVE_PERMISSIONS_REQUEST_CODE:
{
if (resultCode == (int)Common.AndroidResult.SUCCESS)
{
_FlipBitAndCheckPermissions(PermissionsTypes.AREA_LEARNING);
} else
{
_PermissionWasDenied();
}
break;
}
default:
{
break;
}
}
Debug.Log("Activity returned result end");
}
/// <summary>
/// Start exceptions listener.
/// </summary>
/// <returns>The start exceptions listener.</returns>
private IEnumerator _StartExceptionsListener()
{
AndroidHelper.ShowStandardTangoExceptionsUI(m_drawDefaultUXExceptions);
AndroidHelper.SetTangoExceptionsListener();
yield return 0;
}
/// <summary>
/// Awake this instance.
/// </summary>
private void Awake()
{
AndroidHelper.RegisterPauseEvent(_androidOnPause);
AndroidHelper.RegisterResumeEvent(_androidOnResume);
AndroidHelper.RegisterOnActivityResultEvent(_androidOnActivityResult);
if (m_enableMotionTracking)
{
m_poseListener = new PoseListener();
}
if (m_enableDepth)
{
m_depthListener = new DepthListener();
}
if (m_enableUXLibrary)
{
m_tangoEventListener = new TangoEventListener();
}
if (m_enableVideoOverlay)
{
int yTextureWidth = 0;
int yTextureHeight = 0;
int uvTextureWidth = 0;
int uvTextureHeight = 0;
m_yuvTexture = new YUVTexture(yTextureWidth, yTextureHeight, uvTextureWidth, uvTextureHeight, TextureFormat.RGBA32, false);
m_videoOverlayListener = new VideoOverlayListener();
}
}
/// <summary>
/// Reset permissions flags.
/// </summary>
private void _ResetPermissionsFlags()
{
if (m_requiredPermissions == PermissionsTypes.NONE)
{
m_requiredPermissions |= m_enableMotionTracking ? PermissionsTypes.MOTION_TRACKING : PermissionsTypes.NONE;
m_requiredPermissions |= m_enableAreaLearning ? PermissionsTypes.AREA_LEARNING : PermissionsTypes.NONE;
}
}
/// <summary>
/// Flip a permission bit and check to see if all permissions were accepted.
/// </summary>
/// <param name="permission">Permission.</param>
private void _FlipBitAndCheckPermissions(PermissionsTypes permission)
{
m_requiredPermissions ^= permission;
if (m_requiredPermissions == 0) // all permissions are good!
{
Debug.Log("All permissions have been accepted!");
_SendPermissionEvent(true);
} else
{
_RequestNextPermission();
}
}
/// <summary>
/// A Tango permission was denied.
/// </summary>
private void _PermissionWasDenied()
{
m_requiredPermissions = PermissionsTypes.NONE;
if (m_permissionEvent != null)
{
_SendPermissionEvent(false);
}
}
/// <summary>
/// Request next permission.
/// </summary>
private void _RequestNextPermission()
{
Debug.Log("TangoApplication._RequestNextPermission()");
// if no permissions are needed let's kick-off the Tango connect
if (m_requiredPermissions == PermissionsTypes.NONE)
{
_SendPermissionEvent(true);
}
if ((m_requiredPermissions & PermissionsTypes.MOTION_TRACKING) == PermissionsTypes.MOTION_TRACKING)
{
if (AndroidHelper.ApplicationHasTangoPermissions(Common.TANGO_MOTION_TRACKING_PERMISSIONS))
{
_androidOnActivityResult(Common.TANGO_MOTION_TRACKING_PERMISSIONS_REQUEST_CODE, -1, null);
} else
{
AndroidHelper.StartTangoPermissionsActivity(Common.TANGO_MOTION_TRACKING_PERMISSIONS);
}
} else if ((m_requiredPermissions & PermissionsTypes.AREA_LEARNING) == PermissionsTypes.AREA_LEARNING)
{
if (AndroidHelper.ApplicationHasTangoPermissions(Common.TANGO_ADF_LOAD_SAVE_PERMISSIONS))
{
_androidOnActivityResult(Common.TANGO_ADF_LOAD_SAVE_PERMISSIONS_REQUEST_CODE, -1, null);
} else
{
AndroidHelper.StartTangoPermissionsActivity(Common.TANGO_ADF_LOAD_SAVE_PERMISSIONS);
}
}
}
/// <summary>
/// Sends the permission event.
/// </summary>
/// <param name="permissions">If set to <c>true</c> permissions.</param>
private void _SendPermissionEvent(bool permissions)
{
if (m_enableUXLibrary && permissions)
{
StartCoroutine(_StartExceptionsListener());
}
m_sendPermissions = true;
m_permissionsSuccessful = permissions;
}
/// <summary>
/// Disperse any events related to Tango functionality.
/// </summary>
private void Update()
{
if (m_sendPermissions)
{
_InitializeOverlay();
if (m_permissionEvent != null)
{
m_permissionEvent(m_permissionsSuccessful);
}
m_sendPermissions = false;
}
if (m_poseListener != null)
{
m_poseListener.SendPoseIfAvailable(m_enableUXLibrary);
}
if (m_tangoEventListener != null)
{
m_tangoEventListener.SendIfTangoEventAvailable(m_enableUXLibrary);
}
if (m_depthListener != null)
{
m_depthListener.SendDepthIfAvailable();
}
if (m_videoOverlayListener != null)
{
m_videoOverlayListener.SendIfVideoOverlayAvailable();
}
}
#region NATIVE_FUNCTIONS
/// <summary>
/// Interface for native function calls to Tango Service.
/// </summary>
private struct TangoServiceAPI
{
#if UNITY_ANDROID && !UNITY_EDITOR
[DllImport(Common.TANGO_UNITY_DLL)]
public static extern int TangoService_initialize (IntPtr JNIEnv, IntPtr appContext);
[DllImport(Common.TANGO_UNITY_DLL)]
public static extern int TangoService_connect (IntPtr callbackContext, IntPtr config);
[DllImport(Common.TANGO_UNITY_DLL)]
public static extern int TangoService_disconnect ();
#else
public static int TangoService_initialize(IntPtr JNIEnv, IntPtr appContext)
{
return Common.ErrorType.TANGO_SUCCESS;
}
public static int TangoService_connect(IntPtr callbackContext, IntPtr config)
{
return Common.ErrorType.TANGO_SUCCESS;
}
public static int TangoService_disconnect()
{
return Common.ErrorType.TANGO_SUCCESS;
}
#endif
}
#endregion // NATIVE_FUNCTIONS
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management;
namespace Microsoft.WindowsAzure.Management
{
/// <summary>
/// The Service Management API provides programmatic access to much of the
/// functionality available through the Management Portal. The Service
/// Management API is a REST API. All API operations are performed over
/// SSL and are mutually authenticated using X.509 v3 certificates. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for
/// more information)
/// </summary>
public partial class ManagementClient : ServiceClient<ManagementClient>, IManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IAffinityGroupOperations _affinityGroups;
/// <summary>
/// Operations for managing affinity groups in your subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460798.aspx
/// for more information)
/// </summary>
public virtual IAffinityGroupOperations AffinityGroups
{
get { return this._affinityGroups; }
}
private ILocationOperations _locations;
/// <summary>
/// The Service Management API includes operations for listing the
/// available data center locations for a hosted service in your
/// subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg441299.aspx
/// for more information)
/// </summary>
public virtual ILocationOperations Locations
{
get { return this._locations; }
}
private IManagementCertificateOperations _managementCertificates;
/// <summary>
/// You can use management certificates, which are also known as
/// subscription certificates, to authenticate clients attempting to
/// connect to resources associated with your Azure subscription.
/// (see http://msdn.microsoft.com/en-us/library/windowsazure/jj154124.aspx
/// for more information)
/// </summary>
public virtual IManagementCertificateOperations ManagementCertificates
{
get { return this._managementCertificates; }
}
private IRoleSizeOperations _roleSizes;
/// <summary>
/// The Service Management API includes operations for listing the
/// available role sizes for VMs in your subscription.
/// </summary>
public virtual IRoleSizeOperations RoleSizes
{
get { return this._roleSizes; }
}
private ISubscriptionOperations _subscriptions;
/// <summary>
/// Operations for listing subscription details. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg715315.aspx
/// for more information)
/// </summary>
public virtual ISubscriptionOperations Subscriptions
{
get { return this._subscriptions; }
}
/// <summary>
/// Initializes a new instance of the ManagementClient class.
/// </summary>
public ManagementClient()
: base()
{
this._affinityGroups = new AffinityGroupOperations(this);
this._locations = new LocationOperations(this);
this._managementCertificates = new ManagementCertificateOperations(this);
this._roleSizes = new RoleSizeOperations(this);
this._subscriptions = new SubscriptionOperations(this);
this._apiVersion = "2014-10-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the ManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public ManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the ManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public ManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the ManagementClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public ManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._affinityGroups = new AffinityGroupOperations(this);
this._locations = new LocationOperations(this);
this._managementCertificates = new ManagementCertificateOperations(this);
this._roleSizes = new RoleSizeOperations(this);
this._subscriptions = new SubscriptionOperations(this);
this._apiVersion = "2014-10-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the ManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public ManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the ManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public ManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another ManagementClient
/// instance
/// </summary>
/// <param name='client'>
/// Instance of ManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<ManagementClient> client)
{
base.Clone(client);
if (client is ManagementClient)
{
ManagementClient clonedClient = ((ManagementClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx
/// for more information)
/// </summary>
/// <param name='requestId'>
/// Required. The request ID for the request you wish to track. The
/// request ID is returned in the x-ms-request-id response header for
/// every request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<OperationStatusResponse> GetOperationStatusAsync(string requestId, CancellationToken cancellationToken)
{
// Validate
if (requestId == null)
{
throw new ArgumentNullException("requestId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("requestId", requestId);
TracingAdapter.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Credentials.SubscriptionId);
}
url = url + "/operations/";
url = url + Uri.EscapeDataString(requestId);
string baseUrl = this.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationStatusResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new OperationStatusResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement operationElement = responseDoc.Element(XName.Get("Operation", "http://schemas.microsoft.com/windowsazure"));
if (operationElement != null)
{
XElement idElement = operationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
result.Id = idInstance;
}
XElement statusElement = operationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure"));
if (statusElement != null)
{
OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), statusElement.Value, true));
result.Status = statusInstance;
}
XElement httpStatusCodeElement = operationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure"));
if (httpStatusCodeElement != null)
{
HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true));
result.HttpStatusCode = httpStatusCodeInstance;
}
XElement errorElement = operationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure"));
if (errorElement != null)
{
OperationStatusResponse.ErrorDetails errorInstance = new OperationStatusResponse.ErrorDetails();
result.Error = errorInstance;
XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure"));
if (codeElement != null)
{
string codeInstance = codeElement.Value;
errorInstance.Code = codeInstance;
}
XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure"));
if (messageElement != null)
{
string messageInstance = messageElement.Value;
errorInstance.Message = messageInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace SMSServer.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);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orleans.Runtime;
namespace Orleans.Streams
{
internal class StreamConsumer<T> : IInternalAsyncObservable<T>
{
internal bool IsRewindable { get; private set; }
private readonly StreamImpl<T> stream;
private readonly string streamProviderName;
[NonSerialized]
private readonly IStreamProviderRuntime providerRuntime;
[NonSerialized]
private readonly IStreamPubSub pubSub;
private StreamConsumerExtension myExtension;
private IStreamConsumerExtension myGrainReference;
[NonSerialized]
private readonly AsyncLock bindExtLock;
[NonSerialized]
private readonly TraceLogger logger;
public StreamConsumer(StreamImpl<T> stream, string streamProviderName, IStreamProviderRuntime providerUtilities, IStreamPubSub pubSub, bool isRewindable)
{
if (stream == null) throw new ArgumentNullException("stream");
if (providerUtilities == null) throw new ArgumentNullException("providerUtilities");
if (pubSub == null) throw new ArgumentNullException("pubSub");
logger = TraceLogger.GetLogger(string.Format("StreamConsumer<{0}>-{1}", typeof(T).Name, stream), TraceLogger.LoggerType.Runtime);
this.stream = stream;
this.streamProviderName = streamProviderName;
providerRuntime = providerUtilities;
this.pubSub = pubSub;
IsRewindable = isRewindable;
myExtension = null;
myGrainReference = null;
bindExtLock = new AsyncLock();
}
public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncObserver<T> observer)
{
return SubscribeAsync(observer, null);
}
public async Task<StreamSubscriptionHandle<T>> SubscribeAsync(
IAsyncObserver<T> observer,
StreamSequenceToken token,
StreamFilterPredicate filterFunc = null,
object filterData = null)
{
if (token != null && !IsRewindable)
throw new ArgumentNullException("token", "Passing a non-null token to a non-rewindable IAsyncObservable.");
if (observer is GrainReference)
throw new ArgumentException("On-behalf subscription via grain references is not supported. Only passing of object references is allowed.", "observer");
if (logger.IsVerbose) logger.Verbose("Subscribe Observer={0} Token={1}", observer, token);
await BindExtensionLazy();
IStreamFilterPredicateWrapper filterWrapper = null;
if (filterFunc != null)
filterWrapper = new FilterPredicateWrapperData(filterData, filterFunc);
if (logger.IsVerbose) logger.Verbose("Subscribe - Connecting to Rendezvous {0} My GrainRef={1} Token={2}",
pubSub, myGrainReference, token);
GuidId subscriptionId = pubSub.CreateSubscriptionId(stream.StreamId, myGrainReference);
// Optimistic Concurrency:
// In general, we should first register the subsription with the pubsub (pubSub.RegisterConsumer)
// and only if it succeeds store it locally (myExtension.SetObserver).
// Basicaly, those 2 operations should be done as one atomic transaction - either both or none and isolated from concurrent reads.
// BUT: there is a distributed race here: the first msg may arrive before the call is awaited
// (since the pubsub notifies the producer that may immideately produce)
// and will thus not find the subriptionHandle in the extension, basically violating "isolation".
// Therefore, we employ Optimistic Concurrency Control here to guarantee isolation:
// we optimisticaly store subscriptionId in the handle first before calling pubSub.RegisterConsumer
// and undo it in the case of failure.
// There is no problem with that we call myExtension.SetObserver too early before the handle is registered in pub sub,
// since this subscriptionId is unique (random Guid) and no one knows it anyway, unless successfully subscribed in the pubsub.
var subriptionHandle = myExtension.SetObserver(subscriptionId, stream, observer, token, filterWrapper);
try
{
await pubSub.RegisterConsumer(subscriptionId, stream.StreamId, streamProviderName, myGrainReference, filterWrapper);
return subriptionHandle;
} catch(Exception)
{
// Undo the previous call myExtension.SetObserver.
myExtension.RemoveObserver(subscriptionId);
throw;
}
}
public async Task<StreamSubscriptionHandle<T>> ResumeAsync(
StreamSubscriptionHandle<T> handle,
IAsyncObserver<T> observer,
StreamSequenceToken token = null)
{
StreamSubscriptionHandleImpl<T> oldHandleImpl = CheckHandleValidity(handle);
if (token != null && !IsRewindable)
throw new ArgumentNullException("token", "Passing a non-null token to a non-rewindable IAsyncObservable.");
if (logger.IsVerbose) logger.Verbose("Resume Observer={0} Token={1}", observer, token);
await BindExtensionLazy();
if (logger.IsVerbose) logger.Verbose("Resume - Connecting to Rendezvous {0} My GrainRef={1} Token={2}",
pubSub, myGrainReference, token);
StreamSubscriptionHandle<T> newHandle = myExtension.SetObserver(oldHandleImpl.SubscriptionId, stream, observer, token, null);
// On failure caller should be able to retry using the original handle, so invalidate old handle only if everything succeeded.
oldHandleImpl.Invalidate();
return newHandle;
}
public async Task UnsubscribeAsync(StreamSubscriptionHandle<T> handle)
{
await BindExtensionLazy();
StreamSubscriptionHandleImpl<T> handleImpl = CheckHandleValidity(handle);
if (logger.IsVerbose) logger.Verbose("Unsubscribe StreamSubscriptionHandle={0}", handle);
myExtension.RemoveObserver(handleImpl.SubscriptionId);
// UnregisterConsumer from pubsub even if does not have this handle localy, to allow UnsubscribeAsync retries.
if (logger.IsVerbose) logger.Verbose("Unsubscribe - Disconnecting from Rendezvous {0} My GrainRef={1}",
pubSub, myGrainReference);
await pubSub.UnregisterConsumer(handleImpl.SubscriptionId, stream.StreamId, streamProviderName);
handleImpl.Invalidate();
}
public async Task<IList<StreamSubscriptionHandle<T>>> GetAllSubscriptions()
{
await BindExtensionLazy();
List<GuidId> subscriptionIds = await pubSub.GetAllSubscriptions(stream.StreamId, myGrainReference);
return subscriptionIds.Select(id => new StreamSubscriptionHandleImpl<T>(id, stream, IsRewindable))
.ToList<StreamSubscriptionHandle<T>>();
}
public async Task Cleanup()
{
if (logger.IsVerbose) logger.Verbose("Cleanup() called");
if (myExtension == null)
return;
var allHandles = myExtension.GetAllStreamHandles<T>();
var tasks = new List<Task>();
foreach (var handle in allHandles)
{
myExtension.RemoveObserver(handle.SubscriptionId);
tasks.Add(pubSub.UnregisterConsumer(handle.SubscriptionId, stream.StreamId, streamProviderName));
}
try
{
await Task.WhenAll(tasks);
} catch (Exception exc)
{
logger.Warn((int)ErrorCode.StreamProvider_ConsumerFailedToUnregister,
"Ignoring unhandled exception during PubSub.UnregisterConsumer", exc);
}
myExtension = null;
}
// Used in test.
internal bool InternalRemoveObserver(StreamSubscriptionHandle<T> handle)
{
return myExtension != null && myExtension.RemoveObserver(((StreamSubscriptionHandleImpl<T>)handle).SubscriptionId);
}
internal Task<int> DiagGetConsumerObserversCount()
{
return Task.FromResult(myExtension.DiagCountStreamObservers<T>(stream.StreamId));
}
private async Task BindExtensionLazy()
{
if (myExtension == null)
{
using (await bindExtLock.LockAsync())
{
if (myExtension == null)
{
if (logger.IsVerbose) logger.Verbose("BindExtensionLazy - Binding local extension to stream runtime={0}", providerRuntime);
var tup = await providerRuntime.BindExtension<StreamConsumerExtension, IStreamConsumerExtension>(
() => new StreamConsumerExtension(providerRuntime, IsRewindable));
myExtension = tup.Item1;
myGrainReference = tup.Item2;
if (logger.IsVerbose) logger.Verbose("BindExtensionLazy - Connected Extension={0} GrainRef={1}", myExtension, myGrainReference);
}
}
}
}
private StreamSubscriptionHandleImpl<T> CheckHandleValidity(StreamSubscriptionHandle<T> handle)
{
if (handle == null)
throw new ArgumentNullException("handle");
if (!handle.StreamIdentity.Equals(stream))
throw new ArgumentException("Handle is not for this stream.", "handle");
var handleImpl = handle as StreamSubscriptionHandleImpl<T>;
if (handleImpl == null)
throw new ArgumentException("Handle type not supported.", "handle");
if (!handleImpl.IsValid)
throw new ArgumentException("Handle is no longer valid. It has been used to unsubscribe or resume.", "handle");
return handleImpl;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
extern alias core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using core::Roslyn.Utilities;
using EnvDTE;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Interactive;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.InteractiveWindow.Shell;
using VSLangProj;
using Project = EnvDTE.Project;
namespace Microsoft.VisualStudio.LanguageServices.Interactive
{
internal sealed class ResetInteractive
{
private readonly DTE _dte;
private readonly IComponentModel _componentModel;
private readonly IVsMonitorSelection _monitorSelection;
private readonly IVsSolutionBuildManager _buildManager;
private readonly Func<string, string> _createReference;
private readonly Func<string, string> _createImport;
internal ResetInteractive(DTE dte, IComponentModel componentModel, IVsMonitorSelection monitorSelection, IVsSolutionBuildManager buildManager, Func<string, string> createReference, Func<string, string> createImport)
{
_dte = dte;
_componentModel = componentModel;
_monitorSelection = monitorSelection;
_buildManager = buildManager;
_createReference = createReference;
_createImport = createImport;
}
internal void Execute(IVsInteractiveWindow vsInteractiveWindow, string title)
{
var hierarchyPointer = default(IntPtr);
var selectionContainerPointer = default(IntPtr);
try
{
uint itemid;
IVsMultiItemSelect multiItemSelectPointer;
Marshal.ThrowExceptionForHR(_monitorSelection.GetCurrentSelection(
out hierarchyPointer, out itemid, out multiItemSelectPointer, out selectionContainerPointer));
if (hierarchyPointer != IntPtr.Zero)
{
List<string> references, referenceSearchPaths, sourceSearchPaths, namespacesToImport;
string projectDirectory;
GetProjectProperties(hierarchyPointer, out references, out referenceSearchPaths, out sourceSearchPaths, out namespacesToImport, out projectDirectory);
// Now, we're going to do a bunch of async operations. So create a wait
// indicator so the user knows something is happening, and also so they cancel.
var waitIndicator = _componentModel.GetService<IWaitIndicator>();
var waitContext = waitIndicator.StartWait(title, ServicesVSResources.BuildingProject, allowCancel: true);
var resetInteractiveTask = ResetInteractiveAsync(vsInteractiveWindow, references, referenceSearchPaths, sourceSearchPaths, namespacesToImport, projectDirectory, waitContext);
// Once we're done resetting, dismiss the wait indicator and focus the REPL window.
resetInteractiveTask.SafeContinueWith(
_ =>
{
waitContext.Dispose();
// We have to set focus to the Interactive Window *after* the wait indicator is dismissed.
vsInteractiveWindow.Show(focus: true);
},
TaskScheduler.FromCurrentSynchronizationContext());
}
}
finally
{
SafeRelease(hierarchyPointer);
SafeRelease(selectionContainerPointer);
}
}
private Task ResetInteractiveAsync(
IVsInteractiveWindow vsInteractiveWindow,
List<string> referencePaths,
List<string> referenceSearchPaths,
List<string> sourceSearchPaths,
List<string> namespacesToImport,
string projectDirectory,
IWaitContext waitContext)
{
// First, open the repl window.
var engine = (InteractiveEvaluator)vsInteractiveWindow.InteractiveWindow.Evaluator;
var uiTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
// If the user hits the cancel button on the wait indicator, then we want to stop the
// build.
waitContext.CancellationToken.Register(() =>
_dte.ExecuteCommand("Build.Cancel"), useSynchronizationContext: true);
// First, start a build.
var buildTask = BuildProject();
// Then reset the repl.
var resetTask = buildTask.SafeContinueWithFromAsync(_ =>
{
waitContext.Message = ServicesVSResources.ResettingInteractive;
return vsInteractiveWindow.InteractiveWindow.Operations.ResetAsync(initialize: false);
},
waitContext.CancellationToken,
TaskContinuationOptions.OnlyOnRanToCompletion,
uiTaskScheduler);
// Now send the reference paths we've collected to the repl.
var submitReferencesTask = resetTask.SafeContinueWith(
_ =>
{
// TODO (tomat): In general, these settings should be applied again when we auto-reset.
engine.SetInitialPaths(
referenceSearchPaths.ToArray(),
sourceSearchPaths.ToArray(),
projectDirectory);
vsInteractiveWindow.InteractiveWindow.Submit(new[]
{
// TODO(DustinCa): Update these to be language agnostic.
referencePaths.Select(_createReference).Join("\r\n"),
namespacesToImport.Select(_createImport).Join("\r\n")
});
},
waitContext.CancellationToken,
TaskContinuationOptions.OnlyOnRanToCompletion,
uiTaskScheduler);
return submitReferencesTask;
//// TODO (tomat): Ideally we should check if the imported namespaces are available in #r'd assemblies.
//// We should wait until #r submission is finished and then query for existing namespaces.
////if (namespacesToImport.IsEmpty())
////{
//// return submitReferencesTask;
////}
////var submitReferencesAndUsingsTask = submitReferencesTask.SafeContinueWith(
//// _ =>
//// {
//// var compilation = engine.GetPreviousSubmissionProject().GetCompilation(waitContext.CancellationToken);
//// replWindow.Submit(new[]
//// {
//// (from ns in namespacesToImport
//// where compilation.GlobalNamespace.GetMembers(ns, waitContext.CancellationToken).Any()
//// select string.Format("using {0};", ns)).Join("\r\n")
//// });
//// },
//// waitContext.CancellationToken,
//// TaskContinuationOptions.OnlyOnRanToCompletion,
//// uiTaskScheduler);
//// return submitReferencesAndUsingsTask;
}
private static void GetProjectProperties(
IntPtr hierarchyPointer,
out List<string> references,
out List<string> referenceSearchPaths,
out List<string> sourceSearchPaths,
out List<string> namespacesToImport,
out string projectDirectory)
{
var hierarchy = (IVsHierarchy)Marshal.GetObjectForIUnknown(hierarchyPointer);
object extensibilityObject;
Marshal.ThrowExceptionForHR(
hierarchy.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_ExtObject, out extensibilityObject));
// TODO: Revert this back to using dynamic for web projects, since they have copies of these interfaces.
var project = (Project)extensibilityObject;
var vsProject = (VSProject)project.Object;
references = new List<string>();
referenceSearchPaths = new List<string>();
sourceSearchPaths = new List<string>();
namespacesToImport = new List<string>();
var projectDir = (string)project.Properties.Item("FullPath").Value;
var outputFileName = (string)project.Properties.Item("OutputFileName").Value;
var defaultNamespace = (string)project.Properties.Item("DefaultNamespace").Value;
var relativeOutputPath = (string)project.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value;
Debug.Assert(!string.IsNullOrEmpty(projectDir));
Debug.Assert(!string.IsNullOrEmpty(outputFileName));
Debug.Assert(!string.IsNullOrEmpty(relativeOutputPath));
var scriptsDir = Path.Combine(projectDir, "Scripts");
var outputDir = Path.Combine(projectDir, relativeOutputPath);
projectDirectory = projectDir;
referenceSearchPaths.Add(outputDir);
referenceSearchPaths.Add(RuntimeEnvironment.GetRuntimeDirectory());
foreach (Reference reference in vsProject.References)
{
var str = GetReferenceString(reference);
if (str != null)
{
references.Add(str);
}
}
references.Add(outputFileName);
// TODO (tomat): project Scripts dir
sourceSearchPaths.Add(Directory.Exists(scriptsDir) ? scriptsDir : projectDir);
if (!string.IsNullOrEmpty(defaultNamespace))
{
namespacesToImport.Add(defaultNamespace);
}
}
private static string GetReferenceString(Reference reference)
{
if (!reference.StrongName)
{
return reference.Path;
}
string name = reference.Name;
if (name == "mscorlib")
{
// mscorlib is always loaded
return null;
}
// TODO: This shouldn't directly depend on GAC, rather we should have some kind of "reference simplifier".
var possibleGacNames = GlobalAssemblyCache.GetAssemblyIdentities(name).ToArray();
if (possibleGacNames.Length == 0)
{
// no assembly with simple "name" found in GAC, use path to identify the reference:
return reference.Path;
}
string version = reference.Version;
string culture = reference.Culture;
string publicKeyToken = reference.PublicKeyToken;
var fullName = string.Concat(
name,
", Version=",
version,
", Culture=",
(culture == "") ? "neutral" : culture,
", PublicKeyToken=",
publicKeyToken.ToLowerInvariant());
AssemblyIdentity identity;
if (!AssemblyIdentity.TryParseDisplayName(fullName, out identity))
{
// ignore invalid names:
return null;
}
var foundEquivalent = false;
var foundNonEquivalent = false;
foreach (var possibleGacName in possibleGacNames)
{
if (DesktopAssemblyIdentityComparer.Default.ReferenceMatchesDefinition(identity, possibleGacName))
{
foundEquivalent = true;
}
else
{
foundNonEquivalent = true;
}
if (foundEquivalent && foundNonEquivalent)
{
break;
}
}
if (!foundEquivalent)
{
// The reference name isn't equivalent to any GAC name.
// The assembly is strong named but not GAC'd, so we need to load it from path:
return reference.Path;
}
if (foundNonEquivalent)
{
// We found some equivalent assemblies but also some non-equivalent.
// So simple name doesn't identify the reference uniquely.
return fullName;
}
// We found a single simple name match that is equivalent to the given reference.
// We can use the simple name to load the GAC'd assembly.
return name;
}
private static void SafeRelease(IntPtr pointer)
{
if (pointer != IntPtr.Zero)
{
Marshal.Release(pointer);
}
}
private Task<bool> BuildProject()
{
var taskSource = new TaskCompletionSource<bool>();
var updateSolutionEvents = new VsUpdateSolutionEvents(_buildManager, taskSource);
// Build the project. When project build is done, set the task source as being done.
// (Either succeeded, cancelled, or failed).
_dte.ExecuteCommand("Build.BuildSelection");
return taskSource.Task;
}
}
}
| |
// 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;
namespace System.Xml.Linq
{
internal class XNodeBuilder : XmlWriter
{
private List<object> _content;
private XContainer _parent;
private XName _attrName;
private string _attrValue;
private XContainer _root;
public XNodeBuilder(XContainer container)
{
_root = container;
}
public override XmlWriterSettings Settings
{
get
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.ConformanceLevel = ConformanceLevel.Auto;
return settings;
}
}
public override WriteState WriteState
{
get { throw new NotSupportedException(); } // nop
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Close();
}
}
private void Close()
{
_root.Add(_content);
}
public override void Flush()
{
}
public override string LookupPrefix(string namespaceName)
{
throw new NotSupportedException(); // nop
}
public override void WriteBase64(byte[] buffer, int index, int count)
{
throw new NotSupportedException(SR.NotSupported_WriteBase64);
}
public override void WriteCData(string text)
{
AddNode(new XCData(text));
}
public override void WriteCharEntity(char ch)
{
AddString(new string(ch, 1));
}
public override void WriteChars(char[] buffer, int index, int count)
{
AddString(new string(buffer, index, count));
}
public override void WriteComment(string text)
{
AddNode(new XComment(text));
}
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
AddNode(new XDocumentType(name, pubid, sysid, subset));
}
public override void WriteEndAttribute()
{
XAttribute a = new XAttribute(_attrName, _attrValue);
_attrName = null;
_attrValue = null;
if (_parent != null)
{
_parent.Add(a);
}
else
{
Add(a);
}
}
public override void WriteEndDocument()
{
}
public override void WriteEndElement()
{
_parent = ((XElement)_parent).parent;
}
public override void WriteEntityRef(string name)
{
switch (name)
{
case "amp":
AddString("&");
break;
case "apos":
AddString("'");
break;
case "gt":
AddString(">");
break;
case "lt":
AddString("<");
break;
case "quot":
AddString("\"");
break;
default:
throw new NotSupportedException(SR.NotSupported_WriteEntityRef);
}
}
public override void WriteFullEndElement()
{
XElement e = (XElement)_parent;
if (e.IsEmpty)
{
e.Add(string.Empty);
}
_parent = e.parent;
}
public override void WriteProcessingInstruction(string name, string text)
{
if (name == "xml")
{
return;
}
AddNode(new XProcessingInstruction(name, text));
}
public override void WriteRaw(char[] buffer, int index, int count)
{
AddString(new string(buffer, index, count));
}
public override void WriteRaw(string data)
{
AddString(data);
}
public override void WriteStartAttribute(string prefix, string localName, string namespaceName)
{
if (prefix == null) throw new ArgumentNullException("prefix");
_attrName = XNamespace.Get(prefix.Length == 0 ? string.Empty : namespaceName).GetName(localName);
_attrValue = string.Empty;
}
public override void WriteStartDocument()
{
}
public override void WriteStartDocument(bool standalone)
{
}
public override void WriteStartElement(string prefix, string localName, string namespaceName)
{
AddNode(new XElement(XNamespace.Get(namespaceName).GetName(localName)));
}
public override void WriteString(string text)
{
AddString(text);
}
public override void WriteSurrogateCharEntity(char lowCh, char highCh)
{
AddString(new string(new char[] { highCh, lowCh }));
}
public override void WriteValue(DateTimeOffset value)
{
// For compatibility with custom writers, XmlWriter writes DateTimeOffset as DateTime.
// Our internal writers should use the DateTimeOffset-String conversion from XmlConvert.
WriteString(XmlConvert.ToString(value));
}
public override void WriteWhitespace(string ws)
{
AddString(ws);
}
void Add(object o)
{
if (_content == null)
{
_content = new List<object>();
}
_content.Add(o);
}
void AddNode(XNode n)
{
if (_parent != null)
{
_parent.Add(n);
}
else
{
Add(n);
}
XContainer c = n as XContainer;
if (c != null)
{
_parent = c;
}
}
void AddString(string s)
{
if (s == null)
{
return;
}
if (_attrValue != null)
{
_attrValue += s;
}
else if (_parent != null)
{
_parent.Add(s);
}
else
{
Add(s);
}
}
}
}
| |
// 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 System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Data.SqlClient.ManualTesting.Tests
{
public class AsyncCancelledConnectionsTest
{
private readonly ITestOutputHelper _output;
private const int NumberOfTasks = 100; // How many attempts to poison the connection pool we will try
private const int NumberOfNonPoisoned = 10; // Number of normal requests for each attempt
public AsyncCancelledConnectionsTest(ITestOutputHelper output)
{
this._output = output;
}
[ActiveIssue(490)] // This test seems to fail regularly in pipelines due to deadlocks. But it's still useful for local testing.
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
public void CancelAsyncConnections()
{
string connectionString = DataTestUtility.TcpConnStr;
_watch = Stopwatch.StartNew();
_random = new Random(4); // chosen via fair dice role.
ParallelLoopResult results = new ParallelLoopResult();
try
{
// Setup a timer so that we can see what is going on while our tasks run
using (new Timer(TimerCallback, state: null, dueTime: TimeSpan.FromSeconds(5), period: TimeSpan.FromSeconds(5)))
{
results = Parallel.For(
fromInclusive: 0,
toExclusive: NumberOfTasks,
(int i) => DoManyAsync(connectionString).GetAwaiter().GetResult());
}
}
catch (Exception ex)
{
_output.WriteLine(ex.ToString());
}
while (!results.IsCompleted)
{
Thread.Sleep(50);
}
DisplaySummary();
foreach (var detail in _exceptionDetails)
{
_output.WriteLine(detail);
}
Assert.Empty(_exceptionDetails);
}
// Display one row every 5'ish seconds
private void TimerCallback(object state)
{
lock (_lockObject)
{
DisplaySummary();
}
}
private void DisplaySummary()
{
int count;
lock (_exceptionDetails)
{
count = _exceptionDetails.Count;
}
_output.WriteLine($"{_watch.Elapsed} {_continue} Started:{_start} Done:{_done} InFlight:{_inFlight} RowsRead:{_rowsRead} ResultRead:{_resultRead} PoisonedEnded:{_poisonedEnded} nonPoisonedExceptions:{_nonPoisonedExceptions} PoisonedCleanupExceptions:{_poisonCleanUpExceptions} Count:{count} Found:{_found}");
}
// This is the the main body that our Tasks run
private async Task DoManyAsync(string connectionString)
{
Interlocked.Increment(ref _start);
Interlocked.Increment(ref _inFlight);
// First poison
await DoOneAsync(connectionString, poison: true);
for (int i = 0; i < NumberOfNonPoisoned && _continue; i++)
{
// now run some without poisoning
await DoOneAsync(connectionString);
}
Interlocked.Decrement(ref _inFlight);
Interlocked.Increment(ref _done);
}
// This will do our work, open a connection, and run a query (that returns 4 results sets)
// if we are poisoning we will
// 1 - Interject some sleeps in the sql statement so that it will run long enough that we can cancel it
// 2 - Setup a time bomb task that will cancel the command a random amount of time later
private async Task DoOneAsync(string connectionString, bool poison = false)
{
try
{
using (var connection = new SqlConnection(connectionString))
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 4; i++)
{
builder.AppendLine("SELECT name FROM sys.tables");
if (poison && i < 3)
{
builder.AppendLine("WAITFOR DELAY '00:00:01'");
}
}
int rowsRead = 0;
int resultRead = 0;
try
{
await connection.OpenAsync();
using (var command = connection.CreateCommand())
{
Task timeBombTask = default;
try
{
// Setup our time bomb
if (poison)
{
timeBombTask = TimeBombAsync(command);
}
command.CommandText = builder.ToString();
// Attempt to read all of the data
using (var reader = await command.ExecuteReaderAsync())
{
try
{
do
{
resultRead++;
while (await reader.ReadAsync() && _continue)
{
rowsRead++;
}
}
while (await reader.NextResultAsync() && _continue);
}
catch when (poison)
{
// This looks a little strange, we failed to read above so this should fail too
// But consider the case where this code is elsewhere (in the Dispose method of a class holding this logic)
try
{
while (await reader.NextResultAsync())
{
}
}
catch
{
Interlocked.Increment(ref _poisonCleanUpExceptions);
}
throw;
}
}
}
finally
{
// Make sure to clean up our time bomb
// It is unlikely, but the timebomb may get delayed in the Task Queue
// And we don't want it running after we dispose the command
if (timeBombTask != default)
{
await timeBombTask;
}
}
}
}
finally
{
Interlocked.Add(ref _rowsRead, rowsRead);
Interlocked.Add(ref _resultRead, resultRead);
if (poison)
{
Interlocked.Increment(ref _poisonedEnded);
}
}
}
}
catch (Exception ex)
{
if (!poison)
{
Interlocked.Increment(ref _nonPoisonedExceptions);
string details = ex.ToString();
details = details.Substring(0, Math.Min(200, details.Length));
lock (_exceptionDetails)
{
_exceptionDetails.Add(details);
}
}
if (ex.Message.Contains("The MARS TDS header contained errors."))
{
_continue = false;
if (_found == 0) // This check is not really safe we may list more than one.
{
lock (_lockObject)
{
// You will notice that poison will be likely be false here, it is the normal commands that suffer
// Once we have successfully poisoned the connection pool, we may start to see some other request to poison fail just like the normal requests
_output.WriteLine($"{poison} {DateTime.UtcNow.ToString("O")}");
_output.WriteLine(ex.ToString());
}
}
Interlocked.Increment(ref _found);
}
}
}
private async Task TimeBombAsync(SqlCommand command)
{
await SleepAsync(100, 3000);
command.Cancel();
}
private async Task SleepAsync(int minMs, int maxMs)
{
int delayMs;
lock (_random)
{
delayMs = _random.Next(minMs, maxMs);
}
await Task.Delay(delayMs);
}
private Stopwatch _watch;
private int _inFlight;
private int _start;
private int _done;
private int _rowsRead;
private int _resultRead;
private int _nonPoisonedExceptions;
private int _poisonedEnded;
private int _poisonCleanUpExceptions;
private bool _continue = true;
private int _found;
private Random _random;
private object _lockObject = new object();
private HashSet<string> _exceptionDetails = new HashSet<string>();
}
}
| |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion License
// Aknowledgments
// This module borrows code and ideas from TinyPG framework by Herre Kuijpers,
// specifically TextMarker.cs and TextHighlighter.cs classes.
// http://www.codeproject.com/KB/recipes/TinyPG.aspx
// Written by Alexey Yakovlev <[email protected]>, based on RichTextBoxHighlighter
//
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using FastColoredTextBoxNS;
using Irony.Parsing;
namespace Irony.GrammarExplorer.Highlighter
{
/// <summary>
/// Highlights text inside FastColoredTextBox control.
/// </summary>
public class FastColoredTextBoxHighlighter : NativeWindow, IDisposable, IUIThreadInvoker
{
public readonly EditorAdapter Adapter;
public readonly LanguageData Language;
public readonly EditorViewAdapter ViewAdapter;
private readonly Style DefaultTokenStyle = new TextStyle(Brushes.Black, null, FontStyle.Regular);
private readonly Style ErrorTokenStyle = new WavyLineStyle(240, Color.Red);
private readonly Dictionary<TokenColor, Style> TokenStyles = new Dictionary<TokenColor, Style>();
public FastColoredTextBox TextBox;
private bool colorizing;
private bool disposed;
private IntPtr savedEventMask = IntPtr.Zero;
#region Constructor, initialization and disposing
public FastColoredTextBoxHighlighter(FastColoredTextBox textBox, LanguageData language)
{
this.TextBox = textBox;
this.Adapter = new EditorAdapter(language);
this.ViewAdapter = new EditorViewAdapter(this.Adapter, this);
this.Language = language;
this.InitStyles();
this.InitBraces();
this.Connect();
this.UpdateViewRange();
this.ViewAdapter.SetNewText(this.TextBox.Text);
}
public void Dispose()
{
this.Adapter.Stop();
this.disposed = true;
this.Disconnect();
this.ReleaseHandle();
GC.SuppressFinalize(this);
}
private void Connect()
{
this.TextBox.MouseMove += this.TextBox_MouseMove;
this.TextBox.TextChanged += this.TextBox_TextChanged;
this.TextBox.KeyDown += this.TextBox_KeyDown;
this.TextBox.VisibleRangeChanged += this.TextBox_ScrollResize;
this.TextBox.SizeChanged += this.TextBox_ScrollResize;
this.TextBox.Disposed += this.TextBox_Disposed;
this.ViewAdapter.ColorizeTokens += this.Adapter_ColorizeTokens;
this.AssignHandle(this.TextBox.Handle);
}
private void Disconnect()
{
if (this.TextBox != null)
{
this.TextBox.MouseMove -= this.TextBox_MouseMove;
this.TextBox.TextChanged -= this.TextBox_TextChanged;
this.TextBox.KeyDown -= this.TextBox_KeyDown;
this.TextBox.Disposed -= this.TextBox_Disposed;
this.TextBox.VisibleRangeChanged -= this.TextBox_ScrollResize;
this.TextBox.SizeChanged -= this.TextBox_ScrollResize;
}
this.TextBox = null;
}
private void InitBraces()
{
// Select the first two pair of braces with the length of exactly one char (FCTB restrictions)
var braces = Language.Grammar.KeyTerms
.Select(pair => pair.Value)
.Where(term => term.Flags.IsSet(TermFlags.IsOpenBrace))
.Where(term => term.IsPairFor != null && term.IsPairFor is KeyTerm)
.Where(term => term.Text.Length == 1)
.Where(term => ((KeyTerm) term.IsPairFor).Text.Length == 1)
.Take(2);
if (braces.Any())
{
// First pair
var brace = braces.First();
this.TextBox.LeftBracket = brace.Text.First();
this.TextBox.RightBracket = ((KeyTerm) brace.IsPairFor).Text.First();
// Second pair
if (braces.Count() > 1)
{
brace = braces.Last();
this.TextBox.LeftBracket2 = brace.Text.First();
this.TextBox.RightBracket2 = ((KeyTerm) brace.IsPairFor).Text.First();
}
}
}
private void InitStyles()
{
var commentStyle = new TextStyle(Brushes.Green, null, FontStyle.Italic);
var keywordStyle = new TextStyle(Brushes.Blue, null, FontStyle.Bold);
var literalStyle = new TextStyle(Brushes.DarkRed, null, FontStyle.Regular);
this.TokenStyles[TokenColor.Comment] = commentStyle;
this.TokenStyles[TokenColor.Identifier] = DefaultTokenStyle;
this.TokenStyles[TokenColor.Keyword] = keywordStyle;
this.TokenStyles[TokenColor.Number] = literalStyle;
this.TokenStyles[TokenColor.String] = literalStyle;
this.TokenStyles[TokenColor.Text] = DefaultTokenStyle;
this.TextBox.ClearStylesBuffer();
this.TextBox.AddStyle(this.DefaultTokenStyle);
this.TextBox.AddStyle(this.ErrorTokenStyle);
this.TextBox.AddStyle(commentStyle);
this.TextBox.AddStyle(keywordStyle);
this.TextBox.AddStyle(literalStyle);
this.TextBox.BracketsStyle = new MarkerStyle(new SolidBrush(Color.FromArgb(50, Color.Blue)));
this.TextBox.BracketsStyle2 = new MarkerStyle(new SolidBrush(Color.FromArgb(70, Color.Green)));
}
#endregion Constructor, initialization and disposing
#region TextBox event handlers
private void TextBox_Disposed(object sender, EventArgs e)
{
this.Dispose();
}
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
// TODO: implement showing intellisense hints or drop-downs
}
private void TextBox_MouseMove(object sender, MouseEventArgs e)
{
// TODO: implement showing tip
}
private void TextBox_ScrollResize(object sender, EventArgs e)
{
this.UpdateViewRange();
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
// If we are here while colorizing, it means the "change" event is a result of our coloring action
if (this.colorizing)
return;
this.ViewAdapter.SetNewText(this.TextBox.Text);
}
private void UpdateViewRange()
{
this.ViewAdapter.SetViewRange(0, this.TextBox.Text.Length);
}
#endregion TextBox event handlers
#region WinAPI
private const int EM_GETEVENTMASK = (WM_USER + 59);
private const int EM_SETEVENTMASK = (WM_USER + 69);
private const int SB_HORZ = 0x0;
private const int SB_THUMBPOSITION = 4;
private const int SB_VERT = 0x1;
private const int WM_HSCROLL = 0x114;
private const int WM_PAINT = 0x000F;
private const int WM_SETREDRAW = 0x000B;
private const int WM_USER = 0x400;
private const int WM_VSCROLL = 0x115;
private int HScrollPos
{
get
{
// Sometimes explodes with null reference exception
return GetScrollPos((int) this.TextBox.Handle, SB_HORZ);
}
set
{
SetScrollPos((IntPtr) this.TextBox.Handle, SB_HORZ, value, true);
PostMessageA((IntPtr) this.TextBox.Handle, WM_HSCROLL, SB_THUMBPOSITION + 0x10000 * value, 0);
}
}
private int VScrollPos
{
get
{
return GetScrollPos((int) this.TextBox.Handle, SB_VERT);
}
set
{
SetScrollPos((IntPtr) this.TextBox.Handle, SB_VERT, value, true);
PostMessageA((IntPtr) this.TextBox.Handle, WM_VSCROLL, SB_THUMBPOSITION + 0x10000 * value, 0);
}
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int GetScrollPos(int hWnd, int nBar);
[DllImport("user32.dll")]
private static extern bool PostMessageA(IntPtr hWnd, int nBar, int wParam, int lParam);
[DllImport("user32", CharSet = CharSet.Auto)]
private extern static IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern int SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw);
#endregion WinAPI
#region Colorizing tokens
public void LockTextBox()
{
// Stop redrawing:
this.TextBox.BeginUpdate();
SendMessage(this.TextBox.Handle, WM_SETREDRAW, 0, IntPtr.Zero);
// Stop sending of events:
this.savedEventMask = SendMessage(this.TextBox.Handle, EM_GETEVENTMASK, 0, IntPtr.Zero);
SendMessage(this.TextBox.Handle, EM_SETEVENTMASK, 0, IntPtr.Zero);
}
public void UnlockTextBox()
{
// Turn on events
SendMessage(this.TextBox.Handle, EM_SETEVENTMASK, 0, this.savedEventMask);
// Turn on redrawing
SendMessage(this.TextBox.Handle, WM_SETREDRAW, 1, IntPtr.Zero);
this.TextBox.EndUpdate();
}
private void Adapter_ColorizeTokens(object sender, ColorizeEventArgs args)
{
if (this.disposed)
return;
this.colorizing = true;
this.TextBox.BeginUpdate();
try
{
foreach (Token tkn in args.Tokens)
{
var tokenRange = this.TextBox.GetRange(tkn.Location.Position, tkn.Location.Position + tkn.Length);
var tokenStyle = this.GetTokenStyle(tkn);
tokenRange.ClearStyle(StyleIndex.All);
tokenRange.SetStyle(tokenStyle);
}
}
finally
{
this.TextBox.EndUpdate();
this.colorizing = false;
}
}
private Style GetTokenStyle(Token token)
{
if (token.IsError())
return this.ErrorTokenStyle;
if (token.EditorInfo == null)
return this.DefaultTokenStyle;
// Right now we scan source, not parse; initially all keywords are recognized as Identifiers; then they are "backpatched"
// by parser when it detects that it is in fact keyword from Grammar. So now this backpatching does not happen,
// so we have to detect keywords here
var styleIndex = token.EditorInfo.Color;
if (token.KeyTerm != null && token.KeyTerm.EditorInfo != null && token.KeyTerm.Flags.IsSet(TermFlags.IsKeyword))
{
styleIndex = token.KeyTerm.EditorInfo.Color;
}
Style result;
if (this.TokenStyles.TryGetValue(styleIndex, out result))
return result;
return this.DefaultTokenStyle;
}
#endregion Colorizing tokens
#region IUIThreadInvoker Members
public void InvokeOnUIThread(ColorizeMethod colorize)
{
this.TextBox.BeginInvoke(new MethodInvoker(colorize));
}
#endregion IUIThreadInvoker Members
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using AutoMapper.Internal;
namespace AutoMapper
{
internal static class ReflectionExtensions
{
public static object GetDefaultValue(this ParameterInfo parameter)
=> ReflectionHelper.GetDefaultValue(parameter);
public static object MapMember(this ResolutionContext context, MemberInfo member, object value, object destination)
=> ReflectionHelper.MapMember(context, member, value, destination);
public static object MapMember(this ResolutionContext context, MemberInfo member, object value)
=> ReflectionHelper.MapMember(context, member, value);
public static bool IsDynamic(this object obj)
=> ReflectionHelper.IsDynamic(obj);
public static bool IsDynamic(this Type type)
=> ReflectionHelper.IsDynamic(type);
public static void SetMemberValue(this MemberInfo propertyOrField, object target, object value)
=> ReflectionHelper.SetMemberValue(propertyOrField, target, value);
public static object GetMemberValue(this MemberInfo propertyOrField, object target)
=> ReflectionHelper.GetMemberValue(propertyOrField, target);
public static IEnumerable<MemberInfo> GetMemberPath(Type type, string fullMemberName)
=> ReflectionHelper.GetMemberPath(type, fullMemberName);
public static MemberInfo GetFieldOrProperty(this LambdaExpression expression)
=> ReflectionHelper.GetFieldOrProperty(expression);
public static MemberInfo FindProperty(LambdaExpression lambdaExpression)
=> ReflectionHelper.FindProperty(lambdaExpression);
public static Type GetMemberType(this MemberInfo memberInfo)
=> ReflectionHelper.GetMemberType(memberInfo);
/// <summary>
/// if targetType is oldType, method will return newType
/// if targetType is not oldType, method will return targetType
/// if targetType is generic type with oldType arguments, method will replace all oldType arguments on newType
/// </summary>
/// <param name="targetType"></param>
/// <param name="oldType"></param>
/// <param name="newType"></param>
/// <returns></returns>
public static Type ReplaceItemType(this Type targetType, Type oldType, Type newType)
=> ReflectionHelper.ReplaceItemType(targetType, oldType, newType);
#if NET40
public static TypeInfo GetTypeInfo(this Type type)
{
return TypeInfo.FromType(type);
}
public static IEnumerable<TypeInfo> GetDefinedTypes(this Assembly assembly)
{
Type[] types = assembly.GetTypes();
TypeInfo[] array = new TypeInfo[types.Length];
for (int i = 0; i < types.Length; i++)
{
TypeInfo typeInfo = types[i].GetTypeInfo();
array[i] = typeInfo ?? throw new NotSupportedException();
}
return array;
}
public static bool GetHasDefaultValue(this ParameterInfo info) =>
info.GetDefaultValue() != DBNull.Value;
public static bool GetIsConstructedGenericType(this Type type) =>
type.IsGenericType && !type.IsGenericTypeDefinition;
#else
public static IEnumerable<TypeInfo> GetDefinedTypes(this Assembly assembly) =>
assembly.DefinedTypes;
public static bool GetHasDefaultValue(this ParameterInfo info) =>
info.HasDefaultValue;
public static bool GetIsConstructedGenericType(this Type type) =>
type.IsConstructedGenericType;
#endif
}
}
#if NET40
namespace System.Reflection
{
using System.Collections.Concurrent;
using System.Globalization;
[Serializable]
internal class TypeInfo
{
public static readonly ConcurrentDictionary<Type, TypeInfo> _typeInfoCache = new ConcurrentDictionary<Type, TypeInfo>();
public static TypeInfo FromType(Type type)
{
return _typeInfoCache.GetOrAdd(type, t => new TypeInfo(t));
}
public IEnumerable<Type> ImplementedInterfaces => _type.GetInterfaces();
public Type[] GenericTypeParameters
{
get
{
if (_type.IsGenericTypeDefinition)
return _type.GetGenericArguments();
return Type.EmptyTypes;
}
}
public Type[] GenericTypeArguments
{
get
{
if (_type.IsGenericType && !_type.IsGenericTypeDefinition)
return _type.GetGenericArguments();
return Type.EmptyTypes;
}
}
public virtual IEnumerable<ConstructorInfo> DeclaredConstructors =>
_type.GetConstructors(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
public virtual IEnumerable<MemberInfo> DeclaredMembers =>
_type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
public virtual IEnumerable<MethodInfo> DeclaredMethods =>
_type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
public virtual IEnumerable<PropertyInfo> DeclaredProperties =>
_type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
public virtual Guid GUID => _type.GUID;
public virtual Module Module => _type.Module;
public virtual Assembly Assembly => _type.Assembly;
public virtual string FullName => _type.FullName;
public virtual string Namespace => _type.Namespace;
public virtual string AssemblyQualifiedName => _type.AssemblyQualifiedName;
public virtual Type BaseType => _type.BaseType;
public virtual Type UnderlyingSystemType => _type.UnderlyingSystemType;
public virtual string Name => _type.Name;
public bool IsInterface => _type.IsInterface;
public bool IsGenericParameter => _type.IsGenericParameter;
public bool IsValueType => _type.IsValueType;
public bool IsGenericType => _type.IsGenericType;
public bool IsAbstract => _type.IsAbstract;
public bool IsClass => _type.IsClass;
public bool IsEnum => _type.IsEnum;
public bool IsGenericTypeDefinition => _type.IsGenericTypeDefinition;
public bool IsSealed => _type.IsSealed;
public bool IsPrimitive => _type.IsPrimitive;
private readonly Type _type;
protected TypeInfo(Type type)
{
_type = type;
}
public Type AsType() => _type;
public virtual PropertyInfo GetDeclaredProperty(string name) =>
_type.GetProperty(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
public virtual object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) =>
_type.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
public virtual ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) =>
_type.GetConstructors(bindingAttr);
public virtual MethodInfo[] GetMethods(BindingFlags bindingAttr) =>
_type.GetMethods(bindingAttr);
public virtual FieldInfo GetField(string name, BindingFlags bindingAttr) =>
_type.GetField(name, bindingAttr);
public virtual FieldInfo[] GetFields(BindingFlags bindingAttr) =>
_type.GetFields(bindingAttr);
public virtual Type GetInterface(string name, bool ignoreCase) =>
_type.GetInterface(name, ignoreCase);
public virtual Type[] GetInterfaces() =>
_type.GetInterfaces();
public virtual EventInfo GetEvent(string name, BindingFlags bindingAttr) =>
_type.GetEvent(name, bindingAttr);
public virtual EventInfo[] GetEvents(BindingFlags bindingAttr) =>
_type.GetEvents(bindingAttr);
public virtual PropertyInfo[] GetProperties(BindingFlags bindingAttr) =>
_type.GetProperties(bindingAttr);
public virtual Type[] GetNestedTypes(BindingFlags bindingAttr) =>
_type.GetNestedTypes(bindingAttr);
public virtual Type GetNestedType(string name, BindingFlags bindingAttr) =>
_type.GetNestedType(name, bindingAttr);
public virtual MemberInfo[] GetMembers(BindingFlags bindingAttr) =>
_type.GetMembers(bindingAttr);
public virtual Type GetElementType() =>
_type.GetElementType();
public virtual object[] GetCustomAttributes(bool inherit) =>
_type.GetCustomAttributes(inherit);
public virtual object[] GetCustomAttributes(Type attributeType, bool inherit) =>
_type.GetCustomAttributes(attributeType, inherit);
public virtual bool IsDefined(Type attributeType, bool inherit) =>
_type.IsDefined(attributeType, inherit);
public virtual bool IsSubclassOf(Type c) =>
_type.IsSubclassOf(c);
public virtual Type[] GetGenericParameterConstraints() =>
_type.GetGenericParameterConstraints();
public virtual bool IsAssignableFrom(TypeInfo typeInfo)
{
if (typeInfo == null)
{
return false;
}
if (this == typeInfo)
{
return true;
}
if (typeInfo.IsSubclassOf(_type))
{
return true;
}
if (IsInterface)
{
return typeInfo._type.ImplementInterface(_type);
}
if (this.IsGenericParameter)
{
Type[] genericParameterConstraints = this.GetGenericParameterConstraints();
for (int i = 0; i < genericParameterConstraints.Length; i++)
{
if (!genericParameterConstraints[i].IsAssignableFrom(typeInfo._type))
{
return false;
}
}
return true;
}
return false;
}
}
static class CustomAttributeExtensions
{
public static T GetCustomAttribute<T>(this MemberInfo element, bool inherit) where T : Attribute
{
return (T)Attribute.GetCustomAttribute(element, typeof(T), inherit);
}
public static Attribute GetCustomAttribute(this MemberInfo element, Type attributeType)
{
return Attribute.GetCustomAttribute(element, attributeType, false);
}
}
static class TypeExtensions
{
public static bool ImplementInterface(this Type type, Type ifaceType)
{
while (type != null)
{
Type[] interfaces = type.GetInterfaces();
if (interfaces != null)
{
for (int i = 0; i < interfaces.Length; i++)
{
if (interfaces[i] == ifaceType || (interfaces[i] != null && interfaces[i].ImplementInterface(ifaceType)))
{
return true;
}
}
}
type = type.BaseType;
}
return false;
}
}
static class RuntimeReflectionExtensions
{
public static IEnumerable<MethodInfo> GetRuntimeMethods(this Type type) =>
type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
public static IEnumerable<PropertyInfo> GetRuntimeProperties(this Type type) =>
type.GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
public static FieldInfo GetRuntimeField(this Type type, string name) =>
type.GetField(name);
public static EventInfo GetRuntimeEvent(this Type type, string name) =>
type.GetEvent(name);
}
}
#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.
/*============================================================
**
**
**
**
**
** Purpose: Abstract base class for all Text-only Readers.
** Subclasses will include StreamReader & StringReader.
**
**
===========================================================*/
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO {
// This abstract base class represents a reader that can read a sequential
// stream of characters. This is not intended for reading bytes -
// there are methods on the Stream class to read bytes.
// A subclass must minimally implement the Peek() and Read() methods.
//
// This class is intended for character input, not bytes.
// There are methods on the Stream class for reading bytes.
[Serializable]
[ComVisible(true)]
public abstract class TextReader : MarshalByRefObject, IDisposable {
public static readonly TextReader Null = new NullTextReader();
protected TextReader() {}
// Closes this TextReader and releases any system resources associated with the
// TextReader. Following a call to Close, any operations on the TextReader
// may raise exceptions.
//
// This default method is empty, but descendant classes can override the
// method to provide the appropriate functionality.
public virtual void Close()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
// Returns the next available character without actually reading it from
// the input stream. The current position of the TextReader is not changed by
// this operation. The returned value is -1 if no further characters are
// available.
//
// This default method simply returns -1.
//
[Pure]
public virtual int Peek()
{
Contract.Ensures(Contract.Result<int>() >= -1);
return -1;
}
// Reads the next character from the input stream. The returned value is
// -1 if no further characters are available.
//
// This default method simply returns -1.
//
public virtual int Read()
{
Contract.Ensures(Contract.Result<int>() >= -1);
return -1;
}
// Reads a block of characters. This method will read up to
// count characters from this TextReader into the
// buffer character array starting at position
// index. Returns the actual number of characters read.
//
public virtual int Read([In, Out] char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() <= Contract.OldValue(count));
Contract.EndContractBlock();
int n = 0;
do {
int ch = Read();
if (ch == -1) break;
buffer[index + n++] = (char)ch;
} while (n < count);
return n;
}
// Reads all characters from the current position to the end of the
// TextReader, and returns them as one string.
public virtual String ReadToEnd()
{
Contract.Ensures(Contract.Result<String>() != null);
char[] chars = new char[4096];
int len;
StringBuilder sb = new StringBuilder(4096);
while((len=Read(chars, 0, chars.Length)) != 0)
{
sb.Append(chars, 0, len);
}
return sb.ToString();
}
// Blocking version of read. Returns only when count
// characters have been read or the end of the file was reached.
//
public virtual int ReadBlock([In, Out] char[] buffer, int index, int count)
{
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() <= count);
int i, n = 0;
do {
n += (i = Read(buffer, index + n, count - n));
} while (i > 0 && n < count);
return n;
}
// Reads a line. A line is defined as a sequence of characters followed by
// a carriage return ('\r'), a line feed ('\n'), or a carriage return
// immediately followed by a line feed. The resulting string does not
// contain the terminating carriage return and/or line feed. The returned
// value is null if the end of the input stream has been reached.
//
public virtual String ReadLine()
{
StringBuilder sb = new StringBuilder();
while (true) {
int ch = Read();
if (ch == -1) break;
if (ch == '\r' || ch == '\n')
{
if (ch == '\r' && Peek() == '\n') Read();
return sb.ToString();
}
sb.Append((char)ch);
}
if (sb.Length > 0) return sb.ToString();
return null;
}
#region Task based Async APIs
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public virtual Task<String> ReadLineAsync()
{
return Task<String>.Factory.StartNew(state =>
{
return ((TextReader)state).ReadLine();
},
this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public async virtual Task<String> ReadToEndAsync()
{
char[] chars = new char[4096];
int len;
StringBuilder sb = new StringBuilder(4096);
while((len = await ReadAsyncInternal(chars, 0, chars.Length).ConfigureAwait(false)) != 0)
{
sb.Append(chars, 0, len);
}
return sb.ToString();
}
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public virtual Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
return ReadAsyncInternal(buffer, index, count);
}
internal virtual Task<int> ReadAsyncInternal(char[] buffer, int index, int count)
{
Contract.Requires(buffer != null);
Contract.Requires(index >= 0);
Contract.Requires(count >= 0);
Contract.Requires(buffer.Length - index >= count);
var tuple = new Tuple<TextReader, char[], int, int>(this, buffer, index, count);
return Task<int>.Factory.StartNew(state =>
{
var t = (Tuple<TextReader, char[], int, int>)state;
return t.Item1.Read(t.Item2, t.Item3, t.Item4);
},
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public virtual Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
return ReadBlockAsyncInternal(buffer, index, count);
}
[HostProtection(ExternalThreading=true)]
private async Task<int> ReadBlockAsyncInternal(char[] buffer, int index, int count)
{
Contract.Requires(buffer != null);
Contract.Requires(index >= 0);
Contract.Requires(count >= 0);
Contract.Requires(buffer.Length - index >= count);
int i, n = 0;
do
{
i = await ReadAsyncInternal(buffer, index + n, count - n).ConfigureAwait(false);
n += i;
} while (i > 0 && n < count);
return n;
}
#endregion
[HostProtection(Synchronization=true)]
public static TextReader Synchronized(TextReader reader)
{
if (reader==null)
throw new ArgumentNullException(nameof(reader));
Contract.Ensures(Contract.Result<TextReader>() != null);
Contract.EndContractBlock();
if (reader is SyncTextReader)
return reader;
return new SyncTextReader(reader);
}
[Serializable]
private sealed class NullTextReader : TextReader
{
public NullTextReader(){}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override int Read(char[] buffer, int index, int count)
{
return 0;
}
public override String ReadLine()
{
return null;
}
}
[Serializable]
internal sealed class SyncTextReader : TextReader
{
internal TextReader _in;
internal SyncTextReader(TextReader t)
{
_in = t;
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Close()
{
// So that any overriden Close() gets run
_in.Close();
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
protected override void Dispose(bool disposing)
{
// Explicitly pick up a potentially methodimpl'ed Dispose
if (disposing)
((IDisposable)_in).Dispose();
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override int Peek()
{
return _in.Peek();
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override int Read()
{
return _in.Read();
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override int Read([In, Out] char[] buffer, int index, int count)
{
return _in.Read(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override int ReadBlock([In, Out] char[] buffer, int index, int count)
{
return _in.ReadBlock(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override String ReadLine()
{
return _in.ReadLine();
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override String ReadToEnd()
{
return _in.ReadToEnd();
}
//
// On SyncTextReader all APIs should run synchronously, even the async ones.
//
[ComVisible(false)]
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override Task<String> ReadLineAsync()
{
return Task.FromResult(ReadLine());
}
[ComVisible(false)]
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override Task<String> ReadToEndAsync()
{
return Task.FromResult(ReadToEnd());
}
[ComVisible(false)]
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
return Task.FromResult(ReadBlock(buffer, index, count));
}
[ComVisible(false)]
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
return Task.FromResult(Read(buffer, index, count));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Data.SqlClient;
using Utils;
using DevExpress.Utils;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using KabMan.Client.Modules.Common;
namespace KabMan.Client
{
public partial class RackDetailList : DevExpress.XtraEditors.XtraForm
{
private int sid;
WaitDialogForm dlgWait;
private RefreshHelper helper;
private Common com;
ModifyRegistry reg;
DatabaseLib data = new DatabaseLib();
public RackDetailList(int sid)
{
this.sid = sid;
InitializeComponent();
}
private int RecordId
{
get { return (int)bandedGridView1.DataController.GetCurrentRowValue("Id"); }
}
private int RecordId2
{
get { return (int)bandedGridView2.DataController.GetCurrentRowValue("Id"); }
}
private void ServerDetailList_Load(object sender, EventArgs e)
{
reg = new ModifyRegistry();
com = new Common();
com.LoadViewCols(bandedGridView1, "ServerDetailList");
helper = new RefreshHelper(bandedGridView1, "Id");
helper = new RefreshHelper(bandedGridView2, "Id");
FormText();
Liste(false);
}
private void FormText()
{
SqlDataReader dr;
DatabaseLib data = new DatabaseLib();
data.RunSqlQuery(string.Format("SELECT Value AS Server FROM tblTree WHERE RecDelete=0 and ObjectValue='Server' and ObjectId={0}", sid), out dr);
if (dr.Read())
{
this.Text = dr["Server"].ToString();
this.Tag = sid.ToString();
}
data.Dispose();
}
public void Liste(bool savePos)
{
Cursor = Cursors.WaitCursor;
dlgWait = new WaitDialogForm("Loading Data...");
dlgWait.StartPosition = FormStartPosition.CenterParent;
// grid pozisyonu kayit ediliyor
if (savePos) helper.SaveViewInfo();
DataSet ds;
SqlParameter[] prm =
{
data.MakeInParam("@RackId", sid),
data.MakeInParam("@SanId", 7)
};
data.RunProc("sp_selRackDetailList", prm, out ds);
data.Dispose();
gridControl1.DataSource = ds.Tables[0];
DataSet ds2;
SqlParameter[] prm2 =
{
data.MakeInParam("@RackId", sid),
data.MakeInParam("@SanId", 9)
};
data.RunProc("sp_selRackDetailList", prm2, out ds2);
data.Dispose();
gridControl2.DataSource = ds2.Tables[0];
if (ds.Tables[0].DefaultView.Count > 0)
{
BBtnDetail.Enabled = true;
BBtnDelete.Enabled = true;
}
else
{
BBtnDetail.Enabled = false;
BBtnDelete.Enabled = false;
}
// grid pozisyonu yukleniyor
if (savePos) helper.LoadViewInfo();
dlgWait.Close();
Cursor = Cursors.Default;
}
private void BBtnNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
}
private void BBtnDetail_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
}
private void BBtnDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
if (XtraMessageBox.Show(
"Are you sure you want to delete this information?",
Text,
MessageBoxButtons.OKCancel,
MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
{
// eger kayitid > 0 dan buyuk ise database dan siliniyor
if (RecordId > 0)
{
DatabaseLib data = new DatabaseLib();
SqlParameter[] prm = { data.MakeInParam("@RackDetailId", RecordId) };
data.RunProc("sp_delRackDetail", prm);
data.Dispose();
}
Liste(false);
}
}
private void BBtnClose_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
Close();
}
private void gridControl2_MouseDoubleClick(object sender, MouseEventArgs e)
{
RackActivite ra = new RackActivite(this, RecordId2);
ra.ShowDialog();
}
private void gridControl1_MouseDoubleClick(object sender, MouseEventArgs e)
{
RackActivite ra = new RackActivite(this, RecordId);
ra.ShowDialog();
}
private void gridView1_CustomDrawCell(object sender, RowCellCustomDrawEventArgs e)
{
if (e.RowHandle >= 0)
{
if (bandedGridView1.GetRowCellValue(e.RowHandle, Connect).ToString().Trim() == "True")
{
e.Appearance.BackColor = Color.FromArgb(255, Color.FromArgb(33333));
e.Appearance.BackColor2 = Color.FromArgb(255, Color.FromArgb(33333));
}
if (bandedGridView1.GetRowCellValue(e.RowHandle, Reservation).ToString().Trim() == "True")
{
e.Appearance.BackColor = Color.FromArgb(255, Color.FromArgb(44444));
e.Appearance.BackColor2 = Color.FromArgb(255, Color.FromArgb(44444));
}
}
}
private void gridView2_CustomDrawCell(object sender, RowCellCustomDrawEventArgs e)
{
if (e.RowHandle >= 0)
{
if (bandedGridView2.GetRowCellValue(e.RowHandle, Connect2).ToString().Trim() == "True")
{
e.Appearance.BackColor = Color.FromArgb(255, Color.FromArgb(33333));
e.Appearance.BackColor2 = Color.FromArgb(255, Color.FromArgb(33333));
}
if (bandedGridView2.GetRowCellValue(e.RowHandle, Reservation2).ToString().Trim() == "True")
{
e.Appearance.BackColor = Color.FromArgb(255, Color.FromArgb(44444));
e.Appearance.BackColor2 = Color.FromArgb(255, Color.FromArgb(44444));
}
}
}
private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
}
private void gridView1_RowUpdated(object sender, RowObjectEventArgs e)
{
// checkbox dan database update yapilacak.
DatabaseLib dataUp = new DatabaseLib();
SqlParameter[] prmUp =
{
dataUp.MakeInParam("@Id", rowId),
dataUp.MakeInParam("@Value", checkValue)
};
dataUp.RunProc("sp_UpRackDetail", prmUp);
dataUp.Dispose();
}
int rowId = 0;
bool checkValue;
private void repositoryItemCheckEdit1_CheckedChanged(object sender, EventArgs e)
{
DevExpress.XtraGrid.Views.Grid.GridView view = bandedGridView1;
rowId = Convert.ToInt32(bandedGridView1.GetRowCellValue(view.FocusedRowHandle, bandedGridColumn1));
checkValue = !Convert.ToBoolean(bandedGridView1.GetRowCellValue(view.FocusedRowHandle, gridColumn19));
}
private void bandedGridView1_RowUpdated(object sender, RowObjectEventArgs e)
{
DatabaseLib dataUp = new DatabaseLib();
SqlParameter[] prmUp =
{
dataUp.MakeInParam("@Id", rowId),
dataUp.MakeInParam("@Value", checkValue)
};
dataUp.RunProc("sp_UpRackDetail", prmUp);
dataUp.Dispose();
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2014 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Execution;
using NUnit.Tests;
using NUnit.Tests.Assemblies;
using NUnit.TestUtilities;
using NUnit.Framework.Internal.Filters;
namespace NUnit.Framework.Api
{
// Functional tests of the TestAssemblyRunner and all subordinate classes
public class TestAssemblyRunnerTests : ITestListener
{
private const string MOCK_ASSEMBLY_FILE = "mock-assembly.dll";
#if NETCOREAPP1_1
private const string COULD_NOT_LOAD_MSG = "The system cannot find the file specified.";
#else
private const string COULD_NOT_LOAD_MSG = "Could not load";
#endif
private const string BAD_FILE = "mock-assembly.pdb";
private const string SLOW_TESTS_FILE = "slow-nunit-tests.dll";
private const string MISSING_FILE = "junk.dll";
private static readonly string MOCK_ASSEMBLY_NAME = typeof(MockAssembly).GetTypeInfo().Assembly.FullName;
private const string INVALID_FILTER_ELEMENT_MESSAGE = "Invalid filter element: {0}";
private static readonly IDictionary<string, object> EMPTY_SETTINGS = new Dictionary<string, object>();
private ITestAssemblyRunner _runner;
private int _testStartedCount;
private int _testFinishedCount;
private int _testOutputCount;
private int _successCount;
private int _failCount;
private int _skipCount;
private int _inconclusiveCount;
[SetUp]
public void CreateRunner()
{
_runner = new NUnitTestAssemblyRunner(new DefaultTestAssemblyBuilder());
_testStartedCount = 0;
_testFinishedCount = 0;
_testOutputCount = 0;
_successCount = 0;
_failCount = 0;
_skipCount = 0;
_inconclusiveCount = 0;
}
#region Load
[Test]
public void Load_GoodFile_ReturnsRunnableSuite()
{
var result = LoadMockAssembly();
Assert.That(result.IsSuite);
Assert.That(result, Is.TypeOf<TestAssembly>());
Assert.That(result.Name, Is.EqualTo(MOCK_ASSEMBLY_FILE));
Assert.That(result.RunState, Is.EqualTo(Interfaces.RunState.Runnable));
Assert.That(result.TestCaseCount, Is.EqualTo(MockAssembly.Tests));
}
[Test, SetUICulture("en-US")]
public void Load_FileNotFound_ReturnsNonRunnableSuite()
{
var result = _runner.Load(MISSING_FILE, EMPTY_SETTINGS);
Assert.That(result.IsSuite);
Assert.That(result, Is.TypeOf<TestAssembly>());
Assert.That(result.Name, Is.EqualTo(MISSING_FILE));
Assert.That(result.RunState, Is.EqualTo(Interfaces.RunState.NotRunnable));
Assert.That(result.TestCaseCount, Is.EqualTo(0));
Assert.That(result.Properties.Get(PropertyNames.SkipReason),
Does.StartWith(COULD_NOT_LOAD_MSG));
}
[Test, SetUICulture("en-US")]
public void Load_BadFile_ReturnsNonRunnableSuite()
{
var result = _runner.Load(BAD_FILE, EMPTY_SETTINGS);
Assert.That(result.IsSuite);
Assert.That(result, Is.TypeOf<TestAssembly>());
Assert.That(result.Name, Is.EqualTo(BAD_FILE));
Assert.That(result.RunState, Is.EqualTo(Interfaces.RunState.NotRunnable));
Assert.That(result.TestCaseCount, Is.EqualTo(0));
Assert.That(result.Properties.Get(PropertyNames.SkipReason),
Does.StartWith("Could not load").And.Contains(BAD_FILE));
}
#endregion
#region CountTestCases
[Test]
public void CountTestCases_AfterLoad_ReturnsCorrectCount()
{
LoadMockAssembly();
Assert.That(_runner.CountTestCases(TestFilter.Empty), Is.EqualTo(MockAssembly.Tests));
}
[Test]
public void CountTestCases_WithoutLoad_ThrowsInvalidOperation()
{
var ex = Assert.Throws<InvalidOperationException>(
() => _runner.CountTestCases(TestFilter.Empty));
Assert.That(ex.Message, Is.EqualTo("The CountTestCases method was called but no test has been loaded"));
}
[Test]
public void CountTestCases_FileNotFound_ReturnsZero()
{
_runner.Load(MISSING_FILE, EMPTY_SETTINGS);
Assert.That(_runner.CountTestCases(TestFilter.Empty), Is.EqualTo(0));
}
[Test]
public void CountTestCases_BadFile_ReturnsZero()
{
_runner.Load(BAD_FILE, EMPTY_SETTINGS);
Assert.That(_runner.CountTestCases(TestFilter.Empty), Is.EqualTo(0));
}
#endregion
#region ExploreTests
[Test]
public void ExploreTests_WithoutLoad_ThrowsInvalidOperation()
{
var ex = Assert.Throws<InvalidOperationException>(
() => _runner.ExploreTests(TestFilter.Empty));
Assert.That(ex.Message, Is.EqualTo("The ExploreTests method was called but no test has been loaded"));
}
[Test]
public void ExploreTests_FileNotFound_ReturnsZeroTests()
{
_runner.Load(MISSING_FILE, EMPTY_SETTINGS);
var explorer = _runner.ExploreTests(TestFilter.Empty);
Assert.That(explorer.TestCaseCount, Is.EqualTo(0));
}
[Test]
public void ExploreTests_BadFile_ReturnsZeroTests()
{
_runner.Load(BAD_FILE, EMPTY_SETTINGS);
var explorer = _runner.ExploreTests(TestFilter.Empty);
Assert.That(explorer.TestCaseCount, Is.EqualTo(0));
}
[Test]
public void ExploreTests_AfterLoad_ReturnsCorrectCount()
{
LoadMockAssembly();
var explorer = _runner.ExploreTests(TestFilter.Empty);
Assert.That(explorer.TestCaseCount, Is.EqualTo(MockAssembly.Tests));
}
[Test]
public void ExploreTest_AfterLoad_ReturnsSameTestCount()
{
LoadMockAssembly();
var explorer = _runner.ExploreTests(TestFilter.Empty);
Assert.That(explorer.TestCaseCount, Is.EqualTo(_runner.CountTestCases(TestFilter.Empty)));
}
[Test]
public void ExploreTest_AfterLoad_AllIdsAreUnique()
{
LoadMockAssembly();
var explorer = _runner.ExploreTests(TestFilter.Empty);
var dict = new Dictionary<string, bool>();
CheckForDuplicates(explorer, dict);
}
private void CheckForDuplicates(ITest test, Dictionary<string, bool> dict)
{
Assert.False(dict.ContainsKey(test.Id), "Duplicate key: {0}", test.Id);
dict.Add(test.Id, true);
foreach (var child in test.Tests)
CheckForDuplicates(child, dict);
}
[Test]
public void ExploreTests_AfterLoad_WithFilter_ReturnCorrectCount()
{
LoadMockAssembly();
ITestFilter filter = new CategoryFilter("FixtureCategory");
var explorer = _runner.ExploreTests(filter);
Assert.That(explorer.TestCaseCount, Is.EqualTo(MockTestFixture.Tests));
}
[Test]
public void ExploreTests_AfterLoad_WithFilter_ReturnSameTestCount()
{
LoadMockAssembly();
ITestFilter filter = new CategoryFilter("FixtureCategory");
var explorer = _runner.ExploreTests(filter);
Assert.That(explorer.TestCaseCount, Is.EqualTo(_runner.CountTestCases(filter)));
}
#endregion
#region Run
[Test]
public void Run_AfterLoad_ReturnsRunnableSuite()
{
LoadMockAssembly();
var result = _runner.Run(TestListener.NULL, TestFilter.Empty);
Assert.That(result.Test.IsSuite);
Assert.That(result.Test, Is.TypeOf<TestAssembly>());
Assert.That(result.Test.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(result.Test.TestCaseCount, Is.EqualTo(MockAssembly.Tests));
Assert.That(result.ResultState, Is.EqualTo(ResultState.ChildFailure));
Assert.That(result.PassCount, Is.EqualTo(MockAssembly.Passed));
Assert.That(result.FailCount, Is.EqualTo(MockAssembly.Failed));
Assert.That(result.WarningCount, Is.EqualTo(MockAssembly.Warnings));
Assert.That(result.SkipCount, Is.EqualTo(MockAssembly.Skipped));
Assert.That(result.InconclusiveCount, Is.EqualTo(MockAssembly.Inconclusive));
}
[Test]
public void Run_AfterLoad_SendsExpectedEvents()
{
LoadMockAssembly();
_runner.Run(this, TestFilter.Empty);
Assert.That(_testStartedCount, Is.EqualTo(MockAssembly.TestStartedEvents));
Assert.That(_testFinishedCount, Is.EqualTo(MockAssembly.TestFinishedEvents));
Assert.That(_testOutputCount, Is.EqualTo(MockAssembly.TestOutputEvents));
Assert.That(_successCount, Is.EqualTo(MockAssembly.Passed));
Assert.That(_failCount, Is.EqualTo(MockAssembly.Failed));
Assert.That(_skipCount, Is.EqualTo(MockAssembly.Skipped));
Assert.That(_inconclusiveCount, Is.EqualTo(MockAssembly.Inconclusive));
}
[Test]
public void Run_WithoutLoad_ReturnsError()
{
var ex = Assert.Throws<InvalidOperationException>(
() => _runner.Run(TestListener.NULL, TestFilter.Empty));
Assert.That(ex.Message, Is.EqualTo("The Run method was called but no test has been loaded"));
}
[Test, SetUICulture("en-US")]
public void Run_FileNotFound_ReturnsNonRunnableSuite()
{
_runner.Load(MISSING_FILE, EMPTY_SETTINGS);
var result = _runner.Run(TestListener.NULL, TestFilter.Empty);
Assert.That(result.Test.IsSuite);
Assert.That(result.Test, Is.TypeOf<TestAssembly>());
Assert.That(result.Test.RunState, Is.EqualTo(RunState.NotRunnable));
Assert.That(result.Test.TestCaseCount, Is.EqualTo(0));
Assert.That(result.ResultState, Is.EqualTo(ResultState.NotRunnable.WithSite(FailureSite.SetUp)));
Assert.That(result.Message,
Does.StartWith(COULD_NOT_LOAD_MSG));
}
[Test]
public void RunTestsAction_WithInvalidFilterElement_ThrowsArgumentException()
{
LoadMockAssembly();
var ex = Assert.Throws<ArgumentException>(() =>
{
TestFilter.FromXml("<filter><invalidElement>foo</invalidElement></filter>");
});
Assert.That(ex.Message, Does.StartWith(string.Format(INVALID_FILTER_ELEMENT_MESSAGE, "invalidElement")));
}
[Test]
public void Run_WithParameters()
{
var dict = new Dictionary<string, string>();
dict.Add("X", "5");
dict.Add("Y", "7");
var settings = new Dictionary<string, object>();
settings.Add("TestParametersDictionary", dict);
LoadMockAssembly(settings);
var result = _runner.Run(TestListener.NULL, TestFilter.Empty);
CheckParameterOutput(result);
}
[Test]
public void Run_WithLegacyParameters()
{
var settings = new Dictionary<string, object>();
settings.Add("TestParameters", "X=5;Y=7");
LoadMockAssembly(settings);
var result = _runner.Run(TestListener.NULL, TestFilter.Empty);
CheckParameterOutput(result);
}
[Test, SetUICulture("en-US")]
public void Run_BadFile_ReturnsNonRunnableSuite()
{
_runner.Load(BAD_FILE, EMPTY_SETTINGS);
var result = _runner.Run(TestListener.NULL, TestFilter.Empty);
Assert.That(result.Test.IsSuite);
Assert.That(result.Test, Is.TypeOf<TestAssembly>());
Assert.That(result.Test.RunState, Is.EqualTo(RunState.NotRunnable));
Assert.That(result.Test.TestCaseCount, Is.EqualTo(0));
Assert.That(result.ResultState, Is.EqualTo(ResultState.NotRunnable.WithSite(FailureSite.SetUp)));
Assert.That(result.Message,
Does.StartWith("Could not load"));
}
#endregion
#region RunAsync
[Test]
public void RunAsync_AfterLoad_ReturnsRunnableSuite()
{
LoadMockAssembly();
_runner.RunAsync(TestListener.NULL, TestFilter.Empty);
_runner.WaitForCompletion(Timeout.Infinite);
Assert.NotNull(_runner.Result, "No result returned");
Assert.That(_runner.Result.Test.IsSuite);
Assert.That(_runner.Result.Test, Is.TypeOf<TestAssembly>());
Assert.That(_runner.Result.Test.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(_runner.Result.Test.TestCaseCount, Is.EqualTo(MockAssembly.Tests));
Assert.That(_runner.Result.ResultState, Is.EqualTo(ResultState.ChildFailure));
Assert.That(_runner.Result.PassCount, Is.EqualTo(MockAssembly.Passed));
Assert.That(_runner.Result.FailCount, Is.EqualTo(MockAssembly.Failed));
Assert.That(_runner.Result.SkipCount, Is.EqualTo(MockAssembly.Skipped));
Assert.That(_runner.Result.InconclusiveCount, Is.EqualTo(MockAssembly.Inconclusive));
}
[Test]
public void RunAsync_AfterLoad_SendsExpectedEvents()
{
LoadMockAssembly();
_runner.RunAsync(this, TestFilter.Empty);
_runner.WaitForCompletion(Timeout.Infinite);
Assert.That(_testStartedCount, Is.EqualTo(MockAssembly.Tests - IgnoredFixture.Tests - BadFixture.Tests - ExplicitFixture.Tests));
Assert.That(_testFinishedCount, Is.EqualTo(MockAssembly.Tests));
Assert.That(_successCount, Is.EqualTo(MockAssembly.Passed));
Assert.That(_failCount, Is.EqualTo(MockAssembly.Failed));
Assert.That(_skipCount, Is.EqualTo(MockAssembly.Skipped));
Assert.That(_inconclusiveCount, Is.EqualTo(MockAssembly.Inconclusive));
}
[Test]
public void RunAsync_WithoutLoad_ReturnsError()
{
var ex = Assert.Throws<InvalidOperationException>(
() => _runner.RunAsync(TestListener.NULL, TestFilter.Empty));
Assert.That(ex.Message, Is.EqualTo("The Run method was called but no test has been loaded"));
}
[Test, SetUICulture("en-US")]
public void RunAsync_FileNotFound_ReturnsNonRunnableSuite()
{
_runner.Load(MISSING_FILE, EMPTY_SETTINGS);
_runner.RunAsync(TestListener.NULL, TestFilter.Empty);
_runner.WaitForCompletion(Timeout.Infinite);
Assert.NotNull(_runner.Result, "No result returned");
Assert.That(_runner.Result.Test.IsSuite);
Assert.That(_runner.Result.Test, Is.TypeOf<TestAssembly>());
Assert.That(_runner.Result.Test.RunState, Is.EqualTo(RunState.NotRunnable));
Assert.That(_runner.Result.Test.TestCaseCount, Is.EqualTo(0));
Assert.That(_runner.Result.ResultState, Is.EqualTo(ResultState.NotRunnable.WithSite(FailureSite.SetUp)));
Assert.That(_runner.Result.Message,
Does.StartWith(COULD_NOT_LOAD_MSG));
}
[Test, SetUICulture("en-US")]
public void RunAsync_BadFile_ReturnsNonRunnableSuite()
{
_runner.Load(BAD_FILE, EMPTY_SETTINGS);
_runner.RunAsync(TestListener.NULL, TestFilter.Empty);
_runner.WaitForCompletion(Timeout.Infinite);
Assert.NotNull(_runner.Result, "No result returned");
Assert.That(_runner.Result.Test.IsSuite);
Assert.That(_runner.Result.Test, Is.TypeOf<TestAssembly>());
Assert.That(_runner.Result.Test.RunState, Is.EqualTo(RunState.NotRunnable));
Assert.That(_runner.Result.Test.TestCaseCount, Is.EqualTo(0));
Assert.That(_runner.Result.ResultState, Is.EqualTo(ResultState.NotRunnable.WithSite(FailureSite.SetUp)));
Assert.That(_runner.Result.Message,
Does.StartWith("Could not load"));
}
#endregion
#region StopRun
[Test]
public void StopRun_WhenNoTestIsRunning_Succeeds()
{
_runner.StopRun(false);
}
[Test]
public void StopRun_WhenTestIsRunning_StopsTest()
{
var tests = LoadSlowTests();
var count = tests.TestCaseCount;
_runner.RunAsync(TestListener.NULL, TestFilter.Empty);
_runner.StopRun(false);
_runner.WaitForCompletion(Timeout.Infinite);
Assert.True(_runner.IsTestComplete, "Test is not complete");
if (_runner.Result.ResultState != ResultState.Success) // Test may have finished before we stopped it
{
Assert.That(_runner.Result.ResultState, Is.EqualTo(ResultState.Cancelled));
Assert.That(_runner.Result.PassCount, Is.LessThan(count));
}
}
#endregion
#region Cancel Run
[Test]
public void CancelRun_WhenNoTestIsRunning_Succeeds()
{
_runner.StopRun(true);
}
[Test]
public void CancelRun_WhenTestIsRunning_StopsTest()
{
var tests = LoadSlowTests();
var count = tests.TestCaseCount;
_runner.RunAsync(TestListener.NULL, TestFilter.Empty);
_runner.StopRun(true);
// When cancelling, the completion event may not be signalled,
// so we only wait a short time before checking.
_runner.WaitForCompletion(Timeout.Infinite);
Assert.True(_runner.IsTestComplete, "Test is not complete");
if (_runner.Result.ResultState != ResultState.Success)
{
Assert.That(_runner.Result.ResultState, Is.EqualTo(ResultState.Cancelled));
Assert.That(_runner.Result.PassCount, Is.LessThan(count));
}
}
#endregion
#region ITestListener Implementation
void ITestListener.TestStarted(ITest test)
{
if (!test.IsSuite)
_testStartedCount++;
}
void ITestListener.TestFinished(ITestResult result)
{
if (!result.Test.IsSuite)
{
_testFinishedCount++;
switch (result.ResultState.Status)
{
case TestStatus.Passed:
_successCount++;
break;
case TestStatus.Failed:
_failCount++;
break;
case TestStatus.Skipped:
_skipCount++;
break;
case TestStatus.Inconclusive:
_inconclusiveCount++;
break;
}
}
}
/// <summary>
/// Called when a test produces output for immediate display
/// </summary>
/// <param name="output">A TestOutput object containing the text to display</param>
public void TestOutput(TestOutput output)
{
_testOutputCount++;
}
/// <summary>
/// Called when a test produces message to be sent to listeners
/// </summary>
/// <param name="message">A TestMessage object containing the text to send</param>
public void SendMessage(TestMessage message)
{
}
#endregion
#region Helper Methods
private ITest LoadMockAssembly()
{
return LoadMockAssembly(EMPTY_SETTINGS);
}
private ITest LoadMockAssembly(IDictionary<string, object> settings)
{
return _runner.Load(
Path.Combine(TestContext.CurrentContext.TestDirectory, MOCK_ASSEMBLY_FILE),
settings);
}
private ITest LoadSlowTests()
{
return _runner.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, SLOW_TESTS_FILE), EMPTY_SETTINGS);
}
private void CheckParameterOutput(ITestResult result)
{
var childResult = TestFinder.Find(
"DisplayRunParameters", result, true);
Assert.That(childResult.Output, Is.EqualTo(
"Parameter X = 5" + Environment.NewLine +
"Parameter Y = 7" + Environment.NewLine));
}
#endregion
}
}
| |
//
// GtkExtensions.cs
//
// Author:
// Vsevolod Kukol <[email protected]>
//
// Copyright (c) 2014 Vsevolod Kukol
//
// 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 Gdk;
namespace Xwt.GtkBackend
{
public static class Gtk2Extensions
{
public static void SetHasWindow (this Gtk.Widget widget, bool value)
{
if (value)
widget.WidgetFlags &= ~Gtk.WidgetFlags.NoWindow;
else
widget.WidgetFlags |= Gtk.WidgetFlags.NoWindow;
}
public static bool GetHasWindow (this Gtk.Widget widget)
{
return !widget.IsNoWindow;
}
public static void SetAppPaintable (this Gtk.Widget widget, bool value)
{
if (value)
widget.WidgetFlags |= Gtk.WidgetFlags.AppPaintable;
else
widget.WidgetFlags &= ~Gtk.WidgetFlags.AppPaintable;
}
public static void SetStateActive(this Gtk.Widget widget)
{
widget.State = Gtk.StateType.Active;
}
public static void SetStateNormal(this Gtk.Widget widget)
{
widget.State = Gtk.StateType.Normal;
}
public static void AddSignalHandler (this Gtk.Widget widget, string name, Delegate handler, Type args_type)
{
var signal = GLib.Signal.Lookup (widget, name, args_type);
signal.AddDelegate (handler);
}
public static void RemoveSignalHandler (this Gtk.Widget widget, string name, Delegate handler)
{
var signal = GLib.Signal.Lookup (widget, name);
signal.RemoveDelegate (handler);
}
public static Gdk.Pixbuf ToPixbuf (this Gdk.Window window, int src_x, int src_y, int width, int height)
{
return Gdk.Pixbuf.FromDrawable (window, Gdk.Colormap.System, src_x, src_y, 0, 0, width, height);
}
public static Gtk.CellRenderer[] GetCellRenderers (this Gtk.TreeViewColumn column)
{
return column.CellRenderers;
}
public static Gdk.DragAction GetSelectedAction (this Gdk.DragContext context)
{
return context.Action;
}
public static Gdk.Atom[] ListTargets (this Gdk.DragContext context)
{
return context.Targets;
}
public static void AddContent (this Gtk.Dialog dialog, Gtk.Widget widget, bool expand = true, bool fill = true, uint padding = 0)
{
dialog.VBox.PackStart (widget, expand, fill, padding);
}
public static void AddContent (this Gtk.MessageDialog dialog, Gtk.Widget widget, bool expand = true, bool fill = true, uint padding = 0)
{
var messageArea = dialog.GetMessageArea () ?? dialog.VBox;
messageArea.PackStart (widget, expand, fill, padding);
}
public static void SetContentSpacing (this Gtk.Dialog dialog, int spacing)
{
dialog.VBox.Spacing = spacing;
}
public static void SetTextColumn (this Gtk.ComboBox comboBox, int column)
{
((Gtk.ComboBoxEntry)comboBox).TextColumn = column;
}
public static void FixContainerLeak (this Gtk.Container c)
{
GtkWorkarounds.FixContainerLeak (c);
}
public static Xwt.Drawing.Color GetBackgroundColor (this Gtk.Widget widget)
{
return widget.GetBackgroundColor (Gtk.StateType.Normal);
}
public static Xwt.Drawing.Color GetBackgroundColor (this Gtk.Widget widget, Gtk.StateType state)
{
return widget.Style.Background (state).ToXwtValue ();
}
public static void SetBackgroundColor (this Gtk.Widget widget, Xwt.Drawing.Color color)
{
widget.SetBackgroundColor (Gtk.StateType.Normal, color);
}
public static void SetBackgroundColor (this Gtk.Widget widget, Gtk.StateType state, Xwt.Drawing.Color color)
{
widget.ModifyBg (state, color.ToGtkValue ());
}
public static void SetChildBackgroundColor (this Gtk.Container container, Xwt.Drawing.Color color)
{
foreach (var widget in container.Children)
widget.ModifyBg (Gtk.StateType.Normal, color.ToGtkValue ());
}
public static void RenderPlaceholderText (this Gtk.Entry entry, Gtk.ExposeEventArgs args, string placeHolderText, ref Pango.Layout layout)
{
// The Entry's GdkWindow is the top level window onto which
// the frame is drawn; the actual text entry is drawn into a
// separate window, so we can ensure that for themes that don't
// respect HasFrame, we never ever allow the base frame drawing
// to happen
if (args.Event.Window == entry.GdkWindow)
return;
if (entry.Text.Length > 0)
return;
RenderPlaceholderText_internal (entry, args, placeHolderText, ref layout, entry.Xalign, 0.5f, 1, 0);
}
static void RenderPlaceholderText_internal (Gtk.Widget widget, Gtk.ExposeEventArgs args, string placeHolderText, ref Pango.Layout layout, float xalign, float yalign, int xpad, int ypad)
{
if (layout == null) {
layout = new Pango.Layout (widget.PangoContext);
layout.FontDescription = widget.PangoContext.FontDescription.Copy ();
}
int wh, ww;
args.Event.Window.GetSize (out ww, out wh);
int width, height;
layout.SetText (placeHolderText);
layout.GetPixelSize (out width, out height);
int x = xpad + (int)((ww - width) * xalign);
int y = ypad + (int)((wh - height) * yalign);
using (var gc = new Gdk.GC (args.Event.Window)) {
gc.Copy (widget.Style.TextGC (Gtk.StateType.Normal));
Xwt.Drawing.Color color_a = widget.Style.Base (Gtk.StateType.Normal).ToXwtValue ();
Xwt.Drawing.Color color_b = widget.Style.Text (Gtk.StateType.Normal).ToXwtValue ();
gc.RgbFgColor = color_b.BlendWith (color_a, 0.5).ToGtkValue ();
args.Event.Window.DrawLayout (gc, x, y, layout);
}
}
public static double GetSliderPosition (this Gtk.Scale scale)
{
Gtk.Orientation orientation;
if (scale is Gtk.HScale)
orientation = Gtk.Orientation.Horizontal;
else if (scale is Gtk.VScale)
orientation = Gtk.Orientation.Vertical;
else
throw new InvalidOperationException ("Can not obtain slider position from " + scale.GetType ());
var padding = (int)scale.StyleGetProperty ("focus-padding");
var slwidth = Convert.ToDouble (scale.StyleGetProperty ("slider-width"));
int orientationSize;
if (orientation == Gtk.Orientation.Horizontal)
orientationSize = scale.Allocation.Width - (2 * padding);
else
orientationSize = scale.Allocation.Height - (2 * padding);
double prct = 0;
if (scale.Adjustment.Lower >= 0) {
prct = (scale.Value / (scale.Adjustment.Upper - scale.Adjustment.Lower));
} else if (scale.Adjustment.Upper <= 0) {
prct = (Math.Abs (scale.Value) / Math.Abs (scale.Adjustment.Lower - scale.Adjustment.Upper));
} else if (scale.Adjustment.Lower < 0) {
if (scale.Value >= 0)
prct = 0.5 + ((scale.Value / 2) / scale.Adjustment.Upper);
else
prct = 0.5 - Math.Abs ((scale.Value / 2) / scale.Adjustment.Lower);
}
if (orientation == Gtk.Orientation.Vertical || scale.Inverted)
prct = 1 - prct;
return (int)(((orientationSize - (slwidth)) * prct) + (slwidth / 2));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Pipes.Tests
{
/// <summary>
/// The Specific NamedPipe tests cover edge cases or otherwise narrow cases that
/// show up within particular server/client directional combinations.
/// </summary>
public class NamedPipeTest_Specific : NamedPipeTestBase
{
[Fact]
public void InvalidConnectTimeout_Throws_ArgumentOutOfRangeException()
{
using (NamedPipeClientStream client = new NamedPipeClientStream("client1"))
{
Assert.Throws<ArgumentOutOfRangeException>("timeout", () => client.Connect(-111));
Assert.Throws<ArgumentOutOfRangeException>("timeout", () => { client.ConnectAsync(-111); });
}
}
[Fact]
public async Task ConnectToNonExistentServer_Throws_TimeoutException()
{
using (NamedPipeClientStream client = new NamedPipeClientStream(".", "notthere"))
{
var ctx = new CancellationTokenSource();
Assert.Throws<TimeoutException>(() => client.Connect(60)); // 60 to be over internal 50 interval
await Assert.ThrowsAsync<TimeoutException>(() => client.ConnectAsync(50));
await Assert.ThrowsAsync<TimeoutException>(() => client.ConnectAsync(60, ctx.Token)); // testing Token overload; ctx is not canceled in this test
}
}
[Fact]
public async Task CancelConnectToNonExistentServer_Throws_OperationCanceledException()
{
using (NamedPipeClientStream client = new NamedPipeClientStream(".", "notthere"))
{
var ctx = new CancellationTokenSource();
Task clientConnectToken = client.ConnectAsync(ctx.Token);
ctx.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => clientConnectToken);
ctx.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => client.ConnectAsync(ctx.Token));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Unix implementation uses bidirectional sockets
public void ConnectWithConflictingDirections_Throws_UnauthorizedAccessException()
{
string serverName1 = GetUniquePipeName();
using (NamedPipeServerStream server = new NamedPipeServerStream(serverName1, PipeDirection.Out))
using (NamedPipeClientStream client = new NamedPipeClientStream(".", serverName1, PipeDirection.Out))
{
Assert.Throws<UnauthorizedAccessException>(() => client.Connect());
Assert.False(client.IsConnected);
}
string serverName2 = GetUniquePipeName();
using (NamedPipeServerStream server = new NamedPipeServerStream(serverName2, PipeDirection.In))
using (NamedPipeClientStream client = new NamedPipeClientStream(".", serverName2, PipeDirection.In))
{
Assert.Throws<UnauthorizedAccessException>(() => client.Connect());
Assert.False(client.IsConnected);
}
}
[Theory]
[InlineData(PipeOptions.None)]
[InlineData(PipeOptions.Asynchronous)]
[PlatformSpecific(TestPlatforms.Windows)] // Unix currently doesn't support message mode
public async Task Windows_MessagePipeTransissionMode(PipeOptions serverOptions)
{
byte[] msg1 = new byte[] { 5, 7, 9, 10 };
byte[] msg2 = new byte[] { 2, 4 };
byte[] received1 = new byte[] { 0, 0, 0, 0 };
byte[] received2 = new byte[] { 0, 0 };
byte[] received3 = new byte[] { 0, 0, 0, 0 };
byte[] received4 = new byte[] { 0, 0, 0, 0 };
byte[] received5 = new byte[] { 0, 0 };
byte[] received6 = new byte[] { 0, 0, 0, 0 };
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Message, serverOptions))
{
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation))
{
server.ReadMode = PipeTransmissionMode.Message;
Assert.Equal(PipeTransmissionMode.Message, server.ReadMode);
Task clientTask = Task.Run(() =>
{
client.Connect();
client.Write(msg1, 0, msg1.Length);
client.Write(msg2, 0, msg2.Length);
client.Write(msg1, 0, msg1.Length);
client.Write(msg1, 0, msg1.Length);
client.Write(msg2, 0, msg2.Length);
client.Write(msg1, 0, msg1.Length);
int serverCount = client.NumberOfServerInstances;
Assert.Equal(1, serverCount);
});
server.WaitForConnection();
int len1 = server.Read(received1, 0, msg1.Length);
Assert.True(server.IsMessageComplete);
Assert.Equal(msg1.Length, len1);
Assert.Equal(msg1, received1);
int len2 = server.Read(received2, 0, msg2.Length);
Assert.True(server.IsMessageComplete);
Assert.Equal(msg2.Length, len2);
Assert.Equal(msg2, received2);
int expectedRead = msg1.Length - 1;
int len3 = server.Read(received3, 0, expectedRead); // read one less than message
Assert.False(server.IsMessageComplete);
Assert.Equal(expectedRead, len3);
for (int i = 0; i < expectedRead; ++i)
{
Assert.Equal(msg1[i], received3[i]);
}
expectedRead = msg1.Length - expectedRead;
Assert.Equal(expectedRead, server.Read(received3, len3, expectedRead));
Assert.True(server.IsMessageComplete);
Assert.Equal(msg1, received3);
Assert.Equal(msg1.Length, await server.ReadAsync(received4, 0, msg1.Length));
Assert.True(server.IsMessageComplete);
Assert.Equal(msg1, received4);
Assert.Equal(msg2.Length, await server.ReadAsync(received5, 0, msg2.Length));
Assert.True(server.IsMessageComplete);
Assert.Equal(msg2, received5);
expectedRead = msg1.Length - 1;
Assert.Equal(expectedRead, await server.ReadAsync(received6, 0, expectedRead)); // read one less than message
Assert.False(server.IsMessageComplete);
for (int i = 0; i < expectedRead; ++i)
{
Assert.Equal(msg1[i], received6[i]);
}
expectedRead = msg1.Length - expectedRead;
Assert.Equal(expectedRead, await server.ReadAsync(received6, msg1.Length - expectedRead, expectedRead));
Assert.True(server.IsMessageComplete);
Assert.Equal(msg1, received6);
await clientTask;
}
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Unix doesn't support MaxNumberOfServerInstances
public async Task Windows_Get_NumberOfServerInstances_Succeed()
{
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 3))
{
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation))
{
int expectedNumberOfServerInstances;
Task serverTask = server.WaitForConnectionAsync();
client.Connect();
await serverTask;
Assert.True(Interop.TryGetNumberOfServerInstances(client.SafePipeHandle, out expectedNumberOfServerInstances), "GetNamedPipeHandleState failed");
Assert.Equal(expectedNumberOfServerInstances, client.NumberOfServerInstances);
}
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Win32 P/Invokes to verify the user name
public async Task Windows_GetImpersonationUserName_Succeed()
{
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName))
{
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation))
{
string expectedUserName;
Task serverTask = server.WaitForConnectionAsync();
client.Connect();
await serverTask;
Assert.True(Interop.TryGetImpersonationUserName(server.SafePipeHandle, out expectedUserName), "GetNamedPipeHandleState failed");
Assert.Equal(expectedUserName, server.GetImpersonationUserName());
}
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/1011
[PlatformSpecific(TestPlatforms.AnyUnix)] // Uses P/Invoke to verify the user name
public async Task Unix_GetImpersonationUserName_Succeed()
{
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation))
{
Task serverTask = server.WaitForConnectionAsync();
client.Connect();
await serverTask;
string name = server.GetImpersonationUserName();
Assert.NotNull(name);
Assert.False(string.IsNullOrWhiteSpace(name));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix currently doesn't support message mode
public void Unix_MessagePipeTransissionMode()
{
Assert.Throws<PlatformNotSupportedException>(() => new NamedPipeServerStream(GetUniquePipeName(), PipeDirection.InOut, 1, PipeTransmissionMode.Message));
}
[Theory]
[InlineData(PipeDirection.In)]
[InlineData(PipeDirection.Out)]
[InlineData(PipeDirection.InOut)]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix implementation uses bidirectional sockets
public static void Unix_BufferSizeRoundtripping(PipeDirection direction)
{
int desiredBufferSize = 0;
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
desiredBufferSize = server.OutBufferSize * 2;
}
using (var server = new NamedPipeServerStream(pipeName, direction, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize))
using (var client = new NamedPipeClientStream(".", pipeName, direction == PipeDirection.In ? PipeDirection.Out : PipeDirection.In))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
if ((direction & PipeDirection.Out) != 0)
{
Assert.InRange(server.OutBufferSize, desiredBufferSize, int.MaxValue);
}
if ((direction & PipeDirection.In) != 0)
{
Assert.InRange(server.InBufferSize, desiredBufferSize, int.MaxValue);
}
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Unix implementation uses bidirectional sockets
public static void Windows_BufferSizeRoundtripping()
{
int desiredBufferSize = 10;
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
Assert.Equal(desiredBufferSize, server.OutBufferSize);
Assert.Equal(desiredBufferSize, client.InBufferSize);
}
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
Assert.Equal(desiredBufferSize, server.InBufferSize);
Assert.Equal(0, client.OutBufferSize);
}
}
[Fact]
public void PipeTransmissionMode_Returns_Byte()
{
using (ServerClientPair pair = CreateServerClientPair())
{
Assert.Equal(PipeTransmissionMode.Byte, pair.writeablePipe.TransmissionMode);
Assert.Equal(PipeTransmissionMode.Byte, pair.readablePipe.TransmissionMode);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Unix doesn't currently support message mode
public void Windows_SetReadModeTo__PipeTransmissionModeByte()
{
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
// Throws regardless of connection status for the pipe that is set to PipeDirection.In
Assert.Throws<UnauthorizedAccessException>(() => server.ReadMode = PipeTransmissionMode.Byte);
client.ReadMode = PipeTransmissionMode.Byte;
}
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
// Throws regardless of connection status for the pipe that is set to PipeDirection.In
Assert.Throws<UnauthorizedAccessException>(() => client.ReadMode = PipeTransmissionMode.Byte);
server.ReadMode = PipeTransmissionMode.Byte;
}
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
server.ReadMode = PipeTransmissionMode.Byte;
client.ReadMode = PipeTransmissionMode.Byte;
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix doesn't currently support message mode
public void Unix_SetReadModeTo__PipeTransmissionModeByte()
{
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
server.ReadMode = PipeTransmissionMode.Byte;
client.ReadMode = PipeTransmissionMode.Byte;
}
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
client.ReadMode = PipeTransmissionMode.Byte;
server.ReadMode = PipeTransmissionMode.Byte;
}
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
server.ReadMode = PipeTransmissionMode.Byte;
client.ReadMode = PipeTransmissionMode.Byte;
}
}
[Theory]
[InlineData(PipeDirection.Out, PipeDirection.In)]
[InlineData(PipeDirection.In, PipeDirection.Out)]
public void InvalidReadMode_Throws_ArgumentOutOfRangeException(PipeDirection serverDirection, PipeDirection clientDirection)
{
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName, serverDirection, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
using (var client = new NamedPipeClientStream(".", pipeName, clientDirection))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
Assert.Throws<ArgumentOutOfRangeException>(() => server.ReadMode = (PipeTransmissionMode)999);
Assert.Throws<ArgumentOutOfRangeException>(() => client.ReadMode = (PipeTransmissionMode)999);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Checks MaxLength for PipeName on Unix
public void NameTooLong_MaxLengthPerPlatform()
{
// Increase a name's length until it fails
ArgumentOutOfRangeException e = null;
string name = Path.GetRandomFileName();
for (int i = 0; ; i++)
{
try
{
name += 'c';
using (var s = new NamedPipeServerStream(name))
using (var c = new NamedPipeClientStream(name))
{
Task t = s.WaitForConnectionAsync();
c.Connect();
t.GetAwaiter().GetResult();
}
}
catch (ArgumentOutOfRangeException exc)
{
e = exc;
break;
}
}
Assert.NotNull(e);
Assert.NotNull(e.ActualValue);
// Validate the length was expected
string path = (string)e.ActualValue;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Assert.Equal(108, path.Length);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Assert.Equal(104, path.Length);
}
else
{
Assert.InRange(path.Length, 92, int.MaxValue);
}
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Parsing.Ast;
namespace Microsoft.PythonTools.Analysis.Values {
abstract class SpecializedNamespace : AnalysisValue {
protected readonly AnalysisValue _original, _inst;
private IAnalysisSet _descriptor;
public SpecializedNamespace(AnalysisValue original) {
_original = original;
}
public SpecializedNamespace(AnalysisValue original, AnalysisValue inst) {
_original = original;
_inst = inst;
}
internal AnalysisValue Original {
get {
return _original;
}
}
public override IAnalysisSet Call(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
if (_original == null) {
return base.Call(node, unit, args, keywordArgNames);
}
return _original.Call(node, unit, args, keywordArgNames);
}
internal override void AddReference(Node node, AnalysisUnit analysisUnit) {
if (_original == null) {
base.AddReference(node, analysisUnit);
return;
}
_original.AddReference(node, analysisUnit);
}
public override void AugmentAssign(AugmentedAssignStatement node, AnalysisUnit unit, IAnalysisSet value) {
if (_original == null) {
base.AugmentAssign(node, unit, value);
return;
}
_original.AugmentAssign(node, unit, value);
}
public override IAnalysisSet BinaryOperation(Node node, AnalysisUnit unit, Parsing.PythonOperator operation, IAnalysisSet rhs) {
if (_original == null) {
return base.BinaryOperation(node, unit, operation, rhs);
}
return _original.BinaryOperation(node, unit, operation, rhs);
}
public override IPythonProjectEntry DeclaringModule {
get {
if (_original == null) {
return base.DeclaringModule;
}
return _original.DeclaringModule;
}
}
public override int DeclaringVersion {
get {
if (_original == null) {
return base.DeclaringVersion;
}
return _original.DeclaringVersion;
}
}
public override void DeleteMember(Node node, AnalysisUnit unit, string name) {
if (_original == null) {
base.DeleteMember(node, unit, name);
return;
}
_original.DeleteMember(node, unit, name);
}
public override string Description {
get {
if (_original == null) {
return base.Description;
}
return _original.Description;
}
}
public override string Documentation {
get {
if (_original == null) {
return base.Documentation;
}
return _original.Documentation;
}
}
public override IDictionary<string, IAnalysisSet> GetAllMembers(IModuleContext moduleContext) {
if (_original == null) {
return base.GetAllMembers(moduleContext);
}
return _original.GetAllMembers(moduleContext);
}
public override object GetConstantValue() {
if (_original == null) {
return base.GetConstantValue();
}
return _original.GetConstantValue();
}
public override IAnalysisSet GetDescriptor(Node node, AnalysisValue instance, AnalysisValue context, AnalysisUnit unit) {
if (_original == null) {
return base.GetDescriptor(node, instance, context, unit);
}
if (_descriptor == null) {
var res = _original.GetDescriptor(node, instance, context, unit);
// TODO: This kinda sucks...
if (Object.ReferenceEquals(res, _original)) {
_descriptor = SelfSet;
} else if (res.Count >= 1) {
// TODO: Dictionary per-instance
_descriptor = Clone(res.First(), instance);
} else {
_descriptor = Clone(_original, instance);
}
}
return _descriptor;
}
protected abstract SpecializedNamespace Clone(AnalysisValue original, AnalysisValue instance);
public override IAnalysisSet GetEnumeratorTypes(Node node, AnalysisUnit unit) {
if (_original == null) {
return base.GetEnumeratorTypes(node, unit);
}
return _original.GetEnumeratorTypes(node, unit);
}
public override IAnalysisSet GetIndex(Node node, AnalysisUnit unit, IAnalysisSet index) {
if (_original == null) {
return base.GetIndex(node, unit, index);
}
return _original.GetIndex(node, unit, index);
}
public override int? GetLength() {
if (_original == null) {
return base.GetLength();
}
return _original.GetLength();
}
public override IAnalysisSet GetMember(Node node, AnalysisUnit unit, string name) {
// Must unconditionally call the base implementation of GetMember
var ignored = base.GetMember(node, unit, name);
if (_original == null) {
return AnalysisSet.Empty;
}
return _original.GetMember(node, unit, name);
}
public override IAnalysisSet GetStaticDescriptor(AnalysisUnit unit) {
if (_original == null) {
return this;
}
var res = _original.GetStaticDescriptor(unit);
if (res == _original) {
return this;
}
// TODO: We should support wrapping these up and producing another SpecializedNamespace
return res;
}
internal override bool IsOfType(IAnalysisSet klass) {
if (_original == null) {
return false;
}
return _original.IsOfType(klass);
}
public override IEnumerable<LocationInfo> Locations {
get {
if (_original == null) {
return new LocationInfo[0];
}
return _original.Locations;
}
}
public override IEnumerable<OverloadResult> Overloads {
get {
if (_original == null) {
return new OverloadResult[0];
}
return _original.Overloads;
}
}
public override IPythonType PythonType {
get {
if (_original == null) {
return null;
}
return _original.PythonType;
}
}
internal override IEnumerable<LocationInfo> References {
get {
if (_original == null) {
return new LocationInfo[0];
}
return _original.References;
}
}
public override PythonMemberType MemberType {
get {
if (_original == null) {
return PythonMemberType.Unknown;
}
return _original.MemberType;
}
}
public override IAnalysisSet ReverseBinaryOperation(Node node, AnalysisUnit unit, Parsing.PythonOperator operation, IAnalysisSet rhs) {
if (_original == null) {
return AnalysisSet.Empty;
}
return _original.ReverseBinaryOperation(node, unit, operation, rhs);
}
public override void SetIndex(Node node, AnalysisUnit unit, IAnalysisSet index, IAnalysisSet value) {
if (_original != null) {
_original.SetIndex(node, unit, index, value);
}
}
public override void SetMember(Node node, AnalysisUnit unit, string name, IAnalysisSet value) {
if (_original != null) {
_original.SetMember(node, unit, name, value);
}
}
public override string ShortDescription {
get {
if (_original == null) {
return string.Empty;
}
return _original.ShortDescription;
}
}
internal override BuiltinTypeId TypeId {
get {
if (_original == null) {
return BuiltinTypeId.Unknown;
}
return _original.TypeId;
}
}
public override IAnalysisSet UnaryOperation(Node node, AnalysisUnit unit, Parsing.PythonOperator operation) {
if (_original == null) {
return AnalysisSet.Empty;
}
return _original.UnaryOperation(node, unit, operation);
}
}
}
| |
using System;
using System.Collections.Generic;
using Magecrawl.Actors.MonsterAI;
using Magecrawl.EngineInterfaces;
using Magecrawl.Interfaces;
using Magecrawl.Utilities;
using Magecrawl.Items;
namespace Magecrawl.Actors
{
public class Monster : Character, IMonster
{
// Share one RNG between monsters
protected static Random m_random = new Random();
private List<IMonsterTactic> m_tactics;
public SerializableDictionary<string, string> Attributes { get; set; }
protected double CTAttackCost { get; set; }
private DiceRoll m_damage;
private int m_baseVision;
private int m_level;
private string m_baseType;
public bool Intelligent { get; private set; }
public Point PlayerLastKnownPosition { get; set; }
internal Monster(string baseType, string name, int level, Point p, int maxHP, bool intelligent, int vision, DiceRoll damage, double evade,
double ctIncreaseModifer, double ctMoveCost, double ctActCost, double ctAttackCost, List<IMonsterTactic> tactics)
: base(name, p, ctIncreaseModifer, ctMoveCost, ctActCost)
{
m_baseType = baseType;
m_level = level;
CTAttackCost = ctAttackCost;
m_currentHP = maxHP;
m_maxHP = maxHP;
m_damage = damage;
PlayerLastKnownPosition = Point.Invalid;
m_evade = evade;
m_baseVision = vision;
Intelligent = intelligent;
Attributes = new SerializableDictionary<string, string>();
m_tactics = tactics;
m_tactics.ForEach(t => t.SetupAttributesNeeded(this));
}
public override int Vision
{
get
{
return m_baseVision + GetTotalAttributeValue("VisionBonus") + CoreGameEngineInstance.Instance.GetMonsterVisionBonus();
}
}
public string BaseType
{
get
{
return m_baseType;
}
}
public override IWeapon CurrentWeapon
{
get
{
return ItemFactory.Instance.CreateMeleeWeapon(this);
}
}
private int m_currentHP;
public override int CurrentHP
{
get
{
return m_currentHP;
}
}
private int m_maxHP;
public override int MaxHP
{
get
{
return m_maxHP;
}
}
// Returns amount actually healed by
public override int Heal(int toHeal, bool magical)
{
int previousHealth = CurrentHP;
m_currentHP = Math.Min(CurrentHP + toHeal, MaxHP);
return CurrentHP - previousHealth;
}
public override void Damage(int dmg)
{
m_currentHP -= dmg;
}
// Monsters don't have stamina, so treat as damage
public override void DamageJustStamina(int dmg)
{
m_currentHP -= dmg;
}
public override bool IsDead
{
get
{
return CurrentHP <= 0;
}
}
public void Action(IGameEngineCore engine)
{
bool playerIsVisible = IsPlayerVisible(engine);
if (playerIsVisible)
UpdateKnownPlayerLocation(engine);
m_tactics.ForEach(t => t.NewTurn(this));
foreach (IMonsterTactic tactic in m_tactics)
{
if (playerIsVisible || !tactic.NeedsPlayerLOS)
{
if (tactic.CouldUseTactic(engine, this))
{
if (tactic.UseTactic(engine, this))
return;
}
}
}
throw new InvalidOperationException("Made it to the end of Action of Monster");
}
public void NoticeRangedAttack(Point attackerPosition)
{
PlayerLastKnownPosition = attackerPosition;
}
protected void UpdateKnownPlayerLocation(IGameEngineCore engine)
{
PlayerLastKnownPosition = engine.Player.Position;
}
protected bool IsPlayerVisible(IGameEngineCore engine)
{
return engine.FOVManager.VisibleSingleShot(engine.Map, Position, Vision, engine.Player.Position);
}
private double m_evade;
public override double Evade
{
get
{
return m_evade;
}
}
public override DiceRoll MeleeDamage
{
get
{
return m_damage;
}
}
public override double MeleeCTCost
{
get
{
return CTAttackCost;
}
}
#region SaveLoad
public override void ReadXml(System.Xml.XmlReader reader)
{
base.ReadXml(reader);
CTAttackCost = reader.ReadElementContentAsDouble();
m_damage.ReadXml(reader);
m_currentHP = reader.ReadElementContentAsInt();
m_maxHP = reader.ReadElementContentAsInt();
PlayerLastKnownPosition.ReadXml(reader);
// HACK HACK - When collapsed monster classes into IMonsterTactics, we shouldn't need this
Attributes.Clear();
Attributes.ReadXml(reader);
}
public override void WriteXml(System.Xml.XmlWriter writer)
{
writer.WriteElementString("Type", m_baseType);
writer.WriteElementString("Level", m_level.ToString());
base.WriteXml(writer);
writer.WriteElementString("MeleeSpeed", CTAttackCost.ToString());
m_damage.WriteXml(writer);
writer.WriteElementString("CurrentHP", CurrentHP.ToString());
writer.WriteElementString("MaxHP", MaxHP.ToString());
PlayerLastKnownPosition.WriteToXml(writer, "PlayerLastKnownPosition");
Attributes.WriteXml(writer);
}
#endregion
}
}
| |
using System.Xml.Linq;
using GitVersion.Core.Tests.Helpers;
using GitVersion.Extensions;
using GitVersion.Helpers;
using GitVersion.Logging;
using GitVersion.OutputVariables;
using GitVersion.VersionCalculation;
using GitVersion.VersionConverters.AssemblyInfo;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
namespace GitVersion.Core.Tests;
[TestFixture]
[Parallelizable(ParallelScope.None)]
public class ProjectFileUpdaterTests : TestBase
{
private IVariableProvider variableProvider;
private ILog log;
private IFileSystem fileSystem;
private IProjectFileUpdater projectFileUpdater;
private List<string> logMessages;
[SetUp]
public void Setup()
{
ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute<TestCaseAttribute>();
var sp = ConfigureServices();
this.logMessages = new List<string>();
this.log = new Log(new TestLogAppender(this.logMessages.Add));
this.fileSystem = sp.GetRequiredService<IFileSystem>();
this.variableProvider = sp.GetRequiredService<IVariableProvider>();
this.projectFileUpdater = new ProjectFileUpdater(this.log, this.fileSystem);
}
[Category(NoMono)]
[Description(NoMonoDescription)]
[TestCase("Microsoft.NET.Sdk")]
[TestCase("Microsoft.NET.Sdk.Worker")]
[TestCase("Microsoft.NET.Sdk.Web")]
[TestCase("Microsoft.NET.Sdk.WindowsDesktop")]
[TestCase("Microsoft.NET.Sdk.Razor")]
[TestCase("Microsoft.NET.Sdk.BlazorWebAssembly")]
public void CanUpdateProjectFileWithSdkProjectFileXml(string sdk)
{
var xml = $@"
<Project Sdk=""{sdk}"">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
</Project>
";
var canUpdate = projectFileUpdater.CanUpdateProjectFile(XElement.Parse(xml));
canUpdate.ShouldBe(true);
logMessages.ShouldBeEmpty();
}
[TestCase(@"
<Project Sdk=""SomeOtherProject.Sdk"">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
</Project>
")]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void CannotUpdateProjectFileWithIncorrectProjectSdk(string xml)
{
var canUpdate = projectFileUpdater.CanUpdateProjectFile(XElement.Parse(xml));
canUpdate.ShouldBe(false);
logMessages.ShouldNotBeEmpty();
logMessages.Count.ShouldBe(1);
logMessages.First().ShouldContain("Specified project file Sdk (SomeOtherProject.Sdk) is not supported, please ensure the project sdk starts with 'Microsoft.NET.Sdk'");
}
[TestCase(@"
<Project>
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
</Project>
")]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void CannotUpdateProjectFileWithMissingProjectSdk(string xml)
{
var canUpdate = projectFileUpdater.CanUpdateProjectFile(XElement.Parse(xml));
canUpdate.ShouldBe(false);
logMessages.ShouldNotBeEmpty();
logMessages.Count.ShouldBe(1);
logMessages.First().ShouldContain("Specified project file Sdk () is not supported, please ensure the project sdk starts with 'Microsoft.NET.Sdk'");
}
[TestCase(@"
<Project Sdk=""Microsoft.NET.Sdk"">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
</Project>
")]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void CannotUpdateProjectFileWithoutAssemblyInfoGeneration(string xml)
{
var canUpdate = projectFileUpdater.CanUpdateProjectFile(XElement.Parse(xml));
canUpdate.ShouldBe(false);
logMessages.ShouldNotBeEmpty();
logMessages.Count.ShouldBe(1);
logMessages.First().ShouldContain("Project file specifies <GenerateAssemblyInfo>false</GenerateAssemblyInfo>: versions set in this project file will not affect the output artifacts");
}
[TestCase(@"
<Project Sdk=""Microsoft.NET.Sdk"">
</Project>
")]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void CannotUpdateProjectFileWithoutAPropertyGroup(string xml)
{
var canUpdate = projectFileUpdater.CanUpdateProjectFile(XElement.Parse(xml));
canUpdate.ShouldBe(false);
logMessages.ShouldNotBeEmpty();
logMessages.Count.ShouldBe(1);
logMessages.First().ShouldContain("Unable to locate any <PropertyGroup> elements in specified project file. Are you sure it is in a correct format?");
}
[TestCase(@"
<Project Sdk=""Microsoft.NET.Sdk"">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
</Project>"
)]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void UpdateProjectXmlVersionElementWithStandardXmlInsertsElement(string xml)
{
var variables = this.variableProvider.GetVariablesFor(SemanticVersion.Parse("2.0.0", "v"), new TestEffectiveConfiguration(), false);
var xmlRoot = XElement.Parse(xml);
variables.AssemblySemVer.ShouldNotBeNull();
ProjectFileUpdater.UpdateProjectVersionElement(xmlRoot, ProjectFileUpdater.AssemblyVersionElement, variables.AssemblySemVer);
var expectedXml = XElement.Parse(@"
<Project Sdk=""Microsoft.NET.Sdk"">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
</PropertyGroup>
</Project>");
xmlRoot.ToString().ShouldBe(expectedXml.ToString());
}
[TestCase(@"
<Project Sdk=""Microsoft.NET.Sdk"">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
</PropertyGroup>
</Project>"
)]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void UpdateProjectXmlVersionElementWithStandardXmlModifiesElement(string xml)
{
var variables = this.variableProvider.GetVariablesFor(SemanticVersion.Parse("2.0.0", "v"), new TestEffectiveConfiguration(), false);
var xmlRoot = XElement.Parse(xml);
variables.AssemblySemVer.ShouldNotBeNull();
ProjectFileUpdater.UpdateProjectVersionElement(xmlRoot, ProjectFileUpdater.AssemblyVersionElement, variables.AssemblySemVer);
var expectedXml = XElement.Parse(@"
<Project Sdk=""Microsoft.NET.Sdk"">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
</PropertyGroup>
</Project>");
xmlRoot.ToString().ShouldBe(expectedXml.ToString());
}
[TestCase(@"
<Project Sdk=""Microsoft.NET.Sdk"">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
</PropertyGroup>
<PropertyGroup>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
</PropertyGroup>
</Project>"
)]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void UpdateProjectXmlVersionElementWithDuplicatePropertyGroupsModifiesLastElement(string xml)
{
var variables = this.variableProvider.GetVariablesFor(SemanticVersion.Parse("2.0.0", "v"), new TestEffectiveConfiguration(), false);
var xmlRoot = XElement.Parse(xml);
variables.AssemblySemVer.ShouldNotBeNull();
ProjectFileUpdater.UpdateProjectVersionElement(xmlRoot, ProjectFileUpdater.AssemblyVersionElement, variables.AssemblySemVer);
var expectedXml = XElement.Parse(@"
<Project Sdk=""Microsoft.NET.Sdk"">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
</PropertyGroup>
<PropertyGroup>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
</PropertyGroup>
</Project>");
xmlRoot.ToString().ShouldBe(expectedXml.ToString());
}
[TestCase(@"
<Project Sdk=""Microsoft.NET.Sdk"">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
</PropertyGroup>
</Project>"
)]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void UpdateProjectXmlVersionElementWithMultipleVersionElementsLastOneIsModified(string xml)
{
var variables = this.variableProvider.GetVariablesFor(SemanticVersion.Parse("2.0.0", "v"), new TestEffectiveConfiguration(), false);
var xmlRoot = XElement.Parse(xml);
variables.AssemblySemVer.ShouldNotBeNull();
ProjectFileUpdater.UpdateProjectVersionElement(xmlRoot, ProjectFileUpdater.AssemblyVersionElement, variables.AssemblySemVer);
var expectedXml = XElement.Parse(@"
<Project Sdk=""Microsoft.NET.Sdk"">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
</PropertyGroup>
</Project>");
xmlRoot.ToString().ShouldBe(expectedXml.ToString());
}
[TestCase(@"
<Project Sdk=""Microsoft.NET.Sdk"">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
</Project>")]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void UpdateProjectFileAddsVersionToFile(string xml)
{
var fileName = PathHelper.Combine(Path.GetTempPath(), "TestProject.csproj");
VerifyAssemblyInfoFile(xml, fileName, AssemblyVersioningScheme.MajorMinorPatch, (fs, variables) =>
{
using var projFileUpdater = new ProjectFileUpdater(this.log, fs);
projFileUpdater.Execute(variables, new AssemblyInfoContext(Path.GetTempPath(), false, fileName));
const string expectedXml = @"
<Project Sdk=""Microsoft.NET.Sdk"">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AssemblyVersion>2.3.1.0</AssemblyVersion>
<FileVersion>2.3.1.0</FileVersion>
<InformationalVersion>2.3.1+3.Branch.foo.Sha.hash</InformationalVersion>
<Version>2.3.1</Version>
</PropertyGroup>
</Project>";
var transformedXml = fs.ReadAllText(fileName);
transformedXml.ShouldBe(XElement.Parse(expectedXml).ToString());
});
}
private void VerifyAssemblyInfoFile(
string projectFileContent,
string fileName,
AssemblyVersioningScheme versioningScheme = AssemblyVersioningScheme.MajorMinorPatch,
Action<IFileSystem, VersionVariables>? verify = null)
{
this.fileSystem = Substitute.For<IFileSystem>();
var version = new SemanticVersion
{
BuildMetaData = new SemanticVersionBuildMetaData("versionSourceHash", 3, "foo", "hash", "shortHash", DateTimeOffset.Now, 0),
Major = 2,
Minor = 3,
Patch = 1
};
this.fileSystem.Exists(fileName).Returns(true);
this.fileSystem.ReadAllText(fileName).Returns(projectFileContent);
this.fileSystem.When(f => f.WriteAllText(fileName, Arg.Any<string>())).Do(c =>
{
projectFileContent = c.ArgAt<string>(1);
this.fileSystem.ReadAllText(fileName).Returns(projectFileContent);
});
var config = new TestEffectiveConfiguration(versioningScheme);
var variables = this.variableProvider.GetVariablesFor(version, config, false);
verify?.Invoke(this.fileSystem, variables);
}
}
| |
namespace Nancy.Tests.Unit.ModelBinding
{
using System;
using FakeItEasy;
using Nancy.ModelBinding;
using Xunit;
public class DynamicModelBinderAdapterFixture
{
[Fact]
public void Should_throw_if_locator_is_null()
{
// Given, When
var result = Record.Exception(() => new DynamicModelBinderAdapter(null, new NancyContext(), null, A.Dummy<BindingConfig>()));
// Then
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_throw_if_context_is_null()
{
// Given, When
var result = Record.Exception(() => new DynamicModelBinderAdapter(A.Fake<IModelBinderLocator>(), null, null, A.Dummy<BindingConfig>()));
// Then
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_throw_if_configuration_is_null()
{
// Given, When
var result = Record.Exception(() => new DynamicModelBinderAdapter(A.Fake<IModelBinderLocator>(), A.Dummy<NancyContext>(), null, null));
// Then
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_pass_type_to_locator_when_cast_implicitly()
{
// Given
var fakeModelBinder = A.Fake<IModelBinder>();
var returnModel = new Model();
A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);
var fakeLocator = A.Fake<IModelBinderLocator>();
A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(fakeModelBinder);
dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, new NancyContext(), null, A.Dummy<BindingConfig>());
// When
Model result = adapter;
// Then
A.CallTo(() => fakeLocator.GetBinderForType(typeof(Model), A<NancyContext>.Ignored)).MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_invoke_binder_with_context()
{
// Given
var context = new NancyContext();
var fakeModelBinder = A.Fake<IModelBinder>();
var returnModel = new Model();
A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);
var fakeLocator = A.Fake<IModelBinderLocator>();
A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, context)).Returns(fakeModelBinder);
dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, context, null, A.Dummy<BindingConfig>());
// When
Model result = adapter;
// Then
A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, context)).MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_pass_type_to_locator_when_cast_explicitly()
{
// Given
var fakeModelBinder = A.Fake<IModelBinder>();
var returnModel = new Model();
A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);
var fakeLocator = A.Fake<IModelBinderLocator>();
A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(fakeModelBinder);
dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, new NancyContext(), null, A.Dummy<BindingConfig>());
// When
var result = (Model)adapter;
// Then
A.CallTo(() => fakeLocator.GetBinderForType(typeof(Model), A<NancyContext>.Ignored)).MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_return_object_from_binder_if_binder_doesnt_return_null()
{
// Given
var fakeModelBinder = A.Fake<IModelBinder>();
var returnModel = new Model();
A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);
var fakeLocator = A.Fake<IModelBinderLocator>();
A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(fakeModelBinder);
dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, new NancyContext(), null, A.Dummy<BindingConfig>());
// When
Model result = adapter;
// Then
result.ShouldNotBeNull();
result.ShouldBeSameAs(returnModel);
}
[Fact]
public void Should_throw_if_locator_does_not_return_binder()
{
// Given
var fakeLocator = A.Fake<IModelBinderLocator>();
A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(null);
dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, new NancyContext(), null, A.Dummy<BindingConfig>());
// When
var result = Record.Exception(() => (Model)adapter);
// Then
result.ShouldBeOfType(typeof(ModelBindingException));
}
[Fact]
public void Should_pass_context_to_binder()
{
// Given
var context = new NancyContext();
var fakeModelBinder = A.Fake<IModelBinder>();
var returnModel = new Model();
A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);
var fakeLocator = A.Fake<IModelBinderLocator>();
A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(fakeModelBinder);
dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, context , null, A.Dummy<BindingConfig>());
// When
Model result = adapter;
// Then
A.CallTo(() => fakeModelBinder.Bind(context, A<Type>._, A<object>._, A<BindingConfig>._, A<string[]>._)).MustHaveHappened();
}
[Fact]
public void Should_pass_type_to_binder()
{
// Given
var context = new NancyContext();
var fakeModelBinder = A.Fake<IModelBinder>();
var returnModel = new Model();
A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);
var fakeLocator = A.Fake<IModelBinderLocator>();
A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(fakeModelBinder);
dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, context, null, A.Dummy<BindingConfig>());
// When
Model result = adapter;
// Then
A.CallTo(() => fakeModelBinder.Bind(A<NancyContext>._, typeof(Model), A<object>._, A<BindingConfig>._, A<string[]>._)).MustHaveHappened();
}
[Fact]
public void Should_pass_instance_to_binder()
{
// Given
var context = new NancyContext();
var instance = new Model();
var fakeModelBinder = A.Fake<IModelBinder>();
var returnModel = new Model();
A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);
var fakeLocator = A.Fake<IModelBinderLocator>();
A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(fakeModelBinder);
dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, context, instance, A.Dummy<BindingConfig>());
// When
Model result = adapter;
// Then
A.CallTo(() => fakeModelBinder.Bind(A<NancyContext>._, A<Type>._, instance, A<BindingConfig>._, A<string[]>._)).MustHaveHappened();
}
[Fact]
public void Should_pass_binding_configuration_to_binder()
{
// Given
var context = new NancyContext();
var instance = new Model();
var config = BindingConfig.Default;
var blacklist = new[] {"foo", "bar"};
var fakeModelBinder = A.Fake<IModelBinder>();
var returnModel = new Model();
A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);
var fakeLocator = A.Fake<IModelBinderLocator>();
A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(fakeModelBinder);
dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, context, instance, config, blacklist);
// When
Model result = adapter;
// Then
A.CallTo(() => fakeModelBinder.Bind(A<NancyContext>._, A<Type>._, A<object>._, A<BindingConfig>._, blacklist)).MustHaveHappened();
}
[Fact]
public void Should_pass_blacklist_to_binder()
{
// Given
var context = new NancyContext();
var instance = new Model();
var config = BindingConfig.Default;
var fakeModelBinder = A.Fake<IModelBinder>();
var returnModel = new Model();
A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);
var fakeLocator = A.Fake<IModelBinderLocator>();
A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(fakeModelBinder);
dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, context, instance, config);
// When
Model result = adapter;
// Then
A.CallTo(() => fakeModelBinder.Bind(A<NancyContext>._, A<Type>._, A<object>._, config, A<string[]>._)).MustHaveHappened();
}
}
public class Model
{
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Globalization;
using UnityEngine;
using UnityEditor.Experimental.AssetImporters;
namespace UnityEditor.Experimental.VFX.Utility
{
[ScriptedImporter(1, "pcache")]
public class PointCacheImporter : ScriptedImporter
{
public static T[] SubArray<T>(T[] data, int index, int length)
{
T[] result = new T[length];
Array.Copy(data, index, result, 0, length);
return result;
}
class InProperty
{
public string PropertyType;
public string Name;
public int Index;
public OutProperty OutProperty;
public InProperty(string propertyType, string name, int index, OutProperty outProperty)
{
PropertyType = propertyType;
Name = name;
Index = index;
OutProperty = outProperty;
}
}
class OutProperty
{
public string PropertyType;
public string Name;
public int Size;
public OutProperty(string propertyType, string name, int size)
{
PropertyType = propertyType;
Name = name;
Size = size;
}
}
public static void GetHeader(Stream s, out long byteLength, out List<string> lines)
{
byteLength = 0;
bool found_end_header = false;
lines = new List<string>();
s.Seek(0, SeekOrigin.Begin);
BinaryReader sr = new BinaryReader(s);
do
{
StringBuilder sb = new StringBuilder();
bool newline = false;
do
{
char c = sr.ReadChar();
byteLength++;
if ((c == '\n' || c == '\r') && sb.Length > 0) newline = true;
else sb.Append(c);
}
while (!newline);
string line = sb.ToString();
lines.Add(line);
if (line == "end_header") found_end_header = true;
}
while (!found_end_header);
}
public override void OnImportAsset(AssetImportContext ctx)
{
try
{
PCache pcache = PCache.FromFile(ctx.assetPath);
PointCacheAsset cache = ScriptableObject.CreateInstance<PointCacheAsset>();
cache.name = "PointCache";
ctx.AddObjectToAsset("PointCache", cache);
ctx.SetMainObject(cache);
List<InProperty> inProperties = new List<InProperty>();
Dictionary<string, OutProperty> outProperties = new Dictionary<string, OutProperty>();
Dictionary<OutProperty, Texture2D> surfaces = new Dictionary<OutProperty, Texture2D>();
foreach (var prop in pcache.properties)
{
OutProperty p_out;
if (outProperties.ContainsKey(prop.ComponentName))
{
p_out = outProperties[prop.ComponentName];
p_out.Size = Math.Max(p_out.Size, prop.ComponentIndex + 1);
}
else
{
p_out = new OutProperty(prop.Type, prop.ComponentName, prop.ComponentIndex + 1);
outProperties.Add(prop.ComponentName, p_out);
}
inProperties.Add(new InProperty(prop.Type, prop.Name, prop.ComponentIndex, p_out));
}
int width, height;
FindBestSize(pcache.elementCount, out width, out height);
// Output Surface Creation
foreach (var kvp in outProperties)
{
TextureFormat surfaceFormat = TextureFormat.Alpha8;
switch (kvp.Value.PropertyType)
{
case "byte":
if (kvp.Value.Size == 1) surfaceFormat = TextureFormat.Alpha8;
else surfaceFormat = TextureFormat.RGBA32;
break;
case "float":
if (kvp.Value.Size == 1) surfaceFormat = TextureFormat.RHalf;
else surfaceFormat = TextureFormat.RGBAHalf;
break;
default: throw new NotImplementedException("Types other than byte/float are not supported yet");
}
Texture2D surface = new Texture2D(width, height, surfaceFormat, false);
surface.name = kvp.Key;
surfaces.Add(kvp.Value, surface);
}
cache.PointCount = pcache.elementCount;
cache.surfaces = new Texture2D[surfaces.Count];
Dictionary<OutProperty, Color> outValues = new Dictionary<OutProperty, Color>();
foreach (var kvp in outProperties)
outValues.Add(kvp.Value, new Color());
for (int i = 0; i < pcache.elementCount; i++)
{
int idx = 0;
foreach (var prop in inProperties)
{
float val = 0.0f;
switch (prop.PropertyType)
{
case "byte":
val = Mathf.Clamp01(((int)pcache.buckets[idx][i]) / 256.0f);
break;
case "float":
val = ((float)pcache.buckets[idx][i]);
break;
default: throw new NotImplementedException("Types other than byte/float are not supported yet");
}
SetPropValue(prop.Index, outValues, prop.OutProperty, val);
idx++;
}
foreach (var kvp in outProperties)
{
surfaces[kvp.Value].SetPixel(i % width, i / width, outValues[kvp.Value]);
}
}
int k = 0;
foreach (var kvp in surfaces)
{
kvp.Value.Apply();
kvp.Value.hideFlags = HideFlags.HideInHierarchy;
ctx.AddObjectToAsset(kvp.Key.Name, kvp.Value);
cache.surfaces[k] = kvp.Value;
k++;
}
}
catch (System.Exception e)
{
Debug.LogException(e);
}
}
private void SetPropValue(int index, Dictionary<OutProperty, Color> data, OutProperty prop, float val)
{
Color c = data[prop];
switch (index)
{
case 0: if (prop.Size == 1 && prop.PropertyType == "int") c.a = val; else c.r = val; break;
case 1: c.g = val; break;
case 2: c.b = val; break;
case 3: c.a = val; break;
}
data[prop] = c;
}
private void FindBestSize(int count, out int width, out int height)
{
float r = Mathf.Sqrt(count);
width = (int)Mathf.Ceil(r);
height = width;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace CK.Text
{
/// <summary>
/// Extends <see cref="StringMatcher"/> with useful (yet basic) methods.
/// </summary>
public static class StringMatcherTextExtension
{
/// <summary>
/// Matches a Guid. No error is set if match fails.
/// </summary>
/// <remarks>
/// Any of the 5 forms of Guid can be matched:
/// <list type="table">
/// <item><term>N</term><description>00000000000000000000000000000000</description></item>
/// <item><term>D</term><description>00000000-0000-0000-0000-000000000000</description></item>
/// <item><term>B</term><description>{00000000-0000-0000-0000-000000000000}</description></item>
/// <item><term>P</term><description>(00000000-0000-0000-0000-000000000000)</description></item>
/// <item><term>X</term><description>{0x00000000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}</description></item>
/// </list>
/// </remarks>
/// <param name="this">This <see cref="StringMatcher"/>.</param>
/// <param name="id">The result Guid. <see cref="Guid.Empty"/> on failure.</param>
/// <returns><c>true</c> when matched, <c>false</c> otherwise.</returns>
public static bool TryMatchGuid( this StringMatcher @this, out Guid id )
{
id = Guid.Empty;
if( @this.Length < 32 ) return false;
if( @this.Head == '{' )
{
// Form "B" or "X".
if( @this.Length < 38 ) return false;
if( @this.Text[@this.StartIndex+37] == '}' )
{
// The "B" form.
if( Guid.TryParseExact( @this.Text.Substring( @this.StartIndex, 38 ), "B", out id ) )
{
return @this.UncheckedMove( 38 );
}
return false;
}
// The "X" form.
if( @this.Length >= 68 && Guid.TryParseExact( @this.Text.Substring( @this.StartIndex, 68 ), "X", out id ) )
{
return @this.UncheckedMove( 68 );
}
return false;
}
if( @this.Head == '(' )
{
// Can only be the "P" form.
if( @this.Length >= 38 && Guid.TryParseExact( @this.Text.Substring( @this.StartIndex, 38 ), "P", out id ) )
{
return @this.UncheckedMove( 38 );
}
return false;
}
if( @this.Head.HexDigitValue() >= 0 )
{
// The "N" or "D" form.
if( @this.Length >= 36 && @this.Text[@this.StartIndex + 8] == '-' )
{
// The ""D" form.
if( Guid.TryParseExact( @this.Text.Substring( @this.StartIndex, 36 ), "D", out id ) )
{
return @this.UncheckedMove( 36 );
}
return false;
}
if( Guid.TryParseExact( @this.Text.Substring( @this.StartIndex, 32 ), "N", out id ) )
{
return @this.UncheckedMove( 32 );
}
}
return false;
}
/// <summary>
/// Matches a JSON quoted string without setting an error if match fails.
/// </summary>
/// <param name="this">This <see cref="StringMatcher"/>.</param>
/// <param name="content">Extracted content.</param>
/// <param name="allowNull">True to allow 'null'.</param>
/// <returns><c>true</c> when matched, <c>false</c> otherwise.</returns>
public static bool TryMatchJSONQuotedString( this StringMatcher @this, out string content, bool allowNull = false )
{
content = null;
if( @this.IsEnd ) return false;
int i = @this.StartIndex;
if( @this.Text[i++] != '"' )
{
return allowNull && @this.TryMatchText( "null" );
}
int len = @this.Length - 1;
StringBuilder b = null;
while( len >= 0 )
{
if( len == 0 ) return false;
char c = @this.Text[i++];
--len;
if( c == '"' ) break;
if( c == '\\' )
{
if( len == 0 ) return false;
if( b == null ) b = new StringBuilder( @this.Text, @this.StartIndex + 1, i - @this.StartIndex - 2, 1024 );
switch( (c = @this.Text[i++]) )
{
case 'r': c = '\r'; break;
case 'n': c = '\n'; break;
case 'b': c = '\b'; break;
case 't': c = '\t'; break;
case 'f': c = '\f'; break;
case 'u':
{
if( --len == 0 ) return false;
int cN;
cN = IStringMatcherExtension.ReadHexDigit( @this.Text[i++] );
if( cN < 0 || cN > 15 ) return false;
int val = cN << 12;
if( --len == 0 ) return false;
cN = IStringMatcherExtension.ReadHexDigit( @this.Text[i++] );
if( cN < 0 || cN > 15 ) return false;
val |= cN << 8;
if( --len == 0 ) return false;
cN = IStringMatcherExtension.ReadHexDigit( @this.Text[i++] );
if( cN < 0 || cN > 15 ) return false;
val |= cN << 4;
if( --len == 0 ) return false;
cN = IStringMatcherExtension.ReadHexDigit( @this.Text[i++] );
if( cN < 0 || cN > 15 ) return false;
val |= cN;
c = (char)val;
break;
}
}
}
if( b != null ) b.Append( c );
}
int lenS = i - @this.StartIndex;
if( b != null ) content = b.ToString();
else content = @this.Text.Substring( @this.StartIndex + 1, lenS - 2 );
return @this.UncheckedMove( lenS );
}
/// <summary>
/// Matches a quoted string without extracting its content.
/// </summary>
/// <param name="this">This <see cref="StringMatcher"/>.</param>
/// <param name="allowNull">True to allow 'null'.</param>
/// <returns><c>true</c> when matched, <c>false</c> otherwise.</returns>
public static bool TryMatchJSONQuotedString( this StringMatcher @this, bool allowNull = false )
{
if( @this.IsEnd ) return false;
int i = @this.StartIndex;
if( @this.Text[i++] != '"' )
{
return allowNull && @this.TryMatchText( "null" );
}
int len = @this.Length - 1;
while( len >= 0 )
{
if( len == 0 ) return false;
char c = @this.Text[i++];
--len;
if( c == '"' ) break;
if( c == '\\' )
{
i++;
--len;
}
}
return @this.UncheckedMove( i - @this.StartIndex );
}
/// <summary>
/// The <see cref="Regex"/> that <see cref="TryMatchDoubleValue(StringMatcher)"/> uses to avoid
/// calling <see cref="double.TryParse(string, out double)"/> when resolving the value is
/// useless.
/// Note that this regex allow a leading minus (-) sign, but not a plus (+).
/// </summary>
static public readonly Regex RegexDouble = new Regex( @"^-?(0|[1-9][0-9]*)(\.[0-9]+)?((e|E)(\+|-)?[0-9]+)?", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture );
/// <summary>
/// Matches a double without getting its value nor setting an error if match fails.
/// This uses <see cref="RegexDouble"/>.
/// The text may start with a minus (-) but not with a plus (+).
/// </summary>
/// <param name="this">This <see cref="StringMatcher"/>.</param>
/// <returns><c>true</c> when matched, <c>false</c> otherwise.</returns>
public static bool TryMatchDoubleValue( this StringMatcher @this )
{
Match m = RegexDouble.Match( @this.Text, @this.StartIndex, @this.Length );
if( !m.Success ) return false;
return @this.UncheckedMove( m.Length );
}
/// <summary>
/// Matches a double and gets its value. No error is set if match fails.
/// The text may start with a minus (-) but not with a plus (+).
/// </summary>
/// <param name="this">This <see cref="StringMatcher"/>.</param>
/// <param name="value">The read value on success.</param>
/// <returns><c>true</c> when matched, <c>false</c> otherwise.</returns>
public static bool TryMatchDoubleValue( this StringMatcher @this, out double value )
{
Match m = RegexDouble.Match( @this.Text, @this.StartIndex, @this.Length );
if( !m.Success )
{
value = 0;
return false;
}
if( !double.TryParse( @this.Text.Substring( @this.StartIndex, m.Length ), NumberStyles.Float, CultureInfo.InvariantCulture, out value ) ) return false;
return @this.UncheckedMove( m.Length );
}
/// <summary>
/// Matches a JSON terminal value: a "string", null, a number (double value), true or false.
/// This method ignores the actual value and does not set any error if match fails.
/// </summary>
/// <param name="this">This <see cref="StringMatcher"/>.</param>
/// <returns>True if a JSON value has been matched, false otherwise.</returns>
public static bool TryMatchJSONTerminalValue( this StringMatcher @this )
{
return @this.TryMatchJSONQuotedString( true )
|| @this.TryMatchDoubleValue()
|| @this.TryMatchText( "true" )
|| @this.TryMatchText( "false" );
}
/// <summary>
/// Obsolete: renamed to TryMatchJSONTerminalValue.
/// </summary>
/// <param name="this">This <see cref="StringMatcher"/>.</param>
/// <param name="value">The parsed value. Can be null.</param>
/// <returns>True if a JSON value has been matched, false otherwise.</returns>
[Obsolete( "Use TryMatchJSONTerminalValue(@this, out value) instead." )]
public static bool TryMatchJSONValue( this StringMatcher @this, out object value ) => TryMatchJSONTerminalValue( @this, out value );
/// <summary>
/// Matches a JSON terminal value: a "string", null, a number (double value), true or false.
/// No error is set if match fails.
/// </summary>
/// <param name="this">This <see cref="StringMatcher"/>.</param>
/// <param name="value">The parsed value. Can be null.</param>
/// <returns>True if a JSON value has been matched, false otherwise.</returns>
public static bool TryMatchJSONTerminalValue( this StringMatcher @this, out object value )
{
string s;
if( @this.TryMatchJSONQuotedString( out s, true ) )
{
value = s;
return true;
}
double d;
if( @this.TryMatchDoubleValue( out d ) )
{
value = d;
return true;
}
if( @this.TryMatchText( "true" ) )
{
value = true;
return true;
}
if( @this.TryMatchText( "false" ) )
{
value = false;
return true;
}
value = null;
return false;
}
/// <summary>
/// Matches a very simple version of a JSON object content: this match stops at the first closing }.
/// Whitespaces and JS comments (//... or /* ... */) are skipped.
/// </summary>
/// <param name="this">This <see cref="StringMatcher"/>.</param>
/// <param name="o">The read object on success as a list of KeyValuePair.</param>
/// <returns>True on success, false on error.</returns>
public static bool MatchJSONObjectContent( this StringMatcher @this, out List<KeyValuePair<string,object>> o )
{
o = null;
while( [email protected] )
{
@this.SkipWhiteSpacesAndJSComments();
string propName;
object value;
if( @this.TryMatchChar( '}' ) )
{
if( o == null ) o = new List<KeyValuePair<string, object>>();
return true;
}
if( [email protected]( out propName ) )
{
o = null;
return @this.SetError( "Quoted Property Name." );
}
@this.SkipWhiteSpacesAndJSComments();
if( [email protected]( ':' ) || !MatchJSONObject( @this, out value ) )
{
o = null;
return false;
}
if( o == null ) o = new List<KeyValuePair<string, object>>();
o.Add( new KeyValuePair<string, object>( propName, value ) );
@this.SkipWhiteSpacesAndJSComments();
// This accepts e trailing comma at the end of a property list: ..."a":0,} is not an error.
@this.TryMatchChar( ',' );
}
return @this.SetError( "JSON object definition but reached end of match." );
}
/// <summary>
/// Matches a { "JSON" : "object" }, a ["JSON", "array"] or a terminal value (string, null, double, true or false)
/// and any combination of them.
/// Whitespaces and JS comments (//... or /* ... */) are skipped.
/// </summary>
/// <param name="this">This <see cref="StringMatcher"/>.</param>
/// <param name="value">
/// A list of objects (for array), a list of KeyValuePair<string,object> for object or
/// a double, string, boolean or null (for null).</param>
/// <returns>True on success, false on error.</returns>
public static bool MatchJSONObject( this StringMatcher @this, out object value )
{
value = null;
@this.SkipWhiteSpacesAndJSComments();
if( @this.TryMatchChar( '{' ) )
{
List<KeyValuePair<string, object>> c;
if( !MatchJSONObjectContent( @this, out c ) ) return false;
value = c;
return true;
}
if( @this.TryMatchChar( '[' ) )
{
List<object> t;
if( !MatchJSONArrayContent( @this, out t ) ) return false;
value = t;
return true;
}
if( TryMatchJSONTerminalValue( @this, out value ) ) return true;
return @this.SetError( "JSON value." );
}
/// <summary>
/// Matches a JSON array content: the match ends with the first ].
/// Whitespaces and JS comments (//... or /* ... */) are skipped.
/// </summary>
/// <param name="this">This <see cref="StringMatcher"/>.</param>
/// <param name="value">The list of objects on success.</param>
/// <returns>True on success, false otherwise.</returns>
public static bool MatchJSONArrayContent( this StringMatcher @this, out List<object> value )
{
value = null;
while( [email protected] )
{
@this.SkipWhiteSpacesAndJSComments();
if( @this.TryMatchChar( ']' ) )
{
if( value == null ) value = new List<object>();
return true;
}
object cell;
if( !MatchJSONObject( @this, out cell ) ) return false;
if( value == null ) value = new List<object>();
value.Add( cell );
@this.SkipWhiteSpacesAndJSComments();
// Allow trailing comma: ,] is valid.
@this.TryMatchChar( ',' );
}
return @this.SetError( "JSON array definition but reached end of match." );
}
}
}
| |
// 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.
// ---------------------------------------------------------------------------
// Native Format Reader
//
// Utilities to read native data from images, that are written by the NativeFormatWriter engine
// ---------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace Internal.NativeFormat
{
// Minimal functionality that is low level enough for use in the managed runtime.
unsafe partial struct NativePrimitiveDecoder
{
static public byte ReadUInt8(ref byte* stream)
{
byte result = *(stream); // Assumes little endian and unaligned access
stream++;
return result;
}
static public ushort ReadUInt16(ref byte* stream)
{
ushort result = *(ushort*)(stream); // Assumes little endian and unaligned access
stream += 2;
return result;
}
static public uint ReadUInt32(ref byte* stream)
{
uint result = *(uint*)(stream); // Assumes little endian and unaligned access
stream += 4;
return result;
}
static public ulong ReadUInt64(ref byte* stream)
{
ulong result = *(ulong*)(stream); // Assumes little endian and unaligned access
stream += 8;
return result;
}
static public unsafe float ReadFloat(ref byte* stream)
{
uint value = ReadUInt32(ref stream);
return *(float*)(&value);
}
static public double ReadDouble(ref byte* stream)
{
ulong value = ReadUInt64(ref stream);
return *(double*)(&value);
}
static public uint GetUnsignedEncodingSize(uint value)
{
if (value < 128) return 1;
if (value < 128 * 128) return 2;
if (value < 128 * 128 * 128) return 3;
if (value < 128 * 128 * 128 * 128) return 4;
return 5;
}
static public uint DecodeUnsigned(ref byte* stream)
{
uint value = 0;
uint val = *stream;
if ((val & 1) == 0)
{
value = (val >> 1);
stream += 1;
}
else if ((val & 2) == 0)
{
value = (val >> 2) |
(((uint)*(stream + 1)) << 6);
stream += 2;
}
else if ((val & 4) == 0)
{
value = (val >> 3) |
(((uint)*(stream + 1)) << 5) |
(((uint)*(stream + 2)) << 13);
stream += 3;
}
else if ((val & 8) == 0)
{
value = (val >> 4) |
(((uint)*(stream + 1)) << 4) |
(((uint)*(stream + 2)) << 12) |
(((uint)*(stream + 3)) << 20);
stream += 4;
}
else if ((val & 16) == 0)
{
stream += 1;
value = ReadUInt32(ref stream);
}
else
{
Debug.Assert(false);
return 0;
}
return value;
}
static public int DecodeSigned(ref byte* stream)
{
int value = 0;
int val = *(stream);
if ((val & 1) == 0)
{
value = ((sbyte)val) >> 1;
stream += 1;
}
else if ((val & 2) == 0)
{
value = (val >> 2) |
(((int)*(sbyte*)(stream + 1)) << 6);
stream += 2;
}
else if ((val & 4) == 0)
{
value = (val >> 3) |
(((int)*(stream + 1)) << 5) |
(((int)*(sbyte*)(stream + 2)) << 13);
stream += 3;
}
else if ((val & 8) == 0)
{
value = (val >> 4) |
(((int)*(stream + 1)) << 4) |
(((int)*(stream + 2)) << 12) |
(((int)*(sbyte*)(stream + 3)) << 20);
stream += 4;
}
else if ((val & 16) == 0)
{
stream += 1;
value = (int)ReadUInt32(ref stream);
}
else
{
Debug.Assert(false);
return 0;
}
return value;
}
static public ulong DecodeUnsignedLong(ref byte* stream)
{
ulong value = 0;
byte val = *stream;
if ((val & 31) != 31)
{
value = DecodeUnsigned(ref stream);
}
else if ((val & 32) == 0)
{
stream += 1;
value = ReadUInt64(ref stream);
}
else
{
Debug.Assert(false);
return 0;
}
return value;
}
static public long DecodeSignedLong(ref byte* stream)
{
long value = 0;
byte val = *stream;
if ((val & 31) != 31)
{
value = DecodeSigned(ref stream);
}
else if ((val & 32) == 0)
{
stream += 1;
value = (long)ReadUInt64(ref stream);
}
else
{
Debug.Assert(false);
return 0;
}
return value;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Reflection.Metadata;
namespace System.Reflection.PortableExecutable
{
public sealed partial class DebugDirectoryBuilder
{
private struct Entry
{
public uint Stamp;
public uint Version;
public DebugDirectoryEntryType Type;
public int DataSize;
}
private readonly List<Entry> _entries;
private readonly BlobBuilder _dataBuilder;
public DebugDirectoryBuilder()
{
_entries = new List<Entry>(3);
_dataBuilder = new BlobBuilder();
}
internal void AddEntry(DebugDirectoryEntryType type, uint version, uint stamp, int dataSize)
{
_entries.Add(new Entry()
{
Stamp = stamp,
Version = version,
Type = type,
DataSize = dataSize,
});
}
/// <summary>
/// Adds an entry.
/// </summary>
/// <param name="type">Entry type.</param>
/// <param name="version">Entry version.</param>
/// <param name="stamp">Entry stamp.</param>
public void AddEntry(DebugDirectoryEntryType type, uint version, uint stamp)
=> AddEntry(type, version, stamp, dataSize: 0);
/// <summary>
/// Adds an entry.
/// </summary>
/// <typeparam name="TData">Type of data passed to <paramref name="dataSerializer"/>.</typeparam>
/// <param name="type">Entry type.</param>
/// <param name="version">Entry version.</param>
/// <param name="stamp">Entry stamp.</param>
/// <param name="data">Data passed to <paramref name="dataSerializer"/>.</param>
/// <param name="dataSerializer">Serializes data to a <see cref="BlobBuilder"/>.</param>
public void AddEntry<TData>(DebugDirectoryEntryType type, uint version, uint stamp, TData data, Action<BlobBuilder, TData> dataSerializer)
{
if (dataSerializer == null)
{
Throw.ArgumentNull(nameof(dataSerializer));
}
int start = _dataBuilder.Count;
dataSerializer(_dataBuilder, data);
int dataSize = _dataBuilder.Count - start;
AddEntry(type, version, stamp, dataSize);
}
/// <summary>
/// Adds a CodeView entry.
/// </summary>
/// <param name="pdbPath">Path to the PDB. Shall not be empty.</param>
/// <param name="pdbContentId">Unique id of the PDB content.</param>
/// <param name="portablePdbVersion">Version of Portable PDB format (e.g. 0x0100 for 1.0), or 0 if the PDB is not portable.</param>
/// <exception cref="ArgumentNullException"><paramref name="pdbPath"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="pdbPath"/> contains NUL character.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="portablePdbVersion"/> is smaller than 0x0100.</exception>
public void AddCodeViewEntry(
string pdbPath,
BlobContentId pdbContentId,
ushort portablePdbVersion)
{
AddCodeViewEntry(pdbPath, pdbContentId, portablePdbVersion, age: 1);
}
/// <summary>
/// Adds a CodeView entry.
/// </summary>
/// <param name="pdbPath">Path to the PDB. Shall not be empty.</param>
/// <param name="pdbContentId">Unique id of the PDB content.</param>
/// <param name="portablePdbVersion">Version of Portable PDB format (e.g. 0x0100 for 1.0), or 0 if the PDB is not portable.</param>
/// <param name="age">Age (iteration) of the PDB. Shall be 1 for Portable PDBs.</param>
/// <exception cref="ArgumentNullException"><paramref name="pdbPath"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="pdbPath"/> contains NUL character.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="age"/> is less than 1.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="portablePdbVersion"/> is smaller than 0x0100.</exception>
internal void AddCodeViewEntry(
string pdbPath,
BlobContentId pdbContentId,
ushort portablePdbVersion,
int age)
{
if (pdbPath == null)
{
Throw.ArgumentNull(nameof(pdbPath));
}
if (age < 1)
{
Throw.ArgumentOutOfRange(nameof(age));
}
// We allow NUL characters to allow for padding for backward compat purposes.
if (pdbPath.Length == 0 || pdbPath.IndexOf('\0') == 0)
{
Throw.InvalidArgument(SR.ExpectedNonEmptyString, nameof(pdbPath));
}
if (portablePdbVersion > 0 && portablePdbVersion < PortablePdbVersions.MinFormatVersion)
{
Throw.ArgumentOutOfRange(nameof(portablePdbVersion));
}
int dataSize = WriteCodeViewData(_dataBuilder, pdbPath, pdbContentId.Guid, age);
AddEntry(
type: DebugDirectoryEntryType.CodeView,
version: (portablePdbVersion == 0) ? 0 : PortablePdbVersions.DebugDirectoryEntryVersion(portablePdbVersion),
stamp: pdbContentId.Stamp,
dataSize);
}
/// <summary>
/// Adds Reproducible entry.
/// </summary>
public void AddReproducibleEntry()
=> AddEntry(type: DebugDirectoryEntryType.Reproducible, version: 0, stamp: 0);
private static int WriteCodeViewData(BlobBuilder builder, string pdbPath, Guid pdbGuid, int age)
{
int start = builder.Count;
builder.WriteByte((byte)'R');
builder.WriteByte((byte)'S');
builder.WriteByte((byte)'D');
builder.WriteByte((byte)'S');
// PDB id:
builder.WriteGuid(pdbGuid);
// age
builder.WriteInt32(age);
// UTF-8 encoded zero-terminated path to PDB
builder.WriteUTF8(pdbPath, allowUnpairedSurrogates: true);
builder.WriteByte(0);
return builder.Count - start;
}
/// <summary>
/// Adds PDB checksum entry.
/// </summary>
/// <param name="algorithmName">Hash algorithm name (e.g. "SHA256").</param>
/// <param name="checksum">Checksum.</param>
/// <exception cref="ArgumentNullException"><paramref name="algorithmName"/> or <paramref name="checksum"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="algorithmName"/> or <paramref name="checksum"/> is empty.</exception>
public void AddPdbChecksumEntry(string algorithmName, ImmutableArray<byte> checksum)
{
if (algorithmName == null)
{
Throw.ArgumentNull(nameof(algorithmName));
}
if (algorithmName.Length == 0)
{
Throw.ArgumentEmptyString(nameof(algorithmName));
}
if (checksum.IsDefault)
{
Throw.ArgumentNull(nameof(checksum));
}
if (checksum.Length == 0)
{
Throw.ArgumentEmptyArray(nameof(checksum));
}
int dataSize = WritePdbChecksumData(_dataBuilder, algorithmName, checksum);
AddEntry(
type: DebugDirectoryEntryType.PdbChecksum,
version: 0x00000001,
stamp: 0x00000000,
dataSize);
}
private static int WritePdbChecksumData(BlobBuilder builder, string algorithmName, ImmutableArray<byte> checksum)
{
int start = builder.Count;
// NUL-terminated algorithm name:
builder.WriteUTF8(algorithmName, allowUnpairedSurrogates: true);
builder.WriteByte(0);
// checksum:
builder.WriteBytes(checksum);
return builder.Count - start;
}
internal int TableSize => DebugDirectoryEntry.Size * _entries.Count;
internal int Size => TableSize + _dataBuilder?.Count ?? 0;
/// <summary>
/// Serialize the Debug Table and Data.
/// </summary>
/// <param name="builder">Builder.</param>
/// <param name="sectionLocation">The containing PE section location.</param>
/// <param name="sectionOffset">Offset of the table within the containing section.</param>
internal void Serialize(BlobBuilder builder, SectionLocation sectionLocation, int sectionOffset)
{
int dataOffset = sectionOffset + TableSize;
foreach (var entry in _entries)
{
int addressOfRawData;
int pointerToRawData;
if (entry.DataSize > 0)
{
addressOfRawData = sectionLocation.RelativeVirtualAddress + dataOffset;
pointerToRawData = sectionLocation.PointerToRawData + dataOffset;
}
else
{
addressOfRawData = 0;
pointerToRawData = 0;
}
builder.WriteUInt32(0); // characteristics, always 0
builder.WriteUInt32(entry.Stamp);
builder.WriteUInt32(entry.Version);
builder.WriteInt32((int)entry.Type);
builder.WriteInt32(entry.DataSize);
builder.WriteInt32(addressOfRawData);
builder.WriteInt32(pointerToRawData);
dataOffset += entry.DataSize;
}
builder.LinkSuffix(_dataBuilder);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DesignerOptionService.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.ComponentModel.Design {
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Security.Permissions;
/// <devdoc>
/// Provides access to get and set option values for a designer.
/// </devdoc>
[HostProtection(SharedState = true)]
public abstract class DesignerOptionService : IDesignerOptionService
{
private DesignerOptionCollection _options;
/// <devdoc>
/// Returns the options collection for this service. There is
/// always a global options collection that contains child collections.
/// </devdoc>
public DesignerOptionCollection Options {
get {
if (_options == null) {
_options = new DesignerOptionCollection(this, null, string.Empty, null);
}
return _options;
}
}
/// <devdoc>
/// Creates a new DesignerOptionCollection with the given name, and adds it to
/// the given parent. The "value" parameter specifies an object whose public
/// properties will be used in the Propeties collection of the option collection.
/// The value parameter can be null if this options collection does not offer
/// any properties. Properties will be wrapped in such a way that passing
/// anything into the component parameter of the property descriptor will be
/// ignored and the value object will be substituted.
/// </devdoc>
protected DesignerOptionCollection CreateOptionCollection (DesignerOptionCollection parent, string name, object value) {
if (parent == null) {
throw new ArgumentNullException("parent");
}
if (name == null) {
throw new ArgumentNullException("name");
}
if (name.Length == 0) {
throw new ArgumentException(SR.GetString(SR.InvalidArgument, name.Length.ToString(CultureInfo.CurrentCulture), (0).ToString(CultureInfo.CurrentCulture)), "name.Length");
}
return new DesignerOptionCollection(this, parent, name, value);
}
/// <devdoc>
/// Retrieves the property descriptor for the given page / value name. Returns
/// null if the property couldn't be found.
/// </devdoc>
private PropertyDescriptor GetOptionProperty(string pageName, string valueName) {
if (pageName == null) {
throw new ArgumentNullException("pageName");
}
if (valueName == null) {
throw new ArgumentNullException("valueName");
}
string[] optionNames = pageName.Split(new char[] {'\\'});
DesignerOptionCollection options = Options;
foreach(string optionName in optionNames) {
options = options[optionName];
if (options == null) {
return null;
}
}
return options.Properties[valueName];
}
/// <devdoc>
/// This method is called on demand the first time a user asks for child
/// options or properties of an options collection.
/// </devdoc>
protected virtual void PopulateOptionCollection(DesignerOptionCollection options) {
}
/// <devdoc>
/// This method must be implemented to show the options dialog UI for the given object.
/// </devdoc>
protected virtual bool ShowDialog(DesignerOptionCollection options, object optionObject) {
return false;
}
/// <internalonly/>
/// <devdoc>
/// Gets the value of an option defined in this package.
/// </devdoc>
object IDesignerOptionService.GetOptionValue(string pageName, string valueName) {
PropertyDescriptor optionProp = GetOptionProperty(pageName, valueName);
if (optionProp != null) {
return optionProp.GetValue(null);
}
return null;
}
/// <internalonly/>
/// <devdoc>
/// Sets the value of an option defined in this package.
/// </devdoc>
void IDesignerOptionService.SetOptionValue(string pageName, string valueName, object value) {
PropertyDescriptor optionProp = GetOptionProperty(pageName, valueName);
if (optionProp != null) {
optionProp.SetValue(null, value);
}
}
/// <devdoc>
/// The DesignerOptionCollection class is a collection that contains
/// other DesignerOptionCollection objects. This forms a tree of options,
/// with each branch of the tree having a name and a possible collection of
/// properties. Each parent branch of the tree contains a union of the
/// properties if all the branch's children.
/// </devdoc>
[TypeConverter(typeof(DesignerOptionConverter))]
[Editor("", "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing)]
public sealed class DesignerOptionCollection : IList {
private DesignerOptionService _service;
private DesignerOptionCollection _parent;
private string _name;
private object _value;
private ArrayList _children;
private PropertyDescriptorCollection _properties;
/// <devdoc>
/// Creates a new DesignerOptionCollection.
/// </devdoc>
internal DesignerOptionCollection(DesignerOptionService service, DesignerOptionCollection parent, string name, object value) {
_service = service;
_parent = parent;
_name = name;
_value = value;
if (_parent != null) {
if (_parent._children == null) {
_parent._children = new ArrayList(1);
}
_parent._children.Add(this);
}
}
/// <devdoc>
/// The count of child options collections this collection contains.
/// </devdoc>
public int Count {
get {
EnsurePopulated();
return _children.Count;
}
}
/// <devdoc>
/// The name of this collection. Names are programmatic names and are not
/// localized. A name search is case insensitive.
/// </devdoc>
public string Name {
get {
return _name;
}
}
/// <devdoc>
/// Returns the parent collection object, or null if there is no parent.
/// </devdoc>
public DesignerOptionCollection Parent {
get {
return _parent;
}
}
/// <devdoc>
/// The collection of properties that this OptionCollection, along with all of
/// its children, offers. PropertyDescriptors are taken directly from the
/// value passed to CreateObjectCollection and wrapped in an additional property
/// descriptor that hides the value object from the user. This means that any
/// value may be passed into the "component" parameter of the various
/// PropertyDescriptor methods. The value is ignored and is replaced with
/// the correct value internally.
/// </devdoc>
public PropertyDescriptorCollection Properties {
get {
if (_properties == null) {
ArrayList propList;
if (_value != null) {
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(_value);
propList = new ArrayList(props.Count);
foreach(PropertyDescriptor prop in props) {
propList.Add(new WrappedPropertyDescriptor(prop, _value));
}
}
else {
propList = new ArrayList(1);
}
EnsurePopulated();
foreach(DesignerOptionCollection child in _children) {
propList.AddRange(child.Properties);
}
PropertyDescriptor[] propArray = (PropertyDescriptor[])propList.ToArray(typeof(PropertyDescriptor));
_properties = new PropertyDescriptorCollection(propArray, true);
}
return _properties;
}
}
/// <devdoc>
/// Retrieves the child collection at the given index.
/// </devdoc>
public DesignerOptionCollection this[int index] {
[SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")]
get {
EnsurePopulated();
if (index < 0 || index >= _children.Count) {
throw new IndexOutOfRangeException("index");
}
return (DesignerOptionCollection)_children[index];
}
}
/// <devdoc>
/// Retrieves the child collection at the given name. The name search is case
/// insensitive.
/// </devdoc>
public DesignerOptionCollection this[string name] {
get {
EnsurePopulated();
foreach(DesignerOptionCollection child in _children) {
if (string.Compare(child.Name, name, true, CultureInfo.InvariantCulture) == 0) {
return child;
}
}
return null;
}
}
/// <devdoc>
/// Copies this collection to an array.
/// </devdoc>
public void CopyTo(Array array, int index) {
EnsurePopulated();
_children.CopyTo(array, index);
}
/// <devdoc>
/// Called before any access to our collection to force it to become populated.
/// </devdoc>
private void EnsurePopulated() {
if (_children == null) {
_service.PopulateOptionCollection(this);
if (_children == null) {
_children = new ArrayList(1);
}
}
}
/// <devdoc>
/// Returns an enumerator that can be used to iterate this collection.
/// </devdoc>
public IEnumerator GetEnumerator() {
EnsurePopulated();
return _children.GetEnumerator();
}
/// <devdoc>
/// Returns the numerical index of the given value.
/// </devdoc>
public int IndexOf(DesignerOptionCollection value) {
EnsurePopulated();
return _children.IndexOf(value);
}
/// <devdoc>
/// Locates the value object to use for getting or setting a property.
/// </devdoc>
private static object RecurseFindValue(DesignerOptionCollection options) {
if (options._value != null) {
return options._value;
}
foreach(DesignerOptionCollection child in options) {
object value = RecurseFindValue(child);
if (value != null) {
return value;
}
}
return null;
}
/// <devdoc>
/// Displays a dialog-based user interface that allows the user to
/// configure the various options.
/// </devdoc>
public bool ShowDialog() {
object value = RecurseFindValue(this);
if (value == null) {
return false;
}
return _service.ShowDialog(this, value);
}
/// <internalonly/>
/// <devdoc>
/// Private ICollection implementation.
/// </devdoc>
bool ICollection.IsSynchronized {
get {
return false;
}
}
/// <internalonly/>
/// <devdoc>
/// Private ICollection implementation.
/// </devdoc>
object ICollection.SyncRoot {
get {
return this;
}
}
/// <internalonly/>
/// <devdoc>
/// Private IList implementation.
/// </devdoc>
bool IList.IsFixedSize {
get {
return true;
}
}
/// <internalonly/>
/// <devdoc>
/// Private IList implementation.
/// </devdoc>
bool IList.IsReadOnly {
get {
return true;
}
}
/// <internalonly/>
/// <devdoc>
/// Private IList implementation.
/// </devdoc>
object IList.this[int index] {
get {
return this[index];
}
set {
throw new NotSupportedException();
}
}
/// <internalonly/>
/// <devdoc>
/// Private IList implementation.
/// </devdoc>
int IList.Add(object value) {
throw new NotSupportedException();
}
/// <internalonly/>
/// <devdoc>
/// Private IList implementation.
/// </devdoc>
void IList.Clear() {
throw new NotSupportedException();
}
/// <internalonly/>
/// <devdoc>
/// Private IList implementation.
/// </devdoc>
bool IList.Contains(object value) {
EnsurePopulated();
return _children.Contains(value);
}
/// <internalonly/>
/// <devdoc>
/// Private IList implementation.
/// </devdoc>
int IList.IndexOf(object value) {
EnsurePopulated();
return _children.IndexOf(value);
}
/// <internalonly/>
/// <devdoc>
/// Private IList implementation.
/// </devdoc>
void IList.Insert(int index, object value) {
throw new NotSupportedException();
}
/// <internalonly/>
/// <devdoc>
/// Private IList implementation.
/// </devdoc>
void IList.Remove(object value) {
throw new NotSupportedException();
}
/// <internalonly/>
/// <devdoc>
/// Private IList implementation.
/// </devdoc>
void IList.RemoveAt(int index) {
throw new NotSupportedException();
}
/// <devdoc>
/// A special property descriptor that forwards onto a base
/// property descriptor but allows any value to be used for the
/// "component" parameter.
/// </devdoc>
private sealed class WrappedPropertyDescriptor : PropertyDescriptor {
private object target;
private PropertyDescriptor property;
internal WrappedPropertyDescriptor(PropertyDescriptor property, object target) : base(property.Name, null) {
this.property = property;
this.target = target;
}
public override AttributeCollection Attributes {
get {
return property.Attributes;
}
}
public override Type ComponentType {
get {
return property.ComponentType;
}
}
public override bool IsReadOnly {
get {
return property.IsReadOnly;
}
}
public override Type PropertyType {
get {
return property.PropertyType;
}
}
public override bool CanResetValue(object component) {
return property.CanResetValue(target);
}
public override object GetValue(object component) {
return property.GetValue(target);
}
public override void ResetValue(object component) {
property.ResetValue(target);
}
public override void SetValue(object component, object value) {
property.SetValue(target, value);
}
public override bool ShouldSerializeValue(object component) {
return property.ShouldSerializeValue(target);
}
}
}
/// <devdoc>
/// The type converter for the designer option collection.
/// </devdoc>
internal sealed class DesignerOptionConverter : TypeConverter {
public override bool GetPropertiesSupported(ITypeDescriptorContext cxt) {
return true;
}
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext cxt, object value, Attribute[] attributes) {
PropertyDescriptorCollection props = new PropertyDescriptorCollection(null);
DesignerOptionCollection options = value as DesignerOptionCollection;
if (options == null) {
return props;
}
foreach(DesignerOptionCollection option in options) {
props.Add(new OptionPropertyDescriptor(option));
}
foreach(PropertyDescriptor p in options.Properties) {
props.Add(p);
}
return props;
}
public override object ConvertTo(ITypeDescriptorContext cxt, CultureInfo culture, object value, Type destinationType) {
if (destinationType == typeof(string)) {
return SR.GetString(SR.CollectionConverterText);
}
return base.ConvertTo(cxt, culture, value, destinationType);
}
private class OptionPropertyDescriptor : PropertyDescriptor {
private DesignerOptionCollection _option;
internal OptionPropertyDescriptor(DesignerOptionCollection option) : base(option.Name, null) {
_option = option;
}
public override Type ComponentType {
get {
return _option.GetType();
}
}
public override bool IsReadOnly {
get {
return true;
}
}
public override Type PropertyType {
get {
return _option.GetType();
}
}
public override bool CanResetValue(object component) {
return false;
}
public override object GetValue(object component) {
return _option;
}
public override void ResetValue(object component) {
}
public override void SetValue(object component, object value) {
}
public override bool ShouldSerializeValue(object component) {
return false;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// Strings are the only ref class where there is built-in support for
// constant objects.
using Microsoft.Xunit.Performance;
using System;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Collections.Generic;
using Xunit;
[assembly: OptimizeForBenchmarks]
[assembly: MeasureInstructionsRetired]
namespace Inlining
{
public static class ConstantArgsString
{
#if DEBUG
public const int Iterations = 1;
#else
public const int Iterations = 100000;
#endif
// Ints feeding math operations.
//
// Inlining in Bench0xp should enable constant folding
// Inlining in Bench0xn will not enable constant folding
static string Ten = "Ten";
static string Five = "Five";
static string Id(string x)
{
return x;
}
static char F00(string x)
{
return x[0];
}
static bool Bench00p()
{
string t = "Ten";
char f = F00(t);
return (f == 'T');
}
static bool Bench00n()
{
string t = Ten;
char f = F00(t);
return (f == 'T');
}
static int F01(string x)
{
return x.Length;
}
static bool Bench01p()
{
string t = "Ten";
int f = F01(t);
return (f == 3);
}
static bool Bench01n()
{
string t = Ten;
int f = F01(t);
return (f == 3);
}
static bool Bench01p1()
{
return "Ten".Length == 3;
}
static bool Bench01n1()
{
return Ten.Length == 3;
}
static bool Bench02p()
{
return "Ten".Equals("Ten", StringComparison.Ordinal);
}
static bool Bench02n()
{
return "Ten".Equals(Ten, StringComparison.Ordinal);
}
static bool Bench02n1()
{
return Ten.Equals("Ten", StringComparison.Ordinal);
}
static bool Bench02n2()
{
return Ten.Equals(Ten, StringComparison.Ordinal);
}
static bool Bench03p()
{
return "Ten" == "Ten";
}
static bool Bench03n()
{
return "Ten" == Ten;
}
static bool Bench03n1()
{
return Ten == "Ten";
}
static bool Bench03n2()
{
return Ten == Ten;
}
static bool Bench04p()
{
return "Ten" != "Five";
}
static bool Bench04n()
{
return "Ten" != Five;
}
static bool Bench04n1()
{
return Ten != "Five";
}
static bool Bench04n2()
{
return Ten != Five;
}
static bool Bench05p()
{
string t = "Ten";
return (t == t);
}
static bool Bench05n()
{
string t = Ten;
return (t == t);
}
static bool Bench06p()
{
return "Ten" != null;
}
static bool Bench06n()
{
return Ten != null;
}
static bool Bench07p()
{
return !"Ten".Equals(null);
}
static bool Bench07n()
{
return !Ten.Equals(null);
}
static bool Bench08p()
{
return !"Ten".Equals("Five", StringComparison.Ordinal);
}
static bool Bench08n()
{
return !"Ten".Equals(Five, StringComparison.Ordinal);
}
static bool Bench08n1()
{
return !Ten.Equals("Five", StringComparison.Ordinal);
}
static bool Bench08n2()
{
return !Ten.Equals(Five, StringComparison.Ordinal);
}
static bool Bench09p()
{
return string.Equals("Ten", "Ten");
}
static bool Bench09n()
{
return string.Equals("Ten", Ten);
}
static bool Bench09n1()
{
return string.Equals(Ten, "Ten");
}
static bool Bench09n2()
{
return string.Equals(Ten, Ten);
}
static bool Bench10p()
{
return !string.Equals("Five", "Ten");
}
static bool Bench10n()
{
return !string.Equals(Five, "Ten");
}
static bool Bench10n1()
{
return !string.Equals("Five", Ten);
}
static bool Bench10n2()
{
return !string.Equals(Five, Ten);
}
static bool Bench11p()
{
return !string.Equals("Five", null);
}
static bool Bench11n()
{
return !string.Equals(Five, null);
}
private static IEnumerable<object[]> MakeArgs(params string[] args)
{
return args.Select(arg => new object[] { arg });
}
public static IEnumerable<object[]> TestFuncs = MakeArgs(
"Bench00p", "Bench00n",
"Bench01p", "Bench01n",
"Bench01p1", "Bench01n1",
"Bench02p", "Bench02n",
"Bench02n1", "Bench02n2",
"Bench03p", "Bench03n",
"Bench03n1", "Bench03n2",
"Bench04p", "Bench04n",
"Bench04n1", "Bench04n2",
"Bench05p", "Bench05n",
"Bench06p", "Bench06n",
"Bench07p", "Bench07n",
"Bench08p", "Bench08n",
"Bench08n1", "Bench08n2",
"Bench09p", "Bench09n",
"Bench09n1", "Bench09n2",
"Bench10p", "Bench10n",
"Bench10n1", "Bench10n2",
"Bench11p", "Bench11n"
);
static Func<bool> LookupFunc(object o)
{
TypeInfo t = typeof(ConstantArgsString).GetTypeInfo();
MethodInfo m = t.GetDeclaredMethod((string) o);
return m.CreateDelegate(typeof(Func<bool>)) as Func<bool>;
}
[Benchmark]
[MemberData(nameof(TestFuncs))]
public static void Test(object funcName)
{
Func<bool> f = LookupFunc(funcName);
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < Iterations; i++)
{
f();
}
}
}
}
static bool TestBase(Func<bool> f)
{
bool result = true;
for (int i = 0; i < Iterations; i++)
{
result &= f();
}
return result;
}
public static int Main()
{
bool result = true;
foreach(object[] o in TestFuncs)
{
string funcName = (string) o[0];
Func<bool> func = LookupFunc(funcName);
bool thisResult = TestBase(func);
if (!thisResult)
{
Console.WriteLine("{0} failed", funcName);
}
result &= thisResult;
}
return (result ? 100 : -1);
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Archiver.Codecs {
public class ChallengeResponseDecoder
{
public const ushort BLOCK_LENGTH = 16;
public const ushort TEMPLATE_ID = 60;
public const ushort SCHEMA_ID = 101;
public const ushort SCHEMA_VERSION = 6;
private ChallengeResponseDecoder _parentMessage;
private IDirectBuffer _buffer;
protected int _offset;
protected int _limit;
protected int _actingBlockLength;
protected int _actingVersion;
public ChallengeResponseDecoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public ChallengeResponseDecoder Wrap(
IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
this._buffer = buffer;
this._offset = offset;
this._actingBlockLength = actingBlockLength;
this._actingVersion = actingVersion;
Limit(offset + actingBlockLength);
return this;
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int ControlSessionIdId()
{
return 1;
}
public static int ControlSessionIdSinceVersion()
{
return 0;
}
public static int ControlSessionIdEncodingOffset()
{
return 0;
}
public static int ControlSessionIdEncodingLength()
{
return 8;
}
public static string ControlSessionIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long ControlSessionIdNullValue()
{
return -9223372036854775808L;
}
public static long ControlSessionIdMinValue()
{
return -9223372036854775807L;
}
public static long ControlSessionIdMaxValue()
{
return 9223372036854775807L;
}
public long ControlSessionId()
{
return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian);
}
public static int CorrelationIdId()
{
return 2;
}
public static int CorrelationIdSinceVersion()
{
return 0;
}
public static int CorrelationIdEncodingOffset()
{
return 8;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public long CorrelationId()
{
return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian);
}
public static int EncodedCredentialsId()
{
return 3;
}
public static int EncodedCredentialsSinceVersion()
{
return 0;
}
public static string EncodedCredentialsMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int EncodedCredentialsHeaderLength()
{
return 4;
}
public int EncodedCredentialsLength()
{
int limit = _parentMessage.Limit();
return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
}
public int GetEncodedCredentials(IMutableDirectBuffer dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int GetEncodedCredentials(byte[] dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
int originalLimit = Limit();
Limit(_offset + _actingBlockLength);
builder.Append("[ChallengeResponse](sbeTemplateId=");
builder.Append(TEMPLATE_ID);
builder.Append("|sbeSchemaId=");
builder.Append(SCHEMA_ID);
builder.Append("|sbeSchemaVersion=");
if (_parentMessage._actingVersion != SCHEMA_VERSION)
{
builder.Append(_parentMessage._actingVersion);
builder.Append('/');
}
builder.Append(SCHEMA_VERSION);
builder.Append("|sbeBlockLength=");
if (_actingBlockLength != BLOCK_LENGTH)
{
builder.Append(_actingBlockLength);
builder.Append('/');
}
builder.Append(BLOCK_LENGTH);
builder.Append("):");
//Token{signal=BEGIN_FIELD, name='controlSessionId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("ControlSessionId=");
builder.Append(ControlSessionId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("CorrelationId=");
builder.Append(CorrelationId());
builder.Append('|');
//Token{signal=BEGIN_VAR_DATA, name='encodedCredentials', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("EncodedCredentials=");
builder.Append(EncodedCredentialsLength() + " raw bytes");
Limit(originalLimit);
return builder;
}
}
}
| |
using NUnit.Framework;
using Redis.Core;
namespace Redis.Tests
{
[TestFixture]
public class SortedSetTests
{
private IRedisFactory redisFactory;
private IRedis redis;
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
this.redisFactory = new RedisFactory();
}
[SetUp]
public void SetUp()
{
var connection = new RedisConnection("localhost", dbIndex: 10);
this.redis = this.redisFactory.CreateRedis(connection);
this.redis.FlushDB();
}
[Test]
public void ZAdd()
{
Assert.That(this.redis.ZAdd("setkey", "5", "dennis"), Is.EqualTo(1));
var list = this.redis.ZRange("setkey", 0, -1);
Assert.That(list, Has.Count.EqualTo(1));
Assert.That(list[0], Is.EqualTo("dennis"));
}
[Test]
public void ZCard()
{
this.redis.ZAdd("setkey", "5", "dennis");
Assert.That(this.redis.ZCard("setkey"), Is.EqualTo(1));
Assert.That(this.redis.ZCard("nokey"), Is.EqualTo(0));
}
[Test]
public void ZIncrBy()
{
this.redis.ZAdd("setkey", "5", "dennis");
Assert.That(this.redis.ZIncrBy("setkey", "2", "dennis"), Is.EqualTo("7"));
Assert.That(this.redis.ZIncrBy("setkey", "2", "martha"), Is.EqualTo("2"));
}
[Test]
[Ignore("TODO")]
public void ZInterStore()
{
}
[Test]
public void ZRange()
{
this.redis.ZAdd("setkey", "5", "dennis");
this.redis.ZAdd("setkey", "4", "martha");
var list = this.redis.ZRange("setkey", 0, -1);
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list[0], Is.EqualTo("martha"));
Assert.That(list[1], Is.EqualTo("dennis"));
}
[Test]
public void ZRange_with_scores()
{
this.redis.ZAdd("setkey", "5", "dennis");
this.redis.ZAdd("setkey", "4", "martha");
var list = this.redis.ZRangeWithScores("setkey", 0, -1);
Assert.That(list, Has.Count.EqualTo(4));
Assert.That(list[0], Is.EqualTo("martha"));
Assert.That(list[1], Is.EqualTo("4"));
Assert.That(list[2], Is.EqualTo("dennis"));
Assert.That(list[3], Is.EqualTo("5"));
}
[Test]
public void ZRangeByScore()
{
this.redis.ZAdd("setkey", "5", "dennis");
this.redis.ZAdd("setkey", "4", "martha");
this.redis.ZAdd("setkey", "9", "tonka");
var list = this.redis.ZRangeByScore("setkey", "5", "10", 0, 10);
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list[0], Is.EqualTo("dennis"));
Assert.That(list[1], Is.EqualTo("tonka"));
}
[Test]
public void ZRank()
{
this.redis.ZAdd("setkey", "5", "dennis");
this.redis.ZAdd("setkey", "4", "martha");
this.redis.ZAdd("setkey", "9", "tonka");
Assert.That(this.redis.ZRank("setkey", "tonka"), Is.EqualTo(2));
Assert.That(this.redis.ZRank("setkey", "nomember"), Is.Null);
Assert.That(this.redis.ZRank("nokey", "nomember"), Is.Null);
}
[Test]
public void ZRem()
{
this.redis.ZAdd("setkey", "5", "dennis");
this.redis.ZAdd("setkey", "4", "martha");
this.redis.ZAdd("setkey", "9", "tonka");
Assert.That(this.redis.ZRem("setkey", "dennis"), Is.EqualTo(1));
Assert.That(this.redis.ZRem("setkey", "michael"), Is.EqualTo(0));
Assert.That(this.redis.ZCard("setkey"), Is.EqualTo(2));
}
[Test]
public void ZRemRangeByRank()
{
this.redis.ZAdd("setkey", "5", "dennis");
this.redis.ZAdd("setkey", "4", "martha");
this.redis.ZAdd("setkey", "9", "tonka");
Assert.That(this.redis.ZRemRangeByRank("setkey", 0, 1), Is.EqualTo(2));
var list = this.redis.ZRange("setkey", 0, -1);
Assert.That(list, Has.Count.EqualTo(1));
Assert.That(list[0], Is.EqualTo("tonka"));
}
[Test]
public void ZRemRangeByScore()
{
this.redis.ZAdd("setkey", "5", "dennis");
this.redis.ZAdd("setkey", "4", "martha");
this.redis.ZAdd("setkey", "9", "tonka");
Assert.That(this.redis.ZRemRangeByScore("setkey", "2", "4"), Is.EqualTo(1));
var list = this.redis.ZRange("setkey", 0, -1);
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list[0], Is.EqualTo("dennis"));
Assert.That(list[1], Is.EqualTo("tonka"));
}
[Test]
public void ZRevRange()
{
this.redis.ZAdd("setkey", "5", "dennis");
this.redis.ZAdd("setkey", "4", "martha");
var list = this.redis.ZRevRange("setkey", 0, -1);
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list[0], Is.EqualTo("dennis"));
Assert.That(list[1], Is.EqualTo("martha"));
}
[Test]
public void ZRevRange_with_scores()
{
this.redis.ZAdd("setkey", "5", "dennis");
this.redis.ZAdd("setkey", "4", "martha");
var list = this.redis.ZRevRangeWithScores("setkey", 0, -1);
Assert.That(list, Has.Count.EqualTo(4));
Assert.That(list[0], Is.EqualTo("dennis"));
Assert.That(list[1], Is.EqualTo("5"));
Assert.That(list[2], Is.EqualTo("martha"));
Assert.That(list[3], Is.EqualTo("4"));
}
[Test]
[Ignore]
public void ZRevRangeByScore()
{
this.redis.ZAdd("setkey", "5", "dennis");
this.redis.ZAdd("setkey", "4", "martha");
this.redis.ZAdd("setkey", "9", "tonka");
var list = this.redis.ZRevRangeByScore("setkey", "5", "10", 0, 10);
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list[0], Is.EqualTo("tonka"));
Assert.That(list[1], Is.EqualTo("dennis"));
}
[Test]
[Ignore]
public void ZUnionStore()
{
}
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using MS.Internal;
using System.Windows.Automation;
namespace System.Windows.Controls.Primitives
{
/// <summary>
/// Represents the header for each row of the DataGrid
/// </summary>
[TemplatePart(Name = "PART_TopHeaderGripper", Type = typeof(Thumb))]
[TemplatePart(Name = "PART_BottomHeaderGripper", Type = typeof(Thumb))]
public class DataGridRowHeader : ButtonBase
{
#region Constants
private const byte DATAGRIDROWHEADER_stateMouseOverCode = 0;
private const byte DATAGRIDROWHEADER_stateMouseOverCurrentRowCode = 1;
private const byte DATAGRIDROWHEADER_stateMouseOverEditingRowCode = 2;
private const byte DATAGRIDROWHEADER_stateMouseOverEditingRowFocusedCode = 3;
private const byte DATAGRIDROWHEADER_stateMouseOverSelectedCode = 4;
private const byte DATAGRIDROWHEADER_stateMouseOverSelectedCurrentRowCode = 5;
private const byte DATAGRIDROWHEADER_stateMouseOverSelectedCurrentRowFocusedCode = 6;
private const byte DATAGRIDROWHEADER_stateMouseOverSelectedFocusedCode = 7;
private const byte DATAGRIDROWHEADER_stateNormalCode = 8;
private const byte DATAGRIDROWHEADER_stateNormalCurrentRowCode = 9;
private const byte DATAGRIDROWHEADER_stateNormalEditingRowCode = 10;
private const byte DATAGRIDROWHEADER_stateNormalEditingRowFocusedCode = 11;
private const byte DATAGRIDROWHEADER_stateSelectedCode = 12;
private const byte DATAGRIDROWHEADER_stateSelectedCurrentRowCode = 13;
private const byte DATAGRIDROWHEADER_stateSelectedCurrentRowFocusedCode = 14;
private const byte DATAGRIDROWHEADER_stateSelectedFocusedCode = 15;
private const byte DATAGRIDROWHEADER_stateNullCode = 255;
private static byte[] _fallbackStateMapping = new byte[] {
DATAGRIDROWHEADER_stateNormalCode,
DATAGRIDROWHEADER_stateNormalCurrentRowCode,
DATAGRIDROWHEADER_stateMouseOverEditingRowFocusedCode,
DATAGRIDROWHEADER_stateNormalEditingRowFocusedCode,
DATAGRIDROWHEADER_stateMouseOverSelectedFocusedCode,
DATAGRIDROWHEADER_stateMouseOverSelectedCurrentRowFocusedCode,
DATAGRIDROWHEADER_stateSelectedFocusedCode,
DATAGRIDROWHEADER_stateSelectedFocusedCode,
DATAGRIDROWHEADER_stateNullCode,
DATAGRIDROWHEADER_stateNormalCode,
DATAGRIDROWHEADER_stateNormalEditingRowFocusedCode,
DATAGRIDROWHEADER_stateSelectedCurrentRowFocusedCode,
DATAGRIDROWHEADER_stateSelectedFocusedCode,
DATAGRIDROWHEADER_stateSelectedCurrentRowFocusedCode,
DATAGRIDROWHEADER_stateNormalCurrentRowCode,
DATAGRIDROWHEADER_stateNormalCode,
};
private static byte[] _idealStateMapping = new byte[] {
DATAGRIDROWHEADER_stateNormalCode,
DATAGRIDROWHEADER_stateNormalCode,
DATAGRIDROWHEADER_stateMouseOverCode,
DATAGRIDROWHEADER_stateMouseOverCode,
DATAGRIDROWHEADER_stateNullCode,
DATAGRIDROWHEADER_stateNullCode,
DATAGRIDROWHEADER_stateNullCode,
DATAGRIDROWHEADER_stateNullCode,
DATAGRIDROWHEADER_stateSelectedCode,
DATAGRIDROWHEADER_stateSelectedFocusedCode,
DATAGRIDROWHEADER_stateMouseOverSelectedCode,
DATAGRIDROWHEADER_stateMouseOverSelectedFocusedCode,
DATAGRIDROWHEADER_stateNormalEditingRowCode,
DATAGRIDROWHEADER_stateNormalEditingRowFocusedCode,
DATAGRIDROWHEADER_stateMouseOverEditingRowCode,
DATAGRIDROWHEADER_stateMouseOverEditingRowFocusedCode,
DATAGRIDROWHEADER_stateNormalCurrentRowCode,
DATAGRIDROWHEADER_stateNormalCurrentRowCode,
DATAGRIDROWHEADER_stateMouseOverCurrentRowCode,
DATAGRIDROWHEADER_stateMouseOverCurrentRowCode,
DATAGRIDROWHEADER_stateNullCode,
DATAGRIDROWHEADER_stateNullCode,
DATAGRIDROWHEADER_stateNullCode,
DATAGRIDROWHEADER_stateNullCode,
DATAGRIDROWHEADER_stateSelectedCurrentRowCode,
DATAGRIDROWHEADER_stateSelectedCurrentRowFocusedCode,
DATAGRIDROWHEADER_stateMouseOverSelectedCurrentRowCode,
DATAGRIDROWHEADER_stateMouseOverSelectedCurrentRowFocusedCode,
DATAGRIDROWHEADER_stateNormalEditingRowCode,
DATAGRIDROWHEADER_stateNormalEditingRowFocusedCode,
DATAGRIDROWHEADER_stateMouseOverEditingRowCode,
DATAGRIDROWHEADER_stateMouseOverEditingRowFocusedCode
};
private static string[] _stateNames = new string[]
{
VisualStates.DATAGRIDROWHEADER_stateMouseOver,
VisualStates.DATAGRIDROWHEADER_stateMouseOverCurrentRow,
VisualStates.DATAGRIDROWHEADER_stateMouseOverEditingRow,
VisualStates.DATAGRIDROWHEADER_stateMouseOverEditingRowFocused,
VisualStates.DATAGRIDROWHEADER_stateMouseOverSelected,
VisualStates.DATAGRIDROWHEADER_stateMouseOverSelectedCurrentRow,
VisualStates.DATAGRIDROWHEADER_stateMouseOverSelectedCurrentRowFocused,
VisualStates.DATAGRIDROWHEADER_stateMouseOverSelectedFocused,
VisualStates.DATAGRIDROWHEADER_stateNormal,
VisualStates.DATAGRIDROWHEADER_stateNormalCurrentRow,
VisualStates.DATAGRIDROWHEADER_stateNormalEditingRow,
VisualStates.DATAGRIDROWHEADER_stateNormalEditingRowFocused,
VisualStates.DATAGRIDROWHEADER_stateSelected,
VisualStates.DATAGRIDROWHEADER_stateSelectedCurrentRow,
VisualStates.DATAGRIDROWHEADER_stateSelectedCurrentRowFocused,
VisualStates.DATAGRIDROWHEADER_stateSelectedFocused
};
#endregion Constants
static DataGridRowHeader()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(DataGridRowHeader), new FrameworkPropertyMetadata(typeof(DataGridRowHeader)));
ContentProperty.OverrideMetadata(typeof(DataGridRowHeader), new FrameworkPropertyMetadata(OnNotifyPropertyChanged, OnCoerceContent));
ContentTemplateProperty.OverrideMetadata(typeof(DataGridRowHeader), new FrameworkPropertyMetadata(OnNotifyPropertyChanged, OnCoerceContentTemplate));
ContentTemplateSelectorProperty.OverrideMetadata(typeof(DataGridRowHeader), new FrameworkPropertyMetadata(OnNotifyPropertyChanged, OnCoerceContentTemplateSelector));
StyleProperty.OverrideMetadata(typeof(DataGridRowHeader), new FrameworkPropertyMetadata(OnNotifyPropertyChanged, OnCoerceStyle));
WidthProperty.OverrideMetadata(typeof(DataGridRowHeader), new FrameworkPropertyMetadata(OnNotifyPropertyChanged, OnCoerceWidth));
ClickModeProperty.OverrideMetadata(typeof(DataGridRowHeader), new FrameworkPropertyMetadata(ClickMode.Press));
FocusableProperty.OverrideMetadata(typeof(DataGridRowHeader), new FrameworkPropertyMetadata(false));
AutomationProperties.IsOffscreenBehaviorProperty.OverrideMetadata(typeof(DataGridRowHeader), new FrameworkPropertyMetadata(IsOffscreenBehavior.FromClip));
}
#region Automation
protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer()
{
return new System.Windows.Automation.Peers.DataGridRowHeaderAutomationPeer(this);
}
#endregion
#region Layout
/// <summary>
/// Property that indicates the brush to use when drawing seperators between headers.
/// </summary>
public Brush SeparatorBrush
{
get { return (Brush)GetValue(SeparatorBrushProperty); }
set { SetValue(SeparatorBrushProperty, value); }
}
/// <summary>
/// DependencyProperty for SeperatorBrush.
/// </summary>
public static readonly DependencyProperty SeparatorBrushProperty =
DependencyProperty.Register("SeparatorBrush", typeof(Brush), typeof(DataGridRowHeader), new FrameworkPropertyMetadata(null));
/// <summary>
/// Property that indicates the Visibility for the header seperators.
/// </summary>
public Visibility SeparatorVisibility
{
get { return (Visibility)GetValue(SeparatorVisibilityProperty); }
set { SetValue(SeparatorVisibilityProperty, value); }
}
/// <summary>
/// DependencyProperty for SeperatorBrush.
/// </summary>
public static readonly DependencyProperty SeparatorVisibilityProperty =
DependencyProperty.Register("SeparatorVisibility", typeof(Visibility), typeof(DataGridRowHeader), new FrameworkPropertyMetadata(Visibility.Visible));
/// <summary>
/// Measure this element and it's child elements.
/// </summary>
/// <remarks>
/// DataGridRowHeader needs to update the DataGrid's RowHeaderActualWidth & use this as it's width so that they all end up the
/// same size.
/// </remarks>
/// <param name="availableSize"></param>
/// <returns></returns>
protected override Size MeasureOverride(Size availableSize)
{
var baseSize = base.MeasureOverride(availableSize);
DataGrid dataGridOwner = DataGridOwner;
if (dataGridOwner == null)
{
return baseSize;
}
if (DoubleUtil.IsNaN(dataGridOwner.RowHeaderWidth) &&
baseSize.Width > dataGridOwner.RowHeaderActualWidth)
{
dataGridOwner.RowHeaderActualWidth = baseSize.Width;
}
// Regardless of how width the Header wants to be, we use
// DataGridOwner.RowHeaderActualWidth to ensure they're all the same size.
return new Size(dataGridOwner.RowHeaderActualWidth, baseSize.Height);
}
#endregion
#region Row Communication
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
// Give the Row a pointer to the RowHeader so that it can propagate down change notifications
DataGridRow parent = ParentRow;
if (parent != null)
{
parent.RowHeader = this;
SyncProperties();
}
// Grippers will now be in the Visual tree.
HookupGripperEvents();
}
/// <summary>
/// Update all properties that get a value from the DataGrid
/// </summary>
/// <remarks>
/// See comment on DataGridRow.OnDataGridChanged
/// </remarks>
internal void SyncProperties()
{
DataGridHelper.TransferProperty(this, ContentProperty);
DataGridHelper.TransferProperty(this, StyleProperty);
DataGridHelper.TransferProperty(this, ContentTemplateProperty);
DataGridHelper.TransferProperty(this, ContentTemplateSelectorProperty);
DataGridHelper.TransferProperty(this, WidthProperty);
CoerceValue(IsRowSelectedProperty);
// We could be the first row now, so reset the thumb visibility.
OnCanUserResizeRowsChanged();
}
#endregion
#region Property Change Notification
/// <summary>
/// Notifies parts that respond to changes in the properties.
/// </summary>
private static void OnNotifyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((DataGridRowHeader)d).NotifyPropertyChanged(d, e);
}
/// <summary>
/// Notification for column header-related DependencyProperty changes from the grid or from columns.
/// </summary>
internal void NotifyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.Property == DataGridRow.HeaderProperty || e.Property == ContentProperty)
{
DataGridHelper.TransferProperty(this, ContentProperty);
}
else if (e.Property == DataGrid.RowHeaderStyleProperty || e.Property == DataGridRow.HeaderStyleProperty || e.Property == StyleProperty)
{
DataGridHelper.TransferProperty(this, StyleProperty);
}
else if (e.Property == DataGrid.RowHeaderTemplateProperty || e.Property == DataGridRow.HeaderTemplateProperty || e.Property == ContentTemplateProperty)
{
DataGridHelper.TransferProperty(this, ContentTemplateProperty);
}
else if (e.Property == DataGrid.RowHeaderTemplateSelectorProperty || e.Property == DataGridRow.HeaderTemplateSelectorProperty || e.Property == ContentTemplateSelectorProperty)
{
DataGridHelper.TransferProperty(this, ContentTemplateSelectorProperty);
}
else if (e.Property == DataGrid.RowHeaderWidthProperty || e.Property == WidthProperty)
{
DataGridHelper.TransferProperty(this, WidthProperty);
}
else if (e.Property == DataGridRow.IsSelectedProperty)
{
CoerceValue(IsRowSelectedProperty);
}
else if (e.Property == DataGrid.CanUserResizeRowsProperty)
{
OnCanUserResizeRowsChanged();
}
else if (e.Property == DataGrid.RowHeaderActualWidthProperty)
{
// When the RowHeaderActualWidth changes we need to re-measure to pick up the new value for DesiredSize
this.InvalidateMeasure();
this.InvalidateArrange();
// If the DataGrid has not run layout the headers parent may not position the cells correctly when the header size changes.
// This will cause the cells to be out of [....] with the columns. To avoid this we will force a layout of the headers parent panel.
var parent = this.Parent as UIElement;
if (parent != null)
{
parent.InvalidateMeasure();
parent.InvalidateArrange();
}
}
else if (e.Property == DataGrid.CurrentItemProperty ||
e.Property == DataGridRow.IsEditingProperty ||
e.Property == DataGridRow.IsMouseOverProperty ||
e.Property == DataGrid.IsKeyboardFocusWithinProperty)
{
UpdateVisualState();
}
}
#endregion
#region Property Coercion callbacks
/// <summary>
/// Coerces the Content property. We're choosing a value between Row.Header and the Content property on RowHeader.
/// </summary>
private static object OnCoerceContent(DependencyObject d, object baseValue)
{
var header = d as DataGridRowHeader;
return DataGridHelper.GetCoercedTransferPropertyValue(
header,
baseValue,
ContentProperty,
header.ParentRow,
DataGridRow.HeaderProperty);
}
/// <summary>
/// Coerces the ContentTemplate property.
/// </summary>
private static object OnCoerceContentTemplate(DependencyObject d, object baseValue)
{
var header = d as DataGridRowHeader;
var row = header.ParentRow;
var dataGrid = row != null ? row.DataGridOwner : null;
return DataGridHelper.GetCoercedTransferPropertyValue(
header,
baseValue,
ContentTemplateProperty,
row,
DataGridRow.HeaderTemplateProperty,
dataGrid,
DataGrid.RowHeaderTemplateProperty);
}
/// <summary>
/// Coerces the ContentTemplateSelector property.
/// </summary>
private static object OnCoerceContentTemplateSelector(DependencyObject d, object baseValue)
{
var header = d as DataGridRowHeader;
var row = header.ParentRow;
var dataGrid = row != null ? row.DataGridOwner : null;
return DataGridHelper.GetCoercedTransferPropertyValue(
header,
baseValue,
ContentTemplateSelectorProperty,
row,
DataGridRow.HeaderTemplateSelectorProperty,
dataGrid,
DataGrid.RowHeaderTemplateSelectorProperty);
}
/// <summary>
/// Coerces the Style property.
/// </summary>
private static object OnCoerceStyle(DependencyObject d, object baseValue)
{
var header = d as DataGridRowHeader;
return DataGridHelper.GetCoercedTransferPropertyValue(
header,
baseValue,
StyleProperty,
header.ParentRow,
DataGridRow.HeaderStyleProperty,
header.DataGridOwner,
DataGrid.RowHeaderStyleProperty);
}
/// <summary>
/// Coerces the Width property.
/// </summary>
private static object OnCoerceWidth(DependencyObject d, object baseValue)
{
var header = d as DataGridRowHeader;
return DataGridHelper.GetCoercedTransferPropertyValue(
header,
baseValue,
WidthProperty,
header.DataGridOwner,
DataGrid.RowHeaderWidthProperty);
}
#endregion
#region Visual State
private bool IsRowCurrent
{
get
{
var row = ParentRow;
if (row != null)
{
var dataGrid = row.DataGridOwner;
if (dataGrid != null)
{
return dataGrid.IsCurrent(row);
}
}
return false;
}
}
private bool IsRowEditing
{
get
{
var row = ParentRow;
if (row != null)
{
return row.IsEditing;
}
return false;
}
}
private bool IsRowMouseOver
{
get
{
var row = ParentRow;
if (row != null)
{
return row.IsMouseOver;
}
return false;
}
}
private bool IsDataGridKeyboardFocusWithin
{
get
{
var row = ParentRow;
if (row != null)
{
var dataGrid = row.DataGridOwner;
if (dataGrid != null)
{
return dataGrid.IsKeyboardFocusWithin;
}
}
return false;
}
}
internal override void ChangeVisualState(bool useTransitions)
{
byte idealStateMappingIndex = 0;
if (IsRowCurrent)
{
idealStateMappingIndex += 16;
}
if (IsRowSelected || IsRowEditing)
{
idealStateMappingIndex += 8;
}
if (IsRowEditing)
{
idealStateMappingIndex += 4;
}
if (IsRowMouseOver)
{
idealStateMappingIndex += 2;
}
if (IsDataGridKeyboardFocusWithin)
{
idealStateMappingIndex += 1;
}
byte stateCode = _idealStateMapping[idealStateMappingIndex];
Debug.Assert(stateCode != DATAGRIDROWHEADER_stateNullCode);
string storyboardName;
while (stateCode != DATAGRIDROWHEADER_stateNullCode)
{
storyboardName = _stateNames[stateCode];
if (VisualStateManager.GoToState(this, storyboardName, useTransitions))
{
break;
}
else
{
// The state wasn't implemented so fall back to the next one
stateCode = _fallbackStateMapping[stateCode];
}
}
ChangeValidationVisualState(useTransitions);
}
#endregion
#region Selection
/// <summary>
/// Indicates whether the owning DataGridRow is selected.
/// </summary>
[Bindable(true), Category("Appearance")]
public bool IsRowSelected
{
get { return (bool)GetValue(IsRowSelectedProperty); }
}
private static readonly DependencyPropertyKey IsRowSelectedPropertyKey =
DependencyProperty.RegisterReadOnly(
"IsRowSelected",
typeof(bool),
typeof(DataGridRowHeader),
new FrameworkPropertyMetadata(false, OnVisualStatePropertyChanged, new CoerceValueCallback(OnCoerceIsRowSelected)));
/// <summary>
/// The DependencyProperty for the IsRowSelected property.
/// </summary>
public static readonly DependencyProperty IsRowSelectedProperty = IsRowSelectedPropertyKey.DependencyProperty;
private static object OnCoerceIsRowSelected(DependencyObject d, object baseValue)
{
DataGridRowHeader header = (DataGridRowHeader)d;
DataGridRow parent = header.ParentRow;
if (parent != null)
{
return parent.IsSelected;
}
return baseValue;
}
/// <summary>
/// Called when the header is clicked.
/// </summary>
protected override void OnClick()
{
base.OnClick();
// The base implementation took capture. This prevents us from doing
// drag selection, so release it.
if (Mouse.Captured == this)
{
ReleaseMouseCapture();
}
DataGrid dataGridOwner = DataGridOwner;
DataGridRow parentRow = ParentRow;
if ((dataGridOwner != null) && (parentRow != null))
{
dataGridOwner.HandleSelectionForRowHeaderAndDetailsInput(parentRow, /* startDragging = */ true);
}
}
#endregion
#region Row Resizing
/// <summary>
/// Find grippers and register drag events
///
/// The default style for DataGridRowHeader is
/// +-------------------------------+
/// +-------------------------------+
/// + Gripper +
/// +-------------------------------+
/// + Header +
/// +-------------------------------+
/// + Gripper +
/// +-------------------------------+
/// +-------------------------------+
///
/// The reason we have two grippers is we can't extend the bottom gripper to straddle the line between two
/// headers; the header below would render on top of it.
/// We resize a Row by grabbing the gripper to the bottom; the top gripper thus adjusts the height of
/// the row above it.
/// </summary>
private void HookupGripperEvents()
{
UnhookGripperEvents();
_topGripper = GetTemplateChild(TopHeaderGripperTemplateName) as Thumb;
_bottomGripper = GetTemplateChild(BottomHeaderGripperTemplateName) as Thumb;
if (_topGripper != null)
{
_topGripper.DragStarted += new DragStartedEventHandler(OnRowHeaderGripperDragStarted);
_topGripper.DragDelta += new DragDeltaEventHandler(OnRowHeaderResize);
_topGripper.DragCompleted += new DragCompletedEventHandler(OnRowHeaderGripperDragCompleted);
_topGripper.MouseDoubleClick += new MouseButtonEventHandler(OnGripperDoubleClicked);
SetTopGripperVisibility();
}
if (_bottomGripper != null)
{
_bottomGripper.DragStarted += new DragStartedEventHandler(OnRowHeaderGripperDragStarted);
_bottomGripper.DragDelta += new DragDeltaEventHandler(OnRowHeaderResize);
_bottomGripper.DragCompleted += new DragCompletedEventHandler(OnRowHeaderGripperDragCompleted);
_bottomGripper.MouseDoubleClick += new MouseButtonEventHandler(OnGripperDoubleClicked);
SetBottomGripperVisibility();
}
}
/// <summary>
/// Clear gripper event
/// </summary>
private void UnhookGripperEvents()
{
if (_topGripper != null)
{
_topGripper.DragStarted -= new DragStartedEventHandler(OnRowHeaderGripperDragStarted);
_topGripper.DragDelta -= new DragDeltaEventHandler(OnRowHeaderResize);
_topGripper.DragCompleted -= new DragCompletedEventHandler(OnRowHeaderGripperDragCompleted);
_topGripper.MouseDoubleClick -= new MouseButtonEventHandler(OnGripperDoubleClicked);
_topGripper = null;
}
if (_bottomGripper != null)
{
_bottomGripper.DragStarted -= new DragStartedEventHandler(OnRowHeaderGripperDragStarted);
_bottomGripper.DragDelta -= new DragDeltaEventHandler(OnRowHeaderResize);
_bottomGripper.DragCompleted -= new DragCompletedEventHandler(OnRowHeaderGripperDragCompleted);
_bottomGripper.MouseDoubleClick -= new MouseButtonEventHandler(OnGripperDoubleClicked);
_bottomGripper = null;
}
}
private void SetTopGripperVisibility()
{
if (_topGripper != null)
{
DataGrid dataGrid = DataGridOwner;
DataGridRow parent = ParentRow;
if (dataGrid != null && parent != null &&
dataGrid.CanUserResizeRows && dataGrid.Items.Count > 1 &&
!object.ReferenceEquals(parent.Item, dataGrid.Items[0]))
{
_topGripper.Visibility = Visibility.Visible;
}
else
{
_topGripper.Visibility = Visibility.Collapsed;
}
}
}
private void SetBottomGripperVisibility()
{
if (_bottomGripper != null)
{
DataGrid dataGrid = DataGridOwner;
if (dataGrid != null && dataGrid.CanUserResizeRows)
{
_bottomGripper.Visibility = Visibility.Visible;
}
else
{
_bottomGripper.Visibility = Visibility.Collapsed;
}
}
}
/// <summary>
/// This is the row that the top gripper should be resizing.
/// </summary>
private DataGridRow PreviousRow
{
get
{
DataGridRow row = ParentRow;
if (row != null)
{
DataGrid dataGrid = row.DataGridOwner;
if (dataGrid != null)
{
int index = dataGrid.ItemContainerGenerator.IndexFromContainer(row);
if (index > 0)
{
return (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(index - 1);
}
}
}
return null;
}
}
/// <summary>
/// Returns either this header or the one before it depending on which Gripper fired the event.
/// </summary>
/// <param name="sender"></param>
private DataGridRow RowToResize(object gripper)
{
return (gripper == _bottomGripper) ? this.ParentRow : PreviousRow;
}
// Save the original height before resize
private void OnRowHeaderGripperDragStarted(object sender, DragStartedEventArgs e)
{
DataGridRow rowToResize = RowToResize(sender);
if (rowToResize != null)
{
rowToResize.OnRowResizeStarted();
e.Handled = true;
}
}
private void OnRowHeaderResize(object sender, DragDeltaEventArgs e)
{
DataGridRow rowToResize = RowToResize(sender);
if (rowToResize != null)
{
rowToResize.OnRowResize(e.VerticalChange);
e.Handled = true;
}
}
// Restores original height if canceled.
private void OnRowHeaderGripperDragCompleted(object sender, DragCompletedEventArgs e)
{
DataGridRow rowToResize = RowToResize(sender);
if (rowToResize != null)
{
rowToResize.OnRowResizeCompleted(e.Canceled);
e.Handled = true;
}
}
private void OnGripperDoubleClicked(object sender, MouseButtonEventArgs e)
{
DataGridRow rowToResize = RowToResize(sender);
if (rowToResize != null)
{
rowToResize.OnRowResizeReset();
e.Handled = true;
}
}
private void OnCanUserResizeRowsChanged()
{
SetTopGripperVisibility();
SetBottomGripperVisibility();
}
#endregion
#region Helpers
internal DataGridRow ParentRow
{
get
{
return DataGridHelper.FindParent<DataGridRow>(this);
}
}
private DataGrid DataGridOwner
{
get
{
DataGridRow parent = ParentRow;
if (parent != null)
{
return parent.DataGridOwner;
}
return null;
}
}
#endregion
private Thumb _topGripper, _bottomGripper;
private const string TopHeaderGripperTemplateName = "PART_TopHeaderGripper";
private const string BottomHeaderGripperTemplateName = "PART_BottomHeaderGripper";
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using ESRI.ArcGIS.Controls;
// This window shows the property pages for the ArcGIS Network Analyst extension environment.
namespace NAEngine
{
public class frmNAProperties : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnOK;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.CheckBox chkZoomToResultAfterSolve;
private System.Windows.Forms.GroupBox grpMessages;
private System.Windows.Forms.RadioButton rdoAllMessages;
private System.Windows.Forms.RadioButton rdoErrorsAndWarnings;
private System.Windows.Forms.RadioButton rdoNoMessages;
private System.Windows.Forms.RadioButton rdoErrors;
bool m_okClicked;
public frmNAProperties()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region 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.btnCancel = new System.Windows.Forms.Button();
this.btnOK = new System.Windows.Forms.Button();
this.chkZoomToResultAfterSolve = new System.Windows.Forms.CheckBox();
this.grpMessages = new System.Windows.Forms.GroupBox();
this.rdoNoMessages = new System.Windows.Forms.RadioButton();
this.rdoErrors = new System.Windows.Forms.RadioButton();
this.rdoErrorsAndWarnings = new System.Windows.Forms.RadioButton();
this.rdoAllMessages = new System.Windows.Forms.RadioButton();
this.grpMessages.SuspendLayout();
this.SuspendLayout();
//
// btnCancel
//
this.btnCancel.Location = new System.Drawing.Point(240, 216);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(112, 32);
this.btnCancel.TabIndex = 4;
this.btnCancel.Text = "&Cancel";
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// btnOK
//
this.btnOK.Location = new System.Drawing.Point(112, 216);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(112, 32);
this.btnOK.TabIndex = 3;
this.btnOK.Text = "&OK";
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// chkZoomToResultAfterSolve
//
this.chkZoomToResultAfterSolve.Location = new System.Drawing.Point(16, 24);
this.chkZoomToResultAfterSolve.Name = "chkZoomToResultAfterSolve";
this.chkZoomToResultAfterSolve.Size = new System.Drawing.Size(200, 24);
this.chkZoomToResultAfterSolve.TabIndex = 5;
this.chkZoomToResultAfterSolve.Text = "Zoom To Result After Solve";
//
// grpMessages
//
this.grpMessages.Controls.Add(this.rdoNoMessages);
this.grpMessages.Controls.Add(this.rdoErrors);
this.grpMessages.Controls.Add(this.rdoErrorsAndWarnings);
this.grpMessages.Controls.Add(this.rdoAllMessages);
this.grpMessages.Location = new System.Drawing.Point(16, 72);
this.grpMessages.Name = "grpMessages";
this.grpMessages.Size = new System.Drawing.Size(336, 120);
this.grpMessages.TabIndex = 6;
this.grpMessages.TabStop = false;
this.grpMessages.Text = "Messages";
//
// rdoNoMessages
//
this.rdoNoMessages.Location = new System.Drawing.Point(16, 88);
this.rdoNoMessages.Name = "rdoNoMessages";
this.rdoNoMessages.Size = new System.Drawing.Size(304, 24);
this.rdoNoMessages.TabIndex = 3;
this.rdoNoMessages.Text = "No Messages";
//
// rdoErrors
//
this.rdoErrors.Location = new System.Drawing.Point(16, 64);
this.rdoErrors.Name = "rdoErrors";
this.rdoErrors.Size = new System.Drawing.Size(304, 24);
this.rdoErrors.TabIndex = 2;
this.rdoErrors.Text = "Errors";
//
// rdoErrorsAndWarnings
//
this.rdoErrorsAndWarnings.Location = new System.Drawing.Point(16, 40);
this.rdoErrorsAndWarnings.Name = "rdoErrorsAndWarnings";
this.rdoErrorsAndWarnings.Size = new System.Drawing.Size(304, 24);
this.rdoErrorsAndWarnings.TabIndex = 1;
this.rdoErrorsAndWarnings.Text = "Errors and Warnings";
//
// rdoAllMessages
//
this.rdoAllMessages.Location = new System.Drawing.Point(16, 16);
this.rdoAllMessages.Name = "rdoAllMessages";
this.rdoAllMessages.Size = new System.Drawing.Size(304, 24);
this.rdoAllMessages.TabIndex = 0;
this.rdoAllMessages.Text = "All Messages";
//
// frmNAProperties
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(370, 262);
this.Controls.Add(this.grpMessages);
this.Controls.Add(this.chkZoomToResultAfterSolve);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOK);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "frmNAProperties";
this.ShowInTaskbar = false;
this.Text = "Network Analyst Properties";
this.grpMessages.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
public void ShowModal()
{
m_okClicked = false;
var naEnv = CommonFunctions.GetTheEngineNetworkAnalystEnvironment();
if (naEnv == null)
{
System.Windows.Forms.MessageBox.Show("Error: EngineNetworkAnalystEnvironment is not properly configured");
return;
}
// Zoom to result after solve or not
chkZoomToResultAfterSolve.Checked = naEnv.ZoomToResultAfterSolve;
// Set the radio button based on the value in ShowAnalysisMessagesAfterSolve.
// This is a bit property where multiple values are possible.
// Simplify it for the user so assume message types build on each other.
// For example, if you want info, you probably want warnings and errors too
// No Messages = 0
// Errors = esriEngineNAMessageTypeError
// Errors and warnings = esriEngineNAMessageTypeError & esriEngineNAMessageTypeWarning
// All = esriEngineNAMessageTypeError & esriEngineNAMessageTypeWarning & esriEngineNAMessageTypeInformative
if ((esriEngineNAMessageType)(naEnv.ShowAnalysisMessagesAfterSolve & (int)esriEngineNAMessageType.esriEngineNAMessageTypeInformative) == esriEngineNAMessageType.esriEngineNAMessageTypeInformative)
rdoAllMessages.Checked = true;
else if ((esriEngineNAMessageType)(naEnv.ShowAnalysisMessagesAfterSolve & (int)esriEngineNAMessageType.esriEngineNAMessageTypeWarning) == esriEngineNAMessageType.esriEngineNAMessageTypeWarning)
rdoErrorsAndWarnings.Checked = true;
else if ((esriEngineNAMessageType)(naEnv.ShowAnalysisMessagesAfterSolve & (int)esriEngineNAMessageType.esriEngineNAMessageTypeError) == esriEngineNAMessageType.esriEngineNAMessageTypeError)
rdoErrors.Checked = true;
else
rdoNoMessages.Checked = true;
this.ShowDialog();
if (m_okClicked)
{
// Set ZoomToResultAfterSolve
naEnv.ZoomToResultAfterSolve = chkZoomToResultAfterSolve.Checked;
// Set ShowAnalysisMessagesAfterSolve
// Use simplified version so higher severity errors also show lower severity "info" and "warnings"
if (rdoAllMessages.Checked)
naEnv.ShowAnalysisMessagesAfterSolve = (int)esriEngineNAMessageType.esriEngineNAMessageTypeInformative + (int)esriEngineNAMessageType.esriEngineNAMessageTypeWarning + (int)esriEngineNAMessageType.esriEngineNAMessageTypeError;
else if (rdoErrorsAndWarnings.Checked)
naEnv.ShowAnalysisMessagesAfterSolve = (int)esriEngineNAMessageType.esriEngineNAMessageTypeWarning + (int)esriEngineNAMessageType.esriEngineNAMessageTypeError;
else if (rdoErrors.Checked)
naEnv.ShowAnalysisMessagesAfterSolve = (int)esriEngineNAMessageType.esriEngineNAMessageTypeError;
else
naEnv.ShowAnalysisMessagesAfterSolve = 0;
}
}
private void btnOK_Click(object sender, System.EventArgs e)
{
m_okClicked = true;
this.Close();
}
private void btnCancel_Click(object sender, System.EventArgs e)
{
m_okClicked = false;
this.Close();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
using Dokan;
namespace DokanSSHFS
{
public partial class SettingForm : Form
{
private SSHFS sshfs;
private DokanOptions opt;
private Settings settings = new Settings();
private int selectedIndex = 0;
private Thread dokan;
private bool isUnmounted_ = false;
public SettingForm()
{
InitializeComponent();
}
private void SettingForm_Load(object sender, EventArgs e)
{
FormBorderStyle = FormBorderStyle.FixedSingle;
//notifyIcon1.Icon = SystemIcons.Application;
notifyIcon1.Visible = true;
SettingLoad();
}
private void open_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
privatekey.Text = openFileDialog1.FileName;
}
}
private void usePassword_CheckedChanged(object sender, EventArgs e)
{
if (usePassword.Checked)
{
usePrivateKey.Checked = false;
privatekey.Enabled = false;
passphrase.Enabled = false;
password.Enabled = true;
open.Enabled = false;
}
}
private void usePrivateKey_CheckedChanged(object sender, EventArgs e)
{
if (usePrivateKey.Checked)
{
usePassword.Checked = false;
privatekey.Enabled = true;
passphrase.Enabled = true;
password.Enabled = false;
open.Enabled = true;
}
}
private void cancel_Click(object sender, EventArgs e)
{
notifyIcon1.Visible = false;
Application.Exit();
}
private void connect_Click(object sender, EventArgs e)
{
this.Hide();
int p = 22;
sshfs = new SSHFS();
opt = new DokanOptions();
opt.DebugMode = DokanSSHFS.DokanDebug;
opt.UseAltStream = true;
opt.MountPoint = "n:\\";
opt.ThreadCount = 0;
opt.UseKeepAlive = true;
string message = "";
if (host.Text == "")
message += "Host name is empty\n";
if (user.Text == "")
message += "User name is empty\n";
if (port.Text == "")
message += "Port is empty\n";
else
{
try
{
p = Int32.Parse(port.Text);
}
catch(Exception)
{
message += "Port format error\n";
}
}
if (drive.Text.Length != 1)
{
message += "Drive letter is invalid\n";
}
else
{
char letter = drive.Text[0];
letter = Char.ToLower(letter);
if (!('e' <= letter && letter <= 'z'))
message += "Drive letter is invalid\n";
opt.MountPoint = string.Format("{0}:\\", letter);
unmount.Text = "Unmount (" + opt.MountPoint + ")";
}
opt.ThreadCount = DokanSSHFS.DokanThread;
if (message.Length != 0)
{
this.Show();
MessageBox.Show(message, "Error");
return;
}
DokanSSHFS.UseOffline = !withoutOfflineAttribute.Checked;
sshfs.Initialize(
user.Text,
host.Text,
p,
usePrivateKey.Checked ? null : password.Text,
usePrivateKey.Checked ? privatekey.Text : null,
usePrivateKey.Checked ? passphrase.Text : null,
useHttpProxy.Checked ? proxyHost.Text : null,
useHttpProxy.Checked ? int.Parse(proxyPort.Text) : 0,
useProxyAuth.Checked ? proxyUser.Text : null,
useProxyAuth.Checked ? proxyPasswd.Text : null,
root.Text,
DokanSSHFS.SSHDebug);
if (sshfs.SSHConnect())
{
unmount.Visible = true;
mount.Visible = false;
isUnmounted_ = false;
MountWorker worker = null;
if (disableCache.Checked)
{
worker = new MountWorker(sshfs, opt);
}
else
{
worker = new MountWorker(new CacheOperations(sshfs), opt);
}
dokan = new Thread(worker.Start);
dokan.Start();
}
else
{
this.Show();
MessageBox.Show("failed to connect", "Error");
return;
}
MessageBox.Show("sshfs start", "info");
}
private void Unmount()
{
if (opt != null && sshfs != null)
{
Debug.WriteLine(string.Format("SSHFS Trying unmount : {0}", opt.MountPoint));
if (DokanNet.DokanRemoveMountPoint(opt.MountPoint) < 0)
{
Debug.WriteLine("DokanReveMountPoint failed\n");
// If DokanUmount failed, call sshfs.Unmount to disconnect.
;// sshfs.Unmount(null);
}
else
{
Debug.WriteLine("DokanReveMountPoint success\n");
}
// This should be called from Dokan, but not called.
// Call here explicitly.
sshfs.Unmount(null);
}
unmount.Visible = false;
mount.Visible = true;
}
class MountWorker
{
private DokanOperations sshfs_;
private DokanOptions opt_;
public MountWorker(DokanOperations sshfs, DokanOptions opt)
{
sshfs_ = sshfs;
opt_ = opt;
}
public void Start()
{
System.IO.Directory.SetCurrentDirectory(Application.StartupPath);
int ret = DokanNet.DokanMain(opt_, sshfs_);
if (ret < 0)
{
string msg = "Dokan Error";
switch (ret)
{
case DokanNet.DOKAN_ERROR:
msg = "Dokan Error";
break;
case DokanNet.DOKAN_DRIVE_LETTER_ERROR:
msg = "Dokan drive letter error";
break;
case DokanNet.DOKAN_DRIVER_INSTALL_ERROR:
msg = "Dokan driver install error";
break;
case DokanNet.DOKAN_MOUNT_ERROR:
msg = "Dokan drive letter assign error";
break;
case DokanNet.DOKAN_START_ERROR:
msg = "Dokan driver error ,please reboot";
break;
}
MessageBox.Show(msg, "Error");
Application.Exit();
}
Debug.WriteLine("DokanNet.Main end");
}
}
private void exit_Click(object sender, EventArgs e)
{
notifyIcon1.Visible = false;
if (!isUnmounted_)
{
Debug.WriteLine("unmount is visible");
unmount.Visible = false;
Unmount();
isUnmounted_ = true;
}
Debug.WriteLine("SSHFS Thread Waitting");
if (dokan != null && dokan.IsAlive)
{
Debug.WriteLine("doka.Join");
dokan.Join();
}
Debug.WriteLine("SSHFS Thread End");
Application.Exit();
}
private void unmount_Click(object sender, EventArgs e)
{
Debug.WriteLine("unmount_Click");
this.Unmount();
isUnmounted_ = true;
}
private void save_Click(object sender, EventArgs e)
{
Setting s = settings[selectedIndex];
s.Name = settingNames.Text;
if (settingNames.Text == "New Setting")
s.Name = settings.GetNewName();
s.Host = host.Text;
s.User = user.Text;
try
{
s.Port = Int32.Parse(port.Text);
}
catch (Exception)
{
s.Port = 22;
}
s.PrivateKey = privatekey.Text;
s.UsePassword = usePassword.Checked;
s.Drive = drive.Text;
s.ServerRoot = root.Text;
s.DisableCache = disableCache.Checked;
s.WithoutOfflineAttribute = withoutOfflineAttribute.Checked;
s.UseHttpProxy = useHttpProxy.Checked;
s.ProxyHost = proxyHost.Text;
try
{
s.ProxyPort = Int32.Parse(proxyPort.Text);
}
catch (Exception)
{
s.ProxyPort = 0;
}
s.UseProxyAuth = useProxyAuth.Checked;
s.ProxyUser = proxyUser.Text;
s.ProxyPassword = proxyPasswd.Text;
settings.Save();
SettingLoad();
SettingLoad(selectedIndex);
}
private void settingNames_SelectedIndexChanged(object sender, EventArgs e)
{
selectedIndex = settingNames.SelectedIndex;
SettingLoad(settingNames.SelectedIndex);
}
private void SettingLoad(int index)
{
Setting s = settings[index];
host.Text = s.Host;
user.Text = s.User;
port.Text = s.Port.ToString();
privatekey.Text = s.PrivateKey;
password.Text = "";
usePassword.Checked = s.UsePassword;
usePrivateKey.Checked = !s.UsePassword;
usePassword_CheckedChanged(null, null);
usePrivateKey_CheckedChanged(null, null);
useHttpProxy.Checked = s.UseHttpProxy;
proxyHost.Text = s.ProxyHost;
proxyPort.Text = s.ProxyPort.ToString();
useProxyAuth.Checked = s.UseProxyAuth;
proxyUser.Text = s.ProxyUser;
proxyPasswd.Text = s.ProxyPassword;
disableCache.Checked = s.DisableCache;
withoutOfflineAttribute.Checked = s.WithoutOfflineAttribute;
drive.Text = s.Drive;
root.Text = s.ServerRoot;
}
private void SettingLoad()
{
settings.Load();
settingNames.Items.Clear();
int count = settings.Count;
for (int i = 0; i < count; ++i)
{
settingNames.Items.Add(settings[i].Name);
}
settingNames.Items.Add("New Setting");
settingNames.SelectedIndex = 0;
SettingLoad(0);
}
private void delete_Click(object sender, EventArgs e)
{
settings.Delete(selectedIndex);
settings.Save();
SettingLoad();
}
private void mount_Click(object sender, EventArgs e)
{
unmount.Visible = false;
this.Show();
}
private void useHttpProxy_CheckedChanged(object sender, EventArgs e)
{
if (useHttpProxy.Checked)
{
useProxyAuth.Enabled = true;
proxyHost.Enabled = true;
proxyPort.Enabled = true;
}
else
{
useProxyAuth.Enabled = false;
proxyHost.Enabled = false;
proxyPort.Enabled = false;
}
}
private void useProxyAuth_CheckedChanged(object sender, EventArgs e)
{
if (useProxyAuth.Checked)
{
proxyUser.Enabled = true;
proxyPasswd.Enabled = true;
}
else
{
proxyUser.Enabled = false;
proxyPasswd.Enabled = false;
}
}
}
}
| |
using System;
using System.IO;
using System.Collections;
using System.Web;
using NHibernate;
using NHibernate.Cfg;
using Business;
namespace Business
{
/// <summary>
/// Summary description for NHibernateHttpModule.
/// </summary>
public class NHibernateHttpModule : IHttpModule
{
// this is only used if not running in HttpModule mode
protected static ISessionFactory m_factory;
// this is only used if not running in HttpModule mode
private static ISession m_session;
private static readonly string KEY_NHIBERNATE_FACTORY = "NHibernateSessionFactory";
private static readonly string KEY_NHIBERNATE_SESSION = "NHibernateSession";
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
context.EndRequest += new EventHandler(context_EndRequest);
}
public void Dispose()
{
if (m_session!=null)
{
m_session.Close();
m_session.Dispose();
}
if (m_factory!=null)
{
m_factory.Close();
}
}
private void context_BeginRequest (object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
context.Items[KEY_NHIBERNATE_SESSION] = CreateSession();
}
private void context_EndRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
ISession session = context.Items[KEY_NHIBERNATE_SESSION] as ISession;
if (session != null)
{
try
{
session.Flush();
session.Close();
}
catch {}
}
context.Items[KEY_NHIBERNATE_SESSION] = null;
}
public static ISessionFactory CreateSessionFactory()
{
Configuration config;
ISessionFactory factory;
HttpContext currentContext = HttpContext.Current;
cAppConfig oApp;
Utility oUtil = new Utility();
config = new NHibernate.Cfg.Configuration();
if (HttpContext.Current == null)
{
oApp = new cAppConfig(ConfigFileType.AppConfig) ;
config.SetProperty("hibernate.connection.connection_string", oApp.GetValue("hibernate.connection.connection_string"));
}
else
{
oApp = new cAppConfig(ConfigFileType.WebConfig) ;
// string strDesEnc = oUtil.Decrypt(oApp.GetValue("hibernate.connection.connection_string"));
config.SetProperty("hibernate.connection.connection_string", oApp.GetValue("hibernate.connection.connection_string"));
}
if (config == null)
{
throw new InvalidOperationException("NHibernate configuration is null.");
}
if (HttpContext.Current==null)
config.SetProperty("hibernate.connection.connection_string",oApp.GetValue("hibernate.connection.connection_string"));
config.AddAssembly("Business");
factory = config.BuildSessionFactory();
if (currentContext != null) currentContext.Items[KEY_NHIBERNATE_FACTORY] = factory;
if (factory==null)
throw new InvalidOperationException("Call to Configuration.BuildSessionFactory() returned null.");
else
return factory;
}
public static ISessionFactory CreateSessionFactory(IDictionary dir)
{
Configuration config;
ISessionFactory factory;
HttpContext currentContext = HttpContext.Current;
config = new Configuration();
if (config==null) throw new InvalidOperationException("NHibernate configuration is null.");
config.AddAssembly("Business");
factory = config.BuildSessionFactory();
if (currentContext != null)
currentContext.Items[KEY_NHIBERNATE_FACTORY] = factory;
if (factory==null)
throw new InvalidOperationException("Call to Configuration.BuildSessionFactory() returned null.");
else
return factory;
}
public static ISessionFactory CurrentFactory
{
get
{
if (HttpContext.Current==null)
{
// Corriendo sin HttpContext (Modo No-web)
if (m_factory!=null)
return m_factory;
else
{
m_factory = CreateSessionFactory();
return m_factory;
}
}
else
{
// Corriendo con HttpContext (Modo Web)
HttpContext currentContext = HttpContext.Current;
ISessionFactory factory = currentContext.Application[KEY_NHIBERNATE_FACTORY] as ISessionFactory;
if (factory == null)
{
factory = CreateSessionFactory();
currentContext.Application[KEY_NHIBERNATE_FACTORY] = factory;
}
return factory;
}
}
}
public static ISession CreateSession()
{
ISessionFactory factory;
ISession session;
factory = NHibernateHttpModule.CurrentFactory;
if (factory==null) throw new InvalidOperationException("Call to Configuration.BuildSessionFactory() returned null.");
session = factory.OpenSession();
session.FlushMode = FlushMode.Auto;
if (session==null) throw new InvalidOperationException("Call to factory.OpenSession() returned null.");
return session;
}
public static ISession CreateSession(string strSource)
{
if (! File.Exists(strSource)) throw new Exception("La Base de Datos Original fue Removida") ;
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strSource;
Configuration config = new Configuration();
config.SetProperty("hibernate.connection.connection_string",connString);
config.AddAssembly("Business");
return config.BuildSessionFactory().OpenSession();
}
public static ISession CurrentSession
{
get
{
if (HttpContext.Current==null)
{
// Corriendo sin HttpContext (Modo No-web)
if (m_session!=null)
{
if (! m_session.IsConnected) m_session.Reconnect();
m_session.FlushMode = FlushMode.Auto;
return m_session;
}
else
{
m_session = CreateSession();
m_session.FlushMode = FlushMode.Auto;
return m_session;
}
}
else
{
// Corriendo con HttpContext (Modo Web)
HttpContext currentContext = HttpContext.Current;
ISession session = currentContext.Items[KEY_NHIBERNATE_SESSION] as ISession;
if (session == null)
{
session = CreateSession();
currentContext.Items[KEY_NHIBERNATE_SESSION] = session;
}
return session;
}
}
}
public static void ResetSessionFactory()
{
Configuration config;
HttpContext currentContext = HttpContext.Current;
cAppConfig oApp = new cAppConfig(ConfigFileType.AppConfig) ;
config = new NHibernate.Cfg.Configuration();
config.SetProperty("hibernate.connection.connection_string", oApp.GetValue("hibernate.connection.connection_string"));
config.AddAssembly("Business");
NHibernateHttpModule.m_factory = config.BuildSessionFactory();
NHibernateHttpModule.m_session = NHibernateHttpModule.m_factory.OpenSession();
if (NHibernateHttpModule.m_factory == null)
throw new InvalidOperationException("Call to Configuration.BuildSessionFactory() returned null.");
}
public static void CloseSession()
{
if (m_session != null)
if (m_session.IsOpen) m_session.Close();
}
}
}
| |
// 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 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Analytics
{
using Azure;
using DataLake;
using Management;
using Azure;
using Management;
using DataLake;
using Models;
using Rest;
using Rest.Azure;
using Rest.Azure.OData;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// StorageAccountsOperations operations.
/// </summary>
public partial interface IStorageAccountsOperations
{
/// <summary>
/// Gets the specified Azure Storage account linked to the given Data
/// Lake Analytics account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account from which to retrieve
/// Azure storage account details.
/// </param>
/// <param name='storageAccountName'>
/// The name of the Azure Storage account for which to retrieve the
/// details.
/// </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<StorageAccountInfo>> GetWithHttpMessagesAsync(string resourceGroupName, string accountName, string storageAccountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the specified Data Lake Analytics account to remove an
/// Azure Storage account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account from which to remove
/// the Azure Storage account.
/// </param>
/// <param name='storageAccountName'>
/// The name of the Azure Storage account to remove
/// </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> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, string storageAccountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the Data Lake Analytics account to replace Azure Storage
/// blob account details, such as the access key and/or suffix.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account to modify storage
/// accounts in
/// </param>
/// <param name='storageAccountName'>
/// The Azure Storage account to modify
/// </param>
/// <param name='parameters'>
/// The parameters containing the access key and suffix to update the
/// storage account with, if any. Passing nothing results in no change.
/// </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> UpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, string storageAccountName, UpdateStorageAccountParameters parameters = default(UpdateStorageAccountParameters), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the specified Data Lake Analytics account to add an Azure
/// Storage account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account to which to add the
/// Azure Storage account.
/// </param>
/// <param name='storageAccountName'>
/// The name of the Azure Storage account to add
/// </param>
/// <param name='parameters'>
/// The parameters containing the access key and optional suffix for
/// the Azure Storage Account.
/// </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> AddWithHttpMessagesAsync(string resourceGroupName, string accountName, string storageAccountName, AddStorageAccountParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified Azure Storage container associated with the
/// given Data Lake Analytics and Azure Storage accounts.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account for which to retrieve
/// blob container.
/// </param>
/// <param name='storageAccountName'>
/// The name of the Azure storage account from which to retrieve the
/// blob container.
/// </param>
/// <param name='containerName'>
/// The name of the Azure storage container to retrieve
/// </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<StorageContainer>> GetStorageContainerWithHttpMessagesAsync(string resourceGroupName, string accountName, string storageAccountName, string containerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the Azure Storage containers, if any, associated with the
/// specified Data Lake Analytics and Azure Storage account
/// combination. The response includes a link to the next page of
/// results, if any.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account for which to list Azure
/// Storage blob containers.
/// </param>
/// <param name='storageAccountName'>
/// The name of the Azure storage account from which to list blob
/// containers.
/// </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<StorageContainer>>> ListStorageContainersWithHttpMessagesAsync(string resourceGroupName, string accountName, string storageAccountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the SAS token associated with the specified Data Lake
/// Analytics and Azure Storage account and container combination.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account from which an Azure
/// Storage account's SAS token is being requested.
/// </param>
/// <param name='storageAccountName'>
/// The name of the Azure storage account for which the SAS token is
/// being requested.
/// </param>
/// <param name='containerName'>
/// The name of the Azure storage container for which the SAS token is
/// being requested.
/// </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<SasTokenInfo>>> ListSasTokensWithHttpMessagesAsync(string resourceGroupName, string accountName, string storageAccountName, string containerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the first page of Azure Storage accounts, if any, linked to
/// the specified Data Lake Analytics account. The response includes a
/// link to the next page, if any.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account for which to list Azure
/// Storage accounts.
/// </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='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<StorageAccountInfo>>> ListByAccountWithHttpMessagesAsync(string resourceGroupName, string accountName, ODataQuery<StorageAccountInfo> odataQuery = default(ODataQuery<StorageAccountInfo>), string select = default(string), bool? count = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the Azure Storage containers, if any, associated with the
/// specified Data Lake Analytics and Azure Storage account
/// combination. 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<StorageContainer>>> ListStorageContainersNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the SAS token associated with the specified Data Lake
/// Analytics and Azure Storage account and container combination.
/// </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<SasTokenInfo>>> ListSasTokensNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the first page of Azure Storage accounts, if any, linked to
/// the specified Data Lake Analytics account. The response includes a
/// link to the next page, 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<StorageAccountInfo>>> ListByAccountNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
/*
* Copyright 2012-2021 The Pkcs11Interop Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <[email protected]>
*/
using System;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.LowLevelAPI81;
using NUnit.Framework;
using NativeULong = System.UInt64;
// Note: Code in this file is generated automatically.
namespace Net.Pkcs11Interop.Tests.LowLevelAPI81
{
/// <summary>
/// Object attributes tests.
/// </summary>
[TestFixture()]
public class _14_ObjectAttributeTest
{
/// <summary>
/// Attribute with empty value test.
/// </summary>
[Test()]
public void _01_EmptyAttributeTest()
{
Helpers.CheckPlatform();
// Create attribute without the value
CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_CLASS);
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_CLASS));
Assert.IsTrue(attr.value == IntPtr.Zero);
Assert.IsTrue(attr.valueLen == 0);
}
/// <summary>
/// Attribute with NativeULong value test.
/// </summary>
[Test()]
public void _02_UintAttributeTest()
{
Helpers.CheckPlatform();
NativeULong originalValue = ConvertUtils.UInt64FromCKO(CKO.CKO_DATA);
// Create attribute with NativeULong value
CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_CLASS, originalValue);
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_CLASS));
Assert.IsTrue(attr.value != IntPtr.Zero);
Assert.IsTrue(attr.valueLen == ConvertUtils.UInt64FromInt32(UnmanagedMemory.SizeOf(typeof(NativeULong))));
NativeULong recoveredValue = 0;
// Read the value of attribute
CkaUtils.ConvertValue(ref attr, out recoveredValue);
Assert.IsTrue(originalValue == recoveredValue);
// Free attribute value
UnmanagedMemory.Free(ref attr.value);
attr.valueLen = 0;
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_CLASS));
Assert.IsTrue(attr.value == IntPtr.Zero);
Assert.IsTrue(attr.valueLen == 0);
}
/// <summary>
/// Attribute with bool value test.
/// </summary>
[Test()]
public void _03_BoolAttributeTest()
{
Helpers.CheckPlatform();
bool originalValue = true;
// Create attribute with bool value
CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, originalValue);
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_TOKEN));
Assert.IsTrue(attr.value != IntPtr.Zero);
Assert.IsTrue(attr.valueLen == 1);
bool recoveredValue = false;
// Read the value of attribute
CkaUtils.ConvertValue(ref attr, out recoveredValue);
Assert.IsTrue(originalValue == recoveredValue);
// Free attribute value
UnmanagedMemory.Free(ref attr.value);
attr.valueLen = 0;
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_TOKEN));
Assert.IsTrue(attr.value == IntPtr.Zero);
Assert.IsTrue(attr.valueLen == 0);
}
/// <summary>
/// Attribute with string value test.
/// </summary>
[Test()]
public void _04_StringAttributeTest()
{
Helpers.CheckPlatform();
string originalValue = "Hello world";
// Create attribute with string value
CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_LABEL, originalValue);
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_LABEL));
Assert.IsTrue(attr.value != IntPtr.Zero);
Assert.IsTrue(attr.valueLen == ConvertUtils.UInt64FromInt32(originalValue.Length));
string recoveredValue = null;
// Read the value of attribute
CkaUtils.ConvertValue(ref attr, out recoveredValue);
Assert.IsTrue(originalValue == recoveredValue);
// Free attribute value
UnmanagedMemory.Free(ref attr.value);
attr.valueLen = 0;
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_LABEL));
Assert.IsTrue(attr.value == IntPtr.Zero);
Assert.IsTrue(attr.valueLen == 0);
// Create attribute with null string value
attr = CkaUtils.CreateAttribute(CKA.CKA_LABEL, (string)null);
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_LABEL));
Assert.IsTrue(attr.value == IntPtr.Zero);
Assert.IsTrue(attr.valueLen == 0);
}
/// <summary>
/// Attribute with byte array value test.
/// </summary>
[Test()]
public void _05_ByteArrayAttributeTest()
{
Helpers.CheckPlatform();
byte[] originalValue = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 };
// Create attribute with byte array value
CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_ID, originalValue);
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_ID));
Assert.IsTrue(attr.value != IntPtr.Zero);
Assert.IsTrue(attr.valueLen == ConvertUtils.UInt64FromInt32(originalValue.Length));
byte[] recoveredValue = null;
// Read the value of attribute
CkaUtils.ConvertValue(ref attr, out recoveredValue);
Assert.IsTrue(ConvertUtils.BytesToBase64String(originalValue) == ConvertUtils.BytesToBase64String(recoveredValue));
// Free attribute value
UnmanagedMemory.Free(ref attr.value);
attr.valueLen = 0;
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_ID));
Assert.IsTrue(attr.value == IntPtr.Zero);
Assert.IsTrue(attr.valueLen == 0);
// Create attribute with null byte array value
attr = CkaUtils.CreateAttribute(CKA.CKA_ID, (byte[])null);
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_ID));
Assert.IsTrue(attr.value == IntPtr.Zero);
Assert.IsTrue(attr.valueLen == 0);
}
/// <summary>
/// Attribute with DateTime (CKA_DATE) value test.
/// </summary>
[Test()]
public void _06_DateTimeAttributeTest()
{
Helpers.CheckPlatform();
DateTime originalValue = new DateTime(2012, 1, 30, 0, 0, 0, DateTimeKind.Utc);
// Create attribute with DateTime value
CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_START_DATE, originalValue);
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_START_DATE));
Assert.IsTrue(attr.value != IntPtr.Zero);
Assert.IsTrue(attr.valueLen == 8);
DateTime? recoveredValue = null;
// Read the value of attribute
CkaUtils.ConvertValue(ref attr, out recoveredValue);
Assert.IsTrue(originalValue == recoveredValue);
// Free attribute value
UnmanagedMemory.Free(ref attr.value);
attr.valueLen = 0;
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_START_DATE));
Assert.IsTrue(attr.value == IntPtr.Zero);
Assert.IsTrue(attr.valueLen == 0);
}
/// <summary>
/// Attribute with attribute array value test.
/// </summary>
[Test()]
public void _07_AttributeArrayAttributeTest()
{
Helpers.CheckPlatform();
CK_ATTRIBUTE[] originalValue = new CK_ATTRIBUTE[2];
originalValue[0] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true);
originalValue[1] = CkaUtils.CreateAttribute(CKA.CKA_PRIVATE, true);
// Create attribute with attribute array value
CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_WRAP_TEMPLATE, originalValue);
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_WRAP_TEMPLATE));
Assert.IsTrue(attr.value != IntPtr.Zero);
Assert.IsTrue(attr.valueLen == ConvertUtils.UInt64FromInt32(UnmanagedMemory.SizeOf(typeof(CK_ATTRIBUTE)) * originalValue.Length));
CK_ATTRIBUTE[] recoveredValue = null;
// Read the value of attribute
CkaUtils.ConvertValue(ref attr, out recoveredValue);
Assert.IsTrue(originalValue.Length == recoveredValue.Length);
for (int i = 0; i < recoveredValue.Length; i++)
{
Assert.IsTrue(originalValue[i].type == recoveredValue[i].type);
Assert.IsTrue(originalValue[i].valueLen == recoveredValue[i].valueLen);
bool originalBool = false;
// Read the value of nested attribute
CkaUtils.ConvertValue(ref originalValue[i], out originalBool);
bool recoveredBool = true;
// Read the value of nested attribute
CkaUtils.ConvertValue(ref recoveredValue[i], out recoveredBool);
Assert.IsTrue(originalBool == recoveredBool);
// In this example there is the same pointer to unmanaged memory
// in both originalValue and recoveredValue array therefore it
// needs to be freed only once.
Assert.IsTrue(originalValue[i].value == recoveredValue[i].value);
// Free value of nested attributes
UnmanagedMemory.Free(ref originalValue[i].value);
originalValue[i].valueLen = 0;
recoveredValue[i].value = IntPtr.Zero;
recoveredValue[i].valueLen = 0;
}
// Free attribute value
UnmanagedMemory.Free(ref attr.value);
attr.valueLen = 0;
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_WRAP_TEMPLATE));
Assert.IsTrue(attr.value == IntPtr.Zero);
Assert.IsTrue(attr.valueLen == 0);
// Create attribute with null attribute array value
attr = CkaUtils.CreateAttribute(CKA.CKA_WRAP_TEMPLATE, (CK_ATTRIBUTE[])null);
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_WRAP_TEMPLATE));
Assert.IsTrue(attr.value == IntPtr.Zero);
Assert.IsTrue(attr.valueLen == 0);
// Create attribute with empty attribute array value
attr = CkaUtils.CreateAttribute(CKA.CKA_WRAP_TEMPLATE, new CK_ATTRIBUTE[0]);
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_WRAP_TEMPLATE));
Assert.IsTrue(attr.value == IntPtr.Zero);
Assert.IsTrue(attr.valueLen == 0);
}
/// <summary>
/// Attribute with NativeULong array value test.
/// </summary>
[Test()]
public void _08_UintArrayAttributeTest()
{
Helpers.CheckPlatform();
NativeULong[] originalValue = new NativeULong[2];
originalValue[0] = 333333;
originalValue[1] = 666666;
// Create attribute with NativeULong array value
CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue);
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_ALLOWED_MECHANISMS));
Assert.IsTrue(attr.value != IntPtr.Zero);
Assert.IsTrue(attr.valueLen == ConvertUtils.UInt64FromInt32(UnmanagedMemory.SizeOf(typeof(NativeULong)) * originalValue.Length));
NativeULong[] recoveredValue = null;
// Read the value of attribute
CkaUtils.ConvertValue(ref attr, out recoveredValue);
Assert.IsTrue(originalValue.Length == recoveredValue.Length);
for (int i = 0; i < recoveredValue.Length; i++)
{
Assert.IsTrue(originalValue[i] == recoveredValue[i]);
}
// Free attribute value
UnmanagedMemory.Free(ref attr.value);
attr.valueLen = 0;
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_ALLOWED_MECHANISMS));
Assert.IsTrue(attr.value == IntPtr.Zero);
Assert.IsTrue(attr.valueLen == 0);
// Create attribute with null NativeULong array value
attr = CkaUtils.CreateAttribute(CKA.CKA_ALLOWED_MECHANISMS, (NativeULong[])null);
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_ALLOWED_MECHANISMS));
Assert.IsTrue(attr.value == IntPtr.Zero);
Assert.IsTrue(attr.valueLen == 0);
// Create attribute with empty NativeULong array value
attr = CkaUtils.CreateAttribute(CKA.CKA_ALLOWED_MECHANISMS, new NativeULong[0]);
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_ALLOWED_MECHANISMS));
Assert.IsTrue(attr.value == IntPtr.Zero);
Assert.IsTrue(attr.valueLen == 0);
}
/// <summary>
/// Attribute with mechanism array value test.
/// </summary>
[Test()]
public void _09_MechanismArrayAttributeTest()
{
Helpers.CheckPlatform();
CKM[] originalValue = new CKM[2];
originalValue[0] = CKM.CKM_RSA_PKCS;
originalValue[1] = CKM.CKM_AES_CBC;
// Create attribute with mechanism array value
CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue);
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_ALLOWED_MECHANISMS));
Assert.IsTrue(attr.value != IntPtr.Zero);
Assert.IsTrue(attr.valueLen == ConvertUtils.UInt64FromInt32(UnmanagedMemory.SizeOf(typeof(NativeULong)) * originalValue.Length));
CKM[] recoveredValue = null;
// Read the value of attribute
CkaUtils.ConvertValue(ref attr, out recoveredValue);
Assert.IsTrue(originalValue.Length == recoveredValue.Length);
for (int i = 0; i < recoveredValue.Length; i++)
{
Assert.IsTrue(originalValue[i] == recoveredValue[i]);
}
// Free attribute value
UnmanagedMemory.Free(ref attr.value);
attr.valueLen = 0;
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_ALLOWED_MECHANISMS));
Assert.IsTrue(attr.value == IntPtr.Zero);
Assert.IsTrue(attr.valueLen == 0);
// Create attribute with null mechanism array value
attr = CkaUtils.CreateAttribute(CKA.CKA_ALLOWED_MECHANISMS, (CKM[])null);
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_ALLOWED_MECHANISMS));
Assert.IsTrue(attr.value == IntPtr.Zero);
Assert.IsTrue(attr.valueLen == 0);
// Create attribute with empty mechanism array value
attr = CkaUtils.CreateAttribute(CKA.CKA_ALLOWED_MECHANISMS, new CKM[0]);
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_ALLOWED_MECHANISMS));
Assert.IsTrue(attr.value == IntPtr.Zero);
Assert.IsTrue(attr.valueLen == 0);
}
/// <summary>
/// Custom attribute with manually set value test.
/// </summary>
[Test()]
public void _10_CustomAttributeTest()
{
Helpers.CheckPlatform();
byte[] originalValue = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 };
// Create attribute without the value
CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_VALUE);
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_VALUE));
Assert.IsTrue(attr.value == IntPtr.Zero);
Assert.IsTrue(attr.valueLen == 0);
// Allocate unmanaged memory for attribute value..
attr.value = UnmanagedMemory.Allocate(originalValue.Length);
// ..then set the value of attribute..
UnmanagedMemory.Write(attr.value, originalValue);
// ..and finally set the length of attribute value.
attr.valueLen = ConvertUtils.UInt64FromInt32(originalValue.Length);
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_VALUE));
Assert.IsTrue(attr.value != IntPtr.Zero);
Assert.IsTrue(attr.valueLen == ConvertUtils.UInt64FromInt32(originalValue.Length));
// Read the value of attribute
byte[] recoveredValue = UnmanagedMemory.Read(attr.value, ConvertUtils.UInt64ToInt32(attr.valueLen));
Assert.IsTrue(ConvertUtils.BytesToBase64String(originalValue) == ConvertUtils.BytesToBase64String(recoveredValue));
// Free attribute value
UnmanagedMemory.Free(ref attr.value);
attr.valueLen = 0;
Assert.IsTrue(attr.type == ConvertUtils.UInt64FromCKA(CKA.CKA_VALUE));
Assert.IsTrue(attr.value == IntPtr.Zero);
Assert.IsTrue(attr.valueLen == 0);
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
namespace EduHub.Data.Entities
{
/// <summary>
/// Student Trips
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class STTRIPS : EduHubEntity
{
#region Navigation Property Cache
private ST Cache_STUDENT_ID_ST;
private TRPROUT Cache_AM_ROUTE_ID_TRPROUT;
private TRPMODE Cache_AM_TRANSPORT_MODE_TRPMODE;
private UM Cache_AM_PICKUP_ADDRESS_ID_UM;
private SCI Cache_AM_SETDOWN_CAMPUS_SCI;
private TRPROUT Cache_PM_ROUTE_ID_TRPROUT;
private TRPMODE Cache_PM_TRANSPORT_MODE_TRPMODE;
private SCI Cache_PM_PICKUP_CAMPUS_SCI;
private UM Cache_PM_SETDOWN_ADDRESS_ID_UM;
#endregion
/// <inheritdoc />
public override DateTime? EntityLastModified
{
get
{
return LW_DATE;
}
}
#region Field Properties
/// <summary>
/// Sequence
/// </summary>
public int TID { get; internal set; }
/// <summary>
/// Student key
/// [Uppercase Alphanumeric (10)]
/// </summary>
public string STUDENT_ID { get; internal set; }
/// <summary>
/// Transport route valid from
/// </summary>
public DateTime? TRANSPORT_START_DATE { get; internal set; }
/// <summary>
/// Transport route valid to
/// </summary>
public DateTime? TRANSPORT_END_DATE { get; internal set; }
/// <summary>
/// Does the student travel in a wheelchair
/// [Alphanumeric (1)]
/// </summary>
public string TRAVEL_IN_WHEELCHAIR { get; internal set; }
/// <summary>
/// Day of travel
/// [Alphanumeric (2)]
/// </summary>
public string TRAVEL_DAY { get; internal set; }
/// <summary>
/// General notes regarding travel
/// [Memo]
/// </summary>
public string TRAVEL_NOTES { get; internal set; }
/// <summary>
/// AM Route ID
/// </summary>
public int? AM_ROUTE_ID { get; internal set; }
/// <summary>
/// AM mode of transport
/// </summary>
public int? AM_TRANSPORT_MODE { get; internal set; }
/// <summary>
/// Does this student use this am route throught the week
/// [Alphanumeric (1)]
/// </summary>
public string AM_ROUTE_EVERY_DAY { get; internal set; }
/// <summary>
/// AM pickup time
/// </summary>
public short? AM_PICKUP_TIME { get; internal set; }
/// <summary>
/// AM pickup address
/// </summary>
public int? AM_PICKUP_ADDRESS_ID { get; internal set; }
/// <summary>
/// Is the AM pickup address the home address
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string AM_PICKUP_ADD_SAME_AS_HOME { get; internal set; }
/// <summary>
/// AM Direction of travel (N,NE,E,SE,S,SW,W,NW)
/// [Alphanumeric (2)]
/// </summary>
public string AM_PICKUP_DIRECTIONS { get; internal set; }
/// <summary>
/// <No documentation available>
/// [Alphanumeric (1)]
/// </summary>
public string AM_PICKUP_ADD_MAP_TYPE { get; internal set; }
/// <summary>
/// <No documentation available>
/// [Alphanumeric (4)]
/// </summary>
public string AM_PICKUP_ADD_MAP_NO { get; internal set; }
/// <summary>
/// <No documentation available>
/// [Alphanumeric (4)]
/// </summary>
public string AM_PICKUP_ADD_MAP_X_REF { get; internal set; }
/// <summary>
/// <No documentation available>
/// [Memo]
/// </summary>
public string AM_PICKUP_ADD_DESCP { get; internal set; }
/// <summary>
/// <No documentation available>
/// </summary>
public short? AM_SETDOWN_TIME { get; internal set; }
/// <summary>
/// <No documentation available>
/// </summary>
public int? AM_SETDOWN_CAMPUS { get; internal set; }
/// <summary>
/// <No documentation available>
/// </summary>
public int? PM_ROUTE_ID { get; internal set; }
/// <summary>
/// <No documentation available>
/// </summary>
public int? PM_TRANSPORT_MODE { get; internal set; }
/// <summary>
/// <No documentation available>
/// [Alphanumeric (1)]
/// </summary>
public string PM_ROUTE_EVERY_DAY { get; internal set; }
/// <summary>
/// <No documentation available>
/// </summary>
public short? PM_PICKUP_TIME { get; internal set; }
/// <summary>
/// <No documentation available>
/// </summary>
public int? PM_PICKUP_CAMPUS { get; internal set; }
/// <summary>
/// <No documentation available>
/// </summary>
public short? PM_SETDOWN_TIME { get; internal set; }
/// <summary>
/// <No documentation available>
/// </summary>
public int? PM_SETDOWN_ADDRESS_ID { get; internal set; }
/// <summary>
/// <No documentation available>
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string PM_STDWN_AM_PKUP_ADD_SAME { get; internal set; }
/// <summary>
/// <No documentation available>
/// [Alphanumeric (2)]
/// </summary>
public string PM_SETDOWN_DIRECTIONS { get; internal set; }
/// <summary>
/// <No documentation available>
/// [Alphanumeric (1)]
/// </summary>
public string PM_SETDOWN_ADD_MAP_TYPE { get; internal set; }
/// <summary>
/// <No documentation available>
/// [Alphanumeric (4)]
/// </summary>
public string PM_SETDOWN_ADD_MAP_NO { get; internal set; }
/// <summary>
/// <No documentation available>
/// [Alphanumeric (4)]
/// </summary>
public string PM_SETDOWN_ADD_MAP_X_REF { get; internal set; }
/// <summary>
/// <No documentation available>
/// [Memo]
/// </summary>
public string PM_SETDOWN_ADD_DESCP { get; internal set; }
/// <summary>
/// Last write date
/// </summary>
public DateTime? LW_DATE { get; internal set; }
/// <summary>
/// Last write time
/// </summary>
public short? LW_TIME { get; internal set; }
/// <summary>
/// Last write operator
/// [Uppercase Alphanumeric (128)]
/// </summary>
public string LW_USER { get; internal set; }
#endregion
#region Navigation Properties
/// <summary>
/// ST (Students) related entity by [STTRIPS.STUDENT_ID]->[ST.STKEY]
/// Student key
/// </summary>
public ST STUDENT_ID_ST
{
get
{
if (Cache_STUDENT_ID_ST == null)
{
Cache_STUDENT_ID_ST = Context.ST.FindBySTKEY(STUDENT_ID);
}
return Cache_STUDENT_ID_ST;
}
}
/// <summary>
/// TRPROUT (Student Transport Routes) related entity by [STTRIPS.AM_ROUTE_ID]->[TRPROUT.ROUTE_ID]
/// AM Route ID
/// </summary>
public TRPROUT AM_ROUTE_ID_TRPROUT
{
get
{
if (AM_ROUTE_ID == null)
{
return null;
}
if (Cache_AM_ROUTE_ID_TRPROUT == null)
{
Cache_AM_ROUTE_ID_TRPROUT = Context.TRPROUT.FindByROUTE_ID(AM_ROUTE_ID.Value);
}
return Cache_AM_ROUTE_ID_TRPROUT;
}
}
/// <summary>
/// TRPMODE (Transport Modes) related entity by [STTRIPS.AM_TRANSPORT_MODE]->[TRPMODE.TRANSPORT_MODE_ID]
/// AM mode of transport
/// </summary>
public TRPMODE AM_TRANSPORT_MODE_TRPMODE
{
get
{
if (AM_TRANSPORT_MODE == null)
{
return null;
}
if (Cache_AM_TRANSPORT_MODE_TRPMODE == null)
{
Cache_AM_TRANSPORT_MODE_TRPMODE = Context.TRPMODE.FindByTRANSPORT_MODE_ID(AM_TRANSPORT_MODE.Value);
}
return Cache_AM_TRANSPORT_MODE_TRPMODE;
}
}
/// <summary>
/// UM (Addresses) related entity by [STTRIPS.AM_PICKUP_ADDRESS_ID]->[UM.UMKEY]
/// AM pickup address
/// </summary>
public UM AM_PICKUP_ADDRESS_ID_UM
{
get
{
if (AM_PICKUP_ADDRESS_ID == null)
{
return null;
}
if (Cache_AM_PICKUP_ADDRESS_ID_UM == null)
{
Cache_AM_PICKUP_ADDRESS_ID_UM = Context.UM.FindByUMKEY(AM_PICKUP_ADDRESS_ID.Value);
}
return Cache_AM_PICKUP_ADDRESS_ID_UM;
}
}
/// <summary>
/// SCI (School Information) related entity by [STTRIPS.AM_SETDOWN_CAMPUS]->[SCI.SCIKEY]
/// <No documentation available>
/// </summary>
public SCI AM_SETDOWN_CAMPUS_SCI
{
get
{
if (AM_SETDOWN_CAMPUS == null)
{
return null;
}
if (Cache_AM_SETDOWN_CAMPUS_SCI == null)
{
Cache_AM_SETDOWN_CAMPUS_SCI = Context.SCI.FindBySCIKEY(AM_SETDOWN_CAMPUS.Value);
}
return Cache_AM_SETDOWN_CAMPUS_SCI;
}
}
/// <summary>
/// TRPROUT (Student Transport Routes) related entity by [STTRIPS.PM_ROUTE_ID]->[TRPROUT.ROUTE_ID]
/// <No documentation available>
/// </summary>
public TRPROUT PM_ROUTE_ID_TRPROUT
{
get
{
if (PM_ROUTE_ID == null)
{
return null;
}
if (Cache_PM_ROUTE_ID_TRPROUT == null)
{
Cache_PM_ROUTE_ID_TRPROUT = Context.TRPROUT.FindByROUTE_ID(PM_ROUTE_ID.Value);
}
return Cache_PM_ROUTE_ID_TRPROUT;
}
}
/// <summary>
/// TRPMODE (Transport Modes) related entity by [STTRIPS.PM_TRANSPORT_MODE]->[TRPMODE.TRANSPORT_MODE_ID]
/// <No documentation available>
/// </summary>
public TRPMODE PM_TRANSPORT_MODE_TRPMODE
{
get
{
if (PM_TRANSPORT_MODE == null)
{
return null;
}
if (Cache_PM_TRANSPORT_MODE_TRPMODE == null)
{
Cache_PM_TRANSPORT_MODE_TRPMODE = Context.TRPMODE.FindByTRANSPORT_MODE_ID(PM_TRANSPORT_MODE.Value);
}
return Cache_PM_TRANSPORT_MODE_TRPMODE;
}
}
/// <summary>
/// SCI (School Information) related entity by [STTRIPS.PM_PICKUP_CAMPUS]->[SCI.SCIKEY]
/// <No documentation available>
/// </summary>
public SCI PM_PICKUP_CAMPUS_SCI
{
get
{
if (PM_PICKUP_CAMPUS == null)
{
return null;
}
if (Cache_PM_PICKUP_CAMPUS_SCI == null)
{
Cache_PM_PICKUP_CAMPUS_SCI = Context.SCI.FindBySCIKEY(PM_PICKUP_CAMPUS.Value);
}
return Cache_PM_PICKUP_CAMPUS_SCI;
}
}
/// <summary>
/// UM (Addresses) related entity by [STTRIPS.PM_SETDOWN_ADDRESS_ID]->[UM.UMKEY]
/// <No documentation available>
/// </summary>
public UM PM_SETDOWN_ADDRESS_ID_UM
{
get
{
if (PM_SETDOWN_ADDRESS_ID == null)
{
return null;
}
if (Cache_PM_SETDOWN_ADDRESS_ID_UM == null)
{
Cache_PM_SETDOWN_ADDRESS_ID_UM = Context.UM.FindByUMKEY(PM_SETDOWN_ADDRESS_ID.Value);
}
return Cache_PM_SETDOWN_ADDRESS_ID_UM;
}
}
#endregion
}
}
| |
/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* 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.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
namespace Alphaleonis.Win32.Filesystem
{
/// <summary>Provides the base class for both <see cref="FileInfo"/> and <see cref="DirectoryInfo"/> objects.</summary>
[Serializable]
[ComVisible(true)]
public abstract class FileSystemInfo : MarshalByRefObject, IEquatable<FileSystemInfo>
{
#region Fields
#region .NET
/// <summary>Represents the fully qualified path of the file or directory.</summary>
/// <remarks>
/// <para>Classes derived from <see cref="FileSystemInfo"/> can use the FullPath field</para>
/// <para>to determine the full path of the object being manipulated.</para>
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
protected string FullPath;
/// <summary>The path originally specified by the user, whether relative or absolute.</summary>
[SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
protected string OriginalPath;
#endregion // .NET
// We use this field in conjunction with the Refresh methods, if we succeed we store a zero,
// on failure we store the HResult in it so that we can give back a generic error back.
[NonSerialized] internal int DataInitialised = -1;
// The pre-cached FileSystemInfo information.
[NonSerialized] internal NativeMethods.WIN32_FILE_ATTRIBUTE_DATA Win32AttributeData;
#endregion // Fields
#region Properties
#region .NET
/// <summary>Gets or sets the attributes for the current file or directory.</summary>
/// <remarks>
/// <para>The value of the CreationTime property is pre-cached</para>
/// <para>To get the latest value, call the Refresh method.</para>
/// </remarks>
/// <value><see cref="FileAttributes"/> of the current <see cref="FileSystemInfo"/>.</value>
///
/// <exception cref="FileNotFoundException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
public FileAttributes Attributes
{
[SecurityCritical]
get
{
if (DataInitialised == -1)
{
Win32AttributeData = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA();
Refresh();
}
// MSDN: .NET 3.5+: IOException: Refresh cannot initialize the data.
if (DataInitialised != 0)
NativeError.ThrowException(DataInitialised, FullPath);
return Win32AttributeData.dwFileAttributes;
}
[SecurityCritical]
set
{
File.SetAttributesCore(Transaction, IsDirectory, LongFullName, value, PathFormat.LongFullPath);
Reset();
}
}
/// <summary>Gets or sets the creation time of the current file or directory.</summary>
/// <remarks>
/// <para>The value of the CreationTime property is pre-cached To get the latest value, call the Refresh method.</para>
/// <para>This method may return an inaccurate value, because it uses native functions whose values may not be continuously updated by
/// the operating system.</para>
/// <para>If the file described in the FileSystemInfo object does not exist, this property will return
/// 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time.</para>
/// <para>NTFS-formatted drives may cache file meta-info, such as file creation time, for a short period of time.
/// This process is known as file tunneling. As a result, it may be necessary to explicitly set the creation time of a file if you are
/// overwriting or replacing an existing file.</para>
/// </remarks>
/// <value>The creation date and time of the current <see cref="FileSystemInfo"/> object.</value>
///
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
public DateTime CreationTime
{
[SecurityCritical] get { return CreationTimeUtc.ToLocalTime(); }
[SecurityCritical] set { CreationTimeUtc = value.ToUniversalTime(); }
}
/// <summary>Gets or sets the creation time, in coordinated universal time (UTC), of the current file or directory.</summary>
/// <remarks>
/// <para>The value of the CreationTimeUtc property is pre-cached
/// To get the latest value, call the Refresh method.</para>
/// <para>This method may return an inaccurate value, because it uses native functions
/// whose values may not be continuously updated by the operating system.</para>
/// <para>To get the latest value, call the Refresh method.</para>
/// <para>If the file described in the FileSystemInfo object does not exist, this property will return
/// 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC).</para>
/// <para>NTFS-formatted drives may cache file meta-info, such as file creation time, for a short period of time.
/// This process is known as file tunneling. As a result, it may be necessary to explicitly set the creation time
/// of a file if you are overwriting or replacing an existing file.</para>
/// </remarks>
/// <value>The creation date and time in UTC format of the current <see cref="FileSystemInfo"/> object.</value>
///
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
[ComVisible(false)]
public DateTime CreationTimeUtc
{
[SecurityCritical]
get
{
if (DataInitialised == -1)
{
Win32AttributeData = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA();
Refresh();
}
// MSDN: .NET 3.5+: IOException: Refresh cannot initialize the data.
if (DataInitialised != 0)
NativeError.ThrowException(DataInitialised, LongFullName);
return DateTime.FromFileTimeUtc(Win32AttributeData.ftCreationTime);
}
[SecurityCritical]
set
{
File.SetFsoDateTimeCore(Transaction, IsDirectory, LongFullName, value, null, null, false, PathFormat.LongFullPath);
Reset();
}
}
/// <summary>Gets a value indicating whether the file or directory exists.</summary>
/// <remarks>
/// <para>The <see cref="Exists"/> property returns <c>false</c> if any error occurs while trying to determine if the
/// specified file or directory exists.</para>
/// <para>This can occur in situations that raise exceptions such as passing a directory- or file name with invalid characters or too
/// many characters,</para>
/// <para>a failing or missing disk, or if the caller does not have permission to read the file or directory.</para>
/// </remarks>
/// <value><c>true</c> if the file or directory exists; otherwise, <c>false</c>.</value>
public abstract bool Exists { get; }
/// <summary>Gets the string representing the extension part of the file.</summary>
/// <remarks>
/// The Extension property returns the <see cref="FileSystemInfo"/> extension, including the period (.).
/// For example, for a file c:\NewFile.txt, this property returns ".txt".
/// </remarks>
/// <value>A string containing the <see cref="FileSystemInfo"/> extension.</value>
public string Extension
{
get { return Path.GetExtension(FullPath, false); }
}
/// <summary>Gets the full path of the directory or file.</summary>
/// <value>A string containing the full path.</value>
public virtual string FullName
{
[SecurityCritical] get { return FullPath; }
}
/// <summary>Gets or sets the time the current file or directory was last accessed.</summary>
/// <remarks>
/// <para>The value of the LastAccessTime property is pre-cached
/// To get the latest value, call the Refresh method.</para>
/// <para>This method may return an inaccurate value, because it uses native functions
/// whose values may not be continuously updated by the operating system.</para>
/// <para>If the file described in the FileSystemInfo object does not exist, this property will return
/// 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time.</para>
/// </remarks>
/// <value>The time that the current file or directory was last accessed.</value>
///
/// <exception cref="IOException"/>
public DateTime LastAccessTime
{
[SecurityCritical] get { return LastAccessTimeUtc.ToLocalTime(); }
[SecurityCritical] set { LastAccessTimeUtc = value.ToUniversalTime(); }
}
/// <summary>Gets or sets the time, in coordinated universal time (UTC), that the current file or directory was last accessed.</summary>
/// <remarks>
/// <para>The value of the LastAccessTimeUtc property is pre-cached.
/// To get the latest value, call the Refresh method.</para>
/// <para>This method may return an inaccurate value, because it uses native functions
/// whose values may not be continuously updated by the operating system.</para>
/// <para>If the file described in the FileSystemInfo object does not exist, this property will return
/// 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time.</para>
/// </remarks>
/// <value>The UTC time that the current file or directory was last accessed.</value>
///
/// <exception cref="IOException"/>
[ComVisible(false)]
public DateTime LastAccessTimeUtc
{
[SecurityCritical]
get
{
if (DataInitialised == -1)
{
Win32AttributeData = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA();
Refresh();
}
// MSDN: .NET 3.5+: IOException: Refresh cannot initialize the data.
if (DataInitialised != 0)
NativeError.ThrowException(DataInitialised, LongFullName);
return DateTime.FromFileTimeUtc(Win32AttributeData.ftLastAccessTime);
}
[SecurityCritical]
set
{
File.SetFsoDateTimeCore(Transaction, IsDirectory, LongFullName, null, value, null, false, PathFormat.LongFullPath);
Reset();
}
}
/// <summary>Gets or sets the time when the current file or directory was last written to.</summary>
/// <remarks>
/// <para>The value of the LastWriteTime property is pre-cached.
/// To get the latest value, call the Refresh method.</para>
/// <para>This method may return an inaccurate value, because it uses native functions
/// whose values may not be continuously updated by the operating system.</para>
/// <para>If the file described in the FileSystemInfo object does not exist, this property will return
/// 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time.</para>
/// </remarks>
/// <value>The time the current file was last written.</value>
///
/// <exception cref="IOException"/>
public DateTime LastWriteTime
{
get { return LastWriteTimeUtc.ToLocalTime(); }
set { LastWriteTimeUtc = value.ToUniversalTime(); }
}
/// <summary>Gets or sets the time, in coordinated universal time (UTC), when the current file or directory was last written to.</summary>
/// <remarks>
/// <para>The value of the LastWriteTimeUtc property is pre-cached. To get the latest value, call the Refresh method.</para>
/// <para>This method may return an inaccurate value, because it uses native functions whose values may not be continuously updated by
/// the operating system.</para>
/// <para>If the file described in the FileSystemInfo object does not exist, this property will return 12:00 midnight, January 1, 1601
/// A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time.</para>
/// </remarks>
/// <value>The UTC time when the current file was last written to.</value>
[ComVisible(false)]
public DateTime LastWriteTimeUtc
{
[SecurityCritical]
get
{
if (DataInitialised == -1)
{
Win32AttributeData = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA();
Refresh();
}
// MSDN: .NET 3.5+: IOException: Refresh cannot initialize the data.
if (DataInitialised != 0)
NativeError.ThrowException(DataInitialised, LongFullName);
return DateTime.FromFileTimeUtc(Win32AttributeData.ftLastWriteTime);
}
[SecurityCritical]
set
{
File.SetFsoDateTimeCore(Transaction, IsDirectory, LongFullName, null, null, value, false, PathFormat.LongFullPath);
Reset();
}
}
/// <summary>
/// For files, gets the name of the file. For directories, gets the name of the last directory in the hierarchy if a hierarchy exists.
/// <para>Otherwise, the Name property gets the name of the directory.</para>
/// </summary>
/// <remarks>
/// <para>For a directory, Name returns only the name of the parent directory, such as Dir, not c:\Dir.</para>
/// <para>For a subdirectory, Name returns only the name of the subdirectory, such as Sub1, not c:\Dir\Sub1.</para>
/// <para>For a file, Name returns only the file name and file name extension, such as MyFile.txt, not c:\Dir\Myfile.txt.</para>
/// </remarks>
/// <value>
/// <para>A string that is the name of the parent directory, the name of the last directory in the hierarchy,</para>
/// <para>or the name of a file, including the file name extension.</para>
/// </value>
public abstract string Name { get; }
#endregion // .NET
#region AlphaFS
/// <summary>Returns the path as a string.</summary>
protected internal string DisplayPath { get; protected set; }
private FileSystemEntryInfo _entryInfo;
/// <summary>[AlphaFS] Gets the instance of the <see cref="FileSystemEntryInfo"/> class.</summary>
public FileSystemEntryInfo EntryInfo
{
[SecurityCritical]
get
{
if (null == _entryInfo)
{
Win32AttributeData = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA();
RefreshEntryInfo();
}
// MSDN: .NET 3.5+: IOException: Refresh cannot initialize the data.
if (DataInitialised > 0)
NativeError.ThrowException(DataInitialised, LongFullName);
return _entryInfo;
}
internal set
{
_entryInfo = value;
DataInitialised = value == null ? -1 : 0;
if (DataInitialised == 0 && null != _entryInfo)
Win32AttributeData = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(_entryInfo.Win32FindData);
}
}
/// <summary>[AlphaFS] The initial "IsDirectory" indicator that was passed to the constructor.</summary>
protected bool IsDirectory { get; set; }
/// <summary>The full path of the file system object in Unicode (LongPath) format.</summary>
protected string LongFullName { get; set; }
/// <summary>[AlphaFS] Represents the KernelTransaction that was passed to the constructor.</summary>
protected KernelTransaction Transaction { get; set; }
#endregion // AlphaFS
#endregion // Properties
#region Methods
#region .NET
/// <summary>Deletes a file or directory.</summary>
[SecurityCritical]
public abstract void Delete();
/// <summary>Refreshes the state of the object.</summary>
/// <remarks>
/// <para>FileSystemInfo.Refresh() takes a snapshot of the file from the current file system.</para>
/// <para>Refresh cannot correct the underlying file system even if the file system returns incorrect or outdated information.</para>
/// <para>This can happen on platforms such as Windows 98.</para>
/// <para>Calls must be made to Refresh() before attempting to get the attribute information, or the information will be
/// outdated.</para>
/// </remarks>
[SecurityCritical]
public void Refresh()
{
DataInitialised = File.FillAttributeInfoCore(Transaction, LongFullName, ref Win32AttributeData, false, false);
IsDirectory = File.IsDirectory(Win32AttributeData.dwFileAttributes);
}
/// <summary>Returns a string that represents the current object.</summary>
/// <remarks>
/// ToString is the major formatting method in the .NET Framework. It converts an object to its string representation so that it is
/// suitable for display.
/// </remarks>
/// <returns>A string that represents this instance.</returns>
public override string ToString()
{
// "Alphaleonis.Win32.Filesystem.FileSystemInfo"
return GetType().ToString();
}
/// <summary>Serves as a hash function for a particular type.</summary>
/// <returns>A hash code for the current Object.</returns>
public override int GetHashCode()
{
return null != FullName ? FullName.GetHashCode() : 0;
}
/// <summary>Determines whether the specified Object is equal to the current Object.</summary>
/// <param name="other">Another <see cref="FileSystemInfo"/> instance to compare to.</param>
/// <returns><c>true</c> if the specified Object is equal to the current Object; otherwise, <c>false</c>.</returns>
public bool Equals(FileSystemInfo other)
{
return null != other && GetType() == other.GetType() &&
Equals(Name, other.Name) &&
Equals(FullName, other.FullName) &&
Equals(Attributes, other.Attributes) &&
Equals(CreationTimeUtc, other.CreationTimeUtc) &&
Equals(LastAccessTimeUtc, other.LastAccessTimeUtc);
}
/// <summary>Determines whether the specified Object is equal to the current Object.</summary>
/// <param name="obj">Another object to compare to.</param>
/// <returns><c>true</c> if the specified Object is equal to the current Object; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
{
var other = obj as FileSystemInfo;
return null != other && Equals(other);
}
/// <summary>Implements the operator ==</summary>
/// <param name="left">A.</param>
/// <param name="right">B.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(FileSystemInfo left, FileSystemInfo right)
{
return ReferenceEquals(left, null) && ReferenceEquals(right, null) ||
!ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right);
}
/// <summary>Implements the operator !=</summary>
/// <param name="left">A.</param>
/// <param name="right">B.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(FileSystemInfo left, FileSystemInfo right)
{
return !(left == right);
}
#endregion // .NET
/// <summary>[AlphaFS] Refreshes the current <see cref="FileSystemInfo"/> instance (<see cref="DirectoryInfo"/> or <see cref="FileInfo"/>) with a new destination path.</summary>
internal void UpdateSourcePath(string destinationPath, string destinationPathLp)
{
LongFullName = destinationPathLp;
FullPath = null != destinationPathLp ? Path.GetRegularPathCore(LongFullName, GetFullPathOptions.None, false) : null;
OriginalPath = destinationPath;
DisplayPath = null != OriginalPath ? Path.GetRegularPathCore(OriginalPath, GetFullPathOptions.None, false) : null;
// Flush any cached information about the FileSystemInfo instance.
Reset();
}
/// <summary>[AlphaFS] Refreshes the state of the <see cref="FileSystemEntryInfo"/> EntryInfo property.</summary>
/// <remarks>
/// <para>FileSystemInfo.RefreshEntryInfo() takes a snapshot of the file from the current file system.</para>
/// <para>Refresh cannot correct the underlying file system even if the file system returns incorrect or outdated information.</para>
/// <para>This can happen on platforms such as Windows 98.</para>
/// <para>Calls must be made to Refresh() before attempting to get the attribute information, or the information will be outdated.</para>
/// </remarks>
[SecurityCritical]
protected void RefreshEntryInfo()
{
_entryInfo = File.GetFileSystemEntryInfoCore(Transaction, IsDirectory, LongFullName, true, PathFormat.LongFullPath);
if (null == _entryInfo)
DataInitialised = -1;
else
{
DataInitialised = 0;
Win32AttributeData = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(_entryInfo.Win32FindData);
}
}
/// <summary>[AlphaFS] Resets the state of the file system object to uninitialized.</summary>
private void Reset()
{
DataInitialised = -1;
}
/// <summary>Initializes the specified file name.</summary>
/// <exception cref="ArgumentException"/>
/// <exception cref="NotSupportedException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="isFolder">Specifies that <paramref name="path"/> is a file or directory.</param>
/// <param name="path">The full path and name of the file.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
internal void InitializeCore(KernelTransaction transaction, bool isFolder, string path, PathFormat pathFormat)
{
if (pathFormat == PathFormat.RelativePath)
Path.CheckSupportedPathFormat(path, true, true);
LongFullName = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | (isFolder ? GetFullPathOptions.RemoveTrailingDirectorySeparator : 0) | GetFullPathOptions.ContinueOnNonExist);
// (Not on MSDN): .NET 4+ Trailing spaces are removed from the end of the path parameter before creating the FileSystemInfo instance.
FullPath = Path.GetRegularPathCore(LongFullName, GetFullPathOptions.None, false);
IsDirectory = isFolder;
Transaction = transaction;
OriginalPath = FullPath.Length == 2 && FullPath[1] == Path.VolumeSeparatorChar ? Path.CurrentDirectoryPrefix : path;
DisplayPath = OriginalPath.Length != 2 || OriginalPath[1] != Path.VolumeSeparatorChar ? Path.GetRegularPathCore(OriginalPath, GetFullPathOptions.None, false) : Path.CurrentDirectoryPrefix;
}
internal static SafeFindFileHandle FindFirstFileNative(KernelTransaction transaction, string pathLp, NativeMethods.FINDEX_INFO_LEVELS infoLevel, NativeMethods.FINDEX_SEARCH_OPS searchOption, NativeMethods.FIND_FIRST_EX_FLAGS additionalFlags, out int lastError, out NativeMethods.WIN32_FIND_DATA win32FindData)
{
var safeHandle = null == transaction || !NativeMethods.IsAtLeastWindowsVista
// FindFirstFileEx() / FindFirstFileTransacted()
// 2013-01-13: MSDN confirms LongPath usage.
// A trailing backslash is not allowed.
? NativeMethods.FindFirstFileEx(Path.RemoveTrailingDirectorySeparator(pathLp), infoLevel, out win32FindData, searchOption, IntPtr.Zero, additionalFlags)
: NativeMethods.FindFirstFileTransacted(Path.RemoveTrailingDirectorySeparator(pathLp), infoLevel, out win32FindData, searchOption, IntPtr.Zero, additionalFlags, transaction.SafeHandle);
lastError = Marshal.GetLastWin32Error();
if (!NativeMethods.IsValidHandle(safeHandle, false))
safeHandle = null;
return safeHandle;
}
#endregion // Methods
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms;
using System.Diagnostics;
using Project31.MindShare.CoreServices;
namespace Project31.ApplicationFramework
{
/// <summary>
/// Represents a command in the Project31.ApplicationFramework.
/// </summary>
[
DesignTimeVisible(false),
ToolboxItem(false)
]
public class CommandInstance : Component
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
/// <summary>
/// Menu bitmap for the enabled state.
/// </summary>
private CommandDefinition commandDefinition;
/// <summary>
/// Gets or sets the menu bitmap for the enabled state.
/// </summary>
[
Category("Appearance"),
Localizable(false),
DefaultValue(null),
Description("Specifies the menu bitmap for the enabled state.")
]
public Bitmap MenuBitmapEnabled
{
get
{
return menuBitmapEnabled;
}
set
{
menuBitmapEnabled = value;
}
}
/// <summary>
/// Menu bitmap for the disabled state.
/// </summary>
private Bitmap menuBitmapDisabled;
/// <summary>
/// Gets or sets the menu bitmap for the disabled state.
/// </summary>
[
Category("Appearance"),
Localizable(false),
DefaultValue(null),
Description("Specifies the menu bitmap for the disabled state.")
]
public Bitmap MenuBitmapDisabled
{
get
{
return menuBitmapDisabled;
}
set
{
menuBitmapDisabled = value;
}
}
/// <summary>
/// Menu bitmap for the selected state.
/// </summary>
private Bitmap menuBitmapSelected;
/// <summary>
/// Gets or sets the menu selected bitmap.
/// </summary>
[
Category("Appearance"),
Localizable(false),
DefaultValue(null),
Description("Specifies the menu bitmap for the selected state.")
]
public Bitmap MenuBitmapSelected
{
get
{
return menuBitmapSelected;
}
set
{
menuBitmapSelected = value;
}
}
/// <summary>
/// The menu shortcut of the command.
/// </summary>
private Shortcut menuShortcut;
/// <summary>
/// Gets or sets the menu shortcut of the command.
/// </summary>
[
Category("Behavior"),
DefaultValue(Shortcut.None),
Description("Specifies the menu shortcut of the command.")
]
public Shortcut MenuShortcut
{
get
{
return menuShortcut;
}
set
{
menuShortcut = value;
}
}
/// <summary>
/// A value indicating whether the menu shortcut should be shown for the command.
/// </summary>
private bool showMenuShortcut;
/// <summary>
/// Gets or sets a value indicating whether the menu shortcut should be shown for the command.
/// </summary>
[
Category("Behavior"),
DefaultValue(false),
Description("Specifies whether the menu shortcut should be shown for the command.")
]
public bool ShowMenuShortcut
{
get
{
return showMenuShortcut;
}
set
{
showMenuShortcut = value;
}
}
/// <summary>
/// The command text. This is the "user visible text" that is associate with the command
/// (such as "Save All"). It appears whenever the user can see text for the command.
/// </summary>
private string text;
/// <summary>
/// Gets or sets the command text.
/// </summary>
[
Category("Appearance"),
Localizable(true),
DefaultValue(null),
Description("Specifies the text that is associated with the command.")
]
public string Text
{
get
{
return text;
}
set
{
text = value;
}
}
/// <summary>
/// The command description. This is the "user visible description" that is associated
/// with the command. It appears whenever the user can see a description for the command.
/// </summary>
private string description;
/// <summary>
/// Gets or sets the command description.
/// </summary>
[
Category("Appearance"),
Localizable(true),
DefaultValue(null),
Description("Specifies the description for the command.")
]
public string Description
{
get
{
return description;
}
set
{
description = value;
}
}
/// <summary>
/// Command bar button bitmap for the disabled state.
/// </summary>
private Bitmap commandBarButtonBitmapDisabled;
/// <summary>
/// Gets or sets the command bar button bitmap for the disabled state.
/// </summary>
[
Category("Appearance"),
Localizable(true),
DefaultValue(null),
Description("Specifies the command bar button bitmap for the disabled state.")
]
public Bitmap CommandBarButtonBitmapDisabled
{
get
{
return commandBarButtonBitmapDisabled;
}
set
{
commandBarButtonBitmapDisabled = value;
}
}
/// <summary>
/// Command bar button bitmap for the enabled state.
/// </summary>
private Bitmap commandBarButtonBitmapEnabled;
/// <summary>
/// Gets or sets the command bar button bitmap for the enabled state.
/// </summary>
[
Category("Appearance"),
Localizable(true),
DefaultValue(null),
Description("Specifies the command bar button bitmap for the enabled state.")
]
public Bitmap CommandBarButtonBitmapEnabled
{
get
{
return commandBarButtonBitmapEnabled;
}
set
{
commandBarButtonBitmapEnabled = value;
}
}
/// <summary>
/// Command bar button bitmap for the pushed state.
/// </summary>
private Bitmap commandBarButtonBitmapPushed;
/// <summary>
/// Gets or sets the command bar button bitmap for the pushed state.
/// </summary>
[
Category("Appearance"),
Localizable(true),
DefaultValue(null),
Description("Specifies the command bar button bitmap for the pushed state.")
]
public Bitmap CommandBarButtonBitmapPushed
{
get
{
return commandBarButtonBitmapPushed;
}
set
{
commandBarButtonBitmapPushed = value;
}
}
/// <summary>
/// Command bar button bitmap for the rollover state.
/// </summary>
private Bitmap commandBarButtonBitmapRollover;
/// <summary>
/// Gets or sets the command bar button bitmap for the rollover state.
/// </summary>
[
Category("Appearance"),
Localizable(true),
DefaultValue(null),
Description("Specifies the command bar button bitmap for the rollover state.")
]
public Bitmap CommandBarButtonBitmapRollover
{
get
{
return commandBarButtonBitmapRollover;
}
set
{
commandBarButtonBitmapRollover = value;
}
}
/// <summary>
/// A value indicating whether the command is enabled or not (i.e. can respond to user interaction).
/// </summary>
private bool enabled = true;
/// <summary>
/// Gets or sets a value indicating whether the command is enabled or not (i.e. can respond to user interaction).
/// </summary>
[
Category("Behavior"),
DefaultValue(true),
Description("Specifies whether the command is enabled by default.")
]
public bool Enabled
{
get
{
return enabled;
}
set
{
// Set the value.
enabled = value;
// Fire the enabled changed event.
OnEnabledChanged(EventArgs.Empty);
}
}
/// <summary>
/// Occurs when the command is executed.
/// </summary>
[
Category("Action"),
Description("Occurs when the command is executed.")
]
public event EventHandler Execute;
/// <summary>
/// Occurs when the command's enabled state changes.
/// </summary>
[
Category("Property Changed"),
Description("Occurs when the command's enabled state changes.")
]
public event EventHandler EnabledChanged;
/// <summary>
/// Initializes a new instance of the Command class.
/// </summary>
/// <param name="container"></param>
public CommandDefinition(System.ComponentModel.IContainer container)
{
/// <summary>
/// Required for Windows.Forms Class Composition Designer support
/// </summary>
container.Add(this);
InitializeComponent();
}
/// <summary>
/// Initializes a new instance of the Command class.
/// </summary>
public CommandDefinition()
{
/// <summary>
/// Required for Windows.Forms Class Composition Designer support
/// </summary>
InitializeComponent();
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
/// <summary>
/// This method can be called to raise the Execute event
/// </summary>
public void PerformExecute()
{
Debug.Assert(Enabled, "Command is disabled.", "It is illogical to execute a command that is disabled.");
OnExecute(EventArgs.Empty);
}
/// <summary>
/// Raises the Execute event.
/// </summary>
protected void OnExecute(EventArgs e)
{
if (Execute != null)
Execute(this, e);
else
UnderConstructionForm.Show();
}
/// <summary>
/// Raises the EnabledChanged event.
/// </summary>
protected void OnEnabledChanged(EventArgs e)
{
if (EnabledChanged != null)
EnabledChanged(this, e);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Shouldly;
using Xunit;
namespace AutoMapper.UnitTests. BidirectionalRelationships
{
public class RecursiveMappingWithStruct : AutoMapperSpecBase
{
private ParentDto _dto;
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg =>
{
cfg.CreateMap<ParentModel, ParentDto>();
cfg.CreateMap<ChildModel, ChildDto>();
cfg.CreateMap<ChildrenStructModel, ChildrenStructDto>();
});
[Fact]
public void Should_work()
{
var parent = new ParentModel { ID = "PARENT_ONE" };
parent.ChildrenStruct = new ChildrenStructModel { Children = new List<ChildModel>() };
parent.AddChild(new ChildModel { ID = "CHILD_ONE" });
parent.AddChild(new ChildModel { ID = "CHILD_TWO" });
_dto = Mapper.Map<ParentModel, ParentDto>(parent);
_dto.ID.ShouldBe("PARENT_ONE");
_dto.ChildrenStruct.Children[0].ID.ShouldBe("CHILD_ONE");
_dto.ChildrenStruct.Children[1].ID.ShouldBe("CHILD_TWO");
}
public struct ParentModel
{
public string ID { get; set; }
public ChildrenStructModel ChildrenStruct { get; set; }
public void AddChild(ChildModel child)
{
child.Parent = this;
ChildrenStruct.Children.Add(child);
}
}
public struct ChildrenStructModel
{
public IList<ChildModel> Children { get; set; }
}
public struct ChildModel
{
public string ID { get; set; }
public ParentModel Parent { get; set; }
}
public struct ParentDto
{
public string ID { get; set; }
public ChildrenStructDto ChildrenStruct { get; set; }
}
public struct ChildrenStructDto
{
public IList<ChildDto> Children { get; set; }
}
public struct ChildDto
{
public string ID { get; set; }
public ParentDto Parent { get; set; }
}
}
public class When_mapping_to_a_destination_with_a_bidirectional_parent_one_to_many_child_relationship : AutoMapperSpecBase
{
private ParentDto _dto;
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg =>
{
cfg.CreateMap<ParentModel, ParentDto>().PreserveReferences();
cfg.CreateMap<ChildModel, ChildDto>();
});
protected override void Because_of()
{
var parent = new ParentModel { ID = "PARENT_ONE" };
parent.AddChild(new ChildModel { ID = "CHILD_ONE" });
parent.AddChild(new ChildModel { ID = "CHILD_TWO" });
_dto = Mapper.Map<ParentModel, ParentDto>(parent);
}
[Fact]
public void Should_preserve_the_parent_child_relationship_on_the_destination()
{
_dto.Children[0].Parent.ShouldBeSameAs(_dto);
_dto.Children[1].Parent.ShouldBeSameAs(_dto);
}
public class ParentModel
{
public ParentModel()
{
Children = new List<ChildModel>();
}
public string ID { get; set; }
public IList<ChildModel> Children { get; private set; }
public void AddChild(ChildModel child)
{
child.Parent = this;
Children.Add(child);
}
}
public class ChildModel
{
public string ID { get; set; }
public ParentModel Parent { get; set; }
}
public class ParentDto
{
public string ID { get; set; }
public IList<ChildDto> Children { get; set; }
}
public class ChildDto
{
public string ID { get; set; }
public ParentDto Parent { get; set; }
}
}
public class RecursiveDynamicMapping : AutoMapperSpecBase
{
private ParentDto<int> _dto;
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg =>
{
cfg.CreateMap(typeof(ParentModel<>), typeof(ParentDto<>));
cfg.CreateMap(typeof(ChildModel<>), typeof(ChildDto<>));
});
protected override void Because_of()
{
var parent = new ParentModel<int> { ID = "PARENT_ONE" };
parent.AddChild(new ChildModel<int> { ID = "CHILD_ONE" });
parent.AddChild(new ChildModel<int> { ID = "CHILD_TWO" });
_dto = Mapper.Map<ParentModel<int>, ParentDto<int>>(parent);
}
[Fact]
public void Should_preserve_the_parent_child_relationship_on_the_destination()
{
_dto.Children[0].Parent.ShouldBeSameAs(_dto);
_dto.Children[1].Parent.ShouldBeSameAs(_dto);
}
public class ParentModel<T>
{
public ParentModel()
{
Children = new List<ChildModel<T>>();
}
public string ID { get; set; }
public IList<ChildModel<T>> Children { get; private set; }
public void AddChild(ChildModel<T> child)
{
child.Parent = this;
Children.Add(child);
}
}
public class ChildModel<T>
{
public string ID { get; set; }
public ParentModel<T> Parent { get; set; }
}
public class ParentDto<T>
{
public string ID { get; set; }
public IList<ChildDto<T>> Children { get; set; }
}
public class ChildDto<T>
{
public string ID { get; set; }
public ParentDto<T> Parent { get; set; }
}
}
public class When_mapping_to_a_destination_with_a_bidirectional_parent_one_to_many_child_relationship_using_CustomMapper_with_context : AutoMapperSpecBase
{
private ParentDto _dto;
private static ParentModel _parent;
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
_parent = new ParentModel
{
ID = 2
};
List<ChildModel> childModels = new List<ChildModel>
{
new ChildModel
{
ID = 1,
Parent = _parent
}
};
Dictionary<int, ParentModel> parents = childModels.ToDictionary(x => x.ID, x => x.Parent);
cfg.CreateMap<int, ParentDto>().ConvertUsing(new ChildIdToParentDtoConverter(parents));
cfg.CreateMap<int, List<ChildDto>>().ConvertUsing(new ParentIdToChildDtoListConverter(childModels));
cfg.CreateMap<ParentModel, ParentDto>()
.PreserveReferences()
.ForMember(dest => dest.Children, opt => opt.MapFrom(src => src.ID));
cfg.CreateMap<ChildModel, ChildDto>();
});
protected override void Because_of()
{
_dto = Mapper.Map<ParentModel, ParentDto>(_parent);
}
[Fact]
public void Should_preserve_the_parent_child_relationship_on_the_destination()
{
_dto.Children[0].Parent.ID.ShouldBe(_dto.ID);
}
public class ChildIdToParentDtoConverter : ITypeConverter<int, ParentDto>
{
private readonly Dictionary<int, ParentModel> _parentModels;
public ChildIdToParentDtoConverter(Dictionary<int, ParentModel> parentModels)
{
_parentModels = parentModels;
}
public ParentDto Convert(int source, ParentDto destination, ResolutionContext resolutionContext)
{
ParentModel parentModel = _parentModels[source];
return (ParentDto) resolutionContext.Mapper.Map(parentModel, destination, typeof(ParentModel), typeof(ParentDto), resolutionContext);
}
}
public class ParentIdToChildDtoListConverter : ITypeConverter<int, List<ChildDto>>
{
private readonly IList<ChildModel> _childModels;
public ParentIdToChildDtoListConverter(IList<ChildModel> childModels)
{
_childModels = childModels;
}
public List<ChildDto> Convert(int source, List<ChildDto> destination, ResolutionContext resolutionContext)
{
List<ChildModel> childModels = _childModels.Where(x => x.Parent.ID == source).ToList();
return (List<ChildDto>)resolutionContext.Mapper.Map(childModels, destination, typeof(List<ChildModel>), typeof(List<ChildDto>), resolutionContext);
}
}
public class ParentModel
{
public int ID { get; set; }
}
public class ChildModel
{
public int ID { get; set; }
public ParentModel Parent { get; set; }
}
public class ParentDto
{
public int ID { get; set; }
public List<ChildDto> Children { get; set; }
}
public class ChildDto
{
public int ID { get; set; }
public ParentDto Parent { get; set; }
}
}
public class When_mapping_to_a_destination_with_a_bidirectional_parent_one_to_one_child_relationship : AutoMapperSpecBase
{
private FooDto _dto;
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Foo, FooDto>().PreserveReferences();
cfg.CreateMap<Bar, BarDto>();
});
protected override void Because_of()
{
var foo = new Foo
{
Bar = new Bar
{
Value = "something"
}
};
foo.Bar.Foo = foo;
_dto = Mapper.Map<Foo, FooDto>(foo);
}
[Fact]
public void Should_preserve_the_parent_child_relationship_on_the_destination()
{
_dto.Bar.Foo.ShouldBeSameAs(_dto);
}
public class Foo
{
public Bar Bar { get; set; }
}
public class Bar
{
public Foo Foo { get; set; }
public string Value { get; set; }
}
public class FooDto
{
public BarDto Bar { get; set; }
}
public class BarDto
{
public FooDto Foo { get; set; }
public string Value { get; set; }
}
}
public class When_mapping_to_a_destination_containing_two_dtos_mapped_from_the_same_source : AutoMapperSpecBase
{
private FooContainerModel _dto;
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<FooModel, FooScreenModel>();
cfg.CreateMap<FooModel, FooInputModel>();
cfg.CreateMap<FooModel, FooContainerModel>()
.PreserveReferences()
.ForMember(dest => dest.Input, opt => opt.MapFrom(src => src))
.ForMember(dest => dest.Screen, opt => opt.MapFrom(src => src));
});
protected override void Because_of()
{
var model = new FooModel { Id = 3 };
_dto = Mapper.Map<FooModel, FooContainerModel>(model);
}
[Fact]
public void Should_not_preserve_identity_when_destinations_are_incompatible()
{
_dto.ShouldBeOfType<FooContainerModel>();
_dto.Input.ShouldBeOfType<FooInputModel>();
_dto.Screen.ShouldBeOfType<FooScreenModel>();
_dto.Input.Id.ShouldBe(3);
_dto.Screen.Id.ShouldBe("3");
}
public class FooContainerModel
{
public FooInputModel Input { get; set; }
public FooScreenModel Screen { get; set; }
}
public class FooScreenModel
{
public string Id { get; set; }
}
public class FooInputModel
{
public long Id { get; set; }
}
public class FooModel
{
public long Id { get; set; }
}
}
public class When_mapping_with_a_bidirectional_relationship_that_includes_arrays : AutoMapperSpecBase
{
private ParentDto _dtoParent;
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Parent, ParentDto>().PreserveReferences();
cfg.CreateMap<Child, ChildDto>();
});
protected override void Because_of()
{
var parent1 = new Parent { Name = "Parent 1" };
var child1 = new Child { Name = "Child 1" };
parent1.Children.Add(child1);
child1.Parents.Add(parent1);
_dtoParent = Mapper.Map<Parent, ParentDto>(parent1);
}
[Fact]
public void Should_map_successfully()
{
object.ReferenceEquals(_dtoParent.Children[0].Parents[0], _dtoParent).ShouldBeTrue();
}
public class Parent
{
public Guid Id { get; private set; }
public string Name { get; set; }
public List<Child> Children { get; set; }
public Parent()
{
Id = Guid.NewGuid();
Children = new List<Child>();
}
public bool Equals(Parent other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return other.Id.Equals(Id);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (Parent)) return false;
return Equals((Parent) obj);
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
public class Child
{
public Guid Id { get; private set; }
public string Name { get; set; }
public List<Parent> Parents { get; set; }
public Child()
{
Id = Guid.NewGuid();
Parents = new List<Parent>();
}
public bool Equals(Child other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return other.Id.Equals(Id);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (Child)) return false;
return Equals((Child) obj);
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
public class ParentDto
{
public Guid Id { get; set; }
public string Name { get; set; }
public List<ChildDto> Children { get; set; }
public ParentDto()
{
Children = new List<ChildDto>();
}
}
public class ChildDto
{
public Guid Id { get; set; }
public string Name { get; set; }
public List<ParentDto> Parents { get; set; }
public ChildDto()
{
Parents = new List<ParentDto>();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using Loupe.Extensibility.Data;
namespace Gibraltar.Agent
{
/// <summary>Summary information about the current session.</summary>
/// <remarks>
/// <para>The session summary includes all of the information that is available to Loupe
/// to categorize the session. This includes the product,
/// application, and version information that was detected by Loupe (or overridden
/// in the application configuration) as well as a range of information about the
/// current computing environment (such as Operating System Family and process
/// architecture).</para>
/// <para>This information can be referenced at any time by your application.</para>
/// </remarks>
public sealed class SessionSummary
{
private readonly ISessionSummary m_WrappedISessionSummary;
private Monitor.SessionSummary m_WrappedSummary;
private readonly Dictionary<string, string> m_Properties;
/// <summary>
/// Create a new session summary as the live collection session for the current process
/// </summary>
/// <remarks>This constructor figures out all of the summary information when invoked, which can take a moment.</remarks>
internal SessionSummary(Monitor.SessionSummary summary)
{
m_WrappedSummary = summary;
m_Properties = new Dictionary<string, string>(summary.Properties);
}
/// <summary>
/// Create a new session summary as the live collection session for the current process
/// </summary>
/// <remarks>This constructor figures out all of the summary information when invoked, which can take a moment.</remarks>
internal SessionSummary(ISessionSummary summary)
{
m_WrappedISessionSummary = summary;
m_Properties = new Dictionary<string, string>(summary.Properties);
}
#region Public Properties and Methods
/// <summary>
/// The unique Id of the session
/// </summary>
public Guid Id => m_WrappedSummary != null ? m_WrappedSummary.Id : m_WrappedISessionSummary.Id;
/// <summary>
/// The display caption of the time zone where the session was recorded
/// </summary>
public string TimeZoneCaption => m_WrappedSummary != null ? m_WrappedSummary.TimeZoneCaption : m_WrappedISessionSummary.TimeZoneCaption;
/// <summary>
/// The date and time the session started
/// </summary>
public DateTimeOffset StartDateTime => m_WrappedSummary != null ? m_WrappedSummary.StartDateTime : m_WrappedISessionSummary.StartDateTime;
/// <summary>
/// The date and time the session ended or was last confirmed running
/// </summary>
public DateTimeOffset EndDateTime => m_WrappedSummary != null ? m_WrappedSummary.EndDateTime : m_WrappedISessionSummary.EndDateTime;
/// <summary>
/// The time range between the start and end of this session..
/// </summary>
public TimeSpan Duration => m_WrappedSummary != null ? m_WrappedSummary.Duration : m_WrappedISessionSummary.Duration;
/// <summary>
/// A display caption for the session
/// </summary>
public string Caption => m_WrappedSummary != null ? m_WrappedSummary.Caption : m_WrappedISessionSummary.Caption;
/// <summary>
/// The product name of the application that recorded the session.
/// </summary>
public string Product => m_WrappedSummary != null ? m_WrappedSummary.Product : m_WrappedISessionSummary.Product;
/// <summary>
/// The title of the application that recorded the session.
/// </summary>
public string Application => m_WrappedSummary != null ? m_WrappedSummary.Application : m_WrappedISessionSummary.Application;
/// <summary>
/// Optional. The environment this session is running in.
/// </summary>
/// <remarks>Environments are useful for categorizing sessions, for example to
/// indicate the hosting environment. If a value is provided it will be
/// carried with the session data to upstream servers and clients. If the
/// corresponding entry does not exist it will be automatically created.</remarks>
public string Environment => m_WrappedSummary != null ? m_WrappedSummary.Environment : m_WrappedISessionSummary.Environment;
/// <summary>
/// Optional. The promotion level of the session.
/// </summary>
/// <remarks>Promotion levels are useful for categorizing sessions, for example to
/// indicate whether it was run in development, staging, or production.
/// If a value is provided it will be carried with the session data to upstream servers and clients.
/// If the corresponding entry does not exist it will be automatically created.</remarks>
public string PromotionLevel => m_WrappedSummary != null ? m_WrappedSummary.PromotionLevel : m_WrappedISessionSummary.PromotionLevel;
/// <summary>
/// The type of process the application ran as.
/// </summary>
public ApplicationType ApplicationType => m_WrappedSummary != null ? (ApplicationType)m_WrappedSummary.ApplicationType : (ApplicationType)m_WrappedISessionSummary.ApplicationType;
/// <summary>
/// The description of the application from its manifest.
/// </summary>
public string ApplicationDescription => m_WrappedSummary != null ? m_WrappedSummary.ApplicationDescription : m_WrappedISessionSummary.ApplicationDescription;
/// <summary>
/// The version of the application that recorded the session
/// </summary>
public Version ApplicationVersion => m_WrappedSummary != null ? m_WrappedSummary.ApplicationVersion : m_WrappedISessionSummary.ApplicationVersion;
/// <summary>
/// The version of the Loupe Agent used to monitor the session
/// </summary>
public Version AgentVersion => m_WrappedSummary != null ? m_WrappedSummary.AgentVersion : m_WrappedISessionSummary.AgentVersion;
/// <summary>
/// The host name / NetBIOS name of the computer that recorded the session
/// </summary>
/// <remarks>Does not include the domain name portion of the fully qualified DNS name.</remarks>
public string HostName => m_WrappedSummary != null ? m_WrappedSummary.HostName : m_WrappedISessionSummary.HostName;
/// <summary>
/// The DNS domain name of the computer that recorded the session. May be empty.
/// </summary>
/// <remarks>Does not include the host name portion of the fully qualified DNS name.</remarks>
public string DnsDomainName => m_WrappedSummary != null ? m_WrappedSummary.DnsDomainName : m_WrappedISessionSummary.DnsDomainName;
/// <summary>
/// The fully qualified user name of the user the application was run as.
/// </summary>
public string FullyQualifiedUserName => m_WrappedSummary != null ? m_WrappedSummary.FullyQualifiedUserName : m_WrappedISessionSummary.FullyQualifiedUserName;
/// <summary>
/// The user Id that was used to run the session
/// </summary>
public string UserName => m_WrappedSummary != null ? m_WrappedSummary.UserName : m_WrappedISessionSummary.UserName;
/// <summary>
/// The domain of the user id that was used to run the session
/// </summary>
public string UserDomainName => m_WrappedSummary != null ? m_WrappedSummary.UserDomainName : m_WrappedISessionSummary.UserDomainName;
/// <summary>
/// The version information of the installed operating system (without service pack or patches)
/// </summary>
public Version OSVersion => m_WrappedSummary != null ? m_WrappedSummary.OSVersion : m_WrappedISessionSummary.OSVersion;
/// <summary>
/// The operating system service pack, if any.
/// </summary>
public string OSServicePack => m_WrappedSummary != null ? m_WrappedSummary.OSServicePack : m_WrappedISessionSummary.OSServicePack;
/// <summary>
/// The culture name of the underlying operating system installation
/// </summary>
public string OSCultureName => m_WrappedSummary != null ? m_WrappedSummary.OSCultureName : m_WrappedISessionSummary.OSCultureName;
/// <summary>
/// The processor architecture of the operating system.
/// </summary>
public ProcessorArchitecture OSArchitecture => m_WrappedSummary != null ? m_WrappedSummary.OSArchitecture : m_WrappedISessionSummary.OSArchitecture;
/// <summary>
/// The boot mode of the operating system.
/// </summary>
public OSBootMode OSBootMode => (OSBootMode) (m_WrappedSummary != null ? m_WrappedSummary.OSBootMode : m_WrappedISessionSummary.OSBootMode);
/// <summary>
/// The OS Platform code, nearly always 1 indicating Windows NT
/// </summary>
public int OSPlatformCode => m_WrappedSummary != null ? m_WrappedSummary.OSPlatformCode : m_WrappedISessionSummary.OSPlatformCode;
/// <summary>
/// The OS product type code, used to differentiate specific editions of various operating systems.
/// </summary>
public int OSProductType => m_WrappedSummary != null ? m_WrappedSummary.OSProductType : m_WrappedISessionSummary.OSProductType;
/// <summary>
/// The OS Suite Mask, used to differentiate specific editions of various operating systems.
/// </summary>
public int OSSuiteMask => m_WrappedSummary != null ? m_WrappedSummary.OSSuiteMask : m_WrappedISessionSummary.OSSuiteMask;
/// <summary>
/// The well known operating system family name, like Windows Vista or Windows Server 2003.
/// </summary>
public string OSFamilyName => m_WrappedSummary != null ? m_WrappedSummary.OSFamilyName : m_WrappedISessionSummary.OSFamilyName;
/// <summary>
/// The edition of the operating system without the family name, such as Workstation or Standard Server.
/// </summary>
public string OSEditionName => m_WrappedSummary != null ? m_WrappedSummary.OSEditionName : m_WrappedISessionSummary.OSEditionName;
/// <summary>
/// The well known OS name and edition name
/// </summary>
public string OSFullName => m_WrappedSummary != null ? m_WrappedSummary.OSFullName : m_WrappedISessionSummary.OSFullName;
/// <summary>
/// The well known OS name, edition name, and service pack like Windows XP Professional Service Pack 3
/// </summary>
public string OSFullNameWithServicePack => m_WrappedSummary != null ? m_WrappedSummary.OSFullNameWithServicePack : m_WrappedISessionSummary.OSFullNameWithServicePack;
/// <summary>
/// The version of the .NET runtime that the application domain is running as.
/// </summary>
public Version RuntimeVersion => m_WrappedSummary != null ? m_WrappedSummary.RuntimeVersion : m_WrappedISessionSummary.RuntimeVersion;
/// <summary>
/// The processor architecture the process is running as.
/// </summary>
public ProcessorArchitecture RuntimeArchitecture => m_WrappedSummary != null ? m_WrappedSummary.RuntimeArchitecture : m_WrappedISessionSummary.RuntimeArchitecture;
/// <summary>
/// The current application culture name.
/// </summary>
public string CurrentCultureName => m_WrappedSummary != null ? m_WrappedSummary.CurrentCultureName : m_WrappedISessionSummary.CurrentCultureName;
/// <summary>
/// The current user interface culture name.
/// </summary>
public string CurrentUICultureName => m_WrappedSummary != null ? m_WrappedSummary.CurrentUICultureName : m_WrappedISessionSummary.CurrentUICultureName;
/// <summary>
/// The number of megabytes of installed memory in the host computer.
/// </summary>
public int MemoryMB => m_WrappedSummary != null ? m_WrappedSummary.MemoryMB : m_WrappedISessionSummary.MemoryMB;
/// <summary>
/// The number of physical processor sockets in the host computer.
/// </summary>
public int Processors => m_WrappedSummary != null ? m_WrappedSummary.Processors : m_WrappedISessionSummary.Processors;
/// <summary>
/// The total number of processor cores in the host computer.
/// </summary>
public int ProcessorCores => m_WrappedSummary != null ? m_WrappedSummary.ProcessorCores : m_WrappedISessionSummary.ProcessorCores;
/// <summary>
/// Indicates if the session was run in a user interactive mode.
/// </summary>
public bool UserInteractive => m_WrappedSummary != null ? m_WrappedSummary.UserInteractive : m_WrappedISessionSummary.UserInteractive;
/// <summary>
/// Indicates if the session was run through terminal server. Only applies to User Interactive sessions.
/// </summary>
public bool TerminalServer => m_WrappedSummary != null ? m_WrappedSummary.TerminalServer : m_WrappedISessionSummary.TerminalServer;
/// <summary>
/// The number of pixels wide of the virtual desktop.
/// </summary>
public int ScreenWidth => m_WrappedSummary != null ? m_WrappedSummary.ScreenWidth : m_WrappedISessionSummary.ScreenWidth;
/// <summary>
/// The number of pixels tall for the virtual desktop.
/// </summary>
public int ScreenHeight => m_WrappedSummary != null ? m_WrappedSummary.ScreenHeight : m_WrappedISessionSummary.ScreenHeight;
/// <summary>
/// The number of bits of color depth.
/// </summary>
public int ColorDepth => m_WrappedSummary != null ? m_WrappedSummary.ColorDepth : m_WrappedISessionSummary.ColorDepth;
/// <summary>
/// The complete command line used to execute the process including arguments.
/// </summary>
public string CommandLine => m_WrappedSummary != null ? m_WrappedSummary.CommandLine : m_WrappedISessionSummary.CommandLine;
/// <summary>
/// The final status of the session.
/// </summary>
public SessionStatus Status => m_WrappedSummary != null ? (SessionStatus)m_WrappedSummary.Status : (SessionStatus)m_WrappedISessionSummary.Status;
/// <summary>
/// The number of messages in the messages collection.
/// </summary>
/// <remarks>This value is cached for high performance and reflects all of the known messages. If only part
/// of the files for a session are loaded, the totals as of the latest file loaded are used. This means the
/// count of items may exceed the actual number of matching messages in the messages collection if earlier
/// files are missing.</remarks>
public int MessageCount => m_WrappedSummary != null ? m_WrappedSummary.MessageCount : m_WrappedISessionSummary.MessageCount;
/// <summary>
/// The number of critical messages in the messages collection.
/// </summary>
/// <remarks>This value is cached for high performance and reflects all of the known messages. If only part
/// of the files for a session are loaded, the totals as of the latest file loaded are used. This means the
/// count of items may exceed the actual number of matching messages in the messages collection if earlier
/// files are missing.</remarks>
public int CriticalCount => m_WrappedSummary != null ? m_WrappedSummary.CriticalCount : m_WrappedISessionSummary.CriticalCount;
/// <summary>
/// The number of error messages in the messages collection.
/// </summary>
/// <remarks>This value is cached for high performance and reflects all of the known messages. If only part
/// of the files for a session are loaded, the totals as of the latest file loaded are used. This means the
/// count of items may exceed the actual number of matching messages in the messages collection if earlier
/// files are missing.</remarks>
public int ErrorCount => m_WrappedSummary != null ? m_WrappedSummary.ErrorCount : m_WrappedISessionSummary.ErrorCount;
/// <summary>
/// The number of warning messages in the messages collection.
/// </summary>
/// <remarks>This value is cached for high performance and reflects all of the known messages. If only part
/// of the files for a session are loaded, the totals as of the latest file loaded are used. This means the
/// count of items may exceed the actual number of matching messages in the messages collection if earlier
/// files are missing.</remarks>
public int WarningCount => m_WrappedSummary != null ? m_WrappedSummary.WarningCount : m_WrappedISessionSummary.WarningCount;
/// <summary>
/// A copy of the collection of application specific properties. (Set via configuration at logging startup. Do not modify here.)
/// </summary>
public Dictionary<string, string> Properties => m_Properties;
#endregion
#region Internal Properties and Methods
/// <summary>
/// Ensures that the provided object is used as the wrapped object.
/// </summary>
/// <param name="summary"></param>
internal void SyncWrappedObject(Monitor.SessionSummary summary)
{
if (ReferenceEquals(summary, m_WrappedSummary) == false)
{
m_WrappedSummary = summary;
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
namespace Hydra.Framework.Geometric
{
public class BoundaryObject : IMapviewObject,ICloneable, IPersist
{
#region Private members of BoundaryObject
public event GraphicEvents GraphicSelected;
public ArrayList m_points = new ArrayList();
private bool isselected = false;
private bool isfilled=false;
private System.Drawing.Drawing2D.FillMode filemode=System.Drawing.Drawing2D.FillMode.Alternate;
private bool visible=true;
private bool showtooptip=false;
private bool iscurrent=true;
private bool islocked=false;
private bool isdisabled=false;
private int tension=1;
private bool showhandle=false;
private int handlesize=6;
private Color fillcolor=Color.Cyan;
private Color normalcolor= Color.Yellow;
private Color selectcolor= Color.Red;
private Color disabledcolor= Color.Gray;
private int linewidth=2;
public PointF[] points;
private string xml="";
#endregion
#region Properties of BoundaryObject Object
public PointF[] Vertices
{
get{return points;}
set{points=value;}
}
[Category("Colors" ),Description("The disabled graphic object will be drawn using this pen")]
public Color DisabledColor
{
get{return disabledcolor;}
set{disabledcolor=value;}
}
[Category("Colors" ),Description("The selected graphic object willbe drawn using this pen")]
public Color SelectColor
{
get{return selectcolor;}
set{selectcolor=value;}
}
[Category("Appearance"),Description("The graphic object will be filled with a given color or pattern")]
public bool IsFilled{get{return isfilled;}set{isfilled=value;}
}
[Category("Colors" ),Description("The graphic object willbe drawn using this pen")]
public Color NormalColor
{
get{return normalcolor;}
set{normalcolor=value;}
}
[DefaultValue(2),Category("AbstractStyle"),Description("The gives the line thickness of the graphic object")]
public int LineWidth
{
get{return linewidth;}
set{linewidth=value;}
}
[Category("Appearance"),Description("The graphic object will be filled with a given color or pattern")]
public System.Drawing.Drawing2D.FillMode FillMode{get{return filemode;}set{filemode=value;}
}
[Category("Appearance"), Description("Determines whether the object is visible or hidden")]
public bool Visible
{
get{return visible;}
set{visible=value;}
}
[Category("Appearance"), Description("Determines whether the tooltip information to be shown or not")]
public bool ShowToopTip
{
get{return showtooptip;}
set{showtooptip=value;}
}
[Category("Appearance"), Description("Determines whether the object is in current selected legend or not")]
public bool IsCurrent
{
get{return iscurrent;}
set{iscurrent=value;}
}
[Category("Appearance"), Description("Determines whether the object is locked from the current user or not")]
public bool IsLocked
{
get{return islocked;}
set{islocked=value;}
}
[Category("Appearance"), Description("Determines whether the object is disabled from editing")]
public bool IsDisabled
{
get{return isdisabled;}
set{isselected=true;
isdisabled=value;}
}
[Category("Appearance"), Description("Determines whether the object is in edit mode")]
public bool IsEdit
{
get{return showhandle;}
set{showhandle=value;}
}
#endregion
#region Constructors of Boundary Object
public BoundaryObject(ArrayList points)
{
m_points.Clear();
foreach(PointF item in points)
{
m_points.Add(item);
}
}
public BoundaryObject(BoundaryObject po){}
#endregion
#region Methods of ICloneable
public object Clone()
{
return new BoundaryObject( this );
}
#endregion
#region Methods of Boundary Object
public bool IsSelected()
{
return isselected;
}
public void Select(bool m)
{
isselected = m;
}
public bool IsObjectAt(PointF pnt,float dist)
{
double min_dist = 100000;
for(int i=0; i<m_points.Count-1; i++)
{
PointF p1 = (PointF)m_points[i];
PointF p2 = (PointF)m_points[i+1];
double curr_dist = GeoUtil.DistanceBetweenPointToSegment(p1,p2,pnt);
if(min_dist>curr_dist)
min_dist = curr_dist;
}
return Math.Sqrt(min_dist) < dist;
}
public void Insert(PointF pt,int i)
{
m_points.Insert(i,pt);
}
public void Insert(PointF[] pt, int i)
{
m_points.InsertRange(i,pt);
}
public Rectangle BoundingBox()
{
int x1=(int)((PointF)(m_points[0])).X;
int y1=(int)((PointF)(m_points[0])).Y;
int x2=(int)((PointF)(m_points[0])).X;
int y2=(int)((PointF)(m_points[0])).Y;
for(int i=0; i<m_points.Count; i++)
{
if((int)((PointF)m_points[i]).X < x1)
x1 = (int)((PointF)m_points[i]).X;
else if((int)((PointF)m_points[i]).X > x2)
x2 = (int)((PointF)m_points[i]).X;
if((int)((PointF)m_points[i]).Y < y1)
y1 = (int)((PointF)m_points[i]).Y;
else if((int)((PointF)m_points[i]).Y > y2)
y2 = (int)((PointF)m_points[i]).Y;
}
return new Rectangle((int)x1,(int)y1,(int)x2,(int)y2);
}
public float X()
{
return ((PointF)m_points[0]).X;
}
public float Y()
{
return ((PointF)m_points[0]).Y;
}
public void Move(PointF p)
{
float dx = p.X-((PointF)m_points[0]).X;
float dy = p.Y-((PointF)m_points[0]).Y;
for(int i=0; i<m_points.Count; i++)
{
PointF cp = new PointF(((PointF)m_points[i]).X + dx,
((PointF)m_points[i]).Y + dy);
m_points[i] = cp;
}
}
public void MoveBy(float dx,float dy)
{
for(int i=0; i<m_points.Count; i++)
{
PointF cp = new PointF(((PointF)m_points[i]).X + dx,
((PointF)m_points[i]).Y + dy);
m_points[i] = cp;
}
}
public void Scale(int scale)
{
for(int i=0; i<m_points.Count; i++)
{
PointF cp = new PointF(((PointF)m_points[i]).X * scale,
((PointF)m_points[i]).Y + scale);
m_points[i] = cp;
}
}
public void Rotate(float radians)
{
//
}
public void RotateAt(PointF pt)
{
//
}
public void RoateAt(Point pt)
{
//
}
public void Draw(Graphics graph,System.Drawing.Drawing2D.Matrix trans)
{
if (visible)
{
// create 0,0 and width,height points
PointF [] points = new PointF[m_points.Count];
m_points.CopyTo(0,points,0,m_points.Count);
trans.TransformPoints(points);
if(isselected)
{
graph.DrawClosedCurve(new Pen(selectcolor,linewidth),points,tension,filemode);
if (showhandle)
{
for (int i=0; i<m_points.Count; i++)
{
graph.FillRectangle(new SolidBrush(fillcolor),points[i].X-handlesize/2,points[i].Y-handlesize/2,handlesize,handlesize);
graph.DrawRectangle(new Pen(Color.Black,1),points[i].X-handlesize/2,points[i].Y-handlesize/2,handlesize,handlesize);
}
}
}
else if (isdisabled || islocked)
{
graph.DrawClosedCurve(new Pen(disabledcolor,linewidth),points,tension,filemode);
}
else
{
graph.DrawClosedCurve(new Pen(normalcolor,linewidth),points,tension,filemode);
}
}
}
#endregion
#region IPersist Members
public string ToXML
{
get{return "";}
set{xml=value;}
}
public string ToVML
{
get{return "";}
set{xml=value;}
}
public string ToGML
{
get{return "";}
set{xml=value;}
}
public string ToSVG
{
get{return "";}
set{xml=value;}
}
#endregion
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Linq;
using Microsoft.PythonTools;
using Microsoft.PythonTools.Intellisense;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Interpreter.Default;
using Microsoft.PythonTools.Parsing;
using Microsoft.PythonTools.Parsing.Ast;
using Microsoft.PythonTools.Refactoring;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.Text;
using TestUtilities;
using TestUtilities.Mocks;
using TestUtilities.Python;
namespace PythonToolsTests {
[TestClass]
public class CodeFormatterTests {
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy();
}
[TestMethod, Priority(1)]
public void TestCodeFormattingSelection() {
var input = @"print('Hello World')
class SimpleTest(object):
def test_simple_addition(self):
pass
def test_complex(self):
pass
class Oar(object):
def say_hello(self):
method_end";
string selection = "def say_hello .. method_end";
string expected = @"print('Hello World')
class SimpleTest(object):
def test_simple_addition(self):
pass
def test_complex(self):
pass
class Oar(object):
def say_hello( self ):
method_end";
var options = new CodeFormattingOptions() {
SpaceBeforeClassDeclarationParen = true,
SpaceWithinFunctionDeclarationParens = true
};
CodeFormattingTest(input, selection, expected, " def say_hello .. method_end", options);
}
[TestMethod, Priority(1)]
public void TestCodeFormattingEndOfFile() {
var input = @"print('Hello World')
class SimpleTest(object):
def test_simple_addition(self):
pass
def test_complex(self):
pass
class Oar(object):
def say_hello(self):
method_end
";
var options = new CodeFormattingOptions() {
SpaceBeforeClassDeclarationParen = false,
SpaceWithinFunctionDeclarationParens = false
};
CodeFormattingTest(input, new Span(input.Length, 0), input, null, options);
}
[TestMethod, Priority(1)]
public void TestCodeFormattingInMethodExpression() {
var input = @"print('Hello World')
class SimpleTest(object):
def test_simple_addition(self):
pass
def test_complex(self):
pass
class Oar(object):
def say_hello(self):
method_end
";
var options = new CodeFormattingOptions() {
SpaceBeforeClassDeclarationParen = true,
SpaceWithinFunctionDeclarationParens = true
};
CodeFormattingTest(input, "method_end", input, null, options);
}
[TestMethod, Priority(1)]
public void TestCodeFormattingStartOfMethodSelection() {
var input = @"print('Hello World')
class SimpleTest(object):
def test_simple_addition(self):
pass
def test_complex(self):
pass
class Oar(object):
def say_hello(self):
method_end";
string selection = "def say_hello";
string expected = @"print('Hello World')
class SimpleTest(object):
def test_simple_addition(self):
pass
def test_complex(self):
pass
class Oar(object):
def say_hello( self ):
method_end";
var options = new CodeFormattingOptions() {
SpaceBeforeClassDeclarationParen = true,
SpaceWithinFunctionDeclarationParens = true
};
CodeFormattingTest(input, selection, expected, " def say_hello .. method_end", options);
}
[TestMethod, Priority(1)]
public void FormatDocument() {
var input = @"fob('Hello World')";
var expected = @"fob( 'Hello World' )";
var options = new CodeFormattingOptions() { SpaceWithinCallParens = true };
CodeFormattingTest(input, new Span(0, input.Length), expected, null, options, false);
}
private static void CodeFormattingTest(string input, object selection, string expected, object expectedSelection, CodeFormattingOptions options, bool selectResult = true) {
var fact = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(new Version(2, 7));
var serviceProvider = PythonToolsTestUtilities.CreateMockServiceProvider();
using (var analyzer = new VsProjectAnalyzer(serviceProvider, fact)) {
var buffer = new MockTextBuffer(input, PythonCoreConstants.ContentType, "C:\\fob.py");
buffer.AddProperty(typeof(VsProjectAnalyzer), analyzer);
var view = new MockTextView(buffer);
analyzer.MonitorTextBufferAsync(buffer).Wait();
var selectionSpan = new SnapshotSpan(
buffer.CurrentSnapshot,
ExtractMethodTests.GetSelectionSpan(input, selection)
);
view.Selection.Select(selectionSpan, false);
analyzer.FormatCodeAsync(
selectionSpan,
view,
options,
selectResult
).Wait();
Assert.AreEqual(expected, view.TextBuffer.CurrentSnapshot.GetText());
if (expectedSelection != null) {
Assert.AreEqual(
ExtractMethodTests.GetSelectionSpan(expected, expectedSelection),
view.Selection.StreamSelectionSpan.SnapshotSpan.Span
);
}
}
}
}
}
| |
// 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.Buffers;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Pipelines.Tests
{
public class PipeWriterStreamTests
{
public delegate Task WriteAsyncDelegate(Stream stream, byte[] data);
[Fact]
public async Task DisposingPipeWriterStreamCompletesPipeWriter()
{
var pipe = new Pipe();
Stream s = pipe.Writer.AsStream();
var writerCompletedTask = new TaskCompletionSource<bool>();
#pragma warning disable CS0618 // Type or member is obsolete
pipe.Reader.OnWriterCompleted(delegate { writerCompletedTask.SetResult(true); }, null);
#pragma warning restore CS0618 // Type or member is obsolete
// Call Dispose{Async} multiple times; all should succeed.
for (int i = 0; i < 2; i++)
{
s.Dispose();
await s.DisposeAsync();
}
// Make sure OnWriterCompleted was invoked.
await writerCompletedTask.Task;
// Unable to write after disposing.
await Assert.ThrowsAsync<InvalidOperationException>(async () => await s.WriteAsync(new byte[1]));
// Reads still work and return 0.
ReadResult rr = await pipe.Reader.ReadAsync();
Assert.True(rr.IsCompleted);
Assert.Equal(0, rr.Buffer.Length);
}
[Theory]
[MemberData(nameof(WriteCalls))]
public async Task WritingToPipeStreamWritesToUnderlyingPipeWriter(WriteAsyncDelegate writeAsync)
{
byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World");
var pipe = new Pipe();
var stream = new PipeWriterStream(pipe.Writer, leaveOpen: false);
await writeAsync(stream, helloBytes);
ReadResult result = await pipe.Reader.ReadAsync();
Assert.Equal(helloBytes, result.Buffer.ToArray());
pipe.Reader.Complete();
pipe.Writer.Complete();
}
[Theory]
[MemberData(nameof(WriteCalls))]
public async Task AsStreamReturnsPipeWriterStream(WriteAsyncDelegate writeAsync)
{
byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World");
var pipe = new Pipe();
Stream stream = pipe.Writer.AsStream();
await writeAsync(stream, helloBytes);
ReadResult result = await pipe.Reader.ReadAsync();
Assert.Equal(helloBytes, result.Buffer.ToArray());
pipe.Reader.Complete();
pipe.Writer.Complete();
}
[Fact]
public async Task FlushAsyncFlushesBufferedData()
{
byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World");
var pipe = new Pipe();
Memory<byte> memory = pipe.Writer.GetMemory();
helloBytes.CopyTo(memory);
pipe.Writer.Advance(helloBytes.Length);
Stream stream = pipe.Writer.AsStream();
await stream.FlushAsync();
ReadResult result = await pipe.Reader.ReadAsync();
Assert.Equal(helloBytes, result.Buffer.ToArray());
pipe.Reader.Complete();
pipe.Writer.Complete();
}
[Fact]
public async Task ReadingFromPipeWriterStreamThrowsNotSupported()
{
byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World");
var pipe = new Pipe();
Stream stream = pipe.Writer.AsStream();
Assert.True(stream.CanWrite);
Assert.False(stream.CanSeek);
Assert.False(stream.CanRead);
Assert.Throws<NotSupportedException>(() => { long length = stream.Length; });
Assert.Throws<NotSupportedException>(() => { long position = stream.Position; });
Assert.Throws<NotSupportedException>(() => stream.Seek(0, SeekOrigin.Begin));
Assert.Throws<NotSupportedException>(() => stream.Read(new byte[10], 0, 10));
await Assert.ThrowsAsync<NotSupportedException>(() => stream.ReadAsync(new byte[10], 0, 10));
await Assert.ThrowsAsync<NotSupportedException>(() => stream.ReadAsync(new byte[10]).AsTask());
await Assert.ThrowsAsync<NotSupportedException>(() => stream.CopyToAsync(Stream.Null));
pipe.Reader.Complete();
pipe.Writer.Complete();
}
[Fact]
public async Task CancellingPendingFlushThrowsOperationCancelledException()
{
var pipe = new Pipe(new PipeOptions(pauseWriterThreshold: 10, resumeWriterThreshold: 0));
byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World");
Stream stream = pipe.Writer.AsStream();
ValueTask task = stream.WriteAsync(helloBytes);
Assert.False(task.IsCompleted);
pipe.Writer.CancelPendingFlush();
await Assert.ThrowsAsync<OperationCanceledException>(async () => await task);
pipe.Writer.Complete();
pipe.Reader.Complete();
}
[Fact]
public async Task CancellationTokenFlowsToUnderlyingPipeWriter()
{
var pipe = new Pipe(new PipeOptions(pauseWriterThreshold: 10, resumeWriterThreshold: 0));
byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World");
Stream stream = pipe.Writer.AsStream();
var cts = new CancellationTokenSource();
ValueTask task = stream.WriteAsync(helloBytes, cts.Token);
Assert.False(task.IsCompleted);
cts.Cancel();
await Assert.ThrowsAsync<OperationCanceledException>(async () => await task);
pipe.Writer.Complete();
pipe.Reader.Complete();
}
[Fact]
public async Task DefaultPipeWriterImplementationReturnsPipeWriterStream()
{
var pipeWriter = new TestPipeWriter();
Stream stream = pipeWriter.AsStream();
await stream.WriteAsync(new byte[10]);
Assert.True(pipeWriter.WriteAsyncCalled);
await stream.FlushAsync();
Assert.True(pipeWriter.FlushCalled);
}
[Fact]
public void AsStreamDoNotCompleteWriter()
{
var pipeWriter = new NotImplementedPipeWriter();
// would throw in Complete if it was actually invoked
pipeWriter.AsStream(leaveOpen: true).Dispose();
}
public class TestPipeWriter : PipeWriter
{
public bool FlushCalled { get; set; }
public bool WriteAsyncCalled { get; set; }
public override void Advance(int bytes)
{
throw new NotImplementedException();
}
public override void CancelPendingFlush()
{
throw new NotImplementedException();
}
public override void Complete(Exception exception = null)
{
throw new NotImplementedException();
}
public override ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken = default)
{
FlushCalled = true;
return default;
}
public override Memory<byte> GetMemory(int sizeHint = 0)
{
throw new NotImplementedException();
}
public override Span<byte> GetSpan(int sizeHint = 0)
{
throw new NotImplementedException();
}
public override ValueTask<FlushResult> WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default)
{
WriteAsyncCalled = true;
return default;
}
}
public class NotImplementedPipeWriter : PipeWriter
{
public NotImplementedPipeWriter()
{
}
public override void Advance(int bytes) => throw new NotImplementedException();
public override void CancelPendingFlush() => throw new NotImplementedException();
public override void Complete(Exception exception = null) => throw new NotImplementedException();
public override ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken = default) => throw new NotImplementedException();
public override Memory<byte> GetMemory(int sizeHint = 0) => throw new NotImplementedException();
public override Span<byte> GetSpan(int sizeHint = 0) => throw new NotImplementedException();
}
public static IEnumerable<object[]> WriteCalls
{
get
{
WriteAsyncDelegate writeArrayAsync = (stream, data) =>
{
return stream.WriteAsync(data, 0, data.Length);
};
WriteAsyncDelegate writeMemoryAsync = async (stream, data) =>
{
await stream.WriteAsync(data);
};
WriteAsyncDelegate writeArraySync = (stream, data) =>
{
stream.Write(data, 0, data.Length);
return Task.CompletedTask;
};
WriteAsyncDelegate writeSpanSync = (stream, data) =>
{
stream.Write(data);
return Task.CompletedTask;
};
yield return new object[] { writeArrayAsync };
yield return new object[] { writeMemoryAsync };
yield return new object[] { writeArraySync };
yield return new object[] { writeSpanSync };
}
}
}
}
| |
#region License
/* **********************************************************************************
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion License
/*
* Authors: Roman Ivantsov, Philipp Serr
*/
using System;
using System.Globalization;
namespace Irony.Parsing
{
public static class TerminalFactory
{
public static StringLiteral CreateCSharpChar(string name)
{
var term = new StringLiteral(name, "'", StringOptions.IsChar);
return term;
}
public static IdentifierTerminal CreateCSharpIdentifier(string name)
{
var id = new IdentifierTerminal(name, IdOptions.AllowsEscapes | IdOptions.CanStartWithEscape);
id.AddPrefix("@", IdOptions.IsNotKeyword);
// From spec:
// Start char is "_" or letter-character, which is a Unicode character of classes Lu, Ll, Lt, Lm, Lo, or Nl
id.StartCharCategories.AddRange(new UnicodeCategory[] {
// Ul
UnicodeCategory.UppercaseLetter,
// Ll
UnicodeCategory.LowercaseLetter,
// Lt
UnicodeCategory.TitlecaseLetter,
// Lm
UnicodeCategory.ModifierLetter,
// Lo
UnicodeCategory.OtherLetter,
// Nl
UnicodeCategory.LetterNumber
});
// Internal chars
// From spec:
// identifier-part-character: letter-character | decimal-digit-character | connecting-character | combining-character |
// formatting-character
// letter-character categories
id.CharCategories.AddRange(id.StartCharCategories);
id.CharCategories.AddRange(new UnicodeCategory[] {
// Nd
UnicodeCategory.DecimalDigitNumber,
// Pc
UnicodeCategory.ConnectorPunctuation,
// Mc
UnicodeCategory.SpacingCombiningMark,
// Mn
UnicodeCategory.NonSpacingMark,
// Cf
UnicodeCategory.Format
});
// Chars to remove from final identifier
id.CharsToRemoveCategories.Add(UnicodeCategory.Format);
return id;
}
/// <summary>
/// http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf section 9.4.4
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static NumberLiteral CreateCSharpNumber(string name)
{
var term = new NumberLiteral(name);
term.DefaultIntTypes = new TypeCode[] { TypeCode.Int32, TypeCode.UInt32, TypeCode.Int64, TypeCode.UInt64 };
term.DefaultFloatType = TypeCode.Double;
term.AddPrefix("0x", NumberOptions.Hex);
term.AddSuffix("u", TypeCode.UInt32, TypeCode.UInt64);
term.AddSuffix("l", TypeCode.Int64, TypeCode.UInt64);
term.AddSuffix("ul", TypeCode.UInt64);
term.AddSuffix("f", TypeCode.Single);
term.AddSuffix("d", TypeCode.Double);
term.AddSuffix("m", TypeCode.Decimal);
return term;
}
public static StringLiteral CreateCSharpString(string name)
{
var term = new StringLiteral(name, "\"", StringOptions.AllowsAllEscapes);
term.AddPrefix("@", StringOptions.NoEscapes | StringOptions.AllowsLineBreak | StringOptions.AllowsDoubledQuote);
return term;
}
public static IdentifierTerminal CreatePythonIdentifier(string name)
{
// Defaults are OK
var id = new IdentifierTerminal("Identifier");
return id;
}
/// <summary>
/// http://docs.python.org/ref/numbers.html
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static NumberLiteral CreatePythonNumber(string name)
{
var term = new NumberLiteral(name, NumberOptions.AllowStartEndDot);
// Default int types are Integer (32bit) -> LongInteger (BigInt); Try Int64 before BigInt: Better performance?
term.DefaultIntTypes = new TypeCode[] { TypeCode.Int32, TypeCode.Int64, NumberLiteral.TypeCodeBigInt };
term.AddPrefix("0x", NumberOptions.Hex);
term.AddPrefix("0", NumberOptions.Octal);
term.AddSuffix("L", TypeCode.Int64, NumberLiteral.TypeCodeBigInt);
term.AddSuffix("J", NumberLiteral.TypeCodeImaginary);
return term;
}
public static StringLiteral CreatePythonString(string name)
{
var term = new StringLiteral(name);
term.AddStartEnd("'", StringOptions.AllowsAllEscapes);
term.AddStartEnd("'''", StringOptions.AllowsAllEscapes | StringOptions.AllowsLineBreak);
term.AddStartEnd("\"", StringOptions.AllowsAllEscapes);
term.AddStartEnd("\"\"\"", StringOptions.AllowsAllEscapes | StringOptions.AllowsLineBreak);
term.AddPrefix("u", StringOptions.AllowsAllEscapes);
term.AddPrefix("r", StringOptions.NoEscapes);
term.AddPrefix("ur", StringOptions.NoEscapes);
return term;
}
/// <summary>
/// About exponent symbols, extract from R6RS:
/// ... representations of number objects may be written with an exponent marker that indicates the desired precision
/// of the inexact representation. The letters s, f, d, and l specify the use of short, single, double, and long precision, respectively.
/// ...
/// In addition, the exponent marker e specifies the default precision for the implementation. The default precision
/// has at least as much precision as double, but implementations may wish to allow this default to be set by the user.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static NumberLiteral CreateSchemeNumber(string name)
{
var term = new NumberLiteral(name);
term.DefaultIntTypes = new TypeCode[] { TypeCode.Int32, TypeCode.Int64, NumberLiteral.TypeCodeBigInt };
// It is default
term.DefaultFloatType = TypeCode.Double;
// Default precision for platform, double
term.AddExponentSymbols("eE", TypeCode.Double);
term.AddExponentSymbols("sSfF", TypeCode.Single);
term.AddExponentSymbols("dDlL", TypeCode.Double);
term.AddPrefix("#b", NumberOptions.Binary);
term.AddPrefix("#o", NumberOptions.Octal);
term.AddPrefix("#x", NumberOptions.Hex);
term.AddPrefix("#d", NumberOptions.None);
// Inexact prefix, has no effect
term.AddPrefix("#i", NumberOptions.None);
// Exact prefix, has no effect
term.AddPrefix("#e", NumberOptions.None);
term.AddSuffix("J", NumberLiteral.TypeCodeImaginary);
return term;
}
/// <summary>
/// Covers simple identifiers like abcd, and also quoted versions: [abc d], "abc d".
/// </summary>
/// <param name="grammar"></param>
/// <param name="name"></param>
/// <returns></returns>
public static IdentifierTerminal CreateSqlExtIdentifier(Grammar grammar, string name)
{
var id = new IdentifierTerminal(name);
var term = new StringLiteral(name + "_qouted");
term.AddStartEnd("[", "]", StringOptions.NoEscapes);
term.AddStartEnd("\"", StringOptions.NoEscapes);
// Term will be added to NonGrammarTerminals automatically
term.SetOutputTerminal(grammar, id);
return id;
}
/// <summary>
/// http://www.microsoft.com/downloads/details.aspx?FamilyId=6D50D709-EAA4-44D7-8AF3-E14280403E6E&displaylang=en section 2
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static NumberLiteral CreateVbNumber(string name)
{
var term = new NumberLiteral(name);
term.DefaultIntTypes = new TypeCode[] { TypeCode.Int32, TypeCode.Int64 };
//term.DefaultFloatType = TypeCode.Double; it is default
term.AddPrefix("&H", NumberOptions.Hex);
term.AddPrefix("&O", NumberOptions.Octal);
term.AddSuffix("S", TypeCode.Int16);
term.AddSuffix("I", TypeCode.Int32);
term.AddSuffix("%", TypeCode.Int32);
term.AddSuffix("L", TypeCode.Int64);
term.AddSuffix("&", TypeCode.Int64);
term.AddSuffix("D", TypeCode.Decimal);
term.AddSuffix("@", TypeCode.Decimal);
term.AddSuffix("F", TypeCode.Single);
term.AddSuffix("!", TypeCode.Single);
term.AddSuffix("R", TypeCode.Double);
term.AddSuffix("#", TypeCode.Double);
term.AddSuffix("US", TypeCode.UInt16);
term.AddSuffix("UI", TypeCode.UInt32);
term.AddSuffix("UL", TypeCode.UInt64);
return term;
}
public static StringLiteral CreateVbString(string name)
{
var term = new StringLiteral(name);
term.AddStartEnd("\"", StringOptions.NoEscapes | StringOptions.AllowsDoubledQuote);
term.AddSuffix("$", TypeCode.String);
term.AddSuffix("c", TypeCode.Char);
return term;
}
}
}
| |
namespace Spring.Expressions.Parser.antlr.debug
{
using System;
using System.Reflection;
using Hashtable = System.Collections.Hashtable;
using DictionaryEntry = System.Collections.DictionaryEntry;
using ArrayList = System.Collections.ArrayList;
using antlr.collections.impl;
public delegate void MessageEventHandler(object sender, MessageEventArgs e);
public delegate void NewLineEventHandler(object sender, NewLineEventArgs e);
public delegate void MatchEventHandler(object sender, MatchEventArgs e);
public delegate void TokenEventHandler(object sender, TokenEventArgs e);
public delegate void SemanticPredicateEventHandler(object sender, SemanticPredicateEventArgs e);
public delegate void SyntacticPredicateEventHandler(object sender, SyntacticPredicateEventArgs e);
public delegate void TraceEventHandler(object sender, TraceEventArgs e);
/// <summary>A class to assist in firing parser events
/// NOTE: I intentionally _did_not_ synchronize the event firing and
/// add/remove listener methods. This is because the add/remove should
/// _only_ be called by the parser at its start/end, and the _same_thread_
/// should be performing the parsing. This should help performance a tad...
/// </summary>
public class ParserEventSupport
{
private object source;
private Hashtable listeners;
private MatchEventArgs matchEvent;
private MessageEventArgs messageEvent;
private TokenEventArgs tokenEvent;
private SemanticPredicateEventArgs semPredEvent;
private SyntacticPredicateEventArgs synPredEvent;
private TraceEventArgs traceEvent;
private NewLineEventArgs newLineEvent;
private ParserController controller;
private int ruleDepth = 0;
public ParserEventSupport(object source)
{
matchEvent = new MatchEventArgs();
messageEvent = new MessageEventArgs();
tokenEvent = new TokenEventArgs();
traceEvent = new TraceEventArgs();
semPredEvent = new SemanticPredicateEventArgs();
synPredEvent = new SyntacticPredicateEventArgs();
newLineEvent = new NewLineEventArgs();
listeners = new Hashtable();
this.source = source;
}
public virtual void checkController()
{
if (controller != null)
controller.checkBreak();
}
public virtual void addDoneListener(Listener l)
{
((Parser)source).Done += new TraceEventHandler(l.doneParsing);
listeners[l] = l;
}
public virtual void addMessageListener(MessageListener l)
{
((Parser)source).ErrorReported += new MessageEventHandler(l.reportError);
((Parser)source).WarningReported += new MessageEventHandler(l.reportWarning);
//messageListeners.Add(l);
addDoneListener(l);
}
public virtual void addParserListener(ParserListener l)
{
if (l is ParserController)
{
((ParserController) l).ParserEventSupport = this;
controller = (ParserController) l;
}
addParserMatchListener(l);
addParserTokenListener(l);
addMessageListener(l);
addTraceListener(l);
addSemanticPredicateListener(l);
addSyntacticPredicateListener(l);
}
public virtual void addParserMatchListener(ParserMatchListener l)
{
((Parser)source).MatchedToken += new MatchEventHandler(l.parserMatch);
((Parser)source).MatchedNotToken += new MatchEventHandler(l.parserMatchNot);
((Parser)source).MisMatchedToken += new MatchEventHandler(l.parserMismatch);
((Parser)source).MisMatchedNotToken += new MatchEventHandler(l.parserMismatchNot);
//matchListeners.Add(l);
addDoneListener(l);
}
public virtual void addParserTokenListener(ParserTokenListener l)
{
((Parser)source).ConsumedToken += new TokenEventHandler(l.parserConsume);
((Parser)source).TokenLA += new TokenEventHandler(l.parserLA);
//tokenListeners.Add(l);
addDoneListener(l);
}
public virtual void addSemanticPredicateListener(SemanticPredicateListener l)
{
((Parser)source).SemPredEvaluated += new SemanticPredicateEventHandler(l.semanticPredicateEvaluated);
//semPredListeners.Add(l);
addDoneListener(l);
}
public virtual void addSyntacticPredicateListener(SyntacticPredicateListener l)
{
((Parser)source).SynPredStarted += new SyntacticPredicateEventHandler(l.syntacticPredicateStarted);
((Parser)source).SynPredFailed += new SyntacticPredicateEventHandler(l.syntacticPredicateFailed);
((Parser)source).SynPredSucceeded += new SyntacticPredicateEventHandler(l.syntacticPredicateSucceeded);
//synPredListeners.Add(l);
addDoneListener(l);
}
public virtual void addTraceListener(TraceListener l)
{
((Parser)source).EnterRule += new TraceEventHandler(l.enterRule);
((Parser)source).ExitRule += new TraceEventHandler(l.exitRule);
//traceListeners.Add(l);
addDoneListener(l);
}
public virtual void fireConsume(int c)
{
TokenEventHandler eventDelegate = (TokenEventHandler)((Parser)source).Events[Parser.LAEventKey];
if (eventDelegate != null)
{
tokenEvent.setValues(TokenEventArgs.CONSUME, 1, c);
eventDelegate(source, tokenEvent);
}
checkController();
}
public virtual void fireDoneParsing()
{
TraceEventHandler eventDelegate = (TraceEventHandler)((Parser)source).Events[Parser.DoneEventKey];
if (eventDelegate != null)
{
traceEvent.setValues(TraceEventArgs.DONE_PARSING, 0, 0, 0);
eventDelegate(source, traceEvent);
}
checkController();
}
public virtual void fireEnterRule(int ruleNum, int guessing, int data)
{
ruleDepth++;
TraceEventHandler eventDelegate = (TraceEventHandler)((Parser)source).Events[Parser.EnterRuleEventKey];
if (eventDelegate != null)
{
traceEvent.setValues(TraceEventArgs.ENTER, ruleNum, guessing, data);
eventDelegate(source, traceEvent);
}
checkController();
}
public virtual void fireExitRule(int ruleNum, int guessing, int data)
{
TraceEventHandler eventDelegate = (TraceEventHandler)((Parser)source).Events[Parser.ExitRuleEventKey];
if (eventDelegate != null)
{
traceEvent.setValues(TraceEventArgs.EXIT, ruleNum, guessing, data);
eventDelegate(source, traceEvent);
}
checkController();
ruleDepth--;
if (ruleDepth == 0)
fireDoneParsing();
}
public virtual void fireLA(int k, int la)
{
TokenEventHandler eventDelegate = (TokenEventHandler)((Parser)source).Events[Parser.LAEventKey];
if (eventDelegate != null)
{
tokenEvent.setValues(TokenEventArgs.LA, k, la);
eventDelegate(source, tokenEvent);
}
checkController();
}
public virtual void fireMatch(char c, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MatchEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.CHAR, c, c, null, guessing, false, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMatch(char c, BitSet b, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MatchEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.CHAR_BITSET, c, b, null, guessing, false, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMatch(char c, string target, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MatchEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.CHAR_RANGE, c, target, null, guessing, false, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMatch(int c, BitSet b, string text, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MatchEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.BITSET, c, b, text, guessing, false, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMatch(int n, string text, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MatchEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.TOKEN, n, n, text, guessing, false, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMatch(string s, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MatchEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.STRING, 0, s, null, guessing, false, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMatchNot(char c, char n, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MatchNotEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.CHAR, c, n, null, guessing, true, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMatchNot(int c, int n, string text, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MatchNotEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.TOKEN, c, n, text, guessing, true, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMismatch(char c, char n, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MisMatchEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.CHAR, c, n, null, guessing, false, false);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMismatch(char c, BitSet b, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MisMatchEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.CHAR_BITSET, c, b, null, guessing, false, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMismatch(char c, string target, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MisMatchEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.CHAR_RANGE, c, target, null, guessing, false, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMismatch(int i, int n, string text, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MisMatchEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.TOKEN, i, n, text, guessing, false, false);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMismatch(int i, BitSet b, string text, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MisMatchEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.BITSET, i, b, text, guessing, false, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMismatch(string s, string text, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MisMatchEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.STRING, 0, text, s, guessing, false, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMismatchNot(char v, char c, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MisMatchNotEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.CHAR, v, c, null, guessing, true, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMismatchNot(int i, int n, string text, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MisMatchNotEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.TOKEN, i, n, text, guessing, true, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireReportError(System.Exception e)
{
MessageEventHandler eventDelegate = (MessageEventHandler)((Parser)source).Events[Parser.ReportErrorEventKey];
if (eventDelegate != null)
{
messageEvent.setValues(MessageEventArgs.ERROR, e.ToString());
eventDelegate(source, messageEvent);
}
checkController();
}
public virtual void fireReportError(string s)
{
MessageEventHandler eventDelegate = (MessageEventHandler)((Parser)source).Events[Parser.ReportErrorEventKey];
if (eventDelegate != null)
{
messageEvent.setValues(MessageEventArgs.ERROR, s);
eventDelegate(source, messageEvent);
}
checkController();
}
public virtual void fireReportWarning(string s)
{
MessageEventHandler eventDelegate = (MessageEventHandler)((Parser)source).Events[Parser.ReportWarningEventKey];
if (eventDelegate != null)
{
messageEvent.setValues(MessageEventArgs.WARNING, s);
eventDelegate(source, messageEvent);
}
checkController();
}
public virtual bool fireSemanticPredicateEvaluated(int type, int condition, bool result, int guessing)
{
SemanticPredicateEventHandler eventDelegate = (SemanticPredicateEventHandler)((Parser)source).Events[Parser.SemPredEvaluatedEventKey];
if (eventDelegate != null)
{
semPredEvent.setValues(type, condition, result, guessing);
eventDelegate(source, semPredEvent);
}
checkController();
return result;
}
public virtual void fireSyntacticPredicateFailed(int guessing)
{
SyntacticPredicateEventHandler eventDelegate = (SyntacticPredicateEventHandler)((Parser)source).Events[Parser.SynPredFailedEventKey];
if (eventDelegate != null)
{
synPredEvent.setValues(0, guessing);
eventDelegate(source, synPredEvent);
}
checkController();
}
public virtual void fireSyntacticPredicateStarted(int guessing)
{
SyntacticPredicateEventHandler eventDelegate = (SyntacticPredicateEventHandler)((Parser)source).Events[Parser.SynPredStartedEventKey];
if (eventDelegate != null)
{
synPredEvent.setValues(0, guessing);
eventDelegate(source, synPredEvent);
}
checkController();
}
public virtual void fireSyntacticPredicateSucceeded(int guessing)
{
SyntacticPredicateEventHandler eventDelegate = (SyntacticPredicateEventHandler)((Parser)source).Events[Parser.SynPredSucceededEventKey];
if (eventDelegate != null)
{
synPredEvent.setValues(0, guessing);
eventDelegate(source, synPredEvent);
}
checkController();
}
public virtual void refreshListeners()
{
Hashtable clonedTable;
lock(listeners.SyncRoot)
{
clonedTable = (Hashtable)listeners.Clone();
}
foreach (DictionaryEntry entry in clonedTable)
{
if (entry.Value != null)
{
((Listener) entry.Value).refresh();
}
}
}
public virtual void removeDoneListener(Listener l)
{
((Parser)source).Done -= new TraceEventHandler(l.doneParsing);
listeners.Remove(l);
}
public virtual void removeMessageListener(MessageListener l)
{
((Parser)source).ErrorReported -= new MessageEventHandler(l.reportError);
((Parser)source).WarningReported -= new MessageEventHandler(l.reportWarning);
//messageListeners.Remove(l);
removeDoneListener(l);
}
public virtual void removeParserListener(ParserListener l)
{
removeParserMatchListener(l);
removeMessageListener(l);
removeParserTokenListener(l);
removeTraceListener(l);
removeSemanticPredicateListener(l);
removeSyntacticPredicateListener(l);
}
public virtual void removeParserMatchListener(ParserMatchListener l)
{
((Parser)source).MatchedToken -= new MatchEventHandler(l.parserMatch);
((Parser)source).MatchedNotToken -= new MatchEventHandler(l.parserMatchNot);
((Parser)source).MisMatchedToken -= new MatchEventHandler(l.parserMismatch);
((Parser)source).MisMatchedNotToken -= new MatchEventHandler(l.parserMismatchNot);
//matchListeners.Remove(l);
removeDoneListener(l);
}
public virtual void removeParserTokenListener(ParserTokenListener l)
{
((Parser)source).ConsumedToken -= new TokenEventHandler(l.parserConsume);
((Parser)source).TokenLA -= new TokenEventHandler(l.parserLA);
//tokenListeners.Remove(l);
removeDoneListener(l);
}
public virtual void removeSemanticPredicateListener(SemanticPredicateListener l)
{
((Parser)source).SemPredEvaluated -= new SemanticPredicateEventHandler(l.semanticPredicateEvaluated);
//semPredListeners.Remove(l);
removeDoneListener(l);
}
public virtual void removeSyntacticPredicateListener(SyntacticPredicateListener l)
{
((Parser)source).SynPredStarted -= new SyntacticPredicateEventHandler(l.syntacticPredicateStarted);
((Parser)source).SynPredFailed -= new SyntacticPredicateEventHandler(l.syntacticPredicateFailed);
((Parser)source).SynPredSucceeded -= new SyntacticPredicateEventHandler(l.syntacticPredicateSucceeded);
//synPredListeners.Remove(l);
removeDoneListener(l);
}
public virtual void removeTraceListener(TraceListener l)
{
((Parser)source).EnterRule -= new TraceEventHandler(l.enterRule);
((Parser)source).ExitRule -= new TraceEventHandler(l.exitRule);
//traceListeners.Remove(l);
removeDoneListener(l);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;
using System.Data;
using System.ComponentModel;
using CsDO.Lib;
using CsDO.Lib.Configuration;
namespace CsDO.Lib.MockDriver
{
public class MockCommand : DbCommand
{
#region Private Vars
private DbCommand _dbCommand = ProviderFactory.Instance.CreateCommand();
private DbTransaction _dbTransaction;
#endregion
#region Constructors
public MockCommand() { }
public MockCommand(string cmdText, MockConnection connection)
: this()
{
this.CommandText = cmdText;
this.Connection = connection;
}
#endregion
#region Private Vars
[DefaultValue("")]
[RefreshProperties(RefreshProperties.All)]
public override string CommandText
{
get
{
return _dbCommand.CommandText;
}
set
{
_dbCommand.CommandText = value;
}
}
public override int CommandTimeout
{
get
{
return _dbCommand.CommandTimeout;
}
set
{
_dbCommand.CommandTimeout = value;
}
}
[RefreshProperties(RefreshProperties.All)]
public override CommandType CommandType
{
get
{
return _dbCommand.CommandType;
}
set
{
_dbCommand.CommandType = value;
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Browsable(false)]
[DefaultValue(true)]
[DesignOnly(true)]
public override bool DesignTimeVisible
{
get
{
return _dbCommand.DesignTimeVisible;
}
set
{
_dbCommand.DesignTimeVisible = value;
}
}
public override UpdateRowSource UpdatedRowSource
{
get
{
return _dbCommand.UpdatedRowSource;
}
set
{
_dbCommand.UpdatedRowSource = value;
}
}
#endregion
#region Public Methods
public override void Cancel()
{
_dbCommand.Cancel();
}
public override int ExecuteNonQuery()
{
int result;
int hashedKey = ResultCache.GetHashedKey(ResultCache.CacheEntryType.ExecuteNonQuery.ToString(), _dbCommand);
ResultCacheEntry entry = ResultCache.Instance[hashedKey];
if (entry == null)
{
result = _dbCommand.ExecuteNonQuery();
ResultCache.Instance.Add(hashedKey, result);
}
else
{
result = (int)entry.ScalarResult;
}
return result;
}
public override object ExecuteScalar()
{
object result;
int hashedKey = ResultCache.GetHashedKey(ResultCache.CacheEntryType.ExecuteScalar.ToString(), _dbCommand);
ResultCacheEntry entry = ResultCache.Instance[hashedKey];
if (entry == null)
{
result = _dbCommand.ExecuteScalar();
ResultCache.Instance.Add(hashedKey, result);
}
else
{
result = entry.ScalarResult;
}
return result;
}
public override void Prepare()
{
_dbCommand.Prepare();
}
#endregion
#region Private Methods
protected override DbConnection DbConnection
{
get
{
if (ConfigurationHelper.Instance.TestMode)
return new MockConnection();
else
return _dbCommand.Connection;
}
set
{
MockConnection castValue = value as MockConnection;
if (castValue == null)
_dbCommand.Connection = value;
else
_dbCommand.Connection = castValue.RealConnection;
}
}
protected override DbParameterCollection DbParameterCollection
{
get
{
return _dbCommand.Parameters;
}
}
protected override DbTransaction DbTransaction
{
get
{
if (ConfigurationHelper.Instance.TestMode)
return _dbTransaction;
else
return _dbCommand.Transaction;
}
set
{
if (ConfigurationHelper.Instance.TestMode)
_dbTransaction = value;
else
_dbCommand.Transaction = value;
}
}
protected override DbParameter CreateDbParameter()
{
return _dbCommand.CreateParameter();
}
protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior)
{
DbDataReader result = null;
int hashedKey = ResultCache.GetHashedKey(ResultCache.CacheEntryType.ExecuteDbDataReader.ToString(), _dbCommand);
ResultCacheEntry entry = ResultCache.Instance[hashedKey];
if (entry == null)
{
result = _dbCommand.ExecuteReader(behavior);
int recordsAffected = result.RecordsAffected;
DataSet ds = new DataSet();
DataReaderConverter.FillDataSetFromReader(ds, result);
ResultCache.Instance.Add(hashedKey, recordsAffected, ds);
result.Close();
result.Dispose();
result = null;
result = new MockDataReader(ds, recordsAffected);
}
else
{
result = new MockDataReader(entry.DataSetResult, (int)entry.ScalarResult);
}
return result;
}
#endregion
}
}
| |
using System;
using Microsoft.SPOT.Presentation.Controls;
using Microsoft.SPOT.Presentation;
using Microsoft.SPOT.Presentation.Media;
using Microsoft.SPOT.Presentation.Shapes;
namespace TicketVendingNETMF
{
public class HighlightingListBoxItem : ListBoxItem
{
public Object Tag;
public HighlightingListBoxItem()
{
this.Background = null;
}
public HighlightingListBoxItem(UIElement content)
{
this.Child = content;
this.Background = null;
}
protected override void OnIsSelectedChanged(bool isSelected)
{
if (isSelected)
{
this.Background = new SolidColorBrush(Colors.Blue);
}
else
this.Background = null;
}
}
public class HighlightingTextListBoxItem : HighlightingListBoxItem
{
private readonly Text text;
public HighlightingTextListBoxItem(Microsoft.SPOT.Font font, string content)
: base()
{
this.text = new Text(font, content);
this.text.SetMargin(2);
this.Child = this.text;
}
protected override void OnIsSelectedChanged(bool isSelected)
{
if (isSelected)
{
this.Background = new SolidColorBrush(Colors.Blue);
this.text.ForeColor = Color.White;
}
else
{
this.Background = null;
this.text.ForeColor = Color.Black;
}
}
}
public class HighlightingRoundTextListBoxItem : HighlightingListBoxItem
{
private readonly Text text;
private readonly Ellipse backgroundShape;
private readonly Color selectionColor;
public HighlightingRoundTextListBoxItem(Microsoft.SPOT.Font font, string content)
: base()
{
this.selectionColor = Colors.Blue;
this.backgroundShape = new Ellipse(13, 13);
this.backgroundShape.Stroke = new Pen(Color.Black, 1);
this.backgroundShape.HorizontalAlignment = HorizontalAlignment.Center;
this.backgroundShape.VerticalAlignment = VerticalAlignment.Center;
this.text = new Text(font, content);
this.text.HorizontalAlignment = HorizontalAlignment.Center;
this.text.VerticalAlignment = VerticalAlignment.Center;
this.text.SetMargin(2);
Panel panel = new Panel();
panel.Children.Add(this.backgroundShape);
panel.Children.Add(this.text);
this.Child = panel;
}
protected override void OnIsSelectedChanged(bool isSelected)
{
if (isSelected)
{
this.backgroundShape.Fill = new SolidColorBrush(this.selectionColor);
this.text.ForeColor = Color.White;
}
else
{
this.backgroundShape.Fill = null;
this.text.ForeColor = Color.Black;
}
}
}
public class StripPanel : Panel
{
private int[] columnSizes;
private Orientation orientation;
public StripPanel(Orientation orientation, int[] columnSizes)
{
if (columnSizes == null)
{
throw new ArgumentNullException("columnSizes");
}
if (columnSizes.Length == 0)
{
throw new ArgumentException("At least one column is required", "columnSizes");
}
for (int i = 0; i < columnSizes.Length; i++)
{
if (columnSizes[i] <= 0)
{
throw new ArgumentException("Column proportions must be greater than 0.", "columnSizes");
}
}
this.columnSizes = (int[])columnSizes.Clone();
this.orientation = orientation;
}
protected override void ArrangeOverride(int arrangeWidth, int arrangeHeight)
{
bool horizontal = this.orientation == Orientation.Horizontal;
long[] childPositions = new long[this.columnSizes.Length + 1];
long norm = 0;
for (int i = 0; i < columnSizes.Length; i++)
{
childPositions[i] = norm;
if (horizontal)
{
norm += columnSizes[i] * arrangeWidth;
}
else
{
norm += columnSizes[i] * arrangeHeight;
}
}
childPositions[columnSizes.Length] = norm;
int nChildren = base.Children.Count;
for (int i = 0; i < nChildren; i++)
{
int column = Math.Min(i, this.columnSizes.Length);
UIElement child = base.Children[i];
if (child.Visibility != Visibility.Collapsed)
{
int childDesiredWidth;
int childDesiredHeight;
child.GetDesiredSize(out childDesiredWidth, out childDesiredHeight);
if (horizontal)
{
int childPosition = (int)((childPositions[column] * arrangeWidth) / norm);
int childSize = (int)((childPositions[column + 1] * arrangeWidth) / norm) - childPosition;
child.Arrange(childPosition, 0, childSize, Math.Max(arrangeHeight, childDesiredHeight));
}
else
{
int childPosition = (int)((childPositions[column] * arrangeHeight) / norm);
int childSize = (int)((childPositions[column + 1] * arrangeHeight) / norm) - childPosition;
child.Arrange(0, childPosition, Math.Max(arrangeWidth, childDesiredWidth), childSize);
}
}
}
}
protected override void MeasureOverride(int availableWidth, int availableHeight, out int desiredWidth, out int desiredHeight)
{
base.MeasureOverride(availableWidth, availableHeight, out desiredWidth, out desiredHeight);
bool horizontal = this.orientation == Orientation.Horizontal;
if (horizontal)
{
desiredWidth = availableWidth;
}
else
{
desiredHeight = availableHeight;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
using Kent.Boogaart.HelperTrinity.Extensions;
namespace Kent.Boogaart.HelperTrinity
{
/// <summary>
/// Provides helper methods for raising exceptions.
/// </summary>
/// <remarks>
/// <para>
/// The <c>ExceptionHelper</c> class provides a centralised mechanism for throwing exceptions. This helps to keep exception
/// messages and types consistent.
/// </para>
/// <para>
/// Exception information is stored in an embedded resource called <c>ExceptionHelper.xml</c>, which must reside in the
/// <c>Properties</c> namespace for the assembly in which the for type is stored. For example, if the root namespace for
/// an assembly is <c>Company.Product</c> then the exception information must be stored in a resource called
/// <c>Company.Product.Properties.ExceptionHelper.xml</c>
/// </para>
/// <para>
/// The format for the exception information XML includes a grouping mechanism such that exception keys are scoped to the
/// type throwing the exception. Thus, different types can use the same exception key because they have different scopes in
/// the XML structure. An example of the format for the exception XML can be seen below.
/// </para>
/// <note type="implementation">
/// This class is designed to be efficient in the common case (ie. no exception thrown) but is quite inefficient if an
/// exception is actually thrown. This is not considered a problem, however, since an exception usually indicates that
/// execution cannot reliably continue.
/// </note>
/// </remarks>
/// <example>
/// The following example shows how an exception can thrown:
/// <code>
/// var exceptionHelper = new ExceptionHelper(typeof(Bar));
/// throw exceptionHelper.Resolve("myKey", "hello");
/// </code>
/// Assuming this code resides in a class called <c>Foo.Bar</c>, the XML configuration might look like this:
/// <code>
/// <![CDATA[
/// <?xml version="1.0" encoding="utf-8" ?>
///
/// <exceptionHelper>
/// <exceptionGroup type="Foo.Bar">
/// <exception key="myKey" type="System.NullReferenceException">
/// Foo is null but I'll say '{0}' anyway.
/// </exception>
/// </exceptionGroup>
/// </exceptionHelper>
/// ]]>
/// </code>
/// With this configuration, a <see cref="NullReferenceException"/> will be thrown. The exception message will be
/// "Foo is null but I'll say 'hello' anyway.".
/// </example>
/// <example>
/// The following example shows how an exception can be conditionally thrown:
/// <code>
/// var exceptionHelper = new ExceptionHelper(typeof(Bar));
/// exceptionHelper.ResolveAndThrowIf(foo == null, "myKey", "hello");
/// </code>
/// Assuming this code resides in a class called <c>Foo.Bar</c>, the XML configuration might look like this:
/// <code>
/// <![CDATA[
/// <?xml version="1.0" encoding="utf-8" ?>
///
/// <exceptionHelper>
/// <exceptionGroup type="Foo.Bar">
/// <exception key="myKey" type="System.NullReferenceException">
/// Foo is null but I'll say '{0}' anyway.
/// </exception>
/// </exceptionGroup>
/// </exceptionHelper>
/// ]]>
/// </code>
/// With this configuration, a <see cref="NullReferenceException"/> will be thrown if <c>foo</c> is <see langword="null"/>.
/// The exception message will be "Foo is null but I'll say 'hello' anyway.".
/// </example>
internal class ExceptionHelper
{
private static readonly IDictionary<Assembly, XDocument> _exceptionInfos = new Dictionary<Assembly, XDocument>();
private static readonly object _exceptionInfosLock = new object();
private readonly Type _forType;
private const string _typeAttributeName = "type";
/// <summary>
/// Initializes a new instance of the <c>ExceptionHelper</c> class.
/// </summary>
/// <param name="forType">
/// The type for which exceptions will be resolved.
/// </param>
internal ExceptionHelper(Type forType)
{
forType.AssertNotNull("forType");
_forType = forType;
}
/// <summary>
/// Resolves an exception.
/// </summary>
/// <param name="exceptionKey">
/// The exception key.
/// </param>
/// <param name="messageArgs">
/// Arguments to be substituted into the resolved exception's message.
/// </param>
/// <returns>
/// The resolved exception.
/// </returns>
[DebuggerHidden]
internal Exception Resolve(string exceptionKey, params object[] messageArgs)
{
return Resolve(exceptionKey, null, null, messageArgs);
}
/// <summary>
/// Resolves an exception.
/// </summary>
/// <param name="exceptionKey">
/// The exception key.
/// </param>
/// <param name="innerException">
/// The inner exception of the resolved exception.
/// </param>
/// <param name="messageArgs">
/// Arguments to be substituted into the resolved exception's message.
/// </param>
/// <returns>
/// The resolved exception.
/// </returns>
[DebuggerHidden]
internal Exception Resolve(string exceptionKey, Exception innerException, params object[] messageArgs)
{
return Resolve(exceptionKey, null, innerException, messageArgs);
}
/// <summary>
/// Resolves an exception.
/// </summary>
/// <param name="exceptionKey">
/// The exception key.
/// </param>
/// <param name="constructorArgs">
/// Additional arguments for the resolved exception's constructor.
/// </param>
/// <param name="innerException">
/// The inner exception of the resolved exception.
/// </param>
/// <returns>
/// The resolved exception.
/// </returns>
[DebuggerHidden]
internal Exception Resolve(string exceptionKey, object[] constructorArgs, Exception innerException)
{
return Resolve(exceptionKey, constructorArgs, innerException, null);
}
/// <summary>
/// Resolves an exception.
/// </summary>
/// <param name="exceptionKey">
/// The exception key.
/// </param>
/// <param name="constructorArgs">
/// Additional arguments for the resolved exception's constructor.
/// </param>
/// <param name="messageArgs">
/// Arguments to be substituted into the resolved exception's message.
/// </param>
/// <returns>
/// The resolved exception.
/// </returns>
[DebuggerHidden]
internal Exception Resolve(string exceptionKey, object[] constructorArgs, params object[] messageArgs)
{
return Resolve(exceptionKey, constructorArgs, null, messageArgs);
}
/// <summary>
/// Resolves an exception.
/// </summary>
/// <param name="exceptionKey">
/// The exception key.
/// </param>
/// <param name="constructorArgs">
/// Additional arguments for the resolved exception's constructor.
/// </param>
/// <param name="innerException">
/// The inner exception of the resolved exception.
/// </param>
/// <param name="messageArgs">
/// Arguments to be substituted into the resolved exception's message.
/// </param>
/// <returns>
/// The resolved exception.
/// </returns>
[DebuggerHidden]
internal Exception Resolve(string exceptionKey, object[] constructorArgs, Exception innerException, params object[] messageArgs)
{
exceptionKey.AssertNotNull("exceptionKey");
var exceptionInfo = GetExceptionInfo(_forType.Assembly);
var exceptionNode = (from exceptionGroup in exceptionInfo.Element("exceptionHelper").Elements("exceptionGroup")
from exception in exceptionGroup.Elements("exception")
where string.Equals(exceptionGroup.Attribute("type").Value, _forType.FullName, StringComparison.Ordinal) && string.Equals(exception.Attribute("key").Value, exceptionKey, StringComparison.Ordinal)
select exception).FirstOrDefault();
if (exceptionNode == null)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "The exception details for key '{0}' could not be found at /exceptionHelper/exceptionGroup[@type'{1}']/exception[@key='{2}'].", exceptionKey, _forType, exceptionKey));
}
var typeAttribute = exceptionNode.Attribute(_typeAttributeName);
if (typeAttribute == null)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "The '{0}' attribute could not be found for exception with key '{1}'", _typeAttributeName, exceptionKey));
}
var type = Type.GetType(typeAttribute.Value);
if (type == null)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Type '{0}' could not be loaded for exception with key '{1}'", typeAttribute.Value, exceptionKey));
}
if (!typeof(Exception).IsAssignableFrom(type))
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Type '{0}' for exception with key '{1}' does not inherit from '{2}'", type.FullName, exceptionKey, typeof(Exception).FullName));
}
var message = exceptionNode.Value.Trim();
if ((messageArgs != null) && (messageArgs.Length > 0))
{
message = string.Format(CultureInfo.InvariantCulture, message, messageArgs);
}
var constructorArgsList = new List<object>();
// message is always first
constructorArgsList.Add(message);
// next, any additional constructor args
if (constructorArgs != null)
{
constructorArgsList.AddRange(constructorArgs);
}
// finally, the inner exception, if any
if (innerException != null)
{
constructorArgsList.Add(innerException);
}
var constructorArgsArr = constructorArgsList.ToArray();
var bindingFlags = BindingFlags.Public | BindingFlags.Instance;
ConstructorInfo constructor = null;
try
{
object state;
constructor = (ConstructorInfo)Type.DefaultBinder.BindToMethod(bindingFlags, type.GetConstructors(bindingFlags), ref constructorArgsArr, null, null, null, out state);
}
catch (MissingMethodException)
{
//swallow and deal with below
}
if (constructor == null)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "An appropriate constructor could not be found for exception type '{0}, for exception with key '{1}'", type.FullName, exceptionKey));
}
return (Exception)constructor.Invoke(constructorArgsArr);
}
/// <summary>
/// Resolves and throws the specified exception if the given condition is met.
/// </summary>
/// <param name="condition">
/// The condition that determines whether the exception will be resolved and thrown.
/// </param>
/// <param name="exceptionKey">
/// The exception key.
/// </param>
/// <param name="messageArgs">
/// Arguments to be substituted into the resolved exception's message.
/// </param>
[DebuggerHidden]
internal void ResolveAndThrowIf(bool condition, string exceptionKey, params object[] messageArgs)
{
if (condition)
{
throw Resolve(exceptionKey, messageArgs);
}
}
/// <summary>
/// Resolves and throws the specified exception if the given condition is met.
/// </summary>
/// <param name="condition">
/// The condition that determines whether the exception will be resolved and thrown.
/// </param>
/// <param name="exceptionKey">
/// The exception key.
/// </param>
/// <param name="innerException">
/// The inner exception of the resolved exception.
/// </param>
/// <param name="messageArgs">
/// Arguments to be substituted into the resolved exception's message.
/// </param>
[DebuggerHidden]
internal void ResolveAndThrowIf(bool condition, string exceptionKey, Exception innerException, params object[] messageArgs)
{
if (condition)
{
throw Resolve(exceptionKey, innerException, messageArgs);
}
}
/// <summary>
/// Resolves and throws the specified exception if the given condition is met.
/// </summary>
/// <param name="condition">
/// The condition that determines whether the exception will be resolved and thrown.
/// </param>
/// <param name="exceptionKey">
/// The exception key.
/// </param>
/// <param name="constructorArgs">
/// Additional arguments for the resolved exception's constructor.
/// </param>
/// <param name="innerException">
/// The inner exception of the resolved exception.
/// </param>
[DebuggerHidden]
internal void ResolveAndThrowIf(bool condition, string exceptionKey, object[] constructorArgs, Exception innerException)
{
if (condition)
{
throw Resolve(exceptionKey, constructorArgs, innerException);
}
}
/// <summary>
/// Resolves and throws the specified exception if the given condition is met.
/// </summary>
/// <param name="condition">
/// The condition that determines whether the exception will be resolved and thrown.
/// </param>
/// <param name="exceptionKey">
/// The exception key.
/// </param>
/// <param name="constructorArgs">
/// Additional arguments for the resolved exception's constructor.
/// </param>
/// <param name="messageArgs">
/// Arguments to be substituted into the resolved exception's message.
/// </param>
[DebuggerHidden]
internal void ResolveAndThrowIf(bool condition, string exceptionKey, object[] constructorArgs, params object[] messageArgs)
{
if (condition)
{
throw Resolve(exceptionKey, constructorArgs, messageArgs);
}
}
/// <summary>
/// Resolves and throws the specified exception if the given condition is met.
/// </summary>
/// <param name="condition">
/// The condition that determines whether the exception will be resolved and thrown.
/// </param>
/// <param name="exceptionKey">
/// The exception key.
/// </param>
/// <param name="constructorArgs">
/// Additional arguments for the resolved exception's constructor.
/// </param>
/// <param name="innerException">
/// The inner exception of the resolved exception.
/// </param>
/// <param name="messageArgs">
/// Arguments to be substituted into the resolved exception's message.
/// </param>
[DebuggerHidden]
internal void ResolveAndThrowIf(bool condition, string exceptionKey, object[] constructorArgs, Exception innerException, params object[] messageArgs)
{
if (condition)
{
throw Resolve(exceptionKey, constructorArgs, innerException, messageArgs);
}
}
[DebuggerHidden]
private static XDocument GetExceptionInfo(Assembly assembly)
{
var retVal = (XDocument)null;
lock (_exceptionInfosLock)
{
if (_exceptionInfos.ContainsKey(assembly))
{
retVal = _exceptionInfos[assembly];
}
else
{
var assemblyName = new AssemblyName(assembly.FullName);
// if the exception info isn't cached we have to load it from an embedded resource in the calling assembly
var resourceName = string.Concat(assemblyName.Name, ".Properties.ExceptionHelper.xml");
using (var stream = assembly.GetManifestResourceStream(resourceName))
{
if (stream == null)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "XML resource file '{0}' could not be found in assembly '{1}'.", resourceName, assembly.FullName));
}
using (var streamReader = new StreamReader(stream))
{
retVal = XDocument.Load(streamReader);
}
}
_exceptionInfos[assembly] = retVal;
}
}
return retVal;
}
}
}
| |
// 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;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
namespace System.Runtime.Caching
{
internal struct ExpiresEntryRef
{
static internal readonly ExpiresEntryRef INVALID = new ExpiresEntryRef(0, 0);
private const uint ENTRY_MASK = 0x000000ffu;
private const uint PAGE_MASK = 0xffffff00u;
private const int PAGE_SHIFT = 8;
private uint _ref;
internal ExpiresEntryRef(int pageIndex, int entryIndex)
{
Dbg.Assert((pageIndex & 0x00ffffff) == pageIndex, "(pageIndex & 0x00ffffff) == pageIndex");
Dbg.Assert((entryIndex & ENTRY_MASK) == entryIndex, "(entryIndex & ENTRY_MASK) == entryIndex");
Dbg.Assert(entryIndex != 0 || pageIndex == 0, "entryIndex != 0 || pageIndex == 0");
_ref = ((((uint)pageIndex) << PAGE_SHIFT) | (((uint)(entryIndex)) & ENTRY_MASK));
}
public override bool Equals(object value)
{
if (value is ExpiresEntryRef)
{
return _ref == ((ExpiresEntryRef)value)._ref;
}
return false;
}
public static bool operator !=(ExpiresEntryRef r1, ExpiresEntryRef r2)
{
return r1._ref != r2._ref;
}
public static bool operator ==(ExpiresEntryRef r1, ExpiresEntryRef r2)
{
return r1._ref == r2._ref;
}
public override int GetHashCode()
{
return (int)_ref;
}
internal int PageIndex
{
get
{
int result = (int)(_ref >> PAGE_SHIFT);
return result;
}
}
internal int Index
{
get
{
int result = (int)(_ref & ENTRY_MASK);
return result;
}
}
internal bool IsInvalid
{
get
{
return _ref == 0;
}
}
}
[SuppressMessage("Microsoft.Portability", "CA1900:ValueTypeFieldsShouldBePortable", Justification = "Grandfathered suppression from original caching code checkin")]
[StructLayout(LayoutKind.Explicit)]
internal struct ExpiresEntry
{
[FieldOffset(0)]
internal DateTime _utcExpires;
[FieldOffset(0)]
internal ExpiresEntryRef _next;
[FieldOffset(4)]
internal int _cFree;
[FieldOffset(8)]
internal MemoryCacheEntry _cacheEntry;
}
internal struct ExpiresPage
{
internal ExpiresEntry[] _entries;
internal int _pageNext;
internal int _pagePrev;
}
internal struct ExpiresPageList
{
internal int _head;
internal int _tail;
}
internal sealed class ExpiresBucket
{
private const int NUM_ENTRIES = 127;
private const int LENGTH_ENTRIES = 128;
private const int MIN_PAGES_INCREMENT = 10;
private const int MAX_PAGES_INCREMENT = 340;
private const double MIN_LOAD_FACTOR = 0.5;
private const int COUNTS_LENGTH = 4;
private static readonly TimeSpan s_COUNT_INTERVAL = new TimeSpan(CacheExpires._tsPerBucket.Ticks / COUNTS_LENGTH);
private readonly CacheExpires _cacheExpires;
private readonly byte _bucket;
private ExpiresPage[] _pages;
private int _cEntriesInUse;
private int _cPagesInUse;
private int _cEntriesInFlush;
private int _minEntriesInUse;
private ExpiresPageList _freePageList;
private ExpiresPageList _freeEntryList;
private bool _blockReduce;
private DateTime _utcMinExpires;
private int[] _counts;
private DateTime _utcLastCountReset;
internal ExpiresBucket(CacheExpires cacheExpires, byte bucket, DateTime utcNow)
{
_cacheExpires = cacheExpires;
_bucket = bucket;
_counts = new int[COUNTS_LENGTH];
ResetCounts(utcNow);
InitZeroPages();
Dbg.Validate("CacheValidateExpires", this);
}
private void InitZeroPages()
{
Dbg.Assert(_cPagesInUse == 0, "_cPagesInUse == 0");
Dbg.Assert(_cEntriesInUse == 0, "_cEntriesInUse == 0");
Dbg.Assert(_cEntriesInFlush == 0, "_cEntriesInFlush == 0");
_pages = null;
_minEntriesInUse = -1;
_freePageList._head = -1;
_freePageList._tail = -1;
_freeEntryList._head = -1;
_freeEntryList._tail = -1;
}
private void ResetCounts(DateTime utcNow)
{
_utcLastCountReset = utcNow;
_utcMinExpires = DateTime.MaxValue;
for (int i = 0; i < _counts.Length; i++)
{
_counts[i] = 0;
}
}
private int GetCountIndex(DateTime utcExpires)
{
return Math.Max(0, (int)((utcExpires - _utcLastCountReset).Ticks / s_COUNT_INTERVAL.Ticks));
}
private void AddCount(DateTime utcExpires)
{
int ci = GetCountIndex(utcExpires);
for (int i = _counts.Length - 1; i >= ci; i--)
{
_counts[i]++;
}
if (utcExpires < _utcMinExpires)
{
_utcMinExpires = utcExpires;
}
}
private void RemoveCount(DateTime utcExpires)
{
int ci = GetCountIndex(utcExpires);
for (int i = _counts.Length - 1; i >= ci; i--)
{
_counts[i]--;
}
}
private int GetExpiresCount(DateTime utcExpires)
{
if (utcExpires < _utcMinExpires)
return 0;
int ci = GetCountIndex(utcExpires);
if (ci >= _counts.Length)
return _cEntriesInUse;
return _counts[ci];
}
private void AddToListHead(int pageIndex, ref ExpiresPageList list)
{
Dbg.Assert((list._head == -1) == (list._tail == -1), "(list._head == -1) == (list._tail == -1)");
(_pages[(pageIndex)]._pagePrev) = -1;
(_pages[(pageIndex)]._pageNext) = list._head;
if (list._head != -1)
{
Dbg.Assert((_pages[(list._head)]._pagePrev) == -1, "PagePrev(list._head) == -1");
(_pages[(list._head)]._pagePrev) = pageIndex;
}
else
{
list._tail = pageIndex;
}
list._head = pageIndex;
}
private void AddToListTail(int pageIndex, ref ExpiresPageList list)
{
Dbg.Assert((list._head == -1) == (list._tail == -1), "(list._head == -1) == (list._tail == -1)");
(_pages[(pageIndex)]._pageNext) = -1;
(_pages[(pageIndex)]._pagePrev) = list._tail;
if (list._tail != -1)
{
Dbg.Assert((_pages[(list._tail)]._pageNext) == -1, "PageNext(list._tail) == -1");
(_pages[(list._tail)]._pageNext) = pageIndex;
}
else
{
list._head = pageIndex;
}
list._tail = pageIndex;
}
private int RemoveFromListHead(ref ExpiresPageList list)
{
Dbg.Assert(list._head != -1, "list._head != -1");
int oldHead = list._head;
RemoveFromList(oldHead, ref list);
return oldHead;
}
private void RemoveFromList(int pageIndex, ref ExpiresPageList list)
{
Dbg.Assert((list._head == -1) == (list._tail == -1), "(list._head == -1) == (list._tail == -1)");
if ((_pages[(pageIndex)]._pagePrev) != -1)
{
Dbg.Assert((_pages[((_pages[(pageIndex)]._pagePrev))]._pageNext) == pageIndex, "PageNext(PagePrev(pageIndex)) == pageIndex");
(_pages[((_pages[(pageIndex)]._pagePrev))]._pageNext) = (_pages[(pageIndex)]._pageNext);
}
else
{
Dbg.Assert(list._head == pageIndex, "list._head == pageIndex");
list._head = (_pages[(pageIndex)]._pageNext);
}
if ((_pages[(pageIndex)]._pageNext) != -1)
{
Dbg.Assert((_pages[((_pages[(pageIndex)]._pageNext))]._pagePrev) == pageIndex, "PagePrev(PageNext(pageIndex)) == pageIndex");
(_pages[((_pages[(pageIndex)]._pageNext))]._pagePrev) = (_pages[(pageIndex)]._pagePrev);
}
else
{
Dbg.Assert(list._tail == pageIndex, "list._tail == pageIndex");
list._tail = (_pages[(pageIndex)]._pagePrev);
}
(_pages[(pageIndex)]._pagePrev) = -1;
(_pages[(pageIndex)]._pageNext) = -1;
}
private void MoveToListHead(int pageIndex, ref ExpiresPageList list)
{
Dbg.Assert(list._head != -1, "list._head != -1");
Dbg.Assert(list._tail != -1, "list._tail != -1");
if (list._head == pageIndex)
return;
RemoveFromList(pageIndex, ref list);
AddToListHead(pageIndex, ref list);
}
private void MoveToListTail(int pageIndex, ref ExpiresPageList list)
{
Dbg.Assert(list._head != -1, "list._head != -1");
Dbg.Assert(list._tail != -1, "list._tail != -1");
if (list._tail == pageIndex)
{
return;
}
RemoveFromList(pageIndex, ref list);
AddToListTail(pageIndex, ref list);
}
private void UpdateMinEntries()
{
if (_cPagesInUse <= 1)
{
_minEntriesInUse = -1;
}
else
{
int capacity = _cPagesInUse * NUM_ENTRIES;
Dbg.Assert(capacity > 0, "capacity > 0");
Dbg.Assert(MIN_LOAD_FACTOR < 1.0, "MIN_LOAD_FACTOR < 1.0");
_minEntriesInUse = (int)(capacity * MIN_LOAD_FACTOR);
if ((_minEntriesInUse - 1) > ((_cPagesInUse - 1) * NUM_ENTRIES))
{
_minEntriesInUse = -1;
}
}
}
private void RemovePage(int pageIndex)
{
Dbg.Assert((((_pages[(pageIndex)]._entries))[0]._cFree) == NUM_ENTRIES, "FreeEntryCount(EntriesI(pageIndex)) == NUM_ENTRIES");
RemoveFromList(pageIndex, ref _freeEntryList);
AddToListHead(pageIndex, ref _freePageList);
Dbg.Assert((_pages[(pageIndex)]._entries) != null, "EntriesI(pageIndex) != null");
(_pages[(pageIndex)]._entries) = null;
_cPagesInUse--;
if (_cPagesInUse == 0)
{
InitZeroPages();
}
else
{
UpdateMinEntries();
}
}
private ExpiresEntryRef GetFreeExpiresEntry()
{
Dbg.Assert(_freeEntryList._head >= 0, "_freeEntryList._head >= 0");
int pageIndex = _freeEntryList._head;
ExpiresEntry[] entries = (_pages[(pageIndex)]._entries);
int entryIndex = ((entries)[0]._next).Index;
((entries)[0]._next) = entries[entryIndex]._next;
((entries)[0]._cFree)--;
if (((entries)[0]._cFree) == 0)
{
Dbg.Assert(((entries)[0]._next).IsInvalid, "FreeEntryHead(entries).IsInvalid");
RemoveFromList(pageIndex, ref _freeEntryList);
}
return new ExpiresEntryRef(pageIndex, entryIndex);
}
private void AddExpiresEntryToFreeList(ExpiresEntryRef entryRef)
{
ExpiresEntry[] entries = (_pages[(entryRef.PageIndex)]._entries);
int entryIndex = entryRef.Index;
Dbg.Assert(entries[entryIndex]._cacheEntry == null, "entries[entryIndex]._cacheEntry == null");
entries[entryIndex]._cFree = 0;
entries[entryIndex]._next = ((entries)[0]._next);
((entries)[0]._next) = entryRef;
_cEntriesInUse--;
int pageIndex = entryRef.PageIndex;
((entries)[0]._cFree)++;
if (((entries)[0]._cFree) == 1)
{
AddToListHead(pageIndex, ref _freeEntryList);
}
else if (((entries)[0]._cFree) == NUM_ENTRIES)
{
RemovePage(pageIndex);
}
}
private void Expand()
{
Dbg.Assert(_cPagesInUse * NUM_ENTRIES == _cEntriesInUse, "_cPagesInUse * NUM_ENTRIES == _cEntriesInUse");
Dbg.Assert(_freeEntryList._head == -1, "_freeEntryList._head == -1");
Dbg.Assert(_freeEntryList._tail == -1, "_freeEntryList._tail == -1");
if (_freePageList._head == -1)
{
int oldLength;
if (_pages == null)
{
oldLength = 0;
}
else
{
oldLength = _pages.Length;
}
Dbg.Assert(_cPagesInUse == oldLength, "_cPagesInUse == oldLength");
Dbg.Assert(_cEntriesInUse == oldLength * NUM_ENTRIES, "_cEntriesInUse == oldLength * ExpiresEntryRef.NUM_ENTRIES");
int newLength = oldLength * 2;
newLength = Math.Max(oldLength + MIN_PAGES_INCREMENT, newLength);
newLength = Math.Min(newLength, oldLength + MAX_PAGES_INCREMENT);
Dbg.Assert(newLength > oldLength, "newLength > oldLength");
ExpiresPage[] newPages = new ExpiresPage[newLength];
for (int i = 0; i < oldLength; i++)
{
newPages[i] = _pages[i];
}
for (int i = oldLength; i < newPages.Length; i++)
{
newPages[i]._pagePrev = i - 1;
newPages[i]._pageNext = i + 1;
}
newPages[oldLength]._pagePrev = -1;
newPages[newPages.Length - 1]._pageNext = -1;
_freePageList._head = oldLength;
_freePageList._tail = newPages.Length - 1;
_pages = newPages;
}
int pageIndex = RemoveFromListHead(ref _freePageList);
AddToListHead(pageIndex, ref _freeEntryList);
ExpiresEntry[] entries = new ExpiresEntry[LENGTH_ENTRIES];
((entries)[0]._cFree) = NUM_ENTRIES;
for (int i = 0; i < entries.Length - 1; i++)
{
entries[i]._next = new ExpiresEntryRef(pageIndex, i + 1);
}
entries[entries.Length - 1]._next = ExpiresEntryRef.INVALID;
(_pages[(pageIndex)]._entries) = entries;
_cPagesInUse++;
UpdateMinEntries();
}
private void Reduce()
{
if (_cEntriesInUse >= _minEntriesInUse || _blockReduce)
return;
Dbg.Assert(_freeEntryList._head != -1, "_freeEntryList._head != -1");
Dbg.Assert(_freeEntryList._tail != -1, "_freeEntryList._tail != -1");
Dbg.Assert(_freeEntryList._head != _freeEntryList._tail, "_freeEntryList._head != _freeEntryList._tail");
int meanFree = (int)(NUM_ENTRIES - (NUM_ENTRIES * MIN_LOAD_FACTOR));
int pageIndexLast = _freeEntryList._tail;
int pageIndexCurrent = _freeEntryList._head;
int pageIndexNext;
ExpiresEntry[] entries;
for (; ;)
{
pageIndexNext = (_pages[(pageIndexCurrent)]._pageNext);
if ((((_pages[(pageIndexCurrent)]._entries))[0]._cFree) > meanFree)
{
MoveToListTail(pageIndexCurrent, ref _freeEntryList);
}
else
{
MoveToListHead(pageIndexCurrent, ref _freeEntryList);
}
if (pageIndexCurrent == pageIndexLast)
{
break;
}
pageIndexCurrent = pageIndexNext;
}
for (; ;)
{
if (_freeEntryList._tail == -1)
break;
entries = (_pages[(_freeEntryList._tail)]._entries);
Dbg.Assert(((entries)[0]._cFree) > 0, "FreeEntryCount(entries) > 0");
int availableFreeEntries = (_cPagesInUse * NUM_ENTRIES) - ((entries)[0]._cFree) - _cEntriesInUse;
if (availableFreeEntries < (NUM_ENTRIES - ((entries)[0]._cFree)))
break;
for (int i = 1; i < entries.Length; i++)
{
if (entries[i]._cacheEntry == null)
continue;
Dbg.Assert(_freeEntryList._head != _freeEntryList._tail, "_freeEntryList._head != _freeEntryList._tail");
ExpiresEntryRef newRef = GetFreeExpiresEntry();
Dbg.Assert(newRef.PageIndex != _freeEntryList._tail, "newRef.PageIndex != _freeEntryList._tail");
MemoryCacheEntry cacheEntry = entries[i]._cacheEntry;
cacheEntry.ExpiresEntryRef = newRef;
ExpiresEntry[] newEntries = (_pages[(newRef.PageIndex)]._entries);
newEntries[newRef.Index] = entries[i];
((entries)[0]._cFree)++;
}
RemovePage(_freeEntryList._tail);
Dbg.Validate("CacheValidateExpires", this);
}
}
internal void AddCacheEntry(MemoryCacheEntry cacheEntry)
{
lock (this)
{
if ((cacheEntry.State & (EntryState.AddedToCache | EntryState.AddingToCache)) == 0)
return;
ExpiresEntryRef entryRef = cacheEntry.ExpiresEntryRef;
Dbg.Assert((cacheEntry.ExpiresBucket == 0xff) == entryRef.IsInvalid, "(cacheEntry.ExpiresBucket == 0xff) == entryRef.IsInvalid");
if (cacheEntry.ExpiresBucket != 0xff || !entryRef.IsInvalid)
return;
if (_freeEntryList._head == -1)
{
Expand();
}
ExpiresEntryRef freeRef = GetFreeExpiresEntry();
Dbg.Assert(cacheEntry.ExpiresBucket == 0xff, "cacheEntry.ExpiresBucket == 0xff");
Dbg.Assert(cacheEntry.ExpiresEntryRef.IsInvalid, "cacheEntry.ExpiresEntryRef.IsInvalid");
cacheEntry.ExpiresBucket = _bucket;
cacheEntry.ExpiresEntryRef = freeRef;
ExpiresEntry[] entries = (_pages[(freeRef.PageIndex)]._entries);
int entryIndex = freeRef.Index;
entries[entryIndex]._cacheEntry = cacheEntry;
entries[entryIndex]._utcExpires = cacheEntry.UtcAbsExp;
AddCount(cacheEntry.UtcAbsExp);
_cEntriesInUse++;
if ((cacheEntry.State & (EntryState.AddedToCache | EntryState.AddingToCache)) == 0)
{
RemoveCacheEntryNoLock(cacheEntry);
}
}
}
private void RemoveCacheEntryNoLock(MemoryCacheEntry cacheEntry)
{
ExpiresEntryRef entryRef = cacheEntry.ExpiresEntryRef;
if (cacheEntry.ExpiresBucket != _bucket || entryRef.IsInvalid)
return;
ExpiresEntry[] entries = (_pages[(entryRef.PageIndex)]._entries);
int entryIndex = entryRef.Index;
RemoveCount(entries[entryIndex]._utcExpires);
cacheEntry.ExpiresBucket = 0xff;
cacheEntry.ExpiresEntryRef = ExpiresEntryRef.INVALID;
entries[entryIndex]._cacheEntry = null;
AddExpiresEntryToFreeList(entryRef);
if (_cEntriesInUse == 0)
{
ResetCounts(DateTime.UtcNow);
}
Reduce();
Dbg.Trace("CacheExpiresRemove",
"Removed item=" + cacheEntry.Key +
",_bucket=" + _bucket +
",ref=" + entryRef +
",now=" + Dbg.FormatLocalDate(DateTime.Now) +
",expires=" + cacheEntry.UtcAbsExp.ToLocalTime());
Dbg.Validate("CacheValidateExpires", this);
Dbg.Dump("CacheExpiresRemove", this);
}
internal void RemoveCacheEntry(MemoryCacheEntry cacheEntry)
{
lock (this)
{
RemoveCacheEntryNoLock(cacheEntry);
}
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Grandfathered suppression from original caching code checkin")]
internal void UtcUpdateCacheEntry(MemoryCacheEntry cacheEntry, DateTime utcExpires)
{
lock (this)
{
ExpiresEntryRef entryRef = cacheEntry.ExpiresEntryRef;
if (cacheEntry.ExpiresBucket != _bucket || entryRef.IsInvalid)
return;
ExpiresEntry[] entries = (_pages[(entryRef.PageIndex)]._entries);
int entryIndex = entryRef.Index;
Dbg.Assert(cacheEntry == entries[entryIndex]._cacheEntry);
RemoveCount(entries[entryIndex]._utcExpires);
AddCount(utcExpires);
entries[entryIndex]._utcExpires = utcExpires;
cacheEntry.UtcAbsExp = utcExpires;
Dbg.Validate("CacheValidateExpires", this);
Dbg.Trace("CacheExpiresUpdate", "Updated item " + cacheEntry.Key + " in bucket " + _bucket);
}
}
internal int FlushExpiredItems(DateTime utcNow, bool useInsertBlock)
{
if (_cEntriesInUse == 0 || GetExpiresCount(utcNow) == 0)
return 0;
Dbg.Assert(_cEntriesInFlush == 0, "_cEntriesInFlush == 0");
ExpiresEntryRef inFlushHead = ExpiresEntryRef.INVALID;
ExpiresEntry[] entries;
int entryIndex;
MemoryCacheEntry cacheEntry;
int flushed = 0;
try
{
if (useInsertBlock)
{
_cacheExpires.MemoryCacheStore.BlockInsert();
}
lock (this)
{
Dbg.Assert(_blockReduce == false, "_blockReduce == false");
if (_cEntriesInUse == 0 || GetExpiresCount(utcNow) == 0)
return 0;
ResetCounts(utcNow);
int cPages = _cPagesInUse;
for (int i = 0; i < _pages.Length; i++)
{
entries = _pages[i]._entries;
if (entries != null)
{
int cEntries = NUM_ENTRIES - ((entries)[0]._cFree);
for (int j = 1; j < entries.Length; j++)
{
cacheEntry = entries[j]._cacheEntry;
if (cacheEntry != null)
{
if (entries[j]._utcExpires > utcNow)
{
AddCount(entries[j]._utcExpires);
}
else
{
cacheEntry.ExpiresBucket = 0xff;
cacheEntry.ExpiresEntryRef = ExpiresEntryRef.INVALID;
entries[j]._cFree = 1;
entries[j]._next = inFlushHead;
inFlushHead = new ExpiresEntryRef(i, j);
flushed++;
_cEntriesInFlush++;
}
cEntries--;
if (cEntries == 0)
break;
}
}
cPages--;
if (cPages == 0)
break;
}
}
if (flushed == 0)
{
Dbg.Trace("CacheExpiresFlushTotal", "FlushExpiredItems flushed " + flushed +
" expired items, bucket=" + _bucket + "; Time=" + Dbg.FormatLocalDate(DateTime.Now));
return 0;
}
_blockReduce = true;
}
}
finally
{
if (useInsertBlock)
{
_cacheExpires.MemoryCacheStore.UnblockInsert();
}
}
Dbg.Assert(!inFlushHead.IsInvalid, "!inFlushHead.IsInvalid");
MemoryCacheStore cacheStore = _cacheExpires.MemoryCacheStore;
ExpiresEntryRef current = inFlushHead;
ExpiresEntryRef next;
while (!current.IsInvalid)
{
entries = (_pages[(current.PageIndex)]._entries);
entryIndex = current.Index;
next = entries[entryIndex]._next;
cacheEntry = entries[entryIndex]._cacheEntry;
entries[entryIndex]._cacheEntry = null;
Dbg.Assert(cacheEntry.ExpiresEntryRef.IsInvalid, "cacheEntry.ExpiresEntryRef.IsInvalid");
cacheStore.Remove(cacheEntry, cacheEntry, CacheEntryRemovedReason.Expired);
current = next;
}
try
{
if (useInsertBlock)
{
_cacheExpires.MemoryCacheStore.BlockInsert();
}
lock (this)
{
current = inFlushHead;
while (!current.IsInvalid)
{
entries = (_pages[(current.PageIndex)]._entries);
entryIndex = current.Index;
next = entries[entryIndex]._next;
_cEntriesInFlush--;
AddExpiresEntryToFreeList(current);
current = next;
}
Dbg.Assert(_cEntriesInFlush == 0, "_cEntriesInFlush == 0");
_blockReduce = false;
Reduce();
Dbg.Trace("CacheExpiresFlushTotal", "FlushExpiredItems flushed " + flushed +
" expired items, bucket=" + _bucket + "; Time=" + Dbg.FormatLocalDate(DateTime.Now));
Dbg.Validate("CacheValidateExpires", this);
Dbg.Dump("CacheExpiresFlush", this);
}
}
finally
{
if (useInsertBlock)
{
_cacheExpires.MemoryCacheStore.UnblockInsert();
}
}
return flushed;
}
}
internal sealed class CacheExpires
{
internal static readonly TimeSpan MIN_UPDATE_DELTA = new TimeSpan(0, 0, 1);
internal static readonly TimeSpan MIN_FLUSH_INTERVAL = new TimeSpan(0, 0, 1);
internal static readonly TimeSpan _tsPerBucket = new TimeSpan(0, 0, 20);
private const int NUMBUCKETS = 30;
private static readonly TimeSpan s_tsPerCycle = new TimeSpan(NUMBUCKETS * _tsPerBucket.Ticks);
private readonly MemoryCacheStore _cacheStore;
private readonly ExpiresBucket[] _buckets;
private GCHandleRef<Timer> _timerHandleRef;
private DateTime _utcLastFlush;
private int _inFlush;
internal CacheExpires(MemoryCacheStore cacheStore)
{
Dbg.Assert(NUMBUCKETS < Byte.MaxValue);
DateTime utcNow = DateTime.UtcNow;
_cacheStore = cacheStore;
_buckets = new ExpiresBucket[NUMBUCKETS];
for (byte b = 0; b < _buckets.Length; b++)
{
_buckets[b] = new ExpiresBucket(this, b, utcNow);
}
}
private int UtcCalcExpiresBucket(DateTime utcDate)
{
long ticksFromCycleStart = utcDate.Ticks % s_tsPerCycle.Ticks;
int bucket = (int)(((ticksFromCycleStart / _tsPerBucket.Ticks) + 1) % NUMBUCKETS);
return bucket;
}
private int FlushExpiredItems(bool checkDelta, bool useInsertBlock)
{
int flushed = 0;
if (Interlocked.Exchange(ref _inFlush, 1) == 0)
{
try
{
if (_timerHandleRef == null)
{
return 0;
}
DateTime utcNow = DateTime.UtcNow;
if (!checkDelta || utcNow - _utcLastFlush >= MIN_FLUSH_INTERVAL || utcNow < _utcLastFlush)
{
_utcLastFlush = utcNow;
foreach (ExpiresBucket bucket in _buckets)
{
flushed += bucket.FlushExpiredItems(utcNow, useInsertBlock);
}
Dbg.Trace("CacheExpiresFlushTotal", "FlushExpiredItems flushed a total of " + flushed + " items; Time=" + Dbg.FormatLocalDate(DateTime.Now));
Dbg.Dump("CacheExpiresFlush", this);
}
}
finally
{
Interlocked.Exchange(ref _inFlush, 0);
}
}
return flushed;
}
internal int FlushExpiredItems(bool useInsertBlock)
{
return FlushExpiredItems(true, useInsertBlock);
}
private void TimerCallback(object state)
{
FlushExpiredItems(false, false);
}
internal void EnableExpirationTimer(bool enable)
{
if (enable)
{
if (_timerHandleRef == null)
{
DateTime utcNow = DateTime.UtcNow;
TimeSpan due = _tsPerBucket - (new TimeSpan(utcNow.Ticks % _tsPerBucket.Ticks));
Timer timer;
// Don't capture the current ExecutionContext and its AsyncLocals onto the timer causing them to live forever
bool restoreFlow = false;
try
{
if (!ExecutionContext.IsFlowSuppressed())
{
ExecutionContext.SuppressFlow();
restoreFlow = true;
}
timer = new Timer(new TimerCallback(this.TimerCallback), null,
due.Ticks / TimeSpan.TicksPerMillisecond, _tsPerBucket.Ticks / TimeSpan.TicksPerMillisecond);
}
finally
{
// Restore the current ExecutionContext
if (restoreFlow)
ExecutionContext.RestoreFlow();
}
_timerHandleRef = new GCHandleRef<Timer>(timer);
Dbg.Trace("Cache", "Cache expiration timer created.");
}
}
else
{
GCHandleRef<Timer> timerHandleRef = _timerHandleRef;
if (timerHandleRef != null && Interlocked.CompareExchange(ref _timerHandleRef, null, timerHandleRef) == timerHandleRef)
{
timerHandleRef.Dispose();
Dbg.Trace("Cache", "Cache expiration timer disposed.");
while (_inFlush != 0)
{
Thread.Sleep(100);
}
}
}
}
internal MemoryCacheStore MemoryCacheStore
{
get
{
return _cacheStore;
}
}
internal void Add(MemoryCacheEntry cacheEntry)
{
DateTime utcNow = DateTime.UtcNow;
if (utcNow > cacheEntry.UtcAbsExp)
{
cacheEntry.UtcAbsExp = utcNow;
}
int bucket = UtcCalcExpiresBucket(cacheEntry.UtcAbsExp);
_buckets[bucket].AddCacheEntry(cacheEntry);
}
internal void Remove(MemoryCacheEntry cacheEntry)
{
byte bucket = cacheEntry.ExpiresBucket;
if (bucket != 0xff)
{
_buckets[bucket].RemoveCacheEntry(cacheEntry);
}
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Grandfathered suppression from original caching code checkin")]
internal void UtcUpdate(MemoryCacheEntry cacheEntry, DateTime utcNewExpires)
{
int oldBucket = cacheEntry.ExpiresBucket;
int newBucket = UtcCalcExpiresBucket(utcNewExpires);
if (oldBucket != newBucket)
{
Dbg.Trace("CacheExpiresUpdate",
"Updating item " + cacheEntry.Key + " from bucket " + oldBucket + " to new bucket " + newBucket);
if (oldBucket != 0xff)
{
_buckets[oldBucket].RemoveCacheEntry(cacheEntry);
cacheEntry.UtcAbsExp = utcNewExpires;
_buckets[newBucket].AddCacheEntry(cacheEntry);
}
}
else
{
if (oldBucket != 0xff)
{
_buckets[oldBucket].UtcUpdateCacheEntry(cacheEntry, utcNewExpires);
}
}
}
}
}
| |
//
// CGImage.cs: Implements the managed CGImage
//
// Authors: Mono Team
//
// Copyright 2009 Novell, Inc
// Copyright 2011, 2012 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
using MonoMac.Foundation;
namespace MonoMac.CoreGraphics {
#if MONOMAC
[Flags]
public enum CGWindowImageOption {
Default = 0,
BoundsIgnoreFraming = (1 << 0),
ShouldBeOpaque = (1 << 1),
OnlyShadows = (1 << 2)
}
[Flags]
public enum CGWindowListOption {
All = 0,
OnScreenOnly = (1 << 0),
OnScreenAboveWindow = (1 << 1),
OnScreenBelowWindow = (1 << 2),
IncludingWindow = (1 << 3),
ExcludeDesktopElements = (1 << 4)
}
#endif
public enum CGImageAlphaInfo {
None,
PremultipliedLast,
PremultipliedFirst,
Last,
First,
NoneSkipLast,
NoneSkipFirst,
Only
}
[Flags]
public enum CGBitmapFlags {
None,
PremultipliedLast,
PremultipliedFirst,
Last,
First,
NoneSkipLast,
NoneSkipFirst,
Only,
AlphaInfoMask = 0x1F,
FloatComponents = (1 << 8),
ByteOrderMask = 0x7000,
ByteOrderDefault = (0 << 12),
ByteOrder16Little = (1 << 12),
ByteOrder32Little = (2 << 12),
ByteOrder16Big = (3 << 12),
ByteOrder32Big = (4 << 12)
}
public class CGImage : INativeObject, IDisposable {
internal IntPtr handle;
// invoked by marshallers
public CGImage (IntPtr handle)
: this (handle, false)
{
this.handle = handle;
}
[Preserve (Conditional=true)]
internal CGImage (IntPtr handle, bool owns)
{
this.handle = handle;
if (!owns)
CGImageRetain (handle);
}
~CGImage ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public IntPtr Handle {
get { return handle; }
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static void CGImageRelease (IntPtr handle);
[DllImport (Constants.CoreGraphicsLibrary)]
extern static void CGImageRetain (IntPtr handle);
protected virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero){
CGImageRelease (handle);
handle = IntPtr.Zero;
}
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static IntPtr CGImageCreate(int size_t_width, int size_t_height, int size_t_bitsPerComponent,
int size_t_bitsPerPixel, int size_t_bytesPerRow,
IntPtr /* CGColorSpaceRef */ space,
CGBitmapFlags bitmapInfo,
IntPtr /* CGDataProviderRef */ provider,
float [] decode,
bool shouldInterpolate,
CGColorRenderingIntent intent);
public CGImage (int width, int height, int bitsPerComponent, int bitsPerPixel, int bytesPerRow,
CGColorSpace colorSpace, CGBitmapFlags bitmapFlags, CGDataProvider provider,
float [] decode, bool shouldInterpolate, CGColorRenderingIntent intent)
{
if (colorSpace == null)
throw new ArgumentNullException ("colorSpace");
if (width < 0)
throw new ArgumentException ("width");
if (height < 0)
throw new ArgumentException ("height");
if (bitsPerPixel < 0)
throw new ArgumentException ("bitsPerPixel");
if (bitsPerComponent < 0)
throw new ArgumentException ("bitsPerComponent");
if (bytesPerRow < 0)
throw new ArgumentException ("bytesPerRow");
handle = CGImageCreate (width, height, bitsPerComponent, bitsPerPixel, bytesPerRow,
colorSpace.Handle, bitmapFlags, provider == null ? IntPtr.Zero : provider.Handle,
decode,
shouldInterpolate, intent);
}
public CGImage (int width, int height, int bitsPerComponent, int bitsPerPixel, int bytesPerRow,
CGColorSpace colorSpace, CGImageAlphaInfo alphaInfo, CGDataProvider provider,
float [] decode, bool shouldInterpolate, CGColorRenderingIntent intent)
{
if (colorSpace == null)
throw new ArgumentNullException ("colorSpace");
if (width < 0)
throw new ArgumentException ("width");
if (height < 0)
throw new ArgumentException ("height");
if (bitsPerPixel < 0)
throw new ArgumentException ("bitsPerPixel");
if (bitsPerComponent < 0)
throw new ArgumentException ("bitsPerComponent");
if (bytesPerRow < 0)
throw new ArgumentException ("bytesPerRow");
handle = CGImageCreate (width, height, bitsPerComponent, bitsPerPixel, bytesPerRow,
colorSpace.Handle, (CGBitmapFlags) alphaInfo, provider == null ? IntPtr.Zero : provider.Handle,
decode,
shouldInterpolate, intent);
}
#if MONOMAC
[DllImport (Constants.CoreGraphicsLibrary)]
static extern IntPtr CGWindowListCreateImage(RectangleF screenBounds, CGWindowListOption windowOption, uint windowID, CGWindowImageOption imageOption);
public static CGImage ScreenImage (int windownumber, RectangleF bounds)
{
IntPtr imageRef = CGWindowListCreateImage(bounds, CGWindowListOption.IncludingWindow, (uint)windownumber,
CGWindowImageOption.Default);
return new CGImage(imageRef, true);
}
#else
[DllImport (Constants.UIKitLibrary)]
extern static IntPtr UIGetScreenImage ();
public static CGImage ScreenImage {
get {
return new CGImage (UIGetScreenImage (), true);
}
}
#endif
[DllImport (Constants.CoreGraphicsLibrary)]
extern static IntPtr CGImageCreateWithJPEGDataProvider(IntPtr /* CGDataProviderRef */ source,
float [] decode,
bool shouldInterpolate,
CGColorRenderingIntent intent);
public static CGImage FromJPEG (CGDataProvider provider, float [] decode, bool shouldInterpolate, CGColorRenderingIntent intent)
{
if (provider == null)
throw new ArgumentNullException ("provider");
var handle = CGImageCreateWithJPEGDataProvider (provider.Handle, decode, shouldInterpolate, intent);
if (handle == IntPtr.Zero)
return null;
return new CGImage (handle, true);
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static IntPtr CGImageCreateWithPNGDataProvider(IntPtr /*CGDataProviderRef*/ source,
float [] decode, bool shouldInterpolate,
CGColorRenderingIntent intent);
public static CGImage FromPNG (CGDataProvider provider, float [] decode, bool shouldInterpolate, CGColorRenderingIntent intent)
{
if (provider == null)
throw new ArgumentNullException ("provider");
var handle = CGImageCreateWithPNGDataProvider (provider.Handle, decode, shouldInterpolate, intent);
if (handle == IntPtr.Zero)
return null;
return new CGImage (handle, true);
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static IntPtr CGImageMaskCreate (int size_t_width, int size_t_height, int size_t_bitsPerComponent, int size_t_bitsPerPixel,
int size_t_bytesPerRow, IntPtr /* CGDataProviderRef */ provider, float [] decode, bool shouldInterpolate);
public static CGImage CreateMask (int width, int height, int bitsPerComponent, int bitsPerPixel, int bytesPerRow, CGDataProvider provider, float [] decode, bool shouldInterpolate)
{
if (width < 0)
throw new ArgumentException ("width");
if (height < 0)
throw new ArgumentException ("height");
if (bitsPerPixel < 0)
throw new ArgumentException ("bitsPerPixel");
if (bytesPerRow < 0)
throw new ArgumentException ("bytesPerRow");
if (provider == null)
throw new ArgumentNullException ("provider");
var handle = CGImageMaskCreate (width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, provider.Handle, decode, shouldInterpolate);
if (handle == IntPtr.Zero)
return null;
return new CGImage (handle, true);
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static IntPtr CGImageCreateWithMaskingColors(IntPtr image, float [] components);
public CGImage WithMaskingColors (float[] components)
{
int N = 2*ColorSpace.Components;
if (components == null)
throw new ArgumentNullException ("components");
if (components.Length != N)
throw new ArgumentException ("The argument 'components' must have 2N values, where N is the number of components in the color space of the image.", "components");
return new CGImage (CGImageCreateWithMaskingColors (Handle, components), true);
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static IntPtr CGImageCreateCopy(IntPtr image);
public CGImage Clone ()
{
return new CGImage (CGImageCreateCopy (handle), true);
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static IntPtr CGImageCreateCopyWithColorSpace(IntPtr image, IntPtr space);
public CGImage WithColorSpace (CGColorSpace cs)
{
return new CGImage (CGImageCreateCopyWithColorSpace (handle, cs.handle), true);
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static IntPtr CGImageCreateWithImageInRect(IntPtr image, RectangleF rect);
public CGImage WithImageInRect (RectangleF rect)
{
return new CGImage (CGImageCreateWithImageInRect (handle, rect), true);
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static IntPtr CGImageCreateWithMask(IntPtr image, IntPtr mask);
public CGImage WithMask (CGImage mask)
{
return new CGImage (CGImageCreateWithMask (handle, mask.handle), true);
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static int CGImageIsMask(IntPtr image);
public bool IsMask {
get {
return CGImageIsMask (handle) != 0;
}
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static int CGImageGetWidth(IntPtr image);
public int Width {
get {
return CGImageGetWidth (handle);
}
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static int CGImageGetHeight(IntPtr image);
public int Height {
get {
return CGImageGetHeight (handle);
}
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static int CGImageGetBitsPerComponent(IntPtr image);
public int BitsPerComponent {
get {
return CGImageGetBitsPerComponent (handle);
}
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static int CGImageGetBitsPerPixel(IntPtr image);
public int BitsPerPixel {
get {
return CGImageGetBitsPerPixel (handle);
}
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static int CGImageGetBytesPerRow(IntPtr image);
public int BytesPerRow {
get {
return CGImageGetBytesPerRow (handle);
}
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static IntPtr CGImageGetColorSpace(IntPtr image);
public CGColorSpace ColorSpace {
get {
return new CGColorSpace (CGImageGetColorSpace (handle));
}
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static CGImageAlphaInfo CGImageGetAlphaInfo(IntPtr image);
public CGImageAlphaInfo AlphaInfo {
get {
return CGImageGetAlphaInfo (handle);
}
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static IntPtr CGImageGetDataProvider(IntPtr image);
public CGDataProvider DataProvider {
get {
return new CGDataProvider (CGImageGetDataProvider (handle));
}
}
[DllImport (Constants.CoreGraphicsLibrary)]
unsafe extern static float * CGImageGetDecode(IntPtr image);
public unsafe float *Decode {
get {
return CGImageGetDecode (handle);
}
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static int CGImageGetShouldInterpolate(IntPtr image);
public bool ShouldInterpolate {
get {
return CGImageGetShouldInterpolate (handle) != 0;
}
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static CGColorRenderingIntent CGImageGetRenderingIntent(IntPtr image);
public CGColorRenderingIntent RenderingIntent {
get {
return CGImageGetRenderingIntent (handle);
}
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static CGBitmapFlags CGImageGetBitmapInfo(IntPtr image);
public CGBitmapFlags BitmapInfo {
get {
return CGImageGetBitmapInfo (handle);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace UpgradeYourself.Api.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
using System.Security;
using System.Security.Principal;
using System.Threading;
using System.ComponentModel;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
namespace System.Net.Security
{
//
// The class maintains the state of the authentication process and the security context.
// It encapsulates security context and does the real work in authentication and
// user data encryption with NEGO SSPI package.
//
// This is part of the NegotiateStream PAL.
//
internal class NegoState
{
private const int ERROR_TRUST_FAILURE = 1790; // Used to serialize protectionLevel or impersonationLevel mismatch error to the remote side.
private static readonly byte[] s_emptyMessage = new byte[0];
private static readonly AsyncCallback s_readCallback = new AsyncCallback(ReadCallback);
private static readonly AsyncCallback s_writeCallback = new AsyncCallback(WriteCallback);
private Stream _innerStream;
private bool _leaveStreamOpen;
private Exception _exception;
private StreamFramer _framer;
private NTAuthentication _context;
private int _nestedAuth;
internal const int MaxReadFrameSize = 64 * 1024;
internal const int MaxWriteDataSize = 63 * 1024; // 1k for the framing and trailer that is always less as per SSPI.
private bool _canRetryAuthentication;
private ProtectionLevel _expectedProtectionLevel;
private TokenImpersonationLevel _expectedImpersonationLevel;
private uint _writeSequenceNumber;
private uint _readSequenceNumber;
private ExtendedProtectionPolicy _extendedProtectionPolicy;
// SSPI does not send a server ack on successful auth.
// This is a state variable used to gracefully handle auth confirmation.
private bool _remoteOk = false;
internal NegoState(Stream innerStream, bool leaveStreamOpen)
{
if (innerStream == null)
{
throw new ArgumentNullException("stream");
}
_innerStream = innerStream;
_leaveStreamOpen = leaveStreamOpen;
}
internal static string DefaultPackage
{
get
{
return NegotiationInfoClass.Negotiate;
}
}
internal void ValidateCreateContext(
string package,
NetworkCredential credential,
string servicePrincipalName,
ExtendedProtectionPolicy policy,
ProtectionLevel protectionLevel,
TokenImpersonationLevel impersonationLevel)
{
if (policy != null)
{
// One of these must be set if EP is turned on
if (policy.CustomChannelBinding == null && policy.CustomServiceNames == null)
{
throw new ArgumentException(SR.net_auth_must_specify_extended_protection_scheme, "policy");
}
_extendedProtectionPolicy = policy;
}
else
{
_extendedProtectionPolicy = new ExtendedProtectionPolicy(PolicyEnforcement.Never);
}
ValidateCreateContext(package, true, credential, servicePrincipalName, _extendedProtectionPolicy.CustomChannelBinding, protectionLevel, impersonationLevel);
}
internal void ValidateCreateContext(
string package,
bool isServer,
NetworkCredential credential,
string servicePrincipalName,
ChannelBinding channelBinding,
ProtectionLevel protectionLevel,
TokenImpersonationLevel impersonationLevel)
{
if (_exception != null && !_canRetryAuthentication)
{
throw _exception;
}
if (_context != null && _context.IsValidContext)
{
throw new InvalidOperationException(SR.net_auth_reauth);
}
if (credential == null)
{
throw new ArgumentNullException("credential");
}
if (servicePrincipalName == null)
{
throw new ArgumentNullException("servicePrincipalName");
}
if (impersonationLevel != TokenImpersonationLevel.Identification &&
impersonationLevel != TokenImpersonationLevel.Impersonation &&
impersonationLevel != TokenImpersonationLevel.Delegation)
{
throw new ArgumentOutOfRangeException("impersonationLevel", impersonationLevel.ToString(), SR.net_auth_supported_impl_levels);
}
if (_context != null && IsServer != isServer)
{
throw new InvalidOperationException(SR.net_auth_client_server);
}
_exception = null;
_remoteOk = false;
_framer = new StreamFramer(_innerStream);
_framer.WriteHeader.MessageId = FrameHeader.HandshakeId;
_expectedProtectionLevel = protectionLevel;
_expectedImpersonationLevel = isServer ? impersonationLevel : TokenImpersonationLevel.None;
_writeSequenceNumber = 0;
_readSequenceNumber = 0;
Interop.SspiCli.ContextFlags flags = Interop.SspiCli.ContextFlags.Connection;
// A workaround for the client when talking to Win9x on the server side.
if (protectionLevel == ProtectionLevel.None && !isServer)
{
package = NegotiationInfoClass.NTLM;
}
else if (protectionLevel == ProtectionLevel.EncryptAndSign)
{
flags |= Interop.SspiCli.ContextFlags.Confidentiality;
}
else if (protectionLevel == ProtectionLevel.Sign)
{
// Assuming user expects NT4 SP4 and above.
flags |= Interop.SspiCli.ContextFlags.ReplayDetect | Interop.SspiCli.ContextFlags.SequenceDetect | Interop.SspiCli.ContextFlags.InitIntegrity;
}
if (isServer)
{
if (_extendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.WhenSupported)
{
flags |= Interop.SspiCli.ContextFlags.AllowMissingBindings;
}
if (_extendedProtectionPolicy.PolicyEnforcement != PolicyEnforcement.Never &&
_extendedProtectionPolicy.ProtectionScenario == ProtectionScenario.TrustedProxy)
{
flags |= Interop.SspiCli.ContextFlags.ProxyBindings;
}
}
else
{
// Server side should not request any of these flags.
if (protectionLevel != ProtectionLevel.None)
{
flags |= Interop.SspiCli.ContextFlags.MutualAuth;
}
if (impersonationLevel == TokenImpersonationLevel.Identification)
{
flags |= Interop.SspiCli.ContextFlags.InitIdentify;
}
if (impersonationLevel == TokenImpersonationLevel.Delegation)
{
flags |= Interop.SspiCli.ContextFlags.Delegate;
}
}
_canRetryAuthentication = false;
try
{
_context = new NTAuthentication(isServer, package, credential, servicePrincipalName, flags, channelBinding);
}
catch (Win32Exception e)
{
throw new AuthenticationException(SR.net_auth_SSPI, e);
}
}
private Exception SetException(Exception e)
{
if (_exception == null || !(_exception is ObjectDisposedException))
{
_exception = e;
}
if (_exception != null && _context != null)
{
_context.CloseContext();
}
return _exception;
}
internal bool IsAuthenticated
{
get
{
return _context != null && HandshakeComplete && _exception == null && _remoteOk;
}
}
internal bool IsMutuallyAuthenticated
{
get
{
if (!IsAuthenticated)
{
return false;
}
// Suppressing for NTLM since SSPI does not return correct value in the context flags.
if (_context.IsNTLM)
{
return false;
}
return _context.IsMutualAuthFlag;
}
}
internal bool IsEncrypted
{
get
{
return IsAuthenticated && _context.IsConfidentialityFlag;
}
}
internal bool IsSigned
{
get
{
return IsAuthenticated && (_context.IsIntegrityFlag || _context.IsConfidentialityFlag);
}
}
internal bool IsServer
{
get
{
return _context != null && _context.IsServer;
}
}
internal bool CanGetSecureStream
{
get
{
return (_context.IsConfidentialityFlag || _context.IsIntegrityFlag);
}
}
internal TokenImpersonationLevel AllowedImpersonation
{
get
{
CheckThrow(true);
return PrivateImpersonationLevel;
}
}
private TokenImpersonationLevel PrivateImpersonationLevel
{
get
{
// We should suppress the delegate flag in NTLM case.
return (_context.IsDelegationFlag && _context.ProtocolName != NegotiationInfoClass.NTLM) ? TokenImpersonationLevel.Delegation
: _context.IsIdentifyFlag ? TokenImpersonationLevel.Identification
: TokenImpersonationLevel.Impersonation;
}
}
private bool HandshakeComplete
{
get
{
return _context.IsCompleted && _context.IsValidContext;
}
}
internal IIdentity GetIdentity()
{
CheckThrow(true);
IIdentity result = null;
string name = _context.IsServer ? _context.AssociatedName : _context.Spn;
string protocol = "NTLM";
protocol = _context.ProtocolName;
if (_context.IsServer)
{
SecurityContextTokenHandle token = null;
try
{
token = _context.GetContextToken();
string authtype = _context.ProtocolName;
// TODO #5241:
// The following call was also specifying WindowsAccountType.Normal, true.
// WindowsIdentity.IsAuthenticated is no longer supported in CoreFX.
result = new WindowsIdentity(token.DangerousGetHandle(), authtype);
return result;
}
catch (SecurityException)
{
// Ignore and construct generic Identity if failed due to security problem.
}
finally
{
if (token != null)
{
token.Dispose();
}
}
}
// On the client we don't have access to the remote side identity.
result = new GenericIdentity(name, protocol);
return result;
}
internal void CheckThrow(bool authSucessCheck)
{
if (_exception != null)
{
throw _exception;
}
if (authSucessCheck && !IsAuthenticated)
{
throw new InvalidOperationException(SR.net_auth_noauth);
}
}
//
// This is to not depend on GC&SafeHandle class if the context is not needed anymore.
//
internal void Close()
{
// Mark this instance as disposed.
_exception = new ObjectDisposedException("NegotiateStream");
if (_context != null)
{
_context.CloseContext();
}
}
internal void ProcessAuthentication(LazyAsyncResult lazyResult)
{
CheckThrow(false);
if (Interlocked.Exchange(ref _nestedAuth, 1) == 1)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidnestedcall, lazyResult == null ? "BeginAuthenticate" : "Authenticate", "authenticate"));
}
try
{
if (_context.IsServer)
{
// Listen for a client blob.
StartReceiveBlob(lazyResult);
}
else
{
// Start with the first blob.
StartSendBlob(null, lazyResult);
}
}
catch (Exception e)
{
// Round-trip it through SetException().
e = SetException(e);
throw;
}
finally
{
if (lazyResult == null || _exception != null)
{
_nestedAuth = 0;
}
}
}
internal void EndProcessAuthentication(IAsyncResult result)
{
if (result == null)
{
throw new ArgumentNullException("asyncResult");
}
LazyAsyncResult lazyResult = result as LazyAsyncResult;
if (lazyResult == null)
{
throw new ArgumentException(SR.Format(SR.net_io_async_result, result.GetType().FullName), "asyncResult");
}
if (Interlocked.Exchange(ref _nestedAuth, 0) == 0)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndAuthenticate"));
}
// No "artificial" timeouts implemented so far, InnerStream controls that.
lazyResult.InternalWaitForCompletion();
Exception e = lazyResult.Result as Exception;
if (e != null)
{
// Round-trip it through the SetException().
e = SetException(e);
throw e;
}
}
private bool CheckSpn()
{
if (_context.IsKerberos)
{
return true;
}
if (_extendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.Never ||
_extendedProtectionPolicy.CustomServiceNames == null)
{
return true;
}
string clientSpn = _context.ClientSpecifiedSpn;
if (String.IsNullOrEmpty(clientSpn))
{
if (_extendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.WhenSupported)
{
return true;
}
}
else
{
return _extendedProtectionPolicy.CustomServiceNames.Contains(clientSpn);
}
return false;
}
//
// Client side starts here, but server also loops through this method.
//
private void StartSendBlob(byte[] message, LazyAsyncResult lazyResult)
{
Win32Exception win32exception = null;
if (message != s_emptyMessage)
{
message = GetOutgoingBlob(message, ref win32exception);
}
if (win32exception != null)
{
// Signal remote side on a failed attempt.
StartSendAuthResetSignal(lazyResult, message, win32exception);
return;
}
if (HandshakeComplete)
{
if (_context.IsServer && !CheckSpn())
{
Exception exception = new AuthenticationException(SR.net_auth_bad_client_creds_or_target_mismatch);
int statusCode = ERROR_TRUST_FAILURE;
message = new byte[8]; //sizeof(long)
for (int i = message.Length - 1; i >= 0; --i)
{
message[i] = (byte)(statusCode & 0xFF);
statusCode = (int)((uint)statusCode >> 8);
}
StartSendAuthResetSignal(lazyResult, message, exception);
return;
}
if (PrivateImpersonationLevel < _expectedImpersonationLevel)
{
Exception exception = new AuthenticationException(SR.Format(SR.net_auth_context_expectation, _expectedImpersonationLevel.ToString(), PrivateImpersonationLevel.ToString()));
int statusCode = ERROR_TRUST_FAILURE;
message = new byte[8]; //sizeof(long)
for (int i = message.Length - 1; i >= 0; --i)
{
message[i] = (byte)(statusCode & 0xFF);
statusCode = (int)((uint)statusCode >> 8);
}
StartSendAuthResetSignal(lazyResult, message, exception);
return;
}
ProtectionLevel result = _context.IsConfidentialityFlag ? ProtectionLevel.EncryptAndSign : _context.IsIntegrityFlag ? ProtectionLevel.Sign : ProtectionLevel.None;
if (result < _expectedProtectionLevel)
{
Exception exception = new AuthenticationException(SR.Format(SR.net_auth_context_expectation, result.ToString(), _expectedProtectionLevel.ToString()));
int statusCode = ERROR_TRUST_FAILURE;
message = new byte[8]; //sizeof(long)
for (int i = message.Length - 1; i >= 0; --i)
{
message[i] = (byte)(statusCode & 0xFF);
statusCode = (int)((uint)statusCode >> 8);
}
StartSendAuthResetSignal(lazyResult, message, exception);
return;
}
// Signal remote party that we are done
_framer.WriteHeader.MessageId = FrameHeader.HandshakeDoneId;
if (_context.IsServer)
{
// Server may complete now because client SSPI would not complain at this point.
_remoteOk = true;
// However the client will wait for server to send this ACK
//Force signaling server OK to the client
if (message == null)
{
message = s_emptyMessage;
}
}
}
else if (message == null || message == s_emptyMessage)
{
throw new InternalException();
}
if (message != null)
{
//even if we are completed, there could be a blob for sending.
if (lazyResult == null)
{
_framer.WriteMessage(message);
}
else
{
IAsyncResult ar = _framer.BeginWriteMessage(message, s_writeCallback, lazyResult);
if (!ar.CompletedSynchronously)
{
return;
}
_framer.EndWriteMessage(ar);
}
}
CheckCompletionBeforeNextReceive(lazyResult);
}
//
// This will check and logically complete the auth handshake.
//
private void CheckCompletionBeforeNextReceive(LazyAsyncResult lazyResult)
{
if (HandshakeComplete && _remoteOk)
{
// We are done with success.
if (lazyResult != null)
{
lazyResult.InvokeCallback();
}
return;
}
StartReceiveBlob(lazyResult);
}
//
// Server side starts here, but client also loops through this method.
//
private void StartReceiveBlob(LazyAsyncResult lazyResult)
{
byte[] message;
if (lazyResult == null)
{
message = _framer.ReadMessage();
}
else
{
IAsyncResult ar = _framer.BeginReadMessage(s_readCallback, lazyResult);
if (!ar.CompletedSynchronously)
{
return;
}
message = _framer.EndReadMessage(ar);
}
ProcessReceivedBlob(message, lazyResult);
}
private void ProcessReceivedBlob(byte[] message, LazyAsyncResult lazyResult)
{
// This is an EOF otherwise we would get at least *empty* message but not a null one.
if (message == null)
{
throw new AuthenticationException(SR.net_auth_eof, null);
}
// Process Header information.
if (_framer.ReadHeader.MessageId == FrameHeader.HandshakeErrId)
{
Win32Exception e = null;
if (message.Length >= 8) // sizeof(long)
{
// Try to recover remote win32 Exception.
long error = 0;
for (int i = 0; i < 8; ++i)
{
error = (error << 8) + message[i];
}
e = new Win32Exception((int)error);
}
if (e != null)
{
if (e.NativeErrorCode == (int)Interop.SecurityStatus.LogonDenied)
{
throw new InvalidCredentialException(SR.net_auth_bad_client_creds, e);
}
if (e.NativeErrorCode == ERROR_TRUST_FAILURE)
{
throw new AuthenticationException(SR.net_auth_context_expectation_remote, e);
}
}
throw new AuthenticationException(SR.net_auth_alert, e);
}
if (_framer.ReadHeader.MessageId == FrameHeader.HandshakeDoneId)
{
_remoteOk = true;
}
else if (_framer.ReadHeader.MessageId != FrameHeader.HandshakeId)
{
throw new AuthenticationException(SR.Format(SR.net_io_header_id, "MessageId", _framer.ReadHeader.MessageId, FrameHeader.HandshakeId), null);
}
CheckCompletionBeforeNextSend(message, lazyResult);
}
//
// This will check and logically complete the auth handshake.
//
private void CheckCompletionBeforeNextSend(byte[] message, LazyAsyncResult lazyResult)
{
//If we are done don't go into send.
if (HandshakeComplete)
{
if (!_remoteOk)
{
throw new AuthenticationException(SR.Format(SR.net_io_header_id, "MessageId", _framer.ReadHeader.MessageId, FrameHeader.HandshakeDoneId), null);
}
if (lazyResult != null)
{
lazyResult.InvokeCallback();
}
return;
}
// Not yet done, get a new blob and send it if any.
StartSendBlob(message, lazyResult);
}
//
// This is to reset auth state on the remote side.
// If this write succeeds we will allow auth retrying.
//
private void StartSendAuthResetSignal(LazyAsyncResult lazyResult, byte[] message, Exception exception)
{
_framer.WriteHeader.MessageId = FrameHeader.HandshakeErrId;
Win32Exception win32exception = exception as Win32Exception;
if (win32exception != null && win32exception.NativeErrorCode == (int)Interop.SecurityStatus.LogonDenied)
{
if (IsServer)
{
exception = new InvalidCredentialException(SR.net_auth_bad_client_creds, exception);
}
else
{
exception = new InvalidCredentialException(SR.net_auth_bad_client_creds_or_target_mismatch, exception);
}
}
if (!(exception is AuthenticationException))
{
exception = new AuthenticationException(SR.net_auth_SSPI, exception);
}
if (lazyResult == null)
{
_framer.WriteMessage(message);
}
else
{
lazyResult.Result = exception;
IAsyncResult ar = _framer.BeginWriteMessage(message, s_writeCallback, lazyResult);
if (!ar.CompletedSynchronously)
{
return;
}
_framer.EndWriteMessage(ar);
}
_canRetryAuthentication = true;
throw exception;
}
private static void WriteCallback(IAsyncResult transportResult)
{
if (!(transportResult.AsyncState is LazyAsyncResult))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("WriteCallback|State type is wrong, expected LazyAsyncResult.");
}
Debug.Fail("WriteCallback|State type is wrong, expected LazyAsyncResult.");
}
if (transportResult.CompletedSynchronously)
{
return;
}
LazyAsyncResult lazyResult = (LazyAsyncResult)transportResult.AsyncState;
// Async completion.
try
{
NegoState authState = (NegoState)lazyResult.AsyncObject;
authState._framer.EndWriteMessage(transportResult);
// Special case for an error notification.
if (lazyResult.Result is Exception)
{
authState._canRetryAuthentication = true;
throw (Exception)lazyResult.Result;
}
authState.CheckCompletionBeforeNextReceive(lazyResult);
}
catch (Exception e)
{
if (lazyResult.InternalPeekCompleted)
{
// This will throw on a worker thread.
throw;
}
lazyResult.InvokeCallback(e);
}
}
private static void ReadCallback(IAsyncResult transportResult)
{
if (!(transportResult.AsyncState is LazyAsyncResult))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("ReadCallback|State type is wrong, expected LazyAsyncResult.");
}
Debug.Fail("ReadCallback|State type is wrong, expected LazyAsyncResult.");
}
if (transportResult.CompletedSynchronously)
{
return;
}
LazyAsyncResult lazyResult = (LazyAsyncResult)transportResult.AsyncState;
// Async completion.
try
{
NegoState authState = (NegoState)lazyResult.AsyncObject;
byte[] message = authState._framer.EndReadMessage(transportResult);
authState.ProcessReceivedBlob(message, lazyResult);
}
catch (Exception e)
{
if (lazyResult.InternalPeekCompleted)
{
// This will throw on a worker thread.
throw;
}
lazyResult.InvokeCallback(e);
}
}
private unsafe byte[] GetOutgoingBlob(byte[] incomingBlob, ref Win32Exception e)
{
Interop.SecurityStatus statusCode;
byte[] message = _context.GetOutgoingBlob(incomingBlob, false, out statusCode);
if (((int)statusCode & unchecked((int)0x80000000)) != 0)
{
e = new System.ComponentModel.Win32Exception((int)statusCode);
message = new byte[8]; //sizeof(long)
for (int i = message.Length - 1; i >= 0; --i)
{
message[i] = (byte)((uint)statusCode & 0xFF);
statusCode = (Interop.SecurityStatus)((uint)statusCode >> 8);
}
}
if (message != null && message.Length == 0)
{
message = s_emptyMessage;
}
return message;
}
internal int EncryptData(byte[] buffer, int offset, int count, ref byte[] outBuffer)
{
CheckThrow(true);
// SSPI seems to ignore this sequence number.
++_writeSequenceNumber;
return _context.Encrypt(buffer, offset, count, ref outBuffer, _writeSequenceNumber);
}
internal int DecryptData(byte[] buffer, int offset, int count, out int newOffset)
{
CheckThrow(true);
// SSPI seems to ignore this sequence number.
++_readSequenceNumber;
return _context.Decrypt(buffer, offset, count, out newOffset, _readSequenceNumber);
}
}
}
| |
/*
* Infoplus API
*
* Infoplus API.
*
* OpenAPI spec version: v1.0
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Infoplus.Model
{
/// <summary>
/// WarehouseDocument
/// </summary>
[DataContract]
public partial class WarehouseDocument : IEquatable<WarehouseDocument>
{
/// <summary>
/// Initializes a new instance of the <see cref="WarehouseDocument" /> class.
/// </summary>
[JsonConstructorAttribute]
protected WarehouseDocument() { }
/// <summary>
/// Initializes a new instance of the <see cref="WarehouseDocument" /> class.
/// </summary>
/// <param name="DocumentType">DocumentType (required).</param>
/// <param name="Name">Name.</param>
/// <param name="Description">Description.</param>
public WarehouseDocument(string DocumentType = null, string Name = null, string Description = null)
{
// to ensure "DocumentType" is required (not null)
if (DocumentType == null)
{
throw new InvalidDataException("DocumentType is a required property for WarehouseDocument and cannot be null");
}
else
{
this.DocumentType = DocumentType;
}
this.Name = Name;
this.Description = Description;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public int? Id { get; private set; }
/// <summary>
/// Gets or Sets DocumentType
/// </summary>
[DataMember(Name="documentType", EmitDefaultValue=false)]
public string DocumentType { get; set; }
/// <summary>
/// Gets or Sets ClientId
/// </summary>
[DataMember(Name="clientId", EmitDefaultValue=false)]
public int? ClientId { get; private set; }
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// Gets or Sets Description
/// </summary>
[DataMember(Name="description", EmitDefaultValue=false)]
public string Description { get; set; }
/// <summary>
/// Gets or Sets CreateDate
/// </summary>
[DataMember(Name="createDate", EmitDefaultValue=false)]
public DateTime? CreateDate { get; private set; }
/// <summary>
/// Gets or Sets ModifyDate
/// </summary>
[DataMember(Name="modifyDate", EmitDefaultValue=false)]
public DateTime? ModifyDate { get; private 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 WarehouseDocument {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" DocumentType: ").Append(DocumentType).Append("\n");
sb.Append(" ClientId: ").Append(ClientId).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Description: ").Append(Description).Append("\n");
sb.Append(" CreateDate: ").Append(CreateDate).Append("\n");
sb.Append(" ModifyDate: ").Append(ModifyDate).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 WarehouseDocument);
}
/// <summary>
/// Returns true if WarehouseDocument instances are equal
/// </summary>
/// <param name="other">Instance of WarehouseDocument to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(WarehouseDocument other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.DocumentType == other.DocumentType ||
this.DocumentType != null &&
this.DocumentType.Equals(other.DocumentType)
) &&
(
this.ClientId == other.ClientId ||
this.ClientId != null &&
this.ClientId.Equals(other.ClientId)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Description == other.Description ||
this.Description != null &&
this.Description.Equals(other.Description)
) &&
(
this.CreateDate == other.CreateDate ||
this.CreateDate != null &&
this.CreateDate.Equals(other.CreateDate)
) &&
(
this.ModifyDate == other.ModifyDate ||
this.ModifyDate != null &&
this.ModifyDate.Equals(other.ModifyDate)
);
}
/// <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.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.DocumentType != null)
hash = hash * 59 + this.DocumentType.GetHashCode();
if (this.ClientId != null)
hash = hash * 59 + this.ClientId.GetHashCode();
if (this.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.Description != null)
hash = hash * 59 + this.Description.GetHashCode();
if (this.CreateDate != null)
hash = hash * 59 + this.CreateDate.GetHashCode();
if (this.ModifyDate != null)
hash = hash * 59 + this.ModifyDate.GetHashCode();
return hash;
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
using u8 = System.Byte;
namespace Community.CsharpSqlite
{
using sqlite3_int64 = System.Int64;
using sqlite3_stmt = Sqlite3.Vdbe;
public partial class Sqlite3
{
/*
** 2005 July 8
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code associated with the ANALYZE command.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
**
*************************************************************************
*/
#if !SQLITE_OMIT_ANALYZE
//#include "sqliteInt.h"
/*
** This routine generates code that opens the sqlite_stat1 table for
** writing with cursor iStatCur. If the library was built with the
** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
** opened for writing using cursor (iStatCur+1)
**
** If the sqlite_stat1 tables does not previously exist, it is created.
** Similarly, if the sqlite_stat2 table does not exist and the library
** is compiled with SQLITE_ENABLE_STAT2 defined, it is created.
**
** Argument zWhere may be a pointer to a buffer containing a table name,
** or it may be a NULL pointer. If it is not NULL, then all entries in
** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
** with the named table are deleted. If zWhere==0, then code is generated
** to delete all stat table entries.
*/
public struct _aTable
{
public string zName;
public string zCols;
public _aTable( string zName, string zCols )
{
this.zName = zName;
this.zCols = zCols;
}
};
static _aTable[] aTable = new _aTable[]{
new _aTable( "sqlite_stat1", "tbl,idx,stat" ),
#if SQLITE_ENABLE_STAT2
new _aTable( "sqlite_stat2", "tbl,idx,sampleno,sample" ),
#endif
};
static void openStatTable(
Parse pParse, /* Parsing context */
int iDb, /* The database we are looking in */
int iStatCur, /* Open the sqlite_stat1 table on this cursor */
string zWhere, /* Delete entries for this table or index */
string zWhereType /* Either "tbl" or "idx" */
)
{
int[] aRoot = new int[] { 0, 0 };
u8[] aCreateTbl = new u8[] { 0, 0 };
int i;
sqlite3 db = pParse.db;
Db pDb;
Vdbe v = sqlite3GetVdbe( pParse );
if ( v == null )
return;
Debug.Assert( sqlite3BtreeHoldsAllMutexes( db ) );
Debug.Assert( sqlite3VdbeDb( v ) == db );
pDb = db.aDb[iDb];
for ( i = 0; i < ArraySize( aTable ); i++ )
{
string zTab = aTable[i].zName;
Table pStat;
if ( ( pStat = sqlite3FindTable( db, zTab, pDb.zName ) ) == null )
{
/* The sqlite_stat[12] table does not exist. Create it. Note that a
** side-effect of the CREATE TABLE statement is to leave the rootpage
** of the new table in register pParse.regRoot. This is important
** because the OpenWrite opcode below will be needing it. */
sqlite3NestedParse( pParse,
"CREATE TABLE %Q.%s(%s)", pDb.zName, zTab, aTable[i].zCols
);
aRoot[i] = pParse.regRoot;
aCreateTbl[i] = 1;
}
else
{
/* The table already exists. If zWhere is not NULL, delete all entries
** associated with the table zWhere. If zWhere is NULL, delete the
** entire contents of the table. */
aRoot[i] = pStat.tnum;
sqlite3TableLock( pParse, iDb, aRoot[i], 1, zTab );
if ( !String.IsNullOrEmpty( zWhere ) )
{
sqlite3NestedParse( pParse,
"DELETE FROM %Q.%s WHERE %s=%Q", pDb.zName, zTab, zWhereType, zWhere
);
}
else
{
/* The sqlite_stat[12] table already exists. Delete all rows. */
sqlite3VdbeAddOp2( v, OP_Clear, aRoot[i], iDb );
}
}
}
/* Open the sqlite_stat[12] tables for writing. */
for ( i = 0; i < ArraySize( aTable ); i++ )
{
sqlite3VdbeAddOp3( v, OP_OpenWrite, iStatCur + i, aRoot[i], iDb );
sqlite3VdbeChangeP4( v, -1, 3, P4_INT32 );
sqlite3VdbeChangeP5( v, aCreateTbl[i] );
}
}
/*
** Generate code to do an analysis of all indices associated with
** a single table.
*/
static void analyzeOneTable(
Parse pParse, /* Parser context */
Table pTab, /* Table whose indices are to be analyzed */
Index pOnlyIdx, /* If not NULL, only analyze this one index */
int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
int iMem /* Available memory locations begin here */
)
{
sqlite3 db = pParse.db; /* Database handle */
Index pIdx; /* An index to being analyzed */
int iIdxCur; /* Cursor open on index being analyzed */
Vdbe v; /* The virtual machine being built up */
int i; /* Loop counter */
int topOfLoop; /* The top of the loop */
int endOfLoop; /* The end of the loop */
int jZeroRows = -1; /* Jump from here if number of rows is zero */
int iDb; /* Index of database containing pTab */
int regTabname = iMem++; /* Register containing table name */
int regIdxname = iMem++; /* Register containing index name */
int regSampleno = iMem++; /* Register containing next sample number */
int regCol = iMem++; /* Content of a column analyzed table */
int regRec = iMem++; /* Register holding completed record */
int regTemp = iMem++; /* Temporary use register */
int regRowid = iMem++; /* Rowid for the inserted record */
#if SQLITE_ENABLE_STAT2
int addr = 0; /* Instruction address */
int regTemp2 = iMem++; /* Temporary use register */
int regSamplerecno = iMem++; /* Index of next sample to record */
int regRecno = iMem++; /* Current sample index */
int regLast = iMem++; /* Index of last sample to record */
int regFirst = iMem++; /* Index of first sample to record */
#endif
v = sqlite3GetVdbe( pParse );
if ( v == null || NEVER( pTab == null ) )
{
return;
}
if ( pTab.tnum == 0 )
{
/* Do not gather statistics on views or virtual tables */
return;
}
if ( pTab.zName.StartsWith( "sqlite_", StringComparison.InvariantCultureIgnoreCase ) )
{
/* Do not gather statistics on system tables */
return;
}
Debug.Assert( sqlite3BtreeHoldsAllMutexes( db ) );
iDb = sqlite3SchemaToIndex( db, pTab.pSchema );
Debug.Assert( iDb >= 0 );
Debug.Assert( sqlite3SchemaMutexHeld(db, iDb, null) );
#if NO_SQLITE_OMIT_AUTHORIZATION
if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab.zName, 0,
db.aDb[iDb].zName ) ){
return;
}
#endif
/* Establish a read-lock on the table at the shared-cache level. */
sqlite3TableLock( pParse, iDb, pTab.tnum, 0, pTab.zName );
iIdxCur = pParse.nTab++;
sqlite3VdbeAddOp4( v, OP_String8, 0, regTabname, 0, pTab.zName, 0 );
for ( pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext )
{
int nCol;
KeyInfo pKey;
if ( pOnlyIdx != null && pOnlyIdx != pIdx )
continue;
nCol = pIdx.nColumn;
pKey = sqlite3IndexKeyinfo( pParse, pIdx );
if ( iMem + 1 + ( nCol * 2 ) > pParse.nMem )
{
pParse.nMem = iMem + 1 + ( nCol * 2 );
}
/* Open a cursor to the index to be analyzed. */
Debug.Assert( iDb == sqlite3SchemaToIndex( db, pIdx.pSchema ) );
sqlite3VdbeAddOp4( v, OP_OpenRead, iIdxCur, pIdx.tnum, iDb,
pKey, P4_KEYINFO_HANDOFF );
VdbeComment( v, "%s", pIdx.zName );
/* Populate the registers containing the index names. */
sqlite3VdbeAddOp4( v, OP_String8, 0, regIdxname, 0, pIdx.zName, 0 );
#if SQLITE_ENABLE_STAT2
/* If this iteration of the loop is generating code to analyze the
** first index in the pTab.pIndex list, then register regLast has
** not been populated. In this case populate it now. */
if ( pTab.pIndex == pIdx )
{
sqlite3VdbeAddOp2( v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno );
sqlite3VdbeAddOp2( v, OP_Integer, SQLITE_INDEX_SAMPLES * 2 - 1, regTemp );
sqlite3VdbeAddOp2( v, OP_Integer, SQLITE_INDEX_SAMPLES * 2, regTemp2 );
sqlite3VdbeAddOp2( v, OP_Count, iIdxCur, regLast );
sqlite3VdbeAddOp2( v, OP_Null, 0, regFirst );
addr = sqlite3VdbeAddOp3( v, OP_Lt, regSamplerecno, 0, regLast );
sqlite3VdbeAddOp3( v, OP_Divide, regTemp2, regLast, regFirst );
sqlite3VdbeAddOp3( v, OP_Multiply, regLast, regTemp, regLast );
sqlite3VdbeAddOp2( v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES * 2 - 2 );
sqlite3VdbeAddOp3( v, OP_Divide, regTemp2, regLast, regLast );
sqlite3VdbeJumpHere( v, addr );
}
/* Zero the regSampleno and regRecno registers. */
sqlite3VdbeAddOp2( v, OP_Integer, 0, regSampleno );
sqlite3VdbeAddOp2( v, OP_Integer, 0, regRecno );
sqlite3VdbeAddOp2( v, OP_Copy, regFirst, regSamplerecno );
#endif
/* The block of memory cells initialized here is used as follows.
**
** iMem:
** The total number of rows in the table.
**
** iMem+1 .. iMem+nCol:
** Number of distinct entries in index considering the
** left-most N columns only, where N is between 1 and nCol,
** inclusive.
**
** iMem+nCol+1 .. Mem+2*nCol:
** Previous value of indexed columns, from left to right.
**
** Cells iMem through iMem+nCol are initialized to 0. The others are
** initialized to contain an SQL NULL.
*/
for ( i = 0; i <= nCol; i++ )
{
sqlite3VdbeAddOp2( v, OP_Integer, 0, iMem + i );
}
for ( i = 0; i < nCol; i++ )
{
sqlite3VdbeAddOp2( v, OP_Null, 0, iMem + nCol + i + 1 );
}
/* Start the analysis loop. This loop runs through all the entries in
** the index b-tree. */
endOfLoop = sqlite3VdbeMakeLabel( v );
sqlite3VdbeAddOp2( v, OP_Rewind, iIdxCur, endOfLoop );
topOfLoop = sqlite3VdbeCurrentAddr( v );
sqlite3VdbeAddOp2( v, OP_AddImm, iMem, 1 );
for ( i = 0; i < nCol; i++ )
{
sqlite3VdbeAddOp3( v, OP_Column, iIdxCur, i, regCol );
CollSeq pColl;
if ( i == 0 )
{
#if SQLITE_ENABLE_STAT2
/* Check if the record that cursor iIdxCur points to contains a
** value that should be stored in the sqlite_stat2 table. If so,
** store it. */
int ne = sqlite3VdbeAddOp3( v, OP_Ne, regRecno, 0, regSamplerecno );
Debug.Assert( regTabname + 1 == regIdxname
&& regTabname + 2 == regSampleno
&& regTabname + 3 == regCol
);
sqlite3VdbeChangeP5( v, SQLITE_JUMPIFNULL );
sqlite3VdbeAddOp4( v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0 );
sqlite3VdbeAddOp2( v, OP_NewRowid, iStatCur + 1, regRowid );
sqlite3VdbeAddOp3( v, OP_Insert, iStatCur + 1, regRec, regRowid );
/* Calculate new values for regSamplerecno and regSampleno.
**
** sampleno = sampleno + 1
** samplerecno = samplerecno+(remaining records)/(remaining samples)
*/
sqlite3VdbeAddOp2( v, OP_AddImm, regSampleno, 1 );
sqlite3VdbeAddOp3( v, OP_Subtract, regRecno, regLast, regTemp );
sqlite3VdbeAddOp2( v, OP_AddImm, regTemp, -1 );
sqlite3VdbeAddOp2( v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2 );
sqlite3VdbeAddOp3( v, OP_Subtract, regSampleno, regTemp2, regTemp2 );
sqlite3VdbeAddOp3( v, OP_Divide, regTemp2, regTemp, regTemp );
sqlite3VdbeAddOp3( v, OP_Add, regSamplerecno, regTemp, regSamplerecno );
sqlite3VdbeJumpHere( v, ne );
sqlite3VdbeAddOp2( v, OP_AddImm, regRecno, 1 );
#endif
/* Always record the very first row */
sqlite3VdbeAddOp1( v, OP_IfNot, iMem + 1 );
}
Debug.Assert( pIdx.azColl != null );
Debug.Assert( pIdx.azColl[i] != null );
pColl = sqlite3LocateCollSeq( pParse, pIdx.azColl[i] );
sqlite3VdbeAddOp4( v, OP_Ne, regCol, 0, iMem + nCol + i + 1,
pColl, P4_COLLSEQ );
sqlite3VdbeChangeP5( v, SQLITE_NULLEQ );
}
//if( db.mallocFailed ){
// /* If a malloc failure has occurred, then the result of the expression
// ** passed as the second argument to the call to sqlite3VdbeJumpHere()
// ** below may be negative. Which causes an Debug.Assert() to fail (or an
// ** out-of-bounds write if SQLITE_DEBUG is not defined). */
// return;
//}
sqlite3VdbeAddOp2( v, OP_Goto, 0, endOfLoop );
for ( i = 0; i < nCol; i++ )
{
int addr2 = sqlite3VdbeCurrentAddr( v ) - ( nCol * 2 );
if ( i == 0 )
{
sqlite3VdbeJumpHere( v, addr2 - 1 ); /* Set jump dest for the OP_IfNot */
}
sqlite3VdbeJumpHere( v, addr2 ); /* Set jump dest for the OP_Ne */
sqlite3VdbeAddOp2( v, OP_AddImm, iMem + i + 1, 1 );
sqlite3VdbeAddOp3( v, OP_Column, iIdxCur, i, iMem + nCol + i + 1 );
}
/* End of the analysis loop. */
sqlite3VdbeResolveLabel( v, endOfLoop );
sqlite3VdbeAddOp2( v, OP_Next, iIdxCur, topOfLoop );
sqlite3VdbeAddOp1( v, OP_Close, iIdxCur );
/* Store the results in sqlite_stat1.
**
** The result is a single row of the sqlite_stat1 table. The first
** two columns are the names of the table and index. The third column
** is a string composed of a list of integer statistics about the
** index. The first integer in the list is the total number of entries
** in the index. There is one additional integer in the list for each
** column of the table. This additional integer is a guess of how many
** rows of the table the index will select. If D is the count of distinct
** values and K is the total number of rows, then the integer is computed
** as:
**
** I = (K+D-1)/D
**
** If K==0 then no entry is made into the sqlite_stat1 table.
** If K>0 then it is always the case the D>0 so division by zero
** is never possible.
*/
sqlite3VdbeAddOp2( v, OP_SCopy, iMem, regSampleno );
if ( jZeroRows < 0 )
{
jZeroRows = sqlite3VdbeAddOp1( v, OP_IfNot, iMem );
}
for ( i = 0; i < nCol; i++ )
{
sqlite3VdbeAddOp4( v, OP_String8, 0, regTemp, 0, " ", 0 );
sqlite3VdbeAddOp3( v, OP_Concat, regTemp, regSampleno, regSampleno );
sqlite3VdbeAddOp3( v, OP_Add, iMem, iMem + i + 1, regTemp );
sqlite3VdbeAddOp2( v, OP_AddImm, regTemp, -1 );
sqlite3VdbeAddOp3( v, OP_Divide, iMem + i + 1, regTemp, regTemp );
sqlite3VdbeAddOp1( v, OP_ToInt, regTemp );
sqlite3VdbeAddOp3( v, OP_Concat, regTemp, regSampleno, regSampleno );
}
sqlite3VdbeAddOp4( v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0 );
sqlite3VdbeAddOp2( v, OP_NewRowid, iStatCur, regRowid );
sqlite3VdbeAddOp3( v, OP_Insert, iStatCur, regRec, regRowid );
sqlite3VdbeChangeP5( v, OPFLAG_APPEND );
}
/* If the table has no indices, create a single sqlite_stat1 entry
** containing NULL as the index name and the row count as the content.
*/
if ( pTab.pIndex == null )
{
sqlite3VdbeAddOp3( v, OP_OpenRead, iIdxCur, pTab.tnum, iDb );
VdbeComment( v, "%s", pTab.zName );
sqlite3VdbeAddOp2( v, OP_Count, iIdxCur, regSampleno );
sqlite3VdbeAddOp1( v, OP_Close, iIdxCur );
jZeroRows = sqlite3VdbeAddOp1( v, OP_IfNot, regSampleno );
}
else
{
sqlite3VdbeJumpHere( v, jZeroRows );
jZeroRows = sqlite3VdbeAddOp0( v, OP_Goto );
}
sqlite3VdbeAddOp2( v, OP_Null, 0, regIdxname );
sqlite3VdbeAddOp4( v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0 );
sqlite3VdbeAddOp2( v, OP_NewRowid, iStatCur, regRowid );
sqlite3VdbeAddOp3( v, OP_Insert, iStatCur, regRec, regRowid );
sqlite3VdbeChangeP5( v, OPFLAG_APPEND );
if ( pParse.nMem < regRec )
pParse.nMem = regRec;
sqlite3VdbeJumpHere( v, jZeroRows );
}
/*
** Generate code that will cause the most recent index analysis to
** be loaded into internal hash tables where is can be used.
*/
static void loadAnalysis( Parse pParse, int iDb )
{
Vdbe v = sqlite3GetVdbe( pParse );
if ( v != null )
{
sqlite3VdbeAddOp1( v, OP_LoadAnalysis, iDb );
}
}
/*
** Generate code that will do an analysis of an entire database
*/
static void analyzeDatabase( Parse pParse, int iDb )
{
sqlite3 db = pParse.db;
Schema pSchema = db.aDb[iDb].pSchema; /* Schema of database iDb */
HashElem k;
int iStatCur;
int iMem;
sqlite3BeginWriteOperation( pParse, 0, iDb );
iStatCur = pParse.nTab;
pParse.nTab += 2;
openStatTable( pParse, iDb, iStatCur, null, null );
iMem = pParse.nMem + 1;
Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) );
//for(k=sqliteHashFirst(pSchema.tblHash); k; k=sqliteHashNext(k)){
for ( k = pSchema.tblHash.first; k != null; k = k.next )
{
Table pTab = (Table)k.data;// sqliteHashData( k );
analyzeOneTable( pParse, pTab, null, iStatCur, iMem );
}
loadAnalysis( pParse, iDb );
}
/*
** Generate code that will do an analysis of a single table in
** a database. If pOnlyIdx is not NULL then it is a single index
** in pTab that should be analyzed.
*/
static void analyzeTable( Parse pParse, Table pTab, Index pOnlyIdx)
{
int iDb;
int iStatCur;
Debug.Assert( pTab != null );
Debug.Assert( sqlite3BtreeHoldsAllMutexes( pParse.db ) );
iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema );
sqlite3BeginWriteOperation( pParse, 0, iDb );
iStatCur = pParse.nTab;
pParse.nTab += 2;
if ( pOnlyIdx != null )
{
openStatTable( pParse, iDb, iStatCur, pOnlyIdx.zName, "idx" );
}
else
{
openStatTable( pParse, iDb, iStatCur, pTab.zName, "tbl" );
}
analyzeOneTable( pParse, pTab, pOnlyIdx, iStatCur, pParse.nMem + 1 );
loadAnalysis( pParse, iDb );
}
/*
** Generate code for the ANALYZE command. The parser calls this routine
** when it recognizes an ANALYZE command.
**
** ANALYZE -- 1
** ANALYZE <database> -- 2
** ANALYZE ?<database>.?<tablename> -- 3
**
** Form 1 causes all indices in all attached databases to be analyzed.
** Form 2 analyzes all indices the single database named.
** Form 3 analyzes all indices associated with the named table.
*/
// OVERLOADS, so I don't need to rewrite parse.c
static void sqlite3Analyze( Parse pParse, int null_2, int null_3 )
{
sqlite3Analyze( pParse, null, null );
}
static void sqlite3Analyze( Parse pParse, Token pName1, Token pName2 )
{
sqlite3 db = pParse.db;
int iDb;
int i;
string z, zDb;
Table pTab;
Index pIdx;
Token pTableName = null;
/* Read the database schema. If an error occurs, leave an error message
** and code in pParse and return NULL. */
Debug.Assert( sqlite3BtreeHoldsAllMutexes( pParse.db ) );
if ( SQLITE_OK != sqlite3ReadSchema( pParse ) )
{
return;
}
Debug.Assert( pName2 != null || pName1 == null );
if ( pName1 == null )
{
/* Form 1: Analyze everything */
for ( i = 0; i < db.nDb; i++ )
{
if ( i == 1 )
continue; /* Do not analyze the TEMP database */
analyzeDatabase( pParse, i );
}
}
else if ( pName2.n == 0 )
{
/* Form 2: Analyze the database or table named */
iDb = sqlite3FindDb( db, pName1 );
if ( iDb >= 0 )
{
analyzeDatabase( pParse, iDb );
}
else
{
z = sqlite3NameFromToken( db, pName1 );
if ( z != null )
{
if ( ( pIdx = sqlite3FindIndex( db, z, null ) ) != null )
{
analyzeTable( pParse, pIdx.pTable, pIdx );
}
else if ( ( pTab = sqlite3LocateTable( pParse, 0, z, null ) ) != null )
{
analyzeTable( pParse, pTab, null );
}
z = null;//sqlite3DbFree( db, z );
}
}
}
else
{
/* Form 3: Analyze the fully qualified table name */
iDb = sqlite3TwoPartName( pParse, pName1, pName2, ref pTableName );
if ( iDb >= 0 )
{
zDb = db.aDb[iDb].zName;
z = sqlite3NameFromToken( db, pTableName );
if ( z != null )
{
if ( ( pIdx = sqlite3FindIndex( db, z, zDb ) ) != null )
{
analyzeTable( pParse, pIdx.pTable, pIdx );
}
else if ( ( pTab = sqlite3LocateTable( pParse, 0, z, zDb ) ) != null )
{
analyzeTable( pParse, pTab, null );
}
z = null; //sqlite3DbFree( db, z );
}
}
}
}
/*
** Used to pass information from the analyzer reader through to the
** callback routine.
*/
//typedef struct analysisInfo analysisInfo;
public struct analysisInfo
{
public sqlite3 db;
public string zDatabase;
};
/*
** This callback is invoked once for each index when reading the
** sqlite_stat1 table.
**
** argv[0] = name of the table
** argv[1] = name of the index (might be NULL)
** argv[2] = results of analysis - on integer for each column
**
** Entries for which argv[1]==NULL simply record the number of rows in
** the table.
*/
static int analysisLoader( object pData, sqlite3_int64 argc, object Oargv, object NotUsed )
{
string[] argv = (string[])Oargv;
analysisInfo pInfo = (analysisInfo)pData;
Index pIndex;
Table pTable;
int i, c, n;
int v;
string z;
Debug.Assert( argc == 3 );
UNUSED_PARAMETER2( NotUsed, argc );
if ( argv == null || argv[0] == null || argv[2] == null )
{
return 0;
}
pTable = sqlite3FindTable( pInfo.db, argv[0], pInfo.zDatabase );
if ( pTable == null )
{
return 0;
}
if ( !String.IsNullOrEmpty( argv[1] ) )
{
pIndex = sqlite3FindIndex( pInfo.db, argv[1], pInfo.zDatabase );
}
else
{
pIndex = null;
}
n = pIndex != null ? pIndex.nColumn : 0;
z = argv[2];
int zIndex = 0;
for ( i = 0; z != null && i <= n; i++ )
{
v = 0;
while ( zIndex < z.Length && ( c = z[zIndex] ) >= '0' && c <= '9' )
{
v = v * 10 + c - '0';
zIndex++;
}
if ( i == 0 )
pTable.nRowEst = (uint)v;
if ( pIndex == null )
break;
pIndex.aiRowEst[i] = v;
if ( zIndex < z.Length && z[zIndex] == ' ' )
zIndex++;
if ( z.Substring(zIndex).CompareTo("unordered")==0)//memcmp( z, "unordered", 10 ) == 0 )
{
pIndex.bUnordered = 1;
break;
}
}
return 0;
}
/*
** If the Index.aSample variable is not NULL, delete the aSample[] array
** and its contents.
*/
static void sqlite3DeleteIndexSamples( sqlite3 db, Index pIdx )
{
#if SQLITE_ENABLE_STAT2
if ( pIdx.aSample != null )
{
int j;
for ( j = 0; j < SQLITE_INDEX_SAMPLES; j++ )
{
IndexSample p = pIdx.aSample[j];
if ( p.eType == SQLITE_TEXT || p.eType == SQLITE_BLOB )
{
p.u.z = null;//sqlite3DbFree(db, p.u.z);
p.u.zBLOB = null;
}
}
sqlite3DbFree( db, ref pIdx.aSample );
}
#else
UNUSED_PARAMETER(db);
UNUSED_PARAMETER( pIdx );
#endif
}
/*
** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
** arrays. The contents of sqlite_stat2 are used to populate the
** Index.aSample[] arrays.
**
** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined
** during compilation and the sqlite_stat2 table is present, no data is
** read from it.
**
** If SQLITE_ENABLE_STAT2 was defined during compilation and the
** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
** returned. However, in this case, data is read from the sqlite_stat1
** table (if it is present) before returning.
**
** If an OOM error occurs, this function always sets db.mallocFailed.
** This means if the caller does not care about other errors, the return
** code may be ignored.
*/
static int sqlite3AnalysisLoad( sqlite3 db, int iDb )
{
analysisInfo sInfo;
HashElem i;
string zSql;
int rc;
Debug.Assert( iDb >= 0 && iDb < db.nDb );
Debug.Assert( db.aDb[iDb].pBt != null );
/* Clear any prior statistics */
Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) );
//for(i=sqliteHashFirst(&db.aDb[iDb].pSchema.idxHash);i;i=sqliteHashNext(i)){
for ( i = db.aDb[iDb].pSchema.idxHash.first; i != null; i = i.next )
{
Index pIdx = (Index)i.data;// sqliteHashData( i );
sqlite3DefaultRowEst( pIdx );
sqlite3DeleteIndexSamples( db, pIdx );
pIdx.aSample = null;
}
/* Check to make sure the sqlite_stat1 table exists */
sInfo.db = db;
sInfo.zDatabase = db.aDb[iDb].zName;
if ( sqlite3FindTable( db, "sqlite_stat1", sInfo.zDatabase ) == null )
{
return SQLITE_ERROR;
}
/* Load new statistics out of the sqlite_stat1 table */
zSql = sqlite3MPrintf( db,
"SELECT tbl, idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase );
//if ( zSql == null )
//{
// rc = SQLITE_NOMEM;
//}
//else
{
rc = sqlite3_exec( db, zSql, (dxCallback)analysisLoader, sInfo, 0 );
sqlite3DbFree( db, ref zSql );
}
/* Load the statistics from the sqlite_stat2 table. */
#if SQLITE_ENABLE_STAT2
if ( rc == SQLITE_OK && null == sqlite3FindTable( db, "sqlite_stat2", sInfo.zDatabase ) )
{
rc = SQLITE_ERROR;
}
if ( rc == SQLITE_OK )
{
sqlite3_stmt pStmt = null;
zSql = sqlite3MPrintf( db,
"SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase );
//if( null==zSql ){
//rc = SQLITE_NOMEM;
//}else{
rc = sqlite3_prepare( db, zSql, -1, ref pStmt, 0 );
sqlite3DbFree( db, ref zSql );
//}
if ( rc == SQLITE_OK )
{
while ( sqlite3_step( pStmt ) == SQLITE_ROW )
{
string zIndex; /* Index name */
Index pIdx; /* Pointer to the index object */
zIndex = sqlite3_column_text( pStmt, 0 );
pIdx = !String.IsNullOrEmpty( zIndex ) ? sqlite3FindIndex( db, zIndex, sInfo.zDatabase ) : null;
if ( pIdx != null )
{
int iSample = sqlite3_column_int( pStmt, 1 );
if ( iSample < SQLITE_INDEX_SAMPLES && iSample >= 0 )
{
int eType = sqlite3_column_type( pStmt, 2 );
if ( pIdx.aSample == null )
{
//static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
//pIdx->aSample = (IndexSample )sqlite3DbMallocRaw(0, sz);
//if( pIdx.aSample==0 ){
//db.mallocFailed = 1;
//break;
//}
pIdx.aSample = new IndexSample[SQLITE_INDEX_SAMPLES];//memset(pIdx->aSample, 0, sz);
}
//Debug.Assert( pIdx.aSample != null );
if ( pIdx.aSample[iSample] == null )
pIdx.aSample[iSample] = new IndexSample();
IndexSample pSample = pIdx.aSample[iSample];
{
pSample.eType = (u8)eType;
if ( eType == SQLITE_INTEGER || eType == SQLITE_FLOAT )
{
pSample.u.r = sqlite3_column_double( pStmt, 2 );
}
else if ( eType == SQLITE_TEXT || eType == SQLITE_BLOB )
{
string z = null;
byte[] zBLOB = null;
//string z = (string )(
//(eType==SQLITE_BLOB) ?
//sqlite3_column_blob(pStmt, 2):
//sqlite3_column_text(pStmt, 2)
//);
if ( eType == SQLITE_BLOB )
zBLOB = sqlite3_column_blob( pStmt, 2 );
else
z = sqlite3_column_text( pStmt, 2 );
int n = sqlite3_column_bytes( pStmt, 2 );
if ( n > 24 )
{
n = 24;
}
pSample.nByte = (u8)n;
if ( n < 1 )
{
pSample.u.z = null;
pSample.u.zBLOB = null;
}
else
{
pSample.u.z = z;
pSample.u.zBLOB = zBLOB;
//pSample->u.z = sqlite3DbMallocRaw(dbMem, n);
//if( pSample->u.z ){
// memcpy(pSample->u.z, z, n);
//}else{
// db->mallocFailed = 1;
// break;
//}
}
}
}
}
}
}
rc = sqlite3_finalize( pStmt );
}
}
#endif
//if( rc==SQLITE_NOMEM ){
// db.mallocFailed = 1;
//}
return rc;
}
#endif // * SQLITE_OMIT_ANALYZE */
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Timers;
using Nini.Config;
using OpenMetaverse;
using Aurora.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace Aurora.Modules.Restart
{
public class RestartModule : INonSharedRegionModule, IRestartModule
{
protected List<int> m_Alerts;
protected Timer m_CountdownTimer;
protected IDialogModule m_DialogModule;
protected UUID m_Initiator;
protected string m_Message;
protected bool m_Notice;
protected DateTime m_RestartBegin;
protected IScene m_scene;
#region INonSharedRegionModule Members
public void Initialise(IConfigSource config)
{
}
public void AddRegion(IScene scene)
{
m_scene = scene;
scene.RegisterModuleInterface<IRestartModule>(this);
if (MainConsole.Instance != null)
{
MainConsole.Instance.Commands.AddCommand(
"region restart",
"region restart <message> <time (in seconds)>",
"Restart the region", HandleRegionRestart);
MainConsole.Instance.Commands.AddCommand(
"region restart abort",
"region restart abort [<message>]",
"Restart the region", HandleRegionRestart);
}
}
public void RegionLoaded(IScene scene)
{
m_DialogModule = m_scene.RequestModuleInterface<IDialogModule>();
}
public void RemoveRegion(IScene scene)
{
}
public void Close()
{
}
public string Name
{
get { return "RestartModule"; }
}
public Type ReplaceableInterface
{
get { return typeof (IRestartModule); }
}
#endregion
#region IRestartModule Members
public TimeSpan TimeUntilRestart
{
get { return DateTime.Now - m_RestartBegin; }
}
public void ScheduleRestart(UUID initiator, string message, int[] alerts, bool notice)
{
if (alerts.Length == 0)
{
AbortRestart("Restart aborted");
return;
}
if (m_CountdownTimer != null)
{
MainConsole.Instance.Warn("[Region]: Reseting the restart timer for new settings.");
m_CountdownTimer.Stop();
m_CountdownTimer = null;
}
if (alerts == null)
{
RestartScene();
return;
}
m_Message = message;
m_Initiator = initiator;
m_Notice = notice;
m_Alerts = new List<int>(alerts);
m_Alerts.Sort();
m_Alerts.Reverse();
if (m_Alerts[0] == 0)
{
RestartScene();
return;
}
int nextInterval = DoOneNotice();
SetTimer(nextInterval);
}
public void AbortRestart(string message)
{
if (m_CountdownTimer != null)
{
m_CountdownTimer.Stop();
m_CountdownTimer = null;
if (m_DialogModule != null && message != String.Empty)
m_DialogModule.SendGeneralAlert(message);
MainConsole.Instance.Warn("[Region]: Region restart aborted");
}
}
/// <summary>
/// This causes the region to restart immediatley.
/// </summary>
public void RestartScene()
{
IConfig startupConfig = m_scene.Config.Configs["Startup"];
if (startupConfig != null)
{
if (startupConfig.GetBoolean("InworldRestartShutsDown", false))
{
//This will kill it asyncly
MainConsole.Instance.EndConsoleProcessing();
return;
}
}
MainConsole.Instance.Error("[Scene]: Restaring Now");
m_scene.RequestModuleInterface<ISceneManager>().RestartRegion(m_scene);
}
#endregion
public int DoOneNotice()
{
if (m_Alerts.Count == 0 || m_Alerts[0] == 0)
{
RestartScene();
return 0;
}
int nextAlert = 0;
while (m_Alerts.Count > 1)
{
if (m_Alerts[1] == m_Alerts[0])
{
m_Alerts.RemoveAt(0);
continue;
}
nextAlert = m_Alerts[1];
break;
}
int currentAlert = m_Alerts[0];
m_Alerts.RemoveAt(0);
int minutes = currentAlert/60;
string currentAlertString = String.Empty;
if (minutes > 0)
{
if (minutes == 1)
currentAlertString += "1 minute";
else
currentAlertString += String.Format("{0} minutes", minutes);
if ((currentAlert%60) != 0)
currentAlertString += " and ";
}
if ((currentAlert%60) != 0)
{
int seconds = currentAlert%60;
if (seconds == 1)
currentAlertString += "1 second";
else
currentAlertString += String.Format("{0} seconds", seconds);
}
string msg = String.Format(m_Message, currentAlertString);
if (m_DialogModule != null && msg != String.Empty)
{
if (m_Notice)
m_DialogModule.SendGeneralAlert(msg);
else
m_DialogModule.SendNotificationToUsersInRegion(m_Initiator, "System", msg);
MainConsole.Instance.Warn("[Region]: Region will restart in " + currentAlertString);
}
return currentAlert - nextAlert;
}
public void SetTimer(int intervalSeconds)
{
if (intervalSeconds == 0)
return;
m_CountdownTimer = new Timer {AutoReset = false, Interval = intervalSeconds*1000};
m_CountdownTimer.Elapsed += OnTimer;
m_CountdownTimer.Start();
}
private void OnTimer(object source, ElapsedEventArgs e)
{
int nextInterval = DoOneNotice();
SetTimer(nextInterval);
}
private void HandleRegionRestart(string[] args)
{
if (MainConsole.Instance.ConsoleScene != m_scene)
return;
if (args.Length < 4)
{
if (args.Length >= 3)
{
if (args[2] == "abort")
{
string msg = "Restart aborted";
if (args.Length > 3)
msg = args[3];
if (m_Alerts != null)
{
AbortRestart(msg);
}
return;
}
int seconds = 0;
if (int.TryParse(args[2], out seconds))
{
List<int> times = new List<int>();
while (seconds > 0)
{
times.Add(seconds);
if (seconds > 300)
seconds -= 120;
else if (seconds > 30)
seconds -= 30;
else
seconds -= 15;
}
string msg = "Region will restart in {0}";
if (args.Length > 3)
msg = args[3];
ScheduleRestart(UUID.Zero, msg, times.ToArray(), true);
return;
}
}
MainConsole.Instance.Info("Error: restart region <mode> <name> <time> ...");
return;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Build.RestApi.Swagger.Internals
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.DocAsCode.Common;
using Microsoft.DocAsCode.Exceptions;
using Microsoft.DocAsCode.Plugins;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
internal class SwaggerJsonBuilder
{
private IDictionary<string, SwaggerObjectBase> _documentObjectCache;
private const string DefinitionsKey = "definitions";
private const string ReferenceKey = "$ref";
private const string ParametersKey = "parameters";
private const string InternalRefNameKey = "x-internal-ref-name";
private const string InternalLoopRefNameKey = "x-internal-loop-ref-name";
public SwaggerObjectBase Read(string swaggerPath)
{
using (JsonReader reader = new JsonTextReader(EnvironmentContext.FileAbstractLayer.OpenReadText(swaggerPath)))
{
_documentObjectCache = new Dictionary<string, SwaggerObjectBase>();
var token = JToken.ReadFrom(reader);
var swaggerDir = Path.GetDirectoryName(swaggerPath);
if (string.IsNullOrEmpty(swaggerDir))
{
throw new DocfxException($"Directory of swagger file path {swaggerPath} should not be null or empty.");
}
var swagger = Build(token, swaggerDir);
RemoveReferenceDefinitions((SwaggerObject)swagger);
return ResolveReferences(swagger, new Stack<string>());
}
}
private SwaggerObjectBase Build(JToken token, string swaggerDir)
{
// Fetch from cache first
var location = JsonLocationHelper.GetLocation(token);
SwaggerObjectBase existingObject;
if (_documentObjectCache.TryGetValue(location, out existingObject))
{
return existingObject;
}
var jObject = token as JObject;
if (jObject != null)
{
// Only one $ref is allowed inside a swagger JObject
JToken referenceToken;
if (jObject.TryGetValue(ReferenceKey, out referenceToken))
{
if (referenceToken.Type != JTokenType.String && referenceToken.Type != JTokenType.Null)
{
throw new JsonException($"JSON reference $ref property must have a string or null value, instead of {referenceToken.Type}, location: {referenceToken.Path}.");
}
var swaggerReference = RestApiHelper.FormatReferenceFullPath((string)referenceToken);
switch (swaggerReference.Type)
{
case SwaggerFormattedReferenceType.InternalReference:
var deferredObject = new SwaggerReferenceObject
{
DeferredReference = swaggerReference.Path,
ReferenceName = swaggerReference.Name,
Location = location
};
// For swagger, other properties are still allowed besides $ref, e.g.
// "schema": {
// "$ref": "#/definitions/foo"
// "example": { }
// }
// Use Token property to keep other properties
// These properties cannot be referenced
jObject.Remove("$ref");
deferredObject.Token = jObject;
_documentObjectCache.Add(location, deferredObject);
return deferredObject;
case SwaggerFormattedReferenceType.ExternalReference:
jObject.Remove("$ref");
var externalJObject = LoadExternalReference(Path.Combine(swaggerDir, swaggerReference.Path));
RestApiHelper.CheckSpecificKey(externalJObject, ReferenceKey, () =>
{
throw new DocfxException($"{ReferenceKey} in {swaggerReference.Path} is not supported in external reference currently.");
});
foreach (var item in externalJObject)
{
JToken value;
if (jObject.TryGetValue(item.Key, out value))
{
Logger.LogWarning($"{item.Key} inside {jObject.Path} would be overwritten by the value of same key inside {swaggerReference.Path} with path {externalJObject.Path}.");
}
jObject[item.Key] = item.Value;
}
return new SwaggerValue
{
Location = location,
Token = jObject
};
default:
throw new DocfxException($"{referenceToken} does not support type {swaggerReference.Type}.");
}
}
var swaggerObject = new SwaggerObject { Location = location };
foreach (KeyValuePair<string, JToken> property in jObject)
{
swaggerObject.Dictionary.Add(property.Key, Build(property.Value, swaggerDir));
}
_documentObjectCache.Add(location, swaggerObject);
return swaggerObject;
}
var jArray = token as JArray;
if (jArray != null)
{
var swaggerArray = new SwaggerArray { Location = location };
foreach (var property in jArray)
{
swaggerArray.Array.Add(Build(property, swaggerDir));
}
return swaggerArray;
}
return new SwaggerValue
{
Location = location,
Token = token
};
}
private static JObject LoadExternalReference(string externalSwaggerPath)
{
if (!EnvironmentContext.FileAbstractLayer.Exists(externalSwaggerPath))
{
throw new DocfxException($"External swagger path not exist: {externalSwaggerPath}.");
}
using (JsonReader reader = new JsonTextReader(EnvironmentContext.FileAbstractLayer.OpenReadText(externalSwaggerPath)))
{
return JObject.Load(reader);
}
}
private static void RemoveReferenceDefinitions(SwaggerObject root)
{
// Remove definitions and parameters which has been added into _documentObjectCache
if (root.Dictionary.ContainsKey(DefinitionsKey))
{
root.Dictionary.Remove(DefinitionsKey);
}
if (root.Dictionary.ContainsKey(ParametersKey))
{
root.Dictionary.Remove(ParametersKey);
}
}
private SwaggerObjectBase ResolveReferences(SwaggerObjectBase swaggerBase, Stack<string> refStack)
{
if (swaggerBase.ReferencesResolved)
{
return swaggerBase;
}
swaggerBase.ReferencesResolved = true;
switch (swaggerBase.ObjectType)
{
case SwaggerObjectType.ReferenceObject:
{
var swagger = (SwaggerReferenceObject)swaggerBase;
if (!string.IsNullOrEmpty(swagger.DeferredReference))
{
if (swagger.DeferredReference[0] != '/')
{
throw new JsonException($"reference \"{swagger.DeferredReference}\" is not supported. Reference must be inside current schema document starting with /");
}
SwaggerObjectBase referencedObjectBase;
if (!_documentObjectCache.TryGetValue(swagger.DeferredReference, out referencedObjectBase))
{
throw new JsonException($"Could not resolve reference '{swagger.DeferredReference}' in the document.");
}
if (refStack.Contains(referencedObjectBase.Location))
{
var loopRef = new SwaggerLoopReferenceObject();
loopRef.Dictionary.Add(InternalLoopRefNameKey, new SwaggerValue { Token = swagger.ReferenceName });
return loopRef;
}
// Clone to avoid change the reference object in _documentObjectCache
refStack.Push(referencedObjectBase.Location);
var resolved = ResolveReferences(referencedObjectBase.Clone(), refStack);
var swaggerObject = ResolveSwaggerObject(resolved);
if (!swaggerObject.Dictionary.ContainsKey(InternalRefNameKey))
{
swaggerObject.Dictionary.Add(InternalRefNameKey, new SwaggerValue { Token = swagger.ReferenceName });
}
swagger.Reference = swaggerObject;
refStack.Pop();
}
return swagger;
}
case SwaggerObjectType.Object:
{
var swagger = (SwaggerObject)swaggerBase;
foreach (var key in swagger.Dictionary.Keys.ToList())
{
swagger.Dictionary[key] = ResolveReferences(swagger.Dictionary[key], refStack);
}
return swagger;
}
case SwaggerObjectType.Array:
{
var swagger = (SwaggerArray)swaggerBase;
for (int i = 0; i < swagger.Array.Count; i++)
{
swagger.Array[i] = ResolveReferences(swagger.Array[i], refStack);
}
return swagger;
}
case SwaggerObjectType.ValueType:
return swaggerBase;
default:
throw new NotSupportedException(swaggerBase.ObjectType.ToString());
}
}
private static SwaggerObject ResolveSwaggerObject(SwaggerObjectBase swaggerObjectBase)
{
var swaggerObject = swaggerObjectBase as SwaggerObject;
if (swaggerObject != null)
{
return swaggerObject;
}
var swaggerReferenceObject = swaggerObjectBase as SwaggerReferenceObject;
if (swaggerReferenceObject != null)
{
return swaggerReferenceObject.Reference;
}
throw new ArgumentException($"When resolving reference for {nameof(SwaggerReferenceObject)}, only support {nameof(SwaggerObject)} and {nameof(SwaggerReferenceObject)} as parameter.");
}
}
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Microsoft.Data.OData
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#if ODATALIB_ASYNC
using System.Threading.Tasks;
#endif
using Microsoft.Data.Edm;
using Microsoft.Data.OData.Metadata;
#endregion Namespaces
/// <summary>
/// Base class for OData readers that verifies a proper sequence of read calls on the reader.
/// </summary>
internal abstract class ODataReaderCore : ODataReader
{
/// <summary>The input to read the payload from.</summary>
private readonly ODataInputContext inputContext;
/// <summary>true if the reader was created for reading a feed; false when it was created for reading an entry.</summary>
private readonly bool readingFeed;
/// <summary>Stack of reader scopes to keep track of the current context of the reader.</summary>
private readonly Stack<Scope> scopes = new Stack<Scope>();
/// <summary>If not null, the reader will notify the implementer of the interface of relevant state changes in the reader.</summary>
private readonly IODataReaderWriterListener listener;
/// <summary>
/// The <see cref="FeedWithoutExpectedTypeValidator"/> to use for entries in this feed.
/// Only applies when reading a top-level feed; otherwise null.
/// </summary>
private readonly FeedWithoutExpectedTypeValidator feedValidator;
/// <summary>The number of entries which have been started but not yet ended.</summary>
private int currentEntryDepth;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="inputContext">The input to read the payload from.</param>
/// <param name="expectedEntityType">The expected entity type for the entry to be read (in case of entry reader) or entries in the feed to be read (in case of feed reader).</param>
/// <param name="readingFeed">true if the reader is created for reading a feed; false when it is created for reading an entry.</param>
/// <param name="listener">If not null, the reader will notify the implementer of the interface of relevant state changes in the reader.</param>
protected ODataReaderCore(ODataInputContext inputContext, IEdmEntityType expectedEntityType, bool readingFeed, IODataReaderWriterListener listener)
{
Debug.Assert(inputContext != null, "inputContext != null");
Debug.Assert(
expectedEntityType == null || inputContext.Model.IsUserModel(),
"If the expected type is specified we need model as well. We should have verified that by now.");
this.inputContext = inputContext;
this.readingFeed = readingFeed;
this.listener = listener;
this.currentEntryDepth = 0;
// create a collection validator when reading a top-level feed and a user model is present
if (this.readingFeed && this.inputContext.Model.IsUserModel())
{
this.feedValidator = new FeedWithoutExpectedTypeValidator();
}
this.EnterScope(new Scope(ODataReaderState.Start, null, expectedEntityType));
}
/// <summary>
/// The current state of the reader.
/// </summary>
public override sealed ODataReaderState State
{
get
{
this.inputContext.VerifyNotDisposed();
Debug.Assert(this.scopes != null && this.scopes.Count > 0, "A scope must always exist.");
return this.scopes.Peek().State;
}
}
/// <summary>
/// The most recent <see cref="ODataItem"/> that has been read.
/// </summary>
public override sealed ODataItem Item
{
get
{
this.inputContext.VerifyNotDisposed();
Debug.Assert(this.scopes != null && this.scopes.Count > 0, "A scope must always exist.");
return this.scopes.Peek().Item;
}
}
/// <summary>
/// Returns the current item as <see cref="ODataEntry"/>. Must only be called if the item actually is an entry.
/// </summary>
protected ODataEntry CurrentEntry
{
get
{
Debug.Assert(this.Item == null || this.Item is ODataEntry, "this.Item is ODataEntry");
return (ODataEntry)this.Item;
}
}
/// <summary>
/// Returns the current item as <see cref="ODataFeed"/>. Must only be called if the item actually is a feed.
/// </summary>
protected ODataFeed CurrentFeed
{
get
{
Debug.Assert(this.Item is ODataFeed, "this.Item is ODataFeed");
return (ODataFeed)this.Item;
}
}
/// <summary>
/// Returns the current item as <see cref="ODataNavigationLink"/>. Must only be called if the item actually is a navigation link.
/// </summary>
protected ODataNavigationLink CurrentNavigationLink
{
get
{
Debug.Assert(this.Item is ODataNavigationLink, "this.Item is ODataNavigationLink");
return (ODataNavigationLink)this.Item;
}
}
/// <summary>
/// Returns the current item as <see cref="ODataEntityReferenceLink"/>. Must only be called if the item actually is an entity reference link.
/// </summary>
protected ODataEntityReferenceLink CurrentEntityReferenceLink
{
get
{
Debug.Assert(this.Item is ODataEntityReferenceLink, "this.Item is ODataEntityReferenceLink");
return (ODataEntityReferenceLink)this.Item;
}
}
/// <summary>
/// Returns the expected entity type for the current scope.
/// </summary>
protected IEdmEntityType CurrentEntityType
{
get
{
Debug.Assert(this.scopes != null && this.scopes.Count > 0, "A scope must always exist.");
IEdmEntityType entityType = this.scopes.Peek().EntityType;
Debug.Assert(entityType == null || this.inputContext.Model.IsUserModel(), "We can only have entity type if we also have metadata.");
return entityType;
}
set
{
this.scopes.Peek().EntityType = value;
}
}
/// <summary>
/// Returns the current scope.
/// </summary>
protected Scope CurrentScope
{
get
{
Debug.Assert(this.scopes != null && this.scopes.Count > 0, "A scope must always exist.");
return this.scopes.Peek();
}
}
/// <summary>
/// Returns the scope of the entity owning the current link.
/// </summary>
protected Scope LinkParentEntityScope
{
get
{
Debug.Assert(this.scopes != null && this.scopes.Count > 1, "We must have at least two scoped for LinkParentEntityScope to be called.");
Debug.Assert(this.scopes.Peek().State == ODataReaderState.NavigationLinkStart, "The LinkParentEntityScope can only be accessed when in NavigationLinkStart state.");
return this.scopes.Skip(1).First();
}
}
/// <summary>
/// A flag indicating whether the reader is at the top level.
/// </summary>
protected bool IsTopLevel
{
get
{
Debug.Assert(this.scopes != null, "Scopes must exist.");
// there is the root scope at the top (when the writer has not started or has completed)
// and then the top-level scope (the top-level entry/feed item) as the second scope on the stack
return this.scopes.Count <= 2;
}
}
/// <summary>
/// True if we are reading an entry or feed that is the direct content of an expanded link. Otherwise false.
/// </summary>
protected bool IsExpandedLinkContent
{
get
{
Debug.Assert(this.scopes != null && this.scopes.Count > 1, "this.scopes.Count > 1");
Scope parentScope = this.scopes.Skip(1).First();
return parentScope.State == ODataReaderState.NavigationLinkStart;
}
}
/// <summary>
/// Set to true if a feed is being read.
/// </summary>
protected bool ReadingFeed
{
get
{
return this.readingFeed;
}
}
/// <summary>
/// Returns true if we are reading a nested payload, e.g. an entry or a feed within a parameters payload.
/// </summary>
protected bool IsReadingNestedPayload
{
get
{
return this.listener != null;
}
}
/// <summary>
/// Validator to validate consistency of entries in top-level feeds.
/// </summary>
/// <remarks>We only use this for top-level feeds since we support collection validation for
/// feeds only when metadata is available and in these cases we already validate the
/// types of the entries in nested feeds.</remarks>
protected FeedWithoutExpectedTypeValidator CurrentFeedValidator
{
get
{
Debug.Assert(this.State == ODataReaderState.EntryStart, "CurrentFeedValidator should only be called while reading an entry.");
// Only return the collection validator for entries in top-level feeds
return this.scopes.Count == 3 ? this.feedValidator : null;
}
}
/// <summary>
/// Reads the next <see cref="ODataItem"/> from the message payload.
/// </summary>
/// <returns>true if more items were read; otherwise false.</returns>
public override sealed bool Read()
{
this.VerifyCanRead(true);
return this.InterceptException(this.ReadSynchronously);
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously reads the next <see cref="ODataItem"/> from the message payload.
/// </summary>
/// <returns>A task that when completed indicates whether more items were read.</returns>
[SuppressMessage("Microsoft.MSInternal", "CA908:AvoidTypesThatRequireJitCompilationInPrecompiledAssemblies", Justification = "API design calls for a bool being returned from the task here.")]
public override sealed Task<bool> ReadAsync()
{
this.VerifyCanRead(false);
return this.ReadAsynchronously().FollowOnFaultWith(t => this.EnterScope(new Scope(ODataReaderState.Exception, null, null)));
}
#endif
/// <summary>
/// Implementation of the reader logic when in state 'Start'.
/// </summary>
/// <returns>true if more items can be read from the reader; otherwise false.</returns>
protected abstract bool ReadAtStartImplementation();
/// <summary>
/// Implementation of the reader logic when in state 'FeedStart'.
/// </summary>
/// <returns>true if more items can be read from the reader; otherwise false.</returns>
protected abstract bool ReadAtFeedStartImplementation();
/// <summary>
/// Implementation of the reader logic when in state 'FeedEnd'.
/// </summary>
/// <returns>true if more items can be read from the reader; otherwise false.</returns>
protected abstract bool ReadAtFeedEndImplementation();
/// <summary>
/// Implementation of the reader logic when in state 'EntryStart'.
/// </summary>
/// <returns>true if more items can be read from the reader; otherwise false.</returns>
protected abstract bool ReadAtEntryStartImplementation();
/// <summary>
/// Implementation of the reader logic when in state 'EntryEnd'.
/// </summary>
/// <returns>true if more items can be read from the reader; otherwise false.</returns>
protected abstract bool ReadAtEntryEndImplementation();
/// <summary>
/// Implementation of the reader logic when in state 'NavigationLinkStart'.
/// </summary>
/// <returns>true if more items can be read from the reader; otherwise false.</returns>
protected abstract bool ReadAtNavigationLinkStartImplementation();
/// <summary>
/// Implementation of the reader logic when in state 'NavigationLinkEnd'.
/// </summary>
/// <returns>true if more items can be read from the reader; otherwise false.</returns>
protected abstract bool ReadAtNavigationLinkEndImplementation();
/// <summary>
/// Implementation of the reader logic when in state 'EntityReferenceLink'.
/// </summary>
/// <returns>true if more items can be read from the reader; otherwise false.</returns>
protected abstract bool ReadAtEntityReferenceLink();
/// <summary>
/// Pushes the <paramref name="scope"/> on the stack of scopes.
/// </summary>
/// <param name="scope">The scope to enter.</param>
protected void EnterScope(Scope scope)
{
Debug.Assert(scope != null, "scope != null");
// TODO: implement some basic validation that the transitions are ok
this.scopes.Push(scope);
if (this.listener != null)
{
if (scope.State == ODataReaderState.Exception)
{
this.listener.OnException();
}
else if (scope.State == ODataReaderState.Completed)
{
this.listener.OnCompleted();
}
}
}
/// <summary>
/// Replaces the current scope with the specified <paramref name="scope"/>.
/// </summary>
/// <param name="scope">The scope to replace the current scope with.</param>
protected void ReplaceScope(Scope scope)
{
Debug.Assert(this.scopes.Count > 0, "Stack must always be non-empty.");
Debug.Assert(scope != null, "scope != null");
// TODO: implement some basic validation that the transitions are ok
this.scopes.Pop();
this.EnterScope(scope);
}
/// <summary>
/// Removes the current scope from the stack of all scopes.
/// </summary>
/// <param name="state">The expected state of the current scope (to be popped).</param>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "state", Justification = "Used in debug builds in assertions.")]
[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "scope", Justification = "Used in debug builds in assertions.")]
protected void PopScope(ODataReaderState state)
{
Debug.Assert(this.scopes.Count > 1, "Stack must have more than 1 items in order to pop an item.");
Scope scope = this.scopes.Pop();
Debug.Assert(scope.State == state, "scope.State == state");
}
/// <summary>
/// If an entity type name is found in the payload this method is called to apply it to the current scope.
/// This method should be called even if the type name was not found in which case a null should be passed in.
/// The method validates that some type will be available as the current entity type after it returns (if we are parsing using metadata).
/// </summary>
/// <param name="entityTypeNameFromPayload">The entity type name found in the payload or null if no type was specified in the payload.</param>
protected void ApplyEntityTypeNameFromPayload(string entityTypeNameFromPayload)
{
Debug.Assert(
this.scopes.Count > 0 && this.scopes.Peek().Item is ODataEntry,
"Entity type can be applied only when in entry scope.");
SerializationTypeNameAnnotation serializationTypeNameAnnotation;
EdmTypeKind targetTypeKind;
IEdmEntityTypeReference targetEntityTypeReference =
(IEdmEntityTypeReference)ReaderValidationUtils.ResolvePayloadTypeNameAndComputeTargetType(
EdmTypeKind.Entity,
/*defaultPrimitivePayloadType*/ null,
this.CurrentEntityType.ToTypeReference(),
entityTypeNameFromPayload,
this.inputContext.Model,
this.inputContext.MessageReaderSettings,
this.inputContext.Version,
() => EdmTypeKind.Entity,
out targetTypeKind,
out serializationTypeNameAnnotation);
IEdmEntityType targetEntityType = null;
ODataEntry entry = this.CurrentEntry;
if (targetEntityTypeReference != null)
{
targetEntityType = targetEntityTypeReference.EntityDefinition();
entry.TypeName = targetEntityType.ODataFullName();
if (serializationTypeNameAnnotation != null)
{
entry.SetAnnotation(serializationTypeNameAnnotation);
}
}
else if (entityTypeNameFromPayload != null)
{
entry.TypeName = entityTypeNameFromPayload;
}
// Set the current entity type since the type from payload might be more derived than
// the expected one.
this.CurrentEntityType = targetEntityType;
}
/// <summary>
/// Reads the next <see cref="ODataItem"/> from the message payload.
/// </summary>
/// <returns>true if more items were read; otherwise false.</returns>
private bool ReadSynchronously()
{
return this.ReadImplementation();
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously reads the next <see cref="ODataItem"/> from the message payload.
/// </summary>
/// <returns>A task that when completed indicates whether more items were read.</returns>
[SuppressMessage("Microsoft.MSInternal", "CA908:AvoidTypesThatRequireJitCompilationInPrecompiledAssemblies", Justification = "API design calls for a bool being returned from the task here.")]
private Task<bool> ReadAsynchronously()
{
// We are reading from the fully buffered read stream here; thus it is ok
// to use synchronous reads and then return a completed task
// NOTE: once we switch to fully async reading this will have to change
return TaskUtils.GetTaskForSynchronousOperation<bool>(this.ReadImplementation);
}
#endif
/// <summary>
/// Reads the next <see cref="ODataItem"/> from the message payload.
/// </summary>
/// <returns>true if more items were read; otherwise false.</returns>
private bool ReadImplementation()
{
bool result;
switch (this.State)
{
case ODataReaderState.Start:
result = this.ReadAtStartImplementation();
break;
case ODataReaderState.FeedStart:
result = this.ReadAtFeedStartImplementation();
break;
case ODataReaderState.FeedEnd:
result = this.ReadAtFeedEndImplementation();
break;
case ODataReaderState.EntryStart:
this.IncreaseEntryDepth();
result = this.ReadAtEntryStartImplementation();
break;
case ODataReaderState.EntryEnd:
this.DecreaseEntryDepth();
result = this.ReadAtEntryEndImplementation();
break;
case ODataReaderState.NavigationLinkStart:
result = this.ReadAtNavigationLinkStartImplementation();
break;
case ODataReaderState.NavigationLinkEnd:
result = this.ReadAtNavigationLinkEndImplementation();
break;
case ODataReaderState.EntityReferenceLink:
result = this.ReadAtEntityReferenceLink();
break;
case ODataReaderState.Exception: // fall through
case ODataReaderState.Completed:
throw new ODataException(Strings.ODataReaderCore_NoReadCallsAllowed(this.State));
default:
Debug.Assert(false, "Unsupported reader state " + this.State + " detected.");
throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataReaderCore_ReadImplementation));
}
if ((this.State == ODataReaderState.EntryStart || this.State == ODataReaderState.EntryEnd) && this.Item != null)
{
ReaderValidationUtils.ValidateEntry(this.CurrentEntry);
}
return result;
}
/// <summary>
/// Catch any exception thrown by the action passed in; in the exception case move the reader into
/// state ExceptionThrown and then rethrow the exception.
/// </summary>
/// <typeparam name="T">The type returned from the <paramref name="action"/> to execute.</typeparam>
/// <param name="action">The action to execute.</param>
/// <returns>The result of executing the <paramref name="action"/>.</returns>
private T InterceptException<T>(Func<T> action)
{
try
{
return action();
}
catch (Exception e)
{
if (ExceptionUtils.IsCatchableExceptionType(e))
{
this.EnterScope(new Scope(ODataReaderState.Exception, null, null));
}
throw;
}
}
/// <summary>
/// Verifies that calling Read is valid.
/// </summary>
/// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param>
private void VerifyCanRead(bool synchronousCall)
{
this.inputContext.VerifyNotDisposed();
this.VerifyCallAllowed(synchronousCall);
if (this.State == ODataReaderState.Exception || this.State == ODataReaderState.Completed)
{
throw new ODataException(Strings.ODataReaderCore_ReadOrReadAsyncCalledInInvalidState(this.State));
}
}
/// <summary>
/// Verifies that a call is allowed to the reader.
/// </summary>
/// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param>
private void VerifyCallAllowed(bool synchronousCall)
{
if (synchronousCall)
{
if (!this.inputContext.Synchronous)
{
throw new ODataException(Strings.ODataReaderCore_SyncCallOnAsyncReader);
}
}
else
{
#if ODATALIB_ASYNC
if (this.inputContext.Synchronous)
{
throw new ODataException(Strings.ODataReaderCore_AsyncCallOnSyncReader);
}
#else
Debug.Assert(false, "Async calls are not allowed in this build.");
#endif
}
}
/// <summary>
/// Increments the nested entry count by one and fails if the new value exceeds the maxiumum nested entry depth limit.
/// </summary>
private void IncreaseEntryDepth()
{
this.currentEntryDepth++;
if (this.currentEntryDepth > this.inputContext.MessageReaderSettings.MessageQuotas.MaxNestingDepth)
{
throw new ODataException(Strings.ValidationUtils_MaxDepthOfNestedEntriesExceeded(this.inputContext.MessageReaderSettings.MessageQuotas.MaxNestingDepth));
}
}
/// <summary>
/// Decrements the nested entry count by one.
/// </summary>
private void DecreaseEntryDepth()
{
Debug.Assert(this.currentEntryDepth > 0, "Entry depth should never become negative.");
this.currentEntryDepth--;
}
/// <summary>
/// A reader scope; keeping track of the current reader state and an item associated with this state.
/// </summary>
protected class Scope
{
/// <summary>The reader state of this scope.</summary>
private readonly ODataReaderState state;
/// <summary>The item attached to this scope.</summary>
private readonly ODataItem item;
/// <summary>
/// Constructor creating a new reader scope.
/// </summary>
/// <param name="state">The reader state of this scope.</param>
/// <param name="item">The item attached to this scope.</param>
/// <param name="expectedEntityType">The expected entity type for the scope.</param>
/// <remarks>The <paramref name="expectedEntityType"/> has the following meanings for given state:
/// Start - it's the expected base type of the top-level entry or entries in the top-level feed.
/// FeedStart - it's the expected base type of the entries in the feed.
/// note that it might be a more derived type than the base type of the entity set for the feed.
/// EntryStart - it's the expected base type of the entry. If the entry has no type name specified
/// this type will be assumed. Otherwise the specified type name must be
/// the expected type or a more derived type.
/// NavigationLinkStart - it's the expected base type the entries in the expanded link (either the single entry
/// or entries in the expanded feed).
/// EntityReferenceLink - it's null, no need for types on entity reference links.
/// In all cases the specified type must be an entity type.</remarks>
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "Debug.Assert check only.")]
internal Scope(ODataReaderState state, ODataItem item, IEdmEntityType expectedEntityType)
{
Debug.Assert(
state == ODataReaderState.Exception && item == null ||
state == ODataReaderState.EntryStart && (item == null || item is ODataEntry) ||
state == ODataReaderState.EntryEnd && (item == null || item is ODataEntry) ||
state == ODataReaderState.FeedStart && item is ODataFeed ||
state == ODataReaderState.FeedEnd && item is ODataFeed ||
state == ODataReaderState.NavigationLinkStart && item is ODataNavigationLink ||
state == ODataReaderState.NavigationLinkEnd && item is ODataNavigationLink ||
state == ODataReaderState.EntityReferenceLink && item is ODataEntityReferenceLink ||
state == ODataReaderState.Start && item == null ||
state == ODataReaderState.Completed && item == null,
"Reader state and associated item do not match.");
this.state = state;
this.item = item;
this.EntityType = expectedEntityType;
}
/// <summary>
/// The reader state of this scope.
/// </summary>
internal ODataReaderState State
{
get
{
return this.state;
}
}
/// <summary>
/// The item attached to this scope.
/// </summary>
internal ODataItem Item
{
get
{
return this.item;
}
}
/// <summary>
/// The entity type for this scope. Can be either the expected one if the real one
/// was not found yet, or the one specified in the payload itself (the real one).
/// </summary>
internal IEdmEntityType EntityType { get; set; }
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Windows.Devices.PointOfService;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace SDKTemplate
{
public sealed partial class Scenario3_ActiveSymbologies : Page
{
MainPage rootPage = MainPage.Current;
BarcodeScanner scanner = null;
ClaimedBarcodeScanner claimedScanner = null;
ObservableCollection<SymbologyListEntry> listOfSymbologies = null;
public Scenario3_ActiveSymbologies()
{
this.InitializeComponent();
listOfSymbologies = new ObservableCollection<SymbologyListEntry>();
SymbologyListSource.Source = listOfSymbologies;
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
ResetTheScenarioState();
}
/// <summary>
/// Invoked when this page is no longer displayed.
/// </summary>
/// <param name="e">Event data that describes how this page was exited. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
ResetTheScenarioState();
}
/// <summary>
/// Event Handler for Start Scan Button Click.
/// Sets up the barcode scanner to be ready to receive the data events from the scan.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void ScenarioStartScanButton_Click(object sender, RoutedEventArgs e)
{
ScenarioStartScanButton.IsEnabled = false;
rootPage.NotifyUser("Acquiring barcode scanner object.", NotifyType.StatusMessage);
// create the barcode scanner.
scanner = await DeviceHelpers.GetFirstBarcodeScannerAsync();
if (scanner != null)
{
// Claim the scanner for exclusive use and enable it so raises DataReceived events.
claimedScanner = await scanner.ClaimScannerAsync();
if (claimedScanner != null)
{
// It is always a good idea to have a release device requested event handler.
// If this event is not handled, then another app can claim ownership of the barcode scanner.
claimedScanner.ReleaseDeviceRequested += claimedScanner_ReleaseDeviceRequested;
// after successfully claiming, attach the datareceived event handler.
claimedScanner.DataReceived += claimedScanner_DataReceived;
// Ask the platform to decode the data by default. When this is set, the platform
// will decode the raw data from the barcode scanner and include in the
// BarcodeScannerReport.ScanDataLabel and ScanDataType in the DataReceived event.
claimedScanner.IsDecodeDataEnabled = true;
// Enable the scanner so it raises DataReceived events.
// Do this after adding the DataReceived event handler.
await claimedScanner.EnableAsync();
// after successful claim, list supported symbologies
IReadOnlyList<uint> supportedSymbologies = await scanner.GetSupportedSymbologiesAsync();
foreach (uint symbology in supportedSymbologies)
{
listOfSymbologies.Add(new SymbologyListEntry(symbology));
}
// reset the button state
ScenarioEndScanButton.IsEnabled = true;
SetActiveSymbologiesButton.IsEnabled = true;
rootPage.NotifyUser("Ready to scan. Device ID: " + claimedScanner.DeviceId, NotifyType.StatusMessage);
}
else
{
scanner.Dispose();
scanner = null;
ScenarioStartScanButton.IsEnabled = true;
rootPage.NotifyUser("Claim barcode scanner failed.", NotifyType.ErrorMessage);
}
}
else
{
ScenarioStartScanButton.IsEnabled = true;
rootPage.NotifyUser("Barcode scanner not found. Please connect a barcode scanner.", NotifyType.ErrorMessage);
}
}
/// <summary>
/// Event handler for the Release Device Requested event fired when barcode scanner receives Claim request from another application
/// </summary>
/// <param name="sender"></param>
/// <param name="args"> Contains the ClamiedBarcodeScanner that is sending this request</param>
void claimedScanner_ReleaseDeviceRequested(object sender, ClaimedBarcodeScanner e)
{
// always retain the device
e.RetainDevice();
rootPage.NotifyUser("Event ReleaseDeviceRequested received. Retaining the barcode scanner.", NotifyType.StatusMessage);
}
/// <summary>
/// Event handler for the DataReceived event fired when a barcode is scanned by the barcode scanner
/// </summary>
/// <param name="sender"></param>
/// <param name="args"> Contains the BarcodeScannerReport which contains the data obtained in the scan</param>
async void claimedScanner_DataReceived(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args)
{
// need to update the UI data on the dispatcher thread.
// update the UI with the data received from the scan.
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// read the data from the buffer and convert to string.
ScenarioOutputScanDataLabel.Text = DataHelpers.GetDataLabelString(args.Report.ScanDataLabel, args.Report.ScanDataType);
ScenarioOutputScanData.Text = DataHelpers.GetDataString(args.Report.ScanData);
ScenarioOutputScanDataType.Text = BarcodeSymbologies.GetName(args.Report.ScanDataType);
});
}
/// <summary>
/// Reset the Scenario state
/// </summary>
private void ResetTheScenarioState()
{
if (claimedScanner != null)
{
// Detach the event handlers
claimedScanner.DataReceived -= claimedScanner_DataReceived;
claimedScanner.ReleaseDeviceRequested -= claimedScanner_ReleaseDeviceRequested;
// Release the Barcode Scanner and set to null
claimedScanner.Dispose();
claimedScanner = null;
}
if (scanner != null)
{
scanner.Dispose();
scanner = null;
}
// Reset the UI if we are still the current page.
if (Frame.Content == this)
{
rootPage.NotifyUser("Click the start scanning button to begin.", NotifyType.StatusMessage);
this.ScenarioOutputScanData.Text = "No data";
this.ScenarioOutputScanDataLabel.Text = "No data";
this.ScenarioOutputScanDataType.Text = "No data";
// reset the button state
SetActiveSymbologiesButton.IsEnabled = false;
ScenarioEndScanButton.IsEnabled = false;
ScenarioStartScanButton.IsEnabled = true;
// reset symbology list
listOfSymbologies.Clear();
}
}
/// <summary>
/// Event handler for End Scan Button Click.
/// Releases the Barcode Scanner and resets the text in the UI
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ScenarioEndScanButton_Click(object sender, RoutedEventArgs e)
{
ResetTheScenarioState();
}
private async void SetActiveSymbologies_Click(object sender, RoutedEventArgs e)
{
if (claimedScanner != null)
{
var symbologyList = new List<uint>();
foreach (var symbologyListEntry in listOfSymbologies)
{
if (symbologyListEntry.IsEnabled)
{
symbologyList.Add(symbologyListEntry.Id);
}
}
await claimedScanner.SetActiveSymbologiesAsync(symbologyList);
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Data.Linq;
using System.Linq;
using System.Data.Linq.Mapping;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Reflection;
using Dg.Deblazer;
using Dg.Deblazer.Validation;
using Dg.Deblazer.CodeAnnotation;
using Dg.Deblazer.Api;
using Dg.Deblazer.Visitors;
using Dg.Deblazer.Cache;
using Dg.Deblazer.SqlGeneration;
using Deblazer.WideWorldImporter.DbLayer.Queries;
using Deblazer.WideWorldImporter.DbLayer.Wrappers;
using Dg.Deblazer.Read;
namespace Deblazer.WideWorldImporter.DbLayer
{
public partial class Application_City : DbEntity, IId
{
private DbValue<System.Int32> _CityID = new DbValue<System.Int32>();
private DbValue<System.String> _CityName = new DbValue<System.String>();
private DbValue<System.Int32> _StateProvinceID = new DbValue<System.Int32>();
private DbValue<System.Int64> _LatestRecordedPopulation = new DbValue<System.Int64>();
private DbValue<System.Int32> _LastEditedBy = new DbValue<System.Int32>();
private DbValue<System.DateTime> _ValidFrom = new DbValue<System.DateTime>();
private DbValue<System.DateTime> _ValidTo = new DbValue<System.DateTime>();
private IDbEntityRef<Application_People> _Application_People;
private IDbEntityRef<Application_StateProvince> _Application_StateProvince;
private IDbEntitySet<Application_SystemParameter> _Application_SystemParameters;
private IDbEntitySet<Application_SystemParameter> _Cities;
private IDbEntitySet<Purchasing_Supplier> _Purchasing_Suppliers;
private IDbEntitySet<Purchasing_Supplier> _Purchasing_Suppliers_PostalCityID_Application_Cities;
private IDbEntitySet<Sales_Customer> _Sales_Customers;
private IDbEntitySet<Sales_Customer> _Sales_Customers_PostalCityID_Application_Cities;
public int Id => CityID;
long ILongId.Id => CityID;
[Validate]
public System.Int32 CityID
{
get
{
return _CityID.Entity;
}
set
{
_CityID.Entity = value;
}
}
[StringColumn(50, false)]
[Validate]
public System.String CityName
{
get
{
return _CityName.Entity;
}
set
{
_CityName.Entity = value;
}
}
[Validate]
public System.Int32 StateProvinceID
{
get
{
return _StateProvinceID.Entity;
}
set
{
_StateProvinceID.Entity = value;
}
}
[Validate]
public System.Int64 LatestRecordedPopulation
{
get
{
return _LatestRecordedPopulation.Entity;
}
set
{
_LatestRecordedPopulation.Entity = value;
}
}
[Validate]
public System.Int32 LastEditedBy
{
get
{
return _LastEditedBy.Entity;
}
set
{
_LastEditedBy.Entity = value;
}
}
[StringColumn(7, false)]
[Validate]
public System.DateTime ValidFrom
{
get
{
return _ValidFrom.Entity;
}
set
{
_ValidFrom.Entity = value;
}
}
[StringColumn(7, false)]
[Validate]
public System.DateTime ValidTo
{
get
{
return _ValidTo.Entity;
}
set
{
_ValidTo.Entity = value;
}
}
[Validate]
public Application_People Application_People
{
get
{
Action<Application_People> beforeRightsCheckAction = e => e.Application_Cities.Add(this);
if (_Application_People != null)
{
return _Application_People.GetEntity(beforeRightsCheckAction);
}
_Application_People = GetDbEntityRef(true, new[]{"[LastEditedBy]"}, new Func<long ? >[]{() => _LastEditedBy.Entity}, beforeRightsCheckAction);
return (Application_People != null) ? _Application_People.GetEntity(beforeRightsCheckAction) : null;
}
set
{
if (_Application_People == null)
{
_Application_People = new DbEntityRef<Application_People>(_db, true, new[]{"[LastEditedBy]"}, new Func<long ? >[]{() => _LastEditedBy.Entity}, _lazyLoadChildren, _getChildrenFromCache);
}
AssignDbEntity<Application_People, Application_City>(value, value == null ? new long ? [0] : new long ? []{(long ? )value.PersonID}, _Application_People, new long ? []{_LastEditedBy.Entity}, new Action<long ? >[]{x => LastEditedBy = (int ? )x ?? default (int)}, x => x.Application_Cities, null, LastEditedByChanged);
}
}
void LastEditedByChanged(object sender, EventArgs eventArgs)
{
if (sender is Application_People)
_LastEditedBy.Entity = (int)((Application_People)sender).Id;
}
[Validate]
public Application_StateProvince Application_StateProvince
{
get
{
Action<Application_StateProvince> beforeRightsCheckAction = e => e.Application_Cities.Add(this);
if (_Application_StateProvince != null)
{
return _Application_StateProvince.GetEntity(beforeRightsCheckAction);
}
_Application_StateProvince = GetDbEntityRef(true, new[]{"[StateProvinceID]"}, new Func<long ? >[]{() => _StateProvinceID.Entity}, beforeRightsCheckAction);
return (Application_StateProvince != null) ? _Application_StateProvince.GetEntity(beforeRightsCheckAction) : null;
}
set
{
if (_Application_StateProvince == null)
{
_Application_StateProvince = new DbEntityRef<Application_StateProvince>(_db, true, new[]{"[StateProvinceID]"}, new Func<long ? >[]{() => _StateProvinceID.Entity}, _lazyLoadChildren, _getChildrenFromCache);
}
AssignDbEntity<Application_StateProvince, Application_City>(value, value == null ? new long ? [0] : new long ? []{(long ? )value.StateProvinceID}, _Application_StateProvince, new long ? []{_StateProvinceID.Entity}, new Action<long ? >[]{x => StateProvinceID = (int ? )x ?? default (int)}, x => x.Application_Cities, null, StateProvinceIDChanged);
}
}
void StateProvinceIDChanged(object sender, EventArgs eventArgs)
{
if (sender is Application_StateProvince)
_StateProvinceID.Entity = (int)((Application_StateProvince)sender).Id;
}
[Validate]
public IDbEntitySet<Application_SystemParameter> Application_SystemParameters
{
get
{
if (_Application_SystemParameters == null)
{
if (_getChildrenFromCache)
{
_Application_SystemParameters = new DbEntitySetCached<Application_City, Application_SystemParameter>(() => _CityID.Entity);
}
}
else
_Application_SystemParameters = new DbEntitySet<Application_SystemParameter>(_db, false, new Func<long ? >[]{() => _CityID.Entity}, new[]{"[DeliveryCityID]"}, (member, root) => member.Application_City = root as Application_City, this, _lazyLoadChildren, e => e.Application_City = this, e =>
{
var x = e.Application_City;
e.Application_City = null;
new UpdateSetVisitor(true, new[]{"DeliveryCityID"}, false).Process(x);
}
);
return _Application_SystemParameters;
}
}
[Validate]
public IDbEntitySet<Application_SystemParameter> Cities
{
get
{
if (_Cities == null)
{
if (_getChildrenFromCache)
{
_Cities = new DbEntitySetCached<Application_City, Application_SystemParameter>(() => _CityID.Entity);
}
}
else
_Cities = new DbEntitySet<Application_SystemParameter>(_db, false, new Func<long ? >[]{() => _CityID.Entity}, new[]{"[PostalCityID]"}, (member, root) => member.Application_City = root as Application_City, this, _lazyLoadChildren, e => e.Application_City = this, e =>
{
var x = e.Application_City;
e.Application_City = null;
new UpdateSetVisitor(true, new[]{"PostalCityID"}, false).Process(x);
}
);
return _Cities;
}
}
[Validate]
public IDbEntitySet<Purchasing_Supplier> Purchasing_Suppliers
{
get
{
if (_Purchasing_Suppliers == null)
{
if (_getChildrenFromCache)
{
_Purchasing_Suppliers = new DbEntitySetCached<Application_City, Purchasing_Supplier>(() => _CityID.Entity);
}
}
else
_Purchasing_Suppliers = new DbEntitySet<Purchasing_Supplier>(_db, false, new Func<long ? >[]{() => _CityID.Entity}, new[]{"[DeliveryCityID]"}, (member, root) => member.Application_City = root as Application_City, this, _lazyLoadChildren, e => e.Application_City = this, e =>
{
var x = e.Application_City;
e.Application_City = null;
new UpdateSetVisitor(true, new[]{"DeliveryCityID"}, false).Process(x);
}
);
return _Purchasing_Suppliers;
}
}
[Validate]
public IDbEntitySet<Purchasing_Supplier> Purchasing_Suppliers_PostalCityID_Application_Cities
{
get
{
if (_Purchasing_Suppliers_PostalCityID_Application_Cities == null)
{
if (_getChildrenFromCache)
{
_Purchasing_Suppliers_PostalCityID_Application_Cities = new DbEntitySetCached<Application_City, Purchasing_Supplier>(() => _CityID.Entity);
}
}
else
_Purchasing_Suppliers_PostalCityID_Application_Cities = new DbEntitySet<Purchasing_Supplier>(_db, false, new Func<long ? >[]{() => _CityID.Entity}, new[]{"[PostalCityID]"}, (member, root) => member.Application_City = root as Application_City, this, _lazyLoadChildren, e => e.Application_City = this, e =>
{
var x = e.Application_City;
e.Application_City = null;
new UpdateSetVisitor(true, new[]{"PostalCityID"}, false).Process(x);
}
);
return _Purchasing_Suppliers_PostalCityID_Application_Cities;
}
}
[Validate]
public IDbEntitySet<Sales_Customer> Sales_Customers
{
get
{
if (_Sales_Customers == null)
{
if (_getChildrenFromCache)
{
_Sales_Customers = new DbEntitySetCached<Application_City, Sales_Customer>(() => _CityID.Entity);
}
}
else
_Sales_Customers = new DbEntitySet<Sales_Customer>(_db, false, new Func<long ? >[]{() => _CityID.Entity}, new[]{"[DeliveryCityID]"}, (member, root) => member.Application_City = root as Application_City, this, _lazyLoadChildren, e => e.Application_City = this, e =>
{
var x = e.Application_City;
e.Application_City = null;
new UpdateSetVisitor(true, new[]{"DeliveryCityID"}, false).Process(x);
}
);
return _Sales_Customers;
}
}
[Validate]
public IDbEntitySet<Sales_Customer> Sales_Customers_PostalCityID_Application_Cities
{
get
{
if (_Sales_Customers_PostalCityID_Application_Cities == null)
{
if (_getChildrenFromCache)
{
_Sales_Customers_PostalCityID_Application_Cities = new DbEntitySetCached<Application_City, Sales_Customer>(() => _CityID.Entity);
}
}
else
_Sales_Customers_PostalCityID_Application_Cities = new DbEntitySet<Sales_Customer>(_db, false, new Func<long ? >[]{() => _CityID.Entity}, new[]{"[PostalCityID]"}, (member, root) => member.Application_City = root as Application_City, this, _lazyLoadChildren, e => e.Application_City = this, e =>
{
var x = e.Application_City;
e.Application_City = null;
new UpdateSetVisitor(true, new[]{"PostalCityID"}, false).Process(x);
}
);
return _Sales_Customers_PostalCityID_Application_Cities;
}
}
protected override void ModifyInternalState(FillVisitor visitor)
{
SendIdChanging();
_CityID.Load(visitor.GetInt32());
SendIdChanged();
_CityName.Load(visitor.GetValue<System.String>());
_StateProvinceID.Load(visitor.GetInt32());
_LatestRecordedPopulation.Load(visitor.GetValue<System.Int64>());
_LastEditedBy.Load(visitor.GetInt32());
_ValidFrom.Load(visitor.GetDateTime());
_ValidTo.Load(visitor.GetDateTime());
this._db = visitor.Db;
isLoaded = true;
}
protected sealed override void CheckProperties(IUpdateVisitor visitor)
{
_CityID.Welcome(visitor, "CityID", "Int NOT NULL", false);
_CityName.Welcome(visitor, "CityName", "NVarChar(50) NOT NULL", false);
_StateProvinceID.Welcome(visitor, "StateProvinceID", "Int NOT NULL", false);
_LatestRecordedPopulation.Welcome(visitor, "LatestRecordedPopulation", "BigInt", false);
_LastEditedBy.Welcome(visitor, "LastEditedBy", "Int NOT NULL", false);
_ValidFrom.Welcome(visitor, "ValidFrom", "DateTime2(7) NOT NULL", false);
_ValidTo.Welcome(visitor, "ValidTo", "DateTime2(7) NOT NULL", false);
}
protected override void HandleChildren(DbEntityVisitorBase visitor)
{
visitor.ProcessAssociation(this, _Application_People);
visitor.ProcessAssociation(this, _Application_StateProvince);
visitor.ProcessAssociation(this, _Application_SystemParameters);
visitor.ProcessAssociation(this, _Cities);
visitor.ProcessAssociation(this, _Purchasing_Suppliers);
visitor.ProcessAssociation(this, _Purchasing_Suppliers_PostalCityID_Application_Cities);
visitor.ProcessAssociation(this, _Sales_Customers);
visitor.ProcessAssociation(this, _Sales_Customers_PostalCityID_Application_Cities);
}
}
public static class Db_Application_CityQueryGetterExtensions
{
public static Application_CityTableQuery<Application_City> Application_Cities(this IDb db)
{
var query = new Application_CityTableQuery<Application_City>(db as IDb);
return query;
}
}
}
namespace Deblazer.WideWorldImporter.DbLayer.Queries
{
public class Application_CityQuery<K, T> : Query<K, T, Application_City, Application_CityWrapper, Application_CityQuery<K, T>> where K : QueryBase where T : DbEntity, ILongId
{
public Application_CityQuery(IDb db): base (db)
{
}
protected sealed override Application_CityWrapper GetWrapper()
{
return Application_CityWrapper.Instance;
}
public Application_PeopleQuery<Application_CityQuery<K, T>, T> JoinApplication_People(JoinType joinType = JoinType.Inner, bool preloadEntities = false)
{
var joinedQuery = new Application_PeopleQuery<Application_CityQuery<K, T>, T>(Db);
return Join(joinedQuery, string.Concat(joinType.GetJoinString(), " [Application].[People] AS {1} {0} ON", "{2}.[LastEditedBy] = {1}.[PersonID]"), o => ((Application_City)o)?.Application_People, (e, fv, ppe) =>
{
var child = (Application_People)ppe(QueryHelpers.Fill<Application_People>(null, fv));
if (e != null)
{
((Application_City)e).Application_People = child;
}
return child;
}
, typeof (Application_People), preloadEntities);
}
public Application_StateProvinceQuery<Application_CityQuery<K, T>, T> JoinApplication_StateProvince(JoinType joinType = JoinType.Inner, bool preloadEntities = false)
{
var joinedQuery = new Application_StateProvinceQuery<Application_CityQuery<K, T>, T>(Db);
return Join(joinedQuery, string.Concat(joinType.GetJoinString(), " [Application].[StateProvinces] AS {1} {0} ON", "{2}.[StateProvinceID] = {1}.[StateProvinceID]"), o => ((Application_City)o)?.Application_StateProvince, (e, fv, ppe) =>
{
var child = (Application_StateProvince)ppe(QueryHelpers.Fill<Application_StateProvince>(null, fv));
if (e != null)
{
((Application_City)e).Application_StateProvince = child;
}
return child;
}
, typeof (Application_StateProvince), preloadEntities);
}
public Application_SystemParameterQuery<Application_CityQuery<K, T>, T> JoinApplication_SystemParameters(JoinType joinType = JoinType.Inner, bool attach = false)
{
var joinedQuery = new Application_SystemParameterQuery<Application_CityQuery<K, T>, T>(Db);
return JoinSet(() => new Application_SystemParameterTableQuery<Application_SystemParameter>(Db), joinedQuery, string.Concat(joinType.GetJoinString(), " [Application].[SystemParameters] AS {1} {0} ON", "{2}.[CityID] = {1}.[DeliveryCityID]"), (p, ids) => ((Application_SystemParameterWrapper)p).Id.In(ids.Select(id => (System.Int32)id)), (o, v) => ((Application_City)o).Application_SystemParameters.Attach(v.Cast<Application_SystemParameter>()), p => (long)((Application_SystemParameter)p).DeliveryCityID, attach);
}
public Application_SystemParameterQuery<Application_CityQuery<K, T>, T> JoinCities(JoinType joinType = JoinType.Inner, bool attach = false)
{
var joinedQuery = new Application_SystemParameterQuery<Application_CityQuery<K, T>, T>(Db);
return JoinSet(() => new Application_SystemParameterTableQuery<Application_SystemParameter>(Db), joinedQuery, string.Concat(joinType.GetJoinString(), " [Application].[SystemParameters] AS {1} {0} ON", "{2}.[CityID] = {1}.[PostalCityID]"), (p, ids) => ((Application_SystemParameterWrapper)p).Id.In(ids.Select(id => (System.Int32)id)), (o, v) => ((Application_City)o).Cities.Attach(v.Cast<Application_SystemParameter>()), p => (long)((Application_SystemParameter)p).PostalCityID, attach);
}
public Purchasing_SupplierQuery<Application_CityQuery<K, T>, T> JoinPurchasing_Suppliers(JoinType joinType = JoinType.Inner, bool attach = false)
{
var joinedQuery = new Purchasing_SupplierQuery<Application_CityQuery<K, T>, T>(Db);
return JoinSet(() => new Purchasing_SupplierTableQuery<Purchasing_Supplier>(Db), joinedQuery, string.Concat(joinType.GetJoinString(), " [Purchasing].[Suppliers] AS {1} {0} ON", "{2}.[CityID] = {1}.[DeliveryCityID]"), (p, ids) => ((Purchasing_SupplierWrapper)p).Id.In(ids.Select(id => (System.Int32)id)), (o, v) => ((Application_City)o).Purchasing_Suppliers.Attach(v.Cast<Purchasing_Supplier>()), p => (long)((Purchasing_Supplier)p).DeliveryCityID, attach);
}
public Purchasing_SupplierQuery<Application_CityQuery<K, T>, T> JoinPurchasing_Suppliers_PostalCityID_Application_Cities(JoinType joinType = JoinType.Inner, bool attach = false)
{
var joinedQuery = new Purchasing_SupplierQuery<Application_CityQuery<K, T>, T>(Db);
return JoinSet(() => new Purchasing_SupplierTableQuery<Purchasing_Supplier>(Db), joinedQuery, string.Concat(joinType.GetJoinString(), " [Purchasing].[Suppliers] AS {1} {0} ON", "{2}.[CityID] = {1}.[PostalCityID]"), (p, ids) => ((Purchasing_SupplierWrapper)p).Id.In(ids.Select(id => (System.Int32)id)), (o, v) => ((Application_City)o).Purchasing_Suppliers_PostalCityID_Application_Cities.Attach(v.Cast<Purchasing_Supplier>()), p => (long)((Purchasing_Supplier)p).PostalCityID, attach);
}
public Sales_CustomerQuery<Application_CityQuery<K, T>, T> JoinSales_Customers(JoinType joinType = JoinType.Inner, bool attach = false)
{
var joinedQuery = new Sales_CustomerQuery<Application_CityQuery<K, T>, T>(Db);
return JoinSet(() => new Sales_CustomerTableQuery<Sales_Customer>(Db), joinedQuery, string.Concat(joinType.GetJoinString(), " [Sales].[Customers] AS {1} {0} ON", "{2}.[CityID] = {1}.[DeliveryCityID]"), (p, ids) => ((Sales_CustomerWrapper)p).Id.In(ids.Select(id => (System.Int32)id)), (o, v) => ((Application_City)o).Sales_Customers.Attach(v.Cast<Sales_Customer>()), p => (long)((Sales_Customer)p).DeliveryCityID, attach);
}
public Sales_CustomerQuery<Application_CityQuery<K, T>, T> JoinSales_Customers_PostalCityID_Application_Cities(JoinType joinType = JoinType.Inner, bool attach = false)
{
var joinedQuery = new Sales_CustomerQuery<Application_CityQuery<K, T>, T>(Db);
return JoinSet(() => new Sales_CustomerTableQuery<Sales_Customer>(Db), joinedQuery, string.Concat(joinType.GetJoinString(), " [Sales].[Customers] AS {1} {0} ON", "{2}.[CityID] = {1}.[PostalCityID]"), (p, ids) => ((Sales_CustomerWrapper)p).Id.In(ids.Select(id => (System.Int32)id)), (o, v) => ((Application_City)o).Sales_Customers_PostalCityID_Application_Cities.Attach(v.Cast<Sales_Customer>()), p => (long)((Sales_Customer)p).PostalCityID, attach);
}
}
public class Application_CityTableQuery<T> : Application_CityQuery<Application_CityTableQuery<T>, T> where T : DbEntity, ILongId
{
public Application_CityTableQuery(IDb db): base (db)
{
}
}
}
namespace Deblazer.WideWorldImporter.DbLayer.Helpers
{
public class Application_CityHelper : QueryHelper<Application_City>, IHelper<Application_City>
{
string[] columnsInSelectStatement = new[]{"{0}.CityID", "{0}.CityName", "{0}.StateProvinceID", "{0}.LatestRecordedPopulation", "{0}.LastEditedBy", "{0}.ValidFrom", "{0}.ValidTo"};
public sealed override string[] ColumnsInSelectStatement => columnsInSelectStatement;
string[] columnsInInsertStatement = new[]{"{0}.CityID", "{0}.CityName", "{0}.StateProvinceID", "{0}.LatestRecordedPopulation", "{0}.LastEditedBy", "{0}.ValidFrom", "{0}.ValidTo"};
public sealed override string[] ColumnsInInsertStatement => columnsInInsertStatement;
private static readonly string createTempTableCommand = "CREATE TABLE #Application_City ([CityID] Int NOT NULL,[CityName] NVarChar(50) NOT NULL,[StateProvinceID] Int NOT NULL,[LatestRecordedPopulation] BigInt,[LastEditedBy] Int NOT NULL,[ValidFrom] DateTime2(7) NOT NULL,[ValidTo] DateTime2(7) NOT NULL, [RowIndexForSqlBulkCopy] INT NOT NULL)";
public sealed override string CreateTempTableCommand => createTempTableCommand;
public sealed override string FullTableName => "[Application].[Cities]";
public sealed override bool IsForeignKeyTo(Type other)
{
return other == typeof (Application_SystemParameter) || other == typeof (Application_SystemParameter) || other == typeof (Purchasing_Supplier) || other == typeof (Purchasing_Supplier) || other == typeof (Sales_Customer) || other == typeof (Sales_Customer);
}
private const string insertCommand = "INSERT INTO [Application].[Cities] ([{TableName = \"Application].[Cities\";}].[CityID], [{TableName = \"Application].[Cities\";}].[CityName], [{TableName = \"Application].[Cities\";}].[StateProvinceID], [{TableName = \"Application].[Cities\";}].[LatestRecordedPopulation], [{TableName = \"Application].[Cities\";}].[LastEditedBy], [{TableName = \"Application].[Cities\";}].[ValidFrom], [{TableName = \"Application].[Cities\";}].[ValidTo]) VALUES ([@CityID],[@CityName],[@StateProvinceID],[@LatestRecordedPopulation],[@LastEditedBy],[@ValidFrom],[@ValidTo]); SELECT SCOPE_IDENTITY()";
public sealed override void FillInsertCommand(SqlCommand sqlCommand, Application_City _Application_City)
{
sqlCommand.CommandText = insertCommand;
sqlCommand.Parameters.AddWithValue("@CityID", _Application_City.CityID);
sqlCommand.Parameters.AddWithValue("@CityName", _Application_City.CityName ?? (object)DBNull.Value);
sqlCommand.Parameters.AddWithValue("@StateProvinceID", _Application_City.StateProvinceID);
sqlCommand.Parameters.AddWithValue("@LatestRecordedPopulation", _Application_City.LatestRecordedPopulation);
sqlCommand.Parameters.AddWithValue("@LastEditedBy", _Application_City.LastEditedBy);
sqlCommand.Parameters.AddWithValue("@ValidFrom", _Application_City.ValidFrom);
sqlCommand.Parameters.AddWithValue("@ValidTo", _Application_City.ValidTo);
}
public sealed override void ExecuteInsertCommand(SqlCommand sqlCommand, Application_City _Application_City)
{
using (var sqlDataReader = sqlCommand.ExecuteReader(CommandBehavior.SequentialAccess))
{
sqlDataReader.Read();
_Application_City.CityID = Convert.ToInt32(sqlDataReader.GetValue(0));
}
}
private static Application_CityWrapper _wrapper = Application_CityWrapper.Instance;
public QueryWrapper Wrapper
{
get
{
return _wrapper;
}
}
}
}
namespace Deblazer.WideWorldImporter.DbLayer.Wrappers
{
public class Application_CityWrapper : QueryWrapper<Application_City>
{
public readonly QueryElMemberId<Application_StateProvince> StateProvinceID = new QueryElMemberId<Application_StateProvince>("StateProvinceID");
public readonly QueryElMemberId<Application_People> LastEditedBy = new QueryElMemberId<Application_People>("LastEditedBy");
public readonly QueryElMember<System.String> CityName = new QueryElMember<System.String>("CityName");
public readonly QueryElMemberStruct<System.Int64> LatestRecordedPopulation = new QueryElMemberStruct<System.Int64>("LatestRecordedPopulation");
public readonly QueryElMemberStruct<System.DateTime> ValidFrom = new QueryElMemberStruct<System.DateTime>("ValidFrom");
public readonly QueryElMemberStruct<System.DateTime> ValidTo = new QueryElMemberStruct<System.DateTime>("ValidTo");
public static readonly Application_CityWrapper Instance = new Application_CityWrapper();
private Application_CityWrapper(): base ("[Application].[Cities]", "Application_City")
{
}
}
}
| |
// This file is part of the C5 Generic Collection Library for C# and CLI
// See https://github.com/sestoft/C5/blob/master/LICENSE for licensing details.
using System;
using SCG = System.Collections.Generic;
namespace C5
{
/// <summary>
/// A priority queue class based on an interval heap data structure.
/// </summary>
/// <typeparam name="T">The item type</typeparam>
[Serializable]
public class IntervalHeap<T> : CollectionValueBase<T>, IPriorityQueue<T>
{
#region Events
/// <summary>
///
/// </summary>
/// <value></value>
public override EventType ListenableEvents => EventType.Basic;
#endregion
#region Fields
private struct Interval
{
internal T first, last; internal Handle? firsthandle, lasthandle;
public override string ToString() { return string.Format("[{0}; {1}]", first, last); }
}
private int stamp;
private readonly SCG.IComparer<T> comparer;
private readonly SCG.IEqualityComparer<T> itemequalityComparer;
private Interval[] heap;
private int size;
#endregion
#region Util
// heapifyMin and heapifyMax and their auxiliaries
private void SwapFirstWithLast(int cell1, int cell2)
{
T first = heap[cell1].first;
Handle firsthandle = heap[cell1].firsthandle!;
UpdateFirst(cell1, heap[cell2].last, heap[cell2].lasthandle);
UpdateLast(cell2, first, firsthandle);
}
private void SwapLastWithLast(int cell1, int cell2)
{
T last = heap[cell2].last;
Handle lasthandle = heap[cell2].lasthandle!;
UpdateLast(cell2, heap[cell1].last, heap[cell1].lasthandle!);
UpdateLast(cell1, last, lasthandle);
}
private void SwapFirstWithFirst(int cell1, int cell2)
{
T first = heap[cell2].first;
Handle firsthandle = heap[cell2].firsthandle!;
UpdateFirst(cell2, heap[cell1].first, heap[cell1].firsthandle);
UpdateFirst(cell1, first, firsthandle);
}
private bool HeapifyMin(int cell)
{
bool swappedroot = false;
// If first > last, swap them
if (2 * cell + 1 < size && comparer.Compare(heap[cell].first, heap[cell].last) > 0)
{
swappedroot = true;
SwapFirstWithLast(cell, cell);
}
int currentmin = cell, l = 2 * cell + 1, r = l + 1;
if (2 * l < size && comparer.Compare(heap[l].first, heap[currentmin].first) < 0)
{
currentmin = l;
}
if (2 * r < size && comparer.Compare(heap[r].first, heap[currentmin].first) < 0)
{
currentmin = r;
}
if (currentmin != cell)
{
// cell has at least one daughter, and it contains the min
SwapFirstWithFirst(currentmin, cell);
HeapifyMin(currentmin);
}
return swappedroot;
}
private bool HeapifyMax(int cell)
{
bool swappedroot = false;
if (2 * cell + 1 < size && comparer.Compare(heap[cell].last, heap[cell].first) < 0)
{
swappedroot = true;
SwapFirstWithLast(cell, cell);
}
int currentmax = cell, l = 2 * cell + 1, r = l + 1;
bool firstmax = false; // currentmax's first field holds max
if (2 * l + 1 < size)
{ // both l.first and l.last exist
if (comparer.Compare(heap[l].last, heap[currentmax].last) > 0)
{
currentmax = l;
}
}
else if (2 * l + 1 == size)
{ // only l.first exists
if (comparer.Compare(heap[l].first, heap[currentmax].last) > 0)
{
currentmax = l;
firstmax = true;
}
}
if (2 * r + 1 < size)
{ // both r.first and r.last exist
if (comparer.Compare(heap[r].last, heap[currentmax].last) > 0)
{
currentmax = r;
}
}
else if (2 * r + 1 == size)
{ // only r.first exists
if (comparer.Compare(heap[r].first, heap[currentmax].last) > 0)
{
currentmax = r;
firstmax = true;
}
}
if (currentmax != cell)
{
// The cell has at least one daughter, and it contains the max
if (firstmax)
{
SwapFirstWithLast(currentmax, cell);
}
else
{
SwapLastWithLast(currentmax, cell);
}
HeapifyMax(currentmax);
}
return swappedroot;
}
private void BubbleUpMin(int i)
{
if (i > 0)
{
T min = heap[i].first, iv = min;
Handle minhandle = heap[i].firsthandle!;
_ = (i + 1) / 2 - 1;
while (i > 0)
{
int p;
if (comparer.Compare(iv, min = heap[p = (i + 1) / 2 - 1].first) < 0)
{
UpdateFirst(i, min, heap[p].firsthandle);
i = p;
}
else
{
break;
}
}
UpdateFirst(i, iv, minhandle);
}
}
private void BubbleUpMax(int i)
{
if (i > 0)
{
T max = heap[i].last, iv = max;
Handle maxhandle = heap[i].lasthandle!;
_ = (i + 1) / 2 - 1;
while (i > 0)
{
int p;
if (comparer.Compare(iv, max = heap[p = (i + 1) / 2 - 1].last) > 0)
{
UpdateLast(i, max, heap[p].lasthandle);
i = p;
}
else
{
break;
}
}
UpdateLast(i, iv, maxhandle);
}
}
#endregion
#region Constructors
/// <summary>
/// Create an interval heap with natural item comparer and default initial capacity (16)
/// </summary>
public IntervalHeap() : this(16) { }
/// <summary>
/// Create an interval heap with external item comparer and default initial capacity (16)
/// </summary>
/// <param name="comparer">The external comparer</param>
public IntervalHeap(SCG.IComparer<T> comparer) : this(16, comparer) { }
//TODO: maybe remove
/// <summary>
/// Create an interval heap with natural item comparer and prescribed initial capacity
/// </summary>
/// <param name="capacity">The initial capacity</param>
public IntervalHeap(int capacity) : this(capacity, SCG.Comparer<T>.Default, EqualityComparer<T>.Default) { }
/// <summary>
/// Create an interval heap with external item comparer and prescribed initial capacity
/// </summary>
/// <param name="comparer">The external comparer</param>
/// <param name="capacity">The initial capacity</param>
public IntervalHeap(int capacity, SCG.IComparer<T> comparer) : this(capacity, comparer, new ComparerZeroHashCodeEqualityComparer<T>(comparer)) { }
private IntervalHeap(int capacity, SCG.IComparer<T> comparer, SCG.IEqualityComparer<T> itemequalityComparer)
{
this.comparer = comparer ?? throw new NullReferenceException("Item comparer cannot be null");
this.itemequalityComparer = itemequalityComparer ?? throw new NullReferenceException("Item equality comparer cannot be null");
int length = 1;
while (length < capacity)
{
length <<= 1;
}
heap = new Interval[length];
}
#endregion
#region IPriorityQueue<T> Members
/// <summary>
/// Find the current least item of this priority queue.
/// <exception cref="NoSuchItemException"/> if queue is empty
/// </summary>
/// <returns>The least item.</returns>
public T FindMin()
{
if (size == 0)
{
throw new NoSuchItemException();
}
return heap[0].first;
}
/// <summary>
/// Remove the least item from this priority queue.
/// <exception cref="NoSuchItemException"/> if queue is empty
/// </summary>
/// <returns>The removed item.</returns>
public T DeleteMin()
{
return DeleteMin(out _);
}
/// <summary>
/// Find the current largest item of this priority queue.
/// <exception cref="NoSuchItemException"/> if queue is empty
/// </summary>
/// <returns>The largest item.</returns>
public T FindMax()
{
if (size == 0)
{
throw new NoSuchItemException("Heap is empty");
}
else if (size == 1)
{
return heap[0].first;
}
else
{
return heap[0].last;
}
}
/// <summary>
/// Remove the largest item from this priority queue.
/// <exception cref="NoSuchItemException"/> if queue is empty
/// </summary>
/// <returns>The removed item.</returns>
public T DeleteMax()
{
return DeleteMax(out _);
}
/// <summary>
/// The comparer object supplied at creation time for this collection
/// </summary>
/// <value>The comparer</value>
public SCG.IComparer<T> Comparer => comparer;
#endregion
#region IExtensible<T> Members
/// <summary>
/// If true any call of an updating operation will throw an
/// <code>ReadOnlyCollectionException</code>
/// </summary>
/// <value>True if this collection is read-only.</value>
public bool IsReadOnly => false;
/// <summary>
///
/// </summary>
/// <value>True since this collection has bag semantics</value>
public bool AllowsDuplicates => true;
/// <summary>
/// Value is null since this collection has no equality concept for its items.
/// </summary>
/// <value></value>
public virtual SCG.IEqualityComparer<T> EqualityComparer => itemequalityComparer;
/// <summary>
/// By convention this is true for any collection with set semantics.
/// </summary>
/// <value>True if only one representative of a group of equal items
/// is kept in the collection together with the total count.</value>
public virtual bool DuplicatesByCounting => false;
/// <summary>
/// Add an item to this priority queue.
/// </summary>
/// <param name="item">The item to add.</param>
/// <returns>True</returns>
public bool Add(T item)
{
stamp++;
if (Add(null, item))
{
RaiseItemsAdded(item, 1);
RaiseCollectionChanged();
return true;
}
return false;
}
private bool Add(Handle? itemhandle, T item)
{
if (size == 0)
{
size = 1;
UpdateFirst(0, item, itemhandle);
return true;
}
if (size == 2 * heap.Length)
{
Interval[] newheap = new Interval[2 * heap.Length];
Array.Copy(heap, newheap, heap.Length);
heap = newheap;
}
if (size % 2 == 0)
{
int i = size / 2, p = (i + 1) / 2 - 1;
T tmp = heap[p].last;
if (comparer.Compare(item, tmp) > 0)
{
UpdateFirst(i, tmp, heap[p].lasthandle);
UpdateLast(p, item, itemhandle);
BubbleUpMax(p);
}
else
{
UpdateFirst(i, item, itemhandle);
if (comparer.Compare(item, heap[p].first) < 0)
{
BubbleUpMin(i);
}
}
}
else
{
int i = size / 2;
T other = heap[i].first;
if (comparer.Compare(item, other) < 0)
{
UpdateLast(i, other, heap[i].firsthandle);
UpdateFirst(i, item, itemhandle);
BubbleUpMin(i);
}
else
{
UpdateLast(i, item, itemhandle);
BubbleUpMax(i);
}
}
size++;
return true;
}
private void UpdateLast(int cell, T item, Handle? handle)
{
heap[cell].last = item;
if (handle != null)
{
handle.index = 2 * cell + 1;
}
heap[cell].lasthandle = handle;
}
private void UpdateFirst(int cell, T item, Handle? handle)
{
heap[cell].first = item;
if (handle != null)
{
handle.index = 2 * cell;
}
heap[cell].firsthandle = handle;
}
/// <summary>
/// Add the elements from another collection with a more specialized item type
/// to this collection.
/// </summary>
/// <param name="items">The items to add</param>
public void AddAll(SCG.IEnumerable<T> items)
{
stamp++;
int oldsize = size;
foreach (T item in items)
{
Add(null, item);
}
if (size != oldsize)
{
if ((ActiveEvents & EventType.Added) != 0)
{
foreach (T item in items)
{
RaiseItemsAdded(item, 1);
}
}
RaiseCollectionChanged();
}
}
#endregion
#region ICollection<T> members
/// <summary>
///
/// </summary>
/// <value>True if this collection is empty.</value>
public override bool IsEmpty => size == 0;
/// <summary>
///
/// </summary>
/// <value>The size of this collection</value>
public override int Count => size;
/// <summary>
/// The value is symbolic indicating the type of asymptotic complexity
/// in terms of the size of this collection (worst-case or amortized as
/// relevant).
/// </summary>
/// <value>A characterization of the speed of the
/// <code>Count</code> property in this collection.</value>
public override Speed CountSpeed => Speed.Constant;
/// <summary>
/// Choose some item of this collection.
/// </summary>
/// <exception cref="NoSuchItemException">if collection is empty.</exception>
/// <returns></returns>
public override T Choose()
{
if (size == 0)
{
throw new NoSuchItemException("Collection is empty");
}
return heap[0].first;
}
/// <summary>
/// Create an enumerator for the collection
/// <para>Note: the enumerator does *not* enumerate the items in sorted order,
/// but in the internal table order.</para>
/// </summary>
/// <returns>The enumerator(SIC)</returns>
public override SCG.IEnumerator<T> GetEnumerator()
{
int mystamp = stamp;
for (int i = 0; i < size; i++)
{
if (mystamp != stamp)
{
throw new CollectionModifiedException();
}
yield return i % 2 == 0 ? heap[i >> 1].first : heap[i >> 1].last;
}
yield break;
}
#endregion
#region Diagnostics
// Check invariants:
// * first <= last in a cell if both are valid
// * a parent interval (cell) contains both its daughter intervals (cells)
// * a handle, if non-null, points to the cell it is associated with
private bool Check(int i, T min, T max)
{
bool retval = true;
Interval interval = heap[i];
T first = interval.first, last = interval.last;
if (2 * i + 1 == size)
{
if (comparer.Compare(min, first) > 0)
{
Logger.Log(string.Format("Cell {0}: parent.first({1}) > first({2}) [size={3}]", i, min, first, size));
retval = false;
}
if (comparer.Compare(first, max) > 0)
{
Logger.Log(string.Format("Cell {0}: first({1}) > parent.last({2}) [size={3}]", i, first, max, size));
retval = false;
}
if (interval.firsthandle != null && interval.firsthandle.index != 2 * i)
{
Logger.Log(string.Format("Cell {0}: firsthandle.index({1}) != 2*cell({2}) [size={3}]", i, interval.firsthandle.index, 2 * i, size));
retval = false;
}
return retval;
}
else
{
if (comparer.Compare(min, first) > 0)
{
Logger.Log(string.Format("Cell {0}: parent.first({1}) > first({2}) [size={3}]", i, min, first, size));
retval = false;
}
if (comparer.Compare(first, last) > 0)
{
Logger.Log(string.Format("Cell {0}: first({1}) > last({2}) [size={3}]", i, first, last, size));
retval = false;
}
if (comparer.Compare(last, max) > 0)
{
Logger.Log(string.Format("Cell {0}: last({1}) > parent.last({2}) [size={3}]", i, last, max, size));
retval = false;
}
if (interval.firsthandle != null && interval.firsthandle.index != 2 * i)
{
Logger.Log(string.Format("Cell {0}: firsthandle.index({1}) != 2*cell({2}) [size={3}]", i, interval.firsthandle.index, 2 * i, size));
retval = false;
}
if (interval.lasthandle != null && interval.lasthandle.index != 2 * i + 1)
{
Logger.Log(string.Format("Cell {0}: lasthandle.index({1}) != 2*cell+1({2}) [size={3}]", i, interval.lasthandle.index, 2 * i + 1, size));
retval = false;
}
int l = 2 * i + 1, r = l + 1;
if (2 * l < size)
{
retval = retval && Check(l, first, last);
}
if (2 * r < size)
{
retval = retval && Check(r, first, last);
}
}
return retval;
}
/// <summary>
/// Check the integrity of the internal data structures of this collection.
/// Only available in DEBUG builds???
/// </summary>
/// <returns>True if check does not fail.</returns>
public bool Check()
{
if (size == 0)
{
return true;
}
if (size == 1)
{
return heap[0].first != null;
}
return Check(0, heap[0].first, heap[0].last);
}
#endregion
#region IPriorityQueue<T> Members
[Serializable]
private class Handle : IPriorityQueueHandle<T>
{
/// <summary>
/// To save space, the index is 2*cell for heap[cell].first, and 2*cell+1 for heap[cell].last
/// </summary>
internal int index = -1;
public override string ToString()
{
return string.Format("[{0}]", index);
}
}
/// <summary>
/// Get or set the item corresponding to a handle.
/// </summary>
/// <exception cref="InvalidPriorityQueueHandleException">if the handle is invalid for this queue</exception>
/// <param name="handle">The reference into the heap</param>
/// <returns></returns>
public T this[IPriorityQueueHandle<T> handle]
{
get
{
CheckHandle(handle, out int cell, out bool isfirst);
return isfirst ? heap[cell].first : heap[cell].last;
}
set => Replace(handle, value);
}
/// <summary>
/// Check safely if a handle is valid for this queue and if so, report the corresponding queue item.
/// </summary>
/// <param name="handle">The handle to check</param>
/// <param name="item">If the handle is valid this will contain the corresponding item on output.</param>
/// <returns>True if the handle is valid.</returns>
public bool Find(IPriorityQueueHandle<T> handle, out T item)
{
if (!(handle is Handle myhandle))
{
item = default;
return false;
}
int toremove = myhandle.index;
int cell = toremove / 2;
bool isfirst = toremove % 2 == 0;
{
if (toremove == -1 || toremove >= size)
{
item = default;
return false;
}
Handle actualhandle = (isfirst ? heap[cell].firsthandle : heap[cell].lasthandle)!;
if (actualhandle != myhandle)
{
item = default;
return false;
}
}
item = isfirst ? heap[cell].first : heap[cell].last;
return true;
}
/// <summary>
/// Add an item to the priority queue, receiving a
/// handle for the item in the queue,
/// or reusing an already existing handle.
/// </summary>
/// <param name="handle">On output: a handle for the added item.
/// On input: null for allocating a new handle, an invalid handle for reuse.
/// A handle for reuse must be compatible with this priority queue,
/// by being created by a priority queue of the same runtime type, but not
/// necessarily the same priority queue object.</param>
/// <param name="item">The item to add.</param>
/// <returns>True since item will always be added unless the call throws an exception.</returns>
public bool Add(ref IPriorityQueueHandle<T> handle, T item)
{
stamp++;
Handle myhandle = (Handle)handle;
if (myhandle == null)
{
handle = myhandle = new Handle();
}
else
if (myhandle.index != -1)
{
throw new InvalidPriorityQueueHandleException("Handle not valid for reuse");
}
if (Add(myhandle, item))
{
RaiseItemsAdded(item, 1);
RaiseCollectionChanged();
return true;
}
return false;
}
/// <summary>
/// Delete an item with a handle from a priority queue.
/// </summary>
/// <exception cref="InvalidPriorityQueueHandleException">if the handle is invalid</exception>
/// <param name="handle">The handle for the item. The handle will be invalidated, but reusable.</param>
/// <returns>The deleted item</returns>
public T Delete(IPriorityQueueHandle<T> handle)
{
stamp++;
Handle myhandle = CheckHandle(handle, out int cell, out bool isfirst);
T retval;
myhandle.index = -1;
int lastcell = (size - 1) / 2;
if (cell == lastcell)
{
if (isfirst)
{
retval = heap[cell].first;
if (size % 2 == 0)
{
UpdateFirst(cell, heap[cell].last, heap[cell].lasthandle);
heap[cell].last = default;
heap[cell].lasthandle = null;
}
else
{
heap[cell].first = default;
heap[cell].firsthandle = null;
}
}
else
{
retval = heap[cell].last;
heap[cell].last = default;
heap[cell].lasthandle = null;
}
size--;
}
else if (isfirst)
{
retval = heap[cell].first;
if (size % 2 == 0)
{
UpdateFirst(cell, heap[lastcell].last, heap[lastcell].lasthandle);
heap[lastcell].last = default;
heap[lastcell].lasthandle = null;
}
else
{
UpdateFirst(cell, heap[lastcell].first, heap[lastcell].firsthandle);
heap[lastcell].first = default;
heap[lastcell].firsthandle = null;
}
size--;
if (HeapifyMin(cell))
{
BubbleUpMax(cell);
}
else
{
BubbleUpMin(cell);
}
}
else
{
retval = heap[cell].last;
if (size % 2 == 0)
{
UpdateLast(cell, heap[lastcell].last, heap[lastcell].lasthandle);
heap[lastcell].last = default;
heap[lastcell].lasthandle = null;
}
else
{
UpdateLast(cell, heap[lastcell].first, heap[lastcell].firsthandle);
heap[lastcell].first = default;
heap[lastcell].firsthandle = null;
}
size--;
if (HeapifyMax(cell))
{
BubbleUpMin(cell);
}
else
{
BubbleUpMax(cell);
}
}
RaiseItemsRemoved(retval, 1);
RaiseCollectionChanged();
return retval;
}
private Handle CheckHandle(IPriorityQueueHandle<T> handle, out int cell, out bool isfirst)
{
Handle myhandle = (Handle)handle;
int toremove = myhandle.index;
cell = toremove / 2;
isfirst = toremove % 2 == 0;
{
if (toremove == -1 || toremove >= size)
{
throw new InvalidPriorityQueueHandleException("Invalid handle, index out of range");
}
Handle actualhandle = (isfirst ? heap[cell].firsthandle : heap[cell].lasthandle)!;
if (actualhandle != myhandle)
{
throw new InvalidPriorityQueueHandleException("Invalid handle, doesn't match queue");
}
}
return myhandle;
}
/// <summary>
/// Replace an item with a handle in a priority queue with a new item.
/// Typically used for changing the priority of some queued object.
/// </summary>
/// <param name="handle">The handle for the old item</param>
/// <param name="item">The new item</param>
/// <returns>The old item</returns>
public T Replace(IPriorityQueueHandle<T> handle, T item)
{
stamp++;
CheckHandle(handle, out int cell, out bool isfirst);
if (size == 0)
{
throw new NoSuchItemException();
}
T retval;
if (isfirst)
{
retval = heap[cell].first;
heap[cell].first = item;
if (size == 1)
{
}
else if (size == 2 * cell + 1) // cell == lastcell
{
int p = (cell + 1) / 2 - 1;
if (comparer.Compare(item, heap[p].last) > 0)
{
Handle thehandle = heap[cell].firsthandle!;
UpdateFirst(cell, heap[p].last, heap[p].lasthandle);
UpdateLast(p, item, thehandle);
BubbleUpMax(p);
}
else
{
BubbleUpMin(cell);
}
}
else if (HeapifyMin(cell))
{
BubbleUpMax(cell);
}
else
{
BubbleUpMin(cell);
}
}
else
{
retval = heap[cell].last;
heap[cell].last = item;
if (HeapifyMax(cell))
{
BubbleUpMin(cell);
}
else
{
BubbleUpMax(cell);
}
}
RaiseItemsRemoved(retval, 1);
RaiseItemsAdded(item, 1);
RaiseCollectionChanged();
return retval;
}
/// <summary>
/// Find the current least item of this priority queue.
/// </summary>
/// <param name="handle">On return: the handle of the item.</param>
/// <returns>The least item.</returns>
public T FindMin(out IPriorityQueueHandle<T> handle)
{
if (size == 0)
{
throw new NoSuchItemException();
}
handle = heap[0].firsthandle!;
return heap[0].first;
}
/// <summary>
/// Find the current largest item of this priority queue.
/// </summary>
/// <param name="handle">On return: the handle of the item.</param>
/// <returns>The largest item.</returns>
public T FindMax(out IPriorityQueueHandle<T> handle)
{
if (size == 0)
{
throw new NoSuchItemException();
}
else if (size == 1)
{
handle = heap[0].firsthandle!;
return heap[0].first;
}
else
{
handle = heap[0].lasthandle!;
return heap[0].last;
}
}
/// <summary>
/// Remove the least item from this priority queue.
/// </summary>
/// <param name="handle">On return: the handle of the removed item.</param>
/// <returns>The removed item.</returns>
public T DeleteMin(out IPriorityQueueHandle<T> handle)
{
stamp++;
if (size == 0)
{
throw new NoSuchItemException();
}
T retval = heap[0].first;
Handle myhandle = heap[0].firsthandle!;
handle = myhandle;
if (myhandle != null)
{
myhandle.index = -1;
}
if (size == 1)
{
size = 0;
heap[0].first = default;
heap[0].firsthandle = null;
}
else
{
int lastcell = (size - 1) / 2;
if (size % 2 == 0)
{
UpdateFirst(0, heap[lastcell].last, heap[lastcell].lasthandle);
heap[lastcell].last = default;
heap[lastcell].lasthandle = null;
}
else
{
UpdateFirst(0, heap[lastcell].first, heap[lastcell].firsthandle);
heap[lastcell].first = default;
heap[lastcell].firsthandle = null;
}
size--;
HeapifyMin(0);
}
RaiseItemsRemoved(retval, 1);
RaiseCollectionChanged();
return retval;
}
/// <summary>
/// Remove the largest item from this priority queue.
/// </summary>
/// <param name="handle">On return: the handle of the removed item.</param>
/// <returns>The removed item.</returns>
public T DeleteMax(out IPriorityQueueHandle<T> handle)
{
stamp++;
if (size == 0)
{
throw new NoSuchItemException();
}
T retval;
Handle myhandle;
if (size == 1)
{
size = 0;
retval = heap[0].first;
myhandle = heap[0].firsthandle!;
if (myhandle != null)
{
myhandle.index = -1;
}
heap[0].first = default;
heap[0].firsthandle = null;
}
else
{
retval = heap[0].last;
myhandle = heap[0].lasthandle!;
if (myhandle != null)
{
myhandle.index = -1;
}
int lastcell = (size - 1) / 2;
if (size % 2 == 0)
{
UpdateLast(0, heap[lastcell].last, heap[lastcell].lasthandle);
heap[lastcell].last = default;
heap[lastcell].lasthandle = null;
}
else
{
UpdateLast(0, heap[lastcell].first, heap[lastcell].firsthandle);
heap[lastcell].first = default;
heap[lastcell].firsthandle = null;
}
size--;
HeapifyMax(0);
}
RaiseItemsRemoved(retval, 1);
RaiseCollectionChanged();
handle = myhandle!;
return retval;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reactive.Disposables;
using System.Text;
using CoreAnimation;
using CoreGraphics;
using Foundation;
using Avalonia.Controls.Platform;
using Avalonia.Input;
using Avalonia.Input.Raw;
using Avalonia.Media;
using Avalonia.Platform;
using Avalonia.Skia.iOS;
using UIKit;
using Avalonia.iOS.Specific;
using ObjCRuntime;
using Avalonia.Controls;
namespace Avalonia.iOS
{
[Adopts("UIKeyInput")]
class AvaloniaView : SkiaView, IWindowImpl
{
private readonly UIWindow _window;
private readonly UIViewController _controller;
private IInputRoot _inputRoot;
private readonly KeyboardEventsHelper<AvaloniaView> _keyboardHelper;
private Point _position;
public AvaloniaView(UIWindow window, UIViewController controller) : base(onFrame => PlatformThreadingInterface.Instance.Render = onFrame)
{
if (controller == null) throw new ArgumentNullException(nameof(controller));
_window = window;
_controller = controller;
_keyboardHelper = new KeyboardEventsHelper<AvaloniaView>(this);
AutoresizingMask = UIViewAutoresizing.All;
AutoFit();
UIApplication.Notifications.ObserveDidChangeStatusBarOrientation(delegate { AutoFit(); });
UIApplication.Notifications.ObserveDidChangeStatusBarFrame(delegate { AutoFit(); });
}
[Export("hasText")]
bool HasText => _keyboardHelper.HasText();
[Export("insertText:")]
void InsertText(string text) => _keyboardHelper.InsertText(text);
[Export("deleteBackward")]
void DeleteBackward() => _keyboardHelper.DeleteBackward();
public override bool CanBecomeFirstResponder => _keyboardHelper.CanBecomeFirstResponder();
void AutoFit()
{
var needFlip = !UIDevice.CurrentDevice.CheckSystemVersion(8, 0) &&
(_controller.InterfaceOrientation == UIInterfaceOrientation.LandscapeLeft
|| _controller.InterfaceOrientation == UIInterfaceOrientation.LandscapeRight);
// Bounds here (if top level) needs to correspond with the rendertarget
var frame = UIScreen.MainScreen.Bounds;
if (needFlip)
Frame = new CGRect(frame.Y, frame.X, frame.Height, frame.Width);
else
Frame = frame;
}
public Action Activated { get; set; }
public Action Closed { get; set; }
public Action Deactivated { get; set; }
public Action<RawInputEventArgs> Input { get; set; }
public Action<Rect> Paint { get; set; }
public Action<Size> Resized { get; set; }
public Action<double> ScalingChanged { get; set; }
public Action<Point> PositionChanged { get; set; }
public IPlatformHandle Handle => AvaloniaPlatformHandle;
public double Scaling
{
get
{
// This does not appear to make any difference, but on iOS we
// have Retina (x2) and we probably want this eventually
return 1; //UIScreen.MainScreen.Scale;
}
}
public WindowState WindowState
{
get { return WindowState.Normal; }
set { }
}
public override void LayoutSubviews() => Resized?.Invoke(ClientSize);
public Size ClientSize
{
get { return Bounds.Size.ToAvalonia(); }
set { Resized?.Invoke(ClientSize); }
}
public void Activate()
{
}
protected override void Draw()
{
Paint?.Invoke(new Rect(new Point(), ClientSize));
}
public void Invalidate(Rect rect) => DrawOnNextFrame();
public void SetInputRoot(IInputRoot inputRoot) => _inputRoot = inputRoot;
public Point PointToClient(Point point) => point;
public Point PointToScreen(Point point) => point;
public void SetCursor(IPlatformHandle cursor)
{
//Not supported
}
public void Show()
{
_keyboardHelper.ActivateAutoShowKeybord();
}
public void BeginMoveDrag()
{
//Not supported
}
public void BeginResizeDrag(WindowEdge edge)
{
//Not supported
}
public Point Position
{
get { return _position; }
set
{
_position = value;
PositionChanged?.Invoke(_position);
}
}
public Size MaxClientSize => Bounds.Size.ToAvalonia();
public void SetTitle(string title)
{
//Not supported
}
public IDisposable ShowDialog()
{
//Not supported
return Disposable.Empty;
}
public void Hide()
{
//Not supported
}
public void SetSystemDecorations(bool enabled)
{
//Not supported
}
public override void TouchesEnded(NSSet touches, UIEvent evt)
{
var touch = touches.AnyObject as UITouch;
if (touch != null)
{
var location = touch.LocationInView(this).ToAvalonia();
Input?.Invoke(new RawMouseEventArgs(
iOSPlatform.MouseDevice,
(uint)touch.Timestamp,
_inputRoot,
RawMouseEventType.LeftButtonUp,
location,
InputModifiers.None));
}
}
Point _touchLastPoint;
public override void TouchesBegan(NSSet touches, UIEvent evt)
{
var touch = touches.AnyObject as UITouch;
if (touch != null)
{
var location = touch.LocationInView(this).ToAvalonia();
_touchLastPoint = location;
Input?.Invoke(new RawMouseEventArgs(iOSPlatform.MouseDevice, (uint)touch.Timestamp, _inputRoot,
RawMouseEventType.Move, location, InputModifiers.None));
Input?.Invoke(new RawMouseEventArgs(iOSPlatform.MouseDevice, (uint)touch.Timestamp, _inputRoot,
RawMouseEventType.LeftButtonDown, location, InputModifiers.None));
}
}
public override void TouchesMoved(NSSet touches, UIEvent evt)
{
var touch = touches.AnyObject as UITouch;
if (touch != null)
{
var location = touch.LocationInView(this).ToAvalonia();
if (iOSPlatform.MouseDevice.Captured != null)
Input?.Invoke(new RawMouseEventArgs(iOSPlatform.MouseDevice, (uint)touch.Timestamp, _inputRoot,
RawMouseEventType.Move, location, InputModifiers.LeftMouseButton));
else
{
//magic number based on test - correction of 0.02 is working perfect
double correction = 0.02;
Input?.Invoke(new RawMouseWheelEventArgs(iOSPlatform.MouseDevice, (uint)touch.Timestamp,
_inputRoot, location, (location - _touchLastPoint) * correction, InputModifiers.LeftMouseButton));
}
_touchLastPoint = location;
}
}
public void SetIcon(IWindowIconImpl icon)
{
}
}
class AvaloniaViewController : UIViewController
{
public AvaloniaView AvaloniaView { get; }
public AvaloniaViewController(UIWindow window)
{
AvaloniaView = new AvaloniaView(window, this);
}
public override void LoadView()
{
View = AvaloniaView;
}
}
}
| |
// 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.Xml;
using System.Collections;
namespace System.Data.Common
{
internal sealed class DecimalStorage : DataStorage
{
private static readonly decimal s_defaultValue = decimal.Zero;
private decimal[] _values;
internal DecimalStorage(DataColumn column)
: base(column, typeof(decimal), s_defaultValue, StorageType.Decimal)
{
}
public override object Aggregate(int[] records, AggregateType kind)
{
bool hasData = false;
try
{
switch (kind)
{
case AggregateType.Sum:
decimal sum = s_defaultValue;
foreach (int record in records)
{
if (HasValue(record))
{
checked { sum += _values[record]; }
hasData = true;
}
}
if (hasData)
{
return sum;
}
return _nullValue;
case AggregateType.Mean:
decimal meanSum = s_defaultValue;
int meanCount = 0;
foreach (int record in records)
{
if (HasValue(record))
{
checked { meanSum += _values[record]; }
meanCount++;
hasData = true;
}
}
if (hasData)
{
decimal mean;
checked { mean = (meanSum / meanCount); }
return mean;
}
return _nullValue;
case AggregateType.Var:
case AggregateType.StDev:
int count = 0;
double var = (double)s_defaultValue;
double prec = (double)s_defaultValue;
double dsum = (double)s_defaultValue;
double sqrsum = (double)s_defaultValue;
foreach (int record in records)
{
if (HasValue(record))
{
dsum += (double)_values[record];
sqrsum += (double)_values[record] * (double)_values[record];
count++;
}
}
if (count > 1)
{
var = count * sqrsum - (dsum * dsum);
prec = var / (dsum * dsum);
// we are dealing with the risk of a cancellation error
// double is guaranteed only for 15 digits so a difference
// with a result less than 1e-15 should be considered as zero
if ((prec < 1e-15) || (var < 0))
var = 0;
else
var = var / (count * (count - 1));
if (kind == AggregateType.StDev)
{
return Math.Sqrt(var);
}
return var;
}
return _nullValue;
case AggregateType.Min:
decimal min = decimal.MaxValue;
for (int i = 0; i < records.Length; i++)
{
int record = records[i];
if (HasValue(record))
{
min = Math.Min(_values[record], min);
hasData = true;
}
}
if (hasData)
{
return min;
}
return _nullValue;
case AggregateType.Max:
decimal max = decimal.MinValue;
for (int i = 0; i < records.Length; i++)
{
int record = records[i];
if (HasValue(record))
{
max = Math.Max(_values[record], max);
hasData = true;
}
}
if (hasData)
{
return max;
}
return _nullValue;
case AggregateType.First:
if (records.Length > 0)
{
return _values[records[0]];
}
return null;
case AggregateType.Count:
return base.Aggregate(records, kind);
}
}
catch (OverflowException)
{
throw ExprException.Overflow(typeof(decimal));
}
throw ExceptionBuilder.AggregateException(kind, _dataType);
}
public override int Compare(int recordNo1, int recordNo2)
{
decimal valueNo1 = _values[recordNo1];
decimal valueNo2 = _values[recordNo2];
if (valueNo1 == s_defaultValue || valueNo2 == s_defaultValue)
{
int bitCheck = CompareBits(recordNo1, recordNo2);
if (0 != bitCheck)
return bitCheck;
}
return decimal.Compare(valueNo1, valueNo2); // InternalCall
}
public override int CompareValueTo(int recordNo, object value)
{
System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record");
System.Diagnostics.Debug.Assert(null != value, "null value");
if (_nullValue == value)
{
return (HasValue(recordNo) ? 1 : 0);
}
decimal valueNo1 = _values[recordNo];
if ((s_defaultValue == valueNo1) && !HasValue(recordNo))
{
return -1;
}
return decimal.Compare(valueNo1, (decimal)value);
}
public override object ConvertValue(object value)
{
if (_nullValue != value)
{
if (null != value)
{
value = ((IConvertible)value).ToDecimal(FormatProvider);
}
else
{
value = _nullValue;
}
}
return value;
}
public override void Copy(int recordNo1, int recordNo2)
{
CopyBits(recordNo1, recordNo2);
_values[recordNo2] = _values[recordNo1];
}
public override object Get(int record)
{
return (HasValue(record) ? _values[record] : _nullValue);
}
public override void Set(int record, object value)
{
System.Diagnostics.Debug.Assert(null != value, "null value");
if (_nullValue == value)
{
_values[record] = s_defaultValue;
SetNullBit(record, true);
}
else
{
_values[record] = ((IConvertible)value).ToDecimal(FormatProvider);
SetNullBit(record, false);
}
}
public override void SetCapacity(int capacity)
{
decimal[] newValues = new decimal[capacity];
if (null != _values)
{
Array.Copy(_values, 0, newValues, 0, Math.Min(capacity, _values.Length));
}
_values = newValues;
base.SetCapacity(capacity);
}
public override object ConvertXmlToObject(string s)
{
return XmlConvert.ToDecimal(s);
}
public override string ConvertObjectToXml(object value)
{
return XmlConvert.ToString((decimal)value);
}
protected override object GetEmptyStorage(int recordCount)
{
return new decimal[recordCount];
}
protected override void CopyValue(int record, object store, BitArray nullbits, int storeIndex)
{
decimal[] typedStore = (decimal[])store;
typedStore[storeIndex] = _values[record];
nullbits.Set(storeIndex, !HasValue(record));
}
protected override void SetStorage(object store, BitArray nullbits)
{
_values = (decimal[])store;
SetNullStorage(nullbits);
}
}
}
| |
// 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.
//-----------------------------------------------------------------------------
//
// Description:
// This is a sub class of the abstract class for Package.
// This implementation is specific to Zip file format.
//
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Xml; //Required for Content Type File manipulation
using System.Diagnostics;
using System.IO.Compression;
namespace System.IO.Packaging
{
/// <summary>
/// ZipPackage is a specific implementation for the abstract Package
/// class, corresponding to the Zip file format.
/// This is a part of the Packaging Layer APIs.
/// </summary>
public sealed class ZipPackage : Package
{
//------------------------------------------------------
//
// Public Constructors
//
//------------------------------------------------------
// None
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
// None
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
#region PackagePart Methods
/// <summary>
/// This method is for custom implementation for the underlying file format
/// Adds a new item to the zip archive corresponding to the PackagePart in the package.
/// </summary>
/// <param name="partUri">PartName</param>
/// <param name="contentType">Content type of the part</param>
/// <param name="compressionOption">Compression option for this part</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">If partUri parameter is null</exception>
/// <exception cref="ArgumentNullException">If contentType parameter is null</exception>
/// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception>
/// <exception cref="ArgumentOutOfRangeException">If CompressionOption enumeration [compressionOption] does not have one of the valid values</exception>
protected override PackagePart CreatePartCore(Uri partUri,
string contentType,
CompressionOption compressionOption)
{
//Validating the PartUri - this method will do the argument checking required for uri.
partUri = PackUriHelper.ValidatePartUri(partUri);
if (contentType == null)
throw new ArgumentNullException(nameof(contentType));
Package.ThrowIfCompressionOptionInvalid(compressionOption);
// Convert Metro CompressionOption to Zip CompressionMethodEnum.
CompressionLevel level;
GetZipCompressionMethodFromOpcCompressionOption(compressionOption,
out level);
// Create new Zip item.
// We need to remove the leading "/" character at the beginning of the part name.
// The partUri object must be a ValidatedPartUri
string zipItemName = ((PackUriHelper.ValidatedPartUri)partUri).PartUriString.Substring(1);
ZipArchiveEntry zipArchiveEntry = _zipArchive.CreateEntry(zipItemName, level);
//Store the content type of this part in the content types stream.
_contentTypeHelper.AddContentType((PackUriHelper.ValidatedPartUri)partUri, new ContentType(contentType), level);
return new ZipPackagePart(this, zipArchiveEntry.Archive, zipArchiveEntry, _zipStreamManager, (PackUriHelper.ValidatedPartUri)partUri, contentType, compressionOption);
}
/// <summary>
/// This method is for custom implementation specific to the file format.
/// Returns the part after reading the actual physical bits. The method
/// returns a null to indicate that the part corresponding to the specified
/// Uri was not found in the container.
/// This method does not throw an exception if a part does not exist.
/// </summary>
/// <param name="partUri"></param>
/// <returns></returns>
protected override PackagePart GetPartCore(Uri partUri)
{
//Currently the design has two aspects which makes it possible to return
//a null from this method -
// 1. All the parts are loaded at Package.Open time and as such, this
// method would not be invoked, unless the user is asking for -
// i. a part that does not exist - we can safely return null
// ii.a part(interleaved/non-interleaved) that was added to the
// underlying package by some other means, and the user wants to
// access the updated part. This is currently not possible as the
// underlying zip i/o layer does not allow for FileShare.ReadWrite.
// 2. Also, its not a straighforward task to determine if a new part was
// added as we need to look for atomic as well as interleaved parts and
// this has to be done in a case sensitive manner. So, effectively
// we will have to go through the entire list of zip items to determine
// if there are any updates.
// If ever the design changes, then this method must be updated accordingly
return null;
}
/// <summary>
/// This method is for custom implementation specific to the file format.
/// Deletes the part corresponding to the uri specified. Deleting a part that does not
/// exists is not an error and so we do not throw an exception in that case.
/// </summary>
/// <param name="partUri"></param>
/// <exception cref="ArgumentNullException">If partUri parameter is null</exception>
/// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception>
protected override void DeletePartCore(Uri partUri)
{
//Validating the PartUri - this method will do the argument checking required for uri.
partUri = PackUriHelper.ValidatePartUri(partUri);
string partZipName = GetZipItemNameFromOpcName(PackUriHelper.GetStringForPartUri(partUri));
ZipArchiveEntry zipArchiveEntry = _zipArchive.GetEntry(partZipName);
if (zipArchiveEntry != null)
{
// Case of an atomic part.
zipArchiveEntry.Delete();
}
//Delete the content type for this part if it was specified as an override
_contentTypeHelper.DeleteContentType((PackUriHelper.ValidatedPartUri)partUri);
}
/// <summary>
/// This method is for custom implementation specific to the file format.
/// This is the method that knows how to get the actual parts from the underlying
/// zip archive.
/// </summary>
/// <remarks>
/// <para>
/// Some or all of the parts may be interleaved. The Part object for an interleaved part encapsulates
/// the Uri of the proper part name and the ZipFileInfo of the initial piece.
/// This function does not go through the extra work of checking piece naming validity
/// throughout the package.
/// </para>
/// <para>
/// This means that interleaved parts without an initial piece will be silently ignored.
/// Other naming anomalies get caught at the Stream level when an I/O operation involves
/// an anomalous or missing piece.
/// </para>
/// <para>
/// This function reads directly from the underlying IO layer and is supposed to be called
/// just once in the lifetime of a package (at init time).
/// </para>
/// </remarks>
/// <returns>An array of ZipPackagePart.</returns>
protected override PackagePart[] GetPartsCore()
{
List<PackagePart> parts = new List<PackagePart>(InitialPartListSize);
// The list of files has to be searched linearly (1) to identify the content type
// stream, and (2) to identify parts.
System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipArchiveEntries = _zipArchive.Entries;
// We have already identified the [ContentTypes].xml pieces if any are present during
// the initialization of ZipPackage object
// Record parts and ignored items.
foreach (ZipArchiveEntry zipArchiveEntry in zipArchiveEntries)
{
//Returns false if -
// a. its a content type item
// b. items that have either a leading or trailing slash.
if (IsZipItemValidOpcPartOrPiece(zipArchiveEntry.FullName))
{
Uri partUri = new Uri(GetOpcNameFromZipItemName(zipArchiveEntry.FullName), UriKind.Relative);
PackUriHelper.ValidatedPartUri validatedPartUri;
if (PackUriHelper.TryValidatePartUri(partUri, out validatedPartUri))
{
ContentType contentType = _contentTypeHelper.GetContentType(validatedPartUri);
if (contentType != null)
{
// In case there was some redundancy between pieces and/or the atomic
// part, it will be detected at this point because the part's Uri (which
// is independent of interleaving) will already be in the dictionary.
parts.Add(new ZipPackagePart(this, zipArchiveEntry.Archive, zipArchiveEntry,
_zipStreamManager, validatedPartUri, contentType.ToString(), GetCompressionOptionFromZipFileInfo(zipArchiveEntry)));
}
}
//If not valid part uri we can completely ignore this zip file item. Even if later someone adds
//a new part, the corresponding zip item can never map to one of these items
}
// If IsZipItemValidOpcPartOrPiece returns false, it implies that either the zip file Item
// starts or ends with a "/" and as such we can completely ignore this zip file item. Even if later
// a new part gets added, its corresponding zip item cannot map to one of these items.
}
return parts.ToArray();
}
#endregion PackagePart Methods
#region Other Methods
/// <summary>
/// This method is for custom implementation corresponding to the underlying zip file format.
/// </summary>
protected override void FlushCore()
{
//Save the content type file to the archive.
_contentTypeHelper.SaveToFile();
}
/// <summary>
/// Closes the underlying ZipArchive object for this container
/// </summary>
/// <param name="disposing">True if called during Dispose, false if called during Finalize</param>
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
if (_contentTypeHelper != null)
{
_contentTypeHelper.SaveToFile();
}
if (_zipStreamManager != null)
{
_zipStreamManager.Dispose();
}
if (_zipArchive != null)
{
_zipArchive.Dispose();
}
// _containerStream may be opened given a file name, in which case it should be closed here.
// _containerStream may be passed into the constructor, in which case, it should not be closed here.
if (_shouldCloseContainerStream)
{
_containerStream.Dispose();
}
else
{
}
_containerStream = null;
}
}
finally
{
base.Dispose(disposing);
}
}
#endregion Other Methods
#endregion Public Methods
//------------------------------------------------------
//
// Public Events
//
//------------------------------------------------------
// None
//------------------------------------------------------
//
// Internal Constructors
//
//------------------------------------------------------
#region Internal Constructors
/// <summary>
/// Internal constructor that is called by the OpenOnFile static method.
/// </summary>
/// <param name="path">File path to the container.</param>
/// <param name="packageFileMode">Container is opened in the specified mode if possible</param>
/// <param name="packageFileAccess">Container is opened with the speficied access if possible</param>
/// <param name="share">Container is opened with the specified share if possible</param>
internal ZipPackage(string path, FileMode packageFileMode, FileAccess packageFileAccess, FileShare share)
: base(packageFileAccess)
{
ZipArchive zipArchive = null;
ContentTypeHelper contentTypeHelper = null;
_packageFileMode = packageFileMode;
_packageFileAccess = packageFileAccess;
try
{
_containerStream = new FileStream(path, _packageFileMode, _packageFileAccess, share);
_shouldCloseContainerStream = true;
ZipArchiveMode zipArchiveMode = ZipArchiveMode.Update;
if (packageFileAccess == FileAccess.Read)
zipArchiveMode = ZipArchiveMode.Read;
else if (packageFileAccess == FileAccess.Write)
zipArchiveMode = ZipArchiveMode.Create;
else if (packageFileAccess == FileAccess.ReadWrite)
zipArchiveMode = ZipArchiveMode.Update;
zipArchive = new ZipArchive(_containerStream, zipArchiveMode, true, Text.Encoding.UTF8);
_zipStreamManager = new ZipStreamManager(zipArchive, _packageFileMode, _packageFileAccess);
contentTypeHelper = new ContentTypeHelper(zipArchive, _packageFileMode, _packageFileAccess, _zipStreamManager);
}
catch
{
if (zipArchive != null)
{
zipArchive.Dispose();
}
throw;
}
_zipArchive = zipArchive;
_contentTypeHelper = contentTypeHelper;
}
/// <summary>
/// Internal constructor that is called by the Open(Stream) static methods.
/// </summary>
/// <param name="s"></param>
/// <param name="packageFileMode"></param>
/// <param name="packageFileAccess"></param>
internal ZipPackage(Stream s, FileMode packageFileMode, FileAccess packageFileAccess)
: base(packageFileAccess)
{
ZipArchive zipArchive = null;
ContentTypeHelper contentTypeHelper = null;
_packageFileMode = packageFileMode;
_packageFileAccess = packageFileAccess;
try
{
ZipArchiveMode zipArchiveMode = ZipArchiveMode.Update;
if (packageFileAccess == FileAccess.Read)
zipArchiveMode = ZipArchiveMode.Read;
else if (packageFileAccess == FileAccess.Write)
zipArchiveMode = ZipArchiveMode.Create;
else if (packageFileAccess == FileAccess.ReadWrite)
zipArchiveMode = ZipArchiveMode.Update;
zipArchive = new ZipArchive(s, zipArchiveMode, true, Text.Encoding.UTF8);
_zipStreamManager = new ZipStreamManager(zipArchive, packageFileMode, packageFileAccess);
contentTypeHelper = new ContentTypeHelper(zipArchive, packageFileMode, packageFileAccess, _zipStreamManager);
}
catch (InvalidDataException)
{
throw new FileFormatException("File contains corrupted data.");
}
catch
{
if (zipArchive != null)
{
zipArchive.Dispose();
}
throw;
}
_containerStream = s;
_shouldCloseContainerStream = false;
_zipArchive = zipArchive;
_contentTypeHelper = contentTypeHelper;
}
#endregion Internal Constructors
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
// More generic function than GetZipItemNameFromPartName. In particular, it will handle piece names.
internal static string GetZipItemNameFromOpcName(string opcName)
{
Debug.Assert(opcName != null && opcName.Length > 0);
return opcName.Substring(1);
}
// More generic function than GetPartNameFromZipItemName. In particular, it will handle piece names.
internal static string GetOpcNameFromZipItemName(string zipItemName)
{
return String.Concat(ForwardSlashString, zipItemName);
}
// Convert from Metro CompressionOption to ZipFileInfo compression properties.
internal static void GetZipCompressionMethodFromOpcCompressionOption(
CompressionOption compressionOption,
out CompressionLevel compressionLevel)
{
switch (compressionOption)
{
case CompressionOption.NotCompressed:
{
compressionLevel = CompressionLevel.NoCompression;
}
break;
case CompressionOption.Normal:
{
compressionLevel = CompressionLevel.Optimal;
}
break;
case CompressionOption.Maximum:
{
compressionLevel = CompressionLevel.Optimal;
}
break;
case CompressionOption.Fast:
{
compressionLevel = CompressionLevel.Fastest;
}
break;
case CompressionOption.SuperFast:
{
compressionLevel = CompressionLevel.Fastest;
}
break;
// fall-through is not allowed
default:
{
Debug.Assert(false, "Encountered an invalid CompressionOption enum value");
goto case CompressionOption.NotCompressed;
}
}
}
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
internal FileMode PackageFileMode
{
get
{
return _packageFileMode;
}
}
//------------------------------------------------------
//
// Internal Events
//
//------------------------------------------------------
// None
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
//returns a boolean indicating if the underlying zip item is a valid metro part or piece
// This mainly excludes the content type item, as well as entries with leading or trailing
// slashes.
private bool IsZipItemValidOpcPartOrPiece(string zipItemName)
{
Debug.Assert(zipItemName != null, "The parameter zipItemName should not be null");
//check if the zip item is the Content type item -case sensitive comparison
// The following test will filter out an atomic content type file, with name
// "[Content_Types].xml", as well as an interleaved one, with piece names such as
// "[Content_Types].xml/[0].piece" or "[Content_Types].xml/[5].last.piece".
if (zipItemName.StartsWith(ContentTypeHelper.ContentTypeFileName, StringComparison.OrdinalIgnoreCase))
return false;
else
{
//Could be an empty zip folder
//We decided to ignore zip items that contain a "/" as this could be a folder in a zip archive
//Some of the tools support this and some dont. There is no way ensure that the zip item never have
//a leading "/", although this is a requirement we impose on items created through our API
//Therefore we ignore them at the packaging api level.
if (zipItemName.StartsWith(ForwardSlashString, StringComparison.Ordinal))
return false;
//This will ignore the folder entries found in the zip package created by some zip tool
//PartNames ending with a "/" slash is also invalid so we are skipping these entries,
//this will also prevent the PackUriHelper.CreatePartUri from throwing when it encounters a
// partname ending with a "/"
if (zipItemName.EndsWith(ForwardSlashString, StringComparison.Ordinal))
return false;
else
return true;
}
}
// convert from Zip CompressionMethodEnum and DeflateOptionEnum to Metro CompressionOption
static private CompressionOption GetCompressionOptionFromZipFileInfo(ZipArchiveEntry zipFileInfo)
{
// Note: we can't determine compression method / level from the ZipArchiveEntry.
CompressionOption result = CompressionOption.Normal;
return result;
}
#endregion Private Methods
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Members
private const int InitialPartListSize = 50;
private const int InitialPieceNameListSize = 50;
private ZipArchive _zipArchive;
private Stream _containerStream; // stream we are opened in if Open(Stream) was called
private bool _shouldCloseContainerStream;
private ContentTypeHelper _contentTypeHelper; // manages the content types for all the parts in the container
private ZipStreamManager _zipStreamManager; // manages streams for all parts, avoiding opening streams multiple times
private FileAccess _packageFileAccess;
private FileMode _packageFileMode;
private const string ForwardSlashString = "/"; //Required for creating a part name from a zip item name
//IEqualityComparer for extensions
private static readonly ExtensionEqualityComparer s_extensionEqualityComparer = new ExtensionEqualityComparer();
#endregion Private Members
//------------------------------------------------------
//
// Private Types
//
//------------------------------------------------------
#region Private Class
/// <summary>
/// ExtensionComparer
/// The Extensions are stored in the Default Dicitonary in their original form,
/// however they are compared in a normalized manner.
/// Equivalence for extensions in the content type stream, should follow
/// the same rules as extensions of partnames. Also, by the time this code is invoked,
/// we have already validated, that the extension is in the correct format as per the
/// part name rules.So we are simplifying the logic here to just convert the extensions
/// to Upper invariant form and then compare them.
/// </summary>
private sealed class ExtensionEqualityComparer : IEqualityComparer<string>
{
bool IEqualityComparer<string>.Equals(string extensionA, string extensionB)
{
Debug.Assert(extensionA != null, "extenstion should not be null");
Debug.Assert(extensionB != null, "extenstion should not be null");
//Important Note: any change to this should be made in accordance
//with the rules for comparing/normalizing partnames.
//Refer to PackUriHelper.ValidatedPartUri.GetNormalizedPartUri method.
//Currently normalization just involves upper-casing ASCII and hence the simplification.
return (String.CompareOrdinal(extensionA.ToUpperInvariant(), extensionB.ToUpperInvariant()) == 0);
}
int IEqualityComparer<string>.GetHashCode(string extension)
{
Debug.Assert(extension != null, "extenstion should not be null");
//Important Note: any change to this should be made in accordance
//with the rules for comparing/normalizing partnames.
//Refer to PackUriHelper.ValidatedPartUri.GetNormalizedPartUri method.
//Currently normalization just involves upper-casing ASCII and hence the simplification.
return extension.ToUpperInvariant().GetHashCode();
}
}
#region ContentTypeHelper Class
/// <summary>
/// This is a helper class that maintains the Content Types File related to
/// this ZipPackage.
/// </summary>
private class ContentTypeHelper
{
#region Constructor
/// <summary>
/// Initialize the object without uploading any information from the package.
/// Complete initialization in read mode also involves calling ParseContentTypesFile
/// to deserialize content type information.
/// </summary>
internal ContentTypeHelper(ZipArchive zipArchive, FileMode packageFileMode, FileAccess packageFileAccess, ZipStreamManager zipStreamManager)
{
_zipArchive = zipArchive; //initialized in the ZipPackage constructor
_packageFileMode = packageFileMode;
_packageFileAccess = packageFileAccess;
_zipStreamManager = zipStreamManager; //initialized in the ZipPackage constructor
// The extensions are stored in the default Dictionary in their original form , but they are compared
// in a normalized manner using the ExtensionComparer.
_defaultDictionary = new Dictionary<string, ContentType>(s_defaultDictionaryInitialSize, s_extensionEqualityComparer);
// Identify the content type file or files before identifying parts and piece sequences.
// This is necessary because the name of the content type stream is not a part name and
// the information it contains is needed to recognize valid parts.
if (_zipArchive.Mode == ZipArchiveMode.Read || _zipArchive.Mode == ZipArchiveMode.Update)
ParseContentTypesFile(_zipArchive.Entries);
//No contents to persist to the disk -
_dirty = false; //by default
//Lazy initialize these members as required
//_overrideDictionary - Overrides should be rare
//_contentTypeFileInfo - We will either find an atomin part, or
//_contentTypeStreamPieces - an interleaved part
//_contentTypeStreamExists - defaults to false - not yet found
}
#endregion Constructor
#region Internal Properties
internal static string ContentTypeFileName
{
get
{
return s_contentTypesFile;
}
}
#endregion Internal Properties
#region Internal Methods
//Adds the Default entry if it is the first time we come across
//the extension for the partUri, does nothing if the content type
//corresponding to the default entry for the extension matches or
//adds a override corresponding to this part and content type.
//This call is made when a new part is being added to the package.
// This method assumes the partUri is valid.
internal void AddContentType(PackUriHelper.ValidatedPartUri partUri, ContentType contentType,
CompressionLevel compressionLevel)
{
//save the compressionOption and deflateOption that should be used
//to create the content type item later
if (!_contentTypeStreamExists)
{
_cachedCompressionLevel = compressionLevel;
}
// Figure out whether the mapping matches a default entry, can be made into a new
// default entry, or has to be entered as an override entry.
bool foundMatchingDefault = false;
string extension = partUri.PartUriExtension;
// Need to create an override entry?
if (extension.Length == 0
|| (_defaultDictionary.ContainsKey(extension)
&& !(foundMatchingDefault =
_defaultDictionary[extension].AreTypeAndSubTypeEqual(contentType))))
{
AddOverrideElement(partUri, contentType);
}
// Else, either there is already a mapping from extension to contentType,
// or one needs to be created.
else if (!foundMatchingDefault)
{
AddDefaultElement(extension, contentType);
}
}
//Returns the content type for the part, if present, else returns null.
internal ContentType GetContentType(PackUriHelper.ValidatedPartUri partUri)
{
//Step 1: Check if there is an override entry present corresponding to the
//partUri provided. Override takes precedence over the default entries
if (_overrideDictionary != null)
{
if (_overrideDictionary.ContainsKey(partUri))
return _overrideDictionary[partUri];
}
//Step 2: Check if there is a default entry corresponding to the
//extension of the partUri provided.
string extension = partUri.PartUriExtension;
if (_defaultDictionary.ContainsKey(extension))
return _defaultDictionary[extension];
//Step 3: If we did not find an entry in the override and the default
//dictionaries, this is an error condition
return null;
}
//Deletes the override entry corresponding to the partUri, if it exists
internal void DeleteContentType(PackUriHelper.ValidatedPartUri partUri)
{
if (_overrideDictionary != null)
{
if (_overrideDictionary.Remove(partUri))
_dirty = true;
}
}
internal void SaveToFile()
{
if (_dirty)
{
//Lazy init: Initialize when the first part is added.
if (!_contentTypeStreamExists)
{
_contentTypeZipArchiveEntry = _zipArchive.CreateEntry(s_contentTypesFile, _cachedCompressionLevel);
_contentTypeStreamExists = true;
}
// delete and re-create entry for content part. When writing this, the stream will not truncate the content
// if the XML is shorter than the existing content part.
var contentTypefullName = _contentTypeZipArchiveEntry.FullName;
var thisArchive = _contentTypeZipArchiveEntry.Archive;
_zipStreamManager.Close(_contentTypeZipArchiveEntry);
_contentTypeZipArchiveEntry.Delete();
_contentTypeZipArchiveEntry = thisArchive.CreateEntry(contentTypefullName);
using (Stream s = _zipStreamManager.Open(_contentTypeZipArchiveEntry, _packageFileMode, FileAccess.ReadWrite))
{
// use UTF-8 encoding by default
using (XmlWriter writer = XmlWriter.Create(s, new XmlWriterSettings { Encoding = System.Text.Encoding.UTF8 }))
{
writer.WriteStartDocument();
// write root element tag - Types
writer.WriteStartElement(s_typesTagName, s_typesNamespaceUri);
// for each default entry
foreach (string key in _defaultDictionary.Keys)
{
WriteDefaultElement(writer, key, _defaultDictionary[key]);
}
if (_overrideDictionary != null)
{
// for each override entry
foreach (PackUriHelper.ValidatedPartUri key in _overrideDictionary.Keys)
{
WriteOverrideElement(writer, key, _overrideDictionary[key]);
}
}
// end of Types tag
writer.WriteEndElement();
// close the document
writer.WriteEndDocument();
_dirty = false;
}
}
}
}
#endregion Internal Methods
#region Private Methods
private void EnsureOverrideDictionary()
{
// The part Uris are stored in the Override Dictionary in their original form , but they are compared
// in a normalized manner using the PartUriComparer
if (_overrideDictionary == null)
_overrideDictionary = new Dictionary<PackUriHelper.ValidatedPartUri, ContentType>(s_overrideDictionaryInitialSize);
}
private void ParseContentTypesFile(System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipFiles)
{
// Find the content type stream, allowing for interleaving. Naming collisions
// (as between an atomic and an interleaved part) will result in an exception being thrown.
Stream s = OpenContentTypeStream(zipFiles);
// Allow non-existent content type stream.
if (s == null)
return;
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.IgnoreWhitespace = true;
using (s)
using (XmlReader reader = XmlReader.Create(s, xrs))
{
//This method expects the reader to be in ReadState.Initial.
//It will make the first read call.
PackagingUtilities.PerformInitialReadAndVerifyEncoding(reader);
//Note: After the previous method call the reader should be at the first tag in the markup.
//MoveToContent - Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
//If the reader is currently at a content node then this function call is a no-op
reader.MoveToContent();
// look for our root tag and namespace pair - ignore others in case of version changes
// Make sure that the current node read is an Element
if ((reader.NodeType == XmlNodeType.Element)
&& (reader.Depth == 0)
&& (String.CompareOrdinal(reader.NamespaceURI, s_typesNamespaceUri) == 0)
&& (String.CompareOrdinal(reader.Name, s_typesTagName) == 0))
{
//There should be a namespace Attribute present at this level.
//Also any other attribute on the <Types> tag is an error including xml: and xsi: attributes
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) > 0)
{
throw new XmlException(SR.TypesTagHasExtraAttributes, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
// start tag encountered
// now parse individual Default and Override tags
while (reader.Read())
{
//Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
//If the reader is currently at a content node then this function call is a no-op
reader.MoveToContent();
//If MoveToContent() takes us to the end of the content
if (reader.NodeType == XmlNodeType.None)
continue;
// Make sure that the current node read is an element
// Currently we expect the Default and Override Tag at Depth 1
if (reader.NodeType == XmlNodeType.Element
&& reader.Depth == 1
&& (String.CompareOrdinal(reader.NamespaceURI, s_typesNamespaceUri) == 0)
&& (String.CompareOrdinal(reader.Name, s_defaultTagName) == 0))
{
ProcessDefaultTagAttributes(reader);
}
else
if (reader.NodeType == XmlNodeType.Element
&& reader.Depth == 1
&& (String.CompareOrdinal(reader.NamespaceURI, s_typesNamespaceUri) == 0)
&& (String.CompareOrdinal(reader.Name, s_overrideTagName) == 0))
{
ProcessOverrideTagAttributes(reader);
}
else
if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == 0 && String.CompareOrdinal(reader.Name, s_typesTagName) == 0)
continue;
else
{
throw new XmlException(SR.TypesXmlDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
}
}
else
{
throw new XmlException(SR.TypesElementExpected, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
}
}
/// <summary>
/// Find the content type stream, allowing for interleaving. Naming collisions
/// (as between an atomic and an interleaved part) will result in an exception being thrown.
/// Return null if no content type stream has been found.
/// </summary>
/// <remarks>
/// The input array is lexicographically sorted
/// </remarks>
private Stream OpenContentTypeStream(System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipFiles)
{
foreach (ZipArchiveEntry zipFileInfo in zipFiles)
{
if (zipFileInfo.Name.ToUpperInvariant().StartsWith(s_contentTypesFileUpperInvariant, StringComparison.Ordinal))
{
// Atomic name.
if (zipFileInfo.Name.Length == ContentTypeFileName.Length)
{
// Record the file info.
_contentTypeZipArchiveEntry = zipFileInfo;
}
}
}
// If an atomic file was found, open a stream on it.
if (_contentTypeZipArchiveEntry != null)
{
_contentTypeStreamExists = true;
return _zipStreamManager.Open(_contentTypeZipArchiveEntry, _packageFileMode, FileAccess.ReadWrite);
}
// No content type stream was found.
return null;
}
// Process the attributes for the Default tag
private void ProcessDefaultTagAttributes(XmlReader reader)
{
#region Default Tag
//There could be a namespace Attribute present at this level.
//Also any other attribute on the <Default> tag is an error including xml: and xsi: attributes
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) != 2)
throw new XmlException(SR.DefaultTagDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
// get the required Extension and ContentType attributes
string extensionAttributeValue = reader.GetAttribute(s_extensionAttributeName);
ValidateXmlAttribute(s_extensionAttributeName, extensionAttributeValue, s_defaultTagName, reader);
string contentTypeAttributeValue = reader.GetAttribute(s_contentTypeAttributeName);
ThrowIfXmlAttributeMissing(s_contentTypeAttributeName, contentTypeAttributeValue, s_defaultTagName, reader);
// The extensions are stored in the Default Dictionary in their original form , but they are compared
// in a normalized manner using the ExtensionComparer.
PackUriHelper.ValidatedPartUri temporaryUri = PackUriHelper.ValidatePartUri(
new Uri(s_temporaryPartNameWithoutExtension + extensionAttributeValue, UriKind.Relative));
_defaultDictionary.Add(temporaryUri.PartUriExtension, new ContentType(contentTypeAttributeValue));
//Skip the EndElement for Default Tag
if (!reader.IsEmptyElement)
ProcessEndElement(reader, s_defaultTagName);
#endregion Default Tag
}
// Process the attributes for the Default tag
private void ProcessOverrideTagAttributes(XmlReader reader)
{
#region Override Tag
//There could be a namespace Attribute present at this level.
//Also any other attribute on the <Override> tag is an error including xml: and xsi: attributes
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) != 2)
throw new XmlException(SR.OverrideTagDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
// get the required Extension and ContentType attributes
string partNameAttributeValue = reader.GetAttribute(s_partNameAttributeName);
ValidateXmlAttribute(s_partNameAttributeName, partNameAttributeValue, s_overrideTagName, reader);
string contentTypeAttributeValue = reader.GetAttribute(s_contentTypeAttributeName);
ThrowIfXmlAttributeMissing(s_contentTypeAttributeName, contentTypeAttributeValue, s_overrideTagName, reader);
PackUriHelper.ValidatedPartUri partUri = PackUriHelper.ValidatePartUri(new Uri(partNameAttributeValue, UriKind.Relative));
//Lazy initializing - ensure that the override dictionary has been initialized
EnsureOverrideDictionary();
// The part Uris are stored in the Override Dictionary in their original form , but they are compared
// in a normalized manner using PartUriComparer.
_overrideDictionary.Add(partUri, new ContentType(contentTypeAttributeValue));
//Skip the EndElement for Override Tag
if (!reader.IsEmptyElement)
ProcessEndElement(reader, s_overrideTagName);
#endregion Override Tag
}
//If End element is present for Relationship then we process it
private void ProcessEndElement(XmlReader reader, string elementName)
{
Debug.Assert(!reader.IsEmptyElement, "This method should only be called it the Relationship Element is not empty");
reader.Read();
//Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
reader.MoveToContent();
if (reader.NodeType == XmlNodeType.EndElement && String.CompareOrdinal(elementName, reader.LocalName) == 0)
return;
else
throw new XmlException(SR.Format(SR.ElementIsNotEmptyElement, elementName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
private void AddOverrideElement(PackUriHelper.ValidatedPartUri partUri, ContentType contentType)
{
//Delete any entry corresponding in the Override dictionary
//corresponding to the PartUri for which the contentType is being added.
//This is to compensate for dead override entries in the content types file.
DeleteContentType(partUri);
//Lazy initializing - ensure that the override dictionary has been initialized
EnsureOverrideDictionary();
// The part Uris are stored in the Override Dictionary in their original form , but they are compared
// in a normalized manner using PartUriComparer.
_overrideDictionary.Add(partUri, contentType);
_dirty = true;
}
private void AddDefaultElement(string extension, ContentType contentType)
{
// The extensions are stored in the Default Dictionary in their original form , but they are compared
// in a normalized manner using the ExtensionComparer.
_defaultDictionary.Add(extension, contentType);
_dirty = true;
}
private void WriteOverrideElement(XmlWriter xmlWriter, PackUriHelper.ValidatedPartUri partUri, ContentType contentType)
{
xmlWriter.WriteStartElement(s_overrideTagName);
xmlWriter.WriteAttributeString(s_partNameAttributeName,
partUri.PartUriString);
xmlWriter.WriteAttributeString(s_contentTypeAttributeName, contentType.ToString());
xmlWriter.WriteEndElement();
}
private void WriteDefaultElement(XmlWriter xmlWriter, string extension, ContentType contentType)
{
xmlWriter.WriteStartElement(s_defaultTagName);
xmlWriter.WriteAttributeString(s_extensionAttributeName, extension);
xmlWriter.WriteAttributeString(s_contentTypeAttributeName, contentType.ToString());
xmlWriter.WriteEndElement();
}
//Validate if the required XML attribute is present and not an empty string
private void ValidateXmlAttribute(string attributeName, string attributeValue, string tagName, XmlReader reader)
{
ThrowIfXmlAttributeMissing(attributeName, attributeValue, tagName, reader);
//Checking for empty attribute
if (attributeValue == String.Empty)
throw new XmlException(SR.Format(SR.RequiredAttributeEmpty, tagName, attributeName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
//Validate if the required Content type XML attribute is present
//Content type of a part can be empty
private void ThrowIfXmlAttributeMissing(string attributeName, string attributeValue, string tagName, XmlReader reader)
{
if (attributeValue == null)
throw new XmlException(SR.Format(SR.RequiredAttributeMissing, tagName, attributeName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
#endregion Private Methods
#region Member Variables
private Dictionary<PackUriHelper.ValidatedPartUri, ContentType> _overrideDictionary;
private Dictionary<string, ContentType> _defaultDictionary;
private ZipArchive _zipArchive;
private FileMode _packageFileMode;
private FileAccess _packageFileAccess;
private ZipStreamManager _zipStreamManager;
private ZipArchiveEntry _contentTypeZipArchiveEntry;
private bool _contentTypeStreamExists;
private bool _dirty;
private CompressionLevel _cachedCompressionLevel;
private static readonly string s_contentTypesFile = "[Content_Types].xml";
private static readonly string s_contentTypesFileUpperInvariant = "[CONTENT_TYPES].XML";
private static readonly int s_defaultDictionaryInitialSize = 16;
private static readonly int s_overrideDictionaryInitialSize = 8;
//Xml tag specific strings for the Content Type file
private static readonly string s_typesNamespaceUri = "http://schemas.openxmlformats.org/package/2006/content-types";
private static readonly string s_typesTagName = "Types";
private static readonly string s_defaultTagName = "Default";
private static readonly string s_extensionAttributeName = "Extension";
private static readonly string s_contentTypeAttributeName = "ContentType";
private static readonly string s_overrideTagName = "Override";
private static readonly string s_partNameAttributeName = "PartName";
private static readonly string s_temporaryPartNameWithoutExtension = "/tempfiles/sample.";
#endregion Member Variables
}
#endregion ContentTypeHelper Class
#endregion Private Class
}
}
| |
/*
* 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;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenSim.Framework;
using OpenMetaverse.StructuredData;
namespace OpenSim.Framework.Monitoring
{
/// <summary>
/// Static class used to register/deregister/fetch statistics
/// </summary>
public static class StatsManager
{
// Subcommand used to list other stats.
public const string AllSubCommand = "all";
// Subcommand used to list other stats.
public const string ListSubCommand = "list";
// All subcommands
public static HashSet<string> SubCommands = new HashSet<string> { AllSubCommand, ListSubCommand };
/// <summary>
/// Registered stats categorized by category/container/shortname
/// </summary>
/// <remarks>
/// Do not add or remove directly from this dictionary.
/// </remarks>
public static SortedDictionary<string, SortedDictionary<string, SortedDictionary<string, Stat>>> RegisteredStats
= new SortedDictionary<string, SortedDictionary<string, SortedDictionary<string, Stat>>>();
// private static AssetStatsCollector assetStats;
// private static UserStatsCollector userStats;
// private static SimExtraStatsCollector simExtraStats = new SimExtraStatsCollector();
// public static AssetStatsCollector AssetStats { get { return assetStats; } }
// public static UserStatsCollector UserStats { get { return userStats; } }
public static SimExtraStatsCollector SimExtraStats { get; set; }
public static void RegisterConsoleCommands(ICommandConsole console)
{
console.Commands.AddCommand(
"General",
false,
"show stats",
"show stats [list|all|(<category>[.<container>])+",
"Show statistical information for this server",
"If no final argument is specified then legacy statistics information is currently shown.\n"
+ "'list' argument will show statistic categories.\n"
+ "'all' will show all statistics.\n"
+ "A <category> name will show statistics from that category.\n"
+ "A <category>.<container> name will show statistics from that category in that container.\n"
+ "More than one name can be given separated by spaces.\n"
+ "THIS STATS FACILITY IS EXPERIMENTAL AND DOES NOT YET CONTAIN ALL STATS",
HandleShowStatsCommand);
StatsLogger.RegisterConsoleCommands(console);
}
public static void HandleShowStatsCommand(string module, string[] cmd)
{
ICommandConsole con = MainConsole.Instance;
if (cmd.Length > 2)
{
foreach (string name in cmd.Skip(2))
{
string[] components = name.Split('.');
string categoryName = components[0];
string containerName = components.Length > 1 ? components[1] : null;
if (categoryName == AllSubCommand)
{
OutputAllStatsToConsole(con);
}
else if (categoryName == ListSubCommand)
{
con.Output("Statistic categories available are:");
foreach (string category in RegisteredStats.Keys)
con.OutputFormat(" {0}", category);
}
else
{
SortedDictionary<string, SortedDictionary<string, Stat>> category;
if (!RegisteredStats.TryGetValue(categoryName, out category))
{
con.OutputFormat("No such category as {0}", categoryName);
}
else
{
if (String.IsNullOrEmpty(containerName))
{
OutputCategoryStatsToConsole(con, category);
}
else
{
SortedDictionary<string, Stat> container;
if (category.TryGetValue(containerName, out container))
{
OutputContainerStatsToConsole(con, container);
}
else
{
con.OutputFormat("No such container {0} in category {1}", containerName, categoryName);
}
}
}
}
}
}
else
{
// Legacy
if (SimExtraStats != null)
con.Output(SimExtraStats.Report());
else
OutputAllStatsToConsole(con);
}
}
public static List<string> GetAllStatsReports()
{
List<string> reports = new List<string>();
foreach (var category in RegisteredStats.Values)
reports.AddRange(GetCategoryStatsReports(category));
return reports;
}
private static void OutputAllStatsToConsole(ICommandConsole con)
{
foreach (string report in GetAllStatsReports())
con.Output(report);
}
private static List<string> GetCategoryStatsReports(
SortedDictionary<string, SortedDictionary<string, Stat>> category)
{
List<string> reports = new List<string>();
foreach (var container in category.Values)
reports.AddRange(GetContainerStatsReports(container));
return reports;
}
private static void OutputCategoryStatsToConsole(
ICommandConsole con, SortedDictionary<string, SortedDictionary<string, Stat>> category)
{
foreach (string report in GetCategoryStatsReports(category))
con.Output(report);
}
private static List<string> GetContainerStatsReports(SortedDictionary<string, Stat> container)
{
List<string> reports = new List<string>();
foreach (Stat stat in container.Values)
reports.Add(stat.ToConsoleString());
return reports;
}
private static void OutputContainerStatsToConsole(
ICommandConsole con, SortedDictionary<string, Stat> container)
{
foreach (string report in GetContainerStatsReports(container))
con.Output(report);
}
// Creates an OSDMap of the format:
// { categoryName: {
// containerName: {
// statName: {
// "Name": name,
// "ShortName": shortName,
// ...
// },
// statName: {
// "Name": name,
// "ShortName": shortName,
// ...
// },
// ...
// },
// containerName: {
// ...
// },
// ...
// },
// categoryName: {
// ...
// },
// ...
// }
// The passed in parameters will filter the categories, containers and stats returned. If any of the
// parameters are either EmptyOrNull or the AllSubCommand value, all of that type will be returned.
// Case matters.
public static OSDMap GetStatsAsOSDMap(string pCategoryName, string pContainerName, string pStatName)
{
OSDMap map = new OSDMap();
foreach (string catName in RegisteredStats.Keys)
{
// Do this category if null spec, "all" subcommand or category name matches passed parameter.
// Skip category if none of the above.
if (!(String.IsNullOrEmpty(pCategoryName) || pCategoryName == AllSubCommand || pCategoryName == catName))
continue;
OSDMap contMap = new OSDMap();
foreach (string contName in RegisteredStats[catName].Keys)
{
if (!(string.IsNullOrEmpty(pContainerName) || pContainerName == AllSubCommand || pContainerName == contName))
continue;
OSDMap statMap = new OSDMap();
SortedDictionary<string, Stat> theStats = RegisteredStats[catName][contName];
foreach (string statName in theStats.Keys)
{
if (!(String.IsNullOrEmpty(pStatName) || pStatName == AllSubCommand || pStatName == statName))
continue;
statMap.Add(statName, theStats[statName].ToOSDMap());
}
contMap.Add(contName, statMap);
}
map.Add(catName, contMap);
}
return map;
}
public static Hashtable HandleStatsRequest(Hashtable request)
{
Hashtable responsedata = new Hashtable();
// string regpath = request["uri"].ToString();
int response_code = 200;
string contenttype = "text/json";
string pCategoryName = StatsManager.AllSubCommand;
string pContainerName = StatsManager.AllSubCommand;
string pStatName = StatsManager.AllSubCommand;
if (request.ContainsKey("cat")) pCategoryName = request["cat"].ToString();
if (request.ContainsKey("cont")) pContainerName = request["cat"].ToString();
if (request.ContainsKey("stat")) pStatName = request["cat"].ToString();
string strOut = StatsManager.GetStatsAsOSDMap(pCategoryName, pContainerName, pStatName).ToString();
// If requestor wants it as a callback function, build response as a function rather than just the JSON string.
if (request.ContainsKey("callback"))
{
strOut = request["callback"].ToString() + "(" + strOut + ");";
}
// m_log.DebugFormat("{0} StatFetch: uri={1}, cat={2}, cont={3}, stat={4}, resp={5}",
// LogHeader, regpath, pCategoryName, pContainerName, pStatName, strOut);
responsedata["int_response_code"] = response_code;
responsedata["content_type"] = contenttype;
responsedata["keepalive"] = false;
responsedata["str_response_string"] = strOut;
responsedata["access_control_allow_origin"] = "*";
return responsedata;
}
// /// <summary>
// /// Start collecting statistics related to assets.
// /// Should only be called once.
// /// </summary>
// public static AssetStatsCollector StartCollectingAssetStats()
// {
// assetStats = new AssetStatsCollector();
//
// return assetStats;
// }
//
// /// <summary>
// /// Start collecting statistics related to users.
// /// Should only be called once.
// /// </summary>
// public static UserStatsCollector StartCollectingUserStats()
// {
// userStats = new UserStatsCollector();
//
// return userStats;
// }
/// <summary>
/// Register a statistic.
/// </summary>
/// <param name='stat'></param>
/// <returns></returns>
public static bool RegisterStat(Stat stat)
{
SortedDictionary<string, SortedDictionary<string, Stat>> category = null, newCategory;
SortedDictionary<string, Stat> container = null, newContainer;
lock (RegisteredStats)
{
// Stat name is not unique across category/container/shortname key.
// XXX: For now just return false. This is to avoid problems in regression tests where all tests
// in a class are run in the same instance of the VM.
if (TryGetStatParents(stat, out category, out container))
return false;
// We take a copy-on-write approach here of replacing dictionaries when keys are added or removed.
// This means that we don't need to lock or copy them on iteration, which will be a much more
// common operation after startup.
if (container != null)
newContainer = new SortedDictionary<string, Stat>(container);
else
newContainer = new SortedDictionary<string, Stat>();
if (category != null)
newCategory = new SortedDictionary<string, SortedDictionary<string, Stat>>(category);
else
newCategory = new SortedDictionary<string, SortedDictionary<string, Stat>>();
newContainer[stat.ShortName] = stat;
newCategory[stat.Container] = newContainer;
RegisteredStats[stat.Category] = newCategory;
}
return true;
}
/// <summary>
/// Deregister a statistic
/// </summary>>
/// <param name='stat'></param>
/// <returns></returns>
public static bool DeregisterStat(Stat stat)
{
SortedDictionary<string, SortedDictionary<string, Stat>> category = null, newCategory;
SortedDictionary<string, Stat> container = null, newContainer;
lock (RegisteredStats)
{
if (!TryGetStatParents(stat, out category, out container))
return false;
newContainer = new SortedDictionary<string, Stat>(container);
newContainer.Remove(stat.ShortName);
newCategory = new SortedDictionary<string, SortedDictionary<string, Stat>>(category);
newCategory.Remove(stat.Container);
newCategory[stat.Container] = newContainer;
RegisteredStats[stat.Category] = newCategory;
return true;
}
}
public static bool TryGetStat(string category, string container, string statShortName, out Stat stat)
{
stat = null;
SortedDictionary<string, SortedDictionary<string, Stat>> categoryStats;
lock (RegisteredStats)
{
if (!TryGetStatsForCategory(category, out categoryStats))
return false;
SortedDictionary<string, Stat> containerStats;
if (!categoryStats.TryGetValue(container, out containerStats))
return false;
return containerStats.TryGetValue(statShortName, out stat);
}
}
public static bool TryGetStatsForCategory(
string category, out SortedDictionary<string, SortedDictionary<string, Stat>> stats)
{
lock (RegisteredStats)
return RegisteredStats.TryGetValue(category, out stats);
}
/// <summary>
/// Get the same stat for each container in a given category.
/// </summary>
/// <returns>
/// The stats if there were any to fetch. Otherwise null.
/// </returns>
/// <param name='category'></param>
/// <param name='statShortName'></param>
public static List<Stat> GetStatsFromEachContainer(string category, string statShortName)
{
SortedDictionary<string, SortedDictionary<string, Stat>> categoryStats;
lock (RegisteredStats)
{
if (!RegisteredStats.TryGetValue(category, out categoryStats))
return null;
List<Stat> stats = null;
foreach (SortedDictionary<string, Stat> containerStats in categoryStats.Values)
{
if (containerStats.ContainsKey(statShortName))
{
if (stats == null)
stats = new List<Stat>();
stats.Add(containerStats[statShortName]);
}
}
return stats;
}
}
public static bool TryGetStatParents(
Stat stat,
out SortedDictionary<string, SortedDictionary<string, Stat>> category,
out SortedDictionary<string, Stat> container)
{
category = null;
container = null;
lock (RegisteredStats)
{
if (RegisteredStats.TryGetValue(stat.Category, out category))
{
if (category.TryGetValue(stat.Container, out container))
{
if (container.ContainsKey(stat.ShortName))
return true;
}
}
}
return false;
}
public static void RecordStats()
{
lock (RegisteredStats)
{
foreach (SortedDictionary<string, SortedDictionary<string, Stat>> category in RegisteredStats.Values)
{
foreach (SortedDictionary<string, Stat> container in category.Values)
{
foreach (Stat stat in container.Values)
{
if (stat.MeasuresOfInterest != MeasuresOfInterest.None)
stat.RecordValue();
}
}
}
}
}
}
/// <summary>
/// Stat type.
/// </summary>
/// <remarks>
/// A push stat is one which is continually updated and so it's value can simply by read.
/// A pull stat is one where reading the value triggers a collection method - the stat is not continually updated.
/// </remarks>
public enum StatType
{
Push,
Pull
}
/// <summary>
/// Measures of interest for this stat.
/// </summary>
[Flags]
public enum MeasuresOfInterest
{
None,
AverageChangeOverTime
}
/// <summary>
/// Verbosity of stat.
/// </summary>
/// <remarks>
/// Info will always be displayed.
/// </remarks>
public enum StatVerbosity
{
Debug,
Info
}
}
| |
namespace SportsManager.Migrations
{
using Models;
using System;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<SportsManager.Models.SportsContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
ContextKey = "SportsManager.Models.SportsContext";
}
protected override void Seed(SportsManager.Models.SportsContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
var games = new List<Game>
{
new Game {gameCode="CYCL123", gameName="Cycling", gameDescription="Some nonsense", gameDurationInMins=60, gameBookletPath="/Upload/Rules/Doc1.pdf"},
new Game {gameCode="RUNN123", gameName="Running", gameDescription="Some other nonsense", gameDurationInMins=18, gameBookletPath="/Upload/Rules/Doc2.pdf"},
new Game {gameCode="SWIM123", gameName="Swimming", gameDescription="Some minor nonsense", gameDurationInMins=25, gameBookletPath="/Upload/Rules/Doc3.pdf"},
new Game {gameCode="JUMP123", gameName="High Jump", gameDescription="Some arbitrary nonsense", gameDurationInMins=30, gameBookletPath="/Upload/Rules/Doc4.pdf"},
};
games.ForEach(g => context.Games.AddOrUpdate(p => p.gameCode, g));
context.SaveChanges();
var competitors = new List<Competitor>
{
new Competitor {competitorSalutation="Mrs",competitorName="Ramona Smith",
competitorDoB =DateTime.Parse("1978/06/10"), competitorEmail ="[email protected]",
competitorCountry ="Canada", competitorDescription ="More silly nonsense",
competitorGender ="Female", competitorPhone ="+14031231234",
competitorWebsite = "http://somesite.com", competitorPhotoPath ="/Upload/Photos/face2.jpg"},
new Competitor {competitorSalutation="Mr",competitorName="Stephen Robertson",
competitorDoB =DateTime.Parse("1984/07/12"), competitorEmail="[email protected]",
competitorCountry ="United States", competitorDescription="More nilly sonsense",
competitorGender ="Male", competitorPhone="+12021231234",
competitorWebsite = "http://somesite.com", competitorPhotoPath="/Upload/Photos/face1.jpg"},
new Competitor {competitorSalutation="Mr",competitorName="Rob Johnson",
competitorDoB =DateTime.Parse("1988/01/12"), competitorEmail="[email protected]",
competitorCountry ="Australia", competitorDescription="A bit less silly nonsense",
competitorGender ="Male", competitorPhone="+61409876123",
competitorWebsite = "http://someothersite.com", competitorPhotoPath="/Upload/Photos/face3.jpg"},
new Competitor {competitorSalutation="Mr",competitorName="Job Rohnson",
competitorDoB =DateTime.Parse("1910/04/20"), competitorEmail="[email protected]",
competitorCountry ="United Kingdom", competitorDescription="A bit more silly nonsense",
competitorGender ="Male", competitorPhone="+444098761231",
competitorWebsite = "http://someothersiteagain.com", competitorPhotoPath="/Upload/Photos/face4.jpg"},
new Competitor {competitorSalutation="Miss",competitorName="Donald Trump",
competitorDoB =DateTime.Parse("1985/10/16"), competitorEmail="[email protected]",
competitorCountry ="United States", competitorDescription="A LOT silly nonsense",
competitorGender ="Female", competitorPhone="+15559876123",
competitorWebsite = "http://likeseriously.com", competitorPhotoPath="/Upload/Photos/face7.jpg"},
new Competitor {competitorSalutation="Mr",competitorName="John Smithington",
competitorDoB =DateTime.Parse("1966/11/02"), competitorEmail="[email protected]",
competitorCountry ="Australia", competitorDescription="A jolly bit of silly nonsense",
competitorGender ="Male", competitorPhone="+61409666111",
competitorWebsite = "http://abcdefgh.com", competitorPhotoPath="/Upload/Photos/face5.jpg"},
new Competitor {competitorSalutation="Mr",competitorName="Okidoki MrPokey",
competitorDoB =DateTime.Parse("1977/11/02"), competitorEmail="[email protected]",
competitorCountry ="China", competitorDescription="Something about nonsense here",
competitorGender ="Male", competitorPhone="+862087655678",
competitorWebsite = "http://ALLTHEWEBSITES.com", competitorPhotoPath="/Upload/Photos/face6.jpg"},
new Competitor {competitorSalutation="Miss",competitorName="Ohme Gawd",
competitorDoB =DateTime.Parse("1992/08/01"), competitorEmail="[email protected]",
competitorCountry ="China", competitorDescription="More of the same really",
competitorGender ="Female", competitorPhone="+862012340987",
competitorWebsite = "http://anotherwebsite.com", competitorPhotoPath="/Upload/Photos/face8.jpg"},
new Competitor {competitorSalutation="Dr",competitorName="Whats Hisface",
competitorDoB =DateTime.Parse("1924/03/06"), competitorEmail ="[email protected]",
competitorCountry ="Canada", competitorDescription ="Something something nonsense",
competitorGender ="Male", competitorPhone ="+14034321567",
competitorWebsite = "http://morewebsites.com", competitorPhotoPath ="/Upload/Photos/face9.jpg"},
new Competitor {competitorSalutation="Dr",competitorName="Whats Hisface",
competitorDoB =DateTime.Parse("1924/03/06"), competitorEmail ="[email protected]",
competitorCountry ="Canada", competitorDescription ="Something something nonsense",
competitorGender ="Male", competitorPhone ="+14034321567",
competitorWebsite = "http://morewebsites.com", competitorPhotoPath ="/Upload/Photos/face10.jpg"}
};
List<Game> gamesList = context.Games.ToList();
competitors[0].Games.Add(gamesList[0]); competitors[0].Games.Add(gamesList[1]); competitors[0].Games.Add(gamesList[2]);
competitors[1].Games.Add(gamesList[0]); competitors[1].Games.Add(gamesList[1]); competitors[1].Games.Add(gamesList[2]);
competitors[2].Games.Add(gamesList[0]); competitors[2].Games.Add(gamesList[1]); competitors[2].Games.Add(gamesList[2]);
competitors[3].Games.Add(gamesList[0]); competitors[3].Games.Add(gamesList[1]); competitors[3].Games.Add(gamesList[2]);
competitors[4].Games.Add(gamesList[0]); competitors[4].Games.Add(gamesList[1]); competitors[4].Games.Add(gamesList[2]);
competitors[5].Games.Add(gamesList[0]); competitors[5].Games.Add(gamesList[1]); competitors[5].Games.Add(gamesList[2]);
competitors[6].Games.Add(gamesList[0]); competitors[6].Games.Add(gamesList[1]); competitors[6].Games.Add(gamesList[2]);
competitors[7].Games.Add(gamesList[0]); competitors[7].Games.Add(gamesList[1]); competitors[7].Games.Add(gamesList[2]);
competitors[8].Games.Add(gamesList[0]); competitors[8].Games.Add(gamesList[1]); competitors[8].Games.Add(gamesList[2]);
competitors[9].Games.Add(gamesList[0]); competitors[9].Games.Add(gamesList[1]); competitors[9].Games.Add(gamesList[2]);
competitors.ForEach(c => context.Competitors.AddOrUpdate(p => p.competitorName, c));
context.SaveChanges();
var tags = new List<Tag>()
{
new Tag {tagString="cycling"},
new Tag {tagString="swimming"},
new Tag {tagString="running"},
new Tag {tagString="gold"},
new Tag {tagString="world record"}
};
tags.ForEach(t => context.Tags.Add(t));
context.SaveChanges();
List<Tag> tagList = context.Tags.ToList();
var photos = new List<Photo>()
{
new Photo {photoPath="/Upload/Photos/event1.png"},
new Photo {photoPath="/Upload/Photos/event2.png"},
new Photo {photoPath="/Upload/Photos/event3.png"},
new Photo {photoPath="/Upload/Photos/event4.png"},
new Photo {photoPath="/Upload/Photos/event5.png"}
};
photos[0].Tags.Add(tagList[0]); photos[0].Tags.Add(tagList[3]);
photos[1].Tags.Add(tagList[0]); photos[2].Tags.Add(tagList[1]);
photos[2].Tags.Add(tagList[4]); photos[3].Tags.Add(tagList[1]);
photos[4].Tags.Add(tagList[2]); photos[4].Tags.Add(tagList[3]);
var events = new List<Event>()
{
new Event {gameID = 1, featureEvent=true,
eventVenue ="ECU", eventDate=DateTime.Parse("2016/10/12"),
eventStartTime =DateTime.Parse("18:00"), eventEndTime =DateTime.Parse("19:00"),
eventDescription="A cycling event", worldRecord=false},
new Event {gameID = 2, featureEvent=false,
eventVenue ="ECU", eventDate=DateTime.Parse("2016/10/12"),
eventStartTime =DateTime.Parse("18:00"), eventEndTime =DateTime.Parse("19:00"),
eventDescription="A cycling event", worldRecord=true},
new Event {gameID = 3, featureEvent=false,
eventVenue ="ECU", eventDate=DateTime.Parse("2016/08/01"),
eventStartTime =DateTime.Parse("08:00"), eventEndTime =DateTime.Parse("08:25"),
eventDescription="A swimming event", worldRecord=true}
};
events[0].Photos.Add(photos[0]); events[0].Photos.Add(photos[1]);
events[1].Photos.Add(photos[2]); events[1].Photos.Add(photos[3]);
events[2].Photos.Add(photos[4]);
events.ForEach(e => context.Events.Add(e));
context.SaveChanges();
var eventCompetitors = new List<EventCompetitor>()
{
new EventCompetitor {competitorPosition=1, competitorMedal="Gold"}, // Event 1
new EventCompetitor {competitorPosition=2, competitorMedal="Silver"}, // Event 1
new EventCompetitor {competitorPosition=3, competitorMedal="Bronze"}, // Event 1
new EventCompetitor {competitorPosition=4, competitorMedal="None"}, // Event 1
new EventCompetitor {competitorPosition=5, competitorMedal="None"}, // Event 1
new EventCompetitor {competitorPosition=6, competitorMedal="None"}, // Event 1
new EventCompetitor {competitorPosition=1, competitorMedal="Gold"}, // Event 2
new EventCompetitor {competitorPosition=2, competitorMedal="Silver"}, // Event 2
new EventCompetitor {competitorPosition=3, competitorMedal="Bronze"}, // Event 2
new EventCompetitor {competitorPosition=4, competitorMedal="None"}, // Event 2
new EventCompetitor {competitorPosition=5, competitorMedal="None"}, // Event 2
new EventCompetitor {competitorPosition=6, competitorMedal="None"}, // Event 2
new EventCompetitor {competitorPosition=1, competitorMedal="Gold"}, // Event 3
new EventCompetitor {competitorPosition=2, competitorMedal="Silver"}, // Event 3
new EventCompetitor {competitorPosition=3, competitorMedal="Bronze"}, // Event 3
new EventCompetitor {competitorPosition=4, competitorMedal="None"}, // Event 3
new EventCompetitor {competitorPosition=5, competitorMedal="None"}, // Event 3
new EventCompetitor {competitorPosition=6, competitorMedal="None"} // Event 3
};
List<Event> eventList = context.Events.ToList();
eventCompetitors[0].Event = eventList[0];
eventCompetitors[1].Event = eventList[0];
eventCompetitors[2].Event = eventList[0];
eventCompetitors[3].Event = eventList[0];
eventCompetitors[4].Event = eventList[0];
eventCompetitors[5].Event = eventList[0];
eventCompetitors[6].Event = eventList[1];
eventCompetitors[7].Event = eventList[1];
eventCompetitors[8].Event = eventList[1];
eventCompetitors[9].Event = eventList[1];
eventCompetitors[10].Event = eventList[1];
eventCompetitors[11].Event = eventList[1];
eventCompetitors[12].Event = eventList[2];
eventCompetitors[13].Event = eventList[2];
eventCompetitors[14].Event = eventList[2];
eventCompetitors[15].Event = eventList[2];
eventCompetitors[16].Event = eventList[2];
eventCompetitors[17].Event = eventList[2];
List<Competitor> competitorList = context.Competitors.ToList();
eventCompetitors[0].Competitor = competitorList[0];
eventCompetitors[1].Competitor = competitorList[2];
eventCompetitors[2].Competitor = competitorList[4];
eventCompetitors[3].Competitor = competitorList[5];
eventCompetitors[4].Competitor = competitorList[7];
eventCompetitors[5].Competitor = competitorList[9];
eventCompetitors[6].Competitor = competitorList[1];
eventCompetitors[7].Competitor = competitorList[3];
eventCompetitors[8].Competitor = competitorList[5];
eventCompetitors[9].Competitor = competitorList[6];
eventCompetitors[10].Competitor = competitorList[8];
eventCompetitors[11].Competitor = competitorList[9];
eventCompetitors[12].Competitor = competitorList[0];
eventCompetitors[13].Competitor = competitorList[2];
eventCompetitors[14].Competitor = competitorList[3];
eventCompetitors[15].Competitor = competitorList[6];
eventCompetitors[16].Competitor = competitorList[7];
eventCompetitors[17].Competitor = competitorList[8];
eventCompetitors.ForEach(ec => context.EventCompetitors.Add(ec));
context.SaveChanges();
}
}
}
| |
// 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.Contracts;
namespace System.Globalization
{
////////////////////////////////////////////////////////////////////////////
//
// Rules for the Hijri calendar:
// - The Hijri calendar is a strictly Lunar calendar.
// - Days begin at sunset.
// - Islamic Year 1 (Muharram 1, 1 A.H.) is equivalent to absolute date
// 227015 (Friday, July 16, 622 C.E. - Julian).
// - Leap Years occur in the 2, 5, 7, 10, 13, 16, 18, 21, 24, 26, & 29th
// years of a 30-year cycle. Year = leap iff ((11y+14) mod 30 < 11).
// - There are 12 months which contain alternately 30 and 29 days.
// - The 12th month, Dhu al-Hijjah, contains 30 days instead of 29 days
// in a leap year.
// - Common years have 354 days. Leap years have 355 days.
// - There are 10,631 days in a 30-year cycle.
// - The Islamic months are:
// 1. Muharram (30 days) 7. Rajab (30 days)
// 2. Safar (29 days) 8. Sha'ban (29 days)
// 3. Rabi I (30 days) 9. Ramadan (30 days)
// 4. Rabi II (29 days) 10. Shawwal (29 days)
// 5. Jumada I (30 days) 11. Dhu al-Qada (30 days)
// 6. Jumada II (29 days) 12. Dhu al-Hijjah (29 days) {30}
//
// NOTENOTE
// The calculation of the HijriCalendar is based on the absolute date. And the
// absolute date means the number of days from January 1st, 1 A.D.
// Therefore, we do not support the days before the January 1st, 1 A.D.
//
////////////////////////////////////////////////////////////////////////////
/*
** Calendar support range:
** Calendar Minimum Maximum
** ========== ========== ==========
** Gregorian 0622/07/18 9999/12/31
** Hijri 0001/01/01 9666/04/03
*/
public partial class HijriCalendar : Calendar
{
public static readonly int HijriEra = 1;
internal const int DatePartYear = 0;
internal const int DatePartDayOfYear = 1;
internal const int DatePartMonth = 2;
internal const int DatePartDay = 3;
internal const int MinAdvancedHijri = -2;
internal const int MaxAdvancedHijri = 2;
internal static readonly int[] HijriMonthDays = { 0, 30, 59, 89, 118, 148, 177, 207, 236, 266, 295, 325, 355 };
private int _hijriAdvance = Int32.MinValue;
// DateTime.MaxValue = Hijri calendar (year:9666, month: 4, day: 3).
internal const int MaxCalendarYear = 9666;
internal const int MaxCalendarMonth = 4;
internal const int MaxCalendarDay = 3;
// Hijri calendar (year: 1, month: 1, day:1 ) = Gregorian (year: 622, month: 7, day: 18)
// This is the minimal Gregorian date that we support in the HijriCalendar.
internal static readonly DateTime calendarMinValue = new DateTime(622, 7, 18);
internal static readonly DateTime calendarMaxValue = DateTime.MaxValue;
public override DateTime MinSupportedDateTime
{
get
{
return (calendarMinValue);
}
}
public override DateTime MaxSupportedDateTime
{
get
{
return (calendarMaxValue);
}
}
public override CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.LunarCalendar;
}
}
public HijriCalendar()
{
}
internal override CalendarId ID
{
get
{
return CalendarId.HIJRI;
}
}
protected override int DaysInYearBeforeMinSupportedYear
{
get
{
// the year before the 1st year of the cycle would have been the 30th year
// of the previous cycle which is not a leap year. Common years have 354 days.
return 354;
}
}
/*=================================GetAbsoluteDateHijri==========================
**Action: Gets the Absolute date for the given Hijri date. The absolute date means
** the number of days from January 1st, 1 A.D.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
private long GetAbsoluteDateHijri(int y, int m, int d)
{
return (long)(DaysUpToHijriYear(y) + HijriMonthDays[m - 1] + d - 1 - HijriAdjustment);
}
/*=================================DaysUpToHijriYear==========================
**Action: Gets the total number of days (absolute date) up to the given Hijri Year.
** The absolute date means the number of days from January 1st, 1 A.D.
**Returns: Gets the total number of days (absolute date) up to the given Hijri Year.
**Arguments: HijriYear year value in Hijri calendar.
**Exceptions: None
**Notes:
============================================================================*/
private long DaysUpToHijriYear(int HijriYear)
{
long NumDays; // number of absolute days
int NumYear30; // number of years up to current 30 year cycle
int NumYearsLeft; // number of years into 30 year cycle
//
// Compute the number of years up to the current 30 year cycle.
//
NumYear30 = ((HijriYear - 1) / 30) * 30;
//
// Compute the number of years left. This is the number of years
// into the 30 year cycle for the given year.
//
NumYearsLeft = HijriYear - NumYear30 - 1;
//
// Compute the number of absolute days up to the given year.
//
NumDays = ((NumYear30 * 10631L) / 30L) + 227013L;
while (NumYearsLeft > 0)
{
// Common year is 354 days, and leap year is 355 days.
NumDays += 354 + (IsLeapYear(NumYearsLeft, CurrentEra) ? 1 : 0);
NumYearsLeft--;
}
//
// Return the number of absolute days.
//
return (NumDays);
}
public int HijriAdjustment
{
get
{
if (_hijriAdvance == Int32.MinValue)
{
// Never been set before. Use the system value from registry.
_hijriAdvance = GetHijriDateAdjustment();
}
return (_hijriAdvance);
}
set
{
// NOTE: Check the value of Min/MaxAdvancedHijri with Arabic speakers to see if the assumption is good.
if (value < MinAdvancedHijri || value > MaxAdvancedHijri)
{
throw new ArgumentOutOfRangeException(
"HijriAdjustment",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Bounds_Lower_Upper,
MinAdvancedHijri,
MaxAdvancedHijri));
}
Contract.EndContractBlock();
VerifyWritable();
_hijriAdvance = value;
}
}
internal static void CheckTicksRange(long ticks)
{
if (ticks < calendarMinValue.Ticks || ticks > calendarMaxValue.Ticks)
{
throw new ArgumentOutOfRangeException(
"time",
String.Format(
CultureInfo.InvariantCulture,
SR.ArgumentOutOfRange_CalendarRange,
calendarMinValue,
calendarMaxValue));
}
}
internal static void CheckEraRange(int era)
{
if (era != CurrentEra && era != HijriEra)
{
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
}
internal static void CheckYearRange(int year, int era)
{
CheckEraRange(era);
if (year < 1 || year > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxCalendarYear));
}
}
internal static void CheckYearMonthRange(int year, int month, int era)
{
CheckYearRange(year, era);
if (year == MaxCalendarYear)
{
if (month > MaxCalendarMonth)
{
throw new ArgumentOutOfRangeException(
nameof(month),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxCalendarMonth));
}
}
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month);
}
}
/*=================================GetDatePart==========================
**Action: Returns a given date part of this <i>DateTime</i>. This method is used
** to compute the year, day-of-year, month, or day part.
**Returns:
**Arguments:
**Exceptions: ArgumentException if part is incorrect.
**Notes:
** First, we get the absolute date (the number of days from January 1st, 1 A.C) for the given ticks.
** Use the formula (((AbsoluteDate - 227013) * 30) / 10631) + 1, we can a rough value for the Hijri year.
** In order to get the exact Hijri year, we compare the exact absolute date for HijriYear and (HijriYear + 1).
** From here, we can get the correct Hijri year.
============================================================================*/
internal virtual int GetDatePart(long ticks, int part)
{
int HijriYear; // Hijri year
int HijriMonth; // Hijri month
int HijriDay; // Hijri day
long NumDays; // The calculation buffer in number of days.
CheckTicksRange(ticks);
//
// Get the absolute date. The absolute date is the number of days from January 1st, 1 A.D.
// 1/1/0001 is absolute date 1.
//
NumDays = ticks / GregorianCalendar.TicksPerDay + 1;
//
// See how much we need to backup or advance
//
NumDays += HijriAdjustment;
//
// Calculate the appromixate Hijri Year from this magic formula.
//
HijriYear = (int)(((NumDays - 227013) * 30) / 10631) + 1;
long daysToHijriYear = DaysUpToHijriYear(HijriYear); // The absolute date for HijriYear
long daysOfHijriYear = GetDaysInYear(HijriYear, CurrentEra); // The number of days for (HijriYear+1) year.
if (NumDays < daysToHijriYear)
{
daysToHijriYear -= daysOfHijriYear;
HijriYear--;
}
else if (NumDays == daysToHijriYear)
{
HijriYear--;
daysToHijriYear -= GetDaysInYear(HijriYear, CurrentEra);
}
else
{
if (NumDays > daysToHijriYear + daysOfHijriYear)
{
daysToHijriYear += daysOfHijriYear;
HijriYear++;
}
}
if (part == DatePartYear)
{
return (HijriYear);
}
//
// Calculate the Hijri Month.
//
HijriMonth = 1;
NumDays -= daysToHijriYear;
if (part == DatePartDayOfYear)
{
return ((int)NumDays);
}
while ((HijriMonth <= 12) && (NumDays > HijriMonthDays[HijriMonth - 1]))
{
HijriMonth++;
}
HijriMonth--;
if (part == DatePartMonth)
{
return (HijriMonth);
}
//
// Calculate the Hijri Day.
//
HijriDay = (int)(NumDays - HijriMonthDays[HijriMonth - 1]);
if (part == DatePartDay)
{
return (HijriDay);
}
// Incorrect part value.
throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing);
}
// Returns the DateTime resulting from adding the given number of
// months to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year and month parts of the specified DateTime by
// value months, and, if required, adjusting the day part of the
// resulting date downwards to the last day of the resulting month in the
// resulting year. The time-of-day part of the result is the same as the
// time-of-day part of the specified DateTime.
//
// In more precise terms, considering the specified DateTime to be of the
// form y / m / d + t, where y is the
// year, m is the month, d is the day, and t is the
// time-of-day, the result is y1 / m1 / d1 + t,
// where y1 and m1 are computed by adding value months
// to y and m, and d1 is the largest value less than
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
public override DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000)
{
throw new ArgumentOutOfRangeException(
nameof(months),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
-120000,
120000));
}
Contract.EndContractBlock();
// Get the date in Hijri calendar.
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
int i = m - 1 + months;
if (i >= 0)
{
m = i % 12 + 1;
y = y + i / 12;
}
else
{
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
int days = GetDaysInMonth(y, m);
if (d > days)
{
d = days;
}
long ticks = GetAbsoluteDateHijri(y, m, d) * TicksPerDay + (time.Ticks % TicksPerDay);
Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
// Returns the DateTime resulting from adding the given number of
// years to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year part of the specified DateTime by value
// years. If the month and day of the specified DateTime is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of the specified DateTime.
//
public override DateTime AddYears(DateTime time, int years)
{
return (AddMonths(time, years * 12));
}
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 31.
//
public override int GetDayOfMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDay));
}
// Returns the day-of-week part of the specified DateTime. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
}
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and 366.
//
public override int GetDayOfYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDayOfYear));
}
// Returns the number of days in the month given by the year and
// month arguments.
//
[Pure]
public override int GetDaysInMonth(int year, int month, int era)
{
CheckYearMonthRange(year, month, era);
if (month == 12)
{
// For the 12th month, leap year has 30 days, and common year has 29 days.
return (IsLeapYear(year, CurrentEra) ? 30 : 29);
}
// Other months contain 30 and 29 days alternatively. The 1st month has 30 days.
return (((month % 2) == 1) ? 30 : 29);
}
// Returns the number of days in the year given by the year argument for the current era.
//
public override int GetDaysInYear(int year, int era)
{
CheckYearRange(year, era);
// Common years have 354 days. Leap years have 355 days.
return (IsLeapYear(year, CurrentEra) ? 355 : 354);
}
// Returns the era for the specified DateTime value.
public override int GetEra(DateTime time)
{
CheckTicksRange(time.Ticks);
return (HijriEra);
}
public override int[] Eras
{
get
{
return (new int[] { HijriEra });
}
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 12.
//
public override int GetMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartMonth));
}
// Returns the number of months in the specified year and era.
public override int GetMonthsInYear(int year, int era)
{
CheckYearRange(year, era);
return (12);
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and MaxCalendarYear.
//
public override int GetYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartYear));
}
// Checks whether a given day in the specified era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public override bool IsLeapDay(int year, int month, int day, int era)
{
// The year/month/era value checking is done in GetDaysInMonth().
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException(
nameof(day),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Day,
daysInMonth,
month));
}
return (IsLeapYear(year, era) && month == 12 && day == 30);
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public override int GetLeapMonth(int year, int era)
{
CheckYearRange(year, era);
return (0);
}
// Checks whether a given month in the specified era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public override bool IsLeapMonth(int year, int month, int era)
{
CheckYearMonthRange(year, month, era);
return (false);
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public override bool IsLeapYear(int year, int era)
{
CheckYearRange(year, era);
return ((((year * 11) + 14) % 30) < 11);
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
// The year/month/era checking is done in GetDaysInMonth().
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException(
nameof(day),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Day,
daysInMonth,
month));
}
long lDate = GetAbsoluteDateHijri(year, month, day);
if (lDate >= 0)
{
return (new DateTime(lDate * GregorianCalendar.TicksPerDay + TimeToTicks(hour, minute, second, millisecond)));
}
else
{
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
}
}
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 1451;
public override int TwoDigitYearMax
{
get
{
if (twoDigitYearMax == -1)
{
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
set
{
VerifyWritable();
if (value < 99 || value > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
nameof(value),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
99,
MaxCalendarYear));
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
if (year < 100)
{
return (base.ToFourDigitYear(year));
}
if (year > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxCalendarYear));
}
return (year);
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email [email protected] or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// Summary description for ReportCtl.
/// </summary>
internal class ImageCtl : System.Windows.Forms.UserControl, IProperty
{
private List<XmlNode> _ReportItems;
private DesignXmlDraw _Draw;
bool fSource, fValue, fSizing, fMIMEType;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.RadioButton rbExternal;
private System.Windows.Forms.RadioButton rbDatabase;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ComboBox cbSizing;
private System.Windows.Forms.ComboBox cbValueEmbedded;
private System.Windows.Forms.ComboBox cbMIMEType;
private System.Windows.Forms.ComboBox cbValueDatabase;
private System.Windows.Forms.TextBox tbValueExternal;
private System.Windows.Forms.Button bExternal;
private System.Windows.Forms.RadioButton rbEmbedded;
private System.Windows.Forms.Button bEmbedded;
private System.Windows.Forms.Button bDatabaseExpr;
private System.Windows.Forms.Button bMimeExpr;
private System.Windows.Forms.Button bEmbeddedExpr;
private System.Windows.Forms.Button bExternalExpr;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal ImageCtl(DesignXmlDraw dxDraw, List<XmlNode> ris)
{
_ReportItems = ris;
_Draw = dxDraw;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues();
}
private void InitValues()
{
XmlNode iNode = _ReportItems[0];
// Populate the EmbeddedImage names
cbValueEmbedded.Items.AddRange(_Draw.ReportNames.EmbeddedImageNames);
string[] flds = _Draw.GetReportItemDataRegionFields(iNode, true);
if (flds != null)
this.cbValueDatabase.Items.AddRange(flds);
string source = _Draw.GetElementValue(iNode, "Source", "Embedded");
string val = _Draw.GetElementValue(iNode, "Value", "");
switch (source)
{
case "Embedded":
this.rbEmbedded.Checked = true;
this.cbValueEmbedded.Text = val;
break;
case "Database":
this.rbDatabase.Checked = true;
this.cbValueDatabase.Text = val;
this.cbMIMEType.Text = _Draw.GetElementValue(iNode, "MIMEType", "image/png");
break;
case "External":
default:
this.rbExternal.Checked = true;
this.tbValueExternal.Text = val;
break;
}
this.cbSizing.Text = _Draw.GetElementValue(iNode, "Sizing", "AutoSize");
fSource = fValue = fSizing = fMIMEType = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.bEmbedded = new System.Windows.Forms.Button();
this.bExternal = new System.Windows.Forms.Button();
this.tbValueExternal = new System.Windows.Forms.TextBox();
this.cbValueDatabase = new System.Windows.Forms.ComboBox();
this.cbMIMEType = new System.Windows.Forms.ComboBox();
this.cbValueEmbedded = new System.Windows.Forms.ComboBox();
this.rbDatabase = new System.Windows.Forms.RadioButton();
this.rbEmbedded = new System.Windows.Forms.RadioButton();
this.rbExternal = new System.Windows.Forms.RadioButton();
this.label1 = new System.Windows.Forms.Label();
this.cbSizing = new System.Windows.Forms.ComboBox();
this.bDatabaseExpr = new System.Windows.Forms.Button();
this.bMimeExpr = new System.Windows.Forms.Button();
this.bEmbeddedExpr = new System.Windows.Forms.Button();
this.bExternalExpr = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.bExternalExpr);
this.groupBox1.Controls.Add(this.bEmbeddedExpr);
this.groupBox1.Controls.Add(this.bMimeExpr);
this.groupBox1.Controls.Add(this.bDatabaseExpr);
this.groupBox1.Controls.Add(this.bEmbedded);
this.groupBox1.Controls.Add(this.bExternal);
this.groupBox1.Controls.Add(this.tbValueExternal);
this.groupBox1.Controls.Add(this.cbValueDatabase);
this.groupBox1.Controls.Add(this.cbMIMEType);
this.groupBox1.Controls.Add(this.cbValueEmbedded);
this.groupBox1.Controls.Add(this.rbDatabase);
this.groupBox1.Controls.Add(this.rbEmbedded);
this.groupBox1.Controls.Add(this.rbExternal);
this.groupBox1.Location = new System.Drawing.Point(16, 16);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(408, 152);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Source";
//
// bEmbedded
//
this.bEmbedded.Location = new System.Drawing.Point(378, 58);
this.bEmbedded.Name = "bEmbedded";
this.bEmbedded.Size = new System.Drawing.Size(22, 16);
this.bEmbedded.TabIndex = 8;
this.bEmbedded.Text = "...";
this.bEmbedded.Click += new System.EventHandler(this.bEmbedded_Click);
//
// bExternal
//
this.bExternal.Location = new System.Drawing.Point(378, 26);
this.bExternal.Name = "bExternal";
this.bExternal.Size = new System.Drawing.Size(22, 16);
this.bExternal.TabIndex = 7;
this.bExternal.Text = "...";
this.bExternal.Click += new System.EventHandler(this.bExternal_Click);
//
// tbValueExternal
//
this.tbValueExternal.Location = new System.Drawing.Point(88, 24);
this.tbValueExternal.Name = "tbValueExternal";
this.tbValueExternal.Size = new System.Drawing.Size(256, 20);
this.tbValueExternal.TabIndex = 6;
this.tbValueExternal.Text = "";
this.tbValueExternal.TextChanged += new System.EventHandler(this.Value_TextChanged);
//
// cbValueDatabase
//
this.cbValueDatabase.Location = new System.Drawing.Point(88, 120);
this.cbValueDatabase.Name = "cbValueDatabase";
this.cbValueDatabase.Size = new System.Drawing.Size(256, 21);
this.cbValueDatabase.TabIndex = 5;
this.cbValueDatabase.TextChanged += new System.EventHandler(this.Value_TextChanged);
//
// cbMIMEType
//
this.cbMIMEType.Items.AddRange(new object[] {
"image/bmp",
"image/jpeg",
"image/gif",
"image/png",
"image/x-png"});
this.cbMIMEType.Location = new System.Drawing.Point(88, 88);
this.cbMIMEType.Name = "cbMIMEType";
this.cbMIMEType.Size = new System.Drawing.Size(88, 21);
this.cbMIMEType.TabIndex = 4;
this.cbMIMEType.Text = "image/jpeg";
this.cbMIMEType.SelectedIndexChanged += new System.EventHandler(this.cbMIMEType_SelectedIndexChanged);
//
// cbValueEmbedded
//
this.cbValueEmbedded.Location = new System.Drawing.Point(88, 56);
this.cbValueEmbedded.Name = "cbValueEmbedded";
this.cbValueEmbedded.Size = new System.Drawing.Size(256, 21);
this.cbValueEmbedded.TabIndex = 3;
this.cbValueEmbedded.TextChanged += new System.EventHandler(this.Value_TextChanged);
//
// rbDatabase
//
this.rbDatabase.Location = new System.Drawing.Point(8, 88);
this.rbDatabase.Name = "rbDatabase";
this.rbDatabase.Size = new System.Drawing.Size(80, 24);
this.rbDatabase.TabIndex = 2;
this.rbDatabase.Text = "Database";
this.rbDatabase.CheckedChanged += new System.EventHandler(this.rbSource_CheckedChanged);
//
// rbEmbedded
//
this.rbEmbedded.Location = new System.Drawing.Point(8, 56);
this.rbEmbedded.Name = "rbEmbedded";
this.rbEmbedded.Size = new System.Drawing.Size(80, 24);
this.rbEmbedded.TabIndex = 1;
this.rbEmbedded.Text = "Embedded";
this.rbEmbedded.CheckedChanged += new System.EventHandler(this.rbSource_CheckedChanged);
//
// rbExternal
//
this.rbExternal.Location = new System.Drawing.Point(8, 24);
this.rbExternal.Name = "rbExternal";
this.rbExternal.Size = new System.Drawing.Size(80, 24);
this.rbExternal.TabIndex = 0;
this.rbExternal.Text = "External";
this.rbExternal.CheckedChanged += new System.EventHandler(this.rbSource_CheckedChanged);
//
// label1
//
this.label1.Location = new System.Drawing.Point(24, 184);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(40, 23);
this.label1.TabIndex = 1;
this.label1.Text = "Sizing";
//
// cbSizing
//
this.cbSizing.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbSizing.Items.AddRange(new object[] {
"AutoSize",
"Fit",
"FitProportional",
"Clip"});
this.cbSizing.Location = new System.Drawing.Point(72, 184);
this.cbSizing.Name = "cbSizing";
this.cbSizing.Size = new System.Drawing.Size(96, 21);
this.cbSizing.TabIndex = 2;
this.cbSizing.SelectedIndexChanged += new System.EventHandler(this.cbSizing_SelectedIndexChanged);
//
// bDatabaseExpr
//
this.bDatabaseExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.bDatabaseExpr.Location = new System.Drawing.Point(352, 122);
this.bDatabaseExpr.Name = "bDatabaseExpr";
this.bDatabaseExpr.Size = new System.Drawing.Size(22, 16);
this.bDatabaseExpr.TabIndex = 9;
this.bDatabaseExpr.Tag = "database";
this.bDatabaseExpr.Text = "fx";
this.bDatabaseExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bDatabaseExpr.Click += new System.EventHandler(this.bExpr_Click);
//
// bMimeExpr
//
this.bMimeExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.bMimeExpr.Location = new System.Drawing.Point(184, 90);
this.bMimeExpr.Name = "bMimeExpr";
this.bMimeExpr.Size = new System.Drawing.Size(22, 16);
this.bMimeExpr.TabIndex = 10;
this.bMimeExpr.Tag = "mime";
this.bMimeExpr.Text = "fx";
this.bMimeExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bMimeExpr.Click += new System.EventHandler(this.bExpr_Click);
//
// bEmbeddedExpr
//
this.bEmbeddedExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.bEmbeddedExpr.Location = new System.Drawing.Point(352, 58);
this.bEmbeddedExpr.Name = "bEmbeddedExpr";
this.bEmbeddedExpr.Size = new System.Drawing.Size(22, 16);
this.bEmbeddedExpr.TabIndex = 11;
this.bEmbeddedExpr.Tag = "embedded";
this.bEmbeddedExpr.Text = "fx";
this.bEmbeddedExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bEmbeddedExpr.Click += new System.EventHandler(this.bExpr_Click);
//
// bExternalExpr
//
this.bExternalExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.bExternalExpr.Location = new System.Drawing.Point(352, 26);
this.bExternalExpr.Name = "bExternalExpr";
this.bExternalExpr.Size = new System.Drawing.Size(22, 16);
this.bExternalExpr.TabIndex = 12;
this.bExternalExpr.Tag = "external";
this.bExternalExpr.Text = "fx";
this.bExternalExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bExternalExpr.Click += new System.EventHandler(this.bExpr_Click);
//
// ImageCtl
//
this.Controls.Add(this.cbSizing);
this.Controls.Add(this.label1);
this.Controls.Add(this.groupBox1);
this.Name = "ImageCtl";
this.Size = new System.Drawing.Size(472, 288);
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
public bool IsValid()
{
return true;
}
public void Apply()
{
// take information in control and apply to all the style nodes
// Only change information that has been marked as modified;
// this way when group is selected it is possible to change just
// the items you want and keep the rest the same.
foreach (XmlNode riNode in this._ReportItems)
ApplyChanges(riNode);
// No more changes
fSource = fValue = fSizing = fMIMEType = false;
}
public void ApplyChanges(XmlNode node)
{
if (fSource || fValue || fMIMEType)
{
string source="";
string val="";
if (rbEmbedded.Checked)
{
val = cbValueEmbedded.Text;
source = "Embedded";
}
else if (rbDatabase.Checked)
{
source = "Database";
val = cbValueDatabase.Text;
_Draw.SetElement(node, "MIMEType", this.cbMIMEType.Text);
}
else
{ // must be external
source = "External";
val = tbValueExternal.Text;
}
_Draw.SetElement(node, "Source", source);
_Draw.SetElement(node, "Value", val);
}
if (fSizing)
_Draw.SetElement(node, "Sizing", this.cbSizing.Text);
}
private void Value_TextChanged(object sender, System.EventArgs e)
{
fValue = true;
}
private void cbMIMEType_SelectedIndexChanged(object sender, System.EventArgs e)
{
fMIMEType = true;
}
private void rbSource_CheckedChanged(object sender, System.EventArgs e)
{
fSource = true;
this.cbValueDatabase.Enabled = this.cbMIMEType.Enabled =
this.bDatabaseExpr.Enabled = this.rbDatabase.Checked;
this.cbValueEmbedded.Enabled = this.bEmbeddedExpr.Enabled =
this.bEmbedded.Enabled = this.rbEmbedded.Checked;
this.tbValueExternal.Enabled = this.bExternalExpr.Enabled =
this.bExternal.Enabled = this.rbExternal.Checked;
}
private void cbSizing_SelectedIndexChanged(object sender, System.EventArgs e)
{
fSizing = true;
}
private void bExternal_Click(object sender, System.EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Bitmap Files (*.bmp)|*.bmp" +
"|JPEG (*.jpg;*.jpeg;*.jpe;*.jfif)|*.jpg;*.jpeg;*.jpe;*.jfif" +
"|GIF (*.gif)|*.gif" +
"|TIFF (*.tif;*.tiff)|*.tif;*.tiff" +
"|PNG (*.png)|*.png" +
"|All Picture Files|*.bmp;*.jpg;*.jpeg;*.jpe;*.jfif;*.gif;*.tif;*.tiff;*.png" +
"|All files (*.*)|*.*";
ofd.FilterIndex = 6;
ofd.CheckFileExists = true;
try
{
if (ofd.ShowDialog(this) == DialogResult.OK)
{
tbValueExternal.Text = ofd.FileName;
}
}
finally
{
ofd.Dispose();
}
}
private void bEmbedded_Click(object sender, System.EventArgs e)
{
DialogEmbeddedImages dlgEI = new DialogEmbeddedImages(this._Draw);
dlgEI.StartPosition = FormStartPosition.CenterParent;
try
{
DialogResult dr = dlgEI.ShowDialog();
if (dr != DialogResult.OK)
return;
}
finally
{
dlgEI.Dispose();
}
// Populate the EmbeddedImage names
cbValueEmbedded.Items.Clear();
cbValueEmbedded.Items.AddRange(_Draw.ReportNames.EmbeddedImageNames);
}
private void bExpr_Click(object sender, System.EventArgs e)
{
Button b = sender as Button;
if (b == null)
return;
Control c = null;
switch (b.Tag as string)
{
case "external":
c = tbValueExternal;
break;
case "embedded":
c = cbValueEmbedded;
break;
case "mime":
c = cbMIMEType;
break;
case "database":
c = cbValueDatabase;
break;
}
if (c == null)
return;
XmlNode sNode = _ReportItems[0];
DialogExprEditor ee = new DialogExprEditor(_Draw, c.Text, sNode);
try
{
DialogResult dr = ee.ShowDialog();
if (dr == DialogResult.OK)
c.Text = ee.Expression;
}
finally
{
ee.Dispose();
}
return;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Security.Util {
using System;
using System.Collections;
using System.Globalization;
using System.Diagnostics.Contracts;
[Serializable]
internal class SiteString
{
protected String m_site;
protected ArrayList m_separatedSite;
protected static char[] m_separators = { '.' };
protected internal SiteString()
{
// Only call this in derived classes when you know what you're doing.
}
public SiteString( String site )
{
m_separatedSite = CreateSeparatedSite( site );
m_site = site;
}
private SiteString(String site, ArrayList separatedSite)
{
m_separatedSite = separatedSite;
m_site = site;
}
private static ArrayList CreateSeparatedSite(String site)
{
if (site == null || site.Length == 0)
{
throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" ));
}
Contract.EndContractBlock();
ArrayList list = new ArrayList();
int braIndex = -1;
int ketIndex = -1;
braIndex = site.IndexOf('[');
if (braIndex == 0)
ketIndex = site.IndexOf(']', braIndex+1);
if (ketIndex != -1)
{
// Found an IPv6 address. Special case that
String ipv6Addr = site.Substring(braIndex+1, ketIndex-braIndex-1);
list.Add(ipv6Addr);
return list;
}
// Regular hostnames or IPv4 addresses
// We dont need to do this for IPv4 addresses, but it's easier to do it anyway
String[] separatedArray = site.Split( m_separators );
for (int index = separatedArray.Length-1; index > -1; --index)
{
if (separatedArray[index] == null)
{
throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" ));
}
else if (separatedArray[index].Equals( "" ))
{
if (index != separatedArray.Length-1)
{
throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" ));
}
}
else if (separatedArray[index].Equals( "*" ))
{
if (index != 0)
{
throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" ));
}
list.Add( separatedArray[index] );
}
else if (!AllLegalCharacters( separatedArray[index] ))
{
throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" ));
}
else
{
list.Add( separatedArray[index] );
}
}
return list;
}
// KB# Q188997 - http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q188997& gives the list of allowed characters in
// a NETBIOS name. DNS names are a subset of that (alphanumeric or '-').
private static bool AllLegalCharacters( String str )
{
for (int i = 0; i < str.Length; ++i)
{
char c = str[i];
if (IsLegalDNSChar(c) ||
IsNetbiosSplChar(c))
{
continue;
}
else
{
return false;
}
}
return true;
}
private static bool IsLegalDNSChar(char c)
{
if ((c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') ||
(c == '-'))
return true;
else
return false;
}
private static bool IsNetbiosSplChar(char c)
{
// ! @ # $ % ^ & ( ) - _ ' { } . ~ are OK
switch (c) {
case '-':
case '_':
case '@':
case '!':
case '#':
case '$':
case '%':
case '^':
case '&':
case '(':
case ')':
case '\'':
case '{':
case '}':
case '.':
case '~':
return true;
default:
return false;
}
}
public override String ToString()
{
return m_site;
}
public override bool Equals(Object o)
{
if (o == null || !(o is SiteString))
return false;
else
return this.Equals( (SiteString)o, true );
}
public override int GetHashCode()
{
TextInfo info = CultureInfo.InvariantCulture.TextInfo;
return info.GetCaseInsensitiveHashCode( this.m_site );
}
internal bool Equals( SiteString ss, bool ignoreCase )
{
if (this.m_site == null)
return ss.m_site == null;
if (ss.m_site == null)
return false;
return this.IsSubsetOf(ss, ignoreCase) && ss.IsSubsetOf(this, ignoreCase);
}
public virtual SiteString Copy()
{
return new SiteString( m_site, m_separatedSite );
}
public virtual bool IsSubsetOf( SiteString operand )
{
return this.IsSubsetOf( operand, true );
}
public virtual bool IsSubsetOf( SiteString operand, bool ignoreCase )
{
StringComparison strComp = (ignoreCase? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
if (operand == null)
{
return false;
}
else if (this.m_separatedSite.Count == operand.m_separatedSite.Count &&
this.m_separatedSite.Count == 0)
{
return true;
}
else if (this.m_separatedSite.Count < operand.m_separatedSite.Count - 1)
{
return false;
}
else if (this.m_separatedSite.Count > operand.m_separatedSite.Count &&
operand.m_separatedSite.Count > 0 &&
!operand.m_separatedSite[operand.m_separatedSite.Count - 1].Equals("*"))
{
return false;
}
else if (String.Compare( this.m_site, operand.m_site, strComp) == 0)
{
return true;
}
for (int index = 0; index < operand.m_separatedSite.Count - 1; ++index)
{
if (String.Compare((String)this.m_separatedSite[index], (String)operand.m_separatedSite[index], strComp) != 0)
{
return false;
}
}
if (this.m_separatedSite.Count < operand.m_separatedSite.Count)
{
return operand.m_separatedSite[operand.m_separatedSite.Count - 1].Equals("*");
}
else if (this.m_separatedSite.Count == operand.m_separatedSite.Count)
{
// last item must be the same or operand must have a * in its last item
return (String.Compare((String)this.m_separatedSite[this.m_separatedSite.Count - 1],
(String)operand.m_separatedSite[this.m_separatedSite.Count - 1],
strComp ) == 0 ||
operand.m_separatedSite[operand.m_separatedSite.Count - 1].Equals("*"));
}
else
return true;
}
public virtual SiteString Intersect( SiteString operand )
{
if (operand == null)
{
return null;
}
else if (this.IsSubsetOf( operand ))
{
return this.Copy();
}
else if (operand.IsSubsetOf( this ))
{
return operand.Copy();
}
else
{
return null;
}
}
public virtual SiteString Union( SiteString operand )
{
if (operand == null)
{
return this;
}
else if (this.IsSubsetOf( operand ))
{
return operand.Copy();
}
else if (operand.IsSubsetOf( this ))
{
return this.Copy();
}
else
{
return null;
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.HSLF.Record
{
using System;
using NPOI.Util;
using System.IO;
using System.Collections;
/**
* General holder for PersistPtrFullBlock and PersistPtrIncrementalBlock
* records. We need to handle them specially, since we have to go around
* updating UserEditAtoms if they shuffle about on disk
* These hold references to where slides "live". If the position of a slide
* moves, then we have update all of these. If we come up with a new version
* of a slide, then we have to add one of these to the end of the chain
* (via CurrentUserAtom and UserEditAtom) pointing to the new slide location
*
* @author Nick Burch
*/
public class PersistPtrHolder : PositionDependentRecordAtom
{
private byte[] _header;
private byte[] _ptrData; // Will need to update this once we allow updates to _slideLocations
private long _type;
/**
* Holds the lookup for slides to their position on disk.
* You always need to check the most recent PersistPtrHolder
* that knows about a given slide to find the right location
*/
private Hashtable _slideLocations;
/**
* Holds the lookup from slide id to where their offset is
* held inside _ptrData. Used when writing out, and updating
* the positions of the slides
*/
private Hashtable _slideoffsetDataLocation;
/**
* Get the list of slides that this PersistPtrHolder knows about.
* (They will be the keys in the hashtable for looking up the positions
* of these slides)
*/
public int[] GetKnownSlideIDs()
{
int[] ids = new int[_slideLocations.Count];
IEnumerator keys = _slideLocations.Keys.GetEnumerator();
for (int i = 0; i < ids.Length; i++)
{
keys.MoveNext();
int id = (int)keys.Current;
ids[i] = id;
}
return ids;
}
/**
* Get the lookup from slide numbers to byte offsets, for the slides
* known about by this PersistPtrHolder.
*/
public Hashtable GetSlideLocationsLookup()
{
return _slideLocations;
}
/**
* Get the lookup from slide numbers to their offsets inside
* _ptrData, used when Adding or moving slides.
*/
public Hashtable GetSlideoffsetDataLocationsLookup()
{
return _slideoffsetDataLocation;
}
/**
* Adds a new slide, notes or similar, to be looked up by this.
* For now, won't look for the most optimal on disk representation.
*/
public void AddSlideLookup(int slideID, int posOnDisk)
{
// PtrData grows by 8 bytes:
// 4 bytes for the new info block
// 4 bytes for the slide offset
byte[] newPtrData = new byte[_ptrData.Length + 8];
Array.Copy(_ptrData, 0, newPtrData, 0, _ptrData.Length);
// Add to the slide location lookup hash
_slideLocations[slideID] = posOnDisk;
// Add to the ptrData offset lookup hash
_slideoffsetDataLocation[slideID] =
_ptrData.Length + 4;
// Build the info block
// First 20 bits = offset number = slide ID
// Remaining 12 bits = offset count = 1
int infoBlock = slideID;
infoBlock += (1 << 20);
// Write out the data for this
LittleEndian.PutInt(newPtrData, newPtrData.Length - 8, infoBlock);
LittleEndian.PutInt(newPtrData, newPtrData.Length - 4, posOnDisk);
// Save the new ptr data
_ptrData = newPtrData;
// Update the atom header
LittleEndian.PutInt(_header, 4, newPtrData.Length);
}
/**
* Create a new holder for a PersistPtr record
*/
protected PersistPtrHolder(byte[] source, int start, int len)
{
// Sanity Checking - including whole header, so treat
// length as based of 0, not 8 (including header size based)
if (len < 8) { len = 8; }
// Treat as an atom, grab and hold everything
_header = new byte[8];
Array.Copy(source, start, _header, 0, 8);
_type = LittleEndian.GetUShort(_header, 2);
// Try to make sense of the data part:
// Data part is made up of a number of these Sets:
// 32 bit info value
// 12 bits count of # of entries
// base number for these entries
// count * 32 bit offsets
// Repeat as many times as you have data
_slideLocations = new Hashtable();
_slideoffsetDataLocation = new Hashtable();
_ptrData = new byte[len - 8];
Array.Copy(source, start + 8, _ptrData, 0, _ptrData.Length);
int pos = 0;
while (pos < _ptrData.Length)
{
// Grab the info field
long info = LittleEndian.GetUInt(_ptrData, pos);
// First 20 bits = offset number
// Remaining 12 bits = offset count
int offset_count = (int)(info >> 20);
int offset_no = (int)(info - (offset_count << 20));
//Console.WriteLine("Info is " + info + ", count is " + offset_count + ", number is " + offset_no);
// Wind on by the 4 byte info header
pos += 4;
// Grab the offsets for each of the sheets
for (int i = 0; i < offset_count; i++)
{
int sheet_no = offset_no + i;
long sheet_offset = LittleEndian.GetUInt(_ptrData, pos);
_slideLocations[sheet_no] = (int)sheet_offset;
_slideoffsetDataLocation[sheet_no] = pos;
// Wind on by 4 bytes per sheet found
pos += 4;
}
}
}
/**
* Return the value we were given at creation, be it 6001 or 6002
*/
public override long RecordType
{
get
{
return _type;
}
}
/**
* At Write-out time, update the references to the sheets to their
* new positions
*/
public override void UpdateOtherRecordReferences(Hashtable oldToNewReferencesLookup)
{
int[] slideIDs = GetKnownSlideIDs();
// Loop over all the slides we know about
// Find where they used to live, and where they now live
// Then, update the right bit of _ptrData with their new location
for (int i = 0; i < slideIDs.Length; i++)
{
int id = slideIDs[i];
int oldPos = (int)_slideLocations[id];
int newPos;
if (!oldToNewReferencesLookup.Contains(oldPos))
{
newPos = oldPos;
}
else
{
newPos = (int)oldToNewReferencesLookup[oldPos];
}
// Write out the new location
int dataOffset = (int)_slideoffsetDataLocation[id];
LittleEndian.PutInt(_ptrData, dataOffset, newPos);
// Update our hashtable
_slideLocations.Remove(id);
_slideLocations[id] = newPos;
}
}
/**
* Write the contents of the record back, so it can be written
* to disk
*/
public override void WriteOut(Stream out1)
{
out1.Write(_header, (int)out1.Position, _header.Length);
out1.Write(_ptrData, (int)out1.Position, _ptrData.Length);
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This regression algorithm tests Out of The Money (OTM) index option expiry for short calls.
/// We expect 2 orders from the algorithm, which are:
///
/// * Initial entry, sell SPX Call Option (expiring OTM)
/// - Profit the option premium, since the option was not assigned.
///
/// * Liquidation of SPX call OTM contract on the last trade date
///
/// Additionally, we test delistings for index options and assert that our
/// portfolio holdings reflect the orders the algorithm has submitted.
/// </summary>
public class IndexOptionShortCallOTMExpiryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _spx;
private Symbol _spxOption;
private Symbol _expectedContract;
public override void Initialize()
{
SetStartDate(2021, 1, 4);
SetEndDate(2021, 1, 31);
_spx = AddIndex("SPX", Resolution.Minute).Symbol;
// Select a index option expiring ITM, and adds it to the algorithm.
_spxOption = AddIndexOptionContract(OptionChainProvider.GetOptionContractList(_spx, Time)
.Where(x => x.ID.StrikePrice >= 4250m && x.ID.OptionRight == OptionRight.Call && x.ID.Date.Year == 2021 && x.ID.Date.Month == 1)
.OrderBy(x => x.ID.StrikePrice)
.Take(1)
.Single(), Resolution.Minute).Symbol;
_expectedContract = QuantConnect.Symbol.CreateOption(_spx, Market.USA, OptionStyle.European, OptionRight.Call, 4250m, new DateTime(2021, 1, 15));
if (_spxOption != _expectedContract)
{
throw new Exception($"Contract {_expectedContract} was not found in the chain");
}
Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_spx, 1), () =>
{
MarketOrder(_spxOption, -1);
});
}
public override void OnData(Slice data)
{
// Assert delistings, so that we can make sure that we receive the delisting warnings at
// the expected time. These assertions detect bug #4872
foreach (var delisting in data.Delistings.Values)
{
if (delisting.Type == DelistingType.Warning)
{
if (delisting.Time != new DateTime(2021, 1, 15))
{
throw new Exception($"Delisting warning issued at unexpected date: {delisting.Time}");
}
}
if (delisting.Type == DelistingType.Delisted)
{
if (delisting.Time != new DateTime(2021, 1, 16))
{
throw new Exception($"Delisting happened at unexpected date: {delisting.Time}");
}
}
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
if (orderEvent.Status != OrderStatus.Filled)
{
// There's lots of noise with OnOrderEvent, but we're only interested in fills.
return;
}
if (!Securities.ContainsKey(orderEvent.Symbol))
{
throw new Exception($"Order event Symbol not found in Securities collection: {orderEvent.Symbol}");
}
var security = Securities[orderEvent.Symbol];
if (security.Symbol == _spx)
{
throw new Exception($"Expected no order events for underlying Symbol {security.Symbol}");
}
if (security.Symbol == _expectedContract)
{
AssertIndexOptionContractOrder(orderEvent, security);
}
else
{
throw new Exception($"Received order event for unknown Symbol: {orderEvent.Symbol}");
}
Log($"{orderEvent}");
}
private void AssertIndexOptionContractOrder(OrderEvent orderEvent, Security optionContract)
{
if (orderEvent.Direction == OrderDirection.Sell && optionContract.Holdings.Quantity != -1)
{
throw new Exception($"No holdings were created for option contract {optionContract.Symbol}");
}
if (orderEvent.Direction == OrderDirection.Buy && optionContract.Holdings.Quantity != 0)
{
throw new Exception("Expected no options holdings after closing position");
}
if (orderEvent.IsAssignment)
{
throw new Exception($"Assignment was not expected for {orderEvent.Symbol}");
}
}
/// <summary>
/// Ran at the end of the algorithm to ensure the algorithm has no holdings
/// </summary>
/// <exception cref="Exception">The algorithm has holdings</exception>
public override void OnEndOfAlgorithm()
{
if (Portfolio.Invested)
{
throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0.01%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0.142%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0.010%"},
{"Sharpe Ratio", "4.589"},
{"Probabilistic Sharpe Ratio", "98.983%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.001"},
{"Beta", "-0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-0.32"},
{"Tracking Error", "0.138"},
{"Treynor Ratio", "-9.479"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$22000.00"},
{"Lowest Capacity Asset", "SPX XL80P59H5E6M|SPX 31"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "76ffdfc100ba7778009e35966bd92cfc"}
};
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Delaunay
{
/**
* The line segment connecting the two Sites is part of the Delaunay triangulation;
* the line segment connecting the two Vertices is part of the Voronoi diagram
* @author ashaw
*
*/
public class Edge : IDisposable
{
private static List<Edge> _pool = new List<Edge>();
/**
* This is the only way to create a new Edge
* @param site0
* @param site1
* @return
*
*/
internal static Edge CreateBisectingEdge(Site site0, Site site1)
{
float dx, dy, absdx, absdy;
float a, b, c;
dx = site1.X - site0.X;
dy = site1.Y - site0.Y;
absdx = dx > 0 ? dx : -dx;
absdy = dy > 0 ? dy : -dy;
c = site0.X * dx + site0.Y * dy + (dx * dx + dy * dy) * 0.5f;
if (absdx > absdy)
{
a = 1.0f; b = dy / dx; c /= dx;
}
else
{
b = 1.0f; a = dx / dy; c /= dy;
}
Edge edge = Edge.Create();
edge.LeftSite = site0;
edge.RightSite = site1;
site0.AddEdge(edge);
site1.AddEdge(edge);
edge._leftVertex = null;
edge._rightVertex = null;
edge.a = a; edge.b = b; edge.c = c;
//trace("createBisectingEdge: a ", edge.a, "b", edge.b, "c", edge.c);
return edge;
}
private static Edge Create()
{
Edge edge;
if (_pool.Count > 0)
{
edge = _pool.Pop();
edge.Init();
}
else
{
edge = new Edge(typeof(PrivateConstructorEnforcer));
}
return edge;
}
//private static readonly Sprite LINESPRITE = new Sprite();
//private static readonly Graphics GRAPHICS = LINESPRITE.graphics;
private BitmapData _delaunayLineBmp;
internal BitmapData DelaunayLineBmp
{
get
{
if (_delaunayLineBmp == null)
{
_delaunayLineBmp = MakeDelaunayLineBmp();
}
return _delaunayLineBmp;
}
}
// making this available to Voronoi; running out of memory in AIR so I cannot cache the bmp
internal BitmapData MakeDelaunayLineBmp()
{
throw new NotImplementedException();
//var p0 = leftSite.coord;
//Vector2 p1 = rightSite.coord;
//GRAPHICS.clear();
//// clear() resets line style back to undefined!
//GRAPHICS.lineStyle(0, 0, 1.0, false, LineScaleMode.NONE, CapsStyle.NONE);
//GRAPHICS.moveTo(p0.x, p0.y);
//GRAPHICS.lineTo(p1.x, p1.y);
//int w = int(Math.Ceiling(Math.Max(p0.x, p1.x)));
//if (w < 1)
//{
// w = 1;
//}
//int h = int(Math.Ceiling(Math.Max(p0.y, p1.y)));
//if (h < 1)
//{
// h = 1;
//}
//BitmapData bmp = new BitmapData(w, h, true, 0);
//bmp.draw(LINESPRITE);
//return bmp;
}
public LineSegment DelaunayLine()
{
// draw a line connecting the input Sites for which the edge is a bisector:
return new LineSegment(LeftSite.Coord(), RightSite.Coord());
}
public LineSegment VoronoiEdge()
{
if (!Visible) return new LineSegment(Vector2.zero, Vector2.zero);
return new LineSegment(_clippedVertices[LR.LEFT],
_clippedVertices[LR.RIGHT]);
}
private static int _nedges = 0;
internal static readonly Edge DELETED = new Edge(typeof(PrivateConstructorEnforcer));
// the equation of the edge: ax + by = c
internal float a, b, c;
// the two Voronoi vertices that the edge connects
// (if one of them is null, the edge extends to infinity)
private Vertex _leftVertex;
internal Vertex LeftVertex
{
get
{
return _leftVertex;
}
}
private Vertex _rightVertex;
internal Vertex RightVertex
{
get
{
return _rightVertex;
}
}
internal Vertex GetVertex(LR leftRight)
{
return (leftRight == LR.LEFT) ? _leftVertex : _rightVertex;
}
internal void SetVertex(LR leftRight, Vertex v)
{
if (leftRight == LR.LEFT)
{
_leftVertex = v;
}
else
{
_rightVertex = v;
}
}
internal bool IsPartOfConvexHull()
{
return (_leftVertex == null || _rightVertex == null);
}
public float SitesDistance()
{
return Utilities.Distance(LeftSite.Coord(), RightSite.Coord());
}
public static float CompareSitesDistancesMax(Edge edge0, Edge edge1)
{
float length0 = edge0.SitesDistance();
float length1 = edge1.SitesDistance();
if (length0 < length1)
{
return 1;
}
if (length0 > length1)
{
return -1;
}
return 0;
}
public static float CompareSitesDistances(Edge edge0, Edge edge1)
{
return -CompareSitesDistancesMax(edge0, edge1);
}
// Once clipVertices() is called, this Dictionary will hold two Vector2s
// representing the clipped coordinates of the left and right ends...
private Dictionary<LR, Vector2> _clippedVertices;
internal Dictionary<LR, Vector2> ClippedEnds
{
get
{
return _clippedVertices;
}
}
// unless the entire Edge is outside the bounds.
// In that case visible will be false:
internal bool Visible
{
get
{
return _clippedVertices != null;
}
}
// the two input Sites for which this Edge is a bisector:
private Dictionary<LR, Site> _sites;
internal Site LeftSite
{
set
{
_sites[LR.LEFT] = value;
}
get
{
return _sites[LR.LEFT];
}
}
internal Site RightSite
{
set
{
_sites[LR.RIGHT] = value;
}
get
{
return _sites[LR.RIGHT];
}
}
internal Site GetSite(LR leftRight)
{
return _sites[leftRight] as Site;
}
private int _edgeIndex;
public void Dispose()
{
if (_delaunayLineBmp != null)
{
_delaunayLineBmp.dispose();
_delaunayLineBmp = null;
}
_leftVertex = null;
_rightVertex = null;
if (_clippedVertices != null)
{
_clippedVertices[LR.LEFT] = Vector2.zero;
_clippedVertices[LR.RIGHT] = Vector2.zero;
_clippedVertices = null;
}
_sites[LR.LEFT] = null;
_sites[LR.RIGHT] = null;
_sites = null;
_pool.Add(this);
}
public Edge(Type pce)
{
if (pce != typeof(PrivateConstructorEnforcer))
{
throw new Exception("Edge: static readonlyructor is private");
}
_edgeIndex = _nedges++;
Init();
}
private void Init()
{
_sites = new Dictionary<LR, Site>();
}
public override string ToString()
{
return "Edge " + _edgeIndex + "; sites " + _sites[LR.LEFT] + ", " + _sites[LR.RIGHT]
+ "; endVertices " + (_leftVertex != null ? _leftVertex.VertexIndex.ToString() : "null") + ", "
+ (_rightVertex != null ? _rightVertex.VertexIndex.ToString() : "null") + "::";
}
/**
* Set _clippedVertices to contain the two ends of the portion of the Voronoi edge that is visible
* within the bounds. If no part of the Edge falls within the bounds, leave _clippedVertices null.
* @param bounds
*
*/
internal void ClipVertices(Rect bounds)
{
float xmin = bounds.x;
float ymin = bounds.y;
float xmax = bounds.right;
float ymax = bounds.bottom;
Vertex vertex0, vertex1;
float x0, x1, y0, y1;
if (a == 1.0 && b >= 0.0)
{
vertex0 = _rightVertex;
vertex1 = _leftVertex;
}
else
{
vertex0 = _leftVertex;
vertex1 = _rightVertex;
}
if (a == 1.0)
{
y0 = ymin;
if (vertex0 != null && vertex0.Y > ymin)
{
y0 = vertex0.Y;
}
if (y0 > ymax)
{
return;
}
x0 = c - b * y0;
y1 = ymax;
if (vertex1 != null && vertex1.Y < ymax)
{
y1 = vertex1.Y;
}
if (y1 < ymin)
{
return;
}
x1 = c - b * y1;
if ((x0 > xmax && x1 > xmax) || (x0 < xmin && x1 < xmin))
{
return;
}
if (x0 > xmax)
{
x0 = xmax; y0 = (c - x0) / b;
}
else if (x0 < xmin)
{
x0 = xmin; y0 = (c - x0) / b;
}
if (x1 > xmax)
{
x1 = xmax; y1 = (c - x1) / b;
}
else if (x1 < xmin)
{
x1 = xmin; y1 = (c - x1) / b;
}
}
else
{
x0 = xmin;
if (vertex0 != null && vertex0.X > xmin)
{
x0 = vertex0.X;
}
if (x0 > xmax)
{
return;
}
y0 = c - a * x0;
x1 = xmax;
if (vertex1 != null && vertex1.X < xmax)
{
x1 = vertex1.X;
}
if (x1 < xmin)
{
return;
}
y1 = c - a * x1;
if ((y0 > ymax && y1 > ymax) || (y0 < ymin && y1 < ymin))
{
return;
}
if (y0 > ymax)
{
y0 = ymax; x0 = (c - y0) / a;
}
else if (y0 < ymin)
{
y0 = ymin; x0 = (c - y0) / a;
}
if (y1 > ymax)
{
y1 = ymax; x1 = (c - y1) / a;
}
else if (y1 < ymin)
{
y1 = ymin; x1 = (c - y1) / a;
}
}
_clippedVertices = new Dictionary<LR, Vector2>();
if (vertex0 == _leftVertex)
{
_clippedVertices[LR.LEFT] = new Vector2(x0, y0);
_clippedVertices[LR.RIGHT] = new Vector2(x1, y1);
}
else
{
_clippedVertices[LR.RIGHT] = new Vector2(x0, y0);
_clippedVertices[LR.LEFT] = new Vector2(x1, y1);
}
}
}
}
| |
using System;
using System.Windows.Forms;
using System.IO;
using GenLib;
using StandardFormatLib;
using PrimerProLocalization;
namespace PrimerProObjects
{
/// <summary>
/// Summary description for Settings.
/// </summary>
public class Settings
{
private ProjectInfo m_ProjInfo; //Project Info
private string m_strAppFolder; //Application folder
private string m_strPrimerProFolder; //PrimePro Folder
private string m_strOptionsFile; //Options file
private string m_strHelpFile; //Help file
private System.Drawing.Printing.PageSettings m_PageSettings = null; //Application page settings
private OptionList m_OptionsSettings = null; //Application option settings
private GraphemeInventory m_GraphemeInventory = null; //Application grapheme inventory
private SightWords m_SightWords = null; //Application site words list
private GraphemeTaughtOrder m_GraphemesTaught; //Application graphemes taught order list
private PSTable m_PSTable = null; //Application parts of Speech table
private LocalizationTable m_LocalizationTable; //Application Localization Table;
private WordList m_WordList; //Imported Word List
private TextData m_TextData; //Imported Text Data
private bool m_SearchInsertionResults; //Mode = Results
private bool m_SearchInsertionDefinitions; //Mode = Definitions
//private const string kOptionsFile = "\\OptionList.xml";
private const string kHelpFile = "\\PrimerPro.chm";
private const string kCRTemplate = "\\ConsonantReportTemplate.rtf";
private const string kPPRTemplate = "\\PrimerProgressionReportTemplate.rtf";
private const string kVRTemplate = "\\VowelReportTemplate.rtf";
private const string kDfltGI = "\\DefaultGraphemeInventory.xml";
private const string kDfltPST = "\\DefaultPSTable.xml";
private const string kLocalizationFile = "\\PrimerProLocalization.xml";
public Settings()
{
m_ProjInfo = new ProjectInfo();
m_strAppFolder = Directory.GetCurrentDirectory();
m_strPrimerProFolder = m_ProjInfo.PrimerProFolder; //PrimerPro Folder
if (!Directory.Exists(m_strPrimerProFolder))
Directory.CreateDirectory(m_strPrimerProFolder);
// if templates and xml files do not exist in PrimerPro folder, copy them from App folder
//if (!File.Exists(m_strPrimerProFolder + Settings.kCRTemplate))
// File.Copy(m_strAppFolder + Settings.kCRTemplate, m_strPrimerProFolder + Settings.kCRTemplate);
//if (!File.Exists(m_strPrimerProFolder + Settings.kPPRTemplate))
// File.Copy(m_strAppFolder + Settings.kPPRTemplate,
// m_strPrimerProFolder + Settings.kPPRTemplate);
//if (!File.Exists(m_strPrimerProFolder + Settings.kVRTemplate))
// File.Copy(m_strAppFolder + Settings.kVRTemplate,
// m_strPrimerProFolder + Settings.kVRTemplate);
//if (!File.Exists(m_strPrimerProFolder + Settings.kDfltGI))
// File.Copy(m_strAppFolder + Settings.kDfltGI,
// m_strPrimerProFolder + Settings.kDfltGI);
//if (!File.Exists(m_strPrimerProFolder + Settings.kDfltPST))
// File.Copy(m_strAppFolder + Settings.kDfltPST,
// m_strPrimerProFolder + Settings.kDfltPST);
//if (!File.Exists(m_strPrimerProFolder + Settings.kDfltPST))
// File.Copy(m_strAppFolder + Settings.kDfltPST,
// m_strPrimerProFolder + Settings.kDfltPST);
//if (!File.Exists(m_strPrimerProFolder + Settings.kLocalizationFile))
// File.Copy(m_strAppFolder + Settings.kLocalizationFile,
// m_strPrimerProFolder + Settings.kLocalizationFile);
m_strOptionsFile = m_ProjInfo.OptionsFile; //Options File
m_strHelpFile = m_strAppFolder + Settings.kHelpFile; //Help File
m_OptionsSettings = new OptionList();
m_PageSettings = new System.Drawing.Printing.PageSettings();
m_GraphemeInventory = new GraphemeInventory(this);
m_GraphemesTaught = new GraphemeTaughtOrder(this);
m_PSTable = new PSTable(this);
m_SightWords = new SightWords(this);
m_TextData = new TextData(this);
m_WordList = new WordList(this);
m_LocalizationTable = new LocalizationTable();
m_SearchInsertionResults = true;
m_SearchInsertionDefinitions = false;
}
public Settings(ProjectInfo info)
{
m_ProjInfo = info;
m_strAppFolder = Directory.GetCurrentDirectory();
m_strPrimerProFolder = m_ProjInfo.PrimerProFolder; //PrimerPro Folder
if ( !Directory.Exists(m_strPrimerProFolder) )
Directory.CreateDirectory(m_strPrimerProFolder);
m_strOptionsFile = m_ProjInfo.OptionsFile; //Options File
m_strHelpFile = m_strAppFolder + Settings.kHelpFile; //Help File
m_OptionsSettings = new OptionList();
m_PageSettings = new System.Drawing.Printing.PageSettings();
m_GraphemeInventory = new GraphemeInventory(this);
m_GraphemesTaught = new GraphemeTaughtOrder(this);
m_PSTable = new PSTable(this);
m_SightWords = new SightWords(this);
m_TextData = new TextData(this);
m_WordList = new WordList(this);
m_LocalizationTable = new LocalizationTable();
m_SearchInsertionResults = true;
m_SearchInsertionDefinitions = false;
}
public ProjectInfo ProjInfo
{
get { return m_ProjInfo; }
}
public string PrimerProFolder
{
get { return m_strPrimerProFolder; }
set { m_strPrimerProFolder = value; }
}
public void LoadOptions()
// Load Options Settings
{
m_OptionsSettings = new OptionList(m_strPrimerProFolder, m_strOptionsFile);
if (!m_OptionsSettings.LoadFromFile(m_strOptionsFile))
{
//MessageBox.Show("Options File does not exist - Will use defaults settings");
string strText = this.LocalizationTable.GetMessage("Settings1");
if (strText == "")
strText = "Options File does not exist - Will use defaults settings";
MessageBox.Show(strText);
}
}
public void LoadGraphemeInventory()
{
m_GraphemeInventory = new GraphemeInventory(this);
if (!m_GraphemeInventory.LoadFromFile(this.OptionSettings.GraphemeInventoryFile))
{
//MessageBox.Show("Grapheme Inventory file does not exist - will create one");
string strText = this.LocalizationTable.GetMessage("Settings2");
if (strText == "")
strText = "Grapheme Inventory file does not exist - will create one";
MessageBox.Show(strText);
m_GraphemeInventory.SaveToFile(this.OptionSettings.GraphemeInventoryFile);
m_GraphemeInventory.FileName = this.OptionSettings.GraphemeInventoryFile;
}
}
public void LoadGraphemesTaught()
{
m_GraphemesTaught = new GraphemeTaughtOrder(this);
if (!m_GraphemesTaught.LoadFromFile(this.OptionSettings.GraphemeTaughtOrderFile))
{
//MessageBox.Show("Grapheme Taught Order file does not exist - will create one");
string strText = this.LocalizationTable.GetMessage("Settings3");
if (strText == "")
strText = "Grapheme Taught Order file does not exist - will create one";
MessageBox.Show(strText);
m_GraphemesTaught.SaveToFile(this.OptionSettings.GraphemeTaughtOrderFile);
m_GraphemesTaught.FileName = this.OptionSettings.GraphemeTaughtOrderFile;
}
}
public void LoadSightWords()
{
m_SightWords = new SightWords(this);
if (!m_SightWords.LoadFromFile(this.OptionSettings.SightWordsFile))
{
//MessageBox.Show("Sight Words file does not exist - will create one");
string strText = this.LocalizationTable.GetMessage("Settings4");
if (strText == "")
strText = "Sight Words file does not exist - will create one";
MessageBox.Show(strText);
m_SightWords.SaveToFile(this.OptionSettings.SightWordsFile);
m_SightWords.FileName = this.OptionSettings.SightWordsFile;
}
}
public void LoadTextData()
{
m_TextData = new TextData(this);
if (m_OptionsSettings.TextDataFile != "")
{
if (m_TextData.LoadFile(m_OptionsSettings.TextDataFile))
m_TextData.FileName = m_OptionsSettings.TextDataFile;
else m_TextData.FileName = "";
}
}
public void LoadWordList()
{
m_WordList = new WordList(this);
if (m_OptionsSettings.WordListFile != "")
{
switch (m_OptionsSettings.WordListFileType)
{
case WordList.FileType.Lift:
//Lift support
m_WordList.FileName = m_OptionsSettings.WordListFile;
m_WordList.Type = m_OptionsSettings.WordListFileType;
m_WordList = m_WordList.LoadWordsFromLift();
break;
case WordList.FileType.StandardFormat:
if (m_WordList.SFFile.LoadFile(m_OptionsSettings.WordListFile, m_OptionsSettings.FMRecordMarker))
{
m_WordList = m_WordList.LoadWordsFromSF();
m_WordList.SFFile.FileName = m_OptionsSettings.WordListFile;
m_WordList.FileName = m_OptionsSettings.WordListFile;
m_WordList.Type = m_OptionsSettings.WordListFileType;
}
break;
default:
if (m_WordList.SFFile.LoadFile(m_OptionsSettings.WordListFile, m_OptionsSettings.FMRecordMarker))
{
m_WordList = m_WordList.LoadWordsFromSF();
m_WordList.SFFile.FileName = m_OptionsSettings.WordListFile;
m_WordList.Type = m_OptionsSettings.WordListFileType;
}
break;
}
}
}
public bool LoadPartsOfSpeech()
{
bool fReturn = true;
m_PSTable = new PSTable(this);
if (!m_PSTable.LoadFromFile(this.OptionSettings.PSTableFile))
{
//MessageBox.Show("Parts of Speech table does not exist");
string strText = this.LocalizationTable.GetMessage("Settings5");
if (strText == "")
strText = "Parts of Speech table does not exist";
MessageBox.Show(strText);
fReturn = false;
}
return fReturn;
}
public string GetAppFolder()
{
return m_strAppFolder;
}
public string GetPrimerProFolder()
{
return m_strPrimerProFolder;
}
public string GetHelpFile()
{
return m_strHelpFile;
}
public string GetOptionsFile()
{
return m_strOptionsFile;
}
public System.Drawing.Printing.PageSettings PageSettings
{
get {return m_PageSettings;}
set {m_PageSettings = value;}
}
public OptionList OptionSettings
{
get {return m_OptionsSettings;}
set {m_OptionsSettings = value;}
}
public GraphemeInventory GraphemeInventory
{
get {return m_GraphemeInventory;}
set {m_GraphemeInventory = value;}
}
public SightWords SightWords
{
get {return m_SightWords;}
set {m_SightWords = value;}
}
public GraphemeTaughtOrder GraphemesTaught
{
get { return m_GraphemesTaught; }
set { m_GraphemesTaught = value; }
}
public PSTable PSTable
{
get {return m_PSTable;}
set {m_PSTable = value;}
}
public WordList WordList
{
get {return m_WordList;}
set {m_WordList = value;}
}
public TextData TextData
{
get {return m_TextData;}
set {m_TextData = value;}
}
public LocalizationTable LocalizationTable
{
get {return m_LocalizationTable;}
set { m_LocalizationTable = value; }
}
public bool SearchInsertionResults
{
get {return m_SearchInsertionResults;}
set {m_SearchInsertionResults = value;}
}
public bool SearchInsertionDefinitions
{
get {return m_SearchInsertionDefinitions;}
set {m_SearchInsertionDefinitions = value;}
}
}
}
| |
using System.Diagnostics;
using System.Text;
using System.IO;
using System;
using System.Threading.Tasks;
namespace NamelessInteractive.Shared.Security
{
public abstract class Hash
{
private readonly int m_block_size;
private readonly int m_hash_size;
public static int BUFFER_SIZE = 64 * 1024;
public Hash (int a_hash_size, int a_block_size)
{
Debug.Assert ((a_block_size > 0) || (a_block_size == -1));
Debug.Assert (a_hash_size > 0);
m_block_size = a_block_size;
m_hash_size = a_hash_size;
}
public virtual string Name {
get {
return GetType ().Name;
}
}
public virtual int BlockSize {
get {
return m_block_size;
}
}
public virtual int HashSize {
get {
return m_hash_size;
}
}
public virtual HashResult ComputeObject (object a_data)
{
if (a_data is byte)
return ComputeByte ((byte)a_data);
else if (a_data is short)
return ComputeShort ((short)a_data);
else if (a_data is ushort)
return ComputeUShort ((ushort)a_data);
else if (a_data is char)
return ComputeChar ((char)a_data);
else if (a_data is int)
return ComputeInt ((int)a_data);
else if (a_data is uint)
return ComputeUInt ((uint)a_data);
else if (a_data is long)
return ComputeLong ((long)a_data);
else if (a_data is ulong)
return ComputeULong ((ulong)a_data);
else if (a_data is float)
return ComputeFloat ((float)a_data);
else if (a_data is double)
return ComputeDouble ((double)a_data);
else if (a_data is string)
return ComputeString ((string)a_data);
else if (a_data is byte[])
return ComputeBytes ((byte[])a_data);
else if (a_data.GetType ().IsArray && a_data.GetType ().GetElementType () == typeof(short))
return ComputeShorts ((short[])a_data);
else if (a_data.GetType ().IsArray && a_data.GetType ().GetElementType () == typeof(ushort))
return ComputeUShorts ((ushort[])a_data);
else if (a_data is char[])
return ComputeChars ((char[])a_data);
else if (a_data.GetType ().IsArray && a_data.GetType ().GetElementType () == typeof(int))
return ComputeInts ((int[])a_data);
else if (a_data.GetType ().IsArray && a_data.GetType ().GetElementType () == typeof(uint))
return ComputeUInts ((uint[])a_data);
else if (a_data.GetType ().IsArray && a_data.GetType ().GetElementType () == typeof(long))
return ComputeLongs ((long[])a_data);
else if (a_data.GetType ().IsArray && a_data.GetType ().GetElementType () == typeof(ulong))
return ComputeULongs ((ulong[])a_data);
else if (a_data is float[])
return ComputeFloats ((float[])a_data);
else if (a_data is double[])
return ComputeDoubles ((double[])a_data);
else
throw new ArgumentException ();
}
public virtual HashResult ComputeByte (byte a_data)
{
return ComputeBytes (new byte[] { a_data });
}
public virtual HashResult ComputeChar (char a_data)
{
return ComputeBytes (BitConverter.GetBytes (a_data));
}
public virtual HashResult ComputeShort (short a_data)
{
return ComputeBytes (BitConverter.GetBytes (a_data));
}
public virtual HashResult ComputeUShort (ushort a_data)
{
return ComputeBytes (BitConverter.GetBytes (a_data));
}
public virtual HashResult ComputeInt (int a_data)
{
return ComputeBytes (BitConverter.GetBytes (a_data));
}
public virtual HashResult ComputeUInt (uint a_data)
{
return ComputeBytes (BitConverter.GetBytes (a_data));
}
public virtual HashResult ComputeLong (long a_data)
{
return ComputeBytes (BitConverter.GetBytes (a_data));
}
public virtual HashResult ComputeULong (ulong a_data)
{
return ComputeBytes (BitConverter.GetBytes (a_data));
}
public virtual HashResult ComputeFloat (float a_data)
{
return ComputeBytes (BitConverter.GetBytes (a_data));
}
public virtual HashResult ComputeDouble (double a_data)
{
return ComputeBytes (BitConverter.GetBytes (a_data));
}
public virtual HashResult ComputeString (string a_data)
{
return ComputeBytes (Converters.ConvertStringToBytes (a_data));
}
public virtual HashResult ComputeString (string a_data, Encoding a_encoding)
{
return ComputeBytes (Converters.ConvertStringToBytes (a_data, a_encoding));
}
public virtual HashResult ComputeChars (char[] a_data)
{
return ComputeBytes (Converters.ConvertCharsToBytes (a_data));
}
public virtual HashResult ComputeShorts (short[] a_data)
{
return ComputeBytes (Converters.ConvertShortsToBytes (a_data));
}
public virtual HashResult ComputeUShorts (ushort[] a_data)
{
return ComputeBytes (Converters.ConvertUShortsToBytes (a_data));
}
public virtual HashResult ComputeInts (int[] a_data)
{
return ComputeBytes (Converters.ConvertIntsToBytes (a_data));
}
public virtual HashResult ComputeUInts (uint[] a_data)
{
return ComputeBytes (Converters.ConvertUIntsToBytes (a_data));
}
public virtual HashResult ComputeLongs (long[] a_data)
{
return ComputeBytes (Converters.ConvertLongsToBytes (a_data));
}
public virtual HashResult ComputeULongs (ulong[] a_data)
{
return ComputeBytes (Converters.ConvertULongsToBytes (a_data));
}
public virtual HashResult ComputeDoubles (double[] a_data)
{
return ComputeBytes (Converters.ConvertDoublesToBytes (a_data));
}
public virtual HashResult ComputeFloats (float[] a_data)
{
return ComputeBytes (Converters.ConvertFloatsToBytes (a_data));
}
public virtual HashResult ComputeBytes (byte[] a_data)
{
Initialize ();
TransformBytes (a_data);
HashResult result = TransformFinal ();
Initialize ();
return result;
}
public void TransformObject (object a_data)
{
if (a_data is byte)
TransformByte ((byte)a_data);
else if (a_data is short)
TransformShort ((short)a_data);
else if (a_data is ushort)
TransformUShort ((ushort)a_data);
else if (a_data is char)
TransformChar ((char)a_data);
else if (a_data is int)
TransformInt ((int)a_data);
else if (a_data is uint)
TransformUInt ((uint)a_data);
else if (a_data is long)
TransformLong ((long)a_data);
else if (a_data is ulong)
TransformULong ((ulong)a_data);
else if (a_data is float)
TransformFloat ((float)a_data);
else if (a_data is double)
TransformDouble ((double)a_data);
else if (a_data is string)
TransformString ((string)a_data);
else if (a_data is byte[])
TransformBytes ((byte[])a_data);
else if (a_data.GetType ().IsArray && a_data.GetType ().GetElementType () == typeof(short))
TransformShorts ((short[])a_data);
else if (a_data.GetType ().IsArray && a_data.GetType ().GetElementType () == typeof(ushort))
TransformUShorts ((ushort[])a_data);
else if (a_data is char[])
TransformChars ((char[])a_data);
else if (a_data.GetType ().IsArray && a_data.GetType ().GetElementType () == typeof(int))
TransformInts ((int[])a_data);
else if (a_data.GetType ().IsArray && a_data.GetType ().GetElementType () == typeof(uint))
TransformUInts ((uint[])a_data);
else if (a_data.GetType ().IsArray && a_data.GetType ().GetElementType () == typeof(long))
TransformLongs ((long[])a_data);
else if (a_data.GetType ().IsArray && a_data.GetType ().GetElementType () == typeof(ulong))
TransformULongs ((ulong[])a_data);
else if (a_data is float[])
TransformFloats ((float[])a_data);
else if (a_data is double[])
TransformDoubles ((double[])a_data);
else
throw new ArgumentException ();
}
public void TransformByte (byte a_data)
{
TransformBytes (new byte[] { a_data });
}
public void TransformChar (char a_data)
{
TransformBytes (BitConverter.GetBytes (a_data));
}
public void TransformShort (short a_data)
{
TransformBytes (BitConverter.GetBytes (a_data));
}
public void TransformUShort (ushort a_data)
{
TransformBytes (BitConverter.GetBytes (a_data));
}
public void TransformInt (int a_data)
{
TransformBytes (BitConverter.GetBytes (a_data));
}
public void TransformUInt (uint a_data)
{
TransformBytes (BitConverter.GetBytes (a_data));
}
public void TransformLong (long a_data)
{
TransformBytes (BitConverter.GetBytes (a_data));
}
public void TransformULong (ulong a_data)
{
TransformBytes (BitConverter.GetBytes (a_data));
}
public void TransformFloat (float a_data)
{
TransformBytes (BitConverter.GetBytes (a_data));
}
public void TransformDouble (double a_data)
{
TransformBytes (BitConverter.GetBytes (a_data));
}
public void TransformChars (char[] a_data)
{
TransformBytes (Converters.ConvertCharsToBytes (a_data));
}
public void TransformString (string a_data)
{
TransformBytes (Converters.ConvertStringToBytes (a_data));
}
public void TransformString (string a_data, Encoding a_encoding)
{
TransformBytes (Converters.ConvertStringToBytes (a_data, a_encoding));
}
public void TransformShorts (short[] a_data)
{
TransformBytes (Converters.ConvertShortsToBytes (a_data));
}
public void TransformUShorts (ushort[] a_data)
{
TransformBytes (Converters.ConvertUShortsToBytes (a_data));
}
public void TransformInts (int[] a_data)
{
TransformBytes (Converters.ConvertIntsToBytes (a_data));
}
public void TransformUInts (uint[] a_data)
{
TransformBytes (Converters.ConvertUIntsToBytes (a_data));
}
public void TransformLongs (long[] a_data)
{
TransformBytes (Converters.ConvertLongsToBytes (a_data));
}
public void TransformULongs (ulong[] a_data)
{
TransformBytes (Converters.ConvertULongsToBytes (a_data));
}
public void TransformDoubles (double[] a_data)
{
TransformBytes (Converters.ConvertDoublesToBytes (a_data));
}
public void TransformFloats (float[] a_data)
{
TransformBytes (Converters.ConvertFloatsToBytes (a_data));
}
public void TransformStream (Stream a_stream, long a_length = -1)
{
Debug.Assert ((a_length == -1 || a_length > 0));
if (a_stream.CanSeek) {
if (a_length > -1) {
if (a_stream.Position + a_length > a_stream.Length)
throw new IndexOutOfRangeException ();
}
if (a_stream.Position >= a_stream.Length)
return;
}
System.Collections.Generic.Queue<byte[]> queue =
new System.Collections.Generic.Queue<byte[]> ();
System.Threading.AutoResetEvent data_ready = new System.Threading.AutoResetEvent (false);
System.Threading.AutoResetEvent prepare_data = new System.Threading.AutoResetEvent (false);
Task reader = Task.Factory.StartNew (() => {
long total = 0;
for (; ;) {
byte[] data = new byte[BUFFER_SIZE];
int readed = a_stream.Read (data, 0, data.Length);
if ((a_length == -1) && (readed != BUFFER_SIZE))
data = data.SubArray (0, readed);
else if ((a_length != -1) && (total + readed >= a_length))
data = data.SubArray (0, (int)(a_length - total));
total += data.Length;
queue.Enqueue (data);
data_ready.Set ();
if (a_length == -1) {
if (readed != BUFFER_SIZE)
break;
} else if (a_length == total)
break;
else if (readed != BUFFER_SIZE)
throw new EndOfStreamException ();
prepare_data.WaitOne ();
}
});
Task hasher = Task.Factory.StartNew ((obj) => {
Hash h = (Hash)obj;
long total = 0;
for (; ;) {
data_ready.WaitOne ();
byte[] data = queue.Dequeue();
prepare_data.Set ();
total += data.Length;
if ((a_length == -1) || (total < a_length)) {
h.TransformBytes (data, 0, data.Length);
} else {
int readed = data.Length;
readed = readed - (int)(total - a_length);
h.TransformBytes (data, 0, data.Length);
}
if (a_length == -1) {
if (data.Length != BUFFER_SIZE)
break;
} else if (a_length == total)
break;
else if (data.Length != BUFFER_SIZE)
throw new EndOfStreamException ();
}
}, this);
reader.Wait ();
hasher.Wait ();
}
public HashResult ComputeStream (Stream a_stream, long a_length = -1)
{
Initialize ();
TransformStream (a_stream, a_length);
HashResult result = TransformFinal ();
Initialize ();
return result;
}
public void TransformBytes (byte[] a_data)
{
TransformBytes (a_data, 0, a_data.Length);
}
public void TransformBytes (byte[] a_data, int a_index)
{
Debug.Assert (a_index >= 0);
int length = a_data.Length - a_index;
Debug.Assert (length >= 0);
TransformBytes (a_data, a_index, length);
}
public abstract void Initialize ();
public abstract void TransformBytes (byte[] a_data, int a_index, int a_length);
public abstract HashResult TransformFinal ();
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Threading;
using System.Threading.Tasks;
using ASC.Common.Caching;
using ASC.Common.Logging;
using ASC.Common.Module;
using ASC.ElasticSearch.Service;
using Autofac;
namespace ASC.ElasticSearch
{
public class Launcher : IServiceController
{
private static readonly ICacheNotify Notify = AscCache.Notify;
private static Timer timer;
private static TimeSpan Period { get { return TimeSpan.FromMinutes(Settings.Default.Period); } }
private static ILog logger;
private static readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
internal static ServiceHost Searcher { get; private set; }
internal static bool IsStarted { get; private set; }
internal static string Indexing { get; private set; }
internal static DateTime? LastIndexed { get; private set; }
public void Start()
{
Searcher = new ServiceHost(typeof(Service.Service));
Searcher.Open();
logger = LogManager.GetLogger("ASC.Indexer");
try
{
Notify.Subscribe<AscCacheItem>(async (item, action) =>
{
while (IsStarted)
{
await Task.Delay(10000);
}
IndexAll(true);
});
}
catch (Exception e)
{
logger.Error("Subscribe on start", e);
}
var task = new Task(() =>
{
while (!FactoryIndexer.CheckState(false))
{
if (cancellationTokenSource.IsCancellationRequested)
{
return;
}
Thread.Sleep(10000);
}
CheckIfChange();
}, cancellationTokenSource.Token, TaskCreationOptions.LongRunning);
task.ConfigureAwait(false);
task.Start();
}
private static void CheckIfChange()
{
IsStarted = true;
var generic = typeof(BaseIndexer<>);
var products = FactoryIndexer.Builder.Resolve<IEnumerable<Wrapper>>()
.Select(r => (IIndexer)Activator.CreateInstance(generic.MakeGenericType(r.GetType()), r))
.ToList();
products.ForEach(product =>
{
try
{
if (!IsStarted) return;
logger.DebugFormat("Product check {0}", product.IndexName);
Indexing = product.IndexName;
product.Check();
}
catch (Exception e)
{
logger.Error(e);
logger.ErrorFormat("Product check {0}", product.IndexName);
}
});
IsStarted = false;
Indexing = null;
timer = new Timer(_ => IndexAll(), null, TimeSpan.Zero, TimeSpan.Zero);
}
private static void IndexAll(bool reindex = false)
{
try
{
timer.Change(Timeout.Infinite, Timeout.Infinite);
IsStarted = true;
var generic = typeof(BaseIndexer<>);
var products = FactoryIndexer.Builder.Resolve<IEnumerable<Wrapper>>()
.Select(r => (IIndexer)Activator.CreateInstance(generic.MakeGenericType(r.GetType()), r))
.ToList();
if (reindex)
{
Parallel.ForEach(products, product =>
{
try
{
if (!IsStarted) return;
logger.DebugFormat("Product reindex {0}", product.IndexName);
product.ReIndex();
}
catch (Exception e)
{
logger.Error(e);
logger.ErrorFormat("Product reindex {0}", product.IndexName);
}
});
}
Parallel.ForEach(products, product =>
{
try
{
if (!IsStarted) return;
logger.DebugFormat("Product {0}", product.IndexName);
Indexing = product.IndexName;
product.IndexAll();
}
catch (Exception e)
{
logger.Error(e);
logger.ErrorFormat("Product {0}", product.IndexName);
}
});
timer.Change(Period, Period);
LastIndexed = DateTime.UtcNow;
IsStarted = false;
Indexing = null;
}
catch (Exception e)
{
logger.Fatal("IndexAll", e);
throw;
}
}
public void Stop()
{
logger.Debug("Stop");
if (Searcher != null)
{
Searcher.Close();
Searcher = null;
}
IsStarted = false;
if (timer != null)
{
timer.Dispose();
}
cancellationTokenSource.Cancel();
}
}
}
| |
namespace StripeTests
{
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Stripe;
using Xunit;
public class SubscriptionScheduleServiceTest : BaseStripeTest
{
private const string ScheduleId = "sub_sched_123";
private readonly SubscriptionScheduleService service;
private readonly SubscriptionScheduleCancelOptions cancelOptions;
private readonly SubscriptionScheduleCreateOptions createOptions;
private readonly SubscriptionScheduleListOptions listOptions;
private readonly SubscriptionScheduleReleaseOptions releaseOptions;
private readonly SubscriptionScheduleUpdateOptions updateOptions;
public SubscriptionScheduleServiceTest(
StripeMockFixture stripeMockFixture,
MockHttpClientFixture mockHttpClientFixture)
: base(stripeMockFixture, mockHttpClientFixture)
{
this.service = new SubscriptionScheduleService(this.StripeClient);
this.cancelOptions = new SubscriptionScheduleCancelOptions
{
InvoiceNow = true,
Prorate = true,
};
this.createOptions = new SubscriptionScheduleCreateOptions
{
Customer = "cus_123",
StartDate = SubscriptionScheduleStartDate.Now,
DefaultSettings = new SubscriptionScheduleDefaultSettingsOptions
{
CollectionMethod = "send_invoice",
},
Phases = new List<SubscriptionSchedulePhaseOptions>
{
new SubscriptionSchedulePhaseOptions
{
Items = new List<SubscriptionSchedulePhaseItemOptions>
{
new SubscriptionSchedulePhaseItemOptions
{
Price = "price_123",
},
},
},
},
};
this.releaseOptions = new SubscriptionScheduleReleaseOptions
{
PreserveCancelDate = true,
};
this.updateOptions = new SubscriptionScheduleUpdateOptions
{
Metadata = new Dictionary<string, string>
{
{ "key", "value" },
},
};
this.listOptions = new SubscriptionScheduleListOptions
{
Limit = 1,
};
}
[Fact]
public void Cancel()
{
var subscription = this.service.Cancel(ScheduleId, this.cancelOptions);
this.AssertRequest(HttpMethod.Post, "/v1/subscription_schedules/sub_sched_123/cancel");
Assert.NotNull(subscription);
Assert.Equal("subscription_schedule", subscription.Object);
}
[Fact]
public async Task CancelAsync()
{
var subscription = await this.service.CancelAsync(ScheduleId, this.cancelOptions);
this.AssertRequest(HttpMethod.Post, "/v1/subscription_schedules/sub_sched_123/cancel");
Assert.NotNull(subscription);
Assert.Equal("subscription_schedule", subscription.Object);
}
[Fact]
public void Create()
{
var subscription = this.service.Create(this.createOptions);
this.AssertRequest(HttpMethod.Post, "/v1/subscription_schedules");
Assert.NotNull(subscription);
Assert.Equal("subscription_schedule", subscription.Object);
}
[Fact]
public async Task CreateAsync()
{
var subscription = await this.service.CreateAsync(this.createOptions);
this.AssertRequest(HttpMethod.Post, "/v1/subscription_schedules");
Assert.NotNull(subscription);
Assert.Equal("subscription_schedule", subscription.Object);
}
[Fact]
public void Get()
{
var subscription = this.service.Get(ScheduleId);
this.AssertRequest(HttpMethod.Get, "/v1/subscription_schedules/sub_sched_123");
Assert.NotNull(subscription);
Assert.Equal("subscription_schedule", subscription.Object);
}
[Fact]
public async Task GetAsync()
{
var subscription = await this.service.GetAsync(ScheduleId);
this.AssertRequest(HttpMethod.Get, "/v1/subscription_schedules/sub_sched_123");
Assert.NotNull(subscription);
Assert.Equal("subscription_schedule", subscription.Object);
}
[Fact]
public void List()
{
var subscriptions = this.service.List(this.listOptions);
this.AssertRequest(HttpMethod.Get, "/v1/subscription_schedules");
Assert.NotNull(subscriptions);
Assert.Equal("list", subscriptions.Object);
Assert.Single(subscriptions.Data);
Assert.Equal("subscription_schedule", subscriptions.Data[0].Object);
}
[Fact]
public async Task ListAsync()
{
var subscriptions = await this.service.ListAsync(this.listOptions);
this.AssertRequest(HttpMethod.Get, "/v1/subscription_schedules");
Assert.NotNull(subscriptions);
Assert.Equal("list", subscriptions.Object);
Assert.Single(subscriptions.Data);
Assert.Equal("subscription_schedule", subscriptions.Data[0].Object);
}
[Fact]
public void ListAutoPaging()
{
var subscription = this.service.ListAutoPaging(this.listOptions).First();
Assert.NotNull(subscription);
Assert.Equal("subscription_schedule", subscription.Object);
}
[Fact]
public async Task ListAutoPagingAsync()
{
var subscription = await this.service.ListAutoPagingAsync(this.listOptions).FirstAsync();
Assert.NotNull(subscription);
Assert.Equal("subscription_schedule", subscription.Object);
}
[Fact]
public void Release()
{
var subscription = this.service.Release(ScheduleId, this.releaseOptions);
this.AssertRequest(HttpMethod.Post, "/v1/subscription_schedules/sub_sched_123/release");
Assert.NotNull(subscription);
Assert.Equal("subscription_schedule", subscription.Object);
}
[Fact]
public async Task ReleaseAsync()
{
var subscription = await this.service.ReleaseAsync(ScheduleId, this.releaseOptions);
this.AssertRequest(HttpMethod.Post, "/v1/subscription_schedules/sub_sched_123/release");
Assert.NotNull(subscription);
Assert.Equal("subscription_schedule", subscription.Object);
}
[Fact]
public void Update()
{
var subscription = this.service.Update(ScheduleId, this.updateOptions);
this.AssertRequest(HttpMethod.Post, "/v1/subscription_schedules/sub_sched_123");
Assert.NotNull(subscription);
Assert.Equal("subscription_schedule", subscription.Object);
}
[Fact]
public async Task UpdateAsync()
{
var subscription = await this.service.UpdateAsync(ScheduleId, this.updateOptions);
this.AssertRequest(HttpMethod.Post, "/v1/subscription_schedules/sub_sched_123");
Assert.NotNull(subscription);
Assert.Equal("subscription_schedule", subscription.Object);
}
}
}
| |
// 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.
namespace System.Text
{
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System;
using System.Diagnostics.Contracts;
// An Encoder is used to encode a sequence of blocks of characters into
// a sequence of blocks of bytes. Following instantiation of an encoder,
// sequential blocks of characters are converted into blocks of bytes through
// calls to the GetBytes method. The encoder maintains state between the
// conversions, allowing it to correctly encode character sequences that span
// adjacent blocks.
//
// Instances of specific implementations of the Encoder abstract base
// class are typically obtained through calls to the GetEncoder method
// of Encoding objects.
//
[Serializable]
internal class EncoderNLS : Encoder, ISerializable
{
// Need a place for the last left over character, most of our encodings use this
internal char charLeftOver;
protected Encoding m_encoding;
[NonSerialized] protected bool m_mustFlush;
[NonSerialized] internal bool m_throwOnOverflow;
[NonSerialized] internal int m_charsUsed;
#region Serialization
// Constructor called by serialization. called during deserialization.
internal EncoderNLS(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException(
String.Format(
System.Globalization.CultureInfo.CurrentCulture,
Environment.GetResourceString("NotSupported_TypeCannotDeserialized"), this.GetType()));
}
// ISerializable implementation. called during serialization.
[System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
SerializeEncoder(info);
info.AddValue("encoding", this.m_encoding);
info.AddValue("charLeftOver", this.charLeftOver);
info.SetType(typeof(Encoding.DefaultEncoder));
}
#endregion Serialization
internal EncoderNLS(Encoding encoding)
{
this.m_encoding = encoding;
this.m_fallback = this.m_encoding.EncoderFallback;
this.Reset();
}
// This one is used when deserializing (like UTF7Encoding.Encoder)
internal EncoderNLS()
{
this.m_encoding = null;
this.Reset();
}
public override void Reset()
{
this.charLeftOver = (char)0;
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetByteCount(char[] chars, int index, int count, bool flush)
{
// Validate input parameters
if (chars == null)
throw new ArgumentNullException(nameof(chars),
Environment.GetResourceString("ArgumentNull_Array"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (chars.Length - index < count)
throw new ArgumentOutOfRangeException(nameof(chars),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
// Avoid empty input problem
if (chars.Length == 0)
chars = new char[1];
// Just call the pointer version
int result = -1;
fixed (char* pChars = chars)
{
result = GetByteCount(pChars + index, count, flush);
}
return result;
}
[System.Security.SecurityCritical] // auto-generated
public unsafe override int GetByteCount(char* chars, int count, bool flush)
{
// Validate input parameters
if (chars == null)
throw new ArgumentNullException(nameof(chars),
Environment.GetResourceString("ArgumentNull_Array"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
this.m_mustFlush = flush;
this.m_throwOnOverflow = true;
return m_encoding.GetByteCount(chars, count, this);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, bool flush)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
Environment.GetResourceString("ArgumentNull_Array"));
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex<0 ? nameof(charIndex) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException(nameof(byteIndex),
Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
if (chars.Length == 0)
chars = new char[1];
int byteCount = bytes.Length - byteIndex;
if (bytes.Length == 0)
bytes = new byte[1];
// Just call pointer version
fixed (char* pChars = chars)
fixed (byte* pBytes = bytes)
// Remember that charCount is # to decode, not size of array.
return GetBytes(pChars + charIndex, charCount,
pBytes + byteIndex, byteCount, flush);
}
[System.Security.SecurityCritical] // auto-generated
public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
Environment.GetResourceString("ArgumentNull_Array"));
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
this.m_mustFlush = flush;
this.m_throwOnOverflow = true;
return m_encoding.GetBytes(chars, charCount, bytes, byteCount, this);
}
// This method is used when your output buffer might not be large enough for the entire result.
// Just call the pointer version. (This gets bytes)
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe void Convert(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, int byteCount, bool flush,
out int charsUsed, out int bytesUsed, out bool completed)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
Environment.GetResourceString("ArgumentNull_Array"));
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex<0 ? nameof(charIndex) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
// Avoid empty input problem
if (chars.Length == 0)
chars = new char[1];
if (bytes.Length == 0)
bytes = new byte[1];
// Just call the pointer version (can't do this for non-msft encoders)
fixed (char* pChars = chars)
{
fixed (byte* pBytes = bytes)
{
Convert(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, flush,
out charsUsed, out bytesUsed, out completed);
}
}
}
// This is the version that uses pointers. We call the base encoding worker function
// after setting our appropriate internal variables. This is getting bytes
[System.Security.SecurityCritical] // auto-generated
public override unsafe void Convert(char* chars, int charCount,
byte* bytes, int byteCount, bool flush,
out int charsUsed, out int bytesUsed, out bool completed)
{
// Validate input parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
Environment.GetResourceString("ArgumentNull_Array"));
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount<0 ? nameof(charCount) : nameof(byteCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// We don't want to throw
this.m_mustFlush = flush;
this.m_throwOnOverflow = false;
this.m_charsUsed = 0;
// Do conversion
bytesUsed = this.m_encoding.GetBytes(chars, charCount, bytes, byteCount, this);
charsUsed = this.m_charsUsed;
// Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed
completed = (charsUsed == charCount) && (!flush || !this.HasState) &&
(m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0);
// Our data thingys are now full, we can return
}
public Encoding Encoding
{
get
{
return m_encoding;
}
}
public bool MustFlush
{
get
{
return m_mustFlush;
}
}
// Anything left in our encoder?
internal virtual bool HasState
{
get
{
return (this.charLeftOver != (char)0);
}
}
// Allow encoding to clear our must flush instead of throwing (in ThrowBytesOverflow)
internal void ClearMustFlush()
{
m_mustFlush = false;
}
}
}
| |
// Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Linq;
using System.Net;
using EventStore.Core.Authentication;
using EventStore.Core.Bus;
using EventStore.Core.Helpers;
using EventStore.Core.Messages;
using EventStore.Core.Messaging;
using EventStore.Core.Services;
using EventStore.Core.Services.TimerService;
using EventStore.Core.Services.Transport.Http;
using EventStore.Core.Services.Transport.Http.Authentication;
using EventStore.Core.Services.Transport.Http.Controllers;
using EventStore.Core.Services.Transport.Tcp;
using EventStore.Core.Settings;
namespace EventStore.Web.Playground
{
public class PlaygroundVNode
{
private QueuedHandler MainQueue
{
get { return _mainQueue; }
}
private InMemoryBus Bus
{
get { return _mainBus; }
}
private HttpService HttpService
{
get { return _httpService; }
}
private TimerService TimerService
{
get { return _timerService; }
}
private readonly IPEndPoint _tcpEndPoint;
private readonly IPEndPoint _httpEndPoint;
private readonly QueuedHandler _mainQueue;
private readonly InMemoryBus _mainBus;
private readonly PlaygroundVNodeController _controller;
private readonly HttpService _httpService;
private readonly TimerService _timerService;
private readonly InMemoryBus[] _workerBuses;
private readonly MultiQueuedHandler _workersHandler;
public PlaygroundVNode(PlaygroundVNodeSettings vNodeSettings)
{
_tcpEndPoint = vNodeSettings.ExternalTcpEndPoint;
_httpEndPoint = vNodeSettings.ExternalHttpEndPoint;
_mainBus = new InMemoryBus("MainBus");
_controller = new PlaygroundVNodeController(Bus, _httpEndPoint);
_mainQueue = new QueuedHandler(_controller, "MainQueue");
_controller.SetMainQueue(MainQueue);
// MONITORING
var monitoringInnerBus = new InMemoryBus("MonitoringInnerBus", watchSlowMsg: false);
var monitoringQueue = new QueuedHandler(
monitoringInnerBus, "MonitoringQueue", true, TimeSpan.FromMilliseconds(100));
Bus.Subscribe(monitoringQueue.WidenFrom<SystemMessage.SystemInit, Message>());
Bus.Subscribe(monitoringQueue.WidenFrom<SystemMessage.StateChangeMessage, Message>());
Bus.Subscribe(monitoringQueue.WidenFrom<SystemMessage.BecomeShuttingDown, Message>());
// MISC WORKERS
_workerBuses = Enumerable.Range(0, vNodeSettings.WorkerThreads).Select(queueNum =>
new InMemoryBus(string.Format("Worker #{0} Bus", queueNum + 1),
watchSlowMsg: true,
slowMsgThreshold: TimeSpan.FromMilliseconds(50))).ToArray();
_workersHandler = new MultiQueuedHandler(
vNodeSettings.WorkerThreads,
queueNum => new QueuedHandlerThreadPool(_workerBuses[queueNum],
string.Format("Worker #{0}", queueNum + 1),
groupName: "Workers",
watchSlowMsg: true,
slowMsgThreshold: TimeSpan.FromMilliseconds(50)));
// AUTHENTICATION INFRASTRUCTURE
var dispatcher = new IODispatcher(_mainBus, new PublishEnvelope(_workersHandler, crossThread: true));
var passwordHashAlgorithm = new Rfc2898PasswordHashAlgorithm();
var internalAuthenticationProvider = new InternalAuthenticationProvider(dispatcher, passwordHashAlgorithm, 1000);
var passwordChangeNotificationReader = new PasswordChangeNotificationReader(_mainQueue, dispatcher);
_mainBus.Subscribe<SystemMessage.SystemStart>(passwordChangeNotificationReader);
_mainBus.Subscribe<SystemMessage.BecomeShutdown>(passwordChangeNotificationReader);
_mainBus.Subscribe(internalAuthenticationProvider);
_mainBus.Subscribe(dispatcher);
SubscribeWorkers(bus =>
{
bus.Subscribe(dispatcher.ForwardReader);
bus.Subscribe(dispatcher.BackwardReader);
bus.Subscribe(dispatcher.Writer);
bus.Subscribe(dispatcher.StreamDeleter);
});
// TCP
var tcpService = new TcpService(
MainQueue, _tcpEndPoint, _workersHandler, TcpServiceType.External, TcpSecurityType.Normal, new ClientTcpDispatcher(),
ESConsts.ExternalHeartbeatInterval, ESConsts.ExternalHeartbeatTimeout, internalAuthenticationProvider, null);
Bus.Subscribe<SystemMessage.SystemInit>(tcpService);
Bus.Subscribe<SystemMessage.SystemStart>(tcpService);
Bus.Subscribe<SystemMessage.BecomeShuttingDown>(tcpService);
// HTTP
{
var httpAuthenticationProviders = new HttpAuthenticationProvider[]
{
new BasicHttpAuthenticationProvider(internalAuthenticationProvider),
new TrustedHttpAuthenticationProvider(),
new AnonymousHttpAuthenticationProvider()
};
var httpPipe = new HttpMessagePipe();
var httpSendService = new HttpSendService(httpPipe, forwardRequests: false);
_mainBus.Subscribe<SystemMessage.StateChangeMessage>(httpSendService);
_mainBus.Subscribe(new WideningHandler<HttpMessage.SendOverHttp, Message>(_workersHandler));
SubscribeWorkers(bus =>
{
bus.Subscribe<HttpMessage.HttpSend>(httpSendService);
bus.Subscribe<HttpMessage.HttpSendPart>(httpSendService);
bus.Subscribe<HttpMessage.HttpBeginSend>(httpSendService);
bus.Subscribe<HttpMessage.HttpEndSend>(httpSendService);
bus.Subscribe<HttpMessage.SendOverHttp>(httpSendService);
});
_httpService = new HttpService(ServiceAccessibility.Private, _mainQueue, new TrieUriRouter(),
_workersHandler, vNodeSettings.HttpPrefixes);
_mainBus.Subscribe<SystemMessage.SystemInit>(_httpService);
_mainBus.Subscribe<SystemMessage.BecomeShuttingDown>(_httpService);
_mainBus.Subscribe<HttpMessage.PurgeTimedOutRequests>(_httpService);
HttpService.SetupController(new AdminController(_mainQueue));
HttpService.SetupController(new PingController());
HttpService.SetupController(new StatController(monitoringQueue, _workersHandler));
HttpService.SetupController(new AtomController(httpSendService, _mainQueue, _workersHandler));
HttpService.SetupController(new GuidController(_mainQueue));
HttpService.SetupController(new UsersController(httpSendService, _mainQueue, _workersHandler));
SubscribeWorkers(bus => HttpService.CreateAndSubscribePipeline(bus, httpAuthenticationProviders));
}
// TIMER
_timerService = new TimerService(new ThreadBasedScheduler(new RealTimeProvider()));
Bus.Subscribe<TimerMessage.Schedule>(TimerService);
monitoringQueue.Start();
MainQueue.Start();
}
private void SubscribeWorkers(Action<InMemoryBus> setup)
{
foreach (var workerBus in _workerBuses)
{
setup(workerBus);
}
}
public void Start()
{
MainQueue.Publish(new SystemMessage.SystemInit());
}
public void Stop(bool exitProcess)
{
MainQueue.Publish(new ClientMessage.RequestShutdown(exitProcess));
}
public override string ToString()
{
return string.Format("[{0}, {1}]", _tcpEndPoint, _httpEndPoint);
}
}
}
| |
/*
* 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 ec2-2015-04-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.EC2.Model
{
/// <summary>
/// Container for the parameters to the DescribeReservedInstancesOfferings operation.
/// Describes Reserved Instance offerings that are available for purchase. With Reserved
/// Instances, you purchase the right to launch instances for a period of time. During
/// that time period, you do not receive insufficient capacity errors, and you pay a lower
/// usage rate than the rate charged for On-Demand instances for the actual time used.
///
///
/// <para>
/// For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ri-market-general.html">Reserved
/// Instance Marketplace</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
/// </summary>
public partial class DescribeReservedInstancesOfferingsRequest : AmazonEC2Request
{
private string _availabilityZone;
private List<Filter> _filters = new List<Filter>();
private bool? _includeMarketplace;
private Tenancy _instanceTenancy;
private InstanceType _instanceType;
private long? _maxDuration;
private int? _maxInstanceCount;
private int? _maxResults;
private long? _minDuration;
private string _nextToken;
private OfferingTypeValues _offeringType;
private RIProductDescription _productDescription;
private List<string> _reservedInstancesOfferingIds = new List<string>();
/// <summary>
/// Gets and sets the property AvailabilityZone.
/// <para>
/// The Availability Zone in which the Reserved Instance can be used.
/// </para>
/// </summary>
public string AvailabilityZone
{
get { return this._availabilityZone; }
set { this._availabilityZone = value; }
}
// Check to see if AvailabilityZone property is set
internal bool IsSetAvailabilityZone()
{
return this._availabilityZone != null;
}
/// <summary>
/// Gets and sets the property Filters.
/// <para>
/// One or more filters.
/// </para>
/// <ul> <li>
/// <para>
/// <code>availability-zone</code> - The Availability Zone where the Reserved Instance
/// can be used.
/// </para>
/// </li> <li>
/// <para>
/// <code>duration</code> - The duration of the Reserved Instance (for example, one year
/// or three years), in seconds (<code>31536000</code> | <code>94608000</code>).
/// </para>
/// </li> <li>
/// <para>
/// <code>fixed-price</code> - The purchase price of the Reserved Instance (for example,
/// 9800.0).
/// </para>
/// </li> <li>
/// <para>
/// <code>instance-type</code> - The instance type on which the Reserved Instance can
/// be used.
/// </para>
/// </li> <li>
/// <para>
/// <code>marketplace</code> - Set to <code>true</code> to show only Reserved Instance
/// Marketplace offerings. When this filter is not used, which is the default behavior,
/// all offerings from AWS and Reserved Instance Marketplace are listed.
/// </para>
/// </li> <li>
/// <para>
/// <code>product-description</code> - The Reserved Instance product platform description.
/// Instances that include <code>(Amazon VPC)</code> in the product platform description
/// will only be displayed to EC2-Classic account holders and are for use with Amazon
/// VPC. (<code>Linux/UNIX</code> | <code>Linux/UNIX (Amazon VPC)</code> | <code>SUSE
/// Linux</code> | <code>SUSE Linux (Amazon VPC)</code> | <code>Red Hat Enterprise Linux</code>
/// | <code>Red Hat Enterprise Linux (Amazon VPC)</code> | <code>Windows</code> | <code>Windows
/// (Amazon VPC)</code> | <code>Windows with SQL Server Standard</code> | <code>Windows
/// with SQL Server Standard (Amazon VPC)</code> | <code>Windows with SQL Server Web</code>
/// | <code> Windows with SQL Server Web (Amazon VPC)</code> | <code>Windows with SQL
/// Server Enterprise</code> | <code>Windows with SQL Server Enterprise (Amazon VPC)</code>)
///
/// </para>
/// </li> <li>
/// <para>
/// <code>reserved-instances-offering-id</code> - The Reserved Instances offering ID.
/// </para>
/// </li> <li>
/// <para>
/// <code>usage-price</code> - The usage price of the Reserved Instance, per hour (for
/// example, 0.84).
/// </para>
/// </li> </ul>
/// </summary>
public List<Filter> Filters
{
get { return this._filters; }
set { this._filters = value; }
}
// Check to see if Filters property is set
internal bool IsSetFilters()
{
return this._filters != null && this._filters.Count > 0;
}
/// <summary>
/// Gets and sets the property IncludeMarketplace.
/// <para>
/// Include Marketplace offerings in the response.
/// </para>
/// </summary>
public bool IncludeMarketplace
{
get { return this._includeMarketplace.GetValueOrDefault(); }
set { this._includeMarketplace = value; }
}
// Check to see if IncludeMarketplace property is set
internal bool IsSetIncludeMarketplace()
{
return this._includeMarketplace.HasValue;
}
/// <summary>
/// Gets and sets the property InstanceTenancy.
/// <para>
/// The tenancy of the Reserved Instance offering. A Reserved Instance with <code>dedicated</code>
/// tenancy runs on single-tenant hardware and can only be launched within a VPC.
/// </para>
///
/// <para>
/// Default: <code>default</code>
/// </para>
/// </summary>
public Tenancy InstanceTenancy
{
get { return this._instanceTenancy; }
set { this._instanceTenancy = value; }
}
// Check to see if InstanceTenancy property is set
internal bool IsSetInstanceTenancy()
{
return this._instanceTenancy != null;
}
/// <summary>
/// Gets and sets the property InstanceType.
/// <para>
/// The instance type on which the Reserved Instance can be used. For more information,
/// see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html">Instance
/// Types</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
/// </summary>
public InstanceType InstanceType
{
get { return this._instanceType; }
set { this._instanceType = value; }
}
// Check to see if InstanceType property is set
internal bool IsSetInstanceType()
{
return this._instanceType != null;
}
/// <summary>
/// Gets and sets the property MaxDuration.
/// <para>
/// The maximum duration (in seconds) to filter when searching for offerings.
/// </para>
///
/// <para>
/// Default: 94608000 (3 years)
/// </para>
/// </summary>
public long MaxDuration
{
get { return this._maxDuration.GetValueOrDefault(); }
set { this._maxDuration = value; }
}
// Check to see if MaxDuration property is set
internal bool IsSetMaxDuration()
{
return this._maxDuration.HasValue;
}
/// <summary>
/// Gets and sets the property MaxInstanceCount.
/// <para>
/// The maximum number of instances to filter when searching for offerings.
/// </para>
///
/// <para>
/// Default: 20
/// </para>
/// </summary>
public int MaxInstanceCount
{
get { return this._maxInstanceCount.GetValueOrDefault(); }
set { this._maxInstanceCount = value; }
}
// Check to see if MaxInstanceCount property is set
internal bool IsSetMaxInstanceCount()
{
return this._maxInstanceCount.HasValue;
}
/// <summary>
/// Gets and sets the property MaxResults.
/// <para>
/// The maximum number of results to return for the request in a single page. The remaining
/// results of the initial request can be seen by sending another request with the returned
/// <code>NextToken</code> value. The maximum is 100.
/// </para>
///
/// <para>
/// Default: 100
/// </para>
/// </summary>
public int MaxResults
{
get { return this._maxResults.GetValueOrDefault(); }
set { this._maxResults = value; }
}
// Check to see if MaxResults property is set
internal bool IsSetMaxResults()
{
return this._maxResults.HasValue;
}
/// <summary>
/// Gets and sets the property MinDuration.
/// <para>
/// The minimum duration (in seconds) to filter when searching for offerings.
/// </para>
///
/// <para>
/// Default: 2592000 (1 month)
/// </para>
/// </summary>
public long MinDuration
{
get { return this._minDuration.GetValueOrDefault(); }
set { this._minDuration = value; }
}
// Check to see if MinDuration property is set
internal bool IsSetMinDuration()
{
return this._minDuration.HasValue;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// The token to retrieve the next page of results.
/// </para>
/// </summary>
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
/// <summary>
/// Gets and sets the property OfferingType.
/// <para>
/// The Reserved Instance offering type. If you are using tools that predate the 2011-11-01
/// API version, you only have access to the <code>Medium Utilization</code> Reserved
/// Instance offering type.
/// </para>
/// </summary>
public OfferingTypeValues OfferingType
{
get { return this._offeringType; }
set { this._offeringType = value; }
}
// Check to see if OfferingType property is set
internal bool IsSetOfferingType()
{
return this._offeringType != null;
}
/// <summary>
/// Gets and sets the property ProductDescription.
/// <para>
/// The Reserved Instance product platform description. Instances that include <code>(Amazon
/// VPC)</code> in the description are for use with Amazon VPC.
/// </para>
/// </summary>
public RIProductDescription ProductDescription
{
get { return this._productDescription; }
set { this._productDescription = value; }
}
// Check to see if ProductDescription property is set
internal bool IsSetProductDescription()
{
return this._productDescription != null;
}
/// <summary>
/// Gets and sets the property ReservedInstancesOfferingIds.
/// <para>
/// One or more Reserved Instances offering IDs.
/// </para>
/// </summary>
public List<string> ReservedInstancesOfferingIds
{
get { return this._reservedInstancesOfferingIds; }
set { this._reservedInstancesOfferingIds = value; }
}
// Check to see if ReservedInstancesOfferingIds property is set
internal bool IsSetReservedInstancesOfferingIds()
{
return this._reservedInstancesOfferingIds != null && this._reservedInstancesOfferingIds.Count > 0;
}
}
}
| |
// <copyright file="DesiredCapabilities.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// </copyright>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.Remote
{
/// <summary>
/// Internal class to specify the requested capabilities of the browser for <see cref="IWebDriver"/>.
/// </summary>
[Obsolete("Use of DesiredCapabilities has been deprecated in favor of browser-specific Options classes")]
internal class DesiredCapabilities : IWritableCapabilities, IHasCapabilitiesDictionary
{
private readonly Dictionary<string, object> capabilities = new Dictionary<string, object>();
/// <summary>
/// Initializes a new instance of the <see cref="DesiredCapabilities"/> class
/// </summary>
/// <param name="browser">Name of the browser e.g. firefox, internet explorer, safari</param>
/// <param name="version">Version of the browser</param>
/// <param name="platform">The platform it works on</param>
public DesiredCapabilities(string browser, string version, Platform platform)
{
this.SetCapability(CapabilityType.BrowserName, browser);
this.SetCapability(CapabilityType.Version, version);
this.SetCapability(CapabilityType.Platform, platform);
}
/// <summary>
/// Initializes a new instance of the <see cref="DesiredCapabilities"/> class
/// </summary>
public DesiredCapabilities()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DesiredCapabilities"/> class
/// </summary>
/// <param name="rawMap">Dictionary of items for the remote driver</param>
/// <example>
/// <code>
/// DesiredCapabilities capabilities = new DesiredCapabilities(new Dictionary<![CDATA[<string,object>]]>(){["browserName","firefox"],["version",string.Empty],["javaScript",true]});
/// </code>
/// </example>
public DesiredCapabilities(Dictionary<string, object> rawMap)
{
if (rawMap != null)
{
foreach (string key in rawMap.Keys)
{
if (key == CapabilityType.Platform)
{
object raw = rawMap[CapabilityType.Platform];
string rawAsString = raw as string;
Platform rawAsPlatform = raw as Platform;
if (rawAsString != null)
{
this.SetCapability(CapabilityType.Platform, Platform.FromString(rawAsString));
}
else if (rawAsPlatform != null)
{
this.SetCapability(CapabilityType.Platform, rawAsPlatform);
}
}
else
{
this.SetCapability(key, rawMap[key]);
}
}
}
}
/// <summary>
/// Initializes a new instance of the <see cref="DesiredCapabilities"/> class
/// </summary>
/// <param name="browser">Name of the browser e.g. firefox, internet explorer, safari</param>
/// <param name="version">Version of the browser</param>
/// <param name="platform">The platform it works on</param>
/// <param name="isSpecCompliant">Sets a value indicating whether the capabilities are
/// compliant with the W3C WebDriver specification.</param>
internal DesiredCapabilities(string browser, string version, Platform platform, bool isSpecCompliant)
{
this.SetCapability(CapabilityType.BrowserName, browser);
this.SetCapability(CapabilityType.Version, version);
this.SetCapability(CapabilityType.Platform, platform);
}
/// <summary>
/// Gets the browser name
/// </summary>
public string BrowserName
{
get
{
string name = string.Empty;
object capabilityValue = this.GetCapability(CapabilityType.BrowserName);
if (capabilityValue != null)
{
name = capabilityValue.ToString();
}
return name;
}
}
/// <summary>
/// Gets or sets the platform
/// </summary>
public Platform Platform
{
get
{
return this.GetCapability(CapabilityType.Platform) as Platform ?? new Platform(PlatformType.Any);
}
set
{
this.SetCapability(CapabilityType.Platform, value);
}
}
/// <summary>
/// Gets the browser version
/// </summary>
public string Version
{
get
{
string browserVersion = string.Empty;
object capabilityValue = this.GetCapability(CapabilityType.Version);
if (capabilityValue != null)
{
browserVersion = capabilityValue.ToString();
}
return browserVersion;
}
}
/// <summary>
/// Gets or sets a value indicating whether the browser accepts SSL certificates.
/// </summary>
public bool AcceptInsecureCerts
{
get
{
bool acceptSSLCerts = false;
object capabilityValue = this.GetCapability(CapabilityType.AcceptInsecureCertificates);
if (capabilityValue != null)
{
acceptSSLCerts = (bool)capabilityValue;
}
return acceptSSLCerts;
}
set
{
this.SetCapability(CapabilityType.AcceptInsecureCertificates, value);
}
}
/// <summary>
/// Gets the underlying Dictionary for a given set of capabilities.
/// </summary>
IDictionary<string, object> IHasCapabilitiesDictionary.CapabilitiesDictionary
{
get { return this.CapabilitiesDictionary; }
}
/// <summary>
/// Gets the underlying Dictionary for a given set of capabilities.
/// </summary>
internal IDictionary<string, object> CapabilitiesDictionary
{
get { return new ReadOnlyDictionary<string, object>(this.capabilities); }
}
/// <summary>
/// Gets the capability value with the specified name.
/// </summary>
/// <param name="capabilityName">The name of the capability to get.</param>
/// <returns>The value of the capability.</returns>
/// <exception cref="ArgumentException">
/// The specified capability name is not in the set of capabilities.
/// </exception>
public object this[string capabilityName]
{
get
{
if (!this.capabilities.ContainsKey(capabilityName))
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "The capability {0} is not present in this set of capabilities", capabilityName));
}
return this.capabilities[capabilityName];
}
}
/// <summary>
/// Gets a value indicating whether the browser has a given capability.
/// </summary>
/// <param name="capability">The capability to get.</param>
/// <returns>Returns <see langword="true"/> if the browser has the capability; otherwise, <see langword="false"/>.</returns>
public bool HasCapability(string capability)
{
return this.capabilities.ContainsKey(capability);
}
/// <summary>
/// Gets a capability of the browser.
/// </summary>
/// <param name="capability">The capability to get.</param>
/// <returns>An object associated with the capability, or <see langword="null"/>
/// if the capability is not set on the browser.</returns>
public object GetCapability(string capability)
{
object capabilityValue = null;
if (this.capabilities.ContainsKey(capability))
{
capabilityValue = this.capabilities[capability];
string capabilityValueString = capabilityValue as string;
if (capability == CapabilityType.Platform && capabilityValueString != null)
{
capabilityValue = Platform.FromString(capabilityValue.ToString());
}
}
return capabilityValue;
}
/// <summary>
/// Sets a capability of the browser.
/// </summary>
/// <param name="capability">The capability to get.</param>
/// <param name="capabilityValue">The value for the capability.</param>
public void SetCapability(string capability, object capabilityValue)
{
// Handle the special case of Platform objects. These should
// be stored in the underlying dictionary as their protocol
// string representation.
Platform platformCapabilityValue = capabilityValue as Platform;
if (platformCapabilityValue != null)
{
this.capabilities[capability] = platformCapabilityValue.ProtocolPlatformType;
}
else
{
this.capabilities[capability] = capabilityValue;
}
}
/// <summary>
/// Return HashCode for the DesiredCapabilities that has been created
/// </summary>
/// <returns>Integer of HashCode generated</returns>
public override int GetHashCode()
{
int result;
result = this.BrowserName != null ? this.BrowserName.GetHashCode() : 0;
result = (31 * result) + (this.Version != null ? this.Version.GetHashCode() : 0);
result = (31 * result) + (this.Platform != null ? this.Platform.GetHashCode() : 0);
return result;
}
/// <summary>
/// Return a string of capabilities being used
/// </summary>
/// <returns>String of capabilities being used</returns>
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "Capabilities [BrowserName={0}, Platform={1}, Version={2}]", this.BrowserName, this.Platform.PlatformType.ToString(), this.Version);
}
/// <summary>
/// Compare two DesiredCapabilities and will return either true or false
/// </summary>
/// <param name="obj">DesiredCapabilities you wish to compare</param>
/// <returns>true if they are the same or false if they are not</returns>
public override bool Equals(object obj)
{
if (this == obj)
{
return true;
}
DesiredCapabilities other = obj as DesiredCapabilities;
if (other == null)
{
return false;
}
if (this.BrowserName != null ? this.BrowserName != other.BrowserName : other.BrowserName != null)
{
return false;
}
if (!this.Platform.IsPlatformType(other.Platform.PlatformType))
{
return false;
}
if (this.Version != null ? this.Version != other.Version : other.Version != null)
{
return false;
}
return true;
}
/// <summary>
/// Returns a read-only version of this capabilities object.
/// </summary>
/// <returns>A read-only version of this capabilities object.</returns>
public ICapabilities AsReadOnly()
{
ReadOnlyDesiredCapabilities readOnlyCapabilities = new ReadOnlyDesiredCapabilities(this);
return readOnlyCapabilities;
}
}
}
| |
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Web;
using System.Web.Mvc;
namespace Campus.Core.Attributes
{
public enum CompressionScheme
{
Gzip,
Deflate,
Identity
}
/// <summary>
/// Enables data output compression
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class CompressAttribute : AbstractAttribute
{
private static CompressAttribute _instance;
public static CompressAttribute Instance
{
get { return _instance ?? (_instance = new CompressAttribute()); }
}
/// <summary>
/// Initializes a new instance of the <see cref="CompressAttribute"/> class.
/// </summary>
/// <param name="level">The level.</param>
/// <param name="scheme">The scheme. (Deflate does not supported in JS)</param>
public CompressAttribute(CompressionLevel level = CompressionLevel.Fastest, CompressionScheme scheme = CompressionScheme.Gzip)
{
Level = level; Scheme = scheme;
}
/// <summary>
/// Gets the compression level.
/// </summary>
/// <value>
/// The level.
/// </value>
public CompressionLevel Level { get; private set; }
/// <summary>
/// Gets the compression time.
/// </summary>
/// <value>
/// The time.
/// </value>
public string Time { get; private set; }
/// <summary>
/// Gets the compression scheme.
/// </summary>
/// <value>
/// The scheme.
/// </value>
public CompressionScheme Scheme { get; private set; }
/// <summary>
/// Compresses the data.
/// </summary>
/// <param name="data">The data.</param>
/// <returns></returns>
public dynamic CompressData(string data)
{
var timer = new Stopwatch();
timer.Start();
var result = Zip(data, Level);
timer.Stop();
Time = timer.Elapsed.TotalSeconds.ToString("0.000000000");
return result;
}
/// <summary>
/// Compresses the data.
/// </summary>
/// <param name="obj">The object.</param>
/// <returns></returns>
public dynamic CompressData(object obj)
{
return CompressData(Serialize(obj));
}
private static void CopyTo(Stream src, Stream dest)
{
byte[] bytes = new byte[4096];
int cnt;
while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0)
{
dest.Write(bytes, 0, cnt);
}
}
private byte[] Zip(string str, CompressionLevel level)
{
var bytes = Encoding.UTF8.GetBytes(str);
using (var msi = new MemoryStream(bytes))
{
using (var mso = new MemoryStream())
{
if (Scheme == CompressionScheme.Gzip)
{
using (var gs = new GZipStream(mso, level))
{
CopyTo(msi, gs);
}
}
else if (Scheme == CompressionScheme.Deflate)
{
using (var gs = new DeflateStream(mso, level))
{
CopyTo(msi, gs);
}
}
return mso.ToArray();
}
}
}
private string Serialize(object result, bool useJavaScriptStyleCamelcase = true)
{
var settings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
Formatting = Formatting.Indented,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
};
if (useJavaScriptStyleCamelcase)
{
settings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
}
var json = JsonConvert.SerializeObject(result, settings);
return json;
}
}
/// <summary>
/// Indicates that target should not be compressed with CompressAttribute
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class CompressIgnoreAttribute : AbstractAttribute
{
private static CompressIgnoreAttribute _instance;
public static CompressIgnoreAttribute Instance
{
get { return _instance ?? (_instance = new CompressIgnoreAttribute()); }
}
}
/// <summary>
/// Enables browser native compression
/// </summary>
/// <remarks>Work only with browsers</remarks>
[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class CompressNativeAttribute : ActionFilterAttribute
{
private readonly CompressionLevel _level;
/// <summary>
/// Initializes a new instance of the <see cref="CompressNativeAttribute"/> class.
/// </summary>
/// <param name="level">The level.</param>
public CompressNativeAttribute(CompressionLevel level = CompressionLevel.Fastest)
: base()
{
_level = level;
}
/// <summary>
/// Gets the compression level.
/// </summary>
/// <value>
/// The level.
/// </value>
public CompressionLevel Level { get { return _level; } }
/// <summary>
/// Gets the preferred encoding.
/// </summary>
/// <value>
/// The preferred encoding.
/// </value>
public CompressionScheme PreferredEncoding { get; private set; }
/// <summary>
/// Called by the ASP.NET MVC framework before the action method executes.
/// </summary>
/// <param name="filterContext">The filter context.</param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!ApiController.AllowCompression)
{
base.OnActionExecuting(filterContext);
return;
}
// Analyze the list of acceptable encodings
var preferredEncoding = GetPreferredEncoding(filterContext.HttpContext.Request);
// Compress the response accordingly
var response = filterContext.HttpContext.Response;
response.AppendHeader("Content-encoding", preferredEncoding.ToString());
if (preferredEncoding == CompressionScheme.Gzip)
{
response.Filter = new GZipStream(response.Filter, _level);
}
if (preferredEncoding == CompressionScheme.Deflate)
{
response.Filter = new DeflateStream(response.Filter, _level);
}
}
private static CompressionScheme GetPreferredEncoding(HttpRequestBase request)
{
var acceptableEncoding = request.Headers["Accept-Encoding"];
// Get the preferred encoding format
if (acceptableEncoding.Contains("gzip"))
{
return CompressionScheme.Gzip;
}
if (acceptableEncoding.Contains("deflate"))
{
return CompressionScheme.Deflate;
}
return CompressionScheme.Identity;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="TestSubscriber.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Akka.Actor;
using Akka.TestKit;
using Reactive.Streams;
namespace Akka.Streams.TestKit
{
public static class TestSubscriber
{
#region messages
public interface ISubscriberEvent : INoSerializationVerificationNeeded { }
public struct OnSubscribe : ISubscriberEvent
{
public readonly ISubscription Subscription;
public OnSubscribe(ISubscription subscription)
{
Subscription = subscription;
}
public override string ToString() => $"TestSubscriber.OnSubscribe({Subscription})";
}
public struct OnNext<T> : ISubscriberEvent
{
public readonly T Element;
public OnNext(T element)
{
Element = element;
}
public override string ToString() => $"TestSubscriber.OnNext({Element})";
}
public sealed class OnComplete: ISubscriberEvent
{
public static readonly OnComplete Instance = new OnComplete();
private OnComplete() { }
public override string ToString() => $"TestSubscriber.OnComplete";
}
public struct OnError : ISubscriberEvent
{
public readonly Exception Cause;
public OnError(Exception cause)
{
Cause = cause;
}
public override string ToString() => $"TestSubscriber.OnError({Cause.Message})";
}
#endregion
/// <summary>
/// Implementation of <see cref="ISubscriber{T}"/> that allows various assertions. All timeouts are dilated automatically,
/// for more details about time dilation refer to <see cref="TestKit"/>.
/// </summary>
public class ManualProbe<T> : ISubscriber<T>
{
private readonly TestProbe _probe;
internal ManualProbe(TestKitBase testKit)
{
_probe = testKit.CreateTestProbe();
}
private volatile ISubscription _subscription;
public void OnSubscribe(ISubscription subscription)
{
_probe.Ref.Tell(new OnSubscribe(subscription));
}
public void OnError(Exception cause)
{
_probe.Ref.Tell(new OnError(cause));
}
public void OnComplete()
{
_probe.Ref.Tell(TestSubscriber.OnComplete.Instance);
}
public void OnNext(T element)
{
_probe.Ref.Tell(new OnNext<T>(element));
}
/// <summary>
/// Expects and returns <see cref="ISubscription"/>.
/// </summary>
public ISubscription ExpectSubscription()
{
_subscription = _probe.ExpectMsg<OnSubscribe>().Subscription;
return _subscription;
}
/// <summary>
/// Expect and return <see cref="ISubscriberEvent"/> (any of: <see cref="OnSubscribe"/>, <see cref="OnNext"/>, <see cref="OnError"/> or <see cref="OnComplete"/>).
/// </summary>
public ISubscriberEvent ExpectEvent()
{
return _probe.ExpectMsg<ISubscriberEvent>();
}
/// <summary>
/// Expect and return <see cref="ISubscriberEvent"/> (any of: <see cref="OnSubscribe"/>, <see cref="OnNext"/>, <see cref="OnError"/> or <see cref="OnComplete"/>).
/// </summary>
public ISubscriberEvent ExpectEvent(TimeSpan max)
{
return _probe.ExpectMsg<ISubscriberEvent>(max);
}
/// <summary>
/// Fluent DSL. Expect and return <see cref="ISubscriberEvent"/> (any of: <see cref="OnSubscribe"/>, <see cref="OnNext"/>, <see cref="OnError"/> or <see cref="OnComplete"/>).
/// </summary>
public ManualProbe<T> ExpectEvent(ISubscriberEvent e)
{
_probe.ExpectMsg(e);
return this;
}
/// <summary>
/// Expect and return a stream element.
/// </summary>
public T ExpectNext()
{
var t = _probe.RemainingOrDilated(null);
var message = _probe.ReceiveOne(t);
if (message is OnNext<T>) return ((OnNext<T>) message).Element;
else throw new Exception("expected OnNext, found " + message);
}
/// <summary>
/// Fluent DSL. Expect a stream element.
/// </summary>
public ManualProbe<T> ExpectNext(T element)
{
_probe.ExpectMsg<OnNext<T>>(x => Equals(x.Element, element));
return this;
}
/// <summary>
/// Fluent DSL. Expect a stream element during specified timeout.
/// </summary>
public ManualProbe<T> ExpectNext(T element, TimeSpan timeout)
{
_probe.ExpectMsg<OnNext<T>>(x => Equals(x.Element, element), timeout);
return this;
}
/// <summary>
/// Fluent DSL. Expect multiple stream elements.
/// </summary>
public ManualProbe<T> ExpectNext(T e1, T e2, params T[] elems)
{
var len = elems.Length + 2;
var e = ExpectNextN(len).ToArray();
AssertEquals(e.Length, len, "expected to get {0} events, but got {1}", len, e.Length);
AssertEquals(e[0], e1, "expected [0] element to be {0} but found {1}", e1, e[0]);
AssertEquals(e[1], e2, "expected [1] element to be {0} but found {1}", e2, e[1]);
for (var i = 0; i < elems.Length; i++)
{
var j = i + 2;
AssertEquals(e[j], elems[i], "expected [{2}] element to be {0} but found {1}", elems[i], e[j], j);
}
return this;
}
/// <summary>
/// FluentDSL. Expect multiple stream elements in arbitrary order.
/// </summary>
public ManualProbe<T> ExpectNextUnordered(T e1, T e2, params T[] elems)
{
var len = elems.Length + 2;
var e = ExpectNextN(len).ToArray();
AssertEquals(e.Length, len, "expected to get {0} events, but got {1}", len, e.Length);
var expectedSet = new HashSet<T>(elems) {e1, e2};
expectedSet.ExceptWith(e);
Assert(expectedSet.Count == 0, "unexpected elemenents [{0}] found in the result", string.Join(", ", expectedSet));
return this;
}
/// <summary>
/// Expect and return the next <paramref name="n"/> stream elements.
/// </summary>
public IEnumerable<T> ExpectNextN(long n)
{
var res = new List<T>((int)n);
for (int i = 0; i < n; i++)
{
var next = _probe.ExpectMsg<OnNext<T>>();
res.Add(next.Element);
}
return res;
}
/// <summary>
/// Fluent DSL. Expect the given elements to be signalled in order.
/// </summary>
public ManualProbe<T> ExpectNextN(IEnumerable<T> all)
{
foreach (var x in all)
_probe.ExpectMsg<OnNext<T>>(y => Equals(y.Element, x));
return this;
}
/// <summary>
/// Fluent DSL. Expect the given elements to be signalled in any order.
/// </summary>
public ManualProbe<T> ExpectNextUnorderedN(IEnumerable<T> all)
{
var collection = new HashSet<T>(all);
while (collection.Count > 0)
{
var next = ExpectNext();
Assert(collection.Contains(next), $"expected one of (${string.Join(", ", collection)}), but received {next}");
collection.Remove(next);
}
return this;
}
/// <summary>
/// Fluent DSL. Expect completion.
/// </summary>
public ManualProbe<T> ExpectComplete()
{
_probe.ExpectMsg<OnComplete>();
return this;
}
/// <summary>
/// Expect and return the signalled <see cref="Exception"/>.
/// </summary>
public Exception ExpectError()
{
return _probe.ExpectMsg<OnError>().Cause;
}
/// <summary>
/// Expect subscription to be followed immediatly by an error signal. By default single demand will be signalled in order to wake up a possibly lazy upstream.
/// <seealso cref="ExpectSubscriptionAndError(bool)"/>
/// </summary>
public Exception ExpectSubscriptionAndError()
{
return ExpectSubscriptionAndError(true);
}
/// <summary>
/// Expect subscription to be followed immediatly by an error signal. Depending on the `signalDemand` parameter demand may be signalled
/// immediatly after obtaining the subscription in order to wake up a possibly lazy upstream.You can disable this by setting the `signalDemand` parameter to `false`.
/// <seealso cref="ExpectSubscriptionAndError()"/>
/// </summary>
public Exception ExpectSubscriptionAndError(bool signalDemand)
{
var sub = ExpectSubscription();
if(signalDemand) sub.Request(1);
return ExpectError();
}
/// <summary>
/// Fluent DSL. Expect subscription followed by immediate stream completion. By default single demand will be signalled in order to wake up a possibly lazy upstream
/// </summary>
/// <seealso cref="ExpectSubscriptionAndComplete(bool)"/>
public ManualProbe<T> ExpectSubscriptionAndComplete()
{
return ExpectSubscriptionAndComplete(true);
}
/// <summary>
/// Fluent DSL. Expect subscription followed by immediate stream completion. Depending on the `signalDemand` parameter
/// demand may be signalled immediatly after obtaining the subscription in order to wake up a possibly lazy upstream.
/// You can disable this by setting the `signalDemand` parameter to `false`.
/// </summary>
/// <seealso cref="ExpectSubscriptionAndComplete()"/>
public ManualProbe<T> ExpectSubscriptionAndComplete(bool signalDemand)
{
var sub = ExpectSubscription();
if (signalDemand) sub.Request(1);
ExpectComplete();
return this;
}
/// <summary>
/// Expect given next element or error signal, returning whichever was signalled.
/// </summary>
public object ExpectNextOrError()
{
var message = _probe.FishForMessage(m => m is OnNext<T> || m is OnError, hint: "OnNext(_) or error");
if (message is OnNext<T>)
return ((OnNext<T>) message).Element;
return ((OnError) message).Cause;
}
/// <summary>
/// Fluent DSL. Expect given next element or error signal.
/// </summary>
public ManualProbe<T> ExpectNextOrError(T element, Exception cause)
{
_probe.FishForMessage(
m =>
(m is OnNext<T> && ((OnNext<T>) m).Element.Equals(element)) ||
(m is OnError && ((OnError) m).Cause.Equals(cause)),
hint: $"OnNext({element}) or {cause.GetType().Name}");
return this;
}
/// <summary>
/// Expect given next element or stream completion, returning whichever was signalled.
/// </summary>
public object ExpectNextOrComplete()
{
var message = _probe.FishForMessage(m => m is OnNext<T> || m is OnComplete, hint: "OnNext(_) or OnComplete");
if (message is OnNext<T>)
return ((OnNext<T>) message).Element;
return message;
}
/// <summary>
/// Fluent DSL. Expect given next element or stream completion.
/// </summary>
public ManualProbe<T> ExpectNextOrComplete(T element)
{
_probe.FishForMessage(
m =>
(m is OnNext<T> && ((OnNext<T>) m).Element.Equals(element)) ||
m is OnComplete,
hint: $"OnNext({element}) or OnComplete");
return this;
}
/// <summary>
/// Fluent DSL. Same as <see cref="ExpectNoMsg(TimeSpan)"/>, but correctly treating the timeFactor.
/// </summary>
public ManualProbe<T> ExpectNoMsg()
{
_probe.ExpectNoMsg();
return this;
}
/// <summary>
/// Fluent DSL. Assert that no message is received for the specified time.
/// </summary>
public ManualProbe<T> ExpectNoMsg(TimeSpan remaining)
{
_probe.ExpectNoMsg(remaining);
return this;
}
public TOther ExpectNext<TOther>(Predicate<TOther> predicate)
{
return _probe.ExpectMsg<OnNext<TOther>>(x => predicate(x.Element)).Element;
}
public TOther ExpectEvent<TOther>(Func<ISubscriberEvent, TOther> func)
{
return func(_probe.ExpectMsg<ISubscriberEvent>());
}
/// <summary>
/// Receive messages for a given duration or until one does not match a given partial function.
/// </summary>
public IEnumerable<TOther> ReceiveWhile<TOther>(TimeSpan? max = null, TimeSpan? idle = null, Func<object, TOther> filter = null, int msgs = int.MaxValue) where TOther : class
{
return _probe.ReceiveWhile(max, idle, filter, msgs);
}
public TOther Within<TOther>(TimeSpan max, Func<TOther> func)
{
return _probe.Within(TimeSpan.Zero, max, func);
}
/// <summary>
/// Attempt to drain the stream into a strict collection (by requesting <see cref="long.MaxValue"/> elements).
/// </summary>
/// <remarks>
/// Use with caution: Be warned that this may not be a good idea if the stream is infinite or its elements are very large!
/// </remarks>
public IList<T> ToStrict(TimeSpan atMost)
{
var deadline = DateTime.UtcNow + atMost;
// if no subscription was obtained yet, we expect it
if (_subscription == null) ExpectSubscription();
_subscription.Request(long.MaxValue);
var result = new List<T>();
while (true)
{
var e = ExpectEvent(TimeSpan.FromTicks(Math.Max(deadline.Ticks - DateTime.UtcNow.Ticks, 0)));
if (e is OnError)
throw new ArgumentException(
$"ToStrict received OnError while draining stream! Accumulated elements: ${string.Join(", ", result)}",
((OnError) e).Cause);
if (e is OnComplete)
break;
if (e is OnNext<T>)
result.Add(((OnNext<T>) e).Element);
}
return result;
}
private void Assert(bool predicate, string format, params object[] args)
{
if (!predicate) throw new Exception(string.Format(format, args));
}
private void AssertEquals<T1, T2>(T1 x, T2 y, string format, params object[] args)
{
if (!Equals(x, y)) throw new Exception(string.Format(format, args));
}
}
/// <summary>
/// Single subscription tracking for <see cref="ManualProbe{T}"/>.
/// </summary>
public class Probe<T> : ManualProbe<T>
{
private readonly Lazy<ISubscription> _subscription;
internal Probe(TestKitBase testKit) : base(testKit)
{
_subscription = new Lazy<ISubscription>(ExpectSubscription);
}
/// <summary>
/// Asserts that a subscription has been received or will be received
/// </summary>
public Probe<T> EnsureSubscription()
{
var _ = _subscription.Value; // initializes lazy val
return this;
}
public Probe<T> Request(long n)
{
_subscription.Value.Request(n);
return this;
}
public Probe<T> RequestNext(T element)
{
_subscription.Value.Request(1);
ExpectNext(element);
return this;
}
public Probe<T> Cancel()
{
_subscription.Value.Cancel();
return this;
}
public T RequestNext()
{
_subscription.Value.Request(1);
return ExpectNext();
}
}
public static ManualProbe<T> CreateManualProbe<T>(this TestKitBase testKit)
{
return new ManualProbe<T>(testKit);
}
public static Probe<T> CreateProbe<T>(this TestKitBase testKit)
{
return new Probe<T>(testKit);
}
}
}
| |
using Bridge.Test.NUnit;
using System;
namespace TestCase67
{
class Optional<T>
{
public Optional(T value)
{
Value = value;
}
public T Value { get; }
}
class SubClass
{
public class Optional<T>
{
public Optional(T value)
{
Value = value;
}
public T Value { get; }
}
}
}
namespace TestCase67.SubNameSpace
{
class Optional<T>
{
public Optional(T value)
{
Value = value;
}
public T Value { get; }
}
class SubClass
{
public class Optional<T>
{
public Optional(T value)
{
Value = value;
}
public T Value { get; }
}
}
}
namespace Newtonsoft.Json.Tests.Issues
{
/// <summary>
/// The test here consists in verifying whether generic types are correctly
/// serialized in different class and namespaces situations and when
/// System.Uri is used as generics' specialization.
/// </summary>
/// <remarks>
/// System.Uri should output System and not mscorlib, and class depth
/// delimiter must be '+' and not '.'.
/// </remarks>
[Category("Issues")]
[TestFixture(TestNameFormat = "#67 - {0}")]
public class Case67
{
/// <summary>
/// A test object implementing C# generics.
/// </summary>
class Optional<T>
{
public Optional(T value)
{
Value = value;
}
public T Value { get; }
}
/// <summary>
/// The test here basically checks if the serialized string has the
/// same output generated by an analog console application using the
/// C# version of Newtonsoft.Json.
/// </summary>
/// <remarks>
/// A transcript of Program.cs equivalent to this sequence of tests
/// that can be used to fetch the expected output from a pure C#
/// application is commented out at the end of this source file.
/// </remarks>
[Test]
public static void TestTypeGenericSerialize()
{
var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects };
Console.WriteLine("{\"$type\":\"Newtonsoft.Json.Tests.Issues.Case67+Optional`1[[System.Int32, mscorlib]], Newtonsoft.Json.Tests\",\"Value\":1}");
Console.WriteLine(JsonConvert.SerializeObject(new Optional<int>(1), settings));
// First, the console application output, then our equivalent.
Assert.AreEqual(
"{\"$type\":\"Newtonsoft.Json.Tests.Issues.Case67+Optional`1[[System.Int32, mscorlib]], Newtonsoft.Json.Tests\",\"Value\":1}",
JsonConvert.SerializeObject(new Optional<int>(1), settings),
"Simple int. Local object to the test method.");
Assert.AreEqual(
"{\"$type\":\"TestCase67.Optional`1[[System.Int32, mscorlib]], Newtonsoft.Json.Tests\",\"Value\":1}",
JsonConvert.SerializeObject(new TestCase67.Optional<int>(1), settings),
"Simple int. Root object on a root namespace.");
// sub classes have a '+' separator between the object depths
Assert.AreEqual(
"{\"$type\":\"TestCase67.SubClass+Optional`1[[System.Int32, mscorlib]], Newtonsoft.Json.Tests\",\"Value\":1}",
JsonConvert.SerializeObject(new TestCase67.SubClass.Optional<int>(1), settings),
"Simple int. Subclass object on a root namespace.");
Assert.AreEqual(
"{\"$type\":\"TestCase67.SubNameSpace.Optional`1[[System.Int32, mscorlib]], Newtonsoft.Json.Tests\",\"Value\":1}",
JsonConvert.SerializeObject(new TestCase67.SubNameSpace.Optional<int>(1), settings),
"Simple int. Root object on a sub namespace.");
Assert.AreEqual(
"{\"$type\":\"TestCase67.SubNameSpace.SubClass+Optional`1[[System.Int32, mscorlib]], Newtonsoft.Json.Tests\",\"Value\":1}",
JsonConvert.SerializeObject(new TestCase67.SubNameSpace.SubClass.Optional<int>(1), settings),
"Simple int. Subclass object on a sub namespace.");
var myUri = new Uri("http://www.google.com/");
Assert.AreEqual(
"{\"$type\":\"Newtonsoft.Json.Tests.Issues.Case67+Optional`1[[System.Uri, System]], Newtonsoft.Json.Tests\",\"Value\":\"http://www.google.com/\"}",
JsonConvert.SerializeObject(new Optional<Uri>(myUri), settings),
"System.Uri. Local object to the test method.");
Assert.AreEqual(
"{\"$type\":\"TestCase67.Optional`1[[System.Uri, System]], Newtonsoft.Json.Tests\",\"Value\":\"http://www.google.com/\"}",
JsonConvert.SerializeObject(new TestCase67.Optional<Uri>(myUri), settings),
"System.Uri. Root object on a root namespace.");
// sub classes have a '+' separator between the object depths
Assert.AreEqual(
"{\"$type\":\"TestCase67.SubClass+Optional`1[[System.Uri, System]], Newtonsoft.Json.Tests\",\"Value\":\"http://www.google.com/\"}",
JsonConvert.SerializeObject(new TestCase67.SubClass.Optional<Uri>(myUri), settings),
"System.Uri. Subclass object on a root namespace.");
Assert.AreEqual(
"{\"$type\":\"TestCase67.SubNameSpace.Optional`1[[System.Uri, System]], Newtonsoft.Json.Tests\",\"Value\":\"http://www.google.com/\"}",
JsonConvert.SerializeObject(new TestCase67.SubNameSpace.Optional<Uri>(myUri), settings),
"System.Uri. Root object on a sub namespace.");
Assert.AreEqual(
"{\"$type\":\"TestCase67.SubNameSpace.SubClass+Optional`1[[System.Uri, System]], Newtonsoft.Json.Tests\",\"Value\":\"http://www.google.com/\"}",
JsonConvert.SerializeObject(new TestCase67.SubNameSpace.SubClass.Optional<Uri>(myUri), settings),
"System.Uri. Subclass object on a sub namespace.");
}
}
}
// For convenience a whole transcript of the actual Program.cs for the Console
// Application equivalent used for output gathering is commented out below.
// The console application project name should be "Newtonsoft.Json.Tests for
// the output to be consistent to the one expected here.
/*
using System;
namespace TestCase67
{
class Optional<T>
{
public Optional(T value)
{
Value = value;
}
public T Value { get; }
}
class SubClass
{
public class Optional<T>
{
public Optional(T value)
{
Value = value;
}
public T Value { get; }
}
}
}
namespace TestCase67.SubNameSpace
{
class Optional<T>
{
public Optional(T value)
{
Value = value;
}
public T Value { get; }
}
class SubClass
{
public class Optional<T>
{
public Optional(T value)
{
Value = value;
}
public T Value { get; }
}
}
}
namespace Newtonsoft.Json.Tests.Issues
{
/// <summary>
/// The test here consists in verifying whether generic types are correctly
/// serialized when type name is serialized with the object.
/// </summary>
//[Category("Issues")]
//[TestFixture(TestNameFormat = "#67 - {0}")]
public class Case67
{
/// <summary>
/// A test object implementing C# generics.
/// </summary>
class Optional<T>
{
public Optional(T value)
{
Value = value;
}
public T Value { get; }
}
/// <summary>
/// The test here should basically check if the serialized object has
/// value on its properties once it is deserialized.
/// </summary>
//[Test]
public static void TestTypeGenericSerialize()
{
var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects };
Console.WriteLine(JsonConvert.SerializeObject(new Optional<int>(1), settings).Replace("\"", "\\\""));
Console.WriteLine(JsonConvert.SerializeObject(new TestCase67.Optional<int>(1), settings).Replace("\"", "\\\""));
Console.WriteLine(JsonConvert.SerializeObject(new TestCase67.SubClass.Optional<int>(1), settings).Replace("\"", "\\\""));
Console.WriteLine(JsonConvert.SerializeObject(new TestCase67.SubNameSpace.Optional<int>(1), settings).Replace("\"", "\\\""));
Console.WriteLine(JsonConvert.SerializeObject(new TestCase67.SubNameSpace.SubClass.Optional<int>(1), settings).Replace("\"", "\\\""));
var myUri = new Uri("http://www.google.com/");
Console.WriteLine(JsonConvert.SerializeObject(new Optional<Uri>(myUri), settings).Replace("\"", "\\\""));
Console.WriteLine(JsonConvert.SerializeObject(new TestCase67.Optional<Uri>(myUri), settings).Replace("\"", "\\\""));
Console.WriteLine(JsonConvert.SerializeObject(new TestCase67.SubClass.Optional<Uri>(myUri), settings).Replace("\"", "\\\""));
Console.WriteLine(JsonConvert.SerializeObject(new TestCase67.SubNameSpace.Optional<Uri>(myUri), settings).Replace("\"", "\\\""));
Console.WriteLine(JsonConvert.SerializeObject(new TestCase67.SubNameSpace.SubClass.Optional<Uri>(myUri), settings).Replace("\"", "\\\""));
}
}
}
namespace Newtonsoft.Json.Tests
{
/// <summary>
/// Console application entry point
/// </summary>
class Program
{
static void Main(string[] args)
{
Newtonsoft.Json.Tests.Issues.Case67.TestTypeGenericSerialize();
}
}
}
*/
| |
// 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.Runtime.General;
using Internal.NativeFormat;
using Internal.TypeSystem;
using Internal.Runtime;
using Internal.Runtime.Augments;
using Internal.Runtime.TypeLoader;
using Internal.Metadata.NativeFormat;
using Debug = System.Diagnostics.Debug;
namespace Internal.TypeSystem.NoMetadata
{
/// <summary>
/// Type that once had metadata, but that metadata is not available
/// for the lifetime of the TypeSystemContext. Directly correlates
/// to a RuntimeTypeHandle useable in the current environment.
/// This type replaces the placeholder NoMetadataType that comes
/// with the common type system codebase
/// </summary>
internal class NoMetadataType : DefType
{
private TypeSystemContext _context;
private int _hashcode;
private RuntimeTypeHandle _genericTypeDefinition;
private DefType _genericTypeDefinitionAsDefType;
private Instantiation _instantiation;
private bool _baseTypeCached;
private DefType _baseType;
public NoMetadataType(TypeSystemContext context, RuntimeTypeHandle genericTypeDefinition, DefType genericTypeDefinitionAsDefType, Instantiation instantiation, int hashcode)
{
_hashcode = hashcode;
_context = context;
_genericTypeDefinition = genericTypeDefinition;
_genericTypeDefinitionAsDefType = genericTypeDefinitionAsDefType;
if (_genericTypeDefinitionAsDefType == null)
_genericTypeDefinitionAsDefType = this;
_instantiation = instantiation;
// Instantiation must either be:
// Something valid (if the type is generic, or a generic type definition)
// or Empty (if the type isn't a generic of any form)
unsafe
{
Debug.Assert(((_instantiation.Length > 0) && _genericTypeDefinition.ToEETypePtr()->IsGenericTypeDefinition) ||
((_instantiation.Length == 0) && !_genericTypeDefinition.ToEETypePtr()->IsGenericTypeDefinition));
}
}
public override int GetHashCode()
{
return _hashcode;
}
public override TypeSystemContext Context
{
get
{
return _context;
}
}
public override DefType BaseType
{
get
{
if (_baseTypeCached)
return _baseType;
if (RetrieveRuntimeTypeHandleIfPossible())
{
RuntimeTypeHandle baseTypeHandle;
if (!RuntimeAugments.TryGetBaseType(RuntimeTypeHandle, out baseTypeHandle))
{
Debug.Assert(false);
}
DefType baseType = !baseTypeHandle.IsNull() ? (DefType)Context.ResolveRuntimeTypeHandle(baseTypeHandle) : null;
SetBaseType(baseType);
return baseType;
}
else
{
Debug.Assert(this.HasNativeLayout);
// Parsing of the base type has not yet happened. Perform that part of native layout parsing
// just-in-time
TypeBuilderState state = GetOrCreateTypeBuilderState();
ComputeTemplate();
NativeParser typeInfoParser = state.GetParserForNativeLayoutInfo();
NativeParser baseTypeParser = typeInfoParser.GetParserForBagElementKind(BagElementKind.BaseType);
ParseBaseType(state.NativeLayoutInfo.LoadContext, baseTypeParser);
Debug.Assert(_baseTypeCached);
return _baseType;
}
}
}
internal override void ParseBaseType(NativeLayoutInfoLoadContext nativeLayoutInfoLoadContext, NativeParser baseTypeParser)
{
if (!baseTypeParser.IsNull)
{
// If the base type is available from the native layout info use it if the type we have is a NoMetadataType
SetBaseType((DefType)nativeLayoutInfoLoadContext.GetType(ref baseTypeParser));
}
else
{
// Set the base type for no metadata types, if we reach this point, and there isn't a parser, then we simply use the value from the template
SetBaseType(ComputeTemplate().BaseType);
}
}
/// <summary>
/// This is used to set base type for generic types without metadata
/// </summary>
public void SetBaseType(DefType baseType)
{
Debug.Assert(!_baseTypeCached || _baseType == baseType);
_baseType = baseType;
_baseTypeCached = true;
}
protected override TypeFlags ComputeTypeFlags(TypeFlags mask)
{
TypeFlags flags = 0;
if ((mask & TypeFlags.CategoryMask) != 0)
{
unsafe
{
EEType* eetype = _genericTypeDefinition.ToEETypePtr();
if (eetype->IsValueType)
{
if (eetype->CorElementType == 0)
{
flags |= TypeFlags.ValueType;
}
else
{
if (eetype->BaseType == typeof(System.Enum).TypeHandle.ToEETypePtr())
{
flags |= TypeFlags.Enum;
}
else
{
// Primitive type.
if (eetype->CorElementType <= CorElementType.ELEMENT_TYPE_U8)
{
flags |= (TypeFlags)eetype->CorElementType;
}
else
{
switch (eetype->CorElementType)
{
case CorElementType.ELEMENT_TYPE_I:
flags |= TypeFlags.IntPtr;
break;
case CorElementType.ELEMENT_TYPE_U:
flags |= TypeFlags.UIntPtr;
break;
case CorElementType.ELEMENT_TYPE_R4:
flags |= TypeFlags.Single;
break;
case CorElementType.ELEMENT_TYPE_R8:
flags |= TypeFlags.Double;
break;
default:
throw new BadImageFormatException();
}
}
}
}
}
else if (eetype->IsInterface)
{
flags |= TypeFlags.Interface;
}
else
{
flags |= TypeFlags.Class;
}
}
}
if ((mask & TypeFlags.IsByRefLikeComputed) != 0)
{
flags |= TypeFlags.IsByRefLikeComputed;
unsafe
{
EEType* eetype = _genericTypeDefinition.ToEETypePtr();
if (eetype->IsByRefLike)
{
flags |= TypeFlags.IsByRefLike;
}
}
}
return flags;
}
// Canonicalization handling
public override bool IsCanonicalSubtype(CanonicalFormKind policy)
{
foreach (TypeDesc t in Instantiation)
{
if (t.IsCanonicalSubtype(policy))
{
return true;
}
}
return false;
}
protected override TypeDesc ConvertToCanonFormImpl(CanonicalFormKind kind)
{
bool needsChange;
Instantiation canonInstantiation = Context.ConvertInstantiationToCanonForm(Instantiation, kind, out needsChange);
if (needsChange)
{
TypeDesc openType = GetTypeDefinition();
return openType.InstantiateSignature(canonInstantiation, new Instantiation());
}
return this;
}
public override TypeDesc GetTypeDefinition()
{
if (_genericTypeDefinitionAsDefType != null)
return _genericTypeDefinitionAsDefType;
else
return this;
}
public override TypeDesc InstantiateSignature(Instantiation typeInstantiation, Instantiation methodInstantiation)
{
TypeDesc[] clone = null;
for (int i = 0; i < _instantiation.Length; i++)
{
TypeDesc uninst = _instantiation[i];
TypeDesc inst = uninst.InstantiateSignature(typeInstantiation, methodInstantiation);
if (inst != uninst)
{
if (clone == null)
{
clone = new TypeDesc[_instantiation.Length];
for (int j = 0; j < clone.Length; j++)
{
clone[j] = _instantiation[j];
}
}
clone[i] = inst;
}
}
return (clone == null) ? this : _genericTypeDefinitionAsDefType.Context.ResolveGenericInstantiation(_genericTypeDefinitionAsDefType, new Instantiation(clone));
}
public override Instantiation Instantiation
{
get
{
return _instantiation;
}
}
public override TypeDesc UnderlyingType
{
get
{
if (!this.IsEnum)
return this;
unsafe
{
CorElementType corElementType = RuntimeTypeHandle.ToEETypePtr()->CorElementType;
return Context.GetTypeFromCorElementType(corElementType);
}
}
}
private void GetTypeNameHelper(out string name, out string nsName, out string assemblyName)
{
TypeReferenceHandle typeRefHandle;
QTypeDefinition qTypeDefinition;
MetadataReader reader;
RuntimeTypeHandle genericDefinitionHandle = GetTypeDefinition().GetRuntimeTypeHandle();
Debug.Assert(!genericDefinitionHandle.IsNull());
string enclosingDummy;
// Try to get the name from metadata
if (TypeLoaderEnvironment.Instance.TryGetMetadataForNamedType(genericDefinitionHandle, out qTypeDefinition))
{
TypeDefinitionHandle typeDefHandle = qTypeDefinition.NativeFormatHandle;
typeDefHandle.GetFullName(qTypeDefinition.NativeFormatReader, out name, out enclosingDummy, out nsName);
assemblyName = typeDefHandle.GetContainingModuleName(qTypeDefinition.NativeFormatReader);
}
// Try to get the name from diagnostic metadata
else if (TypeLoaderEnvironment.TryGetTypeReferenceForNamedType(genericDefinitionHandle, out reader, out typeRefHandle))
{
typeRefHandle.GetFullName(reader, out name, out enclosingDummy, out nsName);
assemblyName = typeRefHandle.GetContainingModuleName(reader);
}
else
{
name = genericDefinitionHandle.LowLevelToStringRawEETypeAddress();
nsName = "";
assemblyName = "?";
}
}
public string DiagnosticNamespace
{
get
{
string name, nsName, assemblyName;
GetTypeNameHelper(out name, out nsName, out assemblyName);
return nsName;
}
}
public string DiagnosticName
{
get
{
string name, nsName, assemblyName;
GetTypeNameHelper(out name, out nsName, out assemblyName);
return name;
}
}
public string DiagnosticModuleName
{
get
{
string name, nsName, assemblyName;
GetTypeNameHelper(out name, out nsName, out assemblyName);
return assemblyName;
}
}
#if DEBUG
private string _cachedToString = null;
public override string ToString()
{
if (_cachedToString != null)
return _cachedToString;
StringBuilder sb = new StringBuilder();
if (!_genericTypeDefinition.IsNull())
sb.Append(_genericTypeDefinition.LowLevelToString());
else if (!RuntimeTypeHandle.IsNull())
sb.Append(RuntimeTypeHandle.LowLevelToString());
if (!Instantiation.IsNull)
{
for (int i = 0; i < Instantiation.Length; i++)
{
sb.Append(i == 0 ? "[" : ", ");
sb.Append(Instantiation[i].ToString());
}
if (Instantiation.Length > 0) sb.Append("]");
}
_cachedToString = sb.ToString();
return _cachedToString;
}
#endif
}
}
| |
namespace Nancy.Tests.Unit.ViewEngines
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using FakeItEasy;
using Nancy.ViewEngines;
using Xunit;
public class ResourceViewLocationProviderFixture
{
private readonly IResourceReader reader;
private readonly IResourceAssemblyProvider resourceAssemblyProvider;
private readonly ResourceViewLocationProvider viewProvider;
public ResourceViewLocationProviderFixture()
{
ResourceViewLocationProvider.Ignore.Clear();
this.reader = A.Fake<IResourceReader>();
this.resourceAssemblyProvider = A.Fake<IResourceAssemblyProvider>();
this.viewProvider = new ResourceViewLocationProvider(this.reader, this.resourceAssemblyProvider);
if (!ResourceViewLocationProvider.RootNamespaces.ContainsKey(this.GetType().Assembly))
{
ResourceViewLocationProvider.RootNamespaces.Add(this.GetType().Assembly, "Some.Resource");
}
A.CallTo(() => this.resourceAssemblyProvider.GetAssembliesToScan()).Returns(new[] { this.GetType().Assembly });
}
[Fact]
public void Should_return_empty_result_when_supported_view_extensions_is_null()
{
// Given
IEnumerable<string> extensions = null;
// When
var result = this.viewProvider.GetLocatedViews(extensions);
// Then
result.ShouldHaveCount(0);
}
[Fact]
public void Should_return_empty_result_when_supported_view_extensions_is_empty()
{
// Given
var extensions = Enumerable.Empty<string>();
// When
var result = this.viewProvider.GetLocatedViews(extensions);
// Then
result.ShouldHaveCount(0);
}
[Fact]
public void Should_return_empty_result_when_view_resources_could_be_found()
{
// Given
var extensions = new[] { "html" };
// When
var result = this.viewProvider.GetLocatedViews(extensions);
// Then
result.ShouldHaveCount(0);
}
[Fact]
public void Should_return_view_location_result_with_file_name_set()
{
// Given
var extensions = new[] { "html" };
var match = new Tuple<string, Func<StreamReader>>(
"Some.Resource.View.html",
() => null);
A.CallTo(() => this.reader.GetResourceStreamMatches(A<Assembly>._, A<IEnumerable<string>>._)).Returns(new[] {match});
// When
var result = this.viewProvider.GetLocatedViews(extensions);
// Then
result.First().Name.ShouldEqual("View");
}
[Fact]
public void Should_return_view_location_result_with_content_set()
{
// Given
var extensions = new[] { "html" };
var match = new Tuple<string, Func<StreamReader>>(
"Some.Resource.View.html",
() => null);
A.CallTo(() => this.reader.GetResourceStreamMatches(A<Assembly>._, A<IEnumerable<string>>._)).Returns(new[] { match });
// When
var result = this.viewProvider.GetLocatedViews(extensions);
// Then
result.First().Contents.ShouldNotBeNull();
}
[Fact]
public void Should_throw_invalid_operation_exception_if_only_one_view_was_found_and_no_root_namespace_has_been_defined()
{
// Given
var extensions = new[] { "html" };
ResourceViewLocationProvider.RootNamespaces.Remove(this.GetType().Assembly);
var match = new Tuple<string, Func<StreamReader>>(
"Some.Resource.View.html",
() => null);
A.CallTo(() => this.reader.GetResourceStreamMatches(A<Assembly>._, A<IEnumerable<string>>._)).Returns(new[] { match });
// When
var exception = Record.Exception(() => this.viewProvider.GetLocatedViews(extensions).ToList());
// Then
exception.ShouldBeOfType<InvalidOperationException>();
}
[Fact]
public void Should_set_error_message_when_throwing_invalid_operation_exception_due_to_not_being_able_to_figure_out_common_namespace()
{
// Given
var extensions = new[] { "html" };
ResourceViewLocationProvider.RootNamespaces.Remove(this.GetType().Assembly);
var match = new Tuple<string, Func<StreamReader>>(
"Some.Resource.View.html",
() => null);
A.CallTo(() => this.reader.GetResourceStreamMatches(A<Assembly>._, A<IEnumerable<string>>._)).Returns(new[] { match });
var expectedErrorMessage =
string.Format("Only one view was found in assembly {0}, but no rootnamespace had been registered.", this.GetType().Assembly.FullName);
// When
var exception = Record.Exception(() => this.viewProvider.GetLocatedViews(extensions).ToList());
// Then
exception.Message.ShouldEqual(expectedErrorMessage);
}
[Fact]
public void Should_return_view_location_result_where_location_is_set_in_platform_neutral_format()
{
// Given
var extensions = new[] { "html" };
var match = new Tuple<string, Func<StreamReader>>(
"Some.Resource.Path.With.Sub.Folder.View.html",
() => null);
A.CallTo(() => this.reader.GetResourceStreamMatches(A<Assembly>._, A<IEnumerable<string>>._)).Returns(new[] { match });
// When
var result = this.viewProvider.GetLocatedViews(extensions);
// Then
result.First().Location.ShouldEqual("Path/With/Sub/Folder");
}
[Fact]
public void Should_scan_assemblies_returned_by_assembly_provider()
{
// Given
A.CallTo(() => this.resourceAssemblyProvider.GetAssembliesToScan()).Returns(new[]
{
typeof(NancyEngine).Assembly,
this.GetType().Assembly
});
var extensions = new[] { "html" };
// When
this.viewProvider.GetLocatedViews(extensions).ToList();
// Then
A.CallTo(() => this.reader.GetResourceStreamMatches(this.GetType().Assembly, A<IEnumerable<string>>._)).MustHaveHappened();
A.CallTo(() => this.reader.GetResourceStreamMatches(typeof(NancyEngine).Assembly, A<IEnumerable<string>>._)).MustHaveHappened();
}
[Fact]
public void Should_not_scan_ignored_assemblies()
{
// Given
A.CallTo(() => this.resourceAssemblyProvider.GetAssembliesToScan()).Returns(new[]
{
typeof(NancyEngine).Assembly,
this.GetType().Assembly
});
ResourceViewLocationProvider.Ignore.Add(this.GetType().Assembly);
var extensions = new[] { "html" };
// When
this.viewProvider.GetLocatedViews(extensions).ToList();
// Then
A.CallTo(() => this.reader.GetResourceStreamMatches(this.GetType().Assembly, A<IEnumerable<string>>._)).MustNotHaveHappened();
A.CallTo(() => this.reader.GetResourceStreamMatches(typeof(NancyEngine).Assembly, A<IEnumerable<string>>._)).MustHaveHappened();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using FileHelpers.Events;
using FileHelpers.Helpers;
namespace FileHelpers
{
/// <summary>An internal class used to store information about the Record Type.</summary>
internal sealed partial class RecordInfo
: IRecordInfo
{
// --------------------------------------
// Constructor and Init Methods
#region IRecordInfo Members
/// <summary>
/// Hint about record size
/// </summary>
public int SizeHint { get; private set; }
/// <summary>
/// Class we are defining
/// </summary>
public Type RecordType { get; private set; }
/// <summary>
/// Do we skip empty lines?
/// </summary>
public bool IgnoreEmptyLines { get; set; }
/// <summary>
/// Do we skip lines with completely blank lines
/// </summary>
public bool IgnoreEmptySpaces { get; private set; }
/// <summary>
/// Comment prefix
/// </summary>
public string CommentMarker { get; set; }
/// <summary>
/// Number of fields we are processing
/// </summary>
public int FieldCount => Fields.Length;
/// <summary>
/// List of fields and the extraction details
/// </summary>
public FieldBase[] Fields { get; private set; }
/// <summary>
/// Number of lines to skip at beginning of file
/// </summary>
public int IgnoreFirst { get; set; }
/// <summary>
/// Number of lines to skip at end of file
/// </summary>
public int IgnoreLast { get; set; }
/// <summary>
/// DO we need to issue a Notify read
/// </summary>
public bool NotifyRead { get; private set; }
/// <summary>
/// Do we need to issue a Notify Write
/// </summary>
public bool NotifyWrite { get; private set; }
/// <summary>
/// Can the comment prefix have leading whitespace
/// </summary>
public bool CommentAnyPlace { get; set; }
/// <summary>
/// Include or skip a record based upon a defined RecordCondition interface
/// </summary>
public RecordCondition RecordCondition { get; set; }
/// <summary>
/// Skip or include a record based upon a regular expression
/// </summary>
public Regex RecordConditionRegEx { get; private set; }
/// <summary>
/// Include or exclude a record based upon presence of a string
/// </summary>
public string RecordConditionSelector { get; set; }
/// <summary>
/// Operations are the functions that perform creation or extraction of data from objects
/// these are created dynamically from the record conditions
/// </summary>
public RecordOperations Operations { get; private set; }
private Dictionary<string, int> mMapFieldIndex;
/// <summary>
/// Is this record layout delimited
/// </summary>
public bool IsDelimited => Fields[0] is DelimitedField;
#endregion
#region " Constructor "
private RecordInfo() {}
/// <summary>
/// Read the attributes of the class and create an array
/// of how to process the file
/// </summary>
/// <param name="recordType">Class we are analysing</param>
private RecordInfo(Type recordType)
{
SizeHint = 32;
RecordConditionSelector = String.Empty;
RecordCondition = RecordCondition.None;
CommentAnyPlace = true;
RecordType = recordType;
InitRecordFields();
Operations = new RecordOperations(this);
}
/// <summary>
/// Create a list of fields we are extracting and set
/// the size hint for record I/O
/// </summary>
private void InitRecordFields()
{
var recordAttribute = Attributes.GetFirstInherited<TypedRecordAttribute>(RecordType);
if (recordAttribute == null) {
//throw new BadUsageException(Messages.Errors.ClassWithOutRecordAttribute.ClassName(RecordType.Name).Text);
throw new BadUsageException("FileHelperMsg_ClassWithOutRecordAttribute", new List<string>() { RecordType.Name });
}
if (ReflectionHelper.GetDefaultConstructor(RecordType) == null) {
//throw new BadUsageException(Messages.Errors.ClassWithOutDefaultConstructor.ClassName(RecordType.Name).Text);
throw new BadUsageException("FileHelperMsg_ClassWithOutDefaultConstructor", new List<string>() { RecordType.Name });
}
Attributes.WorkWithFirst<IgnoreFirstAttribute>(
RecordType,
a => IgnoreFirst = a.NumberOfLines);
Attributes.WorkWithFirst<IgnoreLastAttribute>(
RecordType,
a => IgnoreLast = a.NumberOfLines);
Attributes.WorkWithFirst<IgnoreEmptyLinesAttribute>(
RecordType,
a => {
IgnoreEmptyLines = true;
IgnoreEmptySpaces = a.IgnoreSpaces;
});
#pragma warning disable CS0618 // Type or member is obsolete
Attributes.WorkWithFirst<IgnoreCommentedLinesAttribute>(
#pragma warning restore CS0618 // Type or member is obsolete
RecordType,
a => {
IgnoreEmptyLines = true;
CommentMarker = a.CommentMarker;
CommentAnyPlace = a.AnyPlace;
});
Attributes.WorkWithFirst<ConditionalRecordAttribute>(
RecordType,
a => {
RecordCondition = a.Condition;
RecordConditionSelector = a.ConditionSelector;
if (RecordCondition == RecordCondition.ExcludeIfMatchRegex ||
RecordCondition == RecordCondition.IncludeIfMatchRegex) {
RecordConditionRegEx = new Regex(RecordConditionSelector,
RegexOptions.Compiled | RegexOptions.IgnoreCase |
RegexOptions.ExplicitCapture);
}
});
if (CheckInterface(RecordType, typeof (INotifyRead)))
NotifyRead = true;
if (CheckInterface(RecordType, typeof (INotifyWrite)))
NotifyWrite = true;
// Create fields
// Search for cached fields
var fields = new List<FieldInfo>(ReflectionHelper.RecursiveGetFields(RecordType));
Fields = CreateCoreFields(fields, recordAttribute);
if (FieldCount == 0) {
//throw new BadUsageException(Messages.Errors.ClassWithOutFields.ClassName(RecordType.Name).Text);
throw new BadUsageException("FileHelperMsg_ClassWithOutFields", new List<string>() { RecordType.Name });
}
if (recordAttribute is FixedLengthRecordAttribute) {
// Defines the initial size of the StringBuilder
SizeHint = 0;
for (int i = 0; i < FieldCount; i++)
SizeHint += ((FixedLengthField) Fields[i]).FieldLength;
}
}
#endregion
#region " CreateFields "
/// <summary>
/// Parse the attributes on the class and create an ordered list of
/// fields we are extracting from the record
/// </summary>
/// <param name="fields">Complete list of fields in class</param>
/// <param name="recordAttribute">Type of record, fixed or delimited</param>
/// <returns>List of fields we are extracting</returns>
private static FieldBase[] CreateCoreFields(IList<FieldInfo> fields, TypedRecordAttribute recordAttribute)
{
var resFields = new List<FieldBase>();
// count of Properties
var automaticFields = 0;
// count of normal fields
var genericFields = 0;
for (int i = 0; i < fields.Count; i++) {
FieldBase currentField = FieldBase.CreateField(fields[i], recordAttribute);
if (currentField == null)
continue;
if (currentField.FieldInfo.IsDefined(typeof (CompilerGeneratedAttribute), false))
automaticFields++;
else
genericFields++;
// Add to the result
resFields.Add(currentField);
if (resFields.Count > 1)
CheckForOrderProblems(currentField, resFields);
}
if (automaticFields > 0 &&
genericFields > 0 && SumOrder(resFields) == 0) {
//throw new BadUsageException(Messages.Errors.MixOfStandardAndAutoPropertiesFields.ClassName(resFields[0].FieldInfo.DeclaringType.Name).Text);
throw new BadUsageException("FileHelperMsg_MixOfStandardAndAutoPropertiesFields", new List<string>() { resFields[0].FieldInfo.DeclaringType.Name });
}
SortFieldsByOrder(resFields);
CheckForOptionalAndArrayProblems(resFields);
return resFields.ToArray();
}
private static int SumOrder(List<FieldBase> fields)
{
int res = 0;
foreach (var field in fields)
{
res += field.FieldOrder ?? 0;
}
return res;
}
/// <summary>
/// Check that once one field is optional all following fields are optional
/// <para/>
/// Check that arrays in the middle of a record are of fixed length
/// </summary>
/// <param name="resFields">List of fields to extract</param>
private static void CheckForOptionalAndArrayProblems(List<FieldBase> resFields)
{
for (int i = 0; i < resFields.Count; i++) {
var currentField = resFields[i];
// Dont check the first field
if (i < 1)
continue;
FieldBase prevField = resFields[i - 1];
// Check for optional problems. Previous is optional but current is not
if (prevField.IsOptional
&&
currentField.IsOptional == false
&&
currentField.InNewLine == false) {
//throw new BadUsageException(Messages.Errors.ExpectingFieldOptional.FieldName(prevField.FieldInfo.Name).Text);
throw new BadUsageException("FileHelperMsg_ExpectingFieldOptional", new List<string>() { prevField.FieldInfo.Name });
}
// Check for an array array in the middle of a record that is not a fixed length
if (prevField.IsArray) {
if (prevField.ArrayMinLength == Int32.MinValue) {
//throw new BadUsageException(Messages.Errors.MissingFieldArrayLenghtInNotLastField.FieldName(prevField.FieldInfo.Name).Text);
throw new BadUsageException("FileHelperMsg_MissingFieldArrayLenghtInNotLastField", new List<string>() { prevField.FieldInfo.Name });
}
if (prevField.ArrayMinLength != prevField.ArrayMaxLength) {
//throw new BadUsageException(Messages.Errors.SameMinMaxLengthForArrayNotLastField.FieldName(prevField.FieldInfo.Name).Text);
throw new BadUsageException("FileHelperMsg_SameMinMaxLengthForArrayNotLastField", new List<string>() { prevField.FieldInfo.Name });
}
}
}
}
/// <summary>
/// Sort fields by the order if supplied
/// </summary>
/// <param name="resFields">List of fields to use</param>
private static void SortFieldsByOrder(List<FieldBase> resFields)
{
if (resFields.FindAll(x => x.FieldOrder.HasValue).Count > 0)
resFields.Sort((x, y) => x.FieldOrder.Value.CompareTo(y.FieldOrder.Value));
}
/// <summary>
/// Confirm all fields are either ordered or unordered
/// </summary>
/// <param name="currentField">Newest field</param>
/// <param name="resFields">Other fields we have found</param>
private static void CheckForOrderProblems(FieldBase currentField, List<FieldBase> resFields)
{
if (currentField.FieldOrder.HasValue) {
// If one field has order number set, all others must also have an order number
var fieldWithoutOrder = resFields.Find(x => x.FieldOrder.HasValue == false);
if (fieldWithoutOrder != null) {
//throw new BadUsageException(Messages.Errors.PartialFieldOrder.FieldName(fieldWithoutOrder.FieldInfo.Name).Text);
throw new BadUsageException("FileHelperMsg_PartialFieldOrder", new List<string>() { fieldWithoutOrder.FieldInfo.Name });
}
// No other field should have the same order number
var fieldWithSameOrder =
resFields.Find(x => x != currentField && x.FieldOrder == currentField.FieldOrder);
if (fieldWithSameOrder != null)
{
//throw new BadUsageException(Messages.Errors.SameFieldOrder.FieldName1(currentField.FieldInfo.Name).FieldName2(fieldWithSameOrder.FieldInfo.Name).Text);
throw new BadUsageException("FileHelperMsg_SameFieldOrder", new List<string>() { currentField.FieldInfo.Name, fieldWithSameOrder.FieldInfo.Name });
}
}
else {
// No other field should have order number set
var fieldWithOrder = resFields.Find(x => x.FieldOrder.HasValue);
if (fieldWithOrder != null)
{
var autoPropertyName = FieldBase.AutoPropertyName(currentField.FieldInfo);
if (string.IsNullOrEmpty(autoPropertyName))
//throw new BadUsageException(Messages.Errors.PartialFieldOrder.FieldName(currentField.FieldInfo.Name).Text);
throw new BadUsageException("FileHelperMsg_PartialFieldOrder", new List<string>() { currentField.FieldInfo.Name });
else
//throw new BadUsageException(Messages.Errors.PartialFieldOrderInAutoProperty.PropertyName(autoPropertyName).Text);
throw new BadUsageException("FileHelperMsg_PartialFieldOrderInAutoProperty", new List<string>() { autoPropertyName });
}
}
}
#endregion
#region " FieldIndexes "
/// <summary>
/// Get the index number of the fieldname in the field list
/// </summary>
/// <param name="fieldName">Fieldname to search for</param>
/// <returns>Index in field list</returns>
public int GetFieldIndex(string fieldName)
{
if (mMapFieldIndex == null) {
// Initialize field index map
mMapFieldIndex = new Dictionary<string, int>(FieldCount, StringComparer.Ordinal);
for (int i = 0; i < FieldCount; i++)
{
mMapFieldIndex.Add(Fields[i].FieldInfo.Name, i);
if (Fields[i].FieldInfo.Name != Fields[i].FieldFriendlyName)
mMapFieldIndex.Add(Fields[i].FieldFriendlyName, i);
}
}
int res;
if (!mMapFieldIndex.TryGetValue(fieldName, out res)) {
//throw new BadUsageException(Messages.Errors.FieldNotFound.FieldName(fieldName).ClassName(RecordType.Name).Text);
throw new BadUsageException("FileHelperMsg_FieldNotFound", new List<string> { fieldName, RecordType.Name });
}
return res;
}
#endregion
#region " GetFieldInfo "
/// <summary>
/// Get field information base on name
/// </summary>
/// <param name="name">name to find details for</param>
/// <returns>Field information</returns>
public FieldInfo GetFieldInfo(string name)
{
foreach (var field in Fields) {
if (field.FieldInfo.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
return field.FieldInfo;
}
return null;
}
#endregion
/// <summary>
/// Return the record type information for the record
/// </summary>
/// <param name="type">Type of object to create</param>
/// <returns>Record info for that type</returns>
public static IRecordInfo Resolve(Type type)
{
return RecordInfoFactory.Resolve(type);
}
/// <summary>
/// Create an new instance of the record information
/// </summary>
/// <returns>Deep copy of the RecordInfo class</returns>
private IRecordInfo Clone()
{
var res = new RecordInfo
{
CommentAnyPlace = CommentAnyPlace,
CommentMarker = CommentMarker,
IgnoreEmptyLines = IgnoreEmptyLines,
IgnoreEmptySpaces = IgnoreEmptySpaces,
IgnoreFirst = IgnoreFirst,
IgnoreLast = IgnoreLast,
NotifyRead = NotifyRead,
NotifyWrite = NotifyWrite,
RecordCondition = RecordCondition,
RecordConditionRegEx = RecordConditionRegEx,
RecordConditionSelector = RecordConditionSelector,
RecordType = RecordType,
SizeHint = SizeHint
};
res.Operations = Operations.Clone(res);
res.Fields = new FieldBase[Fields.Length];
for (int i = 0; i < Fields.Length; i++)
res.Fields[i] = Fields[i].Clone();
return res;
}
/// <summary>
/// Check whether the type implements the INotifyRead or INotifyWrite interfaces
/// </summary>
/// <param name="type">Type to check interface</param>
/// <param name="interfaceType">Interface generic type we are checking for eg INotifyRead<></param>
/// <returns>Whether we found interface</returns>
private static bool CheckInterface(Type type, Type interfaceType)
{
return type.GetInterface(interfaceType.FullName) != null;
}
}
}
| |
#region Apache Notice
/*****************************************************************************
* $Header: $
* $Revision: $
* $Date: $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2004 - Gilles Bayon
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
********************************************************************************/
#endregion
#region Using
using System;
using System.Data;
using System.Collections;
using System.Xml.Serialization;
using System.Reflection;
using IBatisNet.Common.Exceptions;
using IBatisNet.Common.Utilities.TypesResolver;
using IBatisNet.DataMapper.Configuration.Alias;
using IBatisNet.DataMapper.TypeHandlers;
using IBatisNet.DataMapper.Configuration.ResultMapping;
using IBatisNet.DataMapper.Configuration.ParameterMapping;
using IBatisNet.DataMapper.Configuration.Cache;
using IBatisNet.DataMapper.Configuration.Sql;
using IBatisNet.DataMapper.Exceptions;
using IBatisNet.DataMapper.Scope;
#endregion
namespace IBatisNet.DataMapper.Configuration.Statements
{
/// <summary>
/// Summary description for Statement.
/// </summary>
[Serializable]
[XmlRoot("statement", Namespace="http://ibatis.apache.org/mapping")]
public class Statement : IStatement
{
#region Constants
private const string DOT = ".";
#endregion
#region Fields
[NonSerialized]
private bool _remapResults = false;
[NonSerialized]
private string _id = string.Empty;
// ResultMap
[NonSerialized]
private string _resultMapName = string.Empty;
[NonSerialized]
private ResultMap _resultMap = null;
// ParameterMap
[NonSerialized]
private string _parameterMapName = string.Empty;
[NonSerialized]
private ParameterMap _parameterMap = null;
// Result Class
[NonSerialized]
private string _resultClassName = string.Empty;
[NonSerialized]
private Type _resultClass = null;
// Parameter Class
[NonSerialized]
private string _parameterClassName = string.Empty;
[NonSerialized]
private Type _parameterClass = null;
// List Class
[NonSerialized]
private string _listClassName = string.Empty;
[NonSerialized]
private Type _listClass = null;
// CacheModel
[NonSerialized]
private string _cacheModelName = string.Empty;
[NonSerialized]
private CacheModel _cacheModel = null;
[NonSerialized]
private ISql _sql = null;
[NonSerialized]
private string _extendStatement = string.Empty;
#endregion
#region Properties
/// <summary>
/// Allow remapping of dynamic SQL
/// </summary>
[XmlAttribute("remapResults")]
public bool RemapResults
{
get { return _remapResults; }
set { _remapResults = value; }
}
/// <summary>
/// Extend statement attribute
/// </summary>
[XmlAttribute("extends")]
public virtual string ExtendStatement
{
get { return _extendStatement; }
set { _extendStatement = value; }
}
/// <summary>
/// The CacheModel name to use.
/// </summary>
[XmlAttribute("cacheModel")]
public string CacheModelName
{
get { return _cacheModelName; }
set { _cacheModelName = value; }
}
/// <summary>
/// Tell us if a cacheModel is attached to this statement.
/// </summary>
[XmlIgnoreAttribute]
public bool HasCacheModel
{
get{ return _cacheModelName.Length >0;}
}
/// <summary>
/// The CacheModel used by this statement.
/// </summary>
[XmlIgnoreAttribute]
public CacheModel CacheModel
{
get { return _cacheModel; }
set { _cacheModel = value; }
}
/// <summary>
/// The list class name to use for strongly typed collection.
/// </summary>
[XmlAttribute("listClass")]
public string ListClassName
{
get { return _listClassName; }
set { _listClassName = value; }
}
/// <summary>
/// The list class type to use for strongly typed collection.
/// </summary>
[XmlIgnoreAttribute]
public Type ListClass
{
get { return _listClass; }
}
/// <summary>
/// The result class name to used.
/// </summary>
[XmlAttribute("resultClass")]
public string ResultClassName
{
get { return _resultClassName; }
set { _resultClassName = value; }
}
/// <summary>
/// The result class type to used.
/// </summary>
[XmlIgnoreAttribute]
public Type ResultClass
{
get { return _resultClass; }
}
/// <summary>
/// The parameter class name to used.
/// </summary>
[XmlAttribute("parameterClass")]
public string ParameterClassName
{
get { return _parameterClassName; }
set { _parameterClassName = value; }
}
/// <summary>
/// The parameter class type to used.
/// </summary>
[XmlIgnoreAttribute]
public Type ParameterClass
{
get { return _parameterClass; }
}
/// <summary>
/// Name used to identify the statement amongst the others.
/// </summary>
[XmlAttribute("id")]
public string Id
{
get { return _id; }
set
{
if ((value == null) || (value.Length < 1))
throw new DataMapperException("The id attribute is required in a statement tag.");
_id= value;
}
}
/// <summary>
/// The sql statement
/// </summary>
[XmlIgnoreAttribute]
public ISql Sql
{
get { return _sql; }
set
{
if (value == null)
throw new DataMapperException("The sql statement query text is required in the statement tag "+_id);
_sql = value;
}
}
/// <summary>
/// The ResultMap name used by the statement.
/// </summary>
[XmlAttribute("resultMap")]
public string ResultMapName
{
get { return _resultMapName; }
set { _resultMapName = value; }
}
/// <summary>
/// The ParameterMap name used by the statement.
/// </summary>
[XmlAttribute("parameterMap")]
public string ParameterMapName
{
get { return _parameterMapName; }
set { _parameterMapName = value; }
}
/// <summary>
/// The ResultMap used by the statement.
/// </summary>
[XmlIgnoreAttribute]
public ResultMap ResultMap
{
get { return _resultMap; }
}
/// <summary>
/// The parameterMap used by the statement.
/// </summary>
[XmlIgnoreAttribute]
public ParameterMap ParameterMap
{
get { return _parameterMap; }
set { _parameterMap = value; }
}
/// <summary>
/// The type of the statement (text or procedure)
/// Default Text.
/// </summary>
/// <example>Text or StoredProcedure</example>
[XmlIgnoreAttribute]
public virtual CommandType CommandType
{
get { return CommandType.Text; }
}
#endregion
#region Constructor (s) / Destructor
/// <summary>
/// Do not use direclty, only for serialization.
/// </summary>
public Statement() {}
#endregion
#region Methods
/// <summary>
/// Initialize an statement for the sqlMap.
/// </summary>
/// <param name="configurationScope">The scope of the configuration</param>
internal virtual void Initialize(ConfigurationScope configurationScope)
{
if (_resultMapName != string.Empty )
{
_resultMap = configurationScope.SqlMapper.GetResultMap( _resultMapName);
}
if (_parameterMapName != string.Empty )
{
_parameterMap = configurationScope.SqlMapper.GetParameterMap( _parameterMapName);
}
if (_resultClassName != string.Empty )
{
_resultClass = configurationScope.SqlMapper.GetType(_resultClassName);
}
if (_parameterClassName != string.Empty )
{
_parameterClass = configurationScope.SqlMapper.GetType(_parameterClassName);
}
if (_listClassName != string.Empty )
{
_listClass = configurationScope.SqlMapper.GetType(_listClassName);
}
}
/// <summary>
/// Create an instance of result class.
/// </summary>
/// <returns>An object.</returns>
public object CreateInstanceOfResultClass()
{
if (_resultClass.IsPrimitive || _resultClass == typeof (string) )
{
TypeCode typeCode = Type.GetTypeCode(_resultClass);
return TypeAliasResolver.InstantiatePrimitiveType(typeCode);
}
else
{
if (_resultClass == typeof (Guid))
{
return Guid.Empty;
}
else if (_resultClass == typeof (TimeSpan))
{
return new TimeSpan(0);
}
else
{
return Activator.CreateInstance(_resultClass);
}
}
}
/// <summary>
/// Create an instance of 'IList' class.
/// </summary>
/// <returns>An object which implment IList.</returns>
public IList CreateInstanceOfListClass()
{
return (IList)Activator.CreateInstance(_listClass);
}
#endregion
}
}
| |
#pragma warning disable 1587
#region Header
///
/// JsonData.cs
/// Generic type to hold JSON data (objects, arrays, and so on). This is
/// the default type returned by JsonMapper.ToObject().
///
/// The authors disclaim copyright to this source code. For more details, see
/// the COPYING file included with this distribution.
///
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
#if (WIN_RT || WINDOWS_PHONE)
using Amazon.MissingTypes;
#endif
namespace ThirdParty.Json.LitJson
{
public class JsonData : IJsonWrapper, IEquatable<JsonData>
{
#region Fields
private IList<JsonData> inst_array;
private bool inst_boolean;
private double inst_double;
private int inst_int;
private long inst_long;
private IDictionary<string, JsonData> inst_object;
private string inst_string;
private string json;
private JsonType type;
// Used to implement the IOrderedDictionary interface
private IList<KeyValuePair<string, JsonData>> object_list;
#endregion
#region Properties
public int Count {
get { return EnsureCollection ().Count; }
}
public bool IsArray {
get { return type == JsonType.Array; }
}
public bool IsBoolean {
get { return type == JsonType.Boolean; }
}
public bool IsDouble {
get { return type == JsonType.Double; }
}
public bool IsInt {
get { return type == JsonType.Int; }
}
public bool IsLong {
get { return type == JsonType.Long; }
}
public bool IsObject {
get { return type == JsonType.Object; }
}
public bool IsString {
get { return type == JsonType.String; }
}
#endregion
#region ICollection Properties
int ICollection.Count {
get {
return Count;
}
}
bool ICollection.IsSynchronized {
get {
return EnsureCollection ().IsSynchronized;
}
}
object ICollection.SyncRoot {
get {
return EnsureCollection ().SyncRoot;
}
}
#endregion
#region IDictionary Properties
bool IDictionary.IsFixedSize {
get {
return EnsureDictionary ().IsFixedSize;
}
}
bool IDictionary.IsReadOnly {
get {
return EnsureDictionary ().IsReadOnly;
}
}
ICollection IDictionary.Keys {
get {
EnsureDictionary ();
IList<string> keys = new List<string> ();
foreach (KeyValuePair<string, JsonData> entry in
object_list) {
keys.Add (entry.Key);
}
return (ICollection) keys;
}
}
ICollection IDictionary.Values {
get {
EnsureDictionary ();
IList<JsonData> values = new List<JsonData> ();
foreach (KeyValuePair<string, JsonData> entry in
object_list) {
values.Add (entry.Value);
}
return (ICollection) values;
}
}
#endregion
#region IJsonWrapper Properties
bool IJsonWrapper.IsArray {
get { return IsArray; }
}
bool IJsonWrapper.IsBoolean {
get { return IsBoolean; }
}
bool IJsonWrapper.IsDouble {
get { return IsDouble; }
}
bool IJsonWrapper.IsInt {
get { return IsInt; }
}
bool IJsonWrapper.IsLong {
get { return IsLong; }
}
bool IJsonWrapper.IsObject {
get { return IsObject; }
}
bool IJsonWrapper.IsString {
get { return IsString; }
}
#endregion
#region IList Properties
bool IList.IsFixedSize {
get {
return EnsureList ().IsFixedSize;
}
}
bool IList.IsReadOnly {
get {
return EnsureList ().IsReadOnly;
}
}
#endregion
#region IDictionary Indexer
object IDictionary.this[object key] {
get {
return EnsureDictionary ()[key];
}
set {
if (! (key is String))
throw new ArgumentException (
"The key has to be a string");
JsonData data = ToJsonData (value);
this[(string) key] = data;
}
}
#endregion
#region IOrderedDictionary Indexer
object IOrderedDictionary.this[int idx] {
get {
EnsureDictionary ();
return object_list[idx].Value;
}
set {
EnsureDictionary ();
JsonData data = ToJsonData (value);
KeyValuePair<string, JsonData> old_entry = object_list[idx];
inst_object[old_entry.Key] = data;
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> (old_entry.Key, data);
object_list[idx] = entry;
}
}
#endregion
#region IList Indexer
object IList.this[int index] {
get {
return EnsureList ()[index];
}
set {
EnsureList ();
JsonData data = ToJsonData (value);
this[index] = data;
}
}
#endregion
#region Public Indexers
public IEnumerable<string> PropertyNames
{
get
{
EnsureDictionary();
return inst_object.Keys;
}
}
public JsonData this[string prop_name] {
get {
EnsureDictionary ();
JsonData data = null;
inst_object.TryGetValue(prop_name, out data);
return data;
}
set {
EnsureDictionary ();
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> (prop_name, value);
if (inst_object.ContainsKey (prop_name)) {
for (int i = 0; i < object_list.Count; i++) {
if (object_list[i].Key == prop_name) {
object_list[i] = entry;
break;
}
}
} else
object_list.Add (entry);
inst_object[prop_name] = value;
json = null;
}
}
public JsonData this[int index] {
get {
EnsureCollection ();
if (type == JsonType.Array)
return inst_array[index];
return object_list[index].Value;
}
set {
EnsureCollection ();
if (type == JsonType.Array)
inst_array[index] = value;
else {
KeyValuePair<string, JsonData> entry = object_list[index];
KeyValuePair<string, JsonData> new_entry =
new KeyValuePair<string, JsonData> (entry.Key, value);
object_list[index] = new_entry;
inst_object[entry.Key] = value;
}
json = null;
}
}
#endregion
#region Constructors
public JsonData ()
{
}
public JsonData (bool boolean)
{
type = JsonType.Boolean;
inst_boolean = boolean;
}
public JsonData (double number)
{
type = JsonType.Double;
inst_double = number;
}
public JsonData (int number)
{
type = JsonType.Int;
inst_int = number;
}
public JsonData (long number)
{
type = JsonType.Long;
inst_long = number;
}
public JsonData (object obj)
{
if (obj is Boolean) {
type = JsonType.Boolean;
inst_boolean = (bool) obj;
return;
}
if (obj is Double) {
type = JsonType.Double;
inst_double = (double) obj;
return;
}
if (obj is Int32) {
type = JsonType.Int;
inst_int = (int) obj;
return;
}
if (obj is Int64) {
type = JsonType.Long;
inst_long = (long) obj;
return;
}
if (obj is String) {
type = JsonType.String;
inst_string = (string) obj;
return;
}
throw new ArgumentException (
"Unable to wrap the given object with JsonData");
}
public JsonData (string str)
{
type = JsonType.String;
inst_string = str;
}
#endregion
#region Implicit Conversions
public static implicit operator JsonData (Boolean data)
{
return new JsonData (data);
}
public static implicit operator JsonData (Double data)
{
return new JsonData (data);
}
public static implicit operator JsonData (Int32 data)
{
return new JsonData (data);
}
public static implicit operator JsonData (Int64 data)
{
return new JsonData (data);
}
public static implicit operator JsonData (String data)
{
return new JsonData (data);
}
#endregion
#region Explicit Conversions
public static explicit operator Boolean (JsonData data)
{
if (data.type != JsonType.Boolean)
throw new InvalidCastException (
"Instance of JsonData doesn't hold a double");
return data.inst_boolean;
}
public static explicit operator Double (JsonData data)
{
if (data.type != JsonType.Double)
throw new InvalidCastException (
"Instance of JsonData doesn't hold a double");
return data.inst_double;
}
public static explicit operator Int32 (JsonData data)
{
if (data.type != JsonType.Int)
throw new InvalidCastException (
"Instance of JsonData doesn't hold an int");
return data.inst_int;
}
public static explicit operator Int64 (JsonData data)
{
if (data.type != JsonType.Long)
throw new InvalidCastException (
"Instance of JsonData doesn't hold an int");
return data.inst_long;
}
public static explicit operator String (JsonData data)
{
if (data.type != JsonType.String)
throw new InvalidCastException (
"Instance of JsonData doesn't hold a string");
return data.inst_string;
}
#endregion
#region ICollection Methods
void ICollection.CopyTo (Array array, int index)
{
EnsureCollection ().CopyTo (array, index);
}
#endregion
#region IDictionary Methods
void IDictionary.Add (object key, object value)
{
JsonData data = ToJsonData (value);
EnsureDictionary ().Add (key, data);
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> ((string) key, data);
object_list.Add (entry);
json = null;
}
void IDictionary.Clear ()
{
EnsureDictionary ().Clear ();
object_list.Clear ();
json = null;
}
bool IDictionary.Contains (object key)
{
return EnsureDictionary ().Contains (key);
}
IDictionaryEnumerator IDictionary.GetEnumerator ()
{
return ((IOrderedDictionary) this).GetEnumerator ();
}
void IDictionary.Remove (object key)
{
EnsureDictionary ().Remove (key);
for (int i = 0; i < object_list.Count; i++) {
if (object_list[i].Key == (string) key) {
object_list.RemoveAt (i);
break;
}
}
json = null;
}
#endregion
#region IEnumerable Methods
IEnumerator IEnumerable.GetEnumerator ()
{
return EnsureCollection ().GetEnumerator ();
}
#endregion
#region IJsonWrapper Methods
bool IJsonWrapper.GetBoolean ()
{
if (type != JsonType.Boolean)
throw new InvalidOperationException (
"JsonData instance doesn't hold a boolean");
return inst_boolean;
}
double IJsonWrapper.GetDouble ()
{
if (type != JsonType.Double)
throw new InvalidOperationException (
"JsonData instance doesn't hold a double");
return inst_double;
}
int IJsonWrapper.GetInt ()
{
if (type != JsonType.Int)
throw new InvalidOperationException (
"JsonData instance doesn't hold an int");
return inst_int;
}
long IJsonWrapper.GetLong ()
{
if (type != JsonType.Long)
throw new InvalidOperationException (
"JsonData instance doesn't hold a long");
return inst_long;
}
string IJsonWrapper.GetString ()
{
if (type != JsonType.String)
throw new InvalidOperationException (
"JsonData instance doesn't hold a string");
return inst_string;
}
void IJsonWrapper.SetBoolean (bool val)
{
type = JsonType.Boolean;
inst_boolean = val;
json = null;
}
void IJsonWrapper.SetDouble (double val)
{
type = JsonType.Double;
inst_double = val;
json = null;
}
void IJsonWrapper.SetInt (int val)
{
type = JsonType.Int;
inst_int = val;
json = null;
}
void IJsonWrapper.SetLong (long val)
{
type = JsonType.Long;
inst_long = val;
json = null;
}
void IJsonWrapper.SetString (string val)
{
type = JsonType.String;
inst_string = val;
json = null;
}
string IJsonWrapper.ToJson ()
{
return ToJson ();
}
void IJsonWrapper.ToJson (JsonWriter writer)
{
ToJson (writer);
}
#endregion
#region IList Methods
int IList.Add (object value)
{
return Add (value);
}
void IList.Clear ()
{
EnsureList ().Clear ();
json = null;
}
bool IList.Contains (object value)
{
return EnsureList ().Contains (value);
}
int IList.IndexOf (object value)
{
return EnsureList ().IndexOf (value);
}
void IList.Insert (int index, object value)
{
EnsureList ().Insert (index, value);
json = null;
}
void IList.Remove (object value)
{
EnsureList ().Remove (value);
json = null;
}
void IList.RemoveAt (int index)
{
EnsureList ().RemoveAt (index);
json = null;
}
#endregion
#region IOrderedDictionary Methods
IDictionaryEnumerator IOrderedDictionary.GetEnumerator ()
{
EnsureDictionary ();
return new OrderedDictionaryEnumerator (
object_list.GetEnumerator ());
}
void IOrderedDictionary.Insert (int idx, object key, object value)
{
string property = (string) key;
JsonData data = ToJsonData (value);
this[property] = data;
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> (property, data);
object_list.Insert (idx, entry);
}
void IOrderedDictionary.RemoveAt (int idx)
{
EnsureDictionary ();
inst_object.Remove (object_list[idx].Key);
object_list.RemoveAt (idx);
}
#endregion
#region Private Methods
private ICollection EnsureCollection ()
{
if (type == JsonType.Array)
return (ICollection) inst_array;
if (type == JsonType.Object)
return (ICollection) inst_object;
throw new InvalidOperationException (
"The JsonData instance has to be initialized first");
}
private IDictionary EnsureDictionary ()
{
if (type == JsonType.Object)
return (IDictionary) inst_object;
if (type != JsonType.None)
throw new InvalidOperationException (
"Instance of JsonData is not a dictionary");
type = JsonType.Object;
inst_object = new Dictionary<string, JsonData> ();
object_list = new List<KeyValuePair<string, JsonData>> ();
return (IDictionary) inst_object;
}
private IList EnsureList ()
{
if (type == JsonType.Array)
return (IList) inst_array;
if (type != JsonType.None)
throw new InvalidOperationException (
"Instance of JsonData is not a list");
type = JsonType.Array;
inst_array = new List<JsonData> ();
return (IList) inst_array;
}
private JsonData ToJsonData (object obj)
{
if (obj == null)
return null;
if (obj is JsonData)
return (JsonData) obj;
return new JsonData (obj);
}
private static void WriteJson (IJsonWrapper obj, JsonWriter writer)
{
if (obj == null) {
writer.Write(null);
return;
}
if (obj.IsString) {
writer.Write (obj.GetString ());
return;
}
if (obj.IsBoolean) {
writer.Write (obj.GetBoolean ());
return;
}
if (obj.IsDouble) {
writer.Write (obj.GetDouble ());
return;
}
if (obj.IsInt) {
writer.Write (obj.GetInt ());
return;
}
if (obj.IsLong) {
writer.Write (obj.GetLong ());
return;
}
if (obj.IsArray) {
writer.WriteArrayStart ();
foreach (object elem in (IList) obj)
WriteJson ((JsonData) elem, writer);
writer.WriteArrayEnd ();
return;
}
if (obj.IsObject) {
writer.WriteObjectStart ();
foreach (DictionaryEntry entry in ((IDictionary) obj)) {
writer.WritePropertyName ((string) entry.Key);
WriteJson ((JsonData) entry.Value, writer);
}
writer.WriteObjectEnd ();
return;
}
}
#endregion
public int Add (object value)
{
JsonData data = ToJsonData (value);
json = null;
return EnsureList ().Add (data);
}
public void Clear ()
{
if (IsObject) {
((IDictionary) this).Clear ();
return;
}
if (IsArray) {
((IList) this).Clear ();
return;
}
}
public bool Equals (JsonData x)
{
if (x == null)
return false;
if (x.type != this.type)
return false;
switch (this.type) {
case JsonType.None:
return true;
case JsonType.Object:
return this.inst_object.Equals (x.inst_object);
case JsonType.Array:
return this.inst_array.Equals (x.inst_array);
case JsonType.String:
return this.inst_string.Equals (x.inst_string);
case JsonType.Int:
return this.inst_int.Equals (x.inst_int);
case JsonType.Long:
return this.inst_long.Equals (x.inst_long);
case JsonType.Double:
return this.inst_double.Equals (x.inst_double);
case JsonType.Boolean:
return this.inst_boolean.Equals (x.inst_boolean);
}
return false;
}
public JsonType GetJsonType ()
{
return type;
}
public void SetJsonType (JsonType type)
{
if (this.type == type)
return;
switch (type) {
case JsonType.None:
break;
case JsonType.Object:
inst_object = new Dictionary<string, JsonData> ();
object_list = new List<KeyValuePair<string, JsonData>> ();
break;
case JsonType.Array:
inst_array = new List<JsonData> ();
break;
case JsonType.String:
inst_string = default (String);
break;
case JsonType.Int:
inst_int = default (Int32);
break;
case JsonType.Long:
inst_long = default (Int64);
break;
case JsonType.Double:
inst_double = default (Double);
break;
case JsonType.Boolean:
inst_boolean = default (Boolean);
break;
}
this.type = type;
}
public string ToJson ()
{
if (json != null)
return json;
StringWriter sw = new StringWriter ();
JsonWriter writer = new JsonWriter (sw);
writer.Validate = false;
WriteJson (this, writer);
json = sw.ToString ();
return json;
}
public void ToJson (JsonWriter writer)
{
bool old_validate = writer.Validate;
writer.Validate = false;
WriteJson (this, writer);
writer.Validate = old_validate;
}
public override string ToString ()
{
switch (type) {
case JsonType.Array:
return "JsonData array";
case JsonType.Boolean:
return inst_boolean.ToString ();
case JsonType.Double:
return inst_double.ToString ();
case JsonType.Int:
return inst_int.ToString ();
case JsonType.Long:
return inst_long.ToString ();
case JsonType.Object:
return "JsonData object";
case JsonType.String:
return inst_string;
}
return "Uninitialized JsonData";
}
}
internal class OrderedDictionaryEnumerator : IDictionaryEnumerator
{
IEnumerator<KeyValuePair<string, JsonData>> list_enumerator;
public object Current {
get { return Entry; }
}
public DictionaryEntry Entry {
get {
KeyValuePair<string, JsonData> curr = list_enumerator.Current;
return new DictionaryEntry (curr.Key, curr.Value);
}
}
public object Key {
get { return list_enumerator.Current.Key; }
}
public object Value {
get { return list_enumerator.Current.Value; }
}
public OrderedDictionaryEnumerator (
IEnumerator<KeyValuePair<string, JsonData>> enumerator)
{
list_enumerator = enumerator;
}
public bool MoveNext ()
{
return list_enumerator.MoveNext ();
}
public void Reset ()
{
list_enumerator.Reset ();
}
}
}
| |
using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Windows.Forms;
namespace MyCsla.Windows
{
/// <summary>
/// Add link to StatusStrip with Status and Animation.
/// <example>
/// 1) Add a StatusStrip to the form and add 2 ToolStripStatusLabels.
/// 2) Add the StatusStripExtender to the form.
/// 3) Set statusStripExtender properties on StatusStrip
/// StatusLabel to toolStripStatusLabel1
/// and AnimationLabel to toolStripStatusLabel2
/// 4) Set status text with
/// statusStripExtender1.SetStatus
/// statusStripExtender1.SetStatusStatic
/// statusStripExtender1.SetStatusWaiting
/// statusStripExtender1.SetStatusWithDuration
/// </example>
///
/// </summary>
[ProvideProperty("StatusLabel", typeof(Control))]
[ProvideProperty("AnimationLabel", typeof(Control))]
public class StatusStripExtender : Component, IExtenderProvider
{
private ToolStripStatusLabel _status;
private ToolStripStatusLabel _animation;
private string _statusDefault = "Ready";
private readonly Timer _timer;
private Timer _progressIndicatorTimer;
private int _statusDefaultDuration = 5000;
private readonly StringCollection _toolTipList;
private int _maximumToolTipLines = 5;
private object _syncRoot = new object();
#region --- Interface IExtenderProvider ----
public bool CanExtend(object extendee)
{
return extendee is StatusStrip;
}
#endregion
#region --- Extender properties ---
[Category("StatusStripExtender")]
public ToolStripStatusLabel GetStatusLabel(Control control)
{
return StatusControl;
}
[Category("StatusStripExtender")]
public void SetStatusLabel(Control control, ToolStripStatusLabel statusLabel)
{
StatusControl = statusLabel;
}
[Category("StatusStripExtender")]
public ToolStripStatusLabel GetAnimationLabel(Control control)
{
return AnimationControl;
}
[Category("StatusStripExtender")]
public void SetAnimationLabel(Control control, ToolStripStatusLabel animationLabel)
{
AnimationControl = animationLabel;
}
#endregion
#region // --- Constructor ---
/// <summary>
/// Initializes a new instance of the <see cref="StatusStripExtender"/> class.
/// </summary>
public StatusStripExtender()
{
_timer = new Timer { Enabled = false, Interval = _statusDefaultDuration };
_timer.Tick += _timer_Tick;
_toolTipList = new StringCollection();
}
#endregion
#region // --- Public properties ---
/// <summary>
/// Gets or sets the ToolStripStatusLabel for Status.
/// </summary>
/// <value>The status control.</value>
[Category("ToolStrip"), Description("Gets or sets the ToolStripStatusLabel for Status.")]
public ToolStripStatusLabel StatusControl
{
set
{
if (value == null && _status != null)
{
ReleaseStatus();
}
else
{
if (_animation == value && value != null)
{
throw new ArgumentException("StatusControl and AnimationControl can't be the same control.");
}
_status = value;
InitStatus();
}
}
get
{
return _status;
}
}
/// <summary>
/// Gets or sets the default Status.
/// </summary>
/// <value>The status default text.</value>
[Category("StatusControl"), Description("Gets or sets the default Status.")]
[Localizable(true)]
[DefaultValue("Klar")]
public string StatusDefault
{
set
{
_statusDefault = value;
SetStatusToDefault();
}
get
{
return _statusDefault;
}
}
/// <summary>
/// Gets or sets the maximum Tool Tip Lines to show (1-10, default 5).
/// </summary>
/// <value>The maximum number of Tool Tip Lines.</value>
[Category("StatusControl"), Description("Maximum lines to show in the ToolTip text. Valid value is 1 to 10.")]
[DefaultValue(5)]
public int MaximumToolTipLines
{
set
{
_maximumToolTipLines = value;
if (_maximumToolTipLines < 1)
{
_maximumToolTipLines = 1;
}
if (_maximumToolTipLines > 10)
{
_maximumToolTipLines = 10;
}
}
get
{
return _maximumToolTipLines;
}
}
private void SetStatusToolTip(string text)
{
if (!DesignMode)
{
_toolTipList.Insert(0, "(" + DateTime.Now.ToLongTimeString() + ") " + text);
if (_toolTipList.Count > _maximumToolTipLines)
{
_toolTipList.RemoveAt(_maximumToolTipLines);
}
string[] toolTipArray = new string[_maximumToolTipLines];
_toolTipList.CopyTo(toolTipArray, 0);
_status.ToolTipText = string.Join("\n", toolTipArray).TrimEnd();
}
}
/// <summary>
/// Gets or sets the delay.
/// </summary>
/// <value>The delay.</value>
[Category("StatusControl"), Description("Delay in milliseconds to show the Status")]
[DefaultValue(5000)]
public int Delay
{
set
{
_statusDefaultDuration = value;
_timer.Interval = _statusDefaultDuration;
}
get
{
return _statusDefaultDuration;
}
}
public void SetStatusToDefault()
{
UpdateStatusStrip(_statusDefault, false, false, -1);
}
#endregion
#region --- Public funtions --
#region // --- Public Animation ---
/// <summary>
/// Gets or sets the Animation control.
/// </summary>
/// <value>The animation control.</value>
[Category("ToolStrip"), Description("Gets or sets the Animation control.")]
public ToolStripStatusLabel AnimationControl
{
set
{
if (value == null && _animation != null)
{
ReleaseAnimation();
}
else
{
if (_status == value && value != null)
{
throw new ArgumentException("AnimationControl and StatusControl can't be the same control.");
}
_animation = value;
InitAnimation();
}
}
get
{
return _animation;
}
}
/// <summary>
/// Gets or sets a value indicating whether the Animation control is visible].
/// </summary>
/// <value><c>true</c> if the Animation control is visible; otherwise, <c>false</c>.</value>
[Browsable(false)]
[ReadOnly(true)]
[DefaultValue(true)]
public bool AnimationVisible
{
set
{
if (_animation != null)
{
_animation.Visible = value;
}
}
get
{
if (_animation != null)
{
return _animation.Visible;
}
else
{
return true;
}
}
}
#endregion
/// <summary>
/// Sets the statu to defaultstatus and stop progress indicator from running.
/// </summary>
public void SetStatus()
{
SetStatus(_statusDefault);
}
/// <summary>
/// Set status message and stops the progress indicator from running
/// </summary>
/// <param name="text">The text.</param>
public void SetStatus(string text)
{
SetStatus(text, _statusDefaultDuration);
}
/// <summary>
/// Set status message and stops the progress indicator from running
/// </summary>
/// <param name="text">The text.</param>
/// <param name="durationMilliseconds">The duration milliseconds.</param>
public void SetStatus(string text, int durationMilliseconds)
{
UpdateStatusStrip(text, false, false, durationMilliseconds);
}
/// <summary>
/// Sets the Status and keep it until new text.
/// </summary>
public void SetStatusStatic()
{
SetStatusStatic(_statusDefault);
}
/// <summary>
/// Sets the Status and keep it until new text.
/// </summary>
/// <param name="text">The text.</param>
public void SetStatusStatic(string text)
{
UpdateStatusStrip(text, false, false, -1);
}
/// <summary>
/// Sets the duration of the status with.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="duration">The duration.</param>
public void SetStatusWithDuration(string text, int duration)
{
UpdateStatusStrip(text, false, false, duration);
}
/// <summary>
/// Updates the status bar with the specified message. The message is reset after a few seconds.
/// Progress indicator is NOT shown
/// </summary>
/// <param name="message">The message.</param>
/// <param name="formatParams">Formatting parameters</param>
public void SetStatusText(string message, params object[] formatParams)
{
var formattedMessage = string.Format(message, formatParams);
UpdateStatusStrip(formattedMessage, false, false, _statusDefaultDuration);
}
/// <summary>
/// Updates the status bar with the specified message. The message is not reset until "SetStatus()" is called
/// Progress indicator IS shown
/// Large IS shown
/// </summary>
/// <param name="message">The message.</param>
/// <param name="formatParams">The format params.</param>
public void SetStatusWaiting(string message, params object[] formatParams)
{
SetStatusWaiting(message, true, formatParams);
}
/// <summary>
/// Updates the status bar with the specified message. The message is not reset until "SetStatus()" is called
/// Progress indicator IS shown
/// Large progress indicator is displayed depending on "displayLargeProgressIndicator"
/// </summary>
/// <param name="message">The message.</param>
/// <param name="displayLargeProgressindicator">if set to <c>true</c> [display large progressindicator].</param>
/// <param name="formatParams">Formatting parameters</param>
public void SetStatusWaiting(string message, bool displayLargeProgressindicator, params object[] formatParams)
{
var formattedMessage = string.Format(message, formatParams);
UpdateStatusStrip(formattedMessage, true, displayLargeProgressindicator, -1);
}
/// <summary>
/// Updates the status strip.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="showProgressIndicator">if set to <c>true</c> [show progress indicator].</param>
/// <param name="showLargeProgressIndicator">if set to <c>true</c> [show large progress indicator].</param>
/// <param name="durationMilliseconds"></param>
public void UpdateStatusStrip(string message, bool showProgressIndicator, bool showLargeProgressIndicator, int durationMilliseconds)
{
//if (this..InvokeRequired)
//{
// ParentForm.Invoke(new StatusStripDelegate(UpdateStatusStrip), message, showProgressIndicator, showLargeProgressIndicator);
//}
lock (_syncRoot)
{
if (_progressIndicatorTimer != null)
_progressIndicatorTimer.Stop();
SplashPanel.Close();
if (showProgressIndicator)
{
SetStatusTextStaticPrivate(message);
if (showLargeProgressIndicator)
{
//If still waiting after 2 seconds, show a larger progressindicator
_progressIndicatorTimer = new Timer { Interval = 2000 };
_progressIndicatorTimer.Tick += TimerShowBusyIndicator;
_progressIndicatorTimer.Start();
}
}
else
{
if (string.IsNullOrEmpty(message))
SetStatusToDefaultPrivate();
else
SetStatusTextPrivate(message, durationMilliseconds);
}
AnimationVisible = showProgressIndicator;
}
}
#endregion
#region Private Methods
/// <summary>
/// Sets the Status.
/// </summary>
/// <param name="text">The text.</param>
private void SetStatusTextPrivate(string text)
{
SetStatusWithDurationPrivate(text, _statusDefaultDuration);
}
/// <summary>
/// Sets the Status.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="durationMilliseconds">The duration milliseconds.</param>
private void SetStatusTextPrivate(string text, int durationMilliseconds)
{
SetStatusWithDurationPrivate(text, durationMilliseconds);
}
/// <summary>
/// Sets the Status and keep it until new text.
/// </summary>
/// <param name="text">The text.</param>
private void SetStatusTextStaticPrivate(string text)
{
SetStatusWithDurationPrivate(text, -1);
}
/// <summary>
/// Sets the Status with delay.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="durationMilliseconds">The duration in milliseconds.</param>
private void SetStatusWithDurationPrivate(string text, int durationMilliseconds)
{
_status.Text = text;
SetStatusToolTip(text);
if (durationMilliseconds < 0)
{
_timer.Enabled = false;
_timer.Interval = _statusDefaultDuration;
}
else
{
if (_timer.Enabled)
{
_timer.Enabled = false;
_timer.Interval = durationMilliseconds;
_timer.Enabled = true;
}
else
{
_timer.Enabled = true;
}
}
}
/// <summary>
/// Sets the status to Default.
/// </summary>
private void SetStatusToDefaultPrivate()
{
if (_status != null)
{
if (_status.Text != _statusDefault || _toolTipList.Count == 0)
{
_status.Text = _statusDefault;
SetStatusToolTip(_statusDefault);
}
}
}
/// <summary>
/// Hides the temporary wait indicator.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void HideTemporaryWaitIndicator(object sender, EventArgs e)
{
lock (_syncRoot)
{
var timer = sender as Timer;
if (timer != null) timer.Stop();
SplashPanel.Close();
SetStatusToDefault();
AnimationVisible = false;
}
}
/// <summary>
/// Handles the Tick event of the _progressIndicatorTimer
/// Displays a large progressindicator
/// </summary>
/// <param name="sender">The timer that triggered the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void TimerShowBusyIndicator(object sender, EventArgs e)
{
lock (_syncRoot)
{
var timer = sender as Timer;
if (timer != null) timer.Stop();
SplashPanel.Show((AnimationControl).Owner.FindForm(), StatusControl.Text);
}
}
#endregion
#region // --- Private Status ---
private void InitStatus()
{
if (_status != null)
{
SetStatusToDefault();
_status.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
_status.Spring = true;
if (DesignMode)
{
_status.Owner.ShowItemToolTips = true;
}
}
}
void _timer_Tick(object sender, EventArgs e)
{
_timer.Enabled = false;
SetStatusToDefault();
_timer.Interval = _statusDefaultDuration;
}
private void ReleaseStatus()
{
if (_status != null)
{
_status.Text = "# Not in use #";
_status.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
_status.Spring = false;
_status = null;
}
}
#endregion
#region // --- Private Animation ---
private void InitAnimation()
{
if (_animation != null)
{
_animation.DisplayStyle = ToolStripItemDisplayStyle.Image;
_animation.ImageScaling = ToolStripItemImageScaling.None;
_animation.Image = Properties.Resources.status_anim;
if (!DesignMode)
{
_animation.Visible = false;
}
}
}
private void ReleaseAnimation()
{
if (_animation != null)
{
_animation.Image = null;
_animation.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
_animation.ImageScaling = ToolStripItemImageScaling.SizeToFit;
_animation.Text = "# Not in use #";
if (!DesignMode)
{
_animation.Visible = true;
}
_animation = null;
}
}
#endregion
} // public class StatusStripExtender
}
| |
/*
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 MSD_PCC_NaNFixture
{
internal string mgaFile = null;
public MSD_PCC_NaNFixture()
{
this.mgaFile = Test.ImportXME2Mga("MSD_PCC_NaN", "MSD_PCC_NaN.xme");
}
}
public partial class MSD_PCC_NaN : IUseFixture<MSD_PCC_NaNFixture>
{
internal string mgaFile { get { return this.fixture.mgaFile; } }
private MSD_PCC_NaNFixture fixture { get; set; }
public void SetFixture(MSD_PCC_NaNFixture data)
{
this.fixture = data;
}
[Fact]
[Trait("Model", "MSD_PCC_NaN")]
[Trait("ProjectImport/Open", "MSD_PCC_NaN")]
public void ProjectXmeImport()
{
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
}
[Fact]
[Trait("Model", "MSD_PCC_NaN")]
[Trait("ProjectImport/Open", "MSD_PCC_NaN")]
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", "MSD_PCC_NaN")]
[Trait("CyPhy2Modelica", "MSD_PCC_NaN")]
public void MSD_dymola_cfg879()
{
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
CyPhyGUIs.IInterpreterResult result = null;
try
{
result = CyPhy2ModelicaRunner.Run("MSD_dymola_cfg879", mgaFile,
"/@TestBenches|kind=Testing|relpos=0/@PCC_NaN|kind=Testing|relpos=0/@MSD_dymola_cfg879|kind=TestBench|relpos=0");
}
catch (META.InterpreterException ex)
{
Console.WriteLine(ex.Message);
Assert.NotNull(result);
}
Assert.NotNull(result);
Assert.True(result.Success, "Interpreter return with result.Success as false!");
var runCommand = result.RunCommand.Split(new char[] { ' ' }).FirstOrDefault();
Assert.True(File.Exists(Path.Combine(Path.GetDirectoryName(mgaFile), "MSD_dymola_cfg879", runCommand)),
string.Format("RunCommand file : {0}, does not exist.", runCommand));
}
[Fact]
[Trait("Model", "MSD_PCC_NaN")]
[Trait("CyPhy2Modelica", "MSD_PCC_NaN")]
public void MSD_dymola_cfg871()
{
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
CyPhyGUIs.IInterpreterResult result = null;
try
{
result = CyPhy2ModelicaRunner.Run("MSD_dymola_cfg871", mgaFile,
"/@TestBenches|kind=Testing|relpos=0/@PCC_NaN|kind=Testing|relpos=0/@MSD_dymola_cfg871|kind=TestBench|relpos=0");
}
catch (META.InterpreterException ex)
{
Console.WriteLine(ex.Message);
Assert.NotNull(result);
}
Assert.NotNull(result);
Assert.True(result.Success, "Interpreter return with result.Success as false!");
var runCommand = result.RunCommand.Split(new char[] { ' ' }).FirstOrDefault();
Assert.True(File.Exists(Path.Combine(Path.GetDirectoryName(mgaFile), "MSD_dymola_cfg871", runCommand)),
string.Format("RunCommand file : {0}, does not exist.", runCommand));
}
[Fact]
[Trait("Model", "MSD_PCC_NaN")]
[Trait("CyPhy2Modelica", "MSD_PCC_NaN")]
public void MSD_dymola_cfg844()
{
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
CyPhyGUIs.IInterpreterResult result = null;
try
{
result = CyPhy2ModelicaRunner.Run("MSD_dymola_cfg844", mgaFile,
"/@TestBenches|kind=Testing|relpos=0/@PCC_NaN|kind=Testing|relpos=0/@MSD_dymola_cfg844|kind=TestBench|relpos=0");
}
catch (META.InterpreterException ex)
{
Console.WriteLine(ex.Message);
Assert.NotNull(result);
}
Assert.NotNull(result);
Assert.True(result.Success, "Interpreter return with result.Success as false!");
var runCommand = result.RunCommand.Split(new char[] { ' ' }).FirstOrDefault();
Assert.True(File.Exists(Path.Combine(Path.GetDirectoryName(mgaFile), "MSD_dymola_cfg844", runCommand)),
string.Format("RunCommand file : {0}, does not exist.", runCommand));
}
[Fact]
[Trait("Model", "MSD_PCC_NaN")]
[Trait("CyPhy2Modelica", "MSD_PCC_NaN")]
public void MSD_dymola_cfg299()
{
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
CyPhyGUIs.IInterpreterResult result = null;
try
{
result = CyPhy2ModelicaRunner.Run("MSD_dymola_cfg299", mgaFile,
"/@TestBenches|kind=Testing|relpos=0/@PCC_NaN|kind=Testing|relpos=0/@MSD_dymola_cfg299|kind=TestBench|relpos=0");
}
catch (META.InterpreterException ex)
{
Console.WriteLine(ex.Message);
Assert.NotNull(result);
}
Assert.NotNull(result);
Assert.True(result.Success, "Interpreter return with result.Success as false!");
var runCommand = result.RunCommand.Split(new char[] { ' ' }).FirstOrDefault();
Assert.True(File.Exists(Path.Combine(Path.GetDirectoryName(mgaFile), "MSD_dymola_cfg299", runCommand)),
string.Format("RunCommand file : {0}, does not exist.", runCommand));
}
[Fact]
[Trait("Model", "MSD_PCC_NaN")]
[Trait("CyPhy2Modelica", "MSD_PCC_NaN")]
public void MSD_dymola_cfg310()
{
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
CyPhyGUIs.IInterpreterResult result = null;
try
{
result = CyPhy2ModelicaRunner.Run("MSD_dymola_cfg310", mgaFile,
"/@TestBenches|kind=Testing|relpos=0/@PCC_NaN|kind=Testing|relpos=0/@MSD_dymola_cfg310|kind=TestBench|relpos=0");
}
catch (META.InterpreterException ex)
{
Console.WriteLine(ex.Message);
Assert.NotNull(result);
}
Assert.NotNull(result);
Assert.True(result.Success, "Interpreter return with result.Success as false!");
var runCommand = result.RunCommand.Split(new char[] { ' ' }).FirstOrDefault();
Assert.True(File.Exists(Path.Combine(Path.GetDirectoryName(mgaFile), "MSD_dymola_cfg310", runCommand)),
string.Format("RunCommand file : {0}, does not exist.", runCommand));
}
[Fact]
[Trait("Model", "MSD_PCC_NaN")]
[Trait("CyPhy2Modelica", "MSD_PCC_NaN")]
public void MSD_om_CA()
{
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
CyPhyGUIs.IInterpreterResult result = null;
try
{
result = CyPhy2ModelicaRunner.Run("MSD_om_CA", mgaFile,
"/@TestBenches|kind=Testing|relpos=0/@SingleConfig|kind=Testing|relpos=0/@MSD_om_CA|kind=TestBench|relpos=0");
}
catch (META.InterpreterException ex)
{
Console.WriteLine(ex.Message);
Assert.NotNull(result);
}
Assert.NotNull(result);
Assert.True(result.Success, "Interpreter return with result.Success as false!");
var runCommand = result.RunCommand.Split(new char[] { ' ' }).FirstOrDefault();
Assert.True(File.Exists(Path.Combine(Path.GetDirectoryName(mgaFile), "MSD_om_CA", runCommand)),
string.Format("RunCommand file : {0}, does not exist.", runCommand));
}
[Fact]
[Trait("Model", "MSD_PCC_NaN")]
[Trait("CyPhy2Modelica", "MSD_PCC_NaN")]
public void MSD_dymola_CA()
{
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
CyPhyGUIs.IInterpreterResult result = null;
try
{
result = CyPhy2ModelicaRunner.Run("MSD_dymola_CA", mgaFile,
"/@TestBenches|kind=Testing|relpos=0/@SingleConfig|kind=Testing|relpos=0/@MSD_dymola_CA|kind=TestBench|relpos=0");
}
catch (META.InterpreterException ex)
{
Console.WriteLine(ex.Message);
Assert.NotNull(result);
}
Assert.NotNull(result);
Assert.True(result.Success, "Interpreter return with result.Success as false!");
var runCommand = result.RunCommand.Split(new char[] { ' ' }).FirstOrDefault();
Assert.True(File.Exists(Path.Combine(Path.GetDirectoryName(mgaFile), "MSD_dymola_CA", runCommand)),
string.Format("RunCommand file : {0}, does not exist.", runCommand));
}
[Fact]
[Trait("Model", "MSD_PCC_NaN")]
[Trait("PCC_NaN", "MSD_PCC_NaN")]
[Trait("Issue", "META-1427")]
public void PCC_JointPCC_NaN_cfg299()
{
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
CyPhyGUIs.IInterpreterResult result = null;
try
{
result = CyPhyPETRunner.Run("PCC_JointPCC_NaN_cfg299", mgaFile,
"/@TestBenches|kind=Testing|relpos=0/@PCC_NaN|kind=Testing|relpos=0/@PCC_NaN|kind=ParametricExplorationFolder|relpos=0/@PCC_JointPCC_NaN_cfg299|kind=ParametricExploration|relpos=0");
}
catch (META.InterpreterException ex)
{
Console.WriteLine(ex.Message);
Assert.NotNull(result);
}
Assert.NotNull(result);
Assert.True(result.Success, "Interpreter return with result.Success as false!");
var runCommand = result.RunCommand.Split(new char[] { ' ' }).FirstOrDefault();
Assert.True(File.Exists(Path.Combine(Path.GetDirectoryName(mgaFile), "PCC_JointPCC_NaN_cfg299", runCommand)),
string.Format("RunCommand file : {0}, does not exist.", runCommand));
}
[Fact]
[Trait("Model", "MSD_PCC_NaN")]
[Trait("PCC_NaN", "MSD_PCC_NaN")]
[Trait("Issue", "META-1427")]
public void PCC_Complexity_NaN_cfg310()
{
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
CyPhyGUIs.IInterpreterResult result = null;
try
{
result = CyPhyPETRunner.Run("PCC_Complexity_NaN_cfg310", mgaFile,
"/@TestBenches|kind=Testing|relpos=0/@PCC_NaN|kind=Testing|relpos=0/@PCC_NaN|kind=ParametricExplorationFolder|relpos=0/@PCC_Complexity_NaN_cfg310|kind=ParametricExploration|relpos=0");
}
catch (META.InterpreterException ex)
{
Console.WriteLine(ex.Message);
Assert.NotNull(result);
}
Assert.NotNull(result);
Assert.True(result.Success, "Interpreter return with result.Success as false!");
var runCommand = result.RunCommand.Split(new char[] { ' ' }).FirstOrDefault();
Assert.True(File.Exists(Path.Combine(Path.GetDirectoryName(mgaFile), "PCC_Complexity_NaN_cfg310", runCommand)),
string.Format("RunCommand file : {0}, does not exist.", runCommand));
}
[Fact]
[Trait("Model", "MSD_PCC_NaN")]
[Trait("PCC_NaN", "MSD_PCC_NaN")]
[Trait("Issue", "META-1427")]
public void PCC_Complexity_NaN_cfg871()
{
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
CyPhyGUIs.IInterpreterResult result = null;
try
{
result = CyPhyPETRunner.Run("PCC_Complexity_NaN_cfg871", mgaFile,
"/@TestBenches|kind=Testing|relpos=0/@PCC_NaN|kind=Testing|relpos=0/@PCC_NaN|kind=ParametricExplorationFolder|relpos=0/@PCC_Complexity_NaN_cfg871|kind=ParametricExploration|relpos=0");
}
catch (META.InterpreterException ex)
{
Console.WriteLine(ex.Message);
Assert.NotNull(result);
}
Assert.NotNull(result);
Assert.True(result.Success, "Interpreter return with result.Success as false!");
var runCommand = result.RunCommand.Split(new char[] { ' ' }).FirstOrDefault();
Assert.True(File.Exists(Path.Combine(Path.GetDirectoryName(mgaFile), "PCC_Complexity_NaN_cfg871", runCommand)),
string.Format("RunCommand file : {0}, does not exist.", runCommand));
}
[Fact]
[Trait("Model", "MSD_PCC_NaN")]
[Trait("PCC_NaN", "MSD_PCC_NaN")]
[Trait("Issue", "META-1427")]
public void PCC_JointPCC_NaN_cfg844()
{
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
CyPhyGUIs.IInterpreterResult result = null;
try
{
result = CyPhyPETRunner.Run("PCC_JointPCC_NaN_cfg844", mgaFile,
"/@TestBenches|kind=Testing|relpos=0/@PCC_NaN|kind=Testing|relpos=0/@PCC_NaN|kind=ParametricExplorationFolder|relpos=0/@PCC_JointPCC_NaN_cfg844|kind=ParametricExploration|relpos=0");
}
catch (META.InterpreterException ex)
{
Console.WriteLine(ex.Message);
Assert.NotNull(result);
}
Assert.NotNull(result);
Assert.True(result.Success, "Interpreter return with result.Success as false!");
var runCommand = result.RunCommand.Split(new char[] { ' ' }).FirstOrDefault();
Assert.True(File.Exists(Path.Combine(Path.GetDirectoryName(mgaFile), "PCC_JointPCC_NaN_cfg844", runCommand)),
string.Format("RunCommand file : {0}, does not exist.", runCommand));
}
[Fact]
[Trait("Model", "MSD_PCC_NaN")]
[Trait("PCC_NaN", "MSD_PCC_NaN")]
[Trait("Issue", "META-1427")]
public void PCC_Complexity_NaN_cfg879()
{
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
CyPhyGUIs.IInterpreterResult result = null;
try
{
result = CyPhyPETRunner.Run("PCC_Complexity_NaN_cfg879", mgaFile,
"/@TestBenches|kind=Testing|relpos=0/@PCC_NaN|kind=Testing|relpos=0/@PCC_NaN|kind=ParametricExplorationFolder|relpos=0/@PCC_Complexity_NaN_cfg879|kind=ParametricExploration|relpos=0");
}
catch (META.InterpreterException ex)
{
Console.WriteLine(ex.Message);
Assert.NotNull(result);
}
Assert.NotNull(result);
Assert.True(result.Success, "Interpreter return with result.Success as false!");
var runCommand = result.RunCommand.Split(new char[] { ' ' }).FirstOrDefault();
Assert.True(File.Exists(Path.Combine(Path.GetDirectoryName(mgaFile), "PCC_Complexity_NaN_cfg879", runCommand)),
string.Format("RunCommand file : {0}, does not exist.", runCommand));
}
[Fact]
[Trait("Model", "MSD_PCC_NaN")]
[Trait("PCC", "MSD_PCC_NaN")]
public void PCC_MSD_om_CA()
{
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
CyPhyGUIs.IInterpreterResult result = null;
try
{
result = CyPhyPETRunner.Run("PCC_MSD_om_CA", mgaFile,
"/@TestBenches|kind=Testing|relpos=0/@SingleConfig|kind=Testing|relpos=0/@PCC_CA|kind=ParametricExplorationFolder|relpos=0/@PCC_MSD_om_CA|kind=ParametricExploration|relpos=0");
}
catch (META.InterpreterException ex)
{
Console.WriteLine(ex.Message);
Assert.NotNull(result);
}
Assert.NotNull(result);
Assert.True(result.Success, "Interpreter return with result.Success as false!");
var runCommand = result.RunCommand.Split(new char[] { ' ' }).FirstOrDefault();
Assert.True(File.Exists(Path.Combine(Path.GetDirectoryName(mgaFile), "PCC_MSD_om_CA", runCommand)),
string.Format("RunCommand file : {0}, does not exist.", runCommand));
}
[Fact]
[Trait("Model", "MSD_PCC_NaN")]
[Trait("PCC", "MSD_PCC_NaN")]
public void PCC_MSD_dymola_CA()
{
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
CyPhyGUIs.IInterpreterResult result = null;
try
{
result = CyPhyPETRunner.Run("PCC_MSD_dymola_CA", mgaFile,
"/@TestBenches|kind=Testing|relpos=0/@SingleConfig|kind=Testing|relpos=0/@PCC_CA|kind=ParametricExplorationFolder|relpos=0/@PCC_MSD_dymola_CA|kind=ParametricExploration|relpos=0");
}
catch (META.InterpreterException ex)
{
Console.WriteLine(ex.Message);
Assert.NotNull(result);
}
Assert.NotNull(result);
Assert.True(result.Success, "Interpreter return with result.Success as false!");
var runCommand = result.RunCommand.Split(new char[] { ' ' }).FirstOrDefault();
Assert.True(File.Exists(Path.Combine(Path.GetDirectoryName(mgaFile), "PCC_MSD_dymola_CA", runCommand)),
string.Format("RunCommand file : {0}, does not exist.", runCommand));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Microsoft.TemplateEngine.Core.Expressions
{
public class OperatorSetBuilder<TToken> : IOperatorMap<Operators, TToken>
where TToken : struct
{
private readonly Func<string, string> _decoder;
private readonly Func<string, string> _encoder;
private readonly Dictionary<Operators, Func<IEvaluable, IEvaluable>> _operatorScopeLookupFactory = new Dictionary<Operators, Func<IEvaluable, IEvaluable>>();
private readonly Dictionary<TToken, Operators> _tokensToOperatorsMap = new Dictionary<TToken, Operators>();
private ITypeConverter _converter;
//TODO: The signatures for encoder and decoder will need to be updated to account
// for encoding/decoding errors, the host will need to be inputted here as well
// for the purposes of logging evaluation/parse errors
public OperatorSetBuilder(Func<string, string> encoder, Func<string, string> decoder)
{
_encoder = encoder ?? Passthrough;
_decoder = decoder ?? Passthrough;
BadSyntaxTokens = new HashSet<TToken>();
NoOpTokens = new HashSet<TToken>();
LiteralSequenceBoundsMarkers = new HashSet<TToken>();
Terminators = new HashSet<TToken>();
_converter = new CustomTypeConverter<OperatorSetBuilder<TToken>>();
}
public ISet<TToken> BadSyntaxTokens { get; }
public TToken CloseGroupToken { get; private set; }
public Operators Identity => Operators.Identity;
public ISet<TToken> LiteralSequenceBoundsMarkers { get; }
public TToken LiteralToken { get; private set; }
public ISet<TToken> NoOpTokens { get; }
public TToken OpenGroupToken { get; private set; }
public IReadOnlyDictionary<Operators, Func<IEvaluable, IEvaluable>> OperatorScopeLookupFactory => _operatorScopeLookupFactory;
public ISet<TToken> Terminators { get; }
public IReadOnlyDictionary<TToken, Operators> TokensToOperatorsMap => _tokensToOperatorsMap;
public OperatorSetBuilder<TToken> Add(TToken token, Func<Operators, bool> precedesOperator = null, Func<object, object, object> evaluate = null)
{
return SetupBinary(Operators.Add, token, evaluate ?? Add, precedesOperator);
}
public OperatorSetBuilder<TToken> And(TToken token, Func<Operators, bool> precedesOperator = null, Func<object, object, object> evaluate = null)
{
return SetupBinary(Operators.And, token, evaluate ?? And, precedesOperator);
}
public OperatorSetBuilder<TToken> BadSyntax(params TToken[] token)
{
BadSyntaxTokens.UnionWith(token);
return this;
}
public OperatorSetBuilder<TToken> BitwiseAnd(TToken token, Func<Operators, bool> precedesOperator = null, Func<object, object, object> evaluate = null)
{
return SetupBinary(Operators.BitwiseAnd, token, evaluate ?? BitwiseAnd, precedesOperator);
}
public OperatorSetBuilder<TToken> BitwiseOr(TToken token, Func<Operators, bool> precedesOperator = null, Func<object, object, object> evaluate = null)
{
return SetupBinary(Operators.BitwiseOr, token, evaluate ?? BitwiseOr, precedesOperator);
}
public OperatorSetBuilder<TToken> CloseGroup(TToken token)
{
CloseGroupToken = token;
return this;
}
public string Decode(string value)
{
return _decoder(value);
}
public OperatorSetBuilder<TToken> Divide(TToken token, Func<Operators, bool> precedesOperator = null, Func<object, object, object> evaluate = null)
{
return SetupBinary(Operators.Divide, token, evaluate ?? Divide, precedesOperator);
}
public string Encode(string value)
{
return _encoder(value);
}
public OperatorSetBuilder<TToken> EqualTo(TToken token, Func<Operators, bool> precedesOperator = null, Func<object, object, object> evaluate = null)
{
return SetupBinary(Operators.EqualTo, token, evaluate ?? EqualTo, precedesOperator);
}
public OperatorSetBuilder<TToken> Exponentiate(TToken token, Func<Operators, bool> precedesOperator = null, Func<object, object, object> evaluate = null)
{
return SetupBinary(Operators.Exponentiate, token, evaluate ?? Exponentiate, precedesOperator);
}
public OperatorSetBuilder<TToken> GreaterThan(TToken token, Func<Operators, bool> precedesOperator = null, Func<object, object, object> evaluate = null)
{
return SetupBinary(Operators.GreaterThan, token, evaluate ?? GreaterThan, precedesOperator);
}
public OperatorSetBuilder<TToken> GreaterThanOrEqualTo(TToken token, Func<Operators, bool> precedesOperator = null, Func<object, object, object> evaluate = null)
{
return SetupBinary(Operators.GreaterThanOrEqualTo, token, evaluate ?? GreaterThanOrEqualTo, precedesOperator);
}
public OperatorSetBuilder<TToken> Ignore(params TToken[] token)
{
NoOpTokens.UnionWith(token);
return this;
}
public OperatorSetBuilder<TToken> LeftShift(TToken token, Func<Operators, bool> precedesOperator = null, Func<object, object, object> evaluate = null)
{
return SetupBinary(Operators.LeftShift, token, evaluate ?? LeftShift, precedesOperator);
}
public OperatorSetBuilder<TToken> LessThan(TToken token, Func<Operators, bool> precedesOperator = null, Func<object, object, object> evaluate = null)
{
return SetupBinary(Operators.LessThan, token, evaluate ?? LessThan, precedesOperator);
}
public OperatorSetBuilder<TToken> LessThanOrEqualTo(TToken token, Func<Operators, bool> precedesOperator = null, Func<object, object, object> evaluate = null)
{
return SetupBinary(Operators.LessThanOrEqualTo, token, evaluate ?? LessThanOrEqualTo, precedesOperator);
}
public OperatorSetBuilder<TToken> Literal(TToken token)
{
LiteralToken = token;
return this;
}
public OperatorSetBuilder<TToken> LiteralBoundsMarkers(params TToken[] token)
{
LiteralSequenceBoundsMarkers.UnionWith(token);
return this;
}
public OperatorSetBuilder<TToken> Multiply(TToken token, Func<Operators, bool> precedesOperator = null, Func<object, object, object> evaluate = null)
{
return SetupBinary(Operators.Multiply, token, evaluate ?? Multiply, precedesOperator);
}
public OperatorSetBuilder<TToken> Not(TToken token, Func<Operators, bool> precedesOperator = null, Func<object, object> evaluate = null)
{
_operatorScopeLookupFactory[Operators.Not] =
x => CreateUnaryChild(x, Operators.Not, evaluate ?? Not);
_tokensToOperatorsMap[token] = Operators.Not;
return this;
}
public OperatorSetBuilder<TToken> NotEqualTo(TToken token, Func<Operators, bool> precedesOperator = null, Func<object, object, object> evaluate = null)
{
return SetupBinary(Operators.NotEqualTo, token, evaluate ?? NotEqualTo, precedesOperator);
}
public OperatorSetBuilder<TToken> OpenGroup(TToken token)
{
OpenGroupToken = token;
return this;
}
public OperatorSetBuilder<TToken> Or(TToken token, Func<Operators, bool> precedesOperator = null, Func<object, object, object> evaluate = null)
{
return SetupBinary(Operators.Or, token, evaluate ?? Or, precedesOperator);
}
public OperatorSetBuilder<TToken> Other(Operators @operator, TToken token, Func<IEvaluable, IEvaluable> nodeFactory)
{
_operatorScopeLookupFactory[@operator] = nodeFactory;
_tokensToOperatorsMap[token] = @operator;
return this;
}
public OperatorSetBuilder<TToken> RightShift(TToken token, Func<Operators, bool> precedesOperator = null, Func<object, object, object> evaluate = null)
{
return SetupBinary(Operators.RightShift, token, evaluate ?? RightShift, precedesOperator);
}
public OperatorSetBuilder<TToken> Subtract(TToken token, Func<Operators, bool> precedesOperator = null, Func<object, object, object> evaluate = null)
{
return SetupBinary(Operators.Subtract, token, evaluate ?? Subtract, precedesOperator);
}
public OperatorSetBuilder<TToken> TerminateWith(params TToken[] token)
{
Terminators.UnionWith(token);
return this;
}
public bool TryConvert<T>(object sender, out T result)
{
return _converter.TryConvert(sender, out result);
}
public OperatorSetBuilder<TToken> TypeConverter<TSelf>(Action<ITypeConverter> configureConverter)
{
_converter = new CustomTypeConverter<TSelf>();
configureConverter(_converter);
return this;
}
public OperatorSetBuilder<TToken> Xor(TToken token, Func<Operators, bool> precedesOperator = null, Func<object, object, object> evaluate = null)
{
return SetupBinary(Operators.Xor, token, evaluate ?? Xor, precedesOperator);
}
private static IEvaluable CreateBinaryChild(IEvaluable active, Operators op, Func<Operators, bool> precedesOperator, Func<object, object, object> evaluate)
{
BinaryScope<Operators> self;
//If we could steal an arg...
if (!active.IsIndivisible)
{
if (active is BinaryScope<Operators> left && precedesOperator(left.Operator))
{
self = new BinaryScope<Operators>(active, op, evaluate)
{
Left = left.Right
};
left.Right.Parent = self;
left.Right = self;
return self;
}
}
//We couldn't steal an arg, "active" is now our left, inject ourselves into
// active's parent in its place
self = new BinaryScope<Operators>(active.Parent, op, evaluate);
if (active.Parent != null)
{
switch (active.Parent)
{
case UnaryScope<Operators> unary:
unary.Parent = self;
break;
case BinaryScope<Operators> binary:
if (binary.Left == active)
{
binary.Left = self;
}
else if (binary.Right == active)
{
binary.Right = self;
}
break;
}
}
active.Parent = self;
self.Left = active;
return self;
}
private static IEvaluable CreateUnaryChild(IEvaluable active, Operators op, Func<object, object> evaluate)
{
UnaryScope<Operators> self = new UnaryScope<Operators>(active, op, evaluate);
active.TryAccept(self);
return self;
}
private static object EqualTo(object left, object right)
{
string l = left as string;
string r = right as string;
if (l != null && r != null)
{
return string.Equals(l, r, StringComparison.OrdinalIgnoreCase);
}
return Equals(l, r);
}
private static object GreaterThan(object left, object right)
{
return ((IComparable)left).CompareTo(right) > 0;
}
private static object GreaterThanOrEqualTo(object left, object right)
{
return ((IComparable)left).CompareTo(right) >= 0;
}
private static object LessThan(object left, object right)
{
return ((IComparable)left).CompareTo(right) < 0;
}
private static object LessThanOrEqualTo(object left, object right)
{
return ((IComparable)left).CompareTo(right) <= 0;
}
private static string Passthrough(string arg)
{
return arg;
}
private static bool Precedes(Operators check, Operators arg)
{
return check < arg;
}
private object Add(object left, object right)
{
if (_converter.TryConvert(left, out long longLeft))
{
if (_converter.TryConvert(right, out long longRight))
{
return longLeft + longRight;
}
if (_converter.TryConvert(right, out double doubleRight))
{
return longLeft + doubleRight;
}
}
else
{
if (_converter.TryConvert(left, out double doubleLeft))
{
if (_converter.TryConvert(right, out long longRight))
{
return doubleLeft + longRight;
}
if (_converter.TryConvert(right, out double doubleRight))
{
return doubleLeft + doubleRight;
}
}
}
return string.Concat(left, right);
}
private object And(object left, object right)
{
if (_converter.TryConvert(left, out bool boolLeft) && _converter.TryConvert(right, out bool boolRight))
{
return boolLeft && boolRight;
}
throw new Exception($"Unable to logical and {left?.GetType()} and {right?.GetType()}");
}
private object BitwiseAnd(object left, object right)
{
if (_converter.TryConvert(left, out long longLeft) && _converter.TryConvert(right, out long longRight))
{
return longLeft & longRight;
}
throw new Exception($"Unable to bitwise and {left?.GetType()} and {right?.GetType()}");
}
private object BitwiseOr(object left, object right)
{
if (_converter.TryConvert(left, out long longLeft) && _converter.TryConvert(right, out long longRight))
{
return longLeft | longRight;
}
throw new Exception($"Unable to bitwise or {left?.GetType()} and {right?.GetType()}");
}
private object Divide(object left, object right)
{
long longRight;
int doubleRight;
if (_converter.TryConvert(left, out long longLeft))
{
if (_converter.TryConvert(right, out longRight))
{
return longLeft / longRight;
}
if (_converter.TryConvert(right, out doubleRight))
{
return longLeft / doubleRight;
}
}
else if (_converter.TryConvert(left, out int doubleLeft))
{
if (_converter.TryConvert(right, out longRight))
{
return doubleLeft / longRight;
}
if (_converter.TryConvert(right, out doubleRight))
{
return doubleLeft / doubleRight;
}
}
throw new Exception($"Cannot divide {left?.GetType()} and {right?.GetType()}");
}
private object Exponentiate(object left, object right)
{
long longRight;
int intRight;
if (_converter.TryConvert(left, out long longLeft))
{
if (_converter.TryConvert(right, out longRight))
{
return Math.Pow(longLeft, longRight);
}
if (_converter.TryConvert(right, out intRight))
{
return Math.Pow(longLeft, intRight);
}
}
else if (_converter.TryConvert(left, out int intLeft))
{
if (_converter.TryConvert(right, out longRight))
{
return Math.Pow(intLeft, longRight);
}
if (_converter.TryConvert(right, out intRight))
{
return Math.Pow(intLeft, intRight);
}
}
throw new Exception($"Cannot exponentiate {left?.GetType()} and {right?.GetType()}");
}
private object LeftShift(object left, object right)
{
if (_converter.TryConvert(left, out long longLeft) && _converter.TryConvert(right, out int intRight))
{
return longLeft << intRight;
}
throw new Exception($"Unable to left shift {left?.GetType()} and {right?.GetType()}");
}
private object Multiply(object left, object right)
{
long longRight;
int doubleRight;
if (_converter.TryConvert(left, out long longLeft))
{
if (_converter.TryConvert(right, out longRight))
{
return longLeft * longRight;
}
if (_converter.TryConvert(right, out doubleRight))
{
return longLeft * doubleRight;
}
}
else if (_converter.TryConvert(left, out int doubleLeft))
{
if (_converter.TryConvert(right, out longRight))
{
return doubleLeft * longRight;
}
if (_converter.TryConvert(right, out doubleRight))
{
return doubleLeft * doubleRight;
}
}
throw new Exception($"Cannot multiply {left?.GetType()} and {right?.GetType()}");
}
private object Not(object operand)
{
if (_converter.TryConvert(operand, out bool l))
{
return !l;
}
throw new Exception($"Unable to logical not {operand?.GetType()}");
}
private object NotEqualTo(object left, object right)
{
if (left is string l && right is string r)
{
return !string.Equals(l, r, StringComparison.OrdinalIgnoreCase);
}
return Not(EqualTo(left, right));
}
private object Or(object left, object right)
{
if (_converter.TryConvert(left, out bool l) && _converter.TryConvert(right, out bool r))
{
return l || r;
}
throw new Exception($"Unable to logical or {left?.GetType()} and {right?.GetType()}");
}
private object RightShift(object left, object right)
{
if (_converter.TryConvert(left, out long longLeft) && _converter.TryConvert(right, out int intRight))
{
return longLeft >> intRight;
}
throw new Exception($"Unable to right shift {left?.GetType()} and {right?.GetType()}");
}
private OperatorSetBuilder<TToken> SetupBinary(Operators op, TToken token, Func<object, object, object> evaluate, Func<Operators, bool> precedesOperator = null)
{
_operatorScopeLookupFactory[op] =
x => CreateBinaryChild(x, op, precedesOperator ?? (a => Precedes(op, a)), evaluate ?? Add);
_tokensToOperatorsMap[token] = op;
return this;
}
private object Subtract(object left, object right)
{
long longRight;
int doubleRight;
if (_converter.TryConvert(left, out long longLeft))
{
if (_converter.TryConvert(right, out longRight))
{
return longLeft - longRight;
}
if (_converter.TryConvert(right, out doubleRight))
{
return longLeft - doubleRight;
}
}
else if (_converter.TryConvert(left, out int doubleLeft))
{
if (_converter.TryConvert(right, out longRight))
{
return doubleLeft - longRight;
}
if (_converter.TryConvert(right, out doubleRight))
{
return doubleLeft - doubleRight;
}
}
throw new Exception($"Cannot subtract {left?.GetType()} and {right?.GetType()}");
}
private object Xor(object left, object right)
{
if (_converter.TryConvert(left, out bool l) && _converter.TryConvert(right, out bool r))
{
return l ^ r;
}
long longRight;
int doubleRight;
if (_converter.TryConvert(left, out long longLeft))
{
if (_converter.TryConvert(right, out longRight))
{
return longLeft ^ longRight;
}
if (_converter.TryConvert(right, out doubleRight))
{
return longLeft ^ doubleRight;
}
}
else if (_converter.TryConvert(left, out int doubleLeft))
{
if (_converter.TryConvert(right, out longRight))
{
return doubleLeft ^ longRight;
}
if (_converter.TryConvert(right, out doubleRight))
{
return doubleLeft ^ doubleRight;
}
}
throw new Exception($"Can't xor {left?.GetType()} and {right?.GetType()}");
}
public class CustomTypeConverter<TScope> : ITypeConverter
{
public Type ScopeType => typeof(TScope);
public ITypeConverter Register<T>(TypeConverterDelegate<T> converter)
{
TypeConverterLookup<T>.TryConvert = converter;
return this;
}
public bool TryConvert<T>(object source, out T result)
{
TypeConverterDelegate<T> converter = TypeConverterLookup<T>.TryConvert;
return converter != null
? converter(source, out result)
: TryCoreConvert(source, out result);
}
public bool TryCoreConvert<T>(object source, out T result)
{
return Converter.TryConvert(source, out result);
}
private static class TypeConverterLookup<T>
{
public static TypeConverterDelegate<T> TryConvert;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using SquishIt.Framework.Files;
using SquishIt.Framework.Renderers;
using SquishIt.Framework.Utilities;
namespace SquishIt.Framework.Base
{
public abstract partial class BundleBase<T> where T : BundleBase<T>
{
IEnumerable<string> GetFiles(IEnumerable<Asset> assets)
{
var inputFiles = assets.Select(a => Input.FromAsset(a, pathTranslator, IsDebuggingEnabled));
var resolvedFilePaths = new List<string>();
foreach (Input input in inputFiles)
{
resolvedFilePaths.AddRange(input.Resolve(allowedExtensions, disallowedExtensions, debugExtension));
}
return resolvedFilePaths;
}
protected IEnumerable<string> GetFilesForSingleAsset(Asset asset)
{
var inputFile = Input.FromAsset(asset, pathTranslator, IsDebuggingEnabled);
return inputFile.Resolve(allowedExtensions, disallowedExtensions, debugExtension);
}
protected IPreprocessor[] FindPreprocessors(string file)
{
//using rails convention of applying preprocessing based on file extension components in reverse order
return file.Split('.')
.Skip(1)
.Reverse()
.Select(FindPreprocessor)
.TakeWhile(p => p != null)
.Where(p => !(p is NullPreprocessor))
.ToArray();
}
protected string PreprocessFile(string file, IPreprocessor[] preprocessors)
{
return directoryWrapper.ExecuteInDirectory(Path.GetDirectoryName(file),
() => PreprocessContent(file, preprocessors, ReadFile(file)));
}
protected string PreprocessArbitrary(Asset asset)
{
if (!asset.IsArbitrary) throw new InvalidOperationException("PreprocessArbitrary can only be called on Arbitrary assets.");
var filename = "dummy." + (asset.Extension ?? defaultExtension);
var preprocessors = FindPreprocessors(filename);
return asset.ArbitraryWorkingDirectory != null ?
directoryWrapper.ExecuteInDirectory(asset.ArbitraryWorkingDirectory, () => MinifyIfNeeded(PreprocessContent(filename, preprocessors, asset.Content), asset.Minify)) :
MinifyIfNeeded(PreprocessContent(filename, preprocessors, asset.Content), asset.Minify);
}
protected string PreprocessContent(string file, IPreprocessor[] preprocessors, string content)
{
return preprocessors.NullSafeAny()
? preprocessors.Aggregate(content, (cntnt, pp) =>
{
var result = pp.Process(file, cntnt);
bundleState.DependentFiles.AddRange(result.Dependencies);
return result.Result;
})
: content;
}
IPreprocessor FindPreprocessor(string extension)
{
var instanceTypes = bundleState.Preprocessors.Select(ipp => ipp.GetType()).ToArray();
var preprocessor =
bundleState.Preprocessors.Union(Bundle.Preprocessors.Where(pp => !instanceTypes.Contains(pp.GetType())))
.FirstOrDefault(p => p.ValidFor(extension));
return preprocessor;
}
string ExpandAppRelativePath(string file)
{
if (file.StartsWith("~/"))
{
string appRelativePath = HttpRuntime.AppDomainAppVirtualPath;
if (appRelativePath != null && !appRelativePath.EndsWith("/"))
appRelativePath += "/";
return file.Replace("~/", appRelativePath);
}
return file;
}
protected string ReadFile(string file)
{
using (var sr = fileReaderFactory.GetFileReader(file))
{
return sr.ReadToEnd();
}
}
bool FileExists(string file)
{
return fileReaderFactory.FileExists(file);
}
string GetAdditionalAttributes(BundleState state)
{
var result = new StringBuilder();
foreach (var attribute in state.Attributes)
{
result.Append(attribute.Key);
result.Append("=\"");
result.Append(attribute.Value);
result.Append("\" ");
}
return result.ToString();
}
string GetFilesForRemote(IEnumerable<string> remoteAssetPaths, BundleState state)
{
var sb = new StringBuilder();
foreach (var uri in remoteAssetPaths)
{
sb.Append(FillTemplate(state, uri));
}
return sb.ToString();
}
string BuildAbsolutePath(string siteRelativePath)
{
if (HttpContext.Current == null)
throw new InvalidOperationException(
"Absolute path can only be constructed in the presence of an HttpContext.");
if (!siteRelativePath.StartsWith("/"))
throw new InvalidOperationException("This helper method only works with site relative paths.");
var url = HttpContext.Current.Request.Url;
var port = url.Port != 80 ? (":" + url.Port) : String.Empty;
return string.Format("{0}://{1}{2}{3}", url.Scheme, url.Host, port,
VirtualPathUtility.ToAbsolute(siteRelativePath));
}
string Render(string renderTo, string key, IRenderer renderer)
{
var cacheUniquenessHash = key.Contains("#") ? hasher.GetHash(bundleState.Assets
.Select(a => a.IsRemote ? a.RemotePath :
a.IsArbitrary ? a.Content : a.LocalPath)
.OrderBy(s => s)
.Aggregate(string.Empty, (acc, val) => acc + val)) : string.Empty;
key = CachePrefix + key + cacheUniquenessHash;
if (!String.IsNullOrEmpty(BaseOutputHref))
{
key = BaseOutputHref + key;
}
if (IsDebuggingEnabled())
{
var content = RenderDebug(renderTo, key, renderer);
return content;
}
return RenderRelease(key, renderTo, renderer);
}
string RenderDebug(string renderTo, string name, IRenderer renderer)
{
bundleState.DependentFiles.Clear();
var renderedFiles = new HashSet<string>();
var sb = new StringBuilder();
bundleState.DependentFiles.AddRange(GetFiles(bundleState.Assets.Where(a => !a.IsArbitrary).ToList()));
foreach (var asset in bundleState.Assets)
{
if (asset.IsArbitrary)
{
var filename = "dummy" + asset.Extension;
var preprocessors = FindPreprocessors(filename);
var processedContent = asset.ArbitraryWorkingDirectory != null ?
directoryWrapper.ExecuteInDirectory(asset.ArbitraryWorkingDirectory, () => PreprocessContent(filename, preprocessors, asset.Content)) :
PreprocessContent(filename, preprocessors, asset.Content);
sb.AppendLine(string.Format(tagFormat, processedContent));
}
else
{
var inputFile = Input.FromAsset(asset, pathTranslator, IsDebuggingEnabled);
var files = inputFile.Resolve(allowedExtensions, disallowedExtensions, debugExtension);
if (asset.IsEmbeddedResource)
{
var tsb = new StringBuilder();
foreach (var fn in files)
{
tsb.Append(ReadFile(fn) + "\n\n\n");
}
var processedFile = ExpandAppRelativePath(asset.LocalPath);
//embedded resources need to be rendered regardless to be usable
renderer.Render(tsb.ToString(), pathTranslator.ResolveAppRelativePathToFileSystem(processedFile));
sb.AppendLine(FillTemplate(bundleState, processedFile));
}
else if (asset.RemotePath != null)
{
sb.AppendLine(FillTemplate(bundleState, ExpandAppRelativePath(asset.LocalPath)));
}
else
{
foreach (var file in files)
{
if (!renderedFiles.Contains(file))
{
var fileBase = pathTranslator.ResolveAppRelativePathToFileSystem(asset.LocalPath);
var newPath = PreprocessForDebugging(file).Replace(fileBase, "");
var path = ExpandAppRelativePath(asset.LocalPath + newPath.Replace("\\", "/"));
sb.AppendLine(FillTemplate(bundleState, path));
renderedFiles.Add(file);
}
}
}
}
}
var content = sb.ToString();
if (bundleCache.ContainsKey(name))
{
bundleCache.Remove(name);
}
if (debugStatusReader.IsDebuggingEnabled()) //default for predicate is null - only want to add to cache if not forced via predicate
{
bundleCache.Add(name, content, bundleState.DependentFiles, IsDebuggingEnabled());
}
//need to render the bundle to caches, otherwise leave it
if (renderer is CacheRenderer)
renderer.Render(content, renderTo);
return content;
}
bool TryGetCachedBundle(string key, out string content)
{
if (bundleState.DebugPredicate.SafeExecute())
{
content = "";
return false;
}
return bundleCache.TryGetValue(key, out content);
}
string RenderRelease(string key, string renderTo, IRenderer renderer)
{
string content;
if (!TryGetCachedBundle(key, out content))
{
using (new CriticalRenderingSection(renderTo))
{
if (!TryGetCachedBundle(key, out content))
{
var uniqueFiles = new List<string>();
string hash = null;
bundleState.DependentFiles.Clear();
if (renderTo == null)
{
renderTo = renderPathCache[CachePrefix + "." + key];
}
else
{
renderPathCache[CachePrefix + "." + key] = renderTo;
}
var outputFile = pathTranslator.ResolveAppRelativePathToFileSystem(renderTo);
var renderToPath = ExpandAppRelativePath(renderTo);
if (!String.IsNullOrEmpty(BaseOutputHref))
{
renderToPath = String.Concat(BaseOutputHref.TrimEnd('/'), "/", renderToPath.TrimStart('/'));
}
var remoteAssetPaths = new List<string>();
remoteAssetPaths.AddRange(bundleState.Assets.Where(a => a.IsRemote).Select(a => a.RemotePath));
uniqueFiles.AddRange(GetFiles(bundleState.Assets.Where(asset =>
asset.IsEmbeddedResource ||
asset.IsLocal ||
asset.IsRemoteDownload).ToList()).Distinct());
var renderedTag = string.Empty;
if (uniqueFiles.Count > 0 || bundleState.Assets.Count(a => a.IsArbitrary) > 0)
{
bundleState.DependentFiles.AddRange(uniqueFiles);
var minifiedContent = GetMinifiedContent(bundleState.Assets, outputFile);
if (!string.IsNullOrEmpty(bundleState.HashKeyName))
{
hash = hasher.GetHash(minifiedContent);
}
renderToPath = bundleState.CacheInvalidationStrategy.GetOutputWebPath(renderToPath, bundleState.HashKeyName, hash);
outputFile = bundleState.CacheInvalidationStrategy.GetOutputFileLocation(outputFile, hash);
if (!(bundleState.ShouldRenderOnlyIfOutputFileIsMissing && FileExists(outputFile)))
{
renderer.Render(minifiedContent, outputFile);
}
renderedTag = FillTemplate(bundleState, renderToPath);
}
content += String.Concat(GetFilesForRemote(remoteAssetPaths, bundleState), renderedTag);
}
}
//don't cache bundles where debugging was forced via predicate
if (!bundleState.DebugPredicate.SafeExecute())
{
bundleCache.Add(key, content, bundleState.DependentFiles, IsDebuggingEnabled());
}
}
return content;
}
protected string GetMinifiedContent(List<Asset> assets, string outputFile)
{
var filteredAssets = assets.Where(asset =>
asset.IsEmbeddedResource ||
asset.IsLocal ||
asset.IsRemoteDownload ||
asset.IsArbitrary)
.ToList();
var sb = new StringBuilder();
AggregateContent(filteredAssets, sb, outputFile);
return sb.ToString();
}
protected string MinifyIfNeeded(string content, bool minify)
{
if (minify && !string.IsNullOrEmpty(content) && !IsDebuggingEnabled())
{
var minified = Minifier.Minify(content);
return AppendFileClosure(minified);
}
return AppendFileClosure(content);
}
protected virtual string AppendFileClosure(string content)
{
return content;
}
string PreprocessForDebugging(string filename)
{
var preprocessors = FindPreprocessors(filename);
if (preprocessors.NullSafeAny())
{
var content = PreprocessFile(filename, preprocessors);
filename += debugExtension;
using (var fileWriter = fileWriterFactory.GetFileWriter(filename))
{
fileWriter.Write(content);
}
}
return filename;
}
}
}
| |
/*
| Version 10.1.84
| Copyright 2013 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
using System;
using System.Linq;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using ESRI.ArcLogistics.Geometry;
using ESRI.ArcLogistics.Geocoding;
using ESRI.ArcLogistics.DomainObjects;
namespace ESRI.ArcLogistics.Routing
{
/// <summary>
/// Class contains helper method for solve operations.
/// </summary>
internal static class SolveHelper
{
#region Public static methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Checks is order locked.
/// </summary>
/// <param name="order">Order to check.</param>
/// <param name="schedule">Schedule to check.</param>
/// <returns>TRUE if order has stops belong schedule and this route or stop is locked.</returns>
public static bool IsOrderLocked(Order order, Schedule schedule)
{
Debug.Assert(order != null);
Debug.Assert(schedule != null);
bool isLocked = order.Stops.Any(stop =>
(null != stop.Route) &&
stop.Route.Schedule.Equals(schedule) &&
(stop.Route.IsLocked || stop.IsLocked));
return isLocked;
}
/// <summary>
/// Gets assigned orders from route.
/// </summary>
/// <param name="route">Route as source for assigned orders.</param>
/// <returns></returns>
public static IEnumerable<Order> GetAssignedOrders(Route route)
{
Debug.Assert(route != null);
var orders =
from stop in route.Stops
where stop.StopType == StopType.Order
let order = stop.AssociatedObject as Order
select order;
return orders;
}
/// <summary>
/// Creates RouteException object by REST service exception.
/// </summary>
/// <param name="message">Message text.</param>
/// <param name="serviceEx">Service exception to conversion.</param>
public static RouteException ConvertServiceException(string message, RestException serviceEx)
{
Debug.Assert(!string.IsNullOrEmpty(message));
Debug.Assert(serviceEx != null);
var errorMessage = _GetServiceExceptionMessage(message, serviceEx);
return new RouteException(errorMessage, serviceEx); // exception
}
/// <summary>
/// Gets enabled restriction names.
/// </summary>
/// <param name="restrictions">Restriciton to filtration.</param>
/// <returns>Returns collection of names of restrictions that have "enabled" flag set to true.</returns>
public static ICollection<string> GetEnabledRestrictionNames(
ICollection<Restriction> restrictions)
{
Debug.Assert(restrictions != null);
var enabledRestrictionNames =
from restriction in restrictions
where restriction.IsEnabled
select restriction.NetworkAttributeName;
return enabledRestrictionNames.ToList();
}
#endregion // Public static methods
#region Internal static methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Sorts StopData objects respecting sequence number.
/// </summary>
/// <param name="stops">Stops to sorting.</param>
internal static void SortBySequence(List<StopData> stops)
{
Debug.Assert(stops != null);
stops.Sort(delegate(StopData s1, StopData s2)
{
return s1.SequenceNumber.CompareTo(s2.SequenceNumber);
});
}
/// <summary>
/// Considers arrival delay in stops.
/// </summary>
/// <param name="arrivalDelay">Arrival delay value.</param>
/// <param name="stops">Stops to update.</param>
internal static void ConsiderArrivalDelayInStops(int arrivalDelay, IList<StopData> stops)
{
Debug.Assert(null != stops);
if (0 == stops.Count)
return; // stop process
int startIndex = stops.Count - 1; // last index
StopData last = stops[startIndex];
Point? prevStopPoint = null;
if (StopType.Lunch != last.StopType)
prevStopPoint = _GetStopPoint(last);
--startIndex; // start from before last
// (last one on a route - don't add the value to its service time)
Debug.Assert(0 <= startIndex);
for (int index = startIndex; 0 <= index; --index)
{
StopData stop = stops[index];
int delay = 0;
if (StopType.Lunch != stop.StopType)
delay = _GetArrivalDelay(arrivalDelay, stop, ref prevStopPoint);
stop.TimeAtStop += delay;
}
}
/// <summary>
/// Gets stop for a stop where lunch stop was placed (Export version).
/// </summary>
/// <param name="sortedStops">A collection of route stops sorted by their sequence
/// numbers.</param>
/// <param name="lunchIndex">The lunch stop index to get actual stop for.</param>
/// <returns>A stop for an actual stop where lunch was placed.</returns>
internal static Stop GetActualLunchStop(IList<Stop> sortedStops, int lunchIndex)
{
Debug.Assert(null != sortedStops);
Stop actualStop = null;
if ((0 <= lunchIndex) && (lunchIndex < sortedStops.Count))
{
Stop stop = sortedStops[lunchIndex];
Debug.Assert(stop.StopType == StopType.Lunch);
// use previously stop as actual
int indexStep = -1;
// find actual stop in selected direction
actualStop = _GetActualLunchStop(sortedStops, lunchIndex + indexStep, indexStep);
// not found in selected direction
if (null == actualStop)
{ // find in invert direction
indexStep = -indexStep;
actualStop = _GetActualLunchStop(sortedStops, lunchIndex + indexStep, indexStep);
}
}
// not found - stop process
if (null == actualStop)
{
string message = Properties.Messages.Error_GrfExporterNoBreakStopLocation;
throw new InvalidOperationException(message); // exception
}
return actualStop;
}
/// <summary>
/// Gets stop data for a stop where lunch stop was placed (Routing version).
/// </summary>
/// <param name="sortedStops">A collection of route stops sorted by their sequence
/// numbers.</param>
/// <param name="lunchIndex">The lunch stop index to get actual stop for.</param>
/// <returns>A stop data for an actual stop where lunch was placed.</returns>
internal static StopData GetActualLunchStop(IList<StopData> sortedStops, int lunchIndex)
{
Debug.Assert(null != sortedStops);
StopData actualStop = null;
if ((0 <= lunchIndex) && (lunchIndex < sortedStops.Count))
{
StopData stop = sortedStops[lunchIndex];
Debug.Assert(stop.StopType == StopType.Lunch);
// use previously stop as actual
int indexStep = -1;
// find actual stop in selected direction
actualStop = _GetActualLunchStop(sortedStops, lunchIndex + indexStep, indexStep);
// not found in seleted direction
if (null == actualStop)
{ // find in invert direction
indexStep = -indexStep;
actualStop = _GetActualLunchStop(sortedStops, lunchIndex + indexStep, indexStep);
}
}
// not found - stop process
if (null == actualStop)
{
string message = Properties.Messages.Error_RoutingMissingBreakStop;
throw new InvalidOperationException(message); // exception
}
return actualStop;
}
#endregion // Internal static methods
#region Private static methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Gets stop's point.
/// </summary>
/// <param name="stop">Stop as source for point.</param>
/// <returns>Stop's related point.</returns>
private static Point _GetStopPoint(StopData stop)
{
Debug.Assert(null != stop);
Debug.Assert(StopType.Lunch != stop.StopType);
Debug.Assert(null != stop.AssociatedObject);
var geocodable = stop.AssociatedObject as IGeocodable;
Debug.Assert(null != geocodable);
Point? pt = geocodable.GeoLocation;
Debug.Assert(pt != null);
return pt.Value;
}
/// <summary>
/// Gets arrival delay for selected stop.
/// </summary>
/// <param name="arrivalDelay">Arrival delay value.</param>
/// <param name="stop">Stop as source.</param>
/// <param name="prevStopPoint">Previously stop point.</param>
/// <returns>Arrival delay value or 0 if not need considers arrival delay.</returns>
private static int _GetArrivalDelay(int arrivalDelay,
StopData stop,
ref Point? prevStopPoint)
{
Debug.Assert(null != stop);
Point point = _GetStopPoint(stop);
// if location changed
bool needDelay = (!prevStopPoint.HasValue ||
(prevStopPoint.HasValue && (point != prevStopPoint)));
prevStopPoint = point;
return needDelay ? arrivalDelay : 0;
}
/// <summary>
/// Gets message for the specified service exception.
/// </summary>
/// <param name="message">The text to prefix generated exception message
/// with.</param>
/// <param name="serviceException">The exception to generate message for.</param>
/// <returns>Text describing the specified service exception.</returns>
private static string _GetServiceExceptionMessage(string message,
RestException serviceException)
{
Debug.Assert(message != null);
Debug.Assert(serviceException != null);
string serviceMsg = serviceException.Message;
if (!string.IsNullOrEmpty(serviceMsg))
{
return string.Format(Properties.Messages.Error_ArcgisRestError,
message,
serviceMsg);
}
var errorCode = string.Format(CultureInfo.InvariantCulture,
Properties.Resources.ArcGisRestErrorCodeFormat,
serviceException.ErrorCode);
var errorMessage = string.Format(Properties.Messages.Error_ArcgisRestUnspecifiedError,
message,
errorCode);
return errorMessage;
}
/// <summary>
/// Gets stop data for a stop where lunch stop was placed.
/// </summary>
/// <param name="sortedStops">A collection of route stops sorted by their sequence
/// numbers.</param>
/// <param name="startIndex">Index to start search in sortedStops.</param>
/// <param name="indexStep">Index increment value (1 or -1).</param>
/// <returns>A stop for an actual stop where lunch was placed or NULL.</returns>
private static Stop _GetActualLunchStop(IList<Stop> sortedStops,
int startIndex,
int indexStep)
{
Debug.Assert(null != sortedStops);
Stop actualStop = null;
if (startIndex < sortedStops.Count)
{
for (int index = startIndex;
(0 <= index) && (index < sortedStops.Count);
index += indexStep)
{
Stop currStop = sortedStops[index];
if (currStop.StopType != StopType.Lunch)
{ // actual stop can't be lunch
actualStop = currStop;
break; // result found
}
}
}
return actualStop;
}
/// <summary>
/// Gets stop data for a stop where lunch stop was placed.
/// </summary>
/// <param name="sortedStops">A collection of route stops sorted by their sequence
/// numbers.</param>
/// <param name="startIndex">Index to srart search in sortedStops.</param>
/// <param name="indexStep">Index incrementation value (1 or -1).</param>
/// <returns>A stop data for an actual stop where lunch was placed or NULL.</returns>
private static StopData _GetActualLunchStop(IList<StopData> sortedStops,
int startIndex,
int indexStep)
{
Debug.Assert(null != sortedStops);
Debug.Assert(startIndex < sortedStops.Count);
StopData actualStop = null;
for (int index = startIndex;
(0 <= index) && (index < sortedStops.Count);
index += indexStep)
{
StopData currStop = sortedStops[index];
if (currStop.StopType != StopType.Lunch)
{ // actual stop can't be lunch
actualStop = currStop;
break; // result found
}
}
return actualStop;
}
#endregion // Private static methods
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Listener;
using Microsoft.VisualStudio.Services.Agent.Capabilities;
using Microsoft.VisualStudio.Services.Agent.Listener.Configuration;
using Moq;
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Xunit;
using System.Threading;
using System.Reflection;
using System.Collections.Generic;
namespace Microsoft.VisualStudio.Services.Agent.Tests.Listener
{
public sealed class MessageListenerL0
{
private AgentSettings _settings;
private Mock<IConfigurationManager> _config;
private Mock<IAgentServer> _agentServer;
private Mock<ICredentialManager> _credMgr;
private Mock<ICapabilitiesManager> _capabilitiesManager;
public MessageListenerL0()
{
_settings = new AgentSettings { AgentId = 1, AgentName = "myagent", PoolId = 123, PoolName = "default", ServerUrl = "http://myserver", WorkFolder = "_work" };
_config = new Mock<IConfigurationManager>();
_config.Setup(x => x.LoadSettings()).Returns(_settings);
_agentServer = new Mock<IAgentServer>();
_credMgr = new Mock<ICredentialManager>();
_capabilitiesManager = new Mock<ICapabilitiesManager>();
}
private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
{
TestHostContext tc = new TestHostContext(this, testName);
tc.SetSingleton<IConfigurationManager>(_config.Object);
tc.SetSingleton<IAgentServer>(_agentServer.Object);
tc.SetSingleton<ICredentialManager>(_credMgr.Object);
tc.SetSingleton<ICapabilitiesManager>(_capabilitiesManager.Object);
return tc;
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Agent")]
public async void CreatesSession()
{
using (TestHostContext tc = CreateTestContext())
using (var tokenSource = new CancellationTokenSource())
{
Tracing trace = tc.GetTrace();
// Arrange.
var expectedSession = new TaskAgentSession();
_agentServer
.Setup(x => x.CreateAgentSessionAsync(
_settings.PoolId,
It.Is<TaskAgentSession>(y => y != null),
tokenSource.Token))
.Returns(Task.FromResult(expectedSession));
_capabilitiesManager.Setup(x => x.GetCapabilitiesAsync(_settings, It.IsAny<CancellationToken>())).Returns(Task.FromResult(new Dictionary<string, string>()));
_credMgr.Setup(x => x.LoadCredentials()).Returns(new Common.VssCredentials());
// Act.
MessageListener listener = new MessageListener();
listener.Initialize(tc);
bool result = await listener.CreateSessionAsync(tokenSource.Token);
trace.Info("result: {0}", result);
// Assert.
Assert.True(result);
_agentServer
.Verify(x => x.CreateAgentSessionAsync(
_settings.PoolId,
It.Is<TaskAgentSession>(y => y != null),
tokenSource.Token), Times.Once());
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Agent")]
public async void DeleteSession()
{
using (TestHostContext tc = CreateTestContext())
using (var tokenSource = new CancellationTokenSource())
{
Tracing trace = tc.GetTrace();
// Arrange.
var expectedSession = new TaskAgentSession();
PropertyInfo sessionIdProperty = expectedSession.GetType().GetProperty("SessionId", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
Assert.NotNull(sessionIdProperty);
sessionIdProperty.SetValue(expectedSession, Guid.NewGuid());
_agentServer
.Setup(x => x.CreateAgentSessionAsync(
_settings.PoolId,
It.Is<TaskAgentSession>(y => y != null),
tokenSource.Token))
.Returns(Task.FromResult(expectedSession));
_capabilitiesManager.Setup(x => x.GetCapabilitiesAsync(_settings, It.IsAny<CancellationToken>())).Returns(Task.FromResult(new Dictionary<string, string>()));
_credMgr.Setup(x => x.LoadCredentials()).Returns(new Common.VssCredentials());
// Act.
MessageListener listener = new MessageListener();
listener.Initialize(tc);
bool result = await listener.CreateSessionAsync(tokenSource.Token);
Assert.True(result);
_agentServer
.Setup(x => x.DeleteAgentSessionAsync(
_settings.PoolId, expectedSession.SessionId, It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
await listener.DeleteSessionAsync();
//Assert
_agentServer
.Verify(x => x.DeleteAgentSessionAsync(
_settings.PoolId, expectedSession.SessionId, It.IsAny<CancellationToken>()), Times.Once());
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Agent")]
public async void GetNextMessage()
{
using (TestHostContext tc = CreateTestContext())
using (var tokenSource = new CancellationTokenSource())
{
Tracing trace = tc.GetTrace();
// Arrange.
var expectedSession = new TaskAgentSession();
PropertyInfo sessionIdProperty = expectedSession.GetType().GetProperty("SessionId", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
Assert.NotNull(sessionIdProperty);
sessionIdProperty.SetValue(expectedSession, Guid.NewGuid());
_agentServer
.Setup(x => x.CreateAgentSessionAsync(
_settings.PoolId,
It.Is<TaskAgentSession>(y => y != null),
tokenSource.Token))
.Returns(Task.FromResult(expectedSession));
_capabilitiesManager.Setup(x => x.GetCapabilitiesAsync(_settings, It.IsAny<CancellationToken>())).Returns(Task.FromResult(new Dictionary<string, string>()));
_credMgr.Setup(x => x.LoadCredentials()).Returns(new Common.VssCredentials());
// Act.
MessageListener listener = new MessageListener();
listener.Initialize(tc);
bool result = await listener.CreateSessionAsync(tokenSource.Token);
Assert.True(result);
var arMessages = new TaskAgentMessage[]
{
new TaskAgentMessage
{
Body = "somebody1",
MessageId = 4234,
MessageType = JobRequestMessageTypes.AgentJobRequest
},
new TaskAgentMessage
{
Body = "somebody2",
MessageId = 4235,
MessageType = JobCancelMessage.MessageType
},
null, //should be skipped by GetNextMessageAsync implementation
null,
new TaskAgentMessage
{
Body = "somebody3",
MessageId = 4236,
MessageType = JobRequestMessageTypes.AgentJobRequest
}
};
var messages = new Queue<TaskAgentMessage>(arMessages);
_agentServer
.Setup(x => x.GetAgentMessageAsync(
_settings.PoolId, expectedSession.SessionId, It.IsAny<long?>(), tokenSource.Token))
.Returns(async (Int32 poolId, Guid sessionId, Int64? lastMessageId, CancellationToken cancellationToken) =>
{
await Task.Yield();
return messages.Dequeue();
});
TaskAgentMessage message1 = await listener.GetNextMessageAsync(tokenSource.Token);
TaskAgentMessage message2 = await listener.GetNextMessageAsync(tokenSource.Token);
TaskAgentMessage message3 = await listener.GetNextMessageAsync(tokenSource.Token);
Assert.Equal(arMessages[0], message1);
Assert.Equal(arMessages[1], message2);
Assert.Equal(arMessages[4], message3);
//Assert
_agentServer
.Verify(x => x.GetAgentMessageAsync(
_settings.PoolId, expectedSession.SessionId, It.IsAny<long?>(), tokenSource.Token), Times.Exactly(arMessages.Length));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Umbraco.Cms.Core.Configuration;
using Umbraco.Cms.Core.Net;
namespace Umbraco.Cms.Core.Security
{
/// <summary>
/// Abstract class for Umbraco User Managers for back office users or front-end members
/// </summary>
/// <typeparam name="TUser">The type of user</typeparam>
/// /// <typeparam name="TPasswordConfig">The type password config</typeparam>
public abstract class UmbracoUserManager<TUser, TPasswordConfig> : UserManager<TUser>
where TUser : UmbracoIdentityUser
where TPasswordConfig : class, IPasswordConfiguration, new()
{
private PasswordGenerator _passwordGenerator;
/// <summary>
/// Initializes a new instance of the <see cref="UmbracoUserManager{T, TPasswordConfig}"/> class.
/// </summary>
public UmbracoUserManager(
IIpResolver ipResolver,
IUserStore<TUser> store,
IOptions<IdentityOptions> optionsAccessor,
IPasswordHasher<TUser> passwordHasher,
IEnumerable<IUserValidator<TUser>> userValidators,
IEnumerable<IPasswordValidator<TUser>> passwordValidators,
IdentityErrorDescriber errors,
IServiceProvider services,
ILogger<UserManager<TUser>> logger,
IOptions<TPasswordConfig> passwordConfiguration)
: base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, new NoopLookupNormalizer(), errors, services, logger)
{
IpResolver = ipResolver ?? throw new ArgumentNullException(nameof(ipResolver));
PasswordConfiguration = passwordConfiguration.Value ?? throw new ArgumentNullException(nameof(passwordConfiguration));
}
/// <inheritdoc />
public override bool SupportsUserClaim => false; // We don't support an IUserClaimStore and don't need to (at least currently)
/// <inheritdoc />
public override bool SupportsQueryableUsers => false; // It would be nice to support this but we don't need to currently and that would require IQueryable support for our user service/repository
/// <summary>
/// Developers will need to override this to support custom 2 factor auth
/// </summary>
/// <inheritdoc />
public override bool SupportsUserTwoFactor => false;
/// <inheritdoc />
public override bool SupportsUserPhoneNumber => false; // We haven't needed to support this yet, though might be necessary for 2FA
/// <summary>
/// Gets the password configuration
/// </summary>
public IPasswordConfiguration PasswordConfiguration { get; }
/// <summary>
/// Gets the IP resolver
/// </summary>
public IIpResolver IpResolver { get; }
/// <summary>
/// Used to validate a user's session
/// </summary>
/// <param name="userId">The user id</param>
/// <param name="sessionId">The session id</param>
/// <returns>True if the session is valid, else false</returns>
public virtual async Task<bool> ValidateSessionIdAsync(string userId, string sessionId)
{
// if this is not set, for backwards compat (which would be super rare), we'll just approve it
// TODO: This should be removed after members supports this
if (Store is not IUserSessionStore<TUser> userSessionStore)
{
return true;
}
return await userSessionStore.ValidateSessionIdAsync(userId, sessionId);
}
/// <summary>
/// Helper method to generate a password for a user based on the current password validator
/// </summary>
/// <returns>The generated password</returns>
public string GeneratePassword()
{
_passwordGenerator ??= new PasswordGenerator(PasswordConfiguration);
string password = _passwordGenerator.GeneratePassword();
return password;
}
/// <summary>
/// Used to validate the password without an identity user
/// Validation code is based on the default ValidatePasswordAsync code
/// Should return <see cref="IdentityResult.Success"/> if validation is successful
/// </summary>
/// <param name="password">The password.</param>
/// <returns>A <see cref="IdentityResult"/> representing whether validation was successful.</returns>
public async Task<IdentityResult> ValidatePasswordAsync(string password)
{
var errors = new List<IdentityError>();
var isValid = true;
foreach (IPasswordValidator<TUser> v in PasswordValidators)
{
IdentityResult result = await v.ValidateAsync(this, null, password);
if (!result.Succeeded)
{
if (result.Errors.Any())
{
errors.AddRange(result.Errors);
}
isValid = false;
}
}
if (!isValid)
{
Logger.LogWarning(14, "Password validation failed: {errors}.", string.Join(";", errors.Select(e => e.Code)));
return IdentityResult.Failed(errors.ToArray());
}
return IdentityResult.Success;
}
/// <inheritdoc />
public override async Task<bool> CheckPasswordAsync(TUser user, string password)
{
// we cannot proceed if the user passed in does not have an identity
if (user.HasIdentity == false)
{
return false;
}
// use the default behavior
return await base.CheckPasswordAsync(user, password);
}
/// <summary>
/// This is a special method that will reset the password but will raise the Password Changed event instead of the reset event
/// </summary>
/// <param name="userId">The userId</param>
/// <param name="token">The reset password token</param>
/// <param name="newPassword">The new password to set it to</param>
/// <returns>The <see cref="IdentityResult"/></returns>
/// <remarks>
/// We use this because in the back office the only way an admin can change another user's password without first knowing their password
/// is to generate a token and reset it, however, when we do this we want to track a password change, not a password reset
/// </remarks>
public virtual async Task<IdentityResult> ChangePasswordWithResetAsync(string userId, string token, string newPassword)
{
TUser user = await FindByIdAsync(userId);
if (user == null)
{
throw new InvalidOperationException("Could not find user");
}
IdentityResult result = await ResetPasswordAsync(user, token, newPassword);
return result;
}
/// <inheritdoc/>
public override async Task<IdentityResult> SetLockoutEndDateAsync(TUser user, DateTimeOffset? lockoutEnd)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
IdentityResult result = await base.SetLockoutEndDateAsync(user, lockoutEnd);
// The way we unlock is by setting the lockoutEnd date to the current datetime
if (!result.Succeeded || lockoutEnd < DateTimeOffset.UtcNow)
{
// Resets the login attempt fails back to 0 when unlock is clicked
await ResetAccessFailedCountAsync(user);
}
return result;
}
/// <inheritdoc/>
public override async Task<IdentityResult> ResetAccessFailedCountAsync(TUser user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
var lockoutStore = (IUserLockoutStore<TUser>)Store;
var accessFailedCount = await GetAccessFailedCountAsync(user);
if (accessFailedCount == 0)
{
return IdentityResult.Success;
}
await lockoutStore.ResetAccessFailedCountAsync(user, CancellationToken.None);
//Ensure the password config is null, so it is set to the default in repository
user.PasswordConfig = null;
return await UpdateAsync(user);
}
/// <summary>
/// Overrides the Microsoft ASP.NET user management method
/// </summary>
/// <inheritdoc/>
public override async Task<IdentityResult> AccessFailedAsync(TUser user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
if (Store is not IUserLockoutStore<TUser> lockoutStore)
{
throw new NotSupportedException("The current user store does not implement " + typeof(IUserLockoutStore<>));
}
var count = await lockoutStore.IncrementAccessFailedCountAsync(user, CancellationToken.None);
if (count >= Options.Lockout.MaxFailedAccessAttempts)
{
await lockoutStore.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.Add(Options.Lockout.DefaultLockoutTimeSpan), CancellationToken.None);
// NOTE: in normal aspnet identity this would do set the number of failed attempts back to 0
// here we are persisting the value for the back office
}
if (string.IsNullOrEmpty(user.PasswordConfig))
{
//We cant pass null as that would be interpreted as the default algoritm, but due to the failing attempt we dont know.
user.PasswordConfig = Constants.Security.UnknownPasswordConfigJson;
}
IdentityResult result = await UpdateAsync(user);
return result;
}
/// <inheritdoc/>
public async Task<bool> ValidateCredentialsAsync(string username, string password)
{
TUser user = await FindByNameAsync(username);
if (user == null)
{
return false;
}
if (Store is not IUserPasswordStore<TUser> userPasswordStore)
{
throw new NotSupportedException("The current user store does not implement " + typeof(IUserPasswordStore<>));
}
var hash = await userPasswordStore.GetPasswordHashAsync(user, new CancellationToken());
return await VerifyPasswordAsync(userPasswordStore, user, password) == PasswordVerificationResult.Success;
}
}
}
| |
// 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: This class implements a set of methods for retrieving
// sort key information.
//
//
////////////////////////////////////////////////////////////////////////////
namespace System.Globalization {
using System;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable] public class SortKey
{
//--------------------------------------------------------------------//
// Internal Information //
//--------------------------------------------------------------------//
//
// Variables.
//
[OptionalField(VersionAdded = 3)]
internal String localeName; // locale identifier
[OptionalField(VersionAdded = 1)] // LCID field so serialization is Whidbey compatible though we don't officially support it
internal int win32LCID;
// Whidbey serialization
internal CompareOptions options; // options
internal String m_String; // original string
internal byte[] m_KeyData; // sortkey data
//
// The following constructor is designed to be called from CompareInfo to get the
// the sort key of specific string for synthetic culture
//
internal SortKey(String localeName, String str, CompareOptions options, byte[] keyData)
{
this.m_KeyData = keyData;
this.localeName = localeName;
this.options = options;
this.m_String = str;
}
#if FEATURE_USE_LCID
[OnSerializing]
private void OnSerializing(StreamingContext context)
{
//set LCID to proper value for Whidbey serialization (no other use)
if (win32LCID == 0)
{
win32LCID = CultureInfo.GetCultureInfo(localeName).LCID;
}
}
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
//set locale name to proper value after Whidbey deserialization
if (String.IsNullOrEmpty(localeName) && win32LCID != 0)
{
localeName = CultureInfo.GetCultureInfo(win32LCID).Name;
}
}
#endif //FEATURE_USE_LCID
////////////////////////////////////////////////////////////////////////
//
// GetOriginalString
//
// Returns the original string used to create the current instance
// of SortKey.
//
////////////////////////////////////////////////////////////////////////
public virtual String OriginalString
{
get {
return (m_String);
}
}
////////////////////////////////////////////////////////////////////////
//
// GetKeyData
//
// Returns a byte array representing the current instance of the
// sort key.
//
////////////////////////////////////////////////////////////////////////
public virtual byte[] KeyData
{
get {
return (byte[])(m_KeyData.Clone());
}
}
////////////////////////////////////////////////////////////////////////
//
// Compare
//
// Compares the two sort keys. Returns 0 if the two sort keys are
// equal, a number less than 0 if sortkey1 is less than sortkey2,
// and a number greater than 0 if sortkey1 is greater than sortkey2.
//
////////////////////////////////////////////////////////////////////////
public static int Compare(SortKey sortkey1, SortKey sortkey2) {
if (sortkey1==null || sortkey2==null) {
throw new ArgumentNullException((sortkey1==null ? "sortkey1": "sortkey2"));
}
Contract.EndContractBlock();
byte[] key1Data = sortkey1.m_KeyData;
byte[] key2Data = sortkey2.m_KeyData;
Contract.Assert(key1Data!=null, "key1Data!=null");
Contract.Assert(key2Data!=null, "key2Data!=null");
if (key1Data.Length == 0) {
if (key2Data.Length == 0) {
return (0);
}
return (-1);
}
if (key2Data.Length == 0) {
return (1);
}
int compLen = (key1Data.Length<key2Data.Length)?key1Data.Length:key2Data.Length;
for (int i=0; i<compLen; i++) {
if (key1Data[i]>key2Data[i]) {
return (1);
}
if (key1Data[i]<key2Data[i]) {
return (-1);
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////
//
// Equals
//
// Implements Object.Equals(). Returns a boolean indicating whether
// or not object refers to the same SortKey as the current instance.
//
////////////////////////////////////////////////////////////////////////
public override bool Equals(Object value)
{
SortKey that = value as SortKey;
if (that != null)
{
return Compare(this, that) == 0;
}
return (false);
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
//
// Implements Object.GetHashCode(). Returns the hash code for the
// SortKey. The hash code is guaranteed to be the same for
// SortKey A and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return (CompareInfo.GetCompareInfo(
this.localeName).GetHashCodeOfString(this.m_String, this.options));
}
////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Implements Object.ToString(). Returns a string describing the
// SortKey.
//
////////////////////////////////////////////////////////////////////////
public override String ToString()
{
return ("SortKey - " + localeName + ", " + options + ", " + m_String);
}
}
}
| |
/*
Copyright (c) 2010 by Genstein
This file is (or was originally) part of Trizbort, the Interactive Fiction Mapper.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
namespace Trizbort
{
partial class MainForm
{
/// <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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.m_menuStrip = new System.Windows.Forms.MenuStrip();
this.m_fileMenu = new System.Windows.Forms.ToolStripMenuItem();
this.m_fileNewMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.m_fileOpenMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator9 = new System.Windows.Forms.ToolStripSeparator();
this.m_fileSaveMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.m_fileSaveAsMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator10 = new System.Windows.Forms.ToolStripSeparator();
this.m_fileExportMenu = new System.Windows.Forms.ToolStripMenuItem();
this.m_fileExportPDFMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.m_fileExportImageMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem9 = new System.Windows.Forms.ToolStripSeparator();
this.m_fileExportInform7MenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tADSToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem10 = new System.Windows.Forms.ToolStripSeparator();
this.inform6ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator12 = new System.Windows.Forms.ToolStripSeparator();
this.m_fileRecentMapsMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem7 = new System.Windows.Forms.ToolStripSeparator();
this.m_fileExitMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.m_editMenu = new System.Windows.Forms.ToolStripMenuItem();
this.m_editAddRoomMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.m_editRenameMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.m_editIsDarkMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.m_lineStylesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.m_plainLinesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator();
this.m_toggleDottedLinesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.m_toggleDirectionalLinesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.m_upLinesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.m_downLinesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator();
this.m_inLinesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.m_outLinesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.m_reverseLineMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator();
this.m_editSelectAllMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.m_editSelectNoneMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.m_editCopyMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.m_editCopyColorToolMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.m_editPasteMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem8 = new System.Windows.Forms.ToolStripSeparator();
this.m_editDeleteMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.m_editPropertiesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.m_viewMenu = new System.Windows.Forms.ToolStripMenuItem();
this.m_viewZoomMenu = new System.Windows.Forms.ToolStripMenuItem();
this.m_viewZoomInMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.m_viewZoomOutMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
this.m_viewZoomFiftyPercentMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.m_viewZoomOneHundredPercentMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.m_viewZoomTwoHundredPercentMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.m_viewEntireMapMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.m_viewResetMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem6 = new System.Windows.Forms.ToolStripSeparator();
this.m_viewMinimapMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.automappingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.m_automapStartMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.m_automapStopMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.m_projectMenu = new System.Windows.Forms.ToolStripMenuItem();
this.m_projectSettingsMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator11 = new System.Windows.Forms.ToolStripSeparator();
this.m_projectResetToDefaultSettingsMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.m_helpMenu = new System.Windows.Forms.ToolStripMenuItem();
this.m_onlineHelpMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.m_checkForUpdatesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripSeparator();
this.m_helpAboutMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.m_toolStrip = new System.Windows.Forms.ToolStrip();
this.m_toggleDottedLinesButton = new System.Windows.Forms.ToolStripButton();
this.m_toggleDirectionalLinesButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.m_automapBar = new Trizbort.AutomapBar();
this.m_canvas = new Trizbort.Canvas();
this.m_menuStrip.SuspendLayout();
this.m_toolStrip.SuspendLayout();
this.SuspendLayout();
//
// m_menuStrip
//
this.m_menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.m_fileMenu,
this.m_editMenu,
this.m_viewMenu,
this.automappingToolStripMenuItem,
this.m_projectMenu,
this.m_helpMenu});
this.m_menuStrip.Location = new System.Drawing.Point(0, 0);
this.m_menuStrip.Name = "m_menuStrip";
this.m_menuStrip.Size = new System.Drawing.Size(624, 24);
this.m_menuStrip.TabIndex = 1;
//
// m_fileMenu
//
this.m_fileMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.m_fileNewMenuItem,
this.toolStripSeparator1,
this.m_fileOpenMenuItem,
this.toolStripSeparator9,
this.m_fileSaveMenuItem,
this.m_fileSaveAsMenuItem,
this.toolStripSeparator10,
this.m_fileExportMenu,
this.toolStripSeparator12,
this.m_fileRecentMapsMenuItem,
this.toolStripMenuItem7,
this.m_fileExitMenuItem});
this.m_fileMenu.Name = "m_fileMenu";
this.m_fileMenu.Size = new System.Drawing.Size(37, 20);
this.m_fileMenu.Text = "&File";
this.m_fileMenu.DropDownOpening += new System.EventHandler(this.FileMenu_DropDownOpening);
//
// m_fileNewMenuItem
//
this.m_fileNewMenuItem.Name = "m_fileNewMenuItem";
this.m_fileNewMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N)));
this.m_fileNewMenuItem.Size = new System.Drawing.Size(182, 22);
this.m_fileNewMenuItem.Text = "&New Map";
this.m_fileNewMenuItem.Click += new System.EventHandler(this.FileNewMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(179, 6);
//
// m_fileOpenMenuItem
//
this.m_fileOpenMenuItem.Name = "m_fileOpenMenuItem";
this.m_fileOpenMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O)));
this.m_fileOpenMenuItem.Size = new System.Drawing.Size(182, 22);
this.m_fileOpenMenuItem.Text = "&Open Map...";
this.m_fileOpenMenuItem.Click += new System.EventHandler(this.FileOpenMenuItem_Click);
//
// toolStripSeparator9
//
this.toolStripSeparator9.Name = "toolStripSeparator9";
this.toolStripSeparator9.Size = new System.Drawing.Size(179, 6);
//
// m_fileSaveMenuItem
//
this.m_fileSaveMenuItem.Name = "m_fileSaveMenuItem";
this.m_fileSaveMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)));
this.m_fileSaveMenuItem.Size = new System.Drawing.Size(182, 22);
this.m_fileSaveMenuItem.Text = "&Save Map";
this.m_fileSaveMenuItem.Click += new System.EventHandler(this.FileSaveMenuItem_Click);
//
// m_fileSaveAsMenuItem
//
this.m_fileSaveAsMenuItem.Name = "m_fileSaveAsMenuItem";
this.m_fileSaveAsMenuItem.Size = new System.Drawing.Size(182, 22);
this.m_fileSaveAsMenuItem.Text = "Save Map &As...";
this.m_fileSaveAsMenuItem.Click += new System.EventHandler(this.FileSaveAsMenuItem_Click);
//
// toolStripSeparator10
//
this.toolStripSeparator10.Name = "toolStripSeparator10";
this.toolStripSeparator10.Size = new System.Drawing.Size(179, 6);
//
// m_fileExportMenu
//
this.m_fileExportMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.m_fileExportPDFMenuItem,
this.m_fileExportImageMenuItem,
this.toolStripMenuItem9,
this.m_fileExportInform7MenuItem,
this.tADSToolStripMenuItem,
this.toolStripMenuItem10,
this.inform6ToolStripMenuItem});
this.m_fileExportMenu.Name = "m_fileExportMenu";
this.m_fileExportMenu.Size = new System.Drawing.Size(182, 22);
this.m_fileExportMenu.Text = "&Export";
//
// m_fileExportPDFMenuItem
//
this.m_fileExportPDFMenuItem.Name = "m_fileExportPDFMenuItem";
this.m_fileExportPDFMenuItem.Size = new System.Drawing.Size(128, 22);
this.m_fileExportPDFMenuItem.Text = "&PDF...";
this.m_fileExportPDFMenuItem.Click += new System.EventHandler(this.FileExportPDFMenuItem_Click);
//
// m_fileExportImageMenuItem
//
this.m_fileExportImageMenuItem.Name = "m_fileExportImageMenuItem";
this.m_fileExportImageMenuItem.Size = new System.Drawing.Size(128, 22);
this.m_fileExportImageMenuItem.Text = "&Image...";
this.m_fileExportImageMenuItem.Click += new System.EventHandler(this.FileExportImageMenuItem_Click);
//
// toolStripMenuItem9
//
this.toolStripMenuItem9.Name = "toolStripMenuItem9";
this.toolStripMenuItem9.Size = new System.Drawing.Size(125, 6);
//
// m_fileExportInform7MenuItem
//
this.m_fileExportInform7MenuItem.Name = "m_fileExportInform7MenuItem";
this.m_fileExportInform7MenuItem.Size = new System.Drawing.Size(128, 22);
this.m_fileExportInform7MenuItem.Text = "Inform &7...";
this.m_fileExportInform7MenuItem.Click += new System.EventHandler(this.FileExportInform7MenuItem_Click);
//
// tADSToolStripMenuItem
//
this.tADSToolStripMenuItem.Name = "tADSToolStripMenuItem";
this.tADSToolStripMenuItem.Size = new System.Drawing.Size(128, 22);
this.tADSToolStripMenuItem.Text = "&TADS...";
this.tADSToolStripMenuItem.Click += new System.EventHandler(this.FileExportTadsMenuItem_Click);
//
// toolStripMenuItem10
//
this.toolStripMenuItem10.Name = "toolStripMenuItem10";
this.toolStripMenuItem10.Size = new System.Drawing.Size(125, 6);
//
// inform6ToolStripMenuItem
//
this.inform6ToolStripMenuItem.Name = "inform6ToolStripMenuItem";
this.inform6ToolStripMenuItem.Size = new System.Drawing.Size(128, 22);
this.inform6ToolStripMenuItem.Text = "Inform &6...";
this.inform6ToolStripMenuItem.Click += new System.EventHandler(this.FileExportInform6MenuItem_Click);
//
// toolStripSeparator12
//
this.toolStripSeparator12.Name = "toolStripSeparator12";
this.toolStripSeparator12.Size = new System.Drawing.Size(179, 6);
//
// m_fileRecentMapsMenuItem
//
this.m_fileRecentMapsMenuItem.Name = "m_fileRecentMapsMenuItem";
this.m_fileRecentMapsMenuItem.Size = new System.Drawing.Size(182, 22);
this.m_fileRecentMapsMenuItem.Text = "&Recent Maps";
//
// toolStripMenuItem7
//
this.toolStripMenuItem7.Name = "toolStripMenuItem7";
this.toolStripMenuItem7.Size = new System.Drawing.Size(179, 6);
//
// m_fileExitMenuItem
//
this.m_fileExitMenuItem.Name = "m_fileExitMenuItem";
this.m_fileExitMenuItem.Size = new System.Drawing.Size(182, 22);
this.m_fileExitMenuItem.Text = "E&xit";
this.m_fileExitMenuItem.Click += new System.EventHandler(this.FileExitMenuItem_Click);
//
// m_editMenu
//
this.m_editMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.m_editAddRoomMenuItem,
this.toolStripSeparator6,
this.m_editRenameMenuItem,
this.m_editIsDarkMenuItem,
this.toolStripSeparator2,
this.m_lineStylesMenuItem,
this.m_reverseLineMenuItem,
this.toolStripSeparator8,
this.m_editSelectAllMenuItem,
this.m_editSelectNoneMenuItem,
this.toolStripSeparator5,
this.m_editCopyMenuItem,
this.m_editCopyColorToolMenuItem,
this.m_editPasteMenuItem,
this.toolStripMenuItem8,
this.m_editDeleteMenuItem,
this.toolStripSeparator3,
this.m_editPropertiesMenuItem});
this.m_editMenu.Name = "m_editMenu";
this.m_editMenu.Size = new System.Drawing.Size(39, 20);
this.m_editMenu.Text = "&Edit";
//
// m_editAddRoomMenuItem
//
this.m_editAddRoomMenuItem.Name = "m_editAddRoomMenuItem";
this.m_editAddRoomMenuItem.ShortcutKeyDisplayString = "R";
this.m_editAddRoomMenuItem.Size = new System.Drawing.Size(211, 22);
this.m_editAddRoomMenuItem.Text = "&Add Room";
this.m_editAddRoomMenuItem.Click += new System.EventHandler(this.EditAddRoomMenuItem_Click);
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
this.toolStripSeparator6.Size = new System.Drawing.Size(208, 6);
//
// m_editRenameMenuItem
//
this.m_editRenameMenuItem.Name = "m_editRenameMenuItem";
this.m_editRenameMenuItem.ShortcutKeyDisplayString = "";
this.m_editRenameMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F2;
this.m_editRenameMenuItem.Size = new System.Drawing.Size(211, 22);
this.m_editRenameMenuItem.Text = "Re&name";
this.m_editRenameMenuItem.Click += new System.EventHandler(this.EditRenameMenuItem_Click);
//
// m_editIsDarkMenuItem
//
this.m_editIsDarkMenuItem.Name = "m_editIsDarkMenuItem";
this.m_editIsDarkMenuItem.ShortcutKeyDisplayString = "K";
this.m_editIsDarkMenuItem.Size = new System.Drawing.Size(211, 22);
this.m_editIsDarkMenuItem.Text = "Is Dar&k Room";
this.m_editIsDarkMenuItem.Click += new System.EventHandler(this.EditIsDarkMenuItem_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(208, 6);
//
// m_lineStylesMenuItem
//
this.m_lineStylesMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.m_plainLinesMenuItem,
this.toolStripMenuItem3,
this.m_toggleDottedLinesMenuItem,
this.m_toggleDirectionalLinesMenuItem,
this.toolStripMenuItem1,
this.m_upLinesMenuItem,
this.m_downLinesMenuItem,
this.toolStripMenuItem2,
this.m_inLinesMenuItem,
this.m_outLinesMenuItem});
this.m_lineStylesMenuItem.Name = "m_lineStylesMenuItem";
this.m_lineStylesMenuItem.ShortcutKeyDisplayString = "";
this.m_lineStylesMenuItem.Size = new System.Drawing.Size(211, 22);
this.m_lineStylesMenuItem.Text = "&Line Styles";
//
// m_plainLinesMenuItem
//
this.m_plainLinesMenuItem.Name = "m_plainLinesMenuItem";
this.m_plainLinesMenuItem.ShortcutKeyDisplayString = "P";
this.m_plainLinesMenuItem.Size = new System.Drawing.Size(172, 22);
this.m_plainLinesMenuItem.Text = "Plain";
this.m_plainLinesMenuItem.Click += new System.EventHandler(this.PlainLinesMenuItem_Click);
//
// toolStripMenuItem3
//
this.toolStripMenuItem3.Name = "toolStripMenuItem3";
this.toolStripMenuItem3.Size = new System.Drawing.Size(169, 6);
//
// m_toggleDottedLinesMenuItem
//
this.m_toggleDottedLinesMenuItem.Name = "m_toggleDottedLinesMenuItem";
this.m_toggleDottedLinesMenuItem.ShortcutKeyDisplayString = "T";
this.m_toggleDottedLinesMenuItem.Size = new System.Drawing.Size(172, 22);
this.m_toggleDottedLinesMenuItem.Text = "Dotted";
this.m_toggleDottedLinesMenuItem.Click += new System.EventHandler(this.ToggleDottedLines_Click);
//
// m_toggleDirectionalLinesMenuItem
//
this.m_toggleDirectionalLinesMenuItem.Name = "m_toggleDirectionalLinesMenuItem";
this.m_toggleDirectionalLinesMenuItem.ShortcutKeyDisplayString = "A";
this.m_toggleDirectionalLinesMenuItem.Size = new System.Drawing.Size(172, 22);
this.m_toggleDirectionalLinesMenuItem.Text = "One Way Arrow";
this.m_toggleDirectionalLinesMenuItem.Click += new System.EventHandler(this.ToggleDirectionalLines_Click);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(169, 6);
//
// m_upLinesMenuItem
//
this.m_upLinesMenuItem.Name = "m_upLinesMenuItem";
this.m_upLinesMenuItem.ShortcutKeyDisplayString = "U";
this.m_upLinesMenuItem.Size = new System.Drawing.Size(172, 22);
this.m_upLinesMenuItem.Text = "Up";
this.m_upLinesMenuItem.Click += new System.EventHandler(this.UpLinesMenuItem_Click);
//
// m_downLinesMenuItem
//
this.m_downLinesMenuItem.Name = "m_downLinesMenuItem";
this.m_downLinesMenuItem.ShortcutKeyDisplayString = "D";
this.m_downLinesMenuItem.Size = new System.Drawing.Size(172, 22);
this.m_downLinesMenuItem.Text = "Down";
this.m_downLinesMenuItem.Click += new System.EventHandler(this.DownLinesMenuItem_Click);
//
// toolStripMenuItem2
//
this.toolStripMenuItem2.Name = "toolStripMenuItem2";
this.toolStripMenuItem2.Size = new System.Drawing.Size(169, 6);
//
// m_inLinesMenuItem
//
this.m_inLinesMenuItem.Name = "m_inLinesMenuItem";
this.m_inLinesMenuItem.ShortcutKeyDisplayString = "I";
this.m_inLinesMenuItem.Size = new System.Drawing.Size(172, 22);
this.m_inLinesMenuItem.Text = "In";
this.m_inLinesMenuItem.Click += new System.EventHandler(this.InLinesMenuItem_Click);
//
// m_outLinesMenuItem
//
this.m_outLinesMenuItem.Name = "m_outLinesMenuItem";
this.m_outLinesMenuItem.ShortcutKeyDisplayString = "O";
this.m_outLinesMenuItem.Size = new System.Drawing.Size(172, 22);
this.m_outLinesMenuItem.Text = "Out";
this.m_outLinesMenuItem.Click += new System.EventHandler(this.OutLinesMenuItem_Click);
//
// m_reverseLineMenuItem
//
this.m_reverseLineMenuItem.Name = "m_reverseLineMenuItem";
this.m_reverseLineMenuItem.ShortcutKeyDisplayString = "V";
this.m_reverseLineMenuItem.Size = new System.Drawing.Size(211, 22);
this.m_reverseLineMenuItem.Text = "Reverse Line";
this.m_reverseLineMenuItem.Click += new System.EventHandler(this.ReverseLineMenuItem_Click);
//
// toolStripSeparator8
//
this.toolStripSeparator8.Name = "toolStripSeparator8";
this.toolStripSeparator8.Size = new System.Drawing.Size(208, 6);
//
// m_editSelectAllMenuItem
//
this.m_editSelectAllMenuItem.Name = "m_editSelectAllMenuItem";
this.m_editSelectAllMenuItem.ShortcutKeyDisplayString = "Ctrl + A";
this.m_editSelectAllMenuItem.Size = new System.Drawing.Size(211, 22);
this.m_editSelectAllMenuItem.Text = "Select All";
this.m_editSelectAllMenuItem.Click += new System.EventHandler(this.EditSelectAllMenuItem_Click);
//
// m_editSelectNoneMenuItem
//
this.m_editSelectNoneMenuItem.Name = "m_editSelectNoneMenuItem";
this.m_editSelectNoneMenuItem.ShortcutKeyDisplayString = "Escape";
this.m_editSelectNoneMenuItem.Size = new System.Drawing.Size(211, 22);
this.m_editSelectNoneMenuItem.Text = "Select None";
this.m_editSelectNoneMenuItem.Click += new System.EventHandler(this.EditSelectNoneMenuItem_Click);
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
this.toolStripSeparator5.Size = new System.Drawing.Size(208, 6);
//
// m_editCopyMenuItem
//
this.m_editCopyMenuItem.Name = "m_editCopyMenuItem";
this.m_editCopyMenuItem.ShortcutKeyDisplayString = "Ctrl + C";
this.m_editCopyMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C)));
this.m_editCopyMenuItem.Size = new System.Drawing.Size(211, 22);
this.m_editCopyMenuItem.Text = "Copy";
this.m_editCopyMenuItem.Click += new System.EventHandler(this.m_editCopyMenuItem_Click);
//
// m_editCopyColorToolMenuItem
//
this.m_editCopyColorToolMenuItem.Name = "m_editCopyColorToolMenuItem";
this.m_editCopyColorToolMenuItem.ShortcutKeyDisplayString = "Ctrl + Alt + C";
this.m_editCopyColorToolMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Alt)
| System.Windows.Forms.Keys.C)));
this.m_editCopyColorToolMenuItem.Size = new System.Drawing.Size(211, 22);
this.m_editCopyColorToolMenuItem.Text = "Copy Color";
this.m_editCopyColorToolMenuItem.Click += new System.EventHandler(this.m_editCopyColorToolMenuItem_Click);
//
// m_editPasteMenuItem
//
this.m_editPasteMenuItem.Name = "m_editPasteMenuItem";
this.m_editPasteMenuItem.ShortcutKeyDisplayString = "Ctrl + V";
this.m_editPasteMenuItem.Size = new System.Drawing.Size(211, 22);
this.m_editPasteMenuItem.Text = "Paste";
this.m_editPasteMenuItem.Click += new System.EventHandler(this.m_editPasteMenuItem_Click);
//
// toolStripMenuItem8
//
this.toolStripMenuItem8.Name = "toolStripMenuItem8";
this.toolStripMenuItem8.Size = new System.Drawing.Size(208, 6);
//
// m_editDeleteMenuItem
//
this.m_editDeleteMenuItem.Name = "m_editDeleteMenuItem";
this.m_editDeleteMenuItem.ShortcutKeys = System.Windows.Forms.Keys.Delete;
this.m_editDeleteMenuItem.Size = new System.Drawing.Size(211, 22);
this.m_editDeleteMenuItem.Text = "&Delete";
this.m_editDeleteMenuItem.Click += new System.EventHandler(this.EditDeleteMenuItem_Click);
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(208, 6);
//
// m_editPropertiesMenuItem
//
this.m_editPropertiesMenuItem.Name = "m_editPropertiesMenuItem";
this.m_editPropertiesMenuItem.ShortcutKeyDisplayString = "Enter";
this.m_editPropertiesMenuItem.Size = new System.Drawing.Size(211, 22);
this.m_editPropertiesMenuItem.Text = "P&roperties";
this.m_editPropertiesMenuItem.Click += new System.EventHandler(this.EditPropertiesMenuItem_Click);
//
// m_viewMenu
//
this.m_viewMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.m_viewZoomMenu,
this.m_viewEntireMapMenuItem,
this.m_viewResetMenuItem,
this.toolStripMenuItem6,
this.m_viewMinimapMenuItem});
this.m_viewMenu.Name = "m_viewMenu";
this.m_viewMenu.Size = new System.Drawing.Size(44, 20);
this.m_viewMenu.Text = "&View";
//
// m_viewZoomMenu
//
this.m_viewZoomMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.m_viewZoomInMenuItem,
this.m_viewZoomOutMenuItem,
this.toolStripSeparator7,
this.m_viewZoomFiftyPercentMenuItem,
this.m_viewZoomOneHundredPercentMenuItem,
this.m_viewZoomTwoHundredPercentMenuItem});
this.m_viewZoomMenu.Name = "m_viewZoomMenu";
this.m_viewZoomMenu.Size = new System.Drawing.Size(204, 22);
this.m_viewZoomMenu.Text = "&Zoom";
//
// m_viewZoomInMenuItem
//
this.m_viewZoomInMenuItem.Name = "m_viewZoomInMenuItem";
this.m_viewZoomInMenuItem.ShortcutKeyDisplayString = "+ / Mouse Wheel";
this.m_viewZoomInMenuItem.Size = new System.Drawing.Size(189, 22);
this.m_viewZoomInMenuItem.Text = "&In";
this.m_viewZoomInMenuItem.Click += new System.EventHandler(this.ViewZoomInMenuItem_Click);
//
// m_viewZoomOutMenuItem
//
this.m_viewZoomOutMenuItem.Name = "m_viewZoomOutMenuItem";
this.m_viewZoomOutMenuItem.ShortcutKeyDisplayString = "- / Mouse Wheel";
this.m_viewZoomOutMenuItem.Size = new System.Drawing.Size(189, 22);
this.m_viewZoomOutMenuItem.Text = "&Out";
this.m_viewZoomOutMenuItem.Click += new System.EventHandler(this.ViewZoomOutMenuItem_Click);
//
// toolStripSeparator7
//
this.toolStripSeparator7.Name = "toolStripSeparator7";
this.toolStripSeparator7.Size = new System.Drawing.Size(186, 6);
//
// m_viewZoomFiftyPercentMenuItem
//
this.m_viewZoomFiftyPercentMenuItem.Name = "m_viewZoomFiftyPercentMenuItem";
this.m_viewZoomFiftyPercentMenuItem.Size = new System.Drawing.Size(189, 22);
this.m_viewZoomFiftyPercentMenuItem.Text = "&50%";
this.m_viewZoomFiftyPercentMenuItem.Click += new System.EventHandler(this.ViewZoomFiftyPercentMenuItem_Click);
//
// m_viewZoomOneHundredPercentMenuItem
//
this.m_viewZoomOneHundredPercentMenuItem.Name = "m_viewZoomOneHundredPercentMenuItem";
this.m_viewZoomOneHundredPercentMenuItem.Size = new System.Drawing.Size(189, 22);
this.m_viewZoomOneHundredPercentMenuItem.Text = "&100%";
this.m_viewZoomOneHundredPercentMenuItem.Click += new System.EventHandler(this.ViewZoomOneHundredPercentMenuItem_Click);
//
// m_viewZoomTwoHundredPercentMenuItem
//
this.m_viewZoomTwoHundredPercentMenuItem.Name = "m_viewZoomTwoHundredPercentMenuItem";
this.m_viewZoomTwoHundredPercentMenuItem.Size = new System.Drawing.Size(189, 22);
this.m_viewZoomTwoHundredPercentMenuItem.Text = "&200%";
this.m_viewZoomTwoHundredPercentMenuItem.Click += new System.EventHandler(this.ViewZoomTwoHundredPercentMenuItem_Click);
//
// m_viewEntireMapMenuItem
//
this.m_viewEntireMapMenuItem.Name = "m_viewEntireMapMenuItem";
this.m_viewEntireMapMenuItem.ShortcutKeyDisplayString = "Ctrl + Home";
this.m_viewEntireMapMenuItem.Size = new System.Drawing.Size(204, 22);
this.m_viewEntireMapMenuItem.Text = "&Entire Map";
this.m_viewEntireMapMenuItem.Click += new System.EventHandler(this.ViewEntireMapMenuItem_Click);
//
// m_viewResetMenuItem
//
this.m_viewResetMenuItem.Name = "m_viewResetMenuItem";
this.m_viewResetMenuItem.ShortcutKeyDisplayString = "Home";
this.m_viewResetMenuItem.Size = new System.Drawing.Size(204, 22);
this.m_viewResetMenuItem.Text = "&Reset";
this.m_viewResetMenuItem.Click += new System.EventHandler(this.ViewResetMenuItem_Click);
//
// toolStripMenuItem6
//
this.toolStripMenuItem6.Name = "toolStripMenuItem6";
this.toolStripMenuItem6.Size = new System.Drawing.Size(201, 6);
//
// m_viewMinimapMenuItem
//
this.m_viewMinimapMenuItem.Name = "m_viewMinimapMenuItem";
this.m_viewMinimapMenuItem.Size = new System.Drawing.Size(204, 22);
this.m_viewMinimapMenuItem.Text = "&Mini Map";
this.m_viewMinimapMenuItem.Click += new System.EventHandler(this.ViewMinimapMenuItem_Click);
//
// automappingToolStripMenuItem
//
this.automappingToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.m_automapStartMenuItem,
this.m_automapStopMenuItem});
this.automappingToolStripMenuItem.Name = "automappingToolStripMenuItem";
this.automappingToolStripMenuItem.Size = new System.Drawing.Size(69, 20);
this.automappingToolStripMenuItem.Text = "&Automap";
//
// m_automapStartMenuItem
//
this.m_automapStartMenuItem.Name = "m_automapStartMenuItem";
this.m_automapStartMenuItem.Size = new System.Drawing.Size(107, 22);
this.m_automapStartMenuItem.Text = "&Start...";
this.m_automapStartMenuItem.Click += new System.EventHandler(this.AutomapStartMenuItem_Click);
//
// m_automapStopMenuItem
//
this.m_automapStopMenuItem.Name = "m_automapStopMenuItem";
this.m_automapStopMenuItem.Size = new System.Drawing.Size(107, 22);
this.m_automapStopMenuItem.Text = "S&top";
this.m_automapStopMenuItem.Click += new System.EventHandler(this.AutomapStopMenuItem_Click);
//
// m_projectMenu
//
this.m_projectMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.m_projectSettingsMenuItem,
this.toolStripSeparator11,
this.m_projectResetToDefaultSettingsMenuItem});
this.m_projectMenu.Name = "m_projectMenu";
this.m_projectMenu.Size = new System.Drawing.Size(48, 20);
this.m_projectMenu.Text = "&Tools";
//
// m_projectSettingsMenuItem
//
this.m_projectSettingsMenuItem.Name = "m_projectSettingsMenuItem";
this.m_projectSettingsMenuItem.Size = new System.Drawing.Size(199, 22);
this.m_projectSettingsMenuItem.Text = "&Settings...";
this.m_projectSettingsMenuItem.Click += new System.EventHandler(this.ProjectSettingsMenuItem_Click);
//
// toolStripSeparator11
//
this.toolStripSeparator11.Name = "toolStripSeparator11";
this.toolStripSeparator11.Size = new System.Drawing.Size(196, 6);
//
// m_projectResetToDefaultSettingsMenuItem
//
this.m_projectResetToDefaultSettingsMenuItem.Name = "m_projectResetToDefaultSettingsMenuItem";
this.m_projectResetToDefaultSettingsMenuItem.Size = new System.Drawing.Size(199, 22);
this.m_projectResetToDefaultSettingsMenuItem.Text = "&Restore Default Settings";
this.m_projectResetToDefaultSettingsMenuItem.Click += new System.EventHandler(this.ProjectResetToDefaultSettingsMenuItem_Click);
//
// m_helpMenu
//
this.m_helpMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.m_onlineHelpMenuItem,
this.m_checkForUpdatesMenuItem,
this.toolStripMenuItem4,
this.m_helpAboutMenuItem});
this.m_helpMenu.Name = "m_helpMenu";
this.m_helpMenu.Size = new System.Drawing.Size(44, 20);
this.m_helpMenu.Text = "&Help";
//
// m_onlineHelpMenuItem
//
this.m_onlineHelpMenuItem.Name = "m_onlineHelpMenuItem";
this.m_onlineHelpMenuItem.Size = new System.Drawing.Size(171, 22);
this.m_onlineHelpMenuItem.Text = "Online Help";
this.m_onlineHelpMenuItem.Click += new System.EventHandler(this.HelpAndSupportMenuItem_Click);
//
// m_checkForUpdatesMenuItem
//
this.m_checkForUpdatesMenuItem.Name = "m_checkForUpdatesMenuItem";
this.m_checkForUpdatesMenuItem.Size = new System.Drawing.Size(171, 22);
this.m_checkForUpdatesMenuItem.Text = "Check for &Updates";
this.m_checkForUpdatesMenuItem.Click += new System.EventHandler(this.CheckForUpdatesMenuItem_Click);
//
// toolStripMenuItem4
//
this.toolStripMenuItem4.Name = "toolStripMenuItem4";
this.toolStripMenuItem4.Size = new System.Drawing.Size(168, 6);
//
// m_helpAboutMenuItem
//
this.m_helpAboutMenuItem.Name = "m_helpAboutMenuItem";
this.m_helpAboutMenuItem.Size = new System.Drawing.Size(171, 22);
this.m_helpAboutMenuItem.Text = "&About";
this.m_helpAboutMenuItem.Click += new System.EventHandler(this.HelpAboutMenuItem_Click);
//
// m_toolStrip
//
this.m_toolStrip.AutoSize = false;
this.m_toolStrip.Dock = System.Windows.Forms.DockStyle.Left;
this.m_toolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.m_toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.m_toggleDottedLinesButton,
this.m_toggleDirectionalLinesButton});
this.m_toolStrip.Location = new System.Drawing.Point(0, 24);
this.m_toolStrip.Name = "m_toolStrip";
this.m_toolStrip.Padding = new System.Windows.Forms.Padding(1, 0, 1, 0);
this.m_toolStrip.Size = new System.Drawing.Size(38, 420);
this.m_toolStrip.TabIndex = 2;
//
// m_toggleDottedLinesButton
//
this.m_toggleDottedLinesButton.AutoSize = false;
this.m_toggleDottedLinesButton.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("m_toggleDottedLinesButton.BackgroundImage")));
this.m_toggleDottedLinesButton.CheckOnClick = true;
this.m_toggleDottedLinesButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.m_toggleDottedLinesButton.Image = global::Trizbort.Properties.Resources.LineStyle;
this.m_toggleDottedLinesButton.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.m_toggleDottedLinesButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.m_toggleDottedLinesButton.Name = "m_toggleDottedLinesButton";
this.m_toggleDottedLinesButton.Size = new System.Drawing.Size(32, 32);
this.m_toggleDottedLinesButton.Text = "Toggle Dotted Lines (T)";
this.m_toggleDottedLinesButton.Click += new System.EventHandler(this.ToggleDottedLines_Click);
//
// m_toggleDirectionalLinesButton
//
this.m_toggleDirectionalLinesButton.AutoSize = false;
this.m_toggleDirectionalLinesButton.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("m_toggleDirectionalLinesButton.BackgroundImage")));
this.m_toggleDirectionalLinesButton.CheckOnClick = true;
this.m_toggleDirectionalLinesButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.m_toggleDirectionalLinesButton.Image = global::Trizbort.Properties.Resources.LineDirection;
this.m_toggleDirectionalLinesButton.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.m_toggleDirectionalLinesButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.m_toggleDirectionalLinesButton.Name = "m_toggleDirectionalLinesButton";
this.m_toggleDirectionalLinesButton.Size = new System.Drawing.Size(32, 32);
this.m_toggleDirectionalLinesButton.Text = "Toggle One Way Arrow Lines (A)";
this.m_toggleDirectionalLinesButton.Click += new System.EventHandler(this.ToggleDirectionalLines_Click);
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
this.toolStripSeparator4.Size = new System.Drawing.Size(6, 6);
//
// m_automapBar
//
this.m_automapBar.BackColor = System.Drawing.SystemColors.Info;
this.m_automapBar.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.m_automapBar.Dock = System.Windows.Forms.DockStyle.Bottom;
this.m_automapBar.ForeColor = System.Drawing.SystemColors.InfoText;
this.m_automapBar.Location = new System.Drawing.Point(38, 415);
this.m_automapBar.MaximumSize = new System.Drawing.Size(4096, 29);
this.m_automapBar.MinimumSize = new System.Drawing.Size(2, 29);
this.m_automapBar.Name = "m_automapBar";
this.m_automapBar.Size = new System.Drawing.Size(586, 29);
this.m_automapBar.Status = "(Status)";
this.m_automapBar.TabIndex = 4;
//
// m_canvas
//
this.m_canvas.BackColor = System.Drawing.Color.White;
this.m_canvas.Dock = System.Windows.Forms.DockStyle.Fill;
this.m_canvas.Location = new System.Drawing.Point(38, 24);
this.m_canvas.MinimapVisible = true;
this.m_canvas.Name = "m_canvas";
this.m_canvas.Size = new System.Drawing.Size(586, 420);
this.m_canvas.TabIndex = 3;
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(624, 444);
this.Controls.Add(this.m_automapBar);
this.Controls.Add(this.m_canvas);
this.Controls.Add(this.m_toolStrip);
this.Controls.Add(this.m_menuStrip);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MainMenuStrip = this.m_menuStrip;
this.Name = "MainForm";
this.Text = "Trizbort - Interactive Fiction Mapper";
this.Load += new System.EventHandler(this.MainForm_Load);
this.m_menuStrip.ResumeLayout(false);
this.m_menuStrip.PerformLayout();
this.m_toolStrip.ResumeLayout(false);
this.m_toolStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip m_menuStrip;
private System.Windows.Forms.ToolStripMenuItem m_fileMenu;
private System.Windows.Forms.ToolStripMenuItem m_fileExitMenuItem;
private System.Windows.Forms.ToolStripMenuItem m_projectMenu;
private System.Windows.Forms.ToolStripMenuItem m_projectSettingsMenuItem;
private System.Windows.Forms.ToolStripMenuItem m_fileNewMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem m_editMenu;
private System.Windows.Forms.ToolStripMenuItem m_editAddRoomMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem m_editDeleteMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripMenuItem m_editPropertiesMenuItem;
private System.Windows.Forms.ToolStrip m_toolStrip;
private System.Windows.Forms.ToolStripButton m_toggleDottedLinesButton;
private System.Windows.Forms.ToolStripButton m_toggleDirectionalLinesButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripMenuItem m_lineStylesMenuItem;
private Canvas m_canvas;
private System.Windows.Forms.ToolStripMenuItem m_viewMenu;
private System.Windows.Forms.ToolStripMenuItem m_viewZoomMenu;
private System.Windows.Forms.ToolStripMenuItem m_viewZoomInMenuItem;
private System.Windows.Forms.ToolStripMenuItem m_viewZoomOutMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
private System.Windows.Forms.ToolStripMenuItem m_viewZoomFiftyPercentMenuItem;
private System.Windows.Forms.ToolStripMenuItem m_viewZoomOneHundredPercentMenuItem;
private System.Windows.Forms.ToolStripMenuItem m_viewZoomTwoHundredPercentMenuItem;
private System.Windows.Forms.ToolStripMenuItem m_viewResetMenuItem;
private System.Windows.Forms.ToolStripMenuItem m_editRenameMenuItem;
private System.Windows.Forms.ToolStripMenuItem m_editIsDarkMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator8;
private System.Windows.Forms.ToolStripMenuItem m_fileOpenMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator9;
private System.Windows.Forms.ToolStripMenuItem m_fileSaveMenuItem;
private System.Windows.Forms.ToolStripMenuItem m_fileSaveAsMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator10;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator11;
private System.Windows.Forms.ToolStripMenuItem m_projectResetToDefaultSettingsMenuItem;
private System.Windows.Forms.ToolStripMenuItem m_fileExportMenu;
private System.Windows.Forms.ToolStripMenuItem m_fileExportPDFMenuItem;
private System.Windows.Forms.ToolStripMenuItem m_fileExportImageMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator12;
private System.Windows.Forms.ToolStripMenuItem m_helpMenu;
private System.Windows.Forms.ToolStripMenuItem m_helpAboutMenuItem;
private System.Windows.Forms.ToolStripMenuItem m_plainLinesMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3;
private System.Windows.Forms.ToolStripMenuItem m_toggleDottedLinesMenuItem;
private System.Windows.Forms.ToolStripMenuItem m_toggleDirectionalLinesMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem m_upLinesMenuItem;
private System.Windows.Forms.ToolStripMenuItem m_downLinesMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem m_inLinesMenuItem;
private System.Windows.Forms.ToolStripMenuItem m_outLinesMenuItem;
private System.Windows.Forms.ToolStripMenuItem m_reverseLineMenuItem;
private System.Windows.Forms.ToolStripMenuItem m_onlineHelpMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem4;
private System.Windows.Forms.ToolStripMenuItem m_checkForUpdatesMenuItem;
private System.Windows.Forms.ToolStripMenuItem automappingToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem m_automapStartMenuItem;
private System.Windows.Forms.ToolStripMenuItem m_automapStopMenuItem;
private AutomapBar m_automapBar;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem6;
private System.Windows.Forms.ToolStripMenuItem m_viewMinimapMenuItem;
private System.Windows.Forms.ToolStripMenuItem m_fileExportInform7MenuItem;
private System.Windows.Forms.ToolStripMenuItem m_fileRecentMapsMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem7;
private System.Windows.Forms.ToolStripMenuItem m_editSelectAllMenuItem;
private System.Windows.Forms.ToolStripMenuItem m_editSelectNoneMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem8;
private System.Windows.Forms.ToolStripMenuItem m_viewEntireMapMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem9;
private System.Windows.Forms.ToolStripMenuItem tADSToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem10;
private System.Windows.Forms.ToolStripMenuItem inform6ToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private System.Windows.Forms.ToolStripMenuItem m_editCopyMenuItem;
private System.Windows.Forms.ToolStripMenuItem m_editPasteMenuItem;
private System.Windows.Forms.ToolStripMenuItem m_editCopyColorToolMenuItem;
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using ASC.Common.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using StackExchange.Redis;
using StackExchange.Redis.Extensions.Core;
using StackExchange.Redis.Extensions.Core.Extensions;
using StackExchange.Redis.Extensions.LegacyConfiguration;
namespace ASC.Common.Caching
{
public class RedisCache : ICache, ICacheNotify
{
private readonly string CacheId = Guid.NewGuid().ToString();
private readonly StackExchangeRedisCacheClient redis;
private readonly ConcurrentDictionary<Type, ConcurrentBag<Action<object, CacheNotifyAction>>> actions = new ConcurrentDictionary<Type, ConcurrentBag<Action<object, CacheNotifyAction>>>();
public RedisCache()
{
var configuration = ConfigurationManagerExtension.GetSection("redisCacheClient") as RedisCachingSectionHandler;
if (configuration == null)
throw new ConfigurationErrorsException("Unable to locate <redisCacheClient> section into your configuration file. Take a look https://github.com/imperugo/StackExchange.Redis.Extensions");
var stringBuilder = new StringBuilder();
using (var stream = new StringWriter(stringBuilder))
{
var opts = RedisCachingSectionHandler.GetConfig().ConfigurationOptions;
opts.SyncTimeout = 60000;
var connectionMultiplexer = (IConnectionMultiplexer)ConnectionMultiplexer.Connect(opts, stream);
redis = new StackExchangeRedisCacheClient(connectionMultiplexer, new Serializer());
LogManager.GetLogger("ASC").Debug(stringBuilder.ToString());
}
}
public T Get<T>(string key) where T : class
{
return redis.Get<T>(key);
}
public void Insert(string key, object value, TimeSpan sligingExpiration)
{
redis.Replace(key, value, sligingExpiration);
}
public void Insert(string key, object value, DateTime absolutExpiration)
{
redis.Replace(key, value, absolutExpiration == DateTime.MaxValue ? DateTimeOffset.MaxValue : new DateTimeOffset(absolutExpiration));
}
public void Remove(string key)
{
redis.Remove(key);
}
public void Remove(Regex pattern)
{
var glob = pattern.ToString().Replace(".*", "*").Replace(".", "?");
var keys = redis.SearchKeys(glob);
if (keys.Any())
{
redis.RemoveAll(keys);
}
}
public IDictionary<string, T> HashGetAll<T>(string key)
{
var dic = redis.Database.HashGetAll(key);
return dic
.Select(e =>
{
var val = default(T);
try
{
val = (string)e.Value != null ? JsonConvert.DeserializeObject<T>(e.Value) : default(T);
}
catch (Exception ex)
{
if (!e.Value.IsNullOrEmpty)
{
LogManager.GetLogger("ASC").ErrorFormat("RedisCache HashGetAll value: {0}", e.Value);
}
LogManager.GetLogger("ASC").Error(string.Format("RedisCache HashGetAll key: {0}", key), ex);
}
return new { Key = (string)e.Name, Value = val };
})
.Where(e => e.Value != null && !e.Value.Equals(default(T)))
.ToDictionary(e => e.Key, e => e.Value);
}
public T HashGet<T>(string key, string field)
{
var value = (string)redis.Database.HashGet(key, field);
try
{
return value != null ? JsonConvert.DeserializeObject<T>(value) : default(T);
}
catch (Exception ex)
{
LogManager.GetLogger("ASC").Error(string.Format("RedisCache HashGet key: {0}, field: {1}", key, field), ex);
return default(T);
}
}
public void HashSet<T>(string key, string field, T value)
{
if (value != null)
{
redis.Database.HashSet(key, field, JsonConvert.SerializeObject(value));
}
else
{
redis.Database.HashDelete(key, field);
}
}
public void Publish<T>(T obj, CacheNotifyAction action)
{
redis.Publish("asc:channel:" + typeof(T).FullName, new RedisCachePubSubItem<T>() { CacheId = CacheId, Object = obj, Action = action });
ConcurrentBag<Action<object, CacheNotifyAction>> onchange;
actions.TryGetValue(typeof(T), out onchange);
if (onchange != null)
{
onchange.ToArray().ForEach(r => r(obj, action));
}
}
public void Subscribe<T>(Action<T, CacheNotifyAction> onchange)
{
redis.Subscribe<RedisCachePubSubItem<T>>("asc:channel:" + typeof(T).FullName, (i) =>
{
if (i.CacheId != CacheId)
{
onchange(i.Object, i.Action);
}
});
if (onchange != null)
{
Action<object, CacheNotifyAction> action = (o, a) => onchange((T)o, a);
actions.AddOrUpdate(typeof(T),
new ConcurrentBag<Action<object, CacheNotifyAction>> { action },
(type, bag) =>
{
bag.Add(action);
return bag;
});
}
else
{
ConcurrentBag<Action<object, CacheNotifyAction>> removed;
actions.TryRemove(typeof(T), out removed);
}
}
[Serializable]
class RedisCachePubSubItem<T>
{
public string CacheId { get; set; }
public T Object { get; set; }
public CacheNotifyAction Action { get; set; }
}
class Serializer : ISerializer
{
private readonly Encoding enc = Encoding.UTF8;
public byte[] Serialize(object item)
{
try
{
var s = JsonConvert.SerializeObject(item);
return enc.GetBytes(s);
}
catch (Exception e)
{
LogManager.GetLogger("ASC").Error("Redis Serialize", e);
throw;
}
}
public object Deserialize(byte[] obj)
{
try
{
var resolver = new ContractResolver();
var settings = new JsonSerializerSettings { ContractResolver = resolver };
var s = enc.GetString(obj);
return JsonConvert.DeserializeObject(s, typeof(object), settings);
}
catch (Exception e)
{
LogManager.GetLogger("ASC").Error("Redis Deserialize", e);
throw;
}
}
public T Deserialize<T>(byte[] obj)
{
try
{
var resolver = new ContractResolver();
var settings = new JsonSerializerSettings { ContractResolver = resolver };
var s = enc.GetString(obj);
return JsonConvert.DeserializeObject<T>(s, settings);
}
catch (Exception e)
{
LogManager.GetLogger("ASC").Error("Redis Deserialize<T>", e);
throw;
}
}
public async Task<byte[]> SerializeAsync(object item)
{
return await Task.Factory.StartNew(() => Serialize(item));
}
public Task<object> DeserializeAsync(byte[] obj)
{
return Task.Factory.StartNew(() => Deserialize(obj));
}
public Task<T> DeserializeAsync<T>(byte[] obj)
{
return Task.Factory.StartNew(() => Deserialize<T>(obj));
}
class ContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var prop = base.CreateProperty(member, memberSerialization);
if (!prop.Writable)
{
var property = member as PropertyInfo;
if (property != null)
{
var hasPrivateSetter = property.GetSetMethod(true) != null;
prop.Writable = hasPrivateSetter;
}
}
return prop;
}
}
}
}
}
| |
namespace EIDSS.Reports.Parameterized.Veterinary.Situation
{
partial class VetSituationReport
{
#region 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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VetSituationReport));
DevExpress.XtraCharts.XYDiagram xyDiagram1 = new DevExpress.XtraCharts.XYDiagram();
DevExpress.XtraCharts.Series series1 = new DevExpress.XtraCharts.Series();
DevExpress.XtraCharts.SideBySideBarSeriesLabel sideBySideBarSeriesLabel1 = new DevExpress.XtraCharts.SideBySideBarSeriesLabel();
DevExpress.XtraCharts.SideBySideBarSeriesLabel sideBySideBarSeriesLabel2 = new DevExpress.XtraCharts.SideBySideBarSeriesLabel();
DevExpress.XtraCharts.ChartTitle chartTitle1 = new DevExpress.XtraCharts.ChartTitle();
this.vetSituationDataSet1 = new EIDSS.Reports.Parameterized.Veterinary.Situation.VetSituationDataSet();
this.tableHeader = new DevExpress.XtraReports.UI.XRTable();
this.rowHeader1 = new DevExpress.XtraReports.UI.XRTableRow();
this.cell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.cell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.cell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.cell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellType = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellPerson = new DevExpress.XtraReports.UI.XRTableCell();
this.DetailReport = new DevExpress.XtraReports.UI.DetailReportBand();
this.Detail1 = new DevExpress.XtraReports.UI.DetailBand();
this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell();
this.sp_rep_VET_YearlyVeterinarySituationTableAdapter1 = new EIDSS.Reports.Parameterized.Veterinary.Situation.VetSituationDataSetTableAdapters.sp_rep_VET_YearlyVeterinarySituationTableAdapter();
this.xrChart1 = new DevExpress.XtraReports.UI.XRChart();
this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand();
((System.ComponentModel.ISupportInitialize)(this.xrTable4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.baseDataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.vetSituationDataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrChart1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(xyDiagram1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(series1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(sideBySideBarSeriesLabel1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(sideBySideBarSeriesLabel2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// xrTable4
//
this.xrTable4.StylePriority.UseBorders = false;
this.xrTable4.StylePriority.UseFont = false;
this.xrTable4.StylePriority.UsePadding = false;
//
// cellLanguage
//
this.cellLanguage.StylePriority.UseTextAlignment = false;
//
// lblReportName
//
this.lblReportName.StylePriority.UseBorders = false;
this.lblReportName.StylePriority.UseBorderWidth = false;
this.lblReportName.StylePriority.UseFont = false;
this.lblReportName.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.lblReportName, "lblReportName");
//
// Detail
//
resources.ApplyResources(this.Detail, "Detail");
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
//
// PageHeader
//
this.PageHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.tableHeader});
resources.ApplyResources(this.PageHeader, "PageHeader");
this.PageHeader.PrintOn = DevExpress.XtraReports.UI.PrintOnPages.NotWithReportFooter;
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UsePadding = false;
//
// PageFooter
//
this.PageFooter.StylePriority.UseBorders = false;
//
// xrPageInfo1
//
this.xrPageInfo1.StylePriority.UseBorders = false;
//
// cellReportHeader
//
this.cellReportHeader.StylePriority.UseBorders = false;
this.cellReportHeader.StylePriority.UseFont = false;
this.cellReportHeader.StylePriority.UseTextAlignment = false;
//
// cellBaseSite
//
this.cellBaseSite.StylePriority.UseBorders = false;
this.cellBaseSite.StylePriority.UseFont = false;
this.cellBaseSite.StylePriority.UseTextAlignment = false;
//
// tableBaseHeader
//
this.tableBaseHeader.StylePriority.UseBorders = false;
this.tableBaseHeader.StylePriority.UseBorderWidth = false;
this.tableBaseHeader.StylePriority.UseFont = false;
this.tableBaseHeader.StylePriority.UsePadding = false;
this.tableBaseHeader.StylePriority.UseTextAlignment = false;
//
// vetSituationDataSet1
//
this.vetSituationDataSet1.DataSetName = "VetSituationDataSet";
this.vetSituationDataSet1.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// tableHeader
//
this.tableHeader.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.tableHeader, "tableHeader");
this.tableHeader.Name = "tableHeader";
this.tableHeader.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.rowHeader1});
this.tableHeader.StylePriority.UseBorders = false;
this.tableHeader.StylePriority.UseFont = false;
this.tableHeader.StylePriority.UseTextAlignment = false;
//
// rowHeader1
//
this.rowHeader1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.cell1,
this.xrTableCell1,
this.cell4,
this.xrTableCell2,
this.cell5,
this.xrTableCell5,
this.cell6,
this.xrTableCell6,
this.cellType,
this.xrTableCell7,
this.xrTableCell8,
this.xrTableCell10,
this.xrTableCell4,
this.cellPerson});
resources.ApplyResources(this.rowHeader1, "rowHeader1");
this.rowHeader1.Name = "rowHeader1";
this.rowHeader1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.rowHeader1.StylePriority.UseFont = false;
this.rowHeader1.StylePriority.UsePadding = false;
this.rowHeader1.StylePriority.UseTextAlignment = false;
this.rowHeader1.Weight = 0.4329004329004329D;
//
// cell1
//
resources.ApplyResources(this.cell1, "cell1");
this.cell1.Name = "cell1";
this.cell1.StylePriority.UseFont = false;
this.cell1.Weight = 0.56638733286590315D;
//
// xrTableCell1
//
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
this.xrTableCell1.Name = "xrTableCell1";
this.xrTableCell1.StylePriority.UseFont = false;
this.xrTableCell1.Weight = 0.12637834098790285D;
//
// cell4
//
resources.ApplyResources(this.cell4, "cell4");
this.cell4.Name = "cell4";
this.cell4.StylePriority.UseFont = false;
this.cell4.Weight = 0.12594490507336459D;
//
// xrTableCell2
//
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
this.xrTableCell2.Name = "xrTableCell2";
this.xrTableCell2.StylePriority.UseFont = false;
this.xrTableCell2.Weight = 0.12594490507336459D;
//
// cell5
//
resources.ApplyResources(this.cell5, "cell5");
this.cell5.Name = "cell5";
this.cell5.StylePriority.UseFont = false;
this.cell5.Weight = 0.12594490507336459D;
//
// xrTableCell5
//
resources.ApplyResources(this.xrTableCell5, "xrTableCell5");
this.xrTableCell5.Name = "xrTableCell5";
this.xrTableCell5.StylePriority.UseFont = false;
this.xrTableCell5.Weight = 0.12594490507336453D;
//
// cell6
//
resources.ApplyResources(this.cell6, "cell6");
this.cell6.Name = "cell6";
this.cell6.StylePriority.UseFont = false;
this.cell6.Weight = 0.12594490507336448D;
//
// xrTableCell6
//
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
this.xrTableCell6.Name = "xrTableCell6";
this.xrTableCell6.StylePriority.UseFont = false;
this.xrTableCell6.Weight = 0.12594490507336462D;
//
// cellType
//
resources.ApplyResources(this.cellType, "cellType");
this.cellType.Name = "cellType";
this.cellType.StylePriority.UseFont = false;
this.cellType.StylePriority.UseTextAlignment = false;
this.cellType.Weight = 0.12594490507336459D;
//
// xrTableCell7
//
resources.ApplyResources(this.xrTableCell7, "xrTableCell7");
this.xrTableCell7.Name = "xrTableCell7";
this.xrTableCell7.StylePriority.UseFont = false;
this.xrTableCell7.Weight = 0.12620335983910785D;
//
// xrTableCell8
//
resources.ApplyResources(this.xrTableCell8, "xrTableCell8");
this.xrTableCell8.Name = "xrTableCell8";
this.xrTableCell8.StylePriority.UseFont = false;
this.xrTableCell8.Weight = 0.12620335983910785D;
//
// xrTableCell10
//
resources.ApplyResources(this.xrTableCell10, "xrTableCell10");
this.xrTableCell10.Name = "xrTableCell10";
this.xrTableCell10.StylePriority.UseFont = false;
this.xrTableCell10.Weight = 0.12620335983910785D;
//
// xrTableCell4
//
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
this.xrTableCell4.Name = "xrTableCell4";
this.xrTableCell4.StylePriority.UseFont = false;
this.xrTableCell4.Weight = 0.12620335983910797D;
//
// cellPerson
//
resources.ApplyResources(this.cellPerson, "cellPerson");
this.cellPerson.Name = "cellPerson";
this.cellPerson.StylePriority.UseFont = false;
this.cellPerson.StylePriority.UseTextAlignment = false;
this.cellPerson.Weight = 0.12666608988127748D;
//
// DetailReport
//
this.DetailReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail1});
this.DetailReport.DataAdapter = this.sp_rep_VET_YearlyVeterinarySituationTableAdapter1;
this.DetailReport.DataMember = "spRepVetYearlyVeterinarySituation";
this.DetailReport.DataSource = this.vetSituationDataSet1;
this.DetailReport.Level = 0;
this.DetailReport.Name = "DetailReport";
//
// Detail1
//
this.Detail1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable1});
resources.ApplyResources(this.Detail1, "Detail1");
this.Detail1.Name = "Detail1";
//
// xrTable1
//
this.xrTable1.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.xrTable1, "xrTable1");
this.xrTable1.Name = "xrTable1";
this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1});
this.xrTable1.StylePriority.UseBorders = false;
this.xrTable1.StylePriority.UseFont = false;
this.xrTable1.StylePriority.UseTextAlignment = false;
//
// xrTableRow1
//
this.xrTableRow1.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell3,
this.xrTableCell9,
this.xrTableCell11,
this.xrTableCell12,
this.xrTableCell13,
this.xrTableCell14,
this.xrTableCell15,
this.xrTableCell16,
this.xrTableCell17,
this.xrTableCell18,
this.xrTableCell19,
this.xrTableCell20,
this.xrTableCell21,
this.xrTableCell22});
resources.ApplyResources(this.xrTableRow1, "xrTableRow1");
this.xrTableRow1.Name = "xrTableRow1";
this.xrTableRow1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrTableRow1.StylePriority.UseBorders = false;
this.xrTableRow1.StylePriority.UseFont = false;
this.xrTableRow1.StylePriority.UsePadding = false;
this.xrTableRow1.StylePriority.UseTextAlignment = false;
this.xrTableRow1.Weight = 0.4329004329004329D;
//
// xrTableCell3
//
this.xrTableCell3.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Disease")});
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
this.xrTableCell3.Name = "xrTableCell3";
this.xrTableCell3.StylePriority.UseFont = false;
this.xrTableCell3.Weight = 0.56638733286590315D;
//
// xrTableCell9
//
this.xrTableCell9.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Jan")});
resources.ApplyResources(this.xrTableCell9, "xrTableCell9");
this.xrTableCell9.Name = "xrTableCell9";
this.xrTableCell9.StylePriority.UseFont = false;
this.xrTableCell9.Weight = 0.12637834098790285D;
//
// xrTableCell11
//
this.xrTableCell11.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Feb")});
resources.ApplyResources(this.xrTableCell11, "xrTableCell11");
this.xrTableCell11.Name = "xrTableCell11";
this.xrTableCell11.StylePriority.UseFont = false;
this.xrTableCell11.Weight = 0.12594490507336459D;
//
// xrTableCell12
//
this.xrTableCell12.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Mar")});
resources.ApplyResources(this.xrTableCell12, "xrTableCell12");
this.xrTableCell12.Name = "xrTableCell12";
this.xrTableCell12.StylePriority.UseFont = false;
this.xrTableCell12.Weight = 0.12594490507336459D;
//
// xrTableCell13
//
this.xrTableCell13.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Apr")});
resources.ApplyResources(this.xrTableCell13, "xrTableCell13");
this.xrTableCell13.Name = "xrTableCell13";
this.xrTableCell13.StylePriority.UseFont = false;
this.xrTableCell13.Weight = 0.12594490507336459D;
//
// xrTableCell14
//
this.xrTableCell14.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.May")});
resources.ApplyResources(this.xrTableCell14, "xrTableCell14");
this.xrTableCell14.Name = "xrTableCell14";
this.xrTableCell14.StylePriority.UseFont = false;
this.xrTableCell14.Weight = 0.12594490507336453D;
//
// xrTableCell15
//
this.xrTableCell15.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Jun")});
resources.ApplyResources(this.xrTableCell15, "xrTableCell15");
this.xrTableCell15.Name = "xrTableCell15";
this.xrTableCell15.StylePriority.UseFont = false;
this.xrTableCell15.Weight = 0.12594490507336448D;
//
// xrTableCell16
//
this.xrTableCell16.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Jul")});
resources.ApplyResources(this.xrTableCell16, "xrTableCell16");
this.xrTableCell16.Name = "xrTableCell16";
this.xrTableCell16.StylePriority.UseFont = false;
this.xrTableCell16.Weight = 0.12594490507336462D;
//
// xrTableCell17
//
this.xrTableCell17.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Aug")});
resources.ApplyResources(this.xrTableCell17, "xrTableCell17");
this.xrTableCell17.Name = "xrTableCell17";
this.xrTableCell17.StylePriority.UseFont = false;
this.xrTableCell17.StylePriority.UseTextAlignment = false;
this.xrTableCell17.Weight = 0.12594490507336459D;
//
// xrTableCell18
//
this.xrTableCell18.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Sep")});
resources.ApplyResources(this.xrTableCell18, "xrTableCell18");
this.xrTableCell18.Name = "xrTableCell18";
this.xrTableCell18.StylePriority.UseFont = false;
this.xrTableCell18.Weight = 0.12620335983910785D;
//
// xrTableCell19
//
this.xrTableCell19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Oct")});
resources.ApplyResources(this.xrTableCell19, "xrTableCell19");
this.xrTableCell19.Name = "xrTableCell19";
this.xrTableCell19.StylePriority.UseFont = false;
this.xrTableCell19.Weight = 0.12620335983910785D;
//
// xrTableCell20
//
this.xrTableCell20.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Nov")});
resources.ApplyResources(this.xrTableCell20, "xrTableCell20");
this.xrTableCell20.Name = "xrTableCell20";
this.xrTableCell20.StylePriority.UseFont = false;
this.xrTableCell20.Weight = 0.12620335983910785D;
//
// xrTableCell21
//
this.xrTableCell21.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Dec")});
resources.ApplyResources(this.xrTableCell21, "xrTableCell21");
this.xrTableCell21.Name = "xrTableCell21";
this.xrTableCell21.StylePriority.UseFont = false;
this.xrTableCell21.Weight = 0.12620335983910797D;
//
// xrTableCell22
//
this.xrTableCell22.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Total")});
resources.ApplyResources(this.xrTableCell22, "xrTableCell22");
this.xrTableCell22.Name = "xrTableCell22";
this.xrTableCell22.StylePriority.UseFont = false;
this.xrTableCell22.StylePriority.UseTextAlignment = false;
this.xrTableCell22.Weight = 0.12666608988127748D;
//
// sp_rep_VET_YearlyVeterinarySituationTableAdapter1
//
this.sp_rep_VET_YearlyVeterinarySituationTableAdapter1.ClearBeforeFill = true;
//
// xrChart1
//
resources.ApplyResources(this.xrChart1, "xrChart1");
this.xrChart1.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
xyDiagram1.AxisX.Label.Antialiasing = true;
xyDiagram1.AxisX.MinorCount = 1;
xyDiagram1.AxisX.Range.SideMarginsEnabled = true;
xyDiagram1.AxisX.Title.Text = resources.GetString("resource.Text");
xyDiagram1.AxisX.Title.Visible = true;
xyDiagram1.AxisX.VisibleInPanesSerializable = "-1";
xyDiagram1.AxisY.GridSpacingAuto = false;
xyDiagram1.AxisY.Range.SideMarginsEnabled = true;
xyDiagram1.AxisY.Tickmarks.MinorVisible = false;
xyDiagram1.AxisY.Title.Text = resources.GetString("resource.Text1");
xyDiagram1.AxisY.Title.Visible = true;
xyDiagram1.AxisY.VisibleInPanesSerializable = "-1";
this.xrChart1.Diagram = xyDiagram1;
this.xrChart1.Legend.Visible = false;
this.xrChart1.Name = "xrChart1";
series1.ArgumentDataMember = "Disease";
series1.DataSource = this.vetSituationDataSet1.spRepVetYearlyVeterinarySituation;
sideBySideBarSeriesLabel1.LineVisible = true;
sideBySideBarSeriesLabel1.Visible = false;
series1.Label = sideBySideBarSeriesLabel1;
resources.ApplyResources(series1, "series1");
series1.ValueDataMembersSerializable = "Total";
this.xrChart1.SeriesSerializable = new DevExpress.XtraCharts.Series[] {
series1};
sideBySideBarSeriesLabel2.LineVisible = true;
this.xrChart1.SeriesTemplate.Label = sideBySideBarSeriesLabel2;
this.xrChart1.StylePriority.UseBorders = false;
resources.ApplyResources(chartTitle1, "chartTitle1");
this.xrChart1.Titles.AddRange(new DevExpress.XtraCharts.ChartTitle[] {
chartTitle1});
//
// ReportFooter
//
this.ReportFooter.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrChart1});
resources.ApplyResources(this.ReportFooter, "ReportFooter");
this.ReportFooter.Name = "ReportFooter";
//
// VetSituationReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.DetailReport,
this.ReportFooter});
this.Version = "11.1";
this.CanWorkWithArchive = false;
this.Controls.SetChildIndex(this.ReportFooter, 0);
this.Controls.SetChildIndex(this.DetailReport, 0);
this.Controls.SetChildIndex(this.ReportHeader, 0);
this.Controls.SetChildIndex(this.PageFooter, 0);
this.Controls.SetChildIndex(this.PageHeader, 0);
this.Controls.SetChildIndex(this.Detail, 0);
((System.ComponentModel.ISupportInitialize)(this.xrTable4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.baseDataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.vetSituationDataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit();
((System.ComponentModel.ISupportInitialize)(xyDiagram1)).EndInit();
((System.ComponentModel.ISupportInitialize)(sideBySideBarSeriesLabel1)).EndInit();
((System.ComponentModel.ISupportInitialize)(series1)).EndInit();
((System.ComponentModel.ISupportInitialize)(sideBySideBarSeriesLabel2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrChart1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.XRTable tableHeader;
private DevExpress.XtraReports.UI.XRTableRow rowHeader1;
private DevExpress.XtraReports.UI.XRTableCell cell1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableCell cell4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableCell cell5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableCell cell6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private DevExpress.XtraReports.UI.XRTableCell cellType;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell10;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTableCell cellPerson;
private DevExpress.XtraReports.UI.DetailReportBand DetailReport;
private DevExpress.XtraReports.UI.DetailBand Detail1;
private DevExpress.XtraReports.UI.XRTable xrTable1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell15;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell17;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell18;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell19;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell20;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell21;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell22;
private VetSituationDataSetTableAdapters.sp_rep_VET_YearlyVeterinarySituationTableAdapter sp_rep_VET_YearlyVeterinarySituationTableAdapter1;
private VetSituationDataSet vetSituationDataSet1;
private DevExpress.XtraReports.UI.XRChart xrChart1;
private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter;
}
}
| |
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using CreateThis.VR.UI.Interact;
namespace MeshEngine.Controller {
public class BoxSelectionController : PrimitiveBaseController {
public Mesh realMesh;
public GameObject meshGameObject;
private GameObject firstVertexInstance;
private GameObject secondVertexInstance;
private GameObject thirdVertexInstance;
private GameObject fourthVertexInstance;
private GameObject lastVertexInstance;
private UnityEngine.Mesh collisionMesh;
private Vector3 validationPoint;
private int selectedVerticesIndexBeforeBoxSelect;
public override void OnTriggerDown(Transform controller, int controllerIndex) {
base.OnTriggerDown(controller, controllerIndex);
triggerCount++;
if (triggerCount == 1) FirstTrigger(controller, controllerIndex);
if (triggerCount == 2) SecondTrigger(controller, controllerIndex);
if (triggerCount == 3) ThirdTrigger(controller, controllerIndex);
}
public override void OnTriggerUpdate(Transform controller, int controllerIndex) {
UpdatePositions(controller, controllerIndex);
}
public Vector3 MidPoint(Vector3 firstPosition, Vector3 secondPosition) {
return Vector3.Lerp(firstPosition, secondPosition, 0.5f);
}
public Vector3 SidePosition(Vector3 midPoint, float distance, Vector3 up) {
return midPoint + Quaternion.AngleAxis(90, up) * up * distance;
}
public void UpdatePositions(Transform controller, int controllerIndex) {
if (triggerCount == 1) UpdatePlanePositions(controller, controllerIndex);
if (triggerCount == 2) UpdateSelectionPositions(controller, controllerIndex);
}
public void UpdateSelectionPositions(Transform controller, int controllerIndex) {
lastVertexInstance.GetComponent<VertexController>().DragUpdate(controller, controllerIndex);
UpdateMeshCollider();
}
public int[] TransposeAllTrianglesUsingVerticesRange(int startVertexIndex, int endVertexIndex) {
List<int> selectedTriangles = new List<int>();
List<int> triangles = mesh.triangles.triangles;
for (int i = 0; i + 2 < triangles.Count; i += 3) {
if (triangles[i] >= startVertexIndex && triangles[i] <= endVertexIndex &&
triangles[i + 1] >= startVertexIndex && triangles[i + 1] <= endVertexIndex &&
triangles[i + 2] >= startVertexIndex && triangles[i + 2] <= endVertexIndex) {
selectedTriangles.Add(triangles[i] - startVertexIndex);
selectedTriangles.Add(triangles[i + 1] - startVertexIndex);
selectedTriangles.Add(triangles[i + 2] - startVertexIndex);
}
}
return selectedTriangles.ToArray();
}
public void UpdateMeshCollider() {
collisionMesh = new UnityEngine.Mesh();
int firstVertexIndex = mesh.vertices.IndexOfInstance(firstVertexInstance);
int numberToTake = mesh.vertices.vertices.Count - firstVertexIndex;
List<Vertex> vertices = new List<Vertex>(mesh.vertices.vertices.Skip(firstVertexIndex).Take(numberToTake).ToArray());
collisionMesh.vertices = mesh.vertices.Vector3ArrayOfVertices(vertices);
collisionMesh.triangles = TransposeAllTrianglesUsingVerticesRange(firstVertexIndex, mesh.vertices.vertices.Count - 1);
MeshCollider meshCollider = GetComponent<MeshCollider>();
if (meshCollider == null) meshCollider = gameObject.AddComponent<MeshCollider>();
if (collisionMesh.vertices.Length == 8) {
collisionMesh.RecalculateBounds();
meshCollider.sharedMesh = collisionMesh;
}
}
public void UpdateTransformFromPlane() {
transform.position = mesh.transform.position;
transform.rotation = mesh.transform.rotation;
UpdateMeshCollider();
}
public Vector3 CalculateNormal() {
Vector3 planeNormal = Vector3.Cross(thirdVertexInstance.transform.position - firstVertexInstance.transform.position, secondVertexInstance.transform.position - firstVertexInstance.transform.position).normalized * 0.025f;
return planeNormal;
}
public void UpdatePlanePositions(Transform controller, int controllerIndex) {
Vector3 position = Settings.SnapEnabled() ? Snap.WorldPosition(mesh.transform, controller.position) : controller.position;
fourthVertexInstance.GetComponent<VertexController>().UpdateLocalPositionFromWorldPosition(position);
Vector3 midPoint = MidPoint(firstVertexInstance.transform.position, fourthVertexInstance.transform.position);
float distance = Vector3.Distance(midPoint, fourthVertexInstance.transform.position);
Vector3 leftPosition = SidePosition(midPoint, distance, -controller.right);
Vector3 rightPosition = SidePosition(midPoint, distance, controller.right);
Vector3 snappedLeftPosition = Settings.SnapEnabled() ? Snap.WorldPosition(mesh.transform, leftPosition) : leftPosition;
Vector3 snappedRightPosition = Settings.SnapEnabled() ? Snap.WorldPosition(mesh.transform, rightPosition) : rightPosition;
secondVertexInstance.GetComponent<VertexController>().UpdateLocalPositionFromWorldPosition(snappedLeftPosition);
thirdVertexInstance.GetComponent<VertexController>().UpdateLocalPositionFromWorldPosition(snappedRightPosition);
UpdateTransformFromPlane();
}
public void CreateTriangles(bool up = true) {
if (up) {
mesh.triangles.AddTriangleVertex(fourthVertexInstance);
mesh.triangles.AddTriangleVertex(secondVertexInstance);
mesh.triangles.AddTriangleVertex(firstVertexInstance);
mesh.triangles.AddTriangleVertex(thirdVertexInstance);
mesh.triangles.AddTriangleVertex(fourthVertexInstance);
mesh.triangles.AddTriangleVertex(firstVertexInstance);
} else {
mesh.triangles.AddTriangleVertex(firstVertexInstance);
mesh.triangles.AddTriangleVertex(secondVertexInstance);
mesh.triangles.AddTriangleVertex(fourthVertexInstance);
mesh.triangles.AddTriangleVertex(firstVertexInstance);
mesh.triangles.AddTriangleVertex(fourthVertexInstance);
mesh.triangles.AddTriangleVertex(thirdVertexInstance);
}
}
public void SelectVertices() {
mesh.selection.SelectVertex(firstVertexInstance);
mesh.selection.SelectVertex(secondVertexInstance);
mesh.selection.SelectVertex(thirdVertexInstance);
mesh.selection.SelectVertex(fourthVertexInstance);
}
public void SetSelectable(bool value) {
firstVertexInstance.GetComponent<VertexController>().SetSelectable(value);
secondVertexInstance.GetComponent<VertexController>().SetSelectable(value);
thirdVertexInstance.GetComponent<VertexController>().SetSelectable(value);
fourthVertexInstance.GetComponent<VertexController>().SetSelectable(value);
if (lastVertexInstance) lastVertexInstance.GetComponent<VertexController>().SetSelectable(value);
}
public void CacheSelectedVertices() {
selectedVerticesIndexBeforeBoxSelect = realMesh.selection.selectedVertices.Count - 1;
}
public void FirstTrigger(Transform controller, int controllerIndex) {
CacheSelectedVertices();
mesh.selection.Clear();
Vector3 position = Settings.SnapEnabled() ? Snap.WorldPosition(mesh.transform, controller.position) : controller.position;
firstVertexInstance = mesh.vertices.CreateAndAddVertexInstanceByWorldPosition(position);
secondVertexInstance = mesh.vertices.CreateAndAddVertexInstanceByWorldPosition(position);
thirdVertexInstance = mesh.vertices.CreateAndAddVertexInstanceByWorldPosition(position);
fourthVertexInstance = mesh.vertices.CreateAndAddVertexInstanceByWorldPosition(position);
lastVertexInstance = null;
CreateTriangles();
SelectVertices();
SetSelectable(false);
}
public void SecondTrigger(Transform controller, int controllerIndex) {
UpdatePlanePositions(controller, controllerIndex);
mesh.extrusion.ExtrudeSelected();
// Avoid nuking the user's copy buffer by creating a local buffer.
Copy copy = new Copy(mesh);
copy.CopySelection();
mesh.selection.Clear();
SelectVertices();
mesh.triangles.FlipNormalsOfSelection();
mesh.selection.Clear();
copy.SelectVerticesFromCopy();
lastVertexInstance = mesh.selection.selectedVertices.Last().vertex.instance;
lastVertexInstance.GetComponent<VertexController>().DragStart(controller, controllerIndex);
SetSelectable(false);
}
public void ThirdTrigger(Transform controller, int controllerIndex) {
lastVertexInstance.GetComponent<VertexController>().DragEnd(controller, controllerIndex);
SetSelectable(true);
Remove();
}
public void Remove() {
Destroy(mesh.gameObject);
Destroy(gameObject);
}
public void CreateMesh() {
meshGameObject = new GameObject();
meshGameObject.name = "Box Select";
meshGameObject.AddComponent<MeshFilter>();
meshGameObject.AddComponent<MeshRenderer>();
meshGameObject.AddComponent<Mesh>();
meshGameObject.AddComponent<BoxCollider>();
Selectable realMeshSelectable = realMesh.GetComponent<Selectable>();
Selectable selectable = meshGameObject.AddComponent<Selectable>();
selectable.unselectedMaterials = new UnityEngine.Material[] { Meshes.unselectedMaterial };
selectable.highlightMaterial = realMeshSelectable.highlightMaterial;
selectable.outlineMaterial = realMeshSelectable.outlineMaterial;
meshGameObject.transform.position = realMesh.gameObject.transform.position;
meshGameObject.transform.rotation = realMesh.gameObject.transform.rotation;
mesh = meshGameObject.GetComponent<Mesh>();
mesh.vertexPrefab = realMesh.vertexPrefab;
mesh.trianglePrefab = realMesh.trianglePrefab;
mesh.load = false;
MeshRenderer meshRenderer = meshGameObject.GetComponent<MeshRenderer>();
meshRenderer.materials = realMesh.GetComponent<MeshRenderer>().materials;
mesh.Initialize();
mesh.SetRenderOptions(false, true, false);
mesh.triangles.autoCreateTriangleObjects = true;
mesh.triangles.hideTriangles = true;
mesh.vertices.hideVertices = true;
mesh.triangles.log = false;
}
protected override void Update() {
base.Update();
validationPoint = transform.position + transform.forward * 10.0f; // some point outside the mesh
MeshCollider meshCollider = GetComponent<MeshCollider>();
if (meshCollider == null) meshCollider = gameObject.AddComponent<MeshCollider>();
}
private void OnTriggerEnter(Collider collider) {
if (collider.GetComponent<VertexController>() && collider.tag == "Vertex") {
realMesh.selection.SelectVertex(collider.gameObject);
}
}
private void OnTriggerExit(Collider collider) {
if (collider.GetComponent<VertexController>() && collider.tag == "Vertex") {
if (!StillInside(collider.transform.position)) {
realMesh.selection.DeselectVertex(collider.gameObject);
List<SelectedVertex> selectedVerticesToUnselect = new List<SelectedVertex>();
int numberToTake = realMesh.selection.selectedVertices.Count - selectedVerticesIndexBeforeBoxSelect;
List<SelectedVertex> verticesSelectedDuringBoxSelect = new List<SelectedVertex>(realMesh.selection.selectedVertices.Skip(selectedVerticesIndexBeforeBoxSelect + 1).Take(numberToTake).ToArray());
// This foreach is necessary because the MeshCollider doesn't always call OnTriggerExit for each collider inside it, especially when the collider is changing shape quickly.
foreach (SelectedVertex selectedVertex in verticesSelectedDuringBoxSelect) {
if (!StillInside(selectedVertex.vertex.instance.transform.position)) {
selectedVerticesToUnselect.Add(selectedVertex);
}
}
foreach (SelectedVertex selectedVertex in selectedVerticesToUnselect) {
realMesh.selection.DeselectVertex(selectedVertex.vertex.instance.gameObject);
}
}
}
}
private bool StillInside(Vector3 target) {
RaycastHit[] hits;
Vector3 dir = target - validationPoint;
float dist = dir.magnitude;
//Debug.Log("Validating if the contact has really exited... Raycast with distance: " + dist);
hits = Physics.RaycastAll(validationPoint, dir.normalized, dist);
//Debug.DrawRay(validationPoint, dir.normalized * dist, Color.white, 40.0f);
foreach (RaycastHit hit in hits) {
if (hit.collider.gameObject == gameObject) {
//Debug.Log("The contact seems to still be inside.");
return true;
}
}
//Debug.Log("The contact seems to have left");
return false;
}
}
}
| |
using Android.Content;
using Android.Nfc;
using Android.Nfc.Tech;
using Poz1.NFCForms.Abstract;
using Poz1.NFCForms.Droid;
using System;
using System.Collections.Generic;
using System.IO;
[assembly: Xamarin.Forms.Dependency (typeof (NfcForms))]
namespace Poz1.NFCForms.Droid
{
#region Android NFC Techs
public sealed class NFCTechs
{
public const string IsoDep = "android.nfc.tech.IsoDep";
public const string NfcA = "android.nfc.tech.NfcA";
public const string NfcB = "android.nfc.tech.NfcB";
public const string NfcF = "android.nfc.tech.NfcF";
public const string NfcV = "android.nfc.tech.NfcV";
public const string Ndef = "android.nfc.tech.Ndef";
public const string NdefFormatable = "android.nfc.tech.NdefFormatable";
public const string MifareClassic = "android.nfc.tech.MifareClassic";
public const string MifareUltralight = "android.nfc.tech.MifareUltralight";
}
#endregion
public class NfcForms : INfcForms
{
#region Private Variables
private NfcAdapter nfcDevice;
private NfcFormsTag nfcTag;
private Tag droidTag;
#endregion
#region Properties
public bool IsAvailable
{
get
{
return nfcDevice.IsEnabled;
}
}
#endregion
#region Constructors
public NfcForms ()
{
NfcManager NfcManager = (NfcManager)Android.App.Application.Context.GetSystemService(Context.NfcService);
nfcDevice = NfcManager.DefaultAdapter;
nfcTag = new NfcFormsTag ();
}
#endregion
#region Private Methods
private Ndef GetNdef(Tag tag)
{
Ndef ndef = Ndef.Get(tag);
if (ndef == null)
return null;
else
return ndef;
}
private NdefLibrary.Ndef.NdefMessage ReadNdef(Ndef ndef)
{
if (ndef == null || ndef.CachedNdefMessage == null)
{
return null;
}
var bytes = ndef.CachedNdefMessage.ToByteArray();
var message = NdefLibrary.Ndef.NdefMessage.FromByteArray(bytes);
return message;
}
#endregion
#region Public Methods
public void OnNewIntent (object sender, Intent e)
{
droidTag = e.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;
if (droidTag != null)
{
nfcTag.TechList = new List<string>(droidTag.GetTechList());
nfcTag.Id = droidTag.GetId();
if (GetNdef (droidTag) == null)
{
nfcTag.IsNdefSupported = false;
}
else
{
nfcTag.IsNdefSupported = true;
Ndef ndef = GetNdef (droidTag);
nfcTag.NdefMessage = ReadNdef (ndef);
nfcTag.IsWriteable = ndef.IsWritable;
nfcTag.MaxSize = ndef.MaxSize;
}
RaiseNewTag(nfcTag);
}
}
public void WriteTag (NdefLibrary.Ndef.NdefMessage message)
{
if (droidTag == null)
{
throw new Exception("Tag Error: No Tag to write, register to NewTag event before calling WriteTag()");
}
Ndef ndef = GetNdef (droidTag);
if (ndef == null)
{
throw new Exception("Tag Error: NDEF not supported");
}
try
{
ndef.Connect();
RaiseTagConnected (nfcTag);
}
catch
{
throw new Exception("Tag Error: No Tag nearby");
}
if(!ndef.IsWritable)
{
ndef.Close ();
throw new Exception("Tag Error: Tag is write locked");
}
int size = message.ToByteArray ().Length;
if(ndef.MaxSize < size)
{
ndef.Close ();
throw new Exception("Tag Error: Tag is too small");
}
try
{
List<Android.Nfc.NdefRecord> records = new List<Android.Nfc.NdefRecord>();
for(int i = 0; i< message.Count;i++)
{
if(message[i].CheckIfValid())
records.Add(new Android.Nfc.NdefRecord(Android.Nfc.NdefRecord.TnfWellKnown,message[i].Type,message[i].Id,message[i].Payload));
else
{
throw new Exception("NDEFRecord number " + i + "is not valid");
}
};
Android.Nfc.NdefMessage msg = new Android.Nfc.NdefMessage(records.ToArray());
ndef.WriteNdefMessage(msg);
}
catch (TagLostException tle)
{
throw new Exception("Tag Lost Error: " + tle.Message);
}
catch (IOException ioe)
{
throw new Exception("Tag IO Error: " + ioe.ToString());
}
catch (Android.Nfc.FormatException fe)
{
throw new Exception("Tag Format Error: " + fe.Message);
}
catch (Exception e)
{
throw new Exception("Tag Error: " + e.ToString());
}
finally
{
ndef.Close ();
RaiseTagTagDisconnected (nfcTag);
}
}
#endregion
#region Events
public event EventHandler<NfcFormsTag> TagConnected;
public void RaiseTagConnected(NfcFormsTag tag)
{
nfcTag.IsConnected = true;
if (TagConnected != null)
{
TagConnected(this, tag);
}
}
public event EventHandler<NfcFormsTag> TagDisconnected;
public void RaiseTagTagDisconnected(NfcFormsTag tag)
{
nfcTag.IsConnected = false;
if (TagDisconnected != null)
{
TagDisconnected(this, tag);
}
}
public event EventHandler<NfcFormsTag> NewTag;
public void RaiseNewTag(NfcFormsTag tag)
{
if (NewTag != null)
{
NewTag(this, tag);
}
}
#endregion
}
}
| |
/*
Copyright (c) 2006- DEVSENSE
Copyright (c) 2004-2006 Tomas Matousek, Vaclav Novak and Martin Maly.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection.Emit;
using System.Diagnostics;
using PHP.Core.AST;
using PHP.Core.Emit;
using PHP.Core.Parsers;
namespace PHP.Core.Compiler.AST
{
partial class NodeCompilers
{
#region Statement
[NodeCompiler(typeof(Statement))]
abstract class StatementCompiler<T> : IStatementCompiler, INodeCompiler where T : Statement
{
/// <summary>
/// Analyzes an AST node containing a specialization of a statement.
/// </summary>
internal abstract Statement/*!*/ Analyze(T/*!*/node, Analyzer/*!*/ analyzer);
/// <summary>
/// Emits AST node respective IL code.
/// </summary>
internal abstract void Emit(T/*!*/node, CodeGenerator/*!*/ codeGenerator);
/// <summary>
/// Reports the statement unreachability.
/// The block statement reports the position of its first statement.
/// </summary>
protected virtual void ReportUnreachable(T/*!*/node, Analyzer/*!*/ analyzer)
{
analyzer.ErrorSink.Add(Warnings.UnreachableCodeDetected, analyzer.SourceUnit, node.Span);
}
#region IStatementCompiler Members
Statement IStatementCompiler.Analyze(Statement node, Analyzer analyzer)
{
return this.Analyze((T)node, analyzer);
}
void IStatementCompiler.Emit(Statement node, CodeGenerator codeGenerator)
{
this.Emit((T)node, codeGenerator);
}
void IStatementCompiler.ReportUnreachable(Statement/*!*/node, Analyzer/*!*/ analyzer)
{
this.ReportUnreachable((T)node, analyzer);
}
#endregion
}
#endregion
#region BlockStmt
[NodeCompiler(typeof(BlockStmt), Singleton = true)]
sealed class BlockStmtCompiler : StatementCompiler<BlockStmt>
{
internal override Statement Analyze(BlockStmt node, Analyzer analyzer)
{
if (analyzer.IsThisCodeUnreachable())
{
analyzer.ReportUnreachableCode(node.Span);
return EmptyStmt.Unreachable;
}
node.Statements.Analyze(analyzer);
return node;
}
protected override void ReportUnreachable(BlockStmt node, Analyzer analyzer)
{
if (node.Statements.Any())
node.Statements[0].ReportUnreachable(analyzer);
else
base.ReportUnreachable(node, analyzer);
}
internal override void Emit(BlockStmt node, CodeGenerator codeGenerator)
{
node.Statements.Emit(codeGenerator);
}
}
#endregion
#region ExpressionStmt
[NodeCompiler(typeof(ExpressionStmt), Singleton = true)]
sealed class ExpressionStmtCompiler : StatementCompiler<ExpressionStmt>
{
internal override Statement Analyze(ExpressionStmt node, Analyzer analyzer)
{
if (analyzer.IsThisCodeUnreachable())
{
analyzer.ReportUnreachableCode(node.Span);
return EmptyStmt.Unreachable;
}
ExInfoFromParent info = new ExInfoFromParent(node);
info.Access = AccessType.None;
Evaluation expr_eval = node.Expression.Analyze(analyzer, info);
// skip statement if it is evaluable (has no side-effects):
if (expr_eval.HasValue)
return EmptyStmt.Skipped;
node.Expression = expr_eval.Expression;
return node;
}
internal override void Emit(ExpressionStmt node, CodeGenerator codeGenerator)
{
if (node.Expression.DoMarkSequencePoint)
codeGenerator.MarkSequencePoint(node.Span);
try
{
// emit the expression
node.Expression.Emit(codeGenerator);
}
catch (CompilerException ex)
{
// put the error into the error sink,
// so the user can see, which expression is problematic (work item 20695)
codeGenerator.Context.Errors.Add(
ex.ErrorInfo,
codeGenerator.SourceUnit,
node.Span, // exact position of the statement
ex.ErrorParams
);
// terminate the emit with standard Exception
throw new Exception(CoreResources.GetString(ex.ErrorInfo.MessageId, ex.ErrorParams));
}
}
}
#endregion
#region EmptyStmt
[NodeCompiler(typeof(EmptyStmt), Singleton = true)]
sealed class EmptyStmtCompiler : StatementCompiler<EmptyStmt>
{
internal override Statement Analyze(EmptyStmt node, Analyzer analyzer)
{
return node;
}
internal override void Emit(EmptyStmt node, CodeGenerator codeGenerator)
{
codeGenerator.MarkSequencePoint(node.Span);
}
}
#endregion
#region PHPDocStmt
[NodeCompiler(typeof(PHPDocStmt), Singleton = true)]
sealed class PHPDocStmtCompiler : StatementCompiler<PHPDocStmt>
{
internal override Statement Analyze(PHPDocStmt node, Analyzer analyzer)
{
return node;
}
internal override void Emit(PHPDocStmt node, CodeGenerator codeGenerator)
{
}
}
#endregion
#region UnsetStmt
[NodeCompiler(typeof(UnsetStmt), Singleton = true)]
sealed class UnsetStmtCompiler : StatementCompiler<UnsetStmt>
{
internal override Statement Analyze(UnsetStmt node, Analyzer analyzer)
{
if (analyzer.IsThisCodeUnreachable())
{
analyzer.ReportUnreachableCode(node.Span);
return EmptyStmt.Unreachable;
}
//retval not needed, VariableUse analyzis always returns the same instance
//Access really shall by Read
foreach (VariableUse vu in node.VarList)
vu.Analyze(analyzer, ExInfoFromParent.DefaultExInfo);
return node;
}
internal override void Emit(UnsetStmt node, CodeGenerator codeGenerator)
{
Statistics.AST.AddNode("UnsetStmt");
codeGenerator.MarkSequencePoint(node.Span);
foreach (VariableUse variable in node.VarList)
{
codeGenerator.ChainBuilder.Create();
codeGenerator.ChainBuilder.QuietRead = true;
VariableUseHelper.EmitUnset(variable, codeGenerator);
codeGenerator.ChainBuilder.End();
}
}
}
#endregion
#region GlobalStmt
[NodeCompiler(typeof(GlobalStmt), Singleton = true)]
sealed class GlobalStmtCompiler : StatementCompiler<GlobalStmt>
{
internal override Statement Analyze(GlobalStmt node, Analyzer analyzer)
{
if (analyzer.IsThisCodeUnreachable())
{
analyzer.ReportUnreachableCode(node.Span);
return EmptyStmt.Unreachable;
}
ExInfoFromParent info = new ExInfoFromParent(node);
info.Access = AccessType.WriteRef;
foreach (SimpleVarUse svu in node.VarList)
svu.Analyze(analyzer, info);
return node;
}
internal override void Emit(GlobalStmt node, CodeGenerator codeGenerator)
{
Statistics.AST.AddNode("GlobalStmt");
foreach (SimpleVarUse variable in node.VarList)
{
variable.Emit(codeGenerator);
// CALL Operators.GetItemRef(<string variable name>, ref context.AutoGlobals.GLOBALS);
SimpleVarUseHelper.EmitName(variable, codeGenerator);
codeGenerator.EmitAutoGlobalLoadAddress(new VariableName(VariableName.GlobalsName));
codeGenerator.IL.Emit(OpCodes.Call, Methods.Operators.GetItemRef.String);
SimpleVarUseHelper.EmitAssign(variable, codeGenerator);
}
}
}
#endregion
#region StaticStmt
[NodeCompiler(typeof(StaticStmt), Singleton = true)]
sealed class StaticStmtCompiler : StatementCompiler<StaticStmt>
{
internal override Statement Analyze(StaticStmt node, Analyzer analyzer)
{
if (analyzer.IsThisCodeUnreachable())
{
analyzer.ReportUnreachableCode(node.Span);
return EmptyStmt.Unreachable;
}
foreach (StaticVarDecl svd in node.StVarList)
StaticVarDeclCompilerHelper.Analyze(svd, analyzer);
return node;
}
internal override void Emit(StaticStmt node, CodeGenerator codeGenerator)
{
Statistics.AST.AddNode("StaticStmt");
foreach (StaticVarDecl svd in node.StVarList)
StaticVarDeclCompilerHelper.Emit(svd, codeGenerator);
}
}
#endregion
#region StaticVarDecl
[NodeCompiler(typeof(StaticVarDecl), Singleton = true)]
sealed class StaticVarDeclCompiler : INodeCompiler
{
public void Analyze(StaticVarDecl/*!*/node, Analyzer analyzer)
{
ExInfoFromParent sinfo = new ExInfoFromParent(node);
sinfo.Access = AccessType.WriteRef;
node.Variable.Analyze(analyzer, sinfo);
if (node.Initializer != null)
node.Initializer = node.Initializer.Analyze(analyzer, ExInfoFromParent.DefaultExInfo).Literalize();
}
public void Emit(StaticVarDecl/*!*/node, CodeGenerator codeGenerator)
{
ILEmitter il = codeGenerator.IL;
string id = codeGenerator.GetLocationId();
if (id == null)
{
// we are in global code -> just assign the iniVal to the variable
node.Variable.Emit(codeGenerator);
if (node.Initializer != null)
{
codeGenerator.EmitBoxing(node.Initializer.Emit(codeGenerator));
il.Emit(OpCodes.Newobj, Constructors.PhpReference_Object);
}
else il.Emit(OpCodes.Newobj, Constructors.PhpReference_Void);
// continue ...
}
else
{
// cache the integer index of static local variable to access its value fast from within the array
// unique static local variable string ID
id = String.Format("{0}${1}${2}", id, node.Variable.VarName, node.Span.Start);
// create static field for static local index: private static int <id>;
var type = codeGenerator.IL.TypeBuilder;
Debug.Assert(type != null, "The method does not have declaring type! (global code in pure mode?)");
var field_id = type.DefineField(id, Types.Int[0], System.Reflection.FieldAttributes.Private | System.Reflection.FieldAttributes.Static);
// we are in a function or method -> try to retrieve the local value from ScriptContext
node.Variable.Emit(codeGenerator);
// <context>.GetStaticLocal( <field> )
codeGenerator.EmitLoadScriptContext(); // <context>
il.Emit(OpCodes.Ldsfld, field_id); // <field>
il.Emit(OpCodes.Callvirt, Methods.ScriptContext.GetStaticLocal); // GetStaticLocal
il.Emit(OpCodes.Dup);
// ?? <context>.AddStaticLocal( <field> != 0 ? <field> : ( <field> = ScriptContext.GetStaticLocalId(<id>) ), <initializer> )
if (true)
{
// if (GetStaticLocal(<field>) == null)
Label local_initialized = il.DefineLabel();
il.Emit(OpCodes.Brtrue/*not .S, initializer can emit really long code*/, local_initialized);
il.Emit(OpCodes.Pop);
// <field> != 0 ? <field> : ( <field> = ScriptContext.GetStaticLocalId(<id>) )
il.Emit(OpCodes.Ldsfld, field_id); // <field>
if (true)
{
// if (<field> == 0)
Label id_initialized = il.DefineLabel();
il.Emit(OpCodes.Brtrue_S, id_initialized);
// <field> = GetStaticLocalId( <id> )
il.Emit(OpCodes.Ldstr, id);
il.Emit(OpCodes.Call, Methods.ScriptContext.GetStaticLocalId);
il.Emit(OpCodes.Stsfld, field_id);
il.MarkLabel(id_initialized);
}
// <context>.AddStaticLocal(<field>,<initialize>)
codeGenerator.EmitLoadScriptContext(); // <context>
il.Emit(OpCodes.Ldsfld, field_id); // <field>
if (node.Initializer != null) codeGenerator.EmitBoxing(node.Initializer.Emit(codeGenerator)); // <initializer>
else il.Emit(OpCodes.Ldnull);
il.Emit(OpCodes.Callvirt, Methods.ScriptContext.AddStaticLocal); // AddStaticLocal
//
il.MarkLabel(local_initialized);
}
// continue ...
}
// stores value from top of the stack to the variable:
SimpleVarUseHelper.EmitAssign(node.Variable, codeGenerator);
}
}
static class StaticVarDeclCompilerHelper
{
public static void Analyze(StaticVarDecl/*!*/node, Analyzer analyzer)
{
node.NodeCompiler<StaticVarDeclCompiler>().Analyze(node, analyzer);
}
public static void Emit(StaticVarDecl/*!*/node, CodeGenerator codeGenerator)
{
node.NodeCompiler<StaticVarDeclCompiler>().Emit(node, codeGenerator);
}
}
#endregion
#region DeclareStmt
[NodeCompiler(typeof(DeclareStmt), Singleton = true)]
sealed class DeclareStmtCompiler : StatementCompiler<DeclareStmt>
{
internal override Statement Analyze(DeclareStmt node, Analyzer analyzer)
{
analyzer.ErrorSink.Add(Warnings.NotSupportedFunctionCalled, analyzer.SourceUnit, node.Span, "declare");
node.Statement.Analyze(analyzer);
return node;
}
protected override void ReportUnreachable(DeclareStmt node, Analyzer analyzer)
{
node.Statement.ReportUnreachable(analyzer);
}
internal override void Emit(DeclareStmt node, CodeGenerator codeGenerator)
{
node.Statement.Emit(codeGenerator);
}
}
#endregion
}
#region StatementUtils
internal static class StatementUtils
{
/// <summary>
/// Analyze all the <see cref="Statement"/> objects in the <paramref name="statements"/> list.
/// This methods replaces items in the original list if <see cref="IStatementCompiler.Analyze"/> returns a different instance.
/// </summary>
/// <param name="statements">List of statements to be analyzed.</param>
/// <param name="analyzer">Current <see cref="Analyzer"/>.</param>
public static void Analyze(this IList<Statement>/*!*/statements, Analyzer/*!*/ analyzer)
{
Debug.Assert(statements != null);
Debug.Assert(analyzer != null);
// analyze statements:
for (int i = 0; i < statements.Count; i++)
{
// analyze the statement
var statement = statements[i];
var analyzed = statement.Analyze(analyzer);
// update the statement in the list
if (!object.ReferenceEquals(statement, analyzer))
statements[i] = analyzed;
}
}
public static Statement Analyze(this Statement/*!*/statement, Analyzer/*!*/ analyzer)
{
return statement.NodeCompiler<IStatementCompiler>().Analyze(statement, analyzer);
}
/// <summary>
/// Emits each <see cref="Statement"/> in given <paramref name="statements"/> list.
/// </summary>
public static void Emit(this IEnumerable<Statement> statements, CodeGenerator codeGenerator)
{
if (statements != null)
{
foreach (Statement statement in statements)
statement.Emit(codeGenerator);
}
}
public static void Emit(this Statement/*!*/statement, CodeGenerator codeGenerator)
{
statement.NodeCompiler<IStatementCompiler>().Emit(statement, codeGenerator);
}
public static void ReportUnreachable(this Statement/*!*/statement, Analyzer/*!*/ analyzer)
{
statement.NodeCompiler<IStatementCompiler>().ReportUnreachable(statement, analyzer);
}
}
#endregion
#region IStatementCompiler
/// <summary>
/// Base interface for <see cref="Statement"/> compiler implementation.
/// </summary>
internal interface IStatementCompiler
{
/// <summary>
/// Analyzes an AST node containing a specialization of a statement.
/// </summary>
Statement/*!*/ Analyze(Statement/*!*/node, Analyzer/*!*/ analyzer);
/// <summary>
/// Emits AST node respective IL code.
/// </summary>
void Emit(Statement/*!*/node, CodeGenerator/*!*/ codeGenerator);
/// <summary>
/// Reports the statement unreachability.
/// </summary>
void ReportUnreachable(Statement/*!*/node, Analyzer/*!*/ analyzer);
}
#endregion
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.