context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
namespace Microsoft.Protocols.TestSuites.Common
{
using System.Text.RegularExpressions;
/// <summary>
/// This class implements rfc 822 compliant email validator routines.
/// </summary>
public static class RFC822AddressParser
{
/// <summary>
/// The constant string for the Escape character
/// </summary>
private const string Escape = @"\\";
/// <summary>
/// The constant string for the Period
/// </summary>
private const string Period = @"\.";
/// <summary>
/// The constant string for the Space
/// </summary>
private const string Space = @"\040";
/// <summary>
/// The constant string for the Tab
/// </summary>
private const string Tab = @"\t";
/// <summary>
/// The constant string for the open brackets
/// </summary>
private const string OpenBr = @"\[";
/// <summary>
/// The constant string for the close brackets
/// </summary>
private const string CloseBr = @"\]";
/// <summary>
/// The constant string for the open parentheses
/// </summary>
private const string OpenParen = @"\(";
/// <summary>
/// The constant string for the close parentheses
/// </summary>
private const string CloseParen = @"\)";
/// <summary>
/// The constant string for the Non-ASCII characters
/// </summary>
private const string NonAscii = @"\x80-\xff";
/// <summary>
/// The constant string for the Ctrl
/// </summary>
private const string Ctrl = @"\000-\037";
/// <summary>
/// The constant string for the carriage return/line feed
/// </summary>
private const string CRLF = @"\n\015";
/// <summary>
/// The regex expression for address
/// </summary>
private static Regex addreg;
/// <summary>
/// Initializes static members of the RFC822AddressParser class
/// </summary>
static RFC822AddressParser()
{
// Initialize the regex expression
InitialRegex();
}
/// <summary>
/// Verify whether the specified email address is compliant with RFC822 or not
/// </summary>
/// <param name="emailaddress">A string represent a actual email address</param>
/// <returns>A value indicates whether the address is a valid email address, true if the specified emailaddress is compliant with RFC822, otherwise return false.</returns>
public static bool IsValidAddress(string emailaddress)
{
return addreg.IsMatch(emailaddress);
}
/// <summary>
/// Initialize the regex expression
/// </summary>
private static void InitialRegex()
{
string qtext = @"[^" + RFC822AddressParser.Escape +
RFC822AddressParser.NonAscii +
RFC822AddressParser.CRLF + "\"]";
string dtext = @"[^" + RFC822AddressParser.Escape +
RFC822AddressParser.NonAscii +
RFC822AddressParser.CRLF +
RFC822AddressParser.OpenBr +
RFC822AddressParser.CloseBr + "\"]";
string quoted_pair = " " + RFC822AddressParser.Escape + " [^" + RFC822AddressParser.NonAscii + "] ";
string ctext = @" [^" + RFC822AddressParser.Escape +
RFC822AddressParser.NonAscii +
RFC822AddressParser.CRLF + "()] ";
// Nested quoted pairs
string cnested = string.Empty;
cnested += RFC822AddressParser.OpenParen;
cnested += ctext + "*";
cnested += "(?:" + quoted_pair + " " + ctext + "*)*";
cnested += RFC822AddressParser.CloseParen;
// A comment
string comment = string.Empty;
comment += RFC822AddressParser.OpenParen;
comment += ctext + "*";
comment += "(?:";
comment += "(?: " + quoted_pair + " | " + cnested + ")";
comment += ctext + "*";
comment += ")*";
comment += RFC822AddressParser.CloseParen;
// x is optional whitespace/comments
string x = string.Empty;
x += "[" + RFC822AddressParser.Space + RFC822AddressParser.Tab + "]*";
x += "(?: " + comment + " [" + RFC822AddressParser.Space + RFC822AddressParser.Tab + "]* )*";
// An email address atom
string atom_char = @"[^(" + RFC822AddressParser.Space + ")<>\\@,;:\\\"." + RFC822AddressParser.Escape + RFC822AddressParser.OpenBr +
RFC822AddressParser.CloseBr +
RFC822AddressParser.Ctrl +
RFC822AddressParser.NonAscii + "]";
string atom = string.Empty;
atom += atom_char + "+";
atom += "(?!" + atom_char + ")";
// Double quoted string, unrolled.
string quoted_str = "(?'quotedstr'";
quoted_str += "\\\"";
quoted_str += qtext + " *";
quoted_str += "(?: " + quoted_pair + qtext + " * )*";
quoted_str += "\\\")";
// A word is an atom or quoted string
string word = string.Empty;
word += "(?:";
word += atom;
word += "|";
word += quoted_str;
word += ")";
// A domain-ref is just an atom
string domain_ref = atom;
// A domain-literal is like a quoted string, but [...] instead of "..."
string domain_lit = string.Empty;
domain_lit += RFC822AddressParser.OpenBr;
domain_lit += "(?: " + dtext + " | " + quoted_pair + " )*";
domain_lit += RFC822AddressParser.CloseBr;
// A sub-domain is a domain-ref or a domain-literal
string sub_domain = string.Empty;
sub_domain += "(?:";
sub_domain += domain_ref;
sub_domain += "|";
sub_domain += domain_lit;
sub_domain += ")";
sub_domain += x;
// A domain is a list of subdomains separated by dots
string domain = "(?'domain'";
domain += sub_domain;
domain += "(:?";
domain += RFC822AddressParser.Period + " " + x + " " + sub_domain;
domain += ")*)";
// A route. A bunch of "@ domain" separated by commas, followed by a colon.
string route = string.Empty;
route += "\\@ " + x + " " + domain;
route += "(?: , " + x + " \\@ " + x + " " + domain + ")*";
route += ":";
route += x;
// A local-part is a bunch of 'word' separated by periods
string local_part = "(?'localpart'";
local_part += word + " " + x;
local_part += "(?:";
local_part += RFC822AddressParser.Period + " " + x + " " + word + " " + x;
local_part += ")*)";
// An addr-spec is local@domain
string addr_spec = local_part + " \\@ " + x + " " + domain;
// A route-addr is <route? addr-spec>
string route_addr = string.Empty;
route_addr += "< " + x;
route_addr += "(?: " + route + " )?";
route_addr += addr_spec;
route_addr += ">";
// A phrase
string phrase_ctrl = @"\000-\010\012-\037";
// Like atom-char, but without listing space, and uses phrase_ctrl. Since the class is negated, this matches the same as atom-char plus space and tab
string phrase_char = "[^()<>\\@,;:\\\"." + RFC822AddressParser.Escape +
RFC822AddressParser.OpenBr +
RFC822AddressParser.CloseBr +
RFC822AddressParser.NonAscii +
phrase_ctrl + "]";
string phrase = string.Empty;
phrase += word;
phrase += phrase_char;
phrase += "(?:";
phrase += "(?: " + comment + " | " + quoted_str + " )";
phrase += phrase_char + " *";
phrase += ")*";
// A mailbox is an addr_spec or a phrase/route_addr
string mailbox = string.Empty;
mailbox += x;
mailbox += "(?'mailbox'";
mailbox += addr_spec;
mailbox += "|";
mailbox += phrase + " " + route_addr;
mailbox += ")";
RFC822AddressParser.addreg = new Regex(mailbox, RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace);
}
}
}
| |
/***********************************************************************************************************************
Copyright (c) 2016, Imagination Technologies Limited and/or its affiliated group companies.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***********************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Threading;
using System.Diagnostics;
using Imagination.Model;
namespace Imagination
{
/// <summary>
/// Base class from Caching
/// Has a capacity and when this is reached the oldest item is replaced
/// </summary>
/// <typeparam name="TValue">Type that you want to cache</typeparam>
///
public class GenericCache<TKey, TValue>
{
public delegate void RemovedItemEventHandler(TKey key, TValue value);
public event RemovedItemEventHandler RemovedItem;
protected int _DefaultLockTimeOut = 100;
protected int _Count;
protected int _Capacity;
//protected ReaderWriterLockSlim _Lock = new ReaderWriterLockSlim();
protected ReaderWriterSpinLock _Lock = new ReaderWriterSpinLock();
protected Dictionary<TKey, TValue> _Cache;
private TKey[] _KeyQueue;
private int _KeyQueueHeadIndex;
private int _KeyQueueTailIndex;
private string _Name;
private class RemovedEntry
{
public TKey Key { get; set; }
public TValue Value { get; set; }
}
public GenericCache()
: this(1000)
{
}
public GenericCache(int capacity)
{
_Count = 0;
_Capacity = capacity;
_Cache = new Dictionary<TKey, TValue>(_Capacity);
_KeyQueue = new TKey[_Capacity];
_KeyQueueHeadIndex = 0;
_KeyQueueTailIndex = _Capacity-1;
_Name = typeof(TValue).Name;
}
public void Clear()
{
if (_Lock.TryEnterWriteLock(_DefaultLockTimeOut))
{
try
{
_Cache.Clear();
_Count = 0;
}
finally
{
_Lock.ExitWriteLock();
}
}
else
{
ApplicationEventLog.WriteEntry("Flow", string.Format("GenericCache:Clear - Failed to acquire lock."), EventLogEntryType.Error);
}
}
/// <summary>
/// Add item to cache
/// </summary>
/// <param name="key">Unique key of finding item</param>
/// <param name="item">Item to add</param>
/// <remarks>If already in cache it gets updated</remarks>
public void Add(TKey key, TValue item)
{
if (_Lock.TryEnterWriteLock(_DefaultLockTimeOut))
{
RemovedEntry removedItem = null;
try
{
TValue existingItem;
if (_Cache.TryGetValue(key, out existingItem))
{
_Cache[key] = item;
}
else if (key != null)
{
if ((_Count + 1) > _Capacity)
{
removedItem = RemoveOldestRequestedItem();
}
else
_Count++;
_Cache.Add(key, item);
_KeyQueueTailIndex = (_KeyQueueTailIndex + 1) % _Capacity;
_KeyQueue[_KeyQueueTailIndex] = key;
}
}
finally
{
_Lock.ExitWriteLock();
}
if ((removedItem != null) && (RemovedItem != null))
RemovedItem(removedItem.Key, removedItem.Value);
}
else
{
ApplicationEventLog.WriteEntry("Flow", string.Format("GenericCache:Add - Failed to acquire lock for key={0} value={1}", key, item), EventLogEntryType.Error);
}
}
/// <summary>
/// Removes item from cache
/// </summary>
/// <param name="key">Unique key of finding item.</param>
public void Remove(TKey key)
{
if (_Lock.TryEnterWriteLock(_DefaultLockTimeOut))
{
RemovedEntry removedItem = null;
try
{
TValue value;
if (_Cache.TryGetValue(key, out value))
{
bool removed = _Cache.Remove(key);
#if DEBUG
//ApplicationEventLog.WriteEntry("Flow", string.Format("GenericCache: removing item {0} of type {1} = removed={2}", key, typeof(TValue).Name, removed), EventLogEntryType.Information);
#endif
removedItem = new RemovedEntry() { Key = key, Value = value };
}
}
finally
{
_Lock.ExitWriteLock();
}
if ((removedItem != null) && (RemovedItem != null))
RemovedItem(removedItem.Key, removedItem.Value);
}
else
{
ApplicationEventLog.WriteEntry("Flow", string.Format("GenericCache:Remove - Failed to acquire lock for key={0} ", key), EventLogEntryType.Error);
}
}
private RemovedEntry RemoveOldestRequestedItem()
{
RemovedEntry result = null;
TValue value;
TKey key = _KeyQueue[_KeyQueueHeadIndex];
_KeyQueueHeadIndex = (_KeyQueueHeadIndex + 1) % _Capacity;
if (_Cache.TryGetValue(key, out value))
{
#if DEBUG
//ApplicationEventLog.WriteEntry("Flow", string.Format("GenericCache:Removing old item {0} of type {1}", key, typeof(TValue).Name), EventLogEntryType.Information);
#endif
_Cache.Remove(key);
result = new RemovedEntry() { Key = key, Value = value };
}
return result;
}
/// <summary>
/// Try to retrieve an item from the cache.
/// </summary>
/// <param name="key">Unique key of finding item</param>
/// <param name="item">The returned item.</param>
/// <returns>True if an item with the specified key was found.</returns>
public bool TryGetItem(TKey key, out TValue item)
{
bool result = false;
item = default(TValue);
if (_Lock.TryEnterReadLock(_DefaultLockTimeOut))
{
try
{
result = _Cache.TryGetValue(key, out item);
}
finally
{
_Lock.ExitReadLock();
}
}
else
{
ApplicationEventLog.WriteEntry("Flow", string.Format("GenericCache:TryGetItem - Failed to acquire lock for key={0}", key), EventLogEntryType.Error);
}
return result;
}
/// <summary>
/// Get/Add item in cache
/// </summary>
/// <param name="key">Unique key of finding item</param>
/// <returns></returns>
public TValue this[TKey key]
{
get
{
TValue result;
TryGetItem(key, out result);
return result;
}
set
{
Add(key,value);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Validation;
namespace System.Collections.Immutable
{
/// <content>
/// Contains the inner HashBucket struct.
/// </content>
public partial class ImmutableHashSet<T>
{
/// <summary>
/// The result of a mutation operation.
/// </summary>
internal enum OperationResult
{
/// <summary>
/// The change required element(s) to be added or removed from the collection.
/// </summary>
SizeChanged,
/// <summary>
/// No change was required (the operation ended in a no-op).
/// </summary>
NoChangeRequired,
}
/// <summary>
/// Contains all the keys in the collection that hash to the same value.
/// </summary>
internal struct HashBucket
{
/// <summary>
/// One of the values in this bucket.
/// </summary>
private readonly T firstValue;
/// <summary>
/// Any other elements that hash to the same value.
/// </summary>
/// <value>
/// This is null if and only if the entire bucket is empty (including <see cref="firstValue"/>).
/// It's empty if <see cref="firstValue"/> has an element but no additional elements.
/// </value>
private readonly ImmutableList<T>.Node additionalElements;
/// <summary>
/// Initializes a new instance of the <see cref="HashBucket"/> struct.
/// </summary>
/// <param name="firstElement">The first element.</param>
/// <param name="additionalElements">The additional elements.</param>
private HashBucket(T firstElement, ImmutableList<T>.Node additionalElements = null)
{
this.firstValue = firstElement;
this.additionalElements = additionalElements ?? ImmutableList<T>.Node.EmptyNode;
}
/// <summary>
/// Gets a value indicating whether this instance is empty.
/// </summary>
/// <value>
/// <c>true</c> if this instance is empty; otherwise, <c>false</c>.
/// </value>
internal bool IsEmpty
{
get { return this.additionalElements == null; }
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <summary>
/// Adds the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <param name="result">A description of the effect was on adding an element to this HashBucket.</param>
/// <returns>A new HashBucket that contains the added value and any values already held by this hashbucket.</returns>
internal HashBucket Add(T value, IEqualityComparer<T> valueComparer, out OperationResult result)
{
if (this.IsEmpty)
{
result = OperationResult.SizeChanged;
return new HashBucket(value);
}
if (valueComparer.Equals(value, this.firstValue) || this.additionalElements.IndexOf(value, valueComparer) >= 0)
{
result = OperationResult.NoChangeRequired;
return this;
}
result = OperationResult.SizeChanged;
return new HashBucket(this.firstValue, this.additionalElements.Add(value));
}
/// <summary>
/// Determines whether the HashBucket contains the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="valueComparer">The value comparer.</param>
internal bool Contains(T value, IEqualityComparer<T> valueComparer)
{
if (this.IsEmpty)
{
return false;
}
return valueComparer.Equals(value, this.firstValue) || this.additionalElements.IndexOf(value, valueComparer) >= 0;
}
/// <summary>
/// Searches the set for a given value and returns the equal value it finds, if any.
/// </summary>
/// <param name="value">The value to search for.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <param name="existingValue">The value from the set that the search found, or the original value if the search yielded no match.</param>
/// <returns>
/// A value indicating whether the search was successful.
/// </returns>
internal bool TryExchange(T value, IEqualityComparer<T> valueComparer, out T existingValue)
{
if (!this.IsEmpty)
{
if (valueComparer.Equals(value, this.firstValue))
{
existingValue = this.firstValue;
return true;
}
int index = this.additionalElements.IndexOf(value, valueComparer);
if (index >= 0)
{
existingValue = this.additionalElements[index];
return true;
}
}
existingValue = value;
return false;
}
/// <summary>
/// Removes the specified value if it exists in the collection.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="equalityComparer">The equality comparer.</param>
/// <param name="result">A description of the effect was on adding an element to this HashBucket.</param>
/// <returns>A new HashBucket that does not contain the removed value and any values already held by this hashbucket.</returns>
internal HashBucket Remove(T value, IEqualityComparer<T> equalityComparer, out OperationResult result)
{
if (this.IsEmpty)
{
result = OperationResult.NoChangeRequired;
return this;
}
if (equalityComparer.Equals(this.firstValue, value))
{
if (this.additionalElements.IsEmpty)
{
result = OperationResult.SizeChanged;
return new HashBucket();
}
else
{
// We can promote any element from the list into the first position, but it's most efficient
// to remove the root node in the binary tree that implements the list.
int indexOfRootNode = ((IBinaryTree<T>)this.additionalElements).Left.Count;
result = OperationResult.SizeChanged;
return new HashBucket(this.additionalElements.Key, this.additionalElements.RemoveAt(indexOfRootNode));
}
}
int index = this.additionalElements.IndexOf(value, equalityComparer);
if (index < 0)
{
result = OperationResult.NoChangeRequired;
return this;
}
else
{
result = OperationResult.SizeChanged;
return new HashBucket(this.firstValue, this.additionalElements.RemoveAt(index));
}
}
/// <summary>
/// Freezes this instance so that any further mutations require new memory allocations.
/// </summary>
internal void Freeze()
{
if (this.additionalElements != null)
{
this.additionalElements.Freeze();
}
}
/// <summary>
/// Enumerates all the elements in this instance.
/// </summary>
internal struct Enumerator : IEnumerator<T>, IDisposable
{
/// <summary>
/// The bucket being enumerated.
/// </summary>
private readonly HashBucket bucket;
/// <summary>
/// A value indicating whether this enumerator has been disposed.
/// </summary>
private bool disposed;
/// <summary>
/// The current position of this enumerator.
/// </summary>
private Position currentPosition;
/// <summary>
/// The enumerator that represents the current position over the additionalValues of the HashBucket.
/// </summary>
private ImmutableList<T>.Enumerator additionalEnumerator;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableHashSet<T>.HashBucket.Enumerator"/> struct.
/// </summary>
/// <param name="bucket">The bucket.</param>
internal Enumerator(HashBucket bucket)
{
this.disposed = false;
this.bucket = bucket;
this.currentPosition = Position.BeforeFirst;
this.additionalEnumerator = default(ImmutableList<T>.Enumerator);
}
/// <summary>
/// Describes the positions the enumerator state machine may be in.
/// </summary>
private enum Position
{
/// <summary>
/// The first element has not yet been moved to.
/// </summary>
BeforeFirst,
/// <summary>
/// We're at the firstValue of the containing bucket.
/// </summary>
First,
/// <summary>
/// We're enumerating the additionalValues in the bucket.
/// </summary>
Additional,
/// <summary>
/// The end of enumeration has been reached.
/// </summary>
End,
}
/// <summary>
/// Gets the current element.
/// </summary>
object IEnumerator.Current
{
get { return this.Current; }
}
/// <summary>
/// Gets the current element.
/// </summary>
public T Current
{
get
{
this.ThrowIfDisposed();
switch (this.currentPosition)
{
case Position.First:
return this.bucket.firstValue;
case Position.Additional:
return this.additionalEnumerator.Current;
default:
throw new InvalidOperationException();
}
}
}
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns>
/// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created. </exception>
public bool MoveNext()
{
this.ThrowIfDisposed();
if (this.bucket.IsEmpty)
{
this.currentPosition = Position.End;
return false;
}
switch (this.currentPosition)
{
case Position.BeforeFirst:
this.currentPosition = Position.First;
return true;
case Position.First:
if (this.bucket.additionalElements.IsEmpty)
{
this.currentPosition = Position.End;
return false;
}
this.currentPosition = Position.Additional;
this.additionalEnumerator = new ImmutableList<T>.Enumerator(this.bucket.additionalElements);
return this.additionalEnumerator.MoveNext();
case Position.Additional:
return this.additionalEnumerator.MoveNext();
case Position.End:
return false;
default:
throw new InvalidOperationException();
}
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the collection.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created. </exception>
public void Reset()
{
this.ThrowIfDisposed();
this.additionalEnumerator.Dispose();
this.currentPosition = Position.BeforeFirst;
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
this.disposed = true;
this.additionalEnumerator.Dispose();
}
/// <summary>
/// Throws an ObjectDisposedException if this enumerator has been disposed.
/// </summary>
private void ThrowIfDisposed()
{
if (this.disposed)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
namespace Microsoft.Management.UI.Internal
{
/// <summary>
/// Interaction logic for ColumnPicker.xaml.
/// </summary>
/// <remarks>
/// The logic for manipulating the column lists is in
/// <see cref="InnerListGridView.OnColumnPicker"/>.
/// </remarks>
[SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")]
public partial class ColumnPicker : Window
{
private ObservableCollection<InnerListColumn> notSelectedColumns = new ObservableCollection<InnerListColumn>();
private ObservableCollection<InnerListColumn> selectedColumns = new ObservableCollection<InnerListColumn>();
#region constructor
/// <summary>
/// Default Constructor.
/// </summary>
internal ColumnPicker()
{
this.InitializeComponent();
CollectionViewSource view =
(CollectionViewSource)this.Resources["SortedAvailableColumns"];
view.Source = this.notSelectedColumns;
this.PART_SelectedList.ItemsSource = this.selectedColumns;
}
/// <summary>
/// Constructor which initializes lists.
/// </summary>
/// <param name="columns">Initially selected columns.</param>
/// <param name="availableColumns">
/// All initial columns, if these include any which are selected
/// these are excluded.
/// </param>
/// <remarks>
/// It is not sufficient to just get
/// <paramref name="availableColumns"/>, since this does not
/// communicate the current ordering of visible columns.
/// </remarks>
internal ColumnPicker(
ICollection<GridViewColumn> columns,
ICollection<InnerListColumn> availableColumns)
: this()
{
if (columns == null)
{
throw new ArgumentNullException("columns");
}
if (availableColumns == null)
{
throw new ArgumentNullException("availableColumns");
}
// Add visible columns to Selected list, preserving order
// Note that availableColumns is not necessarily in the order
// in which columns are currently displayed.
foreach (InnerListColumn column in columns)
{
Debug.Assert(availableColumns.Contains(column), "all visible columns should be in availableColumns");
Debug.Assert(column.Visible, "all visible columns should have Visible==true");
this.SelectedColumns.Add(column);
}
foreach (InnerListColumn column in availableColumns)
{
Debug.Assert(column.Visible == columns.Contains(column), "exactly visible columns should have Visible==true");
// only add columns not in selected list
if (!columns.Contains(column))
{
Debug.Assert(!column.Required, "Required columns should be visible");
this.NotSelectedColumns.Add(column);
}
}
if (this.SelectedColumns.Count > 0)
{
this.PART_SelectedList.SelectedIndex = 0;
}
if (this.NotSelectedColumns.Count > 0)
{
this.PART_NotSelectedList.SelectedIndex = 0;
}
// If we don't do this, the last call to OnSelectionChanged
// may have been made while there was only one column
// (after the first column was added).
this.OnSelectionChanged();
}
#endregion constructor
#region properties
/// <summary>
/// Gets the columns in "Selected columns" list.
/// </summary>
internal ObservableCollection<InnerListColumn> SelectedColumns
{
get
{
return this.selectedColumns;
}
}
/// <summary>
/// Gets the columns in "Available columns" list.
/// </summary>
internal ObservableCollection<InnerListColumn> NotSelectedColumns
{
get
{
return this.notSelectedColumns;
}
}
#endregion properties
#region button clicks
/// <summary>
/// OK button was clicked.
/// </summary>
/// <param name="sender">OK button.</param>
/// <param name="e">The RoutedEventArgs.</param>
internal void OkButtonClick(object sender, RoutedEventArgs e)
{
foreach (InnerListColumn column in this.NotSelectedColumns)
{
column.Visible = false;
}
foreach (InnerListColumn column in this.SelectedColumns)
{
column.Visible = true;
}
this.DialogResult = true; // close the dialog
}
/// <summary>
/// Move Up button was clicked.
/// </summary>
/// <param name="sender">Move Up button.</param>
/// <param name="e">The RoutedEventArgs.</param>
/// <remarks>
/// Moving the selected item in the bound collection does not
/// trigger the SelectionChanged event in the listbox.
/// </remarks>
internal void MoveUpButtonClick(object sender, RoutedEventArgs e)
{
int selectedIndex = this.PART_SelectedList.SelectedIndex;
Debug.Assert(selectedIndex > 0, "Cannot move past top");
this.SelectedColumns.Move(selectedIndex, selectedIndex - 1);
// Moving the selected item in the bound collection does not
// trigger the SelectionChanged event in the listbox,
// so we call OnSelectionChanged explicitly.
this.OnSelectionChanged();
}
/// <summary>
/// Move Down button was clicked.
/// </summary>
/// <param name="sender">Move Down button.</param>
/// <param name="e">The RoutedEventArgs.</param>
internal void MoveDownButtonClick(object sender, RoutedEventArgs e)
{
int selectedIndex = this.PART_SelectedList.SelectedIndex;
Debug.Assert(this.SelectedColumns.Count > selectedIndex + 1, "Cannot move past bottom");
this.SelectedColumns.Move(selectedIndex, selectedIndex + 1);
// Moving the selected item in the bound collection does not
// trigger the SelectionChanged event in the listbox,
// so we call OnSelectionChanged explicitly.
this.OnSelectionChanged();
}
/// <summary>
/// Add button was clicked.
/// </summary>
/// <param name="sender">Add button.</param>
/// <param name="e">The RoutedEventArgs.</param>
internal void AddButtonClick(object sender, RoutedEventArgs e)
{
InnerListColumn column = (InnerListColumn)this.PART_NotSelectedList.SelectedItem;
Debug.Assert(column != null, "not null");
this.SelectedColumns.Add(column);
this.NotSelectedColumns.Remove(column);
// The next item in the NotSelected list
// is automatically selected.
// select new item in Selected list
this.PART_SelectedList.SelectedItem = column;
// Just to make sure, we call OnSelectionChanged
// explicitly here as well.
this.OnSelectionChanged();
}
/// <summary>
/// Remove button was clicked.
/// </summary>
/// <param name="sender">Remove button.</param>
/// <param name="e">The RoutedEventArgs.</param>
/// <remarks>
/// Note that we do not attempt to maintain the ordering of items
/// in the NotSelected list when they are removed and then added back.
/// In the current implementation, the View of the NotSelected list is
/// sorted by name through the CollectionViewSource.
/// </remarks>
internal void RemoveButtonClick(object sender, RoutedEventArgs e)
{
InnerListColumn column = (InnerListColumn)this.PART_SelectedList.SelectedItem;
Debug.Assert(column != null, "not null");
int selectedIndex = this.PART_SelectedList.SelectedIndex;
Debug.Assert(selectedIndex >= 0, "greater than or equal to 0");
this.NotSelectedColumns.Add(column);
this.SelectedColumns.Remove(column);
// Without this, there is no selection after the item is removed.
if (selectedIndex < this.SelectedColumns.Count)
{ // Select next item in Selected list
// Note that we select the next item based on the index
// in the View rather than the ViewModel.
this.PART_SelectedList.SelectedIndex = selectedIndex;
}
else if (selectedIndex > 0)
{ // Highest-index item removed, select previous item
Debug.Assert((selectedIndex - 1) < this.SelectedColumns.Count, "less than count");
this.PART_SelectedList.SelectedIndex = selectedIndex - 1;
} // otherwise there are no more items to select
// select new item in NotSelected list
this.PART_NotSelectedList.SelectedItem = column;
// Just to make sure, we call OnSelectionChanged
// explicitly here as well.
this.OnSelectionChanged();
}
#endregion button clicks
#region Automation
/// <summary>
/// Creates AutomationPeer (<see cref="UIElement.OnCreateAutomationPeer"/>).
/// </summary>
/// <returns>New AutomationPeer.</returns>
protected override AutomationPeer OnCreateAutomationPeer()
{
return new ExtendedFrameworkElementAutomationPeer(this, AutomationControlType.Window);
}
#endregion Automation
#region enable/disable buttons
/// <summary>
/// The selection changed in either the Selected or NotSelected list.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The eventargs.</param>
private void ListSelectionChanged(
object sender, SelectionChangedEventArgs e)
{
this.OnSelectionChanged();
}
/// <summary>
/// Update which buttons are enabled based on current selection,
/// also whether RequiredColumnText or LastColumnText
/// should be visible.
/// </summary>
private void OnSelectionChanged()
{
Selector selectedList = (Selector)this.FindName(
"PART_SelectedList");
Selector notSelectedList = (Selector)this.FindName(
"PART_NotSelectedList");
this.AddButton.IsEnabled = notSelectedList.SelectedIndex >= 0;
int selectedIndex = selectedList.SelectedIndex;
bool selectionValid = selectedIndex >= 0;
this.MoveUpButton.IsEnabled = selectedIndex > 0;
this.MoveDownButton.IsEnabled = selectionValid && this.SelectedColumns.Count > selectedIndex + 1;
bool hasOneColumn = this.SelectedColumns.Count < 2;
bool requiredColumn = selectionValid &&
this.SelectedColumns[selectedIndex].Required;
this.RemoveButton.IsEnabled = selectionValid && !requiredColumn && !hasOneColumn;
this.RequiredColumnText.Visibility = requiredColumn ? Visibility.Visible : Visibility.Hidden;
this.LastColumnText.Visibility = (hasOneColumn && !requiredColumn) ? Visibility.Visible : Visibility.Hidden;
}
#endregion enable/disable buttons
/// <summary>
/// Handles mouse double-click of items in
/// <see cref="PART_NotSelectedList"/>.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The eventargs.</param>
private void NotSelectedList_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
// Ignore right-double-click, and also ignore cases where
// the add button is disabled (which really shouldn't happen).
if (e.ChangedButton != MouseButton.Left || !this.AddButton.IsEnabled)
{
return;
}
// Ignore double-clicks on the listbox whitespace
if (this.PART_NotSelectedList.ContainerFromElement((DependencyObject)e.OriginalSource) == null)
{
return;
}
// We rely on the behavior where double-click implicitly
// selects a list box item.
this.AddButtonClick(sender, e);
}
/// <summary>
/// Handles mouse double-click of items in
/// <see cref="PART_SelectedList"/>.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The eventargs.</param>
private void SelectedList_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
// Ignore right-double-click, and also ignore cases where
// the remove button is disabled. This can happen,
// see OnSelectionChanged for details.
if (e.ChangedButton != MouseButton.Left || !this.RemoveButton.IsEnabled)
{
return;
}
// Ignore double-clicks on the listbox whitespace
if (this.PART_SelectedList.ContainerFromElement((DependencyObject)e.OriginalSource) == null)
{
return;
}
// We rely on the behavior where double-click implicitly
// selects a list box item.
this.RemoveButtonClick(sender, e);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Internal.TypeSystem;
using Interlocked = System.Threading.Interlocked;
namespace Internal.IL.Stubs
{
/// <summary>
/// Base class for all delegate invocation thunks.
/// </summary>
public abstract class DelegateThunk : ILStubMethod
{
private DelegateInfo _delegateInfo;
public DelegateThunk(DelegateInfo delegateInfo)
{
_delegateInfo = delegateInfo;
}
public sealed override TypeSystemContext Context
{
get
{
return _delegateInfo.Type.Context;
}
}
public sealed override TypeDesc OwningType
{
get
{
return _delegateInfo.Type;
}
}
public sealed override MethodSignature Signature
{
get
{
return _delegateInfo.Signature;
}
}
public sealed override Instantiation Instantiation
{
get
{
return Instantiation.Empty;
}
}
protected TypeDesc SystemDelegateType
{
get
{
return Context.GetWellKnownType(WellKnownType.MulticastDelegate).BaseType;
}
}
protected FieldDesc ExtraFunctionPointerOrDataField
{
get
{
return SystemDelegateType.GetKnownField("m_extraFunctionPointerOrData");
}
}
protected FieldDesc HelperObjectField
{
get
{
return SystemDelegateType.GetKnownField("m_helperObject");
}
}
protected FieldDesc FirstParameterField
{
get
{
return SystemDelegateType.GetKnownField("m_firstParameter");
}
}
protected FieldDesc FunctionPointerField
{
get
{
return SystemDelegateType.GetKnownField("m_functionPointer");
}
}
}
/// <summary>
/// Invoke thunk for open delegates to static methods. Loads all arguments except
/// the 'this' pointer and performs an indirect call to the delegate target.
/// This method is injected into delegate types.
/// </summary>
public sealed class DelegateInvokeOpenStaticThunk : DelegateThunk
{
internal DelegateInvokeOpenStaticThunk(DelegateInfo delegateInfo)
: base(delegateInfo)
{
}
public override MethodIL EmitIL()
{
// Target has the same signature as the Invoke method, except it's static.
MethodSignatureBuilder builder = new MethodSignatureBuilder(Signature);
builder.Flags = Signature.Flags | MethodSignatureFlags.Static;
var emitter = new ILEmitter();
ILCodeStream codeStream = emitter.NewCodeStream();
// Load all arguments except 'this'
for (int i = 0; i < Signature.Length; i++)
{
codeStream.EmitLdArg(i + 1);
}
// Indirectly call the delegate target static method.
codeStream.EmitLdArg(0);
codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(ExtraFunctionPointerOrDataField));
codeStream.Emit(ILOpcode.calli, emitter.NewToken(builder.ToSignature()));
codeStream.Emit(ILOpcode.ret);
return emitter.Link(this);
}
public override string Name
{
get
{
return "InvokeOpenStaticThunk";
}
}
}
/// <summary>
/// Invoke thunk for closed delegates to static methods. The target
/// is a static method, but the first argument is captured by the delegate.
/// The signature of the target has an extra object-typed argument, followed
/// by the arguments that are delegate-compatible with the thunk signature.
/// This method is injected into delegate types.
/// </summary>
public sealed class DelegateInvokeClosedStaticThunk : DelegateThunk
{
internal DelegateInvokeClosedStaticThunk(DelegateInfo delegateInfo)
: base(delegateInfo)
{
}
public override MethodIL EmitIL()
{
TypeDesc[] targetMethodParameters = new TypeDesc[Signature.Length + 1];
targetMethodParameters[0] = Context.GetWellKnownType(WellKnownType.Object);
for (int i = 0; i < Signature.Length; i++)
{
targetMethodParameters[i + 1] = Signature[i];
}
var targetMethodSignature = new MethodSignature(
Signature.Flags | MethodSignatureFlags.Static, 0, Signature.ReturnType, targetMethodParameters);
var emitter = new ILEmitter();
ILCodeStream codeStream = emitter.NewCodeStream();
// Load the stored 'this'
codeStream.EmitLdArg(0);
codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(HelperObjectField));
// Load all arguments except 'this'
for (int i = 0; i < Signature.Length; i++)
{
codeStream.EmitLdArg(i + 1);
}
// Indirectly call the delegate target static method.
codeStream.EmitLdArg(0);
codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(ExtraFunctionPointerOrDataField));
codeStream.Emit(ILOpcode.calli, emitter.NewToken(targetMethodSignature));
codeStream.Emit(ILOpcode.ret);
return emitter.Link(this);
}
public override string Name
{
get
{
return "InvokeClosedStaticThunk";
}
}
}
/// <summary>
/// Multicast invoke thunk for delegates that are a result of Delegate.Combine.
/// Passes it's arguments to each of the delegates that got combined and calls them
/// one by one. Returns the value of the last delegate executed.
/// This method is injected into delegate types.
/// </summary>
public sealed class DelegateInvokeMulticastThunk : DelegateThunk
{
internal DelegateInvokeMulticastThunk(DelegateInfo delegateInfo)
: base(delegateInfo)
{
}
public override MethodIL EmitIL()
{
ILEmitter emitter = new ILEmitter();
ILCodeStream codeStream = emitter.NewCodeStream();
ArrayType invocationListArrayType = SystemDelegateType.MakeArrayType();
ILLocalVariable delegateArrayLocal = emitter.NewLocal(invocationListArrayType);
ILLocalVariable invocationCountLocal = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32));
ILLocalVariable iteratorLocal = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32));
ILLocalVariable delegateToCallLocal = emitter.NewLocal(SystemDelegateType);
ILLocalVariable returnValueLocal = 0;
if (!Signature.ReturnType.IsVoid)
{
returnValueLocal = emitter.NewLocal(Signature.ReturnType);
}
// Fill in delegateArrayLocal
// Delegate[] delegateArrayLocal = (Delegate[])this.m_helperObject
// ldarg.0 (this pointer)
// ldfld Delegate.HelperObjectField
// castclass Delegate[]
// stloc delegateArrayLocal
codeStream.EmitLdArg(0);
codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(HelperObjectField));
codeStream.Emit(ILOpcode.castclass, emitter.NewToken(invocationListArrayType));
codeStream.EmitStLoc(delegateArrayLocal);
// Fill in invocationCountLocal
// int invocationCountLocal = this.m_extraFunctionPointerOrData
// ldarg.0 (this pointer)
// ldfld Delegate.m_extraFunctionPointerOrData
// stloc invocationCountLocal
codeStream.EmitLdArg(0);
codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(ExtraFunctionPointerOrDataField));
codeStream.EmitStLoc(invocationCountLocal);
// Fill in iteratorLocal
// int iteratorLocal = 0;
// ldc.0
// stloc iteratorLocal
codeStream.EmitLdc(0);
codeStream.EmitStLoc(iteratorLocal);
// Loop across every element of the array.
ILCodeLabel startOfLoopLabel = emitter.NewCodeLabel();
codeStream.EmitLabel(startOfLoopLabel);
// Implement as do/while loop. We only have this stub in play if we're in the multicast situation
// Find the delegate to call
// Delegate = delegateToCallLocal = delegateArrayLocal[iteratorLocal];
// ldloc delegateArrayLocal
// ldloc iteratorLocal
// ldelem System.Delegate
// stloc delegateToCallLocal
codeStream.EmitLdLoc(delegateArrayLocal);
codeStream.EmitLdLoc(iteratorLocal);
codeStream.Emit(ILOpcode.ldelem, emitter.NewToken(SystemDelegateType));
codeStream.EmitStLoc(delegateToCallLocal);
// Call the delegate
// returnValueLocal = delegateToCallLocal(...);
// ldloc delegateToCallLocal
// ldfld System.Delegate.m_firstParameter
// ldarg 1, n
// ldloc delegateToCallLocal
// ldfld System.Delegate.m_functionPointer
// calli returnValueType thiscall (all the params)
// IF there is a return value
// stloc returnValueLocal
codeStream.EmitLdLoc(delegateToCallLocal);
codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(FirstParameterField));
for (int i = 0; i < Signature.Length; i++)
{
codeStream.EmitLdArg(i + 1);
}
codeStream.EmitLdLoc(delegateToCallLocal);
codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(FunctionPointerField));
codeStream.Emit(ILOpcode.calli, emitter.NewToken(Signature));
if (returnValueLocal != 0)
codeStream.EmitStLoc(returnValueLocal);
// Increment iteratorLocal
// ++iteratorLocal;
// ldloc iteratorLocal
// ldc.i4.1
// add
// stloc iteratorLocal
codeStream.EmitLdLoc(iteratorLocal);
codeStream.EmitLdc(1);
codeStream.Emit(ILOpcode.add);
codeStream.EmitStLoc(iteratorLocal);
// Check to see if the loop is done
codeStream.EmitLdLoc(invocationCountLocal);
codeStream.EmitLdLoc(iteratorLocal);
codeStream.Emit(ILOpcode.bne_un, startOfLoopLabel);
// Return to caller. If the delegate has a return value, be certain to return that.
// return returnValueLocal;
// ldloc returnValueLocal
// ret
if (returnValueLocal != 0)
codeStream.EmitLdLoc(returnValueLocal);
codeStream.Emit(ILOpcode.ret);
return emitter.Link(this);
}
public override string Name
{
get
{
return "InvokeMulticastThunk";
}
}
}
/// <summary>
/// Delegate thunk that supports Delegate.DynamicInvoke. This thunk has heavy dependencies on the
/// general dynamic invocation infrastructure in System.InvokeUtils and gets called from there
/// at runtime. See comments in System.InvokeUtils for a more thorough explanation.
/// </summary>
public sealed class DelegateDynamicInvokeThunk : ILStubMethod
{
private DelegateInfo _delegateInfo;
private MethodSignature _signature;
public DelegateDynamicInvokeThunk(DelegateInfo delegateInfo)
{
_delegateInfo = delegateInfo;
}
public override TypeSystemContext Context
{
get
{
return _delegateInfo.Type.Context;
}
}
public override TypeDesc OwningType
{
get
{
return _delegateInfo.Type;
}
}
public override MethodSignature Signature
{
get
{
if (_signature == null)
{
_signature = new MethodSignature(0, 0,
Context.GetWellKnownType(WellKnownType.Object),
new TypeDesc[] {
Context.GetWellKnownType(WellKnownType.Object),
Context.GetWellKnownType(WellKnownType.IntPtr),
ArgSetupStateType.MakeByRefType() });
}
return _signature;
}
}
public override Instantiation Instantiation
{
get
{
return Instantiation.Empty;
}
}
public override string Name
{
get
{
return "DynamicInvokeImpl";
}
}
private MetadataType InvokeUtilsType
{
get
{
return Context.SystemModule.GetKnownType("System", "InvokeUtils");
}
}
private MetadataType ArgSetupStateType
{
get
{
return InvokeUtilsType.GetNestedType("ArgSetupState");
}
}
public override MethodIL EmitIL()
{
ILEmitter emitter = new ILEmitter();
ILCodeStream argSetupStream = emitter.NewCodeStream();
ILCodeStream callSiteSetupStream = emitter.NewCodeStream();
// This function will look like
//
// !For each parameter to the delegate
// !if (parameter is In Parameter)
// localX is TypeOfParameterX&
// ldtoken TypeOfParameterX
// call DynamicInvokeParamHelperIn(RuntimeTypeHandle)
// stloc localX
// !else
// localX is TypeOfParameter
// ldtoken TypeOfParameterX
// call DynamicInvokeParamHelperRef(RuntimeTypeHandle)
// stloc localX
// ldarg.3
// call DynamicInvokeArgSetupComplete(ref ArgSetupState)
// *** Second instruction stream starts here ***
// ldarg.1 // Load this pointer
// !For each parameter
// !if (parameter is In Parameter)
// ldloc localX
// ldobj TypeOfParameterX
// !else
// ldloc localX
// ldarg.1
// calli ReturnType thiscall(TypeOfParameter1, ...)
// !if ((ReturnType == void)
// ldnull
// !else if (ReturnType is a byref)
// ldobj StripByRef(ReturnType)
// box StripByRef(ReturnType)
// !else
// box ReturnType
// ret
callSiteSetupStream.EmitLdArg(1);
MethodSignature delegateSignature = _delegateInfo.Signature;
TypeDesc[] targetMethodParameters = new TypeDesc[delegateSignature.Length];
for (int paramIndex = 0; paramIndex < delegateSignature.Length; paramIndex++)
{
TypeDesc paramType = delegateSignature[paramIndex];
TypeDesc localType = paramType;
targetMethodParameters[paramIndex] = paramType;
if (localType.IsByRef)
{
// Strip ByRef
localType = ((ByRefType)localType).ParameterType;
}
else
{
// Only if this is not a ByRef, convert the parameter type to something boxable.
// Everything but pointer types are boxable.
localType = ConvertToBoxableType(localType);
}
ILLocalVariable local = emitter.NewLocal(localType.MakeByRefType());
callSiteSetupStream.EmitLdLoc(local);
argSetupStream.Emit(ILOpcode.ldtoken, emitter.NewToken(localType));
if (paramType.IsByRef)
{
argSetupStream.Emit(ILOpcode.call, emitter.NewToken(InvokeUtilsType.GetKnownMethod("DynamicInvokeParamHelperRef", null)));
}
else
{
argSetupStream.Emit(ILOpcode.call, emitter.NewToken(InvokeUtilsType.GetKnownMethod("DynamicInvokeParamHelperIn", null)));
callSiteSetupStream.Emit(ILOpcode.ldobj, emitter.NewToken(paramType));
}
argSetupStream.EmitStLoc(local);
}
argSetupStream.EmitLdArg(3);
argSetupStream.Emit(ILOpcode.call, emitter.NewToken(InvokeUtilsType.GetKnownMethod("DynamicInvokeArgSetupComplete", null)));
callSiteSetupStream.EmitLdArg(2);
MethodSignature targetMethodSig = new MethodSignature(0, 0, delegateSignature.ReturnType, targetMethodParameters);
callSiteSetupStream.Emit(ILOpcode.calli, emitter.NewToken(targetMethodSig));
if (delegateSignature.ReturnType.IsVoid)
{
callSiteSetupStream.Emit(ILOpcode.ldnull);
}
else if (delegateSignature.ReturnType.IsByRef)
{
TypeDesc targetType = ((ByRefType)delegateSignature.ReturnType).ParameterType;
callSiteSetupStream.Emit(ILOpcode.ldobj, emitter.NewToken(targetType));
callSiteSetupStream.Emit(ILOpcode.box, emitter.NewToken(targetType));
}
else
{
callSiteSetupStream.Emit(ILOpcode.box, emitter.NewToken(delegateSignature.ReturnType));
}
callSiteSetupStream.Emit(ILOpcode.ret);
return emitter.Link(this);
}
private TypeDesc ConvertToBoxableType(TypeDesc type)
{
if (type.IsPointer)
{
return type.Context.GetWellKnownType(WellKnownType.IntPtr);
}
return type;
}
}
/// <summary>
/// Synthetic method override of "IntPtr Delegate.GetThunk(Int32)". This method is injected
/// into all delegate types and provides means for System.Delegate to access the various thunks
/// generated by the compiler.
/// </summary>
public sealed class DelegateGetThunkMethodOverride : ILStubMethod
{
private DelegateInfo _delegateInfo;
private MethodSignature _signature;
internal DelegateGetThunkMethodOverride(DelegateInfo delegateInfo)
{
_delegateInfo = delegateInfo;
}
public override TypeSystemContext Context
{
get
{
return _delegateInfo.Type.Context;
}
}
public override TypeDesc OwningType
{
get
{
return _delegateInfo.Type;
}
}
public override MethodSignature Signature
{
get
{
if (_signature == null)
{
TypeSystemContext context = _delegateInfo.Type.Context;
TypeDesc intPtrType = context.GetWellKnownType(WellKnownType.IntPtr);
TypeDesc int32Type = context.GetWellKnownType(WellKnownType.Int32);
_signature = new MethodSignature(0, 0, intPtrType, new[] { int32Type });
}
return _signature;
}
}
public override MethodIL EmitIL()
{
const DelegateThunkKind maxThunkKind = DelegateThunkKind.ObjectArrayThunk + 1;
ILEmitter emitter = new ILEmitter();
var codeStream = emitter.NewCodeStream();
ILCodeLabel returnNullLabel = emitter.NewCodeLabel();
ILCodeLabel[] labels = new ILCodeLabel[(int)maxThunkKind];
for (DelegateThunkKind i = 0; i < maxThunkKind; i++)
{
MethodDesc thunk = _delegateInfo.Thunks[i];
if (thunk != null)
labels[(int)i] = emitter.NewCodeLabel();
else
labels[(int)i] = returnNullLabel;
}
codeStream.EmitLdArg(1);
codeStream.EmitSwitch(labels);
codeStream.Emit(ILOpcode.br, returnNullLabel);
for (DelegateThunkKind i = 0; i < maxThunkKind; i++)
{
MethodDesc thunk = _delegateInfo.Thunks[i];
if (thunk != null)
{
codeStream.EmitLabel(labels[(int)i]);
codeStream.Emit(ILOpcode.ldftn, emitter.NewToken(thunk.InstantiateAsOpen()));
codeStream.Emit(ILOpcode.ret);
}
}
codeStream.EmitLabel(returnNullLabel);
codeStream.EmitLdc(0);
codeStream.Emit(ILOpcode.conv_i);
codeStream.Emit(ILOpcode.ret);
return emitter.Link(this);
}
public override Instantiation Instantiation
{
get
{
return Instantiation.Empty;
}
}
public override bool IsVirtual
{
get
{
return true;
}
}
public override string Name
{
get
{
return "GetThunk";
}
}
}
}
| |
#region License
/*
* HttpServer.cs
*
* A simple HTTP server that allows to accept the WebSocket connection requests.
*
* The MIT License
*
* Copyright (c) 2012-2015 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Contributors
/*
* Contributors:
* - Juan Manuel Lallana <juan.manuel.lallana@gmail.com>
* - Liryna <liryna.stark@gmail.com>
* - Rohan Singh <rohan-singh@hotmail.com>
*/
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Threading;
using WebSocketSharp.Net;
using WebSocketSharp.Net.WebSockets;
namespace WebSocketSharp.Server
{
/// <summary>
/// Provides a simple HTTP server that allows to accept the WebSocket connection requests.
/// </summary>
/// <remarks>
/// The HttpServer class can provide multiple WebSocket services.
/// </remarks>
public class HttpServer
{
#region Private Fields
private System.Net.IPAddress _address;
private string _hostname;
private HttpListener _listener;
private Logger _logger;
private int _port;
private Thread _receiveThread;
private string _rootPath;
private bool _secure;
private WebSocketServiceManager _services;
private volatile ServerState _state;
private object _sync;
private bool _windows;
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class.
/// </summary>
/// <remarks>
/// An instance initialized by this constructor listens for the incoming requests on port 80.
/// </remarks>
public HttpServer ()
{
init ("*", System.Net.IPAddress.Any, 80, false);
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class with
/// the specified <paramref name="port"/>.
/// </summary>
/// <remarks>
/// <para>
/// An instance initialized by this constructor listens for the incoming requests on
/// <paramref name="port"/>.
/// </para>
/// <para>
/// If <paramref name="port"/> is 443, that instance provides a secure connection.
/// </para>
/// </remarks>
/// <param name="port">
/// An <see cref="int"/> that represents the port number on which to listen.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> isn't between 1 and 65535 inclusive.
/// </exception>
public HttpServer (int port)
: this (port, port == 443)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class with
/// the specified HTTP URL.
/// </summary>
/// <remarks>
/// <para>
/// An instance initialized by this constructor listens for the incoming requests on
/// the host name and port in <paramref name="url"/>.
/// </para>
/// <para>
/// If <paramref name="url"/> doesn't include a port, either port 80 or 443 is used on
/// which to listen. It's determined by the scheme (http or https) in <paramref name="url"/>.
/// (Port 80 if the scheme is http.)
/// </para>
/// </remarks>
/// <param name="url">
/// A <see cref="string"/> that represents the HTTP URL of the server.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="url"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="url"/> is empty.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="url"/> is invalid.
/// </para>
/// </exception>
public HttpServer (string url)
{
if (url == null)
throw new ArgumentNullException ("url");
if (url.Length == 0)
throw new ArgumentException ("An empty string.", "url");
Uri uri;
string msg;
if (!tryCreateUri (url, out uri, out msg))
throw new ArgumentException (msg, "url");
var host = uri.DnsSafeHost;
var addr = host.ToIPAddress ();
if (!addr.IsLocal ())
throw new ArgumentException ("The host part isn't a local host name: " + url, "url");
init (host, addr, uri.Port, uri.Scheme == "https");
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class with
/// the specified <paramref name="port"/> and <paramref name="secure"/>.
/// </summary>
/// <remarks>
/// An instance initialized by this constructor listens for the incoming requests on
/// <paramref name="port"/>.
/// </remarks>
/// <param name="port">
/// An <see cref="int"/> that represents the port number on which to listen.
/// </param>
/// <param name="secure">
/// A <see cref="bool"/> that indicates providing a secure connection or not.
/// (<c>true</c> indicates providing a secure connection.)
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> isn't between 1 and 65535 inclusive.
/// </exception>
public HttpServer (int port, bool secure)
{
if (!port.IsPortNumber ())
throw new ArgumentOutOfRangeException (
"port", "Not between 1 and 65535 inclusive: " + port);
init ("*", System.Net.IPAddress.Any, port, secure);
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class with
/// the specified <paramref name="address"/> and <paramref name="port"/>.
/// </summary>
/// <remarks>
/// <para>
/// An instance initialized by this constructor listens for the incoming requests on
/// <paramref name="address"/> and <paramref name="port"/>.
/// </para>
/// <para>
/// If <paramref name="port"/> is 443, that instance provides a secure connection.
/// </para>
/// </remarks>
/// <param name="address">
/// A <see cref="System.Net.IPAddress"/> that represents the local IP address of the server.
/// </param>
/// <param name="port">
/// An <see cref="int"/> that represents the port number on which to listen.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="address"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="address"/> isn't a local IP address.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> isn't between 1 and 65535 inclusive.
/// </exception>
public HttpServer (System.Net.IPAddress address, int port)
: this (address, port, port == 443)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class with
/// the specified <paramref name="address"/>, <paramref name="port"/>,
/// and <paramref name="secure"/>.
/// </summary>
/// <remarks>
/// An instance initialized by this constructor listens for the incoming requests on
/// <paramref name="address"/> and <paramref name="port"/>.
/// </remarks>
/// <param name="address">
/// A <see cref="System.Net.IPAddress"/> that represents the local IP address of the server.
/// </param>
/// <param name="port">
/// An <see cref="int"/> that represents the port number on which to listen.
/// </param>
/// <param name="secure">
/// A <see cref="bool"/> that indicates providing a secure connection or not.
/// (<c>true</c> indicates providing a secure connection.)
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="address"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="address"/> isn't a local IP address.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> isn't between 1 and 65535 inclusive.
/// </exception>
public HttpServer (System.Net.IPAddress address, int port, bool secure)
{
if (address == null)
throw new ArgumentNullException ("address");
if (!address.IsLocal ())
throw new ArgumentException ("Not a local IP address: " + address, "address");
if (!port.IsPortNumber ())
throw new ArgumentOutOfRangeException (
"port", "Not between 1 and 65535 inclusive: " + port);
init (null, address, port, secure);
}
#endregion
#region Public Properties
/// <summary>
/// Gets the local IP address of the server.
/// </summary>
/// <value>
/// A <see cref="System.Net.IPAddress"/> that represents the local IP address of the server.
/// </value>
public System.Net.IPAddress Address {
get {
return _address;
}
}
/// <summary>
/// Gets or sets the scheme used to authenticate the clients.
/// </summary>
/// <value>
/// One of the <see cref="WebSocketSharp.Net.AuthenticationSchemes"/> enum values,
/// indicates the scheme used to authenticate the clients. The default value is
/// <see cref="WebSocketSharp.Net.AuthenticationSchemes.Anonymous"/>.
/// </value>
public AuthenticationSchemes AuthenticationSchemes {
get {
return _listener.AuthenticationSchemes;
}
set {
var msg = _state.CheckIfAvailable (true, false, false);
if (msg != null) {
_logger.Error (msg);
return;
}
_listener.AuthenticationSchemes = value;
}
}
/// <summary>
/// Gets a value indicating whether the server has started.
/// </summary>
/// <value>
/// <c>true</c> if the server has started; otherwise, <c>false</c>.
/// </value>
public bool IsListening {
get {
return _state == ServerState.Start;
}
}
/// <summary>
/// Gets a value indicating whether the server provides a secure connection.
/// </summary>
/// <value>
/// <c>true</c> if the server provides a secure connection; otherwise, <c>false</c>.
/// </value>
public bool IsSecure {
get {
return _secure;
}
}
/// <summary>
/// Gets or sets a value indicating whether the server cleans up
/// the inactive sessions in the WebSocket services periodically.
/// </summary>
/// <value>
/// <c>true</c> if the server cleans up the inactive sessions every 60 seconds;
/// otherwise, <c>false</c>. The default value is <c>true</c>.
/// </value>
public bool KeepClean {
get {
return _services.KeepClean;
}
set {
var msg = _state.CheckIfAvailable (true, false, false);
if (msg != null) {
_logger.Error (msg);
return;
}
_services.KeepClean = value;
}
}
/// <summary>
/// Gets the logging functions.
/// </summary>
/// <remarks>
/// The default logging level is <see cref="LogLevel.Error"/>. If you would like to change it,
/// you should set the <c>Log.Level</c> property to any of the <see cref="LogLevel"/> enum
/// values.
/// </remarks>
/// <value>
/// A <see cref="Logger"/> that provides the logging functions.
/// </value>
public Logger Log {
get {
return _logger;
}
}
/// <summary>
/// Gets the port on which to listen for incoming requests.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the port number on which to listen.
/// </value>
public int Port {
get {
return _port;
}
}
/// <summary>
/// Gets or sets the name of the realm associated with the server.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the name of the realm. The default value is
/// <c>"SECRET AREA"</c>.
/// </value>
public string Realm {
get {
return _listener.Realm;
}
set {
var msg = _state.CheckIfAvailable (true, false, false);
if (msg != null) {
_logger.Error (msg);
return;
}
_listener.Realm = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the server is allowed to be bound to
/// an address that is already in use.
/// </summary>
/// <remarks>
/// If you would like to resolve to wait for socket in <c>TIME_WAIT</c> state,
/// you should set this property to <c>true</c>.
/// </remarks>
/// <value>
/// <c>true</c> if the server is allowed to be bound to an address that is already in use;
/// otherwise, <c>false</c>. The default value is <c>false</c>.
/// </value>
public bool ReuseAddress {
get {
return _listener.ReuseAddress;
}
set {
var msg = _state.CheckIfAvailable (true, false, false);
if (msg != null) {
_logger.Error (msg);
return;
}
_listener.ReuseAddress = value;
}
}
/// <summary>
/// Gets or sets the document root path of the server.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the document root path of the server.
/// The default value is <c>"./Public"</c>.
/// </value>
public string RootPath {
get {
return _rootPath != null && _rootPath.Length > 0 ? _rootPath : (_rootPath = "./Public");
}
set {
var msg = _state.CheckIfAvailable (true, false, false);
if (msg != null) {
_logger.Error (msg);
return;
}
_rootPath = value;
}
}
/// <summary>
/// Gets or sets the SSL configuration used to authenticate the server and
/// optionally the client for secure connection.
/// </summary>
/// <value>
/// A <see cref="ServerSslConfiguration"/> that represents the configuration used to
/// authenticate the server and optionally the client for secure connection.
/// </value>
public ServerSslConfiguration SslConfiguration {
get {
return _listener.SslConfiguration;
}
set {
var msg = _state.CheckIfAvailable (true, false, false);
if (msg != null) {
_logger.Error (msg);
return;
}
_listener.SslConfiguration = value;
}
}
/// <summary>
/// Gets or sets the delegate called to find the credentials for an identity used to
/// authenticate a client.
/// </summary>
/// <value>
/// A <c>Func<<see cref="IIdentity"/>, <see cref="NetworkCredential"/>></c> delegate that
/// references the method(s) used to find the credentials. The default value is a function that
/// only returns <see langword="null"/>.
/// </value>
public Func<IIdentity, NetworkCredential> UserCredentialsFinder {
get {
return _listener.UserCredentialsFinder;
}
set {
var msg = _state.CheckIfAvailable (true, false, false);
if (msg != null) {
_logger.Error (msg);
return;
}
_listener.UserCredentialsFinder = value;
}
}
/// <summary>
/// Gets or sets the wait time for the response to the WebSocket Ping or Close.
/// </summary>
/// <value>
/// A <see cref="TimeSpan"/> that represents the wait time. The default value is
/// the same as 1 second.
/// </value>
public TimeSpan WaitTime {
get {
return _services.WaitTime;
}
set {
var msg = _state.CheckIfAvailable (true, false, false) ?? value.CheckIfValidWaitTime ();
if (msg != null) {
_logger.Error (msg);
return;
}
_services.WaitTime = value;
}
}
/// <summary>
/// Gets the access to the WebSocket services provided by the server.
/// </summary>
/// <value>
/// A <see cref="WebSocketServiceManager"/> that manages the WebSocket services.
/// </value>
public WebSocketServiceManager WebSocketServices {
get {
return _services;
}
}
#endregion
#region Public Events
/// <summary>
/// Occurs when the server receives an HTTP CONNECT request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnConnect;
/// <summary>
/// Occurs when the server receives an HTTP DELETE request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnDelete;
/// <summary>
/// Occurs when the server receives an HTTP GET request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnGet;
/// <summary>
/// Occurs when the server receives an HTTP HEAD request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnHead;
/// <summary>
/// Occurs when the server receives an HTTP OPTIONS request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnOptions;
/// <summary>
/// Occurs when the server receives an HTTP PATCH request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnPatch;
/// <summary>
/// Occurs when the server receives an HTTP POST request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnPost;
/// <summary>
/// Occurs when the server receives an HTTP PUT request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnPut;
/// <summary>
/// Occurs when the server receives an HTTP TRACE request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnTrace;
#endregion
#region Private Methods
private void abort ()
{
lock (_sync) {
if (!IsListening)
return;
_state = ServerState.ShuttingDown;
}
_services.Stop (new CloseEventArgs (CloseStatusCode.ServerError), true, false);
_listener.Abort ();
_state = ServerState.Stop;
}
private string checkIfCertificateExists ()
{
if (!_secure)
return null;
var usr = _listener.SslConfiguration.ServerCertificate != null;
var port = EndPointListener.CertificateExists (_port, _listener.CertificateFolderPath);
if (usr && port) {
_logger.Warn ("The server certificate associated with the port number already exists.");
return null;
}
return !(usr || port) ? "The secure connection requires a server certificate." : null;
}
private void init (string hostname, System.Net.IPAddress address, int port, bool secure)
{
_hostname = hostname ?? address.ToString ();
_address = address;
_port = port;
_secure = secure;
_listener = new HttpListener ();
_listener.Prefixes.Add (
String.Format ("http{0}://{1}:{2}/", secure ? "s" : "", _hostname, port));
_logger = _listener.Log;
_services = new WebSocketServiceManager (_logger);
_sync = new object ();
var os = Environment.OSVersion;
_windows = os.Platform != PlatformID.Unix && os.Platform != PlatformID.MacOSX;
}
private void processRequest (HttpListenerContext context)
{
var method = context.Request.HttpMethod;
var evt = method == "GET"
? OnGet
: method == "HEAD"
? OnHead
: method == "POST"
? OnPost
: method == "PUT"
? OnPut
: method == "DELETE"
? OnDelete
: method == "OPTIONS"
? OnOptions
: method == "TRACE"
? OnTrace
: method == "CONNECT"
? OnConnect
: method == "PATCH"
? OnPatch
: null;
if (evt != null)
evt (this, new HttpRequestEventArgs (context));
else
context.Response.StatusCode = (int) HttpStatusCode.NotImplemented;
context.Response.Close ();
}
private void processRequest (HttpListenerWebSocketContext context)
{
WebSocketServiceHost host;
if (!_services.InternalTryGetServiceHost (context.RequestUri.AbsolutePath, out host)) {
context.Close (HttpStatusCode.NotImplemented);
return;
}
host.StartSession (context);
}
private void receiveRequest ()
{
while (true) {
try {
var ctx = _listener.GetContext ();
ThreadPool.QueueUserWorkItem (
state => {
try {
if (ctx.Request.IsUpgradeTo ("websocket")) {
processRequest (ctx.AcceptWebSocket (null));
return;
}
processRequest (ctx);
}
catch (Exception ex) {
_logger.Fatal (ex.ToString ());
ctx.Connection.Close (true);
}
});
}
catch (HttpListenerException ex) {
_logger.Warn ("Receiving has been stopped.\n reason: " + ex.Message);
break;
}
catch (Exception ex) {
_logger.Fatal (ex.ToString ());
break;
}
}
if (IsListening)
abort ();
}
private void startReceiving ()
{
_listener.Start ();
_receiveThread = new Thread (new ThreadStart (receiveRequest));
_receiveThread.IsBackground = true;
_receiveThread.Start ();
}
private void stopReceiving (int millisecondsTimeout)
{
_listener.Close ();
_receiveThread.Join (millisecondsTimeout);
}
private static bool tryCreateUri (string uriString, out Uri result, out string message)
{
result = null;
var uri = uriString.ToUri ();
if (uri == null) {
message = "An invalid URI string: " + uriString;
return false;
}
if (!uri.IsAbsoluteUri) {
message = "Not an absolute URI: " + uriString;
return false;
}
var schm = uri.Scheme;
if (!(schm == "http" || schm == "https")) {
message = "The scheme part isn't 'http' or 'https': " + uriString;
return false;
}
if (uri.PathAndQuery != "/") {
message = "Includes the path or query component: " + uriString;
return false;
}
if (uri.Fragment.Length > 0) {
message = "Includes the fragment component: " + uriString;
return false;
}
if (uri.Port == 0) {
message = "The port part is zero: " + uriString;
return false;
}
result = uri;
message = String.Empty;
return true;
}
#endregion
#region Public Methods
/// <summary>
/// Adds the WebSocket service with the specified behavior, <paramref name="path"/>,
/// and <paramref name="initializer"/>.
/// </summary>
/// <remarks>
/// <para>
/// This method converts <paramref name="path"/> to URL-decoded string,
/// and removes <c>'/'</c> from tail end of <paramref name="path"/>.
/// </para>
/// <para>
/// <paramref name="initializer"/> returns an initialized specified typed
/// <see cref="WebSocketBehavior"/> instance.
/// </para>
/// </remarks>
/// <param name="path">
/// A <see cref="string"/> that represents the absolute path to the service to add.
/// </param>
/// <param name="initializer">
/// A <c>Func<T></c> delegate that references the method used to initialize
/// a new specified typed <see cref="WebSocketBehavior"/> instance (a new
/// <see cref="IWebSocketSession"/> instance).
/// </param>
/// <typeparam name="TBehavior">
/// The type of the behavior of the service to add. The TBehavior must inherit
/// the <see cref="WebSocketBehavior"/> class.
/// </typeparam>
public void AddWebSocketService<TBehavior> (string path, Func<TBehavior> initializer)
where TBehavior : WebSocketBehavior
{
var msg = path.CheckIfValidServicePath () ??
(initializer == null ? "'initializer' is null." : null);
if (msg != null) {
_logger.Error (msg);
return;
}
_services.Add<TBehavior> (path, initializer);
}
/// <summary>
/// Adds a WebSocket service with the specified behavior and <paramref name="path"/>.
/// </summary>
/// <remarks>
/// This method converts <paramref name="path"/> to URL-decoded string,
/// and removes <c>'/'</c> from tail end of <paramref name="path"/>.
/// </remarks>
/// <param name="path">
/// A <see cref="string"/> that represents the absolute path to the service to add.
/// </param>
/// <typeparam name="TBehaviorWithNew">
/// The type of the behavior of the service to add. The TBehaviorWithNew must inherit
/// the <see cref="WebSocketBehavior"/> class, and must have a public parameterless
/// constructor.
/// </typeparam>
public void AddWebSocketService<TBehaviorWithNew> (string path)
where TBehaviorWithNew : WebSocketBehavior, new ()
{
AddWebSocketService<TBehaviorWithNew> (path, () => new TBehaviorWithNew ());
}
/// <summary>
/// Gets the contents of the file with the specified <paramref name="path"/>.
/// </summary>
/// <returns>
/// An array of <see cref="byte"/> that receives the contents of the file,
/// or <see langword="null"/> if it doesn't exist.
/// </returns>
/// <param name="path">
/// A <see cref="string"/> that represents the virtual path to the file to find.
/// </param>
public byte[] GetFile (string path)
{
path = RootPath + path;
if (_windows)
path = path.Replace ("/", "\\");
return File.Exists (path) ? File.ReadAllBytes (path) : null;
}
/// <summary>
/// Removes the WebSocket service with the specified <paramref name="path"/>.
/// </summary>
/// <remarks>
/// This method converts <paramref name="path"/> to URL-decoded string,
/// and removes <c>'/'</c> from tail end of <paramref name="path"/>.
/// </remarks>
/// <returns>
/// <c>true</c> if the service is successfully found and removed; otherwise, <c>false</c>.
/// </returns>
/// <param name="path">
/// A <see cref="string"/> that represents the absolute path to the service to find.
/// </param>
public bool RemoveWebSocketService (string path)
{
var msg = path.CheckIfValidServicePath ();
if (msg != null) {
_logger.Error (msg);
return false;
}
return _services.Remove (path);
}
/// <summary>
/// Starts receiving the HTTP requests.
/// </summary>
public void Start ()
{
lock (_sync) {
var msg = _state.CheckIfAvailable (true, false, false) ?? checkIfCertificateExists ();
if (msg != null) {
_logger.Error (msg);
return;
}
_services.Start ();
startReceiving ();
_state = ServerState.Start;
}
}
/// <summary>
/// Stops receiving the HTTP requests.
/// </summary>
public void Stop ()
{
lock (_sync) {
var msg = _state.CheckIfAvailable (false, true, false);
if (msg != null) {
_logger.Error (msg);
return;
}
_state = ServerState.ShuttingDown;
}
_services.Stop (new CloseEventArgs (), true, true);
stopReceiving (5000);
_state = ServerState.Stop;
}
/// <summary>
/// Stops receiving the HTTP requests with the specified <see cref="ushort"/> and
/// <see cref="string"/> used to stop the WebSocket services.
/// </summary>
/// <param name="code">
/// A <see cref="ushort"/> that represents the status code indicating the reason for the stop.
/// </param>
/// <param name="reason">
/// A <see cref="string"/> that represents the reason for the stop.
/// </param>
public void Stop (ushort code, string reason)
{
lock (_sync) {
var msg = _state.CheckIfAvailable (false, true, false) ??
WebSocket.CheckCloseParameters (code, reason, false);
if (msg != null) {
_logger.Error (msg);
return;
}
_state = ServerState.ShuttingDown;
}
if (code == (ushort) CloseStatusCode.NoStatus) {
_services.Stop (new CloseEventArgs (), true, true);
}
else {
var send = !code.IsReserved ();
_services.Stop (new CloseEventArgs (code, reason), send, send);
}
stopReceiving (5000);
_state = ServerState.Stop;
}
/// <summary>
/// Stops receiving the HTTP requests with the specified <see cref="CloseStatusCode"/> and
/// <see cref="string"/> used to stop the WebSocket services.
/// </summary>
/// <param name="code">
/// One of the <see cref="CloseStatusCode"/> enum values, represents the status code indicating
/// the reason for the stop.
/// </param>
/// <param name="reason">
/// A <see cref="string"/> that represents the reason for the stop.
/// </param>
public void Stop (CloseStatusCode code, string reason)
{
lock (_sync) {
var msg = _state.CheckIfAvailable (false, true, false) ??
WebSocket.CheckCloseParameters (code, reason, false);
if (msg != null) {
_logger.Error (msg);
return;
}
_state = ServerState.ShuttingDown;
}
if (code == CloseStatusCode.NoStatus) {
_services.Stop (new CloseEventArgs (), true, true);
}
else {
var send = !code.IsReserved ();
_services.Stop (new CloseEventArgs (code, reason), send, send);
}
stopReceiving (5000);
_state = ServerState.Stop;
}
#endregion
}
}
| |
//#define B2_DEBUG_SOLVER
/*
* Velcro Physics:
* Copyright (c) 2017 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using VelcroPhysics.Collision.ContactSystem;
using VelcroPhysics.Collision.Narrowphase;
using VelcroPhysics.Collision.Shapes;
using VelcroPhysics.Shared;
using VelcroPhysics.Shared.Optimization;
using VelcroPhysics.Utilities;
namespace VelcroPhysics.Dynamics.Solver
{
public class ContactSolver
{
private Contact[] _contacts;
private int _count;
private ContactPositionConstraint[] _positionConstraints;
private Position[] _positions;
private TimeStep _step;
private Velocity[] _velocities;
public ContactVelocityConstraint[] VelocityConstraints;
public void Reset(TimeStep step, int count, Contact[] contacts, Position[] positions, Velocity[] velocities)
{
_step = step;
_count = count;
_positions = positions;
_velocities = velocities;
_contacts = contacts;
// grow the array
if (VelocityConstraints == null || VelocityConstraints.Length < count)
{
VelocityConstraints = new ContactVelocityConstraint[count * 2];
_positionConstraints = new ContactPositionConstraint[count * 2];
for (int i = 0; i < VelocityConstraints.Length; i++)
{
VelocityConstraints[i] = new ContactVelocityConstraint();
}
for (int i = 0; i < _positionConstraints.Length; i++)
{
_positionConstraints[i] = new ContactPositionConstraint();
}
}
// Initialize position independent portions of the constraints.
for (int i = 0; i < _count; ++i)
{
Contact contact = contacts[i];
Fixture fixtureA = contact.FixtureA;
Fixture fixtureB = contact.FixtureB;
Shape shapeA = fixtureA.Shape;
Shape shapeB = fixtureB.Shape;
float radiusA = shapeA.Radius;
float radiusB = shapeB.Radius;
Body bodyA = fixtureA.Body;
Body bodyB = fixtureB.Body;
Manifold manifold = contact.Manifold;
int pointCount = manifold.PointCount;
Debug.Assert(pointCount > 0);
ContactVelocityConstraint vc = VelocityConstraints[i];
vc.Friction = contact.Friction;
vc.Restitution = contact.Restitution;
vc.TangentSpeed = contact.TangentSpeed;
vc.IndexA = bodyA.IslandIndex;
vc.IndexB = bodyB.IslandIndex;
vc.InvMassA = bodyA._invMass;
vc.InvMassB = bodyB._invMass;
vc.InvIA = bodyA._invI;
vc.InvIB = bodyB._invI;
vc.ContactIndex = i;
vc.PointCount = pointCount;
vc.K.SetZero();
vc.NormalMass.SetZero();
ContactPositionConstraint pc = _positionConstraints[i];
pc.IndexA = bodyA.IslandIndex;
pc.IndexB = bodyB.IslandIndex;
pc.InvMassA = bodyA._invMass;
pc.InvMassB = bodyB._invMass;
pc.LocalCenterA = bodyA._sweep.LocalCenter;
pc.LocalCenterB = bodyB._sweep.LocalCenter;
pc.InvIA = bodyA._invI;
pc.InvIB = bodyB._invI;
pc.LocalNormal = manifold.LocalNormal;
pc.LocalPoint = manifold.LocalPoint;
pc.PointCount = pointCount;
pc.RadiusA = radiusA;
pc.RadiusB = radiusB;
pc.Type = manifold.Type;
for (int j = 0; j < pointCount; ++j)
{
ManifoldPoint cp = manifold.Points[j];
VelocityConstraintPoint vcp = vc.Points[j];
if (Settings.EnableWarmstarting)
{
vcp.NormalImpulse = _step.dtRatio * cp.NormalImpulse;
vcp.TangentImpulse = _step.dtRatio * cp.TangentImpulse;
}
else
{
vcp.NormalImpulse = 0.0f;
vcp.TangentImpulse = 0.0f;
}
vcp.rA = Vector2.Zero;
vcp.rB = Vector2.Zero;
vcp.NormalMass = 0.0f;
vcp.TangentMass = 0.0f;
vcp.VelocityBias = 0.0f;
pc.LocalPoints[j] = cp.LocalPoint;
}
}
}
/// <summary>
/// Initialize position dependent portions of the velocity constraints.
/// </summary>
public void InitializeVelocityConstraints()
{
for (int i = 0; i < _count; ++i)
{
ContactVelocityConstraint vc = VelocityConstraints[i];
ContactPositionConstraint pc = _positionConstraints[i];
float radiusA = pc.RadiusA;
float radiusB = pc.RadiusB;
Manifold manifold = _contacts[vc.ContactIndex].Manifold;
int indexA = vc.IndexA;
int indexB = vc.IndexB;
float mA = vc.InvMassA;
float mB = vc.InvMassB;
float iA = vc.InvIA;
float iB = vc.InvIB;
Vector2 localCenterA = pc.LocalCenterA;
Vector2 localCenterB = pc.LocalCenterB;
Vector2 cA = _positions[indexA].C;
float aA = _positions[indexA].A;
Vector2 vA = _velocities[indexA].V;
float wA = _velocities[indexA].W;
Vector2 cB = _positions[indexB].C;
float aB = _positions[indexB].A;
Vector2 vB = _velocities[indexB].V;
float wB = _velocities[indexB].W;
Debug.Assert(manifold.PointCount > 0);
Transform xfA = new Transform();
Transform xfB = new Transform();
xfA.q.Set(aA);
xfB.q.Set(aB);
xfA.p = cA - MathUtils.Mul(xfA.q, localCenterA);
xfB.p = cB - MathUtils.Mul(xfB.q, localCenterB);
WorldManifold.Initialize(ref manifold, ref xfA, radiusA, ref xfB, radiusB, out Vector2 normal, out FixedArray2<Vector2> points, out _);
vc.Normal = normal;
int pointCount = vc.PointCount;
for (int j = 0; j < pointCount; ++j)
{
VelocityConstraintPoint vcp = vc.Points[j];
vcp.rA = points[j] - cA;
vcp.rB = points[j] - cB;
float rnA = MathUtils.Cross(vcp.rA, vc.Normal);
float rnB = MathUtils.Cross(vcp.rB, vc.Normal);
float kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
vcp.NormalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f;
Vector2 tangent = MathUtils.Cross(vc.Normal, 1.0f);
float rtA = MathUtils.Cross(vcp.rA, tangent);
float rtB = MathUtils.Cross(vcp.rB, tangent);
float kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB;
vcp.TangentMass = kTangent > 0.0f ? 1.0f / kTangent : 0.0f;
// Setup a velocity bias for restitution.
vcp.VelocityBias = 0.0f;
float vRel = Vector2.Dot(vc.Normal, vB + MathUtils.Cross(wB, vcp.rB) - vA - MathUtils.Cross(wA, vcp.rA));
if (vRel < -Settings.VelocityThreshold)
{
vcp.VelocityBias = -vc.Restitution * vRel;
}
}
// If we have two points, then prepare the block solver.
if (vc.PointCount == 2 && Settings.BlockSolve)
{
VelocityConstraintPoint vcp1 = vc.Points[0];
VelocityConstraintPoint vcp2 = vc.Points[1];
float rn1A = MathUtils.Cross(vcp1.rA, vc.Normal);
float rn1B = MathUtils.Cross(vcp1.rB, vc.Normal);
float rn2A = MathUtils.Cross(vcp2.rA, vc.Normal);
float rn2B = MathUtils.Cross(vcp2.rB, vc.Normal);
float k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B;
float k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B;
float k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B;
// Ensure a reasonable condition number.
const float k_maxConditionNumber = 1000.0f;
if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12))
{
// K is safe to invert.
vc.K.ex = new Vector2(k11, k12);
vc.K.ey = new Vector2(k12, k22);
vc.NormalMass = vc.K.Inverse;
}
else
{
// The constraints are redundant, just use one.
// TODO_ERIN use deepest?
vc.PointCount = 1;
}
}
}
}
public void WarmStart()
{
// Warm start.
for (int i = 0; i < _count; ++i)
{
ContactVelocityConstraint vc = VelocityConstraints[i];
int indexA = vc.IndexA;
int indexB = vc.IndexB;
float mA = vc.InvMassA;
float iA = vc.InvIA;
float mB = vc.InvMassB;
float iB = vc.InvIB;
int pointCount = vc.PointCount;
Vector2 vA = _velocities[indexA].V;
float wA = _velocities[indexA].W;
Vector2 vB = _velocities[indexB].V;
float wB = _velocities[indexB].W;
Vector2 normal = vc.Normal;
Vector2 tangent = MathUtils.Cross(normal, 1.0f);
for (int j = 0; j < pointCount; ++j)
{
VelocityConstraintPoint vcp = vc.Points[j];
Vector2 P = vcp.NormalImpulse * normal + vcp.TangentImpulse * tangent;
wA -= iA * MathUtils.Cross(vcp.rA, P);
vA -= mA * P;
wB += iB * MathUtils.Cross(vcp.rB, P);
vB += mB * P;
}
_velocities[indexA].V = vA;
_velocities[indexA].W = wA;
_velocities[indexB].V = vB;
_velocities[indexB].W = wB;
}
}
public void SolveVelocityConstraints()
{
for (int i = 0; i < _count; ++i)
{
ContactVelocityConstraint vc = VelocityConstraints[i];
int indexA = vc.IndexA;
int indexB = vc.IndexB;
float mA = vc.InvMassA;
float iA = vc.InvIA;
float mB = vc.InvMassB;
float iB = vc.InvIB;
int pointCount = vc.PointCount;
Vector2 vA = _velocities[indexA].V;
float wA = _velocities[indexA].W;
Vector2 vB = _velocities[indexB].V;
float wB = _velocities[indexB].W;
Vector2 normal = vc.Normal;
Vector2 tangent = MathUtils.Cross(normal, 1.0f);
float friction = vc.Friction;
Debug.Assert(pointCount == 1 || pointCount == 2);
// Solve tangent constraints first because non-penetration is more important
// than friction.
for (int j = 0; j < pointCount; ++j)
{
VelocityConstraintPoint vcp = vc.Points[j];
// Relative velocity at contact
Vector2 dv = vB + MathUtils.Cross(wB, vcp.rB) - vA - MathUtils.Cross(wA, vcp.rA);
// Compute tangent force
float vt = Vector2.Dot(dv, tangent) - vc.TangentSpeed;
float lambda = vcp.TangentMass * (-vt);
// b2Clamp the accumulated force
float maxFriction = friction * vcp.NormalImpulse;
float newImpulse = MathUtils.Clamp(vcp.TangentImpulse + lambda, -maxFriction, maxFriction);
lambda = newImpulse - vcp.TangentImpulse;
vcp.TangentImpulse = newImpulse;
// Apply contact impulse
Vector2 P = lambda * tangent;
vA -= mA * P;
wA -= iA * MathUtils.Cross(vcp.rA, P);
vB += mB * P;
wB += iB * MathUtils.Cross(vcp.rB, P);
}
// Solve normal constraints
if (pointCount == 1 || Settings.BlockSolve == false)
{
for (int j = 0; j < pointCount; ++j)
{
VelocityConstraintPoint vcp = vc.Points[j];
// Relative velocity at contact
Vector2 dv = vB + MathUtils.Cross(wB, vcp.rB) - vA - MathUtils.Cross(wA, vcp.rA);
// Compute normal impulse
float vn = Vector2.Dot(dv, normal);
float lambda = -vcp.NormalMass * (vn - vcp.VelocityBias);
// b2Clamp the accumulated impulse
float newImpulse = Math.Max(vcp.NormalImpulse + lambda, 0.0f);
lambda = newImpulse - vcp.NormalImpulse;
vcp.NormalImpulse = newImpulse;
// Apply contact impulse
Vector2 P = lambda * normal;
vA -= mA * P;
wA -= iA * MathUtils.Cross(vcp.rA, P);
vB += mB * P;
wB += iB * MathUtils.Cross(vcp.rB, P);
}
}
else
{
// Block solver developed in collaboration with Dirk Gregorius (back in 01/07 on Box2D_Lite).
// Build the mini LCP for this contact patch
//
// vn = A * x + b, vn >= 0, x >= 0 and vn_i * x_i = 0 with i = 1..2
//
// A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n )
// b = vn0 - velocityBias
//
// The system is solved using the "Total enumeration method" (s. Murty). The complementary constraint vn_i * x_i
// implies that we must have in any solution either vn_i = 0 or x_i = 0. So for the 2D contact problem the cases
// vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0 and vn1 = 0 need to be tested. The first valid
// solution that satisfies the problem is chosen.
//
// In order to account of the accumulated impulse 'a' (because of the iterative nature of the solver which only requires
// that the accumulated impulse is clamped and not the incremental impulse) we change the impulse variable (x_i).
//
// Substitute:
//
// x = a + d
//
// a := old total impulse
// x := new total impulse
// d := incremental impulse
//
// For the current iteration we extend the formula for the incremental impulse
// to compute the new total impulse:
//
// vn = A * d + b
// = A * (x - a) + b
// = A * x + b - A * a
// = A * x + b'
// b' = b - A * a;
VelocityConstraintPoint cp1 = vc.Points[0];
VelocityConstraintPoint cp2 = vc.Points[1];
Vector2 a = new Vector2(cp1.NormalImpulse, cp2.NormalImpulse);
Debug.Assert(a.X >= 0.0f && a.Y >= 0.0f);
// Relative velocity at contact
Vector2 dv1 = vB + MathUtils.Cross(wB, cp1.rB) - vA - MathUtils.Cross(wA, cp1.rA);
Vector2 dv2 = vB + MathUtils.Cross(wB, cp2.rB) - vA - MathUtils.Cross(wA, cp2.rA);
// Compute normal velocity
float vn1 = Vector2.Dot(dv1, normal);
float vn2 = Vector2.Dot(dv2, normal);
Vector2 b = Vector2.Zero;
b.X = vn1 - cp1.VelocityBias;
b.Y = vn2 - cp2.VelocityBias;
const float k_errorTol = 1e-3f;
// Compute b'
b -= MathUtils.Mul(ref vc.K, a);
for (;;)
{
//
// Case 1: vn = 0
//
// 0 = A * x + b'
//
// Solve for x:
//
// x = - inv(A) * b'
//
Vector2 x = -MathUtils.Mul(ref vc.NormalMass, b);
if (x.X >= 0.0f && x.Y >= 0.0f)
{
// Get the incremental impulse
Vector2 d = x - a;
// Apply incremental impulse
Vector2 P1 = d.X * normal;
Vector2 P2 = d.Y * normal;
vA -= mA * (P1 + P2);
wA -= iA * (MathUtils.Cross(cp1.rA, P1) + MathUtils.Cross(cp2.rA, P2));
vB += mB * (P1 + P2);
wB += iB * (MathUtils.Cross(cp1.rB, P1) + MathUtils.Cross(cp2.rB, P2));
// Accumulate
cp1.NormalImpulse = x.X;
cp2.NormalImpulse = x.Y;
#if B2_DEBUG_SOLVER
// Postconditions
dv1 = vB + MathUtils.Cross(wB, cp1.rB) - vA - MathUtils.Cross(wA, cp1.rA);
dv2 = vB + MathUtils.Cross(wB, cp2.rB) - vA - MathUtils.Cross(wA, cp2.rA);
// Compute normal velocity
vn1 = Vector2.Dot(dv1, normal);
vn2 = Vector2.Dot(dv2, normal);
Debug.Assert(Math.Abs(vn1 - cp1.VelocityBias) < k_errorTol);
Debug.Assert(Math.Abs(vn2 - cp2.VelocityBias) < k_errorTol);
#endif
break;
}
//
// Case 2: vn1 = 0 and x2 = 0
//
// 0 = a11 * x1 + a12 * 0 + b1'
// vn2 = a21 * x1 + a22 * 0 + b2'
//
x.X = -cp1.NormalMass * b.X;
x.Y = 0.0f;
vn1 = 0.0f;
vn2 = vc.K.ex.Y * x.X + b.Y;
if (x.X >= 0.0f && vn2 >= 0.0f)
{
// Get the incremental impulse
Vector2 d = x - a;
// Apply incremental impulse
Vector2 P1 = d.X * normal;
Vector2 P2 = d.Y * normal;
vA -= mA * (P1 + P2);
wA -= iA * (MathUtils.Cross(cp1.rA, P1) + MathUtils.Cross(cp2.rA, P2));
vB += mB * (P1 + P2);
wB += iB * (MathUtils.Cross(cp1.rB, P1) + MathUtils.Cross(cp2.rB, P2));
// Accumulate
cp1.NormalImpulse = x.X;
cp2.NormalImpulse = x.Y;
#if B2_DEBUG_SOLVER
// Postconditions
dv1 = vB + MathUtils.Cross(wB, cp1.rB) - vA - MathUtils.Cross(wA, cp1.rA);
// Compute normal velocity
vn1 = Vector2.Dot(dv1, normal);
Debug.Assert(Math.Abs(vn1 - cp1.VelocityBias) < k_errorTol);
#endif
break;
}
//
// Case 3: vn2 = 0 and x1 = 0
//
// vn1 = a11 * 0 + a12 * x2 + b1'
// 0 = a21 * 0 + a22 * x2 + b2'
//
x.X = 0.0f;
x.Y = -cp2.NormalMass * b.Y;
vn1 = vc.K.ey.X * x.Y + b.X;
vn2 = 0.0f;
if (x.Y >= 0.0f && vn1 >= 0.0f)
{
// Resubstitute for the incremental impulse
Vector2 d = x - a;
// Apply incremental impulse
Vector2 P1 = d.X * normal;
Vector2 P2 = d.Y * normal;
vA -= mA * (P1 + P2);
wA -= iA * (MathUtils.Cross(cp1.rA, P1) + MathUtils.Cross(cp2.rA, P2));
vB += mB * (P1 + P2);
wB += iB * (MathUtils.Cross(cp1.rB, P1) + MathUtils.Cross(cp2.rB, P2));
// Accumulate
cp1.NormalImpulse = x.X;
cp2.NormalImpulse = x.Y;
#if B2_DEBUG_SOLVER
// Postconditions
dv2 = vB + MathUtils.Cross(wB, cp2.rB) - vA - MathUtils.Cross(wA, cp2.rA);
// Compute normal velocity
vn2 = Vector2.Dot(dv2, normal);
Debug.Assert(Math.Abs(vn2 - cp2.VelocityBias) < k_errorTol);
#endif
break;
}
//
// Case 4: x1 = 0 and x2 = 0
//
// vn1 = b1
// vn2 = b2;
x.X = 0.0f;
x.Y = 0.0f;
vn1 = b.X;
vn2 = b.Y;
if (vn1 >= 0.0f && vn2 >= 0.0f)
{
// Resubstitute for the incremental impulse
Vector2 d = x - a;
// Apply incremental impulse
Vector2 P1 = d.X * normal;
Vector2 P2 = d.Y * normal;
vA -= mA * (P1 + P2);
wA -= iA * (MathUtils.Cross(cp1.rA, P1) + MathUtils.Cross(cp2.rA, P2));
vB += mB * (P1 + P2);
wB += iB * (MathUtils.Cross(cp1.rB, P1) + MathUtils.Cross(cp2.rB, P2));
// Accumulate
cp1.NormalImpulse = x.X;
cp2.NormalImpulse = x.Y;
break;
}
// No solution, give up. This is hit sometimes, but it doesn't seem to matter.
break;
}
}
_velocities[indexA].V = vA;
_velocities[indexA].W = wA;
_velocities[indexB].V = vB;
_velocities[indexB].W = wB;
}
}
public void StoreImpulses()
{
for (int i = 0; i < _count; ++i)
{
ContactVelocityConstraint vc = VelocityConstraints[i];
Manifold manifold = _contacts[vc.ContactIndex].Manifold;
for (int j = 0; j < vc.PointCount; ++j)
{
ManifoldPoint point = manifold.Points[j];
point.NormalImpulse = vc.Points[j].NormalImpulse;
point.TangentImpulse = vc.Points[j].TangentImpulse;
manifold.Points[j] = point;
}
_contacts[vc.ContactIndex].Manifold = manifold;
}
}
public bool SolvePositionConstraints()
{
float minSeparation = 0.0f;
for (int i = 0; i < _count; ++i)
{
ContactPositionConstraint pc = _positionConstraints[i];
int indexA = pc.IndexA;
int indexB = pc.IndexB;
Vector2 localCenterA = pc.LocalCenterA;
float mA = pc.InvMassA;
float iA = pc.InvIA;
Vector2 localCenterB = pc.LocalCenterB;
float mB = pc.InvMassB;
float iB = pc.InvIB;
int pointCount = pc.PointCount;
Vector2 cA = _positions[indexA].C;
float aA = _positions[indexA].A;
Vector2 cB = _positions[indexB].C;
float aB = _positions[indexB].A;
// Solve normal constraints
for (int j = 0; j < pointCount; ++j)
{
Transform xfA = new Transform();
Transform xfB = new Transform();
xfA.q.Set(aA);
xfB.q.Set(aB);
xfA.p = cA - MathUtils.Mul(xfA.q, localCenterA);
xfB.p = cB - MathUtils.Mul(xfB.q, localCenterB);
PositionSolverManifold.Initialize(pc, xfA, xfB, j, out Vector2 normal, out Vector2 point, out float separation);
Vector2 rA = point - cA;
Vector2 rB = point - cB;
// Track max constraint error.
minSeparation = Math.Min(minSeparation, separation);
// Prevent large corrections and allow slop.
float C = MathUtils.Clamp(Settings.Baumgarte * (separation + Settings.LinearSlop), -Settings.MaxLinearCorrection, 0.0f);
// Compute the effective mass.
float rnA = MathUtils.Cross(rA, normal);
float rnB = MathUtils.Cross(rB, normal);
float K = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
// Compute normal impulse
float impulse = K > 0.0f ? -C / K : 0.0f;
Vector2 P = impulse * normal;
cA -= mA * P;
aA -= iA * MathUtils.Cross(rA, P);
cB += mB * P;
aB += iB * MathUtils.Cross(rB, P);
}
_positions[indexA].C = cA;
_positions[indexA].A = aA;
_positions[indexB].C = cB;
_positions[indexB].A = aB;
}
// We can't expect minSpeparation >= -b2_linearSlop because we don't
// push the separation above -b2_linearSlop.
return minSeparation >= -3.0f * Settings.LinearSlop;
}
// Sequential position solver for position constraints.
public bool SolveTOIPositionConstraints(int toiIndexA, int toiIndexB)
{
float minSeparation = 0.0f;
for (int i = 0; i < _count; ++i)
{
ContactPositionConstraint pc = _positionConstraints[i];
int indexA = pc.IndexA;
int indexB = pc.IndexB;
Vector2 localCenterA = pc.LocalCenterA;
Vector2 localCenterB = pc.LocalCenterB;
int pointCount = pc.PointCount;
float mA = 0.0f;
float iA = 0.0f;
if (indexA == toiIndexA || indexA == toiIndexB)
{
mA = pc.InvMassA;
iA = pc.InvIA;
}
float mB = 0.0f;
float iB = 0.0f;
if (indexB == toiIndexA || indexB == toiIndexB)
{
mB = pc.InvMassB;
iB = pc.InvIB;
}
Vector2 cA = _positions[indexA].C;
float aA = _positions[indexA].A;
Vector2 cB = _positions[indexB].C;
float aB = _positions[indexB].A;
// Solve normal constraints
for (int j = 0; j < pointCount; ++j)
{
Transform xfA = new Transform();
Transform xfB = new Transform();
xfA.q.Set(aA);
xfB.q.Set(aB);
xfA.p = cA - MathUtils.Mul(xfA.q, localCenterA);
xfB.p = cB - MathUtils.Mul(xfB.q, localCenterB);
PositionSolverManifold.Initialize(pc, xfA, xfB, j, out Vector2 normal, out Vector2 point, out float separation);
Vector2 rA = point - cA;
Vector2 rB = point - cB;
// Track max constraint error.
minSeparation = Math.Min(minSeparation, separation);
// Prevent large corrections and allow slop.
float C = MathUtils.Clamp(Settings.Baumgarte * (separation + Settings.LinearSlop), -Settings.MaxLinearCorrection, 0.0f);
// Compute the effective mass.
float rnA = MathUtils.Cross(rA, normal);
float rnB = MathUtils.Cross(rB, normal);
float K = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
// Compute normal impulse
float impulse = K > 0.0f ? -C / K : 0.0f;
Vector2 P = impulse * normal;
cA -= mA * P;
aA -= iA * MathUtils.Cross(rA, P);
cB += mB * P;
aB += iB * MathUtils.Cross(rB, P);
}
_positions[indexA].C = cA;
_positions[indexA].A = aA;
_positions[indexB].C = cB;
_positions[indexB].A = aB;
}
// We can't expect minSpeparation >= -b2_linearSlop because we don't
// push the separation above -b2_linearSlop.
return minSeparation >= -1.5f * Settings.LinearSlop;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
using System.IO;
using System.ServiceProcess;
using System.Threading;
using Xunit;
using Microsoft.Win32;
namespace System.ServiceProcessServiceController.Tests
{
internal sealed class ServiceProvider
{
public readonly string TestMachineName;
public readonly TimeSpan ControlTimeout;
public readonly string TestServiceName;
public readonly string TestServiceDisplayName;
public readonly string DependentTestServiceNamePrefix;
public readonly string DependentTestServiceDisplayNamePrefix;
public readonly string TestServiceRegistryKey;
public ServiceProvider()
{
TestMachineName = ".";
ControlTimeout = TimeSpan.FromSeconds(3);
TestServiceName = Guid.NewGuid().ToString();
TestServiceDisplayName = "Test Service " + TestServiceName;
DependentTestServiceNamePrefix = TestServiceName + ".Dependent";
DependentTestServiceDisplayNamePrefix = TestServiceDisplayName + ".Dependent";
TestServiceRegistryKey = @"HKEY_USERS\.DEFAULT\dotnetTests\ServiceController\" + TestServiceName;
// Create the service
CreateTestServices();
}
private void CreateTestServices()
{
// Create the test service and its dependent services. Then, start the test service.
// All control tests assume that the test service is running when they are executed.
// So all tests should make sure to restart the service if they stop, pause, or shut
// it down.
RunServiceExecutable("create");
}
public void DeleteTestServices()
{
RunServiceExecutable("delete");
RegistryKey users = Registry.Users;
if (users.OpenSubKey(".DEFAULT\\dotnetTests") != null)
users.DeleteSubKeyTree(".DEFAULT\\dotnetTests");
}
private void RunServiceExecutable(string action)
{
const string serviceExecutable = "System.ServiceProcess.ServiceController.TestNativeService.exe";
var process = new Process();
process.StartInfo.FileName = serviceExecutable;
process.StartInfo.Arguments = string.Format("\"{0}\" \"{1}\" {2}", TestServiceName, TestServiceDisplayName, action);
process.Start();
process.WaitForExit();
if (process.ExitCode != 0)
{
throw new Exception("error: " + serviceExecutable + " failed with exit code " + process.ExitCode.ToString());
}
}
}
public class ServiceControllerTests : IDisposable
{
private const int ExpectedDependentServiceCount = 3;
ServiceProvider _testService;
public ServiceControllerTests()
{
_testService = new ServiceProvider();
}
[Fact]
public void ConstructWithServiceName()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.Equal(_testService.TestServiceName, controller.ServiceName);
Assert.Equal(_testService.TestServiceDisplayName, controller.DisplayName);
Assert.Equal(_testService.TestMachineName, controller.MachineName);
Assert.Equal(ServiceType.Win32OwnProcess, controller.ServiceType);
}
[Fact]
public void ConstructWithDisplayName()
{
var controller = new ServiceController(_testService.TestServiceDisplayName);
Assert.Equal(_testService.TestServiceName, controller.ServiceName);
Assert.Equal(_testService.TestServiceDisplayName, controller.DisplayName);
Assert.Equal(_testService.TestMachineName, controller.MachineName);
Assert.Equal(ServiceType.Win32OwnProcess, controller.ServiceType);
}
[Fact]
public void ConstructWithMachineName()
{
var controller = new ServiceController(_testService.TestServiceName, _testService.TestMachineName);
Assert.Equal(_testService.TestServiceName, controller.ServiceName);
Assert.Equal(_testService.TestServiceDisplayName, controller.DisplayName);
Assert.Equal(_testService.TestMachineName, controller.MachineName);
Assert.Equal(ServiceType.Win32OwnProcess, controller.ServiceType);
Assert.Throws<ArgumentException>(() => { var c = new ServiceController(_testService.TestServiceName, ""); });
}
[Fact]
public void ControlCapabilities()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.True(controller.CanStop);
Assert.True(controller.CanPauseAndContinue);
Assert.False(controller.CanShutdown);
}
[Fact]
public void StartWithArguments()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Stopped, controller.Status);
var args = new[] { "a", "b", "c", "d", "e" };
controller.Start(args);
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
// The test service writes the arguments that it was started with to the _testService.TestServiceRegistryKey.
// Read this key to verify that the arguments were properly passed to the service.
string argsString = Registry.GetValue(_testService.TestServiceRegistryKey, "ServiceArguments", null) as string;
Assert.Equal(string.Join(",", args), argsString);
}
[Fact]
public void StopAndStart()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
for (int i = 0; i < 2; i++)
{
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Stopped, controller.Status);
controller.Start();
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
}
}
[Fact]
public void PauseAndContinue()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
for (int i = 0; i < 2; i++)
{
controller.Pause();
controller.WaitForStatus(ServiceControllerStatus.Paused, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Paused, controller.Status);
controller.Continue();
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
}
}
[Fact]
public void WaitForStatusTimeout()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.Throws<System.ServiceProcess.TimeoutException>(() => controller.WaitForStatus(ServiceControllerStatus.Paused, TimeSpan.Zero));
}
[Fact]
public void GetServices()
{
bool foundTestService = false;
foreach (var service in ServiceController.GetServices())
{
if (service.ServiceName == _testService.TestServiceName)
{
foundTestService = true;
}
}
Assert.True(foundTestService, "Test service was not enumerated with all services");
}
[Fact]
public void GetDevices()
{
var devices = ServiceController.GetDevices();
Assert.True(devices.Length != 0);
const ServiceType SERVICE_TYPE_DRIVER =
ServiceType.FileSystemDriver |
ServiceType.KernelDriver |
ServiceType.RecognizerDriver;
Assert.All(devices, device => Assert.NotEqual(0, (int)(device.ServiceType & SERVICE_TYPE_DRIVER)));
}
[Fact]
public void Dependencies()
{
// The test service creates a number of dependent services, each of which is depended on
// by all the services created after it.
var controller = new ServiceController(_testService.TestServiceName);
Assert.Equal(ExpectedDependentServiceCount, controller.DependentServices.Length);
for (int i = 0; i < controller.DependentServices.Length; i++)
{
var dependent = AssertHasDependent(controller, _testService.DependentTestServiceNamePrefix + i, _testService.DependentTestServiceDisplayNamePrefix + i);
Assert.Equal(ServiceType.Win32OwnProcess, dependent.ServiceType);
// Assert that this dependent service is depended on by all the test services created after it
Assert.Equal(ExpectedDependentServiceCount - i - 1, dependent.DependentServices.Length);
for (int j = i + 1; j < ExpectedDependentServiceCount; j++)
{
AssertHasDependent(dependent, _testService.DependentTestServiceNamePrefix + j, _testService.DependentTestServiceDisplayNamePrefix + j);
}
// Assert that the dependent service depends on the main test service
AssertDependsOn(dependent, _testService.TestServiceName, _testService.TestServiceDisplayName);
// Assert that this dependent service depends on all the test services created before it
Assert.Equal(i + 1, dependent.ServicesDependedOn.Length);
for (int j = i - 1; j >= 0; j--)
{
AssertDependsOn(dependent, _testService.DependentTestServiceNamePrefix + j, _testService.DependentTestServiceDisplayNamePrefix + j);
}
}
}
[Fact]
public void ServicesStartMode()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.Equal(ServiceStartMode.Manual, controller.StartType);
// Check for the startType of the dependent services.
for (int i = 0; i < controller.DependentServices.Length; i++)
{
Assert.Equal(ServiceStartMode.Disabled, controller.DependentServices[i].StartType);
}
}
public void Dispose()
{
_testService.DeleteTestServices();
}
private static ServiceController AssertHasDependent(ServiceController controller, string serviceName, string displayName)
{
var dependent = FindService(controller.DependentServices, serviceName, displayName);
Assert.NotNull(dependent);
return dependent;
}
private static ServiceController AssertDependsOn(ServiceController controller, string serviceName, string displayName)
{
var dependency = FindService(controller.ServicesDependedOn, serviceName, displayName);
Assert.NotNull(dependency);
return dependency;
}
private static ServiceController FindService(ServiceController[] services, string serviceName, string displayName)
{
foreach (ServiceController service in services)
{
if (service.ServiceName == serviceName && service.DisplayName == displayName)
{
return service;
}
}
return null;
}
}
}
| |
using System;
using System.Linq;
using Abp.AspNetCore;
using Abp.Castle.Logging.Log4Net;
using Abp.Dependency;
using Abp.Extensions;
using Abp.Hangfire;
using Abp.Timing;
using Castle.Facilities.Logging;
using Hangfire;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Cors.Internal;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Helios.Web.Authentication.JwtBearer;
using PaulMiami.AspNetCore.Mvc.Recaptcha;
using Swashbuckle.AspNetCore.Swagger;
using Helios.Web.IdentityServer;
using Helios.Configuration;
using Helios.Identity;
#if FEATURE_SIGNALR
using Helios.Web.Owin;
using Abp.Owin;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Cors;
using Owin;
using Owin.Security.AesDataProtectorProvider;
using Abp.Web.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
#endif
namespace Helios.Web.Startup
{
public class Startup
{
private const string DefaultCorsPolicyName = "localhost";
private readonly IConfigurationRoot _appConfiguration;
public Startup(IHostingEnvironment env)
{
_appConfiguration = env.GetAppConfiguration();
}
public IServiceProvider ConfigureServices(IServiceCollection services)
{
//MVC
services.AddMvc(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory(DefaultCorsPolicyName));
});
//Configure CORS for angular2 UI
services.AddCors(options =>
{
options.AddPolicy(DefaultCorsPolicyName, builder =>
{
//App:CorsOrigins in appsettings.json can contain more than one address with splitted by comma.
builder
//.WithOrigins(_appConfiguration["App:CorsOrigins"].Split(",", StringSplitOptions.RemoveEmptyEntries).Select(o => o.RemovePostFix("/")).ToArray())
.AllowAnyOrigin() //TODO: Will be replaced by above when Microsoft releases microsoft.aspnetcore.cors 2.0 - https://github.com/aspnet/CORS/pull/94
.AllowAnyHeader()
.AllowAnyMethod();
});
});
IdentityRegistrar.Register(services);
AuthConfigurer.Configure(services, _appConfiguration);
//Identity server
if (bool.Parse(_appConfiguration["IdentityServer:IsEnabled"]))
{
IdentityServerRegistrar.Register(services, _appConfiguration);
}
//Swagger - Enable this line and the related lines in Configure method to enable swagger UI
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Info { Title = "HeliosZero API", Version = "v1" });
options.DocInclusionPredicate((docName, description) => true);
});
//Recaptcha
services.AddRecaptcha(new RecaptchaOptions
{
SiteKey = _appConfiguration["Recaptcha:SiteKey"],
SecretKey = _appConfiguration["Recaptcha:SecretKey"]
});
//Hangfire (Enable to use Hangfire instead of default job manager)
//services.AddHangfire(config =>
//{
// config.UseSqlServerStorage(_appConfiguration.GetConnectionString("Default"));
//});
//Configure Abp and Dependency Injection
return services.AddAbp<HeliosZeroWebHostModule>(options =>
{
//Configure Log4Net logging
options.IocManager.IocContainer.AddFacility<LoggingFacility>(
f => f.UseAbpLog4Net().WithConfig("log4net.config")
);
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//Initializes ABP framework.
app.UseAbp(options =>
{
options.UseAbpRequestLocalization = false; //used below: UseAbpRequestLocalization
});
app.UseCors(DefaultCorsPolicyName); //Enable CORS!
app.UseAuthentication();
app.UseJwtTokenMiddleware();
if (bool.Parse(_appConfiguration["IdentityServer:IsEnabled"]))
{
app.UseIdentityServer();
/* We can not use app.UseIdentityServerAuthentication because IdentityServer4.AccessTokenValidation
* is not ported to asp.net core 2.0 yet. See issue: https://github.com/IdentityServer/IdentityServer4/issues/1055
* Once it's ported, add IdentityServer4.AccessTokenValidation to Web.Core project and enable following lines:
*/
//app.UseIdentityServerAuthentication(
// new IdentityServerAuthenticationOptions
// {
// Authority = _appConfiguration["App:ServerRootAddress"],
// RequireHttpsMetadata = false
// });
}
app.UseStaticFiles();
app.UseAbpRequestLocalization();
#if FEATURE_SIGNALR
//Integrate to OWIN
app.UseAppBuilder(ConfigureOwinServices);
#endif
//Hangfire dashboard & server (Enable to use Hangfire instead of default job manager)
//app.UseHangfireDashboard("/hangfire", new DashboardOptions
//{
// Authorization = new[] { new AbpHangfireAuthorizationFilter(AppPermissions.Pages_Administration_HangfireDashboard) }
//});
//app.UseHangfireServer();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "defaultWithArea",
template: "{area}/{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
// Enable middleware to serve generated Swagger as a JSON endpoint
app.UseSwagger();
// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "HeliosZero API V1");
options.InjectOnCompleteJavaScript("/swagger/ui/swagger.zh-CN.js");
}); //URL: /swagger
}
#if FEATURE_SIGNALR
private static void ConfigureOwinServices(IAppBuilder app)
{
GlobalHost.DependencyResolver.Register(typeof(IAssemblyLocator), () => new SignalRAssemblyLocator());
app.Properties["host.AppName"] = "HeliosZero";
app.UseAbp();
app.UseAesDataProtectorProvider();
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
EnableJSONP = true
};
map.RunSignalR(hubConfiguration);
});
}
#endif
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsAzureCompositeModelClient
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// PolymorphicrecursiveOperations operations.
/// </summary>
internal partial class PolymorphicrecursiveOperations : Microsoft.Rest.IServiceOperations<AzureCompositeModel>, IPolymorphicrecursiveOperations
{
/// <summary>
/// Initializes a new instance of the PolymorphicrecursiveOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal PolymorphicrecursiveOperations(AzureCompositeModel client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AzureCompositeModel
/// </summary>
public AzureCompositeModel Client { get; private set; }
/// <summary>
/// Get complex types that are polymorphic and have recursive references
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Fish>> GetValidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphicrecursive/valid").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Fish>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Fish>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types that are polymorphic and have recursive references
/// </summary>
/// <param name='complexBody'>
/// Please put a salmon that looks like this:
/// {
/// "fishtype": "salmon",
/// "species": "king",
/// "length": 1,
/// "age": 1,
/// "location": "alaska",
/// "iswild": true,
/// "siblings": [
/// {
/// "fishtype": "shark",
/// "species": "predator",
/// "length": 20,
/// "age": 6,
/// "siblings": [
/// {
/// "fishtype": "salmon",
/// "species": "coho",
/// "length": 2,
/// "age": 2,
/// "location": "atlantic",
/// "iswild": true,
/// "siblings": [
/// {
/// "fishtype": "shark",
/// "species": "predator",
/// "length": 20,
/// "age": 6
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "length": 10,
/// "age": 105
/// }
/// ]
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "length": 10,
/// "age": 105
/// }
/// ]
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "length": 10,
/// "age": 105
/// }
/// ]
/// }
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutValidWithHttpMessagesAsync(Fish complexBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (complexBody == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "complexBody");
}
if (complexBody != null)
{
complexBody.Validate();
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphicrecursive/valid").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using Gallio.Common;
using Gallio.Common.Concurrency;
namespace Gallio.AutoCAD.Commands
{
/// <summary>
/// Runs commands in a remote AutoCAD process via COM interop.
/// </summary>
public class AcadCommandRunner : IAcadCommandRunner
{
private static readonly TimeSpan ReadyTimeout = TimeSpan.FromSeconds(60);
private static readonly TimeSpan ReadyPollInterval = TimeSpan.FromSeconds(0.25);
/// <inheritdoc/>
public IAsyncResult BeginRun(AcadCommand command, IProcess process, AsyncCallback completionCallback, object asyncState)
{
if (command == null)
throw new ArgumentNullException("command");
if (process == null)
throw new ArgumentNullException("process");
if (process.HasExited)
throw new ArgumentNullException("process", "Process has exited.");
var task = new CommandTask(command, process, completionCallback, asyncState);
return task.Begin();
}
/// <inheritdoc/>
public void EndRun(IAsyncResult result)
{
if (result == null)
throw new ArgumentNullException("result");
var taskResult = result as CommandTaskResult;
if (taskResult == null)
throw new ArgumentException("Unknown result type.", "result");
taskResult.Get();
}
private class CommandTask
{
private readonly AcadCommand command;
private readonly IProcess process;
private readonly CommandTaskResult result;
public CommandTask(AcadCommand command, IProcess process, AsyncCallback completionCallback, object asyncState)
{
this.command = command;
this.process = process;
this.result = new CommandTaskResult(completionCallback, asyncState);
}
public CommandTaskResult Begin()
{
CreateSTAThread(Run).Start();
return result;
}
private void Run()
{
object application = GetAcadApplication(process);
using (MessageFilter.Register(Stopwatch.StartNew()))
{
try
{
SendCommand(application, command);
result.Complete(null);
}
catch (Exception e)
{
result.Complete(e);
}
}
}
private static ThreadTask CreateSTAThread(Action start)
{
var task = new ThreadTask("AutoCAD Command Runner", start)
{
ApartmentState = ApartmentState.STA
};
return task;
}
private static object GetAcadApplication(IProcess process)
{
Stopwatch stopwatch = Stopwatch.StartNew();
process.WaitForInputIdle(ReadyTimeout.Milliseconds);
while (stopwatch.Elapsed < ReadyTimeout)
{
try
{
var application = Marshal.GetActiveObject("AutoCAD.Application");
if (application != null)
return application;
}
catch (COMException)
{
}
Thread.Sleep(ReadyPollInterval);
}
throw new TimeoutException("Unable to acquire the AutoCAD automation object from the running object table.");
}
private static void SendCommand(object application, AcadCommand command)
{
try
{
var document = GetActiveDocument(application);
var parameters = new object[] { command.ToLispExpression(application) };
document.GetType().InvokeMember("SendCommand", BindingFlags.InvokeMethod, null, document, parameters);
GC.KeepAlive(application);
}
catch (COMException e)
{
throw new TimeoutException("Unable to send messages to the AutoCAD process.", e);
}
}
private static object GetActiveDocument(object application)
{
var document = application.GetType().InvokeMember("ActiveDocument", BindingFlags.GetProperty, null, application, null);
if (document == null)
throw new InvalidOperationException("Unable to acquire the active document from AutoCAD.");
return document;
}
}
private class CommandTaskResult : IAsyncResult
{
private readonly object syncLock = new object();
private readonly object asyncState;
private readonly AsyncCallback completionCallback;
private ManualResetEvent waitHandle;
private bool isCompleted;
private Exception exception;
public CommandTaskResult(AsyncCallback completionCallback, object asyncState)
{
this.completionCallback = completionCallback;
this.asyncState = asyncState;
}
internal void Complete(Exception exception)
{
lock (syncLock)
{
this.exception = exception;
isCompleted = true;
if (waitHandle != null)
waitHandle.Set();
}
if (completionCallback != null)
completionCallback(this);
}
internal void Get()
{
if (IsCompleted == false)
{
try
{
AsyncWaitHandle.WaitOne();
}
finally
{
AsyncWaitHandle.Close();
}
}
if (exception != null)
throw exception;
}
public bool IsCompleted
{
get { return isCompleted; }
}
public WaitHandle AsyncWaitHandle
{
get
{
lock (syncLock)
{
if (waitHandle == null)
waitHandle = new ManualResetEvent(isCompleted);
}
return waitHandle;
}
}
public object AsyncState
{
get { return asyncState; }
}
public bool CompletedSynchronously
{
get { return false; }
}
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("00000016-0000-0000-C000-000000000046")]
private interface IOleMessageFilter
{
[PreserveSig]
int HandleInComingCall(
[In] uint dwCallType,
[In] IntPtr htaskCaller,
[In] uint dwTickCount,
[In] IntPtr lpInterfaceInfo);
[PreserveSig]
int RetryRejectedCall(
[In] IntPtr htaskCallee,
[In] uint dwTickCount,
[In] uint dwRejectType);
int MessagePending(
[In] IntPtr htaskCallee,
[In] uint dwTickCount,
[In] uint dwPendingType);
}
private class MessageFilter : IOleMessageFilter, IDisposable
{
private readonly Stopwatch elapsed;
private IOleMessageFilter oldFilter;
private MessageFilter(Stopwatch elapsed)
{
this.elapsed = elapsed;
}
internal static IDisposable Register(Stopwatch elapsed)
{
var filter = new MessageFilter(elapsed);
CoRegisterMessageFilter(filter, out filter.oldFilter);
return filter;
}
public void Dispose()
{
IOleMessageFilter dummy;
CoRegisterMessageFilter(oldFilter, out dummy);
}
int IOleMessageFilter.HandleInComingCall(uint dwCallType, IntPtr htaskCaller, uint dwTickCount, IntPtr lpInterfaceInfo)
{
if (oldFilter == null)
return 0; // SERVERCALL_ISHANDLED
return oldFilter.HandleInComingCall(dwCallType, htaskCaller, dwTickCount, lpInterfaceInfo);
}
int IOleMessageFilter.RetryRejectedCall(IntPtr htaskCallee, uint dwTickCount, uint dwRejectType)
{
if (dwRejectType == 2) // SERVERCALL_RETRYLATER
return 100; // retry in 100 ms
if (dwRejectType == 1)
{
if (elapsed.Elapsed > ReadyTimeout)
return -1;
return 100;
}
return -1;
}
int IOleMessageFilter.MessagePending(IntPtr htaskCallee, uint dwTickCount, uint dwPendingType)
{
if (oldFilter == null)
return 1; // PENDINGMSG_WAITNOPROCESS
return oldFilter.MessagePending(htaskCallee, dwTickCount, dwPendingType);
}
[DllImport("ole32.dll")]
private static extern int CoRegisterMessageFilter(IOleMessageFilter lpMessageFilter, out IOleMessageFilter lplpMessageFilter);
}
}
}
| |
// 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.Diagnostics;
using System.Security.Cryptography;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.X509Certificates.Asn1;
using Microsoft.Win32.SafeHandles;
namespace Internal.Cryptography.Pal
{
internal sealed class OpenSslX509ChainProcessor : IChainPal
{
// The average chain is 3 (End-Entity, Intermediate, Root)
// 10 is plenty big.
private const int DefaultChainCapacity = 10;
private static readonly string s_userRootPath =
DirectoryBasedStoreProvider.GetStorePath(X509Store.RootStoreName);
private static readonly string s_userIntermediatePath =
DirectoryBasedStoreProvider.GetStorePath(X509Store.IntermediateCAStoreName);
private static readonly string s_userPersonalPath =
DirectoryBasedStoreProvider.GetStorePath(X509Store.MyStoreName);
private SafeX509Handle _leafHandle;
private SafeX509StoreHandle _store;
private readonly SafeX509StackHandle _untrustedLookup;
private readonly SafeX509StoreCtxHandle _storeCtx;
private readonly DateTime _verificationTime;
private TimeSpan _remainingDownloadTime;
private X509RevocationMode _revocationMode;
private OpenSslX509ChainProcessor(
SafeX509Handle leafHandle,
SafeX509StoreHandle store,
SafeX509StackHandle untrusted,
SafeX509StoreCtxHandle storeCtx,
DateTime verificationTime,
TimeSpan remainingDownloadTime)
{
_leafHandle = leafHandle;
_store = store;
_untrustedLookup = untrusted;
_storeCtx = storeCtx;
_verificationTime = verificationTime;
_remainingDownloadTime = remainingDownloadTime;
}
public void Dispose()
{
_storeCtx?.Dispose();
_untrustedLookup?.Dispose();
_store?.Dispose();
// We don't own this one.
_leafHandle = null;
}
public bool? Verify(X509VerificationFlags flags, out Exception exception)
{
exception = null;
return ChainVerifier.Verify(ChainElements, flags);
}
public X509ChainElement[] ChainElements { get; private set; }
public X509ChainStatus[] ChainStatus { get; private set; }
public SafeX509ChainHandle SafeHandle
{
get { return null; }
}
internal static OpenSslX509ChainProcessor InitiateChain(
SafeX509Handle leafHandle,
DateTime verificationTime,
TimeSpan remainingDownloadTime)
{
SafeX509StackHandle systemTrust = StorePal.GetMachineRoot().GetNativeCollection();
SafeX509StackHandle systemIntermediate = StorePal.GetMachineIntermediate().GetNativeCollection();
SafeX509StoreHandle store = null;
SafeX509StackHandle untrusted = null;
SafeX509StoreCtxHandle storeCtx = null;
try
{
store = Interop.Crypto.X509ChainNew(systemTrust, s_userRootPath);
untrusted = Interop.Crypto.NewX509Stack();
Interop.Crypto.X509StackAddDirectoryStore(untrusted, s_userIntermediatePath);
Interop.Crypto.X509StackAddDirectoryStore(untrusted, s_userPersonalPath);
Interop.Crypto.X509StackAddMultiple(untrusted, systemIntermediate);
Interop.Crypto.X509StoreSetVerifyTime(store, verificationTime);
storeCtx = Interop.Crypto.X509StoreCtxCreate();
if (!Interop.Crypto.X509StoreCtxInit(storeCtx, store, leafHandle, untrusted))
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
return new OpenSslX509ChainProcessor(
leafHandle,
store,
untrusted,
storeCtx,
verificationTime,
remainingDownloadTime);
}
catch
{
store?.Dispose();
untrusted?.Dispose();
storeCtx?.Dispose();
throw;
}
}
internal Interop.Crypto.X509VerifyStatusCode FindFirstChain(X509Certificate2Collection extraCerts)
{
SafeX509StoreCtxHandle storeCtx = _storeCtx;
// While this returns true/false, at this stage we care more about the detailed error code.
Interop.Crypto.X509VerifyCert(storeCtx);
Interop.Crypto.X509VerifyStatusCode statusCode = Interop.Crypto.X509StoreCtxGetError(storeCtx);
if (IsCompleteChain(statusCode))
{
return statusCode;
}
SafeX509StackHandle untrusted = _untrustedLookup;
if (extraCerts?.Count > 0)
{
foreach(X509Certificate2 cert in extraCerts)
{
AddToStackAndUpRef(((OpenSslX509CertificateReader)cert.Pal).SafeHandle, untrusted);
}
Interop.Crypto.X509StoreCtxRebuildChain(storeCtx);
statusCode = Interop.Crypto.X509StoreCtxGetError(storeCtx);
}
return statusCode;
}
internal static bool IsCompleteChain(Interop.Crypto.X509VerifyStatusCode statusCode)
{
switch (statusCode)
{
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
return false;
default:
return true;
}
}
internal Interop.Crypto.X509VerifyStatusCode FindChainViaAia(
ref List<X509Certificate2> downloadedCerts)
{
IntPtr lastCert = IntPtr.Zero;
SafeX509StoreCtxHandle storeCtx = _storeCtx;
Interop.Crypto.X509VerifyStatusCode statusCode =
Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
while (!IsCompleteChain(statusCode))
{
using (SafeX509Handle currentCert = Interop.Crypto.X509StoreCtxGetCurrentCert(storeCtx))
{
IntPtr currentHandle = currentCert.DangerousGetHandle();
// No progress was made, give up.
if (currentHandle == lastCert)
{
break;
}
lastCert = currentHandle;
ArraySegment<byte> authorityInformationAccess =
OpenSslX509CertificateReader.FindFirstExtension(
currentCert,
Oids.AuthorityInformationAccess);
if (authorityInformationAccess.Count == 0)
{
break;
}
X509Certificate2 downloaded = DownloadCertificate(
authorityInformationAccess,
ref _remainingDownloadTime);
// The AIA record is contained in a public structure, so no need to clear it.
ArrayPool<byte>.Shared.Return(authorityInformationAccess.Array);
if (downloaded == null)
{
break;
}
if (downloadedCerts == null)
{
downloadedCerts = new List<X509Certificate2>();
}
AddToStackAndUpRef(downloaded.Handle, _untrustedLookup);
downloadedCerts.Add(downloaded);
Interop.Crypto.X509StoreCtxRebuildChain(storeCtx);
statusCode = Interop.Crypto.X509StoreCtxGetError(storeCtx);
}
}
if (statusCode == Interop.Crypto.X509VerifyStatusCode.X509_V_OK && downloadedCerts != null)
{
using (SafeX509StackHandle chainStack = Interop.Crypto.X509StoreCtxGetChain(_storeCtx))
{
int chainSize = Interop.Crypto.GetX509StackFieldCount(chainStack);
Span<IntPtr> tempChain = stackalloc IntPtr[DefaultChainCapacity];
IntPtr[] tempChainRent = null;
if (chainSize <= tempChain.Length)
{
tempChain = tempChain.Slice(0, chainSize);
}
else
{
tempChainRent = ArrayPool<IntPtr>.Shared.Rent(chainSize);
tempChain = tempChainRent.AsSpan(0, chainSize);
}
for (int i = 0; i < chainSize; i++)
{
tempChain[i] = Interop.Crypto.GetX509StackField(chainStack, i);
}
// In the average case we never made it here.
//
// Given that we made it here, in the average remaining case
// we are doing a one item for which will match in the second position
// of an (on-average) 3 item collection.
//
// The only case where this loop really matters is if downloading the
// certificate made an alternate chain better, which may have resulted in
// an extra download and made the first one not be involved any longer. In
// that case, it's a 2 item for loop matching against a three item set.
//
// So N*M is well contained.
for (int i = downloadedCerts.Count - 1; i >= 0; i--)
{
X509Certificate2 downloadedCert = downloadedCerts[i];
if (!tempChain.Contains(downloadedCert.Handle))
{
downloadedCert.Dispose();
downloadedCerts.RemoveAt(i);
}
}
if (downloadedCerts.Count == 0)
{
downloadedCerts = null;
}
if (tempChainRent != null)
{
// While the IntPtrs aren't secret, clearing them helps prevent
// accidental use-after-free because of pooling.
tempChain.Clear();
ArrayPool<IntPtr>.Shared.Return(tempChainRent);
}
}
}
return statusCode;
}
internal void CommitToChain()
{
Interop.Crypto.X509StoreCtxCommitToChain(_storeCtx);
}
internal void ProcessRevocation(
X509RevocationMode revocationMode,
X509RevocationFlag revocationFlag)
{
_revocationMode = revocationMode;
if (revocationMode == X509RevocationMode.NoCheck)
{
return;
}
using (SafeX509StackHandle chainStack = Interop.Crypto.X509StoreCtxGetChain(_storeCtx))
{
int chainSize =
revocationFlag == X509RevocationFlag.EndCertificateOnly ?
1 :
Interop.Crypto.GetX509StackFieldCount(chainStack);
for (int i = 0; i < chainSize; i++)
{
using (SafeX509Handle cert =
Interop.Crypto.X509UpRef(Interop.Crypto.GetX509StackField(chainStack, i)))
{
CrlCache.AddCrlForCertificate(
cert,
_store,
revocationMode,
_verificationTime,
ref _remainingDownloadTime);
}
}
}
Interop.Crypto.X509StoreSetRevocationFlag(_store, revocationFlag);
Interop.Crypto.X509StoreCtxRebuildChain(_storeCtx);
}
internal void Finish(OidCollection applicationPolicy, OidCollection certificatePolicy)
{
WorkingChain workingChain = null;
// If the chain had any errors during the previous build we need to walk it again with
// the error collector running.
if (Interop.Crypto.X509StoreCtxGetError(_storeCtx) !=
Interop.Crypto.X509VerifyStatusCode.X509_V_OK)
{
Interop.Crypto.X509StoreCtxReset(_storeCtx);
workingChain = new WorkingChain();
Interop.Crypto.X509StoreVerifyCallback workingCallback = workingChain.VerifyCallback;
Interop.Crypto.X509StoreCtxSetVerifyCallback(_storeCtx, workingCallback);
bool verify = Interop.Crypto.X509VerifyCert(_storeCtx);
if (workingChain.AbortedForSignatureError)
{
Debug.Assert(!verify, "verify should have returned false for signature error");
CloneChainForSignatureErrors();
// Reset to a WorkingChain that won't fail.
workingChain = new WorkingChain(abortOnSignatureError: false);
workingCallback = workingChain.VerifyCallback;
Interop.Crypto.X509StoreCtxSetVerifyCallback(_storeCtx, workingCallback);
verify = Interop.Crypto.X509VerifyCert(_storeCtx);
}
GC.KeepAlive(workingCallback);
// Because our callback tells OpenSSL that every problem is ignorable, it should tell us that the
// chain is just fine (unless it returned a negative code for an exception)
Debug.Assert(verify, "verify should have returned true");
const Interop.Crypto.X509VerifyStatusCode NoCrl =
Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_CRL;
ErrorCollection? errors =
workingChain.LastError > 0 ? (ErrorCollection?)workingChain[0] : null;
if (_revocationMode == X509RevocationMode.Online &&
_remainingDownloadTime > TimeSpan.Zero &&
errors?.HasError(NoCrl) == true)
{
Interop.Crypto.X509VerifyStatusCode ocspStatus = CheckOcsp();
ref ErrorCollection refErrors = ref workingChain[0];
if (ocspStatus == Interop.Crypto.X509VerifyStatusCode.X509_V_OK)
{
refErrors.ClearError(NoCrl);
}
else if (ocspStatus != NoCrl)
{
refErrors.ClearError(NoCrl);
refErrors.Add(ocspStatus);
}
}
}
X509ChainElement[] elements = BuildChainElements(
workingChain,
out List<X509ChainStatus> overallStatus);
workingChain?.Dispose();
if (applicationPolicy?.Count > 0 || certificatePolicy?.Count > 0)
{
ProcessPolicy(elements, overallStatus, applicationPolicy, certificatePolicy);
}
ChainStatus = overallStatus?.ToArray() ?? Array.Empty<X509ChainStatus>();
ChainElements = elements;
// The native resources are not needed any longer.
Dispose();
}
private void CloneChainForSignatureErrors()
{
SafeX509StoreHandle newStore;
Interop.Crypto.X509StoreCtxResetForSignatureError(_storeCtx, out newStore);
if (newStore != null)
{
_store.Dispose();
_store = newStore;
}
}
private Interop.Crypto.X509VerifyStatusCode CheckOcsp()
{
string ocspCache = CrlCache.GetCachedOcspResponseDirectory();
Interop.Crypto.X509VerifyStatusCode status =
Interop.Crypto.X509ChainGetCachedOcspStatus(_storeCtx, ocspCache);
if (status != Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_CRL)
{
return status;
}
string baseUri = GetOcspEndpoint(_leafHandle);
if (baseUri == null)
{
return status;
}
using (SafeOcspRequestHandle req = Interop.Crypto.X509ChainBuildOcspRequest(_storeCtx))
{
ArraySegment<byte> encoded = Interop.Crypto.OpenSslRentEncode(
handle => Interop.Crypto.GetOcspRequestDerSize(handle),
(handle, buf) => Interop.Crypto.EncodeOcspRequest(handle, buf),
req);
ArraySegment<char> urlEncoded = Base64UrlEncode(encoded);
string requestUrl = UrlPathAppend(baseUri, urlEncoded);
// Nothing sensitive is in the encoded request (it was sent via HTTP-non-S)
ArrayPool<byte>.Shared.Return(encoded.Array);
ArrayPool<char>.Shared.Return(urlEncoded.Array);
// https://tools.ietf.org/html/rfc6960#appendix-A describes both a GET and a POST
// version of an OCSP responder.
//
// Doing POST via the reflection indirection to HttpClient is difficult, and
// CA/Browser Forum Baseline Requirements (version 1.6.3) section 4.9.10
// (On-line REvocation Checking Requirements) says that the GET method must be supported.
//
// So, for now, only try GET.
SafeOcspResponseHandle resp =
CertificateAssetDownloader.DownloadOcspGet(requestUrl, ref _remainingDownloadTime);
using (resp)
{
if (resp == null || resp.IsInvalid)
{
return Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_CRL;
}
try
{
System.IO.Directory.CreateDirectory(ocspCache);
}
catch
{
// Opportunistic create, suppress all errors.
}
return Interop.Crypto.X509ChainVerifyOcsp(_storeCtx, req, resp, ocspCache);
}
}
}
private static string UrlPathAppend(string baseUri, ReadOnlyMemory<char> resource)
{
Debug.Assert(baseUri.Length > 0);
Debug.Assert(resource.Length > 0);
int count = baseUri.Length + resource.Length;
if (baseUri[baseUri.Length - 1] == '/')
{
return string.Create(
count,
(baseUri, resource),
(buf, st) =>
{
st.baseUri.AsSpan().CopyTo(buf);
st.resource.Span.CopyTo(buf.Slice(st.Item1.Length));
});
}
return string.Create(
count + 1,
(baseUri, resource),
(buf, st) =>
{
st.baseUri.AsSpan().CopyTo(buf);
buf[st.Item1.Length] = '/';
st.resource.Span.CopyTo(buf.Slice(st.Item1.Length + 1));
});
}
private static ArraySegment<char> Base64UrlEncode(ReadOnlySpan<byte> input)
{
// Every 3 bytes turns into 4 chars for the Base64 operation
int base64Len = ((input.Length + 2) / 3) * 4;
char[] base64 = ArrayPool<char>.Shared.Rent(base64Len);
if (!Convert.TryToBase64Chars(input, base64, out int charsWritten))
{
Debug.Fail($"Convert.TryToBase64 failed with {input.Length} bytes to a {base64.Length} buffer");
throw new CryptographicException();
}
Debug.Assert(charsWritten == base64Len);
// In the degenerate case every char will turn into 3 chars.
int urlEncodedLen = charsWritten * 3;
char[] urlEncoded = ArrayPool<char>.Shared.Rent(urlEncodedLen);
int writeIdx = 0;
for (int readIdx = 0; readIdx < charsWritten; readIdx++)
{
char cur = base64[readIdx];
if ((cur >= 'A' && cur <= 'Z') ||
(cur >= 'a' && cur <= 'z') ||
(cur >= '0' && cur <= '9'))
{
urlEncoded[writeIdx++] = cur;
}
else if (cur == '+')
{
urlEncoded[writeIdx++] = '%';
urlEncoded[writeIdx++] = '2';
urlEncoded[writeIdx++] = 'B';
}
else if (cur == '/')
{
urlEncoded[writeIdx++] = '%';
urlEncoded[writeIdx++] = '2';
urlEncoded[writeIdx++] = 'F';
}
else if (cur == '=')
{
urlEncoded[writeIdx++] = '%';
urlEncoded[writeIdx++] = '3';
urlEncoded[writeIdx++] = 'D';
}
else
{
Debug.Fail($"'{cur}' is not a valid Base64 character");
throw new CryptographicException();
}
}
ArrayPool<char>.Shared.Return(base64);
return new ArraySegment<char>(urlEncoded, 0, writeIdx);
}
private X509ChainElement[] BuildChainElements(
WorkingChain workingChain,
out List<X509ChainStatus> overallStatus)
{
X509ChainElement[] elements;
overallStatus = null;
using (SafeX509StackHandle chainStack = Interop.Crypto.X509StoreCtxGetChain(_storeCtx))
{
int chainSize = Interop.Crypto.GetX509StackFieldCount(chainStack);
elements = new X509ChainElement[chainSize];
for (int i = 0; i < chainSize; i++)
{
X509ChainStatus[] status = Array.Empty<X509ChainStatus>();
ErrorCollection? elementErrors =
workingChain?.LastError > i ? (ErrorCollection?)workingChain[i] : null;
if (elementErrors.HasValue && elementErrors.Value.HasErrors)
{
List<X509ChainStatus> statusBuilder = new List<X509ChainStatus>();
overallStatus = overallStatus ?? new List<X509ChainStatus>();
AddElementStatus(elementErrors.Value, statusBuilder, overallStatus);
status = statusBuilder.ToArray();
}
IntPtr elementCertPtr = Interop.Crypto.GetX509StackField(chainStack, i);
if (elementCertPtr == IntPtr.Zero)
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
// Duplicate the certificate handle
X509Certificate2 elementCert = new X509Certificate2(elementCertPtr);
elements[i] = new X509ChainElement(elementCert, status, "");
}
}
return elements;
}
private static void ProcessPolicy(
X509ChainElement[] elements,
List<X509ChainStatus> overallStatus,
OidCollection applicationPolicy,
OidCollection certificatePolicy)
{
List<X509Certificate2> certsToRead = new List<X509Certificate2>();
foreach (X509ChainElement element in elements)
{
certsToRead.Add(element.Certificate);
}
CertificatePolicyChain policyChain = new CertificatePolicyChain(certsToRead);
bool failsPolicyChecks = false;
if (certificatePolicy != null)
{
if (!policyChain.MatchesCertificatePolicies(certificatePolicy))
{
failsPolicyChecks = true;
}
}
if (applicationPolicy != null)
{
if (!policyChain.MatchesApplicationPolicies(applicationPolicy))
{
failsPolicyChecks = true;
}
}
if (failsPolicyChecks)
{
X509ChainElement leafElement = elements[0];
X509ChainStatus chainStatus = new X509ChainStatus
{
Status = X509ChainStatusFlags.NotValidForUsage,
StatusInformation = SR.Chain_NoPolicyMatch,
};
var elementStatus = new List<X509ChainStatus>(leafElement.ChainElementStatus.Length + 1);
elementStatus.AddRange(leafElement.ChainElementStatus);
AddUniqueStatus(elementStatus, ref chainStatus);
AddUniqueStatus(overallStatus, ref chainStatus);
elements[0] = new X509ChainElement(
leafElement.Certificate,
elementStatus.ToArray(),
leafElement.Information);
}
}
private static void AddElementStatus(
ErrorCollection errorCodes,
List<X509ChainStatus> elementStatus,
List<X509ChainStatus> overallStatus)
{
foreach (var errorCode in errorCodes)
{
AddElementStatus(errorCode, elementStatus, overallStatus);
}
}
private static void AddElementStatus(
Interop.Crypto.X509VerifyStatusCode errorCode,
List<X509ChainStatus> elementStatus,
List<X509ChainStatus> overallStatus)
{
X509ChainStatusFlags statusFlag = MapVerifyErrorToChainStatus(errorCode);
Debug.Assert(
(statusFlag & (statusFlag - 1)) == 0,
"Status flag has more than one bit set",
"More than one bit is set in status '{0}' for error code '{1}'",
statusFlag,
errorCode);
foreach (X509ChainStatus currentStatus in elementStatus)
{
if ((currentStatus.Status & statusFlag) != 0)
{
return;
}
}
X509ChainStatus chainStatus = new X509ChainStatus
{
Status = statusFlag,
StatusInformation = Interop.Crypto.GetX509VerifyCertErrorString(errorCode),
};
elementStatus.Add(chainStatus);
AddUniqueStatus(overallStatus, ref chainStatus);
}
private static void AddUniqueStatus(IList<X509ChainStatus> list, ref X509ChainStatus status)
{
X509ChainStatusFlags statusCode = status.Status;
for (int i = 0; i < list.Count; i++)
{
if (list[i].Status == statusCode)
{
return;
}
}
list.Add(status);
}
private static X509ChainStatusFlags MapVerifyErrorToChainStatus(Interop.Crypto.X509VerifyStatusCode code)
{
switch (code)
{
case Interop.Crypto.X509VerifyStatusCode.X509_V_OK:
return X509ChainStatusFlags.NoError;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_NOT_YET_VALID:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_HAS_EXPIRED:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
return X509ChainStatusFlags.NotTimeValid;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_REVOKED:
return X509ChainStatusFlags.Revoked;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_SIGNATURE_FAILURE:
return X509ChainStatusFlags.NotSignatureValid;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_UNTRUSTED:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
return X509ChainStatusFlags.UntrustedRoot;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CRL_HAS_EXPIRED:
return X509ChainStatusFlags.OfflineRevocation;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CRL_NOT_YET_VALID:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CRL_SIGNATURE_FAILURE:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_KEYUSAGE_NO_CRL_SIGN:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_CRL:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION:
return X509ChainStatusFlags.RevocationStatusUnknown;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_EXTENSION:
return X509ChainStatusFlags.InvalidExtension;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
return X509ChainStatusFlags.PartialChain;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_PURPOSE:
return X509ChainStatusFlags.NotValidForUsage;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_CA:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_NON_CA:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_PATH_LENGTH_EXCEEDED:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_KEYUSAGE_NO_CERTSIGN:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE:
return X509ChainStatusFlags.InvalidBasicConstraints;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_POLICY_EXTENSION:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_NO_EXPLICIT_POLICY:
return X509ChainStatusFlags.InvalidPolicyConstraints;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_REJECTED:
return X509ChainStatusFlags.ExplicitDistrust;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION:
return X509ChainStatusFlags.HasNotSupportedCriticalExtension;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_CHAIN_TOO_LONG:
throw new CryptographicException();
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_OUT_OF_MEM:
throw new OutOfMemoryException();
default:
Debug.Fail("Unrecognized X509VerifyStatusCode:" + code);
throw new CryptographicException();
}
}
private static X509Certificate2 DownloadCertificate(
ReadOnlyMemory<byte> authorityInformationAccess,
ref TimeSpan remainingDownloadTime)
{
// Don't do any work if we're over limit.
if (remainingDownloadTime <= TimeSpan.Zero)
{
return null;
}
string uri = FindHttpAiaRecord(authorityInformationAccess, Oids.CertificateAuthorityIssuers);
if (uri == null)
{
return null;
}
return CertificateAssetDownloader.DownloadCertificate(uri, ref remainingDownloadTime);
}
private static string GetOcspEndpoint(SafeX509Handle cert)
{
ArraySegment<byte> authorityInformationAccess =
OpenSslX509CertificateReader.FindFirstExtension(
cert,
Oids.AuthorityInformationAccess);
if (authorityInformationAccess.Count == 0)
{
return null;
}
string baseUrl = FindHttpAiaRecord(authorityInformationAccess, Oids.OcspEndpoint);
ArrayPool<byte>.Shared.Return(authorityInformationAccess.Array);
return baseUrl;
}
private static string FindHttpAiaRecord(ReadOnlyMemory<byte> authorityInformationAccess, string recordTypeOid)
{
AsnReader reader = new AsnReader(authorityInformationAccess, AsnEncodingRules.DER);
AsnReader sequenceReader = reader.ReadSequence();
reader.ThrowIfNotEmpty();
while (sequenceReader.HasData)
{
AccessDescriptionAsn.Decode(sequenceReader, out AccessDescriptionAsn description);
if (StringComparer.Ordinal.Equals(description.AccessMethod, recordTypeOid))
{
GeneralNameAsn name = description.AccessLocation;
if (name.Uri != null &&
Uri.TryCreate(name.Uri, UriKind.Absolute, out Uri uri) &&
uri.Scheme == "http")
{
return name.Uri;
}
}
}
return null;
}
private static void AddToStackAndUpRef(SafeX509Handle cert, SafeX509StackHandle stack)
{
using (SafeX509Handle tmp = Interop.Crypto.X509UpRef(cert))
{
if (!Interop.Crypto.PushX509StackField(stack, tmp))
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
// Ownership was transferred to the cert stack.
tmp.SetHandleAsInvalid();
}
}
private static void AddToStackAndUpRef(IntPtr cert, SafeX509StackHandle stack)
{
using (SafeX509Handle tmp = Interop.Crypto.X509UpRef(cert))
{
if (!Interop.Crypto.PushX509StackField(stack, tmp))
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
// Ownership was transferred to the cert stack.
tmp.SetHandleAsInvalid();
}
}
private sealed class WorkingChain : IDisposable
{
// OpenSSL 1.0 sets a "signature valid, don't check again" if we OK the signature error
// OpenSSL 1.1 does not.
private const long OpenSSL_1_1_0_RTM = 0x10100000L;
private static readonly bool s_defaultAbort = SafeEvpPKeyHandle.OpenSslVersion < OpenSSL_1_1_0_RTM;
private ErrorCollection[] _errors;
internal bool AbortOnSignatureError { get; }
internal bool AbortedForSignatureError { get; private set; }
internal WorkingChain()
: this(s_defaultAbort)
{
}
internal WorkingChain(bool abortOnSignatureError)
{
AbortOnSignatureError = abortOnSignatureError;
}
internal int LastError => _errors?.Length ?? 0;
internal ref ErrorCollection this[int idx] => ref _errors[idx];
public void Dispose()
{
ErrorCollection[] toReturn = _errors;
_errors = null;
if (toReturn != null)
{
ArrayPool<ErrorCollection>.Shared.Return(toReturn);
}
}
internal int VerifyCallback(int ok, IntPtr ctx)
{
if (ok != 0)
{
return ok;
}
try
{
using (var storeCtx = new SafeX509StoreCtxHandle(ctx, ownsHandle: false))
{
Interop.Crypto.X509VerifyStatusCode errorCode = Interop.Crypto.X509StoreCtxGetError(storeCtx);
int errorDepth = Interop.Crypto.X509StoreCtxGetErrorDepth(storeCtx);
if (AbortOnSignatureError &&
errorCode == Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_SIGNATURE_FAILURE)
{
AbortedForSignatureError = true;
return 0;
}
// We don't report "OK" as an error.
// For compatibility with Windows / .NET Framework, do not report X509_V_CRL_NOT_YET_VALID.
if (errorCode != Interop.Crypto.X509VerifyStatusCode.X509_V_OK &&
errorCode != Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CRL_NOT_YET_VALID)
{
if (_errors == null)
{
int size = Math.Max(DefaultChainCapacity, errorDepth + 1);
_errors = ArrayPool<ErrorCollection>.Shared.Rent(size);
// We only do spares writes.
_errors.AsSpan().Clear();
}
else if (errorDepth >= _errors.Length)
{
ErrorCollection[] toReturn = _errors;
_errors = ArrayPool<ErrorCollection>.Shared.Rent(errorDepth + 1);
toReturn.AsSpan().CopyTo(_errors);
// We only do spares writes, clear the remainder.
_errors.AsSpan(toReturn.Length).Clear();
ArrayPool<ErrorCollection>.Shared.Return(toReturn);
}
_errors[errorDepth].Add(errorCode);
}
}
return 1;
}
catch
{
return -1;
}
}
}
private unsafe struct ErrorCollection
{
// As of OpenSSL 1.1.1 there are 74 defined X509_V_ERR values,
// therefore it fits in a bitvector backed by 3 ints (96 bits available).
private const int BucketCount = 3;
private const int OverflowValue = BucketCount * sizeof(int) * 8 - 1;
private fixed int _codes[BucketCount];
internal bool HasOverflow => _codes[2] < 0;
internal bool HasErrors =>
_codes[0] != 0 || _codes[1] != 0 || _codes[2] != 0;
internal void Add(Interop.Crypto.X509VerifyStatusCode statusCode)
{
int bucket = FindBucket(statusCode, out int bitValue);
_codes[bucket] |= bitValue;
}
public void ClearError(Interop.Crypto.X509VerifyStatusCode statusCode)
{
int bucket = FindBucket(statusCode, out int bitValue);
_codes[bucket] &= ~bitValue;
}
internal bool HasError(Interop.Crypto.X509VerifyStatusCode statusCode)
{
int bucket = FindBucket(statusCode, out int bitValue);
return (_codes[bucket] & bitValue) != 0;
}
public Enumerator GetEnumerator()
{
if (HasOverflow)
{
throw new CryptographicException();
}
return new Enumerator(this);
}
private static int FindBucket(Interop.Crypto.X509VerifyStatusCode statusCode, out int bitValue)
{
int val = (int)statusCode;
int bucket;
if (val >= OverflowValue)
{
Debug.Fail($"Out of range X509VerifyStatusCode returned {val} >= {OverflowValue}");
bucket = BucketCount - 1;
bitValue = 1 << 31;
}
else
{
bucket = Math.DivRem(val, 32, out int localBitNumber);
bitValue = (1 << localBitNumber);
}
return bucket;
}
internal struct Enumerator
{
private ErrorCollection _collection;
private int _lastBucket;
private int _lastBit;
internal Enumerator(ErrorCollection coll)
{
_collection = coll;
_lastBucket = -1;
_lastBit = -1;
}
public bool MoveNext()
{
if (_lastBucket >= BucketCount)
{
return false;
}
FindNextBit:
if (_lastBit == -1)
{
_lastBucket++;
while (_lastBucket < BucketCount && _collection._codes[_lastBucket] == 0)
{
_lastBucket++;
}
if (_lastBucket >= BucketCount)
{
return false;
}
}
_lastBit++;
int val = _collection._codes[_lastBucket];
while (_lastBit < 32)
{
if ((val & (1 << _lastBit)) != 0)
{
return true;
}
_lastBit++;
}
_lastBit = -1;
goto FindNextBit;
}
public Interop.Crypto.X509VerifyStatusCode Current =>
_lastBit == -1 ?
Interop.Crypto.X509VerifyStatusCode.X509_V_OK :
(Interop.Crypto.X509VerifyStatusCode)(_lastBit + 32 * _lastBucket);
}
}
}
}
| |
using BorderSkin.Settings;
namespace BorderSkin.Execlusion
{
partial class ExclusionManagerControl : System.Windows.Forms.UserControl
{
//UserControl overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool disposing)
{
try {
if (disposing && components != null) {
components.Dispose();
}
} finally {
base.Dispose(disposing);
}
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
this.GroupBox6 = new System.Windows.Forms.GroupBox();
this.TitleLabel = new System.Windows.Forms.Label();
this.RemoveAllExc = new IconButton();
this.RemoveExc = new IconButton();
this.EditExc = new IconButton();
this.AddExc = new IconButton();
this.ExcList = new System.Windows.Forms.ListView();
this.ColumnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.ColumnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.ColumnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.SkinnedColumn = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.SkinColumn = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.GroupBox6.SuspendLayout();
this.SuspendLayout();
//
// GroupBox6
//
this.GroupBox6.BackColor = System.Drawing.Color.White;
this.GroupBox6.Controls.Add(this.TitleLabel);
this.GroupBox6.Controls.Add(this.RemoveAllExc);
this.GroupBox6.Controls.Add(this.RemoveExc);
this.GroupBox6.Controls.Add(this.EditExc);
this.GroupBox6.Controls.Add(this.AddExc);
this.GroupBox6.Controls.Add(this.ExcList);
this.GroupBox6.Dock = System.Windows.Forms.DockStyle.Fill;
this.GroupBox6.Location = new System.Drawing.Point(0, 0);
this.GroupBox6.Name = "GroupBox6";
this.GroupBox6.Padding = new System.Windows.Forms.Padding(10, 5, 10, 40);
this.GroupBox6.Size = new System.Drawing.Size(680, 454);
this.GroupBox6.TabIndex = 1;
this.GroupBox6.TabStop = false;
//
// TitleLabel
//
this.TitleLabel.AutoSize = true;
this.TitleLabel.BackColor = System.Drawing.Color.White;
this.TitleLabel.ForeColor = System.Drawing.Color.Blue;
this.TitleLabel.Location = new System.Drawing.Point(7, 0);
this.TitleLabel.Name = "TitleLabel";
this.TitleLabel.Size = new System.Drawing.Size(95, 13);
this.TitleLabel.TabIndex = 104;
this.TitleLabel.Tag = "Windows Manager";
this.TitleLabel.Text = "Windows Manager";
//
// RemoveAllExc
//
this.RemoveAllExc.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.RemoveAllExc.Cursor = System.Windows.Forms.Cursors.Hand;
this.RemoveAllExc.Image = global::BorderSkin.Properties.Resources.RemoveAllImage;
this.RemoveAllExc.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.RemoveAllExc.Location = new System.Drawing.Point(429, 421);
this.RemoveAllExc.Name = "RemoveAllExc";
this.RemoveAllExc.Size = new System.Drawing.Size(87, 22);
this.RemoveAllExc.TabIndex = 103;
this.RemoveAllExc.Tag = "Remove All";
this.RemoveAllExc.Text = "Remove All";
this.RemoveAllExc.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.RemoveAllExc.Click += new System.EventHandler(this.RemoveAllExc_Click);
//
// RemoveExc
//
this.RemoveExc.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.RemoveExc.Cursor = System.Windows.Forms.Cursors.Hand;
this.RemoveExc.Image = global::BorderSkin.Properties.Resources.RemoveImage;
this.RemoveExc.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.RemoveExc.Location = new System.Drawing.Point(285, 421);
this.RemoveExc.Name = "RemoveExc";
this.RemoveExc.Size = new System.Drawing.Size(67, 22);
this.RemoveExc.TabIndex = 103;
this.RemoveExc.Tag = "Remove";
this.RemoveExc.Text = "Remove";
this.RemoveExc.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.RemoveExc.Click += new System.EventHandler(this.RemoveExc_Click);
//
// EditExc
//
this.EditExc.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.EditExc.Cursor = System.Windows.Forms.Cursors.Hand;
this.EditExc.Image = global::BorderSkin.Properties.Resources.EditImage;
this.EditExc.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.EditExc.Location = new System.Drawing.Point(361, 421);
this.EditExc.Name = "EditExc";
this.EditExc.Size = new System.Drawing.Size(52, 22);
this.EditExc.TabIndex = 103;
this.EditExc.Tag = "Edit";
this.EditExc.Text = "Edit";
this.EditExc.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.EditExc.Click += new System.EventHandler(this.EditExc_Click);
//
// AddExc
//
this.AddExc.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.AddExc.Cursor = System.Windows.Forms.Cursors.Hand;
this.AddExc.Image = global::BorderSkin.Properties.Resources.AddImage;
this.AddExc.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.AddExc.Location = new System.Drawing.Point(223, 421);
this.AddExc.Name = "AddExc";
this.AddExc.Size = new System.Drawing.Size(47, 22);
this.AddExc.TabIndex = 103;
this.AddExc.Tag = "Add";
this.AddExc.Text = "Add";
this.AddExc.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.AddExc.Click += new System.EventHandler(this.AddExc_Click);
//
// ExcList
//
this.ExcList.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.ColumnHeader1,
this.ColumnHeader2,
this.ColumnHeader3,
this.SkinnedColumn,
this.SkinColumn});
this.ExcList.Dock = System.Windows.Forms.DockStyle.Fill;
this.ExcList.FullRowSelect = true;
this.ExcList.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.ExcList.LabelWrap = false;
this.ExcList.Location = new System.Drawing.Point(10, 18);
this.ExcList.MultiSelect = false;
this.ExcList.Name = "ExcList";
this.ExcList.Size = new System.Drawing.Size(660, 396);
this.ExcList.Sorting = System.Windows.Forms.SortOrder.Ascending;
this.ExcList.TabIndex = 31;
this.ExcList.UseCompatibleStateImageBehavior = false;
this.ExcList.View = System.Windows.Forms.View.Details;
//
// ColumnHeader1
//
this.ColumnHeader1.Tag = "Name";
this.ColumnHeader1.Text = "Name";
this.ColumnHeader1.Width = 149;
//
// ColumnHeader2
//
this.ColumnHeader2.Tag = "Process";
this.ColumnHeader2.Text = "Process";
this.ColumnHeader2.Width = 99;
//
// ColumnHeader3
//
this.ColumnHeader3.Tag = "Classes";
this.ColumnHeader3.Text = "Classes";
this.ColumnHeader3.Width = 149;
//
// SkinnedColumn
//
this.SkinnedColumn.Tag = "Has Skin";
this.SkinnedColumn.Text = "Has Skin";
this.SkinnedColumn.Width = 101;
//
// SkinColumn
//
this.SkinColumn.Tag = "Skin";
this.SkinColumn.Text = "Skin";
this.SkinColumn.Width = 103;
//
// ExclusionManagerControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.GroupBox6);
this.Name = "ExclusionManagerControl";
this.Size = new System.Drawing.Size(680, 454);
this.GroupBox6.ResumeLayout(false);
this.GroupBox6.PerformLayout();
this.ResumeLayout(false);
}
internal System.Windows.Forms.GroupBox GroupBox6;
internal System.Windows.Forms.Label TitleLabel;
internal IconButton RemoveAllExc;
internal IconButton RemoveExc;
internal IconButton EditExc;
internal IconButton AddExc;
internal System.Windows.Forms.ListView ExcList;
internal System.Windows.Forms.ColumnHeader ColumnHeader1;
internal System.Windows.Forms.ColumnHeader ColumnHeader2;
internal System.Windows.Forms.ColumnHeader ColumnHeader3;
internal System.Windows.Forms.ColumnHeader SkinnedColumn;
internal System.Windows.Forms.ColumnHeader SkinColumn;
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
namespace WebsitePanel.Providers.Mail
{
[Serializable]
public class MailList : ServiceProviderItem
{
private string[] members = new string[0];
private string description;
private string textHeader;
private string textFooter;
private string htmlHeader;
private string htmlFooter;
private bool moderated;
private bool enabled;
private string moderatorAddress;
private ReplyTo replyToMode;
private PostingMode postingMode;
private string password;
private string subjectPrefix = "";
private int maxMessageSize;
private int maxRecipientsPerMessage;
private string listToAddress;
private string listFromAddress;
private string listReplytoAddress;
private bool digestmode;
private bool sendsubscribe;
private bool sendunsubscribe;
private bool allowunsubscribe;
private bool disablelistcommand;
private bool disablesubscribecommand;
public int MaxMessageSize
{
get { return maxMessageSize; }
set { maxMessageSize = value; }
}
public int MaxRecipientsPerMessage
{
get { return maxRecipientsPerMessage; }
set { maxRecipientsPerMessage = value; }
}
public string Description
{
get { return this.description; }
set { this.description = value; }
}
public string TextHeader
{
get { return this.textHeader; }
set { this.textHeader = value; }
}
public string TextFooter
{
get { return this.textFooter; }
set { this.textFooter = value; }
}
public string HtmlHeader
{
get { return this.htmlHeader; }
set { this.htmlHeader = value; }
}
public string HtmlFooter
{
get { return this.htmlFooter; }
set { this.htmlFooter = value; }
}
public string ModeratorAddress
{
get { return this.moderatorAddress; }
set { this.moderatorAddress = value; }
}
public PostingMode PostingMode
{
get { return this.postingMode; }
set { this.postingMode = value; }
}
public ReplyTo ReplyToMode
{
get { return this.replyToMode; }
set { this.replyToMode = value; }
}
public bool Moderated
{
get { return this.moderated; }
set { this.moderated = value; }
}
public bool Enabled
{
get { return this.enabled; }
set { this.enabled = value; }
}
[Persistent]
public string Password
{
get { return this.password; }
set { this.password = value; }
}
public string[] Members
{
get { return this.members; }
set { this.members = value; }
}
public string SubjectPrefix
{
get { return subjectPrefix; }
set { subjectPrefix = value; }
}
#region SmarterMail
private bool enableSubjectPrefix;
private bool requirePassword;
public bool EnableSubjectPrefix
{
get { return enableSubjectPrefix; }
set { enableSubjectPrefix = value; }
}
public bool RequirePassword
{
get { return requirePassword; }
set { requirePassword = value; }
}
public string ListToAddress
{
get { return listToAddress; }
set { listToAddress = value; }
}
public string ListFromAddress
{
get { return listFromAddress; }
set { listFromAddress = value; }
}
public string ListReplyToAddress
{
get { return listReplytoAddress; }
set { listReplytoAddress = value; }
}
public bool DigestMode
{
get { return digestmode; }
set { digestmode = value; }
}
public bool SendSubscribe
{
get { return sendsubscribe; }
set { sendsubscribe = value; }
}
public bool SendUnsubscribe
{
get { return sendunsubscribe; }
set { sendunsubscribe = value; }
}
public bool AllowUnsubscribe
{
get { return allowunsubscribe; }
set { allowunsubscribe = value; }
}
public bool DisableListcommand
{
get { return disablelistcommand; }
set { disablelistcommand = value; }
}
public bool DisableSubscribecommand
{
get { return disablesubscribecommand; }
set { disablesubscribecommand = value; }
}
#endregion
#region MailEnable
private int attachHeader;
private int attachFooter;
private PrefixOption prefixOption;
public int AttachHeader
{
get { return this.attachHeader; }
set { this.attachHeader = value; }
}
public int AttachFooter
{
get { return this.attachFooter; }
set { this.attachFooter = value; }
}
public PrefixOption PrefixOption
{
get { return this.prefixOption; }
set { this.prefixOption = value;}
}
#endregion
#region Merak
private bool maxMessageSizeEnabled;
private PasswordProtection passwordProtection;
public bool MaxMessageSizeEnabled
{
get { return maxMessageSizeEnabled; }
set { maxMessageSizeEnabled = value;}
}
public PasswordProtection PasswordProtection
{
get { return passwordProtection;}
set { passwordProtection = value; }
}
#endregion
#region hMailServer
private bool requireSmtpAuthentication;
public bool RequireSmtpAuthentication
{
get { return requireSmtpAuthentication; }
set { requireSmtpAuthentication = value; }
}
#endregion
#region IceWarp
public IceWarpListMembersSource MembersSource { get; set; }
public IceWarpListFromAndReplyToHeader FromHeader { get; set; }
public IceWarpListFromAndReplyToHeader ReplyToHeader { get; set; }
public bool SetReceipientsToToHeader { get; set; }
public IceWarpListOriginator Originator { get; set; }
public IceWarpListDefaultRights DefaultRights { get; set; }
public int MaxMembers { get; set; }
public bool SendToSender { get; set; }
public int MaxMessagesPerMinute { get; set; }
public IceWarpListConfirmSubscription ConfirmSubscription { get; set; }
public bool CommandsInSubject { get; set; }
public bool DisableWhichCommand { get; set; }
public bool DisableReviewCommand { get; set; }
public bool DisableVacationCommand { get; set; }
public string CommandPassword { get; set; }
public bool SuppressCommandResponses { get; set; }
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using GBlue;
// enum PsdLayerVirtualViewScrollDirection
public enum PsdLayerVirtualViewScrollDirection
{
None = 0,
Vertical = 1,
Horizontal = 2,
Free = Vertical | Horizontal,
};
// enum PsdLayerVirtualViewScrollEffect
public enum PsdLayerVirtualViewScrollEffect
{
None,
Momentum,
MomentumAndSpring,
Magnet
};
public sealed class PsdLayerVirtualView : MonoBehaviourEx
{
#region Callback
/// <summary>
/// This event will be fired when Spring animation finished
/// </summary>
public System.Action OnSpringAnimationFinished;
/// <summary>
/// This event will be fired when Magnet animation finished
/// </summary>
public System.Action OnMagnetAnimationFinished;
/// <summary>
/// This event will be fired when GameObject got Start event
/// OnInitSlot(GameObject slot)
/// return value can be null
/// </summary>
public System.Func<GameObject, object> OnInitSlot;
/// <summary>
/// This event will be fired when Reset called
/// OnResetSlot(GameObject slot)
/// </summary>
public System.Action<GameObject> OnResetSlot;
/// <summary>
/// This event will be fired when Refresh called
/// 'slot' parameter is basically GameObject, but if you return a instance of a custom class in OnInitSlot,
/// 'slot' parameter will be the instance of the custom class instead of GameObject.
/// OnUpdateSlot(object slot, object item, int slotIndex, int itemIndex)
/// e.g.
/// view.OnInitSlot = delegate(GameObject slot){ return new CustomSlotManager(); };
/// view.OnUpdateSlot = delegate(object slot, object item, int slotIndex, int itemIndex){ var mgr = slot as CustomSlotManager; };
/// </summary>
public System.Action<object, object, int, int> OnUpdateSlot;
#endregion
#region Child Classes
class Slot
{
public GameObject gameObject
{
get; internal set;
}
public Transform transform
{
get; internal set;
}
public Vector2 Pos
{
get { return this.transform.localPosition; }
internal set { this.transform.localPosition = value; }
}
public bool Visibled
{
get { return Util.IsActive(this.transform); }
set
{
if (Util.IsActive(this.transform) != value)
Util.SetActive(this.transform, value);
}
}
public object InstanceOfCustomSlotManager{
get; internal set;
}
public object Item
{
get; internal set;
}
internal Slot(GameObject go)
{
this.InstanceOfCustomSlotManager = go;
this.gameObject = go;
this.transform = go.transform;
this.Visibled = false;
}
} ;
class Transform2D
{
private Vector2 pos;
public Transform2D(Transform target)
{
var bounds = NGUIMath.CalculateRelativeWidgetBounds(target, true);
var rc = new RectEx(
bounds.center.x - bounds.extents.x,
bounds.center.y - bounds.extents.y,
bounds.size.x, bounds.size.y);
this.Size = new Vector2(rc.W, rc.H);
var s = this.Size;
var p = target.localPosition;
p.x -= s.x * 0.5f;
p.y += s.y * 0.5f;
this.Pos = p;
}
public Vector2 Pos
{
get; private set;
}
public Vector2 Size
{
get; private set;
}
public Rect Area
{
get
{
var p = this.Pos;
var s = this.Size;
return new Rect(p.x, p.y, s.x, s.y);
}
}
} ;
class ItemPositionMaker
{
private PsdLayerVirtualView view;
public ItemPositionMaker(PsdLayerVirtualView view)
{
this.view = view;
this.view.currentColIndex = view.itemStartIndex % view.colCount;
this.view.currentRowIndex = view.itemStartIndex / view.colCount;
}
public Vector2 NextPos
{
get
{
var w = this.view.ItemSize.x;
var h = this.view.ItemSize.y;
var pos = new Vector2(
w * this.view.currentColIndex++,
-h * this.view.currentRowIndex);
if (this.view.currentColIndex >= this.view.colCount)
{
this.view.currentColIndex = 0;
if (++this.view.currentRowIndex >= this.view.rowCount)
this.view.rowCount++;
}
return this.view.ItemStartPos + pos + new Vector2(
-this.view.scrolledPos.x, this.view.scrolledPos.y
);
}
}
} ;
#endregion
#region Properties
public Transform bg;
public RectOffset bgPadding;
private Transform2D bg2d;
public Transform item;
public RectOffset itemMargin;
private Transform2D item2d;
private Vector2 scrolledPos;
private int itemStartIndexOld = 0;
private int itemStartIndex = 0;
private List<object> items;
private List<Slot> slots;
private int rowCount = 1;
private int colCount = 1;
private int currentRowIndex;
private int currentColIndex;
private int actualRowCount;
private int actualColCount;
public bool circulation;
public PsdLayerVirtualViewScrollDirection scrollDirection = PsdLayerVirtualViewScrollDirection.Vertical;
public PsdLayerVirtualViewScrollEffect scrollEffect = PsdLayerVirtualViewScrollEffect.MomentumAndSpring;
public float momentumInertiaDuration = 0.5f;
public float momentumLimit = 100;
private float lastMovedTime = 0f;
private float lastVelocity = 0f;
private float addtionalInertiaDuration = 0f;
public float magnetSensitive = 0.1f;
public float magnetAnimationTime = .3f;
private iTweenSimplePlayer tweener;
private UIPanel uipanel;
public bool IsInited
{
get { return this.slots.Count > 0; }
}
public Vector2 ViewSize
{
get
{
if (this.bg2d == null)
this.bg2d = new Transform2D(this.bg);
return this.bg2d.Size - new Vector2(
this.bgPadding.horizontal,
this.bgPadding.vertical);
}
}
public Vector2 ItemSize
{
get
{
return this.item2d.Size + new Vector2(
this.itemMargin.horizontal,
this.itemMargin.vertical);
}
}
public Rect ViewArea
{
get
{
var p = this.bg2d.Pos;
p.x += this.bgPadding.left;
p.y -= this.bgPadding.top;
var s = this.bg2d.Size;
s.x -= this.bgPadding.horizontal;
s.y -= this.bgPadding.vertical;
return new Rect(p.x, p.y, s.x, s.y);
}
}
public Rect ScrollArea
{
get
{
var a = this.ViewArea;
var s = this.ItemSize;
var col = this.colCount;
var row = this.currentRowIndex + 1;
return new Rect(a.x, a.y, s.x * col, s.y * row);
}
}
public int SlotCount
{
get { return this.items != null && this.items.Count > 0 ? this.slots.Count : 0; }
}
public int ItemCount
{
get { return this.items != null ? this.items.Count : 0; }
}
private Vector2 ItemStartPos
{
get
{
var a = this.ViewArea;
a.x += this.item2d.Size.x * 0.5f + this.itemMargin.left;
a.y -= this.item2d.Size.y * 0.5f + this.itemMargin.top;
return new Vector2(a.x, a.y);
}
}
public bool IsTouched
{
get; internal set;
}
public bool IsFirstPage
{
get { return this.itemStartIndex == 0; }
}
public bool IsLastPage
{
get { return this.items.Count - this.itemStartIndex <= this.actualColCount * this.actualRowCount; }
}
private Vector2 OutOfBoundsDelta
{
get
{
var delta = Vector2.zero;
if (this.slots.Count > 0)
{
var varea = this.ViewArea;
var sarea = this.ScrollArea;
var diff = this.scrolledPos + new Vector2(varea.width, varea.height) -
new Vector2(sarea.width, sarea.height);
if (this.scrolledPos.y < 0)
delta.y = this.scrolledPos.y;
else if (sarea.height >= varea.height && diff.y > 0)
delta.y = diff.y;
else if (sarea.height < varea.height && this.scrolledPos.y > 0)
delta.y = this.scrolledPos.y;
if (this.scrolledPos.x < 0)
delta.x = this.scrolledPos.x;
else if (sarea.width >= varea.width && diff.x > 0)
delta.x = diff.x;
else if (sarea.width < varea.width && this.scrolledPos.x > 0)
delta.x = this.scrolledPos.x;
}
return delta;
}
}
#endregion
void Awake()
{
this.items = new List<object>();
this.slots = new List<Slot>();
this.tweener = new iTweenSimplePlayer();
if (this.bg == null)
{
Debug.LogError("You must set the background");
return;
}
if (this.item == null)
{
Debug.LogError("You must set the base item");
return;
}
if (this.itemMargin == null)
this.itemMargin = new RectOffset();
if (this.bgPadding == null)
this.bgPadding = new RectOffset();
if (this.uipanel == null)
this.uipanel = GBlue.Util.FindComponent<UIPanel>(this.item.parent);
this.item2d = new Transform2D(this.item);
this.bg2d = new Transform2D(this.bg);
var area = this.ViewArea;
this.uipanel.baseClipRegion = new Vector4(
area.x + area.width*0.5f, area.y - area.height*0.5f,
area.width, area.height
);
GBlue.Util.SetActive(this.item, false);
}
void Start()
{
// Init after all other sibling components, which might reference this component, have handled their Start event.
new GBlue.Timer(this, 0.001f, delegate(){
this.MakeSlots();
this.Refresh();
});
}
#if UNITY_EDITOR
void OnDrawGizmos()
{
if (UnityEditor.Selection.activeGameObject != this.gameObject)
return;
if (this.itemMargin == null)
this.itemMargin = new RectOffset();
if (this.bgPadding == null)
this.bgPadding = new RectOffset();
if (this.item2d == null)
this.item2d = new Transform2D(this.item);
if (this.bg2d == null)
this.bg2d = new Transform2D(this.bg);
var area = this.ViewArea;
var pos = new Vector3(area.x + area.width*0.5f, area.y - area.height*0.5f, -1);
var size = new Vector3(area.width, area.height, 0.1f);
Gizmos.matrix = this.transform.localToWorldMatrix;
Gizmos.color = Color.blue;
Gizmos.DrawWireCube(pos, size);
}
#endif
void LateUpdate()
{
if (this.ItemCount == 0 || this.IsTouched || this.tweener.IsPlaying)
return;
var distance = 0f;
if (this.scrollEffect != PsdLayerVirtualViewScrollEffect.None && this.lastVelocity != 0)
{
var inertiaDuration = this.momentumInertiaDuration;
inertiaDuration += this.addtionalInertiaDuration;
var t = (Time.time - this.lastMovedTime) / inertiaDuration;
if (t < inertiaDuration)
{
var velocity = Mathf.Lerp(this.lastVelocity, 0, t);
distance = velocity * Time.smoothDeltaTime;
}
//Debug.Log ("Momentum: "+ this.OutOfBoundsDelta+", "+distance);
}
var outOfBound = this.OutOfBoundsDelta != Vector2.zero;
if (this.scrollEffect == PsdLayerVirtualViewScrollEffect.Magnet)
{
// increase inertia duration
this.addtionalInertiaDuration += this.momentumInertiaDuration * -0.5f;
}
else if (outOfBound)
{
// increase inertia duration
this.addtionalInertiaDuration += this.momentumInertiaDuration * -0.1f;
}
if (!outOfBound && distance != 0)
{
this.OnMoving(new Vector2(0, distance));
}
else
{
if (outOfBound)
{
if (this.scrollEffect == PsdLayerVirtualViewScrollEffect.MomentumAndSpring)
{
if (this.circulation)
{
}
else
this.PlaySpringBreak();
}
else
this.PlayMagnetBreak();
}
this.addtionalInertiaDuration = 0;
this.lastVelocity = 0.0f;
}
}
void OnPress(bool pressed)
{
if (pressed)
this.OnMovingStart();
else
this.OnMovingEnd();
}
void OnDrag(Vector2 delta)
{
this.OnMoving(delta);
}
internal void OnMovingStart()
{
if (this.ItemCount == 0)
return;
this.IsTouched = true;
this.addtionalInertiaDuration = 0;
this.lastVelocity = 0.0f;
this.tweener.Stop();
}
internal void OnMoving(Vector2 delta)
{
if (this.ItemCount == 0 || delta == Vector2.zero)
return;
this.lastMovedTime = Time.time;
this.lastVelocity = delta.y / Time.smoothDeltaTime;
var outOfBound = this.OutOfBoundsDelta != Vector2.zero;
if (outOfBound)
{
delta *= 0.7f;
}
this.AddScrollPos(delta);
this.Scroll();
}
internal void OnMovingEnd()
{
if (this.ItemCount == 0)
return;
this.IsTouched = false;
var outOfBound = this.OutOfBoundsDelta != Vector2.zero;
if (!outOfBound && this.scrollEffect == PsdLayerVirtualViewScrollEffect.Magnet)
{
this.PlayMagnetBreak();
this.addtionalInertiaDuration = 0;
this.lastVelocity = 0.0f;
}
}
private GameObject MakeSlot(bool firstTime)
{
var clone = firstTime ?
this.item.gameObject : GameObject.Instantiate(this.item.gameObject) as GameObject;
{
clone.transform.parent = this.item.parent;
clone.transform.localPosition = Vector2.zero;
clone.transform.localRotation = this.item.localRotation;
clone.transform.localScale = this.item.localScale;
}
return clone;
}
private void MakeSlots()
{
var vw = this.ViewSize.x;
var vh = this.ViewSize.y;
var w = this.ItemSize.x;
var h = this.ItemSize.y;
this.colCount = Mathf.FloorToInt(vw / w);
if (this.colCount <= 1)
this.actualColCount = this.colCount = 1;
else
this.actualColCount = this.colCount + 2;
this.rowCount = Mathf.FloorToInt(vh / h);
if (this.rowCount <= 1)
this.actualRowCount = this.rowCount = 1;
else
this.actualRowCount = this.rowCount + 2;
this.slots.Clear();
for (var row = 0; row < this.actualRowCount; ++row)
{
for (var col = 0; col < this.actualColCount; ++col)
{
var clone = this.MakeSlot(row == 0 && col == 0);
var slot = new Slot(clone);
if (this.OnInitSlot != null)
slot.InstanceOfCustomSlotManager = this.OnInitSlot(clone);
this.slots.Add(slot);
}
}
}
public object GetItem(int i)
{
return this.items[i];
}
public void AddItem(object item)
{
this.AddItem(item, false);
}
public void AddItem(object item, bool refresh)
{
this.items.Add(item);
if (refresh)
this.Refresh();
}
public void RemoveItem(object item)
{
this.RemoveItem(item, false);
}
public void RemoveItem(object item, bool refresh)
{
if (this.items.Remove(item))
{
if (this.itemStartIndex >= this.items.Count)
this.itemStartIndex = Mathf.Max(0, this.items.Count - 1);
}
if (refresh)
this.Refresh();
}
public void RemoveItemAt(int index)
{
this.RemoveItemAt(index, false);
}
public void RemoveItemAt(int index, bool refresh)
{
this.items.RemoveAt(index);
{
if (this.itemStartIndex >= this.items.Count)
this.itemStartIndex = Mathf.Max(0, this.items.Count - 1);
}
if (refresh)
this.Refresh();
}
public void ClearItems()
{
this.items.Clear();
}
public void Refresh()
{
if (Util.IsActive(this.gameObject))
this.Refresh(this.itemStartIndex);
}
private void Refresh(int itemIndex)
{
if (this.ItemCount == 0 || this.SlotCount == 0)
return;
var posMaker = new ItemPositionMaker(this);
var slotIndex = 0;
foreach (var slot in this.slots)
{
if (slot.Visibled = itemIndex < this.items.Count)
{
var item = this.items[itemIndex];
{
slot.Pos = posMaker.NextPos;
slot.Item = item;
if (this.OnUpdateSlot != null)
{
this.OnUpdateSlot(
slot.InstanceOfCustomSlotManager, item, slotIndex, itemIndex);
}
}
slotIndex++;
}
if (++itemIndex >= this.items.Count && this.circulation)
itemIndex = 0;
}
}
public void Shuffle()
{
if (this.ItemCount == 0 || this.SlotCount == 0)
return;
Util.Shuffle(this.items);
}
public void Sort()
{
if (this.ItemCount == 0 || this.SlotCount == 0)
return;
this.items.Sort();
}
public void Sort(System.Comparison<object> comparison)
{
if (this.ItemCount == 0 || this.SlotCount == 0)
return;
this.items.Sort(comparison);
}
public void Reset()
{
this.Reset(true, true);
}
public void Reset(bool resetSlotPosition, bool resetItemPosition)
{
if (this.ItemCount > 0)
{
for (var i = 0; i < this.slots.Count; ++i)
{
var slot = this.slots[i];
if (this.OnResetSlot != null)
this.OnResetSlot(slot.gameObject);
if (resetSlotPosition)
{
//**TODO
}
}
}
if (resetItemPosition)
this.itemStartIndex = 0;
this.Refresh();
}
private void AddScrollPos(Vector2 delta)
{
if (Util.Hasflag((int)this.scrollDirection, (int)PsdLayerVirtualViewScrollDirection.Horizontal))
this.scrolledPos.x -= delta.x;
if (Util.Hasflag((int)this.scrollDirection, (int)PsdLayerVirtualViewScrollDirection.Vertical))
this.scrolledPos.y += delta.y;
}
private void UpdateScrollPos(Vector2 pos)
{
if (Util.Hasflag((int)this.scrollDirection, (int)PsdLayerVirtualViewScrollDirection.Horizontal))
this.scrolledPos.x = pos.x;
if (Util.Hasflag((int)this.scrollDirection, (int)PsdLayerVirtualViewScrollDirection.Vertical))
this.scrolledPos.y = pos.y;
}
private void Scroll()
{
this.itemStartIndex = 0;
if ((this.currentRowIndex + 1) > this.actualRowCount)
{
var outDelta = this.OutOfBoundsDelta;
if (outDelta == Vector2.zero)
{
var s = this.ItemSize;
if (s.y != 0)
{
var y = Mathf.FloorToInt(this.scrolledPos.y / s.y);
if (y != 0)
{
var yy = Mathf.Abs(y);
this.itemStartIndex = yy * this.colCount;
}
}
}
else if (outDelta.y > 0)
{
var s = this.ItemSize;
if (s.y != 0)
{
var y = Mathf.FloorToInt((this.ScrollArea.height - this.ViewArea.height) / s.y);
if (y != 0)
{
var yy = Mathf.Abs(y);
this.itemStartIndex = yy * this.colCount;
}
}
}
else if (outDelta.y < 0)
this.itemStartIndex = 0;
}
//Debug.Log (this.itemStartIndex +", "+ this.itemStartIndexOld);
var refresh = this.itemStartIndex != this.itemStartIndexOld;
var posMaker = new ItemPositionMaker(this);
var itemIndex = this.itemStartIndex;
var slotIndex = 0;
foreach (var slot in this.slots)
{
if (slot.Visibled = itemIndex < this.items.Count)
{
var item = this.items[itemIndex];
{
slot.Pos = posMaker.NextPos;
slot.Item = item;
if (refresh)
{
if (this.OnUpdateSlot != null)
{
this.OnUpdateSlot(
slot.InstanceOfCustomSlotManager, item, slotIndex, itemIndex);
}
}
}
slotIndex++;
}
if (++itemIndex >= this.items.Count && this.circulation)
itemIndex = 0;
}
if (refresh)
this.itemStartIndexOld = this.itemStartIndex;
}
private void PlaySpringBreak()
{
var pos = this.scrolledPos;
var end = this.OutOfBoundsDelta;
this.tweener.Stop();
this.tweener.Play(this, 0.35f, true,
delegate(float percentage)
{
var v = iTweenSimple.easeOutCubic(0, 1, percentage);
this.UpdateScrollPos(pos - v * end);
this.Scroll();
} ,
delegate(bool compelete)
{
if (this.OnSpringAnimationFinished != null)
this.OnSpringAnimationFinished();
}
);
}
private void PlayMagnetBreak()
{
//**??
// var h = this.RowHeight;
// var standard = h * this.magnetSensitive;
//
// var upward = this.lastVelocity >= 0;
// var gap = 0f;
// {
// this.SetVerticalEndPosition(upward);
// gap = h - Mathf.Abs(this.slots[0].distanceToEnd.y);
// }
// if (Mathf.Abs(gap) <= 0.001f)
// return;
//
// this.SetStartPositionByCurrentPosition();
//
// var gotoOrigin = gap < standard;
// if (gotoOrigin)
// this.SetVerticalEndPosition(!upward);
//
// var to = this.slots[0].distanceToEnd.y;
// var time = this.magnetAnimationTime > 0 ? this.magnetAnimationTime : 0.01f;
//
// this.tweener.Stop();
// this.tweener.Play(this, time, true,
// delegate(float percentage){
// var v = iTweenSimple.easeOutSine(0, to, percentage);
// this.Scroll(new Vector2(0, v), false);
//
// if (this.tweener.AnimationTime != this.magnetAnimationTime)
// this.tweener.AnimationTime = this.magnetAnimationTime;
// }
// , delegate(bool compelete){
// this.SetStartPositionByMap();
//
// if (this.OnMagnetAnimationFinished != null)
// this.OnMagnetAnimationFinished();
// }
// );
}
};
| |
namespace java.util.prefs
{
[global::MonoJavaBridge.JavaClass(typeof(global::java.util.prefs.Preferences_))]
public abstract partial class Preferences : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected Preferences(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public abstract global::java.lang.String name();
private static global::MonoJavaBridge.MethodId _m1;
public abstract global::java.util.prefs.Preferences parent();
private static global::MonoJavaBridge.MethodId _m2;
public abstract global::java.lang.String get(java.lang.String arg0, java.lang.String arg1);
private static global::MonoJavaBridge.MethodId _m3;
public abstract void put(java.lang.String arg0, java.lang.String arg1);
private static global::MonoJavaBridge.MethodId _m4;
public abstract global::java.lang.String toString();
private static global::MonoJavaBridge.MethodId _m5;
public abstract bool getBoolean(java.lang.String arg0, bool arg1);
private static global::MonoJavaBridge.MethodId _m6;
public abstract void putBoolean(java.lang.String arg0, bool arg1);
private static global::MonoJavaBridge.MethodId _m7;
public abstract int getInt(java.lang.String arg0, int arg1);
private static global::MonoJavaBridge.MethodId _m8;
public abstract void putInt(java.lang.String arg0, int arg1);
private static global::MonoJavaBridge.MethodId _m9;
public abstract long getLong(java.lang.String arg0, long arg1);
private static global::MonoJavaBridge.MethodId _m10;
public abstract void putLong(java.lang.String arg0, long arg1);
private static global::MonoJavaBridge.MethodId _m11;
public abstract float getFloat(java.lang.String arg0, float arg1);
private static global::MonoJavaBridge.MethodId _m12;
public abstract void putFloat(java.lang.String arg0, float arg1);
private static global::MonoJavaBridge.MethodId _m13;
public abstract double getDouble(java.lang.String arg0, double arg1);
private static global::MonoJavaBridge.MethodId _m14;
public abstract void putDouble(java.lang.String arg0, double arg1);
private static global::MonoJavaBridge.MethodId _m15;
public abstract void clear();
private static global::MonoJavaBridge.MethodId _m16;
public abstract void remove(java.lang.String arg0);
private static global::MonoJavaBridge.MethodId _m17;
public abstract global::java.lang.String[] keys();
private static global::MonoJavaBridge.MethodId _m18;
public abstract void flush();
private static global::MonoJavaBridge.MethodId _m19;
public abstract void sync();
private static global::MonoJavaBridge.MethodId _m20;
public abstract void putByteArray(java.lang.String arg0, byte[] arg1);
private static global::MonoJavaBridge.MethodId _m21;
public abstract byte[] getByteArray(java.lang.String arg0, byte[] arg1);
private static global::MonoJavaBridge.MethodId _m22;
public abstract global::java.util.prefs.Preferences node(java.lang.String arg0);
private static global::MonoJavaBridge.MethodId _m23;
public abstract global::java.lang.String absolutePath();
private static global::MonoJavaBridge.MethodId _m24;
public abstract global::java.lang.String[] childrenNames();
private static global::MonoJavaBridge.MethodId _m25;
public abstract bool nodeExists(java.lang.String arg0);
private static global::MonoJavaBridge.MethodId _m26;
public abstract void removeNode();
private static global::MonoJavaBridge.MethodId _m27;
public abstract bool isUserNode();
private static global::MonoJavaBridge.MethodId _m28;
public abstract void addPreferenceChangeListener(java.util.prefs.PreferenceChangeListener arg0);
private static global::MonoJavaBridge.MethodId _m29;
public abstract void removePreferenceChangeListener(java.util.prefs.PreferenceChangeListener arg0);
private static global::MonoJavaBridge.MethodId _m30;
public abstract void addNodeChangeListener(java.util.prefs.NodeChangeListener arg0);
private static global::MonoJavaBridge.MethodId _m31;
public abstract void removeNodeChangeListener(java.util.prefs.NodeChangeListener arg0);
private static global::MonoJavaBridge.MethodId _m32;
public abstract void exportNode(java.io.OutputStream arg0);
private static global::MonoJavaBridge.MethodId _m33;
public abstract void exportSubtree(java.io.OutputStream arg0);
private static global::MonoJavaBridge.MethodId _m34;
public static global::java.util.prefs.Preferences userNodeForPackage(java.lang.Class arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.util.prefs.Preferences._m34.native == global::System.IntPtr.Zero)
global::java.util.prefs.Preferences._m34 = @__env.GetStaticMethodIDNoThrow(global::java.util.prefs.Preferences.staticClass, "userNodeForPackage", "(Ljava/lang/Class;)Ljava/util/prefs/Preferences;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.util.prefs.Preferences.staticClass, global::java.util.prefs.Preferences._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.util.prefs.Preferences;
}
private static global::MonoJavaBridge.MethodId _m35;
public static global::java.util.prefs.Preferences systemNodeForPackage(java.lang.Class arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.util.prefs.Preferences._m35.native == global::System.IntPtr.Zero)
global::java.util.prefs.Preferences._m35 = @__env.GetStaticMethodIDNoThrow(global::java.util.prefs.Preferences.staticClass, "systemNodeForPackage", "(Ljava/lang/Class;)Ljava/util/prefs/Preferences;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.util.prefs.Preferences.staticClass, global::java.util.prefs.Preferences._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.util.prefs.Preferences;
}
private static global::MonoJavaBridge.MethodId _m36;
public static global::java.util.prefs.Preferences userRoot()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.util.prefs.Preferences._m36.native == global::System.IntPtr.Zero)
global::java.util.prefs.Preferences._m36 = @__env.GetStaticMethodIDNoThrow(global::java.util.prefs.Preferences.staticClass, "userRoot", "()Ljava/util/prefs/Preferences;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.util.prefs.Preferences.staticClass, global::java.util.prefs.Preferences._m36)) as java.util.prefs.Preferences;
}
private static global::MonoJavaBridge.MethodId _m37;
public static global::java.util.prefs.Preferences systemRoot()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.util.prefs.Preferences._m37.native == global::System.IntPtr.Zero)
global::java.util.prefs.Preferences._m37 = @__env.GetStaticMethodIDNoThrow(global::java.util.prefs.Preferences.staticClass, "systemRoot", "()Ljava/util/prefs/Preferences;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.util.prefs.Preferences.staticClass, global::java.util.prefs.Preferences._m37)) as java.util.prefs.Preferences;
}
private static global::MonoJavaBridge.MethodId _m38;
public static void importPreferences(java.io.InputStream arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.util.prefs.Preferences._m38.native == global::System.IntPtr.Zero)
global::java.util.prefs.Preferences._m38 = @__env.GetStaticMethodIDNoThrow(global::java.util.prefs.Preferences.staticClass, "importPreferences", "(Ljava/io/InputStream;)V");
@__env.CallStaticVoidMethod(java.util.prefs.Preferences.staticClass, global::java.util.prefs.Preferences._m38, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m39;
protected Preferences() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.util.prefs.Preferences._m39.native == global::System.IntPtr.Zero)
global::java.util.prefs.Preferences._m39 = @__env.GetMethodIDNoThrow(global::java.util.prefs.Preferences.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.prefs.Preferences.staticClass, global::java.util.prefs.Preferences._m39);
Init(@__env, handle);
}
public static int MAX_KEY_LENGTH
{
get
{
return 80;
}
}
public static int MAX_VALUE_LENGTH
{
get
{
return 8192;
}
}
public static int MAX_NAME_LENGTH
{
get
{
return 80;
}
}
static Preferences()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.util.prefs.Preferences.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/util/prefs/Preferences"));
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::java.util.prefs.Preferences))]
internal sealed partial class Preferences_ : java.util.prefs.Preferences
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal Preferences_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public override global::java.lang.String name()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.util.prefs.Preferences_.staticClass, "name", "()Ljava/lang/String;", ref global::java.util.prefs.Preferences_._m0) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m1;
public override global::java.util.prefs.Preferences parent()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.prefs.Preferences_.staticClass, "parent", "()Ljava/util/prefs/Preferences;", ref global::java.util.prefs.Preferences_._m1) as java.util.prefs.Preferences;
}
private static global::MonoJavaBridge.MethodId _m2;
public override global::java.lang.String get(java.lang.String arg0, java.lang.String arg1)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.util.prefs.Preferences_.staticClass, "get", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", ref global::java.util.prefs.Preferences_._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m3;
public override void put(java.lang.String arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.prefs.Preferences_.staticClass, "put", "(Ljava/lang/String;Ljava/lang/String;)V", ref global::java.util.prefs.Preferences_._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m4;
public override global::java.lang.String toString()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.util.prefs.Preferences_.staticClass, "toString", "()Ljava/lang/String;", ref global::java.util.prefs.Preferences_._m4) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m5;
public override bool getBoolean(java.lang.String arg0, bool arg1)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.prefs.Preferences_.staticClass, "getBoolean", "(Ljava/lang/String;Z)Z", ref global::java.util.prefs.Preferences_._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m6;
public override void putBoolean(java.lang.String arg0, bool arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.prefs.Preferences_.staticClass, "putBoolean", "(Ljava/lang/String;Z)V", ref global::java.util.prefs.Preferences_._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m7;
public override int getInt(java.lang.String arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.prefs.Preferences_.staticClass, "getInt", "(Ljava/lang/String;I)I", ref global::java.util.prefs.Preferences_._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m8;
public override void putInt(java.lang.String arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.prefs.Preferences_.staticClass, "putInt", "(Ljava/lang/String;I)V", ref global::java.util.prefs.Preferences_._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m9;
public override long getLong(java.lang.String arg0, long arg1)
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.util.prefs.Preferences_.staticClass, "getLong", "(Ljava/lang/String;J)J", ref global::java.util.prefs.Preferences_._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m10;
public override void putLong(java.lang.String arg0, long arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.prefs.Preferences_.staticClass, "putLong", "(Ljava/lang/String;J)V", ref global::java.util.prefs.Preferences_._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m11;
public override float getFloat(java.lang.String arg0, float arg1)
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::java.util.prefs.Preferences_.staticClass, "getFloat", "(Ljava/lang/String;F)F", ref global::java.util.prefs.Preferences_._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m12;
public override void putFloat(java.lang.String arg0, float arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.prefs.Preferences_.staticClass, "putFloat", "(Ljava/lang/String;F)V", ref global::java.util.prefs.Preferences_._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m13;
public override double getDouble(java.lang.String arg0, double arg1)
{
return global::MonoJavaBridge.JavaBridge.CallDoubleMethod(this, global::java.util.prefs.Preferences_.staticClass, "getDouble", "(Ljava/lang/String;D)D", ref global::java.util.prefs.Preferences_._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m14;
public override void putDouble(java.lang.String arg0, double arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.prefs.Preferences_.staticClass, "putDouble", "(Ljava/lang/String;D)V", ref global::java.util.prefs.Preferences_._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m15;
public override void clear()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.prefs.Preferences_.staticClass, "clear", "()V", ref global::java.util.prefs.Preferences_._m15);
}
private static global::MonoJavaBridge.MethodId _m16;
public override void remove(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.prefs.Preferences_.staticClass, "remove", "(Ljava/lang/String;)V", ref global::java.util.prefs.Preferences_._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m17;
public override global::java.lang.String[] keys()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.String>(this, global::java.util.prefs.Preferences_.staticClass, "keys", "()[Ljava/lang/String;", ref global::java.util.prefs.Preferences_._m17) as java.lang.String[];
}
private static global::MonoJavaBridge.MethodId _m18;
public override void flush()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.prefs.Preferences_.staticClass, "flush", "()V", ref global::java.util.prefs.Preferences_._m18);
}
private static global::MonoJavaBridge.MethodId _m19;
public override void sync()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.prefs.Preferences_.staticClass, "sync", "()V", ref global::java.util.prefs.Preferences_._m19);
}
private static global::MonoJavaBridge.MethodId _m20;
public override void putByteArray(java.lang.String arg0, byte[] arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.prefs.Preferences_.staticClass, "putByteArray", "(Ljava/lang/String;[B)V", ref global::java.util.prefs.Preferences_._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m21;
public override byte[] getByteArray(java.lang.String arg0, byte[] arg1)
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<byte>(this, global::java.util.prefs.Preferences_.staticClass, "getByteArray", "(Ljava/lang/String;[B)[B", ref global::java.util.prefs.Preferences_._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as byte[];
}
private static global::MonoJavaBridge.MethodId _m22;
public override global::java.util.prefs.Preferences node(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.prefs.Preferences_.staticClass, "node", "(Ljava/lang/String;)Ljava/util/prefs/Preferences;", ref global::java.util.prefs.Preferences_._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.util.prefs.Preferences;
}
private static global::MonoJavaBridge.MethodId _m23;
public override global::java.lang.String absolutePath()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.util.prefs.Preferences_.staticClass, "absolutePath", "()Ljava/lang/String;", ref global::java.util.prefs.Preferences_._m23) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m24;
public override global::java.lang.String[] childrenNames()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.String>(this, global::java.util.prefs.Preferences_.staticClass, "childrenNames", "()[Ljava/lang/String;", ref global::java.util.prefs.Preferences_._m24) as java.lang.String[];
}
private static global::MonoJavaBridge.MethodId _m25;
public override bool nodeExists(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.prefs.Preferences_.staticClass, "nodeExists", "(Ljava/lang/String;)Z", ref global::java.util.prefs.Preferences_._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m26;
public override void removeNode()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.prefs.Preferences_.staticClass, "removeNode", "()V", ref global::java.util.prefs.Preferences_._m26);
}
private static global::MonoJavaBridge.MethodId _m27;
public override bool isUserNode()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.prefs.Preferences_.staticClass, "isUserNode", "()Z", ref global::java.util.prefs.Preferences_._m27);
}
private static global::MonoJavaBridge.MethodId _m28;
public override void addPreferenceChangeListener(java.util.prefs.PreferenceChangeListener arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.prefs.Preferences_.staticClass, "addPreferenceChangeListener", "(Ljava/util/prefs/PreferenceChangeListener;)V", ref global::java.util.prefs.Preferences_._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m29;
public override void removePreferenceChangeListener(java.util.prefs.PreferenceChangeListener arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.prefs.Preferences_.staticClass, "removePreferenceChangeListener", "(Ljava/util/prefs/PreferenceChangeListener;)V", ref global::java.util.prefs.Preferences_._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m30;
public override void addNodeChangeListener(java.util.prefs.NodeChangeListener arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.prefs.Preferences_.staticClass, "addNodeChangeListener", "(Ljava/util/prefs/NodeChangeListener;)V", ref global::java.util.prefs.Preferences_._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m31;
public override void removeNodeChangeListener(java.util.prefs.NodeChangeListener arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.prefs.Preferences_.staticClass, "removeNodeChangeListener", "(Ljava/util/prefs/NodeChangeListener;)V", ref global::java.util.prefs.Preferences_._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m32;
public override void exportNode(java.io.OutputStream arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.prefs.Preferences_.staticClass, "exportNode", "(Ljava/io/OutputStream;)V", ref global::java.util.prefs.Preferences_._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m33;
public override void exportSubtree(java.io.OutputStream arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.prefs.Preferences_.staticClass, "exportSubtree", "(Ljava/io/OutputStream;)V", ref global::java.util.prefs.Preferences_._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
static Preferences_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.util.prefs.Preferences_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/util/prefs/Preferences"));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using Mvc.JQuery.DataTables.Reflection;
namespace Mvc.JQuery.DataTables
{
static class TypeFilters
{
private static readonly Func<string, Type, object> ParseValue =
(input, t) => t.GetTypeInfo().IsEnum ? Enum.Parse(t, input) : Convert.ChangeType(input, t);
internal static string FilterMethod(string q, List<object> parametersForLinqQuery, Type type)
{
Func<string, string, string> makeClause = (method, query) =>
{
parametersForLinqQuery.Add(ParseValue(query, type));
var indexOfParameter = parametersForLinqQuery.Count - 1;
return string.Format("{0}(@{1})", method, indexOfParameter);
};
if (q.StartsWith("^"))
{
if (q.EndsWith("$"))
{
parametersForLinqQuery.Add(ParseValue(q.Substring(1, q.Length - 2), type));
var indexOfParameter = parametersForLinqQuery.Count - 1;
return string.Format("Equals((object)@{0})", indexOfParameter);
}
return makeClause("StartsWith", q.Substring(1));
}
else
{
if (q.EndsWith("$"))
{
return makeClause("EndsWith", q.Substring(0, q.Length - 1));
}
return makeClause("Contains", q);
}
}
public static string NumericFilter(string query, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery)
{
if (query.StartsWith("^")) query = query.TrimStart('^');
if (query.EndsWith("$")) query = query.TrimEnd('$');
if (query == "~") return string.Empty;
if (query.Contains("~"))
{
var parts = query.Split('~');
var clause = null as string;
try
{
parametersForLinqQuery.Add(ChangeType(propertyInfo, parts[0]));
clause = string.Format("{0} >= @{1}", columnname, parametersForLinqQuery.Count - 1);
}
catch (FormatException)
{
}
try
{
parametersForLinqQuery.Add(ChangeType(propertyInfo, parts[1]));
if (clause != null) clause += " and ";
clause += string.Format("{0} <= @{1}", columnname, parametersForLinqQuery.Count - 1);
}
catch (FormatException)
{
}
return clause ?? "true";
}
else
{
try
{
parametersForLinqQuery.Add(ChangeType(propertyInfo, query));
return string.Format("{0} == @{1}", columnname, parametersForLinqQuery.Count - 1);
}
catch (FormatException)
{
}
return null;
}
}
private static object ChangeType(DataTablesPropertyInfo propertyInfo, string query)
{
if (propertyInfo.PropertyInfo.PropertyType.GetTypeInfo().IsGenericType && propertyInfo.Type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
Type u = Nullable.GetUnderlyingType(propertyInfo.Type);
return Convert.ChangeType(query, u);
}
else
{
return Convert.ChangeType(query, propertyInfo.Type);
}
}
public static string DateTimeOffsetFilter(string query, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery)
{
if (query == "~") return string.Empty;
var filterString = null as string;
if (query.Contains("~"))
{
var parts = query.Split('~');
DateTimeOffset start, end;
if (DateTimeOffset.TryParse(parts[0] ?? "", out start))
{
start = start.ToUniversalTime();
filterString = columnname + " >= @" + parametersForLinqQuery.Count;
parametersForLinqQuery.Add(start);
}
if (DateTimeOffset.TryParse(parts[1] ?? "", out end))
{
end = end.ToUniversalTime();
filterString = (filterString == null ? null : filterString + " and ") + columnname + " <= @" + parametersForLinqQuery.Count;
parametersForLinqQuery.Add(end);
}
return filterString ?? "";
}
else
{
DateTimeOffset dateTime;
if (DateTimeOffset.TryParse(query, out dateTime))
{
if (dateTime.Date == dateTime)
{
dateTime = dateTime.ToUniversalTime();
parametersForLinqQuery.Add(dateTime);
parametersForLinqQuery.Add(dateTime.AddDays(1));
filterString = string.Format("{0} >= @{1} and {0} < @{2}", columnname, parametersForLinqQuery.Count - 2, parametersForLinqQuery.Count - 1);
}
else
{
dateTime = dateTime.ToUniversalTime();
filterString = string.Format("{0} == @" + parametersForLinqQuery.Count, columnname);
parametersForLinqQuery.Add(dateTime);
}
}
return filterString;
}
}
public static string DateTimeFilter(string query, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery)
{
if (query == "~") return string.Empty;
var filterString = null as string;
if (query.Contains("~"))
{
var parts = query.Split('~');
DateTime start, end;
if (DateTime.TryParse(parts[0] ?? "", out start))
{
start = start.ToUniversalTime();
filterString = columnname + " >= @" + parametersForLinqQuery.Count;
parametersForLinqQuery.Add(start);
}
if (DateTime.TryParse(parts[1] ?? "", out end))
{
end = end.ToUniversalTime();
filterString = (filterString == null ? null : filterString + " and ") + columnname + " <= @" + parametersForLinqQuery.Count;
parametersForLinqQuery.Add(end);
}
return filterString ?? "";
}
else
{
DateTime dateTime;
if (DateTime.TryParse(query, out dateTime))
{
if (dateTime.Date == dateTime)
{
dateTime = dateTime.ToUniversalTime();
parametersForLinqQuery.Add(dateTime);
parametersForLinqQuery.Add(dateTime.AddDays(1));
filterString = string.Format("({0} >= @{1} and {0} < @{2})", columnname, parametersForLinqQuery.Count - 2, parametersForLinqQuery.Count - 1);
}
else
{
dateTime = dateTime.ToUniversalTime();
filterString = string.Format("{0} == @" + parametersForLinqQuery.Count, columnname);
parametersForLinqQuery.Add(dateTime);
}
}
return filterString;
}
}
public static string BoolFilter(string query, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery)
{
if (query != null)
query = query.TrimStart('^').TrimEnd('$');
var lowerCaseQuery = query.ToLowerInvariant();
if (lowerCaseQuery == "false" || lowerCaseQuery == "true")
{
if (query.ToLower() == "true") return columnname + " == true";
return columnname + " == false";
}
if (propertyInfo.Type == typeof(bool?))
{
if (lowerCaseQuery == "null") return columnname + " == null";
}
return null;
}
public static string StringFilter(string q, string columnname, DataTablesPropertyInfo columntype, List<object> parametersforlinqquery)
{
if (q == ".*") return "";
if (q.StartsWith("^"))
{
if (q.EndsWith("$"))
{
parametersforlinqquery.Add(q.Substring(1, q.Length - 2));
var parameterArg = "@" + (parametersforlinqquery.Count - 1);
return string.Format("{0} == {1}", columnname, parameterArg);
}
else
{
parametersforlinqquery.Add(q.Substring(1));
var parameterArg = "@" + (parametersforlinqquery.Count - 1);
return string.Format("({0} != null && {0} != \"\" && ({0} == {1} || {0}.StartsWith({1})))", columnname, parameterArg);
}
}
else
{
parametersforlinqquery.Add(q);
var parameterArg = "@" + (parametersforlinqquery.Count - 1);
//return string.Format("{0} == {1}", columnname, parameterArg);
return
string.Format(
"({0} != null && {0} != \"\" && ({0} == {1} || {0}.StartsWith({1}) || {0}.Contains({1})))",
columnname, parameterArg);
}
}
public static string EnumFilter(string q, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery)
{
try
{
if (q.StartsWith("^")) q = q.Substring(1);
if (q.EndsWith("$")) q = q.Substring(0, q.Length - 1);
parametersForLinqQuery.Add(ParseValue(q, propertyInfo.Type));
return columnname + " == @" + (parametersForLinqQuery.Count - 1);
}
catch (Exception)
{
return null;
}
}
}
}
| |
#region Copyright
//
// This framework is based on log4j see http://jakarta.apache.org/log4j
// Copyright (C) The Apache Software Foundation. All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.txt file.
//
#endregion
using System;
using System.Reflection;
using log4net.spi;
using log4net.Repository;
namespace log4net
{
/// <summary>
/// This is the class used by client applications to bind to logger
/// instances.
/// </summary>
/// <remarks>
/// <para>
/// See the <see cref="ILog"/> interface for more details.
/// </para>
/// <para>
/// log4net uses NUnit 2.0 to provide internal unit testing.
/// To run the tests you will need a copy of NUnit 2.0. Then
/// run the following command:
/// </para>
/// <code>nunit-console.exe /assembly:<log4net assembly></code>
/// </remarks>
/// <example>Simple example of logging messages
/// <code>
/// ILog log = LogManager.GetLogger("application-log");
///
/// log.Info("Application Start");
/// log.Debug("This is a debug message");
///
/// if (log.IsDebugEnabled)
/// {
/// log.Debug("This is another debug message");
/// }
/// </code>
/// </example>
/// <seealso cref="ILog"/>
public sealed class LogManager
{
#region Private Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="LogManager" /> class.
/// </summary>
/// <remarks>
/// Uses a private access modifier to prevent instantiation of this class.
/// </remarks>
private LogManager()
{
}
#endregion Private Instance Constructors
#region Type Specific Manager Methods
/// <summary>
/// Returns the named logger if it exists.
/// </summary>
/// <remarks>
/// <para>
/// If the named logger exists (in the default hierarchy) then it
/// returns a reference to the logger, otherwise it returns
/// <c>null</c>.
/// </para>
/// </remarks>
/// <param name="name">The fully qualified logger name to look for.</param>
/// <returns>The logger found, or <c>null</c> if no logger could be found.</returns>
public static ILog Exists(string name)
{
return Exists(Assembly.GetCallingAssembly(), name);
}
/// <summary>
/// Returns the named logger if it exists.
/// </summary>
/// <remarks>
/// <para>
/// If the named logger exists (in the specified domain) then it
/// returns a reference to the logger, otherwise it returns
/// <c>null</c>.
/// </para>
/// </remarks>
/// <param name="domain">The domain to lookup in.</param>
/// <param name="name">The fully qualified logger name to look for.</param>
/// <returns>
/// The logger found, or <c>null</c> if the logger doesn't exist in the specified
/// domain.
/// </returns>
public static ILog Exists(string domain, string name)
{
return WrapLogger(LoggerManager.Exists(domain, name));
}
/// <summary>
/// Returns the named logger if it exists.
/// </summary>
/// <param name="domainAssembly">The assembly to use to lookup the domain.</param>
/// <param name="name">The fully qualified logger name to look for.</param>
/// <returns>
/// The logger, or <c>null</c> if the logger doesn't exist in the specified
/// assembly's domain.
/// </returns>
public static ILog Exists(Assembly domainAssembly, string name)
{
return WrapLogger(LoggerManager.Exists(domainAssembly, name));
}
/// <summary>
/// Returns all the currently defined loggers in the default domain.
/// </summary>
/// <remarks>
/// <para>The root logger is <b>not</b> included in the returned array.</para>
/// </remarks>
/// <returns>All the defined loggers.</returns>
public static ILog[] GetCurrentLoggers()
{
return GetCurrentLoggers(Assembly.GetCallingAssembly());
}
/// <summary>
/// Returns all the currently defined loggers in the specified domain.
/// </summary>
/// <param name="domain">The domain to lookup in.</param>
/// <remarks>
/// The root logger is <b>not</b> included in the returned array.
/// </remarks>
/// <returns>All the defined loggers.</returns>
public static ILog[] GetCurrentLoggers(string domain)
{
return WrapLoggers(LoggerManager.GetCurrentLoggers(domain));
}
/// <summary>
/// Returns all the currently defined loggers in the specified assembly's domain.
/// </summary>
/// <param name="domainAssembly">The assembly to use to lookup the domain.</param>
/// <remarks>
/// The root logger is <b>not</b> included in the returned array.
/// </remarks>
/// <returns>All the defined loggers.</returns>
public static ILog[] GetCurrentLoggers(Assembly domainAssembly)
{
return WrapLoggers(LoggerManager.GetCurrentLoggers(domainAssembly));
}
/// <summary>
/// Retrieves or creates a named logger.
/// </summary>
/// <remarks>
/// <para>
/// Retrieves a logger named as the <paramref name="name"/>
/// parameter. If the named logger already exists, then the
/// existing instance will be returned. Otherwise, a new instance is
/// created.
/// </para>
/// <para>By default, loggers do not have a set level but inherit
/// it from the hierarchy. This is one of the central features of
/// log4net.
/// </para>
/// </remarks>
/// <param name="name">The name of the logger to retrieve.</param>
/// <returns>The logger with the name specified.</returns>
public static ILog GetLogger(string name)
{
return GetLogger(Assembly.GetCallingAssembly(), name);
}
/// <summary>
/// Retrieves or creates a named logger.
/// </summary>
/// <remarks>
/// <para>
/// Retrieve a logger named as the <paramref name="name"/>
/// parameter. If the named logger already exists, then the
/// existing instance will be returned. Otherwise, a new instance is
/// created.
/// </para>
/// <para>
/// By default, loggers do not have a set level but inherit
/// it from the hierarchy. This is one of the central features of
/// log4net.
/// </para>
/// </remarks>
/// <param name="domain">The domain to lookup in.</param>
/// <param name="name">The name of the logger to retrieve.</param>
/// <returns>The logger with the name specified.</returns>
public static ILog GetLogger(string domain, string name)
{
return WrapLogger(LoggerManager.GetLogger(domain, name));
}
/// <summary>
/// Retrieves or creates a named logger.
/// </summary>
/// <remarks>
/// <para>
/// Retrieve a logger named as the <paramref name="name"/>
/// parameter. If the named logger already exists, then the
/// existing instance will be returned. Otherwise, a new instance is
/// created.
/// </para>
/// <para>
/// By default, loggers do not have a set level but inherit
/// it from the hierarchy. This is one of the central features of
/// log4net.
/// </para>
/// </remarks>
/// <param name="domainAssembly">The assembly to use to lookup the domain.</param>
/// <param name="name">The name of the logger to retrieve.</param>
/// <returns>The logger with the name specified.</returns>
public static ILog GetLogger(Assembly domainAssembly, string name)
{
return WrapLogger(LoggerManager.GetLogger(domainAssembly, name));
}
/// <summary>
/// Shorthand for <see cref="LogManager.GetLogger(string)"/>.
/// </summary>
/// <remarks>
/// Get the logger for the fully qualified name of the type specified.
/// </remarks>
/// <param name="type">The full name of <paramref name="type"/> will be used as the name of the logger to retrieve.</param>
/// <returns>The logger with the name specified.</returns>
public static ILog GetLogger(Type type)
{
return GetLogger(Assembly.GetCallingAssembly(), type.FullName);
}
/// <summary>
/// Shorthand for <see cref="LogManager.GetLogger(string)"/>.
/// </summary>
/// <remarks>
/// Gets the logger for the fully qualified name of the type specified.
/// </remarks>
/// <param name="domain">The domain to lookup in.</param>
/// <param name="type">The full name of <paramref name="type"/> will be used as the name of the logger to retrieve.</param>
/// <returns>The logger with the name specified.</returns>
public static ILog GetLogger(string domain, Type type)
{
return WrapLogger(LoggerManager.GetLogger(domain, type));
}
/// <summary>
/// Shorthand for <see cref="LogManager.GetLogger(string)"/>.
/// </summary>
/// <remarks>
/// Gets the logger for the fully qualified name of the type specified.
/// </remarks>
/// <param name="domainAssembly">The assembly to use to lookup the domain.</param>
/// <param name="type">The full name of <paramref name="type"/> will be used as the name of the logger to retrieve.</param>
/// <returns>The logger with the name specified.</returns>
public static ILog GetLogger(Assembly domainAssembly, Type type)
{
return WrapLogger(LoggerManager.GetLogger(domainAssembly, type));
}
#endregion Type Specific Manager Methods
#region Domain & Repository Manager Methods
/// <summary>
/// Shuts down the log4net system.
/// </summary>
/// <remarks>
/// <para>
/// Calling this method will <b>safely</b> close and remove all
/// appenders in all the loggers including root contained in all the
/// default repositories.
/// </para>
/// <para>
/// Some appenders need to be closed before the application exists.
/// Otherwise, pending logging events might be lost.
/// </para>
/// <para>The <c>shutdown</c> method is careful to close nested
/// appenders before closing regular appenders. This is allows
/// configurations where a regular appender is attached to a logger
/// and again to a nested appender.
/// </para>
/// </remarks>
public static void Shutdown()
{
LoggerManager.Shutdown();
}
/// <summary>
/// Shuts down the default repository.
/// </summary>
/// <remarks>
/// <para>
/// Calling this method will <b>safely</b> close and remove all
/// appenders in all the loggers including root contained in the
/// default repository.
/// </para>
/// <para>Some appenders need to be closed before the application exists.
/// Otherwise, pending logging events might be lost.
/// </para>
/// <para>The <c>shutdown</c> method is careful to close nested
/// appenders before closing regular appenders. This is allows
/// configurations where a regular appender is attached to a logger
/// and again to a nested appender.
/// </para>
/// </remarks>
public static void ShutdownRepository()
{
ShutdownRepository(Assembly.GetCallingAssembly());
}
/// <summary>
/// Shuts down the repository for the domain specified.
/// </summary>
/// <remarks>
/// <para>
/// Calling this method will <b>safely</b> close and remove all
/// appenders in all the loggers including root contained in the
/// repository for the <paramref name="domain"/> specified.
/// </para>
/// <para>
/// Some appenders need to be closed before the application exists.
/// Otherwise, pending logging events might be lost.
/// </para>
/// <para>The <c>shutdown</c> method is careful to close nested
/// appenders before closing regular appenders. This is allows
/// configurations where a regular appender is attached to a logger
/// and again to a nested appender.
/// </para>
/// </remarks>
/// <param name="domain">The domain to shutdown.</param>
public static void ShutdownRepository(string domain)
{
LoggerManager.ShutdownRepository(domain);
}
/// <summary>
/// Shuts down the repository for the domain specified.
/// </summary>
/// <remarks>
/// <para>
/// Calling this method will <b>safely</b> close and remove all
/// appenders in all the loggers including root contained in the
/// repository for the domain. The domain is looked up using
/// the <paramref name="domainAssembly"/> specified.
/// </para>
/// <para>
/// Some appenders need to be closed before the application exists.
/// Otherwise, pending logging events might be lost.
/// </para>
/// <para>
/// The <c>shutdown</c> method is careful to close nested
/// appenders before closing regular appenders. This is allows
/// configurations where a regular appender is attached to a logger
/// and again to a nested appender.
/// </para>
/// </remarks>
/// <param name="domainAssembly">The assembly to use to lookup the domain.</param>
public static void ShutdownRepository(Assembly domainAssembly)
{
LoggerManager.ShutdownRepository(domainAssembly);
}
/// <summary>
/// Resets all values contained in this repository instance to their defaults.
/// </summary>
/// <remarks>
/// <para>
/// Resets all values contained in the repository instance to their
/// defaults. This removes all appenders from all loggers, sets
/// the level of all non-root loggers to <c>null</c>,
/// sets their additivity flag to <c>true</c> and sets the level
/// of the root logger to <see cref="Level.DEBUG"/>. Moreover,
/// message disabling is set to its default "off" value.
/// </para>
/// </remarks>
public static void ResetConfiguration()
{
ResetConfiguration(Assembly.GetCallingAssembly());
}
/// <summary>
/// Resets all values contained in this repository instance to their defaults.
/// </summary>
/// <remarks>
/// <para>
/// Reset all values contained in the repository instance to their
/// defaults. This removes all appenders from all loggers, sets
/// the level of all non-root loggers to <c>null</c>,
/// sets their additivity flag to <c>true</c> and sets the level
/// of the root logger to <see cref="Level.DEBUG"/>. Moreover,
/// message disabling is set to its default "off" value.
/// </para>
/// </remarks>
/// <param name="domain">The domain to lookup in.</param>
public static void ResetConfiguration(string domain)
{
LoggerManager.ResetConfiguration(domain);
}
/// <summary>
/// Resets all values contained in this repository instance to their defaults.
/// </summary>
/// <remarks>
/// <para>
/// Reset all values contained in the repository instance to their
/// defaults. This removes all appenders from all loggers, sets
/// the level of all non-root loggers to <c>null</c>,
/// sets their additivity flag to <c>true</c> and sets the level
/// of the root logger to <see cref="Level.DEBUG"/>. Moreover,
/// message disabling is set to its default "off" value.
/// </para>
/// </remarks>
/// <param name="domainAssembly">The assembly to use to lookup the domain.</param>
public static void ResetConfiguration(Assembly domainAssembly)
{
LoggerManager.ResetConfiguration(domainAssembly);
}
/// <summary>
/// Returns the default <see cref="ILoggerRepository"/> instance.
/// </summary>
/// <returns>The <see cref="ILoggerRepository"/> instance for the default domain.</returns>
/// <remarks>
/// <para>
/// Gets the <see cref="ILoggerRepository"/> for the domain specified
/// by the callers assembly (<see cref="Assembly.GetCallingAssembly()"/>).
/// </para>
/// </remarks>
public static ILoggerRepository GetLoggerRepository()
{
return GetLoggerRepository(Assembly.GetCallingAssembly());
}
/// <summary>
/// Returns the default <see cref="ILoggerRepository"/> instance.
/// </summary>
/// <param name="domain">The domain to lookup in.</param>
/// <returns>The default <see cref="ILoggerRepository"/> instance.</returns>
/// <remarks>
/// <para>
/// Gets the <see cref="ILoggerRepository"/> for the domain specified
/// by the <paramref name="domain"/> argument.
/// </para>
/// </remarks>
public static ILoggerRepository GetLoggerRepository(string domain)
{
return LoggerManager.GetLoggerRepository(domain);
}
/// <summary>
/// Returns the default <see cref="ILoggerRepository"/> instance.
/// </summary>
/// <param name="domainAssembly">The assembly to use to lookup the domain.</param>
/// <returns>The default <see cref="ILoggerRepository"/> instance.</returns>
/// <remarks>
/// <para>
/// Gets the <see cref="ILoggerRepository"/> for the domain specified
/// by the <paramref name="domainAssembly"/> argument.
/// </para>
/// </remarks>
public static ILoggerRepository GetLoggerRepository(Assembly domainAssembly)
{
return LoggerManager.GetLoggerRepository(domainAssembly);
}
/// <summary>
/// Creates a domain with the specified repository type.
/// </summary>
/// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/>
/// and has a no arg constructor. An instance of this type will be created to act
/// as the <see cref="ILoggerRepository"/> for the domain specified.</param>
/// <returns>The <see cref="ILoggerRepository"/> created for the domain.</returns>
/// <remarks>
/// <para>
/// The <see cref="ILoggerRepository"/> created will be associated with the domain
/// specified such that a call to <see cref="GetLoggerRepository()"/> will return
/// the same repository instance.
/// </para>
/// </remarks>
public static ILoggerRepository CreateDomain(Type repositoryType)
{
return CreateDomain(Assembly.GetCallingAssembly(), repositoryType);
}
/// <summary>
/// Creates a domain with the specified name.
/// </summary>
/// <param name="domain">The name of the domain, this must be unique amongst domain.</param>
/// <returns>The <see cref="ILoggerRepository"/> created for the domain.</returns>
/// <remarks>
/// <para>
/// Creates the default type of <see cref="ILoggerRepository"/> which is a
/// <see cref="log4net.Repository.Hierarchy.Hierarchy"/> object.
/// </para>
/// <para>
/// The <paramref name="domain"/> name must be unique. Domains cannot be redefined.
/// An <see cref="Exception"/> will be thrown if the domain already exists.
/// </para>
/// </remarks>
/// <exception cref="LogException">The specified domain already exists.</exception>
public static ILoggerRepository CreateDomain(string domain)
{
return LoggerManager.CreateDomain(domain);
}
/// <summary>
/// Creates a domain with the specified name and repository type.
/// </summary>
/// <param name="domain">The name of the domain, this must be unique to the domain.</param>
/// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/>
/// and has a no arg constructor. An instance of this type will be created to act
/// as the <see cref="ILoggerRepository"/> for the domain specified.</param>
/// <returns>The <see cref="ILoggerRepository"/> created for the domain.</returns>
/// <remarks>
/// <para>
/// The <paramref name="domain"/> name must be unique. Domains cannot be redefined.
/// An <see cref="Exception"/> will be thrown if the domain already exists.
/// </para>
/// </remarks>
/// <exception cref="LogException">The specified domain already exists.</exception>
public static ILoggerRepository CreateDomain(string domain, Type repositoryType)
{
return LoggerManager.CreateDomain(domain, repositoryType);
}
/// <summary>
/// Creates a domain for the specified assembly and repository type.
/// </summary>
/// <param name="domainAssembly">The assembly to use to get the name of the domain.</param>
/// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/>
/// and has a no arg constructor. An instance of this type will be created to act
/// as the <see cref="ILoggerRepository"/> for the domain specified.</param>
/// <returns>The <see cref="ILoggerRepository"/> created for the domain.</returns>
/// <remarks>
/// <para>
/// The <see cref="ILoggerRepository"/> created will be associated with the domain
/// specified such that a call to <see cref="GetLoggerRepository(Assembly)"/> with the
/// same assembly specified will return the same repository instance.
/// </para>
/// </remarks>
public static ILoggerRepository CreateDomain(Assembly domainAssembly, Type repositoryType)
{
return LoggerManager.CreateDomain(domainAssembly, repositoryType);
}
/// <summary>
/// Gets the list of currently defined repositories.
/// </summary>
/// <returns>An array of all the known <see cref="ILoggerRepository"/> objects.</returns>
public static ILoggerRepository[] GetAllRepositories()
{
return LoggerManager.GetAllRepositories();
}
#endregion Domain & Repository Manager Methods
#region Extension Handlers
/// <summary>
/// Looks up the wrapper object for the logger specified.
/// </summary>
/// <param name="logger">The logger to get the wrapper for.</param>
/// <returns>The wrapper for the logger specified.</returns>
public static ILog WrapLogger(ILogger logger)
{
return (ILog)s_wrapperMap[logger];
}
/// <summary>
/// Looks up the wrapper objects for the loggers specified.
/// </summary>
/// <param name="loggers">The loggers to get the wrappers for.</param>
/// <returns>The wrapper objects for the loggers specified.</returns>
public static ILog[] WrapLoggers(ILogger[] loggers)
{
ILog[] results = new ILog[loggers.Length];
for(int i=0; i<loggers.Length; i++)
{
results[i] = WrapLogger(loggers[i]);
}
return results;
}
/// <summary>
/// Create the <see cref="ILoggerWrapper"/> objects used by
/// this manager.
/// </summary>
/// <param name="logger">The logger to wrap.</param>
/// <returns>The wrapper for the logger specified.</returns>
private static ILoggerWrapper WrapperCreationHandler(ILogger logger)
{
return new LogImpl(logger);
}
#endregion
#region Private Static Fields
/// <summary>
/// The wrapper map to use to hold the <see cref="LogImpl"/> objects.
/// </summary>
private static readonly WrapperMap s_wrapperMap = new WrapperMap(new WrapperCreationHandler(WrapperCreationHandler));
#endregion Private Static Fields
}
}
| |
// Copyright 2007 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
//
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using System.IO;
using System.Text;
using Google.MailClientInterfaces;
using System.Globalization;
namespace Google.Thunderbird {
internal class ThunderbirdEmailEnumerator : IEnumerator,
IDisposable {
FileStream fileStream;
StreamReader fileReader;
ThunderbirdFolder folder;
string currentMessageId;
bool isRead;
bool isStarred;
bool hasFileReadError;
long currentPositionInFile;
long initialMessagePosition;
long finalMessagePosition;
int initialFileSeekPosition;
int carriageReturnSize;
Encoding encoding;
internal ThunderbirdEmailEnumerator(ThunderbirdFolder folder) {
this.folder = folder;
this.isRead = false;
this.isStarred = false;
this.hasFileReadError = false;
try {
this.currentPositionInFile = 0;
this.initialMessagePosition = 0;
this.finalMessagePosition = 0;
this.initialFileSeekPosition = 0;
this.carriageReturnSize = 0;
this.fileStream = new FileStream(this.folder.FolderPath,
FileMode.Open,
FileAccess.Read,
FileShare.Read);
if (this.fileStream.CanSeek) {
// Get the byte order mark, if there is one.
byte[] bom = new byte[4];
this.fileStream.Read(bom, 0, 4);
if (bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf) {
this.initialFileSeekPosition = 3;
this.fileStream.Seek(3, SeekOrigin.Begin);
this.encoding = Encoding.UTF8;
} else if ((bom[0] == 0xff && bom[1] == 0xfe)) {
this.initialFileSeekPosition = 2;
this.fileStream.Seek(2, SeekOrigin.Begin);
this.encoding = Encoding.Unicode;
} else if (bom[0] == 0xfe && bom[1] == 0xff) {
this.initialFileSeekPosition = 2;
this.fileStream.Seek(2, SeekOrigin.Begin);
this.encoding = Encoding.BigEndianUnicode;
} else if (bom[0] == 0 &&
bom[1] == 0 &&
bom[2] == 0xfe &&
bom[3] == 0xff) {
// Encoding.UTF32 is not supported in VS2003. We will be returning
// has fileReadErrors = true in this case. If you are using VS2005,
// please comment the line "this.hasFileReadError = true;" and
// uncomment both the lines following it.
this.hasFileReadError = true;
// this.initialFileSeekPosition = 4;
// this.encoding = Encoding.UTF32;
} else if ((bom[0] == 0x2b && bom[1] == 0x2f && bom[2] == 76) &&
(bom[3] == 38 ||
bom[3] == 39 ||
bom[3] == 0x2b ||
bom[3] == 0x2f)) {
this.initialFileSeekPosition = 4;
this.encoding = Encoding.UTF7;
} else {
this.initialFileSeekPosition = 0;
this.encoding = Encoding.ASCII;
this.fileStream.Seek(0, SeekOrigin.Begin);
}
this.fileStream.Seek(this.initialFileSeekPosition, SeekOrigin.Begin);
this.currentPositionInFile = this.initialFileSeekPosition;
this.fileReader = new StreamReader(fileStream, this.encoding);
this.carriageReturnSize =
this.encoding.GetByteCount(ThunderbirdConstants.CarriageReturn);
// Before proceeding with reading the file check if the file reader
// exists.
if (!this.hasFileReadError) {
// Move the file_reader_ to the first "From - " if it exists.
while (this.fileReader.Peek() != -1) {
string line = fileReader.ReadLine();
// We need to add the size of "\r\n" to position depending upon
// the current encoding. The line read using ReadLine() does not
// include the carriage return, thus we need to add its size also.
this.currentPositionInFile +=
(encoding.GetByteCount(line) + this.carriageReturnSize);
if (line.StartsWith(ThunderbirdConstants.MboxMailStart)) {
break;
}
}
}
} else {
this.hasFileReadError = true;
}
} catch (IOException) {
// There might be 2 reasons for the program to come here.
// 1. The file does not exist.
// 2. The file is beign read by some other program.
this.hasFileReadError = true;
}
}
public Object Current {
get {
return new ThunderbirdEmailMessage(
this.folder,
this.currentMessageId,
this.isRead,
this.isStarred,
this.initialMessagePosition,
this.finalMessagePosition,
this.encoding,
this.carriageReturnSize);
}
}
public bool MoveNext() {
if (this.hasFileReadError) {
return false;
}
try {
// From - is not a part of rfc822. This initialization should take care
// of it
this.initialMessagePosition = this.currentPositionInFile;
// Check for the end of stream. Return false if we hit it.
if (this.fileReader.Peek() == -1) {
return false;
}
while (this.fileReader.Peek() != -1) {
bool isFirstMessageId = true;
string line = this.fileReader.ReadLine();
// Consume all the blank lines before we reach the next message or
// eof.
if ((0 == line.Length) && (this.fileReader.Peek() != -1)) {
this.currentPositionInFile += this.carriageReturnSize;
continue;
}
this.currentPositionInFile +=
encoding.GetByteCount(line) + this.carriageReturnSize;
// If we have reached the eof return false. Also mark the finish
// offset.
if (this.fileReader.Peek() == -1) {
this.finalMessagePosition = this.currentPositionInFile;
return false;
}
while (this.fileReader.Peek() != -1) {
line = this.fileReader.ReadLine();
// See if we have "From - " at the beginning of the line. If it is
// we have reached the next message. Initialize the end of the
// current message and exit the loop.
if (line.StartsWith(ThunderbirdConstants.MboxMailStart)) {
this.finalMessagePosition = this.currentPositionInFile;
// Increment the current position in file as we have not done it.
this.currentPositionInFile +=
encoding.GetByteCount(line) + this.carriageReturnSize;
return true;
}
// Increment the current position in the file.
this.currentPositionInFile +=
encoding.GetByteCount(line) + this.carriageReturnSize;
// If we find the message-id of the current message, populate the
// variable message_id_.
if (isFirstMessageId &&
line.ToLower().StartsWith(
ThunderbirdConstants.MessageIDStart)) {
int endingIndex =
line.IndexOf(ThunderbirdConstants.MessageIDEnd);
string messageId = line.Substring(
ThunderbirdConstants.MessageIdLen,
endingIndex - ThunderbirdConstants.MessageIdLen);
this.currentMessageId = messageId;
isFirstMessageId = false;
}
// If we find X-Mozilla-Status, set up the flags.
if (line.StartsWith(ThunderbirdConstants.XMozillaStatus)) {
int xMozillaStatusLen =
ThunderbirdConstants.XMozillaStatus.Length;
string status = line.Substring(
xMozillaStatusLen - 1,
line.Length - xMozillaStatusLen + 1);
int statusNum = 0;
try {
statusNum = int.Parse(status, NumberStyles.HexNumber);
} catch {
// We should never come here if the mbox file is correctly
// written. In case we come here we move to default behavior
// which is unread, unstarred and not deleted and continue with
// building the message.
continue;
}
int read = statusNum & 0x0001;
isRead = (read > 0);
int starred = statusNum & 0x0004;
isStarred = (starred > 0);
// If the message has been expunged from the mbox, find the next
// "From - ".
int deleted = statusNum & 0x0008;
if (deleted > 0) {
while (this.fileReader.Peek() != -1) {
isFirstMessageId = false;
line = this.fileReader.ReadLine();
this.currentPositionInFile +=
encoding.GetByteCount(line) + this.carriageReturnSize;
if (line.IndexOf(
ThunderbirdConstants.MboxMailStart) == 0) {
this.initialMessagePosition = this.currentPositionInFile;
break;
}
}
if (this.fileReader.Peek() == -1) {
return false;
}
}
}
}
// If we reach the eof on this control path, we have the last email to
// take care of. In that case just add the last line.
this.finalMessagePosition = this.currentPositionInFile;
return true;
}
return true;
} catch (IOException) {
this.hasFileReadError = true;
return false;
}
}
public void Reset() {
try {
this.fileReader.Close();
this.fileStream.Close();
this.currentPositionInFile = 0;
this.initialMessagePosition = 0;
this.finalMessagePosition = 0;
this.hasFileReadError = false;
this.fileStream = File.OpenRead(this.folder.FolderPath);
this.fileStream.Seek(this.initialFileSeekPosition, SeekOrigin.Begin);
this.fileReader = new StreamReader(fileStream, this.encoding);
while (this.fileReader.Peek() != -1) {
string line = fileReader.ReadLine();
this.currentPositionInFile +=
encoding.GetByteCount(line) + this.carriageReturnSize;
if (0 == line.IndexOf(ThunderbirdConstants.MboxMailStart)) {
break;
}
}
} catch {
// There might be 2 reasons for the program to come here.
// 1. The file does not exist.
// 2. The file is beign read by some other program.
this.hasFileReadError = true;
return;
}
}
public void Dispose() {
this.fileReader.Close();
this.fileStream.Close();
}
}
}
| |
using System;
using System.Text;
using TestLibrary;
class EncodingGetByteCount
{
static int Main()
{
EncodingGetByteCount test = new EncodingGetByteCount();
TestFramework.BeginTestCase("Encoding.GetByteCount");
if (test.RunTests())
{
TestFramework.EndTestCase();
TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestFramework.EndTestCase();
TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool ret = true;
// Positive Tests
ret &= PositiveTestString(Encoding.UTF8, "TestString", 10, "00A");
ret &= PositiveTestString(Encoding.UTF8, "", 0, "00B");
ret &= PositiveTestString(Encoding.UTF8, "FooBA\u0400R", 8, "00C");
ret &= PositiveTestString(Encoding.UTF8, "\u00C0nima\u0300l", 9, "00D");
ret &= PositiveTestString(Encoding.UTF8, "Test\uD803\uDD75Test", 12, "00E");
ret &= PositiveTestString(Encoding.UTF8, "Test\uD803Test", 11, "00F");
ret &= PositiveTestString(Encoding.UTF8, "Test\uDD75Test", 11, "00G");
ret &= PositiveTestString(Encoding.UTF8, "TestTest\uDD75", 11, "00H");
ret &= PositiveTestString(Encoding.UTF8, "TestTest\uD803", 11, "00I");
ret &= PositiveTestString(Encoding.UTF8, "\uDD75", 3, "00J");
ret &= PositiveTestString(Encoding.UTF8, "\uD803\uDD75\uD803\uDD75\uD803\uDD75", 12, "00K");
ret &= PositiveTestString(Encoding.UTF8, "\u0130", 2, "00L");
ret &= PositiveTestString(Encoding.Unicode, "TestString", 20, "00A3");
ret &= PositiveTestString(Encoding.Unicode, "", 0, "00B3");
ret &= PositiveTestString(Encoding.Unicode, "FooBA\u0400R", 14, "00C3");
ret &= PositiveTestString(Encoding.Unicode, "\u00C0nima\u0300l", 14, "00D3");
ret &= PositiveTestString(Encoding.Unicode, "Test\uD803\uDD75Test", 20, "00E3");
ret &= PositiveTestString(Encoding.Unicode, "Test\uD803Test", 18, "00F3");
ret &= PositiveTestString(Encoding.Unicode, "Test\uDD75Test", 18, "00G3");
ret &= PositiveTestString(Encoding.Unicode, "TestTest\uDD75", 18, "00H3");
ret &= PositiveTestString(Encoding.Unicode, "TestTest\uD803", 18, "00I3");
ret &= PositiveTestString(Encoding.Unicode, "\uDD75", 2, "00J3");
ret &= PositiveTestString(Encoding.Unicode, "\uD803\uDD75\uD803\uDD75\uD803\uDD75", 12, "00K3");
ret &= PositiveTestString(Encoding.Unicode, "\u0130", 2, "00L3");
ret &= PositiveTestString(Encoding.BigEndianUnicode, "TestString", 20, "00A4");
ret &= PositiveTestString(Encoding.BigEndianUnicode, "", 0, "00B4");
ret &= PositiveTestString(Encoding.BigEndianUnicode, "FooBA\u0400R", 14, "00C4");
ret &= PositiveTestString(Encoding.BigEndianUnicode, "\u00C0nima\u0300l", 14, "00D4");
ret &= PositiveTestString(Encoding.BigEndianUnicode, "Test\uD803\uDD75Test", 20, "00E4");
ret &= PositiveTestString(Encoding.BigEndianUnicode, "Test\uD803Test", 18, "00F4");
ret &= PositiveTestString(Encoding.BigEndianUnicode, "Test\uDD75Test", 18, "00G4");
ret &= PositiveTestString(Encoding.BigEndianUnicode, "TestTest\uDD75", 18, "00H4");
ret &= PositiveTestString(Encoding.BigEndianUnicode, "TestTest\uD803", 18, "00I4");
ret &= PositiveTestString(Encoding.BigEndianUnicode, "\uDD75", 2, "00J4");
ret &= PositiveTestString(Encoding.BigEndianUnicode, "\uD803\uDD75\uD803\uDD75\uD803\uDD75", 12, "00K4");
ret &= PositiveTestString(Encoding.BigEndianUnicode, "\u0130", 2, "00L4");
ret &= PositiveTestChars(Encoding.UTF8, new char[] { 'T', 'e', 's', 't', 'S', 't', 'r', 'i', 'n', 'g' }, 10, "00M");
ret &= PositiveTestChars(Encoding.Unicode, new char[] { 'T', 'e', 's', 't', 'S', 't', 'r', 'i', 'n', 'g' }, 20, "00M3");
ret &= PositiveTestChars(Encoding.BigEndianUnicode, new char[] { 'T', 'e', 's', 't', 'S', 't', 'r', 'i', 'n', 'g' }, 20, "00M4");
// Negative Tests
ret &= NegativeTestString(new UTF8Encoding(), null, typeof(ArgumentNullException), "00N");
ret &= NegativeTestString(new UnicodeEncoding(), null, typeof(ArgumentNullException), "00N3");
ret &= NegativeTestString(new UnicodeEncoding(true, false), null, typeof(ArgumentNullException), "00N4");
ret &= NegativeTestChars(new UTF8Encoding(), null, typeof(ArgumentNullException), "00O");
ret &= NegativeTestChars(new UnicodeEncoding(), null, typeof(ArgumentNullException), "00O3");
ret &= NegativeTestChars(new UnicodeEncoding(true, false), null, typeof(ArgumentNullException), "00O4");
ret &= NegativeTestChars2(new UTF8Encoding(), null, 0, 0, typeof(ArgumentNullException), "00P");
ret &= NegativeTestChars2(new UTF8Encoding(), new char[] { 't' }, -1, 1, typeof(ArgumentOutOfRangeException), "00P");
ret &= NegativeTestChars2(new UTF8Encoding(), new char[] { 't' }, 1, -1, typeof(ArgumentOutOfRangeException), "00Q");
ret &= NegativeTestChars2(new UTF8Encoding(), new char[] { 't' }, 0, 10, typeof(ArgumentOutOfRangeException), "00R");
ret &= NegativeTestChars2(new UTF8Encoding(), new char[] { 't' }, 2, 0, typeof(ArgumentOutOfRangeException), "00S");
ret &= NegativeTestChars2(new UnicodeEncoding(), null, 0, 0, typeof(ArgumentNullException), "00P3");
ret &= NegativeTestChars2(new UnicodeEncoding(), new char[] { 't' }, -1, 1, typeof(ArgumentOutOfRangeException), "00P3");
ret &= NegativeTestChars2(new UnicodeEncoding(), new char[] { 't' }, 1, -1, typeof(ArgumentOutOfRangeException), "00Q3");
ret &= NegativeTestChars2(new UnicodeEncoding(), new char[] { 't' }, 0, 10, typeof(ArgumentOutOfRangeException), "00R3");
ret &= NegativeTestChars2(new UnicodeEncoding(), new char[] { 't' }, 2, 0, typeof(ArgumentOutOfRangeException), "00S3");
ret &= NegativeTestChars2(new UnicodeEncoding(true, false), null, 0, 0, typeof(ArgumentNullException), "00P4");
ret &= NegativeTestChars2(new UnicodeEncoding(true, false), new char[] { 't' }, -1, 1, typeof(ArgumentOutOfRangeException), "00P4");
ret &= NegativeTestChars2(new UnicodeEncoding(true, false), new char[] { 't' }, 1, -1, typeof(ArgumentOutOfRangeException), "00Q4");
ret &= NegativeTestChars2(new UnicodeEncoding(true, false), new char[] { 't' }, 0, 10, typeof(ArgumentOutOfRangeException), "00R4");
ret &= NegativeTestChars2(new UnicodeEncoding(true, false), new char[] { 't' }, 2, 0, typeof(ArgumentOutOfRangeException), "00S4");
return ret;
}
public bool PositiveTestString(Encoding enc, string str, int expected, string id)
{
bool result = true;
TestFramework.BeginScenario(id + ": Getting byte count for " + str + " with encoding " + enc.WebName);
try
{
int output = enc.GetByteCount(str);
if (output != expected)
{
result = false;
TestFramework.LogError("001", "Error in " + id + ", unexpected comparison result. Actual byte count " + output + ", Expected: " + expected);
}
}
catch (Exception exc)
{
result = false;
TestFramework.LogError("002", "Unexpected exception in " + id + ", excpetion: " + exc.ToString());
}
return result;
}
public bool NegativeTestString(Encoding enc, string str, Type excType, string id)
{
bool result = true;
TestFramework.BeginScenario(id + ": Getting byte count with encoding " + enc.WebName);
try
{
int output = enc.GetByteCount(str);
result = false;
TestFramework.LogError("005", "Error in " + id + ", Expected exception not thrown. Actual byte count " + output + ", Expected exception type: " + excType.ToString());
}
catch (Exception exc)
{
if (exc.GetType() != excType)
{
result = false;
TestFramework.LogError("006", "Unexpected exception in " + id + ", excpetion: " + exc.ToString());
}
}
return result;
}
public bool PositiveTestChars(Encoding enc, char[] chars, int expected, string id)
{
bool result = true;
TestFramework.BeginScenario(id + ": Getting byte count for " + new string(chars) + " with encoding " + enc.WebName);
try
{
int output = enc.GetByteCount(chars);
if (output != expected)
{
result = false;
TestFramework.LogError("003", "Error in " + id + ", unexpected comparison result. Actual byte count " + output + ", Expected: " + expected);
}
}
catch (Exception exc)
{
result = false;
TestFramework.LogError("004", "Unexpected exception in " + id + ", excpetion: " + exc.ToString());
}
return result;
}
public bool NegativeTestChars(Encoding enc, char[] str, Type excType, string id)
{
bool result = true;
TestFramework.BeginScenario(id + ": Getting byte count with encoding " + enc.WebName);
try
{
int output = enc.GetByteCount(str);
result = false;
TestFramework.LogError("007", "Error in " + id + ", Expected exception not thrown. Actual byte count " + output + ", Expected exception type: " + excType.ToString());
}
catch (Exception exc)
{
if (exc.GetType() != excType)
{
result = false;
TestFramework.LogError("008", "Unexpected exception in " + id + ", excpetion: " + exc.ToString());
}
}
return result;
}
public bool NegativeTestChars2(Encoding enc, char[] str, int index, int count, Type excType, string id)
{
bool result = true;
TestFramework.BeginScenario(id + ": Getting byte count with encoding " + enc.WebName);
try
{
int output = enc.GetByteCount(str, index, count);
result = false;
TestFramework.LogError("009", "Error in " + id + ", Expected exception not thrown. Actual byte count " + output + ", Expected exception type: " + excType.ToString());
}
catch (Exception exc)
{
if (exc.GetType() != excType)
{
result = false;
TestFramework.LogError("010", "Unexpected exception in " + id + ", excpetion: " + exc.ToString());
}
}
return result;
}
}
| |
//////////////////////////////////////////////////////////
// Arduino Firmata Class : Don't Modify It //
////////////////////////////////////////////////////////
using System;
using System.IO.Ports;
using System.Threading;
namespace wbadry
{
public class ArduinoUno
{
public static int INPUT = 0;
public static int OUTPUT = 1;
public static int LOW = 0;
public static int HIGH = 1;
private const int MAX_DATA_BYTES = 32;
private const int DIGITAL_MESSAGE = 0x90; // send data for a digital port
private const int ANALOG_MESSAGE = 0xE0; // send data for an analog pin (or PWM)
private const int REPORT_ANALOG = 0xC0; // enable analog input by pin #
private const int REPORT_DIGITAL = 0xD0; // enable digital input by port
private const int SET_PIN_MODE = 0xF4; // set a pin to INPUT/OUTPUT/PWM/etc
private const int REPORT_VERSION = 0xF9; // report firmware version
private const int SYSTEM_RESET = 0xFF; // reset from MIDI
private const int START_SYSEX = 0xF0; // start a MIDI SysEx message
private const int END_SYSEX = 0xF7; // end a MIDI SysEx message
private SerialPort _serialPort;
private int delay;
private int waitForData = 0;
private int executeMultiByteCommand = 0;
private int multiByteChannel = 0;
private int[] storedInputData = new int[MAX_DATA_BYTES];
private bool parsingSysex;
private int sysexBytesRead;
private volatile int[] digitalOutputData = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
private volatile int[] digitalInputData = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
private volatile int[] analogInputData = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
//private int majorVersion = 0;
//private int minorVersion = 0;
private Thread readThread = null;
//private object locker = new object();
/// <summary>
///
/// </summary>
/// <param name="serialPortName">String specifying the name of the serial port. eg COM4</param>
/// <param name="baudRate">The baud rate of the communication. Default 115200</param>
/// <param name="autoStart">Determines whether the serial port should be opened automatically.
/// use the Open() method to open the connection manually.</param>
/// <param name="delay">Time delay that may be required to allow some arduino models
/// to reboot after opening a serial connection. The delay will only activate
/// when autoStart is true.</param>
public ArduinoUno(string serialPortName, Int32 baudRate, bool autoStart, int delay)
{
_serialPort = new SerialPort(serialPortName, baudRate);
_serialPort.DataBits = 8;
_serialPort.Parity = Parity.None;
_serialPort.StopBits = StopBits.One;
if (autoStart)
{
this.delay = delay;
this.Open();
}
}
/// <summary>
/// Creates an instance of the ArduinoUno object, based on a user-specified serial port.
/// Assumes default values for baud rate (115200) and reboot delay (8 seconds)
/// and automatically opens the specified serial connection.
/// </summary>
/// <param name="serialPortName">String specifying the name of the serial port. eg COM4</param>
public ArduinoUno(string serialPortName) : this(serialPortName, 115200, false, 8000) { }
/// <summary>
/// Creates an instance of the ArduinoUno object, based on user-specified serial port and baud rate.
/// Assumes default value for reboot delay (8 seconds).
/// and automatically opens the specified serial connection.
/// </summary>
/// <param name="serialPortName">String specifying the name of the serial port. eg COM4</param>
/// <param name="baudRate">Baud rate.</param>
/// <param name="autostart">Start automatically?.</param>
public ArduinoUno(string serialPortName, Int32 baudRate, bool autostart) : this(serialPortName, baudRate, autostart, 8000) { }
/// <summary>
/// Creates an instance of the ArduinoUno object, based on user-specified serial port and baud rate.
/// Assumes default value for reboot delay (8 seconds).
/// and automatically opens the specified serial connection.
/// </summary>
/// <param name="serialPortName">String specifying the name of the serial port. eg COM4</param>
/// <param name="baudRate">Baud rate.</param>
public ArduinoUno(string serialPortName, Int32 baudRate) : this(serialPortName, baudRate, false, 8000) { }
/// <summary>
/// Creates an instance of the ArduinoUno object using default arguments.
/// Assumes the arduino is connected as the HIGHEST serial port on the machine,
/// default baud rate (115200), and a reboot delay (8 seconds).
/// and automatically opens the specified serial connection.
/// </summary>
/// <summary>
/// Opens the serial port connection, should it be required. By default the port is
/// opened when the object is first created.
/// </summary>
public void Open()
{
_serialPort.Open();
Thread.Sleep(delay);
byte[] command = new byte[2];
for (int i = 0; i < 6; i++)
{
command[0] = (byte)(REPORT_ANALOG | i);
command[1] = (byte)1;
_serialPort.Write(command, 0, 2);
}
for (int i = 0; i < 2; i++)
{
command[0] = (byte)(REPORT_DIGITAL | i);
command[1] = (byte)1;
_serialPort.Write(command, 0, 2);
}
command = null;
if (readThread == null)
{
readThread = new Thread(processInput);
readThread.Start();
}
}
/// <summary>
/// Closes the serial port.
/// </summary>
public void Close()
{
readThread.Join(500);
readThread = null;
_serialPort.Close();
}
/// <summary>
/// Lists all available serial ports on current system.
/// </summary>
/// <returns>An array of strings containing all available serial ports.</returns>
public static string[] list()
{
return SerialPort.GetPortNames();
}
/// <summary>
/// Returns the last known state of the digital pin.
/// </summary>
/// <param name="pin">The arduino digital input pin.</param>
/// <returns>ArduinoUno.HIGH or ArduinoUno.LOW</returns>
public int digitalRead(int pin)
{
return (digitalInputData[pin >> 3] >> (pin & 0x07)) & 0x01;
}
/// <summary>
/// Returns the last known state of the analog pin.
/// </summary>
/// <param name="pin">The arduino analog input pin.</param>
/// <returns>A value representing the analog value between 0 (0V) and 1023 (5V).</returns>
public int analogRead(int pin)
{
return analogInputData[pin];
}
/// <summary>
/// Sets the mode of the specified pin (INPUT or OUTPUT).
/// </summary>
/// <param name="pin">The arduino pin.</param>
/// <param name="mode">Mode ArduinoUno.INPUT or ArduinoUno.OUTPUT.</param>
public void pinMode(int pin, int mode)
{
byte[] message = new byte[3];
message[0] = (byte)(SET_PIN_MODE);
message[1] = (byte)(pin);
message[2] = (byte)(mode);
_serialPort.Write(message, 0, 3);
message = null;
}
/// <summary>
/// Write to a digital pin that has been toggled to output mode with pinMode() method.
/// </summary>
/// <param name="pin">The digital pin to write to.</param>
/// <param name="value">Value either ArduinoUno.LOW or ArduinoUno.HIGH.</param>
public void digitalWrite(int pin, int value)
{
int portNumber = (pin >> 3) & 0x0F;
byte[] message = new byte[3];
if (value == 0)
digitalOutputData[portNumber] &= ~(1 << (pin & 0x07));
else
digitalOutputData[portNumber] |= (1 << (pin & 0x07));
message[0] = (byte)(DIGITAL_MESSAGE | portNumber);
message[1] = (byte)(digitalOutputData[portNumber] & 0x7F);
message[2] = (byte)(digitalOutputData[portNumber] >> 7);
_serialPort.Write(message, 0, 3);
}
/// <summary>
/// Write to an analog pin using Pulse-width modulation (PWM).
/// </summary>
/// <param name="pin">Analog output pin.</param>
/// <param name="value">PWM frequency from 0 (always off) to 255 (always on).</param>
public void analogWrite(int pin, int value)
{
byte[] message = new byte[3];
message[0] = (byte)(ANALOG_MESSAGE | (pin & 0x0F));
message[1] = (byte)(value & 0x7F);
message[2] = (byte)(value >> 7);
_serialPort.Write(message, 0, 3);
}
private void setDigitalInputs(int portNumber, int portData)
{
digitalInputData[portNumber] = portData;
}
private void setAnalogInput(int pin, int value)
{
analogInputData[pin] = value;
}
private void setVersion(int majorVersion, int minorVersion)
{
//this.majorVersion = majorVersion;
//this.minorVersion = minorVersion;
}
private int available()
{
return _serialPort.BytesToRead;
}
public void processInput()
{
while (_serialPort.IsOpen)
{
lock (this)
{
try
{
int inputData = _serialPort.ReadByte();
int command;
if (parsingSysex)
{
if (inputData == END_SYSEX)
{
parsingSysex = false;
//processSysexMessage();
}
else
{
storedInputData[sysexBytesRead] = inputData;
sysexBytesRead++;
}
}
else if (waitForData > 0 && inputData < 128)
{
waitForData--;
storedInputData[waitForData] = inputData;
if (executeMultiByteCommand != 0 && waitForData == 0)
{
//we got everything
switch (executeMultiByteCommand)
{
case DIGITAL_MESSAGE:
setDigitalInputs(multiByteChannel, (storedInputData[0] << 7) + storedInputData[1]);
break;
case ANALOG_MESSAGE:
setAnalogInput(multiByteChannel, (storedInputData[0] << 7) + storedInputData[1]);
break;
case REPORT_VERSION:
setVersion(storedInputData[1], storedInputData[0]);
break;
}
}
}
else
{
if (inputData < 0xF0)
{
command = inputData & 0xF0;
multiByteChannel = inputData & 0x0F;
}
else
{
command = inputData;
// commands in the 0xF* range don't use channel data
}
switch (command)
{
case DIGITAL_MESSAGE:
case ANALOG_MESSAGE:
case REPORT_VERSION:
waitForData = 2;
executeMultiByteCommand = command;
break;
}
}
}
catch (TimeoutException)
{
continue;
}
}
}
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.PythonTools;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Intellisense;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Options;
using Microsoft.PythonTools.Parsing;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudioTools;
using Microsoft.VisualStudioTools.MockVsTests;
using TestUtilities;
namespace PythonToolsMockTests {
public sealed class PythonEditor : IDisposable {
private readonly bool _disposeVS, _disposeFactory, _disposeAnalyzer;
public readonly MockVs VS;
public readonly IPythonInterpreterFactory Factory;
public readonly VsProjectAnalyzer Analyzer;
public readonly MockVsTextView View;
public readonly AdvancedEditorOptions AdvancedOptions;
public PythonEditor(
string content = null,
PythonLanguageVersion version = PythonLanguageVersion.V27,
MockVs vs = null,
IPythonInterpreterFactory factory = null,
VsProjectAnalyzer analyzer = null,
string filename = null
) {
if (vs == null) {
_disposeVS = true;
vs = new MockVs();
}
MockVsTextView view = null;
try {
AdvancedOptions = vs.GetPyService().AdvancedOptions;
AdvancedOptions.AutoListMembers = true;
AdvancedOptions.AutoListIdentifiers = false;
if (factory == null) {
_disposeFactory = true;
factory = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(version.ToVersion());
}
if (analyzer == null) {
_disposeAnalyzer = true;
analyzer = new VsProjectAnalyzer(vs.ServiceProvider, factory);
var task = analyzer.ReloadTask;
if (task != null) {
task.WaitAndUnwrapExceptions();
}
}
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
using (var mre = new ManualResetEventSlim()) {
EventHandler evt = (s, e) => mre.Set();
analyzer.AnalysisStarted += evt;
view = vs.CreateTextView(PythonCoreConstants.ContentType, content ?? "", v => {
v.TextView.TextBuffer.Properties.AddProperty(typeof(VsProjectAnalyzer), analyzer);
}, filename);
try {
mre.Wait(cts.Token);
analyzer.WaitForCompleteAnalysis(x => !cts.IsCancellationRequested);
} catch (OperationCanceledException) {
} finally {
analyzer.AnalysisStarted -= evt;
}
if (cts.IsCancellationRequested) {
Assert.Fail("Timed out waiting for code analysis");
}
}
View = view;
view = null;
Analyzer = analyzer;
analyzer = null;
Factory = factory;
factory = null;
VS = vs;
vs = null;
} finally {
if (view != null) {
view.Dispose();
}
if (analyzer != null && _disposeAnalyzer) {
analyzer.Dispose();
}
if (factory != null && _disposeFactory) {
var disp = factory as IDisposable;
if (disp != null) {
disp.Dispose();
}
}
if (vs != null && _disposeVS) {
vs.Dispose();
}
}
}
public string Text {
get { return View.Text; }
set {
using (var mre = new ManualResetEventSlim()) {
EventHandler evt = (s, e) => mre.Set();
using (var edit = View.TextView.TextBuffer.CreateEdit()) {
edit.Delete(0, edit.Snapshot.Length);
edit.Apply();
}
mre.Reset();
var buffer = View.TextView.TextBuffer;
var oldVersion = buffer.CurrentSnapshot;
buffer.GetPythonAnalysisClassifier().ClassificationChanged += (s, e) => {
var entry = View.TextView.GetAnalysisEntry(buffer, VS.ServiceProvider);
if (entry.BufferParser.GetAnalysisVersion(buffer).VersionNumber > oldVersion.Version.VersionNumber) {
mre.Set();
}
};
using (var edit = View.TextView.TextBuffer.CreateEdit()) {
edit.Insert(0, value);
edit.Apply();
}
var analysis = View.TextView.GetAnalysisEntry(buffer, VS.ServiceProvider);
analysis.BufferParser.Requeue(); // force the reparse to happen quickly...
if (!mre.Wait(10000)) {
throw new TimeoutException("Failed to see buffer start analyzing");
}
Analyzer.WaitForCompleteAnalysis(_ => true);
}
}
}
public void Type(string text) {
View.Type(text);
}
public ITextSnapshot CurrentSnapshot {
get { return View.TextView.TextSnapshot; }
}
public List<Completion> GetCompletionListAfter(string substring, bool assertIfNoCompletions = true) {
var snapshot = CurrentSnapshot;
return GetCompletionList(snapshot.GetText().IndexOfEnd(substring), assertIfNoCompletions, snapshot);
}
public List<Completion> GetCompletionList(
int index,
bool assertIfNoCompletions = true,
ITextSnapshot snapshot = null
) {
snapshot = snapshot ?? CurrentSnapshot;
if (index < 0) {
index += snapshot.Length + 1;
}
View.MoveCaret(new SnapshotPoint(snapshot, index));
View.MemberList();
using (var sh = View.WaitForSession<ICompletionSession>(assertIfNoSession: assertIfNoCompletions)) {
if (sh == null) {
return new List<Completion>();
}
return sh.Session.CompletionSets.SelectMany(cs => cs.Completions).ToList();
}
}
public IEnumerable<string> GetCompletions(int index) {
return GetCompletionList(index, false).Select(c => c.DisplayText);
}
public IEnumerable<string> GetCompletionsAfter(string substring) {
return GetCompletionListAfter(substring, false).Select(c => c.DisplayText);
}
public void Dispose() {
if (View != null) {
View.Dispose();
}
if (Analyzer != null && _disposeAnalyzer) {
Analyzer.Dispose();
}
if (Factory != null && _disposeFactory) {
var disp = Factory as IDisposable;
if (disp != null) {
disp.Dispose();
}
}
if (VS != null && _disposeVS) {
VS.Dispose();
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.CSharp;
namespace Microsoft.DotNet.CodeFormatting
{
[Export(typeof(IFormattingEngine))]
internal sealed class FormattingEngineImplementation : IFormattingEngine
{
/// <summary>
/// Developers who want to opt out of the code formatter for items like unicode
/// tables can surround them with #if !DOTNET_FORMATTER.
/// </summary>
internal const string TablePreprocessorSymbolName = "DOTNET_FORMATTER";
private readonly Options _options;
private readonly IEnumerable<IFormattingFilter> _filters;
private readonly IEnumerable<Lazy<ISyntaxFormattingRule, IRuleMetadata>> _syntaxRules;
private readonly IEnumerable<Lazy<ILocalSemanticFormattingRule, IRuleMetadata>> _localSemanticRules;
private readonly IEnumerable<Lazy<IGlobalSemanticFormattingRule, IRuleMetadata>> _globalSemanticRules;
private readonly Stopwatch _watch = new Stopwatch();
private bool _allowTables;
private bool _verbose;
public ImmutableArray<string> CopyrightHeader
{
get { return _options.CopyrightHeader; }
set { _options.CopyrightHeader = value; }
}
public ImmutableArray<string[]> PreprocessorConfigurations
{
get { return _options.PreprocessorConfigurations; }
set { _options.PreprocessorConfigurations = value; }
}
public ImmutableArray<string> FileNames
{
get { return _options.FileNames; }
set { _options.FileNames = value; }
}
public IFormatLogger FormatLogger
{
get { return _options.FormatLogger; }
set { _options.FormatLogger = value; }
}
public bool AllowTables
{
get { return _allowTables; }
set { _allowTables = value; }
}
public bool Verbose
{
get { return _verbose; }
set { _verbose = value; }
}
public bool ConvertUnicodeCharacters
{
get { return _options.ConvertUnicodeCharacters; }
set { _options.ConvertUnicodeCharacters = value; }
}
public FormattingLevel FormattingLevel
{
get { return _options.FormattingLevel; }
set { _options.FormattingLevel = value; }
}
[ImportingConstructor]
internal FormattingEngineImplementation(
Options options,
[ImportMany] IEnumerable<IFormattingFilter> filters,
[ImportMany] IEnumerable<Lazy<ISyntaxFormattingRule, IRuleMetadata>> syntaxRules,
[ImportMany] IEnumerable<Lazy<ILocalSemanticFormattingRule, IRuleMetadata>> localSemanticRules,
[ImportMany] IEnumerable<Lazy<IGlobalSemanticFormattingRule, IRuleMetadata>> globalSemanticRules)
{
_options = options;
_filters = filters;
_syntaxRules = syntaxRules;
_localSemanticRules = localSemanticRules;
_globalSemanticRules = globalSemanticRules;
}
private IEnumerable<TRule> GetOrderedRules<TRule>(IEnumerable<Lazy<TRule, IRuleMetadata>> rules)
where TRule : IFormattingRule
{
return rules
.OrderBy(r => r.Metadata.Order)
.Where(r => r.Metadata.FormattingLevel <= FormattingLevel)
.Select(r => r.Value)
.ToList();
}
public Task FormatSolutionAsync(Solution solution, CancellationToken cancellationToken)
{
var documentIds = solution.Projects.SelectMany(x => x.DocumentIds).ToList();
return FormatAsync(solution.Workspace, documentIds, cancellationToken);
}
public Task FormatProjectAsync(Project project, CancellationToken cancellationToken)
{
return FormatAsync(project.Solution.Workspace, project.DocumentIds, cancellationToken);
}
private async Task FormatAsync(Workspace workspace, IReadOnlyList<DocumentId> documentIds, CancellationToken cancellationToken)
{
var watch = new Stopwatch();
watch.Start();
var originalSolution = workspace.CurrentSolution;
var solution = await FormatCoreAsync(originalSolution, documentIds, cancellationToken);
watch.Stop();
if (!workspace.TryApplyChanges(solution))
{
FormatLogger.WriteErrorLine("Unable to save changes to disk");
}
FormatLogger.WriteLine("Total time {0}", watch.Elapsed);
}
private Solution AddTablePreprocessorSymbol(Solution solution)
{
var projectIds = solution.ProjectIds;
foreach (var projectId in projectIds)
{
var project = solution.GetProject(projectId);
var parseOptions = project.ParseOptions as CSharpParseOptions;
if (parseOptions != null)
{
var list = new List<string>();
list.AddRange(parseOptions.PreprocessorSymbolNames);
list.Add(TablePreprocessorSymbolName);
parseOptions = parseOptions.WithPreprocessorSymbols(list);
solution = project.WithParseOptions(parseOptions).Solution;
}
}
return solution;
}
/// <summary>
/// Remove the added table preprocessor symbol. Don't want that saved into the project
/// file as a change.
/// </summary>
private Solution RemoveTablePreprocessorSymbol(Solution newSolution, Solution oldSolution)
{
var projectIds = newSolution.ProjectIds;
foreach (var projectId in projectIds)
{
var oldProject = oldSolution.GetProject(projectId);
var newProject = newSolution.GetProject(projectId);
newSolution = newProject.WithParseOptions(oldProject.ParseOptions).Solution;
}
return newSolution;
}
internal async Task<Solution> FormatCoreAsync(Solution originalSolution, IReadOnlyList<DocumentId> documentIds, CancellationToken cancellationToken)
{
var solution = originalSolution;
if (_allowTables)
{
solution = AddTablePreprocessorSymbol(originalSolution);
}
solution = await RunSyntaxPass(solution, documentIds, cancellationToken);
solution = await RunLocalSemanticPass(solution, documentIds, cancellationToken);
solution = await RunGlobalSemanticPass(solution, documentIds, cancellationToken);
if (_allowTables)
{
solution = RemoveTablePreprocessorSymbol(solution, originalSolution);
}
return solution;
}
private bool ShouldBeProcessed(Document document)
{
foreach (var filter in _filters)
{
var shouldBeProcessed = filter.ShouldBeProcessed(document);
if (!shouldBeProcessed)
return false;
}
return true;
}
private Task<SyntaxNode> GetSyntaxRootAndFilter(Document document, CancellationToken cancellationToken)
{
if (!ShouldBeProcessed(document))
{
return Task.FromResult<SyntaxNode>(null);
}
return document.GetSyntaxRootAsync(cancellationToken);
}
private Task<SyntaxNode> GetSyntaxRootAndFilter(IFormattingRule formattingRule, Document document, CancellationToken cancellationToken)
{
if (!formattingRule.SupportsLanguage(document.Project.Language))
{
return Task.FromResult<SyntaxNode>(null);
}
return GetSyntaxRootAndFilter(document, cancellationToken);
}
private void StartDocument()
{
_watch.Restart();
}
private void EndDocument(Document document)
{
_watch.Stop();
if (_verbose)
{
FormatLogger.WriteLine(" {0} {1} seconds", document.Name, _watch.Elapsed.TotalSeconds);
}
}
/// <summary>
/// Semantics is not involved in this pass at all. It is just a straight modification of the
/// parse tree so there are no issues about ensuring the version of <see cref="SemanticModel"/> and
/// the <see cref="SyntaxNode"/> line up. Hence we do this by iteraning every <see cref="Document"/>
/// and processing all rules against them at once
/// </summary>
private async Task<Solution> RunSyntaxPass(Solution originalSolution, IReadOnlyList<DocumentId> documentIds, CancellationToken cancellationToken)
{
FormatLogger.WriteLine("\tSyntax Pass");
var currentSolution = originalSolution;
foreach (var documentId in documentIds)
{
var document = originalSolution.GetDocument(documentId);
var syntaxRoot = await GetSyntaxRootAndFilter(document, cancellationToken);
if (syntaxRoot == null)
{
continue;
}
StartDocument();
var newRoot = RunSyntaxPass(syntaxRoot, document.Project.Language);
EndDocument(document);
if (newRoot != syntaxRoot)
{
currentSolution = currentSolution.WithDocumentSyntaxRoot(document.Id, newRoot);
}
}
return currentSolution;
}
private SyntaxNode RunSyntaxPass(SyntaxNode root, string languageName)
{
foreach (var rule in GetOrderedRules(_syntaxRules))
{
if (rule.SupportsLanguage(languageName))
{
root = rule.Process(root, languageName);
}
}
return root;
}
private async Task<Solution> RunLocalSemanticPass(Solution solution, IReadOnlyList<DocumentId> documentIds, CancellationToken cancellationToken)
{
FormatLogger.WriteLine("\tLocal Semantic Pass");
foreach (var localSemanticRule in GetOrderedRules(_localSemanticRules))
{
solution = await RunLocalSemanticPass(solution, documentIds, localSemanticRule, cancellationToken);
}
return solution;
}
private async Task<Solution> RunLocalSemanticPass(Solution originalSolution, IReadOnlyList<DocumentId> documentIds, ILocalSemanticFormattingRule localSemanticRule, CancellationToken cancellationToken)
{
if (_verbose)
{
FormatLogger.WriteLine(" {0}", localSemanticRule.GetType().Name);
}
var currentSolution = originalSolution;
foreach (var documentId in documentIds)
{
var document = originalSolution.GetDocument(documentId);
var syntaxRoot = await GetSyntaxRootAndFilter(localSemanticRule, document, cancellationToken);
if (syntaxRoot == null)
{
continue;
}
StartDocument();
var newRoot = await localSemanticRule.ProcessAsync(document, syntaxRoot, cancellationToken);
EndDocument(document);
if (syntaxRoot != newRoot)
{
currentSolution = currentSolution.WithDocumentSyntaxRoot(documentId, newRoot);
}
}
return currentSolution;
}
private async Task<Solution> RunGlobalSemanticPass(Solution solution, IReadOnlyList<DocumentId> documentIds, CancellationToken cancellationToken)
{
FormatLogger.WriteLine("\tGlobal Semantic Pass");
foreach (var globalSemanticRule in GetOrderedRules(_globalSemanticRules))
{
solution = await RunGlobalSemanticPass(solution, documentIds, globalSemanticRule, cancellationToken);
}
return solution;
}
private async Task<Solution> RunGlobalSemanticPass(Solution solution, IReadOnlyList<DocumentId> documentIds, IGlobalSemanticFormattingRule globalSemanticRule, CancellationToken cancellationToken)
{
if (_verbose)
{
FormatLogger.WriteLine(" {0}", globalSemanticRule.GetType().Name);
}
foreach (var documentId in documentIds)
{
var document = solution.GetDocument(documentId);
var syntaxRoot = await GetSyntaxRootAndFilter(globalSemanticRule, document, cancellationToken);
if (syntaxRoot == null)
{
continue;
}
StartDocument();
solution = await globalSemanticRule.ProcessAsync(document, syntaxRoot, cancellationToken);
EndDocument(document);
}
return solution;
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// ParticipantConversationResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Conversations.V1
{
public class ParticipantConversationResource : Resource
{
public sealed class StateEnum : StringEnum
{
private StateEnum(string value) : base(value) {}
public StateEnum() {}
public static implicit operator StateEnum(string value)
{
return new StateEnum(value);
}
public static readonly StateEnum Inactive = new StateEnum("inactive");
public static readonly StateEnum Active = new StateEnum("active");
public static readonly StateEnum Closed = new StateEnum("closed");
}
private static Request BuildReadRequest(ReadParticipantConversationOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Conversations,
"/v1/ParticipantConversations",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Retrieve a list of all Conversations that this Participant belongs to by identity or by address. Only one parameter
/// should be specified.
/// </summary>
/// <param name="options"> Read ParticipantConversation parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of ParticipantConversation </returns>
public static ResourceSet<ParticipantConversationResource> Read(ReadParticipantConversationOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<ParticipantConversationResource>.FromJson("conversations", response.Content);
return new ResourceSet<ParticipantConversationResource>(page, options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of all Conversations that this Participant belongs to by identity or by address. Only one parameter
/// should be specified.
/// </summary>
/// <param name="options"> Read ParticipantConversation parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of ParticipantConversation </returns>
public static async System.Threading.Tasks.Task<ResourceSet<ParticipantConversationResource>> ReadAsync(ReadParticipantConversationOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<ParticipantConversationResource>.FromJson("conversations", response.Content);
return new ResourceSet<ParticipantConversationResource>(page, options, client);
}
#endif
/// <summary>
/// Retrieve a list of all Conversations that this Participant belongs to by identity or by address. Only one parameter
/// should be specified.
/// </summary>
/// <param name="identity"> A unique string identifier for the conversation participant as Conversation User. </param>
/// <param name="address"> A unique string identifier for the conversation participant who's not a Conversation User.
/// </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of ParticipantConversation </returns>
public static ResourceSet<ParticipantConversationResource> Read(string identity = null,
string address = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadParticipantConversationOptions(){Identity = identity, Address = address, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of all Conversations that this Participant belongs to by identity or by address. Only one parameter
/// should be specified.
/// </summary>
/// <param name="identity"> A unique string identifier for the conversation participant as Conversation User. </param>
/// <param name="address"> A unique string identifier for the conversation participant who's not a Conversation User.
/// </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of ParticipantConversation </returns>
public static async System.Threading.Tasks.Task<ResourceSet<ParticipantConversationResource>> ReadAsync(string identity = null,
string address = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadParticipantConversationOptions(){Identity = identity, Address = address, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<ParticipantConversationResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<ParticipantConversationResource>.FromJson("conversations", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<ParticipantConversationResource> NextPage(Page<ParticipantConversationResource> page,
ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Conversations)
);
var response = client.Request(request);
return Page<ParticipantConversationResource>.FromJson("conversations", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<ParticipantConversationResource> PreviousPage(Page<ParticipantConversationResource> page,
ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Conversations)
);
var response = client.Request(request);
return Page<ParticipantConversationResource>.FromJson("conversations", response.Content);
}
/// <summary>
/// Converts a JSON string into a ParticipantConversationResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> ParticipantConversationResource object represented by the provided JSON </returns>
public static ParticipantConversationResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<ParticipantConversationResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique ID of the Account responsible for this conversation.
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The unique ID of the Conversation Service this conversation belongs to.
/// </summary>
[JsonProperty("chat_service_sid")]
public string ChatServiceSid { get; private set; }
/// <summary>
/// The unique ID of the Participant.
/// </summary>
[JsonProperty("participant_sid")]
public string ParticipantSid { get; private set; }
/// <summary>
/// The unique ID for the conversation participant as Conversation User.
/// </summary>
[JsonProperty("participant_user_sid")]
public string ParticipantUserSid { get; private set; }
/// <summary>
/// A unique string identifier for the conversation participant as Conversation User.
/// </summary>
[JsonProperty("participant_identity")]
public string ParticipantIdentity { get; private set; }
/// <summary>
/// Information about how this participant exchanges messages with the conversation.
/// </summary>
[JsonProperty("participant_messaging_binding")]
public object ParticipantMessagingBinding { get; private set; }
/// <summary>
/// The unique ID of the Conversation this Participant belongs to.
/// </summary>
[JsonProperty("conversation_sid")]
public string ConversationSid { get; private set; }
/// <summary>
/// An application-defined string that uniquely identifies the Conversation resource
/// </summary>
[JsonProperty("conversation_unique_name")]
public string ConversationUniqueName { get; private set; }
/// <summary>
/// The human-readable name of this conversation.
/// </summary>
[JsonProperty("conversation_friendly_name")]
public string ConversationFriendlyName { get; private set; }
/// <summary>
/// An optional string metadata field you can use to store any data you wish.
/// </summary>
[JsonProperty("conversation_attributes")]
public string ConversationAttributes { get; private set; }
/// <summary>
/// The date that this conversation was created.
/// </summary>
[JsonProperty("conversation_date_created")]
public DateTime? ConversationDateCreated { get; private set; }
/// <summary>
/// The date that this conversation was last updated.
/// </summary>
[JsonProperty("conversation_date_updated")]
public DateTime? ConversationDateUpdated { get; private set; }
/// <summary>
/// Creator of this conversation.
/// </summary>
[JsonProperty("conversation_created_by")]
public string ConversationCreatedBy { get; private set; }
/// <summary>
/// The current state of this User Conversation
/// </summary>
[JsonProperty("conversation_state")]
[JsonConverter(typeof(StringEnumConverter))]
public ParticipantConversationResource.StateEnum ConversationState { get; private set; }
/// <summary>
/// Timer date values for this conversation.
/// </summary>
[JsonProperty("conversation_timers")]
public object ConversationTimers { get; private set; }
/// <summary>
/// Absolute URLs to access the participant and conversation of this Participant Conversation.
/// </summary>
[JsonProperty("links")]
public Dictionary<string, string> Links { get; private set; }
private ParticipantConversationResource()
{
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Backlog.User.cs">
// bl4n - Backlog.jp API Client library
// this file is part of bl4n, license under MIT license. http://t-ashula.mit-license.org/2015
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using BL4N.Data;
using Newtonsoft.Json;
namespace BL4N
{
/// <summary> The backlog. for User API </summary>
public partial class Backlog
{
/// <summary> Get User List Returns list of users in your space. </summary>
/// <returns> List of <see cref="IUser"/>. </returns>
public IList<IUser> GetUsers()
{
var api = GetApiUri(new[] { "users" });
var jss = new JsonSerializerSettings();
var res = GetApiResult<List<User>>(api, jss);
var users = res.Result;
return users.ToList<IUser>();
}
/// <summary> Get User returns information about user. </summary>
/// <param name="userId">user id ( not nickname )</param>
/// <returns><see cref="IUser"/></returns>
public IUser GetUser(int userId)
{
var api = GetApiUri(new[] { "users", string.Format("{0}", userId) });
var jss = new JsonSerializerSettings();
var res = GetApiResult<User>(api, jss);
return res.Result;
}
/// <summary>
/// Adds new user to the space.
/// "Project Administrator" cannot add "Admin" user.
/// </summary>
/// <param name="options"> new user options </param>
/// <returns></returns>
public IUser AddUser(AddUserOptions options)
{
var api = GetApiUri(new[] { "users" });
var jss = new JsonSerializerSettings();
var kvs = options.ToKeyValuePairs();
var hc = new FormUrlEncodedContent(kvs);
var res = PostApiResult<User>(api, hc, jss);
return res.Result;
}
/// <summary>
/// Update User
/// Updates information about user.
/// </summary>
/// <param name="userId">user id (number)</param>
/// <param name="options">update options</param>
/// <returns>updated <see cref="IUser"/></returns>
public IUser UpdateUser(long userId, UpdateUserOptions options)
{
var api = GetApiUri(new[] { "users", string.Format("{0}", userId) });
var jss = new JsonSerializerSettings();
var kvs = options.ToKeyValuePairs();
var hc = new FormUrlEncodedContent(kvs);
var res = PatchApiResult<User>(api, hc, jss);
return res.Result;
}
/// <summary>
/// Delete User. Deletes user from the space.
/// </summary>
/// <param name="uid">user id</param>
/// <returns>deleted user</returns>
public IUser DeleteUser(long uid)
{
var api = GetApiUri(new[] { "users", string.Format("{0}", uid) });
var jss = new JsonSerializerSettings();
var res = DeleteApiResult<User>(api, jss);
return res.Result;
}
/// <summary>
/// Get Own User. Returns own information about user.
/// /users/myself
/// </summary>
/// <returns> <see cref="IUser"/> of myself </returns>
public IUser GetOwnUser()
{
var api = GetApiUri(new[] { "users", "myself" });
var jss = new JsonSerializerSettings();
var res = GetApiResult<User>(api, jss);
return res.Result;
}
/// <summary>
/// Get User Icon. Downloads user icon.
/// </summary>
/// <param name="uid">user id</param>
/// <returns>user icon</returns>
public ILogo GetUserIcon(long uid)
{
var api = GetApiUri(new[] { "users", string.Format("{0}", uid), "icon" });
var res = GetApiResultAsFile(api);
return new Logo(res.Result.Item1, res.Result.Item2);
}
/// <summary>
/// Get User Recent Updates. Returns user's recent updates
/// </summary>
/// <param name="uid">user id</param>
/// <param name="filter">activity filtering option</param>
/// <returns> List of <see cref="IActivity"/>. </returns>
public IList<IActivity> GetUserRecentUpdates(long uid, RecentUpdateFilterOptions filter = null)
{
var query = filter == null ? null : filter.ToKeyValuePairs();
var api = GetApiUri(new[] { "users", string.Format("{0}", uid), "activities" }, query);
var jss = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
Converters = new JsonConverter[] { new ActivityConverter() }
};
var res = GetApiResult<List<Activity>>(api, jss);
return res.Result.ToList<IActivity>();
}
/// <summary>
/// Get Received Star List.
/// Returns the list of stars that user received.
/// </summary>
/// <param name="uid">user id</param>
/// <param name="filter">result paging option</param>
/// <returns>list of <see cref="IStar"/></returns>
public IList<IStar> GetReceivedStarList(long uid, ResultPagingOptions filter = null)
{
var query = filter == null ? null : filter.ToKeyValuePairs();
var api = GetApiUri(new[] { "users", string.Format("{0}", uid), "stars" }, query);
var jss = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
};
var res = GetApiResult<List<Star>>(api, jss);
return res.Result.ToList<IStar>();
}
/// <summary>
/// Count User Received Stars
/// Returns number of stars that user received.
/// </summary>
/// <param name="uid">user id</param>
/// <param name="term">term (since and/or until)</param>
/// <returns><see cref="ICounter"/></returns>
public ICounter CountUserReceivedStars(long uid, TermOptions term = null)
{
var query = term == null ? null : term.ToKeyValuePairs();
var api = GetApiUri(new[] { "users", string.Format("{0}", uid), "stars", "count" }, query);
var jss = new JsonSerializerSettings();
var res = GetApiResult<Counter>(api, jss);
return res.Result;
}
/// <summary>
/// Get List of Recently Viewed Issues
/// Returns list of issues which the user viewed recently.
/// </summary>
/// <param name="offset">offse/count/ordre option</param>
/// <returns> list of <see cref="IIssue"/>. </returns>
public IList<IIssueUpdate> GetListOfRecentlyViewedIssues(OffsetOptions offset = null)
{
var query = offset == null ? null : offset.ToKeyValuePairs();
var api = GetApiUri(new[] { "users", "myself", "recentlyViewedIssues" }, query);
var jss = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
NullValueHandling = NullValueHandling.Ignore
};
var res = GetApiResult<List<IssueUpdate>>(api, jss);
return res.Result.ToList<IIssueUpdate>();
}
/// <summary>
/// Get List of Recently Viewed Projects
/// Returns list of projects which the user viewed recently.
/// </summary>
/// <param name="offset">offse/count/ordre option</param>
/// <returns>return list of <see cref="IProjectUpdate"/></returns>
public IList<IProjectUpdate> GetListOfRecentlyViewedProjects(OffsetOptions offset = null)
{
var query = offset == null ? null : offset.ToKeyValuePairs();
var api = GetApiUri(new[] { "users", "myself", "recentlyViewedProjects" }, query);
var jss = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat };
var res = GetApiResult<List<ProjectUpdate>>(api, jss);
return res.Result.ToList<IProjectUpdate>();
}
/// <summary>
/// Get List of Recently Viewed Wikis
/// Returns list of Wikis which the user viewed recently.
/// </summary>
/// <param name="offset">offse/count/ordre option</param>
/// <returns> return list of <see cref="IWikiPageUpdate"/> </returns>
public IList<IWikiPageUpdate> GetListOfRecentlyViewedWikis(OffsetOptions offset = null)
{
var query = offset == null ? null : offset.ToKeyValuePairs();
var api = GetApiUri(new[] { "users", "myself", "recentlyViewedWikis" }, query);
var jss = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat };
var res = GetApiResult<List<WikiPageUpdate>>(api, jss);
return res.Result.ToList<IWikiPageUpdate>();
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using Crispy.Parsing;
using System.Dynamic;
using System.Reflection;
using System.Collections.Generic;
using Crispy.Helpers;
using Crispy.Binders;
namespace Crispy
{
public class Crispy
{
private readonly Assembly[] _assemblies;
private readonly ExpandoObject _globals = new ExpandoObject();
private readonly List<object> _instanceObjects = new List<object>();
public Crispy(Assembly[] assms)
{
_assemblies = assms;
AddAssemblyNamesAndTypes();
}
public Crispy(Assembly[] assms, object[] instanceObjects)
{
_assemblies = assms;
//AddAssemblyNamesAndTypes();
_instanceObjects = instanceObjects.ToList();
AddInstanceObjectNamesAndTypes();
}
// _addNamespacesAndTypes builds a tree of ExpandoObjects representing
// .NET namespaces, with TypeModel objects at the leaves. Though Crispy is
// case-insensitive, we store the names as they appear in .NET reflection
// in case our globals object or a namespace object gets passed as an IDO
// to another language or library, where they may be looking for names
// case-sensitively using EO's default lookup.
//
public void AddAssemblyNamesAndTypes()
{
foreach (var assm in _assemblies)
{
foreach (var typ in assm.GetExportedTypes())
{
string[] names = typ.FullName.Split('.');
var table = _globals;
for (int i = 0; i < names.Length - 1; i++)
{
string name = names[i].ToLower();
if (DynamicObjectHelpers.HasMember(table, name))
{
// Must be Expando since only we have put objs in
// the tables so far.
table = (ExpandoObject)(DynamicObjectHelpers.GetMember(table, name));
}
else
{
var tmp = new ExpandoObject();
DynamicObjectHelpers.SetMember(table, name, tmp);
table = tmp;
}
}
DynamicObjectHelpers.SetMember(table, names[names.Length - 1], new TypeModel(typ));
}
}
}
public void AddInstanceObjectNamesAndTypes()
{
foreach (var instanceObject in _instanceObjects)
{
foreach (var methodName in instanceObject.GetType().GetMethods())
{
var table = _globals;
if (DynamicObjectHelpers.HasMember(table, instanceObject.GetType().Name))
{
table = (ExpandoObject)(DynamicObjectHelpers.GetMember(table, instanceObject.GetType().Name));
} else
{
var tmp = new ExpandoObject();
DynamicObjectHelpers.SetMember(table, instanceObject.GetType().Name, tmp);
table = tmp;
}
DynamicObjectHelpers.SetMember(table, methodName.Name, instanceObject);
}
}
}
// ExecuteFile executes the file in a new module scope and stores the
// scope on Globals, using either the provided name, globalVar, or the
// file's base name. This function returns the module scope.
//
public ExpandoObject ExecuteFile(string filename)
{
return ExecuteFile(filename, null);
}
public ExpandoObject ExecuteFile(string filename, string globalVar)
{
var moduleNamespace = CreateNamespace();
ExecuteFileInScope(filename, moduleNamespace);
globalVar = globalVar ?? Path.GetFileNameWithoutExtension(filename);
DynamicObjectHelpers.SetMember(_globals, globalVar, moduleNamespace);
return moduleNamespace;
}
// ExecuteFileInScope executes the file in the given module scope. This
// does NOT store the module scope on Globals. This function returns
// nothing.
//
public void ExecuteFileInScope(string filename, ExpandoObject moduleNamespace)
{
var f = new StreamReader(filename);
// Simple way to convey script rundir for RuntimeHelpes.CrispyImport
// to load .arity files.
DynamicObjectHelpers.SetMember(moduleNamespace, "__file__", Path.GetFullPath(filename));
try
{
var asts = new Parser(new Tokenizer(f)).ParseFile();
var context = new Context(
null,
filename,
this,
Expression.Parameter(typeof(Crispy), "arityRuntime"),
Expression.Parameter(typeof(ExpandoObject), "fileModule")
) {
InstanceObjects = _instanceObjects
};
var body = new List<Expression>();
foreach (var e in asts)
{
body.Add(e.Eval(context));
}
var moduleFun = Expression.Lambda<Action<Crispy, ExpandoObject>>(
MakeBody(context, body),
context.RuntimeExpr,
context.ModuleExpr
);
var d = moduleFun.Compile();
d(this, moduleNamespace);
}
finally
{
f.Close();
}
}
// Execute a single expression parsed from string in the provided module
// scope and returns the resulting value.
//
public object ExecuteExpr(string text, ExpandoObject moduleNamespace)
{
var t = new Tokenizer(new StringReader(text));
var ast = new Parser(t).Parse();
var context = new Context(
null,
"__snippet__",
this,
Expression.Parameter(typeof(Crispy), "arityRuntime"),
Expression.Parameter(typeof(ExpandoObject), "fileModule")
)
{
InstanceObjects = _instanceObjects
};
List<Expression> body = new List<Expression>();
body.Add(Expression.Convert(ast.Eval(context), typeof(object)));
var moduleFunction = Expression.Lambda<Func<Crispy, ExpandoObject, object>>(
MakeBody(context, body),
context.RuntimeExpr,
context.ModuleExpr
);
var d = moduleFunction.Compile();
return d(this, moduleNamespace);
}
private static Expression MakeBody(Context context, IEnumerable<Expression> body)
{
if (context.Variables.Count > 0)
{
return Expression.Block(
context.Variables.Select(name => name.Value).ToArray(),
body
);
}
return Expression.Block(body);
}
public ExpandoObject Globals { get { return _globals; } }
public static ExpandoObject CreateNamespace()
{
return new ExpandoObject();
}
/////////////////////////
// Canonicalizing Binders
/////////////////////////
// We need to canonicalize binders so that we can share L2 dynamic
// dispatch caching across common call sites. Every call site with the
// same operation and same metadata on their binders should return the
// same rules whenever presented with the same kinds of inputs. The
// DLR saves the L2 cache on the binder instance. If one site somewhere
// produces a rule, another call site performing the same operation with
// the same metadata could get the L2 cached rule rather than computing
// it again. For this to work, we need to place the same binder instance
// on those functionally equivalent call sites.
private readonly Dictionary<string, CrispyGetMemberBinder> _getMemberBinders = new Dictionary<string, CrispyGetMemberBinder>();
public CrispyGetMemberBinder GetGetMemberBinder(string name)
{
lock (_getMemberBinders)
{
// Don't lower the name. Crispy is case-preserving in the metadata
// in case some DynamicMetaObject ignores ignoreCase. This makes
// some interop cases work, but the cost is that if a Crispy program
// spells ".foo" and ".Foo" at different sites, they won't share rules.
if (_getMemberBinders.ContainsKey(name))
return _getMemberBinders[name];
var b = new CrispyGetMemberBinder(name);
_getMemberBinders[name] = b;
return b;
}
}
private readonly Dictionary<string, CrispySetMemberBinder> _setMemberBinders = new Dictionary<string, CrispySetMemberBinder>();
public CrispySetMemberBinder GetSetMemberBinder(string name)
{
lock (_setMemberBinders)
{
// Don't lower the name. Crispy is case-preserving in the metadata
// in case some DynamicMetaObject ignores ignoreCase. This makes
// some interop cases work, but the cost is that if a Crispy program
// spells ".foo" and ".Foo" at different sites, they won't share rules.
if (_setMemberBinders.ContainsKey(name))
return _setMemberBinders[name];
var b = new CrispySetMemberBinder(name);
_setMemberBinders[name] = b;
return b;
}
}
private readonly Dictionary<CallInfo, CrispyInvokeBinder> _invokeBinders = new Dictionary<CallInfo, CrispyInvokeBinder>();
public CrispyInvokeBinder GetInvokeBinder(CallInfo info)
{
lock (_invokeBinders)
{
if (_invokeBinders.ContainsKey(info))
return _invokeBinders[info];
var b = new CrispyInvokeBinder(info);
_invokeBinders[info] = b;
return b;
}
}
private readonly Dictionary<InvokeMemberBinderKey, CrispyInvokeMemberBinder> _invokeMemberBinders = new Dictionary<InvokeMemberBinderKey, CrispyInvokeMemberBinder>();
public CrispyInvokeMemberBinder GetInvokeMemberBinder(InvokeMemberBinderKey info)
{
lock (_invokeMemberBinders)
{
if (_invokeMemberBinders.ContainsKey(info))
return _invokeMemberBinders[info];
var b = new CrispyInvokeMemberBinder(info.Name, info.Info);
_invokeMemberBinders[info] = b;
return b;
}
}
private readonly Dictionary<CallInfo, CrispyCreateInstanceBinder> _createInstanceBinders = new Dictionary<CallInfo, CrispyCreateInstanceBinder>();
public CrispyCreateInstanceBinder GetCreateInstanceBinder(CallInfo info)
{
lock (_createInstanceBinders)
{
if (_createInstanceBinders.ContainsKey(info))
return _createInstanceBinders[info];
var b = new CrispyCreateInstanceBinder(info);
_createInstanceBinders[info] = b;
return b;
}
}
private readonly Dictionary<ExpressionType, CrispyBinaryOperationBinder> _binaryOperationBinders = new Dictionary<ExpressionType, CrispyBinaryOperationBinder>();
public CrispyBinaryOperationBinder GetBinaryOperationBinder(ExpressionType op)
{
lock (_binaryOperationBinders)
{
if (_binaryOperationBinders.ContainsKey(op))
return _binaryOperationBinders[op];
var b = new CrispyBinaryOperationBinder(op);
_binaryOperationBinders[op] = b;
return b;
}
}
private readonly Dictionary<ExpressionType, CrispyUnaryOperationBinder> _unaryOperationBinders = new Dictionary<ExpressionType, CrispyUnaryOperationBinder>();
public CrispyUnaryOperationBinder GetUnaryOperationBinder(ExpressionType op)
{
lock (_unaryOperationBinders)
{
if (_unaryOperationBinders.ContainsKey(op))
return _unaryOperationBinders[op];
var b = new CrispyUnaryOperationBinder(op);
_unaryOperationBinders[op] = b;
return b;
}
}
}
}
| |
// 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.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Windows.Forms;
using OpenLiveWriter.BlogClient;
using OpenLiveWriter.CoreServices.Layout;
using OpenLiveWriter.Extensibility.BlogClient;
using OpenLiveWriter.HtmlEditor ;
using OpenLiveWriter.HtmlEditor.Linking;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.Extensibility.ImageEditing;
using OpenLiveWriter.Localization;
using OpenLiveWriter.Localization.Bidi;
namespace OpenLiveWriter.PostEditor.PostHtmlEditing.ImageEditing.Decorators
{
public class HtmlImageTargetEditor : ImageDecoratorEditor
{
private IContainer components = null;
public HtmlImageTargetEditor()
{
// This call is required by the Windows Form Designer.
InitializeComponent();
this.buttonTargetOptions.Text = Res.Get(StringId.OptionsButton);
imageFileSummaryFormat = TextFormatFlags.SingleLine | TextFormatFlags.ExpandTabs | TextFormatFlags.EndEllipsis | TextFormatFlags.NoPrefix;
imageFileSizeFormat = TextFormatFlags.SingleLine | TextFormatFlags.ExpandTabs | TextFormatFlags.EndEllipsis | TextFormatFlags.NoPrefix;
comboBoxLinkTargets.AccessibleName = ControlHelper.ToAccessibleName(Res.Get(StringId.LinkLinkTo));
}
TextFormatFlags imageFileSummaryFormat;
private Button buttonTargetOptions;
TextFormatFlags imageFileSizeFormat;
protected override void OnLoad(EventArgs e)
{
base.OnLoad (e);
DisplayHelper.AutoFitSystemButton(buttonTargetOptions);
// HACK: for some reason this button scales particularly inaccurately
int extraPadding = (int) DisplayHelper.ScaleX(6);
buttonTargetOptions.Width += extraPadding;
buttonTargetOptions.Left -= extraPadding;
using(new AutoGrow(this, AnchorStyles.Bottom, false))
{
LayoutHelper.FitControlsBelow(3, comboBoxLinkTargets);
}
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
// HACK: 722879
// THis button does not always run its 'clicked' event when it has focus and you press enter, space does
// always seem to work though.
if (buttonTargetOptions.Focused && keyData == Keys.Enter)
{
buttonTargetOptions.PerformClick();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
/// <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 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.buttonTargetOptions = new System.Windows.Forms.Button();
this.comboBoxLinkTargets = new System.Windows.Forms.ComboBox();
this.SuspendLayout();
//
// buttonTargetOptions
//
this.buttonTargetOptions.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonTargetOptions.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonTargetOptions.Location = new System.Drawing.Point(167, 35);
this.buttonTargetOptions.Name = "buttonTargetOptions";
this.buttonTargetOptions.Size = new System.Drawing.Size(66, 22);
this.buttonTargetOptions.TabIndex = 1;
this.buttonTargetOptions.Text = "Options...";
this.buttonTargetOptions.Click += new System.EventHandler(this.buttonTargetOptions_Click);
//
// comboBoxLinkTargets
//
this.comboBoxLinkTargets.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.comboBoxLinkTargets.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxLinkTargets.Location = new System.Drawing.Point(0, 0);
this.comboBoxLinkTargets.Name = "comboBoxLinkTargets";
this.comboBoxLinkTargets.Size = new System.Drawing.Size(232, 21);
this.comboBoxLinkTargets.TabIndex = 0;
this.comboBoxLinkTargets.SelectedIndexChanged += new System.EventHandler(this.comboBoxLinkTargets_SelectedIndexChanged);
//
// HtmlImageTargetEditor
//
this.Controls.Add(this.buttonTargetOptions);
this.Controls.Add(this.comboBoxLinkTargets);
this.Name = "HtmlImageTargetEditor";
this.Size = new System.Drawing.Size(232, 118);
this.ResumeLayout(false);
}
#endregion
protected override void LoadEditor()
{
base.LoadEditor ();
HtmlImageTargetSettings = new HtmlImageTargetDecoratorSettings(EditorContext.Settings, EditorContext.ImgElement);
LoadLinkTargetsCombo();
string imgUrl = (string)EditorContext.ImgElement.getAttribute("src", 2);
LinkToSourceImageEnabled = UrlHelper.IsFileUrl(imgUrl) && GlobalEditorOptions.SupportsFeature(ContentEditorFeature.SupportsImageClickThroughs);
if (ImageEditingContext.EditorOptions.DhtmlImageViewer != null)
{
imageViewer = DhtmlImageViewers.GetImageViewer(ImageEditingContext.EditorOptions.DhtmlImageViewer);
}
}
private ComboBox comboBoxLinkTargets;
private HtmlImageTargetDecoratorSettings HtmlImageTargetSettings;
public override Size GetPreferredSize()
{
return new Size(264, 176);
}
protected override void OnSaveSettings()
{
//NOTE: the settings for this control are changed directly in the
//comboBoxLinkTargets_SelectedIndexChanged method, which isn't
//really correct and needs to be changed so that we persist settings
//here instead.
base.OnSaveSettings ();
}
private LinkTargetType SelectedLinkTarget
{
get
{
OptionItem option = (OptionItem)comboBoxLinkTargets.SelectedItem;
if(option != null)
{
LinkTargetType targetType = (LinkTargetType)option.ItemValue;
return targetType;
}
return LinkTargetType.NONE;
}
}
private void LoadLinkTargetsCombo()
{
LinkTargetType targetType = HtmlImageTargetSettings.LinkTarget;
this.comboBoxLinkTargets.Items.Clear();
if(LinkToSourceImageEnabled)
comboBoxLinkTargets.Items.Add(new OptionItem(Res.Get(StringId.LinkToSource), LinkTargetType.IMAGE));
comboBoxLinkTargets.Items.Add(new OptionItem(Res.Get(StringId.LinkToURL), LinkTargetType.URL));
comboBoxLinkTargets.Items.Add(new OptionItem(Res.Get(StringId.LinkToNone), LinkTargetType.NONE));
comboBoxLinkTargets.SelectedItem = new OptionItem("", targetType);
//comboBoxLinkTargets.Visible = comboBoxLinkTargets.Items.Count > 1;
}
private void ClearTargetSummaryLabel()
{
linkToSummaryText = null ;
linkToSizeText = null ;
Invalidate() ;
}
private void LoadTargetSummaryLabel()
{
if(HtmlImageTargetSettings.LinkTarget == LinkTargetType.IMAGE)
{
linkToSummaryText = Path.GetFileName(EditorContext.SourceImageUri.LocalPath);
linkToSizeText = String.Format(CultureInfo.CurrentCulture, Res.Get(StringId.DimensionsFormat), HtmlImageTargetSettings.ImageSize.Width, HtmlImageTargetSettings.ImageSize.Height);
linkToImageViewer = "";
if (HtmlImageTargetSettings.DhtmlImageViewer != null && HtmlImageTargetSettings.DhtmlImageViewer == ImageEditingContext.EditorOptions.DhtmlImageViewer)
{
if (HtmlImageTargetSettings.LinkOptions.UseImageViewer && HtmlImageTargetSettings.DhtmlImageViewer != "Windows Live Spaces")
{
string viewerName = DhtmlImageViewers.GetLocalizedName(HtmlImageTargetSettings.DhtmlImageViewer);
if (!string.IsNullOrEmpty(HtmlImageTargetSettings.LinkOptions.ImageViewerGroupName))
{
linkToImageViewer =
string.Format(CultureInfo.InvariantCulture,
Res.Get(StringId.ImageViewerDisplayFormatGroup),
viewerName,
HtmlImageTargetSettings.LinkOptions.ImageViewerGroupName);
}
else
{
linkToImageViewer =
string.Format(CultureInfo.InvariantCulture,
Res.Get(StringId.ImageViewerDisplayFormatSingle),
viewerName);
}
}
}
}
else if (HtmlImageTargetSettings.LinkTarget == LinkTargetType.URL)
{
linkToImageViewer = String.Empty;
linkToSummaryText = HtmlImageTargetSettings.LinkTargetUrl;
if(UrlHelper.IsUrl(linkToSummaryText))
{
try
{
//attempt to shorten the URI string into a path-ellipsed format.
Uri sourceUri = new Uri(HtmlImageTargetSettings.LinkTargetUrl);
linkToSummaryText = String.Format(CultureInfo.InvariantCulture, "{0}://{1}", sourceUri.Scheme, sourceUri.Host);
string[] segments = sourceUri.Segments;
if(segments.Length > 2)
{
linkToSummaryText += "/...";
if(segments[segments.Length-2].EndsWith("/"))
linkToSummaryText += "/";
linkToSummaryText += segments[segments.Length-1];
}
else
linkToSummaryText += String.Join("", segments);
if(sourceUri.Query != null)
linkToSummaryText += sourceUri.Query;
}
catch(Exception){}
}
linkToSizeText = null;
}
else
{
linkToSummaryText = null ;
linkToSizeText = null ;
}
PerformLayout();
Invalidate();
}
string linkToSummaryText = String.Empty;
string linkToSizeText = "1024x768";
string linkToImageViewer = String.Empty;
protected override void OnLayout(LayoutEventArgs levent)
{
base.OnLayout (levent);
int summaryY = buttonTargetOptions.Bottom + ScaleY(summaryTextTopMargin);
summaryTextRect = new Rectangle(
0, summaryY,
ClientRectangle.Width,
ClientRectangle.Height - summaryY);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint (e);
BidiGraphics g = new BidiGraphics(e.Graphics, summaryTextRect);
//paint the background over the last text paint
using(Brush backBrush = new SolidBrush(BackColor))
{
g.FillRectangle(backBrush, summaryTextRect);
}
Color textColor = Color.DarkGray;
Size sizeTextSize;
if(linkToSizeText != null)
sizeTextSize = g.MeasureText(linkToSizeText, Font, summaryTextRect.Size, imageFileSizeFormat);
else
sizeTextSize = Size.Empty;
Size summaryTextSize = g.MeasureText(linkToSummaryText, Font, new Size(summaryTextRect.Size.Width-sizeTextSize.Width-ScaleX(summarySizeSpacing),sizeTextSize.Height), imageFileSummaryFormat);
Rectangle summaryTextLayoutRect = new Rectangle(new Point(summaryTextRect.X, summaryTextRect.Y), summaryTextSize);
Rectangle sizeTextLayoutRect = new Rectangle(new Point(summaryTextLayoutRect.Right+summarySizeSpacing, summaryTextRect.Y), sizeTextSize);
Rectangle imageViewerTextLayoutRect = new Rectangle(summaryTextRect.X, sizeTextLayoutRect.Bottom + ScaleY(3), ClientRectangle.Width, (int)Math.Ceiling(Font.GetHeight(e.Graphics)));
g.DrawText(linkToSummaryText, this.Font, summaryTextLayoutRect, textColor, imageFileSummaryFormat);
g.DrawText(linkToSizeText, this.Font, sizeTextLayoutRect, textColor, imageFileSummaryFormat);
if (linkToImageViewer != "")
g.DrawText(linkToImageViewer, this.Font, imageViewerTextLayoutRect, textColor, imageFileSummaryFormat);
}
Rectangle summaryTextRect;
private const int summaryTextTopMargin = 10;
private const int summarySizeSpacing = 5;
public bool LinkToSourceImageEnabled
{
get
{
return _linkToSourceImageEnabled;
}
set
{
if(_linkToSourceImageEnabled != value)
{
_linkToSourceImageEnabled = value;
LoadLinkTargetsCombo();
}
}
}
internal IBlogPostImageEditingContext ImageEditingContext
{
get { return imageEditingContext; }
set { imageEditingContext = value; }
}
public bool _linkToSourceImageEnabled;
private void comboBoxLinkTargets_SelectedIndexChanged(object sender, EventArgs e)
{
if(suppressComboBoxLinkTargetsSelectionChanged)
return;
if(EditorState == ControlState.Loaded)
{
using ( new WaitCursor() )
{
using(IImageDecoratorUndoUnit undo = EditorContext.CreateUndoUnit())
{
bool commitChanges = true;
LinkTargetType target = SelectedLinkTarget;
if(target == LinkTargetType.URL && !comboBoxLinkTargets.DroppedDown)
{
ClearTargetSummaryLabel();
commitChanges = EditTargetOptions() == DialogResult.OK;
}
if(commitChanges)
{
HtmlImageTargetSettings.LinkTarget = target;
SaveSettingsAndApplyDecorator();
//note: this is optionally committed because the EditTargetOptions() method
//makes changes to the settings that persist in the DOM. This is bad and we should
//stop doing that, and save in the OnSaveSettings() method instead. Then we won't
//need this stupid optional commit.
undo.Commit();
}
else
{
//rollback to the previous selected item
suppressComboBoxLinkTargetsSelectionChanged = true;
try
{
comboBoxLinkTargets.SelectedItem = new OptionItem("", HtmlImageTargetSettings.LinkTarget);
}
finally
{
suppressComboBoxLinkTargetsSelectionChanged = false;
}
}
}
}
}
LoadTargetSummaryLabel();
buttonTargetOptions.Enabled = !SelectedLinkTarget.Equals(LinkTargetType.NONE) ;
}
private bool suppressComboBoxLinkTargetsSelectionChanged = false;
private IBlogPostImageEditingContext imageEditingContext;
private ImageViewer imageViewer;
private void buttonTargetOptions_Click(object sender, EventArgs e)
{
using ( new WaitCursor() )
{
using(IImageDecoratorUndoUnit undo = EditorContext.CreateUndoUnit())
{
if(EditTargetOptions() == DialogResult.OK)
{
SaveSettingsAndApplyDecorator();
LoadTargetSummaryLabel() ;
undo.Commit();
}
}
}
}
private DialogResult EditTargetOptions()
{
using(LinkToOptionsForm linkOptionsForm = new LinkToOptionsForm())
{
if(SelectedLinkTarget == LinkTargetType.IMAGE)
{
using(ImageTargetEditorControl editor = new ImageTargetEditorControl())
{
editor.LoadImageSize(HtmlImageTargetSettings.ImageSize, EditorContext.SourceImageSize, EditorContext.ImageRotation);
editor.LinkOptions = HtmlImageTargetSettings.LinkOptions;
editor.EditorOptions = ImageEditingContext.EditorOptions;
linkOptionsForm.EditorControl = editor;
HtmlImageTargetSettings.DhtmlImageViewer = ImageEditingContext.EditorOptions.DhtmlImageViewer;
DialogResult result = linkOptionsForm.ShowDialog(this);
if(result == DialogResult.OK)
{
HtmlImageTargetSettings.ImageSize = editor.ImageSize;
HtmlImageTargetSettings.DhtmlImageViewer = ImageEditingContext.EditorOptions.DhtmlImageViewer;
HtmlImageTargetSettings.LinkOptions = editor.LinkOptions;
HtmlImageTargetSettings.ImageSizeName = editor.ImageBoundsSize;
}
return result;
}
}
else if(SelectedLinkTarget == LinkTargetType.URL)
{
using (HyperlinkForm hyperlinkForm = new HyperlinkForm(EditorContext.CommandManager, GlobalEditorOptions.SupportsFeature(ContentEditorFeature.ShowAllLinkOptions)))
{
hyperlinkForm.ContainsImage = true ;
hyperlinkForm.EditStyle = HtmlImageTargetSettings.LinkTargetUrl != null && HtmlImageTargetSettings.LinkTargetUrl != String.Empty ;
hyperlinkForm.NewWindow = HtmlImageTargetSettings.LinkOptions.ShowInNewWindow ;
if ( HtmlImageTargetSettings.LinkTitle != String.Empty )
hyperlinkForm.LinkTitle = HtmlImageTargetSettings.LinkTitle ;
if ( HtmlImageTargetSettings.LinkRel != String.Empty )
hyperlinkForm.Rel = HtmlImageTargetSettings.LinkRel ;
if ( HtmlImageTargetSettings.LinkTargetUrl != null && HtmlImageTargetSettings.LinkTarget != LinkTargetType.IMAGE)
{
hyperlinkForm.Hyperlink = HtmlImageTargetSettings.LinkTargetUrl ;
}
DialogResult result = hyperlinkForm.ShowDialog(FindForm());
if (result == DialogResult.OK )
{
HtmlImageTargetSettings.LinkTargetUrl = hyperlinkForm.Hyperlink ;
HtmlImageTargetSettings.UpdateImageLinkOptions(hyperlinkForm.LinkTitle, hyperlinkForm.Rel, hyperlinkForm.NewWindow );
HtmlImageTargetSettings.LinkOptions = new LinkOptions(hyperlinkForm.NewWindow, false, null) ;
}
return result;
}
}
return DialogResult.Abort;
}
}
}
}
| |
using NUnit.Framework;
using System.Collections.Generic;
using System.Text;
using System.Xml;
namespace Braintree.Tests
{
[TestFixture]
public class ValidationErrorsTest
{
[Test]
public void OnField_WithValidationError()
{
ValidationErrors errors = new ValidationErrors();
errors.AddError("country_name", new ValidationError("country_name", "91803", "invalid country"));
Assert.AreEqual(ValidationErrorCode.ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED, errors.OnField("country_name")[0].Code);
Assert.AreEqual("invalid country", errors.OnField("country_name")[0].Message);
}
[Test]
public void OnField_WorksWithAllCommonCasing()
{
ValidationError fieldError = new ValidationError("", "1", "");
ValidationErrors errors = new ValidationErrors();
errors.AddError("country_name", fieldError);
Assert.AreEqual(fieldError, errors.OnField("country_name")[0]);
Assert.AreEqual(fieldError, errors.OnField("country-name")[0]);
Assert.AreEqual(fieldError, errors.OnField("countryName")[0]);
Assert.AreEqual(fieldError, errors.OnField("CountryName")[0]);
}
[Test]
public void OnField_WithNonExistingField()
{
ValidationErrors errors = new ValidationErrors();
Assert.IsNull(errors.OnField("foo"));
}
[Test]
public void ForObject_WithNestedErrors()
{
ValidationErrors addressErrors = new ValidationErrors();
addressErrors.AddError("country_name", new ValidationError("country_name", "91803", "invalid country"));
ValidationErrors errors = new ValidationErrors();
errors.AddErrors("address", addressErrors);
Assert.AreEqual(ValidationErrorCode.ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED, errors.ForObject("address").OnField("country_name")[0].Code);
Assert.AreEqual("invalid country", errors.ForObject("address").OnField("country_name")[0].Message);
}
[Test]
public void ForObject_WithNonExistingObject()
{
ValidationErrors errors = new ValidationErrors();
Assert.AreEqual(0, errors.ForObject("address").Count);
}
[Test]
public void ForObject_WorksWithAllCommonCasing()
{
ValidationErrors nestedErrors = new ValidationErrors();
ValidationErrors errors = new ValidationErrors();
errors.AddErrors("credit-card", nestedErrors);
Assert.AreEqual(nestedErrors, errors.ForObject("credit-card"));
Assert.AreEqual(nestedErrors, errors.ForObject("credit_card"));
Assert.AreEqual(nestedErrors, errors.ForObject("creditCard"));
Assert.AreEqual(nestedErrors, errors.ForObject("CreditCard"));
}
[Test]
public void Size_WithShallowErrors()
{
ValidationErrors errors = new ValidationErrors();
errors.AddError("country_name", new ValidationError("country_name", "1", "invalid country"));
errors.AddError("another_field", new ValidationError("another_field", "2", "another message"));
Assert.AreEqual(2, errors.Count);
}
[Test]
public void DeepCount_WithNestedErrors()
{
ValidationErrors addressErrors = new ValidationErrors();
addressErrors.AddError("country_name", new ValidationError("country_name", "1", "invalid country"));
addressErrors.AddError("another_field", new ValidationError("another_field", "2", "another message"));
ValidationErrors errors = new ValidationErrors();
errors.AddError("some_field", new ValidationError("some_field", "3", "some message"));
errors.AddErrors("address", addressErrors);
Assert.AreEqual(3, errors.DeepCount);
Assert.AreEqual(1, errors.Count);
Assert.AreEqual(2, errors.ForObject("address").DeepCount);
Assert.AreEqual(2, errors.ForObject("address").Count);
}
[Test]
public void Constructor_ParsesSimpleValidationErrors()
{
StringBuilder builder = new StringBuilder();
builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
builder.Append("<api-error-response>");
builder.Append(" <errors>");
builder.Append(" <address>");
builder.Append(" <errors type=\"array\">");
builder.Append(" <error>");
builder.Append(" <code>91803</code>");
builder.Append(" <message>Country name is not an accepted country.</message>");
builder.Append(" <attribute type=\"symbol\">country_name</attribute>");
builder.Append(" </error>");
builder.Append(" </errors>");
builder.Append(" </address>");
builder.Append(" <errors type=\"array\"/>");
builder.Append(" </errors>");
builder.Append("</api-error-response>");
XmlDocument doc = new XmlDocument();
doc.LoadXml(builder.ToString());
ValidationErrors errors = new ValidationErrors(new NodeWrapper(doc.ChildNodes[1]));
Assert.AreEqual(1, errors.DeepCount);
Assert.AreEqual(ValidationErrorCode.ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED, errors.ForObject("address").OnField("country_name")[0].Code);
}
[Test]
public void Constructor_ParsesMulitpleValidationErrorsOnOneObject()
{
StringBuilder builder = new StringBuilder();
builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
builder.Append("<api-error-response>");
builder.Append(" <errors>");
builder.Append(" <address>");
builder.Append(" <errors type=\"array\">");
builder.Append(" <error>");
builder.Append(" <code>91803</code>");
builder.Append(" <message>Country name is not an accepted country.</message>");
builder.Append(" <attribute type=\"symbol\">country_name</attribute>");
builder.Append(" </error>");
builder.Append(" <error>");
builder.Append(" <code>81812</code>");
builder.Append(" <message>Street address is too long.</message>");
builder.Append(" <attribute type=\"symbol\">street_address</attribute>");
builder.Append(" </error>");
builder.Append(" </errors>");
builder.Append(" </address>");
builder.Append(" <errors type=\"array\"/>");
builder.Append(" </errors>");
builder.Append("</api-error-response>");
XmlDocument doc = new XmlDocument();
doc.LoadXml(builder.ToString());
ValidationErrors errors = new ValidationErrors(new NodeWrapper(doc.ChildNodes[1]));
Assert.AreEqual(2, errors.DeepCount);
Assert.AreEqual(ValidationErrorCode.ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED, errors.ForObject("address").OnField("country_name")[0].Code);
Assert.AreEqual(ValidationErrorCode.ADDRESS_STREET_ADDRESS_IS_TOO_LONG, errors.ForObject("address").OnField("street_address")[0].Code);
}
[Test]
public void Constructor_ParsesValidationErrorOnNestedObject()
{
StringBuilder builder = new StringBuilder();
builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
builder.Append("<api-error-response>");
builder.Append(" <errors>");
builder.Append(" <errors type=\"array\"/>");
builder.Append(" <credit-card>");
builder.Append(" <billing-address>");
builder.Append(" <errors type=\"array\">");
builder.Append(" <error>");
builder.Append(" <code>91803</code>");
builder.Append(" <message>Country name is not an accepted country.</message>");
builder.Append(" <attribute type=\"symbol\">country_name</attribute>");
builder.Append(" </error>");
builder.Append(" </errors>");
builder.Append(" </billing-address>");
builder.Append(" <errors type=\"array\"/>");
builder.Append(" </credit-card>");
builder.Append(" </errors>");
builder.Append("</api-error-response>");
XmlDocument doc = new XmlDocument();
doc.LoadXml(builder.ToString());
ValidationErrors errors = new ValidationErrors(new NodeWrapper(doc.ChildNodes[1]));
Assert.AreEqual(1, errors.DeepCount);
Assert.AreEqual(ValidationErrorCode.ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED, errors.ForObject("credit-card").ForObject("billing-address").OnField("country_name")[0].Code);
}
[Test]
public void Constructor_ParsesMultipleErrorsOnSingleField()
{
StringBuilder builder = new StringBuilder();
builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
builder.Append("<api-error-response>");
builder.Append(" <errors>");
builder.Append(" <transaction>");
builder.Append(" <errors type=\"array\">");
builder.Append(" <error>");
builder.Append(" <code>91516</code>");
builder.Append(" <message>Cannot provide both payment_method_token and customer_id unless the payment_method belongs to the customer.</message>");
builder.Append(" <attribute type=\"symbol\">base</attribute>");
builder.Append(" </error>");
builder.Append(" <error>");
builder.Append(" <code>91515</code>");
builder.Append(" <message>Cannot provide both payment_method_token and credit_card attributes.</message>");
builder.Append(" <attribute type=\"symbol\">base</attribute>");
builder.Append(" </error>");
builder.Append(" </errors>");
builder.Append(" </transaction>");
builder.Append(" <errors type=\"array\"/>");
builder.Append(" </errors>");
builder.Append("</api-error-response>");
XmlDocument doc = new XmlDocument();
doc.LoadXml(builder.ToString());
ValidationErrors errors = new ValidationErrors(new NodeWrapper(doc.ChildNodes[1]));
Assert.AreEqual(2, errors.DeepCount);
Assert.AreEqual(2, errors.ForObject("transaction").OnField("base").Count);
}
[Test]
public void Constructor_ParsesValidationErrorsAtMultipleLevels()
{
StringBuilder builder = new StringBuilder();
builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
builder.Append("<api-error-response>");
builder.Append(" <errors>");
builder.Append(" <customer>");
builder.Append(" <errors type=\"array\">");
builder.Append(" <error>");
builder.Append(" <code>81608</code>");
builder.Append(" <message>First name is too long.</message>");
builder.Append(" <attribute type=\"symbol\">first_name</attribute>");
builder.Append(" </error>");
builder.Append(" </errors>");
builder.Append(" <credit-card>");
builder.Append(" <billing-address>");
builder.Append(" <errors type=\"array\">");
builder.Append(" <error>");
builder.Append(" <code>91803</code>");
builder.Append(" <message>Country name is not an accepted country.</message>");
builder.Append(" <attribute type=\"symbol\">country_name</attribute>");
builder.Append(" </error>");
builder.Append(" </errors>");
builder.Append(" </billing-address>");
builder.Append(" <errors type=\"array\">");
builder.Append(" <error>");
builder.Append(" <code>81715</code>");
builder.Append(" <message>Credit card number is invalid.</message>");
builder.Append(" <attribute type=\"symbol\">number</attribute>");
builder.Append(" </error>");
builder.Append(" </errors>");
builder.Append(" </credit-card>");
builder.Append(" </customer>");
builder.Append(" <errors type=\"array\"/>");
builder.Append(" </errors>");
builder.Append("</api-error-response>");
XmlDocument doc = new XmlDocument();
doc.LoadXml(builder.ToString());
ValidationErrors errors = new ValidationErrors(new NodeWrapper(doc.ChildNodes[1]));
Assert.AreEqual(3, errors.DeepCount);
Assert.AreEqual(0, errors.Count);
Assert.AreEqual(3, errors.ForObject("customer").DeepCount);
Assert.AreEqual(1, errors.ForObject("customer").Count);
Assert.AreEqual(ValidationErrorCode.CUSTOMER_FIRST_NAME_IS_TOO_LONG, errors.ForObject("customer").OnField("first_name")[0].Code);
Assert.AreEqual(2, errors.ForObject("customer").ForObject("credit-card").DeepCount);
Assert.AreEqual(1, errors.ForObject("customer").ForObject("credit-card").Count);
Assert.AreEqual(ValidationErrorCode.CREDIT_CARD_NUMBER_IS_INVALID, errors.ForObject("customer").ForObject("credit-card").OnField("number")[0].Code);
Assert.AreEqual(1, errors.ForObject("customer").ForObject("credit-card").ForObject("billing-address").DeepCount);
Assert.AreEqual(1, errors.ForObject("customer").ForObject("credit-card").ForObject("billing-address").Count);
Assert.AreEqual(ValidationErrorCode.ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED, errors.ForObject("customer").ForObject("credit-card").ForObject("billing-address").OnField("country_name")[0].Code);
}
[Test]
public void ByFormField_FlattensErrorsToFormElementNames()
{
var errors = new ValidationErrors();
errors.AddError("some_error", new ValidationError("some_error", "1", "some error"));
errors.AddError("some_error", new ValidationError("some_error", "2", "some other error"));
var nestedErrors = new ValidationErrors();
nestedErrors.AddError("some_nested_error", new ValidationError("some_nested_error", "3", "some nested error"));
nestedErrors.AddError("some_nested_error", new ValidationError("some_nested_error", "4", "some other nested error"));
var nestedNestedErrors = new ValidationErrors();
nestedNestedErrors.AddError("some_nested_nested_error", new ValidationError("some_nested_nested_error", "5", "some nested nested error"));
nestedNestedErrors.AddError("some_nested_nested_error", new ValidationError("some_nested_nested_error", "6", "some other nested nested error"));
nestedErrors.AddErrors("some_nested_object", nestedNestedErrors);
errors.AddErrors("some_object", nestedErrors);
Dictionary<string, List<string>> formErrors = errors.ByFormField();
Assert.AreEqual("some error", formErrors["some_error"][0]);
Assert.AreEqual("some other error", formErrors["some_error"][1]);
Assert.AreEqual("some nested error", formErrors["some_object[some_nested_error]"][0]);
Assert.AreEqual("some other nested error", formErrors["some_object[some_nested_error]"][1]);
Assert.AreEqual("some nested nested error", formErrors["some_object[some_nested_object][some_nested_nested_error]"][0]);
Assert.AreEqual("some other nested nested error", formErrors["some_object[some_nested_object][some_nested_nested_error]"][1]);
}
[Test]
public void ByFormField_UnderscoresNodes()
{
var errors = new ValidationErrors();
errors.AddError("some-error", new ValidationError("some-error", "1", "some error"));
errors.AddError("some-error", new ValidationError("some-error", "2", "some other error"));
var nestedErrors = new ValidationErrors();
nestedErrors.AddError("some-nested-error", new ValidationError("some-nested-error", "3", "some nested error"));
nestedErrors.AddError("some-nested-error", new ValidationError("some-nested-error", "4", "some other nested error"));
var nestedNestedErrors = new ValidationErrors();
nestedNestedErrors.AddError("some-nested-nested-error", new ValidationError("some-nested-nested-error", "5", "some nested nested error"));
nestedNestedErrors.AddError("some-nested-nested-error", new ValidationError("some-nested-nested-error", "6", "some other nested nested error"));
nestedErrors.AddErrors("some-nested-object", nestedNestedErrors);
errors.AddErrors("some-object", nestedErrors);
Dictionary<string, List<string>> formErrors = errors.ByFormField();
Assert.AreEqual("some error", formErrors["some_error"][0]);
Assert.AreEqual("some other error", formErrors["some_error"][1]);
Assert.AreEqual("some nested error", formErrors["some_object[some_nested_error]"][0]);
Assert.AreEqual("some other nested error", formErrors["some_object[some_nested_error]"][1]);
Assert.AreEqual("some nested nested error", formErrors["some_object[some_nested_object][some_nested_nested_error]"][0]);
Assert.AreEqual("some other nested nested error", formErrors["some_object[some_nested_object][some_nested_nested_error]"][1]);
}
[Test]
public void All_ReturnsValidationErrorsAtOneLevel()
{
StringBuilder builder = new StringBuilder();
builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
builder.Append("<api-error-response>");
builder.Append(" <errors>");
builder.Append(" <customer>");
builder.Append(" <errors type=\"array\">");
builder.Append(" <error>");
builder.Append(" <code>81608</code>");
builder.Append(" <message>First name is too long.</message>");
builder.Append(" <attribute type=\"symbol\">first_name</attribute>");
builder.Append(" </error>");
builder.Append(" </errors>");
builder.Append(" <credit-card>");
builder.Append(" <errors type=\"array\">");
builder.Append(" <error>");
builder.Append(" <code>81715</code>");
builder.Append(" <message>Credit card number is invalid.</message>");
builder.Append(" <attribute type=\"symbol\">number</attribute>");
builder.Append(" </error>");
builder.Append(" <error>");
builder.Append(" <code>81710</code>");
builder.Append(" <message>Expiration date is invalid.</message>");
builder.Append(" <attribute type=\"symbol\">expiration_date</attribute>");
builder.Append(" </error>");
builder.Append(" </errors>");
builder.Append(" </credit-card>");
builder.Append(" </customer>");
builder.Append(" <errors type=\"array\"/>");
builder.Append(" </errors>");
builder.Append("</api-error-response>");
XmlDocument doc = new XmlDocument();
doc.LoadXml(builder.ToString());
ValidationErrors errors = new ValidationErrors(new NodeWrapper(doc.ChildNodes[1]));
Assert.AreEqual(0, errors.All().Count);
Assert.AreEqual(1, errors.ForObject("customer").All().Count);
Assert.AreEqual("first_name", errors.ForObject("customer").All()[0].Attribute);
Assert.AreEqual(ValidationErrorCode.CUSTOMER_FIRST_NAME_IS_TOO_LONG, errors.ForObject("customer").All()[0].Code);
Assert.AreEqual(2, errors.ForObject("customer").ForObject("credit-card").All().Count);
Assert.AreEqual("number", errors.ForObject("customer").ForObject("credit-card").All()[0].Attribute);
Assert.AreEqual(ValidationErrorCode.CREDIT_CARD_NUMBER_IS_INVALID, errors.ForObject("customer").ForObject("credit-card").All()[0].Code);
Assert.AreEqual("expiration_date", errors.ForObject("customer").ForObject("credit-card").All()[1].Attribute);
Assert.AreEqual(ValidationErrorCode.CREDIT_CARD_EXPIRATION_DATE_IS_INVALID, errors.ForObject("customer").ForObject("credit-card").All()[1].Code);
}
[Test]
public void DeepAll_ReturnsValidationErrorsAtEveryLevel()
{
StringBuilder builder = new StringBuilder();
builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
builder.Append("<api-error-response>");
builder.Append(" <errors>");
builder.Append(" <customer>");
builder.Append(" <errors type=\"array\">");
builder.Append(" <error>");
builder.Append(" <code>81608</code>");
builder.Append(" <message>First name is too long.</message>");
builder.Append(" <attribute type=\"symbol\">first_name</attribute>");
builder.Append(" </error>");
builder.Append(" </errors>");
builder.Append(" <credit-card>");
builder.Append(" <errors type=\"array\">");
builder.Append(" <error>");
builder.Append(" <code>81715</code>");
builder.Append(" <message>Credit card number is invalid.</message>");
builder.Append(" <attribute type=\"symbol\">number</attribute>");
builder.Append(" </error>");
builder.Append(" <error>");
builder.Append(" <code>81710</code>");
builder.Append(" <message>Expiration date is invalid.</message>");
builder.Append(" <attribute type=\"symbol\">expiration_date</attribute>");
builder.Append(" </error>");
builder.Append(" </errors>");
builder.Append(" </credit-card>");
builder.Append(" </customer>");
builder.Append(" <errors type=\"array\"/>");
builder.Append(" </errors>");
builder.Append("</api-error-response>");
XmlDocument doc = new XmlDocument();
doc.LoadXml(builder.ToString());
ValidationErrors errors = new ValidationErrors(new NodeWrapper(doc.ChildNodes[1]));
Assert.AreEqual(3, errors.DeepAll().Count);
Assert.AreEqual("first_name", errors.DeepAll()[0].Attribute);
Assert.AreEqual(ValidationErrorCode.CUSTOMER_FIRST_NAME_IS_TOO_LONG, errors.DeepAll()[0].Code);
Assert.AreEqual("number", errors.DeepAll()[1].Attribute);
Assert.AreEqual(ValidationErrorCode.CREDIT_CARD_NUMBER_IS_INVALID, errors.DeepAll()[1].Code);
Assert.AreEqual("expiration_date", errors.DeepAll()[2].Attribute);
Assert.AreEqual(ValidationErrorCode.CREDIT_CARD_EXPIRATION_DATE_IS_INVALID, errors.DeepAll()[2].Code);
Assert.AreEqual(3, errors.ForObject("customer").DeepAll().Count);
Assert.AreEqual("first_name", errors.ForObject("customer").DeepAll()[0].Attribute);
Assert.AreEqual(ValidationErrorCode.CUSTOMER_FIRST_NAME_IS_TOO_LONG, errors.ForObject("customer").DeepAll()[0].Code);
Assert.AreEqual("number", errors.ForObject("customer").DeepAll()[1].Attribute);
Assert.AreEqual(ValidationErrorCode.CREDIT_CARD_NUMBER_IS_INVALID, errors.ForObject("customer").DeepAll()[1].Code);
Assert.AreEqual("expiration_date", errors.ForObject("customer").DeepAll()[2].Attribute);
Assert.AreEqual(ValidationErrorCode.CREDIT_CARD_EXPIRATION_DATE_IS_INVALID, errors.ForObject("customer").DeepAll()[2].Code);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
using TestLibrary;
#region Sequential
#region sequential struct definition
[StructLayout(LayoutKind.Sequential)]
public struct S_INTArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public int[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_UINTArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public uint[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_SHORTArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public short[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_WORDArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public ushort[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_LONG64Array_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public long[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_ULONG64Array_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public ulong[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_DOUBLEArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public double[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_FLOATArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public float[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_BYTEArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public byte[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_CHARArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public char[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_LPSTRArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public string[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_LPCSTRArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public string[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_BSTRArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE, ArraySubType = UnmanagedType.BStr)]
public string[] arr;
}
//struct array in a struct
[StructLayout(LayoutKind.Sequential)]
public struct TestStruct
{
public int x;
public double d;
public long l;
public string str;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_StructArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public TestStruct[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_BOOLArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public bool[] arr;
}
public enum TestEnum
{
Red = 1,
Green,
Blue
}
[StructLayout(LayoutKind.Sequential)]
public struct EnregisterableNonBlittable_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public TestEnum[] arr;
}
public struct SimpleStruct
{
public int fld;
}
[StructLayout(LayoutKind.Sequential)]
public struct EnregisterableUserType
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public SimpleStruct[] arr;
}
#endregion
#region sequential class definition
[StructLayout(LayoutKind.Sequential)]
public class C_INTArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public int[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_UINTArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public uint[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_SHORTArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public short[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_WORDArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public ushort[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_LONG64Array_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public long[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_ULONG64Array_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public ulong[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_DOUBLEArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public double[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_FLOATArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public float[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_BYTEArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public byte[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_CHARArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public char[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_LPSTRArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public string[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_LPCSTRArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public string[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_BSTRArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE, ArraySubType = UnmanagedType.BStr)]
public string[] arr;
}
//struct array in a class
[StructLayout(LayoutKind.Sequential)]
public class C_StructArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public TestStruct[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_BOOLArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public bool[] arr;
}
#endregion
#endregion
#region Explicit
#region explicit stuct definition
[StructLayout(LayoutKind.Explicit)]
public struct S_INTArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public int[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_UINTArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public uint[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_SHORTArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public short[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_WORDArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public ushort[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_LONG64Array_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE, ArraySubType = UnmanagedType.I8)]
public long[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_ULONG64Array_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public ulong[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_DOUBLEArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public double[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_FLOATArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public float[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_BYTEArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public byte[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_CHARArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public char[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_LPSTRArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public string[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_LPCSTRArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public string[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_BSTRArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE, ArraySubType = UnmanagedType.BStr)]
public string[] arr;
}
//struct array in a struct
[StructLayout(LayoutKind.Explicit)]
public struct S_StructArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public TestStruct[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_BOOLArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public bool[] arr;
}
#endregion
#region explicit class definition
[StructLayout(LayoutKind.Explicit)]
public class C_INTArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public int[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public class C_UINTArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public uint[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public class C_SHORTArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public short[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public class C_WORDArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public ushort[] arr;
}
[StructLayout(LayoutKind.Explicit, Pack = 8)]
public class C_LONG64Array_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public long[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public class C_ULONG64Array_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public ulong[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public class C_DOUBLEArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public double[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public class C_FLOATArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public float[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public class C_BYTEArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public byte[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public class C_CHARArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public char[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public class C_LPSTRArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public string[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public class C_LPCSTRArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public string[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public class C_BSTRArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE, ArraySubType = UnmanagedType.BStr)]
public string[] arr;
}
//struct array in a class
[StructLayout(LayoutKind.Explicit)]
public class C_StructArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public TestStruct[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public class C_BOOLArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public bool[] arr;
}
#endregion
#endregion
class Test
{
//for RunTest1
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeIntArraySeqStructByVal([In]S_INTArray_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeUIntArraySeqStructByVal([In]S_UINTArray_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeShortArraySeqStructByVal([In]S_SHORTArray_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeWordArraySeqStructByVal([In]S_WORDArray_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeLong64ArraySeqStructByVal([In]S_LONG64Array_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeULong64ArraySeqStructByVal([In]S_ULONG64Array_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeDoubleArraySeqStructByVal([In]S_DOUBLEArray_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeFloatArraySeqStructByVal([In]S_FLOATArray_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeByteArraySeqStructByVal([In]S_BYTEArray_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeCharArraySeqStructByVal([In]S_CHARArray_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeLPSTRArraySeqStructByVal([In]S_LPSTRArray_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeLPCSTRArraySeqStructByVal([In]S_LPCSTRArray_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeBSTRArraySeqStructByVal([In]S_BSTRArray_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeStructArraySeqStructByVal([In]S_StructArray_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeEnregistrableNonBlittableSeqStructByVal(EnregisterableNonBlittable_Seq s, TestEnum[] values);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeEnregisterableUserTypeStructByVal(EnregisterableUserType s, SimpleStruct[] values);
//for RunTest2
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeIntArraySeqClassByVal([In]C_INTArray_Seq c, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeUIntArraySeqClassByVal([In]C_UINTArray_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeShortArraySeqClassByVal([In]C_SHORTArray_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeWordArraySeqClassByVal([In]C_WORDArray_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeLong64ArraySeqClassByVal([In]C_LONG64Array_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeULong64ArraySeqClassByVal([In]C_ULONG64Array_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeDoubleArraySeqClassByVal([In]C_DOUBLEArray_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeFloatArraySeqClassByVal([In]C_FLOATArray_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeByteArraySeqClassByVal([In]C_BYTEArray_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeCharArraySeqClassByVal([In]C_CHARArray_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeLPSTRArraySeqClassByVal([In]C_LPSTRArray_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeLPCSTRArraySeqClassByVal([In]C_LPCSTRArray_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeBSTRArraySeqClassByVal([In]C_BSTRArray_Seq s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeStructArraySeqClassByVal([In]C_StructArray_Seq s, int size);
//for RunTest3
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeIntArrayExpStructByVal([In]S_INTArray_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeUIntArrayExpStructByVal([In]S_UINTArray_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeShortArrayExpStructByVal([In]S_SHORTArray_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeWordArrayExpStructByVal([In]S_WORDArray_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeLong64ArrayExpStructByVal([In]S_LONG64Array_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeULong64ArrayExpStructByVal([In]S_ULONG64Array_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeDoubleArrayExpStructByVal([In]S_DOUBLEArray_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeFloatArrayExpStructByVal([In]S_FLOATArray_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeByteArrayExpStructByVal([In]S_BYTEArray_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeCharArrayExpStructByVal([In]S_CHARArray_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeLPSTRArrayExpStructByVal([In]S_LPSTRArray_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeLPCSTRArrayExpStructByVal([In]S_LPCSTRArray_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeBSTRArrayExpStructByVal([In]S_BSTRArray_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeStructArrayExpStructByVal([In]S_StructArray_Exp s, int size);
//for RunTest4
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeIntArrayExpClassByVal([In]C_INTArray_Exp c, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeUIntArrayExpClassByVal([In]C_UINTArray_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeShortArrayExpClassByVal([In]C_SHORTArray_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeWordArrayExpClassByVal([In]C_WORDArray_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeLong64ArrayExpClassByVal([In]C_LONG64Array_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeULong64ArrayExpClassByVal([In]C_ULONG64Array_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeDoubleArrayExpClassByVal([In]C_DOUBLEArray_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeFloatArrayExpClassByVal([In]C_FLOATArray_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeByteArrayExpClassByVal([In]C_BYTEArray_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeCharArrayExpClassByVal([In]C_CHARArray_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeLPSTRArrayExpClassByVal([In]C_LPSTRArray_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeLPCSTRArrayExpClassByVal([In]C_LPCSTRArray_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeBSTRArrayExpClassByVal([In]C_BSTRArray_Exp s, int size);
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern bool TakeStructArrayExpClassByVal([In]C_StructArray_Exp s, int size);
//for RunTest5
//get struct on C++ side as sequential class
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern S_INTArray_Seq S_INTArray_Ret_ByValue();
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern C_INTArray_Seq S_INTArray_Ret();
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern C_UINTArray_Seq S_UINTArray_Ret();
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern C_SHORTArray_Seq S_SHORTArray_Ret();
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern C_WORDArray_Seq S_WORDArray_Ret();
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern C_LONG64Array_Seq S_LONG64Array_Ret();
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern C_ULONG64Array_Seq S_ULONG64Array_Ret();
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern C_DOUBLEArray_Seq S_DOUBLEArray_Ret();
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern C_FLOATArray_Seq S_FLOATArray_Ret();
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern C_BYTEArray_Seq S_BYTEArray_Ret();
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern C_CHARArray_Seq S_CHARArray_Ret();
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern C_LPSTRArray_Seq S_LPSTRArray_Ret();
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern C_BSTRArray_Seq S_BSTRArray_Ret();
[DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)]
static extern C_StructArray_Seq S_StructArray_Ret();
//for RunTest6
//get struct on C++ side as explicit class
[DllImport("MarshalArrayByValArrayNative", EntryPoint = "S_INTArray_Ret")]
static extern C_INTArray_Exp S_INTArray_Ret2();
[DllImport("MarshalArrayByValArrayNative", EntryPoint = "S_UINTArray_Ret")]
static extern C_UINTArray_Exp S_UINTArray_Ret2();
[DllImport("MarshalArrayByValArrayNative", EntryPoint = "S_SHORTArray_Ret")]
static extern C_SHORTArray_Exp S_SHORTArray_Ret2();
[DllImport("MarshalArrayByValArrayNative", EntryPoint = "S_WORDArray_Ret")]
static extern C_WORDArray_Exp S_WORDArray_Ret2();
[DllImport("MarshalArrayByValArrayNative", EntryPoint = "S_LONG64Array_Ret")]
static extern C_LONG64Array_Exp S_LONG64Array_Ret2();
[DllImport("MarshalArrayByValArrayNative", EntryPoint = "S_ULONG64Array_Ret")]
static extern C_ULONG64Array_Exp S_ULONG64Array_Ret2();
[DllImport("MarshalArrayByValArrayNative", EntryPoint = "S_DOUBLEArray_Ret")]
static extern C_DOUBLEArray_Exp S_DOUBLEArray_Ret2();
[DllImport("MarshalArrayByValArrayNative", EntryPoint = "S_FLOATArray_Ret")]
static extern C_FLOATArray_Exp S_FLOATArray_Ret2();
[DllImport("MarshalArrayByValArrayNative", EntryPoint = "S_BYTEArray_Ret")]
static extern C_BYTEArray_Exp S_BYTEArray_Ret2();
[DllImport("MarshalArrayByValArrayNative", EntryPoint = "S_CHARArray_Ret")]
static extern C_CHARArray_Exp S_CHARArray_Ret2();
[DllImport("MarshalArrayByValArrayNative", EntryPoint = "S_LPSTRArray_Ret")]
static extern C_LPSTRArray_Exp S_LPSTRArray_Ret2();
[DllImport("MarshalArrayByValArrayNative", EntryPoint = "S_BSTRArray_Ret")]
static extern C_BSTRArray_Exp S_BSTRArray_Ret2();
[DllImport("MarshalArrayByValArrayNative", EntryPoint = "S_StructArray_Ret")]
static extern C_StructArray_Exp S_StructArray_Ret2();
#region Helper
internal const int ARRAY_SIZE = 100;
static T[] InitArray<T>(int size)
{
T[] array = new T[size];
for (int i = 0; i < array.Length; i++)
array[i] = (T)Convert.ChangeType(i, typeof(T));
return array;
}
static TestStruct[] InitStructArray(int size)
{
TestStruct[] array = new TestStruct[size];
for (int i = 0; i < array.Length; i++)
{
array[i].x = i;
array[i].d = i;
array[i].l = i;
array[i].str = i.ToString();
}
return array;
}
static bool[] InitBoolArray(int size)
{
bool[] array = new bool[size];
for (int i = 0; i < array.Length; i++)
{
if (i % 2 == 0)
array[i] = true;
else
array[i] = false;
}
return array;
}
static bool Equals<T>(T[] arr1, T[] arr2)
{
if (arr1 == null && arr2 == null)
return true;
else if (arr1 == null && arr2 != null)
return false;
else if (arr1 != null && arr2 == null)
return false;
else if (arr1.Length != arr2.Length)
return false;
for (int i = 0; i < arr2.Length; ++i)
{
if (!Object.Equals(arr1[i], arr2[i]))
{
Console.WriteLine("Array marshaling error, when type is {0}", typeof(T));
Console.WriteLine("Expected: {0}, Actual: {1}", arr1[i], arr2[i]);
return false;
}
}
return true;
}
static bool TestStructEquals(TestStruct[] tsArr1, TestStruct[] tsArr2)
{
if (tsArr1 == null && tsArr2 == null)
return true;
else if (tsArr1 == null && tsArr2 != null)
return false;
else if (tsArr1 != null && tsArr2 == null)
return false;
else if (tsArr1.Length != tsArr2.Length)
return false;
bool result = true;
for (int i = 0; i < tsArr2.Length; i++)
{
result = (tsArr1[i].x == tsArr2[i].x &&
tsArr1[i].d == tsArr2[i].d &&
tsArr1[i].l == tsArr2[i].l &&
tsArr1[i].str == tsArr2[i].str) && result;
}
return result;
}
#endregion
static void RunTest1(string report)
{
Console.WriteLine(report);
S_INTArray_Seq s1 = new S_INTArray_Seq();
s1.arr = InitArray<int>(ARRAY_SIZE);
Assert.IsTrue(TakeIntArraySeqStructByVal(s1, s1.arr.Length), "TakeIntArraySeqStructByVal");
S_UINTArray_Seq s2 = new S_UINTArray_Seq();
s2.arr = InitArray<uint>(ARRAY_SIZE);
Assert.IsTrue(TakeUIntArraySeqStructByVal(s2, s2.arr.Length), "TakeUIntArraySeqStructByVal");
S_SHORTArray_Seq s3 = new S_SHORTArray_Seq();
s3.arr = InitArray<short>(ARRAY_SIZE);
Assert.IsTrue(TakeShortArraySeqStructByVal(s3, s3.arr.Length), "TakeShortArraySeqStructByVal");
S_WORDArray_Seq s4 = new S_WORDArray_Seq();
s4.arr = InitArray<ushort>(ARRAY_SIZE);
Assert.IsTrue(TakeWordArraySeqStructByVal(s4, s4.arr.Length), "TakeWordArraySeqStructByVal");
S_LONG64Array_Seq s5 = new S_LONG64Array_Seq();
s5.arr = InitArray<long>(ARRAY_SIZE);
Assert.IsTrue(TakeLong64ArraySeqStructByVal(s5, s5.arr.Length), "TakeLong64ArraySeqStructByVal");
S_ULONG64Array_Seq s6 = new S_ULONG64Array_Seq();
s6.arr = InitArray<ulong>(ARRAY_SIZE);
Assert.IsTrue(TakeULong64ArraySeqStructByVal(s6, s6.arr.Length), "TakeULong64ArraySeqStructByVal");
S_DOUBLEArray_Seq s7 = new S_DOUBLEArray_Seq();
s7.arr = InitArray<double>(ARRAY_SIZE);
Assert.IsTrue(TakeDoubleArraySeqStructByVal(s7, s7.arr.Length), "TakeDoubleArraySeqStructByVal");
S_FLOATArray_Seq s8 = new S_FLOATArray_Seq();
s8.arr = InitArray<float>(ARRAY_SIZE);
Assert.IsTrue(TakeFloatArraySeqStructByVal(s8, s8.arr.Length), "TakeFloatArraySeqStructByVal");
S_BYTEArray_Seq s9 = new S_BYTEArray_Seq();
s9.arr = InitArray<byte>(ARRAY_SIZE);
Assert.IsTrue(TakeByteArraySeqStructByVal(s9, s9.arr.Length), "TakeByteArraySeqStructByVal");
S_CHARArray_Seq s10 = new S_CHARArray_Seq();
s10.arr = InitArray<char>(ARRAY_SIZE);
Assert.IsTrue(TakeCharArraySeqStructByVal(s10, s10.arr.Length), "TakeCharArraySeqStructByVal");
S_LPSTRArray_Seq s11 = new S_LPSTRArray_Seq();
s11.arr = InitArray<string>(ARRAY_SIZE);
Assert.IsTrue(TakeLPSTRArraySeqStructByVal(s11, s11.arr.Length),"TakeLPSTRArraySeqStructByVal");
S_LPCSTRArray_Seq s12 = new S_LPCSTRArray_Seq();
s12.arr = InitArray<string>(ARRAY_SIZE);
Assert.IsTrue(TakeLPCSTRArraySeqStructByVal(s12, s12.arr.Length),"TakeLPCSTRArraySeqStructByVal");
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
S_BSTRArray_Seq s13 = new S_BSTRArray_Seq();
s13.arr = InitArray<string>(ARRAY_SIZE);
Assert.IsTrue(TakeBSTRArraySeqStructByVal(s13, s13.arr.Length),"TakeBSTRArraySeqStructByVal");
}
S_StructArray_Seq s14 = new S_StructArray_Seq();
s14.arr = InitStructArray(ARRAY_SIZE);
Assert.IsTrue(TakeStructArraySeqStructByVal(s14, s14.arr.Length),"TakeStructArraySeqStructByVal");
EnregisterableNonBlittable_Seq s15 = new EnregisterableNonBlittable_Seq
{
arr = new TestEnum[3]
{
TestEnum.Red,
TestEnum.Green,
TestEnum.Blue
}
};
Assert.IsTrue(TakeEnregistrableNonBlittableSeqStructByVal(s15, s15.arr), "EnregisterableNonBlittableSeqStructByVal");
EnregisterableUserType s16 = new EnregisterableUserType
{
arr = new SimpleStruct[3]
{
new SimpleStruct { fld = 10 },
new SimpleStruct { fld = 25 },
new SimpleStruct { fld = 40 }
}
};
Assert.IsTrue(TakeEnregisterableUserTypeStructByVal(s16, s16.arr), "TakeEnregisterableUserTypeStructByVal");
}
static void RunTest2(string report)
{
Console.WriteLine(report);
C_INTArray_Seq c1 = new C_INTArray_Seq();
c1.arr = InitArray<int>(ARRAY_SIZE);
Assert.IsTrue(TakeIntArraySeqClassByVal(c1, c1.arr.Length));
C_UINTArray_Seq c2 = new C_UINTArray_Seq();
c2.arr = InitArray<uint>(ARRAY_SIZE);
Assert.IsTrue(TakeUIntArraySeqClassByVal(c2, c2.arr.Length));
C_SHORTArray_Seq c3 = new C_SHORTArray_Seq();
c3.arr = InitArray<short>(ARRAY_SIZE);
Assert.IsTrue(TakeShortArraySeqClassByVal(c3, c3.arr.Length));
C_WORDArray_Seq c4 = new C_WORDArray_Seq();
c4.arr = InitArray<ushort>(ARRAY_SIZE);
Assert.IsTrue(TakeWordArraySeqClassByVal(c4, c4.arr.Length));
C_LONG64Array_Seq c5 = new C_LONG64Array_Seq();
c5.arr = InitArray<long>(ARRAY_SIZE);
Assert.IsTrue(TakeLong64ArraySeqClassByVal(c5, c5.arr.Length));
C_ULONG64Array_Seq c6 = new C_ULONG64Array_Seq();
c6.arr = InitArray<ulong>(ARRAY_SIZE);
Assert.IsTrue(TakeULong64ArraySeqClassByVal(c6, c6.arr.Length));
C_DOUBLEArray_Seq c7 = new C_DOUBLEArray_Seq();
c7.arr = InitArray<double>(ARRAY_SIZE);
Assert.IsTrue(TakeDoubleArraySeqClassByVal(c7, c7.arr.Length));
C_FLOATArray_Seq c8 = new C_FLOATArray_Seq();
c8.arr = InitArray<float>(ARRAY_SIZE);
Assert.IsTrue(TakeFloatArraySeqClassByVal(c8, c8.arr.Length));
C_BYTEArray_Seq c9 = new C_BYTEArray_Seq();
c9.arr = InitArray<byte>(ARRAY_SIZE);
Assert.IsTrue(TakeByteArraySeqClassByVal(c9, c9.arr.Length));
C_CHARArray_Seq c10 = new C_CHARArray_Seq();
c10.arr = InitArray<char>(ARRAY_SIZE);
Assert.IsTrue(TakeCharArraySeqClassByVal(c10, c10.arr.Length));
C_LPSTRArray_Seq c11 = new C_LPSTRArray_Seq();
c11.arr = InitArray<string>(ARRAY_SIZE);
Assert.IsTrue(TakeLPSTRArraySeqClassByVal(c11, c11.arr.Length));
C_LPCSTRArray_Seq c12 = new C_LPCSTRArray_Seq();
c12.arr = InitArray<string>(ARRAY_SIZE);
Assert.IsTrue(TakeLPCSTRArraySeqClassByVal(c12, c12.arr.Length));
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
C_BSTRArray_Seq c13 = new C_BSTRArray_Seq();
c13.arr = InitArray<string>(ARRAY_SIZE);
Assert.IsTrue(TakeBSTRArraySeqClassByVal(c13, c13.arr.Length));
}
C_StructArray_Seq c14 = new C_StructArray_Seq();
c14.arr = InitStructArray(ARRAY_SIZE);
Assert.IsTrue(TakeStructArraySeqClassByVal(c14, c14.arr.Length));
}
static void RunTest3(string report)
{
Console.WriteLine(report);
S_INTArray_Exp s1 = new S_INTArray_Exp();
s1.arr = InitArray<int>(ARRAY_SIZE);
Assert.IsTrue(TakeIntArrayExpStructByVal(s1, s1.arr.Length), "TakeIntArrayExpStructByVal");
S_UINTArray_Exp s2 = new S_UINTArray_Exp();
s2.arr = InitArray<uint>(ARRAY_SIZE);
Assert.IsTrue(TakeUIntArrayExpStructByVal(s2, s2.arr.Length), "TakeUIntArrayExpStructByVal");
S_SHORTArray_Exp s3 = new S_SHORTArray_Exp();
s3.arr = InitArray<short>(ARRAY_SIZE);
Assert.IsTrue(TakeShortArrayExpStructByVal(s3, s3.arr.Length), "TakeShortArrayExpStructByVal");
S_WORDArray_Exp s4 = new S_WORDArray_Exp();
s4.arr = InitArray<ushort>(ARRAY_SIZE);
Assert.IsTrue(TakeWordArrayExpStructByVal(s4, s4.arr.Length), "TakeWordArrayExpStructByVal");
S_LONG64Array_Exp s5 = new S_LONG64Array_Exp();
s5.arr = InitArray<long>(ARRAY_SIZE);
Assert.IsTrue(TakeLong64ArrayExpStructByVal(s5, s5.arr.Length), "TakeLong64ArrayExpStructByVal");
S_ULONG64Array_Exp s6 = new S_ULONG64Array_Exp();
s6.arr = InitArray<ulong>(ARRAY_SIZE);
Assert.IsTrue(TakeULong64ArrayExpStructByVal(s6, s6.arr.Length), "TakeULong64ArrayExpStructByVal");
S_DOUBLEArray_Exp s7 = new S_DOUBLEArray_Exp();
s7.arr = InitArray<double>(ARRAY_SIZE);
Assert.IsTrue(TakeDoubleArrayExpStructByVal(s7, s7.arr.Length), "TakeDoubleArrayExpStructByVal");
S_FLOATArray_Exp s8 = new S_FLOATArray_Exp();
s8.arr = InitArray<float>(ARRAY_SIZE);
Assert.IsTrue(TakeFloatArrayExpStructByVal(s8, s8.arr.Length), "TakeFloatArrayExpStructByVal");
S_BYTEArray_Exp s9 = new S_BYTEArray_Exp();
s9.arr = InitArray<byte>(ARRAY_SIZE);
Assert.IsTrue(TakeByteArrayExpStructByVal(s9, s9.arr.Length), "TakeByteArrayExpStructByVal");
S_CHARArray_Exp s10 = new S_CHARArray_Exp();
s10.arr = InitArray<char>(ARRAY_SIZE);
Assert.IsTrue(TakeCharArrayExpStructByVal(s10, s10.arr.Length), "TakeCharArrayExpStructByVal");
S_LPSTRArray_Exp s11 = new S_LPSTRArray_Exp();
s11.arr = InitArray<string>(ARRAY_SIZE);
Assert.IsTrue(TakeLPSTRArrayExpStructByVal(s11, s11.arr.Length));
S_LPCSTRArray_Exp s12 = new S_LPCSTRArray_Exp();
s12.arr = InitArray<string>(ARRAY_SIZE);
Assert.IsTrue(TakeLPCSTRArrayExpStructByVal(s12, s12.arr.Length));
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
S_BSTRArray_Exp c13 = new S_BSTRArray_Exp();
c13.arr = InitArray<string>(ARRAY_SIZE);
Assert.IsTrue(TakeBSTRArrayExpStructByVal(c13, c13.arr.Length));
}
S_StructArray_Exp s14 = new S_StructArray_Exp();
s14.arr = InitStructArray(ARRAY_SIZE);
Assert.IsTrue(TakeStructArrayExpStructByVal(s14, s14.arr.Length));
}
static void RunTest4(string report)
{
Console.WriteLine(report);
C_INTArray_Exp c1 = new C_INTArray_Exp();
c1.arr = InitArray<int>(ARRAY_SIZE);
Assert.IsTrue(TakeIntArrayExpClassByVal(c1, c1.arr.Length));
C_UINTArray_Exp c2 = new C_UINTArray_Exp();
c2.arr = InitArray<uint>(ARRAY_SIZE);
Assert.IsTrue(TakeUIntArrayExpClassByVal(c2, c2.arr.Length));
C_SHORTArray_Exp c3 = new C_SHORTArray_Exp();
c3.arr = InitArray<short>(ARRAY_SIZE);
Assert.IsTrue(TakeShortArrayExpClassByVal(c3, c3.arr.Length));
C_WORDArray_Exp c4 = new C_WORDArray_Exp();
c4.arr = InitArray<ushort>(ARRAY_SIZE);
Assert.IsTrue(TakeWordArrayExpClassByVal(c4, c4.arr.Length));
C_LONG64Array_Exp c5 = new C_LONG64Array_Exp();
c5.arr = InitArray<long>(ARRAY_SIZE);
Assert.IsTrue(TakeLong64ArrayExpClassByVal(c5, c5.arr.Length));
C_ULONG64Array_Exp c6 = new C_ULONG64Array_Exp();
c6.arr = InitArray<ulong>(ARRAY_SIZE);
Assert.IsTrue(TakeULong64ArrayExpClassByVal(c6, c6.arr.Length));
C_DOUBLEArray_Exp c7 = new C_DOUBLEArray_Exp();
c7.arr = InitArray<double>(ARRAY_SIZE);
Assert.IsTrue(TakeDoubleArrayExpClassByVal(c7, c7.arr.Length));
C_FLOATArray_Exp c8 = new C_FLOATArray_Exp();
c8.arr = InitArray<float>(ARRAY_SIZE);
Assert.IsTrue(TakeFloatArrayExpClassByVal(c8, c8.arr.Length));
C_BYTEArray_Exp c9 = new C_BYTEArray_Exp();
c9.arr = InitArray<byte>(ARRAY_SIZE);
Assert.IsTrue(TakeByteArrayExpClassByVal(c9, c9.arr.Length));
C_CHARArray_Exp c10 = new C_CHARArray_Exp();
c10.arr = InitArray<char>(ARRAY_SIZE);
Assert.IsTrue(TakeCharArrayExpClassByVal(c10, c10.arr.Length));
C_LPSTRArray_Exp c11 = new C_LPSTRArray_Exp();
c11.arr = InitArray<string>(ARRAY_SIZE);
Assert.IsTrue(TakeLPSTRArrayExpClassByVal(c11, c11.arr.Length));
C_LPCSTRArray_Exp c12 = new C_LPCSTRArray_Exp();
c12.arr = InitArray<string>(ARRAY_SIZE);
Assert.IsTrue(TakeLPCSTRArrayExpClassByVal(c12, c12.arr.Length));
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
C_BSTRArray_Exp c13 = new C_BSTRArray_Exp();
c13.arr = InitArray<string>(ARRAY_SIZE);
Assert.IsTrue(TakeBSTRArrayExpClassByVal(c13, c13.arr.Length));
}
C_StructArray_Exp c14 = new C_StructArray_Exp();
c14.arr = InitStructArray(ARRAY_SIZE);
Assert.IsTrue(TakeStructArrayExpClassByVal(c14, c14.arr.Length));
}
static void RunTest5(string report)
{
Console.WriteLine(report);
S_INTArray_Seq retval = S_INTArray_Ret_ByValue();
Assert.IsTrue(Equals(InitArray<int>(ARRAY_SIZE), retval.arr));
C_INTArray_Seq retval1 = S_INTArray_Ret();
Assert.IsTrue(Equals(InitArray<int>(ARRAY_SIZE), retval1.arr));
C_UINTArray_Seq retval2 = S_UINTArray_Ret();
Assert.IsTrue(Equals(InitArray<uint>(ARRAY_SIZE), retval2.arr));
C_SHORTArray_Seq retval3 = S_SHORTArray_Ret();
Assert.IsTrue(Equals(InitArray<short>(ARRAY_SIZE), retval3.arr));
C_WORDArray_Seq retval4 = S_WORDArray_Ret();
Assert.IsTrue(Equals(InitArray<ushort>(ARRAY_SIZE), retval4.arr));
C_LONG64Array_Seq retval5 = S_LONG64Array_Ret();
Assert.IsTrue(Equals(InitArray<long>(ARRAY_SIZE), retval5.arr));
C_ULONG64Array_Seq retval6 = S_ULONG64Array_Ret();
Assert.IsTrue(Equals(InitArray<ulong>(ARRAY_SIZE), retval6.arr));
C_DOUBLEArray_Seq retval7 = S_DOUBLEArray_Ret();
Assert.IsTrue(Equals(InitArray<double>(ARRAY_SIZE), retval7.arr));
C_FLOATArray_Seq retval8 = S_FLOATArray_Ret();
Assert.IsTrue(Equals(InitArray<float>(ARRAY_SIZE), retval8.arr));
C_BYTEArray_Seq retval9 = S_BYTEArray_Ret();
Assert.IsTrue(Equals(InitArray<byte>(ARRAY_SIZE), retval9.arr));
C_CHARArray_Seq retval10 = S_CHARArray_Ret();
Assert.IsTrue(Equals(InitArray<char>(ARRAY_SIZE), retval10.arr));
C_LPSTRArray_Seq retval11 = S_LPSTRArray_Ret();
Assert.IsTrue(Equals(InitArray<string>(ARRAY_SIZE), retval11.arr));
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
C_BSTRArray_Seq retval12 = S_BSTRArray_Ret();
Assert.IsTrue(Equals(InitArray<string>(ARRAY_SIZE), retval12.arr));
}
C_StructArray_Seq retval13 = S_StructArray_Ret();
Assert.IsTrue(TestStructEquals(InitStructArray(ARRAY_SIZE), retval13.arr));
}
static void RunTest6(string report)
{
Console.WriteLine(report);
C_INTArray_Exp retval1 = S_INTArray_Ret2();
Assert.IsTrue(Equals(InitArray<int>(ARRAY_SIZE), retval1.arr));
C_UINTArray_Exp retval2 = S_UINTArray_Ret2();
Assert.IsTrue(Equals(InitArray<uint>(ARRAY_SIZE), retval2.arr));
C_SHORTArray_Exp retval3 = S_SHORTArray_Ret2();
Assert.IsTrue(Equals(InitArray<short>(ARRAY_SIZE), retval3.arr));
C_WORDArray_Exp retval4 = S_WORDArray_Ret2();
Assert.IsTrue(Equals(InitArray<ushort>(ARRAY_SIZE), retval4.arr));
C_LONG64Array_Exp retval5 = S_LONG64Array_Ret2();
Assert.IsTrue(Equals(InitArray<long>(ARRAY_SIZE), retval5.arr));
C_ULONG64Array_Exp retval6 = S_ULONG64Array_Ret2();
Assert.IsTrue(Equals(InitArray<ulong>(ARRAY_SIZE), retval6.arr));
C_DOUBLEArray_Exp retval7 = S_DOUBLEArray_Ret2();
Assert.IsTrue(Equals(InitArray<double>(ARRAY_SIZE), retval7.arr));
C_FLOATArray_Exp retval8 = S_FLOATArray_Ret2();
Assert.IsTrue(Equals(InitArray<float>(ARRAY_SIZE), retval8.arr));
C_BYTEArray_Exp retval9 = S_BYTEArray_Ret2();
Assert.IsTrue(Equals(InitArray<byte>(ARRAY_SIZE), retval9.arr));
C_CHARArray_Exp retval10 = S_CHARArray_Ret2();
Assert.IsTrue(Equals(InitArray<char>(ARRAY_SIZE), retval10.arr));
C_LPSTRArray_Exp retval11 = S_LPSTRArray_Ret2();
Assert.IsTrue(Equals(InitArray<string>(ARRAY_SIZE), retval11.arr));
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
C_BSTRArray_Exp retval12 = S_BSTRArray_Ret2();
Assert.IsTrue(Equals(InitArray<string>(ARRAY_SIZE), retval12.arr));
}
C_StructArray_Exp retval13 = S_StructArray_Ret2();
Assert.IsTrue(TestStructEquals(InitStructArray(ARRAY_SIZE), retval13.arr));
}
static int Main(string[] args)
{
try
{
RunTest1("RunTest1 : Marshal array as field as ByValArray in sequential struct as parameter.");
RunTest2("RunTest2 : Marshal array as field as ByValArray in sequential class as parameter.");
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
RunTest3("RunTest3 : Marshal array as field as ByValArray in explicit struct as parameter.");
}
RunTest4("RunTest4 : Marshal array as field as ByValArray in explicit class as parameter.");
RunTest5("RunTest5 : Marshal array as field as ByValArray in sequential class as return type.");
RunTest6("RunTest6 : Marshal array as field as ByValArray in explicit class as return type.");
Console.WriteLine("\nTest PASS.");
return 100;
}
catch (Exception e)
{
Console.WriteLine($"\nTEST FAIL: {e.Message}");
return 101;
}
}
}
| |
//
// Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s).
// All rights reserved.
//
using System;
using System.Xml;
using OpenADK.Library.Tools.XPath;
namespace OpenADK.Library.Impl.Surrogates
{
/// <summary>
/// Implements a flexible Rendering surrogate based on a proprietary XPath syntax
/// </summary>
internal class XPathSurrogate : AbstractRenderSurrogate, IRenderSurrogate
{
private String fLegacyXpath;
private String fValueXpath;
public XPathSurrogate( IElementDef def,
String xpathMacro )
: base( def )
{
String[] macroParts = xpathMacro.Split( '=' );
fLegacyXpath = macroParts[0];
fValueXpath = macroParts[1];
}
public void RenderRaw(
XmlWriter writer,
SifVersion version,
Element o,
SifFormatter formatter )
{
SifSimpleType value;
// Read the value out of the source object
if ( fValueXpath.StartsWith( "." ) )
{
value = o.SifValue;
}
else
{
IElementDef valueDef = null;
if ( o is SifElement )
{
valueDef = Adk.Dtd.LookupElementDefBySQP( o.ElementDef, fValueXpath );
}
if ( valueDef == null )
{
throw new InvalidOperationException
( "Support for value path {" + fValueXpath +
"} is not supported by XPathSurrogate." );
}
SimpleField field = ((SifElement) o).GetField( valueDef );
if ( field == null )
{
return;
}
value = field.SifValue;
}
if ( value == null )
{
return;
}
String[] xPathParts = fLegacyXpath.Split( '/' );
int currentSegment = 0;
// Build the path
while ( currentSegment < xPathParts.Length - 1 )
{
writer.WriteStartElement( xPathParts[currentSegment] );
currentSegment++;
}
String finalSegment = xPathParts[currentSegment];
if ( finalSegment.StartsWith( "@" ) )
{
writer.WriteAttributeString(
finalSegment.Substring( 1 ),
value.ToString( formatter ) );
}
else
{
// Note: finalSegment can be equal to ".", which
// signals to render the text only
if ( finalSegment.Length > 1 )
{
writer.WriteStartElement( finalSegment );
currentSegment++;
}
writer.WriteValue( value.ToString( formatter ) );
}
currentSegment--;
// unwind the path
while ( currentSegment > -1 )
{
writer.WriteEndElement();
currentSegment--;
}
}
public bool ReadRaw(
XmlReader reader,
SifVersion version,
SifElement parent,
SifFormatter formatter )
{
String value = null;
//
// STEP 1
// Determine if this surrogate can handle the parsing of this node.
// Retrieve the node value as a string
//
String[] xPathParts = fLegacyXpath.Split( '/' );
XmlNodeType eventType = reader.NodeType;
String localName = reader.LocalName;
if ( eventType == XmlNodeType.Element &&
localName.Equals( xPathParts[0] ) )
{
try
{
int currentSegment = 0;
int lastSegment = xPathParts.Length - 1;
if ( xPathParts[lastSegment].StartsWith( "@" ) )
{
lastSegment--;
}
while ( currentSegment < lastSegment )
{
reader.Read();
currentSegment++;
if ( !reader.LocalName.Equals( xPathParts[currentSegment] ) )
{
ThrowParseException
( "Element {" + reader.LocalName +
"} is not supported by XPathSurrogate path " + fLegacyXpath,
version );
}
}
// New we are at the last segment in the XPath, and the XMLStreamReader
// should be positioned on the proper node. The last segment is either
// an attribute or an element, which need to be read differently
String finalSegment = xPathParts[xPathParts.Length - 1];
if ( finalSegment.StartsWith( "@" ) )
{
value = reader.GetAttribute( finalSegment.Substring( 1 ) );
}
else
{
value = ReadElementTextValue( reader );
}
// Note: Unlike the Java ADK, Surrogates in the the .NET ADK do not have to worry about
// completely consuming the XMLElement and advancing to the next tag. The .NET
// Surrogates are handed a reader that only allows reading the current node and
// the parent reader is automatically advanced when the surrogate is done.
}
catch ( Exception xse )
{
ThrowParseException( xse, reader.LocalName, version );
}
}
else
{
// No match was found
return false;
}
//
// STEP 2
// Find the actual field to set the value to
//
IElementDef fieldDef;
SifElement targetElement = parent;
if ( fValueXpath.Equals( "." ) && fElementDef.Field )
{
fieldDef = fElementDef;
}
else
{
// This indicates a child SifElement that needs to be created
try
{
targetElement = SifElement.Create( parent, fElementDef );
}
catch ( AdkSchemaException adkse )
{
ThrowParseException( adkse, reader.LocalName, version );
}
formatter.AddChild( parent, targetElement, version );
if ( fValueXpath.Equals( "." ) )
{
fieldDef = fElementDef;
}
else
{
String fieldName = fValueXpath;
if ( fValueXpath.StartsWith( "@" ) )
{
fieldName = fValueXpath.Substring( 1 );
}
fieldDef = Adk.Dtd.LookupElementDef( fElementDef, fieldName );
}
}
if ( fieldDef == null )
{
throw new InvalidOperationException
( "Support for value path {" + fValueXpath +
"} is not supported by XPathSurrogate." );
}
//
// STEP 3
// Set the value to the field
//
TypeConverter converter = fieldDef.TypeConverter;
if ( converter == null )
{
// TODO: Determine if we should be automatically creating a converter
// for elementDefs that don't have one, or whether we should just throw the
// spurious data away.
converter = SifTypeConverters.STRING;
}
SifSimpleType data = converter.Parse( formatter, value );
targetElement.SetField( fieldDef, data );
return true;
}
/// <summary>
/// Creates a child element, if supported by this node
/// </summary>
/// <param name="parentPointer"></param>
/// <param name="formatter"></param>
/// <param name="version"></param>
/// <param name="context"></param>
/// <returns></returns>
public INodePointer CreateChild( INodePointer parentPointer, SifFormatter formatter, SifVersion version,
SifXPathContext context )
{
// 1) Create an instance of the SimpleField with a null value (It's assigned later)
//
// STEP 2
// Find the actual field to set the value to
//
SifElement parent = (SifElement) ((SifElementPointer) parentPointer).Element;
SifElement targetElement = parent;
if ( !fElementDef.Field )
{
// This indicates a child SifElement that needs to be created
targetElement = SifElement.Create( parent, fElementDef );
formatter.AddChild( parent, targetElement, version );
}
IElementDef fieldDef = null;
if ( fValueXpath.Equals( "." ) )
{
fieldDef = fElementDef;
}
else
{
String fieldName = fValueXpath;
if ( fValueXpath.StartsWith( "@" ) )
{
fieldName = fValueXpath.Substring( 1 );
}
fieldDef = Adk.Dtd.LookupElementDef( fElementDef, fieldName );
}
if ( fieldDef == null )
{
throw new ArgumentException( "Support for value path {" + fValueXpath +
"} is not supported by XPathSurrogate." );
}
SifSimpleType ssf = fieldDef.TypeConverter.GetSifSimpleType( null );
SimpleField sf = ssf.CreateField( targetElement, fieldDef );
targetElement.SetField( sf );
// 2) built out a fake set of node pointers representing the SIF 1.5r1 path and
// return the root pointer from that stack
return BuildLegacyPointers( parentPointer, sf );
}
#region IRenderSurrogate Members
/// <summary>
/// Called by the ADK XPath traversal code when it is traversing the given element
/// in a legacy version of SIF
/// </summary>
/// <param name="parentPointer">The parent element pointer</param>
/// <param name="sourceElement">The Element to create a node pointer for</param>
/// <param name="version">The SIFVersion in effect</param>
/// <returns>A NodePointer representing the current element</returns>
public INodePointer CreateNodePointer( INodePointer parentPointer, Element sourceElement, SifVersion version )
{
// 1) Find the field referenced by the XPathSurrogate expression
// If it doesn't exist, return null
Element referencedField = FindReferencedElement( sourceElement );
if ( referencedField == null )
{
return null;
}
// 2) If it does exist, build out a fake set of node pointers representing the
// SIF 1.5r1 path and return the root pointer.
return BuildLegacyPointers( parentPointer, referencedField );
}
/**
* Finds the element referenced by the expression after the '=' sign in
* the constructor for XPathSurrogate. This path represents the XPath from
* the element being wrapped to the actual field it represents.
* @param startOfPath
* @return
*/
private Element FindReferencedElement( Element startOfPath )
{
// Read the value out of the source object
if ( fValueXpath.StartsWith( "." ) )
{
return startOfPath;
}
else
{
IElementDef valueDef = null;
if ( startOfPath is SifElement )
{
valueDef = Adk.Dtd.LookupElementDefBySQP( startOfPath.ElementDef, fValueXpath );
}
if ( valueDef == null )
{
throw new NotSupportedException( "Support for value path {" + fValueXpath +
"} is not supported by XPathSurrogate." );
}
SimpleField field = ((SifElement) startOfPath).GetField( valueDef );
return field;
}
}
#endregion
private INodePointer BuildLegacyPointers( INodePointer parent, Element referencedField )
{
String[] xPathParts = fLegacyXpath.Split( '/' );
int currentSegment = 0;
INodePointer root = null;
INodePointer currentParent = parent;
// Build the path
while ( currentSegment < xPathParts.Length - 1 )
{
FauxSifElementPointer pointer = new FauxSifElementPointer( currentParent, xPathParts[currentSegment] );
if ( currentParent != null && currentParent is FauxSifElementPointer )
{
((FauxSifElementPointer) currentParent).SetChild( pointer, xPathParts[currentSegment] );
}
currentParent = pointer;
if ( root == null )
{
root = pointer;
}
currentSegment++;
}
String finalSegment = xPathParts[currentSegment];
bool isAttribute = false;
if ( finalSegment.StartsWith( "@" ) )
{
// This is an attribute
finalSegment = finalSegment.Substring( 1 );
isAttribute = true;
}
SurrogateSimpleFieldPointer fieldPointer =
new SurrogateSimpleFieldPointer( currentParent, finalSegment, referencedField, isAttribute );
if ( currentParent != null && currentParent is FauxSifElementPointer )
{
((FauxSifElementPointer) currentParent).SetChild( fieldPointer, finalSegment );
}
if ( root == null )
{
root = fieldPointer;
}
return root;
}
/// <summary>
/// Gets the element name or path to the element in this version of SIF
/// </summary>
public string Path
{
get { return fLegacyXpath; }
}
public String toString()
{
return "XPathSurrogate{" + fLegacyXpath + "=" + fValueXpath + "}";
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Common;
using Versioning;
using Standardization;
using Common.Posting;
using Fairweather.Service;
using D = System.Collections.Generic.Dictionary<string, string>;
using Line = Fairweather.Service.Pair<Common.Posting.Data_Line, Sage_Int.Line_Data>;
namespace Sage_Int
{
// 21 csv\jcjd.csv 0001 screens screens
public partial class SIT_Engine
{
public SIT_Engine(I_SIT_Exe sit_exe) {
this.sit_exe = sit_exe;
sit_exe.Prepare(this);
now = DateTime.Now;
today = now.Date;
}
public event Action Initial_Setup;
public event Action<Quad<string, string, string, bool>> Scan_Started;
public event Action<Quad<Sit_General_Settings, bool, string, string>> Scan_Failed;
public event Action Interface_Started;
public event Action<Triple<int>, string> Interface_Over;
public event Action Connecting;
public event Action Connected;
public event Action Disconnecting;
public event Action Scan_Only_Success;
public event Action Byed;
readonly DateTime now, today;
readonly I_SIT_Exe sit_exe;
public const string STR_0000 = "0000";
static public int?
Try_Start_SIT(
Func<I_SIT_Exe> sit_exe,
out SIT_Engine engine,
out Logging logger,
out Ini_File ini,
out Sit_General_Settings sett_global) {
ini = null;
sett_global = null;
logger = M.Get_Logger(true, false);
M.Set_Culture();
Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
engine = new SIT_Engine(sit_exe());
engine.Exception += _ex => Logging.Notify(_ex);
var null_rc = engine.Initial_Check();
if (null_rc != null)
return null_rc;
if (!M.Get_Ini_File(true, false, out ini)) {
M.Run_Sescfg(false);
return (int)Return_Code.Not_Registered;
}
sett_global = new Sit_General_Settings(ini);
return null;
}
public int
Run(Sit_General_Settings sett_global,
Sit_Company_Settings sett_company,
Record_Type mode,
bool scan_only,
Credentials creds,
string file) {
try {
int? return_code;
// this here because of 'sett_company' and 'mode'
if (!Validate(out return_code, sett_global, sett_company, mode)) {
M.Run_Sescfg(false);
return_code = return_code ?? (int)Return_Code.Unknown_Error;
return return_code.Value;
}
// * read settings
// * handle any of the special program modes:
// - help
// - registration key
/************* ******* ****************/
// stuff we should have by now:
// * invoked program mode
// * company number
// * username
// * password
// * used program switches
if (!Directory.Exists(Data.STR_Sit_History_Dir.Path))
Directory.CreateDirectory(Data.STR_Sit_History_Dir.Path);
if (!Connect(sett_global, sett_company, creds, out sdo, out ws)) {
return Data.CONNECTION_ERROR;
}
var context = new Sage_Context(ws);
var start = DateTime.Now;
// make sure nobody else touches the file
// until we're done with it
FileStream __;
if (!Open_File(file, out __)) {
return Data.OTHER_ERROR;
}
using (__) {
try {
if (!Check_Empty_File(file, sett_company.Has_Headers == true)) {
Warn(@"Empty files are not allowed.");
return Data.LOGIC_ERROR;
}
string[] headers;
var lines = Get_Data_Lines(sett_company, file, mode, out headers);
Dictionary<string, object> defaults;
Get_Defaults(mode, out defaults);
// Phase 2:
// * verify csv structure
// * verify records consistency
Phase_2(out return_code,
context,
sett_global, sett_company,
creds,
mode, scan_only,
defaults,
file,
headers,
lines);
if (return_code != null) {
return return_code.Value;
}
// Phase 3:
// * insert records
Insert(out return_code,
context,
sett_company,
creds,
mode,
defaults,
headers,
lines);
}
finally {
Try_Disconnect();
// debugging
Console.WriteLine((DateTime.Now - start));
Bye();
}
}
return return_code.GetValueOrDefault(0);
}
catch (Exception ex) {
return Handle_Exception(ex);
}
finally {
Bye();
}
}
public int? Initial_Check() {
string msg;
if (!M.Check_For_Files(false, out msg)) {
Warn(msg +
@"
Program cannot continue.");
return Data.LOGIC_ERROR;
}
if (!Check_Instance())
return Data.LOGIC_ERROR;
return null;
}
/// <summary>
/// when you need to parse some arguments before interface
/// </summary>
public int
Run(string[] args, Ini_File ini, Sit_General_Settings sett_global) {
//#if bench
//Benchmark();
//return 0;
//#endif
try {
int? return_code;
List<string> arguments;
Set<string> switches;
Initial_Setup.Raise();
// 21 20090730.CSV 0001 USER PASSWORD
Sift_Args(args, out arguments, out switches);
Handle_Switches(out return_code, arguments, switches, sett_global);
if (return_code != null)
return return_code.Value;
/************* SETTINGS ****************/
if (switches["/?"]) {
sit_exe.Help(ini, sett_global);
return Data.ALL_OK;
}
Sit_Company_Settings sett_company;
Record_Type mode;
bool scan_only;
Credentials creds;
string file;
/* sadly, we need to know the company number to know
* exactly what the arguments mean */
Read_Arguments(
out return_code,
arguments,
ini,
sett_global,
out sett_company,
out mode,
out scan_only,
out creds,
out file);
if (return_code != null)
return return_code.Value;
(arguments.Count >= 2).tiff();
return Run(sett_global, sett_company, mode, scan_only, creds, file);
}
catch (Exception ex) {
return Handle_Exception(ex);
}
finally {
Bye();
}
}
/// <summary>
/// Loads the default new account settings from Sage's database into _defaults[].
/// </summary>
/// <param name="a">1 means load Sales defaults, 2 means Purchase defaults</param>
/// <returns>True on success</returns>
bool
Get_Defaults(Record_Type mode, out Dictionary<string, object> defaults) {
defaults = new Dictionary<string, object>();
Dictionary<string, string> pairs;
if (mode == Record_Type.Sales)
pairs = new Dictionary<string, string>
{
{"COUNTRY_CODE","CUSTOMER_COUNTRY_CODE"},
{"CURRENCY","SALES_CURRENCY"},
{"DEPT_NUMBER","SALES_DEPARTMENT"},
{"DISCOUNT_TYPE","SALES_DISC_TYPE"},
{"SETTLEMENT_DUE_DAYS","SALES_DUEDAYS"},
{"DEF_NOM_CODE","SALES_NOMINAL"},
{"PAYMENT_DUE_DAYS","SALES_PAY_DUE_DAYS"},
{"TERMS","SALES_TERMS"}
//{"DEF_TAX_CODE","SALES_DEF_TAX_CODE"},*/
//{,"SALES_DEF_CALLRATE",""},
};
else if (mode == Record_Type.Purchase)
pairs = new Dictionary<string, string>
{
{"COUNTRY_CODE","SUPPLIER_COUNTRY_CODE"},
{"CURRENCY","PURCHASE_CURRENCY"},
{"CREDIT_LIMIT","PURCHASE_CREDIT_LIMIT"},
{"DEPT_NUMBER","PURCHASE_DEPARTMENT"},
{"DEF_NOM_CODE","PURCHASE_NOMINAL"},
{"SETTLEMENT_DISC_RATE","PURCHASE_SETT_DISCOUNT"},
{"DEF_TAX_CODE","PURCHASE_TAXCODE"},
{"TERMS","PURCHASE_TERMS" }
//{"","DEF_PUR_ADDRESS"},
};
else
return true;
var sd = ws.Create<SetupData>();
bool ignored;
if (!Try(() => sd.Open(OpenMode.sdoRead),
"Unable to read details from Sage",
out ignored))
return false;
try {
defaults.Fill(pairs.Transform_Values(_s => sd[_s]), false);
}
finally {
sd.Close();
}
return true;
}
// ****************************
bool
Sift_Args(
string[] argv,
out List<string> args,
out Set<string> switches) {
//var parser = new Command_Line_Parser(
// true,
// true,
// false,
// '/',
// '=');
//parser.Parse(
// args_in.Select(_a => _a.ToUpper()),
// out t_args,
// out t_sws);
args = new List<string>();
switches = new Set<string>();
for (int ii = 0; ii < argv.Length; ii++) {
var arg = argv[ii];
arg = arg.ToUpper();
arg = arg.Replace("\"", "");
if (arg[0] == '/') {
switches[arg] = true;
continue;
}
if (arg == "?") {
switches["/?"] = true;
continue;
}
args.Add(arg);
}
return true;
}
bool Check_VCRed(Sit_General_Settings sett_global) {
if (sett_global.Version <= 12)
return true;
if (H.Has_VCRed())
return true;
Warn(
@"Microsoft Visual C++ Redistributable package is required,
but has been uninstalled.
Prior to using this software, you will have to run 'SITCFG.exe' in order to install it.");
return false;
}
bool Check_Instance() {
var ret = !H.Other_Instances().Any();
// string prod_id = "InfoTrends.Interface_Tools";
// H.Ensure_Single_Instance(prod_id, false, out mut);
if (!ret) {
Warn(
@"Another instance of Sage Interface Tools is running.
Program cannot continue.");
}
return ret;
}
// ****************************
void
Handle_Switches(out int? return_code,
List<string> arguments,
Set<string> switches,
Sit_General_Settings sett_global) {
H.assign(out return_code);
int cnt = arguments.Count;
if (cnt == 0) {
if (!switches["/R"] && !switches["/?"]) {
Warn(@"Invalid set of parameters.");
Show_Syntax(sett_global);
return_code = Data.LOGIC_ERROR;
return;
}
}
if (cnt <= 1 && !switches["/?"]) {
Warn(@"Invalid set of parameters.");
Show_Syntax(sett_global);
return_code = Data.LOGIC_ERROR;
return;
}
if (switches["/R"]) {
string req = Activation.Activation_Data.Generate_Request(true);
using (var sw = new StreamWriter("RequestCode.txt"))
sw.Write(req);
return_code = Data.ALL_OK;
return;
}
if (switches["/S"]) { // silent mode
var p = Process.GetCurrentProcess();
var hWnd = p.MainWindowHandle;
if (hWnd != IntPtr.Zero)
Native_Methods.ShowWindow(hWnd, 0);
Console.SetOut(new StringWriter());
}
return_code = null;
}
string
Get_Long_Description(Record_Type mode, bool scan_only) {
var ret = "Type of Interface: {0} - {1}".spf(Get_Module_String(mode, scan_only).ToLower(), mode_descriptions[mode]);
if (scan_only)
ret += ", scan only";
return ret;
}
// ****************************
void
Read_Arguments(
out int? return_code,
List<string> arguments,
Ini_File ini,
Sit_General_Settings sett_global,
out Sit_Company_Settings sett_company,
out Record_Type mode,
out bool scan_only,
out Credentials creds,
out string file) {
H.assign(out return_code, out mode, out scan_only);
H.assign(out sett_company, out creds, out file);
int cnt = arguments.Count;
if (cnt < 2) {
// too few arguments
Warn(@"Too few parameters provided.");
Show_Syntax(sett_global);
return_code = Data.WRONG_PARAMETERS;
return;
}
if (cnt == 4) {
// wrong number of arguments
Warn(@"Wrong number of arguments.");
Show_Syntax(sett_global);
return_code = Data.WRONG_PARAMETERS;
return;
}
if (cnt > 5) {
// too many arguments
Warn(@"Too many parameters provided.");
Show_Syntax(sett_global);
return_code = Data.WRONG_PARAMETERS;
return;
}
if (sett_global.CommandLineCredentials == true && cnt < 5) {
// no username/password
Show_Credentials_Message(false);
return_code = Data.WRONG_PARAMETERS;
return;
}
(arguments.Count >= 2).tiff();
if (!Get_Module(arguments, sett_global, out mode, out scan_only)) {
return_code = Data.WRONG_PARAMETERS;
return;
}
Get_Company_Config(
out return_code,
arguments,
ini,
sett_global,
mode,
out creds,
out sett_company);
if (return_code != null)
return;
if (!Get_File(arguments, out file)) {
return_code = Data.LOGIC_ERROR;
return;
}
}
void
Get_Company_Config(
out int? return_code,
List<string> arguments,
Ini_File ini,
Sit_General_Settings sett_global,
Record_Type mode,
out Credentials creds,
out Sit_Company_Settings sett_company) {
Company_Number number;
string username;
string password;
H.assign(out return_code, out creds, out sett_company, out number);
return_code = null;
int cnt = arguments.Count;
if (sett_global.InternalCredentials) {
(cnt == 2 || cnt == 3 || cnt == 5).tiff();
}
else {
(cnt == 5).tiff();
}
string company_string;
if (cnt == 2) {
var def_company = sett_global.Default_Company;
if (def_company == null) {
Warn(
@"There are no registered companies.
Please run sitcfg.exe and register a company,
in order to interface data.");
return_code = Data.LOGIC_ERROR;
return;
}
company_string = def_company.As_String;
}
else {
company_string = arguments[2];
}
int company_int;
var ok = int.TryParse(company_string, out company_int) && company_int > 0;
if (ok) {
number = new Company_Number(company_int);
}
else {
Warn(
@"Company number '{0}' does not exist in the record.
Program cannot continue.", company_string);
return_code = Data.LOGIC_ERROR;
return;
}
sett_company = new Sit_Company_Settings(ini, number, mode);
if (cnt == 5) {
username = arguments[3];
password = arguments[4];
}
else {
username = sett_company.Username;
password = sett_company.Password;
}
if (username.IsNullOrEmpty() ||
password.IsNullOrEmpty()) {
Show_Credentials_Message(sett_global.InternalCredentials);
return_code = Data.LOGIC_ERROR;
return;
}
return_code = null;
creds = new Credentials(number, username, password);
}
bool
Get_File(List<string> arguments, out string file) {
file = Path.GetFullPath(arguments[1].Trim());
if (!File.Exists(file)) {
Warn(@"File '{0}' does not exist.", file);
return false;
}
var name = Path.GetFileName(file);
var ext = Path.GetExtension(file).ToUpper();
if (ext != ".CSV") {
// wl(extension);
Warn(@"Invalid file type. '{0}' is not a CSV file.", name);
return false;
}
return true;
}
string
Get_Module_String(Record_Type mode, bool scan_only) {
return sit_modes[mode] + (scan_only ? "V" : "");
}
bool
Get_Module(List<string> arguments,
Sit_General_Settings sett_global,
out Record_Type mode,
out bool scan_only) {
H.assign(out mode, out scan_only);
var mode_as_string = arguments[0];
var match = mode_as_string.Match(@"^(\d+)(V?)$", RegexOptions.IgnoreCase);
var ret = match.Success;
int mode_as_int = 0;
if (ret) {
if (match.Groups[2].Value.ToUpper() == "V") {
scan_only = true;
mode_as_string = match.Groups[1].Value;
}
ret = int.TryParse(mode_as_string, out mode_as_int);
}
if (ret) {
ret = sit_modes.TryGetValue(mode_as_int, out mode);
if (!ret) {
Warn(@"Invalid module parameter: ""{0}"".", mode_as_int);
// Warn(@"For a list of valid module parameters, type SIT /? and choose option 1.");
Show_Syntax(sett_global);
}
if (sit_tbi_modes[mode]) {
Warn(@"Module ""{0}"" ({1}) is not yet implemented.", mode_as_int, mode_descriptions[mode]);
}
}
return ret;
}
// ****************************
bool
Validate(
out int? return_code,
Sit_General_Settings sett_global,
Sit_Company_Settings sett_company,
Record_Type mode) {
if (!Check_License(sett_global)) {
M.Run_Sescfg(false);
return_code = Data.LICENSE_ERROR;
return false;
}
if (!Check_Companies(sett_global)) {
return_code = Data.LOGIC_ERROR;
return false;
}
if (!Check_Version(sett_global.Version)) {
return_code = Data.LOGIC_ERROR;
return false;
}
if (!Check_VCRed(sett_global)) {
return_code = Data.LOGIC_ERROR;
return false;
}
// Check _company_ settings
if (!Check_Company_Settings(sett_company)) {
return_code = Data.LOGIC_ERROR;
return false;
}
if (!Check_Module_Enabled(sett_global, mode)) {
return_code = Data.LICENSE_ERROR;
return false;
}
return_code = null;
return true;
}
bool Check_License(Sit_General_Settings sett_global) {
var key = sett_global.Activation_Key;
if (!Activation.Activation_Data.ValidateKey(key))
return false;
return true;
}
bool Check_Company_Settings(Sit_Company_Settings sett_company) {
// old story
/*
foreach (var kvp in sett_company) {
if (kvp.Value.IsNullOrEmpty()) {
Warn(
@"Invalid {0} supplied.
Program cannot continue.", kvp.Key);
return false;
}
}*/
return true;
}
bool Check_Version(int ver) {
if (ver >= Activation.Activation_Helpers.min_ver && ver <= Activation.Activation_Helpers.max_ver)
return true;
Warn(
@"Invalid Sage version, should be {0} to {1}.
Program cannot continue.".spf(Activation.Activation_Helpers.min_ver, Activation.Activation_Helpers.max_ver));
return false;
}
bool Check_Module_Enabled(Sit_General_Settings sett_global, Record_Type mode) {
if (record_modes[mode] && sett_global.Records_Module != true) {
Warn(
@"License error.
Your license does not allow you to use the Records Interface.");
return false;
}
if (trans_modes[mode] && sett_global.Trans_Module != true) {
Warn(
@"License error.
Your license does not allow you to use the Transactions Interface.");
return false;
}
if (docs_modes[mode] && sett_global.Docs_Module != true) {
Warn(
@"License error.
Your license does not allow you to use the Documents Interface.");
return false;
}
return true;
}
bool Check_Companies(Sit_General_Settings sett_global) {
var companies = sett_global.Number_Of_Companies;
(companies < -1).tift();
if (companies <= 0) {
Warn(
@"There are no registered companies.
Please run sitcfg.exe and register a company,
in order to interface data.");
return false;
}
return true;
}
void
Phase_2(out int? return_code,
Sage_Context context,
Sit_General_Settings sett_global,
Sit_Company_Settings sett_company,
Credentials creds,
Record_Type mode,
bool scan_only,
Dictionary<string, object> defaults,
string file,
string[] headers,
IEnumerable<Line> lines) {
Clear();
Scan_Started.Raise(Quad.Make(mode_descriptions[mode],
file,
sett_company.Company_Name,
scan_only));
var scan_result = false;
var errors_file_1 = Data.STR_Sit_Error_Log.Path;
File.Delete(Data.STR_Sit_Success_Log.Path);
File.Delete(Data.STR_Sit_Error_Log.Path);
using (var sw = new StreamWriter(errors_file_1, false)) {
Action<string> report = sw.WriteLine;
var errors_file_2 = Get_Errors_Path(creds.Company);
try {
sw.WriteLine("Validation of file: {0}".spf(file));
sw.WriteLine("Date: {0:dd-MM-yyyy} Time: {1:HH:mm:ss}".spf(today, now));
sw.WriteLine("Company Name: " + sett_company.Company_Name);
sw.WriteLine(Get_Long_Description(mode, scan_only));
sw.WriteLine("");
scan_result = Scan(context,
sett_global, sett_company,
creds, mode,
defaults,
file,
headers,
lines,
report);
if (scan_result) {
sw.WriteLine("Validation of file completed successfully.");
if (!scan_only)
sw.WriteLine("Data entered in Sage 50 Accounts.");
}
else {
sw.WriteLine("Validation of file completed with errors.");
sw.WriteLine("No data entered in Sage 50 Accounts.");
}
}
finally {
sw.Try_Dispose();
Try_Copy_File(errors_file_1, errors_file_2);
}
}
if (scan_result) {
if (scan_only) {
//No insertion required
Scan_Only_Success.Raise();
Bye();
return_code = Data.ALL_OK;
return;
}
}
else {
Scan_Failed.Raise(Quad.Make(sett_global, scan_only, file, Data.STR_Sit_Error_Log.Path));
Bye();
return_code = Data.FILE_FAILED_TO_VALIDATE;
return;
}
return_code = null;
}
bool
Connect(Sit_General_Settings sett_global,
Sit_Company_Settings sett_company,
Credentials creds,
out SDO_Engine sdo,
out Work_Space ws) {
sdo = new SDO_Engine(sett_global.Version);
ws = sdo.WSAdd();
Connecting.Raise();
ws.Connect(
sett_company.Company_Path,
creds.Username,
creds.Password,
true);
Connected.Raise();
return true;
}
void
Try_Disconnect() {
var tmp_vWS = ws;
if (tmp_vWS == null)
return;
if (tmp_vWS.Connected) {
Disconnecting.Raise();
tmp_vWS.Disconnect();
}
}
/* Misc */
void
Show_Syntax(Sit_General_Settings sett_global) {
var source = "Program is set to obtain credentials ";
source += sett_global.InternalCredentials ? "from its data file." :
"from the command prompt.";
string syntax = "Syntax: sit <MODULE> <FILENAME> ";
syntax += sett_global.InternalCredentials
? "<company>"
: "<USERNAME> <PASSWORD> <company>";
Warn(source);
Warn(syntax);
}
void
Show_Credentials_Message(bool from_dta) {
Warn(@"Invalid set of credentials (Sage 50 Accounts Username and Password).");
Warn(@"Program is set to obtain credentials from {0}.", from_dta ? "its data file" : "the command-line");
Warn(@"No credentials {0}.",
from_dta
? "for the specified company are on record"
: "have been entered.");
Warn(@"Use SITCFG.exe to:");
Warn(@"1. Define credentials for the specific company, or");
Warn(@"2. Set the program to obtain credentials from the command-lines");
}
public event Action<Exception> Exception;
int
Handle_Exception(Exception ex) {
Exception.Raise(ex);
int? ret = null;
var as_sce = ex as XSage_Conn;
if (as_sce != null) {
switch (as_sce.Connection_Error) {
case Sage_Connection_Error.Exclusive_Mode: {
Warn(
@"Cannot login to Sage, as it is being used in exclusive mode.
Please wait until the program is released and try again.");
return Data.CONNECTION_ERROR;
}
case Sage_Connection_Error.Invalid_Credentials: {
Warn(
@"Invalid or incorrect username or password
Please verify your authentication and try again.");
return Data.CONNECTION_ERROR;
}
case Sage_Connection_Error.Unsupported_Version:
case Sage_Connection_Error.Invalid_Version: {
Warn(
@"Version mismatch occurred.
Please verify that you are using the correct version of Sage.");
return Data.CONNECTION_ERROR;
}
case Sage_Connection_Error.Folder_Does_Not_Exist:
case Sage_Connection_Error.Invalid_Folder: {
Warn(
@"Invalid data path.
Please verify your settings and try again.");
return Data.DATAPATH_ERROR;
}
case Sage_Connection_Error.SDO_Not_Registered: {
Warn(
@"Third party integration not enabled in Sage.
Program cannot continue.");
return Data.CONNECTION_ERROR;
}
case Sage_Connection_Error.Logon_Count_Exceeded: {
Warn(
@"The program cannot log on to Sage at the moment.
Logon count exceeded."
);
return Data.CONNECTION_ERROR;
}
case Sage_Connection_Error.Username_In_Use_Generic:
case Sage_Connection_Error.Username_In_Use_Cant_Remove:
Warn(
@"Cannot login to Sage, as the username provided is already in use.
Please verify your authentication or wait until the username is freed.");
return Data.CONNECTION_ERROR;
case Sage_Connection_Error.Unspecified:
default:
ret = Data.CONNECTION_ERROR;
break;
}
}
Warn(
@"An unexpected error occurred: {0}
Please make sure that you have the correct version of Sage installed, and are using the appropriate settings.", ex.Msg_Or_Type());
return ret ?? Data.OTHER_ERROR;
}
bool is_byed = false;
void Bye() {
if (H.Set(ref is_byed, true))
return;
Try_Disconnect();
Byed.Raise();
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2014 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.IO;
using System.Xml;
using NUnit.Common;
using NUnit.ConsoleRunner.Utilities;
using NUnit.Engine;
using NUnit.Engine.Extensibility;
namespace NUnit.ConsoleRunner
{
/// <summary>
/// ConsoleRunner provides the nunit-console text-based
/// user interface, running the tests and reporting the results.
/// </summary>
public class ConsoleRunner
{
#region Console Runner Return Codes
public static readonly int OK = 0;
public static readonly int INVALID_ARG = -1;
public static readonly int INVALID_ASSEMBLY = -2;
public static readonly int FIXTURE_NOT_FOUND = -3;
public static readonly int UNEXPECTED_ERROR = -100;
#endregion
#region Instance Fields
private ITestEngine _engine;
private ConsoleOptions _options;
private IResultService _resultService;
private ExtendedTextWriter _outWriter;
private TextWriter _errorWriter = Console.Error;
private string _workDirectory;
#endregion
#region Constructor
public ConsoleRunner(ITestEngine engine, ConsoleOptions options, ExtendedTextWriter writer)
{
_engine = engine;
_options = options;
_outWriter = writer;
_workDirectory = options.WorkDirectory;
if (_workDirectory == null)
_workDirectory = Environment.CurrentDirectory;
else if (!Directory.Exists(_workDirectory))
Directory.CreateDirectory(_workDirectory);
_resultService = _engine.Services.GetService<IResultService>();
}
#endregion
#region Execute Method
/// <summary>
/// Executes tests according to the provided commandline options.
/// </summary>
/// <returns></returns>
public int Execute()
{
_outWriter.WriteLine(ColorStyle.SectionHeader, "Test Files");
foreach (string file in _options.InputFiles)
_outWriter.WriteLine(ColorStyle.Default, " " + file);
_outWriter.WriteLine();
WriteRuntimeEnvironment(_outWriter);
TestPackage package = MakeTestPackage(_options);
TestFilter filter = CreateTestFilter(_options);
if (_options.Explore)
return ExploreTests(package, filter);
else
return RunTests(package, filter);
}
#endregion
#region Helper Methods
private int ExploreTests(TestPackage package, TestFilter filter)
{
XmlNode result;
using (var runner = _engine.GetRunner(package))
result = runner.Explore(filter);
if (_options.ExploreOutputSpecifications.Count == 0)
{
_resultService.GetResultWriter("cases", null).WriteResultFile(result, Console.Out);
}
else
{
foreach (OutputSpecification spec in _options.ExploreOutputSpecifications)
{
_resultService.GetResultWriter(spec.Format, new object[] {spec.Transform}).WriteResultFile(result, spec.OutputPath);
_outWriter.WriteLine("Results ({0}) saved as {1}", spec.Format, spec.OutputPath);
}
}
return ConsoleRunner.OK;
}
private int RunTests(TestPackage package, TestFilter filter)
{
// TODO: We really need options as resolved by engine for most of these
DisplayRequestedOptions();
foreach (var spec in _options.ResultOutputSpecifications)
GetResultWriter(spec).CheckWritability(spec.OutputPath);
// TODO: Incorporate this in EventCollector?
RedirectErrorOutputAsRequested();
var labels = _options.DisplayTestLabels != null
? _options.DisplayTestLabels.ToUpperInvariant()
: "ON";
XmlNode result;
try
{
using (new SaveConsoleOutput())
using (new ColorConsole(ColorStyle.Output))
using (ITestRunner runner = _engine.GetRunner(package))
using (var output = CreateOutputWriter())
{
var eventHandler = new TestEventHandler(output, labels, _options.TeamCity);
result = runner.Run(eventHandler, filter);
}
}
finally
{
RestoreErrorOutput();
}
var writer = new ColorConsoleWriter(!_options.NoColor);
var reporter = new ResultReporter(result, writer, _options);
reporter.ReportResults();
foreach (var spec in _options.ResultOutputSpecifications)
{
GetResultWriter(spec).WriteResultFile(result, spec.OutputPath);
_outWriter.WriteLine("Results ({0}) saved as {1}", spec.Format, spec.OutputPath);
}
return reporter.Summary.InvalidAssemblies > 0
? ConsoleRunner.INVALID_ASSEMBLY
: reporter.Summary.FailureCount + reporter.Summary.ErrorCount + reporter.Summary.InvalidCount;
}
private void WriteRuntimeEnvironment(ExtendedTextWriter OutWriter)
{
OutWriter.WriteLine(ColorStyle.SectionHeader, "Runtime Environment");
OutWriter.WriteLabelLine(" OS Version: ", Environment.OSVersion.ToString());
OutWriter.WriteLabelLine(" CLR Version: ", Environment.Version.ToString());
OutWriter.WriteLine();
}
private void DisplayRequestedOptions()
{
_outWriter.WriteLine(ColorStyle.SectionHeader, "Options");
_outWriter.WriteLabel(" ProcessModel: ", _options.ProcessModel ?? "Default");
_outWriter.WriteLabelLine(" DomainUsage: ", _options.DomainUsage ?? "Default");
_outWriter.WriteLabelLine(" Execution Runtime: ", _options.Framework ?? "Not Specified");
if (_options.DefaultTimeout >= 0)
_outWriter.WriteLabelLine(" Default timeout: ", _options.DefaultTimeout.ToString());
if (_options.NumWorkers > 0)
_outWriter.WriteLabelLine(" Worker Threads: ", _options.NumWorkers.ToString());
_outWriter.WriteLabelLine(" Work Directory: ", _workDirectory);
_outWriter.WriteLabelLine(" Internal Trace: ", _options.InternalTraceLevel ?? "Off");
if (_options.TeamCity)
_outWriter.WriteLine(ColorStyle.Label, " Display TeamCity Service Messages");
_outWriter.WriteLine();
if (_options.TestList.Count > 0)
{
_outWriter.WriteLine(ColorStyle.Label, "Selected test(s):");
using (new ColorConsole(ColorStyle.Default))
foreach (string testName in _options.TestList)
_outWriter.WriteLine(" " + testName);
}
if (!string.IsNullOrEmpty(_options.Include))
_outWriter.WriteLabelLine("Included categories: ", _options.Include);
if (!string.IsNullOrEmpty(_options.Exclude))
_outWriter.WriteLabelLine("Excluded categories: ", _options.Exclude);
}
private void RedirectErrorOutputAsRequested()
{
if (_options.ErrFile != null)
{
var errorStreamWriter = new StreamWriter(Path.Combine(_workDirectory, _options.ErrFile));
errorStreamWriter.AutoFlush = true;
_errorWriter = errorStreamWriter;
}
}
private ExtendedTextWriter CreateOutputWriter()
{
if (_options.OutFile != null)
{
var outStreamWriter = new StreamWriter(Path.Combine(_workDirectory, _options.OutFile));
outStreamWriter.AutoFlush = true;
return new ExtendedTextWrapper(outStreamWriter);
}
return _outWriter;
}
private void RestoreErrorOutput()
{
_errorWriter.Flush();
if (_options.ErrFile != null)
_errorWriter.Close();
}
private IResultWriter GetResultWriter(OutputSpecification spec)
{
return _resultService.GetResultWriter(spec.Format, new object[] {spec.Transform});
}
// This is public static for ease of testing
public static TestPackage MakeTestPackage(ConsoleOptions options)
{
TestPackage package = new TestPackage(options.InputFiles);
if (options.ProcessModel != null) //ProcessModel.Default)
package.AddSetting(PackageSettings.ProcessModel, options.ProcessModel);
if (options.DomainUsage != null)
package.AddSetting(PackageSettings.DomainUsage, options.DomainUsage);
if (options.Framework != null)
package.AddSetting(PackageSettings.RuntimeFramework, options.Framework);
if (options.RunAsX86)
package.AddSetting(PackageSettings.RunAsX86, true);
if (options.DisposeRunners)
package.AddSetting(PackageSettings.DisposeRunners, true);
if (options.ShadowCopyFiles)
package.AddSetting(PackageSettings.ShadowCopyFiles, true);
if (options.DefaultTimeout >= 0)
package.AddSetting(PackageSettings.DefaultTimeout, options.DefaultTimeout);
if (options.InternalTraceLevel != null)
package.AddSetting(PackageSettings.InternalTraceLevel, options.InternalTraceLevel);
if (options.ActiveConfig != null)
package.AddSetting(PackageSettings.ActiveConfig, options.ActiveConfig);
if (options.WorkDirectory != null)
package.AddSetting(PackageSettings.WorkDirectory, options.WorkDirectory);
if (options.StopOnError)
package.AddSetting(PackageSettings.StopOnError, true);
if (options.MaxAgents >= 0)
package.AddSetting(PackageSettings.MaxAgents, options.MaxAgents);
if (options.NumWorkers >= 0)
package.AddSetting(PackageSettings.NumberOfTestWorkers, options.NumWorkers);
if (options.RandomSeed > 0)
package.AddSetting(PackageSettings.RandomSeed, options.RandomSeed);
if (options.Verbose)
package.AddSetting("Verbose", true);
if (options.DebugTests)
{
package.AddSetting(PackageSettings.DebugTests, true);
if (options.NumWorkers < 0)
package.AddSetting(PackageSettings.NumberOfTestWorkers, 0);
}
#if DEBUG
if (options.DebugAgent)
package.AddSetting(PackageSettings.DebugAgent, true);
//foreach (KeyValuePair<string, object> entry in package.Settings)
// if (!(entry.Value is string || entry.Value is int || entry.Value is bool))
// throw new Exception(string.Format("Package setting {0} is not a valid type", entry.Key));
#endif
return package;
}
// This is public static for ease of testing
public static TestFilter CreateTestFilter(ConsoleOptions options)
{
TestFilterBuilder builder = new TestFilterBuilder();
foreach (string testName in options.TestList)
builder.Tests.Add(testName);
// TODO: Support multiple include / exclude options
if (options.Include != null)
builder.Include.Add(options.Include);
if (options.Exclude != null)
builder.Exclude.Add(options.Exclude);
return builder.GetFilter();
}
#endregion
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Activities.Presentation.Model
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
// This is a type converter that wraps another type converter. In the
// editing model, we expose all properties as ModelItem objects, so we need
// to unwrap them before handing them to a type converter. This type
// converter provides that unwrapping seamlessly.
[SuppressMessage("XAML", "XAML1004", Justification = "This is internal, and is always available through TypeConverter.GetConverter, not used in xaml")]
class ModelTypeConverter : TypeConverter
{
ModelTreeManager modelTreeManager;
TypeConverter converter;
internal ModelTypeConverter(ModelTreeManager modelTreeManager, TypeConverter converter)
{
this.modelTreeManager = modelTreeManager;
this.converter = converter;
}
// Wraps the given type descriptor context with the set of this.modelTreeManagers
// available in the editing context.
ITypeDescriptorContext WrapContext(ITypeDescriptorContext context)
{
return new ModelTypeDescriptorContextWrapper(context, this.modelTreeManager);
}
// Returns true if the converter can convert from the given source type.
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == null)
{
throw FxTrace.Exception.AsError(new ArgumentNullException("sourceType"));
}
return this.converter.CanConvertFrom(WrapContext(context), sourceType);
}
// Returns true if the converter can convert to the given target type.
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == null)
{
throw FxTrace.Exception.AsError(new ArgumentNullException("destinationType"));
}
return this.converter.CanConvertTo(WrapContext(context), destinationType);
}
// Performs the actual conversion from one type to antother. If the value provided
// is a ModelItem, it will be unwrapped first. The return value is a ModelItem.
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
ModelItem item = value as ModelItem;
if (item != null)
{
value = item.GetCurrentValue();
}
object convertedValue = this.converter.ConvertFrom(WrapContext(context), culture, value);
if (convertedValue != null)
{
convertedValue = this.modelTreeManager.CreateModelItem(null, convertedValue);
}
return convertedValue;
}
// Performs the actual conversion to another type. If the value provided is an item, it will
// be uwrapped first. The return value is the raw data type.
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
ModelItem item = value as ModelItem;
if (item != null)
{
value = item.GetCurrentValue();
}
if (value != null)
{
return this.converter.ConvertTo(WrapContext(context), culture, value, destinationType);
}
return null;
}
// Creates an instance of an object using a dictionary of property values. The
// return value is a wrapped model item.
public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues)
{
object value = this.converter.CreateInstance(WrapContext(context), propertyValues);
if (value != null)
{
value = this.modelTreeManager.CreateModelItem(null, value);
}
return value;
}
// Returns true if the CreateInstance method can be used to create new instances of
// objects.
public override bool GetCreateInstanceSupported(ITypeDescriptorContext context)
{
return this.converter.GetCreateInstanceSupported(WrapContext(context));
}
// Returns child properties for a type converter. This will wrap all properties returned.
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
{
if (value == null)
{
throw FxTrace.Exception.AsError( new ArgumentNullException("value"));
}
ModelItem item = value as ModelItem;
if (item != null)
{
value = item.GetCurrentValue();
}
PropertyDescriptorCollection props = this.converter.GetProperties(WrapContext(context), value, attributes);
if (props != null && props.Count > 0)
{
if (item == null)
{
// We will need the item for this object.
item = this.modelTreeManager.CreateModelItem(null, value);
}
// Search our item for each property and wrap it. If
// a property is not offered by the model, ommit it.
List<PropertyDescriptor> newProps = new List<PropertyDescriptor>(props.Count);
foreach (PropertyDescriptor p in props)
{
ModelProperty modelProp = item.Properties.Find(p.Name);
if (modelProp != null)
{
newProps.Add(new ModelPropertyDescriptor(modelProp));
}
}
props = new PropertyDescriptorCollection(newProps.ToArray(), true);
}
return props;
}
// Returns true if GetProperties will return child properties for the
// object.
public override bool GetPropertiesSupported(ITypeDescriptorContext context)
{
return this.converter.GetPropertiesSupported(WrapContext(context));
}
// Returns a set of standard values this type converter offers.
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
StandardValuesCollection values = this.converter.GetStandardValues(WrapContext(context));
// Some type converters return null here, which isn't supposed to
// be allowed. Fix them
object[] wrappedValues;
if (values == null)
{
wrappedValues = new object[0];
}
else
{
wrappedValues = new object[values.Count];
int idx = 0;
foreach (object value in values)
{
object wrappedValue;
if (value != null)
{
wrappedValue = this.modelTreeManager.CreateModelItem(null, value);
}
else
{
wrappedValue = value;
}
wrappedValues[idx++] = wrappedValue;
}
}
return new StandardValuesCollection(wrappedValues);
}
// Returns true if the set of standard values cannot be customized.
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return this.converter.GetStandardValuesExclusive(WrapContext(context));
}
// Returns true if this type converter offers a set of standard values.
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return this.converter.GetStandardValuesSupported(WrapContext(context));
}
// Returns true if the given value is a valid value for this type converter.
public override bool IsValid(ITypeDescriptorContext context, object value)
{
ModelItem item = value as ModelItem;
if (item != null)
{
value = item.GetCurrentValue();
}
return this.converter.IsValid(WrapContext(context), value);
}
}
}
| |
//
// Copyright 2014-2015 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Amazon Software License (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/asl/
//
// or in the "license" file accompanying this file. This file is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, express or implied. See the License
// for the specific language governing permissions and
// limitations under the License.
//
/*
* Do not modify this file. This file is generated from the dynamodb-2012-08-10.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.DynamoDBv2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.DynamoDBv2.Model.Internal.MarshallTransformations
{
/// <summary>
/// Query Request Marshaller
/// </summary>
public class QueryRequestMarshaller : IMarshaller<IRequest, QueryRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((QueryRequest)input);
}
public IRequest Marshall(QueryRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.DynamoDBv2");
string target = "DynamoDB_20120810.Query";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.0";
request.HttpMethod = "POST";
string uriResourcePath = "/";
request.ResourcePath = uriResourcePath;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetAttributesToGet())
{
context.Writer.WritePropertyName("AttributesToGet");
context.Writer.WriteArrayStart();
foreach(var publicRequestAttributesToGetListValue in publicRequest.AttributesToGet)
{
context.Writer.Write(publicRequestAttributesToGetListValue);
}
context.Writer.WriteArrayEnd();
}
if(publicRequest.IsSetConditionalOperator())
{
context.Writer.WritePropertyName("ConditionalOperator");
context.Writer.Write(publicRequest.ConditionalOperator);
}
if(publicRequest.IsSetConsistentRead())
{
context.Writer.WritePropertyName("ConsistentRead");
context.Writer.Write(publicRequest.ConsistentRead);
}
if(publicRequest.IsSetExclusiveStartKey())
{
context.Writer.WritePropertyName("ExclusiveStartKey");
context.Writer.WriteObjectStart();
foreach (var publicRequestExclusiveStartKeyKvp in publicRequest.ExclusiveStartKey)
{
context.Writer.WritePropertyName(publicRequestExclusiveStartKeyKvp.Key);
var publicRequestExclusiveStartKeyValue = publicRequestExclusiveStartKeyKvp.Value;
context.Writer.WriteObjectStart();
var marshaller = AttributeValueMarshaller.Instance;
marshaller.Marshall(publicRequestExclusiveStartKeyValue, context);
context.Writer.WriteObjectEnd();
}
context.Writer.WriteObjectEnd();
}
if(publicRequest.IsSetExpressionAttributeNames())
{
context.Writer.WritePropertyName("ExpressionAttributeNames");
context.Writer.WriteObjectStart();
foreach (var publicRequestExpressionAttributeNamesKvp in publicRequest.ExpressionAttributeNames)
{
context.Writer.WritePropertyName(publicRequestExpressionAttributeNamesKvp.Key);
var publicRequestExpressionAttributeNamesValue = publicRequestExpressionAttributeNamesKvp.Value;
context.Writer.Write(publicRequestExpressionAttributeNamesValue);
}
context.Writer.WriteObjectEnd();
}
if(publicRequest.IsSetExpressionAttributeValues())
{
context.Writer.WritePropertyName("ExpressionAttributeValues");
context.Writer.WriteObjectStart();
foreach (var publicRequestExpressionAttributeValuesKvp in publicRequest.ExpressionAttributeValues)
{
context.Writer.WritePropertyName(publicRequestExpressionAttributeValuesKvp.Key);
var publicRequestExpressionAttributeValuesValue = publicRequestExpressionAttributeValuesKvp.Value;
context.Writer.WriteObjectStart();
var marshaller = AttributeValueMarshaller.Instance;
marshaller.Marshall(publicRequestExpressionAttributeValuesValue, context);
context.Writer.WriteObjectEnd();
}
context.Writer.WriteObjectEnd();
}
if(publicRequest.IsSetFilterExpression())
{
context.Writer.WritePropertyName("FilterExpression");
context.Writer.Write(publicRequest.FilterExpression);
}
if(publicRequest.IsSetIndexName())
{
context.Writer.WritePropertyName("IndexName");
context.Writer.Write(publicRequest.IndexName);
}
if(publicRequest.IsSetKeyConditions())
{
context.Writer.WritePropertyName("KeyConditions");
context.Writer.WriteObjectStart();
foreach (var publicRequestKeyConditionsKvp in publicRequest.KeyConditions)
{
context.Writer.WritePropertyName(publicRequestKeyConditionsKvp.Key);
var publicRequestKeyConditionsValue = publicRequestKeyConditionsKvp.Value;
context.Writer.WriteObjectStart();
var marshaller = ConditionMarshaller.Instance;
marshaller.Marshall(publicRequestKeyConditionsValue, context);
context.Writer.WriteObjectEnd();
}
context.Writer.WriteObjectEnd();
}
if(publicRequest.IsSetLimit())
{
context.Writer.WritePropertyName("Limit");
context.Writer.Write(publicRequest.Limit);
}
if(publicRequest.IsSetProjectionExpression())
{
context.Writer.WritePropertyName("ProjectionExpression");
context.Writer.Write(publicRequest.ProjectionExpression);
}
if(publicRequest.IsSetQueryFilter())
{
context.Writer.WritePropertyName("QueryFilter");
context.Writer.WriteObjectStart();
foreach (var publicRequestQueryFilterKvp in publicRequest.QueryFilter)
{
context.Writer.WritePropertyName(publicRequestQueryFilterKvp.Key);
var publicRequestQueryFilterValue = publicRequestQueryFilterKvp.Value;
context.Writer.WriteObjectStart();
var marshaller = ConditionMarshaller.Instance;
marshaller.Marshall(publicRequestQueryFilterValue, context);
context.Writer.WriteObjectEnd();
}
context.Writer.WriteObjectEnd();
}
if(publicRequest.IsSetReturnConsumedCapacity())
{
context.Writer.WritePropertyName("ReturnConsumedCapacity");
context.Writer.Write(publicRequest.ReturnConsumedCapacity);
}
if(publicRequest.IsSetScanIndexForward())
{
context.Writer.WritePropertyName("ScanIndexForward");
context.Writer.Write(publicRequest.ScanIndexForward);
}
if(publicRequest.IsSetSelect())
{
context.Writer.WritePropertyName("Select");
context.Writer.Write(publicRequest.Select);
}
if(publicRequest.IsSetTableName())
{
context.Writer.WritePropertyName("TableName");
context.Writer.Write(publicRequest.TableName);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.Azure.Test;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Newtonsoft.Json.Linq;
using Xunit;
namespace ResourceGroups.Tests
{
public class LiveDeploymentTests : TestBase
{
const string DummyTemplateUri = "https://testtemplates.blob.core.windows.net/templates/dummytemplate.js";
const string GoodWebsiteTemplateUri = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/201-web-app-github-deploy/azuredeploy.json";
const string BadTemplateUri = "https://testtemplates.blob.core.windows.net/templates/bad-website-1.js";
const string LocationWestEurope = "West Europe";
const string LocationSouthCentralUS = "South Central US";
public ResourceManagementClient GetResourceManagementClient(MockContext context, RecordedDelegatingHandler handler)
{
handler.IsPassThrough = true;
return this.GetResourceManagementClientWithHandler(context, handler);
}
// TODO: Fix
[Fact (Skip = "TODO: Re-record test")]
public void CreateDummyDeploymentTemplateWorks()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
var dictionary = new Dictionary<string, object> {
{"string", new Dictionary<string, object>() {
{"value", "myvalue"},
}},
{"securestring", new Dictionary<string, object>() {
{"value", "myvalue"},
}},
{"int", new Dictionary<string, object>() {
{"value", 42},
}},
{"bool", new Dictionary<string, object>() {
{"value", true},
}}
};
using (MockContext context = MockContext.Start(this.GetType()))
{
var client = GetResourceManagementClient(context, handler);
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = DummyTemplateUri
},
Parameters = dictionary,
Mode = DeploymentMode.Incremental,
}
};
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope });
client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters);
JObject json = JObject.Parse(handler.Request);
Assert.NotNull(client.Deployments.Get(groupName, deploymentName));
}
}
[Fact()]
public void CreateDeploymentWithStringTemplateAndParameters()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType()))
{
var client = GetResourceManagementClient(context, handler);
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
Template = File.ReadAllText(Path.Combine("ScenarioTests", "simple-storage-account.json")),
Parameters = File.ReadAllText(Path.Combine("ScenarioTests", "simple-storage-account-parameters.json")),
Mode = DeploymentMode.Incremental,
}
};
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope });
client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters);
var deployment = client.Deployments.Get(groupName, deploymentName);
Assert.Equal("Succeeded", deployment.Properties.ProvisioningState);
}
}
[Fact]
public void CreateDeploymentAndValidateProperties()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType()))
{
var client = GetResourceManagementClient(context, handler);
string resourceName = TestUtilities.GenerateName("csmr");
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = GoodWebsiteTemplateUri,
},
Parameters =
JObject.Parse(
@"{'repoURL': {'value': 'https://github.com/devigned/az-roadshow-oss.git'}, 'siteName': {'value': '" + resourceName + "'}, 'location': {'value': 'westus'}, 'sku': {'value': 'F1'}}"),
Mode = DeploymentMode.Incremental,
},
Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } }
};
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope });
var deploymentCreateResult = client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters);
Assert.NotNull(deploymentCreateResult.Id);
Assert.Equal(deploymentName, deploymentCreateResult.Name);
TestUtilities.Wait(1000);
var deploymentListResult = client.Deployments.ListByResourceGroup(groupName, null);
var deploymentGetResult = client.Deployments.Get(groupName, deploymentName);
Assert.NotEmpty(deploymentListResult);
Assert.Equal(deploymentName, deploymentGetResult.Name);
Assert.Equal(deploymentName, deploymentListResult.First().Name);
Assert.Equal(GoodWebsiteTemplateUri, deploymentGetResult.Properties.TemplateLink.Uri);
Assert.Equal(GoodWebsiteTemplateUri, deploymentListResult.First().Properties.TemplateLink.Uri);
Assert.NotNull(deploymentGetResult.Properties.ProvisioningState);
Assert.NotNull(deploymentListResult.First().Properties.ProvisioningState);
Assert.NotNull(deploymentGetResult.Properties.CorrelationId);
Assert.NotNull(deploymentListResult.First().Properties.CorrelationId);
Assert.NotNull(deploymentListResult.First().Tags);
Assert.True(deploymentListResult.First().Tags.ContainsKey("tagKey1"));
}
}
[Fact]
public void ValidateGoodDeployment()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType()))
{
var client = GetResourceManagementClient(context, handler);
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
string resourceName = TestUtilities.GenerateName("csres");
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = GoodWebsiteTemplateUri,
},
Parameters =
JObject.Parse(@"{'repoURL': {'value': 'https://github.com/devigned/az-roadshow-oss.git'}, 'siteName': {'value': '" + resourceName + "'}, 'location': {'value': 'westus'}, 'sku': {'value': 'F1'}}"),
Mode = DeploymentMode.Incremental,
}
};
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope });
//Action
var validationResult = client.Deployments.Validate(groupName, deploymentName, parameters);
//Assert
Assert.Null(validationResult.Error);
Assert.NotNull(validationResult.Properties);
Assert.NotNull(validationResult.Properties.Providers);
Assert.Equal(1, validationResult.Properties.Providers.Count);
Assert.Equal("Microsoft.Web", validationResult.Properties.Providers[0].NamespaceProperty);
}
}
//TODO: Fix
[Fact(Skip = "TODO: Re-record test")]
public void ValidateGoodDeploymentWithInlineTemplate()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType()))
{
var client = GetResourceManagementClient(context, handler);
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
string resourceName = TestUtilities.GenerateName("csmr");
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
Template = File.ReadAllText(Path.Combine("ScenarioTests", "good-website.json")),
Parameters =
JObject.Parse(@"{'repoURL': {'value': 'https://github.com/devigned/az-roadshow-oss.git'}, 'siteName': {'value': '" + resourceName + "'}, 'hostingPlanName': {'value': 'someplan'}, 'siteLocation': {'value': 'westus'}, 'sku': {'value': 'Standard'}}"),
Mode = DeploymentMode.Incremental,
}
};
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope });
//Action
var validationResult = client.Deployments.Validate(groupName, deploymentName, parameters);
//Assert
Assert.Null(validationResult.Error);
Assert.NotNull(validationResult.Properties);
Assert.NotNull(validationResult.Properties.Providers);
Assert.Equal(1, validationResult.Properties.Providers.Count);
Assert.Equal("Microsoft.Web", validationResult.Properties.Providers[0].NamespaceProperty);
}
}
[Fact]
public void ValidateBadDeployment()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType()))
{
var client = GetResourceManagementClient(context, handler);
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = BadTemplateUri,
},
Parameters =
JObject.Parse(@"{ 'siteName': {'value': 'mctest0101'},'hostingPlanName': {'value': 'mctest0101'},'siteMode': {'value': 'Limited'},'computeMode': {'value': 'Shared'},'siteLocation': {'value': 'North Europe'},'sku': {'value': 'Free'},'workerSize': {'value': '0'}}"),
Mode = DeploymentMode.Incremental,
}
};
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope });
var result = client.Deployments.Validate(groupName, deploymentName, parameters);
Assert.NotNull(result);
Assert.Equal("InvalidTemplate", result.Error.Code);
}
}
// TODO: Fix
[Fact(Skip = "TODO: Re-record test")]
public void CreateDummyDeploymentProducesOperations()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
var dictionary = new Dictionary<string, object> {
{"string", new Dictionary<string, object>() {
{"value", "myvalue"},
}},
{"securestring", new Dictionary<string, object>() {
{"value", "myvalue"},
}},
{"int", new Dictionary<string, object>() {
{"value", 42},
}},
{"bool", new Dictionary<string, object>() {
{"value", true},
}}
};
using (MockContext context = MockContext.Start(this.GetType()))
{
var client = GetResourceManagementClient(context, handler);
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = DummyTemplateUri
},
Parameters = dictionary,
Mode = DeploymentMode.Incremental,
}
};
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
string resourceName = TestUtilities.GenerateName("csmr");
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope });
client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters);
// Wait until deployment completes
TestUtilities.Wait(30000);
var operations = client.DeploymentOperations.List(groupName, deploymentName, null);
Assert.True(operations.Any());
Assert.NotNull(operations.First().Id);
Assert.NotNull(operations.First().OperationId);
Assert.NotNull(operations.First().Properties);
}
}
// TODO: Fix
[Fact(Skip = "TODO: Re-record test")]
public void ListDeploymentsWorksWithFilter()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType()))
{
var client = GetResourceManagementClient(context, handler);
string resourceName = TestUtilities.GenerateName("csmr");
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = GoodWebsiteTemplateUri,
},
Parameters =
JObject.Parse(@"{'repoURL': {'value': 'https://github.com/devigned/az-roadshow-oss.git'}, 'siteName': {'value': '" + resourceName + "'}, 'hostingPlanName': {'value': 'someplan'}, 'siteLocation': {'value': 'westus'}, 'sku': {'value': 'Standard'}}"),
Mode = DeploymentMode.Incremental,
}
};
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope });
client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters);
var deploymentListResult = client.Deployments.ListByResourceGroup(groupName, new ODataQuery<DeploymentExtendedFilter>(d => d.ProvisioningState == "Running"));
if (null == deploymentListResult|| deploymentListResult.Count() == 0)
{
deploymentListResult = client.Deployments.ListByResourceGroup(groupName, new ODataQuery<DeploymentExtendedFilter>(d => d.ProvisioningState == "Accepted"));
}
var deploymentGetResult = client.Deployments.Get(groupName, deploymentName);
Assert.NotEmpty(deploymentListResult);
Assert.Equal(deploymentName, deploymentGetResult.Name);
Assert.Equal(deploymentName, deploymentListResult.First().Name);
Assert.Equal(GoodWebsiteTemplateUri, deploymentGetResult.Properties.TemplateLink.Uri);
Assert.Equal(GoodWebsiteTemplateUri, deploymentListResult.First().Properties.TemplateLink.Uri);
Assert.NotNull(deploymentGetResult.Properties.ProvisioningState);
Assert.NotNull(deploymentListResult.First().Properties.ProvisioningState);
Assert.NotNull(deploymentGetResult.Properties.CorrelationId);
Assert.NotNull(deploymentListResult.First().Properties.CorrelationId);
Assert.Contains("mctest0101", deploymentGetResult.Properties.Parameters.ToString());
Assert.Contains("mctest0101", deploymentListResult.First().Properties.Parameters.ToString());
}
}
[Fact]
public void CreateLargeWebDeploymentTemplateWorks()
{
var handler = new RecordedDelegatingHandler();
using (MockContext context = MockContext.Start(this.GetType()))
{
string resourceName = TestUtilities.GenerateName("csmr");
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
var client = GetResourceManagementClient(context, handler);
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = GoodWebsiteTemplateUri,
},
Parameters =
JObject.Parse("{'repoURL': {'value': 'https://github.com/devigned/az-roadshow-oss.git'}, 'siteName': {'value': '" + resourceName + "'}, 'location': {'value': 'westus'}, 'sku': {'value': 'F1'}}"),
Mode = DeploymentMode.Incremental,
}
};
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationSouthCentralUS });
client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters);
// Wait until deployment completes
TestUtilities.Wait(30000);
var operations = client.DeploymentOperations.List(groupName, deploymentName, null);
Assert.True(operations.Any());
}
}
[Fact]
public void SubscriptionLevelDeployment()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType()))
{
var client = GetResourceManagementClient(context, handler);
string groupName = "SDK-test";
string deploymentName = TestUtilities.GenerateName("csmd");
string resourceName = TestUtilities.GenerateName("csmr");
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
Template = JObject.Parse(File.ReadAllText(Path.Combine("ScenarioTests", "subscription_level_template.json"))),
Parameters =
JObject.Parse("{'storageAccountName': {'value': 'armbuilddemo1803'}}"),
Mode = DeploymentMode.Incremental,
},
Location = "WestUS",
Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } }
};
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "WestUS" });
//Validate
var validationResult = client.Deployments.ValidateAtSubscriptionScope(deploymentName, parameters);
//Assert
Assert.Null(validationResult.Error);
Assert.NotNull(validationResult.Properties);
Assert.NotNull(validationResult.Properties.Providers);
//Put deployment
var deploymentResult = client.Deployments.CreateOrUpdateAtSubscriptionScope(deploymentName, parameters);
var deployment = client.Deployments.GetAtSubscriptionScope(deploymentName);
Assert.Equal("Succeeded", deployment.Properties.ProvisioningState);
Assert.NotNull(deployment.Tags);
Assert.True(deployment.Tags.ContainsKey("tagKey1"));
}
}
[Fact]
public void ManagementGroupLevelDeployment()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType()))
{
var client = GetResourceManagementClient(context, handler);
string groupId = "tag-mg1";
string deploymentName = TestUtilities.GenerateName("csharpsdktest");
var parameters = new ScopedDeployment
{
Properties = new DeploymentProperties()
{
Template = JObject.Parse(File.ReadAllText(Path.Combine("ScenarioTests", "management_group_level_template.json"))),
Parameters =
JObject.Parse("{'storageAccountName': {'value': 'tagsa021920'}}"),
Mode = DeploymentMode.Incremental,
},
Location = "East US",
Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } }
};
//Validate
var validationResult = client.Deployments.ValidateAtManagementGroupScope(groupId, deploymentName, parameters);
//Assert
Assert.Null(validationResult.Error);
Assert.NotNull(validationResult.Properties);
Assert.NotNull(validationResult.Properties.Providers);
//Put deployment
var deploymentResult = client.Deployments.CreateOrUpdateAtManagementGroupScope(groupId, deploymentName, parameters);
var deployment = client.Deployments.GetAtManagementGroupScope(groupId, deploymentName);
Assert.Equal("Succeeded", deployment.Properties.ProvisioningState);
Assert.NotNull(deployment.Tags);
Assert.True(deployment.Tags.ContainsKey("tagKey1"));
}
}
[Fact]
public void TenantLevelDeployment()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType()))
{
var client = GetResourceManagementClient(context, handler);
string deploymentName = TestUtilities.GenerateName("csharpsdktest");
var parameters = new ScopedDeployment
{
Properties = new DeploymentProperties()
{
Template = JObject.Parse(File.ReadAllText(Path.Combine("ScenarioTests", "tenant_level_template.json"))),
Parameters =
JObject.Parse("{'managementGroupId': {'value': 'tiano-mgtest01'}}"),
Mode = DeploymentMode.Incremental,
},
Location = "East US 2",
Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } }
};
//Validate
var validationResult = client.Deployments.ValidateAtTenantScope(deploymentName, parameters);
//Assert
Assert.Null(validationResult.Error);
Assert.NotNull(validationResult.Properties);
Assert.NotNull(validationResult.Properties.Providers);
//Put deployment
var deploymentResult = client.Deployments.CreateOrUpdateAtTenantScope(deploymentName, parameters);
var deployment = client.Deployments.GetAtTenantScope(deploymentName);
Assert.Equal("Succeeded", deployment.Properties.ProvisioningState);
Assert.NotNull(deployment.Tags);
Assert.True(deployment.Tags.ContainsKey("tagKey1"));
var deploymentOperations = client.DeploymentOperations.ListAtTenantScope(deploymentName);
Assert.Equal(4, deploymentOperations.Count());
}
}
[Fact]
public void DeploymentWithScope_AtTenant()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType()))
{
var client = GetResourceManagementClient(context, handler);
string deploymentName = TestUtilities.GenerateName("csharpsdktest");
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
Template = JObject.Parse(File.ReadAllText(Path.Combine("ScenarioTests", "tenant_level_template.json"))),
Parameters =
JObject.Parse("{'managementGroupId': {'value': 'tiano-mgtest01'}}"),
Mode = DeploymentMode.Incremental,
},
Location = "East US 2",
Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } }
};
//Validate
var validationResult = client.Deployments.ValidateAtScope(scope: "", deploymentName: deploymentName, parameters: parameters);
//Assert
Assert.Null(validationResult.Error);
Assert.NotNull(validationResult.Properties);
Assert.NotNull(validationResult.Properties.Providers);
//Put deployment
var deploymentResult = client.Deployments.CreateOrUpdateAtScope(scope: "", deploymentName: deploymentName, parameters: parameters);
var deployment = client.Deployments.GetAtScope(scope: "", deploymentName: deploymentName);
Assert.Equal("Succeeded", deployment.Properties.ProvisioningState);
Assert.NotNull(deployment.Tags);
Assert.True(deployment.Tags.ContainsKey("tagKey1"));
var deploymentOperations = client.DeploymentOperations.ListAtScope(scope: "", deploymentName: deploymentName);
Assert.Equal(4, deploymentOperations.Count());
}
}
[Fact]
public void DeploymentWithScope_AtManagementGroup()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType()))
{
var client = GetResourceManagementClient(context, handler);
string groupId = "tag-mg1";
string deploymentName = TestUtilities.GenerateName("csharpsdktest");
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
Template = JObject.Parse(File.ReadAllText(Path.Combine("ScenarioTests", "management_group_level_template.json"))),
Parameters =
JObject.Parse("{'storageAccountName': {'value': 'tagsa1'}}"),
Mode = DeploymentMode.Incremental,
},
Location = "East US",
Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } }
};
var managementGroupScope = $"/providers/Microsoft.Management/managementGroups/{groupId}";
//Validate
var validationResult = client.Deployments.ValidateAtScope(scope: managementGroupScope, deploymentName: deploymentName, parameters: parameters);
//Assert
Assert.Null(validationResult.Error);
Assert.NotNull(validationResult.Properties);
Assert.NotNull(validationResult.Properties.Providers);
//Put deployment
var deploymentResult = client.Deployments.CreateOrUpdateAtScope(scope: managementGroupScope, deploymentName: deploymentName, parameters: parameters);
var deployment = client.Deployments.GetAtScope(scope: managementGroupScope, deploymentName: deploymentName);
Assert.Equal("Succeeded", deployment.Properties.ProvisioningState);
Assert.NotNull(deployment.Tags);
Assert.True(deployment.Tags.ContainsKey("tagKey1"));
var deploymentOperations = client.DeploymentOperations.ListAtScope(scope: managementGroupScope, deploymentName: deploymentName);
Assert.Equal(4, deploymentOperations.Count());
}
}
[Fact]
public void DeploymentWithScope_AtSubscription()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType()))
{
var client = GetResourceManagementClient(context, handler);
string groupName = "SDK-test";
string deploymentName = TestUtilities.GenerateName("csmd");
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
Template = JObject.Parse(File.ReadAllText(Path.Combine("ScenarioTests", "subscription_level_template.json"))),
Parameters =
JObject.Parse("{'storageAccountName': {'value': 'armbuilddemo1803'}}"),
Mode = DeploymentMode.Incremental,
},
Location = "WestUS",
Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } }
};
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "WestUS" });
var subscriptionScope = $"/subscriptions/{client.SubscriptionId}";
//Validate
var validationResult = client.Deployments.ValidateAtScope(scope: subscriptionScope, deploymentName: deploymentName, parameters: parameters);
//Assert
Assert.Null(validationResult.Error);
Assert.NotNull(validationResult.Properties);
Assert.NotNull(validationResult.Properties.Providers);
//Put deployment
var deploymentResult = client.Deployments.CreateOrUpdateAtScope(scope: subscriptionScope, deploymentName: deploymentName, parameters: parameters);
var deployment = client.Deployments.GetAtScope(scope: subscriptionScope, deploymentName: deploymentName);
Assert.Equal("Succeeded", deployment.Properties.ProvisioningState);
Assert.NotNull(deployment.Tags);
Assert.True(deployment.Tags.ContainsKey("tagKey1"));
var deploymentOperations = client.DeploymentOperations.ListAtScope(scope: subscriptionScope, deploymentName: deploymentName);
Assert.Equal(4, deploymentOperations.Count());
}
}
[Fact]
public void DeploymentWithScope_AtResourceGroup()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType()))
{
var client = GetResourceManagementClient(context, handler);
string groupName = "SDK-test-01";
string deploymentName = TestUtilities.GenerateName("csmd");
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
Template = JObject.Parse(File.ReadAllText(Path.Combine("ScenarioTests", "simple-storage-account.json"))),
Parameters =
JObject.Parse("{'storageAccountName': {'value': 'tianotest105'}}"),
Mode = DeploymentMode.Incremental,
},
Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } }
};
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "WestUS" });
var resourceGroupScope = $"/subscriptions/{client.SubscriptionId}/resourceGroups/{groupName}";
//Validate
var validationResult = client.Deployments.ValidateAtScope(scope: resourceGroupScope, deploymentName: deploymentName, parameters: parameters);
//Assert
Assert.Null(validationResult.Error);
Assert.NotNull(validationResult.Properties);
Assert.NotNull(validationResult.Properties.Providers);
//Put deployment
var deploymentResult = client.Deployments.CreateOrUpdateAtScope(scope: resourceGroupScope, deploymentName: deploymentName, parameters: parameters);
var deployment = client.Deployments.GetAtScope(scope: resourceGroupScope, deploymentName: deploymentName);
Assert.Equal("Succeeded", deployment.Properties.ProvisioningState);
Assert.NotNull(deployment.Tags);
Assert.True(deployment.Tags.ContainsKey("tagKey1"));
var deploymentOperations = client.DeploymentOperations.ListAtScope(scope: resourceGroupScope, deploymentName: deploymentName);
Assert.Equal(2, deploymentOperations.Count());
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting;
using System.Management.Automation.Runspaces;
using System.Security.Principal;
using System.Threading;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
/// <summary>
/// This class wraps a PowerShell object. It is used to function
/// as a server side powershell.
/// </summary>
internal class ServerPowerShellDriver
{
#region Private Members
private bool _extraPowerShellAlreadyScheduled;
// extra PowerShell at the server to be run after localPowerShell
private readonly PowerShell _extraPowerShell;
// output buffer for the local PowerShell that is associated with this powershell driver
// associated with this powershell data structure handler object to handle all communications with the client
private readonly PSDataCollection<PSObject> _localPowerShellOutput;
// if the remaining data has been sent to the client before sending state information
private readonly bool[] _datasent = new bool[2];
// sync object for synchronizing sending data to client
private readonly object _syncObject = new object();
// there is no input when this driver was created
private readonly bool _noInput;
private readonly bool _addToHistory;
// the server remote host instance
// associated with this powershell
private readonly ServerRemoteHost _remoteHost;
// apartment state for this powershell
private readonly ApartmentState apartmentState;
// Handles nested invocation of PS drivers.
private readonly IRSPDriverInvoke _psDriverInvoker;
#endregion Private Members
#region Constructors
/// <summary>
/// Default constructor for creating ServerPowerShellDrivers.
/// </summary>
/// <param name="powershell">Decoded powershell object.</param>
/// <param name="extraPowerShell">Extra pipeline to be run after <paramref name="powershell"/> completes.</param>
/// <param name="noInput">Whether there is input for this powershell.</param>
/// <param name="clientPowerShellId">The client powershell id.</param>
/// <param name="clientRunspacePoolId">The client runspacepool id.</param>
/// <param name="runspacePoolDriver">runspace pool driver
/// which is creating this powershell driver</param>
/// <param name="apartmentState">Apartment state for this powershell.</param>
/// <param name="hostInfo">host info using which the host for
/// this powershell will be constructed</param>
/// <param name="streamOptions">Serialization options for the streams in this powershell.</param>
/// <param name="addToHistory">
/// true if the command is to be added to history list of the runspace. false, otherwise.
/// </param>
/// <param name="rsToUse">
/// If not null, this Runspace will be used to invoke Powershell.
/// If null, the RunspacePool pointed by <paramref name="runspacePoolDriver"/> will be used.
/// </param>
internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShell, bool noInput, Guid clientPowerShellId,
Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver,
ApartmentState apartmentState, HostInfo hostInfo, RemoteStreamOptions streamOptions,
bool addToHistory, Runspace rsToUse)
: this(powershell, extraPowerShell, noInput, clientPowerShellId, clientRunspacePoolId, runspacePoolDriver,
apartmentState, hostInfo, streamOptions, addToHistory, rsToUse, null)
{
}
/// <summary>
/// Default constructor for creating ServerPowerShellDrivers.
/// </summary>
/// <param name="powershell">Decoded powershell object.</param>
/// <param name="extraPowerShell">Extra pipeline to be run after <paramref name="powershell"/> completes.</param>
/// <param name="noInput">Whether there is input for this powershell.</param>
/// <param name="clientPowerShellId">The client powershell id.</param>
/// <param name="clientRunspacePoolId">The client runspacepool id.</param>
/// <param name="runspacePoolDriver">runspace pool driver
/// which is creating this powershell driver</param>
/// <param name="apartmentState">Apartment state for this powershell.</param>
/// <param name="hostInfo">host info using which the host for
/// this powershell will be constructed</param>
/// <param name="streamOptions">Serialization options for the streams in this powershell.</param>
/// <param name="addToHistory">
/// true if the command is to be added to history list of the runspace. false, otherwise.
/// </param>
/// <param name="rsToUse">
/// If not null, this Runspace will be used to invoke Powershell.
/// If null, the RunspacePool pointed by <paramref name="runspacePoolDriver"/> will be used.
/// </param>
/// <param name="output">
/// If not null, this is used as another source of output sent to the client.
/// </param>
internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShell, bool noInput, Guid clientPowerShellId,
Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver,
ApartmentState apartmentState, HostInfo hostInfo, RemoteStreamOptions streamOptions,
bool addToHistory, Runspace rsToUse, PSDataCollection<PSObject> output)
{
InstanceId = clientPowerShellId;
RunspacePoolId = clientRunspacePoolId;
RemoteStreamOptions = streamOptions;
this.apartmentState = apartmentState;
LocalPowerShell = powershell;
_extraPowerShell = extraPowerShell;
_localPowerShellOutput = new PSDataCollection<PSObject>();
_noInput = noInput;
_addToHistory = addToHistory;
_psDriverInvoker = runspacePoolDriver;
DataStructureHandler = runspacePoolDriver.DataStructureHandler.CreatePowerShellDataStructureHandler(clientPowerShellId, clientRunspacePoolId, RemoteStreamOptions, LocalPowerShell);
_remoteHost = DataStructureHandler.GetHostAssociatedWithPowerShell(hostInfo, runspacePoolDriver.ServerRemoteHost);
if (!noInput)
{
InputCollection = new PSDataCollection<object>();
InputCollection.ReleaseOnEnumeration = true;
InputCollection.IdleEvent += HandleIdleEvent;
}
RegisterPipelineOutputEventHandlers(_localPowerShellOutput);
if (LocalPowerShell != null)
{
RegisterPowerShellEventHandlers(LocalPowerShell);
_datasent[0] = false;
}
if (extraPowerShell != null)
{
RegisterPowerShellEventHandlers(extraPowerShell);
_datasent[1] = false;
}
RegisterDataStructureHandlerEventHandlers(DataStructureHandler);
// set the runspace pool and invoke this powershell
if (rsToUse != null)
{
LocalPowerShell.Runspace = rsToUse;
if (extraPowerShell != null)
{
extraPowerShell.Runspace = rsToUse;
}
}
else
{
LocalPowerShell.RunspacePool = runspacePoolDriver.RunspacePool;
if (extraPowerShell != null)
{
extraPowerShell.RunspacePool = runspacePoolDriver.RunspacePool;
}
}
if (output != null)
{
output.DataAdded += (sender, args) =>
{
if (_localPowerShellOutput.IsOpen)
{
var items = output.ReadAll();
foreach (var item in items)
{
_localPowerShellOutput.Add(item);
}
}
};
}
}
#endregion Constructors
#region Internal Methods
/// <summary>
/// Input collection sync object.
/// </summary>
internal PSDataCollection<object> InputCollection { get; }
/// <summary>
/// Local PowerShell instance.
/// </summary>
internal PowerShell LocalPowerShell { get; }
/// <summary>
/// Instance id by which this powershell driver is
/// identified. This is the same as the id of the
/// powershell on the client side.
/// </summary>
internal Guid InstanceId { get; }
/// <summary>
/// Serialization options for the streams in this powershell.
/// </summary>
internal RemoteStreamOptions RemoteStreamOptions { get; }
/// <summary>
/// Id of the runspace pool driver which created
/// this object. This is the same as the id of
/// the runspace pool at the client side which
/// is associated with the powershell on the
/// client side.
/// </summary>
internal Guid RunspacePoolId { get; }
/// <summary>
/// ServerPowerShellDataStructureHandler associated with this
/// powershell driver.
/// </summary>
internal ServerPowerShellDataStructureHandler DataStructureHandler { get; }
private PSInvocationSettings PrepInvoke(bool startMainPowerShell)
{
if (startMainPowerShell)
{
// prepare transport manager for sending and receiving data.
DataStructureHandler.Prepare();
}
PSInvocationSettings settings = new PSInvocationSettings();
settings.ApartmentState = apartmentState;
settings.Host = _remoteHost;
// Flow the impersonation policy to pipeline execution thread
// only if the current thread is impersonated (Delegation is
// also a kind of impersonation).
if (Platform.IsWindows)
{
WindowsIdentity currentThreadIdentity = WindowsIdentity.GetCurrent();
switch (currentThreadIdentity.ImpersonationLevel)
{
case TokenImpersonationLevel.Impersonation:
case TokenImpersonationLevel.Delegation:
settings.FlowImpersonationPolicy = true;
break;
default:
settings.FlowImpersonationPolicy = false;
break;
}
}
else
{
settings.FlowImpersonationPolicy = false;
}
settings.AddToHistory = _addToHistory;
return settings;
}
private IAsyncResult Start(bool startMainPowerShell)
{
PSInvocationSettings settings = PrepInvoke(startMainPowerShell);
if (startMainPowerShell)
{
return LocalPowerShell.BeginInvoke<object, PSObject>(InputCollection, _localPowerShellOutput, settings, null, null);
}
else
{
return _extraPowerShell.BeginInvoke<object, PSObject>(InputCollection, _localPowerShellOutput, settings, null, null);
}
}
/// <summary>
/// Invokes the powershell asynchronously.
/// </summary>
internal IAsyncResult Start()
{
return Start(true);
}
/// <summary>
/// Runs no command but allows the PowerShell object on the client
/// to complete. This is used for running "virtual" remote debug
/// commands that sets debugger state but doesn't run any command
/// on the server runspace.
/// </summary>
/// <param name="output">The output from preprocessing that we want to send to the client.</param>
internal void RunNoOpCommand(IReadOnlyCollection<object> output)
{
if (LocalPowerShell != null)
{
System.Threading.ThreadPool.QueueUserWorkItem(
(state) =>
{
LocalPowerShell.SetStateChanged(
new PSInvocationStateInfo(
PSInvocationState.Running, null));
foreach (var item in output)
{
if (item != null)
{
_localPowerShellOutput.Add(PSObject.AsPSObject(item));
}
}
LocalPowerShell.SetStateChanged(
new PSInvocationStateInfo(
PSInvocationState.Completed, null));
});
}
}
/// <summary>
/// Invokes the Main PowerShell object synchronously.
/// </summary>
internal void InvokeMain()
{
PSInvocationSettings settings = PrepInvoke(true);
Exception ex = null;
try
{
LocalPowerShell.InvokeWithDebugger(InputCollection, _localPowerShellOutput, settings, true);
}
catch (Exception e)
{
ex = e;
}
if (ex != null)
{
// Since this is being invoked asynchronously on a single pipeline thread
// any invoke failures (such as possible debugger failures) need to be
// passed back to client or the original client invoke request will not respond.
string failedCommand = LocalPowerShell.Commands.Commands[0].CommandText;
LocalPowerShell.Commands.Clear();
string msg = StringUtil.Format(
RemotingErrorIdStrings.ServerSideNestedCommandInvokeFailed,
failedCommand ?? string.Empty,
ex.Message ?? string.Empty);
LocalPowerShell.AddCommand("Write-Error").AddArgument(msg);
LocalPowerShell.Invoke();
}
}
#endregion Internal Methods
#region Private Methods
private void RegisterPowerShellEventHandlers(PowerShell powerShell)
{
powerShell.InvocationStateChanged += HandlePowerShellInvocationStateChanged;
powerShell.Streams.Error.DataAdded += HandleErrorDataAdded;
powerShell.Streams.Debug.DataAdded += HandleDebugAdded;
powerShell.Streams.Verbose.DataAdded += HandleVerboseAdded;
powerShell.Streams.Warning.DataAdded += HandleWarningAdded;
powerShell.Streams.Progress.DataAdded += HandleProgressAdded;
powerShell.Streams.Information.DataAdded += HandleInformationAdded;
}
private void UnregisterPowerShellEventHandlers(PowerShell powerShell)
{
powerShell.InvocationStateChanged -= HandlePowerShellInvocationStateChanged;
powerShell.Streams.Error.DataAdded -= HandleErrorDataAdded;
powerShell.Streams.Debug.DataAdded -= HandleDebugAdded;
powerShell.Streams.Verbose.DataAdded -= HandleVerboseAdded;
powerShell.Streams.Warning.DataAdded -= HandleWarningAdded;
powerShell.Streams.Progress.DataAdded -= HandleProgressAdded;
powerShell.Streams.Information.DataAdded -= HandleInformationAdded;
}
private void RegisterDataStructureHandlerEventHandlers(ServerPowerShellDataStructureHandler dsHandler)
{
dsHandler.InputEndReceived += HandleInputEndReceived;
dsHandler.InputReceived += HandleInputReceived;
dsHandler.StopPowerShellReceived += HandleStopReceived;
dsHandler.HostResponseReceived += HandleHostResponseReceived;
dsHandler.OnSessionConnected += HandleSessionConnected;
}
private void UnregisterDataStructureHandlerEventHandlers(ServerPowerShellDataStructureHandler dsHandler)
{
dsHandler.InputEndReceived -= HandleInputEndReceived;
dsHandler.InputReceived -= HandleInputReceived;
dsHandler.StopPowerShellReceived -= HandleStopReceived;
dsHandler.HostResponseReceived -= HandleHostResponseReceived;
dsHandler.OnSessionConnected -= HandleSessionConnected;
}
private void RegisterPipelineOutputEventHandlers(PSDataCollection<PSObject> pipelineOutput)
{
pipelineOutput.DataAdded += HandleOutputDataAdded;
}
private void UnregisterPipelineOutputEventHandlers(PSDataCollection<PSObject> pipelineOutput)
{
pipelineOutput.DataAdded -= HandleOutputDataAdded;
}
/// <summary>
/// Handle state changed information from PowerShell
/// and send it to the client.
/// </summary>
/// <param name="sender">Sender of this event.</param>
/// <param name="eventArgs">arguments describing state changed
/// information for this powershell</param>
private void HandlePowerShellInvocationStateChanged(object sender,
PSInvocationStateChangedEventArgs eventArgs)
{
PSInvocationState state = eventArgs.InvocationStateInfo.State;
switch (state)
{
case PSInvocationState.Completed:
case PSInvocationState.Failed:
case PSInvocationState.Stopped:
{
if (LocalPowerShell.RunningExtraCommands)
{
// If completed successfully then allow extra commands to run.
if (state == PSInvocationState.Completed) { return; }
// For failed or stopped state, extra commands cannot run and
// we allow this command invocation to finish.
}
// send the remaining data before sending in
// state information. This is required because
// the client side runspace pool will remove
// the association with the client side powershell
// once the powershell reaches a terminal state.
// If the association is removed, then any data
// sent to the powershell will be discarded by
// the runspace pool data structure handler on the client side
SendRemainingData();
if (state == PSInvocationState.Completed &&
(_extraPowerShell != null) &&
!_extraPowerShellAlreadyScheduled)
{
_extraPowerShellAlreadyScheduled = true;
Start(false);
}
else
{
DataStructureHandler.RaiseRemoveAssociationEvent();
// send the state change notification to the client
DataStructureHandler.SendStateChangedInformationToClient(
eventArgs.InvocationStateInfo);
UnregisterPowerShellEventHandlers(LocalPowerShell);
if (_extraPowerShell != null)
{
UnregisterPowerShellEventHandlers(_extraPowerShell);
}
UnregisterDataStructureHandlerEventHandlers(DataStructureHandler);
UnregisterPipelineOutputEventHandlers(_localPowerShellOutput);
// BUGBUG: currently the local powershell cannot
// be disposed as raising the events is
// not done towards the end. Need to fix
// powershell in order to get this enabled
// localPowerShell.Dispose();
}
}
break;
case PSInvocationState.Stopping:
{
// abort all pending host calls
_remoteHost.ServerMethodExecutor.AbortAllCalls();
}
break;
}
}
/// <summary>
/// Handles DataAdded event from the Output of the powershell.
/// </summary>
/// <param name="sender">Sender of this information.</param>
/// <param name="e">Arguments describing this event.</param>
private void HandleOutputDataAdded(object sender, DataAddedEventArgs e)
{
int index = e.Index;
lock (_syncObject)
{
int indexIntoDataSent = (!_extraPowerShellAlreadyScheduled) ? 0 : 1;
if (!_datasent[indexIntoDataSent])
{
PSObject data = _localPowerShellOutput[index];
// once send the output is removed so that the same
// is not sent again by SendRemainingData() method
_localPowerShellOutput.RemoveAt(index);
// send the output data to the client
DataStructureHandler.SendOutputDataToClient(data);
}
}
}
/// <summary>
/// Handles DataAdded event from Error of the PowerShell.
/// </summary>
/// <param name="sender">Sender of this event.</param>
/// <param name="e">Arguments describing this event.</param>
private void HandleErrorDataAdded(object sender, DataAddedEventArgs e)
{
int index = e.Index;
lock (_syncObject)
{
int indexIntoDataSent = (!_extraPowerShellAlreadyScheduled) ? 0 : 1;
if ((indexIntoDataSent == 0) && (!_datasent[indexIntoDataSent]))
{
ErrorRecord errorRecord = LocalPowerShell.Streams.Error[index];
// once send the error record is removed so that the same
// is not sent again by SendRemainingData() method
LocalPowerShell.Streams.Error.RemoveAt(index);
// send the error record to the client
DataStructureHandler.SendErrorRecordToClient(errorRecord);
}
}
}
/// <summary>
/// Handles DataAdded event from Progress of PowerShell.
/// </summary>
/// <param name="sender">Sender of this information, unused.</param>
/// <param name="eventArgs">Arguments describing this event.</param>
private void HandleProgressAdded(object sender, DataAddedEventArgs eventArgs)
{
int index = eventArgs.Index;
lock (_syncObject)
{
int indexIntoDataSent = (!_extraPowerShellAlreadyScheduled) ? 0 : 1;
if ((indexIntoDataSent == 0) && (!_datasent[indexIntoDataSent]))
{
ProgressRecord data = LocalPowerShell.Streams.Progress[index];
// once the debug message is sent, it is removed so that
// the same is not sent again by SendRemainingData() method
LocalPowerShell.Streams.Progress.RemoveAt(index);
// send the output data to the client
DataStructureHandler.SendProgressRecordToClient(data);
}
}
}
/// <summary>
/// Handles DataAdded event from Warning of PowerShell.
/// </summary>
/// <param name="sender">Sender of this information, unused.</param>
/// <param name="eventArgs">Arguments describing this event.</param>
private void HandleWarningAdded(object sender, DataAddedEventArgs eventArgs)
{
int index = eventArgs.Index;
lock (_syncObject)
{
int indexIntoDataSent = (!_extraPowerShellAlreadyScheduled) ? 0 : 1;
if ((indexIntoDataSent == 0) && (!_datasent[indexIntoDataSent]))
{
WarningRecord data = LocalPowerShell.Streams.Warning[index];
// once the debug message is sent, it is removed so that
// the same is not sent again by SendRemainingData() method
LocalPowerShell.Streams.Warning.RemoveAt(index);
// send the output data to the client
DataStructureHandler.SendWarningRecordToClient(data);
}
}
}
/// <summary>
/// Handles DataAdded from Verbose of PowerShell.
/// </summary>
/// <param name="sender">Sender of this information, unused.</param>
/// <param name="eventArgs">Sender of this information.</param>
private void HandleVerboseAdded(object sender, DataAddedEventArgs eventArgs)
{
int index = eventArgs.Index;
lock (_syncObject)
{
int indexIntoDataSent = (!_extraPowerShellAlreadyScheduled) ? 0 : 1;
if ((indexIntoDataSent == 0) && (!_datasent[indexIntoDataSent]))
{
VerboseRecord data = LocalPowerShell.Streams.Verbose[index];
// once the debug message is sent, it is removed so that
// the same is not sent again by SendRemainingData() method
LocalPowerShell.Streams.Verbose.RemoveAt(index);
// send the output data to the client
DataStructureHandler.SendVerboseRecordToClient(data);
}
}
}
/// <summary>
/// Handles DataAdded from Debug of PowerShell.
/// </summary>
/// <param name="sender">Sender of this information, unused.</param>
/// <param name="eventArgs">Sender of this information.</param>
private void HandleDebugAdded(object sender, DataAddedEventArgs eventArgs)
{
int index = eventArgs.Index;
lock (_syncObject)
{
int indexIntoDataSent = (!_extraPowerShellAlreadyScheduled) ? 0 : 1;
if ((indexIntoDataSent == 0) && (!_datasent[indexIntoDataSent]))
{
DebugRecord data = LocalPowerShell.Streams.Debug[index];
// once the debug message is sent, it is removed so that
// the same is not sent again by SendRemainingData() method
LocalPowerShell.Streams.Debug.RemoveAt(index);
// send the output data to the client
DataStructureHandler.SendDebugRecordToClient(data);
}
}
}
/// <summary>
/// Handles DataAdded from Information of PowerShell.
/// </summary>
/// <param name="sender">Sender of this information, unused.</param>
/// <param name="eventArgs">Sender of this information.</param>
private void HandleInformationAdded(object sender, DataAddedEventArgs eventArgs)
{
int index = eventArgs.Index;
lock (_syncObject)
{
int indexIntoDataSent = (!_extraPowerShellAlreadyScheduled) ? 0 : 1;
if ((indexIntoDataSent == 0) && (!_datasent[indexIntoDataSent]))
{
InformationRecord data = LocalPowerShell.Streams.Information[index];
// once the Information message is sent, it is removed so that
// the same is not sent again by SendRemainingData() method
LocalPowerShell.Streams.Information.RemoveAt(index);
// send the output data to the client
DataStructureHandler.SendInformationRecordToClient(data);
}
}
}
/// <summary>
/// Send the remaining output and error information to
/// client.
/// </summary>
/// <remarks>This method should be called before
/// sending the state information. The client will
/// remove the association between a powershell and
/// runspace pool if it receives any of the terminal
/// states. Hence all the remaining data should be
/// sent before this happens. Else the data will be
/// discarded</remarks>
private void SendRemainingData()
{
int indexIntoDataSent = (!_extraPowerShellAlreadyScheduled) ? 0 : 1;
lock (_syncObject)
{
_datasent[indexIntoDataSent] = true;
}
try
{
// BUGBUG: change this code to use enumerator
// blocked on bug #108824, to be fixed by Kriscv
for (int i = 0; i < _localPowerShellOutput.Count; i++)
{
PSObject data = _localPowerShellOutput[i];
DataStructureHandler.SendOutputDataToClient(data);
}
_localPowerShellOutput.Clear();
// foreach (ErrorRecord errorRecord in localPowerShell.Error)
for (int i = 0; i < LocalPowerShell.Streams.Error.Count; i++)
{
ErrorRecord errorRecord = LocalPowerShell.Streams.Error[i];
DataStructureHandler.SendErrorRecordToClient(errorRecord);
}
LocalPowerShell.Streams.Error.Clear();
}
finally
{
lock (_syncObject)
{
// reset to original state so other pipelines can stream.
_datasent[indexIntoDataSent] = true;
}
}
}
/// <summary>
/// Stop the local powershell.
/// </summary>
/// <param name="sender">Sender of this event, unused.</param>
/// <param name="eventArgs">Unused.</param>
private void HandleStopReceived(object sender, EventArgs eventArgs)
{
do // false loop
{
if (LocalPowerShell.InvocationStateInfo.State == PSInvocationState.Stopped ||
LocalPowerShell.InvocationStateInfo.State == PSInvocationState.Completed ||
LocalPowerShell.InvocationStateInfo.State == PSInvocationState.Failed ||
LocalPowerShell.InvocationStateInfo.State == PSInvocationState.Stopping)
{
break;
}
else
{
// Ensure that the local PowerShell command is not stopped in debug mode.
bool handledByDebugger = false;
if (!LocalPowerShell.IsNested &&
_psDriverInvoker != null)
{
handledByDebugger = _psDriverInvoker.HandleStopSignal();
}
if (!handledByDebugger)
{
LocalPowerShell.Stop();
}
}
} while (false);
if (_extraPowerShell != null)
{
do // false loop
{
if (_extraPowerShell.InvocationStateInfo.State == PSInvocationState.Stopped ||
_extraPowerShell.InvocationStateInfo.State == PSInvocationState.Completed ||
_extraPowerShell.InvocationStateInfo.State == PSInvocationState.Failed ||
_extraPowerShell.InvocationStateInfo.State == PSInvocationState.Stopping)
{
break;
}
else
{
_extraPowerShell.Stop();
}
} while (false);
}
}
/// <summary>
/// Add input to the local powershell's input collection.
/// </summary>
/// <param name="sender">Sender of this event, unused.</param>
/// <param name="eventArgs">Arguments describing this event.</param>
private void HandleInputReceived(object sender, RemoteDataEventArgs<object> eventArgs)
{
// This can be called in pushed runspace scenarios for error reporting (pipeline stopped).
// Ignore for noInput.
if (!_noInput && (InputCollection != null))
{
InputCollection.Add(eventArgs.Data);
}
}
/// <summary>
/// Close the input collection of the local powershell.
/// </summary>
/// <param name="sender">Sender of this event, unused.</param>
/// <param name="eventArgs">Arguments describing this event.</param>
private void HandleInputEndReceived(object sender, EventArgs eventArgs)
{
// This can be called in pushed runspace scenarios for error reporting (pipeline stopped).
// Ignore for noInput.
if (!_noInput && (InputCollection != null))
{
InputCollection.Complete();
}
}
private void HandleSessionConnected(object sender, EventArgs eventArgs)
{
// Close input if its active. no need to synchronize as input stream would have already been processed
// when connect call came into PS plugin
if (InputCollection != null)
{
// TODO: Post an ETW event
InputCollection.Complete();
}
}
/// <summary>
/// Handle a host message response received.
/// </summary>
/// <param name="sender">Sender of this event, unused.</param>
/// <param name="eventArgs">Arguments describing this event.</param>
private void HandleHostResponseReceived(object sender, RemoteDataEventArgs<RemoteHostResponse> eventArgs)
{
_remoteHost.ServerMethodExecutor.HandleRemoteHostResponseFromClient(eventArgs.Data);
}
/// <summary>
/// Handles the PSDataCollection idle event.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void HandleIdleEvent(object sender, EventArgs args)
{
Runspace rs = DataStructureHandler.RunspaceUsedToInvokePowerShell;
if (rs != null)
{
PSLocalEventManager events = (object)rs.Events as PSLocalEventManager;
if (events != null)
{
foreach (PSEventSubscriber subscriber in events.Subscribers)
{
// Use the synchronous version
events.DrainPendingActions(subscriber);
}
}
}
}
#endregion Private Methods
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsModelFlattening
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// Resource Flattening for AutoRest
/// </summary>
public partial class AutoRestResourceFlatteningTestService : ServiceClient<AutoRestResourceFlatteningTestService>, IAutoRestResourceFlatteningTestService
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestService class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AutoRestResourceFlatteningTestService(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestService class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AutoRestResourceFlatteningTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AutoRestResourceFlatteningTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AutoRestResourceFlatteningTestService(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// An optional partial-method to perform custom initialization.
///</summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.BaseUri = new Uri("http://localhost");
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new TransformationJsonConverter());
}
/// <summary>
/// Put External Resource as an Array
/// </summary>
/// <param name='resourceArray'>
/// External Resource as an Array to put
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutArrayWithHttpMessagesAsync(IList<Resource> resourceArray = default(IList<Resource>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceArray", resourceArray);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutArray", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/array").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(resourceArray != null)
{
_requestContent = SafeJsonConvert.SerializeObject(resourceArray, this.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get External Resource as an Array
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<IList<FlattenedProduct>>> GetArrayWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetArray", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/array").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<IList<FlattenedProduct>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<IList<FlattenedProduct>>(_responseContent, this.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put External Resource as a Dictionary
/// </summary>
/// <param name='resourceDictionary'>
/// External Resource as a Dictionary to put
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutDictionaryWithHttpMessagesAsync(IDictionary<string, FlattenedProduct> resourceDictionary = default(IDictionary<string, FlattenedProduct>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceDictionary", resourceDictionary);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutDictionary", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/dictionary").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(resourceDictionary != null)
{
_requestContent = SafeJsonConvert.SerializeObject(resourceDictionary, this.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get External Resource as a Dictionary
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<IDictionary<string, FlattenedProduct>>> GetDictionaryWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetDictionary", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/dictionary").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<IDictionary<string, FlattenedProduct>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<IDictionary<string, FlattenedProduct>>(_responseContent, this.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put External Resource as a ResourceCollection
/// </summary>
/// <param name='resourceComplexObject'>
/// External Resource as a ResourceCollection to put
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutResourceCollectionWithHttpMessagesAsync(ResourceCollection resourceComplexObject = default(ResourceCollection), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceComplexObject", resourceComplexObject);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutResourceCollection", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/resourcecollection").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(resourceComplexObject != null)
{
_requestContent = SafeJsonConvert.SerializeObject(resourceComplexObject, this.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get External Resource as a ResourceCollection
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<ResourceCollection>> GetResourceCollectionWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetResourceCollection", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/resourcecollection").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<ResourceCollection>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ResourceCollection>(_responseContent, this.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put Simple Product with client flattening true on the model
/// </summary>
/// <param name='simpleBodyProduct'>
/// Simple body product to put
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<SimpleProduct>> PutSimpleProductWithHttpMessagesAsync(SimpleProduct simpleBodyProduct = default(SimpleProduct), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (simpleBodyProduct != null)
{
simpleBodyProduct.Validate();
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("simpleBodyProduct", simpleBodyProduct);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutSimpleProduct", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/customFlattening").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(simpleBodyProduct != null)
{
_requestContent = SafeJsonConvert.SerializeObject(simpleBodyProduct, this.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<SimpleProduct>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<SimpleProduct>(_responseContent, this.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put Flattened Simple Product with client flattening true on the parameter
/// </summary>
/// <param name='productId'>
/// Unique identifier representing a specific product for a given latitude
/// & longitude. For example, uberX in San Francisco will have a
/// different product_id than uberX in Los Angeles.
/// </param>
/// <param name='maxProductDisplayName'>
/// Display name of product.
/// </param>
/// <param name='description'>
/// Description of product.
/// </param>
/// <param name='genericValue'>
/// Generic URL value.
/// </param>
/// <param name='odatavalue'>
/// URL value.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<SimpleProduct>> PostFlattenedSimpleProductWithHttpMessagesAsync(string productId, string maxProductDisplayName, string description = default(string), string genericValue = default(string), string odatavalue = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (productId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "productId");
}
if (maxProductDisplayName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "maxProductDisplayName");
}
SimpleProduct simpleBodyProduct = default(SimpleProduct);
if (productId != null || description != null || maxProductDisplayName != null || genericValue != null || odatavalue != null)
{
simpleBodyProduct = new SimpleProduct();
simpleBodyProduct.ProductId = productId;
simpleBodyProduct.Description = description;
simpleBodyProduct.MaxProductDisplayName = maxProductDisplayName;
simpleBodyProduct.GenericValue = genericValue;
simpleBodyProduct.Odatavalue = odatavalue;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("simpleBodyProduct", simpleBodyProduct);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostFlattenedSimpleProduct", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/customFlattening").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(simpleBodyProduct != null)
{
_requestContent = SafeJsonConvert.SerializeObject(simpleBodyProduct, this.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<SimpleProduct>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<SimpleProduct>(_responseContent, this.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put Simple Product with client flattening true on the model
/// </summary>
/// <param name='flattenParameterGroup'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<SimpleProduct>> PutSimpleProductWithGroupingWithHttpMessagesAsync(FlattenParameterGroup flattenParameterGroup, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (flattenParameterGroup == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "flattenParameterGroup");
}
if (flattenParameterGroup != null)
{
flattenParameterGroup.Validate();
}
string name = default(string);
if (flattenParameterGroup != null)
{
name = flattenParameterGroup.Name;
}
string productId = default(string);
if (flattenParameterGroup != null)
{
productId = flattenParameterGroup.ProductId;
}
string description = default(string);
if (flattenParameterGroup != null)
{
description = flattenParameterGroup.Description;
}
string maxProductDisplayName = default(string);
if (flattenParameterGroup != null)
{
maxProductDisplayName = flattenParameterGroup.MaxProductDisplayName;
}
string genericValue = default(string);
if (flattenParameterGroup != null)
{
genericValue = flattenParameterGroup.GenericValue;
}
string odatavalue = default(string);
if (flattenParameterGroup != null)
{
odatavalue = flattenParameterGroup.Odatavalue;
}
SimpleProduct simpleBodyProduct = default(SimpleProduct);
if (productId != null || description != null || maxProductDisplayName != null || genericValue != null || odatavalue != null)
{
simpleBodyProduct = new SimpleProduct();
simpleBodyProduct.ProductId = productId;
simpleBodyProduct.Description = description;
simpleBodyProduct.MaxProductDisplayName = maxProductDisplayName;
simpleBodyProduct.GenericValue = genericValue;
simpleBodyProduct.Odatavalue = odatavalue;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("name", name);
tracingParameters.Add("productId", productId);
tracingParameters.Add("description", description);
tracingParameters.Add("maxProductDisplayName", maxProductDisplayName);
tracingParameters.Add("genericValue", genericValue);
tracingParameters.Add("odatavalue", odatavalue);
tracingParameters.Add("simpleBodyProduct", simpleBodyProduct);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutSimpleProductWithGrouping", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/customFlattening/parametergrouping/{name}/").ToString();
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(simpleBodyProduct != null)
{
_requestContent = SafeJsonConvert.SerializeObject(simpleBodyProduct, this.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<SimpleProduct>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<SimpleProduct>(_responseContent, this.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
#pragma warning disable 162,108,618
using Casanova.Prelude;
using System.Linq;
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Game1 {public class World1 : MonoBehaviour{
public static int frame;
void Update () { Update(Time.deltaTime, this);
frame++; }
public bool JustEntered = true;
public void Start()
{
myA = new A();
UnityCube = UnityCube.Find();
}
public UnityEngine.Color Color{ get { return UnityCube.Color; }
set{UnityCube.Color = value; }
}
public UnityCube UnityCube;
public System.Boolean enabled{ get { return UnityCube.enabled; }
set{UnityCube.enabled = value; }
}
public UnityEngine.GameObject gameObject{ get { return UnityCube.gameObject; }
}
public UnityEngine.HideFlags hideFlags{ get { return UnityCube.hideFlags; }
set{UnityCube.hideFlags = value; }
}
public System.Boolean isActiveAndEnabled{ get { return UnityCube.isActiveAndEnabled; }
}
public System.Collections.Generic.List<System.Int32> lst{ get { return UnityCube.lst; }
set{UnityCube.lst = value; }
}
public A myA;
public System.String name{ get { return UnityCube.name; }
set{UnityCube.name = value; }
}
public System.String tag{ get { return UnityCube.tag; }
set{UnityCube.tag = value; }
}
public UnityEngine.Transform transform{ get { return UnityCube.transform; }
}
public System.Boolean useGUILayout{ get { return UnityCube.useGUILayout; }
set{UnityCube.useGUILayout = value; }
}
public System.Single count_down2;
public System.Single count_down1;
System.DateTime init_time = System.DateTime.Now;
public void Update(float dt, World1 world) {
var t = System.DateTime.Now;
myA.Update(dt, world);
this.Rule0(dt, world);
this.Rule1(dt, world);
}
int s0=-1;
public void Rule0(float dt, World1 world){
switch (s0)
{
case -1:
count_down2 = 0.5f;
goto case 5;
case 5:
if(((count_down2) > (0f)))
{
count_down2 = ((count_down2) - (dt));
s0 = 5;
return; }else
{
goto case 3; }
case 3:
UnityCube.Color = Color.green;
s0 = 1;
return;
case 1:
count_down1 = 0.5f;
goto case 2;
case 2:
if(((count_down1) > (0f)))
{
count_down1 = ((count_down1) - (dt));
s0 = 2;
return; }else
{
goto case 0; }
case 0:
UnityCube.Color = Color.red;
s0 = -1;
return;
default: return;}}
int s1=-1;
public void Rule1(float dt, World1 world){
switch (s1)
{
case -1:
if(((myA.B.C.Elem) > (0)))
{
goto case 6; }else
{
goto case 7; }
case 6:
myA = myA;
s1 = -1;
return;
case 7:
myA = new A();
s1 = -1;
return;
default: return;}}
}
public class A{
public int frame;
public bool JustEntered = true;
public int ID;
public A()
{JustEntered = false;
frame = World1.frame;
B = new B();
}
public B B;
public void Update(float dt, World1 world) {
frame = World1.frame;
B.Update(dt, world);
this.Rule0(dt, world);
}
int s0=-1;
public void Rule0(float dt, World1 world){
switch (s0)
{
case -1:
if(((B.C.Elem) > (0)))
{
goto case 11; }else
{
goto case 12; }
case 11:
B = B;
s0 = -1;
return;
case 12:
B = new B();
s0 = -1;
return;
default: return;}}
}
public class B{
public int frame;
public bool JustEntered = true;
public int ID;
public B()
{JustEntered = false;
frame = World1.frame;
C = new D();
}
public D C;
public void Update(float dt, World1 world) {
frame = World1.frame;
C.Update(dt, world);
}
}
public class D{
public int frame;
public bool JustEntered = true;
public int ID;
public D()
{JustEntered = false;
frame = World1.frame;
Elem = 1;
}
public System.Int32 Elem;
public void Update(float dt, World1 world) {
frame = World1.frame;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace com.yourapp.data.services
{
public class BaseService<TObject> where TObject : class
{
protected DataContext _context;
/// <summary>
/// The contructor requires an open DataContext to work with
/// </summary>
/// <param name="context">An open DataContext</param>
public BaseService(DataContext context)
{
_context = context;
}
/// <summary>
/// Returns a single object with a primary key of the provided id
/// </summary>
/// <remarks>Synchronous</remarks>
/// <param name="id">The primary key of the object to fetch</param>
/// <returns>A single object with the provided primary key or null</returns>
public TObject Get(int id)
{
return _context.Set<TObject>().Find(id);
}
/// <summary>
/// Returns a single object with a primary key of the provided id
/// </summary>
/// <remarks>Asynchronous</remarks>
/// <param name="id">The primary key of the object to fetch</param>
/// <returns>A single object with the provided primary key or null</returns>
public async Task<TObject> GetAsync(int id)
{
return await _context.Set<TObject>().FindAsync(id);
}
/// <summary>
/// Gets a collection of all objects in the database
/// </summary>
/// <remarks>Synchronous</remarks>
/// <returns>An ICollection of every object in the database</returns>
public ICollection<TObject> GetAll()
{
return _context.Set<TObject>().ToList();
}
/// <summary>
/// Gets a collection of all objects in the database
/// </summary>
/// <remarks>Asynchronous</remarks>
/// <returns>An ICollection of every object in the database</returns>
public async Task<ICollection<TObject>> GetAllAsync()
{
return await _context.Set<TObject>().ToListAsync();
}
/// <summary>
/// Returns a single object which matches the provided expression
/// </summary>
/// <remarks>Synchronous</remarks>
/// <param name="match">A Linq expression filter to find a single result</param>
/// <returns>A single object which matches the expression filter.
/// If more than one object is found or if zero are found, null is returned</returns>
public TObject Find(Expression<Func<TObject, bool>> match)
{
return _context.Set<TObject>().SingleOrDefault(match);
}
/// <summary>
/// Returns a single object which matches the provided expression
/// </summary>
/// <remarks>Asynchronous</remarks>
/// <param name="match">A Linq expression filter to find a single result</param>
/// <returns>A single object which matches the expression filter.
/// If more than one object is found or if zero are found, null is returned</returns>
public async Task<TObject> FindAsync(Expression<Func<TObject, bool>> match)
{
return await _context.Set<TObject>().SingleOrDefaultAsync(match);
}
/// <summary>
/// Returns a collection of objects which match the provided expression
/// </summary>
/// <remarks>Synchronous</remarks>
/// <param name="match">A linq expression filter to find one or more results</param>
/// <returns>An ICollection of object which match the expression filter</returns>
public ICollection<TObject> FindAll(Expression<Func<TObject, bool>> match)
{
return _context.Set<TObject>().Where(match).ToList();
}
/// <summary>
/// Returns a collection of objects which match the provided expression
/// </summary>
/// <remarks>Asynchronous</remarks>
/// <param name="match">A linq expression filter to find one or more results</param>
/// <returns>An ICollection of object which match the expression filter</returns>
public async Task<ICollection<TObject>> FindAllAsync(Expression<Func<TObject, bool>> match)
{
return await _context.Set<TObject>().Where(match).ToListAsync();
}
/// <summary>
/// Inserts a single object to the database and commits the change
/// </summary>
/// <remarks>Synchronous</remarks>
/// <param name="t">The object to insert</param>
/// <returns>The resulting object including its primary key after the insert</returns>
public TObject Add(TObject t)
{
_context.Set<TObject>().Add(t);
_context.SaveChanges();
return t;
}
/// <summary>
/// Inserts a single object to the database and commits the change
/// </summary>
/// <remarks>Asynchronous</remarks>
/// <param name="t">The object to insert</param>
/// <returns>The resulting object including its primary key after the insert</returns>
public async Task<TObject> AddAsync(TObject t)
{
_context.Set<TObject>().Add(t);
await _context.SaveChangesAsync();
return t;
}
/// <summary>
/// Inserts a collection of objects into the database and commits the changes
/// </summary>
/// <remarks>Synchronous</remarks>
/// <param name="tList">An IEnumerable list of objects to insert</param>
/// <returns>The IEnumerable resulting list of inserted objects including the primary keys</returns>
public IEnumerable<TObject> AddAll(IEnumerable<TObject> tList)
{
_context.Set<TObject>().AddRange(tList);
_context.SaveChanges();
return tList;
}
/// <summary>
/// Inserts a collection of objects into the database and commits the changes
/// </summary>
/// <remarks>Asynchronous</remarks>
/// <param name="tList">An IEnumerable list of objects to insert</param>
/// <returns>The IEnumerable resulting list of inserted objects including the primary keys</returns>
public async Task<IEnumerable<TObject>> AddAllAsync(IEnumerable<TObject> tList)
{
_context.Set<TObject>().AddRange(tList);
await _context.SaveChangesAsync();
return tList;
}
/// <summary>
/// Updates a single object based on the provided primary key and commits the change
/// </summary>
/// <remarks>Synchronous</remarks>
/// <param name="updated">The updated object to apply to the database</param>
/// <param name="key">The primary key of the object to update</param>
/// <returns>The resulting updated object</returns>
public TObject Update(TObject updated, int key)
{
if (updated == null)
return null;
TObject existing = _context.Set<TObject>().Find(key);
if (existing != null)
{
_context.Entry(existing).CurrentValues.SetValues(updated);
_context.SaveChanges();
}
return existing;
}
/// <summary>
/// Updates a single object based on the provided primary key and commits the change
/// </summary>
/// <remarks>Asynchronous</remarks>
/// <param name="updated">The updated object to apply to the database</param>
/// <param name="key">The primary key of the object to update</param>
/// <returns>The resulting updated object</returns>
public async Task<TObject> UpdateAsync(TObject updated, int key)
{
if (updated == null)
return null;
TObject existing = await _context.Set<TObject>().FindAsync(key);
if (existing != null)
{
_context.Entry(existing).CurrentValues.SetValues(updated);
await _context.SaveChangesAsync();
}
return existing;
}
/// <summary>
/// Deletes a single object from the database and commits the change
/// </summary>
/// <remarks>Synchronous</remarks>
/// <param name="t">The object to delete</param>
public void Delete(TObject t)
{
_context.Set<TObject>().Remove(t);
_context.SaveChanges();
}
/// <summary>
/// Deletes a single object from the database and commits the change
/// </summary>
/// <remarks>Asynchronous</remarks>
/// <param name="t">The object to delete</param>
public async Task<int> DeleteAsync(TObject t)
{
_context.Set<TObject>().Remove(t);
return await _context.SaveChangesAsync();
}
/// <summary>
/// Gets the count of the number of objects in the databse
/// </summary>
/// <remarks>Synchronous</remarks>
/// <returns>The count of the number of objects</returns>
public int Count()
{
return _context.Set<TObject>().Count();
}
/// <summary>
/// Gets the count of the number of objects in the databse
/// </summary>
/// <remarks>Asynchronous</remarks>
/// <returns>The count of the number of objects</returns>
public async Task<int> CountAsync()
{
return await _context.Set<TObject>().CountAsync();
}
}
}
| |
using nanoFramework.Tools.Debugger;
using System;
using System.Runtime.InteropServices;
namespace CorDebugInterop
{
#pragma warning disable 0108
[Guid("3D6F5F61-7538-11D3-8D5B-00104B35E7EF")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebug
{
[PreserveSig]int Initialize();
[PreserveSig]int Terminate();
[PreserveSig]int SetManagedHandler([In, MarshalAs(UnmanagedType.Interface)]ICorDebugManagedCallback pCallback);
[PreserveSig]int SetUnmanagedHandler([In, MarshalAs(UnmanagedType.Interface)]ICorDebugUnmanagedCallback pCallback);
[PreserveSig]int CreateProcess([In, MarshalAs(UnmanagedType.LPWStr)]string lpApplicationName, [In, MarshalAs(UnmanagedType.LPWStr)]string lpCommandLine, [In]_SECURITY_ATTRIBUTES lpProcessAttributes, [In]_SECURITY_ATTRIBUTES lpThreadAttributes, [In]int bInheritHandles, [In]uint dwCreationFlags, [In]IntPtr lpEnvironment, [In, MarshalAs(UnmanagedType.LPWStr)]string lpCurrentDirectory, [In]_STARTUPINFO lpStartupInfo, [In]_PROCESS_INFORMATION lpProcessInformation, [In]CorDebugCreateProcessFlags debuggingFlags, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugProcess ppProcess);
[PreserveSig]int DebugActiveProcess([In]uint id, [In]int win32Attach, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugProcess ppProcess);
[PreserveSig]int EnumerateProcesses([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugProcessEnum ppProcess);
[PreserveSig]int GetProcess([In]uint dwProcessId, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugProcess ppProcess);
[PreserveSig]int CanLaunchOrAttach([In]uint dwProcessId, [In]int win32DebuggingEnabled);
}
public enum CorDebugInterfaceVersion : int
{
CorDebugInvalidVersion = 0,
CorDebugVersion_1_0 = CorDebugInvalidVersion + 1,
ver_ICorDebugManagedCallback = CorDebugVersion_1_0,
ver_ICorDebugUnmanagedCallback = CorDebugVersion_1_0,
ver_ICorDebug = CorDebugVersion_1_0,
ver_ICorDebugController = CorDebugVersion_1_0,
ver_ICorDebugAppDomain = CorDebugVersion_1_0,
ver_ICorDebugAssembly = CorDebugVersion_1_0,
ver_ICorDebugProcess = CorDebugVersion_1_0,
ver_ICorDebugBreakpoint = CorDebugVersion_1_0,
ver_ICorDebugFunctionBreakpoint = CorDebugVersion_1_0,
ver_ICorDebugModuleBreakpoint = CorDebugVersion_1_0,
ver_ICorDebugValueBreakpoint = CorDebugVersion_1_0,
ver_ICorDebugStepper = CorDebugVersion_1_0,
ver_ICorDebugRegisterSet = CorDebugVersion_1_0,
ver_ICorDebugThread = CorDebugVersion_1_0,
ver_ICorDebugChain = CorDebugVersion_1_0,
ver_ICorDebugFrame = CorDebugVersion_1_0,
ver_ICorDebugILFrame = CorDebugVersion_1_0,
ver_ICorDebugNativeFrame = CorDebugVersion_1_0,
ver_ICorDebugModule = CorDebugVersion_1_0,
ver_ICorDebugFunction = CorDebugVersion_1_0,
ver_ICorDebugCode = CorDebugVersion_1_0,
ver_ICorDebugClass = CorDebugVersion_1_0,
ver_ICorDebugEval = CorDebugVersion_1_0,
ver_ICorDebugValue = CorDebugVersion_1_0,
ver_ICorDebugGenericValue = CorDebugVersion_1_0,
ver_ICorDebugReferenceValue = CorDebugVersion_1_0,
ver_ICorDebugHeapValue = CorDebugVersion_1_0,
ver_ICorDebugObjectValue = CorDebugVersion_1_0,
ver_ICorDebugBoxValue = CorDebugVersion_1_0,
ver_ICorDebugStringValue = CorDebugVersion_1_0,
ver_ICorDebugArrayValue = CorDebugVersion_1_0,
ver_ICorDebugContext = CorDebugVersion_1_0,
ver_ICorDebugEnum = CorDebugVersion_1_0,
ver_ICorDebugObjectEnum = CorDebugVersion_1_0,
ver_ICorDebugBreakpointEnum = CorDebugVersion_1_0,
ver_ICorDebugStepperEnum = CorDebugVersion_1_0,
ver_ICorDebugProcessEnum = CorDebugVersion_1_0,
ver_ICorDebugThreadEnum = CorDebugVersion_1_0,
ver_ICorDebugFrameEnum = CorDebugVersion_1_0,
ver_ICorDebugChainEnum = CorDebugVersion_1_0,
ver_ICorDebugModuleEnum = CorDebugVersion_1_0,
ver_ICorDebugValueEnum = CorDebugVersion_1_0,
ver_ICorDebugCodeEnum = CorDebugVersion_1_0,
ver_ICorDebugTypeEnum = CorDebugVersion_1_0,
ver_ICorDebugErrorInfoEnum = CorDebugVersion_1_0,
ver_ICorDebugAppDomainEnum = CorDebugVersion_1_0,
ver_ICorDebugAssemblyEnum = CorDebugVersion_1_0,
ver_ICorDebugEditAndContinueErrorInfo
= CorDebugVersion_1_0,
ver_ICorDebugEditAndContinueSnapshot
= CorDebugVersion_1_0,
CorDebugVersion_1_1 = CorDebugVersion_1_0 + 1,
// No interface definitions in version 1.1.
CorDebugVersion_2_0 = CorDebugVersion_1_1 + 1,
ver_ICorDebugManagedCallback2 = CorDebugVersion_2_0,
ver_ICorDebugAppDomain2 = CorDebugVersion_2_0,
ver_ICorDebugProcess2 = CorDebugVersion_2_0,
ver_ICorDebugStepper2 = CorDebugVersion_2_0,
ver_ICorDebugRegisterSet2 = CorDebugVersion_2_0,
ver_ICorDebugThread2 = CorDebugVersion_2_0,
ver_ICorDebugILFrame2 = CorDebugVersion_2_0,
ver_ICorDebugModule2 = CorDebugVersion_2_0,
ver_ICorDebugFunction2 = CorDebugVersion_2_0,
ver_ICorDebugCode2 = CorDebugVersion_2_0,
ver_ICorDebugClass2 = CorDebugVersion_2_0,
ver_ICorDebugValue2 = CorDebugVersion_2_0,
ver_ICorDebugEval2 = CorDebugVersion_2_0,
ver_ICorDebugObjectValue2 = CorDebugVersion_2_0,
CorDebugVersion_3_0 = CorDebugVersion_2_0 + 1,
ver_ICorDebugThread3 = CorDebugVersion_3_0,
ver_ICorDebugThread4 = CorDebugVersion_3_0,
ver_ICorDebugStackWalk = CorDebugVersion_3_0,
ver_ICorDebugNativeFrame2 = CorDebugVersion_3_0,
ver_ICorDebugInternalFrame2 = CorDebugVersion_3_0,
ver_ICorDebugRuntimeUnwindableFrame = CorDebugVersion_3_0,
ver_ICorDebugHeapValue3 = CorDebugVersion_3_0,
ver_ICorDebugBlockingObjectEnum = CorDebugVersion_3_0,
CorDebugLatestVersion = CorDebugVersion_3_0
}
[Guid("ECCCCF2E-B286-4b3e-A983-860A8793D105")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebug2
{
[PreserveSig]int SetDebuggerVersion( CorDebugInterfaceVersion maxDebuggerVersion );
}
[Guid("3D6F5F60-7538-11D3-8D5B-00104B35E7EF")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugManagedCallback
{
[PreserveSig]int Breakpoint([In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugThread pThread, [In]IntPtr pBreakpoint);
[PreserveSig]int StepComplete([In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugThread pThread, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugStepper pStepper, [In]CorDebugStepReason reason);
[PreserveSig]int Break([In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugThread thread);
[PreserveSig]int Exception([In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugThread pThread, [In]int unhandled);
[PreserveSig]int EvalComplete([In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugThread pThread, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugEval pEval);
[PreserveSig]int EvalException([In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugThread pThread, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugEval pEval);
[PreserveSig]int CreateProcess([In, MarshalAs(UnmanagedType.Interface)]ICorDebugProcess pProcess);
[PreserveSig]int ExitProcess([In, MarshalAs(UnmanagedType.Interface)]ICorDebugProcess pProcess);
[PreserveSig]int CreateThread([In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugThread thread);
[PreserveSig]int ExitThread([In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugThread thread);
[PreserveSig]int LoadModule([In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugModule pModule);
[PreserveSig]int UnloadModule([In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugModule pModule);
[PreserveSig]int LoadClass([In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugClass c);
[PreserveSig]int UnloadClass([In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugClass c);
[PreserveSig]int DebuggerError([In, MarshalAs(UnmanagedType.Interface)]ICorDebugProcess pProcess, [In, MarshalAs(UnmanagedType.Error)]int errorHR, [In]uint errorCode);
[PreserveSig]int LogMessage([In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugThread pThread, [In]int lLevel, [In]string pLogSwitchName, [In]string pMessage);
[PreserveSig]int LogSwitch([In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugThread pThread, [In]int lLevel, [In]uint ulReason, [In]ref ushort pLogSwitchName, [In]ref ushort pParentName);
[PreserveSig]int CreateAppDomain([In, MarshalAs(UnmanagedType.Interface)]ICorDebugProcess pProcess, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain);
[PreserveSig]int ExitAppDomain([In, MarshalAs(UnmanagedType.Interface)]ICorDebugProcess pProcess, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain);
[PreserveSig]int LoadAssembly([In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugAssembly pAssembly);
[PreserveSig]int UnloadAssembly([In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugAssembly pAssembly);
[PreserveSig]int ControlCTrap([In, MarshalAs(UnmanagedType.Interface)]ICorDebugProcess pProcess);
[PreserveSig]int NameChange([In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugThread pThread);
[PreserveSig]int UpdateModuleSymbols([In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugModule pModule, [In, MarshalAs(UnmanagedType.Interface)]Microsoft.VisualStudio.OLE.Interop.IStream pSymbolStream);
[PreserveSig]int EditAndContinueRemap([In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugThread pThread, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugFunction pFunction, [In]int fAccurate);
[PreserveSig]int BreakpointSetError([In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugThread pThread, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugBreakpoint pBreakpoint, [In]uint dwError);
}
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("5263E909-8CB5-11D3-BD2F-0000F80849BD")]
[ComImport]
public interface ICorDebugUnmanagedCallback
{
[PreserveSig]int DebugEvent([ComAliasName("CorDebugInterop.ULONG_PTR"), In]uint pDebugEvent, [In]int fOutOfBand);
}
[ComConversionLoss]
public struct _STARTUPINFO
{
public int cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public int dwX;
public int dwY;
public int dwXSize;
public int dwYSize;
public int dwXCountChars;
public int dwYCountChars;
public int dwFillAttribute;
public int dwFlags;
public short wShowWindow;
public short cbReserved2;
public int lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[ComConversionLoss]
public struct _PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
[Serializable]
public enum CorDebugCreateProcessFlags
{
DEBUG_NO_SPECIAL_OPTIONS = 0,
}
[Guid("3D6F5F64-7538-11D3-8D5B-00104B35E7EF")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugProcess : ICorDebugController
{
//ICorDebugController
[PreserveSig]int Stop([In]uint dwTimeout);
[PreserveSig]int Continue([In]int fIsOutOfBand);
[PreserveSig]int IsRunning([Out]out int pbRunning);
[PreserveSig]int HasQueuedCallbacks([In, MarshalAs(UnmanagedType.Interface)]ICorDebugThread pThread, [Out]out int pbQueued);
[PreserveSig]int EnumerateThreads([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugThreadEnum ppThreads);
[PreserveSig]int SetAllThreadsDebugState([In]CorDebugThreadState state, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugThread pExceptThisThread);
[PreserveSig]int Detach();
[PreserveSig]int Terminate([In]uint exitCode);
[PreserveSig]int CanCommitChanges([In]uint cSnapshots, [In, MarshalAs(UnmanagedType.Interface)]ref ICorDebugEditAndContinueSnapshot pSnapshots, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugErrorInfoEnum pError);
[PreserveSig]int CommitChanges([In]uint cSnapshots, [In, MarshalAs(UnmanagedType.Interface)]ref ICorDebugEditAndContinueSnapshot pSnapshots, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugErrorInfoEnum pError);
//ICorDebugProcess
[PreserveSig]int GetID([Out]out uint pdwProcessId);
[PreserveSig]int GetHandle([ComAliasName("CorDebugInterop.long"), Out]out uint phProcessHandle);
[PreserveSig]int GetThread([In]uint dwThreadId, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugThread ppThread);
[PreserveSig]int EnumerateObjects([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugObjectEnum ppObjects);
[PreserveSig]int IsTransitionStub([In]ulong address, [Out]out int pbTransitionStub);
[PreserveSig]int IsOSSuspended([In]uint threadID, [Out]out int pbSuspended);
[PreserveSig]int GetThreadContext([In]uint threadID, [In]uint contextSize, [Out]IntPtr context);
[PreserveSig]int SetThreadContext([In]uint threadID, [In]uint contextSize, [In]IntPtr context);
[PreserveSig]int ReadMemory([In]ulong address, [In]uint size, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]byte[] buffer, [Out]out uint read);
[PreserveSig]int WriteMemory([In]ulong address, [In]uint size, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]byte[] buffer, [Out]out uint written);
[PreserveSig]int ClearCurrentException([In]uint threadID);
[PreserveSig]int EnableLogMessages([In]int fOnOff);
[PreserveSig]int ModifyLogSwitch([In, MarshalAs(UnmanagedType.LPWStr)] string pLogSwitchName, [In]int lLevel);
[PreserveSig]int EnumerateAppDomains([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugAppDomainEnum ppAppDomains);
[PreserveSig]int GetObject([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValue ppObject);
[PreserveSig]int ThreadForFiberCookie([In]uint fiberCookie, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugThread ppThread);
[PreserveSig]int GetHelperThreadID([Out]out uint pThreadID);
}
[ComConversionLoss]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("CC7BCB05-8A68-11D2-983C-0000F808342D")]
[ComImport]
public interface ICorDebugProcessEnum : ICorDebugEnum
{
//ICorDebugEnum
[PreserveSig]int Skip([In]uint celt);
[PreserveSig]int Reset();
[PreserveSig]int Clone([Out]out IntPtr ppEnum);
[PreserveSig]int GetCount([Out]out uint pcelt);
//ICorDebugProcessEnum
[PreserveSig]int Next([In]uint celt, [Out]IntPtr processes, [Out]out uint pceltFetched);
}
[ComConversionLoss]
[Guid("3D6F5F63-7538-11D3-8D5B-00104B35E7EF")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugAppDomain : ICorDebugController
{
//ICorDebugController
[PreserveSig]int Stop([In]uint dwTimeout);
[PreserveSig]int Continue([In]int fIsOutOfBand);
[PreserveSig]int IsRunning([Out]out int pbRunning);
[PreserveSig]int HasQueuedCallbacks([In, MarshalAs(UnmanagedType.Interface)]ICorDebugThread pThread, [Out]out int pbQueued);
[PreserveSig]int EnumerateThreads([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugThreadEnum ppThreads);
[PreserveSig]int SetAllThreadsDebugState([In]CorDebugThreadState state, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugThread pExceptThisThread);
[PreserveSig]int Detach();
[PreserveSig]int Terminate([In]uint exitCode);
[PreserveSig]int CanCommitChanges([In]uint cSnapshots, [In, MarshalAs(UnmanagedType.Interface)]ref ICorDebugEditAndContinueSnapshot pSnapshots, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugErrorInfoEnum pError);
[PreserveSig]int CommitChanges([In]uint cSnapshots, [In, MarshalAs(UnmanagedType.Interface)]ref ICorDebugEditAndContinueSnapshot pSnapshots, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugErrorInfoEnum pError);
//ICorDebugAppDomain
[PreserveSig]int GetProcess([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugProcess ppProcess);
[PreserveSig]int EnumerateAssemblies([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugAssemblyEnum ppAssemblies);
[PreserveSig]int GetModuleFromMetaDataInterface([In, MarshalAs(UnmanagedType.IUnknown)]object pIMetaData, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugModule ppModule);
[PreserveSig]int EnumerateBreakpoints([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugBreakpointEnum ppBreakpoints);
[PreserveSig]int EnumerateSteppers([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugStepperEnum ppSteppers);
[PreserveSig]int IsAttached([Out]out int pbAttached);
[PreserveSig]int GetName([In]uint cchName, [Out]IntPtr pcchName, [Out]IntPtr szName);
[PreserveSig]int GetObject([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValue ppObject);
[PreserveSig]int Attach();
[PreserveSig]int GetID([Out]out uint pId);
}
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("938C6D66-7FB6-4F69-B389-425B8987329B")]
[ComImport]
public interface ICorDebugThread
{
[PreserveSig]int GetProcess( [Out, MarshalAs( UnmanagedType.Interface )]out ICorDebugProcess ppProcess );
[PreserveSig]int GetID([Out]out uint pdwThreadId);
[PreserveSig]int GetHandle([ComAliasName("CorDebugInterop.long"), Out]out uint phThreadHandle);
[PreserveSig]int GetAppDomain([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugAppDomain ppAppDomain);
[PreserveSig]int SetDebugState([In]CorDebugThreadState state);
[PreserveSig]int GetDebugState([Out]out CorDebugThreadState pState);
[PreserveSig]int GetUserState([Out]out CorDebugUserState pState);
[PreserveSig]int GetCurrentException([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValue ppExceptionObject);
[PreserveSig]int ClearCurrentException();
[PreserveSig]int CreateStepper([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugStepper ppStepper);
[PreserveSig]int EnumerateChains([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugChainEnum ppChains);
[PreserveSig]int GetActiveChain([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugChain ppChain);
[PreserveSig]int GetActiveFrame([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugFrame ppFrame);
[PreserveSig]int GetRegisterSet([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugRegisterSet ppRegisters);
[PreserveSig]int CreateEval([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugEval ppEval);
[PreserveSig]int GetObject([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValue ppObject);
}
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("CC7BCAEC-8A68-11D2-983C-0000F808342D")]
[ComImport]
public interface ICorDebugStepper
{
[PreserveSig]int IsActive([Out]out int pbActive);
[PreserveSig]int Deactivate();
[PreserveSig]int SetInterceptMask([In]CorDebugIntercept mask);
[PreserveSig]int SetUnmappedStopMask([In]CorDebugUnmappedStop mask);
[PreserveSig]int Step([In]int bStepIn);
[PreserveSig]int StepRange([In]int bStepIn, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)]COR_DEBUG_STEP_RANGE[] ranges, [In]uint cRangeCount);
[PreserveSig]int StepOut();
[PreserveSig]int SetRangeIL([In]int bIL);
}
[Serializable]
public enum CorDebugStepReason
{
STEP_NORMAL = 0,
STEP_RETURN = 1,
STEP_CALL = 2,
STEP_EXCEPTION_FILTER = 3,
STEP_EXCEPTION_HANDLER = 4,
STEP_INTERCEPT = 5,
STEP_EXIT = 6,
}
[Guid("CC7BCAF6-8A68-11D2-983C-0000F808342D")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugEval
{
[PreserveSig]int CallFunction([In, MarshalAs( UnmanagedType.Interface )]ICorDebugFunction pFunction, [In]uint nArgs, [In, MarshalAs( UnmanagedType.LPArray, SizeParamIndex = 1 )]ICorDebugValue[] ppArgs);
[PreserveSig]int NewObject([In, MarshalAs( UnmanagedType.Interface )]ICorDebugFunction pConstructor, [In]uint nArgs, [In, MarshalAs( UnmanagedType.LPArray, SizeParamIndex = 1 )]ICorDebugValue[] ppArgs);
[PreserveSig]int NewObjectNoConstructor([In, MarshalAs(UnmanagedType.Interface)]ICorDebugClass pClass);
[PreserveSig]int NewString([In, MarshalAs(UnmanagedType.LPWStr)]string @string);
[PreserveSig]int NewArray([In]CorElementType elementType, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugClass pElementClass, [In]uint rank, [In] ref uint dims, [In] ref uint lowBounds);
[PreserveSig]int IsActive([Out]out int pbActive);
[PreserveSig]int Abort();
[PreserveSig]int GetResult([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValue ppResult);
[PreserveSig]int GetThread([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugThread ppThread);
[PreserveSig]int CreateValue([In]CorElementType elementType, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugClass pElementClass, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValue ppValue);
}
[Guid("DBA2D8C1-E5C5-4069-8C13-10A7C6ABF43D")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComConversionLoss]
[ComImport]
public interface ICorDebugModule
{
[PreserveSig]int GetProcess([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugProcess ppProcess);
[PreserveSig]int GetBaseAddress([Out]out ulong pAddress);
[PreserveSig]int GetAssembly([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugAssembly ppAssembly);
[PreserveSig]int GetName([In]uint cchName, [Out]IntPtr pcchName, [Out]IntPtr szName);
[PreserveSig]int EnableJITDebugging([In]int bTrackJITInfo, [In]int bAllowJitOpts);
[PreserveSig]int EnableClassLoadCallbacks([In]int bClassLoadCallbacks);
[PreserveSig]int GetFunctionFromToken([In]uint methodDef, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugFunction ppFunction);
[PreserveSig]int GetFunctionFromRVA([In]ulong rva, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugFunction ppFunction);
[PreserveSig]int GetClassFromToken([In]uint typeDef, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugClass ppClass);
[PreserveSig]int CreateBreakpoint([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugModuleBreakpoint ppBreakpoint);
[PreserveSig]int GetEditAndContinueSnapshot([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugEditAndContinueSnapshot ppEditAndContinueSnapshot);
[PreserveSig]int GetMetaDataInterface([In]ref Guid riid, [Out]out IntPtr ppObj);
[PreserveSig]int GetToken([Out]out uint pToken);
[PreserveSig]int IsDynamic([Out]out int pDynamic);
[PreserveSig]int GetGlobalVariableValue([In]uint fieldDef, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValue ppValue);
[PreserveSig]int GetSize([Out]out uint pcBytes);
[PreserveSig]int IsInMemory([Out]out int pInMemory);
}
[Guid("CC7BCAF5-8A68-11D2-983C-0000F808342D")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugClass
{
[PreserveSig]int GetModule([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugModule pModule);
[PreserveSig]int GetToken([Out]out uint pTypeDef);
[PreserveSig]int GetStaticFieldValue([In]uint fieldDef, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugFrame pFrame, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValue ppValue);
}
[ComConversionLoss]
[Guid("DF59507C-D47A-459E-BCE2-6427EAC8FD06")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugAssembly
{
[PreserveSig]int GetProcess([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugProcess ppProcess);
[PreserveSig]int GetAppDomain([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugAppDomain ppAppDomain);
[PreserveSig]int EnumerateModules([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugModuleEnum ppModules);
[PreserveSig]int GetCodeBase([In]uint cchName, [Out]IntPtr pcchName, [Out]IntPtr szName);
[PreserveSig]int GetName([In]uint cchName, [Out]IntPtr pcchName, [Out]IntPtr szName);
}
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("CC7BCAF3-8A68-11D2-983C-0000F808342D")]
[ComImport]
public interface ICorDebugFunction
{
[PreserveSig]int GetModule([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugModule ppModule);
[PreserveSig]int GetClass([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugClass ppClass);
[PreserveSig]int GetToken([Out]out uint pMethodDef);
[PreserveSig]int GetILCode([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugCode ppCode);
[PreserveSig]int GetNativeCode([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugCode ppCode);
[PreserveSig]int CreateBreakpoint([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugFunctionBreakpoint ppBreakpoint);
[PreserveSig]int GetLocalVarSigToken([Out]out uint pmdSig);
[PreserveSig]int GetCurrentVersionNumber([Out]out uint pnCurrentVersion);
}
[Guid("CC7BCAE8-8A68-11D2-983C-0000F808342D")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugBreakpoint
{
[PreserveSig]int Activate([In]int bActive);
[PreserveSig]int IsActive([Out]out int pbActive);
}
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("3D6F5F62-7538-11D3-8D5B-00104B35E7EF")]
[ComImport]
public interface ICorDebugController
{
[PreserveSig]int Stop([In]uint dwTimeout);
[PreserveSig]int Continue([In]int fIsOutOfBand);
[PreserveSig]int IsRunning([Out]out int pbRunning);
[PreserveSig]int HasQueuedCallbacks([In, MarshalAs(UnmanagedType.Interface)]ICorDebugThread pThread, [Out]out int pbQueued);
[PreserveSig]int EnumerateThreads([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugThreadEnum ppThreads);
[PreserveSig]int SetAllThreadsDebugState([In]CorDebugThreadState state, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugThread pExceptThisThread);
[PreserveSig]int Detach();
[PreserveSig]int Terminate([In]uint exitCode);
[PreserveSig]int CanCommitChanges([In]uint cSnapshots, [In, MarshalAs(UnmanagedType.Interface)]ref ICorDebugEditAndContinueSnapshot pSnapshots, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugErrorInfoEnum pError);
[PreserveSig]int CommitChanges([In]uint cSnapshots, [In, MarshalAs(UnmanagedType.Interface)]ref ICorDebugEditAndContinueSnapshot pSnapshots, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugErrorInfoEnum pError);
}
[ComConversionLoss]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("CC7BCB06-8A68-11D2-983C-0000F808342D")]
[ComImport]
public interface ICorDebugThreadEnum : ICorDebugEnum
{
//ICorDebugEnum
[PreserveSig]int Skip([In]uint celt);
[PreserveSig]int Reset();
[PreserveSig]int Clone([Out]out IntPtr ppEnum);
[PreserveSig]int GetCount([Out]out uint pcelt);
//ICorDebugThreadEnum
[PreserveSig]int Next([In]uint celt, [Out]IntPtr threads, [Out]out uint pceltFetched);
}
[Serializable]
public enum CorDebugThreadState
{
THREAD_RUN = 0,
THREAD_SUSPEND = 1,
}
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("6DC3FA01-D7CB-11D2-8A95-0080C792E5D8")]
[ComImport]
public interface ICorDebugEditAndContinueSnapshot
{
[PreserveSig]int CopyMetaData([In, MarshalAs(UnmanagedType.Interface)]Microsoft.VisualStudio.OLE.Interop.IStream pIStream, [Out]out Guid pMvid);
[PreserveSig]int GetMvid([Out]out Guid pMvid);
[PreserveSig]int GetRoDataRVA([Out]out uint pRoDataRVA);
[PreserveSig]int GetRwDataRVA([Out]out uint pRwDataRVA);
[PreserveSig]int SetPEBytes([In, MarshalAs(UnmanagedType.Interface)]Microsoft.VisualStudio.OLE.Interop.IStream pIStream);
[PreserveSig]int SetILMap([In]uint mdFunction, [In]uint cMapSize, [In]ref _COR_IL_MAP map);
[PreserveSig]int SetPESymbolBytes([In, MarshalAs(UnmanagedType.Interface)]Microsoft.VisualStudio.OLE.Interop.IStream pIStream);
}
[ComConversionLoss]
[Guid("F0E18809-72B5-11D2-976F-00A0C9B4D50C")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugErrorInfoEnum : ICorDebugEnum
{
//ICorDebugEnum
[PreserveSig]int Skip([In]uint celt);
[PreserveSig]int Reset();
[PreserveSig]int Clone([Out]out IntPtr ppEnum);
[PreserveSig]int GetCount([Out]out uint pcelt);
//ICorDebugErrorInfoEnum
[PreserveSig]int Next([In]uint celt, [Out]IntPtr errors, [Out]out uint pceltFetched);
}
[ComConversionLoss]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("4A2A1EC9-85EC-4BFB-9F15-A89FDFE0FE83")]
[ComImport]
public interface ICorDebugAssemblyEnum : ICorDebugEnum
{
//ICorDebugEnum
[PreserveSig]int Skip([In]uint celt);
[PreserveSig]int Reset();
[PreserveSig]int Clone([Out]out IntPtr ppEnum);
[PreserveSig]int GetCount([Out]out uint pcelt);
//ICorDebugAssemblyEnum
[PreserveSig]int Next([In]uint celt, [Out]IntPtr values, [Out]out uint pceltFetched);
}
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComConversionLoss]
[Guid("CC7BCB03-8A68-11D2-983C-0000F808342D")]
[ComImport]
public interface ICorDebugBreakpointEnum : ICorDebugEnum
{
//ICorDebugEnum
[PreserveSig]int Skip([In]uint celt);
[PreserveSig]int Reset();
[PreserveSig]int Clone([Out]out IntPtr ppEnum);
[PreserveSig]int GetCount([Out]out uint pcelt);
//ICorDebugBreakpointEnum
[PreserveSig]int Next([In]uint celt, [Out]IntPtr breakpoints, [Out]out uint pceltFetched);
}
[ComConversionLoss]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("CC7BCB04-8A68-11D2-983C-0000F808342D")]
[ComImport]
public interface ICorDebugStepperEnum : ICorDebugEnum
{
//ICorDebugEnum
[PreserveSig]int Skip([In]uint celt);
[PreserveSig]int Reset();
[PreserveSig]int Clone([Out]out IntPtr ppEnum);
[PreserveSig]int GetCount([Out]out uint pcelt);
//ICorDebugStepperEnum
[PreserveSig]int Next([In]uint celt, [Out]IntPtr steppers, [Out]out uint pceltFetched);
}
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("CC7BCAF7-8A68-11D2-983C-0000F808342D")]
[ComImport]
public interface ICorDebugValue
{
[PreserveSig]int GetType([Out]out CorElementType pType);
[PreserveSig]int GetSize([Out]out uint pSize);
[PreserveSig]int GetAddress([Out]out ulong pAddress);
[PreserveSig]int CreateBreakpoint([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValueBreakpoint ppBreakpoint);
}
[Serializable]
public enum CorDebugUserState
{
USER_STOP_REQUESTED = 0x1,
USER_SUSPEND_REQUESTED = 0x2,
USER_BACKGROUND = 0x4,
USER_UNSTARTED = 0x8,
USER_STOPPED = 0x10,
USER_WAIT_SLEEP_JOIN = 0x20,
USER_SUSPENDED = 0x40,
USER_UNSAFE_POINT = 0x80,
}
[Guid("CC7BCB08-8A68-11D2-983C-0000F808342D")]
[ComConversionLoss]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugChainEnum : ICorDebugEnum
{
//ICorDebugEnum
[PreserveSig]int Skip([In]uint celt);
[PreserveSig]int Reset();
[PreserveSig]int Clone([Out]out IntPtr ppEnum);
[PreserveSig]int GetCount([Out]out uint pcelt);
//ICorDebugChainEnum
[PreserveSig]int Next([In]uint celt, [Out]IntPtr chains, [Out]out uint pceltFetched);
}
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("CC7BCAEE-8A68-11D2-983C-0000F808342D")]
[ComImport]
public interface ICorDebugChain
{
[PreserveSig]int GetThread([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugThread ppThread);
[PreserveSig]int GetStackRange([Out]out ulong pStart, [Out]out ulong pEnd);
[PreserveSig]int GetContext([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugContext ppContext);
[PreserveSig]int GetCaller([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugChain ppChain);
[PreserveSig]int GetCallee([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugChain ppChain);
[PreserveSig]int GetPrevious([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugChain ppChain);
[PreserveSig]int GetNext([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugChain ppChain);
[PreserveSig]int IsManaged([Out]out int pManaged);
[PreserveSig]int EnumerateFrames([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugFrameEnum ppFrames);
[PreserveSig]int GetActiveFrame([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugFrame ppFrame);
[PreserveSig]int GetRegisterSet([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugRegisterSet ppRegisters);
[PreserveSig]int GetReason([Out]out CorDebugChainReason pReason);
}
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("CC7BCAEF-8A68-11D2-983C-0000F808342D")]
[ComImport]
public interface ICorDebugFrame
{
[PreserveSig]int GetChain([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugChain ppChain);
[PreserveSig]int GetCode([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugCode ppCode);
[PreserveSig]int GetFunction([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugFunction ppFunction);
[PreserveSig]int GetFunctionToken([Out]out uint pToken);
[PreserveSig]int GetStackRange([Out]out ulong pStart, [Out]out ulong pEnd);
[PreserveSig]int GetCaller([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugFrame ppFrame);
[PreserveSig]int GetCallee([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugFrame ppFrame);
[PreserveSig]int CreateStepper([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugStepper ppStepper);
}
public enum CorDebugRegister
{
REGISTER_INSTRUCTION_POINTER = 0,
REGISTER_STACK_POINTER,
REGISTER_FRAME_POINTER,
REGISTER_X86_EIP = 0,
REGISTER_X86_ESP,
REGISTER_X86_EBP,
REGISTER_X86_EAX,
REGISTER_X86_ECX,
REGISTER_X86_EDX,
REGISTER_X86_EBX,
REGISTER_X86_ESI,
REGISTER_X86_EDI,
REGISTER_X86_FPSTACK_0,
REGISTER_X86_FPSTACK_1,
REGISTER_X86_FPSTACK_2,
REGISTER_X86_FPSTACK_3,
REGISTER_X86_FPSTACK_4,
REGISTER_X86_FPSTACK_5,
REGISTER_X86_FPSTACK_6,
REGISTER_X86_FPSTACK_7,
REGISTER_AMD64_RIP = 0,
REGISTER_AMD64_RSP,
REGISTER_AMD64_RBP,
REGISTER_AMD64_RAX,
REGISTER_AMD64_RCX,
REGISTER_AMD64_RDX,
REGISTER_AMD64_RBX,
REGISTER_AMD64_RSI,
REGISTER_AMD64_RDI,
REGISTER_AMD64_R8,
REGISTER_AMD64_R9,
REGISTER_AMD64_R10,
REGISTER_AMD64_R11,
REGISTER_AMD64_R12,
REGISTER_AMD64_R13,
REGISTER_AMD64_R14,
REGISTER_AMD64_R15,
REGISTER_AMD64_XMM0,
REGISTER_AMD64_XMM1,
REGISTER_AMD64_XMM2,
REGISTER_AMD64_XMM3,
REGISTER_AMD64_XMM4,
REGISTER_AMD64_XMM5,
REGISTER_AMD64_XMM6,
REGISTER_AMD64_XMM7,
REGISTER_AMD64_XMM8,
REGISTER_AMD64_XMM9,
REGISTER_AMD64_XMM10,
REGISTER_AMD64_XMM11,
REGISTER_AMD64_XMM12,
REGISTER_AMD64_XMM13,
REGISTER_AMD64_XMM14,
REGISTER_AMD64_XMM15,
REGISTER_IA64_BSP = REGISTER_FRAME_POINTER,
REGISTER_IA64_R0 = REGISTER_IA64_BSP + 1,
REGISTER_IA64_F0 = REGISTER_IA64_R0 + 128,
}
[Guid("CC7BCB0B-8A68-11D2-983C-0000F808342D")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComConversionLoss]
[ComImport]
public interface ICorDebugRegisterSet
{
[PreserveSig]int GetRegistersAvailable([Out]out ulong pAvailable);
[PreserveSig]int GetRegisters([In]ulong mask, [In]uint regCount, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)]ulong[] regBuffer);
[PreserveSig]int SetRegisters([In]ulong mask, [In]uint regCount, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)]ulong[] regBuffer);
[PreserveSig]int GetThreadContext([In]uint contextSize, [Out]IntPtr context);
[PreserveSig]int SetThreadContext([In]uint contextSize, [In]IntPtr context);
}
[Guid("6DC7BA3F-89BA-4459-9EC1-9D60937B468D")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComConversionLoss]
[ComImport]
public interface ICorDebugRegisterSet2
{
[PreserveSig]int GetRegistersAvailable([In] uint numChunks, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)]byte[] availableRegChunks);
[PreserveSig]int GetRegisters([In] uint maskCount, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] byte[] mask, [In] uint regCount, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] ulong[] regBuffer);
[PreserveSig]int SetRegisters([In] uint maskCount, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] byte[] mask, [In] uint regCount, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] ulong[] regBuffer);
}
[Guid("CC7BCB02-8A68-11D2-983C-0000F808342D")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComConversionLoss]
[ComImport]
public interface ICorDebugObjectEnum : ICorDebugEnum
{
//ICorDebugEnum
[PreserveSig]int Skip([In]uint celt);
[PreserveSig]int Reset();
[PreserveSig]int Clone([Out]out IntPtr ppEnum);
[PreserveSig]int GetCount([Out]out uint pcelt);
//ICorDebugObjectEnum
[PreserveSig]int Next([In]uint celt, [Out]IntPtr objects, [Out]out uint pceltFetched);
}
[Guid("63CA1B24-4359-4883-BD57-13F815F58744")]
[ComConversionLoss]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugAppDomainEnum : ICorDebugEnum
{
//ICorDebugEnum
[PreserveSig]int Skip([In]uint celt);
[PreserveSig]int Reset();
[PreserveSig]int Clone([Out]out IntPtr ppEnum);
[PreserveSig]int GetCount([Out]out uint pcelt);
//ICorDebugAppDomainEnum
[PreserveSig]int Next([In]uint celt, [Out]IntPtr values, [Out]out uint pceltFetched);
}
[Guid("CC7BCB01-8A68-11D2-983C-0000F808342D")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugEnum
{
[PreserveSig]int Skip([In]uint celt);
[PreserveSig]int Reset();
[PreserveSig]int Clone([Out]out IntPtr ppEnum);
[PreserveSig]int GetCount([Out]out uint pcelt);
}
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("CC7BCAEB-8A68-11D2-983C-0000F808342D")]
[ComImport]
public interface ICorDebugValueBreakpoint : ICorDebugBreakpoint
{
//ICorDebugBreakpoint
[PreserveSig]int Activate([In]int bActive);
[PreserveSig]int IsActive([Out]out int pbActive);
//ICorDebugValueBreakpoint
[PreserveSig]int GetValue([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValue ppValue);
}
[Serializable]
public enum CorDebugIntercept
{
INTERCEPT_NONE = 0x0,
INTERCEPT_CLASS_INIT = 0x1,
INTERCEPT_EXCEPTION_FILTER = 0x2,
INTERCEPT_SECURITY = 0x4,
INTERCEPT_CONTEXT_POLICY = 0x8,
INTERCEPT_INTERCEPTION = 0x10,
INTERCEPT_ALL = 0xffff,
}
[Serializable]
public enum CorDebugUnmappedStop
{
STOP_NONE = 0x0,
STOP_PROLOG = 0x1,
STOP_EPILOG = 0x2,
STOP_NO_MAPPING_INFO = 0x4,
STOP_OTHER_UNMAPPED = 0x8,
STOP_UNMANAGED = 0x10,
STOP_ALL = 0xffff,
STOP_ONLYJUSTMYCODE = 0x10000,
}
public struct COR_DEBUG_STEP_RANGE
{
public uint startOffset;
public uint endOffset;
}
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("CC7BCB00-8A68-11D2-983C-0000F808342D")]
[ComImport]
public interface ICorDebugContext : ICorDebugObjectValue
{
//ICorDebugObjectValue
[PreserveSig]int GetType([Out]out CorElementType pType);
[PreserveSig]int GetSize([Out]out uint pSize);
[PreserveSig]int GetAddress([Out]out ulong pAddress);
[PreserveSig]int CreateBreakpoint([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValueBreakpoint ppBreakpoint);
[PreserveSig]int GetClass([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugClass ppClass);
[PreserveSig]int GetFieldValue([In, MarshalAs(UnmanagedType.Interface)]ICorDebugClass pClass, [In]uint fieldDef, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValue ppValue);
[PreserveSig]int GetVirtualMethod([In]uint memberRef, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugFunction ppFunction);
[PreserveSig]int GetContext([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugContext ppContext);
[PreserveSig]int IsValueClass([Out]out int pbIsValueClass);
[PreserveSig]int GetManagedCopy([Out, MarshalAs(UnmanagedType.IUnknown)]out object ppObject);
[PreserveSig]int SetFromManagedCopy([In, MarshalAs(UnmanagedType.IUnknown)]object pObject);
//ICorDebugContext
}
[Guid("CC7BCB07-8A68-11D2-983C-0000F808342D")]
[ComConversionLoss]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugFrameEnum : ICorDebugEnum
{
//ICorDebugEnum
[PreserveSig]int Skip([In]uint celt);
[PreserveSig]int Reset();
[PreserveSig]int Clone([Out]out IntPtr ppEnum);
[PreserveSig]int GetCount([Out]out uint pcelt);
//ICorDebugFrameEnum
[PreserveSig]int Next([In]uint celt, [Out]IntPtr frames, [Out]out uint pceltFetched);
}
[Serializable]
public enum CorDebugChainReason
{
CHAIN_NONE = 0x0,
CHAIN_CLASS_INIT = 0x1,
CHAIN_EXCEPTION_FILTER = 0x2,
CHAIN_SECURITY = 0x4,
CHAIN_CONTEXT_POLICY = 0x8,
CHAIN_INTERCEPTION = 0x10,
CHAIN_PROCESS_START = 0x20,
CHAIN_THREAD_START = 0x40,
CHAIN_ENTER_MANAGED = 0x80,
CHAIN_ENTER_UNMANAGED = 0x100,
CHAIN_DEBUGGER_EVAL = 0x200,
CHAIN_CONTEXT_SWITCH = 0x400,
CHAIN_FUNC_EVAL = 0x800,
}
[Guid("18AD3D6E-B7D2-11D2-BD04-0000F80849BD")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugObjectValue : ICorDebugValue
{
//ICorDebugValue
[PreserveSig]int GetType([Out]out CorElementType pType);
[PreserveSig]int GetSize([Out]out uint pSize);
[PreserveSig]int GetAddress([Out]out ulong pAddress);
[PreserveSig]int CreateBreakpoint([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValueBreakpoint ppBreakpoint);
//ICorDebugObjectValue
[PreserveSig]int GetClass([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugClass ppClass);
[PreserveSig]int GetFieldValue([In, MarshalAs(UnmanagedType.Interface)]ICorDebugClass pClass, [In]uint fieldDef, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValue ppValue);
[PreserveSig]int GetVirtualMethod([In]uint memberRef, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugFunction ppFunction);
[PreserveSig]int GetContext([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugContext ppContext);
[PreserveSig]int IsValueClass([Out]out int pbIsValueClass);
[PreserveSig]int GetManagedCopy([Out, MarshalAs(UnmanagedType.IUnknown)]out object ppObject);
[PreserveSig]int SetFromManagedCopy([In, MarshalAs(UnmanagedType.IUnknown)]object pObject);
}
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("CC7BCAEA-8A68-11D2-983C-0000F808342D")]
[ComImport]
public interface ICorDebugModuleBreakpoint : ICorDebugBreakpoint
{
//ICorDebugBreakpoint
[PreserveSig]int Activate([In]int bActive);
[PreserveSig]int IsActive([Out]out int pbActive);
//ICorDebugModuleBreakpoint
[PreserveSig]int GetModule([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugModule ppModule);
}
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("CC7BCB09-8A68-11D2-983C-0000F808342D")]
[ComConversionLoss]
[ComImport]
public interface ICorDebugModuleEnum : ICorDebugEnum
{
//ICorDebugEnum
[PreserveSig]int Skip([In]uint celt);
[PreserveSig]int Reset();
[PreserveSig]int Clone([Out]out IntPtr ppEnum);
[PreserveSig]int GetCount([Out]out uint pcelt);
//ICorDebugModuleEnum
[PreserveSig]int Next([In]uint celt, [Out]IntPtr modules, [Out]out uint pceltFetched);
}
[Guid("CC7BCAF4-8A68-11D2-983C-0000F808342D")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComConversionLoss]
[ComImport]
public interface ICorDebugCode
{
[PreserveSig]int IsIL([Out]out int pbIL);
[PreserveSig]int GetFunction([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugFunction ppFunction);
[PreserveSig]int GetAddress([Out]out ulong pStart);
[PreserveSig]int GetSize([Out]out uint pcBytes);
[PreserveSig]int CreateBreakpoint([In]uint offset, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugFunctionBreakpoint ppBreakpoint);
[PreserveSig]int GetCode([In]uint startOffset, [In]uint endOffset, [In]uint cBufferAlloc, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=2)]byte[] buffer, [Out]out uint pcBufferSize);
[PreserveSig]int GetVersionNumber([Out]out uint nVersion);
[PreserveSig]int GetILToNativeMapping([In]uint cMap, [Out]out uint pcMap, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] COR_DEBUG_IL_TO_NATIVE_MAP[] map);
[PreserveSig]int GetEnCRemapSequencePoints([In]uint cMap, [Out]out uint pcMap, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)]uint[] offsets);
}
public struct CodeChunkInfo
{
public ulong startAddr;
public uint length;
}
public struct COR_DEBUG_IL_TO_NATIVE_MAP
{
public uint ilOffset;
public uint nativeStartOffset;
public uint nativeEndOffset;
}
enum CorDebugIlToNativeMappingTypes : uint
{
NO_MAPPING = unchecked((uint)-1),
PROLOG = unchecked((uint)-2),
EPILOG = unchecked((uint)-3 )
}
[Guid("5F696509-452F-4436-A3FE-4D11FE7E2347")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugCode2
{
[PreserveSig]int GetCodeChunks([In] uint cbufSize, [Out]out uint pcnumChunks, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)]CodeChunkInfo[] chunks);
[PreserveSig]int GetCompilerFlags( [Out] out int pdwFlags );
}
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("CC7BCAE9-8A68-11D2-983C-0000F808342D")]
[ComImport]
public interface ICorDebugFunctionBreakpoint : ICorDebugBreakpoint
{
//ICorDebugBreakpoint
[PreserveSig]int Activate([In]int bActive);
[PreserveSig]int IsActive([Out]out int pbActive);
//ICorDebugFunctionBreakpoint
[PreserveSig]int GetFunction([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugFunction ppFunction);
[PreserveSig]int GetOffset([Out]out uint pnOffset);
}
public struct _COR_IL_MAP
{
public uint oldOffset;
public uint newOffset;
public int fAccurate;
}
public struct _SECURITY_ATTRIBUTES
{
public uint nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}
[Guid("CC7BCAF9-8A68-11D2-983C-0000F808342D")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugReferenceValue : ICorDebugValue
{
//ICorDebugValue
[PreserveSig]int GetType([Out]out CorElementType pType);
[PreserveSig]int GetSize([Out]out uint pSize);
[PreserveSig]int GetAddress([Out]out ulong pAddress);
[PreserveSig]int CreateBreakpoint([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValueBreakpoint ppBreakpoint);
//ICorDebugReferenceValue
[PreserveSig]int IsNull([Out]out int pbNull);
[PreserveSig]int GetValue([Out]out ulong pValue);
[PreserveSig]int SetValue([In]ulong value);
[PreserveSig]int Dereference([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValue ppValue);
[PreserveSig]int DereferenceStrong([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValue ppValue);
}
[Guid("CC7BCAFA-8A68-11D2-983C-0000F808342D")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugHeapValue : ICorDebugValue
{
//ICorDebugValue
[PreserveSig]int GetType([Out]out CorElementType pType);
[PreserveSig]int GetSize([Out]out uint pSize);
[PreserveSig]int GetAddress([Out]out ulong pAddress);
[PreserveSig]int CreateBreakpoint([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValueBreakpoint ppBreakpoint);
//ICorDebugHeapValue
[PreserveSig]int IsValid([Out]out int pbValid);
[PreserveSig]int CreateRelocBreakpoint([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValueBreakpoint ppBreakpoint);
}
[Guid("CC7BCAFD-8A68-11D2-983C-0000F808342D")]
[ComConversionLoss]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugStringValue : ICorDebugHeapValue
{
//ICorDebugHeapValue
[PreserveSig]int GetType([Out]out CorElementType pType);
[PreserveSig]int GetSize([Out]out uint pSize);
[PreserveSig]int GetAddress([Out]out ulong pAddress);
[PreserveSig]int CreateBreakpoint([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValueBreakpoint ppBreakpoint);
[PreserveSig]int IsValid([Out]out int pbValid);
[PreserveSig]int CreateRelocBreakpoint([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValueBreakpoint ppBreakpoint);
//ICorDebugStringValue
[PreserveSig]int GetLength([Out]out uint pcchString);
[PreserveSig]int GetString([In]uint cchString, [Out]IntPtr pcchString, [Out] IntPtr szString);
}
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("CC7BCAF8-8A68-11D2-983C-0000F808342D")]
[ComImport]
public interface ICorDebugGenericValue : ICorDebugValue
{
//ICorDebugValue
[PreserveSig]int GetType([Out]out CorElementType pType);
[PreserveSig]int GetSize([Out]out uint pSize);
[PreserveSig]int GetAddress([Out]out ulong pAddress);
[PreserveSig]int CreateBreakpoint([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValueBreakpoint ppBreakpoint);
//ICorDebugGenericValue
[PreserveSig]int GetValue([Out]IntPtr pTo);
[PreserveSig]int SetValue([In]IntPtr pFrom);
}
[Guid("CC7BCAFC-8A68-11D2-983C-0000F808342D")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugBoxValue : ICorDebugHeapValue
{
//ICorDebugHeapValue
[PreserveSig]int GetType([Out]out CorElementType pType);
[PreserveSig]int GetSize([Out]out uint pSize);
[PreserveSig]int GetAddress([Out]out ulong pAddress);
[PreserveSig]int CreateBreakpoint([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValueBreakpoint ppBreakpoint);
[PreserveSig]int IsValid([Out]out int pbValid);
[PreserveSig]int CreateRelocBreakpoint([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValueBreakpoint ppBreakpoint);
//ICorDebugBoxValue
[PreserveSig]int GetObject([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugObjectValue ppObject);
}
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("0405B0DF-A660-11D2-BD02-0000F80849BD")]
[ComConversionLoss]
[ComImport]
public interface ICorDebugArrayValue : ICorDebugHeapValue
{
//ICorDebugHeapValue
[PreserveSig]int GetType([Out]out CorElementType pType);
[PreserveSig]int GetSize([Out]out uint pSize);
[PreserveSig]int GetAddress([Out]out ulong pAddress);
[PreserveSig]int CreateBreakpoint([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValueBreakpoint ppBreakpoint);
[PreserveSig]int IsValid([Out]out int pbValid);
[PreserveSig]int CreateRelocBreakpoint([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValueBreakpoint ppBreakpoint);
//ICorDebugArrayValue
[PreserveSig]int GetElementType([Out]out CorElementType pType);
[PreserveSig]int GetRank([Out]out uint pnRank);
[PreserveSig]int GetCount([Out]out uint pnCount);
[PreserveSig]int GetDimensions([In]uint cdim, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)]uint[] dims);
[PreserveSig]int HasBaseIndicies([Out]out int pbHasBaseIndicies);
[PreserveSig]int GetBaseIndicies([In]uint cdim, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)]uint[] indicies);
[PreserveSig]int GetElement([In]uint cdim, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)]uint[] indices, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValue ppValue);
[PreserveSig]int GetElementAtPosition([In]uint nPosition, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValue ppValue);
}
[Guid("03E26311-4F76-11D3-88C6-006097945418")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugILFrame : ICorDebugFrame
{
//ICorDebugFrame
[PreserveSig]int GetChain([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugChain ppChain);
[PreserveSig]int GetCode([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugCode ppCode);
[PreserveSig]int GetFunction([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugFunction ppFunction);
[PreserveSig]int GetFunctionToken([Out]out uint pToken);
[PreserveSig]int GetStackRange([Out]out ulong pStart, [Out]out ulong pEnd);
[PreserveSig]int GetCaller([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugFrame ppFrame);
[PreserveSig]int GetCallee([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugFrame ppFrame);
[PreserveSig]int CreateStepper([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugStepper ppStepper);
//ICorDebugILFrame
[PreserveSig]int GetIP([Out]out uint pnOffset, [Out]out CorDebugMappingResult pMappingResult);
[PreserveSig]int SetIP([In]uint nOffset);
[PreserveSig]int EnumerateLocalVariables([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValueEnum ppValueEnum);
[PreserveSig]int GetLocalVariable([In]uint dwIndex, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValue ppValue);
[PreserveSig]int EnumerateArguments([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValueEnum ppValueEnum);
[PreserveSig]int GetArgument([In]uint dwIndex, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValue ppValue);
[PreserveSig]int GetStackDepth([Out]out uint pDepth);
[PreserveSig]int GetStackValue([In]uint dwIndex, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValue ppValue);
[PreserveSig]int CanSetIP([In]uint nOffset);
}
[Serializable]
public enum CorDebugInternalFrameType
{
STUBFRAME_NONE = 0x00000000,
STUBFRAME_M2U = 0x0000001,
STUBFRAME_U2M = 0x0000002,
STUBFRAME_APPDOMAIN_TRANSITION = 0x00000003,
STUBFRAME_LIGHTWEIGHT_FUNCTION = 0x00000004,
STUBFRAME_FUNC_EVAL = 0x00000005,
}
[Guid("B92CC7F7-9D2D-45c4-BC2B-621FCC9DFBF4")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugInternalFrame : ICorDebugFrame
{
//ICorDebugFrame
[PreserveSig]int GetChain([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugChain ppChain);
[PreserveSig]int GetCode([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugCode ppCode);
[PreserveSig]int GetFunction([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugFunction ppFunction);
[PreserveSig]int GetFunctionToken([Out]out uint pToken);
[PreserveSig]int GetStackRange([Out]out ulong pStart, [Out]out ulong pEnd);
[PreserveSig]int GetCaller([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugFrame ppFrame);
[PreserveSig]int GetCallee([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugFrame ppFrame);
[PreserveSig]int CreateStepper([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugStepper ppStepper);
//ICorDebugInternalFrame
[PreserveSig]int GetFrameType([Out]out CorDebugInternalFrameType pType);
}
[Guid("03E26314-4F76-11d3-88C6-006097945418")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugNativeFrame : ICorDebugFrame
{
//Not yet verified to be correct interop definition
//ICorDebugFrame
[PreserveSig]int GetChain([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugChain ppChain);
[PreserveSig]int GetCode([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugCode ppCode);
[PreserveSig]int GetFunction([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugFunction ppFunction);
[PreserveSig]int GetFunctionToken([Out]out uint pToken);
[PreserveSig]int GetStackRange([Out]out ulong pStart, [Out]out ulong pEnd);
[PreserveSig]int GetCaller([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugFrame ppFrame);
[PreserveSig]int GetCallee([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugFrame ppFrame);
[PreserveSig]int CreateStepper([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugStepper ppStepper);
//ICorDebugNativeFrame
[PreserveSig]int GetIP([Out]out uint pnOffset);
[PreserveSig]int SetIP([In] uint nOffset);
[PreserveSig]int GetRegisterSet([Out] out ICorDebugRegisterSet ppRegisters);
[PreserveSig]int GetLocalRegisterValue([In] CorDebugRegister reg, [In] uint cbSigBlob, [In] IntPtr pvSigBlob, [Out, MarshalAs(UnmanagedType.Interface)] out ICorDebugValue ppValue);
[PreserveSig]int GetLocalDoubleRegisterValue([In] CorDebugRegister highWordReg, [In] CorDebugRegister lowWordReg, [In] uint cbSigBlob, [In] IntPtr pvSigBlob, [Out, MarshalAs(UnmanagedType.Interface)] out ICorDebugValue ppValue);
[PreserveSig]int GetLocalMemoryValue([In] ulong address, [In] uint cbSigBlob, [In] IntPtr pvSigBlob, [Out, MarshalAs(UnmanagedType.Interface)] out ICorDebugValue ppValue);
[PreserveSig]int GetLocalRegisterMemoryValue([In] CorDebugRegister highWordReg, [In] ulong lowWordAddress, [In] uint cbSigBlob, [In] IntPtr pvSigBlob, [Out, MarshalAs(UnmanagedType.Interface)] out ICorDebugValue ppValue);
[PreserveSig]int GetLocalMemoryRegisterValue([In] ulong highWordAddress, [In] CorDebugRegister lowWordRegister, [In] uint cbSigBlob, [In] IntPtr pvSigBlob, [Out, MarshalAs(UnmanagedType.Interface)] out ICorDebugValue ppValue);
[PreserveSig]int CanSetIP([In] uint nOffset);
}
[Serializable]
public enum CorDebugMappingResult
{
MAPPING_PROLOG = 0x1,
MAPPING_EPILOG = 0x2,
MAPPING_NO_INFO = 0x4,
MAPPING_UNMAPPED_ADDRESS = 0x8,
MAPPING_EXACT = 0x10,
MAPPING_APPROXIMATE = 0x20,
}
[Guid("CC7BCB0A-8A68-11D2-983C-0000F808342D")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComConversionLoss]
[ComImport]
public interface ICorDebugValueEnum : ICorDebugEnum
{
//ICorDebugEnum
[PreserveSig]int Skip([In]uint celt);
[PreserveSig]int Reset();
[PreserveSig]int Clone([Out]out IntPtr ppEnum);
[PreserveSig]int GetCount([Out]out uint pcelt);
//ICorDebugValueEnum
[PreserveSig]int Next([In]uint celt, [Out]IntPtr values, [Out]out uint pceltFetched);
}
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("250E5EEA-DB5C-4C76-B6F3-8C46F12E3203")]
[ComImport]
public interface ICorDebugManagedCallback2
{
[PreserveSig]int FunctionRemapOpportunity([In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugThread pThread, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugFunction pOldFunction, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugFunction pNewFunction, [In]uint oldILOffset);
[PreserveSig]int CreateConnection([In, MarshalAs(UnmanagedType.Interface)]ICorDebugProcess pProcess, [In]uint dwConnectionId, [In]ref ushort pConnName);
[PreserveSig]int ChangeConnection([In, MarshalAs(UnmanagedType.Interface)]ICorDebugProcess pProcess, [In]uint dwConnectionId);
[PreserveSig]int DestroyConnection([In, MarshalAs(UnmanagedType.Interface)]ICorDebugProcess pProcess, [In]uint dwConnectionId);
[PreserveSig]int Exception([In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugThread pThread, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugFrame pFrame, [In]uint nOffset, [In]CorDebugExceptionCallbackType dwEventType, [In]uint dwFlags);
[PreserveSig]int ExceptionUnwind([In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugThread pThread, [In]CorDebugExceptionUnwindCallbackType dwEventType, [In]uint dwFlags);
[PreserveSig]int FunctionRemapComplete([In, MarshalAs(UnmanagedType.Interface)]ICorDebugAppDomain pAppDomain, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugThread pThread, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugFunction pFunction);
[PreserveSig]int MDANotification([In, MarshalAs(UnmanagedType.Interface)]ICorDebugController pController, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugThread pThread, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugMDA pMDA);
}
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("CC726F2F-1DB7-459b-B0EC-05F01D841B42")]
[ComImport]
public interface ICorDebugMDA
{
[PreserveSig]int GetName([In]uint cchName, [Out]IntPtr pcchName, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] char[] szName);
[PreserveSig]int GetDescription([In]uint cchName, [Out]IntPtr pcchName, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] char[] szName);
[PreserveSig]int GetXML([In]uint cchName, [Out]IntPtr pcchName, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] char[] szName);
[PreserveSig]int GetFlags([In]CorDebugMDAFlags pFlags);
[PreserveSig]int GetOSThreadId([Out]out uint pOsTid);
}
[Serializable]
public enum CorDebugMDAFlags
{
MDA_FLAG_SEVERE = 0x1,
MDA_FLAG_SLIP = 0x2
}
[Serializable]
public enum CorDebugExceptionCallbackType
{
DEBUG_EXCEPTION_FIRST_CHANCE = 1,
DEBUG_EXCEPTION_USER_FIRST_CHANCE = 2,
DEBUG_EXCEPTION_CATCH_HANDLER_FOUND = 3,
DEBUG_EXCEPTION_UNHANDLED = 4,
}
[Serializable]
public enum CorDebugExceptionUnwindCallbackType
{
DEBUG_EXCEPTION_UNWIND_BEGIN = 1,
DEBUG_EXCEPTION_INTERCEPTED = 2,
}
[Guid("096E81D5-ECDA-4202-83F5-C65980A9EF75")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugAppDomain2
{
[PreserveSig]int GetArrayOrPointerType([In]CorElementType elementType, [In]uint nRank, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugType pTypeArg, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugType ppType);
[PreserveSig]int GetFunctionPointerType([In]uint nTypeArgs, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] ICorDebugType[] ppTypeArgs, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugType ppType);
}
[Guid("D613F0BB-ACE1-4C19-BD72-E4C08D5DA7F5")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugType
{
[PreserveSig]int GetType([Out]out CorElementType ty);
[PreserveSig]int GetClass([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugClass ppClass);
[PreserveSig]int EnumerateTypeParameters([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugTypeEnum ppTyParEnum);
[PreserveSig]int GetFirstTypeParameter([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugType value);
[PreserveSig]int GetBase([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugType pBase);
[PreserveSig]int GetStaticFieldValue([In]uint fieldDef, [In, MarshalAs(UnmanagedType.Interface)]ICorDebugFrame pFrame, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValue ppValue);
[PreserveSig]int GetRank([Out]out uint pnRank);
}
[Guid("10F27499-9DF2-43CE-8333-A321D7C99CB4")]
[ComConversionLoss]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugTypeEnum : ICorDebugEnum
{
//ICorDebugEnum
[PreserveSig]int Skip([In]uint celt);
[PreserveSig]int Reset();
[PreserveSig]int Clone([Out]out IntPtr ppEnum);
[PreserveSig]int GetCount([Out]out uint pcelt);
//ICorDebugTypeEnum
[PreserveSig]int Next([In]uint celt, [Out]IntPtr values, [Out]out uint pceltFetched);
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public struct COR_ACTIVE_FUNCTION
{
public ICorDebugAppDomain pAppDomain;
public ICorDebugModule pModule;
public ICorDebugFunction2 pFunction;
public uint ilOffset;
public uint Flags;
}
[ComConversionLoss]
[Guid("AD1B3588-0EF0-4744-A496-AA09A9F80371")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugProcess2
{
[PreserveSig]int GetThreadForTaskID([In]ulong taskid, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugThread2 ppThread);
[PreserveSig]int GetVersion([Out]out _COR_VERSION version);
[PreserveSig]int SetUnmanagedBreakpoint([In]ulong address, [In]uint bufsize, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] buffer, [Out]out uint bufLen);
[PreserveSig]int ClearUnmanagedBreakpoint([In]ulong address);
[PreserveSig]int SetDesiredNGENCompilerFlags([In]uint pdwFlags);
[PreserveSig]int GetDesiredNGENCompilerFlags([Out]out uint pdwFlags);
[PreserveSig]int GetReferenceValueFromGCHandle([In]UIntPtr handle, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugReferenceValue pOutValue);
}
[Guid("2BD956D9-7B07-4BEF-8A98-12AA862417C5")]
[ComConversionLoss]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugThread2
{
[PreserveSig]int GetActiveFunctions([In]uint cFunctions, [Out]out uint pcFunctions, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] COR_ACTIVE_FUNCTION[] pFunctions);
[PreserveSig]int GetConnectionID([Out]out uint pdwConnectionId);
[PreserveSig]int GetTaskID([Out]out ulong pTaskId);
[PreserveSig]int GetVolatileOSThreadID([Out]out uint pdwTid);
[PreserveSig]int InterceptCurrentException([In, MarshalAs(UnmanagedType.Interface)]ICorDebugFrame pFrame);
}
public struct _COR_VERSION
{
public uint dwMajor;
public uint dwMinor;
public uint dwBuild;
public uint dwSubBuild;
}
[Guid("C5B6E9C3-E7D1-4A8E-873B-7F047F0706F7")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugStepper2
{
[PreserveSig]int SetJMC([In]int fIsJMCStepper);
}
[Guid("5D88A994-6C30-479B-890F-BCEF88B129A5")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugILFrame2
{
[PreserveSig]int RemapFunction([In]uint newILOffset);
[PreserveSig]int EnumerateTypeParameters([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugTypeEnum ppTyParEnum);
}
public enum CorDebugJITCompilerFlags : uint
{
CORDEBUG_JIT_DEFAULT = 0x1, // Track info
CORDEBUG_JIT_DISABLE_OPTIMIZATION = 0x3, // Includes track info
CORDEBUG_JIT_ENABLE_ENC = 0x7 // Includes track & disable opt
}
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("7FCC5FB5-49C0-41DE-9938-3B88B5B9ADD7")]
[ComImport]
public interface ICorDebugModule2
{
[PreserveSig]int SetJMCStatus([In]int bIsJustMyCode, [In]uint cTokens, [In]ref uint pTokens);
[PreserveSig]int ApplyChanges([In]uint cbMetadata, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)]byte[] pbMetadata, [In]uint cbIL, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)]byte[] pbIL);
[PreserveSig]int SetJITCompilerFlags([In]uint dwFlags);
[PreserveSig]int GetJITCompilerFlags([Out]out uint pdwFlags);
[PreserveSig]int ResolveAssembly([In]uint tkAssemblyRef, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugAssembly ppAssembly);
}
[Guid("EF0C490B-94C3-4E4D-B629-DDC134C532D8")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugFunction2
{
[PreserveSig]int SetJMCStatus([In]int bIsJustMyCode);
[PreserveSig]int GetJMCStatus([Out]out int pbIsJustMyCode);
[PreserveSig]int EnumerateNativeCode([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugCodeEnum ppCodeEnum);
[PreserveSig]int GetVersionNumber([Out]out uint pnVersion);
}
[Guid("55E96461-9645-45E4-A2FF-0367877ABCDE")]
[ComConversionLoss]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugCodeEnum : ICorDebugEnum
{
//ICorDebugEnum
[PreserveSig]int Skip([In]uint celt);
[PreserveSig]int Reset();
[PreserveSig]int Clone([Out]out IntPtr ppEnum);
[PreserveSig]int GetCount([Out]out uint pcelt);
//ICorDebugCodeEnum
[PreserveSig]int Next([In]uint celt, [Out]IntPtr values, [Out]out uint pceltFetched);
}
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("B008EA8D-7AB1-43F7-BB20-FBB5A04038AE")]
[ComImport]
public interface ICorDebugClass2
{
[PreserveSig]int GetParameterizedType([In]CorElementType elementType, [In]uint nTypeArgs, [In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.Interface, SizeParamIndex=1)] ICorDebugType[] ppTypeArgs, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugType ppType);
[PreserveSig]int SetJMCStatus([In]int bIsJustMyCode);
}
[Guid("FB0D9CE7-BE66-4683-9D32-A42A04E2FD91")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugEval2
{
[PreserveSig]int CallParameterizedFunction([In, MarshalAs(UnmanagedType.Interface)] ICorDebugFunction pFunction, [In] uint nTypeArgs, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] ICorDebugType[] ppTypeArgs, [In] uint nArgs, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] ICorDebugValue[] ppArgs);
[PreserveSig]int CreateValueForType([In, MarshalAs(UnmanagedType.Interface)] ICorDebugType pType, [Out, MarshalAs(UnmanagedType.Interface)] out ICorDebugValue ppValue);
[PreserveSig]int NewParameterizedObject([In, MarshalAs(UnmanagedType.Interface)] ICorDebugFunction pConstructor, [In] uint nTypeArgs, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] ICorDebugType[] ppTypeArgs, [In] uint nArgs, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] ICorDebugValue[] ppArgs);
[PreserveSig]int NewParameterizedObjectNoConstructor([In, MarshalAs(UnmanagedType.Interface)] ICorDebugClass pClass, [In] uint nTypeArgs, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] ICorDebugType[] ppTypeArgs);
[PreserveSig]int NewParameterizedArray([In, MarshalAs(UnmanagedType.Interface)] ICorDebugType pElementType, [In] uint rank, [In] ref uint dims, [In] ref uint lowBounds);
[PreserveSig]int NewStringWithLength([In, MarshalAs(UnmanagedType.LPWStr)] string @string, [In] uint uiLength);
[PreserveSig]int RudeAbort();
}
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("5E0B54E7-D88A-4626-9420-A691E0A78B49")]
[ComImport]
public interface ICorDebugValue2
{
[PreserveSig]int GetExactType([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugType ppType);
}
[Guid("49E4A320-4A9B-4ECA-B105-229FB7D5009F")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugObjectValue2
{
[PreserveSig]int GetVirtualMethodAndType([In]uint memberRef, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugFunction ppFunction, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugType ppType);
}
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("029596E8-276B-46A1-9821-732E96BBB00B")]
[ComImport]
public interface ICorDebugHandleValue : ICorDebugReferenceValue
{
//ICorDebugReferenceValue
[PreserveSig]int GetType([Out]out CorElementType pType);
[PreserveSig]int GetSize([Out]out uint pSize);
[PreserveSig]int GetAddress([Out]out ulong pAddress);
[PreserveSig]int CreateBreakpoint([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValueBreakpoint ppBreakpoint);
[PreserveSig]int IsNull([Out]out int pbNull);
[PreserveSig]int GetValue([Out]out ulong pValue);
[PreserveSig]int SetValue([In]ulong value);
[PreserveSig]int Dereference([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValue ppValue);
[PreserveSig]int DereferenceStrong([Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugValue ppValue);
//ICorDebugHandleValue
[PreserveSig]int GetHandleType([Out]out CorDebugHandleType pType);
[PreserveSig]int Dispose();
}
[Serializable]
public enum CorDebugHandleType
{
HANDLE_STRONG = 1,
HANDLE_WEAK_TRACK_RESURRECTION = 2,
}
[Guid("E3AC4D6C-9CB7-43E6-96CC-B21540E5083C")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ICorDebugHeapValue2
{
[PreserveSig]int CreateHandle([In]CorDebugHandleType type, [Out, MarshalAs(UnmanagedType.Interface)]out ICorDebugHandleValue ppHandle);
}
[Guid("83C91210-A34F-427C-B35F-79C3995B3C14")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface IDebugRemoteCorDebug
{
[PreserveSig]int CreateProcessEx([In, MarshalAs(UnmanagedType.Interface)]Microsoft.VisualStudio.Debugger.Interop.IDebugPort2 pPort, [In, MarshalAs(UnmanagedType.LPWStr)]string lpApplicationName, [In, MarshalAs(UnmanagedType.LPWStr)]string lpCommandLine, [In]IntPtr lpProcessAttributes, [In]IntPtr lpThreadAttributes, [In]int bInheritHandles, [In]uint dwCreationFlags, [In]IntPtr lpEnvironment, [In, MarshalAs(UnmanagedType.LPWStr)]string lpCurrentDirectory, [In]ref _STARTUPINFO lpStartupInfo, [In]ref _PROCESS_INFORMATION lpProcessInformation, [In]uint debuggingFlags, [Out, MarshalAs(UnmanagedType.IUnknown)]out object ppProcess);
[PreserveSig]int DebugActiveProcessEx([In, MarshalAs(UnmanagedType.Interface)]Microsoft.VisualStudio.Debugger.Interop.IDebugPort2 pPort, [In]uint id, [In]int win32Attach, [Out, MarshalAs(UnmanagedType.IUnknown)]out object ppProcess);
}
[Guid("782CB503-84B1-4B8F-9AAD-A12B75905015")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface IVbCompilerHost
{
[PreserveSig]int OutputString([In, MarshalAs(UnmanagedType.LPWStr)]string @string);
[PreserveSig]int GetSdkPath([Out, MarshalAs(UnmanagedType.BStr)]out string pSdkPath);
[PreserveSig]int GetTargetLibraryType([Out]out __MIDL___MIDL_itf_CorDebugInterop_1054_0004 pTargetLibraryType);
}
[Serializable]
public enum __MIDL___MIDL_itf_CorDebugInterop_1054_0004
{
TLB_Desktop = 1,
TLB_Starlite = 2,
}
[Serializable]
public enum LoggingLevelEnum
{
LTraceLevel0 = 0x0,
LTraceLevel1 = 0x1,
LTraceLevel2 = 0x2,
LTraceLevel3 = 0x3,
LTraceLevel4 = 0x4,
LStatusLevel0 = 0x14,
LStatusLevel1 = 0x15,
LStatusLevel2 = 0x16,
LStatusLevel3 = 0x17,
LStatusLevel4 = 0x18,
LWarningLevel = 0x28,
LErrorLevel = 0x32,
LPanicLevel = 0x64,
}
[Serializable]
public enum AD_PROCESS_ID_TYPE
{
AD_PROCESS_ID_SYSTEM = 0,
AD_PROCESS_ID_GUID = 1,
}
[Serializable]
public enum CorDebugExceptionFlags
{
DEBUG_EXCEPTION_CAN_BE_INTERCEPTED = 1,
}
#pragma warning restore 0108
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace System.IO
{
internal sealed partial class Win32FileSystem : FileSystem
{
public override int MaxPath { get { return Interop.mincore.MAX_PATH; } }
public override int MaxDirectoryPath { get { return Interop.mincore.MAX_DIRECTORY_PATH; } }
public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite)
{
Interop.mincore.SECURITY_ATTRIBUTES secAttrs = default(Interop.mincore.SECURITY_ATTRIBUTES);
int errorCode = Interop.mincore.CopyFile(sourceFullPath, destFullPath, !overwrite);
if (errorCode != Interop.mincore.Errors.ERROR_SUCCESS)
{
String fileName = destFullPath;
if (errorCode != Interop.mincore.Errors.ERROR_FILE_EXISTS)
{
// For a number of error codes (sharing violation, path
// not found, etc) we don't know if the problem was with
// the source or dest file. Try reading the source file.
using (SafeFileHandle handle = Interop.mincore.UnsafeCreateFile(sourceFullPath, Win32FileStream.GENERIC_READ, FileShare.Read, ref secAttrs, FileMode.Open, 0, IntPtr.Zero))
{
if (handle.IsInvalid)
fileName = sourceFullPath;
}
if (errorCode == Interop.mincore.Errors.ERROR_ACCESS_DENIED)
{
if (DirectoryExists(destFullPath))
throw new IOException(SR.Format(SR.Arg_FileIsDirectory_Name, destFullPath), Interop.mincore.Errors.ERROR_ACCESS_DENIED);
}
}
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fileName);
}
}
[System.Security.SecuritySafeCritical]
public override void CreateDirectory(string fullPath)
{
if (PathInternal.IsDirectoryTooLong(fullPath))
throw new PathTooLongException(SR.IO_PathTooLong);
// We can save a bunch of work if the directory we want to create already exists. This also
// saves us in the case where sub paths are inaccessible (due to ERROR_ACCESS_DENIED) but the
// final path is accessable and the directory already exists. For example, consider trying
// to create c:\Foo\Bar\Baz, where everything already exists but ACLS prevent access to c:\Foo
// and c:\Foo\Bar. In that case, this code will think it needs to create c:\Foo, and c:\Foo\Bar
// and fail to due so, causing an exception to be thrown. This is not what we want.
if (DirectoryExists(fullPath))
return;
List<string> stackDir = new List<string>();
// Attempt to figure out which directories don't exist, and only
// create the ones we need. Note that InternalExists may fail due
// to Win32 ACL's preventing us from seeing a directory, and this
// isn't threadsafe.
bool somepathexists = false;
int length = fullPath.Length;
// We need to trim the trailing slash or the code will try to create 2 directories of the same name.
if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath))
length--;
int lengthRoot = PathInternal.GetRootLength(fullPath);
if (length > lengthRoot)
{
// Special case root (fullpath = X:\\)
int i = length - 1;
while (i >= lengthRoot && !somepathexists)
{
String dir = fullPath.Substring(0, i + 1);
if (!DirectoryExists(dir)) // Create only the ones missing
stackDir.Add(dir);
else
somepathexists = true;
while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i])) i--;
i--;
}
}
int count = stackDir.Count;
// If we were passed a DirectorySecurity, convert it to a security
// descriptor and set it in he call to CreateDirectory.
Interop.mincore.SECURITY_ATTRIBUTES secAttrs = default(Interop.mincore.SECURITY_ATTRIBUTES);
bool r = true;
int firstError = 0;
String errorString = fullPath;
// If all the security checks succeeded create all the directories
while (stackDir.Count > 0)
{
String name = stackDir[stackDir.Count - 1];
stackDir.RemoveAt(stackDir.Count - 1);
r = Interop.mincore.CreateDirectory(name, ref secAttrs);
if (!r && (firstError == 0))
{
int currentError = Marshal.GetLastWin32Error();
// While we tried to avoid creating directories that don't
// exist above, there are at least two cases that will
// cause us to see ERROR_ALREADY_EXISTS here. InternalExists
// can fail because we didn't have permission to the
// directory. Secondly, another thread or process could
// create the directory between the time we check and the
// time we try using the directory. Thirdly, it could
// fail because the target does exist, but is a file.
if (currentError != Interop.mincore.Errors.ERROR_ALREADY_EXISTS)
firstError = currentError;
else
{
// If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw.
if (File.InternalExists(name) || (!DirectoryExists(name, out currentError) && currentError == Interop.mincore.Errors.ERROR_ACCESS_DENIED))
{
firstError = currentError;
errorString = name;
}
}
}
}
// We need this check to mask OS differences
// Handle CreateDirectory("X:\\") when X: doesn't exist. Similarly for n/w paths.
if ((count == 0) && !somepathexists)
{
String root = Directory.InternalGetDirectoryRoot(fullPath);
if (!DirectoryExists(root))
throw Win32Marshal.GetExceptionForWin32Error(Interop.mincore.Errors.ERROR_PATH_NOT_FOUND, root);
return;
}
// Only throw an exception if creating the exact directory we
// wanted failed to work correctly.
if (!r && (firstError != 0))
throw Win32Marshal.GetExceptionForWin32Error(firstError, errorString);
}
public override void DeleteFile(System.String fullPath)
{
bool r = Interop.mincore.DeleteFile(fullPath);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND)
return;
else
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
}
}
public override bool DirectoryExists(string fullPath)
{
int lastError = Interop.mincore.Errors.ERROR_SUCCESS;
return DirectoryExists(fullPath, out lastError);
}
private bool DirectoryExists(String path, out int lastError)
{
Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA();
lastError = FillAttributeInfo(path, ref data, false, true);
return (lastError == 0) && (data.fileAttributes != -1)
&& ((data.fileAttributes & Interop.mincore.FileAttributes.FILE_ATTRIBUTE_DIRECTORY) != 0);
}
public override IEnumerable<string> EnumeratePaths(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
return Win32FileSystemEnumerableFactory.CreateFileNameIterator(fullPath, fullPath, searchPattern,
(searchTarget & SearchTarget.Files) == SearchTarget.Files,
(searchTarget & SearchTarget.Directories) == SearchTarget.Directories,
searchOption);
}
public override IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
switch (searchTarget)
{
case SearchTarget.Directories:
return Win32FileSystemEnumerableFactory.CreateDirectoryInfoIterator(fullPath, fullPath, searchPattern, searchOption);
case SearchTarget.Files:
return Win32FileSystemEnumerableFactory.CreateFileInfoIterator(fullPath, fullPath, searchPattern, searchOption);
case SearchTarget.Both:
return Win32FileSystemEnumerableFactory.CreateFileSystemInfoIterator(fullPath, fullPath, searchPattern, searchOption);
default:
throw new ArgumentException(SR.ArgumentOutOfRange_Enum, "searchTarget");
}
}
// Returns 0 on success, otherwise a Win32 error code. Note that
// classes should use -1 as the uninitialized state for dataInitialized.
[System.Security.SecurityCritical] // auto-generated
internal static int FillAttributeInfo(String path, ref Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA data, bool tryagain, bool returnErrorOnNotFound)
{
int errorCode = 0;
if (tryagain) // someone has a handle to the file open, or other error
{
Interop.mincore.WIN32_FIND_DATA findData;
findData = new Interop.mincore.WIN32_FIND_DATA();
// Remove trialing slash since this can cause grief to FindFirstFile. You will get an invalid argument error
String tempPath = path.TrimEnd(PathHelpers.DirectorySeparatorChars);
// For floppy drives, normally the OS will pop up a dialog saying
// there is no disk in drive A:, please insert one. We don't want that.
// SetErrorMode will let us disable this, but we should set the error
// mode back, since this may have wide-ranging effects.
uint oldMode = Interop.mincore.SetErrorMode(Interop.mincore.SEM_FAILCRITICALERRORS);
try
{
bool error = false;
SafeFindHandle handle = Interop.mincore.FindFirstFile(tempPath, ref findData);
try
{
if (handle.IsInvalid)
{
error = true;
errorCode = Marshal.GetLastWin32Error();
if (errorCode == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND ||
errorCode == Interop.mincore.Errors.ERROR_PATH_NOT_FOUND ||
errorCode == Interop.mincore.Errors.ERROR_NOT_READY) // floppy device not ready
{
if (!returnErrorOnNotFound)
{
// Return default value for backward compatibility
errorCode = 0;
data.fileAttributes = -1;
}
}
return errorCode;
}
}
finally
{
// Close the Win32 handle
try
{
handle.Dispose();
}
catch
{
// if we're already returning an error, don't throw another one.
if (!error)
{
throw Win32Marshal.GetExceptionForLastWin32Error();
}
}
}
}
finally
{
Interop.mincore.SetErrorMode(oldMode);
}
// Copy the information to data
data.PopulateFrom(ref findData);
}
else
{
// For floppy drives, normally the OS will pop up a dialog saying
// there is no disk in drive A:, please insert one. We don't want that.
// SetErrorMode will let us disable this, but we should set the error
// mode back, since this may have wide-ranging effects.
bool success = false;
uint oldMode = Interop.mincore.SetErrorMode(Interop.mincore.SEM_FAILCRITICALERRORS);
try
{
success = Interop.mincore.GetFileAttributesEx(path, Interop.mincore.GET_FILEEX_INFO_LEVELS.GetFileExInfoStandard, ref data);
}
finally
{
Interop.mincore.SetErrorMode(oldMode);
}
if (!success)
{
errorCode = Marshal.GetLastWin32Error();
if (errorCode != Interop.mincore.Errors.ERROR_FILE_NOT_FOUND &&
errorCode != Interop.mincore.Errors.ERROR_PATH_NOT_FOUND &&
errorCode != Interop.mincore.Errors.ERROR_NOT_READY) // floppy device not ready
{
// In case someone latched onto the file. Take the perf hit only for failure
return FillAttributeInfo(path, ref data, true, returnErrorOnNotFound);
}
else
{
if (!returnErrorOnNotFound)
{
// Return default value for backward compatibility
errorCode = 0;
data.fileAttributes = -1;
}
}
}
}
return errorCode;
}
public override bool FileExists(System.String fullPath)
{
Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA();
int errorCode = FillAttributeInfo(fullPath, ref data, false, true);
return (errorCode == 0) && (data.fileAttributes != -1)
&& ((data.fileAttributes & Interop.mincore.FileAttributes.FILE_ATTRIBUTE_DIRECTORY) == 0);
}
public override FileAttributes GetAttributes(string fullPath)
{
Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA();
int errorCode = FillAttributeInfo(fullPath, ref data, false, true);
if (errorCode != 0)
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
return (FileAttributes)data.fileAttributes;
}
public override string GetCurrentDirectory()
{
StringBuilder sb = StringBuilderCache.Acquire(Interop.mincore.MAX_PATH + 1);
if (Interop.mincore.GetCurrentDirectory(sb.Capacity, sb) == 0)
throw Win32Marshal.GetExceptionForLastWin32Error();
String currentDirectory = sb.ToString();
// Note that if we have somehow put our command prompt into short
// file name mode (ie, by running edlin or a DOS grep, etc), then
// this will return a short file name.
if (currentDirectory.IndexOf('~') >= 0)
{
int r = Interop.mincore.GetLongPathName(currentDirectory, sb, sb.Capacity);
if (r == 0 || r >= Interop.mincore.MAX_PATH)
{
int errorCode = Marshal.GetLastWin32Error();
if (r >= Interop.mincore.MAX_PATH)
errorCode = Interop.mincore.Errors.ERROR_FILENAME_EXCED_RANGE;
if (errorCode != Interop.mincore.Errors.ERROR_FILE_NOT_FOUND &&
errorCode != Interop.mincore.Errors.ERROR_PATH_NOT_FOUND &&
errorCode != Interop.mincore.Errors.ERROR_INVALID_FUNCTION && // by design - enough said.
errorCode != Interop.mincore.Errors.ERROR_ACCESS_DENIED)
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
currentDirectory = sb.ToString();
}
StringBuilderCache.Release(sb);
return currentDirectory;
}
public override DateTimeOffset GetCreationTime(string fullPath)
{
Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA();
int errorCode = FillAttributeInfo(fullPath, ref data, false, false);
if (errorCode != 0)
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
long dt = ((long)(data.ftCreationTimeHigh) << 32) | ((long)data.ftCreationTimeLow);
return DateTimeOffset.FromFileTime(dt);
}
public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory)
{
return asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
}
public override DateTimeOffset GetLastAccessTime(string fullPath)
{
Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA();
int errorCode = FillAttributeInfo(fullPath, ref data, false, false);
if (errorCode != 0)
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
long dt = ((long)(data.ftLastAccessTimeHigh) << 32) | ((long)data.ftLastAccessTimeLow);
return DateTimeOffset.FromFileTime(dt);
}
public override DateTimeOffset GetLastWriteTime(string fullPath)
{
Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA();
int errorCode = FillAttributeInfo(fullPath, ref data, false, false);
if (errorCode != 0)
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
long dt = ((long)data.ftLastWriteTimeHigh << 32) | ((long)data.ftLastWriteTimeLow);
return DateTimeOffset.FromFileTime(dt);
}
public override void MoveDirectory(string sourceFullPath, string destFullPath)
{
if (!Interop.mincore.MoveFile(sourceFullPath, destFullPath))
{
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND)
throw Win32Marshal.GetExceptionForWin32Error(Interop.mincore.Errors.ERROR_PATH_NOT_FOUND, sourceFullPath);
// This check was originally put in for Win9x (unfortunately without special casing it to be for Win9x only). We can't change the NT codepath now for backcomp reasons.
if (errorCode == Interop.mincore.Errors.ERROR_ACCESS_DENIED) // WinNT throws IOException. This check is for Win9x. We can't change it for backcomp.
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, sourceFullPath), Win32Marshal.MakeHRFromErrorCode(errorCode));
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
public override void MoveFile(string sourceFullPath, string destFullPath)
{
if (!Interop.mincore.MoveFile(sourceFullPath, destFullPath))
{
throw Win32Marshal.GetExceptionForLastWin32Error();
}
}
public override FileStreamBase Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)
{
return new Win32FileStream(fullPath, mode, access, share, bufferSize, options, parent);
}
[System.Security.SecurityCritical]
private static SafeFileHandle OpenHandle(string fullPath, bool asDirectory)
{
String root = fullPath.Substring(0, PathInternal.GetRootLength(fullPath));
if (root == fullPath && root[1] == Path.VolumeSeparatorChar)
{
// intentionally not fullpath, most upstack public APIs expose this as path.
throw new ArgumentException(SR.Arg_PathIsVolume, "path");
}
Interop.mincore.SECURITY_ATTRIBUTES secAttrs = default(Interop.mincore.SECURITY_ATTRIBUTES);
SafeFileHandle handle = Interop.mincore.SafeCreateFile(
fullPath,
(int)Interop.mincore.GenericOperations.GENERIC_WRITE,
FileShare.ReadWrite | FileShare.Delete,
ref secAttrs,
FileMode.Open,
asDirectory ? (int)Interop.mincore.FileOperations.FILE_FLAG_BACKUP_SEMANTICS : (int)FileOptions.None,
IntPtr.Zero
);
if (handle.IsInvalid)
{
int errorCode = Marshal.GetLastWin32Error();
// NT5 oddity - when trying to open "C:\" as a File,
// we usually get ERROR_PATH_NOT_FOUND from the OS. We should
// probably be consistent w/ every other directory.
if (!asDirectory && errorCode == Interop.mincore.Errors.ERROR_PATH_NOT_FOUND && fullPath.Equals(Directory.GetDirectoryRoot(fullPath)))
errorCode = Interop.mincore.Errors.ERROR_ACCESS_DENIED;
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
}
return handle;
}
public override void RemoveDirectory(string fullPath, bool recursive)
{
// Do not recursively delete through reparse points. Perhaps in a
// future version we will add a new flag to control this behavior,
// but for now we're much safer if we err on the conservative side.
// This applies to symbolic links and mount points.
Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA();
int errorCode = FillAttributeInfo(fullPath, ref data, false, true);
if (errorCode != 0)
{
// Ensure we throw a DirectoryNotFoundException.
if (errorCode == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND)
errorCode = Interop.mincore.Errors.ERROR_PATH_NOT_FOUND;
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
}
if (((FileAttributes)data.fileAttributes & FileAttributes.ReparsePoint) != 0)
recursive = false;
// We want extended syntax so we can delete "extended" subdirectories and files
// (most notably ones with trailing whitespace or periods)
RemoveDirectoryHelper(PathInternal.EnsureExtendedPrefix(fullPath), recursive, true);
}
[System.Security.SecurityCritical] // auto-generated
private static void RemoveDirectoryHelper(string fullPath, bool recursive, bool throwOnTopLevelDirectoryNotFound)
{
bool r;
int errorCode;
Exception ex = null;
// Do not recursively delete through reparse points. Perhaps in a
// future version we will add a new flag to control this behavior,
// but for now we're much safer if we err on the conservative side.
// This applies to symbolic links and mount points.
// Note the logic to check whether fullPath is a reparse point is
// in Delete(String, String, bool), and will set "recursive" to false.
// Note that Win32's DeleteFile and RemoveDirectory will just delete
// the reparse point itself.
if (recursive)
{
Interop.mincore.WIN32_FIND_DATA data = new Interop.mincore.WIN32_FIND_DATA();
// Open a Find handle
using (SafeFindHandle hnd = Interop.mincore.FindFirstFile(Directory.EnsureTrailingDirectorySeparator(fullPath) + "*", ref data))
{
if (hnd.IsInvalid)
throw Win32Marshal.GetExceptionForLastWin32Error(fullPath);
do
{
bool isDir = (0 != (data.dwFileAttributes & Interop.mincore.FileAttributes.FILE_ATTRIBUTE_DIRECTORY));
if (isDir)
{
// Skip ".", "..".
if (data.cFileName.Equals(".") || data.cFileName.Equals(".."))
continue;
// Recurse for all directories, unless they are
// reparse points. Do not follow mount points nor
// symbolic links, but do delete the reparse point
// itself.
bool shouldRecurse = (0 == (data.dwFileAttributes & (int)FileAttributes.ReparsePoint));
if (shouldRecurse)
{
string newFullPath = Path.Combine(fullPath, data.cFileName);
try
{
RemoveDirectoryHelper(newFullPath, recursive, false);
}
catch (Exception e)
{
if (ex == null)
ex = e;
}
}
else
{
// Check to see if this is a mount point, and
// unmount it.
if (data.dwReserved0 == Interop.mincore.IOReparseOptions.IO_REPARSE_TAG_MOUNT_POINT)
{
// Use full path plus a trailing '\'
String mountPoint = Path.Combine(fullPath, data.cFileName + PathHelpers.DirectorySeparatorCharAsString);
if (!Interop.mincore.DeleteVolumeMountPoint(mountPoint))
{
errorCode = Marshal.GetLastWin32Error();
if (errorCode != Interop.mincore.Errors.ERROR_SUCCESS &&
errorCode != Interop.mincore.Errors.ERROR_PATH_NOT_FOUND)
{
try
{
throw Win32Marshal.GetExceptionForWin32Error(errorCode, data.cFileName);
}
catch (Exception e)
{
if (ex == null)
ex = e;
}
}
}
}
// RemoveDirectory on a symbolic link will
// remove the link itself.
String reparsePoint = Path.Combine(fullPath, data.cFileName);
r = Interop.mincore.RemoveDirectory(reparsePoint);
if (!r)
{
errorCode = Marshal.GetLastWin32Error();
if (errorCode != Interop.mincore.Errors.ERROR_PATH_NOT_FOUND)
{
try
{
throw Win32Marshal.GetExceptionForWin32Error(errorCode, data.cFileName);
}
catch (Exception e)
{
if (ex == null)
ex = e;
}
}
}
}
}
else
{
String fileName = Path.Combine(fullPath, data.cFileName);
r = Interop.mincore.DeleteFile(fileName);
if (!r)
{
errorCode = Marshal.GetLastWin32Error();
if (errorCode != Interop.mincore.Errors.ERROR_FILE_NOT_FOUND)
{
try
{
throw Win32Marshal.GetExceptionForWin32Error(errorCode, data.cFileName);
}
catch (Exception e)
{
if (ex == null)
ex = e;
}
}
}
}
} while (Interop.mincore.FindNextFile(hnd, ref data));
// Make sure we quit with a sensible error.
errorCode = Marshal.GetLastWin32Error();
}
if (ex != null)
throw ex;
if (errorCode != 0 && errorCode != Interop.mincore.Errors.ERROR_NO_MORE_FILES)
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
}
r = Interop.mincore.RemoveDirectory(fullPath);
if (!r)
{
errorCode = Marshal.GetLastWin32Error();
if (errorCode == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND) // A dubious error code.
errorCode = Interop.mincore.Errors.ERROR_PATH_NOT_FOUND;
// This check was originally put in for Win9x (unfortunately without special casing it to be for Win9x only). We can't change the NT codepath now for backcomp reasons.
if (errorCode == Interop.mincore.Errors.ERROR_ACCESS_DENIED)
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, fullPath));
// don't throw the DirectoryNotFoundException since this is a subdir and
// there could be a race condition between two Directory.Delete callers
if (errorCode == Interop.mincore.Errors.ERROR_PATH_NOT_FOUND && !throwOnTopLevelDirectoryNotFound)
return;
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
}
}
public override void SetAttributes(string fullPath, FileAttributes attributes)
{
SetAttributesInternal(fullPath, attributes);
}
private static void SetAttributesInternal(string fullPath, FileAttributes attributes)
{
bool r = Interop.mincore.SetFileAttributes(fullPath, (int)attributes);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == Interop.mincore.Errors.ERROR_INVALID_PARAMETER)
throw new ArgumentException(SR.Arg_InvalidFileAttrs, "attributes");
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
}
}
public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
SetCreationTimeInternal(fullPath, time, asDirectory);
}
private static void SetCreationTimeInternal(string fullPath, DateTimeOffset time, bool asDirectory)
{
using (SafeFileHandle handle = OpenHandle(fullPath, asDirectory))
{
bool r = Interop.mincore.SetFileTime(handle, creationTime: time.ToFileTime());
if (!r)
{
throw Win32Marshal.GetExceptionForLastWin32Error(fullPath);
}
}
}
public override void SetCurrentDirectory(string fullPath)
{
if (!Interop.mincore.SetCurrentDirectory(fullPath))
{
// If path doesn't exist, this sets last error to 2 (File
// not Found). LEGACY: This may potentially have worked correctly
// on Win9x, maybe.
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND)
errorCode = Interop.mincore.Errors.ERROR_PATH_NOT_FOUND;
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
}
}
public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
SetLastAccessTimeInternal(fullPath, time, asDirectory);
}
private static void SetLastAccessTimeInternal(string fullPath, DateTimeOffset time, bool asDirectory)
{
using (SafeFileHandle handle = OpenHandle(fullPath, asDirectory))
{
bool r = Interop.mincore.SetFileTime(handle, lastAccessTime: time.ToFileTime());
if (!r)
{
throw Win32Marshal.GetExceptionForLastWin32Error(fullPath);
}
}
}
public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
SetLastWriteTimeInternal(fullPath, time, asDirectory);
}
private static void SetLastWriteTimeInternal(string fullPath, DateTimeOffset time, bool asDirectory)
{
using (SafeFileHandle handle = OpenHandle(fullPath, asDirectory))
{
bool r = Interop.mincore.SetFileTime(handle, lastWriteTime: time.ToFileTime());
if (!r)
{
throw Win32Marshal.GetExceptionForLastWin32Error(fullPath);
}
}
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System.Diagnostics;
namespace NLog.UnitTests.Targets.Wrappers
{
using System;
using System.Threading;
using NLog.Common;
using NLog.Targets;
using NLog.Targets.Wrappers;
using Xunit;
public class BufferingTargetWrapperTests : NLogTestBase
{
[Fact]
public void BufferingTargetWrapperSyncTest1()
{
var myTarget = new MyTarget();
var targetWrapper = new BufferingTargetWrapper
{
WrappedTarget = myTarget,
BufferSize = 10,
};
InitializeTargets(myTarget, targetWrapper);
const int totalEvents = 100;
var continuationHit = new bool[totalEvents];
var lastException = new Exception[totalEvents];
var continuationThread = new Thread[totalEvents];
var hitCount = 0;
CreateContinuationFunc createAsyncContinuation =
eventNumber =>
ex =>
{
lastException[eventNumber] = ex;
continuationThread[eventNumber] = Thread.CurrentThread;
continuationHit[eventNumber] = true;
Interlocked.Increment(ref hitCount);
};
// write 9 events - they will all be buffered and no final continuation will be reached
var eventCounter = 0;
for (var i = 0; i < 9; ++i)
{
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
}
Assert.Equal(0, hitCount);
Assert.Equal(0, myTarget.WriteCount);
// write one more event - everything will be flushed
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
Assert.Equal(10, hitCount);
Assert.Equal(1, myTarget.BufferedWriteCount);
Assert.Equal(10, myTarget.BufferedTotalEvents);
Assert.Equal(10, myTarget.WriteCount);
for (var i = 0; i < hitCount; ++i)
{
Assert.Same(Thread.CurrentThread, continuationThread[i]);
Assert.Null(lastException[i]);
}
// write 9 more events - they will all be buffered and no final continuation will be reached
for (var i = 0; i < 9; ++i)
{
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
}
// no change
Assert.Equal(10, hitCount);
Assert.Equal(1, myTarget.BufferedWriteCount);
Assert.Equal(10, myTarget.BufferedTotalEvents);
Assert.Equal(10, myTarget.WriteCount);
Exception flushException = null;
var flushHit = new ManualResetEvent(false);
targetWrapper.Flush(
ex =>
{
flushException = ex;
flushHit.Set();
});
flushHit.WaitOne();
Assert.Null(flushException);
// make sure remaining events were written
Assert.Equal(19, hitCount);
Assert.Equal(2, myTarget.BufferedWriteCount);
Assert.Equal(19, myTarget.BufferedTotalEvents);
Assert.Equal(19, myTarget.WriteCount);
Assert.Equal(1, myTarget.FlushCount);
// flushes happen on the same thread
for (var i = 10; i < hitCount; ++i)
{
Assert.NotNull(continuationThread[i]);
Assert.Same(Thread.CurrentThread, continuationThread[i]);
Assert.Null(lastException[i]);
}
// flush again - should just invoke Flush() on the wrapped target
flushHit.Reset();
targetWrapper.Flush(
ex =>
{
flushException = ex;
flushHit.Set();
});
flushHit.WaitOne();
Assert.Equal(19, hitCount);
Assert.Equal(2, myTarget.BufferedWriteCount);
Assert.Equal(19, myTarget.BufferedTotalEvents);
Assert.Equal(19, myTarget.WriteCount);
Assert.Equal(2, myTarget.FlushCount);
targetWrapper.Close();
myTarget.Close();
}
[Fact]
public void BufferingTargetWithFallbackGroupAndFirstTargetFails_Write_SecondTargetWritesEvents()
{
var myTarget = new MyTarget { FailCounter = 1 };
var myTarget2 = new MyTarget();
var fallbackGroup = new FallbackGroupTarget(myTarget, myTarget2);
var targetWrapper = new BufferingTargetWrapper
{
WrappedTarget = fallbackGroup,
BufferSize = 10,
};
InitializeTargets(myTarget, targetWrapper, myTarget2, fallbackGroup);
const int totalEvents = 100;
var continuationHit = new bool[totalEvents];
var lastException = new Exception[totalEvents];
var continuationThread = new Thread[totalEvents];
CreateContinuationFunc createAsyncContinuation =
eventNumber =>
ex =>
{
lastException[eventNumber] = ex;
continuationThread[eventNumber] = Thread.CurrentThread;
continuationHit[eventNumber] = true;
};
// write 9 events - they will all be buffered and no final continuation will be reached
var eventCounter = 0;
for (var i = 0; i < 9; ++i)
{
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
}
Assert.Equal(0, myTarget.WriteCount);
// write one more event - everything will be flushed
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
Assert.Equal(1, myTarget.WriteCount);
Assert.Equal(10, myTarget2.WriteCount);
targetWrapper.Close();
myTarget.Close();
}
[Fact]
public void BufferingTargetWrapperSyncWithTimedFlushTest()
{
var myTarget = new MyTarget();
var targetWrapper = new BufferingTargetWrapper
{
WrappedTarget = myTarget,
BufferSize = 10,
FlushTimeout = 1000,
};
InitializeTargets(myTarget, targetWrapper);
const int totalEvents = 100;
var continuationHit = new bool[totalEvents];
var lastException = new Exception[totalEvents];
var continuationThread = new Thread[totalEvents];
var hitCount = 0;
CreateContinuationFunc createAsyncContinuation =
eventNumber =>
ex =>
{
lastException[eventNumber] = ex;
continuationThread[eventNumber] = Thread.CurrentThread;
continuationHit[eventNumber] = true;
Interlocked.Increment(ref hitCount);
};
// write 9 events - they will all be buffered and no final continuation will be reached
var eventCounter = 0;
for (var i = 0; i < 9; ++i)
{
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
}
Assert.Equal(0, hitCount);
Assert.Equal(0, myTarget.WriteCount);
// sleep 2 seconds, this will trigger the timer and flush all events
Thread.Sleep(1500);
Assert.Equal(9, hitCount);
Assert.Equal(1, myTarget.BufferedWriteCount);
Assert.Equal(9, myTarget.BufferedTotalEvents);
Assert.Equal(9, myTarget.WriteCount);
for (var i = 0; i < hitCount; ++i)
{
Assert.NotSame(Thread.CurrentThread, continuationThread[i]);
Assert.Null(lastException[i]);
}
// write 11 more events, 10 will be hit immediately because the buffer will fill up
// 1 will be pending
for (var i = 0; i < 11; ++i)
{
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
}
Assert.Equal(19, hitCount);
Assert.Equal(2, myTarget.BufferedWriteCount);
Assert.Equal(19, myTarget.BufferedTotalEvents);
Assert.Equal(19, myTarget.WriteCount);
// sleep 2 seconds and the last remaining one will be flushed
Thread.Sleep(1500);
Assert.Equal(20, hitCount);
Assert.Equal(3, myTarget.BufferedWriteCount);
Assert.Equal(20, myTarget.BufferedTotalEvents);
Assert.Equal(20, myTarget.WriteCount);
}
[Fact]
public void BufferingTargetWrapperAsyncTest1()
{
var myTarget = new MyAsyncTarget();
var targetWrapper = new BufferingTargetWrapper
{
WrappedTarget = myTarget,
BufferSize = 10,
};
InitializeTargets(myTarget, targetWrapper);
const int totalEvents = 100;
var continuationHit = new bool[totalEvents];
var lastException = new Exception[totalEvents];
var continuationThread = new Thread[totalEvents];
var hitCount = 0;
CreateContinuationFunc createAsyncContinuation =
eventNumber =>
ex =>
{
lastException[eventNumber] = ex;
continuationThread[eventNumber] = Thread.CurrentThread;
continuationHit[eventNumber] = true;
Interlocked.Increment(ref hitCount);
};
// write 9 events - they will all be buffered and no final continuation will be reached
var eventCounter = 0;
for (var i = 0; i < 9; ++i)
{
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
}
Assert.Equal(0, hitCount);
// write one more event - everything will be flushed
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
while (hitCount < 10)
{
Thread.Sleep(10);
}
Assert.Equal(10, hitCount);
Assert.Equal(1, myTarget.BufferedWriteCount);
Assert.Equal(10, myTarget.BufferedTotalEvents);
for (var i = 0; i < hitCount; ++i)
{
Assert.NotSame(Thread.CurrentThread, continuationThread[i]);
Assert.Null(lastException[i]);
}
// write 9 more events - they will all be buffered and no final continuation will be reached
for (var i = 0; i < 9; ++i)
{
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
}
// no change
Assert.Equal(10, hitCount);
Assert.Equal(1, myTarget.BufferedWriteCount);
Assert.Equal(10, myTarget.BufferedTotalEvents);
Exception flushException = null;
var flushHit = new ManualResetEvent(false);
targetWrapper.Flush(
ex =>
{
flushException = ex;
flushHit.Set();
});
flushHit.WaitOne();
Assert.Null(flushException);
// make sure remaining events were written
Assert.Equal(19, hitCount);
Assert.Equal(2, myTarget.BufferedWriteCount);
Assert.Equal(19, myTarget.BufferedTotalEvents);
// flushes happen on another thread
for (var i = 10; i < hitCount; ++i)
{
Assert.NotNull(continuationThread[i]);
Assert.NotSame(Thread.CurrentThread, continuationThread[i]);
Assert.Null(lastException[i]);
}
// flush again - should not do anything
flushHit.Reset();
targetWrapper.Flush(
ex =>
{
flushException = ex;
flushHit.Set();
});
flushHit.WaitOne();
Assert.Equal(19, hitCount);
Assert.Equal(2, myTarget.BufferedWriteCount);
Assert.Equal(19, myTarget.BufferedTotalEvents);
targetWrapper.Close();
myTarget.Close();
}
[Fact]
public void BufferingTargetWrapperSyncWithTimedFlushNonSlidingTest()
{
var myTarget = new MyTarget();
var targetWrapper = new BufferingTargetWrapper
{
WrappedTarget = myTarget,
BufferSize = 10,
FlushTimeout = 400,
SlidingTimeout = false,
};
InitializeTargets(myTarget, targetWrapper);
const int totalEvents = 100;
var continuationHit = new bool[totalEvents];
var lastException = new Exception[totalEvents];
var continuationThread = new Thread[totalEvents];
var hitCount = 0;
var resetEvent = new ManualResetEvent(false);
CreateContinuationFunc createAsyncContinuation =
eventNumber =>
ex =>
{
lastException[eventNumber] = ex;
continuationThread[eventNumber] = Thread.CurrentThread;
continuationHit[eventNumber] = true;
Interlocked.Increment(ref hitCount);
if (eventNumber > 0)
{
resetEvent.Set();
}
};
var eventCounter = 0;
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
Assert.Equal(0, hitCount);
Assert.Equal(0, myTarget.WriteCount);
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
Assert.True(resetEvent.WaitOne(5000));
Assert.Equal(2, hitCount);
Assert.Equal(2, myTarget.WriteCount);
}
[Fact]
public void BufferingTargetWrapperSyncWithTimedFlushSlidingTest()
{
var myTarget = new MyTarget();
var targetWrapper = new BufferingTargetWrapper
{
WrappedTarget = myTarget,
BufferSize = 10,
FlushTimeout = 400,
};
InitializeTargets(myTarget, targetWrapper);
const int totalEvents = 100;
var continuationHit = new bool[totalEvents];
var lastException = new Exception[totalEvents];
var continuationThread = new Thread[totalEvents];
var hitCount = 0;
CreateContinuationFunc createAsyncContinuation =
eventNumber =>
ex =>
{
lastException[eventNumber] = ex;
continuationThread[eventNumber] = Thread.CurrentThread;
continuationHit[eventNumber] = true;
Interlocked.Increment(ref hitCount);
};
var eventCounter = 0;
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
Thread.Sleep(100);
Assert.Equal(0, hitCount);
Assert.Equal(0, myTarget.WriteCount);
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
Thread.Sleep(100);
Assert.Equal(0, hitCount);
Assert.Equal(0, myTarget.WriteCount);
Thread.Sleep(600);
Assert.Equal(2, hitCount);
Assert.Equal(2, myTarget.WriteCount);
}
[Fact]
public void WhenWrappedTargetThrowsExceptionThisIsHandled()
{
var myTarget = new MyTarget { ThrowException = true };
var bufferingTargetWrapper = new BufferingTargetWrapper
{
WrappedTarget = myTarget,
FlushTimeout = -1
};
InitializeTargets(myTarget, bufferingTargetWrapper);
bufferingTargetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(_ => { }));
var flushHit = new ManualResetEvent(false);
bufferingTargetWrapper.Flush(ex => flushHit.Set());
flushHit.WaitOne();
Assert.Equal(1, myTarget.FlushCount);
}
private static void InitializeTargets(params Target[] targets)
{
foreach (var target in targets)
{
target.Initialize(null);
}
}
private class MyAsyncTarget : Target
{
public int BufferedWriteCount { get; private set; }
public int BufferedTotalEvents { get; private set; }
protected override void Write(LogEventInfo logEvent)
{
throw new NotSupportedException();
}
protected override void Write(AsyncLogEventInfo[] logEvents)
{
this.BufferedWriteCount++;
this.BufferedTotalEvents += logEvents.Length;
foreach (var logEvent in logEvents)
{
var @event = logEvent;
ThreadPool.QueueUserWorkItem(
s =>
{
if (this.ThrowExceptions)
{
@event.Continuation(new InvalidOperationException("Some problem!"));
@event.Continuation(new InvalidOperationException("Some problem!"));
}
else
{
@event.Continuation(null);
@event.Continuation(null);
}
});
}
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
ThreadPool.QueueUserWorkItem(
s => asyncContinuation(null));
}
public bool ThrowExceptions { get; set; }
}
private class MyTarget : Target
{
public int FlushCount { get; private set; }
public int WriteCount { get; private set; }
public int BufferedWriteCount { get; private set; }
public int BufferedTotalEvents { get; private set; }
public bool ThrowException { get; set; }
public int FailCounter { get; set; }
protected override void Write(AsyncLogEventInfo[] logEvents)
{
this.BufferedWriteCount++;
this.BufferedTotalEvents += logEvents.Length;
base.Write(logEvents);
}
protected override void Write(LogEventInfo logEvent)
{
Assert.True(this.FlushCount <= this.WriteCount);
this.WriteCount++;
if (ThrowException)
{
throw new Exception("Target exception");
}
if (this.FailCounter > 0)
{
this.FailCounter--;
throw new InvalidOperationException("Some failure.");
}
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
this.FlushCount++;
asyncContinuation(null);
}
}
private delegate AsyncContinuation CreateContinuationFunc(int eventNumber);
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using OLEDB.Test.ModuleCore;
namespace System.Xml.Tests
{
public partial class TCReadElementContentAsBase64 : TCXMLReaderBaseGeneral
{
// Type is System.Xml.Tests.TCReadElementContentAsBase64
// Test Case
public override void AddChildren()
{
// for function TestReadBase64_1
{
this.AddChild(new CVariation(TestReadBase64_1) { Attribute = new Variation("ReadBase64 Element with all valid value") });
}
// for function TestReadBase64_2
{
this.AddChild(new CVariation(TestReadBase64_2) { Attribute = new Variation("ReadBase64 Element with all valid Num value") { Pri = 0 } });
}
// for function TestReadBase64_3
{
this.AddChild(new CVariation(TestReadBase64_3) { Attribute = new Variation("ReadBase64 Element with all valid Text value") });
}
// for function TestReadBase64_5
{
this.AddChild(new CVariation(TestReadBase64_5) { Attribute = new Variation("ReadBase64 Element with all valid value (from concatenation), Pri=0") });
}
// for function TestReadBase64_6
{
this.AddChild(new CVariation(TestReadBase64_6) { Attribute = new Variation("ReadBase64 Element with Long valid value (from concatenation), Pri=0") });
}
// for function ReadBase64_7
{
this.AddChild(new CVariation(ReadBase64_7) { Attribute = new Variation("ReadBase64 with count > buffer size") });
}
// for function ReadBase64_8
{
this.AddChild(new CVariation(ReadBase64_8) { Attribute = new Variation("ReadBase64 with count < 0") });
}
// for function ReadBase64_9
{
this.AddChild(new CVariation(ReadBase64_9) { Attribute = new Variation("ReadBase64 with index > buffer size") });
}
// for function ReadBase64_10
{
this.AddChild(new CVariation(ReadBase64_10) { Attribute = new Variation("ReadBase64 with index < 0") });
}
// for function ReadBase64_11
{
this.AddChild(new CVariation(ReadBase64_11) { Attribute = new Variation("ReadBase64 with index + count exceeds buffer") });
}
// for function ReadBase64_12
{
this.AddChild(new CVariation(ReadBase64_12) { Attribute = new Variation("ReadBase64 index & count =0") });
}
// for function TestReadBase64_13
{
this.AddChild(new CVariation(TestReadBase64_13) { Attribute = new Variation("ReadBase64 Element multiple into same buffer (using offset), Pri=0") });
}
// for function TestReadBase64_14
{
this.AddChild(new CVariation(TestReadBase64_14) { Attribute = new Variation("ReadBase64 with buffer == null") });
}
// for function TestReadBase64_15
{
this.AddChild(new CVariation(TestReadBase64_15) { Attribute = new Variation("ReadBase64 after failure") });
}
// for function TestReadBase64_16
{
this.AddChild(new CVariation(TestReadBase64_16) { Attribute = new Variation("Read after partial ReadBase64") { Pri = 0 } });
}
// for function TestReadBase64_17
{
this.AddChild(new CVariation(TestReadBase64_17) { Attribute = new Variation("Current node on multiple calls") });
}
// for function TestTextReadBase64_23
{
this.AddChild(new CVariation(TestTextReadBase64_23) { Attribute = new Variation("ReadBase64 with incomplete sequence") });
}
// for function TestTextReadBase64_24
{
this.AddChild(new CVariation(TestTextReadBase64_24) { Attribute = new Variation("ReadBase64 when end tag doesn't exist") });
}
// for function TestTextReadBase64_26
{
this.AddChild(new CVariation(TestTextReadBase64_26) { Attribute = new Variation("ReadBase64 with whitespaces in the middle") });
}
// for function TestTextReadBase64_27
{
this.AddChild(new CVariation(TestTextReadBase64_27) { Attribute = new Variation("ReadBase64 with = in the middle") });
}
// for function ReadBase64BufferOverflowWorksProperly
{
this.AddChild(new CVariation(ReadBase64RunsIntoOverflow) { Attribute = new Variation("ReadBase64 runs into an Overflow") { Params = new object[] { "1000000" } } });
this.AddChild(new CVariation(ReadBase64RunsIntoOverflow) { Attribute = new Variation("ReadBase64 runs into an Overflow") { Params = new object[] { "10000" } } });
this.AddChild(new CVariation(ReadBase64RunsIntoOverflow) { Attribute = new Variation("ReadBase64 runs into an Overflow") { Params = new object[] { "10000000" } } });
}
// for function TestReadBase64ReadsTheContent
{
this.AddChild(new CVariation(TestReadBase64ReadsTheContent) { Attribute = new Variation("WS:WireCompat:hex binary fails to send/return data after 1787 bytes") });
}
// for function ReadValueChunkWorksProperlyWithSubtreeReaderInsertedAttributes
{
this.AddChild(new CVariation(SubtreeReaderInsertedAttributesWorkWithReadContentAsBase64) { Attribute = new Variation("SubtreeReader inserted attributes don't work with ReadContentAsBase64") });
}
// for function TestReadBase64_28
{
this.AddChild(new CVariation(TestReadBase64_28) { Attribute = new Variation("call ReadContentAsBase64 on two or more nodes") });
}
// for function TestReadBase64_29
{
this.AddChild(new CVariation(TestReadBase64_29) { Attribute = new Variation("read Base64 over invalid text node") });
}
// for function TestReadBase64_30
{
this.AddChild(new CVariation(TestReadBase64_30) { Attribute = new Variation("goto to text node, ask got.Value, readcontentasBase64") });
}
// for function TestReadBase64_31
{
this.AddChild(new CVariation(TestReadBase64_31) { Attribute = new Variation("goto to text node, readcontentasBase64, ask got.Value") });
}
// for function TestReadBase64_32
{
this.AddChild(new CVariation(TestReadBase64_32) { Attribute = new Variation("goto to huge text node, read several chars with ReadContentAsBase64 and Move forward with .Read()") });
}
// for function TestReadBase64_33
{
this.AddChild(new CVariation(TestReadBase64_33) { Attribute = new Variation("goto to huge text node with invalid chars, read several chars with ReadContentAsBase64 and Move forward with .Read()") });
}
// for function TestReadBase64_34
{
this.AddChild(new CVariation(TestReadBase64_34) { Attribute = new Variation("ReadContentAsBase64 on an xmlns attribute") { Param = "<foo xmlns='default'> <bar id='1'/> </foo>" } });
this.AddChild(new CVariation(TestReadBase64_34) { Attribute = new Variation("ReadContentAsBase64 on an xml:lang attribute") { Param = "<foo xml:lang='default'> <bar id='1'/> </foo>" } });
this.AddChild(new CVariation(TestReadBase64_34) { Attribute = new Variation("ReadContentAsBase64 on an xmlns:k attribute") { Param = "<k:foo xmlns:k='default'> <k:bar id='1'/> </k:foo>" } });
this.AddChild(new CVariation(TestReadBase64_34) { Attribute = new Variation("ReadContentAsBase64 on an xml:space attribute") { Param = "<foo xml:space='default'> <bar id='1'/> </foo>" } });
}
// for function TestReadReadBase64_35
{
this.AddChild(new CVariation(TestReadReadBase64_35) { Attribute = new Variation("call ReadContentAsBase64 on two or more nodes and whitespace") });
}
// for function TestReadReadBase64_36
{
this.AddChild(new CVariation(TestReadReadBase64_36) { Attribute = new Variation("call ReadContentAsBase64 on two or more nodes and whitespace after call Value") });
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Binary
{
using System;
using System.Collections.Generic;
using System.Reflection;
using Apache.Ignite.Core.Impl.Binary;
/// <summary>
/// Binary serializer which reflectively writes all fields except of ones with
/// <see cref="System.NonSerializedAttribute"/>.
/// <para />
/// Note that Java platform stores dates as a difference between current time
/// and predefined absolute UTC date. Therefore, this difference is always the
/// same for all time zones. .NET, in contrast, stores dates as a difference
/// between current time and some predefined date relative to the current time
/// zone. It means that this difference will be different as you change time zones.
/// To overcome this discrepancy Ignite always converts .Net date to UTC form
/// before serializing and allows user to decide whether to deserialize them
/// in UTC or local form using <c>ReadTimestamp(..., true/false)</c> methods in
/// <see cref="IBinaryReader"/> and <see cref="IBinaryRawReader"/>.
/// This serializer always read dates in UTC form. It means that if you have
/// local date in any field/property, it will be implicitly converted to UTC
/// form after the first serialization-deserialization cycle.
/// </summary>
public sealed class BinaryReflectiveSerializer : IBinarySerializer
{
/** Cached binding flags. */
private const BindingFlags Flags = BindingFlags.Instance | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
/** Cached type descriptors. */
private readonly IDictionary<Type, Descriptor> _types = new Dictionary<Type, Descriptor>();
/** Raw mode flag. */
private bool _rawMode;
/// <summary>
/// Gets or value indicating whether raw mode serialization should be used.
/// <para />
/// Raw mode does not include field names, improving performance and memory usage.
/// However, queries do not support raw objects.
/// </summary>
public bool RawMode
{
get { return _rawMode; }
set
{
if (_types.Count > 0)
throw new InvalidOperationException(typeof (BinarizableSerializer).Name +
".RawMode cannot be changed after first serialization.");
_rawMode = value;
}
}
/// <summary>
/// Write portalbe object.
/// </summary>
/// <param name="obj">Object.</param>
/// <param name="writer">Writer.</param>
/// <exception cref="BinaryObjectException">Type is not registered in serializer: + type.Name</exception>
public void WriteBinary(object obj, IBinaryWriter writer)
{
var binarizable = obj as IBinarizable;
if (binarizable != null)
binarizable.WriteBinary(writer);
else
GetDescriptor(obj).Write(obj, writer);
}
/// <summary>
/// Read binary object.
/// </summary>
/// <param name="obj">Instantiated empty object.</param>
/// <param name="reader">Reader.</param>
/// <exception cref="BinaryObjectException">Type is not registered in serializer: + type.Name</exception>
public void ReadBinary(object obj, IBinaryReader reader)
{
var binarizable = obj as IBinarizable;
if (binarizable != null)
binarizable.ReadBinary(reader);
else
GetDescriptor(obj).Read(obj, reader);
}
/// <summary>Register type.</summary>
/// <param name="type">Type.</param>
/// <param name="typeId">Type ID.</param>
/// <param name="converter">Name converter.</param>
/// <param name="idMapper">ID mapper.</param>
internal void Register(Type type, int typeId, IBinaryNameMapper converter,
IBinaryIdMapper idMapper)
{
if (type.GetInterface(typeof(IBinarizable).Name) != null)
return;
List<FieldInfo> fields = new List<FieldInfo>();
Type curType = type;
while (curType != null)
{
foreach (FieldInfo field in curType.GetFields(Flags))
{
if (!field.IsNotSerialized)
fields.Add(field);
}
curType = curType.BaseType;
}
IDictionary<int, string> idMap = new Dictionary<int, string>();
foreach (FieldInfo field in fields)
{
string fieldName = BinaryUtils.CleanFieldName(field.Name);
int fieldId = BinaryUtils.FieldId(typeId, fieldName, converter, idMapper);
if (idMap.ContainsKey(fieldId))
{
throw new BinaryObjectException("Conflicting field IDs [type=" +
type.Name + ", field1=" + idMap[fieldId] + ", field2=" + fieldName +
", fieldId=" + fieldId + ']');
}
idMap[fieldId] = fieldName;
}
fields.Sort(Compare);
Descriptor desc = new Descriptor(fields, _rawMode);
_types[type] = desc;
}
/// <summary>
/// Gets the descriptor for an object.
/// </summary>
private Descriptor GetDescriptor(object obj)
{
var type = obj.GetType();
Descriptor desc;
if (!_types.TryGetValue(type, out desc))
throw new BinaryObjectException("Type is not registered in serializer: " + type.Name);
return desc;
}
/// <summary>
/// Compare two FieldInfo instances.
/// </summary>
private static int Compare(FieldInfo info1, FieldInfo info2) {
string name1 = BinaryUtils.CleanFieldName(info1.Name);
string name2 = BinaryUtils.CleanFieldName(info2.Name);
return string.Compare(name1, name2, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Type descriptor.
/// </summary>
private class Descriptor
{
/** Write actions to be performed. */
private readonly List<BinaryReflectiveWriteAction> _wActions;
/** Read actions to be performed. */
private readonly List<BinaryReflectiveReadAction> _rActions;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="fields">Fields.</param>
/// <param name="raw">Raw mode.</param>
public Descriptor(List<FieldInfo> fields, bool raw)
{
_wActions = new List<BinaryReflectiveWriteAction>(fields.Count);
_rActions = new List<BinaryReflectiveReadAction>(fields.Count);
foreach (FieldInfo field in fields)
{
BinaryReflectiveWriteAction writeAction;
BinaryReflectiveReadAction readAction;
BinaryReflectiveActions.GetTypeActions(field, out writeAction, out readAction, raw);
_wActions.Add(writeAction);
_rActions.Add(readAction);
}
}
/// <summary>
/// Write object.
/// </summary>
/// <param name="obj">Object.</param>
/// <param name="writer">Writer.</param>
public void Write(object obj, IBinaryWriter writer)
{
int cnt = _wActions.Count;
for (int i = 0; i < cnt; i++)
_wActions[i](obj, writer);
}
/// <summary>
/// Read object.
/// </summary>
/// <param name="obj">Object.</param>
/// <param name="reader">Reader.</param>
public void Read(object obj, IBinaryReader reader)
{
int cnt = _rActions.Count;
for (int i = 0; i < cnt; i++ )
_rActions[i](obj, reader);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net.Mail;
using System.Runtime.CompilerServices;
using System.Text;
using System.Web;
using Umbraco.Core.Configuration;
using Umbraco.Core;
using Umbraco.Core.Logging;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.property;
using umbraco.cms.businesslogic.web;
using Umbraco.Core.Models.Rdbms;
using umbraco.DataLayer;
using umbraco.interfaces;
using Umbraco.Core.IO;
namespace umbraco.cms.businesslogic.workflow
{
//TODO: Update this to wrap new services/repo!
/// <summary>
/// Notifications are a part of the umbraco workflow.
/// A notification is created every time an action on a node occurs and a umbraco user has subscribed to this specific action on this specific node.
/// Notifications generates an email, which is send to the subscribing users.
/// </summary>
public class Notification
{
/// <summary>
/// Private constructor as this object should not be allowed to be created currently
/// </summary>
private Notification()
{
}
public int NodeId { get; private set; }
public int UserId { get; private set; }
public char ActionId { get; private set; }
/// <summary>
/// Gets the SQL helper.
/// </summary>
/// <value>The SQL helper.</value>
[Obsolete("Obsolete, For querying the database use the new UmbracoDatabase object ApplicationContext.Current.DatabaseContext.Database", false)]
protected static ISqlHelper SqlHelper
{
get { return Application.SqlHelper; }
}
/// <summary>
/// Sends the notifications for the specified user regarding the specified node and action.
/// </summary>
/// <param name="node">The node.</param>
/// <param name="user">The user.</param>
/// <param name="action">The action.</param>
public static void GetNotifications(CMSNode node, User user, IAction action)
{
User[] allUsers = User.getAll();
foreach (User u in allUsers)
{
try
{
if (u.Disabled == false && u.GetNotifications(node.Path).IndexOf(action.Letter.ToString(CultureInfo.InvariantCulture), StringComparison.Ordinal) > -1)
{
LogHelper.Debug<Notification>(string.Format("Notification about {0} sent to {1} ({2})", ui.Text(action.Alias, u), u.Name, u.Email));
SendNotification(user, u, (Document)node, action);
}
}
catch (Exception notifyExp)
{
LogHelper.Error<Notification>("Error in notification", notifyExp);
}
}
}
//TODO: Include update with html mail notification and document contents
private static void SendNotification(User performingUser, User mailingUser, Document documentObject, IAction action)
{
var nService = ApplicationContext.Current.Services.NotificationService;
var pUser = ApplicationContext.Current.Services.UserService.GetUserById(performingUser.Id);
nService.SendNotifications(
pUser, documentObject.ContentEntity, action.Letter.ToString(CultureInfo.InvariantCulture), ui.Text(action.Alias),
new HttpContextWrapper(HttpContext.Current),
(user, strings) => ui.Text("notifications", "mailSubject", strings, mailingUser),
(user, strings) => UmbracoSettings.NotificationDisableHtmlEmail
? ui.Text("notifications", "mailBody", strings, mailingUser)
: ui.Text("notifications", "mailBodyHtml", strings, mailingUser));
}
/// <summary>
/// Returns the notifications for a user
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public static IEnumerable<Notification> GetUserNotifications(User user)
{
var items = new List<Notification>();
var dtos = ApplicationContext.Current.DatabaseContext.Database.Fetch<User2NodeNotifyDto>(
"WHERE userId = @UserId ORDER BY nodeId", new { UserId = user.Id });
foreach (var dto in dtos)
{
items.Add(new Notification
{
NodeId = dto.NodeId,
ActionId = Convert.ToChar(dto.Action),
UserId = dto.UserId
});
}
return items;
}
/// <summary>
/// Returns the notifications for a node
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public static IEnumerable<Notification> GetNodeNotifications(CMSNode node)
{
var items = new List<Notification>();
var dtos = ApplicationContext.Current.DatabaseContext.Database.Fetch<User2NodeNotifyDto>(
"WHERE userId = @UserId ORDER BY nodeId", new { nodeId = node.Id });
foreach (var dto in dtos)
{
items.Add(new Notification
{
NodeId = dto.NodeId,
ActionId = Convert.ToChar(dto.Action),
UserId = dto.UserId
});
}
return items;
}
/// <summary>
/// Deletes notifications by node
/// </summary>
/// <param name="node"></param>
public static void DeleteNotifications(CMSNode node)
{
// delete all settings on the node for this node id
ApplicationContext.Current.DatabaseContext.Database.Delete<User2NodeNotifyDto>("WHERE nodeId = @nodeId",
new {nodeId = node.Id});
}
/// <summary>
/// Delete notifications by user
/// </summary>
/// <param name="user"></param>
public static void DeleteNotifications(User user)
{
// delete all settings on the node for this node id
ApplicationContext.Current.DatabaseContext.Database.Delete<User2NodeNotifyDto>("WHERE userId = @userId",
new { userId = user.Id });
}
/// <summary>
/// Delete notifications by user and node
/// </summary>
/// <param name="user"></param>
/// <param name="node"></param>
public static void DeleteNotifications(User user, CMSNode node)
{
// delete all settings on the node for this user
ApplicationContext.Current.DatabaseContext.Database.Delete<User2NodeNotifyDto>(
"WHERE userId = @userId AND nodeId = @nodeId", new {userId = user.Id, nodeId = node.Id});
}
/// <summary>
/// Creates a new notification
/// </summary>
/// <param name="user">The user.</param>
/// <param name="node">The node.</param>
/// <param name="actionLetter">The action letter.</param>
[MethodImpl(MethodImplOptions.Synchronized)]
public static void MakeNew(User user, CMSNode node, char actionLetter)
{
bool exists = ApplicationContext.Current.DatabaseContext.Database.ExecuteScalar<int>(
"SELECT COUNT(userId) FROM umbracoUser2nodeNotify WHERE userId = @userId AND nodeId = @nodeId AND action = @action",
new { userId = user.Id, nodeId = node.Id, action = actionLetter.ToString()}) > 0;
if (exists == false)
{
ApplicationContext.Current.DatabaseContext.Database.Insert(new User2NodeNotifyDto
{
Action = actionLetter.ToString(),
NodeId = node.Id,
UserId = user.Id
});
}
}
/// <summary>
/// Updates the notifications.
/// </summary>
/// <param name="user">The user.</param>
/// <param name="node">The node.</param>
/// <param name="notifications">The notifications.</param>
[MethodImpl(MethodImplOptions.Synchronized)]
public static void UpdateNotifications(User user, CMSNode node, string notifications)
{
// delete all settings on the node for this user
DeleteNotifications(user, node);
// Loop through the permissions and create them
foreach (char c in notifications)
MakeNew(user, node, c);
}
}
}
| |
// Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
/*
Copyright 2007-2013 The NGenerics Team
(https://github.com/ngenerics/ngenerics/wiki/Team)
This program is licensed under the GNU Lesser General Public License (LGPL). You should
have received a copy of the license along with the source code. If not, an online copy
of the license can be found at http://www.gnu.org/copyleft/lesser.html.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using NGenerics.Patterns.Visitor;
using NGenerics.Util;
using System.Diagnostics.CodeAnalysis;
namespace NGenerics.DataStructures.Trees
{
/// <summary>
/// An implementation of a Binary Tree data structure.
/// </summary>
/// <typeparam name="T">The type of elements in the <see cref="BinaryTree{T}"/>.</typeparam>
//[Serializable]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
public class BinaryTree<T> : ICollection<T>, ITree<T>
{
#region Globals
private BinaryTree<T> _leftSubtree;
private BinaryTree<T> _rightSubtree;
private T _data;
#endregion
#region Construction
/// <param name="data">The data contained in this node.</param>
public BinaryTree(T data) : this(data, null, null) { }
/// <param name="data">The data.</param>
/// <param name="left">The data of the left subtree.</param>
/// <param name="right">The data of the right subtree.</param>
public BinaryTree(T data, T left, T right) : this(data, new BinaryTree<T>(left), new BinaryTree<T>(right)) { }
/// <param name="data">The data contained in this node.</param>
/// <param name="left">The left subtree.</param>
/// <param name="right">The right subtree.</param>
public BinaryTree(T data, BinaryTree<T> left, BinaryTree<T> right)
: this(data, left, right, true)
{
}
/// <param name="data">The data contained in this node.</param>
/// <param name="left">The left subtree.</param>
/// <param name="right">The right subtree.</param>
/// <param name="validateData"><see langword="true"/> to validate <paramref name="data"/>; otherwise <see langword="false"/>.</param>
internal BinaryTree(T data, BinaryTree<T> left, BinaryTree<T> right, bool validateData)
{
#region Validation
//TODO: probably not the most efficient way of doing this but SplayTree needs to use a BinaryTree with null data.
if (validateData)
{
Guard.ArgumentNotNull(data, "data");
}
#endregion
_leftSubtree = left;
if (left != null)
{
left.Parent = this;
}
_rightSubtree = right;
if (right != null)
{
right.Parent = this;
}
_data = data;
}
#endregion
#region ICollection<T> Members
/// <inheritdoc />
public bool IsEmpty => Count == 0;
/// <inheritdoc />
public bool IsFull => (_leftSubtree != null) && (_rightSubtree != null);
/// <inheritdoc />
public bool Contains(T item)
{
foreach (var thisItem in this)
{
if (item.Equals(thisItem))
{
return true;
}
}
return false;
}
/// <inheritdoc />
public void CopyTo(T[] array, int arrayIndex)
{
Guard.ArgumentNotNull(array, "array");
foreach (var item in this)
{
#region Validation
if (arrayIndex >= array.Length)
{
throw new ArgumentException(Constants.NotEnoughSpaceInTheTargetArray, "array");
}
#endregion
array[arrayIndex++] = item;
}
}
/// <inheritdoc />
public int Count
{
get
{
var count = 0;
if (_leftSubtree != null)
{
count++;
}
if (_rightSubtree != null)
{
count++;
}
return count;
}
}
/// <inheritdoc />
public void Add(T item)
{
AddItem(new BinaryTree<T>(item));
}
/// <inheritdoc />
public bool Remove(T item)
{
if (_leftSubtree != null)
{
if (_leftSubtree._data.Equals(item))
{
RemoveLeft();
return true;
}
}
if (_rightSubtree != null)
{
if (_rightSubtree._data.Equals(item))
{
RemoveRight();
return true;
}
}
return false;
}
/// <summary>
/// Removes the specified child.
/// </summary>
/// <param name="child">The child.</param>
/// <returns>A value indicating whether the child was found (and removed) from this tree.</returns>
public bool Remove(BinaryTree<T> child)
{
if (_leftSubtree != null)
{
if (_leftSubtree == child)
{
RemoveLeft();
return true;
}
}
if (_rightSubtree != null)
{
if (_rightSubtree == child)
{
RemoveRight();
return true;
}
}
return false;
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<T> GetEnumerator()
{
var stack = new Stack<BinaryTree<T>>();
stack.Push(this);
while (stack.Count > 0)
{
var tree = stack.Pop();
yield return tree.Data;
if (tree._leftSubtree != null)
{
stack.Push(tree._leftSubtree);
}
if (tree._rightSubtree != null)
{
stack.Push(tree._rightSubtree);
}
}
}
/// <inheritdoc />
public virtual void Clear()
{
if (_leftSubtree != null)
{
_leftSubtree.Parent = null;
_leftSubtree = null;
}
if (_rightSubtree != null)
{
_rightSubtree.Parent = null;
_rightSubtree = null;
}
}
#endregion
#region ITree<T> Members
/// <inheritdoc />
void ITree<T>.Add(ITree<T> child)
{
AddItem((BinaryTree<T>)child);
}
/// <inheritdoc />
ITree<T> ITree<T>.GetChild(int index)
{
return GetChild(index);
}
/// <inheritdoc />
bool ITree<T>.Remove(ITree<T> child)
{
return Remove((BinaryTree<T>)child);
}
/// <inheritdoc />
ITree<T> ITree<T>.FindNode(Predicate<T> condition)
{
return FindNode(condition);
}
/// <inheritdoc />
ITree<T> ITree<T>.Parent => Parent;
#endregion
#region Public Members
/// <summary>
/// Gets the parent of the current node..
/// </summary>
/// <value>The parent of the current node.</value>
public BinaryTree<T> Parent { get; private set; }
/// <summary>
/// Finds the node with the specified condition. If a node is not found matching
/// the specified condition, null is returned.
/// </summary>
/// <param name="condition">The condition to test.</param>
/// <returns>The first node that matches the condition supplied. If a node is not found, null is returned.</returns>
/// <exception cref="ArgumentNullException"><paramref name="condition"/> is a null reference (<c>Nothing</c> in Visual Basic).</exception>
public BinaryTree<T> FindNode(Predicate<T> condition)
{
Guard.ArgumentNotNull(condition, "condition");
if (condition(Data))
{
return this;
}
if (_leftSubtree != null)
{
var ret = _leftSubtree.FindNode(condition);
if (ret != null)
{
return ret;
}
}
if (_rightSubtree != null)
{
var ret = _rightSubtree.FindNode(condition);
if (ret != null)
{
return ret;
}
}
return null;
}
/// <summary>
/// Gets or sets the left subtree.
/// </summary>
/// <value>The left subtree.</value>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual BinaryTree<T> Left
{
get
{
return _leftSubtree;
}
set
{
if (_leftSubtree != null)
{
RemoveLeft();
}
if (value != null)
{
if (value.Parent != null)
{
value.Parent.Remove(value);
}
value.Parent = this;
}
_leftSubtree = value;
}
}
/// <summary>
/// Gets or sets the right subtree.
/// </summary>
/// <value>The right subtree.</value>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual BinaryTree<T> Right
{
get
{
return _rightSubtree;
}
set
{
if (_rightSubtree != null)
{
RemoveRight();
}
if (value != null)
{
if (value.Parent != null)
{
value.Parent.Remove(value);
}
value.Parent = this;
}
_rightSubtree = value;
}
}
/// <inheritdoc />
public virtual T Data
{
get
{
return _data;
}
set
{
#region Validation
Guard.ArgumentNotNull(value, "data");
#endregion
_data = value;
}
}
/// <inheritdoc />
public int Degree => Count;
/// <summary>
/// Gets the child at the specified index.
/// </summary>
/// <param name="index">The index of the child in question.</param>
/// <returns>The child at the specified index.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> does not equal 0 or 1.</exception>
public BinaryTree<T> GetChild(int index)
{
switch (index)
{
case 0:
return _leftSubtree;
case 1:
return _rightSubtree;
default:
throw new ArgumentOutOfRangeException("index");
}
}
/// <inheritdoc />
public virtual int Height
{
get
{
if (Degree == 0)
{
return 0;
}
return 1 + FindMaximumChildHeight();
}
}
/// <summary>
/// Performs a depth first traversal on this tree with the specified visitor.
/// </summary>
/// <param name="orderedVisitor">The ordered visitor.</param>
/// <exception cref="ArgumentNullException"><paramref name="orderedVisitor"/> is a null reference (<c>Nothing</c> in Visual Basic).</exception>
public virtual void DepthFirstTraversal(OrderedVisitor<T> orderedVisitor)
{
Guard.ArgumentNotNull(orderedVisitor, "orderedVisitor");
if (orderedVisitor.HasCompleted)
{
return;
}
// Preorder visit
orderedVisitor.VisitPreOrder(Data);
if (_leftSubtree != null)
{
_leftSubtree.DepthFirstTraversal(orderedVisitor);
}
// In-order visit
orderedVisitor.VisitInOrder(_data);
if (_rightSubtree != null)
{
_rightSubtree.DepthFirstTraversal(orderedVisitor);
}
// PostOrder visit
orderedVisitor.VisitPostOrder(Data);
}
/// <summary>
/// Performs a breadth first traversal on this tree with the specified visitor.
/// </summary>
/// <param name="visitor">The visitor.</param>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is a null reference (<c>Nothing</c> in Visual Basic).</exception>
public virtual void BreadthFirstTraversal(IVisitor<T> visitor)
{
Guard.ArgumentNotNull(visitor, "visitor");
var queue = new Queue<BinaryTree<T>>();
queue.Enqueue(this);
while (queue.Count > 0)
{
if (visitor.HasCompleted)
{
break;
}
var binaryTree = queue.Dequeue();
visitor.Visit(binaryTree.Data);
for (var i = 0; i < binaryTree.Degree; i++)
{
var child = binaryTree.GetChild(i);
if (child != null)
{
queue.Enqueue(child);
}
}
}
}
/// <inheritdoc />
public virtual bool IsLeafNode => Degree == 0;
/// <summary>
/// Removes the left child.
/// </summary>
public virtual void RemoveLeft()
{
if (_leftSubtree != null)
{
_leftSubtree.Parent = null;
_leftSubtree = null;
}
}
/// <summary>
/// Removes the left child.
/// </summary>
public virtual void RemoveRight()
{
if (_rightSubtree != null)
{
_rightSubtree.Parent = null;
_rightSubtree = null;
}
}
/// <summary>
/// Adds an item to the <see cref="ICollection{T}"/>.
/// </summary>
/// <param name="subtree">The subtree.</param>
/// <exception cref="NotSupportedException">The <see cref="ICollection{T}"/> is read-only.</exception>
/// <exception cref="InvalidOperationException">The <see cref="BinaryTree{T}"/> is full.</exception>
/// <exception cref="ArgumentNullException"><paramref name="subtree"/> is null (Nothing in Visual Basic).</exception>
public void Add(BinaryTree<T> subtree)
{
Guard.ArgumentNotNull(subtree, "subtree");
AddItem(subtree);
}
/// <summary>
/// Adds an item to the <see cref="ICollection{T}"/>.
/// </summary>
/// <param name="subtree">The subtree.</param>
/// <remarks>
/// <b>Notes to Inheritors: </b>
/// Derived classes can override this method to change the behavior of the <see cref="Clear"/> method.
/// </remarks>
protected virtual void AddItem(BinaryTree<T> subtree)
{
if (_leftSubtree == null)
{
if (subtree.Parent != null)
{
subtree.Parent.Remove(subtree);
}
_leftSubtree = subtree;
subtree.Parent = this;
}
else if (_rightSubtree == null)
{
if (subtree.Parent != null)
{
subtree.Parent.Remove(subtree);
}
_rightSubtree = subtree;
subtree.Parent = this;
}
else
{
throw new InvalidOperationException("This binary tree is full.");
}
}
#endregion
#region Private Members
/// <summary>
/// Finds the maximum height between the child nodes.
/// </summary>
/// <returns>The maximum height of the tree between all paths from this node and all leaf nodes.</returns>
protected virtual int FindMaximumChildHeight()
{
var leftHeight = 0;
var rightHeight = 0;
if (_leftSubtree != null)
{
leftHeight = _leftSubtree.Height;
}
if (_rightSubtree != null)
{
rightHeight = _rightSubtree.Height;
}
return leftHeight > rightHeight ? leftHeight : rightHeight;
}
#endregion
#region Operator Overloads
/// <summary>
/// Gets the <see cref="BinaryTree{T}"/> at the specified index.
/// </summary>
public BinaryTree<T> this[int index] => GetChild(index);
#endregion
#region ICollection<T> Members
/// <inheritdoc />
public bool IsReadOnly => false;
#endregion
#region IEnumerable Members
/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region Object Members
/// <inheritdoc />
public override string ToString()
{
return _data.ToString();
}
#endregion
}
}
| |
using System;
using System.Globalization;
namespace SharpVectors.Dom.Svg
{
/// <summary>
/// This represents an ordered pair of float precision x- and y-coordinates
/// that defines a point in a two-dimensional plane.
/// </summary>
[Serializable]
public struct SvgPointF : IEquatable<SvgPointF>
{
#region Private Fields
/// <summary>
/// Represents a new instance of the <see cref="SvgPointF"/> structure
/// with member data left uninitialized.
/// </summary>
public static readonly SvgPointF Empty = new SvgPointF();
private double _x;
private double _y;
private bool _notEmpty;
#endregion
#region Constructors and Destructor
/// <summary>
/// Initializes a new instance of the <see cref="SvgPointF"/> structure
/// with the specified coordinates.
/// </summary>
/// <param name="x">The x-coordinate of the point. </param>
/// <param name="y">The y-coordinate of the point. </param>
public SvgPointF(float x, float y)
{
_x = x;
_y = y;
_notEmpty = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="SvgPointF"/> structure
/// with the specified coordinates.
/// </summary>
/// <param name="x">The x-coordinate of the point. </param>
/// <param name="y">The y-coordinate of the point. </param>
public SvgPointF(double x, double y)
{
_x = x;
_y = y;
_notEmpty = true;
}
#endregion
#region Public Properties
/// <summary>
/// Gets a value indicating whether this <see cref="SvgPointF"/> is empty.
/// </summary>
/// <value>
/// This is <see langword="true"/> if both <see cref="SvgPointF.X"/> and
/// <see cref="SvgPointF.Y"/> are 0; otherwise, <see langword="false"/>.
/// </value>
public bool IsEmpty
{
get
{
return !_notEmpty;
}
}
/// <summary>
/// Gets the x-coordinate of this <see cref="SvgPointF"/>.
/// </summary>
/// <value>
/// The x-coordinate of this <see cref="SvgPointF"/>.
/// </value>
public float X
{
get
{
return (float)_x;
}
}
/// <summary>
/// Gets the y-coordinate of this <see cref="SvgPointF"/>.
/// </summary>
/// <value>
/// The y-coordinate of this <see cref="SvgPointF"/>.
/// </value>
public float Y
{
get
{
return (float)_y;
}
}
/// <summary>
/// Gets or sets the x-coordinate of this <see cref="SvgPointF"/>.
/// </summary>
/// <value>
/// The x-coordinate of this <see cref="SvgPointF"/>.
/// </value>
public double ValueX
{
get
{
return _x;
}
set
{
_x = value;
_notEmpty = true;
}
}
/// <summary>
/// Gets or sets the y-coordinate of this <see cref="SvgPointF"/>.
/// </summary>
/// <value>
/// The y-coordinate of this <see cref="SvgPointF"/>.
/// </value>
public double ValueY
{
get
{
return _y;
}
set
{
_y = value;
_notEmpty = true;
}
}
#endregion
#region Public Operators
/// <summary>
/// This translates the <see cref="SvgPointF"/> by the specified
/// <see cref="SvgSizeF"/>.
/// </summary>
/// <param name="sz">
/// The <see cref="SvgSizeF"/> that specifies the numbers to add to the
/// x- and y-coordinates of the <see cref="SvgPointF"/>.
/// </param>
/// <param name="pt">The <see cref="SvgPointF"/> to translate.</param>
/// <returns>The translated <see cref="SvgPointF"/>.</returns>
public static SvgPointF operator +(SvgPointF pt, SvgSizeF sz)
{
return SvgPointF.Add(pt, sz);
}
/// <summary>
/// This translates a <see cref="SvgPointF"/> by the negative of a specified
/// <see cref="SvgSizeF"/>.
/// </summary>
/// <param name="sz">
/// The <see cref="SvgSizeF"/> that specifies the numbers to subtract from
/// the coordinates of pt.
/// </param>
/// <param name="pt">The <see cref="SvgPointF"/> to translate.</param>
/// <returns>The translated <see cref="SvgPointF"/>.</returns>
public static SvgPointF operator -(SvgPointF pt, SvgSizeF sz)
{
return SvgPointF.Subtract(pt, sz);
}
/// <summary>
/// This compares two <see cref="SvgPointF"/> structures. The result
/// specifies whether the values of the <see cref="SvgPointF.X"/> and
/// <see cref="SvgPointF.Y"/> properties of the two <see cref="SvgPointF"/>
/// structures are equal.
/// </summary>
/// <param name="right">A <see cref="SvgPointF"/> to compare. </param>
/// <param name="left">A <see cref="SvgPointF"/> to compare. </param>
/// <returns>
/// This is <see langword="true"/> if the <see cref="SvgPointF.X"/> and
/// <see cref="SvgPointF.Y"/> values of the left and right
/// <see cref="SvgPointF"/> structures are equal; otherwise, <see langword="false"/>.
/// </returns>
public static bool operator ==(SvgPointF left, SvgPointF right)
{
if (left.X.Equals(right.X))
{
return (left.Y.Equals(right.Y));
}
return false;
}
/// <summary>
/// This determines whether the coordinates of the specified points are
/// not equal.
/// </summary>
/// <param name="left">A <see cref="SvgPointF"/> to compare.</param>
/// <param name="right">A <see cref="SvgPointF"/> to compare.</param>
/// <returns>
/// This <see langword="true"/> to indicate the <see cref="SvgPointF.X"/>
/// and <see cref="SvgPointF.Y"/> values of left and right are not equal;
/// otherwise, <see langword="false"/>.
/// </returns>
public static bool operator !=(SvgPointF left, SvgPointF right)
{
return !(left == right);
}
#endregion
#region Public Methods
/// <summary>
/// This computes the distance between this <see cref="SvgPointF"/>
/// and the specified <see cref="SvgPointF"/>.
/// </summary>
/// <param name="point">
/// A <see cref="SvgPointF"/> object specifying the other point from
/// which to determine the distance.
/// </param>
/// <returns>
/// The distance between this point and the specified point.
/// </returns>
public double Distance(SvgPointF point)
{
return Math.Sqrt((point.X - this.X) * (point.X - this.X)
+ (point.Y - this.Y) * (point.Y - this.Y));
}
/// <summary>
/// This determines whether this <see cref="SvgPointF"/> contains the same
/// coordinates as the specified <see cref="System.Object"/>.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to test.
/// </param>
/// <returns>
/// This method returns <see langword="true"/> if the specified object
/// is a <see cref="SvgPointF"/> and has the same coordinates as this
/// <see cref="SvgPointF"/>; otherwise, <see langword="false"/>.
/// </returns>
public override bool Equals(object obj)
{
if (obj is SvgPointF)
{
return Equals((SvgPointF)obj);
}
return false;
}
/// <summary>
/// This determines whether this <see cref="SvgPointF"/> contains the same
/// coordinates as the specified <see cref="SvgPointF"/>.
/// </summary>
/// <param name="other">The <see cref="SvgPointF"/> to test.</param>
/// <returns>
/// This method returns <see langword="true"/> if the specified
/// <see cref="SvgPointF"/> has the same coordinates as this
/// <see cref="SvgPointF"/>; otherwise, <see langword="false"/>.
/// </returns>
public bool Equals(SvgPointF other)
{
if ((other.X == this.X) && (other.Y == this.Y))
{
return other.GetType().Equals(base.GetType());
}
return false;
}
/// <summary>
/// This returns a hash code for this <see cref="SvgPointF"/> structure.
/// </summary>
/// <returns>
/// An integer value that specifies a hash value for this
/// <see cref="SvgPointF"/> structure.
/// </returns>
public override int GetHashCode()
{
return (_x.GetHashCode() ^ _y.GetHashCode());
}
/// <summary>
/// This converts this <see cref="SvgPointF"/> to a human readable string.
/// </summary>
/// <returns>
/// A string that represents this <see cref="SvgPointF"/>.
/// </returns>
public override string ToString()
{
return string.Format(CultureInfo.CurrentCulture,
"{{X={0}, Y={1}}", _x, _y);
}
#endregion
#region Public Static Methods
/// <summary>
/// This translates a given <see cref="SvgPointF"/> by a specified
/// <see cref="SvgSizeF"/>.
/// </summary>
/// <param name="pt">The <see cref="SvgPointF"/> to translate.</param>
/// <param name="sz">
/// The <see cref="SvgSizeF"/> that specifies the numbers to add to the
/// coordinates of pt.
/// </param>
/// <returns>The translated <see cref="SvgPointF"/>.</returns>
public static SvgPointF Add(SvgPointF pt, SvgSizeF sz)
{
return new SvgPointF(pt.X + sz.Width, pt.Y + sz.Height);
}
/// <summary>
/// This translates a <see cref="SvgPointF"/> by the negative of a
/// specified size.
/// </summary>
/// <param name="pt">The <see cref="SvgPointF"/> to translate.</param>
/// <param name="sz">
/// The <see cref="SvgSizeF"/> that specifies the numbers to subtract from
/// the coordinates of pt.
/// </param>
/// <returns>The translated <see cref="SvgPointF"/>.</returns>
public static SvgPointF Subtract(SvgPointF pt, SvgSizeF sz)
{
return new SvgPointF(pt.X - sz.Width, pt.Y - sz.Height);
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.CodeGeneration.IR.DataFlow.ControlTree
{
using System;
using System.Collections.Generic;
public class SpanningTree : GenericDepthFirst
{
//
// State
//
ControlFlowGraphStateForCodeTransformation m_cfg;
List< BasicBlock > m_basicBlocks;
List< Operator > m_operators;
List< VariableExpression > m_variables;
//
// Constructor Methods
//
private SpanningTree( ControlFlowGraphStateForCodeTransformation cfg )
{
m_cfg = cfg;
m_basicBlocks = new List< BasicBlock >();
m_operators = new List< Operator >();
m_variables = new List< VariableExpression >();
Visit( cfg.EntryBasicBlock );
}
public static void Compute( ControlFlowGraphStateForCodeTransformation cfg ,
out BasicBlock[] basicBlocks ,
out Operator[] operators ,
out VariableExpression[] variables )
{
SpanningTree tree = new SpanningTree( cfg );
basicBlocks = tree.m_basicBlocks.ToArray();
operators = tree.m_operators .ToArray();
variables = tree.m_variables .ToArray();
}
//--//
public static BasicBlock[] ComputeAncestors( BasicBlock[] basicBlocks )
{
int bbCount = basicBlocks.Length;
BasicBlock[] ancestors = new BasicBlock[bbCount];
for(int i = 0; i < bbCount; i++)
{
BasicBlock bb = basicBlocks[i];
foreach(BasicBlockEdge edge in bb.Predecessors)
{
if(edge.EdgeClass == BasicBlockEdgeClass.TreeEdge)
{
ancestors[i] = edge.Predecessor;
}
}
}
return ancestors;
}
//--//
protected override void ProcessBefore( BasicBlock bb )
{
bb.SpanningTreeIndex = m_basicBlocks.Count; m_basicBlocks.Add( bb );
foreach(Operator op in bb.Operators)
{
op.SpanningTreeIndex = m_operators.Count; m_operators.Add( op );
foreach(var an in op.FilterAnnotations< InvalidationAnnotation >())
{
AddExpression( an.Target );
}
foreach(var ex in op.Results)
{
AddExpression( ex );
}
foreach(var ex in op.Arguments)
{
AddExpression( ex );
}
}
}
private void AddExpression( Expression ex )
{
if(ex is VariableExpression)
{
AddVariable( (VariableExpression)ex );
}
}
private void AddVariable( VariableExpression var )
{
if(var.SpanningTreeIndex < 0)
{
var.SpanningTreeIndex = m_variables.Count;
m_variables.Add( var );
//
// If this is a fragment, we need to add all the other fragments to the spanning tree.
//
Expression[] fragments = m_cfg.GetFragmentsForExpression( var );
LowLevelVariableExpression lowVar = var as LowLevelVariableExpression;
if(lowVar != null)
{
VariableExpression sourceVar = lowVar.SourceVariable;
if(sourceVar != null)
{
fragments = m_cfg.GetFragmentsForExpression( sourceVar );
CHECKS.ASSERT( fragments != null, "Found an orphan fragment: {0} not part of {1}", lowVar, sourceVar );
}
}
if(fragments != null)
{
foreach(Expression exFragment in fragments)
{
AddVariable( (VariableExpression)exFragment );
}
}
//
// Also add any aliased variable.
//
AddVariable( var.AliasedVariable );
}
}
//--//
protected override void ProcessEdgeBefore( BasicBlockEdge edge )
{
edge.EdgeClass = BasicBlockEdgeClass.TreeEdge;
}
protected override void ProcessEdgeNotTaken( BasicBlockEdge edge )
{
BasicBlock predecessor = edge.Predecessor;
BasicBlock successor = edge.Successor;
if(predecessor.SpanningTreeIndex < successor.SpanningTreeIndex)
{
if(IsAncestor( predecessor, successor ))
{
edge.EdgeClass = BasicBlockEdgeClass.ForwardEdge;
}
else
{
edge.EdgeClass = BasicBlockEdgeClass.CrossEdge;
}
}
else
{
if(IsAncestor( successor, predecessor ))
{
edge.EdgeClass = BasicBlockEdgeClass.BackEdge;
}
else
{
edge.EdgeClass = BasicBlockEdgeClass.CrossEdge;
}
}
}
//--//
public static bool IsAncestor( BasicBlock node ,
BasicBlock child )
{
while(child != null)
{
if(node == child)
{
return true;
}
BasicBlock nodeNext = null;
foreach(BasicBlockEdge edge in child.Predecessors)
{
if(edge.EdgeClass == BasicBlockEdgeClass.TreeEdge)
{
nodeNext = edge.Predecessor;
break;
}
}
CHECKS.ASSERT( nodeNext != null || child.Predecessors.Length == 0, "Child not a member of a spanning tree" );
child = nodeNext;
}
return false;
}
}
}
| |
//
// Copyright 2011, Novell, Inc.
// Copyright 2011, Regan Sarwas
//
//
// 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.
//
//
// imagekit.cs: Bindings for the Image Kit API
//
using System;
using System.Drawing;
using MonoMac.AppKit;
using MonoMac.Foundation;
using MonoMac.ObjCRuntime;
using MonoMac.CoreImage;
//using MonoMac.ImageCaptureCore;
using MonoMac.CoreGraphics;
using MonoMac.CoreAnimation;
namespace MonoMac.ImageKit {
[BaseType (typeof (NSView), Delegates=new string [] { "WeakDelegate" }, Events=new Type [] { typeof (IKCameraDeviceViewDelegate)})]
public interface IKCameraDeviceView {
[Export ("delegate", ArgumentSemantic.Assign), NullAllowed]
NSObject WeakDelegate { get; set; }
[Wrap ("WeakDelegate")]
IKCameraDeviceViewDelegate Delegate { get; set; }
// FIXME need ImageCaptureCore;
// [Export ("cameraDevice", ArgumentSemantic.Assign)]
// ICCameraDevice CameraDevice { get; set; }
[Export ("hasDisplayModeTable")]
bool HasDisplayModeTable { get; set; }
[Export ("hasDisplayModeIcon")]
bool HasDisplayModeIcon { get; set; }
[Export ("downloadAllControlLabel", ArgumentSemantic.Copy)]
string DownloadAllControlLabel { get; set; }
[Export ("downloadSelectedControlLabel", ArgumentSemantic.Copy)]
string DownloadSelectedControlLabel { get; set; }
[Export ("iconSize")]
int IconSize { get; set; }
[Export ("transferMode")]
IKCameraDeviceViewTransferMode TransferMode { get; set; }
[Export ("displaysDownloadsDirectoryControl")]
bool DisplaysDownloadsDirectoryControl { get; set; }
[Export ("downloadsDirectory", ArgumentSemantic.Retain)]
NSUrl DownloadsDirectory { get; set; }
[Export ("displaysPostProcessApplicationControl")]
bool DisplaysPostProcessApplicationControl { get; set; }
[Export ("postProcessApplication", ArgumentSemantic.Retain)]
NSUrl PostProcessApplication { get; set; }
[Export ("canRotateSelectedItemsLeft")]
bool CanRotateSelectedItemsLeft { get; }
[Export ("canRotateSelectedItemsRight")]
bool CanRotateSelectedItemsRight { get; }
[Export ("canDeleteSelectedItems")]
bool CanDeleteSelectedItems { get; }
[Export ("canDownloadSelectedItems")]
bool CanDownloadSelectedItems { get; }
[Export ("selectedIndexes")]
NSIndexSet SelectedIndexes { get; }
[Export ("selectIndexes:byExtendingSelection:")]
void SelectItemsAt (NSIndexSet indexes, bool extendSelection);
[Export ("rotateLeft:")]
void RotateLeft (NSObject sender);
[Export ("rotateRight:")]
void RotateRight (NSObject sender);
[Export ("deleteSelectedItems:")]
void DeleteSelectedItems (NSObject sender);
[Export ("downloadSelectedItems:")]
void DownloadSelectedItems (NSObject sender);
[Export ("downloadAllItems:")]
void DownloadAllItems (NSObject sender);
}
[BaseType (typeof (NSObject))]
[Model]
public interface IKCameraDeviceViewDelegate {
[Export ("cameraDeviceViewSelectionDidChange:"), EventArgs ("IKCameraDeviceView")]
void SelectionDidChange (IKCameraDeviceView cameraDeviceView);
// FIXME need ImageCaptureCore;
// [Export ("cameraDeviceView:didDownloadFile:location:fileData:error:"), EventArgs ("IKCameraDeviceViewICCameraFileNSUrlNSDataNSError")]
// void DidDownloadFile (IKCameraDeviceView cameraDeviceView, ICCameraFile file, NSUrl url, NSData data, NSError error);
[Export ("cameraDeviceView:didEncounterError:"), EventArgs ("IKCameraDeviceViewNSError")]
void DidEncounterError (IKCameraDeviceView cameraDeviceView, NSError error);
}
[BaseType (typeof (NSView), Delegates=new string [] { "WeakDelegate" }, Events=new Type [] { typeof (IKDeviceBrowserViewDelegate)})]
public interface IKDeviceBrowserView {
[Export ("delegate", ArgumentSemantic.Assign), NullAllowed]
NSObject WeakDelegate { get; set; }
[Wrap ("WeakDelegate")]
IKDeviceBrowserViewDelegate Delegate { get; set; }
[Export ("displaysLocalCameras")]
bool DisplaysLocalCameras { get; set; }
[Export ("displaysNetworkCameras")]
bool DisplaysNetworkCameras { get; set; }
[Export ("displaysLocalScanners")]
bool DisplaysLocalScanners { get; set; }
[Export ("displaysNetworkScanners")]
bool DisplaysNetworkScanners { get; set; }
[Export ("mode")]
IKDeviceBrowserViewDisplayMode Mode { get; set; }
// FIXME need ImageCaptureCore;
// [Export ("selectedDevice")]
// ICDevice SelectedDevice { get; }
}
[BaseType (typeof (NSObject))]
[Model]
public interface IKDeviceBrowserViewDelegate {
// FIXME need ImageCaptureCore;
// [Abstract]
// [Export ("deviceBrowserView:selectionDidChange:"), EventArgs ("IKDeviceBrowserViewICDevice")]
// void SelectionDidChange (IKDeviceBrowserView deviceBrowserView, ICDevice device);
[Export ("deviceBrowserView:didEncounterError:"), EventArgs ("IKDeviceBrowserViewNSError")]
void DidEncounterError (IKDeviceBrowserView deviceBrowserView, NSError error);
}
[BaseType (typeof (NSPanel))]
public interface IKFilterBrowserPanel {
[Export ("filterBrowserPanelWithStyleMask:")]
IntPtr Constructor (IKFilterBrowserPanelStyleMask styleMask);
[Export ("filterName")]
string FilterName { get; }
//FIXME - can we do this in a more C#ish way.
[Export ("beginWithOptions:modelessDelegate:didEndSelector:contextInfo:")]
void Begin (NSDictionary options, NSObject modelessDelegate, Selector didEndSelector, IntPtr contextInfo);
[Export ("beginSheetWithOptions:modalForWindow:modalDelegate:didEndSelector:contextInfo:")]
void BeginSheet (NSDictionary options, NSWindow docWindow, NSObject modalDelegate, Selector didEndSelector, IntPtr contextInfo);
[Export ("runModalWithOptions:")]
int RunModal (NSDictionary options);
[Export ("filterBrowserViewWithOptions:")]
IKFilterBrowserView FilterBrowserView (NSDictionary options);
[Export ("finish:")]
void Finish (NSObject sender);
//Check - Do we need Notifications strings?
[Field ("IKFilterBrowserFilterSelectedNotification")]
NSString FilterSelectedNotification { get; }
[Field ("IKFilterBrowserFilterDoubleClickNotification")]
NSString FilterDoubleClickNotification { get; }
[Field ("IKFilterBrowserWillPreviewFilterNotification")]
NSString WillPreviewFilterNotification { get; }
//Dictionary Keys
[Field ("IKFilterBrowserShowCategories")]
NSString ShowCategories { get; }
[Field ("IKFilterBrowserShowPreview")]
NSString ShowPreview { get; }
[Field ("IKFilterBrowserExcludeCategories")]
NSString ExcludeCategories { get; }
[Field ("IKFilterBrowserExcludeFilters")]
NSString ExcludeFilters { get; }
[Field ("IKFilterBrowserDefaultInputImage")]
NSString DefaultInputImage { get; }
}
[BaseType (typeof (NSView))]
public interface IKFilterBrowserView {
[Export ("setPreviewState:")]
void SetPreviewState (bool showPreview);
[Export ("filterName")]
string FilterName { get; }
}
//This protocol is an addition to CIFilter. It is implemented by any filter that provides its own user interface.
[BaseType (typeof (NSObject))]
[Model]
public interface IKFilterCustomUIProvider {
[Abstract]
[Export ("provideViewForUIConfiguration:excludedKeys:")]
IKFilterUIView GetFilterUIView (NSDictionary configurationOptions, NSArray excludedKeys);
//UIConfiguration keys for NSDictionary
[Field ("IKUISizeFlavor")]
NSString SizeFlavor { get; }
[Field ("IKUISizeMini")]
NSString SizeMini { get; }
[Field ("IKUISizeSmall")]
NSString SizeSmall { get; }
[Field ("IKUISizeRegular")]
NSString SizeRegular { get; }
[Field ("IKUImaxSize")]
NSString MaxSize { get; }
[Field ("IKUIFlavorAllowFallback")]
NSString FlavorAllowFallback { get; }
}
[BaseType (typeof (NSView))]
public interface IKFilterUIView {
[Export ("initWithFrame:filter:")]
IntPtr Constructor (RectangleF frame, CIFilter filter);
//This is an extension to CIFilter
[Export ("viewForUIConfiguration:excludedKeys:")]
IKFilterUIView GetFilterUIView ([Target] CIFilter filter, NSDictionary configurationOptions, NSArray excludedKeys);
[Export ("filter")]
CIFilter Filter { get; }
[Export ("objectController")]
NSObjectController ObjectController { get; }
}
[BaseType (typeof (NSObject))]
public interface IKImageBrowserCell {
[Export ("imageBrowserView")]
IKImageBrowserView ImageBrowserView { get; }
[Export ("representedItem")]
NSObject RepresentedItem { get; }
[Export ("indexOfRepresentedItem")]
int IndexOfRepresentedItem { get; }
[Export ("frame")]
RectangleF Frame { get; }
[Export ("imageContainerFrame")]
RectangleF ImageContainerFrame { get; }
[Export ("imageFrame")]
RectangleF ImageFrame { get; }
[Export ("selectionFrame")]
RectangleF SelectionFrame { get; }
[Export ("titleFrame")]
RectangleF TitleFrame { get; }
[Export ("subtitleFrame")]
RectangleF SubtitleFrame { get; }
[Export ("imageAlignment")]
NSImageAlignment ImageAlignment { get; }
[Export ("isSelected")]
bool IsSelected { get; }
[Export ("cellState")]
IKImageBrowserCellState CellState { get; }
[Export ("opacity")]
float Opacity { get; }
[Export ("layerForType:")]
CALayer Layer (string layerType);
// layerType is one of the following
[Field ("IKImageBrowserCellBackgroundLayer")]
NSString BackgroundLayer { get; }
[Field ("IKImageBrowserCellForegroundLayer")]
NSString ForegroundLayer { get; }
[Field ("IKImageBrowserCellSelectionLayer")]
NSString SelectionLayer { get; }
[Field ("IKImageBrowserCellPlaceHolderLayer")]
NSString PlaceHolderLayer { get; }
}
[BaseType (typeof (NSView), Delegates=new string [] { "WeakDelegate" }, Events=new Type [] { typeof (IKImageBrowserDelegate)})]
public interface IKImageBrowserView {
//@category IKImageBrowserView (IKMainMethods)
[Export ("initWithFrame:")]
IntPtr Constructor (RectangleF frame);
//Having a weak and strong datasource seems to work.
[Export ("dataSource", ArgumentSemantic.Assign), NullAllowed]
NSObject WeakDataSource { get; set; }
[Wrap ("WeakDataSource")]
IKImageBrowserDataSource DataSource { get; set; }
[Export ("reloadData")]
void ReloadData ();
[Export ("delegate", ArgumentSemantic.Assign), NullAllowed]
NSObject WeakDelegate { get; set; }
[Wrap ("WeakDelegate")]
IKImageBrowserDelegate Delegate { get; set; }
//@category IKImageBrowserView (IKAppearance)
[Export ("cellsStyleMask")]
IKCellsStyle CellsStyleMask { get; set; }
[Export ("constrainsToOriginalSize")]
bool ConstrainsToOriginalSize { get; set; }
[Export ("backgroundLayer")]
CALayer BackgroundLayer { get; set; }
[Export ("foregroundLayer")]
CALayer ForegroundLayer { get; set; }
[Export ("newCellForRepresentedItem:")]
IKImageBrowserCell NewCell (IKImageBrowserItem representedItem);
[Export ("cellForItemAtIndex:")]
IKImageBrowserCell GetCellAt (int itemIndex);
//@category IKImageBrowserView (IKBrowsing)
[Export ("zoomValue")]
float ZoomValue { get; set; }
[Export ("contentResizingMask")]
NSViewResizingMask ContentResizingMask { get; set; }
[Export ("scrollIndexToVisible:")]
void ScrollIndexToVisible (int index);
[Export ("cellSize")]
SizeF CellSize { get; set; }
[Export ("intercellSpacing")]
SizeF IntercellSpacing { get; set; }
[Export ("indexOfItemAtPoint:")]
int GetIndexOfItem (PointF point);
[Export ("itemFrameAtIndex:")]
RectangleF GetItemFrame (int index);
[Export ("visibleItemIndexes")]
NSIndexSet GetVisibleItemIndexes ();
[Export ("rowIndexesInRect:")]
NSIndexSet GetRowIndexes (RectangleF rect);
[Export ("columnIndexesInRect:")]
NSIndexSet GetColumnIndexes (RectangleF rect);
[Export ("rectOfColumn:")]
RectangleF GetRectOfColumn (int columnIndex);
[Export ("rectOfRow:")]
RectangleF GetRectOfRow (int rowIndex);
[Export ("numberOfRows")]
int RowCount { get; }
[Export ("numberOfColumns")]
int ColumnCount { get; }
[Export ("canControlQuickLookPanel")]
bool CanControlQuickLookPanel { get; set; }
//@category IKImageBrowserView (IKSelectionReorderingAndGrouping)
[Export ("selectionIndexes")]
NSIndexSet SelectionIndexes { get; }
[Export ("setSelectionIndexes:byExtendingSelection:")]
void SelectItemsAt (NSIndexSet indexes, bool extendSelection);
[Export ("allowsMultipleSelection")]
bool AllowsMultipleSelection { get; set; }
[Export ("allowsEmptySelection")]
bool AllowsEmptySelection { get; set; }
[Export ("allowsReordering")]
bool AllowsReordering { get; set; }
[Export ("animates")]
bool Animates { get; set; }
[Export ("expandGroupAtIndex:")]
void ExpandGroup (int index);
[Export ("collapseGroupAtIndex:")]
void CollapseGroup (int index);
[Export ("isGroupExpandedAtIndex:")]
bool IsGroupExpanded (int index);
//@category IKImageBrowserView (IKDragNDrop)
[Export ("draggingDestinationDelegate")]
NSDraggingDestination DraggingDestinationDelegate { get; set; }
[Export ("indexAtLocationOfDroppedItem")]
int GetIndexAtLocationOfDroppedItem ();
[Export ("dropOperation")]
IKImageBrowserDropOperation DropOperation ();
[Export ("allowsDroppingOnItems")]
bool AllowsDroppingOnItems { get; set; }
[Export ("setDropIndex:dropOperation:")]
void SetDropIndex (int index, IKImageBrowserDropOperation operation);
// Keys for the view options, set with base.setValue
[Field ("IKImageBrowserBackgroundColorKey")]
NSString BackgroundColorKey { get; }
[Field ("IKImageBrowserSelectionColorKey")]
NSString SelectionColorKey { get; }
[Field ("IKImageBrowserCellsOutlineColorKey")]
NSString CellsOutlineColorKey { get; }
[Field ("IKImageBrowserCellsTitleAttributesKey")]
NSString CellsTitleAttributesKey { get; }
[Field ("IKImageBrowserCellsHighlightedTitleAttributesKey")]
NSString CellsHighlightedTitleAttributesKey { get; }
[Field ("IKImageBrowserCellsSubtitleAttributesKey")]
NSString CellsSubtitleAttributesKey { get; }
}
[BaseType (typeof (NSObject))]
[Model]
public interface IKImageBrowserDataSource {
[Abstract]
[Export ("numberOfItemsInImageBrowser:")]
int ItemCount (IKImageBrowserView aBrowser);
[Abstract]
[Export ("imageBrowser:itemAtIndex:")]
IKImageBrowserItem GetItem (IKImageBrowserView aBrowser, int index);
[Export ("imageBrowser:removeItemsAtIndexes:")]
void RemoveItems (IKImageBrowserView aBrowser, NSIndexSet indexes);
[Export ("imageBrowser:moveItemsAtIndexes:toIndex:")]
bool MoveItems (IKImageBrowserView aBrowser, NSIndexSet indexes, int destinationIndex);
[Export ("imageBrowser:writeItemsAtIndexes:toPasteboard:")]
int WriteItemsToPasteboard (IKImageBrowserView aBrowser, NSIndexSet itemIndexes, NSPasteboard pasteboard);
[Export ("numberOfGroupsInImageBrowser:")]
int GroupCount (IKImageBrowserView aBrowser);
[Export ("imageBrowser:groupAtIndex:")]
NSDictionary GetGroup (IKImageBrowserView aBrowser, int index);
// Keys for Dictionary returned by GetGroup
[Field ("IKImageBrowserGroupRangeKey")]
NSString GroupRangeKey { get; }
[Field ("IKImageBrowserGroupBackgroundColorKey")]
NSString GroupBackgroundColorKey { get; }
[Field ("IKImageBrowserGroupTitleKey")]
NSString GroupTitleKey { get; }
[Field ("IKImageBrowserGroupStyleKey")]
NSString GroupStyleKey { get; }
[Field ("IKImageBrowserGroupHeaderLayer")]
NSString GroupHeaderLayer { get; }
[Field ("IKImageBrowserGroupFooterLayer")]
NSString GroupFooterLayer { get; }
}
[BaseType (typeof (NSObject))]
[Model]
public interface IKImageBrowserItem {
[Abstract]
[Export ("imageUID")]
string ImageUID { get; }
[Abstract]
[Export ("imageRepresentationType")]
NSString ImageRepresentationType { get; }
//possible strings returned by ImageRepresentationType
[Field ("IKImageBrowserPathRepresentationType")]
NSString PathRepresentationType { get; }
[Field ("IKImageBrowserNSURLRepresentationType")]
NSString NSURLRepresentationType { get; }
[Field ("IKImageBrowserNSImageRepresentationType")]
NSString NSImageRepresentationType { get; }
[Field ("IKImageBrowserCGImageRepresentationType")]
NSString CGImageRepresentationType { get; }
[Field ("IKImageBrowserCGImageSourceRepresentationType")]
NSString CGImageSourceRepresentationType { get; }
[Field ("IKImageBrowserNSDataRepresentationType")]
NSString NSDataRepresentationType { get; }
[Field ("IKImageBrowserNSBitmapImageRepresentationType")]
NSString NSBitmapImageRepresentationType { get; }
[Field ("IKImageBrowserQTMovieRepresentationType")]
NSString QTMovieRepresentationType { get; }
[Field ("IKImageBrowserQTMoviePathRepresentationType")]
NSString QTMoviePathRepresentationType { get; }
[Field ("IKImageBrowserQCCompositionRepresentationType")]
NSString QCCompositionRepresentationType { get; }
[Field ("IKImageBrowserQCCompositionPathRepresentationType")]
NSString QCCompositionPathRepresentationType { get; }
[Field ("IKImageBrowserQuickLookPathRepresentationType")]
NSString QuickLookPathRepresentationType { get; }
[Field ("IKImageBrowserIconRefPathRepresentationType")]
NSString IconRefPathRepresentationType { get; }
[Field ("IKImageBrowserIconRefRepresentationType")]
NSString IconRefRepresentationType { get; }
[Field ("IKImageBrowserPDFPageRepresentationType")]
NSString PDFPageRepresentationType { get; }
[Abstract]
[Export ("imageRepresentation")]
NSObject ImageRepresentation { get; }
[Export ("imageVersion")]
int ImageVersion { get; }
[Export ("imageTitle")]
string ImageTitle { get; }
[Export ("imageSubtitle")]
string ImageSubtitle { get; }
[Export ("isSelectable")]
bool IsSelectable { get; }
}
[BaseType (typeof (NSObject))]
[Model]
public interface IKImageBrowserDelegate {
[Export ("imageBrowserSelectionDidChange:"), EventArgs ("IKImageBrowserView")]
void SelectionDidChange (IKImageBrowserView browser);
[Export ("imageBrowser:cellWasDoubleClickedAtIndex:"), EventArgs ("IKImageBrowserViewIndex")]
void CellWasDoubleClicked (IKImageBrowserView browser, int index);
[Export ("imageBrowser:cellWasRightClickedAtIndex:withEvent:"), EventArgs ("IKImageBrowserViewIndexEvent")]
void CellWasRightClicked (IKImageBrowserView browser, int index, NSEvent nsevent);
[Export ("imageBrowser:backgroundWasRightClickedWithEvent:"), EventArgs ("IKImageBrowserViewEvent")]
void BackgroundWasRightClicked (IKImageBrowserView browser, NSEvent nsevent);
}
[BaseType (typeof (NSPanel))]
public interface IKImageEditPanel {
[Static]
[Export ("sharedImageEditPanel")]
IKImageEditPanel SharedPanel { get; }
[Export ("dataSource", ArgumentSemantic.Assign), NullAllowed]
IKImageEditPanelDataSource DataSource { get; set; }
[Export ("filterArray")]
NSArray filterArray { get; }
[Export ("reloadData")]
void ReloadData ();
}
[BaseType (typeof (NSObject))]
[Model]
public interface IKImageEditPanelDataSource {
[Abstract]
[Export ("image")]
CGImage Image { get; }
[Abstract]
[Export ("setImage:imageProperties:")]
void SetImageAndProperties (CGImage image, NSDictionary metaData);
[Export ("thumbnailWithMaximumSize:")]
CGImage GetThumbnail (SizeF maximumSize);
[Export ("imageProperties")]
NSDictionary ImageProperties { get; }
[Export ("hasAdjustMode")]
bool HasAdjustMode { get; }
[Export ("hasEffectsMode")]
bool HasEffectsMode { get; }
[Export ("hasDetailsMode")]
bool HasDetailsMode { get; }
}
[BaseType (typeof (NSView))]
public interface IKImageView {
//There is no protocol for this delegate. used to respond to messages in the responder chain
[Export ("delegate", ArgumentSemantic.Assign), NullAllowed]
NSObject Delegate { get; set; }
[Export ("zoomFactor")]
float ZoomFactor { get; set; }
[Export ("rotationAngle")]
float RotationAngle { get; set; }
[Export ("currentToolMode")]
string CurrentToolMode { get; set; }
[Export ("autoresizes")]
bool Autoresizes { get; set; }
[Export ("hasHorizontalScroller")]
bool HasHorizontalScroller { get; set; }
[Export ("hasVerticalScroller")]
bool HasVerticalScroller { get; set; }
[Export ("autohidesScrollers")]
bool AutohidesScrollers { get; set; }
[Export ("supportsDragAndDrop")]
bool SupportsDragAndDrop { get; set; }
[Export ("editable")]
bool Editable { get; set; }
[Export ("doubleClickOpensImageEditPanel")]
bool DoubleClickOpensImageEditPanel { get; set; }
[Export ("imageCorrection", ArgumentSemantic.Assign)]
CIFilter ImageCorrection { get; set; }
[Export ("backgroundColor", ArgumentSemantic.Assign)]
NSColor BackgroundColor { get; set; }
[Export ("setImage:imageProperties:")]
void SetImageimageProperties (CGImage image, NSDictionary metaData);
[Export ("setImageWithURL:")]
void SetImageWithURL (NSUrl url);
[Export ("image")]
CGImage Image { get; }
[Export ("imageSize")]
SizeF ImageSize { get; }
[Export ("imageProperties")]
NSDictionary ImageProperties { get; }
[Export ("setRotationAngle:centerPoint:")]
void SetRotation (float rotationAngle, PointF centerPoint);
[Export ("rotateImageLeft:")]
void RotateImageLeft (NSObject sender);
[Export ("rotateImageRight:")]
void RotateImageRight (NSObject sender);
[Export ("setImageZoomFactor:centerPoint:")]
void SetImageZoomFactor (float zoomFactor, PointF centerPoint);
[Export ("zoomImageToRect:")]
void ZoomImageToRect (RectangleF rect);
[Export ("zoomImageToFit:")]
void ZoomImageToFit (NSObject sender);
[Export ("zoomImageToActualSize:")]
void ZoomImageToActualSize (NSObject sender);
[Export ("zoomIn:")]
void ZoomIn (NSObject sender);
[Export ("zoomOut:")]
void ZoomOut (NSObject sender);
[Export ("flipImageHorizontal:")]
void FlipImageHorizontal (NSObject sender);
[Export ("flipImageVertical:")]
void FlipImageVertical (NSObject sender);
[Export ("crop:")]
void Crop (NSObject sender);
[Export ("setOverlay:forType:")]
void SetOverlay (CALayer layer, string layerType);
[Export ("overlayForType:")]
CALayer GetOverlay (string layerType);
[Export ("scrollToPoint:")]
void ScrollTo (PointF point);
[Export ("scrollToRect:")]
void ScrollTo (RectangleF rect);
[Export ("convertViewPointToImagePoint:")]
PointF ConvertViewPointToImagePoint (PointF viewPoint);
[Export ("convertViewRectToImageRect:")]
RectangleF ConvertViewRectToImageRect (RectangleF viewRect);
[Export ("convertImagePointToViewPoint:")]
PointF ConvertImagePointToViewPoint (PointF imagePoint);
[Export ("convertImageRectToViewRect:")]
RectangleF ConvertImageRectToViewRect (RectangleF imageRect);
}
[BaseType (typeof (NSPanel))]
public interface IKPictureTaker {
[Static]
[Export ("pictureTaker")]
IKPictureTaker SharedPictureTaker { get; }
[Export ("runModal")]
int RunModal ();
//FIXME - Yuck. What can I do to fix these three methods?
[Export ("beginPictureTakerWithDelegate:didEndSelector:contextInfo:")]
void BeginPictureTaker (NSObject aDelegate, Selector didEndSelector, IntPtr contextInfo);
[Export ("beginPictureTakerSheetForWindow:withDelegate:didEndSelector:contextInfo:")]
void BeginPictureTakerSheet (NSWindow aWindow, NSObject aDelegate, Selector didEndSelector, IntPtr contextInfo);
[Export ("popUpRecentsMenuForView:withDelegate:didEndSelector:contextInfo:")]
void PopUpRecentsMenu (NSView aView, NSObject aDelegate, Selector didEndSelector, IntPtr contextInfo);
[Export ("inputImage")]
NSImage InputImage { get; set; }
[Export ("outputImage")]
NSImage GetOutputImage ();
[Export ("mirroring")]
bool Mirroring { get; set; }
//Use with NSKeyValueCoding to customize the pictureTaker panel
[Field ("IKPictureTakerAllowsVideoCaptureKey")]
NSString AllowsVideoCaptureKey { get; }
[Field ("IKPictureTakerAllowsFileChoosingKey")]
NSString AllowsFileChoosingKey { get; }
[Field ("IKPictureTakerShowRecentPictureKey")]
NSString ShowRecentPictureKey { get; }
[Field ("IKPictureTakerUpdateRecentPictureKey")]
NSString UpdateRecentPictureKey { get; }
[Field ("IKPictureTakerAllowsEditingKey")]
NSString AllowsEditingKey { get; }
[Field ("IKPictureTakerShowEffectsKey")]
NSString ShowEffectsKey { get; }
[Field ("IKPictureTakerInformationalTextKey")]
NSString InformationalTextKey { get; }
[Field ("IKPictureTakerImageTransformsKey")]
NSString ImageTransformsKey { get; }
[Field ("IKPictureTakerOutputImageMaxSizeKey")]
NSString OutputImageMaxSizeKey { get; }
[Field ("IKPictureTakerCropAreaSizeKey")]
NSString CropAreaSizeKey { get; }
[Field ("IKPictureTakerShowAddressBookPictureKey")]
NSString ShowAddressBookPictureKey { get; }
[Field ("IKPictureTakerShowEmptyPictureKey")]
NSString ShowEmptyPictureKey { get; }
[Field ("IKPictureTakerRemainOpenAfterValidateKey")]
NSString RemainOpenAfterValidateKey { get; }
}
[BaseType (typeof (NSObject), Delegates=new string [] { "WeakDelegate" }, Events=new Type [] { typeof (IKSaveOptionsDelegate)})]
public interface IKSaveOptions {
[Export ("imageProperties")]
NSDictionary ImageProperties { get; }
[Export ("imageUTType")]
string ImageUTType { get; }
[Export ("userSelection")]
NSDictionary UserSelection { get; }
[Export ("delegate", ArgumentSemantic.Assign), NullAllowed]
NSObject WeakDelegate { get; set; }
[Wrap ("WeakDelegate")]
IKSaveOptionsDelegate Delegate { get; set; }
[Export ("initWithImageProperties:imageUTType:")]
IntPtr Constructor (NSDictionary imageProperties, string imageUTType);
[Export ("addSaveOptionsAccessoryViewToSavePanel:")]
void AddSaveOptionsToPanel (NSSavePanel savePanel);
[Export ("addSaveOptionsToView:")]
void AddSaveOptionsToView (NSView view);
}
[BaseType (typeof (NSObject))]
[Model]
public interface IKSaveOptionsDelegate {
[Export ("saveOptions:shouldShowUTType:"), DelegateName ("SaveOptionsShouldShowUTType"), DefaultValue (false)]
bool ShouldShowType (IKSaveOptions saveOptions, string imageUTType);
}
[BaseType (typeof (NSView), Delegates=new string [] { "WeakDelegate" }, Events=new Type [] { typeof (IKScannerDeviceViewDelegate)})]
public interface IKScannerDeviceView {
[Export ("delegate", ArgumentSemantic.Assign), NullAllowed]
NSObject WeakDelegate { get; set; }
[Wrap ("WeakDelegate")]
IKScannerDeviceViewDelegate Delegate { get; set; }
// FIXME need ImageCaptureCore;
// [Export ("scannerDevice", ArgumentSemantic.Assign)]
// ICScannerDevice ScannerDevice { get; set; }
[Export ("mode")]
IKScannerDeviceViewDisplayMode DisplayMode { get; set; }
[Export ("hasDisplayModeSimple")]
bool HasDisplayModeSimple { get; set; }
[Export ("hasDisplayModeAdvanced")]
bool HasDisplayModeAdvanced { get; set; }
[Export ("transferMode")]
IKScannerDeviceViewTransferMode TransferMode { get; set; }
[Export ("scanControlLabel", ArgumentSemantic.Copy)]
string ScanControlLabel { get; set; }
[Export ("overviewControlLabel", ArgumentSemantic.Copy)]
string OverviewControlLabel { get; set; }
[Export ("displaysDownloadsDirectoryControl")]
bool DisplaysDownloadsDirectoryControl { get; set; }
[Export ("downloadsDirectory", ArgumentSemantic.Retain)]
NSUrl DownloadsDirectory { get; set; }
[Export ("documentName", ArgumentSemantic.Copy)]
string DocumentName { get; set; }
[Export ("displaysPostProcessApplicationControl")]
bool DisplaysPostProcessApplicationControl { get; set; }
[Export ("postProcessApplication", ArgumentSemantic.Retain)]
NSUrl PostProcessApplication { get; set; }
}
[BaseType (typeof (NSObject))]
[Model]
public interface IKScannerDeviceViewDelegate {
[Export ("scannerDeviceView:didScanToURL:fileData:error:"), EventArgs ("IKScannerDeviceViewScan")]
void DidScan (IKScannerDeviceView scannerDeviceView, NSUrl url, NSData data, NSError error);
[Export ("scannerDeviceView:didEncounterError:"), EventArgs ("IKScannerDeviceViewError")]
void DidEncounterError (IKScannerDeviceView scannerDeviceView, NSError error);
}
[BaseType (typeof (NSObject))]
public interface IKSlideshow {
[Static]
[Export ("sharedSlideshow")]
IKSlideshow SharedSlideshow { get; }
[Export ("autoPlayDelay")]
double autoPlayDelay { get; set; }
[Export ("runSlideshowWithDataSource:inMode:options:")]
void RunSlideshow (IKSlideshowDataSource dataSource, string slideshowMode, NSDictionary slideshowOptions);
[Export ("stopSlideshow:")]
void StopSlideshow (NSObject sender);
[Export ("reloadData")]
void ReloadData ();
[Export ("reloadSlideshowItemAtIndex:")]
void ReloadSlideshowItem (int index);
[Export ("indexOfCurrentSlideshowItem")]
int IndexOfCurrentSlideshowItem { get; }
[Static]
[Export ("canExportToApplication:")]
bool CanExportToApplication (string applicationBundleIdentifier);
[Static]
[Export ("exportSlideshowItem:toApplication:")]
void ExportSlideshowItemtoApplication (NSObject item, string applicationBundleIdentifier);
[Export ("IKSlideshowModeImages")]
NSString ModeImages { get; }
[Export ("IKSlideshowModePDF")]
NSString ModePDF { get; }
[Export ("IKSlideshowModeOther")]
NSString ModeOther { get; }
[Export ("IKSlideshowWrapAround")]
NSString WrapAround { get; }
[Export ("IKSlideshowStartPaused")]
NSString StartPaused { get; }
[Export ("IKSlideshowStartIndex")]
NSString StartIndex { get; }
[Export ("IKSlideshowScreen")]
NSString Screen { get; }
[Export ("IKSlideshowAudioFile")]
NSString AudioFile { get; }
[Export ("IKSlideshowPDFDisplayBox")]
NSString PDFDisplayBox { get; }
[Export ("IKSlideshowPDFDisplayMode")]
NSString PDFDisplayMode { get; }
[Export ("IKSlideshowPDFDisplaysAsBook")]
NSString PDFDisplaysAsBook { get; }
[Export ("IK_iPhotoBundleIdentifier")]
NSString IPhotoBundleIdentifier { get; }
[Export ("IK_ApertureBundleIdentifier")]
NSString ApertureBundleIdentifier { get; }
[Export ("IK_MailBundleIdentifier")]
NSString MailBundleIdentifier { get; }
}
[BaseType (typeof (NSObject))]
[Model]
public interface IKSlideshowDataSource {
[Abstract]
[Export ("numberOfSlideshowItems")]
int ItemCount { get; }
[Abstract]
[Export ("slideshowItemAtIndex:")]
NSObject GetItemAt (int index);
[Export ("nameOfSlideshowItemAtIndex:")]
string GetNameOfItemAt (int index);
[Export ("canExportSlideshowItemAtIndex:toApplication:")]
bool CanExportItemToApplication (int index, string applicationBundleIdentifier);
[Export ("slideshowWillStart")]
void WillStart ();
[Export ("slideshowDidStop")]
void DidStop ();
[Export ("slideshowDidChangeCurrentIndex:")]
void DidChange (int newIndex);
}
}
| |
/*
* Copyright 2013 ThirdMotion, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @class strange.extensions.dispatcher.eventdispatcher.impl.EventDispatcher
*
* A Dispatcher that uses IEvent to send messages.
*
* Whenever the Dispatcher executes a `Dispatch()`, observers will be
* notified of any event (Key) for which they have registered.
*
* EventDispatcher dispatches TmEvent : IEvent.
*
* The EventDispatcher is the only Dispatcher currently released with Strange
* (though by separating EventDispatcher from Dispatcher I'm obviously
* signalling that I don't think it's the only possible one).
*
* EventDispatcher is both an ITriggerProvider and an ITriggerable.
*
* @see strange.extensions.dispatcher.eventdispatcher.api.IEvent
* @see strange.extensions.dispatcher.api.ITriggerProvider
* @see strange.extensions.dispatcher.api.ITriggerable
*/
using System;
using System.Collections.Generic;
using strange.framework.api;
using strange.framework.impl;
using strange.extensions.dispatcher.api;
using strange.extensions.dispatcher.eventdispatcher.api;
using strange.extensions.pool.api;
using strange.extensions.pool.impl;
namespace strange.extensions.dispatcher.eventdispatcher.impl
{
public class EventDispatcher : Binder, IEventDispatcher, ITriggerProvider, ITriggerable
{
/// The list of clients that will be triggered as a consequence of an Event firing.
protected HashSet<ITriggerable> triggerClients;
protected HashSet<ITriggerable> triggerClientRemovals;
protected bool isTriggeringClients;
/// The eventPool is shared across all EventDispatchers for efficiency
public static IPool<TmEvent> eventPool;
public EventDispatcher ()
{
if (eventPool == null)
{
eventPool = new Pool<TmEvent> ();
eventPool.instanceProvider = new EventInstanceProvider ();
}
}
override public IBinding GetRawBinding()
{
return new EventBinding (resolver);
}
new public IEventBinding Bind(object key)
{
return base.Bind (key) as IEventBinding;
}
public void Dispatch (object eventType)
{
Dispatch (eventType, null);
}
public void Dispatch (object eventType, object data)
{
//Scrub the data to make eventType and data conform if possible
IEvent evt = conformDataToEvent (eventType, data);
if (evt is IPoolable)
{
(evt as IPoolable).Retain ();
}
bool continueDispatch = true;
if (triggerClients != null)
{
isTriggeringClients = true;
foreach (ITriggerable trigger in triggerClients)
{
if (!trigger.Trigger(eventType, evt))
{
continueDispatch = false;
break;
}
}
if (triggerClientRemovals != null)
{
flushRemovals();
}
isTriggeringClients = false;
}
if (!continueDispatch)
{
internalReleaseEvent (evt);
return;
}
IEventBinding binding = GetBinding (eventType) as IEventBinding;
if (binding == null)
{
internalReleaseEvent (evt);
return;
}
object[] callbacks = (binding.value as object[]).Clone() as object[];
if (callbacks == null)
{
internalReleaseEvent (evt);
return;
}
for(int a = 0; a < callbacks.Length; a++)
{
object callback = callbacks[a];
if(callback == null)
continue;
callbacks[a] = null;
object[] currentCallbacks = binding.value as object[];
if(Array.IndexOf(currentCallbacks, callback) == -1)
continue;
if (callback is EventCallback)
{
invokeEventCallback (evt, callback as EventCallback);
}
else if (callback is EmptyCallback)
{
(callback as EmptyCallback)();
}
}
internalReleaseEvent (evt);
}
virtual protected IEvent conformDataToEvent(object eventType, object data)
{
IEvent retv = null;
if (eventType == null)
{
throw new EventDispatcherException("Attempt to Dispatch to null.\ndata: " + data, EventDispatcherExceptionType.EVENT_KEY_NULL);
}
else if (eventType is IEvent)
{
//Client provided a full-formed event
retv = (IEvent)eventType;
}
else if (data == null)
{
//Client provided just an event ID. Create an event for injection
retv = createEvent (eventType, null);
}
else if (data is IEvent)
{
//Client provided both an evertType and a full-formed IEvent
retv = (IEvent)data;
}
else
{
//Client provided an eventType and some data which is not a IEvent.
retv = createEvent (eventType, data);
}
return retv;
}
virtual protected IEvent createEvent(object eventType, object data)
{
IEvent retv = eventPool.GetInstance();
retv.type = eventType;
retv.target = this;
retv.data = data;
return retv;
}
virtual protected void invokeEventCallback(object data, EventCallback callback)
{
try
{
callback (data as IEvent);
}
catch(InvalidCastException)
{
object tgt = callback.Target;
string methodName = (callback as Delegate).Method.Name;
string message = "An EventCallback is attempting an illegal cast. One possible reason is not typing the payload to IEvent in your callback. Another is illegal casting of the data.\nTarget class: " + tgt + " method: " + methodName;
throw new EventDispatcherException (message, EventDispatcherExceptionType.TARGET_INVOCATION);
}
}
public void AddListener(object evt, EventCallback callback)
{
IBinding binding = GetBinding (evt);
if (binding == null)
{
Bind (evt).To (callback);
}
else
{
binding.To (callback);
}
}
public void AddListener(object evt, EmptyCallback callback)
{
IBinding binding = GetBinding (evt);
if (binding == null)
{
Bind (evt).To (callback);
}
else
{
binding.To (callback);
}
}
public void RemoveListener(object evt, EventCallback callback)
{
IBinding binding = GetBinding (evt);
RemoveValue (binding, callback);
}
public void RemoveListener(object evt, EmptyCallback callback)
{
IBinding binding = GetBinding (evt);
RemoveValue (binding, callback);
}
public bool HasListener(object evt, EventCallback callback)
{
IEventBinding binding = GetBinding (evt) as IEventBinding;
if (binding == null)
{
return false;
}
return binding.TypeForCallback (callback) != EventCallbackType.NOT_FOUND;
}
public bool HasListener(object evt, EmptyCallback callback)
{
IEventBinding binding = GetBinding (evt) as IEventBinding;
if (binding == null)
{
return false;
}
return binding.TypeForCallback (callback) != EventCallbackType.NOT_FOUND;
}
public void UpdateListener(bool toAdd, object evt, EventCallback callback)
{
if (toAdd)
{
AddListener (evt, callback);
}
else
{
RemoveListener (evt, callback);
}
}
public void UpdateListener(bool toAdd, object evt, EmptyCallback callback)
{
if (toAdd)
{
AddListener (evt, callback);
}
else
{
RemoveListener (evt, callback);
}
}
public void AddTriggerable(ITriggerable target)
{
if (triggerClients == null)
{
triggerClients = new HashSet<ITriggerable>();
}
triggerClients.Add(target);
}
public void RemoveTriggerable(ITriggerable target)
{
if (triggerClients.Contains(target))
{
if (triggerClientRemovals == null)
{
triggerClientRemovals = new HashSet<ITriggerable>();
}
triggerClientRemovals.Add (target);
if (!isTriggeringClients)
{
flushRemovals();
}
}
}
public int Triggerables
{
get
{
if (triggerClients == null)
return 0;
return triggerClients.Count;
}
}
protected void flushRemovals()
{
if (triggerClientRemovals == null)
{
return;
}
foreach(ITriggerable target in triggerClientRemovals)
{
if (triggerClients.Contains(target))
{
triggerClients.Remove(target);
}
}
triggerClientRemovals = null;
}
public bool Trigger<T>(object data)
{
return Trigger (typeof(T), data);
}
public bool Trigger(object key, object data)
{
bool allow = ((data is IEvent && System.Object.ReferenceEquals((data as IEvent).target, this) == false) ||
(key is IEvent && System.Object.ReferenceEquals((data as IEvent).target, this) == false));
if (allow)
Dispatch(key, data);
return true;
}
protected void internalReleaseEvent(IEvent evt)
{
if (evt is IPoolable)
{
(evt as IPoolable).Release ();
}
}
public void ReleaseEvent(IEvent evt)
{
if ((evt as IPoolable).retain == false)
{
cleanEvent (evt);
eventPool.ReturnInstance (evt);
}
}
protected void cleanEvent(IEvent evt)
{
evt.target = null;
evt.data = null;
evt.type = null;
}
}
class EventInstanceProvider : IInstanceProvider
{
public T GetInstance<T>()
{
object instance = new TmEvent ();
T retv = (T) instance;
return retv;
}
public object GetInstance(Type key)
{
return new TmEvent ();
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Adxstudio.Xrm.Services
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Adxstudio.Xrm.Configuration;
using Adxstudio.Xrm.IdentityModel.ActiveDirectory;
using Adxstudio.Xrm.Performance;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
/// <summary>
/// CrmTokenManager class
/// </summary>
public class CrmTokenManager : ICrmTokenManager
{
/// <summary>
/// A record of <see cref="AuthenticationResult"/> and <see cref="Exception"/>.
/// </summary>
private struct AcquireTokenResult
{
/// <summary>
/// The success result.
/// </summary>
public AuthenticationResult Token;
/// <summary>
/// The error result.
/// </summary>
public Exception Error;
}
/// <summary>
/// Internal cache.
/// </summary>
private AuthenticationResult tokenCache;
/// <summary>
/// The authentication settings.
/// </summary>
public IAuthenticationSettings AuthenticationSettings { get; }
/// <summary>
/// The certificate settings.
/// </summary>
public ICertificateSettings CertificateSettings { get; }
/// <summary>
/// The resource.
/// </summary>
public string Resource { get; }
/// <summary>
/// Initializes a new instance of the <see cref="CrmTokenManager" /> class.
/// </summary>
/// <param name="authenticationSettings">The authentication settings.</param>
/// <param name="certificateSettings">The certificat settings.</param>
/// <param name="resource">The resource.</param>
public CrmTokenManager(IAuthenticationSettings authenticationSettings, ICertificateSettings certificateSettings, string resource)
{
this.AuthenticationSettings = authenticationSettings;
this.CertificateSettings = certificateSettings;
this.Resource = resource;
}
/// <summary>
/// Gets or refreshes token
/// </summary>
/// <param name="authorizationCode">Access code for user assertion.</param>
/// <param name="test">An opportunity to check the validity of the token.</param>
/// <returns>Type: Returns_String Access token</returns>
public async Task<string> GetTokenAsync(string authorizationCode = null, Func<AuthenticationResult, Exception> test = null)
{
if (this.Resource == null)
{
return null;
}
var token = await this.GetAuthenticationResultAsync(authorizationCode, test);
return token != null ? token.AccessToken : null;
}
/// <summary>
/// Gets or refreshes token
/// </summary>
/// <param name="authorizationCode">Access code for user assertion.</param>
/// <param name="test">An opportunity to check the validity of the token.</param>
/// <returns>Type: Returns_String Access token</returns>
public string GetToken(string authorizationCode = null, Func<AuthenticationResult, Exception> test = null)
{
if (this.Resource == null)
{
return null;
}
var token = this.GetAuthenticationResult(authorizationCode, test);
return token != null ? token.AccessToken : null;
}
/// <summary>
/// Resets the manager.
/// </summary>
public void Reset()
{
this.tokenCache = null;
}
/// <summary>
/// Converts to an AcquireTokenResult.
/// </summary>
/// <param name="token">The authentication token.</param>
/// <param name="test">An opportunity to check the validity of the token.</param>
/// <param name="index">The current certificate index.</param>
/// <param name="errors">The current errors.</param>
/// <returns>The AcquireTokenResult.</returns>
private static AcquireTokenResult GetAcquireTokenResult(AuthenticationResult token, Func<AuthenticationResult, Exception> test, int index, ICollection<Exception> errors)
{
if (token == null || string.IsNullOrWhiteSpace(token.AccessToken))
{
throw new PortalAdalServiceException("Token is empty.");
}
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Get token succeeded: index: {0}", index));
if (test != null)
{
var testError = test(token);
if (testError != null)
{
ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("Test token failed: index: {0}: {1}", index, testError));
errors.Add(testError);
}
}
// return the valid token and clear the error
return new AcquireTokenResult { Token = token, Error = null };
}
/// <summary>
/// Process errors.
/// </summary>
/// <param name="e">The current error.</param>
/// <param name="index">The current certificate index.</param>
/// <param name="errors">The current errors.</param>
/// <param name="result">The result when returning early.</param>
/// <returns>'true' to return the result early.</returns>
private static bool TryHandleError(Exception e, int index, ICollection<Exception> errors, out AcquireTokenResult result)
{
// record the error of the failed certificate
ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("Get token failed: index: {0}: {1}", index, e));
var ase = e as AdalServiceException;
if (ase != null)
{
if (ase.ErrorCode == "AADSTS50001")
{
// return fatal error immediately
var aseError = new PortalAdalServiceException("CRM is disabled.", ase);
result = new AcquireTokenResult { Token = null, Error = aseError };
return true;
}
errors.Add(new PortalAdalServiceException("Error Connecting to CRM.", ase));
}
else
{
errors.Add(e);
}
result = default(AcquireTokenResult);
return false;
}
/// <summary>
/// Check if the current token is invalid.
/// </summary>
/// <returns>'true' if the token is invalid.</returns>
private bool TokenIsInvalid()
{
return this.tokenCache == null || this.tokenCache.ExpiresOn.Subtract(this.AuthenticationSettings.TokenRefreshWindow) <= DateTimeOffset.UtcNow;
}
/// <summary>
/// Gets or Refreshes the token
/// </summary>
/// <param name="authorizationCode">The access code for user assertion.</param>
/// <param name="test">An opportunity to check the validity of the token.</param>
/// <returns>Type: Return_AuthenticationResult</returns>
private async Task<AuthenticationResult> GetAuthenticationResultAsync(string authorizationCode, Func<AuthenticationResult, Exception> test)
{
if (this.TokenIsInvalid())
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Get new token required due to: {0}", this.tokenCache == null ? "null token" : "expiring token"));
using (PerformanceProfiler.Instance.StartMarker(PerformanceMarkerName.Services, PerformanceMarkerArea.Crm, PerformanceMarkerTagName.GetToken))
{
// filter out empty thumbprints for the certificate fallback logic to work correctly
var certificates = this.CertificateSettings.FindCertificates().ToList();
if (!certificates.Any())
{
throw new CertificateNotFoundException();
}
var result = await this.GetAuthenticationResultAsync(certificates, authorizationCode, test);
this.ApplyAuthenticationResult(result);
}
}
return this.tokenCache;
}
/// <summary>
/// Retrieve a token.
/// </summary>
/// <param name="certificates">The certificates.</param>
/// <param name="authorizationCode">Optional user's access code for user assertion.</param>
/// <param name="test">An opportunity to check the validity of the token.</param>
/// <returns>The token.</returns>
private async Task<AcquireTokenResult> GetAuthenticationResultAsync(IEnumerable<X509Certificate2> certificates, string authorizationCode, Func<AuthenticationResult, Exception> test)
{
var index = 0;
var errors = new List<Exception>();
foreach (var certificate in certificates)
{
try
{
var token = string.IsNullOrEmpty(authorizationCode)
? await certificate.GetTokenAsync(this.AuthenticationSettings, this.Resource)
: await certificate.GetTokenOnBehalfOfAsync(this.AuthenticationSettings, this.Resource, authorizationCode);
return GetAcquireTokenResult(token, test, index, errors);
}
catch (Exception e)
{
AcquireTokenResult result;
if (TryHandleError(e, index, errors, out result))
{
return result;
}
}
++index;
}
// all certificates are invalid
var error = new AggregateException(errors);
return new AcquireTokenResult { Token = null, Error = error };
}
/// <summary>
/// Gets or Refreshes the token
/// </summary>
/// <param name="authorizationCode">The access code for user assertion.</param>
/// <param name="test">An opportunity to check the validity of the token.</param>
/// <returns>Type: Return_AuthenticationResult</returns>
private AuthenticationResult GetAuthenticationResult(string authorizationCode, Func<AuthenticationResult, Exception> test)
{
if (this.TokenIsInvalid())
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Get new token required due to: {0}", this.tokenCache == null ? "null token" : "expiring token"));
using (PerformanceProfiler.Instance.StartMarker(PerformanceMarkerName.Services, PerformanceMarkerArea.Crm, PerformanceMarkerTagName.GetToken))
{
// filter out empty thumbprints for the certificate fallback logic to work correctly
var certificates = this.CertificateSettings.FindCertificates().ToList();
if (!certificates.Any())
{
throw new CertificateNotFoundException();
}
var result = this.GetAuthenticationResult(certificates, authorizationCode, test);
this.ApplyAuthenticationResult(result);
}
}
return this.tokenCache;
}
/// <summary>
/// Retrieve a token.
/// </summary>
/// <param name="certificates">The certificates.</param>
/// <param name="authorizationCode">Optional user's access code for user assertion.</param>
/// <param name="test">An opportunity to check the validity of the token.</param>
/// <returns>The token.</returns>
private AcquireTokenResult GetAuthenticationResult(IEnumerable<X509Certificate2> certificates, string authorizationCode, Func<AuthenticationResult, Exception> test)
{
var index = 0;
var errors = new List<Exception>();
foreach (var certificate in certificates)
{
try
{
var token = string.IsNullOrEmpty(authorizationCode)
? certificate.GetToken(this.AuthenticationSettings, this.Resource)
: certificate.GetTokenOnBehalfOf(this.AuthenticationSettings, this.Resource, authorizationCode);
return GetAcquireTokenResult(token, test, index, errors);
}
catch (Exception e)
{
AcquireTokenResult result;
if (TryHandleError(e, index, errors, out result))
{
return result;
}
}
++index;
}
// all certificates are invalid
var error = new AggregateException(errors);
return new AcquireTokenResult { Token = null, Error = error };
}
/// <summary>
/// Updates the cached token.
/// </summary>
/// <param name="result">The new token.</param>
private void ApplyAuthenticationResult(AcquireTokenResult result)
{
this.tokenCache = result.Token;
if (result.Error != null)
{
throw result.Error;
}
if (this.tokenCache != null)
{
var duration = this.tokenCache.ExpiresOn - DateTimeOffset.UtcNow;
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("New token expires on: {0}: after: {1}", this.tokenCache.ExpiresOn, duration));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle;
namespace System.Net.Http
{
#if HTTP_DLL
internal enum WindowsProxyUsePolicy
#else
public enum WindowsProxyUsePolicy
#endif
{
DoNotUseProxy = 0, // Don't use a proxy at all.
UseWinHttpProxy = 1, // Use configuration as specified by "netsh winhttp" machine config command. Automatic detect not supported.
UseWinInetProxy = 2, // WPAD protocol and PAC files supported.
UseCustomProxy = 3 // Use the custom proxy specified in the Proxy property.
}
#if HTTP_DLL
internal enum CookieUsePolicy
#else
public enum CookieUsePolicy
#endif
{
IgnoreCookies = 0,
UseInternalCookieStoreOnly = 1,
UseSpecifiedCookieContainer = 2
}
#if HTTP_DLL
internal class WinHttpHandler : HttpMessageHandler
#else
public class WinHttpHandler : HttpMessageHandler
#endif
{
// These are normally defined already in System.Net.Primitives as part of the HttpVersion type.
// However, these are not part of 'netstandard'. WinHttpHandler currently builds against
// 'netstandard' so we need to add these definitions here.
internal static readonly Version HttpVersion20 = new Version(2, 0);
internal static readonly Version HttpVersionUnknown = new Version(0, 0);
private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue);
private static readonly StringWithQualityHeaderValue s_gzipHeaderValue = new StringWithQualityHeaderValue("gzip");
private static readonly StringWithQualityHeaderValue s_deflateHeaderValue = new StringWithQualityHeaderValue("deflate");
[ThreadStatic]
private static StringBuilder t_requestHeadersBuilder;
private object _lockObject = new object();
private bool _doManualDecompressionCheck = false;
private WinInetProxyHelper _proxyHelper = null;
private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection;
private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections;
private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression;
private CookieUsePolicy _cookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly;
private CookieContainer _cookieContainer = null;
private SslProtocols _sslProtocols = SslProtocols.None; // Use most secure protocols available.
private Func<
HttpRequestMessage,
X509Certificate2,
X509Chain,
SslPolicyErrors,
bool> _serverCertificateValidationCallback = null;
private bool _checkCertificateRevocationList = false;
private ClientCertificateOption _clientCertificateOption = ClientCertificateOption.Manual;
private X509Certificate2Collection _clientCertificates = null; // Only create collection when required.
private ICredentials _serverCredentials = null;
private bool _preAuthenticate = false;
private WindowsProxyUsePolicy _windowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinHttpProxy;
private ICredentials _defaultProxyCredentials = null;
private IWebProxy _proxy = null;
private int _maxConnectionsPerServer = int.MaxValue;
private TimeSpan _sendTimeout = TimeSpan.FromSeconds(30);
private TimeSpan _receiveHeadersTimeout = TimeSpan.FromSeconds(30);
private TimeSpan _receiveDataTimeout = TimeSpan.FromSeconds(30);
private int _maxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeadersLength;
private int _maxResponseDrainSize = 64 * 1024;
private IDictionary<string, object> _properties; // Only create dictionary when required.
private volatile bool _operationStarted;
private volatile bool _disposed;
private SafeWinHttpHandle _sessionHandle;
private WinHttpAuthHelper _authHelper = new WinHttpAuthHelper();
public WinHttpHandler()
{
}
#region Properties
public bool AutomaticRedirection
{
get
{
return _automaticRedirection;
}
set
{
CheckDisposedOrStarted();
_automaticRedirection = value;
}
}
public int MaxAutomaticRedirections
{
get
{
return _maxAutomaticRedirections;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxAutomaticRedirections = value;
}
}
public DecompressionMethods AutomaticDecompression
{
get
{
return _automaticDecompression;
}
set
{
CheckDisposedOrStarted();
_automaticDecompression = value;
}
}
public CookieUsePolicy CookieUsePolicy
{
get
{
return _cookieUsePolicy;
}
set
{
if (value != CookieUsePolicy.IgnoreCookies
&& value != CookieUsePolicy.UseInternalCookieStoreOnly
&& value != CookieUsePolicy.UseSpecifiedCookieContainer)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_cookieUsePolicy = value;
}
}
public CookieContainer CookieContainer
{
get
{
return _cookieContainer;
}
set
{
CheckDisposedOrStarted();
_cookieContainer = value;
}
}
public SslProtocols SslProtocols
{
get
{
return _sslProtocols;
}
set
{
CheckDisposedOrStarted();
_sslProtocols = value;
}
}
public Func<
HttpRequestMessage,
X509Certificate2,
X509Chain,
SslPolicyErrors,
bool> ServerCertificateValidationCallback
{
get
{
return _serverCertificateValidationCallback;
}
set
{
CheckDisposedOrStarted();
_serverCertificateValidationCallback = value;
}
}
public bool CheckCertificateRevocationList
{
get
{
return _checkCertificateRevocationList;
}
set
{
CheckDisposedOrStarted();
_checkCertificateRevocationList = value;
}
}
public ClientCertificateOption ClientCertificateOption
{
get
{
return _clientCertificateOption;
}
set
{
if (value != ClientCertificateOption.Manual
&& value != ClientCertificateOption.Automatic)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_clientCertificateOption = value;
}
}
public X509Certificate2Collection ClientCertificates
{
get
{
if (_clientCertificateOption != ClientCertificateOption.Manual)
{
throw new InvalidOperationException(SR.Format(SR.net_http_invalid_enable_first, "ClientCertificateOptions", "Manual"));
}
if (_clientCertificates == null)
{
_clientCertificates = new X509Certificate2Collection();
}
return _clientCertificates;
}
}
public bool PreAuthenticate
{
get
{
return _preAuthenticate;
}
set
{
_preAuthenticate = value;
}
}
public ICredentials ServerCredentials
{
get
{
return _serverCredentials;
}
set
{
_serverCredentials = value;
}
}
public WindowsProxyUsePolicy WindowsProxyUsePolicy
{
get
{
return _windowsProxyUsePolicy;
}
set
{
if (value != WindowsProxyUsePolicy.DoNotUseProxy &&
value != WindowsProxyUsePolicy.UseWinHttpProxy &&
value != WindowsProxyUsePolicy.UseWinInetProxy &&
value != WindowsProxyUsePolicy.UseCustomProxy)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_windowsProxyUsePolicy = value;
}
}
public ICredentials DefaultProxyCredentials
{
get
{
return _defaultProxyCredentials;
}
set
{
CheckDisposedOrStarted();
_defaultProxyCredentials = value;
}
}
public IWebProxy Proxy
{
get
{
return _proxy;
}
set
{
CheckDisposedOrStarted();
_proxy = value;
}
}
public int MaxConnectionsPerServer
{
get
{
return _maxConnectionsPerServer;
}
set
{
if (value < 1)
{
// In WinHTTP, setting this to 0 results in it being reset to 2.
// So, we'll only allow settings above 0.
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxConnectionsPerServer = value;
}
}
public TimeSpan SendTimeout
{
get
{
return _sendTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_sendTimeout = value;
}
}
public TimeSpan ReceiveHeadersTimeout
{
get
{
return _receiveHeadersTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_receiveHeadersTimeout = value;
}
}
public TimeSpan ReceiveDataTimeout
{
get
{
return _receiveDataTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_receiveDataTimeout = value;
}
}
public int MaxResponseHeadersLength
{
get
{
return _maxResponseHeadersLength;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxResponseHeadersLength = value;
}
}
public int MaxResponseDrainSize
{
get
{
return _maxResponseDrainSize;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxResponseDrainSize = value;
}
}
public IDictionary<string, object> Properties
{
get
{
if (_properties == null)
{
_properties = new Dictionary<string, object>();
}
return _properties;
}
}
#endregion
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
_disposed = true;
if (disposing && _sessionHandle != null)
{
SafeWinHttpHandle.DisposeAndClearHandle(ref _sessionHandle);
}
}
base.Dispose(disposing);
}
#if HTTP_DLL
protected internal override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
#else
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
#endif
{
if (request == null)
{
throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest);
}
// Check for invalid combinations of properties.
if (_proxy != null && _windowsProxyUsePolicy != WindowsProxyUsePolicy.UseCustomProxy)
{
throw new InvalidOperationException(SR.net_http_invalid_proxyusepolicy);
}
if (_windowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy && _proxy == null)
{
throw new InvalidOperationException(SR.net_http_invalid_proxy);
}
if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer &&
_cookieContainer == null)
{
throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer);
}
CheckDisposed();
SetOperationStarted();
TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
// Create state object and save current values of handler settings.
var state = new WinHttpRequestState();
state.Tcs = tcs;
state.CancellationToken = cancellationToken;
state.RequestMessage = request;
state.Handler = this;
state.CheckCertificateRevocationList = _checkCertificateRevocationList;
state.ServerCertificateValidationCallback = _serverCertificateValidationCallback;
state.WindowsProxyUsePolicy = _windowsProxyUsePolicy;
state.Proxy = _proxy;
state.ServerCredentials = _serverCredentials;
state.DefaultProxyCredentials = _defaultProxyCredentials;
state.PreAuthenticate = _preAuthenticate;
Task.Factory.StartNew(
s => {
var whrs = (WinHttpRequestState)s;
whrs.Handler.StartRequest(whrs);
},
state,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
return tcs.Task;
}
private static bool IsChunkedModeForSend(HttpRequestMessage requestMessage)
{
bool chunkedMode = requestMessage.Headers.TransferEncodingChunked.HasValue &&
requestMessage.Headers.TransferEncodingChunked.Value;
HttpContent requestContent = requestMessage.Content;
if (requestContent != null)
{
if (requestContent.Headers.ContentLength.HasValue)
{
if (chunkedMode)
{
// Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics.
// Current .NET Desktop HttpClientHandler allows both headers to be specified but ends up
// stripping out 'Content-Length' and using chunked semantics. WinHttpHandler will maintain
// the same behavior.
requestContent.Headers.ContentLength = null;
}
}
else
{
if (!chunkedMode)
{
// Neither 'Content-Length' nor 'Transfer-Encoding: chunked' semantics was given.
// Current .NET Desktop HttpClientHandler uses 'Content-Length' semantics and
// buffers the content as well in some cases. But the WinHttpHandler can't access
// the protected internal TryComputeLength() method of the content. So, it
// will use'Transfer-Encoding: chunked' semantics.
chunkedMode = true;
requestMessage.Headers.TransferEncodingChunked = true;
}
}
}
else if (chunkedMode)
{
throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content);
}
return chunkedMode;
}
private static void AddRequestHeaders(
SafeWinHttpHandle requestHandle,
HttpRequestMessage requestMessage,
CookieContainer cookies,
DecompressionMethods manuallyProcessedDecompressionMethods)
{
// Get a StringBuilder to use for creating the request headers.
// We cache one in TLS to avoid creating a new one for each request.
StringBuilder requestHeadersBuffer = t_requestHeadersBuilder;
if (requestHeadersBuffer != null)
{
requestHeadersBuffer.Clear();
}
else
{
t_requestHeadersBuilder = requestHeadersBuffer = new StringBuilder();
}
// Normally WinHttpHandler will let native WinHTTP add 'Accept-Encoding' request headers
// for gzip and/or default as needed based on whether the handler should do automatic
// decompression of response content. But on Windows 7, WinHTTP doesn't support this feature.
// So, we need to manually add these headers since WinHttpHandler still supports automatic
// decompression (by doing it within the handler).
if (manuallyProcessedDecompressionMethods != DecompressionMethods.None)
{
if ((manuallyProcessedDecompressionMethods & DecompressionMethods.GZip) == DecompressionMethods.GZip &&
!requestMessage.Headers.AcceptEncoding.Contains(s_gzipHeaderValue))
{
requestMessage.Headers.AcceptEncoding.Add(s_gzipHeaderValue);
}
if ((manuallyProcessedDecompressionMethods & DecompressionMethods.Deflate) == DecompressionMethods.Deflate &&
!requestMessage.Headers.AcceptEncoding.Contains(s_deflateHeaderValue))
{
requestMessage.Headers.AcceptEncoding.Add(s_deflateHeaderValue);
}
}
// Manually add cookies.
if (cookies != null && cookies.Count > 0)
{
string cookieHeader = WinHttpCookieContainerAdapter.GetCookieHeader(requestMessage.RequestUri, cookies);
if (!string.IsNullOrEmpty(cookieHeader))
{
requestHeadersBuffer.AppendLine(cookieHeader);
}
}
// Serialize general request headers.
requestHeadersBuffer.AppendLine(requestMessage.Headers.ToString());
// Serialize entity-body (content) headers.
if (requestMessage.Content != null)
{
// TODO (#5523): Content-Length header isn't getting correctly placed using ToString()
// This is a bug in HttpContentHeaders that needs to be fixed.
if (requestMessage.Content.Headers.ContentLength.HasValue)
{
long contentLength = requestMessage.Content.Headers.ContentLength.Value;
requestMessage.Content.Headers.ContentLength = null;
requestMessage.Content.Headers.ContentLength = contentLength;
}
requestHeadersBuffer.AppendLine(requestMessage.Content.Headers.ToString());
}
// Add request headers to WinHTTP request handle.
if (!Interop.WinHttp.WinHttpAddRequestHeaders(
requestHandle,
requestHeadersBuffer,
(uint)requestHeadersBuffer.Length,
Interop.WinHttp.WINHTTP_ADDREQ_FLAG_ADD))
{
WinHttpException.ThrowExceptionUsingLastError(nameof(Interop.WinHttp.WinHttpAddRequestHeaders));
}
}
private void EnsureSessionHandleExists(WinHttpRequestState state)
{
if (_sessionHandle == null)
{
lock (_lockObject)
{
if (_sessionHandle == null)
{
SafeWinHttpHandle sessionHandle;
uint accessType;
// If a custom proxy is specified and it is really the system web proxy
// (initial WebRequest.DefaultWebProxy) then we need to update the settings
// since that object is only a sentinel.
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy)
{
Debug.Assert(state.Proxy != null);
try
{
state.Proxy.GetProxy(state.RequestMessage.RequestUri);
}
catch (PlatformNotSupportedException)
{
// This is the system web proxy.
state.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
state.Proxy = null;
}
}
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.DoNotUseProxy ||
state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy)
{
// Either no proxy at all or a custom IWebProxy proxy is specified.
// For a custom IWebProxy, we'll need to calculate and set the proxy
// on a per request handle basis using the request Uri. For now,
// we set the session handle to have no proxy.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY;
}
else if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinHttpProxy)
{
// Use WinHTTP per-machine proxy settings which are set using the "netsh winhttp" command.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
}
else
{
// Use WinInet per-user proxy settings.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY;
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Proxy accessType={accessType}");
sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
accessType,
Interop.WinHttp.WINHTTP_NO_PROXY_NAME,
Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
if (sessionHandle.IsInvalid)
{
int lastError = Marshal.GetLastWin32Error();
if (NetEventSource.IsEnabled) NetEventSource.Error(this, $"error={lastError}");
if (lastError != Interop.WinHttp.ERROR_INVALID_PARAMETER)
{
ThrowOnInvalidHandle(sessionHandle, nameof(Interop.WinHttp.WinHttpOpen));
}
// We must be running on a platform earlier than Win8.1/Win2K12R2 which doesn't support
// WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY. So, we'll need to read the Wininet style proxy
// settings ourself using our WinInetProxyHelper object.
_proxyHelper = new WinInetProxyHelper();
sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
_proxyHelper.ManualSettingsOnly ? Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY : Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY,
_proxyHelper.ManualSettingsOnly ? _proxyHelper.Proxy : Interop.WinHttp.WINHTTP_NO_PROXY_NAME,
_proxyHelper.ManualSettingsOnly ? _proxyHelper.ProxyBypass : Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
ThrowOnInvalidHandle(sessionHandle, nameof(Interop.WinHttp.WinHttpOpen));
}
uint optionAssuredNonBlockingTrue = 1; // TRUE
if (!Interop.WinHttp.WinHttpSetOption(
sessionHandle,
Interop.WinHttp.WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS,
ref optionAssuredNonBlockingTrue,
(uint)sizeof(uint)))
{
// This option is not available on downlevel Windows versions. While it improves
// performance, we can ignore the error that the option is not available.
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION)
{
throw WinHttpException.CreateExceptionUsingError(lastError, nameof(Interop.WinHttp.WinHttpSetOption));
}
}
SetSessionHandleOptions(sessionHandle);
_sessionHandle = sessionHandle;
}
}
}
}
private async void StartRequest(WinHttpRequestState state)
{
if (state.CancellationToken.IsCancellationRequested)
{
state.Tcs.TrySetCanceled(state.CancellationToken);
state.ClearSendRequestState();
return;
}
SafeWinHttpHandle connectHandle = null;
try
{
EnsureSessionHandleExists(state);
// Specify an HTTP server.
connectHandle = Interop.WinHttp.WinHttpConnect(
_sessionHandle,
state.RequestMessage.RequestUri.HostNameType == UriHostNameType.IPv6 ? "[" + state.RequestMessage.RequestUri.IdnHost + "]" : state.RequestMessage.RequestUri.IdnHost,
(ushort)state.RequestMessage.RequestUri.Port,
0);
ThrowOnInvalidHandle(connectHandle, nameof(Interop.WinHttp.WinHttpConnect));
connectHandle.SetParentHandle(_sessionHandle);
// Try to use the requested version if a known/supported version was explicitly requested.
// Otherwise, we simply use winhttp's default.
string httpVersion = null;
if (state.RequestMessage.Version == HttpVersion.Version10)
{
httpVersion = "HTTP/1.0";
}
else if (state.RequestMessage.Version == HttpVersion.Version11)
{
httpVersion = "HTTP/1.1";
}
// Turn off additional URI reserved character escaping (percent-encoding). This matches
// .NET Framework behavior. System.Uri establishes the baseline rules for percent-encoding
// of reserved characters.
uint flags = Interop.WinHttp.WINHTTP_FLAG_ESCAPE_DISABLE;
if (state.RequestMessage.RequestUri.Scheme == UriScheme.Https)
{
flags |= Interop.WinHttp.WINHTTP_FLAG_SECURE;
}
// Create an HTTP request handle.
state.RequestHandle = Interop.WinHttp.WinHttpOpenRequest(
connectHandle,
state.RequestMessage.Method.Method,
state.RequestMessage.RequestUri.PathAndQuery,
httpVersion,
Interop.WinHttp.WINHTTP_NO_REFERER,
Interop.WinHttp.WINHTTP_DEFAULT_ACCEPT_TYPES,
flags);
ThrowOnInvalidHandle(state.RequestHandle, nameof(Interop.WinHttp.WinHttpOpenRequest));
state.RequestHandle.SetParentHandle(connectHandle);
// Set callback function.
SetStatusCallback(state.RequestHandle, WinHttpRequestCallback.StaticCallbackDelegate);
// Set needed options on the request handle.
SetRequestHandleOptions(state);
bool chunkedModeForSend = IsChunkedModeForSend(state.RequestMessage);
AddRequestHeaders(
state.RequestHandle,
state.RequestMessage,
_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer ? _cookieContainer : null,
_doManualDecompressionCheck ? _automaticDecompression : DecompressionMethods.None);
uint proxyAuthScheme = 0;
uint serverAuthScheme = 0;
state.RetryRequest = false;
// The only way to abort pending async operations in WinHTTP is to close the WinHTTP handle.
// We will detect a cancellation request on the cancellation token by registering a callback.
// If the callback is invoked, then we begin the abort process by disposing the handle. This
// will have the side-effect of WinHTTP cancelling any pending I/O and accelerating its callbacks
// on the handle and thus releasing the awaiting tasks in the loop below. This helps to provide
// a more timely, cooperative, cancellation pattern.
using (state.CancellationToken.Register(s => ((WinHttpRequestState)s).RequestHandle.Dispose(), state))
{
do
{
_authHelper.PreAuthenticateRequest(state, proxyAuthScheme);
await InternalSendRequestAsync(state);
if (state.RequestMessage.Content != null)
{
await InternalSendRequestBodyAsync(state, chunkedModeForSend).ConfigureAwait(false);
}
bool receivedResponse = await InternalReceiveResponseHeadersAsync(state) != 0;
if (receivedResponse)
{
// If we're manually handling cookies, we need to add them to the container after
// each response has been received.
if (state.Handler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer)
{
WinHttpCookieContainerAdapter.AddResponseCookiesToContainer(state);
}
_authHelper.CheckResponseForAuthentication(
state,
ref proxyAuthScheme,
ref serverAuthScheme);
}
} while (state.RetryRequest);
}
state.CancellationToken.ThrowIfCancellationRequested();
// Since the headers have been read, set the "receive" timeout to be based on each read
// call of the response body data. WINHTTP_OPTION_RECEIVE_TIMEOUT sets a timeout on each
// lower layer winsock read.
uint optionData = unchecked((uint)_receiveDataTimeout.TotalMilliseconds);
SetWinHttpOption(state.RequestHandle, Interop.WinHttp.WINHTTP_OPTION_RECEIVE_TIMEOUT, ref optionData);
HttpResponseMessage responseMessage =
WinHttpResponseParser.CreateResponseMessage(state, _doManualDecompressionCheck ? _automaticDecompression : DecompressionMethods.None);
state.Tcs.TrySetResult(responseMessage);
// HttpStatusCode cast is needed for 308 Moved Permenantly, which we support but is not included in NetStandard status codes.
if (NetEventSource.IsEnabled &&
((responseMessage.StatusCode >= HttpStatusCode.MultipleChoices && responseMessage.StatusCode <= HttpStatusCode.SeeOther) ||
(responseMessage.StatusCode >= HttpStatusCode.RedirectKeepVerb && responseMessage.StatusCode <= (HttpStatusCode)308)) &&
state.RequestMessage.RequestUri.Scheme == Uri.UriSchemeHttps && responseMessage.Headers.Location?.Scheme == Uri.UriSchemeHttp)
{
NetEventSource.Error(this, $"Insecure https to http redirect from {state.RequestMessage.RequestUri.ToString()} to {responseMessage.Headers.Location.ToString()} blocked.");
}
}
catch (Exception ex)
{
HandleAsyncException(state, state.SavedException ?? ex);
}
finally
{
SafeWinHttpHandle.DisposeAndClearHandle(ref connectHandle);
state.ClearSendRequestState();
}
}
private void SetSessionHandleOptions(SafeWinHttpHandle sessionHandle)
{
SetSessionHandleConnectionOptions(sessionHandle);
SetSessionHandleTlsOptions(sessionHandle);
SetSessionHandleTimeoutOptions(sessionHandle);
}
private void SetSessionHandleConnectionOptions(SafeWinHttpHandle sessionHandle)
{
uint optionData = (uint)_maxConnectionsPerServer;
SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_SERVER, ref optionData);
SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_1_0_SERVER, ref optionData);
}
private void SetSessionHandleTlsOptions(SafeWinHttpHandle sessionHandle)
{
uint optionData = 0;
SslProtocols sslProtocols =
(_sslProtocols == SslProtocols.None) ? SecurityProtocol.DefaultSecurityProtocols : _sslProtocols;
#pragma warning disable 0618 // SSL2/SSL3 are deprecated
if ((sslProtocols & SslProtocols.Ssl2) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_SSL2;
}
if ((sslProtocols & SslProtocols.Ssl3) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_SSL3;
}
#pragma warning restore 0618
if ((sslProtocols & SslProtocols.Tls) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1;
}
if ((sslProtocols & SslProtocols.Tls11) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1;
}
if ((sslProtocols & SslProtocols.Tls12) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2;
}
SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_SECURE_PROTOCOLS, ref optionData);
}
private void SetSessionHandleTimeoutOptions(SafeWinHttpHandle sessionHandle)
{
if (!Interop.WinHttp.WinHttpSetTimeouts(
sessionHandle,
0,
0,
(int)_sendTimeout.TotalMilliseconds,
(int)_receiveHeadersTimeout.TotalMilliseconds))
{
WinHttpException.ThrowExceptionUsingLastError(nameof(Interop.WinHttp.WinHttpSetTimeouts));
}
}
private void SetRequestHandleOptions(WinHttpRequestState state)
{
SetRequestHandleProxyOptions(state);
SetRequestHandleDecompressionOptions(state.RequestHandle);
SetRequestHandleRedirectionOptions(state.RequestHandle);
SetRequestHandleCookieOptions(state.RequestHandle);
SetRequestHandleTlsOptions(state.RequestHandle);
SetRequestHandleClientCertificateOptions(state.RequestHandle, state.RequestMessage.RequestUri);
SetRequestHandleCredentialsOptions(state);
SetRequestHandleBufferingOptions(state.RequestHandle);
SetRequestHandleHttp2Options(state.RequestHandle, state.RequestMessage.Version);
}
private void SetRequestHandleProxyOptions(WinHttpRequestState state)
{
// We've already set the proxy on the session handle if we're using no proxy or default proxy settings.
// We only need to change it on the request handle if we have a specific IWebProxy or need to manually
// implement Wininet-style auto proxy detection.
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy ||
state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinInetProxy)
{
var proxyInfo = new Interop.WinHttp.WINHTTP_PROXY_INFO();
bool updateProxySettings = false;
Uri uri = state.RequestMessage.RequestUri;
try
{
if (state.Proxy != null)
{
Debug.Assert(state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy);
updateProxySettings = true;
if (state.Proxy.IsBypassed(uri))
{
proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY;
}
else
{
proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY;
Uri proxyUri = state.Proxy.GetProxy(uri);
string proxyString = proxyUri.Scheme + "://" + proxyUri.Authority;
proxyInfo.Proxy = Marshal.StringToHGlobalUni(proxyString);
}
}
else if (_proxyHelper != null && _proxyHelper.AutoSettingsUsed)
{
if (_proxyHelper.GetProxyForUrl(_sessionHandle, uri, out proxyInfo))
{
updateProxySettings = true;
}
}
if (updateProxySettings)
{
GCHandle pinnedHandle = GCHandle.Alloc(proxyInfo, GCHandleType.Pinned);
try
{
SetWinHttpOption(
state.RequestHandle,
Interop.WinHttp.WINHTTP_OPTION_PROXY,
pinnedHandle.AddrOfPinnedObject(),
(uint)Marshal.SizeOf(proxyInfo));
}
finally
{
pinnedHandle.Free();
}
}
}
finally
{
Marshal.FreeHGlobal(proxyInfo.Proxy);
Marshal.FreeHGlobal(proxyInfo.ProxyBypass);
}
}
}
private void SetRequestHandleDecompressionOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = 0;
if (_automaticDecompression != DecompressionMethods.None)
{
if ((_automaticDecompression & DecompressionMethods.GZip) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_DECOMPRESSION_FLAG_GZIP;
}
if ((_automaticDecompression & DecompressionMethods.Deflate) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_DECOMPRESSION_FLAG_DEFLATE;
}
try
{
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_DECOMPRESSION, ref optionData);
}
catch (WinHttpException ex)
{
if (ex.NativeErrorCode != (int)Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION)
{
throw;
}
// We are running on a platform earlier than Win8.1 for which WINHTTP.DLL
// doesn't support this option. So, we'll have to do the decompression
// manually.
_doManualDecompressionCheck = true;
}
}
}
private void SetRequestHandleRedirectionOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = 0;
if (_automaticRedirection)
{
optionData = (uint)_maxAutomaticRedirections;
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS,
ref optionData);
}
optionData = _automaticRedirection ?
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP :
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_NEVER;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY, ref optionData);
}
private void SetRequestHandleCookieOptions(SafeWinHttpHandle requestHandle)
{
if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer ||
_cookieUsePolicy == CookieUsePolicy.IgnoreCookies)
{
uint optionData = Interop.WinHttp.WINHTTP_DISABLE_COOKIES;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_DISABLE_FEATURE, ref optionData);
}
}
private void SetRequestHandleTlsOptions(SafeWinHttpHandle requestHandle)
{
// If we have a custom server certificate validation callback method then
// we need to have WinHTTP ignore some errors so that the callback method
// will have a chance to be called.
uint optionData;
if (_serverCertificateValidationCallback != null)
{
optionData =
Interop.WinHttp.SECURITY_FLAG_IGNORE_UNKNOWN_CA |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_CN_INVALID |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_SECURITY_FLAGS, ref optionData);
}
else if (_checkCertificateRevocationList)
{
// If no custom validation method, then we let WinHTTP do the revocation check itself.
optionData = Interop.WinHttp.WINHTTP_ENABLE_SSL_REVOCATION;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_ENABLE_FEATURE, ref optionData);
}
}
private void SetRequestHandleClientCertificateOptions(SafeWinHttpHandle requestHandle, Uri requestUri)
{
if (requestUri.Scheme != UriScheme.Https)
{
return;
}
X509Certificate2 clientCertificate = null;
if (_clientCertificateOption == ClientCertificateOption.Manual)
{
clientCertificate = CertificateHelper.GetEligibleClientCertificate(ClientCertificates);
}
else
{
clientCertificate = CertificateHelper.GetEligibleClientCertificate();
}
if (clientCertificate != null)
{
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
clientCertificate.Handle,
(uint)Marshal.SizeOf<Interop.Crypt32.CERT_CONTEXT>());
}
else
{
SetNoClientCertificate(requestHandle);
}
}
internal static void SetNoClientCertificate(SafeWinHttpHandle requestHandle)
{
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
IntPtr.Zero,
0);
}
private void SetRequestHandleCredentialsOptions(WinHttpRequestState state)
{
// By default, WinHTTP sets the default credentials policy such that it automatically sends default credentials
// (current user's logged on Windows credentials) to a proxy when needed (407 response). It only sends
// default credentials to a server (401 response) if the server is considered to be on the Intranet.
// WinHttpHandler uses a more granual opt-in model for using default credentials that can be different between
// proxy and server credentials. It will explicitly allow default credentials to be sent at a later stage in
// the request processing (after getting a 401/407 response) when the proxy or server credential is set as
// CredentialCache.DefaultNetworkCredential. For now, we set the policy to prevent any default credentials
// from being automatically sent until we get a 401/407 response.
_authHelper.ChangeDefaultCredentialsPolicy(
state.RequestHandle,
Interop.WinHttp.WINHTTP_AUTH_TARGET_SERVER,
allowDefaultCredentials:false);
}
private void SetRequestHandleBufferingOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = (uint)(_maxResponseHeadersLength * 1024);
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE, ref optionData);
optionData = (uint)_maxResponseDrainSize;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE, ref optionData);
}
private void SetRequestHandleHttp2Options(SafeWinHttpHandle requestHandle, Version requestVersion)
{
Debug.Assert(requestHandle != null);
uint optionData = (requestVersion == HttpVersion20) ? Interop.WinHttp.WINHTTP_PROTOCOL_FLAG_HTTP2 : 0;
if (Interop.WinHttp.WinHttpSetOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_ENABLE_HTTP_PROTOCOL,
ref optionData))
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"HTTP/2 option supported, setting to {optionData}");
}
else
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "HTTP/2 option not supported");
}
}
private void SetWinHttpOption(SafeWinHttpHandle handle, uint option, ref uint optionData)
{
Debug.Assert(handle != null);
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
ref optionData))
{
WinHttpException.ThrowExceptionUsingLastError(nameof(Interop.WinHttp.WinHttpSetOption));
}
}
private static void SetWinHttpOption(
SafeWinHttpHandle handle,
uint option,
IntPtr optionData,
uint optionSize)
{
Debug.Assert(handle != null);
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
optionData,
optionSize))
{
WinHttpException.ThrowExceptionUsingLastError(nameof(Interop.WinHttp.WinHttpSetOption));
}
}
private void HandleAsyncException(WinHttpRequestState state, Exception ex)
{
if (state.CancellationToken.IsCancellationRequested)
{
// If the exception was due to the cancellation token being canceled, throw cancellation exception.
state.Tcs.TrySetCanceled(state.CancellationToken);
}
else if (ex is WinHttpException || ex is IOException || ex is InvalidOperationException)
{
// Wrap expected exceptions as HttpRequestExceptions since this is considered an error during
// execution. All other exception types, including ArgumentExceptions and ProtocolViolationExceptions
// are 'unexpected' or caused by user error and should not be wrapped.
state.Tcs.TrySetException(new HttpRequestException(SR.net_http_client_execution_error, ex));
}
else
{
state.Tcs.TrySetException(ex);
}
}
private void SetOperationStarted()
{
if (!_operationStarted)
{
_operationStarted = true;
}
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_operationStarted)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
private void SetStatusCallback(
SafeWinHttpHandle requestHandle,
Interop.WinHttp.WINHTTP_STATUS_CALLBACK callback)
{
const uint notificationFlags =
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_HANDLES |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_REDIRECT |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_SEND_REQUEST;
IntPtr oldCallback = Interop.WinHttp.WinHttpSetStatusCallback(
requestHandle,
callback,
notificationFlags,
IntPtr.Zero);
if (oldCallback == new IntPtr(Interop.WinHttp.WINHTTP_INVALID_STATUS_CALLBACK))
{
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_INVALID_HANDLE) // Ignore error if handle was already closed.
{
throw WinHttpException.CreateExceptionUsingError(lastError, nameof(Interop.WinHttp.WinHttpSetStatusCallback));
}
}
}
private void ThrowOnInvalidHandle(SafeWinHttpHandle handle, string nameOfCalledFunction)
{
if (handle.IsInvalid)
{
int lastError = Marshal.GetLastWin32Error();
if (NetEventSource.IsEnabled) NetEventSource.Error(this, $"error={lastError}");
throw WinHttpException.CreateExceptionUsingError(lastError, nameOfCalledFunction);
}
}
private RendezvousAwaitable<int> InternalSendRequestAsync(WinHttpRequestState state)
{
lock (state.Lock)
{
state.Pin();
if (!Interop.WinHttp.WinHttpSendRequest(
state.RequestHandle,
null,
0,
IntPtr.Zero,
0,
0,
state.ToIntPtr()))
{
// WinHTTP doesn't always associate our context value (state object) to the request handle.
// And thus we might not get a HANDLE_CLOSING notification which would normally cause the
// state object to be unpinned and disposed. So, we manually dispose the request handle and
// state object here.
state.RequestHandle.Dispose();
state.Dispose();
WinHttpException.ThrowExceptionUsingLastError(nameof(Interop.WinHttp.WinHttpSendRequest));
}
}
return state.LifecycleAwaitable;
}
private async Task InternalSendRequestBodyAsync(WinHttpRequestState state, bool chunkedModeForSend)
{
using (var requestStream = new WinHttpRequestStream(state, chunkedModeForSend))
{
await state.RequestMessage.Content.CopyToAsync(
requestStream,
state.TransportContext).ConfigureAwait(false);
await requestStream.EndUploadAsync(state.CancellationToken).ConfigureAwait(false);
}
}
private RendezvousAwaitable<int> InternalReceiveResponseHeadersAsync(WinHttpRequestState state)
{
lock (state.Lock)
{
if (!Interop.WinHttp.WinHttpReceiveResponse(state.RequestHandle, IntPtr.Zero))
{
throw WinHttpException.CreateExceptionUsingLastError(nameof(Interop.WinHttp.WinHttpReceiveResponse));
}
}
return state.LifecycleAwaitable;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using Microsoft.Rest.Azure;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.Rest;
using Newtonsoft.Json.Linq;
using Xunit;
using Microsoft.Rest.Azure.OData;
namespace ResourceGroups.Tests
{
public class InMemoryResourceLinkTests
{
public ManagementLinkClient GetManagementLinkClient(RecordedDelegatingHandler handler)
{
var subscriptionId = Guid.NewGuid().ToString();
var token = new TokenCredentials(subscriptionId, "abc123");
handler.IsPassThrough = false;
var client = new ManagementLinkClient(token, handler);
client.SubscriptionId = subscriptionId;
return client;
}
[Fact]
public void ResourceLinkCRUD()
{
var response = new HttpResponseMessage(HttpStatusCode.Created)
{
Content = new StringContent(@"{
'id': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink',
'name': 'myLink',
'properties': {
'sourceId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm',
'targetId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2',
'notes': 'myLinkNotes'
}
}")
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.Created };
var client = GetManagementLinkClient(handler);
var result = client.ResourceLinks.CreateOrUpdate(
linkId: "/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink",
parameters: new ResourceLink
{
Properties = new ResourceLinkProperties
{
TargetId = "/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2",
Notes = "myLinkNotes"
}
});
JObject json = JObject.Parse(handler.Request);
// Validate headers
Assert.Equal("application/json; charset=utf-8", handler.ContentHeaders.GetValues("Content-Type").First());
Assert.Equal(HttpMethod.Put, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
// Validate payload
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2", json["properties"]["targetId"].Value<string>());
Assert.Equal("myLinkNotes", json["properties"]["notes"].Value<string>());
// Validate response
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink", result.Id);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm", result.Properties.SourceId);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2", result.Properties.TargetId);
Assert.Equal("myLinkNotes", result.Properties.Notes);
Assert.Equal("myLink", result.Name);
//Get resource link and validate properties
var getResponse = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'id': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink',
'name': 'myLink',
'properties': {
'sourceId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm',
'targetId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2',
'notes': 'myLinkNotes'
}
}")
};
var getHandler = new RecordedDelegatingHandler(getResponse) { StatusCodeToReturn = HttpStatusCode.OK };
client = GetManagementLinkClient(getHandler);
var getResult = client.ResourceLinks.Get("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink");
// Validate response
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink", getResult.Id);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm", getResult.Properties.SourceId);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2", getResult.Properties.TargetId);
Assert.Equal("myLinkNotes", getResult.Properties.Notes);
Assert.Equal("myLink", getResult.Name);
//Delete resource link
var deleteResponse = new HttpResponseMessage(HttpStatusCode.OK);
deleteResponse.Headers.Add("x-ms-request-id", "1");
var deleteHandler = new RecordedDelegatingHandler(deleteResponse) { StatusCodeToReturn = HttpStatusCode.OK };
client = GetManagementLinkClient(deleteHandler);
client.ResourceLinks.Delete("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink");
// Validate headers
Assert.Equal(HttpMethod.Delete, deleteHandler.Method);
// Get a deleted link throws exception
Assert.Throws<CloudException>(() => client.ResourceLinks.Get("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink"));
}
[Fact]
public void ResourceLinkList()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'value': [
{
'id': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink',
'name': 'myLink',
'properties': {
'sourceId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm',
'targetId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2',
'notes': 'myLinkNotes'
}
},
{
'id': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Storage/storageAccounts/myAccount/providers/Microsoft.Resources/links/myLink2',
'name': 'myLink2',
'properties': {
'sourceId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Storage/storageAccounts/myAccount',
'targetId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Storage/storageAccounts/myAccount2',
'notes': 'myLinkNotes2'
}
}],
'nextLink': 'https://wa/subscriptions/subId/links?api-version=1.0&$skiptoken=662idk',
}")
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetManagementLinkClient(handler);
var result = client.ResourceLinks.ListAtSubscription();
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
// Validate result
Assert.Equal(2, result.Count());
Assert.Equal("myLink", result.First().Name);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink", result.First().Id);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm", result.First().Properties.SourceId);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2", result.First().Properties.TargetId);
Assert.Equal("myLinkNotes", result.First().Properties.Notes);
Assert.Equal("https://wa/subscriptions/subId/links?api-version=1.0&$skiptoken=662idk", result.NextPageLink);
// Filter by targetId
var filteredResponse = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'value': [
{
'id': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink',
'name': 'myLink',
'properties': {
'sourceId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm',
'targetId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2',
'notes': 'myLinkNotes'
}
}],
'nextLink': 'https://wa/subscriptions/subId/links?api-version=1.0&$skiptoken=662idk',
}")
};
var filteredHandler = new RecordedDelegatingHandler(filteredResponse) { StatusCodeToReturn = HttpStatusCode.OK };
client = GetManagementLinkClient(filteredHandler);
var filteredResult = client.ResourceLinks.ListAtSubscription(new ODataQuery<ResourceLinkFilter>(f => f.TargetId == "/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2"));
// Validate result
Assert.Equal(1, filteredResult.Count());
Assert.Equal("myLink", filteredResult.First().Name);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink", filteredResult.First().Id);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm", filteredResult.First().Properties.SourceId);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2", filteredResult.First().Properties.TargetId);
Assert.Equal("myLinkNotes", filteredResult.First().Properties.Notes);
Assert.Equal("https://wa/subscriptions/subId/links?api-version=1.0&$skiptoken=662idk", filteredResult.NextPageLink);
}
[Fact]
public void ResourceLinkListAtSourceScope()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'value': [
{
'id': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink',
'name': 'myLink',
'properties': {
'sourceId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm',
'targetId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2',
'notes': 'myLinkNotes'
}
}],
'nextLink': 'https://wa/subscriptions/subId/links?api-version=1.0&$skiptoken=662idk',
}")
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetManagementLinkClient(handler);
var result = client.ResourceLinks.ListAtSourceScope("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm");
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
// Validate result
Assert.Equal(1, result.Count());
Assert.Equal("myLink", result.First().Name);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink", result.First().Id);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm", result.First().Properties.SourceId);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2", result.First().Properties.TargetId);
Assert.Equal("myLinkNotes", result.First().Properties.Notes);
Assert.Equal("https://wa/subscriptions/subId/links?api-version=1.0&$skiptoken=662idk", result.NextPageLink);
}
}
}
| |
// 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.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Threading;
using Windows.Foundation;
using Windows.Storage.Streams;
namespace System.IO
{
/// <summary>Depending on the concrete type of the stream managed by a <c>NetFxToWinRtStreamAdapter</c>,
/// we want the <c>ReadAsync</c> / <c>WriteAsync</c> / <c>FlushAsync</c> / etc. operation to be implemented
/// differently. This is for best performance as we can take advantage of the specifics of particular stream
/// types. For instance, <c>ReadAsync</c> currently has a special implementation for memory streams.
/// Moreover, knowledge about the actual runtime type of the <c>IBuffer</c> can also help choosing the optimal
/// implementation. This type provides static methods that encapsulate the performance logic and can be used
/// by <c>NetFxToWinRtStreamAdapter</c>.</summary>
internal static class StreamOperationsImplementation
{
#region ReadAsync implementations
internal static IAsyncOperationWithProgress<IBuffer, uint> ReadAsync_MemoryStream(Stream stream, IBuffer buffer, uint count)
{
Debug.Assert(stream != null);
Debug.Assert(stream is MemoryStream);
Debug.Assert(stream.CanRead);
Debug.Assert(stream.CanSeek);
Debug.Assert(buffer != null);
Debug.Assert(buffer is IBufferByteAccess);
Debug.Assert(0 <= count);
Debug.Assert(count <= int.MaxValue);
Debug.Assert(count <= buffer.Capacity);
// We will return a different buffer to the user backed directly by the memory stream (avoids memory copy).
// This is permitted by the WinRT stream contract.
// The user specified buffer will not have any data put into it:
buffer.Length = 0;
MemoryStream memStream = stream as MemoryStream;
Debug.Assert(memStream != null);
try
{
IBuffer dataBuffer = memStream.GetWindowsRuntimeBuffer((int)memStream.Position, (int)count);
if (dataBuffer.Length > 0)
memStream.Seek(dataBuffer.Length, SeekOrigin.Current);
return AsyncInfo.CreateCompletedOperation<IBuffer, UInt32>(dataBuffer);
}
catch (Exception ex)
{
return AsyncInfo.CreateFaultedOperation<IBuffer, UInt32>(ex);
}
} // ReadAsync_MemoryStream
internal static IAsyncOperationWithProgress<IBuffer, uint> ReadAsync_AbstractStream(Stream stream, IBuffer buffer, uint count,
InputStreamOptions options)
{
Debug.Assert(stream != null);
Debug.Assert(stream.CanRead);
Debug.Assert(buffer != null);
Debug.Assert(buffer is IBufferByteAccess);
Debug.Assert(0 <= count);
Debug.Assert(count <= int.MaxValue);
Debug.Assert(count <= buffer.Capacity);
Debug.Assert(options == InputStreamOptions.None || options == InputStreamOptions.Partial || options == InputStreamOptions.ReadAhead);
int bytesRequested = (int)count;
// Check if the buffer is our implementation.
// IF YES: In that case, we can read directly into its data array.
// IF NO: The buffer is of unknown implementation. It's not backed by a managed array, but the wrapped stream can only
// read into a managed array. If we used the user-supplied buffer we would need to copy data into it after every read.
// The spec allows to return a buffer instance that is not the same as passed by the user. So, we will create an own
// buffer instance, read data *directly* into the array backing it and then return it to the user.
// Note: the allocation costs we are paying for the new buffer are unavoidable anyway, as we would need to create
// an array to read into either way.
IBuffer dataBuffer = buffer as WindowsRuntimeBuffer;
if (dataBuffer == null)
dataBuffer = WindowsRuntimeBuffer.Create((int)Math.Min((uint)int.MaxValue, buffer.Capacity));
// This operation delegate will we run inside of the returned IAsyncOperationWithProgress:
Func<CancellationToken, IProgress<uint>, Task<IBuffer>> readOperation = async (cancelToken, progressListener) =>
{
// No bytes read yet:
dataBuffer.Length = 0;
// Get the buffer backing array:
byte[] data;
int offset;
bool managedBufferAssert = dataBuffer.TryGetUnderlyingData(out data, out offset);
Debug.Assert(managedBufferAssert);
// Init tracking values:
bool done = cancelToken.IsCancellationRequested;
int bytesCompleted = 0;
// Loop until EOS, cancelled or read enough data according to options:
while (!done)
{
int bytesRead = 0;
try
{
// Read asynchronously:
bytesRead = await stream.ReadAsync(data, offset + bytesCompleted, bytesRequested - bytesCompleted, cancelToken)
.ConfigureAwait(continueOnCapturedContext: false);
// We will continue here on a different thread when read async completed:
bytesCompleted += bytesRead;
// We will handle a cancelation exception and re-throw all others:
}
catch (OperationCanceledException)
{
// We assume that cancelToken.IsCancellationRequested is has been set and simply proceed.
// (we check cancelToken.IsCancellationRequested later)
Debug.Assert(cancelToken.IsCancellationRequested);
// This is because if the cancellation came after we read some bytes we want to return the results we got instead
// of an empty cancelled task, so if we have not yet read anything at all, then we can throw cancellation:
if (bytesCompleted == 0 && bytesRead == 0)
throw;
}
// Update target buffer:
dataBuffer.Length = (uint)bytesCompleted;
Debug.Assert(bytesCompleted <= bytesRequested);
// Check if we are done:
done = options == InputStreamOptions.Partial // If no complete read was requested, any amount of data is OK
|| bytesRead == 0 // this implies EndOfStream
|| bytesCompleted == bytesRequested // read all requested bytes
|| cancelToken.IsCancellationRequested; // operation was cancelled
// Call user Progress handler:
if (progressListener != null)
progressListener.Report(dataBuffer.Length);
} // while (!done)
// If we got here, then no error was detected. Return the results buffer:
return dataBuffer;
}; // readOperation
return AsyncInfo.Run<IBuffer, UInt32>(readOperation);
} // ReadAsync_AbstractStream
#endregion ReadAsync implementations
#region WriteAsync implementations
internal static IAsyncOperationWithProgress<uint, uint> WriteAsync_AbstractStream(Stream stream, IBuffer buffer)
{
Debug.Assert(stream != null);
Debug.Assert(stream.CanWrite);
Debug.Assert(buffer != null);
// Choose the optimal writing strategy for the kind of buffer supplied:
Func<CancellationToken, IProgress<uint>, Task<uint>> writeOperation;
byte[] data;
int offset;
// If buffer is backed by a managed array:
if (buffer.TryGetUnderlyingData(out data, out offset))
{
writeOperation = async (cancelToken, progressListener) =>
{
if (cancelToken.IsCancellationRequested) // CancellationToken is non-nullable
return 0;
Debug.Assert(buffer.Length <= int.MaxValue);
int bytesToWrite = (int)buffer.Length;
await stream.WriteAsync(data, offset, bytesToWrite, cancelToken).ConfigureAwait(continueOnCapturedContext: false);
if (progressListener != null)
progressListener.Report((uint)bytesToWrite);
return (uint)bytesToWrite;
};
// Otherwise buffer is of an unknown implementation:
}
else
{
writeOperation = async (cancelToken, progressListener) =>
{
if (cancelToken.IsCancellationRequested) // CancellationToken is non-nullable
return 0;
uint bytesToWrite = buffer.Length;
Stream dataStream = buffer.AsStream();
int buffSize = 0x4000;
if (bytesToWrite < buffSize)
buffSize = (int)bytesToWrite;
await dataStream.CopyToAsync(stream, buffSize, cancelToken).ConfigureAwait(continueOnCapturedContext: false);
if (progressListener != null)
progressListener.Report((uint)bytesToWrite);
return (uint)bytesToWrite;
};
} // if-else
// Construct and run the async operation:
return AsyncInfo.Run<UInt32, UInt32>(writeOperation);
} // WriteAsync_AbstractStream
#endregion WriteAsync implementations
#region FlushAsync implementations
internal static IAsyncOperation<bool> FlushAsync_AbstractStream(Stream stream)
{
Debug.Assert(stream != null);
Debug.Assert(stream.CanWrite);
Func<CancellationToken, Task<bool>> flushOperation = async (cancelToken) =>
{
if (cancelToken.IsCancellationRequested) // CancellationToken is non-nullable
return false;
await stream.FlushAsync(cancelToken).ConfigureAwait(continueOnCapturedContext: false);
return true;
};
// Construct and run the async operation:
return AsyncInfo.Run<Boolean>(flushOperation);
}
#endregion FlushAsync implementations
} // class StreamOperationsImplementation
} // namespace
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Framework.Client;
using OpenSim.Framework.Monitoring;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Connectors.Hypergrid;
using OpenSim.Services.Interfaces;
using OpenSim.Server.Base;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenMetaverse;
using log4net;
using Nini.Config;
using Mono.Addins;
namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HGEntityTransferModule")]
public class HGEntityTransferModule
: EntityTransferModule, INonSharedRegionModule, IEntityTransferModule, IUserAgentVerificationModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private int m_levelHGTeleport = 0;
private GatekeeperServiceConnector m_GatekeeperConnector;
private IUserAgentService m_UAS;
protected bool m_RestrictAppearanceAbroad;
protected string m_AccountName;
protected List<AvatarAppearance> m_ExportedAppearances;
protected List<AvatarAttachment> m_Attachs;
protected List<AvatarAppearance> ExportedAppearance
{
get
{
if (m_ExportedAppearances != null)
return m_ExportedAppearances;
m_ExportedAppearances = new List<AvatarAppearance>();
m_Attachs = new List<AvatarAttachment>();
string[] names = m_AccountName.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string name in names)
{
string[] parts = name.Trim().Split();
if (parts.Length != 2)
{
m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: Wrong user account name format {0}. Specify 'First Last'", name);
return null;
}
UserAccount account = Scene.UserAccountService.GetUserAccount(UUID.Zero, parts[0], parts[1]);
if (account == null)
{
m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: Unknown account {0}", m_AccountName);
return null;
}
AvatarAppearance a = Scene.AvatarService.GetAppearance(account.PrincipalID);
if (a != null)
m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Successfully retrieved appearance for {0}", name);
foreach (AvatarAttachment att in a.GetAttachments())
{
InventoryItemBase item = Scene.InventoryService.GetItem(account.PrincipalID, att.ItemID);
if (item != null)
a.SetAttachment(att.AttachPoint, att.ItemID, item.AssetID);
else
m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: Unable to retrieve item {0} from inventory {1}", att.ItemID, name);
}
m_ExportedAppearances.Add(a);
m_Attachs.AddRange(a.GetAttachments());
}
return m_ExportedAppearances;
}
}
/// <summary>
/// Used for processing analysis of incoming attachments in a controlled fashion.
/// </summary>
private JobEngine m_incomingSceneObjectEngine;
#region ISharedRegionModule
public override string Name
{
get { return "HGEntityTransferModule"; }
}
public override void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("EntityTransferModule", "");
if (name == Name)
{
IConfig transferConfig = source.Configs["EntityTransfer"];
if (transferConfig != null)
{
m_levelHGTeleport = transferConfig.GetInt("LevelHGTeleport", 0);
m_RestrictAppearanceAbroad = transferConfig.GetBoolean("RestrictAppearanceAbroad", false);
if (m_RestrictAppearanceAbroad)
{
m_AccountName = transferConfig.GetString("AccountForAppearance", string.Empty);
if (m_AccountName == string.Empty)
m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: RestrictAppearanceAbroad is on, but no account has been given for avatar appearance!");
}
}
InitialiseCommon(source);
m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: {0} enabled.", Name);
}
}
}
public override void AddRegion(Scene scene)
{
base.AddRegion(scene);
if (m_Enabled)
{
scene.RegisterModuleInterface<IUserAgentVerificationModule>(this);
//scene.EventManager.OnIncomingSceneObject += OnIncomingSceneObject;
m_incomingSceneObjectEngine
= new JobEngine(
string.Format("HG Incoming Scene Object Engine ({0})", scene.Name),
"HG INCOMING SCENE OBJECT ENGINE");
StatsManager.RegisterStat(
new Stat(
"HGIncomingAttachmentsWaiting",
"Number of incoming attachments waiting for processing.",
"",
"",
"entitytransfer",
Name,
StatType.Pull,
MeasuresOfInterest.None,
stat => stat.Value = m_incomingSceneObjectEngine.JobsWaiting,
StatVerbosity.Debug));
m_incomingSceneObjectEngine.Start();
}
}
protected override void OnNewClient(IClientAPI client)
{
client.OnTeleportHomeRequest += TriggerTeleportHome;
client.OnTeleportLandmarkRequest += RequestTeleportLandmark;
client.OnConnectionClosed += new Action<IClientAPI>(OnConnectionClosed);
}
public override void RegionLoaded(Scene scene)
{
base.RegionLoaded(scene);
if (m_Enabled)
{
m_GatekeeperConnector = new GatekeeperServiceConnector(scene.AssetService);
m_UAS = scene.RequestModuleInterface<IUserAgentService>();
if (m_UAS == null)
m_UAS = new UserAgentServiceConnector(m_ThisHomeURI);
}
}
public override void RemoveRegion(Scene scene)
{
base.RemoveRegion(scene);
if (m_Enabled)
{
scene.UnregisterModuleInterface<IUserAgentVerificationModule>(this);
m_incomingSceneObjectEngine.Stop();
}
}
#endregion
#region HG overrides of IEntityTransferModule
protected override GridRegion GetFinalDestination(GridRegion region, UUID agentID, string agentHomeURI, out string message)
{
int flags = Scene.GridService.GetRegionFlags(Scene.RegionInfo.ScopeID, region.RegionID);
m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: region {0} flags: {1}", region.RegionName, flags);
message = null;
if ((flags & (int)OpenSim.Framework.RegionFlags.Hyperlink) != 0)
{
m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Destination region is hyperlink");
GridRegion real_destination = m_GatekeeperConnector.GetHyperlinkRegion(region, region.RegionID, agentID, agentHomeURI, out message);
if (real_destination != null)
m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: GetFinalDestination: ServerURI={0}", real_destination.ServerURI);
else
m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: GetHyperlinkRegion of region {0} from Gatekeeper {1} failed: {2}", region.RegionID, region.ServerURI, message);
return real_destination;
}
return region;
}
protected override bool NeedsClosing(GridRegion reg, bool OutViewRange)
{
if (OutViewRange)
return true;
int flags = Scene.GridService.GetRegionFlags(Scene.RegionInfo.ScopeID, reg.RegionID);
if (flags == -1 || (flags & (int)OpenSim.Framework.RegionFlags.Hyperlink) != 0)
return true;
return false;
}
protected override void AgentHasMovedAway(ScenePresence sp, bool logout)
{
base.AgentHasMovedAway(sp, logout);
if (logout)
{
// Log them out of this grid
Scene.PresenceService.LogoutAgent(sp.ControllingClient.SessionId);
string userId = Scene.UserManagementModule.GetUserUUI(sp.UUID);
Scene.GridUserService.LoggedOut(userId, UUID.Zero, Scene.RegionInfo.RegionID, sp.AbsolutePosition, sp.Lookat);
}
}
protected override bool CreateAgent(ScenePresence sp, GridRegion reg, GridRegion finalDestination, AgentCircuitData agentCircuit, uint teleportFlags, EntityTransferContext ctx, out string reason, out bool logout)
{
m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: CreateAgent {0} {1}", reg.ServerURI, finalDestination.ServerURI);
reason = string.Empty;
logout = false;
int flags = Scene.GridService.GetRegionFlags(Scene.RegionInfo.ScopeID, reg.RegionID);
if (flags == -1 /* no region in DB */ || (flags & (int)OpenSim.Framework.RegionFlags.Hyperlink) != 0)
{
// this user is going to another grid
// for local users, check if HyperGrid teleport is allowed, based on user level
if (Scene.UserManagementModule.IsLocalGridUser(sp.UUID) && sp.GodController.UserLevel < m_levelHGTeleport)
{
m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: Unable to HG teleport agent due to insufficient UserLevel.");
reason = "Hypergrid teleport not allowed";
return false;
}
if (agentCircuit.ServiceURLs.ContainsKey("HomeURI"))
{
string userAgentDriver = agentCircuit.ServiceURLs["HomeURI"].ToString();
IUserAgentService connector;
if (userAgentDriver.Equals(m_ThisHomeURI) && m_UAS != null)
connector = m_UAS;
else
connector = new UserAgentServiceConnector(userAgentDriver);
GridRegion source = new GridRegion(Scene.RegionInfo);
source.RawServerURI = m_GatekeeperURI;
bool success = connector.LoginAgentToGrid(source, agentCircuit, reg, finalDestination, false, out reason);
logout = success; // flag for later logout from this grid; this is an HG TP
if (success)
Scene.EventManager.TriggerTeleportStart(sp.ControllingClient, reg, finalDestination, teleportFlags, logout);
return success;
}
else
{
m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent does not have a HomeURI address");
return false;
}
}
return base.CreateAgent(sp, reg, finalDestination, agentCircuit, teleportFlags, ctx, out reason, out logout);
}
public override void TriggerTeleportHome(UUID id, IClientAPI client)
{
TeleportHome(id, client);
}
protected override bool ValidateGenericConditions(ScenePresence sp, GridRegion reg, GridRegion finalDestination, uint teleportFlags, out string reason)
{
reason = "Please wear your grid's allowed appearance before teleporting to another grid";
if (!m_RestrictAppearanceAbroad)
return true;
// The rest is only needed for controlling appearance
int flags = Scene.GridService.GetRegionFlags(Scene.RegionInfo.ScopeID, reg.RegionID);
if (flags == -1 /* no region in DB */ || (flags & (int)OpenSim.Framework.RegionFlags.Hyperlink) != 0)
{
// this user is going to another grid
if (Scene.UserManagementModule.IsLocalGridUser(sp.UUID))
{
m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: RestrictAppearanceAbroad is ON. Checking generic appearance");
// Check wearables
for (int i = 0; i < sp.Appearance.Wearables.Length ; i++)
{
for (int j = 0; j < sp.Appearance.Wearables[i].Count; j++)
{
if (sp.Appearance.Wearables[i] == null)
continue;
bool found = false;
foreach (AvatarAppearance a in ExportedAppearance)
if (i < a.Wearables.Length && a.Wearables[i] != null)
{
found = true;
break;
}
if (!found)
{
m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Wearable not allowed to go outside {0}", i);
return false;
}
found = false;
foreach (AvatarAppearance a in ExportedAppearance)
if (i < a.Wearables.Length && sp.Appearance.Wearables[i][j].AssetID == a.Wearables[i][j].AssetID)
{
found = true;
break;
}
if (!found)
{
m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Wearable not allowed to go outside {0}", i);
return false;
}
}
}
// Check attachments
foreach (AvatarAttachment att in sp.Appearance.GetAttachments())
{
bool found = false;
foreach (AvatarAttachment att2 in m_Attachs)
{
if (att2.AssetID == att.AssetID)
{
found = true;
break;
}
}
if (!found)
{
m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Attachment not allowed to go outside {0}", att.AttachPoint);
return false;
}
}
}
}
reason = string.Empty;
return true;
}
//protected override bool UpdateAgent(GridRegion reg, GridRegion finalDestination, AgentData agentData, ScenePresence sp)
//{
// int flags = Scene.GridService.GetRegionFlags(Scene.RegionInfo.ScopeID, reg.RegionID);
// if (flags == -1 /* no region in DB */ || (flags & (int)OpenSim.Data.RegionFlags.Hyperlink) != 0)
// {
// // this user is going to another grid
// if (m_RestrictAppearanceAbroad && Scene.UserManagementModule.IsLocalGridUser(agentData.AgentID))
// {
// // We need to strip the agent off its appearance
// m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: RestrictAppearanceAbroad is ON. Sending generic appearance");
// // Delete existing npc attachments
// Scene.AttachmentsModule.DeleteAttachmentsFromScene(sp, false);
// // XXX: We can't just use IAvatarFactoryModule.SetAppearance() yet since it doesn't transfer attachments
// AvatarAppearance newAppearance = new AvatarAppearance(ExportedAppearance, true);
// sp.Appearance = newAppearance;
// // Rez needed npc attachments
// Scene.AttachmentsModule.RezAttachments(sp);
// IAvatarFactoryModule module = Scene.RequestModuleInterface<IAvatarFactoryModule>();
// //module.SendAppearance(sp.UUID);
// module.RequestRebake(sp, false);
// Scene.AttachmentsModule.CopyAttachments(sp, agentData);
// agentData.Appearance = sp.Appearance;
// }
// }
// foreach (AvatarAttachment a in agentData.Appearance.GetAttachments())
// m_log.DebugFormat("[XXX]: {0}-{1}", a.ItemID, a.AssetID);
// return base.UpdateAgent(reg, finalDestination, agentData, sp);
//}
public override bool TeleportHome(UUID id, IClientAPI client)
{
m_log.DebugFormat(
"[ENTITY TRANSFER MODULE]: Request to teleport {0} {1} home", client.Name, client.AgentId);
// Let's find out if this is a foreign user or a local user
IUserManagement uMan = Scene.RequestModuleInterface<IUserManagement>();
if (uMan != null && uMan.IsLocalGridUser(id))
{
// local grid user
m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: User is local");
return base.TeleportHome(id, client);
}
// Foreign user wants to go home
//
AgentCircuitData aCircuit = ((Scene)(client.Scene)).AuthenticateHandler.GetAgentCircuitData(client.CircuitCode);
if (aCircuit == null || (aCircuit != null && !aCircuit.ServiceURLs.ContainsKey("HomeURI")))
{
client.SendTeleportFailed("Your information has been lost");
m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Unable to locate agent's gateway information");
return false;
}
IUserAgentService userAgentService = new UserAgentServiceConnector(aCircuit.ServiceURLs["HomeURI"].ToString());
Vector3 position = Vector3.UnitY, lookAt = Vector3.UnitY;
GridRegion finalDestination = null;
try
{
finalDestination = userAgentService.GetHomeRegion(aCircuit.AgentID, out position, out lookAt);
}
catch (Exception e)
{
m_log.Debug("[HG ENTITY TRANSFER MODULE]: GetHomeRegion call failed ", e);
}
if (finalDestination == null)
{
client.SendTeleportFailed("Your home region could not be found");
m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent's home region not found");
return false;
}
ScenePresence sp = ((Scene)(client.Scene)).GetScenePresence(client.AgentId);
if (sp == null)
{
client.SendTeleportFailed("Internal error");
m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent not found in the scene where it is supposed to be");
return false;
}
GridRegion homeGatekeeper = MakeRegion(aCircuit);
m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: teleporting user {0} {1} home to {2} via {3}:{4}",
aCircuit.firstname, aCircuit.lastname, finalDestination.RegionName, homeGatekeeper.ServerURI, homeGatekeeper.RegionName);
DoTeleport(sp, homeGatekeeper, finalDestination, position, lookAt, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaHome));
return true;
}
/// <summary>
/// Tries to teleport agent to landmark.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="regionHandle"></param>
/// <param name="position"></param>
public override void RequestTeleportLandmark(IClientAPI remoteClient, AssetLandmark lm)
{
m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Teleporting agent via landmark to {0} region {1} position {2}",
(lm.Gatekeeper == string.Empty) ? "local" : lm.Gatekeeper, lm.RegionID, lm.Position);
if (lm.Gatekeeper == string.Empty)
{
base.RequestTeleportLandmark(remoteClient, lm);
return;
}
GridRegion info = Scene.GridService.GetRegionByUUID(UUID.Zero, lm.RegionID);
// Local region?
if (info != null)
{
Scene.RequestTeleportLocation(
remoteClient, info.RegionHandle, lm.Position,
Vector3.Zero, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaLandmark));
}
else
{
// Foreign region
GatekeeperServiceConnector gConn = new GatekeeperServiceConnector();
GridRegion gatekeeper = new GridRegion();
gatekeeper.ServerURI = lm.Gatekeeper;
string homeURI = Scene.GetAgentHomeURI(remoteClient.AgentId);
string message;
GridRegion finalDestination = gConn.GetHyperlinkRegion(gatekeeper, new UUID(lm.RegionID), remoteClient.AgentId, homeURI, out message);
if (finalDestination != null)
{
ScenePresence sp = Scene.GetScenePresence(remoteClient.AgentId);
if (sp != null)
{
if (message != null)
sp.ControllingClient.SendAgentAlertMessage(message, true);
// Validate assorted conditions
string reason = string.Empty;
if (!ValidateGenericConditions(sp, gatekeeper, finalDestination, 0, out reason))
{
sp.ControllingClient.SendTeleportFailed(reason);
return;
}
DoTeleport(
sp, gatekeeper, finalDestination, lm.Position, Vector3.UnitX,
(uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaLandmark));
}
}
else
{
remoteClient.SendTeleportFailed(message);
}
}
}
private void RemoveIncomingSceneObjectJobs(string commonIdToRemove)
{
List<JobEngine.Job> jobsToReinsert = new List<JobEngine.Job>();
int jobsRemoved = 0;
JobEngine.Job job;
while ((job = m_incomingSceneObjectEngine.RemoveNextJob()) != null)
{
if (job.CommonId != commonIdToRemove)
jobsToReinsert.Add(job);
else
jobsRemoved++;
}
m_log.DebugFormat(
"[HG ENTITY TRANSFER]: Removing {0} jobs with common ID {1} and reinserting {2} other jobs",
jobsRemoved, commonIdToRemove, jobsToReinsert.Count);
if (jobsToReinsert.Count > 0)
{
foreach (JobEngine.Job jobToReinsert in jobsToReinsert)
m_incomingSceneObjectEngine.QueueJob(jobToReinsert);
}
}
public override bool HandleIncomingSceneObject(SceneObjectGroup so, Vector3 newPosition)
{
// FIXME: We must make it so that we can use SOG.IsAttachment here. At the moment it is always null!
if (!so.IsAttachmentCheckFull())
return base.HandleIncomingSceneObject(so, newPosition);
// Equally, we can't use so.AttachedAvatar here.
if (so.OwnerID == UUID.Zero || Scene.UserManagementModule.IsLocalGridUser(so.OwnerID))
return base.HandleIncomingSceneObject(so, newPosition);
// foreign user
AgentCircuitData aCircuit = Scene.AuthenticateHandler.GetAgentCircuitData(so.OwnerID);
if (aCircuit != null)
{
if ((aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) == 0)
{
// We have already pulled the necessary attachments from the source grid.
base.HandleIncomingSceneObject(so, newPosition);
}
else
{
if (aCircuit.ServiceURLs != null && aCircuit.ServiceURLs.ContainsKey("AssetServerURI"))
{
m_incomingSceneObjectEngine.QueueJob(
string.Format("HG UUID Gather for attachment {0} for {1}", so.Name, aCircuit.Name),
() =>
{
string url = aCircuit.ServiceURLs["AssetServerURI"].ToString();
// m_log.DebugFormat(
// "[HG ENTITY TRANSFER MODULE]: Incoming attachment {0} for HG user {1} with asset service {2}",
// so.Name, so.AttachedAvatar, url);
IDictionary<UUID, sbyte> ids = new Dictionary<UUID, sbyte>();
HGUuidGatherer uuidGatherer
= new HGUuidGatherer(Scene.AssetService, url, ids);
uuidGatherer.AddForInspection(so);
while (!uuidGatherer.Complete)
{
int tickStart = Util.EnvironmentTickCount();
UUID? nextUuid = uuidGatherer.NextUuidToInspect;
uuidGatherer.GatherNext();
// m_log.DebugFormat(
// "[HG ENTITY TRANSFER]: Gathered attachment asset uuid {0} for object {1} for HG user {2} took {3} ms with asset service {4}",
// nextUuid, so.Name, so.OwnerID, Util.EnvironmentTickCountSubtract(tickStart), url);
int ticksElapsed = Util.EnvironmentTickCountSubtract(tickStart);
if (ticksElapsed > 30000)
{
m_log.WarnFormat(
"[HG ENTITY TRANSFER]: Removing incoming scene object jobs for HG user {0} as gather of {1} from {2} took {3} ms to respond (> {4} ms)",
so.OwnerID, so.Name, url, ticksElapsed, 30000);
RemoveIncomingSceneObjectJobs(so.OwnerID.ToString());
return;
}
}
// m_log.DebugFormat(
// "[HG ENTITY TRANSFER]: Fetching {0} assets for attachment {1} for HG user {2} with asset service {3}",
// ids.Count, so.Name, so.OwnerID, url);
foreach (KeyValuePair<UUID, sbyte> kvp in ids)
{
int tickStart = Util.EnvironmentTickCount();
uuidGatherer.FetchAsset(kvp.Key);
int ticksElapsed = Util.EnvironmentTickCountSubtract(tickStart);
if (ticksElapsed > 30000)
{
m_log.WarnFormat(
"[HG ENTITY TRANSFER]: Removing incoming scene object jobs for HG user {0} as fetch of {1} from {2} took {3} ms to respond (> {4} ms)",
so.OwnerID, kvp.Key, url, ticksElapsed, 30000);
RemoveIncomingSceneObjectJobs(so.OwnerID.ToString());
return;
}
}
base.HandleIncomingSceneObject(so, newPosition);
// m_log.DebugFormat(
// "[HG ENTITY TRANSFER MODULE]: Completed incoming attachment {0} for HG user {1} with asset server {2}",
// so.Name, so.OwnerID, url);
},
so.OwnerID.ToString());
}
}
}
return true;
}
#endregion
#region IUserAgentVerificationModule
public bool VerifyClient(AgentCircuitData aCircuit, string token)
{
if (aCircuit.ServiceURLs.ContainsKey("HomeURI"))
{
string url = aCircuit.ServiceURLs["HomeURI"].ToString();
IUserAgentService security = new UserAgentServiceConnector(url);
return security.VerifyClient(aCircuit.SessionID, token);
}
else
{
m_log.DebugFormat(
"[HG ENTITY TRANSFER MODULE]: Agent {0} {1} does not have a HomeURI OH NO!",
aCircuit.firstname, aCircuit.lastname);
}
return false;
}
void OnConnectionClosed(IClientAPI obj)
{
if (obj.SceneAgent.IsChildAgent)
return;
// Let's find out if this is a foreign user or a local user
IUserManagement uMan = Scene.RequestModuleInterface<IUserManagement>();
// UserAccount account = Scene.UserAccountService.GetUserAccount(Scene.RegionInfo.ScopeID, obj.AgentId);
if (uMan != null && uMan.IsLocalGridUser(obj.AgentId))
{
// local grid user
m_UAS.LogoutAgent(obj.AgentId, obj.SessionId);
return;
}
AgentCircuitData aCircuit = ((Scene)(obj.Scene)).AuthenticateHandler.GetAgentCircuitData(obj.CircuitCode);
if (aCircuit != null && aCircuit.ServiceURLs != null && aCircuit.ServiceURLs.ContainsKey("HomeURI"))
{
string url = aCircuit.ServiceURLs["HomeURI"].ToString();
IUserAgentService security = new UserAgentServiceConnector(url);
security.LogoutAgent(obj.AgentId, obj.SessionId);
//m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Sent logout call to UserAgentService @ {0}", url);
}
else
{
m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: HomeURI not found for agent {0} logout", obj.AgentId);
}
}
#endregion
private GridRegion MakeRegion(AgentCircuitData aCircuit)
{
GridRegion region = new GridRegion();
Uri uri = null;
if (!aCircuit.ServiceURLs.ContainsKey("HomeURI") ||
(aCircuit.ServiceURLs.ContainsKey("HomeURI") && !Uri.TryCreate(aCircuit.ServiceURLs["HomeURI"].ToString(), UriKind.Absolute, out uri)))
return null;
region.ExternalHostName = uri.Host;
region.HttpPort = (uint)uri.Port;
region.ServerURI = aCircuit.ServiceURLs["HomeURI"].ToString();
region.RegionName = string.Empty;
region.InternalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), (int)0);
return region;
}
}
}
| |
//! \file ImageDREF.cs
//! \date 2018 Jan 22
//! \brief PSB-referenced compound image.
//
// Copyright (C) 2018 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
// not exactly related to Emote engine, but defined in Emote namespace for convenience
namespace GameRes.Formats.Emote
{
internal class DrefMetaData : ImageMetaData
{
public IEnumerable<Tuple<string, string>> Layers;
}
[Export(typeof(ImageFormat))]
public class DrefFormat : ImageFormat
{
public override string Tag { get { return "DREF"; } }
public override string Description { get { return "DPAK-referenced compound image"; } }
public override uint Signature { get { return 0x0070FEFF; } }
public DrefFormat ()
{
// 'psb:' string with possible byte-order-mark prepended
Signatures = new uint[] { 0x0070FEFF, 0x70BFBBEF, 0x3A627370, 0x00730070 };
}
static readonly Regex PathRe = new Regex (@"^psb://([^/]+)/(.+)");
public override ImageMetaData ReadMetaData (IBinaryStream file)
{
if (!file.Name.HasExtension (".dref"))
return null;
var dir = VFS.GetDirectoryName (file.Name);
using (var input = new StreamReader (file.AsStream, Encoding.Unicode, true, 1024, true))
{
var layers = new List<Tuple<string, string>>();
string line;
while ((line = input.ReadLine()) != null)
{
var match = PathRe.Match (line);
if (!match.Success)
return null;
var pak_name = match.Groups[1].Value;
if (!VFS.FileExists (pak_name))
return null;
pak_name = VFS.CombinePath (dir, pak_name);
layers.Add (Tuple.Create (pak_name, match.Groups[2].Value));
}
if (0 == layers.Count)
return null;
return new DrefMetaData { Layers = layers, BPP = 32 };
}
}
static readonly ResourceInstance<ArchiveFormat> Psb = new ResourceInstance<ArchiveFormat> ("PSB/EMOTE");
public override ImageData Read (IBinaryStream file, ImageMetaData info)
{
var meta = (DrefMetaData)info;
ArcFile dpak = null;
try
{
int layers_count = meta.Layers.Count();
WriteableBitmap canvas = null;
foreach (var path in meta.Layers)
{
if (null == dpak || dpak.File.Name != path.Item1)
{
if (dpak != null)
{
dpak.Dispose();
dpak = null;
}
var view = VFS.OpenView (path.Item1);
try
{
dpak = Psb.Value.TryOpen (view);
if (null == dpak)
throw new InvalidFormatException ();
}
catch
{
view.Dispose();
throw;
}
}
var entry = dpak.Dir.FirstOrDefault (e => e.Name == path.Item2);
if (null == entry)
throw new InvalidFormatException();
using (var decoder = dpak.OpenImage (entry))
{
if (1 == layers_count)
return decoder.Image;
if (null == canvas)
{
canvas = new WriteableBitmap (decoder.Image.Bitmap);
meta.Width = decoder.Info.Width;
meta.Height = decoder.Info.Height;
meta.OffsetX = decoder.Info.OffsetX;
meta.OffsetY = decoder.Info.OffsetY;
}
else
{
BlendLayer (canvas, decoder.Image);
}
}
}
if (null == canvas)
throw new InvalidFormatException();
canvas.Freeze();
return new ImageData (canvas, meta);
}
finally
{
if (dpak != null)
dpak.Dispose();
}
}
void BlendLayer (WriteableBitmap canvas, ImageData layer)
{
BitmapSource source = layer.Bitmap;
if (source.Format.BitsPerPixel != 32)
source = new FormatConvertedBitmap (source, PixelFormats.Bgra32, null, 0);
// determine coordinates of the intersection of layer and canvas
var src_rect = new Int32Rect (0, 0, source.PixelWidth, source.PixelHeight);
if (layer.OffsetX < 0)
{
src_rect.X = -layer.OffsetX;
src_rect.Width += layer.OffsetX;
}
if (layer.OffsetY < 0)
{
src_rect.Y = -layer.OffsetY;
src_rect.Height += layer.OffsetY;
}
if (!src_rect.HasArea)
return;
var layer_rect = new Rectangle (layer.OffsetX, layer.OffsetY, source.PixelWidth, source.PixelHeight);
var canvas_rect = new Rectangle (0, 0, canvas.PixelWidth, canvas.PixelHeight);
layer_rect.Intersect (canvas_rect);
if (layer_rect.Width <= 0 || layer_rect.Height <= 0)
return;
// copy out layer area
int src_stride = src_rect.Width * 4;
var pixels = new byte[src_stride * src_rect.Height];
source.CopyPixels (src_rect, pixels, src_stride, 0);
// perform blending within established coordinates
int pixel_size = (canvas.Format.BitsPerPixel + 7) / 8;
int canvas_stride = canvas.BackBufferStride;
int dst_row = layer_rect.Y * canvas_stride + layer_rect.X * pixel_size;
canvas.Lock();
unsafe
{
byte* buffer = (byte*)canvas.BackBuffer;
for (int src = 0; src < pixels.Length; src += src_stride)
{
byte* dst = buffer+dst_row;
for (int x = 0; x < src_stride; x += 4)
{
byte src_alpha = pixels[src+x+3];
if (0xFF == src_alpha)
{
for (int i = 0; i < pixel_size; ++i)
dst[i] = pixels[src+x+i];
}
else if (src_alpha > 0)
{
dst[0] = (byte)((pixels[src+x+0] * src_alpha + dst[0] * (0xFF - src_alpha)) / 0xFF);
dst[1] = (byte)((pixels[src+x+1] * src_alpha + dst[1] * (0xFF - src_alpha)) / 0xFF);
dst[2] = (byte)((pixels[src+x+2] * src_alpha + dst[2] * (0xFF - src_alpha)) / 0xFF);
if (pixel_size > 3)
dst[3] = (byte)Math.Max (src_alpha, dst[3]);
}
dst += pixel_size;
}
dst_row += canvas_stride;
}
}
canvas.Unlock();
}
public override void Write (Stream file, ImageData image)
{
throw new System.NotImplementedException ("DrefFormat.Write not implemented");
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XmlILConstructAnalyzer.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Xml.Xsl.Qil;
namespace System.Xml.Xsl.IlGen {
/// <summary>
/// Until run-time, the exact xml state cannot always be determined. However, the construction analyzer
/// keeps track of the set of possible xml states at each node in order to reduce run-time state management.
/// </summary>
internal enum PossibleXmlStates {
None = 0,
WithinSequence,
EnumAttrs,
WithinContent,
WithinAttr,
WithinComment,
WithinPI,
Any,
};
/// <summary>
/// 1. Some expressions are lazily materialized by creating an iterator over the results (ex. LiteralString, Content).
/// 2. Some expressions are incrementally constructed by a Writer (ex. ElementCtor, XsltCopy).
/// 3. Some expressions can be iterated or written (ex. List).
/// </summary>
internal enum XmlILConstructMethod {
Iterator, // Construct iterator over expression's results
Writer, // Construct expression through calls to Writer
WriterThenIterator, // Construct expression through calls to caching Writer; then construct iterator over cached results
IteratorThenWriter, // Iterate over expression's results and send each item to Writer
};
/// <summary>
/// Every node is annotated with information about how it will be constructed by ILGen.
/// </summary>
internal class XmlILConstructInfo : IQilAnnotation {
private QilNodeType nodeType;
private PossibleXmlStates xstatesInitial, xstatesFinal, xstatesBeginLoop, xstatesEndLoop;
private bool isNmspInScope, mightHaveNmsp, mightHaveAttrs, mightHaveDupAttrs, mightHaveNmspAfterAttrs;
private XmlILConstructMethod constrMeth;
private XmlILConstructInfo parentInfo;
private ArrayList callersInfo;
private bool isReadOnly;
private static volatile XmlILConstructInfo Default;
/// <summary>
/// Get ConstructInfo annotation for the specified node. Lazily create if necessary.
/// </summary>
public static XmlILConstructInfo Read(QilNode nd) {
XmlILAnnotation ann = nd.Annotation as XmlILAnnotation;
XmlILConstructInfo constrInfo = (ann != null) ? ann.ConstructInfo : null;
if (constrInfo == null) {
if (Default == null) {
constrInfo = new XmlILConstructInfo(QilNodeType.Unknown);
constrInfo.isReadOnly = true;
Default = constrInfo;
}
else {
constrInfo = Default;
}
}
return constrInfo;
}
/// <summary>
/// Create and initialize XmlILConstructInfo annotation for the specified node.
/// </summary>
public static XmlILConstructInfo Write(QilNode nd) {
XmlILAnnotation ann = XmlILAnnotation.Write(nd);
XmlILConstructInfo constrInfo = ann.ConstructInfo;
if (constrInfo == null || constrInfo.isReadOnly) {
constrInfo = new XmlILConstructInfo(nd.NodeType);
ann.ConstructInfo = constrInfo;
}
return constrInfo;
}
/// <summary>
/// Default to worst possible construction information.
/// </summary>
private XmlILConstructInfo(QilNodeType nodeType) {
this.nodeType = nodeType;
this.xstatesInitial = this.xstatesFinal = PossibleXmlStates.Any;
this.xstatesBeginLoop = this.xstatesEndLoop = PossibleXmlStates.None;
this.isNmspInScope = false;
this.mightHaveNmsp = true;
this.mightHaveAttrs = true;
this.mightHaveDupAttrs = true;
this.mightHaveNmspAfterAttrs = true;
this.constrMeth = XmlILConstructMethod.Iterator;
this.parentInfo = null;
}
/// <summary>
/// Xml states that are possible as construction of the annotated expression begins.
/// </summary>
public PossibleXmlStates InitialStates {
get { return this.xstatesInitial; }
set {
Debug.Assert(!this.isReadOnly, "This XmlILConstructInfo instance is read-only.");
this.xstatesInitial = value;
}
}
/// <summary>
/// Xml states that are possible as construction of the annotated expression ends.
/// </summary>
public PossibleXmlStates FinalStates {
get { return this.xstatesFinal; }
set {
Debug.Assert(!this.isReadOnly, "This XmlILConstructInfo instance is read-only.");
this.xstatesFinal = value;
}
}
/// <summary>
/// Xml states that are possible as looping begins. This is None if the annotated expression does not loop.
/// </summary>
public PossibleXmlStates BeginLoopStates {
//get { return this.xstatesBeginLoop; }
set {
Debug.Assert(!this.isReadOnly, "This XmlILConstructInfo instance is read-only.");
this.xstatesBeginLoop = value;
}
}
/// <summary>
/// Xml states that are possible as looping ends. This is None if the annotated expression does not loop.
/// </summary>
public PossibleXmlStates EndLoopStates {
//get { return this.xstatesEndLoop; }
set {
Debug.Assert(!this.isReadOnly, "This XmlILConstructInfo instance is read-only.");
this.xstatesEndLoop = value;
}
}
/// <summary>
/// Return the method that will be used to construct the annotated node.
/// </summary>
public XmlILConstructMethod ConstructMethod {
get { return this.constrMeth; }
set {
Debug.Assert(!this.isReadOnly, "This XmlILConstructInfo instance is read-only.");
this.constrMeth = value;
}
}
/// <summary>
/// Returns true if construction method is Writer or WriterThenIterator.
/// </summary>
public bool PushToWriterFirst {
get { return this.constrMeth == XmlILConstructMethod.Writer || this.constrMeth == XmlILConstructMethod.WriterThenIterator; }
set {
Debug.Assert(!this.isReadOnly, "This XmlILConstructInfo instance is read-only.");
Debug.Assert(value);
switch (this.constrMeth) {
case XmlILConstructMethod.Iterator:
this.constrMeth = XmlILConstructMethod.WriterThenIterator;
break;
case XmlILConstructMethod.IteratorThenWriter:
this.constrMeth = XmlILConstructMethod.Writer;
break;
}
}
}
/// <summary>
/// Returns true if construction method is Writer or IteratorThenWriter.
/// </summary>
public bool PushToWriterLast {
get { return this.constrMeth == XmlILConstructMethod.Writer || this.constrMeth == XmlILConstructMethod.IteratorThenWriter; }
set {
Debug.Assert(!this.isReadOnly, "This XmlILConstructInfo instance is read-only.");
Debug.Assert(value);
switch (this.constrMeth) {
case XmlILConstructMethod.Iterator:
this.constrMeth = XmlILConstructMethod.IteratorThenWriter;
break;
case XmlILConstructMethod.WriterThenIterator:
this.constrMeth = XmlILConstructMethod.Writer;
break;
}
}
}
/// <summary>
/// Returns true if construction method is IteratorThenWriter or Iterator.
/// </summary>
public bool PullFromIteratorFirst {
get { return this.constrMeth == XmlILConstructMethod.IteratorThenWriter || this.constrMeth == XmlILConstructMethod.Iterator; }
set {
Debug.Assert(!this.isReadOnly, "This XmlILConstructInfo instance is read-only.");
Debug.Assert(value);
switch (this.constrMeth) {
case XmlILConstructMethod.Writer:
this.constrMeth = XmlILConstructMethod.IteratorThenWriter;
break;
case XmlILConstructMethod.WriterThenIterator:
this.constrMeth = XmlILConstructMethod.Iterator;
break;
}
}
}
/// <summary>
/// If the annotated expression will be constructed as the content of another constructor, and this can be
/// guaranteed at compile-time, then this property will be the non-null XmlILConstructInfo of that constructor.
/// </summary>
public XmlILConstructInfo ParentInfo {
//get { return this.parentInfo; }
set {
Debug.Assert(!this.isReadOnly, "This XmlILConstructInfo instance is read-only.");
this.parentInfo = value;
}
}
/// <summary>
/// If the annotated expression will be constructed as the content of an ElementCtor, and this can be
/// guaranteed at compile-time, then this property will be the non-null XmlILConstructInfo of that constructor.
/// </summary>
public XmlILConstructInfo ParentElementInfo {
get {
if (this.parentInfo != null && this.parentInfo.nodeType == QilNodeType.ElementCtor)
return this.parentInfo;
return null;
}
}
/// <summary>
/// This annotation is only applicable to NamespaceDecl nodes and to ElementCtor and AttributeCtor nodes with
/// literal names. If the namespace is already guaranteed to be constructed, then this property will be true.
/// </summary>
public bool IsNamespaceInScope {
get { return this.isNmspInScope; }
set {
Debug.Assert(!this.isReadOnly, "This XmlILConstructInfo instance is read-only.");
this.isNmspInScope = value;
}
}
/// <summary>
/// This annotation is only applicable to ElementCtor nodes. If the element might have local namespaces
/// added to it at runtime, then this property will be true.
/// </summary>
public bool MightHaveNamespaces {
get { return this.mightHaveNmsp; }
set {
Debug.Assert(!this.isReadOnly, "This XmlILConstructInfo instance is read-only.");
this.mightHaveNmsp = value;
}
}
/// <summary>
/// This annotation is only applicable to ElementCtor nodes. If the element might have namespaces added to it after
/// attributes have already been added, then this property will be true.
/// </summary>
public bool MightHaveNamespacesAfterAttributes {
get { return this.mightHaveNmspAfterAttrs; }
set {
Debug.Assert(!this.isReadOnly, "This XmlILConstructInfo instance is read-only.");
this.mightHaveNmspAfterAttrs = value;
}
}
/// <summary>
/// This annotation is only applicable to ElementCtor nodes. If the element might have attributes added to it at
/// runtime, then this property will be true.
/// </summary>
public bool MightHaveAttributes {
get { return this.mightHaveAttrs; }
set {
Debug.Assert(!this.isReadOnly, "This XmlILConstructInfo instance is read-only.");
this.mightHaveAttrs = value;
}
}
/// <summary>
/// This annotation is only applicable to ElementCtor nodes. If the element might have multiple attributes added to
/// it with the same name, then this property will be true.
/// </summary>
public bool MightHaveDuplicateAttributes {
get { return this.mightHaveDupAttrs; }
set {
Debug.Assert(!this.isReadOnly, "This XmlILConstructInfo instance is read-only.");
this.mightHaveDupAttrs = value;
}
}
/// <summary>
/// This annotation is only applicable to Function nodes. It contains a list of XmlILConstructInfo annontations
/// for all QilInvoke nodes which call the annotated function.
/// </summary>
public ArrayList CallersInfo {
get {
if (this.callersInfo == null)
this.callersInfo = new ArrayList();
return this.callersInfo;
}
}
/// <summary>
/// Return name of this annotation.
/// </summary>
public virtual string Name {
get { return "ConstructInfo"; }
}
/// <summary>
/// Return string representation of this annotation.
/// </summary>
public override string ToString() {
string s = "";
if (this.constrMeth != XmlILConstructMethod.Iterator) {
s += this.constrMeth.ToString();
s += ", " + this.xstatesInitial;
if (this.xstatesBeginLoop != PossibleXmlStates.None) {
s += " => " + this.xstatesBeginLoop.ToString() + " => " + this.xstatesEndLoop.ToString();
}
s += " => " + this.xstatesFinal;
if (!MightHaveAttributes)
s += ", NoAttrs";
if (!MightHaveDuplicateAttributes)
s += ", NoDupAttrs";
if (!MightHaveNamespaces)
s += ", NoNmsp";
if (!MightHaveNamespacesAfterAttributes)
s += ", NoNmspAfterAttrs";
}
return s;
}
}
/// <summary>
/// Scans the content of an constructor and tries to minimize the number of well-formed checks that will have
/// to be made at runtime when constructing content.
/// </summary>
internal class XmlILStateAnalyzer {
protected XmlILConstructInfo parentInfo;
protected QilFactory fac;
protected PossibleXmlStates xstates;
protected bool withinElem;
/// <summary>
/// Constructor.
/// </summary>
public XmlILStateAnalyzer(QilFactory fac) {
this.fac = fac;
}
/// <summary>
/// Perform analysis on the specified constructor and its content. Return the ndContent that was passed in,
/// or a replacement.
/// </summary>
public virtual QilNode Analyze(QilNode ndConstr, QilNode ndContent) {
if (ndConstr == null) {
// Root expression is analyzed
this.parentInfo = null;
this.xstates = PossibleXmlStates.WithinSequence;
this.withinElem = false;
Debug.Assert(ndContent != null);
ndContent = AnalyzeContent(ndContent);
}
else {
this.parentInfo = XmlILConstructInfo.Write(ndConstr);
if (ndConstr.NodeType == QilNodeType.Function) {
// Results of function should be pushed to writer
this.parentInfo.ConstructMethod = XmlILConstructMethod.Writer;
// Start with PossibleXmlStates.None and then add additional possible starting states
PossibleXmlStates xstates = PossibleXmlStates.None;
foreach (XmlILConstructInfo infoCaller in this.parentInfo.CallersInfo) {
if (xstates == PossibleXmlStates.None) {
xstates = infoCaller.InitialStates;
}
else if (xstates != infoCaller.InitialStates) {
xstates = PossibleXmlStates.Any;
}
// Function's results are pushed to Writer, so make sure that Invoke nodes' construct methods match
infoCaller.PushToWriterFirst = true;
}
this.parentInfo.InitialStates = xstates;
}
else {
// Build a standalone tree, with this constructor as its root
if (ndConstr.NodeType != QilNodeType.Choice)
this.parentInfo.InitialStates = this.parentInfo.FinalStates = PossibleXmlStates.WithinSequence;
// Don't stream Rtf; fully cache the Rtf and copy it into any containing tree in order to simplify XmlILVisitor.VisitRtfCtor
if (ndConstr.NodeType != QilNodeType.RtfCtor)
this.parentInfo.ConstructMethod = XmlILConstructMethod.WriterThenIterator;
}
// Set withinElem = true if analyzing element content
this.withinElem = (ndConstr.NodeType == QilNodeType.ElementCtor);
switch (ndConstr.NodeType) {
case QilNodeType.DocumentCtor: this.xstates = PossibleXmlStates.WithinContent; break;
case QilNodeType.ElementCtor: this.xstates = PossibleXmlStates.EnumAttrs; break;
case QilNodeType.AttributeCtor: this.xstates = PossibleXmlStates.WithinAttr; break;
case QilNodeType.NamespaceDecl: Debug.Assert(ndContent == null); break;
case QilNodeType.TextCtor: Debug.Assert(ndContent == null); break;
case QilNodeType.RawTextCtor: Debug.Assert(ndContent == null); break;
case QilNodeType.CommentCtor: this.xstates = PossibleXmlStates.WithinComment; break;
case QilNodeType.PICtor: this.xstates = PossibleXmlStates.WithinPI; break;
case QilNodeType.XsltCopy: this.xstates = PossibleXmlStates.Any; break;
case QilNodeType.XsltCopyOf: Debug.Assert(ndContent == null); break;
case QilNodeType.Function: this.xstates = this.parentInfo.InitialStates; break;
case QilNodeType.RtfCtor: this.xstates = PossibleXmlStates.WithinContent; break;
case QilNodeType.Choice: this.xstates = PossibleXmlStates.Any; break;
default: Debug.Assert(false, ndConstr.NodeType + " is not handled by XmlILStateAnalyzer."); break;
}
if (ndContent != null)
ndContent = AnalyzeContent(ndContent);
if (ndConstr.NodeType == QilNodeType.Choice)
AnalyzeChoice(ndConstr as QilChoice, this.parentInfo);
// Since Function will never be another node's content, set its final states here
if (ndConstr.NodeType == QilNodeType.Function)
this.parentInfo.FinalStates = this.xstates;
}
return ndContent;
}
/// <summary>
/// Recursively analyze content. Return "nd" or a replacement for it.
/// </summary>
protected virtual QilNode AnalyzeContent(QilNode nd) {
XmlILConstructInfo info;
QilNode ndChild;
// Handle special node-types that are replaced
switch (nd.NodeType) {
case QilNodeType.For:
case QilNodeType.Let:
case QilNodeType.Parameter:
// Iterator references are shared and cannot be annotated directly with ConstructInfo,
// so wrap them with Nop node.
nd = this.fac.Nop(nd);
break;
}
// Get node's ConstructInfo annotation
info = XmlILConstructInfo.Write(nd);
// Set node's guaranteed parent constructor
info.ParentInfo = this.parentInfo;
// Construct all content using the Writer
info.PushToWriterLast = true;
// Set states that are possible before expression is constructed
info.InitialStates = this.xstates;
switch (nd.NodeType) {
case QilNodeType.Loop: AnalyzeLoop(nd as QilLoop, info); break;
case QilNodeType.Sequence: AnalyzeSequence(nd as QilList, info); break;
case QilNodeType.Conditional: AnalyzeConditional(nd as QilTernary, info); break;
case QilNodeType.Choice: AnalyzeChoice(nd as QilChoice, info); break;
case QilNodeType.Error:
case QilNodeType.Warning:
// Ensure that construct method is Writer
info.ConstructMethod = XmlILConstructMethod.Writer;
break;
case QilNodeType.Nop:
ndChild = (nd as QilUnary).Child;
switch (ndChild.NodeType) {
case QilNodeType.For:
case QilNodeType.Let:
case QilNodeType.Parameter:
// Copy iterator items as content
AnalyzeCopy(nd, info);
break;
default:
// Ensure that construct method is Writer and recursively analyze content
info.ConstructMethod = XmlILConstructMethod.Writer;
AnalyzeContent(ndChild);
break;
}
break;
default:
AnalyzeCopy(nd, info);
break;
}
// Set states that are possible after expression is constructed
info.FinalStates = this.xstates;
return nd;
}
/// <summary>
/// Analyze loop.
/// </summary>
protected virtual void AnalyzeLoop(QilLoop ndLoop, XmlILConstructInfo info) {
XmlQueryType typ = ndLoop.XmlType;
// Ensure that construct method is Writer
info.ConstructMethod = XmlILConstructMethod.Writer;
if (!typ.IsSingleton)
StartLoop(typ, info);
// Body constructs content
ndLoop.Body = AnalyzeContent(ndLoop.Body);
if (!typ.IsSingleton)
EndLoop(typ, info);
}
/// <summary>
/// Analyze list.
/// </summary>
protected virtual void AnalyzeSequence(QilList ndSeq, XmlILConstructInfo info) {
// Ensure that construct method is Writer
info.ConstructMethod = XmlILConstructMethod.Writer;
// Analyze each item in the list
for (int idx = 0; idx < ndSeq.Count; idx++)
ndSeq[idx] = AnalyzeContent(ndSeq[idx]);
}
/// <summary>
/// Analyze conditional.
/// </summary>
protected virtual void AnalyzeConditional(QilTernary ndCond, XmlILConstructInfo info) {
PossibleXmlStates xstatesTrue;
// Ensure that construct method is Writer
info.ConstructMethod = XmlILConstructMethod.Writer;
// Visit true branch; save resulting states
ndCond.Center = AnalyzeContent(ndCond.Center);
xstatesTrue = this.xstates;
// Restore starting states and visit false branch
this.xstates = info.InitialStates;
ndCond.Right = AnalyzeContent(ndCond.Right);
// Conditional ending states consist of combination of true and false branch states
if (xstatesTrue != this.xstates)
this.xstates = PossibleXmlStates.Any;
}
/// <summary>
/// Analyze choice.
/// </summary>
protected virtual void AnalyzeChoice(QilChoice ndChoice, XmlILConstructInfo info) {
PossibleXmlStates xstatesChoice;
int idx;
// Visit default branch; save resulting states
idx = ndChoice.Branches.Count - 1;
ndChoice.Branches[idx] = AnalyzeContent(ndChoice.Branches[idx]);
xstatesChoice = this.xstates;
// Visit all other branches
while (--idx >= 0) {
// Restore starting states and visit the next branch
this.xstates = info.InitialStates;
ndChoice.Branches[idx] = AnalyzeContent(ndChoice.Branches[idx]);
// Choice ending states consist of combination of all branch states
if (xstatesChoice != this.xstates)
xstatesChoice = PossibleXmlStates.Any;
}
this.xstates = xstatesChoice;
}
/// <summary>
/// Analyze copying items.
/// </summary>
protected virtual void AnalyzeCopy(QilNode ndCopy, XmlILConstructInfo info) {
XmlQueryType typ = ndCopy.XmlType;
// Copying item(s) to output involves looping if there is not exactly one item in the sequence
if (!typ.IsSingleton)
StartLoop(typ, info);
// Determine state transitions that may take place
if (MaybeContent(typ)) {
if (MaybeAttrNmsp(typ)) {
// Node might be Attr/Nmsp or non-Attr/Nmsp, so transition from EnumAttrs to WithinContent *may* occur
if (this.xstates == PossibleXmlStates.EnumAttrs)
this.xstates = PossibleXmlStates.Any;
}
else {
// Node is guaranteed not to be Attr/Nmsp, so transition to WithinContent will occur if starting
// state is EnumAttrs or if constructing within an element (guaranteed to be in EnumAttrs or WithinContent state)
if (this.xstates == PossibleXmlStates.EnumAttrs || this.withinElem)
this.xstates = PossibleXmlStates.WithinContent;
}
}
if (!typ.IsSingleton)
EndLoop(typ, info);
}
/// <summary>
/// Calculate starting xml states that will result when iterating over and constructing an expression of the specified type.
/// </summary>
private void StartLoop(XmlQueryType typ, XmlILConstructInfo info) {
Debug.Assert(!typ.IsSingleton);
// This is tricky, because the looping introduces a feedback loop:
// 1. Because loops may be executed many times, the beginning set of states must include the ending set of states.
// 2. Because loops may be executed 0 times, the final set of states after all looping is complete must include
// the initial set of states.
//
// +-- states-initial
// | |
// | states-begin-loop <--+
// | | |
// | +--------------+ |
// | | Construction | |
// | +--------------+ |
// | | |
// | states-end-loop ----+
// | |
// +--> states-final
// Save starting loop states
info.BeginLoopStates = this.xstates;
if (typ.MaybeMany) {
// If transition might occur from EnumAttrs to WithinContent, then states-end might be WithinContent, which
// means states-begin needs to also include WithinContent.
if (this.xstates == PossibleXmlStates.EnumAttrs && MaybeContent(typ))
info.BeginLoopStates = this.xstates = PossibleXmlStates.Any;
}
}
/// <summary>
/// Calculate ending xml states that will result when iterating over and constructing an expression of the specified type.
/// </summary>
private void EndLoop(XmlQueryType typ, XmlILConstructInfo info) {
Debug.Assert(!typ.IsSingleton);
// Save ending loop states
info.EndLoopStates = this.xstates;
// If it's possible to loop zero times, then states-final needs to include states-initial
if (typ.MaybeEmpty && info.InitialStates != this.xstates)
this.xstates = PossibleXmlStates.Any;
}
/// <summary>
/// Return true if an instance of the specified type might be an attribute or a namespace node.
/// </summary>
private bool MaybeAttrNmsp(XmlQueryType typ) {
return (typ.NodeKinds & (XmlNodeKindFlags.Attribute | XmlNodeKindFlags.Namespace)) != XmlNodeKindFlags.None;
}
/// <summary>
/// Return true if an instance of the specified type might be a non-empty content type (attr/nsmp don't count).
/// </summary>
private bool MaybeContent(XmlQueryType typ) {
return !typ.IsNode || (typ.NodeKinds & ~(XmlNodeKindFlags.Attribute | XmlNodeKindFlags.Namespace)) != XmlNodeKindFlags.None;
}
}
/// <summary>
/// Scans the content of an ElementCtor and tries to minimize the number of well-formed checks that will have
/// to be made at runtime when constructing content.
/// </summary>
internal class XmlILElementAnalyzer : XmlILStateAnalyzer {
private NameTable attrNames = new NameTable();
private ArrayList dupAttrs = new ArrayList();
/// <summary>
/// Constructor.
/// </summary>
public XmlILElementAnalyzer(QilFactory fac) : base(fac) {
}
/// <summary>
/// Analyze the content argument of the ElementCtor. Try to eliminate as many runtime checks as possible,
/// both for the ElementCtor and for content constructors.
/// </summary>
public override QilNode Analyze(QilNode ndElem, QilNode ndContent) {
Debug.Assert(ndElem.NodeType == QilNodeType.ElementCtor);
this.parentInfo = XmlILConstructInfo.Write(ndElem);
// Start by assuming that these properties are false (they default to true, but analyzer might be able to
// prove they are really false).
this.parentInfo.MightHaveNamespacesAfterAttributes = false;
this.parentInfo.MightHaveAttributes = false;
this.parentInfo.MightHaveDuplicateAttributes = false;
// The element's namespace might need to be declared
this.parentInfo.MightHaveNamespaces = !this.parentInfo.IsNamespaceInScope;
// Clear list of duplicate attributes
this.dupAttrs.Clear();
return base.Analyze(ndElem, ndContent);
}
/// <summary>
/// Analyze loop.
/// </summary>
protected override void AnalyzeLoop(QilLoop ndLoop, XmlILConstructInfo info) {
// Constructing attributes/namespaces in a loop can cause duplicates, namespaces after attributes, etc.
if (ndLoop.XmlType.MaybeMany)
CheckAttributeNamespaceConstruct(ndLoop.XmlType);
base.AnalyzeLoop(ndLoop, info);
}
/// <summary>
/// Analyze copying items.
/// </summary>
protected override void AnalyzeCopy(QilNode ndCopy, XmlILConstructInfo info) {
if (ndCopy.NodeType == QilNodeType.AttributeCtor) {
AnalyzeAttributeCtor(ndCopy as QilBinary, info);
}
else {
CheckAttributeNamespaceConstruct(ndCopy.XmlType);
}
base.AnalyzeCopy(ndCopy, info);
}
/// <summary>
/// Analyze attribute constructor.
/// </summary>
private void AnalyzeAttributeCtor(QilBinary ndAttr, XmlILConstructInfo info) {
if (ndAttr.Left.NodeType == QilNodeType.LiteralQName) {
QilName ndName = ndAttr.Left as QilName;
XmlQualifiedName qname;
int idx;
// This attribute might be constructed on the parent element
this.parentInfo.MightHaveAttributes = true;
// Check to see whether this attribute is a duplicate of a previous attribute
if (!this.parentInfo.MightHaveDuplicateAttributes) {
qname = new XmlQualifiedName(this.attrNames.Add(ndName.LocalName), this.attrNames.Add(ndName.NamespaceUri));
for (idx = 0; idx < this.dupAttrs.Count; idx++) {
XmlQualifiedName qnameDup = (XmlQualifiedName) this.dupAttrs[idx];
if ((object) qnameDup.Name == (object) qname.Name && (object) qnameDup.Namespace == (object) qname.Namespace) {
// A duplicate attribute has been encountered
this.parentInfo.MightHaveDuplicateAttributes = true;
}
}
if (idx >= this.dupAttrs.Count) {
// This is not a duplicate attribute, so add it to the set
this.dupAttrs.Add(qname);
}
}
// The attribute's namespace might need to be declared
if (!info.IsNamespaceInScope)
this.parentInfo.MightHaveNamespaces = true;
}
else {
// Attribute prefix and namespace are not known at compile-time
CheckAttributeNamespaceConstruct(ndAttr.XmlType);
}
}
/// <summary>
/// If type might contain attributes or namespaces, set appropriate parent element flags.
/// </summary>
private void CheckAttributeNamespaceConstruct(XmlQueryType typ) {
// If content might contain attributes,
if ((typ.NodeKinds & XmlNodeKindFlags.Attribute) != XmlNodeKindFlags.None) {
// Mark element as possibly having attributes and duplicate attributes (since we don't know the names)
this.parentInfo.MightHaveAttributes = true;
this.parentInfo.MightHaveDuplicateAttributes = true;
// Attribute namespaces might be declared
this.parentInfo.MightHaveNamespaces = true;
}
// If content might contain namespaces,
if ((typ.NodeKinds & XmlNodeKindFlags.Namespace) != XmlNodeKindFlags.None) {
// Then element might have namespaces,
this.parentInfo.MightHaveNamespaces = true;
// If attributes might already have been constructed,
if (this.parentInfo.MightHaveAttributes) {
// Then attributes might precede namespace declarations
this.parentInfo.MightHaveNamespacesAfterAttributes = true;
}
}
}
}
/// <summary>
/// Scans constructed content, looking for redundant namespace declarations. If any are found, then they are marked
/// and removed later.
/// </summary>
internal class XmlILNamespaceAnalyzer {
private XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
private bool addInScopeNmsp;
private int cntNmsp;
/// <summary>
/// Perform scan.
/// </summary>
public void Analyze(QilNode nd, bool defaultNmspInScope) {
this.addInScopeNmsp = false;
this.cntNmsp = 0;
// If xmlns="" is in-scope, push it onto the namespace stack
if (defaultNmspInScope) {
this.nsmgr.PushScope();
this.nsmgr.AddNamespace(string.Empty, string.Empty);
this.cntNmsp++;
}
AnalyzeContent(nd);
if (defaultNmspInScope)
this.nsmgr.PopScope();
}
/// <summary>
/// Recursively analyze content. Return "nd" or a replacement for it.
/// </summary>
private void AnalyzeContent(QilNode nd) {
int cntNmspSave;
switch (nd.NodeType) {
case QilNodeType.Loop:
this.addInScopeNmsp = false;
AnalyzeContent((nd as QilLoop).Body);
break;
case QilNodeType.Sequence:
foreach (QilNode ndContent in nd)
AnalyzeContent(ndContent);
break;
case QilNodeType.Conditional:
this.addInScopeNmsp = false;
AnalyzeContent((nd as QilTernary).Center);
AnalyzeContent((nd as QilTernary).Right);
break;
case QilNodeType.Choice:
this.addInScopeNmsp = false;
QilList ndBranches = (nd as QilChoice).Branches;
for (int idx = 0; idx < ndBranches.Count; idx++)
AnalyzeContent(ndBranches[idx]);
break;
case QilNodeType.ElementCtor:
// Start a new namespace scope
this.addInScopeNmsp = true;
this.nsmgr.PushScope();
cntNmspSave = this.cntNmsp;
if (CheckNamespaceInScope(nd as QilBinary))
AnalyzeContent((nd as QilBinary).Right);
this.nsmgr.PopScope();
this.addInScopeNmsp = false;
this.cntNmsp = cntNmspSave;
break;
case QilNodeType.AttributeCtor:
this.addInScopeNmsp = false;
CheckNamespaceInScope(nd as QilBinary);
break;
case QilNodeType.NamespaceDecl:
CheckNamespaceInScope(nd as QilBinary);
break;
case QilNodeType.Nop:
AnalyzeContent((nd as QilUnary).Child);
break;
default:
this.addInScopeNmsp = false;
break;
}
}
/// <summary>
/// Determine whether an ElementCtor, AttributeCtor, or NamespaceDecl's namespace is already declared. If it is,
/// set the IsNamespaceInScope property to True. Otherwise, add the namespace to the set of in-scope namespaces if
/// addInScopeNmsp is True. Return false if the name is computed or is invalid.
/// </summary>
private bool CheckNamespaceInScope(QilBinary nd) {
QilName ndName;
string prefix, ns, prefixExisting, nsExisting;
XPathNodeType nodeType;
switch (nd.NodeType) {
case QilNodeType.ElementCtor:
case QilNodeType.AttributeCtor:
ndName = nd.Left as QilName;
if (ndName != null) {
prefix = ndName.Prefix;
ns = ndName.NamespaceUri;
nodeType = (nd.NodeType == QilNodeType.ElementCtor) ? XPathNodeType.Element : XPathNodeType.Attribute;
break;
}
// Not a literal name, so return false
return false;
default:
Debug.Assert(nd.NodeType == QilNodeType.NamespaceDecl);
prefix = (string) (QilLiteral) nd.Left;
ns = (string) (QilLiteral) nd.Right;
nodeType = XPathNodeType.Namespace;
break;
}
// Attribute with null namespace and xmlns:xml are always in-scope
if (nd.NodeType == QilNodeType.AttributeCtor && ns.Length == 0 ||
prefix == "xml" && ns == XmlReservedNs.NsXml) {
XmlILConstructInfo.Write(nd).IsNamespaceInScope = true;
return true;
}
// Don't process names that are invalid
if (!ValidateNames.ValidateName(prefix, string.Empty, ns, nodeType, ValidateNames.Flags.CheckPrefixMapping))
return false;
// Atomize names
prefix = this.nsmgr.NameTable.Add(prefix);
ns = this.nsmgr.NameTable.Add(ns);
// Determine whether namespace is already in-scope
for (int iNmsp = 0; iNmsp < this.cntNmsp; iNmsp++) {
this.nsmgr.GetNamespaceDeclaration(iNmsp, out prefixExisting, out nsExisting);
// If prefix is already declared,
if ((object) prefix == (object) prefixExisting) {
// Then if the namespace is the same, this namespace is redundant
if ((object) ns == (object) nsExisting)
XmlILConstructInfo.Write(nd).IsNamespaceInScope = true;
// Else quit searching, because any further matching prefixes will be hidden (not in-scope)
Debug.Assert(nd.NodeType != QilNodeType.NamespaceDecl || !this.nsmgr.HasNamespace(prefix) || this.nsmgr.LookupNamespace(prefix) == ns,
"Compilers must ensure that namespace declarations do not conflict with the namespace used by the element constructor.");
break;
}
}
// If not in-scope, then add if it's allowed
if (this.addInScopeNmsp) {
this.nsmgr.AddNamespace(prefix, ns);
this.cntNmsp++;
}
return true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Threading;
namespace Microsoft.SqlServer.TDS
{
/// <summary>
/// Stream that wraps the data with TDS protocol
/// </summary>
public class TDSStream : Stream
{
/// <summary>
/// Indicates whether inner stream should be closed when TDS stream is closed
/// </summary>
private bool _leaveInnerStreamOpen = false;
/// <summary>
/// Size of the packet
/// </summary>
private uint _packetSize;
/// <summary>
/// Header of the packet being processed
/// </summary>
private TDSPacketHeader OutgoingPacketHeader { get; set; }
/// <summary>
/// Cache of packet header and data
/// </summary>
private byte[] _outgoingPacket;
/// <summary>
/// Header of the packet being read
/// </summary>
public TDSPacketHeader IncomingPacketHeader { get; private set; }
/// <summary>
/// Indicates the position inside the request packet data section
/// </summary>
public ushort IncomingPacketPosition { get; private set; }
/// <summary>
/// Transport stream used to deliver TDS protocol
/// </summary>
public Stream InnerStream { get; set; }
/// <summary>
/// Size of the TDS packet
/// </summary>
public uint PacketSize
{
get
{
return _packetSize;
}
set
{
// Update packet size
_packetSize = value;
// Reallocate outgoing packet buffers
_AllocateOutgoingPacket();
}
}
/// <summary>
/// Identifier of the session
/// </summary>
public ushort OutgoingSessionID { get; set; }
/// <summary>
/// Indicates whether stream can be read
/// </summary>
public override bool CanRead
{
// Delegate to the inner stream
get { return InnerStream.CanRead; }
}
/// <summary>
/// Indicates whether the stream can be positioned
/// </summary>
public override bool CanSeek
{
// Delegate to the inner stream
get { return InnerStream.CanSeek; }
}
/// <summary>
/// Indicates whether the stream can be written
/// </summary>
public override bool CanWrite
{
// Delegate to the inner stream
get { return InnerStream.CanWrite; }
}
/// <summary>
/// Return the length of the stream
/// </summary>
public override long Length
{
// Delegate to the inner stream
get { return InnerStream.Length; }
}
/// <summary>
/// Return position in the stream
/// </summary>
public override long Position
{
// Delegate to the inner stream
get { return InnerStream.Position; }
set { InnerStream.Position = value; }
}
/// <summary>
/// Call back function before calling InnerStream.Write
/// the func should return actual packet length to send
/// </summary>
public Func<byte[], int, int, ushort> PreWriteCallBack { get; set; }
/// <summary>
/// Initialization constructor
/// </summary>
public TDSStream(Stream innerStream) :
this(innerStream, true)
{
}
/// <summary>
/// Initialization constructor
/// </summary>
public TDSStream(Stream innerStream, bool leaveInnerStreamOpen)
{
// Check if inner stream is valid
if (innerStream == null)
{
// We can't proceed without underlying stream
throw new ArgumentNullException(nameof(innerStream), "Underlying stream is required");
}
// Save transport stream
InnerStream = innerStream;
// Save whether inner stream is to be closed as well
_leaveInnerStreamOpen = leaveInnerStreamOpen;
}
/// <summary>
/// Close the stream
/// </summary>
public override void Close()
{
// Check if inner stream needs to be closed
if (!_leaveInnerStreamOpen)
{
// Close inner stream
InnerStream.Close();
}
// Delegate to the base class
base.Close();
}
/// <summary>
/// Flush the data into the underlying stream
/// </summary>
public override void Flush()
{
// Complete current message before flushing the data
EndMessage();
// Delegate to the inner stream
InnerStream.Flush();
}
/// <summary>
/// Start a new message
/// </summary>
/// <param name="type">Type of the message to start</param>
public virtual void StartMessage(TDSMessageType type)
{
// Flush current packet if available
_SendCurrentPacket();
// Create a new packet of the specified type
_CreateOutgoingPacket(type, 1);
}
/// <summary>
/// Send the last packet of the message and complete the request/response
/// </summary>
public virtual void EndMessage()
{
// Check if we have a current packet
if (OutgoingPacketHeader != null)
{
// Indicate that this is the end of message
OutgoingPacketHeader.Status |= TDSPacketStatus.EndOfMessage;
// Send the packet out
_SendCurrentPacket();
}
}
/// <summary>
/// Read packet header
/// </summary>
public virtual bool ReadNextHeader()
{
// Check if we can move to the next incoming packet header
if (!_MoveToNextIncomingPacketHeader())
{
// We can't reach next header at this time
return false;
}
// Allocate a new incoming packet
_AllocateIncomingPacket();
// Inflate the header
if (!IncomingPacketHeader.Inflate(InnerStream))
{
// Header inflation failed
return false;
}
// Advance post header position
IncomingPacketPosition += TDSPacketHeader.Size;
// Header successfully inflated
return true;
}
/// <summary>
/// Read the data from the stream
/// </summary>
public override int Read(byte[] buffer, int offset, int count)
{
// Indication of current position in the buffer that was read from the underlying stream
int bufferReadPosition = 0;
// Get the starting time
DateTime startTime = DateTime.Now;
// Read operation timeout
TimeSpan timeout = new TimeSpan(0, 0, 30); // 30 Sec
// Iterate while there's buffer data left
while (bufferReadPosition < count && DateTime.Now - startTime < timeout)
{
// We need to make sure that there's a packet to read before we start reading it
if (!_EnsureIncomingPacketHasData())
{
// We don't have enough data
return bufferReadPosition;
}
// Calculate how much data can be read until the end of the packet is reached
long packetDataAvailable = IncomingPacketHeader.Length - IncomingPacketPosition;
// Check how much data we should give back in the current iteration
int packetDataToRead = Math.Min((int)packetDataAvailable, count - bufferReadPosition);
// Check if there's data chunk still to be returned
if (packetDataToRead > 0)
{
// Do read operation while the number of read bytes is 0
// Read the data from the underlying stream
int packetDataRead = InnerStream.Read(buffer, bufferReadPosition + offset, packetDataToRead);
if (packetDataRead == 0)
{
for (int i = 0; i < 3 && packetDataRead == 0; i++)
{
Thread.Sleep(50);
packetDataRead = InnerStream.Read(buffer, bufferReadPosition + offset, packetDataToRead);
}
if (packetDataRead == 0)
{
// Server side socket is FIN_WAIT_2 state, throw
throw new EndOfStreamException("Unexpected end of stream");
}
}
// Update current read position
bufferReadPosition += packetDataRead;
// Update current packet position
IncomingPacketPosition += (ushort)packetDataRead;
}
}
// Check if timeout expired
if (DateTime.Now - startTime > timeout)
{
throw new EndOfStreamException("Unexpected end of stream");
}
return bufferReadPosition;
}
/// <summary>
/// Seek position in the stream
/// </summary>
public override long Seek(long offset, SeekOrigin origin)
{
// Delegate to the inner stream
return InnerStream.Seek(offset, origin);
}
/// <summary>
/// Set stream length
/// </summary>
public override void SetLength(long value)
{
// Delegate to the inner stream
InnerStream.SetLength(value);
}
/// <summary>
/// Write data into the stream
/// </summary>
public override void Write(byte[] buffer, int offset, int count)
{
// Indication of current position in the buffer that was sent to the underlying stream
int bufferWrittenPosition = 0;
// Iterate while there's buffer data left
while (bufferWrittenPosition < count)
{
// We need to make sure that current packet has enough space for at least a single byte
_EnsureOutgoingPacketHasSpace();
// Check the last packet available and see how much of data we can write
long packetDataAvailable = PacketSize - OutgoingPacketHeader.Length;
// Check how much data we still have to write
// We shouldn't be writing more than packet data available or left to write
int packetDataToWrite = Math.Min((int)packetDataAvailable, count - bufferWrittenPosition);
// Check if there's space in the last packet
if (packetDataToWrite > 0)
{
// Append new data to the end of the packet data
Array.Copy(buffer, bufferWrittenPosition + offset, _outgoingPacket, OutgoingPacketHeader.Length, packetDataToWrite);
// Register that we've written new data
bufferWrittenPosition += packetDataToWrite;
// Update packet length
OutgoingPacketHeader.Length += (ushort)packetDataToWrite;
}
}
}
/// <summary>
/// Skip current packet if it is pending and move to the next packet, reading only the header
/// </summary>
private bool _MoveToNextIncomingPacketHeader()
{
// Check if we have a packet
if (IncomingPacketHeader == null)
{
// We don't have a packet which means we are at the right spot
return true;
}
// Calculate the span between current position in the packet and it's end
int distanceToEnd = IncomingPacketHeader.Length - IncomingPacketPosition;
// Check if we are right at the end of the packet
if (distanceToEnd <= 0)
{
// We consumed the whole packet so we are ready for the next one
return true;
}
// Allocate a buffer for the rest of the packet
byte[] packetData = new byte[distanceToEnd];
// Read the data
int packetDataRead = InnerStream.Read(packetData, 0, packetData.Length);
// Update packet position
IncomingPacketPosition += (ushort)packetDataRead;
// Check if all of the data was read
return packetDataRead >= packetData.Length;
}
/// <summary>
/// This routine checks whether current packet still has data to read and moves to the next if it doesn't
/// </summary>
private bool _EnsureIncomingPacketHasData()
{
// Indicates whether the current packet is the one we need
bool IsRightPacket = true; // Assume
do
{
// Check if we have a packet
if (IncomingPacketHeader == null || !IsRightPacket)
{
// Move to the next packet
if (!ReadNextHeader())
{
return false;
}
}
// Check if current packet is right
IsRightPacket = (IncomingPacketPosition < IncomingPacketHeader.Length);
}
while (!IsRightPacket);
// We found a packet that satisfies the requirements
return true;
}
/// <summary>
/// Ensures that the current packet has at least a single spare byte
/// </summary>
/// <param name="type">Type of the packet to look for</param>
private void _EnsureOutgoingPacketHasSpace()
{
// Check if we have a packet
if (OutgoingPacketHeader == null)
{
// Message must be started before we can ensure packet availability
throw new InvalidOperationException("Message has not been started");
}
// Check if last packet has no space in it
if (OutgoingPacketHeader.Length >= PacketSize)
{
// Save outgoing packet type before sending it, which will reset the packet header
TDSMessageType outgoingPacketType = OutgoingPacketHeader.Type;
// Save outgoing packet number
byte packetID = OutgoingPacketHeader.PacketID;
// Before allocating a new packet we need to serialize the current packet
_SendCurrentPacket();
// Allocate a new packet since the last packet is full
_CreateOutgoingPacket(outgoingPacketType, (byte)(((int)packetID + 1) % 256));
}
}
/// <summary>
/// Create a new TDS packet in the message
/// </summary>
private void _CreateOutgoingPacket(TDSMessageType type, byte packetID)
{
// Allocate an outgoing packet in case it isn't available
_AllocateOutgoingPacket();
// Allocate a new packet with the specified type and normal status
OutgoingPacketHeader = new TDSPacketHeader(_outgoingPacket, type, TDSPacketStatus.Normal);
// Assign session identifier to the packet
OutgoingPacketHeader.SPID = OutgoingSessionID;
// Increment packet identifier
OutgoingPacketHeader.PacketID = packetID;
}
/// <summary>
/// Serialize current packet into the underlying stream
/// </summary>
private void _SendCurrentPacket()
{
// Check if we have a current packet
if (OutgoingPacketHeader != null)
{
// store the OutgoingPacketHeader.Length, it could be updated in PreWriteCallBack (for Fuzz test)
ushort outgoingPacketHeader_Length = OutgoingPacketHeader.Length;
// PreWrite call before packet writing
if (PreWriteCallBack != null)
{
// By calling PreWriteCallBack,
// The length value in OutgoingPacketHeader (i.e. OutgoingPacketHeader.Length) could be fuzzed
// The actual written length of the packet (i.e. outgoingPacketHeader_Length) could be fuzzed
outgoingPacketHeader_Length = PreWriteCallBack(_outgoingPacket, 0, OutgoingPacketHeader.Length);
}
// Send the packet header along with packet body into the underlying stream
InnerStream.Write(_outgoingPacket, 0, outgoingPacketHeader_Length);
// Reset packet header
OutgoingPacketHeader = null;
// Reset packet
_outgoingPacket = null;
}
}
/// <summary>
/// Allocate or reallocate a packet
/// </summary>
private void _AllocateOutgoingPacket()
{
// Check if we have incoming packet already
if (_outgoingPacket != null)
{
// Check if incoming packet complies
if (_outgoingPacket.Length != PacketSize)
{
// Re-allocate
Array.Resize(ref _outgoingPacket, (int)PacketSize);
}
}
else
{
// Allocate a new packet
_outgoingPacket = new byte[PacketSize];
}
}
/// <summary>
/// Prepare to read and inflate incoming packet
/// </summary>
private void _AllocateIncomingPacket()
{
// Create a new incoming packet header
IncomingPacketHeader = new TDSPacketHeader(new byte[TDSPacketHeader.Size]);
// Reset header data position
IncomingPacketPosition = 0;
}
}
}
| |
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
using UMA;
using UMA.Integrations;
namespace UMAEditor
{
public class DNAMasterEditor
{
private readonly Dictionary<Type, DNASingleEditor> _dnaValues = new Dictionary<Type, DNASingleEditor>();
private readonly Type[] _dnaTypes;
private readonly string[] _dnaTypeNames;
public int viewDna = 0;
public UMAData.UMARecipe recipe;
public static UMAGeneratorBase umaGenerator;
public DNAMasterEditor(UMAData.UMARecipe recipe)
{
this.recipe = recipe;
UMADnaBase[] allDna = recipe.GetAllDna();
_dnaTypes = new Type[allDna.Length];
_dnaTypeNames = new string[allDna.Length];
for (int i = 0; i < allDna.Length; i++)
{
var entry = allDna[i];
var entryType = entry.GetType();
_dnaTypes[i] = entryType;
_dnaTypeNames[i] = entryType.Name;
_dnaValues[entryType] = new DNASingleEditor(entry);
}
}
public bool OnGUI(ref bool _dnaDirty, ref bool _textureDirty, ref bool _meshDirty)
{
GUILayout.BeginHorizontal();
var newToolBarIndex = EditorGUILayout.Popup("DNA", viewDna, _dnaTypeNames);
if (newToolBarIndex != viewDna)
{
viewDna = newToolBarIndex;
}
GUI.enabled = viewDna >= 0;
if (GUILayout.Button("X", EditorStyles.miniButton, GUILayout.Width(24)))
{
if (viewDna >= 0)
{
recipe.RemoveDna(_dnaTypes[viewDna]);
if (viewDna >= _dnaTypes.Length - 1) viewDna--;
GUI.enabled = true;
GUILayout.EndHorizontal();
_dnaDirty = true;
return true;
}
}
GUI.enabled = true;
GUILayout.EndHorizontal();
if (viewDna >= 0)
{
Type dnaType = _dnaTypes[viewDna];
if (_dnaValues[dnaType].OnGUI())
{
_dnaDirty = true;
return true;
}
}
return false;
}
internal bool NeedsReenable()
{
return _dnaValues == null;
}
public bool IsValid
{
get
{
return !(_dnaTypes == null || _dnaTypes.Length == 0);
}
}
}
public class DNASingleEditor
{
private readonly SortedDictionary<string, DNAGroupEditor> _groups = new SortedDictionary<string, DNAGroupEditor>();
public DNASingleEditor(UMADnaBase dna)
{
var fields = dna.GetType().GetFields();
foreach (FieldInfo field in fields)
{
if (field.FieldType != typeof(float))
{
continue;
}
string fieldName;
string groupName;
GetNamesFromField(field, out fieldName, out groupName);
DNAGroupEditor group;
_groups.TryGetValue(groupName, out @group);
if (group == null)
{
@group = new DNAGroupEditor(groupName);
_groups.Add(groupName, @group);
}
var entry = new DNAFieldEditor(fieldName, field, dna);
@group.Add(entry);
}
foreach (var group in _groups.Values)
@group.Sort();
}
private static void GetNamesFromField(FieldInfo field, out string fieldName, out string groupName)
{
fieldName = ObjectNames.NicifyVariableName(field.Name);
groupName = "Other";
string[] chunks = fieldName.Split(' ');
if (chunks.Length > 1)
{
groupName = chunks[0];
fieldName = fieldName.Substring(groupName.Length + 1);
}
}
public bool OnGUI()
{
bool changed = false;
foreach (var dnaGroup in _groups.Values)
{
changed |= dnaGroup.OnGUI();
}
return changed;
}
}
public class DNAGroupEditor
{
private readonly List<DNAFieldEditor> _fields = new List<DNAFieldEditor>();
private readonly string _groupName;
private bool _foldout = true;
public DNAGroupEditor(string groupName)
{
_groupName = groupName;
}
public bool OnGUI()
{
_foldout = EditorGUILayout.Foldout(_foldout, _groupName);
if (!_foldout)
return false;
bool changed = false;
GUILayout.BeginVertical(EditorStyles.textField);
foreach (var field in _fields)
{
changed |= field.OnGUI();
}
GUILayout.EndVertical();
return changed;
}
public void Add(DNAFieldEditor field)
{
_fields.Add(field);
}
public void Sort()
{
_fields.Sort(DNAFieldEditor.comparer);
}
}
public class DNAFieldEditor
{
public static Comparer comparer = new Comparer();
private readonly UMADnaBase _dna;
private readonly FieldInfo _field;
private readonly string _name;
private readonly float _value;
public DNAFieldEditor(string name, FieldInfo field, UMADnaBase dna)
{
_name = name;
_field = field;
_dna = dna;
_value = (float)field.GetValue(dna);
}
public bool OnGUI()
{
float newValue = EditorGUILayout.Slider(_name, _value, 0f, 1f);
//float newValue = EditorGUILayout.FloatField(_name, _value);
if (newValue != _value)
{
_field.SetValue(_dna, newValue);
return true;
}
return false;
}
public class Comparer : IComparer <DNAFieldEditor>
{
public int Compare(DNAFieldEditor x, DNAFieldEditor y)
{
return String.CompareOrdinal(x._name, y._name);
}
}
}
public class SharedColorsCollectionEditor
{
private bool _foldout = true;
static int selectedChannelCount = 2;
String[] names = new string[4] { "1", "2", "3", "4" };
int[] channels = new int[4] { 1, 2, 3, 4 };
static bool[] _ColorFoldouts = new bool[0];
public bool OnGUI (UMAData.UMARecipe _recipe)
{
GUILayout.BeginHorizontal (EditorStyles.toolbarButton);
GUILayout.Space (10);
_foldout = EditorGUILayout.Foldout (_foldout, "Shared Colors");
GUILayout.EndHorizontal ();
if (_foldout) {
bool changed = false;
GUIHelper.BeginVerticalPadded (10, new Color (0.75f, 0.875f, 1f));
EditorGUILayout.BeginHorizontal ();
if (_recipe.sharedColors == null)
_recipe.sharedColors = new OverlayColorData[0];
if (_recipe.sharedColors.Length == 0) {
selectedChannelCount = EditorGUILayout.IntPopup ("Channels", selectedChannelCount, names, channels);
} else {
selectedChannelCount = _recipe.sharedColors [0].channelMask.Length;
}
if (GUILayout.Button ("Add Shared Color")) {
List<OverlayColorData> sharedColors = new List<OverlayColorData> ();
sharedColors.AddRange (_recipe.sharedColors);
sharedColors.Add (new OverlayColorData (selectedChannelCount));
_recipe.sharedColors = sharedColors.ToArray ();
changed = true;
}
if (GUILayout.Button ("Save Collection")) {
changed = true;
}
EditorGUILayout.EndHorizontal ();
if (_ColorFoldouts.Length != _recipe.sharedColors.Length) {
Array.Resize<bool> (ref _ColorFoldouts, _recipe.sharedColors.Length);
}
for (int i = 0; i < _recipe.sharedColors.Length; i++) {
bool del = false;
OverlayColorData ocd = _recipe.sharedColors [i];
GUIHelper.FoldoutBar (ref _ColorFoldouts [i], i + ": " + ocd.name, out del);
if (del) {
List<OverlayColorData> temp = new List<OverlayColorData> ();
temp.AddRange (_recipe.sharedColors);
temp.RemoveAt (i);
_recipe.sharedColors = temp.ToArray ();
// TODO: search the overlays and adjust the shared colors
break;
}
if (_ColorFoldouts [i]) {
if (ocd.name == null)
ocd.name = "";
string NewName = EditorGUILayout.TextField ("Name", ocd.name);
if (NewName != ocd.name) {
ocd.name = NewName;
//changed = true;
}
Color NewChannelMask = EditorGUILayout.ColorField ("Color Multiplier", ocd.channelMask [0]);
if (ocd.channelMask [0] != NewChannelMask) {
ocd.channelMask [0] = NewChannelMask;
changed = true;
}
Color NewChannelAdditiveMask = EditorGUILayout.ColorField ("Color Additive", ocd.channelAdditiveMask [0]);
if (ocd.channelAdditiveMask [0] != NewChannelAdditiveMask) {
ocd.channelAdditiveMask [0] = NewChannelAdditiveMask;
changed = true;
}
for (int j = 1; j < ocd.channelMask.Length; j++) {
NewChannelMask = EditorGUILayout.ColorField ("Texture " + j + "multiplier", ocd.channelMask [j]);
if (ocd.channelMask [j] != NewChannelMask) {
ocd.channelMask [j] = NewChannelMask;
changed = true;
}
NewChannelAdditiveMask = EditorGUILayout.ColorField ("Texture " + j + " additive", ocd.channelAdditiveMask [j]);
if (ocd.channelAdditiveMask [j] != NewChannelAdditiveMask) {
ocd.channelAdditiveMask [j] = NewChannelAdditiveMask;
changed = true;
}
}
}
}
GUIHelper.EndVerticalPadded (10);
return changed;
}
return false;
}
}
public class SlotMasterEditor
{
private readonly UMAData.UMARecipe _recipe;
private readonly List<SlotEditor> _slotEditors = new List<SlotEditor>();
private readonly SharedColorsCollectionEditor _sharedColorsEditor = new SharedColorsCollectionEditor ();
private bool DropAreaGUI(Rect dropArea)
{
int count = 0;
var evt = Event.current;
if (evt.type == EventType.DragUpdated)
{
if (dropArea.Contains(evt.mousePosition))
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
}
}
if (evt.type == EventType.DragPerform)
{
if (dropArea.Contains(evt.mousePosition))
{
DragAndDrop.AcceptDrag();
UnityEngine.Object[] draggedObjects = DragAndDrop.objectReferences as UnityEngine.Object[];
for (int i = 0; i < draggedObjects.Length; i++)
{
if (draggedObjects[i])
{
SlotDataAsset tempSlotDataAsset = draggedObjects[i] as SlotDataAsset;
if (tempSlotDataAsset)
{
AddSlotDataAsset(tempSlotDataAsset);
count++;
continue;
}
var path = AssetDatabase.GetAssetPath(draggedObjects[i]);
if (System.IO.Directory.Exists(path))
{
RecursiveScanFoldersForAssets(path, ref count);
}
}
}
if (count > 0)
{
return true;
}
}
}
return false;
}
private void AddSlotDataAsset(SlotDataAsset added)
{
var slot = new SlotData(added);
_recipe.MergeSlot(slot, false);
}
private void RecursiveScanFoldersForAssets(string path, ref int count)
{
var assetFiles = System.IO.Directory.GetFiles(path, "*.asset");
foreach (var assetFile in assetFiles)
{
var tempSlotDataAsset = AssetDatabase.LoadAssetAtPath(assetFile, typeof(SlotDataAsset)) as SlotDataAsset;
if (tempSlotDataAsset)
{
count++;
AddSlotDataAsset(tempSlotDataAsset);
}
}
foreach (var subFolder in System.IO.Directory.GetDirectories(path))
{
RecursiveScanFoldersForAssets(subFolder.Replace('\\', '/'), ref count);
}
}
public SlotMasterEditor(UMAData.UMARecipe recipe)
{
_recipe = recipe;
if (recipe.slotDataList == null)
{
recipe.slotDataList = new SlotData[0];
}
for (int i = 0; i < recipe.slotDataList.Length; i++ )
{
var slot = recipe.slotDataList[i];
if (slot == null)
continue;
_slotEditors.Add(new SlotEditor(_recipe, slot, i));
}
_slotEditors.Sort(SlotEditor.comparer);
if (_slotEditors.Count > 1)
{
var overlays1 = _slotEditors[0].GetOverlays();
var overlays2 = _slotEditors[1].GetOverlays();
for (int i = 0; i < _slotEditors.Count - 2; i++ )
{
if (overlays1 == overlays2)
_slotEditors[i].sharedOverlays = true;
overlays1 = overlays2;
overlays2 = _slotEditors[i + 2].GetOverlays();
}
}
}
public bool OnGUI(ref bool _dnaDirty, ref bool _textureDirty, ref bool _meshDirty)
{
bool changed = false;
// Have to be able to assign a race on a new recipe.
RaceData newRace = (RaceData)EditorGUILayout.ObjectField("RaceData",_recipe.raceData,typeof(RaceData),false);
if (_recipe.raceData == null) {
GUIHelper.BeginVerticalPadded (10, new Color (0.55f, 0.25f, 0.25f));
GUILayout.Label ("Warning: No race data is set!");
GUIHelper.EndVerticalPadded (10);
}
if (_recipe.raceData != newRace)
{
_recipe.SetRace(newRace);
changed = true;
}
if (GUILayout.Button("Remove Nulls"))
{
var newList = new List<SlotData>(_recipe.slotDataList.Length);
foreach (var slotData in _recipe.slotDataList)
{
if (slotData != null) newList.Add(slotData);
}
_recipe.slotDataList = newList.ToArray();
changed |= true;
_dnaDirty |= true;
_textureDirty |= true;
_meshDirty |= true;
}
if (_sharedColorsEditor.OnGUI (_recipe)) {
changed = true;
_textureDirty = true;
}
GUILayout.Space(20);
Rect dropArea = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true));
GUI.Box(dropArea, "Drag Slots here");
GUILayout.Space(20);
if (DropAreaGUI(dropArea))
{
changed |= true;
_dnaDirty |= true;
_textureDirty |= true;
_meshDirty |= true;
}
var added = (SlotDataAsset)EditorGUILayout.ObjectField("Add Slot", null, typeof(SlotDataAsset), false);
if (added != null)
{
var slot = new SlotData(added);
_recipe.MergeSlot(slot, false);
changed |= true;
_dnaDirty |= true;
_textureDirty |= true;
_meshDirty |= true;
}
GUILayout.BeginHorizontal();
if (GUILayout.Button("Collapse All"))
{
foreach(SlotEditor se in _slotEditors)
{
se.FoldOut = false;
}
}
if (GUILayout.Button("Expand All"))
{
foreach(SlotEditor se in _slotEditors)
{
se.FoldOut = true;
}
}
GUILayout.EndHorizontal();
for (int i = 0; i < _slotEditors.Count; i++)
{
var editor = _slotEditors[i];
if (editor == null)
{
GUILayout.Label("Empty Slot");
continue;
}
changed |= editor.OnGUI(ref _dnaDirty, ref _textureDirty, ref _meshDirty);
if (editor.Delete)
{
_dnaDirty = true;
_textureDirty = true;
_meshDirty = true;
_slotEditors.RemoveAt(i);
_recipe.SetSlot(editor.idx, null);
i--;
changed = true;
}
}
return changed;
}
}
public class SlotEditor
{
private readonly UMAData.UMARecipe _recipe;
private readonly SlotData _slotData;
private readonly List<OverlayData> _overlayData = new List<OverlayData>();
private readonly List<OverlayEditor> _overlayEditors = new List<OverlayEditor>();
private readonly string _name;
public bool Delete { get; private set; }
public bool FoldOut {
get { return _foldout; }
set {_foldout = value; }
}
private bool _foldout = true;
public bool sharedOverlays = false;
public int idx;
public SlotEditor(UMAData.UMARecipe recipe, SlotData slotData, int index)
{
_recipe = recipe;
_slotData = slotData;
_overlayData = slotData.GetOverlayList();
this.idx = index;
_name = slotData.asset.slotName;
for (int i = 0; i < _overlayData.Count; i++)
{
_overlayEditors.Add(new OverlayEditor(_recipe, slotData, _overlayData[i]));
}
}
public List<OverlayData> GetOverlays()
{
return _overlayData;
}
public bool OnGUI(ref bool _dnaDirty, ref bool _textureDirty, ref bool _meshDirty)
{
bool delete;
GUIHelper.FoldoutBar(ref _foldout, _name, out delete);
if (!_foldout)
return false;
Delete = delete;
bool changed = false;
GUIHelper.BeginVerticalPadded(10, new Color(0.75f, 0.875f, 1f));
if (sharedOverlays)
{
List<OverlayData> ovr = GetOverlays();
EditorGUILayout.LabelField("Shared Overlays:");
GUIHelper.BeginVerticalPadded(10, new Color(0.85f, 0.85f, 0.85f));
foreach(OverlayData ov in ovr)
{
EditorGUILayout.LabelField(ov.asset.overlayName);
}
GUIHelper.EndVerticalPadded(10);
}
else
{
var added = (OverlayDataAsset)EditorGUILayout.ObjectField("Add Overlay", null, typeof(OverlayDataAsset), false);
if (added != null)
{
var newOverlay = new OverlayData(added);
_overlayEditors.Add(new OverlayEditor(_recipe, _slotData, newOverlay));
_overlayData.Add(newOverlay);
_dnaDirty = true;
_textureDirty = true;
_meshDirty = true;
changed = true;
}
var addedSlot = (SlotDataAsset)EditorGUILayout.ObjectField("Add Slot", null, typeof(SlotDataAsset), false);
if (addedSlot != null)
{
var newSlot = new SlotData(addedSlot);
newSlot.SetOverlayList(_slotData.GetOverlayList());
_recipe.MergeSlot(newSlot, false);
_dnaDirty = true;
_textureDirty = true;
_meshDirty = true;
changed = true;
}
for (int i = 0; i < _overlayEditors.Count; i++)
{
var overlayEditor = _overlayEditors[i];
if (overlayEditor.OnGUI())
{
_textureDirty = true;
changed = true;
}
if (overlayEditor.Delete)
{
_overlayEditors.RemoveAt(i);
_overlayData.RemoveAt(i);
_textureDirty = true;
changed = true;
i--;
}
}
for (int i = 0; i < _overlayEditors.Count; i++)
{
var overlayEditor = _overlayEditors[i];
if (overlayEditor.move > 0 && i + 1 < _overlayEditors.Count)
{
_overlayEditors[i] = _overlayEditors[i + 1];
_overlayEditors[i + 1] = overlayEditor;
var overlayData = _overlayData[i];
_overlayData[i] = _overlayData[i + 1];
_overlayData[i + 1] = overlayData;
overlayEditor.move = 0;
_textureDirty = true;
changed = true;
continue;
}
if (overlayEditor.move < 0 && i > 0)
{
_overlayEditors[i] = _overlayEditors[i - 1];
_overlayEditors[i - 1] = overlayEditor;
var overlayData = _overlayData[i];
_overlayData[i] = _overlayData[i - 1];
_overlayData[i - 1] = overlayData;
overlayEditor.move = 0;
_textureDirty = true;
changed = true;
continue;
}
}
}
GUIHelper.EndVerticalPadded(10);
return changed;
}
public static Comparer comparer = new Comparer();
public class Comparer : IComparer <SlotEditor>
{
public int Compare(SlotEditor x, SlotEditor y)
{
if (x._overlayData == y._overlayData)
return 0;
if (x._overlayData == null)
return 1;
if (y._overlayData == null)
return -1;
return x._overlayData.GetHashCode() - y._overlayData.GetHashCode();
}
}
}
public class OverlayEditor
{
private readonly UMAData.UMARecipe _recipe;
protected readonly SlotData _slotData;
private readonly OverlayData _overlayData;
private ColorEditor[] _colors;
private bool _sharedColors;
private readonly TextureEditor[] _textures;
private bool _foldout = true;
public bool Delete { get; private set; }
public int move;
private static OverlayData showExtendedRangeForOverlay;
public OverlayEditor(UMAData.UMARecipe recipe, SlotData slotData, OverlayData overlayData)
{
_recipe = recipe;
_overlayData = overlayData;
_slotData = slotData;
_sharedColors = false;
if (_recipe.sharedColors != null)
{
foreach(OverlayColorData ocd in _recipe.sharedColors)
{
if (ocd.GetHashCode() == _overlayData.colorData.GetHashCode()) _sharedColors = true;
}
}
if (_sharedColors && (_overlayData.colorData.name == OverlayColorData.UNSHARED))
{
_sharedColors = false;
}
_textures = new TextureEditor[overlayData.asset.textureList.Length];
for (int i = 0; i < overlayData.asset.textureList.Length; i++)
{
_textures[i] = new TextureEditor(overlayData.asset.textureList[i]);
}
BuildColorEditors();
}
private void BuildColorEditors()
{
_colors = new ColorEditor[_overlayData.colorData.channelMask.Length * 2];
for (int i = 0; i < _overlayData.colorData.channelMask.Length; i++)
{
_colors[i * 2] = new ColorEditor(
_overlayData.colorData.channelMask[i],
String.Format(i == 0
? "Color multiplier"
: "Texture {0} multiplier", i));
_colors[i * 2 + 1] = new ColorEditor(
_overlayData.colorData.channelAdditiveMask[i],
String.Format(i == 0
? "Color additive"
: "Texture {0} additive", i));
}
}
public bool OnGUI()
{
bool delete;
GUIHelper.FoldoutBar(ref _foldout, _overlayData.asset.overlayName, out move, out delete);
if (!_foldout)
return false;
Delete = delete;
GUIHelper.BeginHorizontalPadded(10, Color.white);
GUILayout.BeginVertical();
bool changed = OnColorGUI();
GUILayout.BeginHorizontal();
foreach (var texture in _textures)
{
changed |= texture.OnGUI();
}
GUILayout.EndHorizontal();
GUILayout.EndVertical();
GUIHelper.EndVerticalPadded(10);
return changed;
}
public bool OnColorGUI ()
{
bool changed = false;
int currentsharedcol = 0;
string[] sharednames = new string[_recipe.sharedColors.Length];
if (_sharedColors) {
GUIHelper.BeginVerticalPadded (2f, new Color (0.75f, 0.875f, 1f));
GUILayout.BeginHorizontal ();
if (GUILayout.Toggle (true, "Use Shared Color") == false) {
// Unshare color
_overlayData.colorData = _overlayData.colorData.Duplicate ();
_overlayData.colorData.name = OverlayColorData.UNSHARED;
changed = true;
}
for (int i = 0; i < _recipe.sharedColors.Length; i++) {
sharednames [i] = i + ": " + _recipe.sharedColors [i].name;
if (_overlayData.colorData.GetHashCode () == _recipe.sharedColors [i].GetHashCode ()) {
currentsharedcol = i;
}
}
int newcol = EditorGUILayout.Popup (currentsharedcol, sharednames);
if (newcol != currentsharedcol) {
changed = true;
_overlayData.colorData = _recipe.sharedColors [newcol];
}
GUILayout.EndHorizontal ();
GUIHelper.EndVerticalPadded (2f);
GUILayout.Space (2f);
return changed;
}
GUIHelper.BeginVerticalPadded (2f, new Color (0.75f, 0.875f, 1f));
GUILayout.BeginHorizontal ();
if (_recipe.sharedColors.Length > 0) {
if (GUILayout.Toggle (false, "Use Shared Color")) {
// If we got rid of resetting the name above, we could try to match the last shared color?
// Just set to default for now.
_overlayData.colorData = _recipe.sharedColors [0];
changed = true;
}
}
GUILayout.EndHorizontal ();
bool showExtendedRanges = showExtendedRangeForOverlay == _overlayData;
var newShowExtendedRanges = EditorGUILayout.Toggle ("Show Extended Ranges", showExtendedRanges);
if (showExtendedRanges != newShowExtendedRanges) {
if (newShowExtendedRanges) {
showExtendedRangeForOverlay = _overlayData;
} else {
showExtendedRangeForOverlay = null;
}
}
for (int k = 0; k < _colors.Length; k++) {
Color color;
if (showExtendedRanges && k % 2 == 0) {
Vector4 colorVector = new Vector4 (_colors [k].color.r, _colors [k].color.g, _colors [k].color.b, _colors [k].color.a);
colorVector = EditorGUILayout.Vector4Field (_colors [k].description, colorVector);
color = new Color (colorVector.x, colorVector.y, colorVector.z, colorVector.w);
} else {
color = EditorGUILayout.ColorField (_colors [k].description, _colors [k].color);
}
if (color.r != _colors [k].color.r ||
color.g != _colors [k].color.g ||
color.b != _colors [k].color.b ||
color.a != _colors [k].color.a) {
if (k % 2 == 0) {
_overlayData.colorData.channelMask [k / 2] = color;
} else {
_overlayData.colorData.channelAdditiveMask [k / 2] = color;
}
changed = true;
}
}
GUIHelper.EndVerticalPadded (2f);
GUILayout.Space (2f);
return changed;
}
}
public class TextureEditor
{
private Texture _texture;
public TextureEditor(Texture texture)
{
_texture = texture;
}
public bool OnGUI()
{
bool changed = false;
float origLabelWidth = EditorGUIUtility.labelWidth;
int origIndentLevel = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
EditorGUIUtility.labelWidth = 0;
var newTexture = (Texture)EditorGUILayout.ObjectField("", _texture, typeof(Texture), false, GUILayout.Width(100));
EditorGUI.indentLevel = origIndentLevel;
EditorGUIUtility.labelWidth = origLabelWidth;
if (newTexture != _texture)
{
_texture = newTexture;
changed = true;
}
return changed;
}
}
public class ColorEditor
{
public Color color;
public string description;
public ColorEditor(Color color, string description)
{
this.color = color;
this.description = description;
}
}
public abstract class CharacterBaseEditor : Editor
{
protected readonly string[] toolbar =
{
"DNA", "Slots"
};
protected string _description;
protected string _errorMessage;
protected bool _needsUpdate;
protected bool _dnaDirty;
protected bool _textureDirty;
protected bool _meshDirty;
protected Object _oldTarget;
protected bool showBaseEditor;
protected bool _rebuildOnLayout = false;
protected UMAData.UMARecipe _recipe;
static int _LastToolBar = 0;
protected int _toolbarIndex = _LastToolBar;
protected DNAMasterEditor dnaEditor;
protected SlotMasterEditor slotEditor;
protected bool NeedsReenable()
{
if (dnaEditor == null || dnaEditor.NeedsReenable())
return true;
if (_oldTarget == target)
return false;
_oldTarget = target;
return true;
}
/// <summary>
/// Override PreInspectorGUI in any derived editors to allow editing of new properties added to recipes.
/// </summary>
public virtual bool PreInspectorGUI()
{
return false;
}
public override void OnInspectorGUI()
{
GUILayout.Label(_description);
if (_errorMessage != null)
{
GUI.color = Color.red;
GUILayout.Label(_errorMessage);
if (_recipe != null && GUILayout.Button("Clear"))
{
_errorMessage = null;
} else
{
return;
}
}
try
{
if (target != _oldTarget)
{
_rebuildOnLayout = true;
_oldTarget = target;
}
if (_rebuildOnLayout && Event.current.type == EventType.layout)
{
Rebuild();
}
_needsUpdate = PreInspectorGUI();
if (ToolbarGUI())
{
_needsUpdate = true;
}
if (_needsUpdate)
{
DoUpdate();
}
} catch (UMAResourceNotFoundException e)
{
_errorMessage = e.Message;
}
if (showBaseEditor)
{
base.OnInspectorGUI();
}
}
protected abstract void DoUpdate();
protected virtual void Rebuild()
{
_rebuildOnLayout = false;
if (_recipe != null)
{
int oldViewDNA = dnaEditor.viewDna;
UMAData.UMARecipe oldRecipe = dnaEditor.recipe;
dnaEditor = new DNAMasterEditor(_recipe);
if (oldRecipe == _recipe)
{
dnaEditor.viewDna = oldViewDNA;
}
slotEditor = new SlotMasterEditor(_recipe);
}
}
private bool ToolbarGUI()
{
_toolbarIndex = GUILayout.Toolbar(_toolbarIndex, toolbar);
_LastToolBar = _toolbarIndex;
switch (_toolbarIndex)
{
case 0:
if (!dnaEditor.IsValid) return false;
return dnaEditor.OnGUI(ref _dnaDirty, ref _textureDirty, ref _meshDirty);
case 1:
return slotEditor.OnGUI(ref _dnaDirty, ref _textureDirty, ref _meshDirty);
}
return false;
}
}
}
#endif
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Core.Definitions.Utilities;
using Microsoft.MixedReality.Toolkit.Core.EventDatum.Input;
using Microsoft.MixedReality.Toolkit.Core.Interfaces.InputSystem.Handlers;
using Microsoft.MixedReality.Toolkit.SDK.Input.Handlers;
using System.Collections.Generic;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.SDK.UX.Receivers
{
/// <summary>
/// An interaction receiver is simply a component that attached to a list of interactable objects and does something
/// based on events from those interactable objects. This is the base abstract class to extend from.
/// </summary>
public abstract class InteractionReceiver : BaseInputHandler,
IMixedRealityFocusChangedHandler,
IMixedRealityInputHandler<float>,
IMixedRealityInputHandler<Vector2>,
IMixedRealityGestureHandler<Vector2>,
IMixedRealityGestureHandler<Vector3>,
IMixedRealityGestureHandler<Quaternion>
{
#region Public Members
[SerializeField]
[Tooltip("Target interactable Object to receive events for")]
private List<GameObject> interactables = new List<GameObject>();
/// <summary>
/// List of linked interactable objects to receive events for
/// </summary>
public List<GameObject> Interactables
{
get { return interactables; }
private set { value = interactables; }
}
[Tooltip("Targets for the receiver to affect")]
private List<GameObject> targets = new List<GameObject>();
/// <summary>
/// List of linked targets that the receiver affects
/// </summary>
public List<GameObject> Targets
{
get { return targets; }
private set { value = targets; }
}
#endregion Public Members
[SerializeField]
[Tooltip("When true, this interaction receiver will draw connections in the editor to Interactables and Targets")]
private bool drawEditorConnections = true;
#region MonoBehaviour implementation
/// <summary>
/// On enable, set the BaseInputHandler's IsFocusRequired to false to receive all events.
/// </summary>
protected override void OnEnable()
{
IsFocusRequired = false;
base.OnEnable();
}
/// <summary>
/// When selected draw lines to all linked interactables
/// </summary>
protected virtual void OnDrawGizmosSelected()
{
if (drawEditorConnections)
{
if (interactables.Count > 0)
{
GameObject[] interactableList = interactables.ToArray();
for (int i = 0; i < interactableList.Length; i++)
{
if (interactableList[i] != null)
{
Gizmos.color = Color.green;
Gizmos.DrawLine(transform.position, interactableList[i].transform.position);
}
}
}
if (Targets.Count > 0)
{
GameObject[] targetList = Targets.ToArray();
for (int i = 0; i < targetList.Length; i++)
{
if (targetList[i] != null)
{
Gizmos.color = Color.red;
Gizmos.DrawLine(transform.position, targetList[i].transform.position);
}
}
}
}
}
#endregion MonoBehaviour implementation
/// <summary>
/// Register an interactable with this receiver.
/// </summary>
/// <param name="interactable">takes a GameObject as the interactable to register.</param>
public virtual void RegisterInteractable(GameObject interactable)
{
if (interactable == null || interactables.Contains(interactable))
{
return;
}
interactables.Add(interactable);
}
/// <summary>
/// Function to remove an interactable from the linked list.
/// </summary>
/// <param name="interactable"></param>
public virtual void RemoveInteractable(GameObject interactable)
{
if (interactable != null && interactables.Contains(interactable))
{
interactables.Remove(interactable);
}
}
/// <summary>
/// Clear the interactables list and unregister them
/// </summary>
public virtual void ClearInteractables()
{
GameObject[] _intList = interactables.ToArray();
for (int i = 0; i < _intList.Length; i++)
{
RemoveInteractable(_intList[i]);
}
}
/// <summary>
/// Is the game object interactable in our list of interactables
/// </summary>
/// <param name="interactable"></param>
/// <returns></returns>
protected bool IsInteractable(GameObject interactable)
{
return (interactables != null && interactables.Contains(interactable));
}
#region IMixedRealityFocusChangedHandler Implementation
/// <inheritdoc />
void IMixedRealityFocusChangedHandler.OnBeforeFocusChange(FocusEventData eventData) { /*Unused*/ }
/// <inheritdoc />
void IMixedRealityFocusChangedHandler.OnFocusChanged(FocusEventData eventData)
{
if (eventData.NewFocusedObject != null && IsInteractable(eventData.NewFocusedObject))
{
FocusEnter(eventData.NewFocusedObject, eventData);
}
if (eventData.OldFocusedObject != null && IsInteractable(eventData.OldFocusedObject))
{
FocusExit(eventData.OldFocusedObject, eventData);
}
}
#endregion IMixedRealityFocusChangedHandler Implementation
#region IMixedRealityInputHandler Impmentations
/// <inheritdoc />
void IMixedRealityInputHandler.OnInputUp(InputEventData eventData)
{
if (IsInteractable(eventData.selectedObject))
{
InputUp(eventData.selectedObject, eventData);
}
}
/// <inheritdoc />
void IMixedRealityInputHandler.OnInputDown(InputEventData eventData)
{
if (IsInteractable(eventData.selectedObject))
{
InputDown(eventData.selectedObject, eventData);
}
}
/// <inheritdoc />
void IMixedRealityInputHandler<float>.OnInputChanged(InputEventData<float> eventData)
{
if (IsInteractable(eventData.selectedObject))
{
InputPressed(eventData.selectedObject, eventData);
}
}
/// <inheritdoc />
void IMixedRealityInputHandler<Vector2>.OnInputChanged(InputEventData<Vector2> eventData)
{
if (IsInteractable(eventData.selectedObject))
{
PositionInputChanged(eventData.selectedObject, eventData);
}
}
#endregion IMixedRealityInputHandler Impmentations
#region IMixedRealityGestureHandler Impmentations
/// <inheritdoc />
void IMixedRealityGestureHandler.OnGestureStarted(InputEventData eventData)
{
if (IsInteractable(eventData.selectedObject))
{
GestureStarted(eventData.selectedObject, eventData);
}
}
/// <inheritdoc />
void IMixedRealityGestureHandler.OnGestureUpdated(InputEventData eventData)
{
if (IsInteractable(eventData.selectedObject))
{
GestureUpdated(eventData.selectedObject, eventData);
}
}
/// <inheritdoc />
void IMixedRealityGestureHandler<Vector2>.OnGestureUpdated(InputEventData<Vector2> eventData)
{
if (IsInteractable(eventData.selectedObject))
{
GestureUpdated(eventData.selectedObject, eventData);
}
}
/// <inheritdoc />
void IMixedRealityGestureHandler<Vector3>.OnGestureUpdated(InputEventData<Vector3> eventData)
{
if (IsInteractable(eventData.selectedObject))
{
GestureUpdated(eventData.selectedObject, eventData);
}
}
/// <inheritdoc />
void IMixedRealityGestureHandler<Quaternion>.OnGestureUpdated(InputEventData<Quaternion> eventData)
{
if (IsInteractable(eventData.selectedObject))
{
GestureUpdated(eventData.selectedObject, eventData);
}
}
/// <inheritdoc />
void IMixedRealityGestureHandler.OnGestureCompleted(InputEventData eventData)
{
if (IsInteractable(eventData.selectedObject))
{
GestureCompleted(eventData.selectedObject, eventData);
}
}
/// <inheritdoc />
void IMixedRealityGestureHandler<Vector2>.OnGestureCompleted(InputEventData<Vector2> eventData)
{
if (IsInteractable(eventData.selectedObject))
{
GestureCompleted(eventData.selectedObject, eventData);
}
}
/// <inheritdoc />
void IMixedRealityGestureHandler<Vector3>.OnGestureCompleted(InputEventData<Vector3> eventData)
{
if (IsInteractable(eventData.selectedObject))
{
GestureCompleted(eventData.selectedObject, eventData);
}
}
/// <inheritdoc />
void IMixedRealityGestureHandler<Quaternion>.OnGestureCompleted(InputEventData<Quaternion> eventData)
{
if (IsInteractable(eventData.selectedObject))
{
GestureCompleted(eventData.selectedObject, eventData);
}
}
/// <inheritdoc />
void IMixedRealityGestureHandler.OnGestureCanceled(InputEventData eventData)
{
if (IsInteractable(eventData.selectedObject))
{
GestureCanceled(eventData.selectedObject, eventData);
}
}
#endregion IMixedRealityGestureHandler Impmentations
#region Protected Virtual Callback Functions
/// <summary>
/// Raised when the target interactable object is focused.
/// </summary>
/// <param name="targetObject"></param>
/// <param name="eventData"></param>
protected virtual void FocusEnter(GameObject targetObject, FocusEventData eventData) { }
/// <summary>
/// Raised when the target interactable object has lost focus.
/// </summary>
/// <param name="targetObject"></param>
/// <param name="eventData"></param>
protected virtual void FocusExit(GameObject targetObject, FocusEventData eventData) { }
/// <summary>
/// Raised when the target interactable object receives an input down event.
/// </summary>
/// <param name="targetObject"></param>
/// <param name="eventData"></param>
protected virtual void InputDown(GameObject targetObject, InputEventData eventData) { }
/// <summary>
/// Raised when the target interactable object receives an input up event.
/// </summary>
/// <param name="targetObject"></param>
/// <param name="eventData"></param>
protected virtual void InputUp(GameObject targetObject, InputEventData eventData) { }
/// <summary>
/// Raised when the target interactable object receives an input pressed event.
/// </summary>
/// <param name="targetObject"></param>
/// <param name="eventData"></param>
protected virtual void InputPressed(GameObject targetObject, InputEventData<float> eventData) { }
/// <summary>
/// Raised when the target interactable object receives an input changed event.
/// </summary>
/// <param name="targetObject"></param>
/// <param name="eventData"></param>
protected virtual void PositionInputChanged(GameObject targetObject, InputEventData<Vector2> eventData) { }
/// <summary>
/// Raised when the target interactable object receives an input changed event.
/// </summary>
/// <param name="targetObject"></param>
/// <param name="eventData"></param>
protected virtual void PositionInputChanged(GameObject targetObject, InputEventData<Vector3> eventData) { }
/// <summary>
/// Raised when the target interactable object receives an input changed event.
/// </summary>
/// <param name="targetObject"></param>
/// <param name="eventData"></param>
protected virtual void PositionInputChanged(GameObject targetObject, InputEventData<Quaternion> eventData) { }
/// <summary>
/// Raised when the target interactable object receives an input changed event.
/// </summary>
/// <param name="targetObject"></param>
/// <param name="eventData"></param>
protected virtual void PositionInputChanged(GameObject targetObject, InputEventData<MixedRealityPose> eventData) { }
/// <summary>
/// Raised when the target interactable object receives an gesture started event.
/// </summary>
/// <param name="targetObject"></param>
/// <param name="eventData"></param>
protected virtual void GestureStarted(GameObject targetObject, InputEventData eventData) { }
/// <summary>
/// Raised when the target interactable object receives an gesture updated event.
/// </summary>
/// <param name="targetObject"></param>
/// <param name="eventData"></param>
protected virtual void GestureUpdated(GameObject targetObject, InputEventData eventData) { }
/// <summary>
/// Raised when the target interactable object receives an gesture updated event.
/// </summary>
/// <param name="targetObject"></param>
/// <param name="eventData"></param>
protected virtual void GestureUpdated(GameObject targetObject, InputEventData<Vector2> eventData) { }
/// <summary>
/// Raised when the target interactable object receives an gesture updated event.
/// </summary>
/// <param name="targetObject"></param>
/// <param name="eventData"></param>
protected virtual void GestureUpdated(GameObject targetObject, InputEventData<Vector3> eventData) { }
/// <summary>
/// Raised when the target interactable object receives an gesture updated event.
/// </summary>
/// <param name="targetObject"></param>
/// <param name="eventData"></param>
protected virtual void GestureUpdated(GameObject targetObject, InputEventData<Quaternion> eventData) { }
/// <summary>
/// Raised when the target interactable object receives an gesture completed event.
/// </summary>
/// <param name="targetObject"></param>
/// <param name="eventData"></param>
protected virtual void GestureCompleted(GameObject targetObject, InputEventData eventData) { }
/// <summary>
/// Raised when the target interactable object receives an gesture completed event.
/// </summary>
/// <param name="targetObject"></param>
/// <param name="eventData"></param>
protected virtual void GestureCompleted(GameObject targetObject, InputEventData<Vector2> eventData) { }
/// <summary>
/// Raised when the target interactable object receives an gesture completed event.
/// </summary>
/// <param name="targetObject"></param>
/// <param name="eventData"></param>
protected virtual void GestureCompleted(GameObject targetObject, InputEventData<Vector3> eventData) { }
/// <summary>
/// Raised when the target interactable object receives an gesture completed event.
/// </summary>
/// <param name="targetObject"></param>
/// <param name="eventData"></param>
protected virtual void GestureCompleted(GameObject targetObject, InputEventData<Quaternion> eventData) { }
/// <summary>
/// Raised when the target interactable object receives an gesture canceled event.
/// </summary>
/// <param name="targetObject"></param>
/// <param name="eventData"></param>
protected virtual void GestureCanceled(GameObject targetObject, InputEventData eventData) { }
#endregion Protected Virtual Callback Functions
}
}
| |
namespace Humidifier.OpsWorks
{
using System.Collections.Generic;
using LayerTypes;
public class Layer : Humidifier.Resource
{
public override string AWSTypeName
{
get
{
return @"AWS::OpsWorks::Layer";
}
}
/// <summary>
/// Attributes
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-attributes
/// Required: False
/// UpdateType: Mutable
/// Type: Map
/// PrimitiveItemType: String
/// </summary>
public Dictionary<string, dynamic> Attributes_
{
get;
set;
}
/// <summary>
/// AutoAssignElasticIps
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-autoassignelasticips
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic AutoAssignElasticIps
{
get;
set;
}
/// <summary>
/// AutoAssignPublicIps
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-autoassignpublicips
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic AutoAssignPublicIps
{
get;
set;
}
/// <summary>
/// CustomInstanceProfileArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-custominstanceprofilearn
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic CustomInstanceProfileArn
{
get;
set;
}
/// <summary>
/// CustomJson
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-customjson
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Json
/// </summary>
public dynamic CustomJson
{
get;
set;
}
/// <summary>
/// CustomRecipes
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-customrecipes
/// Required: False
/// UpdateType: Mutable
/// Type: Recipes
/// </summary>
public Recipes CustomRecipes
{
get;
set;
}
/// <summary>
/// CustomSecurityGroupIds
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-customsecuritygroupids
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic CustomSecurityGroupIds
{
get;
set;
}
/// <summary>
/// EnableAutoHealing
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-enableautohealing
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic EnableAutoHealing
{
get;
set;
}
/// <summary>
/// InstallUpdatesOnBoot
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-installupdatesonboot
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic InstallUpdatesOnBoot
{
get;
set;
}
/// <summary>
/// LifecycleEventConfiguration
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-lifecycleeventconfiguration
/// Required: False
/// UpdateType: Mutable
/// Type: LifecycleEventConfiguration
/// </summary>
public LifecycleEventConfiguration LifecycleEventConfiguration
{
get;
set;
}
/// <summary>
/// LoadBasedAutoScaling
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-loadbasedautoscaling
/// Required: False
/// UpdateType: Mutable
/// Type: LoadBasedAutoScaling
/// </summary>
public LoadBasedAutoScaling LoadBasedAutoScaling
{
get;
set;
}
/// <summary>
/// Name
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-name
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Name
{
get;
set;
}
/// <summary>
/// Packages
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-packages
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic Packages
{
get;
set;
}
/// <summary>
/// Shortname
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-shortname
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Shortname
{
get;
set;
}
/// <summary>
/// StackId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-stackid
/// Required: True
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic StackId
{
get;
set;
}
/// <summary>
/// Tags
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-tags
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: Tag
/// </summary>
public List<Tag> Tags
{
get;
set;
}
/// <summary>
/// Type
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-type
/// Required: True
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic Type
{
get;
set;
}
/// <summary>
/// UseEbsOptimizedInstances
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-useebsoptimizedinstances
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic UseEbsOptimizedInstances
{
get;
set;
}
/// <summary>
/// VolumeConfigurations
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-volumeconfigurations
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: VolumeConfiguration
/// </summary>
public List<VolumeConfiguration> VolumeConfigurations
{
get;
set;
}
}
namespace LayerTypes
{
public class ShutdownEventConfiguration
{
/// <summary>
/// DelayUntilElbConnectionsDrained
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-lifecycleeventconfiguration-shutdowneventconfiguration.html#cfn-opsworks-layer-lifecycleconfiguration-shutdowneventconfiguration-delayuntilelbconnectionsdrained
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic DelayUntilElbConnectionsDrained
{
get;
set;
}
/// <summary>
/// ExecutionTimeout
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-lifecycleeventconfiguration-shutdowneventconfiguration.html#cfn-opsworks-layer-lifecycleconfiguration-shutdowneventconfiguration-executiontimeout
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic ExecutionTimeout
{
get;
set;
}
}
public class VolumeConfiguration
{
/// <summary>
/// Encrypted
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-volumeconfiguration.html#cfn-opsworks-layer-volumeconfiguration-encrypted
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic Encrypted
{
get;
set;
}
/// <summary>
/// Iops
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-volumeconfiguration.html#cfn-opsworks-layer-volconfig-iops
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic Iops
{
get;
set;
}
/// <summary>
/// MountPoint
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-volumeconfiguration.html#cfn-opsworks-layer-volconfig-mountpoint
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic MountPoint
{
get;
set;
}
/// <summary>
/// NumberOfDisks
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-volumeconfiguration.html#cfn-opsworks-layer-volconfig-numberofdisks
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic NumberOfDisks
{
get;
set;
}
/// <summary>
/// RaidLevel
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-volumeconfiguration.html#cfn-opsworks-layer-volconfig-raidlevel
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic RaidLevel
{
get;
set;
}
/// <summary>
/// Size
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-volumeconfiguration.html#cfn-opsworks-layer-volconfig-size
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic Size
{
get;
set;
}
/// <summary>
/// VolumeType
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-volumeconfiguration.html#cfn-opsworks-layer-volconfig-volumetype
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic VolumeType
{
get;
set;
}
}
public class LifecycleEventConfiguration
{
/// <summary>
/// ShutdownEventConfiguration
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-lifecycleeventconfiguration.html#cfn-opsworks-layer-lifecycleconfiguration-shutdowneventconfiguration
/// Required: False
/// UpdateType: Mutable
/// Type: ShutdownEventConfiguration
/// </summary>
public ShutdownEventConfiguration ShutdownEventConfiguration
{
get;
set;
}
}
public class LoadBasedAutoScaling
{
/// <summary>
/// DownScaling
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-loadbasedautoscaling.html#cfn-opsworks-layer-loadbasedautoscaling-downscaling
/// Required: False
/// UpdateType: Mutable
/// Type: AutoScalingThresholds
/// </summary>
public AutoScalingThresholds DownScaling
{
get;
set;
}
/// <summary>
/// Enable
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-loadbasedautoscaling.html#cfn-opsworks-layer-loadbasedautoscaling-enable
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic Enable
{
get;
set;
}
/// <summary>
/// UpScaling
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-loadbasedautoscaling.html#cfn-opsworks-layer-loadbasedautoscaling-upscaling
/// Required: False
/// UpdateType: Mutable
/// Type: AutoScalingThresholds
/// </summary>
public AutoScalingThresholds UpScaling
{
get;
set;
}
}
public class AutoScalingThresholds
{
/// <summary>
/// CpuThreshold
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-loadbasedautoscaling-autoscalingthresholds.html#cfn-opsworks-layer-loadbasedautoscaling-autoscalingthresholds-cputhreshold
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Double
/// </summary>
public dynamic CpuThreshold
{
get;
set;
}
/// <summary>
/// IgnoreMetricsTime
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-loadbasedautoscaling-autoscalingthresholds.html#cfn-opsworks-layer-loadbasedautoscaling-autoscalingthresholds-ignoremetricstime
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic IgnoreMetricsTime
{
get;
set;
}
/// <summary>
/// InstanceCount
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-loadbasedautoscaling-autoscalingthresholds.html#cfn-opsworks-layer-loadbasedautoscaling-autoscalingthresholds-instancecount
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic InstanceCount
{
get;
set;
}
/// <summary>
/// LoadThreshold
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-loadbasedautoscaling-autoscalingthresholds.html#cfn-opsworks-layer-loadbasedautoscaling-autoscalingthresholds-loadthreshold
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Double
/// </summary>
public dynamic LoadThreshold
{
get;
set;
}
/// <summary>
/// MemoryThreshold
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-loadbasedautoscaling-autoscalingthresholds.html#cfn-opsworks-layer-loadbasedautoscaling-autoscalingthresholds-memorythreshold
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Double
/// </summary>
public dynamic MemoryThreshold
{
get;
set;
}
/// <summary>
/// ThresholdsWaitTime
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-loadbasedautoscaling-autoscalingthresholds.html#cfn-opsworks-layer-loadbasedautoscaling-autoscalingthresholds-thresholdwaittime
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic ThresholdsWaitTime
{
get;
set;
}
}
public class Recipes
{
/// <summary>
/// Configure
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-recipes.html#cfn-opsworks-layer-customrecipes-configure
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic Configure
{
get;
set;
}
/// <summary>
/// Deploy
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-recipes.html#cfn-opsworks-layer-customrecipes-deploy
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic Deploy
{
get;
set;
}
/// <summary>
/// Setup
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-recipes.html#cfn-opsworks-layer-customrecipes-setup
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic Setup
{
get;
set;
}
/// <summary>
/// Shutdown
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-recipes.html#cfn-opsworks-layer-customrecipes-shutdown
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic Shutdown
{
get;
set;
}
/// <summary>
/// Undeploy
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-recipes.html#cfn-opsworks-layer-customrecipes-undeploy
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic Undeploy
{
get;
set;
}
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core
{
/// <summary>
/// gRPC Channel
/// </summary>
public class Channel : IDisposable
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Channel>();
readonly string target;
readonly GrpcEnvironment environment;
readonly ChannelSafeHandle handle;
readonly List<ChannelOption> options;
bool disposed;
/// <summary>
/// Creates a channel that connects to a specific host.
/// Port will default to 80 for an unsecure channel and to 443 for a secure channel.
/// </summary>
/// <param name="target">Target of the channel.</param>
/// <param name="credentials">Credentials to secure the channel.</param>
/// <param name="options">Channel options.</param>
public Channel(string target, Credentials credentials, IEnumerable<ChannelOption> options = null)
{
this.target = Preconditions.CheckNotNull(target, "target");
this.environment = GrpcEnvironment.GetInstance();
this.options = options != null ? new List<ChannelOption>(options) : new List<ChannelOption>();
EnsureUserAgentChannelOption(this.options);
using (CredentialsSafeHandle nativeCredentials = credentials.ToNativeCredentials())
using (ChannelArgsSafeHandle nativeChannelArgs = ChannelOptions.CreateChannelArgs(this.options))
{
if (nativeCredentials != null)
{
this.handle = ChannelSafeHandle.CreateSecure(nativeCredentials, target, nativeChannelArgs);
}
else
{
this.handle = ChannelSafeHandle.CreateInsecure(target, nativeChannelArgs);
}
}
}
/// <summary>
/// Creates a channel that connects to a specific host and port.
/// </summary>
/// <param name="host">The name or IP address of the host.</param>
/// <param name="port">The port.</param>
/// <param name="credentials">Credentials to secure the channel.</param>
/// <param name="options">Channel options.</param>
public Channel(string host, int port, Credentials credentials, IEnumerable<ChannelOption> options = null) :
this(string.Format("{0}:{1}", host, port), credentials, options)
{
}
/// <summary>
/// Gets current connectivity state of this channel.
/// </summary>
public ChannelState State
{
get
{
return handle.CheckConnectivityState(false);
}
}
/// <summary>
/// Returned tasks completes once channel state has become different from
/// given lastObservedState.
/// If deadline is reached or and error occurs, returned task is cancelled.
/// </summary>
public Task WaitForStateChangedAsync(ChannelState lastObservedState, DateTime? deadline = null)
{
Preconditions.CheckArgument(lastObservedState != ChannelState.FatalFailure,
"FatalFailure is a terminal state. No further state changes can occur.");
var tcs = new TaskCompletionSource<object>();
var deadlineTimespec = deadline.HasValue ? Timespec.FromDateTime(deadline.Value) : Timespec.InfFuture;
var handler = new BatchCompletionDelegate((success, ctx) =>
{
if (success)
{
tcs.SetResult(null);
}
else
{
tcs.SetCanceled();
}
});
handle.WatchConnectivityState(lastObservedState, deadlineTimespec, environment.CompletionQueue, environment.CompletionRegistry, handler);
return tcs.Task;
}
/// <summary>Resolved address of the remote endpoint in URI format.</summary>
public string ResolvedTarget
{
get
{
return handle.GetTarget();
}
}
/// <summary>The original target used to create the channel.</summary>
public string Target
{
get
{
return this.target;
}
}
/// <summary>
/// Allows explicitly requesting channel to connect without starting an RPC.
/// Returned task completes once state Ready was seen. If the deadline is reached,
/// or channel enters the FatalFailure state, the task is cancelled.
/// There is no need to call this explicitly unless your use case requires that.
/// Starting an RPC on a new channel will request connection implicitly.
/// </summary>
public async Task ConnectAsync(DateTime? deadline = null)
{
var currentState = handle.CheckConnectivityState(true);
while (currentState != ChannelState.Ready)
{
if (currentState == ChannelState.FatalFailure)
{
throw new OperationCanceledException("Channel has reached FatalFailure state.");
}
await WaitForStateChangedAsync(currentState, deadline);
currentState = handle.CheckConnectivityState(false);
}
}
/// <summary>
/// Destroys the underlying channel.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
internal ChannelSafeHandle Handle
{
get
{
return this.handle;
}
}
internal GrpcEnvironment Environment
{
get
{
return this.environment;
}
}
protected virtual void Dispose(bool disposing)
{
if (disposing && handle != null && !disposed)
{
disposed = true;
handle.Dispose();
}
}
private static void EnsureUserAgentChannelOption(List<ChannelOption> options)
{
if (!options.Any((option) => option.Name == ChannelOptions.PrimaryUserAgentString))
{
options.Add(new ChannelOption(ChannelOptions.PrimaryUserAgentString, GetUserAgentString()));
}
}
private static string GetUserAgentString()
{
// TODO(jtattermusch): it would be useful to also provide .NET/mono version.
return string.Format("grpc-csharp/{0}", VersionInfo.CurrentVersion);
}
}
}
| |
namespace SIM.Tool.Base
{
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows;
using Microsoft.Web.Administration;
using SIM.Instances;
using Sitecore.Diagnostics.Base;
using Sitecore.Diagnostics.Base.Annotations;
using Sitecore.Diagnostics.Logging;
using SIM.Core;
using SIM.Extensions;
public static class InstanceHelperEx
{
#region Public methods
public static void BrowseInstance([NotNull] Instance instance, [NotNull] Window owner, [NotNull] string virtualPath, bool isFrontEnd, [CanBeNull] string browser = null, [CanBeNull] string[] parameters = null)
{
Assert.ArgumentNotNull(instance, nameof(instance));
Assert.ArgumentNotNull(owner, nameof(owner));
Assert.ArgumentNotNull(virtualPath, nameof(virtualPath));
if (!EnsureAppPoolState(instance, owner))
{
return;
}
Browse(instance, virtualPath, isFrontEnd, browser, parameters);
}
public static void Browse(Instance instance, string virtualPath, bool isFrontEnd, string browser, string[] parameters)
{
var url = instance.GetUrl();
if (!string.IsNullOrEmpty(url))
{
url += '/' + virtualPath.TrimStart('/');
CoreApp.OpenInBrowser(url, isFrontEnd, browser, parameters);
}
}
public static void OpenCurrentLogFile([NotNull] Instance instance, [NotNull] Window owner, [CanBeNull] string logFileType = null)
{
Assert.ArgumentNotNull(instance, nameof(instance));
Assert.ArgumentNotNull(owner, nameof(owner));
var dataFolderPath = instance.DataFolderPath;
FileSystem.FileSystem.Local.Directory.AssertExists(dataFolderPath, "The data folder ({0}) of the {1} instance doesn't exist".FormatWith(dataFolderPath, instance.Name));
var logsFolderPath = instance.LogsFolderPath;
var logFilePrefix = logFileType ?? GetLogFileTypes(owner, logsFolderPath);
if (logFilePrefix == null)
{
Action waitForLogs = delegate
{
while (logFilePrefix == null)
{
logFilePrefix = GetLogFileTypes(owner, logsFolderPath);
Thread.Sleep(100);
}
};
WindowHelper.LongRunningTask(waitForLogs, "Waiting for log files", owner, null, "Waiting for log files to be created in the \"{0}\" folder.".FormatWith(logsFolderPath));
}
var logFilePattern = logFilePrefix + "*.txt";
var files = FileSystem.FileSystem.Local.Directory.GetFiles(logsFolderPath, logFilePattern) ?? new string[0];
var logFilePath = files.OrderByDescending(FileSystem.FileSystem.Local.File.GetCreationTimeUtc).FirstOrDefault();
if (string.IsNullOrEmpty(logFilePath))
{
Action waitForLogs = delegate
{
while (string.IsNullOrEmpty(logFilePath))
{
var files2 = FileSystem.FileSystem.Local.Directory.GetFiles(logsFolderPath, logFilePattern) ?? new string[0];
logFilePath = files2.OrderByDescending(FileSystem.FileSystem.Local.File.GetCreationTimeUtc).FirstOrDefault();
Thread.Sleep(100);
}
};
WindowHelper.LongRunningTask(waitForLogs, "Waiting for log files", owner, null, "Waiting for log files to be created in the \"{0}\" folder.".FormatWith(logsFolderPath));
}
var logViewer = GetLogViewer();
if (string.IsNullOrEmpty(logViewer))
{
return;
}
var fileSystemWatcher = new FileSystemWatcher(logsFolderPath)
{
Filter = logFilePattern,
IncludeSubdirectories = false
};
var reopenLogViewer = false;
var currentProcess = CoreApp.RunApp(logViewer, logFilePath);
if (currentProcess == null)
{
return;
}
// we need to stop all this magic when application closes
currentProcess.Exited += delegate
{
// but shouldn't if it is initiated by this magic
if (reopenLogViewer)
{
reopenLogViewer = false;
return;
}
fileSystemWatcher.EnableRaisingEvents = false;
};
fileSystemWatcher.Created += (sender, args) =>
{
try
{
if (args.ChangeType != WatcherChangeTypes.Created)
{
return;
}
var filePath = args.FullPath;
if (!filePath.Contains(logFilePrefix))
{
return;
}
// indicate that magic begins
reopenLogViewer = true;
// magic begins
currentProcess.Kill();
currentProcess = CoreApp.RunApp(logViewer, filePath);
// we need to stop all this magic when application closes
currentProcess.Exited += delegate
{
// but shouldn't if it is initiated by this magic
if (reopenLogViewer)
{
reopenLogViewer = false;
return;
}
fileSystemWatcher.EnableRaisingEvents = false;
};
}
catch (Exception ex)
{
fileSystemWatcher.EnableRaisingEvents = false;
Log.Error(ex, "Unhandled error happened while reopening log file");
}
};
fileSystemWatcher.EnableRaisingEvents = true;
}
private static string GetLogViewer()
{
var logviewer = WinAppSettings.AppToolsLogViewer.Value;
if (string.IsNullOrEmpty(logviewer))
{
return null;
}
if (logviewer != "logview.exe")
{
return logviewer;
}
return ApplicationManager.GetEmbeddedFile("logview.zip", "SIM.Tool.Windows", "logview.exe");
}
public static void OpenInBrowserAsAdmin([NotNull] Instance instance, [NotNull] Window owner, [CanBeNull] string pageUrl = null, [CanBeNull] string browser = null, [CanBeNull] string[] parameters = null)
{
Assert.ArgumentNotNull(instance, nameof(instance));
Assert.ArgumentNotNull(owner, nameof(owner));
AuthenticationHelper.LoginAsAdmin(instance, owner, pageUrl, browser, parameters);
}
public static bool PreheatInstance(Instance instance, Window mainWindow, bool ignoreAdvancedSetting = false)
{
if (!EnsureAppPoolState(instance, mainWindow))
{
return false;
}
if (!WinAppSettings.AppPreheatEnabled.Value && !ignoreAdvancedSetting)
{
return true;
}
// Check if the instance is responsive now
if (!InstanceHelper.IsInstanceResponsive(instance, "fast"))
{
// It is not responsive so we need to preheat it
// i.e. request with larger timeout and with the
// progress bar shown to the user to avoid UI lag
Exception ex = null;
var res = WindowHelper.LongRunningTask(() => PreheatInstance(instance, out ex), "Starting Sitecore", mainWindow,
"Sitecore is being initialized",
"It may take up to a few minutes on large solutions or slow machines.",
true, true, true);
if (res == null)
{
return false;
}
// if error happened
if (ex != null)
{
const string cancel = "Cancel";
const string openLog = "Open SIM log file";
const string openSitecoreLog = "Open Sitecore log file";
const string openAnyway = "Open in browser";
var message = "The instance returned an error. \n\n" + ex.Message;
Log.Error(ex, message);
var result = WindowHelper.AskForSelection("Running instance failed", null, message,
new[]
{
cancel, openLog, openSitecoreLog, openAnyway
}, mainWindow);
switch (result)
{
case openLog:
CoreApp.OpenFile(ApplicationManager.LogsFolder);
return false;
case openSitecoreLog:
OpenCurrentLogFile(instance, mainWindow);
return false;
case openAnyway:
return true;
default:
return false;
}
}
}
return true;
}
#endregion
#region Private methods
private static bool EnsureAppPoolState([NotNull] Instance instance, [NotNull] Window mainWindow)
{
Assert.ArgumentNotNull(instance, nameof(instance));
Assert.ArgumentNotNull(mainWindow, nameof(mainWindow));
var state = instance.ApplicationPoolState;
if (state == ObjectState.Stopped || state == ObjectState.Stopping)
{
const string cancel = "Cancel";
const string start = "Start";
const string skip = "Skip, open anyway";
var result = WindowHelper.AskForSelection("Instance is stopped", null, "The selected Sitecore instance is stopped. Would you like to start it first?", new[]
{
cancel, start, skip
}, mainWindow, start);
if (result == null || result == cancel)
{
return false;
}
if (result == start)
{
instance.Start();
}
}
return true;
}
// public static void ToggleFavorite(Window mainWindow, Instance instance)
// {
// FavoriteManager.ToggleFavorite(instance.Name);
// }
[CanBeNull]
private static string GetLogFileTypes(Window owner, string logsFolderPath)
{
const string Suffix = ".txt";
const string Pattern = "*" + Suffix;
var files = FileSystem.FileSystem.Local.Directory.GetFiles(logsFolderPath, Pattern);
var groups = InstanceHelper.GetLogGroups(files);
if (groups.Any())
{
return WindowHelper.AskForSelection("Open current log file", "Choose log file type", "There are several types of log files in Sitecore. Please choose what type do you need?", groups, owner, groups.First(), false, true);
}
return null;
}
private static void PreheatInstance(Instance instance, out Exception exception)
{
try
{
InstanceHelper.StartInstance(instance, null, "long");
exception = null;
}
catch (Exception ex)
{
exception = ex;
}
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using System.Collections;
using Ecosim.SceneData;
using Ecosim.SceneData.VegetationRules;
namespace Ecosim.SceneEditor
{
public class VariablePanel : Panel
{
private Scene scene;
private EditorCtrl ctrl;
private Vector2 scrollPos;
// private GUIStyle tabNormal;
// private GUIStyle tabSelected;
private string[] types = new string[] { "bool", "int", "long", "float", "string", "coord",
"bool[]", "int[]", "long[]", "float[]", "string[]", "coord[]" };
private List<string> reserved = new List<string> (new string[] { "if", "for", "foreach", "type", "string", "int",
"long", "bool", "float", "double", "while", "break", "case", "else", "void",
"private", "protected", "public", "year", "budget", "allowResearch", "allowMeasures", "startYear", "lastMeasure", "lastMeasureGroup", "lastMeasureCount",
"lastResearch", "lastResearchGroup", "lastResearchCount" });
int currentTypeIndex = 4;
string newVarName = "";
string newVarError = "";
public List<string> keys;
private bool showPresentValues;
private bool formulasOpened = true;
public void Setup (EditorCtrl ctrl, Scene scene)
{
this.ctrl = ctrl;
this.scene = scene;
keys = new List<string> ();
// tabNormal = ctrl.listItem;
// tabSelected = ctrl.listItemSelected;
if (scene == null)
return;
textFieldDict = new Dictionary<string, string> ();
SetupTextFieldStrings ();
}
void SetupTextFieldStrings ()
{
textFieldDict.Clear ();
foreach (KeyValuePair<string, object> kv in scene.progression.variables) {
if (Progression.predefinedVariables.Contains (kv.Key)) continue;
object val = kv.Value;
if (val is IList) {
int i = 0;
foreach (object o in ((IList) val)) {
AddTextField (kv.Key, i++, o);
}
} else {
AddTextField (kv.Key, -1, val);
}
}
newVarError = "";
keys.Clear ();
keys.AddRange (scene.progression.variables.Keys);
foreach (string k in Progression.predefinedVariables) {
keys.Remove (k);
}
keys.Sort ();
}
void AddTextField (string name, int index, object val)
{
string str = null;
if (index >= 0) {
name = name + " " + index;
}
if (val is Coordinate) {
str = ((Coordinate)val).x.ToString () + "," + ((Coordinate)val).y.ToString ();
} else if (val is bool) {
str = ((bool)val) ? "true" : "false";
} else {
str = val.ToString ();
}
if (textFieldDict.ContainsKey (name)) {
textFieldDict [name] = str;
} else {
textFieldDict.Add (name, str);
}
}
Dictionary<string, string> textFieldDict;
void EditField (object val, string name, int index)
{
string dictName = (index >= 0) ? (name + " " + index) : name;
string dictVal = textFieldDict [dictName];
string newVal = GUILayout.TextField (dictVal, GUILayout.Width (120));
if (newVal != dictVal) {
newVarError = "";
// try to update original value
if (val is string) {
val = newVal;
} else if (val is int) {
int outNr;
if (int.TryParse (newVal, out outNr)) {
val = outNr;
}
} else if (val is long) {
long outNr;
if (long.TryParse (newVal, out outNr)) {
val = outNr;
}
} else if (val is float) {
float outNr;
if (float.TryParse (newVal, out outNr)) {
val = outNr;
}
} else if (val is bool) {
val = ((newVal.ToLower () == "true") || (newVal.ToLower () == "yes"));
}
if (index < 0) {
scene.progression.variables [name] = val;
} else {
IList list = (IList)(scene.progression.variables [name]);
list [index] = val;
}
textFieldDict [dictName] = newVal;
}
}
string DisplayType (object obj)
{
if (obj is bool)
return "bool";
else if (obj is int)
return "int";
else if (obj is long)
return "long";
else if (obj is float)
return "float";
else if (obj is string)
return "string";
else if (obj is Coordinate)
return "coord";
else if (obj is List<bool>)
return "bool[]";
else if (obj is List<int>)
return "int[]";
else if (obj is List<long>)
return "long[]";
else if (obj is List<float>)
return "float[]";
else if (obj is List<string>)
return "string[]";
else if (obj is List<Coordinate>)
return "coord[]";
return "unknown!";
}
void AddToList (IList list)
{
if (list is List<bool>) {
list.Add (false);
} else if (list is List<int>) {
list.Add (0);
} else if (list is List<long>) {
list.Add (0L);
} else if (list is List<float>) {
list.Add (0.0f);
} else if (list is List<string>) {
list.Add ("");
} else if (list is List<Coordinate>) {
list.Add (new Coordinate (0, 0));
}
}
public bool Render (int mx, int my)
{
// Show present(ation) values, name etc.
GUILayout.BeginHorizontal ();//ctrl.skin.box);
{
if (EcoGUI.Toggle ("Show variables and formulas in-game", ref scene.progression.showVariablesInGame))
{
if (GUILayout.Button (((showPresentValues)?"Hide":"Show") + " data", GUILayout.Width (100))) {
showPresentValues = !showPresentValues;
}
}
else showPresentValues = false;
}
GUILayout.EndVertical ();
GUILayout.Space (5f);
// Variables
if (showPresentValues) {
GUILayout.BeginHorizontal ();
{
GUILayout.Label ("<b> variable</b>", GUILayout.MinWidth (100), GUILayout.MaxWidth (150));
GUILayout.Label ("<b> name</b>", GUILayout.Width (100));
GUILayout.Label ("<b> category</b>", GUILayout.Width (100));
GUILayout.Label ("<b> show</b>", GUILayout.Width (35));
}
GUILayout.EndHorizontal ();
}
ManagedDictionary<string, object> variables = scene.progression.variables;
scrollPos = GUILayout.BeginScrollView (scrollPos, false, false);
GUILayout.BeginVertical ();
foreach (string key in keys)
{
GUILayout.BeginHorizontal ();
GUILayout.Label (key, GUILayout.MinWidth (100), GUILayout.MaxWidth (150));
object val = variables [key];
if (!showPresentValues) {
GUILayout.Label ("<b>" + DisplayType (val) + "</b>", GUILayout.Width (40));
if (val is IList) {
IList list = (IList)val;
if (GUILayout.Button ("+")) {
AddToList (list);
SetupTextFieldStrings ();
break;
}
if (GUILayout.Button ("-", GUILayout.Width (20))) {
variables.Remove (key);
SetupTextFieldStrings ();
break;
}
GUILayout.FlexibleSpace ();
GUILayout.EndHorizontal ();
for (int i = 0; i < list.Count; i++) {
GUILayout.BeginHorizontal ();
GUILayout.Label ("", GUILayout.Width (150));
GUILayout.Label (i.ToString (), GUILayout.Width (40));
EditField (list [i], key, i);
GUILayout.FlexibleSpace ();
if (GUILayout.Button ("-", GUILayout.Width (20))) {
list.RemoveAt (i);
SetupTextFieldStrings ();
return true; // ugly, but can't break out of 2 loops
}
GUILayout.EndHorizontal ();
}
} else {
EditField (val, key, -1);
GUILayout.FlexibleSpace ();
if (GUILayout.Button ("-", GUILayout.Width (20))) {
variables.Remove (key);
SetupTextFieldStrings ();
break;
}
GUILayout.EndHorizontal ();
}
} else {
Progression.VariableData vd = null;
if (!scene.progression.variablesData.ContainsKey (key)) {
vd = new Progression.VariableData (key, key, "");
scene.progression.variablesData.Add (key, vd);
} else vd = scene.progression.variablesData [key];
GUI.enabled = vd.enabled;
// Name and category
vd.name = GUILayout.TextField (vd.name, GUILayout.Width (100));
vd.category = GUILayout.TextField (vd.category, GUILayout.Width (100));
GUI.enabled = true;
// Enabled
EcoGUI.Toggle ("", ref vd.enabled);
GUILayout.FlexibleSpace ();
GUILayout.EndHorizontal ();
}
}
GUILayout.Space (8);
// New variable
GUILayout.BeginHorizontal ();
newVarName = GUILayout.TextField (newVarName, GUILayout.Width (100));
newVarName = newVarName.Replace (" ", "");
if (GUILayout.Button (types [currentTypeIndex], GUILayout.Width (40))) {
ctrl.StartSelection (types, currentTypeIndex, newIndex => {
currentTypeIndex = newIndex;
});
}
if (GUILayout.Button ("Create")) {
newVarName = newVarName.Trim ();
if (!StringUtil.IsValidID (newVarName)) {
newVarError = "'" + newVarName + "' is not a valid variable identifier";
} else if (scene.progression.variables.ContainsKey (newVarName)) {
newVarError = "'" + newVarName + "' is already used";
} else if (reserved.Contains (newVarName)) {
newVarError = "'" + newVarName + "' is a reserved keyword";
} else {
switch (currentTypeIndex) {
case 0 :
variables.Add (newVarName, false);
break;
case 1 :
variables.Add (newVarName, 0);
break;
case 2 :
variables.Add (newVarName, 0L);
break;
case 3 :
variables.Add (newVarName, 0.0f);
break;
case 4 :
variables.Add (newVarName, "");
break;
case 5 :
variables.Add (newVarName, new Coordinate (0, 0));
break;
case 6 :
variables.Add (newVarName, new List<bool> ());
break;
case 7 :
variables.Add (newVarName, new List<int> ());
break;
case 8 :
variables.Add (newVarName, new List<long> ());
break;
case 9 :
variables.Add (newVarName, new List<float> ());
break;
case 10 :
variables.Add (newVarName, new List<string> ());
break;
case 11 :
variables.Add (newVarName, new List<Coordinate> ());
break;
}
SetupTextFieldStrings ();
}
}
GUILayout.FlexibleSpace ();
GUILayout.EndHorizontal ();
GUILayout.Space (8);
if (!string.IsNullOrEmpty (newVarError)) {
GUILayout.Label (newVarError);
//GUILayout.FlexibleSpace ();
GUILayout.Space (10);
}
GUILayout.EndVertical ();
// Formulas
if (showPresentValues)
{
GUILayout.BeginVertical (ctrl.skin.box);
{
EcoGUI.Foldout ("Formulas", ref formulasOpened);
GUILayout.Space (2);
if (formulasOpened)
{
if (scene.progression.formulasData.Count > 0)
{
GUILayout.BeginHorizontal ();
{
GUILayout.Space (20);
GUILayout.Label ("<b> name</b>", GUILayout.Width (125));
GUILayout.Label ("<b>category</b>", GUILayout.Width (125));
GUILayout.FlexibleSpace ();
GUILayout.Label ("<b>show</b>", GUILayout.Width (30));
GUILayout.Space (40);
}
GUILayout.EndHorizontal ();
GUILayout.Space (2);
for (int i = 0; i < scene.progression.formulasData.Count; i++)
{
Progression.FormulaData fd = scene.progression.formulasData [i];
GUILayout.BeginVertical (ctrl.skin.box);
{
GUILayout.BeginHorizontal ();
{
GUI.enabled = fd.enabled;
EcoGUI.skipHorizontal = true;
EcoGUI.Foldout ("", ref fd.opened, GUILayout.Width (20));
EcoGUI.skipHorizontal = false;
fd.name = GUILayout.TextField (fd.name, GUILayout.Width (125));
fd.category = GUILayout.TextField (fd.category, GUILayout.Width (125));
GUI.enabled = true;
GUILayout.FlexibleSpace ();
EcoGUI.Toggle ("", ref fd.enabled, 20);
// Up
GUI.enabled = (i > 0);
if (GUILayout.Button ("\u02C4", GUILayout.Width (20))) {
scene.progression.formulasData.Remove (fd);
scene.progression.formulasData.Insert (i - 1, fd);
}
GUI.enabled = true;
if (GUILayout.Button ("-", GUILayout.Width (20))) {
Progression.FormulaData tmp = fd;
ctrl.StartDialog (string.Format ("Are you sure you want to delete formula '{0}'", tmp.name), delegate {
scene.progression.formulasData.Remove (tmp);
}, null);
}
}
GUILayout.EndHorizontal ();
GUILayout.Space (3);
if (fd.enabled && fd.opened)
{
fd.body = GUILayout.TextArea (fd.body);
GUILayout.Space (2);
}
}
GUILayout.EndVertical ();
}
}
GUILayout.Space (5);
if (GUILayout.Button ("New formula", GUILayout.Width (100)))
{
Progression.FormulaData fd = new Progression.FormulaData ("Formula name", "Formula Category", "Formula Body");
fd.opened = true;
scene.progression.formulasData.Add (fd);
}
}
}
GUILayout.EndVertical ();
}
GUILayout.EndScrollView ();
return true;
}
public void RenderExtra (int mx, int my)
{
}
public void RenderSide (int mx, int my)
{
}
public bool NeedSidePanel ()
{
return false;
}
public bool IsAvailable ()
{
return (scene != null);
}
public void Activate ()
{
textFieldDict.Clear ();
SetupTextFieldStrings ();
}
public void Deactivate ()
{
}
public void Update ()
{
}
}
}
| |
using OpenKh.Common;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Xe.BinaryMapper;
namespace OpenKh.Kh2.Ard
{
public interface IAreaDataCommand
{
void Parse(int nRow, List<string> tokens);
}
public interface IAreaDataSetting
{
void Parse(int nRow, List<string> tokens);
}
public enum Party : int
{
NO_FRIEND,
DEFAULT,
W_FRIEND,
W_FRIEND_IN,
W_FRIEND_FIX,
W_FRIEND_ONLY,
DONALD_ONLY,
};
public class SpawnScriptParserException : Exception
{
public SpawnScriptParserException(int line, string message) :
base($"Line {line}: {message}")
{ }
}
public class SpawnScriptMissingProgramException : SpawnScriptParserException
{
public SpawnScriptMissingProgramException(int line) :
base(line, "Expected \"Program\" statement.")
{ }
}
public class SpawnScriptCommandNotRecognizedException : SpawnScriptParserException
{
public SpawnScriptCommandNotRecognizedException(int line, string command) :
base(line, $"The command \"{command}\" was not recognized.")
{ }
}
public class SpawnScriptNotANumberException : SpawnScriptParserException
{
public SpawnScriptNotANumberException(int line, string token) :
base(line, $"Expected an integer value, but got '{token}'.")
{ }
}
public class SpawnScriptShortException : SpawnScriptParserException
{
public SpawnScriptShortException(int line, int value) :
base(line, $"The value {value} is too big. Please chose a value between {0} and {short.MaxValue}.")
{ }
}
public class SpawnScriptStringTooLongException : SpawnScriptParserException
{
public SpawnScriptStringTooLongException(int line, string value, int maxLength) :
base(line, $"The value \"{value}\" is {value.Length} characters long, but the maximum allowed is {maxLength}.")
{ }
}
public class SpawnScriptInvalidEnumException : SpawnScriptParserException
{
public SpawnScriptInvalidEnumException(int line, string token, IEnumerable<string> allowed) :
base(line, $"The token '{token}' is not recognized as only {string.Join(",", allowed.Select(x => $"'{x}'"))} are allowed.")
{ }
}
public class AreaDataScript
{
private static readonly string[] PartyValues = new string[]
{
"NO_FRIEND",
"DEFAULT",
"W_FRIEND",
"W_FRIEND_IN",
"W_FRIEND_FIX",
"W_FRIEND_ONLY",
"DONALD_ONLY",
};
private enum LexState
{
Init,
Code,
}
private const short Terminator = -1;
private static readonly IBinaryMapping Mapping =
MappingConfiguration.DefaultConfiguration()
.ForType<string>(ScriptStringReader, ScriptStringWriter)
.ForType<List<string>>(ScriptMultipleStringReader, ScriptMultipleStringWriter)
.ForType<AreaSettings>(AreaSettingsReader, AreaSettingsWriter)
.ForType<SetInventory>(SetInventoryReader, SetInventoryWriter)
.ForType<If>(IfReader, IfWriter)
.Build();
private static readonly Dictionary<int, Type> _idType = new Dictionary<int, Type>()
{
[0x00] = typeof(Spawn),
[0x01] = typeof(MapVisibility),
[0x02] = typeof(RandomSpawn),
[0x03] = typeof(CasualSpawn),
[0x04] = typeof(Capacity),
[0x05] = typeof(AllocEnemy),
[0x06] = typeof(Unk06),
[0x07] = typeof(Unk07),
[0x09] = typeof(SpawnAlt),
[0x0A] = typeof(MapScript),
[0x0B] = typeof(BarrierFlag),
[0x0C] = typeof(AreaSettings),
[0x0E] = typeof(Unk0e),
[0x0F] = typeof(Party),
[0x10] = typeof(Bgm),
[0x11] = typeof(MsgWall),
[0x12] = typeof(AllocPacket),
[0x13] = typeof(Camera),
[0x14] = typeof(StatusFlag3),
[0x15] = typeof(Mission),
[0x16] = typeof(Layout),
[0x17] = typeof(StatusFlag5),
[0x18] = typeof(AllocEffect),
[0x19] = typeof(Progress),
[0x1A] = typeof(VisibilityOn),
[0x1B] = typeof(VisibilityOff),
[0x1C] = typeof(If),
[0x1D] = typeof(Unk1d),
[0x1E] = typeof(BattleLevel),
[0x1F] = typeof(Unk1f),
};
private static readonly Dictionary<int, Type> _idSetType = new Dictionary<int, Type>()
{
[0x00] = typeof(SetEvent),
[0x01] = typeof(SetJump),
[0x02] = typeof(SetProgressFlag),
[0x03] = typeof(SetMenuFlag),
[0x04] = typeof(SetMember),
[0x05] = typeof(SetUnk05),
[0x06] = typeof(SetInventory),
[0x07] = typeof(SetPartyMenu),
[0x08] = typeof(SetUnkFlag),
};
private static readonly Dictionary<Type, int> _typeId =
_idType.ToDictionary(x => x.Value, x => x.Key);
private static readonly Dictionary<string, Type> _typeStr =
_idType.ToDictionary(x => x.Value.Name, x => x.Value);
private static readonly Dictionary<Type, int> _typeSetId =
_idSetType.ToDictionary(x => x.Value, x => x.Key);
private static readonly Dictionary<string, Type> _typeSetStr =
_idSetType.ToDictionary(x => x.Value.Name, x => x.Value);
private class Header
{
[Data] public short Id { get; set; }
[Data] public short Length { get; set; }
}
public class Spawn : IAreaDataCommand
{
[Data(Count = 4)] public string SpawnSet { get; set; }
public void Parse(int nRow, List<string> tokens)
{
SpawnSet = ParseAsString(nRow, GetToken(nRow, tokens, 1), 4);
}
public override string ToString() =>
$"{nameof(Spawn)} \"{SpawnSet}\"";
}
public class MapVisibility : IAreaDataCommand
{
[Data] public int Flags1 { get; set; }
[Data] public int Flags2 { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Flags1 = ParseAsInt(nRow, GetToken(nRow, tokens, 1));
Flags2 = ParseAsInt(nRow, GetToken(nRow, tokens, 2));
}
public override string ToString() =>
$"{nameof(MapVisibility)} 0x{Flags1:x08} 0x{Flags2:x08}";
}
public class RandomSpawn : IAreaDataCommand
{
[Data] public List<string> SpawnSet { get; set; }
public void Parse(int nRow, List<string> tokens)
{
SpawnSet = Enumerable
.Range(1, tokens.Count - 1)
.Select(i => ParseAsString(nRow, GetToken(nRow, tokens, i), 4))
.ToList();
}
public override string ToString() =>
$"{nameof(RandomSpawn)} {string.Join(" ", SpawnSet.Select(x => $"\"{x}\""))}";
}
public class CasualSpawn : IAreaDataCommand
{
[Data] public int Unk00 { get; set; }
[Data(Count = 4)] public string SpawnSet { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Unk00 = ParseAsInt(nRow, GetToken(nRow, tokens, 1));
SpawnSet = ParseAsString(nRow, GetToken(nRow, tokens, 2), 4);
}
public override string ToString() =>
$"{nameof(CasualSpawn)} {Unk00} \"{SpawnSet}\"";
}
public class Capacity : IAreaDataCommand
{
[Data] public int Value { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Value = ParseAsInt(nRow, GetToken(nRow, tokens, 1));
}
public override string ToString() =>
$"{nameof(Capacity)} {Value}";
}
public class AllocEnemy : IAreaDataCommand
{
[Data] public int Value { get; set; }
public override string ToString() =>
$"{nameof(AllocEnemy)} {Value}";
public void Parse(int nRow, List<string> tokens)
{
Value = ParseAsInt(nRow, GetToken(nRow, tokens, 1));
}
}
public class AllocPacket : IAreaDataCommand
{
[Data] public int Value { get; set; }
public override string ToString() =>
$"{nameof(AllocPacket)} {Value}";
public void Parse(int nRow, List<string> tokens)
{
Value = ParseAsInt(nRow, GetToken(nRow, tokens, 1));
}
}
public class Unk06 : IAreaDataCommand
{
[Data] public int Value { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Value = ParseAsInt(nRow, GetToken(nRow, tokens, 1));
}
public override string ToString() =>
$"{nameof(Unk06)} {Value}";
}
public class Unk07 : IAreaDataCommand
{
[Data] public int Value { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Value = ParseAsInt(nRow, GetToken(nRow, tokens, 1));
}
public override string ToString() =>
$"{nameof(Unk07)} {Value}";
}
public class SpawnAlt : IAreaDataCommand
{
[Data(Count = 4)] public string Value { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Value = ParseAsString(nRow, GetToken(nRow, tokens, 1), 4);
}
public override string ToString() =>
$"{nameof(SpawnAlt)} \"{Value}\"";
}
public class MapScript : IAreaDataCommand
{
[Data] public int Value { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Value = ParseAsInt(nRow, GetToken(nRow, tokens, 1));
}
public override string ToString() =>
$"{nameof(MapScript)} {Value}";
}
public class BarrierFlag : IAreaDataCommand
{
[Data] public int Value1 { get; set; }
[Data] public int Value2 { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Value1 = ParseAsInt(nRow, GetToken(nRow, tokens, 1));
Value2 = ParseAsInt(nRow, GetToken(nRow, tokens, 2));
}
public override string ToString() =>
$"{nameof(BarrierFlag)} 0x{Value1:x} 0x{Value2:x}";
}
public class AreaSettings : IAreaDataCommand
{
public short Unk00 { get; set; }
public short Unk02 { get; set; }
public List<IAreaDataSetting> Settings { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Unk00 = ParseAsShort(nRow, GetToken(nRow, tokens, 1));
Unk02 = (short)ParseAsInt(nRow, GetToken(nRow, tokens, 2));
}
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine($"{nameof(AreaSettings)} {Unk00} {Unk02}");
foreach (var item in Settings)
sb.AppendLine($"\t{item}");
return sb.ToString().Replace("\r", string.Empty);
}
}
public class Unk0e : IAreaDataCommand
{
[Data] public int Value { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Value = ParseAsInt(nRow, GetToken(nRow, tokens, 1));
}
public override string ToString() =>
$"{nameof(Unk0e)} {Value}";
}
public class Party : IAreaDataCommand
{
[Data] public Ard.Party Value { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Value = (Ard.Party)ParseAsEnum(nRow, GetToken(nRow, tokens, 1), PartyValues);
}
public override string ToString() =>
$"{nameof(Party)} {Value}";
}
public class Bgm : IAreaDataCommand
{
[Data] public short BgmField { get; set; }
[Data] public short BgmBattle { get; set; }
public void Parse(int nRow, List<string> tokens)
{
var token1 = GetToken(nRow, tokens, 1);
var token2 = GetToken(nRow, tokens, 2);
BgmField = token1 == "Default" ? (short)0 : ParseAsShort(nRow, token1);
BgmBattle = token2 == "Default" ? (short)0 : ParseAsShort(nRow, token2);
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append($"{nameof(Bgm)} ");
sb.Append(BgmField == 0 ? "Default" : BgmField.ToString());
sb.Append(" ");
sb.Append(BgmBattle == 0 ? "Default" : BgmBattle.ToString());
return sb.ToString();
}
}
public class MsgWall : IAreaDataCommand
{
[Data] public int Value { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Value = ParseAsInt(nRow, GetToken(nRow, tokens, 1));
}
public override string ToString() =>
$"{nameof(MsgWall)} 0x{Value:x}";
}
public class Camera : IAreaDataCommand
{
[Data] public int Value { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Value = ParseAsInt(nRow, GetToken(nRow, tokens, 1));
}
public override string ToString() =>
$"{nameof(Camera)} {Value}";
}
public class StatusFlag3 : IAreaDataCommand
{
public void Parse(int nRow, List<string> tokens) { }
public override string ToString() => nameof(StatusFlag3);
}
public class Mission : IAreaDataCommand
{
[Data] public int Unk00 { get; set; }
[Data(Count = 32)] public string Value { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Unk00 = ParseAsInt(nRow, GetToken(nRow, tokens, 1));
Value = ParseAsString(nRow, GetToken(nRow, tokens, 2), 32);
}
public override string ToString() =>
$"{nameof(Mission)} 0x{Unk00:X} \"{Value}\"";
}
public class Layout : IAreaDataCommand
{
[Data(Count = 32)] public string Value { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Value = ParseAsString(nRow, GetToken(nRow, tokens, 1), 32);
}
public override string ToString() =>
$"{nameof(Layout)} \"{Value}\"";
}
public class StatusFlag5 : IAreaDataCommand
{
public void Parse(int nRow, List<string> tokens) { }
public override string ToString() => nameof(StatusFlag5);
}
public class AllocEffect : IAreaDataCommand
{
[Data] public int Value1 { get; set; }
[Data] public int Value2 { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Value1 = ParseAsInt(nRow, GetToken(nRow, tokens, 1));
Value2 = ParseAsInt(nRow, GetToken(nRow, tokens, 2));
}
public override string ToString() =>
$"{nameof(AllocEffect)} 0x{Value1:x} 0x{Value2:x}";
}
public class Progress : IAreaDataCommand
{
[Data] public int Value { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Value = ParseAsInt(nRow, GetToken(nRow, tokens, 1));
}
public override string ToString() =>
$"{nameof(Progress)} 0x{Value:x}";
}
public class VisibilityOn : IAreaDataCommand
{
[Data] public int Value { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Value = ParseAsInt(nRow, GetToken(nRow, tokens, 1));
}
public override string ToString() =>
$"{nameof(VisibilityOn)} {Value}";
}
public class VisibilityOff : IAreaDataCommand
{
[Data] public int Value { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Value = ParseAsInt(nRow, GetToken(nRow, tokens, 1));
}
public override string ToString() =>
$"{nameof(VisibilityOff)} {Value}";
}
public class If : IAreaDataCommand
{
[Data] public int Value { get; set; }
public List<IAreaDataCommand> Commands { get; set; }
public void Parse(int nRow, List<string> tokens)
{
throw new Exception($"Parsing an '{nameof(If)}' is not yet supported");
}
public override string ToString() =>
$"{nameof(If)} Entrance {Value}{string.Join("\n\t", Commands)}\n";
}
public class Unk1d : IAreaDataCommand
{
[Data] public int Value { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Value = ParseAsInt(nRow, GetToken(nRow, tokens, 1));
}
public override string ToString() =>
$"{nameof(Unk1d)} {Value}";
}
public class BattleLevel : IAreaDataCommand
{
[Data] public int Value { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Value = ParseAsInt(nRow, GetToken(nRow, tokens, 1));
}
public override string ToString() =>
$"{nameof(BattleLevel)} {Value}";
}
public class Unk1f : IAreaDataCommand
{
[Data(Count = 4)] public string Value { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Value = ParseAsString(nRow, GetToken(nRow, tokens, 1), 4);
}
public override string ToString() =>
$"{nameof(Unk1f)} \"{Value}\"";
}
public class SetEvent : IAreaDataSetting
{
[Data] public short Type { get; set; }
[Data(Count = 4)] public string Value { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Type = ParseAsShort(nRow, GetToken(nRow, tokens, 3));
Value = ParseAsString(nRow, GetToken(nRow, tokens, 1), 4);
}
public override string ToString() =>
$"{nameof(SetEvent)} \"{Value}\" Type {Type}";
}
public class SetJump : IAreaDataSetting
{
[Data] public short Padding { get; set; }
[Data] public short Type { get; set; }
[Data] public short World { get; set; }
[Data] public short Area { get; set; }
[Data] public short Entrance { get; set; }
[Data] public short LocalSet { get; set; }
[Data] public short FadeType { get; set; }
public void Parse(int nRow, List<string> tokens)
{
for (var i = 1; i < tokens.Count; i++)
{
switch (tokens[i++])
{
case nameof(Type):
Type = ParseAsShort(nRow, GetToken(nRow, tokens, i));
break;
case nameof(World):
var worldId = GetToken(nRow, tokens, i);
for (var j = 0; j < Constants.WorldIds.Length; j++)
{
if (worldId.ToLower() == Constants.WorldIds[j])
{
World = (short)j;
break;
}
}
break;
case nameof(Area):
Area = ParseAsShort(nRow, GetToken(nRow, tokens, i));
break;
case nameof(Entrance):
Entrance = ParseAsShort(nRow, GetToken(nRow, tokens, i));
break;
case nameof(LocalSet):
LocalSet = ParseAsShort(nRow, GetToken(nRow, tokens, i));
break;
case nameof(FadeType):
FadeType = ParseAsShort(nRow, GetToken(nRow, tokens, i));
break;
}
}
}
public override string ToString()
{
var items = new List<string>();
items.Add(nameof(SetJump));
items.Add(nameof(Type));
items.Add(Type.ToString());
items.Add(nameof(World));
items.Add(Constants.WorldIds[World].ToUpper());
items.Add(nameof(Area));
items.Add(Area.ToString());
items.Add(nameof(Entrance));
items.Add(Entrance.ToString());
items.Add(nameof(LocalSet));
items.Add(LocalSet.ToString());
items.Add(nameof(FadeType));
items.Add(FadeType.ToString());
return string.Join(" ", items);
}
}
public class SetProgressFlag : IAreaDataSetting
{
[Data] public short Value { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Value = ParseAsShort(nRow, GetToken(nRow, tokens, 1));
}
public override string ToString() =>
$"{nameof(SetProgressFlag)} 0x{Value:X}";
}
public class SetMenuFlag : IAreaDataSetting
{
[Data] public short Value { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Value = ParseAsShort(nRow, GetToken(nRow, tokens, 1));
}
public override string ToString() =>
$"{nameof(SetMenuFlag)} 0x{Value:X}";
}
public class SetMember : IAreaDataSetting
{
[Data] public short Value { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Value = ParseAsShort(nRow, GetToken(nRow, tokens, 1));
}
public override string ToString() =>
$"{nameof(SetMember)} {Value}";
}
public class SetUnk05 : IAreaDataSetting
{
[Data] public short Value { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Value = ParseAsShort(nRow, GetToken(nRow, tokens, 1));
}
public override string ToString() =>
$"{nameof(SetUnk05)} 0x{Value:X}";
}
public class SetInventory : IAreaDataSetting
{
public List<int> Items { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Items = new List<int>();
for (var i = 1; i < tokens.Count; i++)
Items.Add(ParseAsInt(nRow, GetToken(nRow, tokens, i)));
}
public override string ToString() =>
$"{nameof(SetInventory)} {string.Join(" ", Items)}";
}
public class SetPartyMenu : IAreaDataSetting
{
[Data] public short Value { get; set; }
public void Parse(int nRow, List<string> tokens)
{
Value = ParseAsShort(nRow, GetToken(nRow, tokens, 1));
}
public override string ToString() =>
$"{nameof(SetPartyMenu)} {Value}";
}
public class SetUnkFlag : IAreaDataSetting
{
public void Parse(int nRow, List<string> tokens) { }
public override string ToString() =>
$"{nameof(SetUnkFlag)}";
}
public short ProgramId { get; set; }
public List<IAreaDataCommand> Functions { get; set; }
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine($"Program 0x{ProgramId:X02}");
sb.Append(string.Join("\n", Functions));
return sb.ToString().Replace("\r", string.Empty);
}
public static bool IsValid(Stream stream)
{
if (stream.Length == 0)
return false;
var isValid = stream.SetPosition(stream.Length - 4).ReadInt32() == 0x0000FFFF;
stream.SetPosition(0);
return isValid;
}
public static List<AreaDataScript> Read(Stream stream) =>
ReadAll(stream).ToList();
public static IEnumerable<IAreaDataCommand> Read(Stream stream, int programId)
{
while (true)
{
var header = BinaryMapping.ReadObject<Header>(stream);
if (header.Id == Terminator && header.Length == 0)
return null;
if (header.Id == programId)
return ParseScript(stream.ReadBytes(header.Length - 4));
else
stream.Position += header.Length - 4;
}
}
public static void Write(Stream stream, IEnumerable<AreaDataScript> scripts)
{
foreach (var script in scripts)
{
using var dataStream = new MemoryStream();
Write(dataStream, script.Functions);
stream.Write(script.ProgramId);
stream.Write((short)(dataStream.Length + 4));
dataStream.SetPosition(0).CopyTo(stream);
}
stream.Write(0x0000FFFF);
}
public static string Decompile(IEnumerable<AreaDataScript> scripts) =>
string.Join("\n\n", scripts.Select(x => x.ToString()));
public static IEnumerable<AreaDataScript> Compile(string text)
{
const char Comment = '#';
AreaDataScript newScript() => new AreaDataScript
{
Functions = new List<IAreaDataCommand>()
};
var script = newScript();
var state = LexState.Init;
var lines = text
.Replace("\n\r", "\n")
.Replace("\r\n", "\n")
.Replace("\r", "\n")
.Split('\n');
var row = 0;
while (row < lines.Length)
{
var line = lines[row++];
var cleanLine = line.Split(Comment);
var tokens = Tokenize(row, cleanLine[0]).ToList();
if (tokens.Count == 0)
continue;
if (state == LexState.Init && tokens[0] != "Program")
throw new SpawnScriptMissingProgramException(row);
switch (tokens[0])
{
case "Program":
var programId = ParseAsShort(row, GetToken(row, tokens, 1));
if (state == LexState.Code)
{
yield return script;
script = newScript();
}
state = LexState.Code;
script.ProgramId = programId;
break;
case "AreaSettings":
var function = new AreaSettings
{
Settings = new List<IAreaDataSetting>()
};
function.Parse(row, tokens);
script.Functions.Add(function);
while (row < lines.Length && (lines[row].Length == 0 || lines[row][0] == '\t'))
{
line = lines[row++];
cleanLine = line.Split(Comment);
tokens = Tokenize(row, cleanLine[0]).ToList();
if (tokens.Count == 0)
continue;
function.Settings.Add(ParseAreaSetting(row, tokens));
}
break;
default:
script.Functions.Add(ParseCommand(row, tokens));
break;
}
}
yield return script;
}
private static IEnumerable<AreaDataScript> ReadAll(Stream stream)
{
while (true)
{
var header = BinaryMapping.ReadObject<Header>(stream);
if (header.Id == Terminator && header.Length == 0)
yield break;
var bytecode = stream.ReadBytes(header.Length - 4);
yield return new AreaDataScript()
{
ProgramId = header.Id,
Functions = ParseScript(bytecode).ToList()
};
}
}
private static IEnumerable<IAreaDataCommand> ParseScript(byte[] bytecode)
{
for (int pc = 0; pc < bytecode.Length;)
{
var opcode = BitConverter.ToUInt16(bytecode, pc);
var parameterCount = BitConverter.ToUInt16(bytecode, pc + 2);
using var stream = new MemoryStream(bytecode, pc + 4, parameterCount * 4);
var instance = Activator.CreateInstance(_idType[opcode]);
yield return Mapping.ReadObject(stream, instance) as IAreaDataCommand;
pc += 4 + parameterCount * 4;
}
}
private static void Write(Stream stream, IEnumerable<IAreaDataCommand> commands)
{
foreach (var command in commands)
{
using var commandStream = new MemoryStream();
Mapping.WriteObject(commandStream, command);
var opcode = (short)_typeId[command.GetType()];
var parameterCount = (short)(commandStream.Length / 4);
stream.Write(opcode);
stream.Write(parameterCount);
commandStream.SetPosition(0).CopyTo(stream);
}
}
private static object ScriptStringReader(MappingReadArgs args)
{
if (args.Count > 1)
{
var data = args.Reader.ReadBytes(args.Count);
int byteCount;
for (byteCount = 0; byteCount < data.Length; byteCount++)
if (data[byteCount] == 0)
break;
return Encoding.UTF8.GetString(data, 0, byteCount);
}
else
{
var sb = new StringBuilder();
while (true)
{
var ch = args.Reader.ReadByte();
if (ch == 0 || ch < 0)
break;
sb.Append((char)ch);
}
return sb.ToString();
}
}
private static void ScriptStringWriter(MappingWriteArgs args)
{
byte[] data;
var value = (string)args.Item;
if (args.Count == 4)
{
data = new byte[4];
if (value.Length > 2)
{
data[0] = (byte)value[0];
data[1] = (byte)value[1];
data[2] = (byte)value[2];
if (value.Length >= 4)
data[3] = (byte)value[3];
}
else if (value.Length > 0)
{
data[0] = (byte)value[0];
if (value.Length == 2)
data[1] = (byte)value[1];
}
}
else
{
var strData = Encoding.ASCII.GetBytes(value);
var length = args.Count == 1 ? Helpers.Align(strData.Length + 1, 4) : args.Count;
data = new byte[length];
Array.Copy(strData, data, strData.Length);
args.Writer.BaseStream.AlignPosition(4);
}
args.Writer.BaseStream.Write(data);
}
private static object ScriptMultipleStringReader(MappingReadArgs args)
{
var list = new List<string>();
args.Count = 4;
while (args.Reader.BaseStream.Position + 3 < args.Reader.BaseStream.Length)
list.Add(ScriptStringReader(args) as string);
return list;
}
private static void ScriptMultipleStringWriter(MappingWriteArgs args)
{
var items = (List<string>)args.Item;
foreach (var item in items)
{
args.Item = item;
args.Count = 4;
ScriptStringWriter(args);
}
}
private static object AreaSettingsReader(MappingReadArgs args)
{
var reader = args.Reader;
var settings = new AreaSettings
{
Unk00 = reader.ReadInt16(),
Unk02 = reader.ReadInt16(),
Settings = new List<IAreaDataSetting>()
};
while (reader.BaseStream.Position < args.Reader.BaseStream.Length)
{
var opcode = reader.ReadInt16();
var instance = Activator.CreateInstance(_idSetType[opcode]);
instance = Mapping.ReadObject(reader.BaseStream, instance);
settings.Settings.Add(instance as IAreaDataSetting);
}
return settings;
}
private static void AreaSettingsWriter(MappingWriteArgs args)
{
var settings = args.Item as AreaSettings;
args.Writer.Write(settings.Unk00);
args.Writer.Write(settings.Unk02);
foreach (var setting in settings.Settings)
{
var opcode = (short)_typeSetId[setting.GetType()];
args.Writer.Write(opcode);
Mapping.WriteObject(args.Writer.BaseStream, setting);
}
}
private static object SetInventoryReader(MappingReadArgs args)
{
var count = args.Reader.ReadInt16();
return new SetInventory
{
Items = Enumerable
.Range(0, count)
.Select(_ => args.Reader.ReadInt32())
.ToList()
};
}
private static void SetInventoryWriter(MappingWriteArgs args)
{
var items = args.Item as SetInventory;
args.Writer.Write((short)items.Items.Count);
foreach (var item in items.Items)
args.Writer.Write(item);
}
private static object IfReader(MappingReadArgs args)
{
var item = new If
{
Value = args.Reader.ReadInt32(),
Commands = ParseScript(args.Reader.BaseStream.ReadBytes()).ToList()
};
return item;
}
private static void IfWriter(MappingWriteArgs args)
{
var item = args.Item as If;
args.Writer.Write(item.Value);
Write(args.Writer.BaseStream, item.Commands);
}
private static IAreaDataCommand ParseCommand(int nRow, List<string> tokens)
{
var commandName = tokens[0];
if (!_typeStr.TryGetValue(commandName, out var type))
throw new SpawnScriptCommandNotRecognizedException(nRow, commandName);
var command = Activator.CreateInstance(type) as IAreaDataCommand;
command.Parse(nRow, tokens);
return command;
}
private static IAreaDataSetting ParseAreaSetting(int nRow, List<string> tokens)
{
var commandName = tokens[0];
if (!_typeSetStr.TryGetValue(commandName, out var type))
throw new SpawnScriptCommandNotRecognizedException(nRow, commandName);
var setting = Activator.CreateInstance(type) as IAreaDataSetting;
setting.Parse(nRow, tokens);
return setting;
}
private static IEnumerable<string> Tokenize(int row, string line)
{
var sb = new StringBuilder();
for (var i = 0; i < line.Length; i++)
{
var ch = line[i];
if (char.IsWhiteSpace(ch))
{
if (sb.Length > 0)
yield return sb.ToString();
sb.Clear();
continue;
}
else if (ch == '"')
{
sb.Append(ch);
do
{
i++;
if (i >= line.Length)
throw new SpawnScriptParserException(row, $"Missing '\"'.");
sb.Append(ch = line[i]);
} while (ch != '"');
}
else
sb.Append(ch);
}
if (sb.Length > 0)
yield return sb.ToString();
}
private static string GetToken(int row, List<string> tokens, int tokenIndex) =>
tokens[tokenIndex];
public static string ParseAsString(int row, string text, int maxLength)
{
if (text.Length < 2)
throw new SpawnScriptParserException(row, $"Expected a string but got '{text}'");
if (text[0] != '"' || text[text.Length - 1] != '"')
throw new SpawnScriptParserException(row, $"Expected a string but got '{text}' with probably wrong double-quotes.");
text = text.Substring(1, text.Length - 2);
if (text.Length > maxLength)
throw new SpawnScriptStringTooLongException(row, text, maxLength);
return text;
}
private static short ParseAsShort(int row, string text)
{
var value = ParseAsInt(row, text);
if (value < short.MinValue || value > short.MaxValue)
throw new SpawnScriptShortException(row, value);
return (short)value;
}
private static int ParseAsInt(int row, string token)
{
var isHexadecimal = token.Length > 2 &&
token[0] == '0' && token[1] == 'x';
var nStyle = isHexadecimal ? NumberStyles.HexNumber : NumberStyles.Integer;
var strValue = isHexadecimal ? token.Substring(2) : token;
if (!int.TryParse(strValue, nStyle, null, out var value))
throw new SpawnScriptNotANumberException(row, token);
return value;
}
private static float ParseAsFloat(int row, string token)
{
if (!float.TryParse(token, out var value))
throw new SpawnScriptNotANumberException(row, token);
return value;
}
private static int ParseAsEnum(int row, string token, string[] allowValues)
{
for (var i = 0; i < allowValues.Length; i++)
{
if (token == allowValues[i])
return i;
}
throw new SpawnScriptInvalidEnumException(row, token, allowValues);
}
}
}
| |
// 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.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Microsoft.PythonTools;
using Microsoft.PythonTools.Debugger;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Project;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudioTools.Project;
using Microsoft.Win32;
namespace Microsoft.IronPythonTools.Debugger {
class IronPythonLauncher : IProjectLauncher {
private static Process _chironProcess;
private static string _chironDir;
private static int _chironPort;
private static readonly Guid _cpyInterpreterGuid = new Guid("{2AF0F10D-7135-4994-9156-5D01C9C11B7E}");
private static readonly Guid _cpy64InterpreterGuid = new Guid("{9A7A9026-48C1-4688-9D5D-E5699D47D074}");
private readonly IPythonProject _project;
private readonly PythonToolsService _pyService;
private readonly IServiceProvider _serviceProvider;
public IronPythonLauncher(IServiceProvider serviceProvider, PythonToolsService pyService, IPythonProject project) {
_serviceProvider = serviceProvider;
_pyService = pyService;
_project = project;
}
#region IPythonLauncher Members
private static readonly Lazy<string> NoIronPythonHelpPage = new Lazy<string>(() => {
try {
var path = Path.GetDirectoryName(typeof(IronPythonLauncher).Assembly.Location);
return Path.Combine(path, "NoIronPython.html");
} catch (ArgumentException) {
} catch (NotSupportedException) {
}
return null;
});
public int LaunchProject(bool debug) {
LaunchConfiguration config;
try {
config = _project.GetLaunchConfigurationOrThrow();
} catch (NoInterpretersException) {
throw new NoInterpretersException(null, NoIronPythonHelpPage.Value);
}
return Launch(config, debug);
}
public int LaunchFile(string file, bool debug) {
LaunchConfiguration config;
try {
config = _project.GetLaunchConfigurationOrThrow();
} catch (NoInterpretersException) {
throw new NoInterpretersException(null, NoIronPythonHelpPage.Value);
}
return Launch(config, debug);
}
private int Launch(LaunchConfiguration config, bool debug) {
//if (factory.Id == _cpyInterpreterGuid || factory.Id == _cpy64InterpreterGuid) {
// MessageBox.Show(
// "The project is currently set to use the .NET debugger for IronPython debugging but the project is configured to start with a CPython interpreter.\r\n\r\nTo fix this change the debugger type in project properties->Debug->Launch mode.\r\nIf IronPython is not an available interpreter you may need to download it from http://ironpython.codeplex.com.",
// "Visual Studio");
// return VSConstants.S_OK;
//}
string extension = Path.GetExtension(config.ScriptName);
if (string.Equals(extension, ".html", StringComparison.OrdinalIgnoreCase) ||
string.Equals(extension, ".htm", StringComparison.OrdinalIgnoreCase)) {
try {
StartSilverlightApp(config, debug);
} catch (ChironNotFoundException ex) {
MessageBox.Show(ex.Message, Strings.ProductTitle);
}
return VSConstants.S_OK;
}
try {
if (debug) {
if (string.IsNullOrEmpty(config.InterpreterArguments)) {
config.InterpreterArguments = "-X:Debug";
} else if (config.InterpreterArguments.IndexOf("-X:Debug", StringComparison.InvariantCultureIgnoreCase) < 0) {
config.InterpreterArguments = "-X:Debug " + config.InterpreterArguments;
}
var debugStdLib = _project.GetProperty(IronPythonLauncherOptions.DebugStandardLibrarySetting);
bool debugStdLibResult;
if (!bool.TryParse(debugStdLib, out debugStdLibResult) || !debugStdLibResult) {
string interpDir = config.Interpreter.PrefixPath;
config.InterpreterArguments += " -X:NoDebug \"" + System.Text.RegularExpressions.Regex.Escape(Path.Combine(interpDir, "Lib\\")) + ".*\"";
}
using (var dti = DebugLaunchHelper.CreateDebugTargetInfo(_serviceProvider, config)) {
// Set the CLR debugger
dti.Info.clsidCustom = VSConstants.CLSID_ComPlusOnlyDebugEngine;
dti.Info.grfLaunch = (uint)__VSDBGLAUNCHFLAGS.DBGLAUNCH_StopDebuggingOnEnd;
// Clear the CLSID list while launching, then restore it
// so Dispose() can free it.
var clsidList = dti.Info.pClsidList;
dti.Info.pClsidList = IntPtr.Zero;
try {
dti.Launch();
} finally {
dti.Info.pClsidList = clsidList;
}
}
} else {
var psi = DebugLaunchHelper.CreateProcessStartInfo(_serviceProvider, config);
Process.Start(psi).Dispose();
}
} catch (FileNotFoundException) {
}
return VSConstants.S_OK;
}
#endregion
private static Guid? guidSilverlightDebug = new Guid("{032F4B8C-7045-4B24-ACCF-D08C9DA108FE}");
public void StartSilverlightApp(LaunchConfiguration config, bool debug) {
var root = Path.GetFullPath(config.WorkingDirectory).TrimEnd('\\');
var file = Path.Combine(root, config.ScriptName);
int port = EnsureChiron(root);
var url = string.Format(
"http://localhost:{0}/{1}",
port,
(file.StartsWith(root + "\\") ? file.Substring(root.Length + 1) : file.TrimStart('\\')).Replace('\\', '/')
);
StartInBrowser(url, debug ? guidSilverlightDebug : null);
}
public void StartInBrowser(string url, Guid? debugEngine) {
if (debugEngine.HasValue) {
// launch via VS debugger, it'll take care of figuring out the browsers
VsDebugTargetInfo dbgInfo = new VsDebugTargetInfo();
dbgInfo.dlo = (DEBUG_LAUNCH_OPERATION)_DEBUG_LAUNCH_OPERATION3.DLO_LaunchBrowser;
dbgInfo.bstrExe = url;
dbgInfo.clsidCustom = debugEngine.Value;
dbgInfo.grfLaunch = (uint)__VSDBGLAUNCHFLAGS.DBGLAUNCH_StopDebuggingOnEnd | (uint)__VSDBGLAUNCHFLAGS4.DBGLAUNCH_UseDefaultBrowser;
dbgInfo.cbSize = (uint)Marshal.SizeOf(dbgInfo);
VsShellUtilities.LaunchDebugger(_serviceProvider, dbgInfo);
} else {
// run the users default browser
var handler = GetBrowserHandlerProgId();
var browserCmd = (string)Registry.ClassesRoot.OpenSubKey(handler).OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command").GetValue("");
if (browserCmd.IndexOf("%1") != -1) {
browserCmd = browserCmd.Replace("%1", url);
} else {
browserCmd = browserCmd + " " + url;
}
bool inQuote = false;
string cmdLine = null;
for (int i = 0; i < browserCmd.Length; i++) {
if (browserCmd[i] == '"') {
inQuote = !inQuote;
}
if (browserCmd[i] == ' ' && !inQuote) {
cmdLine = browserCmd.Substring(0, i);
break;
}
}
if (cmdLine == null) {
cmdLine = browserCmd;
}
Process.Start(cmdLine, browserCmd.Substring(cmdLine.Length));
}
}
private static string GetBrowserHandlerProgId() {
try {
return (string)Registry.CurrentUser.OpenSubKey("Software").OpenSubKey("Microsoft").OpenSubKey("Windows").OpenSubKey("CurrentVersion").OpenSubKey("Explorer").OpenSubKey("FileExts").OpenSubKey(".html").OpenSubKey("UserChoice").GetValue("Progid");
} catch {
return (string)Registry.ClassesRoot.OpenSubKey(".html").GetValue("");
}
}
private int EnsureChiron(string/*!*/ webSiteRoot) {
Debug.Assert(!webSiteRoot.EndsWith("\\"));
if (_chironDir != webSiteRoot && _chironProcess != null && !_chironProcess.HasExited) {
try {
_chironProcess.Kill();
} catch {
// process already exited
}
_chironProcess = null;
}
if (_chironProcess == null || _chironProcess.HasExited) {
// start Chiron
var chironPath = ChironPath;
// Get a free port
_chironPort = GetFreePort();
// TODO: race condition - the port might be taked by the time Chiron attempts to open it
// TODO: we should wait for Chiron before launching the browser
string commandLine = "/w:" + _chironPort + " /notification /d:";
if (webSiteRoot.IndexOf(' ') != -1) {
commandLine += "\"" + webSiteRoot + "\"";
} else {
commandLine += webSiteRoot;
}
ProcessStartInfo startInfo = new ProcessStartInfo(chironPath, commandLine);
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
_chironDir = webSiteRoot;
_chironProcess = Process.Start(startInfo);
}
return _chironPort;
}
private static int GetFreePort() {
return Enumerable.Range(new Random().Next(1200, 2000), 60000).Except(
from connection in IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections()
select connection.LocalEndPoint.Port
).First();
}
public string ChironPath {
get {
string result = GetPythonInstallDir();
if (result != null) {
result = Path.Combine(result, @"Silverlight\bin\Chiron.exe");
if (File.Exists(result)) {
return result;
}
}
result = Path.Combine(Path.GetDirectoryName(typeof(IronPythonLauncher).Assembly.Location), "Chiron.exe");
if (File.Exists(result)) {
return result;
}
throw new ChironNotFoundException();
}
}
internal static string GetPythonInstallDir() {
using (var ipy = Registry.LocalMachine.OpenSubKey("SOFTWARE\\IronPython")) {
if (ipy != null) {
using (var twoSeven = ipy.OpenSubKey("2.7")) {
if (twoSeven != null) {
using (var installPath = twoSeven.OpenSubKey("InstallPath")) {
var path = installPath.GetValue("") as string;
if (path != null) {
return path;
}
}
}
}
}
}
var paths = Environment.GetEnvironmentVariable("PATH");
if (paths != null) {
foreach (string dir in paths.Split(Path.PathSeparator)) {
try {
if (IronPythonExistsIn(dir)) {
return dir;
}
} catch {
// ignore
}
}
}
return null;
}
private static bool IronPythonExistsIn(string/*!*/ dir) {
return File.Exists(Path.Combine(dir, "ipy.exe"));
}
[Serializable]
class ChironNotFoundException : Exception {
public ChironNotFoundException()
: this(Strings.IronPythonSilverlightToolsNotFound) {
}
public ChironNotFoundException(string message) : base(message) { }
public ChironNotFoundException(string message, Exception inner) : base(message, inner) { }
protected ChironNotFoundException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}
}
}
| |
//using Exortech.NetReflector;
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Xml.Serialization;
using NUnit.Framework;
using SIL.TestUtilities;
using SIL.Text;
namespace SIL.Tests.Text
{
[TestFixture]
public class MultiTextBaseTests
{
[Test]
public void NullConditions()
{
MultiTextBase text = new MultiTextBase();
Assert.AreSame(string.Empty, text["foo"], "never before heard of alternative should give back an empty string");
Assert.AreSame(string.Empty, text["foo"], "second time");
Assert.AreSame(string.Empty, text.GetBestAlternative("fox"));
text.SetAlternative("zox", "");
Assert.AreSame(string.Empty, text["zox"]);
text.SetAlternative("zox", null);
Assert.AreSame(string.Empty, text["zox"], "should still be empty string after setting to null");
text.SetAlternative("zox", "something");
text.SetAlternative("zox", null);
Assert.AreSame(string.Empty, text["zox"], "should still be empty string after setting something and then back to null");
}
[Test]
public void BasicStuff()
{
MultiTextBase text = new MultiTextBase();
text["foo"] = "alpha";
Assert.AreSame("alpha", text["foo"]);
text["foo"] = "beta";
Assert.AreSame("beta", text["foo"]);
text["foo"] = "gamma";
Assert.AreSame("gamma", text["foo"]);
text["bee"] = "beeeee";
Assert.AreSame("gamma", text["foo"], "setting a different alternative should not affect this one");
text["foo"] = null;
Assert.AreSame(string.Empty, text["foo"]);
}
// [Test, NUnit.Framework.Category("UsesObsoleteExpectedExceptionAttribute"), ExpectedException(typeof(ArgumentOutOfRangeException))]
// public void GetIndexerThrowsWhenAltIsMissing()
// {
// MultiTextBase text = new MultiTextBase();
// text["foo"] = "alpha";
// string s = text["gee"];
// }
//
// [Test, NUnit.Framework.Category("UsesObsoleteExpectedExceptionAttribute"), ExpectedException(typeof(ArgumentOutOfRangeException))]
// public void GetExactThrowsWhenAltIsMissing()
// {
// MultiTextBase text = new MultiTextBase();
// text["foo"] = "alpha";
// string s = text.GetExactAlternative("gee");
// }
// [Test]
// public void ImplementsIEnumerable()
// {
// MultiTextBase text = new MultiTextBase();
// IEnumerable ienumerable = text;
// Assert.IsNotNull(ienumerable);
// }
[Test]
public void Count()
{
MultiTextBase text = new MultiTextBase();
Assert.AreEqual(0, text.Count);
text["a"] = "alpha";
text["b"] = "beta";
text["g"] = "gamma";
Assert.AreEqual(3, text.Count);
}
[Test]
public void IterateWithForEach()
{
MultiTextBase text = new MultiTextBase();
text["a"] = "alpha";
text["b"] = "beta";
text["g"] = "gamma";
int i = 0;
foreach (LanguageForm l in text)
{
switch (i)
{
case 0:
Assert.AreEqual("a", l.WritingSystemId);
Assert.AreEqual("alpha", l.Form);
break;
case 1:
Assert.AreEqual("b", l.WritingSystemId);
Assert.AreEqual("beta", l.Form);
break;
case 2:
Assert.AreEqual("g", l.WritingSystemId);
Assert.AreEqual("gamma", l.Form);
break;
}
i++;
}
}
[Test]
public void GetEnumerator()
{
MultiTextBase text = new MultiTextBase();
IEnumerator ienumerator = text.GetEnumerator();
Assert.IsNotNull(ienumerator);
}
[Test]
public void MergeWithEmpty()
{
MultiTextBase old = new MultiTextBase();
MultiTextBase newGuy = new MultiTextBase();
old.MergeIn(newGuy);
Assert.AreEqual(0, old.Count);
old = new MultiTextBase();
old["a"] = "alpha";
old.MergeIn(newGuy);
Assert.AreEqual(1, old.Count);
}
[Test]
public void MergeWithOverlap()
{
MultiTextBase old = new MultiTextBase();
old["a"] = "alpha";
old["b"] = "beta";
MultiTextBase newGuy = new MultiTextBase();
newGuy["b"] = "newbeta";
newGuy["c"] = "charlie";
old.MergeIn(newGuy);
Assert.AreEqual(3, old.Count);
Assert.AreEqual("newbeta", old["b"]);
}
[Test]
public void UsesNextAlternativeWhenMissing()
{
MultiTextBase multiTextBase = new MultiTextBase();
multiTextBase["wsWithNullElement"] = null;
multiTextBase["wsWithEmptyElement"] = "";
multiTextBase["wsWithContent"] = "hello";
Assert.AreEqual(String.Empty, multiTextBase.GetExactAlternative("missingWs"));
Assert.AreEqual(String.Empty, multiTextBase.GetExactAlternative("wsWithEmptyElement"));
Assert.AreEqual("hello", multiTextBase.GetBestAlternative("missingWs"));
Assert.AreEqual("hello", multiTextBase.GetBestAlternative("wsWithEmptyElement"));
Assert.AreEqual("hello*", multiTextBase.GetBestAlternative("wsWithEmptyElement", "*"));
Assert.AreEqual("hello", multiTextBase.GetBestAlternative("wsWithNullElement"));
Assert.AreEqual("hello*", multiTextBase.GetBestAlternative("wsWithNullElement", "*"));
Assert.AreEqual("hello", multiTextBase.GetExactAlternative("wsWithContent"));
Assert.AreEqual("hello", multiTextBase.GetBestAlternative("wsWithContent"));
Assert.AreEqual("hello", multiTextBase.GetBestAlternative("wsWithContent", "*"));
}
[Test]
public void SerializeWithXmlSerializer()
{
MultiTextBase text = new MultiTextBase();
text["foo"] = "alpha";
text["boo"] = "beta";
var answerXPath = "/TestMultiTextHolder[namespace::xsd='http://www.w3.org/2001/XMLSchema' and namespace::xsi='http://www.w3.org/2001/XMLSchema-instance']/name/form";
CheckSerializeWithXmlSerializer(text, answerXPath, 2);
}
[Test]
public void SerializeEmptyWithXmlSerializer()
{
MultiTextBase text = new MultiTextBase();
var answerXpath = "/TestMultiTextHolder[namespace::xsd='http://www.w3.org/2001/XMLSchema' and namespace::xsi='http://www.w3.org/2001/XMLSchema-instance']/name";
CheckSerializeWithXmlSerializer(text, answerXpath, 1);
}
private void CheckSerializeWithXmlSerializer(MultiTextBase multiTextBase, string answer, int matches)
{
XmlSerializer ser = new XmlSerializer(typeof(TestMultiTextHolder));
StringWriter writer = new System.IO.StringWriter();
TestMultiTextHolder holder = new TestMultiTextHolder();
holder.Name = multiTextBase;
ser.Serialize(writer, holder);
var mtxml = writer.GetStringBuilder().ToString();
Debug.WriteLine(mtxml);
AssertThatXmlIn.String(mtxml).HasSpecifiedNumberOfMatchesForXpath(answer, matches);
}
public class TestMultiTextHolder
{
[XmlIgnore]
public MultiTextBase _name;
[XmlElement("name")]
public MultiTextBase Name
{
get { return _name; }
set { _name = value; }
}
}
[Test]
public void ObjectEquals_DifferentNumberOfForms_False()
{
MultiTextBase x = new MultiTextBase();
x["ws"] = "test";
x["ws2"] = "test";
MultiTextBase y = new MultiTextBase();
y["ws"] = "test";
Assert.IsFalse(x.Equals((object) y));
Assert.IsFalse(y.Equals((object) x));
}
[Test]
public void ObjectEquals_SameContent_True()
{
MultiTextBase x = new MultiTextBase();
x["ws"] = "test";
MultiTextBase y = new MultiTextBase();
y.MergeIn(x);
Assert.IsTrue(x.Equals((object) y));
Assert.IsTrue(y.Equals((object) x));
}
[Test]
public void ObjectEquals_Identity_True()
{
MultiTextBase x = new MultiTextBase();
Assert.IsTrue(x.Equals((object) x));
}
[Test]
public void ObjectEquals_DifferentValues_False()
{
MultiTextBase x = new MultiTextBase();
x["ws"] = "test";
MultiTextBase y = new MultiTextBase();
y["ws"] = "test1";
Assert.IsFalse(x.Equals((object) y));
Assert.IsFalse(y.Equals((object) x));
}
[Test]
public void ObjectEquals_DifferentWritingSystems_False()
{
MultiTextBase x = new MultiTextBase();
x["ws"] = "test";
MultiTextBase y = new MultiTextBase();
y["ws1"] = "test";
Assert.IsFalse(x.Equals((object) y));
Assert.IsFalse(y.Equals((object) x));
}
[Test]
public void ObjectEquals_Null_False()
{
MultiTextBase x = new MultiTextBase();
x["ws"] = "test";
Assert.IsFalse(x.Equals((object) null));
}
[Test]
public void Equals_Null_False()
{
MultiTextBase x = new MultiTextBase();
x["ws"] = "test";
Assert.IsFalse(x.Equals(null));
}
[Test]
public void Equals_DifferentNumberOfForms_False()
{
MultiTextBase x = new MultiTextBase();
x["ws"] = "test";
x["ws2"] = "test";
MultiTextBase y = new MultiTextBase();
y["ws"] = "test";
Assert.IsFalse(x.Equals(y));
Assert.IsFalse(y.Equals(x));
}
[Test]
public void Equals_SameContent_True()
{
MultiTextBase x = new MultiTextBase();
x["ws"] = "test";
MultiTextBase y = new MultiTextBase();
y.MergeIn(x);
Assert.IsTrue(x.Equals(y));
Assert.IsTrue(y.Equals(x));
}
[Test]
public void Equals_Identity_True()
{
MultiTextBase x = new MultiTextBase();
Assert.IsTrue(x.Equals(x));
}
[Test]
public void Equals_DifferentValues_False()
{
MultiTextBase x = new MultiTextBase();
x["ws"] = "test";
MultiTextBase y = new MultiTextBase();
y["ws"] = "test1";
Assert.IsFalse(x.Equals(y));
Assert.IsFalse(y.Equals(x));
}
[Test]
public void Equals_DifferentWritingSystems_False()
{
MultiTextBase x = new MultiTextBase();
x["ws"] = "test";
MultiTextBase y = new MultiTextBase();
y["ws1"] = "test";
Assert.IsFalse(x.Equals(y));
Assert.IsFalse(y.Equals(x));
}
[Test]
public void ContainsEqualForm_SameContent_True()
{
MultiTextBase x = new MultiTextBase();
x["ws1"] = "testing";
x["ws"] = "test";
x["ws2"] = "testing";
LanguageForm form = new LanguageForm();
form.WritingSystemId = "ws";
form.Form = "test";
Assert.IsTrue(x.ContainsEqualForm(form));
}
[Test]
public void ContainsEqualForm_DifferentWritingSystem_False()
{
MultiTextBase x = new MultiTextBase();
x["ws"] = "test";
LanguageForm form = new LanguageForm();
form.WritingSystemId = "wss";
form.Form = "test";
Assert.IsFalse(x.ContainsEqualForm(form));
}
[Test]
public void ContainsEqualForm_DifferentValue_False()
{
MultiTextBase x = new MultiTextBase();
x["ws"] = "test";
LanguageForm form = new LanguageForm();
form.WritingSystemId = "ws";
form.Form = "tests";
Assert.IsFalse(x.ContainsEqualForm(form));
}
[Test]
public void HasFormWithSameContent_Identity_True()
{
MultiTextBase x = new MultiTextBase();
x["ws1"] = "testing";
x["ws"] = "test";
x["ws2"] = "testing";
Assert.IsTrue(x.HasFormWithSameContent(x));
}
[Test]
public void HasFormWithSameContent_SameContent_True()
{
MultiTextBase x = new MultiTextBase();
x["ws1"] = "testing";
x["ws"] = "test";
x["ws2"] = "testing";
MultiTextBase y = new MultiTextBase();
x["ws1"] = "testin";
y["ws"] = "test";
Assert.IsTrue(x.HasFormWithSameContent(y));
Assert.IsTrue(y.HasFormWithSameContent(x));
}
[Test]
public void HasFormWithSameContent_DifferentWritingSystem_False()
{
MultiTextBase x = new MultiTextBase();
x["ws"] = "test";
MultiTextBase y = new MultiTextBase();
y["wss"] = "test";
Assert.IsFalse(x.HasFormWithSameContent(y));
Assert.IsFalse(y.HasFormWithSameContent(x));
}
[Test]
public void HasFormWithSameContent_DifferentValue_False()
{
MultiTextBase x = new MultiTextBase();
x["ws"] = "test";
MultiTextBase y = new MultiTextBase();
y["ws"] = "tests";
Assert.IsFalse(x.HasFormWithSameContent(y));
Assert.IsFalse(y.HasFormWithSameContent(x));
}
[Test]
public void HasFormWithSameContent_BothEmpty_True()
{
MultiTextBase x = new MultiTextBase();
MultiTextBase y = new MultiTextBase();
Assert.IsTrue(x.HasFormWithSameContent(y));
Assert.IsTrue(y.HasFormWithSameContent(x));
}
[Test]
public void SetAnnotation()
{
MultiTextBase multiTextBase = new MultiTextBase();
multiTextBase.SetAnnotationOfAlternativeIsStarred("zz", true);
Assert.AreEqual(String.Empty, multiTextBase.GetExactAlternative("zz"));
Assert.IsTrue(multiTextBase.GetAnnotationOfAlternativeIsStarred("zz"));
multiTextBase.SetAnnotationOfAlternativeIsStarred("zz", false);
Assert.IsFalse(multiTextBase.GetAnnotationOfAlternativeIsStarred("zz"));
}
[Test]
public void ClearingAnnotationOfEmptyAlternativeRemovesTheAlternative()
{
MultiTextBase multiTextBase = new MultiTextBase();
multiTextBase.SetAnnotationOfAlternativeIsStarred("zz", true);
multiTextBase.SetAnnotationOfAlternativeIsStarred("zz", false);
Assert.IsFalse(multiTextBase.ContainsAlternative("zz"));
}
[Test]
public void ClearingAnnotationOfNonEmptyAlternative()
{
MultiTextBase multiTextBase = new MultiTextBase();
multiTextBase.SetAnnotationOfAlternativeIsStarred("zz", true);
multiTextBase["zz"] = "hello";
multiTextBase.SetAnnotationOfAlternativeIsStarred("zz", false);
Assert.IsTrue(multiTextBase.ContainsAlternative("zz"));
}
[Test]
public void EmptyingTextOfFlaggedAlternativeDoesNotDeleteIfFlagged()
{
// REVIEW: not clear really what behavior we want here, since user deletes via clearing text
MultiTextBase multiTextBase = new MultiTextBase();
multiTextBase["zz"] = "hello";
multiTextBase.SetAnnotationOfAlternativeIsStarred("zz", true);
multiTextBase["zz"] = "";
Assert.IsTrue(multiTextBase.ContainsAlternative("zz"));
}
[Test]
public void AnnotationOfMisssingAlternative()
{
MultiTextBase multiTextBase = new MultiTextBase();
Assert.IsFalse(multiTextBase.GetAnnotationOfAlternativeIsStarred("zz"));
Assert.IsFalse(multiTextBase.ContainsAlternative("zz"), "should not cause the creation of the alt");
}
[Test]
public void ContainsEqualForm_DifferentStarred_False()
{
MultiTextBase x = new MultiTextBase();
x["ws"] = "test";
LanguageForm form = new LanguageForm();
form.WritingSystemId = "ws";
form.Form = "test";
form.IsStarred = true;
Assert.IsFalse(x.ContainsEqualForm(form));
}
[Test]
public void HasFormWithSameContent_DifferentStarred_False()
{
MultiTextBase x = new MultiTextBase();
x["ws"] = "test";
MultiTextBase y = new MultiTextBase();
y["ws"] = "test";
y.SetAnnotationOfAlternativeIsStarred("ws", true);
Assert.IsFalse(x.HasFormWithSameContent(y));
Assert.IsFalse(y.HasFormWithSameContent(x));
}
[Test]
public void HasFormWithSameContent_OneEmpty_False()
{
MultiTextBase x = new MultiTextBase();
MultiTextBase y = new MultiTextBase();
y["ws"] = "test";
y.SetAnnotationOfAlternativeIsStarred("ws", true);
Assert.IsFalse(x.HasFormWithSameContent(y));
Assert.IsFalse(y.HasFormWithSameContent(x));
}
[Test]
public void GetOrderedAndFilteredForms_EmptyIdList_GivesEmptyList()
{
MultiTextBase x = new MultiTextBase();
x["one"] = "test";
Assert.AreEqual(0, x.GetOrderedAndFilteredForms(new string[] { }).Length);
}
[Test]
public void GetOrderedAndFilteredForms_EmptyMultiText_GivesEmptyList()
{
MultiTextBase x = new MultiTextBase();
LanguageForm[] forms = x.GetOrderedAndFilteredForms(new string[] { "one", "three" });
Assert.AreEqual(0, forms.Length);
}
[Test]
public void GetOrderedAndFilteredForms_GivesFormsInOrder()
{
MultiTextBase x = new MultiTextBase();
x["one"] = "1";
x["two"] = "2";
x["three"] = "3";
LanguageForm[] forms = x.GetOrderedAndFilteredForms(new string[] {"one", "three","two" });
Assert.AreEqual(3, forms.Length);
Assert.AreEqual("1", forms[0].Form);
Assert.AreEqual("3", forms[1].Form);
Assert.AreEqual("2", forms[2].Form);
}
[Test]
public void GetOrderedAndFilteredForms_DropsUnlistedForms()
{
MultiTextBase x = new MultiTextBase();
x["one"] = "1";
x["two"] = "2";
x["three"] = "3";
LanguageForm[] forms = x.GetOrderedAndFilteredForms(new string[] { "one", "three" });
Assert.AreEqual(2, forms.Length);
Assert.AreEqual("1", forms[0].Form);
Assert.AreEqual("3", forms[1].Form);
}
[Test]
public void SetAlternative_ThreeDifferentLanguages_LanguageFormsAreSortedbyWritingSystem()
{
MultiTextBase multiTextBaseToPopulate = new MultiTextBase();
multiTextBaseToPopulate.SetAlternative("fr", "fr Word3");
multiTextBaseToPopulate.SetAlternative("de", "de Word1");
multiTextBaseToPopulate.SetAlternative("en", "en Word2");
Assert.AreEqual(3, multiTextBaseToPopulate.Forms.Length);
Assert.AreEqual("de", multiTextBaseToPopulate.Forms[0].WritingSystemId);
Assert.AreEqual("en", multiTextBaseToPopulate.Forms[1].WritingSystemId);
Assert.AreEqual("fr", multiTextBaseToPopulate.Forms[2].WritingSystemId);
}
[Test]
public void CompareTo_Null_ReturnsGreater()
{
MultiTextBase multiTextBase = new MultiTextBase();
multiTextBase.SetAlternative("de", "Word 1");
MultiTextBase multiTextBaseToCompare = null;
Assert.AreEqual(1, multiTextBase.CompareTo(multiTextBaseToCompare));
}
[Test]
public void CompareTo_MultiTextWithFewerForms_ReturnsGreater()
{
MultiTextBase multiTextBase = new MultiTextBase();
multiTextBase.SetAlternative("de", "Word 1");
MultiTextBase multiTextBaseToCompare = new MultiTextBase();
Assert.AreEqual(1, multiTextBase.CompareTo(multiTextBaseToCompare));
}
[Test]
public void CompareTo_MultiTextWithMoreForms_ReturnsLess()
{
MultiTextBase multiTextBase = new MultiTextBase();
MultiTextBase multiTextBaseToCompare = new MultiTextBase();
multiTextBaseToCompare.SetAlternative("de", "Word 1");
Assert.AreEqual(-1, multiTextBase.CompareTo(multiTextBaseToCompare));
}
[Test]
public void CompareTo_MultiTextWithNonIdenticalWritingSystemsAndFirstNonidenticalWritingSystemIsAlphabeticallyEarlier_ReturnsGreater()
{
MultiTextBase multiTextBase = new MultiTextBase();
multiTextBase.SetAlternative("en", "Word 1");
MultiTextBase multiTextBaseToCompare = new MultiTextBase();
multiTextBaseToCompare.SetAlternative("de", "Word 1");
Assert.AreEqual(1, multiTextBase.CompareTo(multiTextBaseToCompare));
}
[Test]
public void CompareTo_MultiTextWithNonIdenticalWritingSystemsAndFirstNonidenticalWritingSystemIsAlphabeticallyLater_ReturnsLess()
{
MultiTextBase multiTextBase = new MultiTextBase();
multiTextBase.SetAlternative("de", "Word 1");
MultiTextBase multiTextBaseToCompare = new MultiTextBase();
multiTextBaseToCompare.SetAlternative("en", "Word 1");
Assert.AreEqual(-1, multiTextBase.CompareTo(multiTextBaseToCompare));
}
[Test]
public void CompareTo_MultiTextWithNonIdenticalFormsAndFirstNonidenticalFormIsAlphabeticallyEarlier_ReturnsGreater()
{
MultiTextBase multiTextBase = new MultiTextBase();
multiTextBase.SetAlternative("de", "Word 2");
MultiTextBase multiTextBaseToCompare = new MultiTextBase();
multiTextBaseToCompare.SetAlternative("de", "Word 1");
Assert.AreEqual(1, multiTextBase.CompareTo(multiTextBaseToCompare));
}
[Test]
public void CompareTo_MultiTextWithNonIdenticalFormsAndFirstNonidenticalformIsAlphabeticallyLater_ReturnsLess()
{
MultiTextBase multiTextBase = new MultiTextBase();
multiTextBase.SetAlternative("de", "Word 1");
MultiTextBase multiTextBaseToCompare = new MultiTextBase();
multiTextBaseToCompare.SetAlternative("de", "Word 2");
Assert.AreEqual(-1, multiTextBase.CompareTo(multiTextBaseToCompare));
}
[Test]
public void CompareTo_IdenticalMultiText_ReturnsEqual()
{
MultiTextBase multiTextBase = new MultiTextBase();
multiTextBase.SetAlternative("de", "Word 1");
MultiTextBase multiTextBaseToCompare = new MultiTextBase();
multiTextBaseToCompare.SetAlternative("de", "Word 1");
Assert.AreEqual(0, multiTextBase.CompareTo(multiTextBaseToCompare));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol.Models
{
using System.Linq;
/// <summary>
/// Specifies details of the jobs to be created on a schedule.
/// </summary>
public partial class JobSpecification
{
/// <summary>
/// Initializes a new instance of the JobSpecification class.
/// </summary>
public JobSpecification() { }
/// <summary>
/// Initializes a new instance of the JobSpecification class.
/// </summary>
/// <param name="poolInfo">The pool on which the Batch service runs the
/// tasks of jobs created under this schedule.</param>
/// <param name="priority">The priority of jobs created under this
/// schedule.</param>
/// <param name="displayName">The display name for jobs created under
/// this schedule.</param>
/// <param name="usesTaskDependencies">The flag that determines if this
/// job will use tasks with dependencies.</param>
/// <param name="onAllTasksComplete">The action the Batch service
/// should take when all tasks in a job created under this schedule are
/// in the completed state.</param>
/// <param name="onTaskFailure">The action the Batch service should
/// take when any task fails in a job created under this schedule. A
/// task is considered to have failed if it completes with a non-zero
/// exit code and has exhausted its retry count, or if it had a
/// scheduling error.</param>
/// <param name="constraints">The execution constraints for jobs
/// created under this schedule.</param>
/// <param name="jobManagerTask">The details of a Job Manager task to
/// be launched when a job is started under this schedule.</param>
/// <param name="jobPreparationTask">The Job Preparation task for jobs
/// created under this schedule.</param>
/// <param name="jobReleaseTask">The Job Release task for jobs created
/// under this schedule.</param>
/// <param name="commonEnvironmentSettings">A list of common
/// environment variable settings. These environment variables are set
/// for all tasks in jobs created under this schedule (including the
/// Job Manager, Job Preparation and Job Release tasks).</param>
/// <param name="metadata">A list of name-value pairs associated with
/// each job created under this schedule as metadata.</param>
public JobSpecification(PoolInformation poolInfo, int? priority = default(int?), string displayName = default(string), bool? usesTaskDependencies = default(bool?), OnAllTasksComplete? onAllTasksComplete = default(OnAllTasksComplete?), OnTaskFailure? onTaskFailure = default(OnTaskFailure?), JobConstraints constraints = default(JobConstraints), JobManagerTask jobManagerTask = default(JobManagerTask), JobPreparationTask jobPreparationTask = default(JobPreparationTask), JobReleaseTask jobReleaseTask = default(JobReleaseTask), System.Collections.Generic.IList<EnvironmentSetting> commonEnvironmentSettings = default(System.Collections.Generic.IList<EnvironmentSetting>), System.Collections.Generic.IList<MetadataItem> metadata = default(System.Collections.Generic.IList<MetadataItem>))
{
Priority = priority;
DisplayName = displayName;
UsesTaskDependencies = usesTaskDependencies;
OnAllTasksComplete = onAllTasksComplete;
OnTaskFailure = onTaskFailure;
Constraints = constraints;
JobManagerTask = jobManagerTask;
JobPreparationTask = jobPreparationTask;
JobReleaseTask = jobReleaseTask;
CommonEnvironmentSettings = commonEnvironmentSettings;
PoolInfo = poolInfo;
Metadata = metadata;
}
/// <summary>
/// Gets or sets the priority of jobs created under this schedule.
/// </summary>
/// <remarks>
/// Priority values can range from -1000 to 1000, with -1000 being the
/// lowest priority and 1000 being the highest priority. The default
/// value is 0. This priority is used as the default for all jobs under
/// the job schedule. You can update a job's priority after it has been
/// created using by using the update job API.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "priority")]
public int? Priority { get; set; }
/// <summary>
/// Gets or sets the display name for jobs created under this schedule.
/// </summary>
/// <remarks>
/// The name need not be unique and can contain any Unicode characters
/// up to a maximum length of 1024.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "displayName")]
public string DisplayName { get; set; }
/// <summary>
/// Gets or sets the flag that determines if this job will use tasks
/// with dependencies.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "usesTaskDependencies")]
public bool? UsesTaskDependencies { get; set; }
/// <summary>
/// Gets or sets the action the Batch service should take when all
/// tasks in a job created under this schedule are in the completed
/// state.
/// </summary>
/// <remarks>
/// Note that if a job contains no tasks, then all tasks are considered
/// complete. This option is therefore most commonly used with a Job
/// Manager task; if you want to use automatic job termination without
/// a Job Manager, you should initially set onAllTasksComplete to
/// noAction and update the job properties to set onAllTasksComplete to
/// terminateJob once you have finished adding tasks. The default is
/// noAction. Possible values include: 'noAction', 'terminateJob'
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "onAllTasksComplete")]
public OnAllTasksComplete? OnAllTasksComplete { get; set; }
/// <summary>
/// Gets or sets the action the Batch service should take when any task
/// fails in a job created under this schedule. A task is considered to
/// have failed if it completes with a non-zero exit code and has
/// exhausted its retry count, or if it had a scheduling error.
/// </summary>
/// <remarks>
/// The default is noAction. Possible values include: 'noAction',
/// 'performExitOptionsJobAction'
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "onTaskFailure")]
public OnTaskFailure? OnTaskFailure { get; set; }
/// <summary>
/// Gets or sets the execution constraints for jobs created under this
/// schedule.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "constraints")]
public JobConstraints Constraints { get; set; }
/// <summary>
/// Gets or sets the details of a Job Manager task to be launched when
/// a job is started under this schedule.
/// </summary>
/// <remarks>
/// If the job does not specify a Job Manager task, the user must
/// explicitly add tasks to the job using the Task API. If the job does
/// specify a Job Manager task, the Batch service creates the Job
/// Manager task when the job is created, and will try to schedule the
/// Job Manager task before scheduling other tasks in the job.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "jobManagerTask")]
public JobManagerTask JobManagerTask { get; set; }
/// <summary>
/// Gets or sets the Job Preparation task for jobs created under this
/// schedule.
/// </summary>
/// <remarks>
/// If a job has a Job Preparation task, the Batch service will run the
/// Job Preparation task on a compute node before starting any tasks of
/// that job on that compute node.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "jobPreparationTask")]
public JobPreparationTask JobPreparationTask { get; set; }
/// <summary>
/// Gets or sets the Job Release task for jobs created under this
/// schedule.
/// </summary>
/// <remarks>
/// The primary purpose of the Job Release task is to undo changes to
/// compute nodes made by the Job Preparation task. Example activities
/// include deleting local files, or shutting down services that were
/// started as part of job preparation. A Job Release task cannot be
/// specified without also specifying a Job Preparation task for the
/// job. The Batch service runs the Job Release task on the compute
/// nodes that have run the Job Preparation task.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "jobReleaseTask")]
public JobReleaseTask JobReleaseTask { get; set; }
/// <summary>
/// Gets or sets a list of common environment variable settings. These
/// environment variables are set for all tasks in jobs created under
/// this schedule (including the Job Manager, Job Preparation and Job
/// Release tasks).
/// </summary>
/// <remarks>
/// Individual tasks can override an environment setting specified here
/// by specifying the same setting name with a different value.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "commonEnvironmentSettings")]
public System.Collections.Generic.IList<EnvironmentSetting> CommonEnvironmentSettings { get; set; }
/// <summary>
/// Gets or sets the pool on which the Batch service runs the tasks of
/// jobs created under this schedule.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "poolInfo")]
public PoolInformation PoolInfo { get; set; }
/// <summary>
/// Gets or sets a list of name-value pairs associated with each job
/// created under this schedule as metadata.
/// </summary>
/// <remarks>
/// The Batch service does not assign any meaning to metadata; it is
/// solely for the use of user code.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "metadata")]
public System.Collections.Generic.IList<MetadataItem> Metadata { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (PoolInfo == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "PoolInfo");
}
if (this.JobManagerTask != null)
{
this.JobManagerTask.Validate();
}
if (this.JobPreparationTask != null)
{
this.JobPreparationTask.Validate();
}
if (this.JobReleaseTask != null)
{
this.JobReleaseTask.Validate();
}
if (this.CommonEnvironmentSettings != null)
{
foreach (var element in this.CommonEnvironmentSettings)
{
if (element != null)
{
element.Validate();
}
}
}
if (this.PoolInfo != null)
{
this.PoolInfo.Validate();
}
if (this.Metadata != null)
{
foreach (var element1 in this.Metadata)
{
if (element1 != null)
{
element1.Validate();
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.Msagl.Core.DataStructures;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.Geometry.Curves;
namespace Microsoft.Msagl.Routing.Visibility {
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")]
internal class TangentVisibilityGraphCalculator {
/// <summary>
/// the list of obstacles
/// </summary>
List<Polygon> polygons;
VisibilityGraph visibilityGraph;
List<Diagonal> diagonals;
List<Tangent> tangents;
RbTree<Diagonal> activeDiagonalTree;
Polygon currentPolygon;
ActiveDiagonalComparerWithRay activeDiagonalComparer = new ActiveDiagonalComparerWithRay();
bool useLeftPTangents;
internal static void AddTangentVisibilityEdgesToGraph(List<Polygon> holes, VisibilityGraph visibilityGraph) {
if (holes.Count > 1) {
TangentVisibilityGraphCalculator calculator = new TangentVisibilityGraphCalculator(holes, visibilityGraph, true);
calculator.CalculateAndAddEdges();
//use another family of tangents
calculator = new TangentVisibilityGraphCalculator(holes, visibilityGraph, false);
calculator.CalculateAndAddEdges();
}
}
private void CalculateAndAddEdges() {
for (int i = 0; i < polygons.Count; i++)
CalculateVisibleTangentsFromPolygon(i);
}
private void CalculateVisibleTangentsFromPolygon(int i) {
AllocateDataStructures(i);
OrganizeTangents();
InitActiveDiagonals();
Sweep();
}
private void AllocateDataStructures(int i) {
tangents = new List<Tangent>();
diagonals = new List<Diagonal>();
activeDiagonalTree = new RbTree<Diagonal>(this.activeDiagonalComparer);
this.currentPolygon = polygons[i];
}
private void Sweep() {
if (tangents.Count < 2)
return;
for (int i = 1; i < tangents.Count; i++) { //we processed the first element already
Tangent t = tangents[i];
if (t.Diagonal != null) {
if (t.Diagonal.RbNode == activeDiagonalTree.TreeMinimum())
AddVisibleEdge(t);
if (t.IsHigh)
RemoveDiagonalFromActiveNodes(t.Diagonal);
} else {
if (t.IsLow) {
this.activeDiagonalComparer.PointOnTangentAndInsertedDiagonal = t.End.Point;
this.InsertActiveDiagonal(new Diagonal(t, t.Comp));
if (t.Diagonal.RbNode == activeDiagonalTree.TreeMinimum())
AddVisibleEdge(t);
}
}
#if TEST_MSAGL
//List<ICurve> cs = new List<ICurve>();
//foreach (Diagonal d in this.activeDiagonalTree) {
// cs.Add(new LineSegment(d.Start, d.End));
//}
//foreach (Polygon p in this.polygons)
// cs.Add(p.Polyline);
//cs.Add(new LineSegment(t.Start.Point, t.End.Point));
//SugiyamaLayoutSettings.Show(cs.ToArray);
#endif
}
}
private void AddVisibleEdge(Tangent t) {
VisibilityGraph.AddEdge(visibilityGraph.GetVertex(t.Start), visibilityGraph.GetVertex(t.End));
}
/// <summary>
/// this function will also add the first tangent to the visible edges if needed
/// </summary>
private void InitActiveDiagonals() {
Tangent firstTangent = this.tangents[0];
Point firstTangentStart = firstTangent.Start.Point;
Point firstTangentEnd = firstTangent.End.Point;
foreach (Diagonal diagonal in diagonals) {
if (RayIntersectDiagonal(firstTangentStart, firstTangentEnd, diagonal)) {
this.activeDiagonalComparer.PointOnTangentAndInsertedDiagonal =
ActiveDiagonalComparerWithRay.IntersectDiagonalWithRay(firstTangentStart, firstTangentEnd, diagonal);
InsertActiveDiagonal(diagonal);
}
}
if (firstTangent.Diagonal.RbNode == this.activeDiagonalTree.TreeMinimum())
AddVisibleEdge(firstTangent);
if (firstTangent.IsLow == false) { //remove the diagonal of the top tangent from active edges
Diagonal diag = firstTangent.Diagonal;
RemoveDiagonalFromActiveNodes(diag);
}
}
#if DEBUG && TEST_MSAGL
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
private void AddPolylinesForShow(List<ICurve> curves) {
foreach (Polygon p in this.polygons)
curves.Add(p.Polyline);
}
#endif
private void RemoveDiagonalFromActiveNodes(Diagonal diag) {
RBNode<Diagonal> changedNode = activeDiagonalTree.DeleteSubtree(diag.RbNode);
if (changedNode != null)
if (changedNode.Item != null)
changedNode.Item.RbNode = changedNode;
diag.LeftTangent.Diagonal = null;
diag.RightTangent.Diagonal = null;
}
private void InsertActiveDiagonal(Diagonal diagonal) {
diagonal.RbNode = activeDiagonalTree.Insert(diagonal);
MarkDiagonalAsActiveInTangents(diagonal);
}
private static void MarkDiagonalAsActiveInTangents(Diagonal diagonal) {
diagonal.LeftTangent.Diagonal = diagonal;
diagonal.RightTangent.Diagonal = diagonal;
}
static bool RayIntersectDiagonal(Point pivot, Point pointOnRay, Diagonal diagonal) {
Point a = diagonal.Start;
Point b = diagonal.End;
return Point.GetTriangleOrientation(pivot, a, b) == TriangleOrientation.Counterclockwise
&&
Point.GetTriangleOrientation(pivot, pointOnRay, a) != TriangleOrientation.Counterclockwise
&&
Point.GetTriangleOrientation(pivot, pointOnRay, b) != TriangleOrientation.Clockwise;
}
/// <summary>
/// compare tangents by measuring the counterclockwise angle between the tangent and the edge
/// </summary>
/// <param name="e0"></param>
/// <param name="e1"></param>
/// <returns></returns>
int TangentComparison(Tangent e0, Tangent e1) {
return StemStartPointComparer.CompareVectorsByAngleToXAxis(e0.End.Point - e0.Start.Point, e1.End.Point - e1.Start.Point);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "cc")]
private void OrganizeTangents() {
foreach (Polygon q in polygons)
if (q != this.currentPolygon)
ProcessPolygonQ(q);
this.tangents.Sort(new Comparison<Tangent>(TangentComparison));
/////debug
//List<ICurve> cc = new List<ICurve>();
//foreach (Tangent t in this.tangents)
// cc.Add(new LineSegment(t.Start.Point, t.End.Point));
//foreach (Polygon p in polygons)
// cc.Add(p.Polyline);
//SugiyamaLayoutSettings.Show(cc.ToArray());
////end debug
}
private void ProcessPolygonQ(Polygon q) {
TangentPair tangentPair = new TangentPair(currentPolygon, q);
if (this.useLeftPTangents)
tangentPair.CalculateLeftTangents();
else
tangentPair.CalculateRightTangents();
Tuple<int, int> couple = useLeftPTangents ? tangentPair.leftPLeftQ : tangentPair.rightPLeftQ;
Tangent t0 = new Tangent(currentPolygon[couple.Item1], q[couple.Item2]);
t0.IsLow = true;
t0.SeparatingPolygons = !this.useLeftPTangents;
couple = useLeftPTangents ? tangentPair.leftPRightQ : tangentPair.rightPRightQ;
Tangent t1 = new Tangent(currentPolygon[couple.Item1], q[couple.Item2]);
t1.IsLow = false;
t1.SeparatingPolygons = this.useLeftPTangents;
t0.Comp = t1;
t1.Comp = t0;
this.tangents.Add(t0);
this.tangents.Add(t1);
this.diagonals.Add(new Diagonal(t0, t1));
}
TangentVisibilityGraphCalculator(List<Polygon> holes, VisibilityGraph visibilityGraph, bool useLeftPTangents) {
this.polygons = holes;
this.visibilityGraph = visibilityGraph;
this.useLeftPTangents = useLeftPTangents;
}
internal delegate bool FilterVisibleEdgesDelegate(Point a, Point b);
}
}
| |
// 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 System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Core.Data;
using ArcGIS.Core.Data.UtilityNetwork;
using ArcGIS.Core.Data.UtilityNetwork.Trace;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Core.Geoprocessing;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Dialogs;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Internal.Mapping;
using ArcGIS.Desktop.Mapping;
using ArcGIS.Desktop.Mapping.Events;
using UtilityNetworkSamples;
namespace LoadReportSample
{
/// <summary>
/// This add-in demonstrates the creation of a simple electric distribution report. It traces downstream from a given point and adds up the count of customers and total load per phase. This sample
/// is meant to be a demonstration on how to use the Utility Network portions of the SDK. The report display is rudimentary. Look elsewhere in the SDK for better examples on how to display data.
///
/// Rather than coding special logic to pick a starting point, this sample leverages the existing Set Trace Locations tool that is included with the product.
/// That tool writes rows to a table called UN_Temp_Starting_Points, which is stored in the default project workspace. This sample reads rows from that table and uses them as starting points
/// for our downstream trace.
/// </summary>
/// <remarks>
/// Instructions for use
/// 1. Select a utility network layer or a feature layer that participates in a utility network
/// 2. Click on the Load Report SDK Sample tab on the Utility Network tab group
/// 3. Click on the Starting Points tool to create a starting point on the map
/// 4. Click on the Create Load Report tool
/// </remarks>
internal class CreateLoadReport : Button
{
// Constants - used with the starting points table created by the Set Trace Locations tool
private const string StartingPointsTableName = "UN_Temp_Starting_Points";
private const string PointsSourceIDFieldName = "SourceID";
private const string PointsAssetGroupFieldName = "AssetGroupCode";
private const string PointsAssetTypeFieldName = "AssetType";
private const string PointsGlobalIDFieldName = "FEATUREGLOBALID";
private const string PointsTerminalFieldName = "TERMINALID";
private const string PointsPercentAlong = "PERCENTALONG";
// Constants - used with the provided sample data
private const string ElectricDomainNetwork = "Electric";
private const string MediumVoltageTier = "Electric Distribution";
private const string ServicePointCategory = "Service Point";
private const string PhaseAttributeName = "E:Phases Current";
private const string LoadAttributeName = "Customer Load";
private const short APhase = 4;
private const short BPhase = 2;
private const short CPhase = 1;
/// <summary>
/// OnClick
///
/// This is the implementation of our button. We pass the selected layer to GenerateReport() which does the bulk of the work.
/// We then display the results, along with error messages, in a MessageBox.
///
/// </summary>
protected override async void OnClick()
{
// Start by checking to make sure we have a single feature layer selected
if (MapView.Active == null)
{
MessageBox.Show("Please select a utility network layer.", "Create Load Report");
return;
}
MapViewEventArgs mapViewEventArgs = new MapViewEventArgs(MapView.Active);
if (mapViewEventArgs.MapView.GetSelectedLayers().Count != 1)
{
MessageBox.Show("Please select a utility network layer.", "Create Load Report");
return;
}
Layer selectionLayer = mapViewEventArgs.MapView.GetSelectedLayers()[0];
if (!(selectionLayer is UtilityNetworkLayer) && !(selectionLayer is FeatureLayer) && !(selectionLayer is SubtypeGroupLayer))
{
MessageBox.Show("Please select a utility network layer.", "Create Load Report");
return;
}
// Generate our report. The LoadTraceResults class is used to pass back results from the worker thread to the UI thread that we're currently executing.
LoadTraceResults traceResults = await QueuedTask.Run<LoadTraceResults>(() =>
{
return GenerateReport(selectionLayer);
});
// Assemble a string to show in the message box
string traceResultsString;
if (traceResults.Success)
{
traceResultsString = String.Format("Customers per Phase:\n A: {0}\n B: {1}\n C: {2}\n\nLoad per Phase:\n A: {3}\n B: {4}\n C: {5}\n\n{6}",
traceResults.NumberServicePointsA.ToString(), traceResults.NumberServicePointsB.ToString(), traceResults.NumberServicePointsC.ToString(),
traceResults.TotalLoadA.ToString(), traceResults.TotalLoadB.ToString(), traceResults.TotalLoadC.ToString(),
traceResults.Message);
}
else
{
traceResultsString = traceResults.Message;
}
// Show our results
MessageBox.Show(traceResultsString, "Create Load Report");
}
/// <summary>
/// GenerateReport
///
/// This routine takes a feature layer that references a feature class that participates in a utility network.
/// It returns a set of data to display on the UI thread.
///
///
/// </summary>
public LoadTraceResults GenerateReport(Layer selectedLayer)
{
// Create a new results object. We use this class to pass back a set of data from the worker thread to the UI thread
LoadTraceResults results = new LoadTraceResults();
// Initialize a number of geodatabase objects
using (UtilityNetwork utilityNetwork = UtilityNetworkUtils.GetUtilityNetworkFromLayer(selectedLayer))
{
if (utilityNetwork == null)
{
results.Message = "Please select a utility network layer.";
results.Success = false;
}
else if (!ValidateDataModel(utilityNetwork))
{
results.Message = "This sample is designed for a different utility network data model";
results.Success = false;
}
else
{
using (Geodatabase utilityNetworkGeodatabase = utilityNetwork.GetDatastore() as Geodatabase)
using (UtilityNetworkDefinition utilityNetworkDefinition = utilityNetwork.GetDefinition())
using (Geodatabase defaultGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(Project.Current.DefaultGeodatabasePath))))
using (TraceManager traceManager = utilityNetwork.GetTraceManager())
{
// Get a row from the starting points table in the default project workspace. This table is created the first time the user creates a starting point
// If the table is missing or empty, a null row is returned
using (Row startingPointRow = GetStartingPointRow(defaultGeodatabase, ref results))
{
if (startingPointRow != null)
{
// Convert starting point row into network element
Element startingPointElement = GetElementFromPointRow(startingPointRow, utilityNetwork, utilityNetworkDefinition);
// Obtain a tracer object
DownstreamTracer downstreamTracer = traceManager.GetTracer<DownstreamTracer>();
// Get the network attributes that we will use in our trace
using (NetworkAttribute phasesNetworkAttribute = utilityNetworkDefinition.GetNetworkAttribute(PhaseAttributeName))
using (NetworkAttribute loadNetworkAttribute = utilityNetworkDefinition.GetNetworkAttribute(LoadAttributeName))
{
if (phasesNetworkAttribute == null || loadNetworkAttribute == null )
{
results.Success = false;
results.Message = "This add-in requires network attributes for phase, service load, and device status.\n";
return results;
}
// Get the Domain Network and Medium Voltage Tier
DomainNetwork electricDomainNetwork = utilityNetworkDefinition.GetDomainNetwork(ElectricDomainNetwork);
Tier mediumVoltageTier = electricDomainNetwork.GetTier(MediumVoltageTier);
// Set up the trace configuration
TraceConfiguration traceConfiguration = new TraceConfiguration();
// Configure the trace to use the electric domain network
traceConfiguration.DomainNetwork = electricDomainNetwork;
// Take the default TraceConfiguration from the Tier for Traversability
Traversability tierTraceTraversability = mediumVoltageTier.TraceConfiguration.Traversability;
traceConfiguration.Traversability.FunctionBarriers = tierTraceTraversability.FunctionBarriers;
traceConfiguration.Traversability.Scope = tierTraceTraversability.Scope;
ConditionalExpression baseCondition = tierTraceTraversability.Barriers as ConditionalExpression;
// Set to false to ensure that ServicePoints with incorrect phasing (which therefore act as barriers)
// are not counted with results
traceConfiguration.IncludeBarriersWithResults = false;
// Create a condition to only return features that have the service point category
ConditionalExpression servicePointCategoryCondition = new CategoryComparison(CategoryOperator.IsEqual, ServicePointCategory);
// Create function to sum loads on service points where phase = A
ConditionalExpression aPhaseCondition = new NetworkAttributeComparison(phasesNetworkAttribute, Operator.DoesNotIncludeTheValues, APhase);
Add aPhaseLoad = new Add(loadNetworkAttribute, servicePointCategoryCondition);
// Create function to sum loads on service points where phase = B
ConditionalExpression bPhaseCondition = new NetworkAttributeComparison(phasesNetworkAttribute, Operator.DoesNotIncludeTheValues, BPhase);
Add bPhaseLoad = new Add(loadNetworkAttribute, servicePointCategoryCondition);
// Create function to sum loads on service points where phase = C
ConditionalExpression cPhaseCondition = new NetworkAttributeComparison(phasesNetworkAttribute, Operator.DoesNotIncludeTheValues, CPhase);
Add cPhaseLoad = new Add(loadNetworkAttribute, servicePointCategoryCondition);
// Set the output condition to only return features that have the service point category
traceConfiguration.OutputCondition = servicePointCategoryCondition;
// Create starting point list and trace argument object
List<Element> startingPointList = new List<Element>() { startingPointElement };
TraceArgument traceArgument = new TraceArgument(startingPointList);
traceArgument.Configuration = traceConfiguration;
// Trace on the A phase
traceConfiguration.Traversability.Barriers = new Or(baseCondition, aPhaseCondition);
traceConfiguration.Functions = new List<Function>() { aPhaseLoad };
traceArgument.Configuration = traceConfiguration;
try
{
IReadOnlyList<Result> resultsA = downstreamTracer.Trace(traceArgument);
ElementResult elementResult = resultsA.OfType<ElementResult>().First();
results.NumberServicePointsA = elementResult.Elements.Count;
FunctionOutputResult functionOutputResult = resultsA.OfType<FunctionOutputResult>().First();
results.TotalLoadA = (double)functionOutputResult.FunctionOutputs.First().Value;
}
catch (ArcGIS.Core.Data.GeodatabaseUtilityNetworkException e)
{
//No A phase connectivity to source
if (!e.Message.Equals("No subnetwork source was discovered."))
{
results.Success = false;
results.Message += "No Subnetwork source was discovered for Phase A.\n";
}
}
// Trace on the B phase
traceConfiguration.Traversability.Barriers = new Or(baseCondition, bPhaseCondition);
traceConfiguration.Functions = new List<Function>() { bPhaseLoad };
traceArgument.Configuration = traceConfiguration;
try
{
IReadOnlyList<Result> resultsB = downstreamTracer.Trace(traceArgument);
ElementResult elementResult = resultsB.OfType<ElementResult>().First();
results.NumberServicePointsB = elementResult.Elements.Count;
FunctionOutputResult functionOutputResult = resultsB.OfType<FunctionOutputResult>().First();
results.TotalLoadB = (double)functionOutputResult.FunctionOutputs.First().Value;
}
catch (ArcGIS.Core.Data.GeodatabaseUtilityNetworkException e)
{
// No B phase connectivity to source
if (!e.Message.Equals("No subnetwork source was discovered."))
{
results.Success = false;
results.Message += "No Subnetwork source was discovered for Phase B.\n";
}
}
// Trace on the C phase
traceConfiguration.Traversability.Barriers = new Or(baseCondition, cPhaseCondition);
traceConfiguration.Functions = new List<Function>() { cPhaseLoad };
traceArgument.Configuration = traceConfiguration;
try
{
IReadOnlyList<Result> resultsC = downstreamTracer.Trace(traceArgument);
ElementResult elementResult = resultsC.OfType<ElementResult>().First();
results.NumberServicePointsC = elementResult.Elements.Count;
FunctionOutputResult functionOutputResult = resultsC.OfType<FunctionOutputResult>().First();
results.TotalLoadC = (double)functionOutputResult.FunctionOutputs.First().Value;
}
catch (ArcGIS.Core.Data.GeodatabaseUtilityNetworkException e)
{
// No C phase connectivity to source
if (!e.Message.Equals("No subnetwork source was discovered."))
{
results.Success = false;
results.Message += "No Subnetwork source was discovered for Phase C.\n";
}
}
}
// append success message to the output string
results.Message += "Trace successful.";
results.Success = true;
}
}
}
}
}
return results;
}
/// <summary>
/// GetStartingPointRow
///
/// This routine opens up the starting points table and tries to read a row. This table is created in
/// the default project workspace when the user first creates a starting point.
///
/// If the table doesn't exist or is empty, we add an error to our results object a null row.
/// If the table contains one row, we just return the row
/// If the table contains more than one row, we return the first row, and log a warning message
/// (this tool only works with one starting point)
///
/// </summary>
private Row GetStartingPointRow(Geodatabase defaultGeodatabase, ref LoadTraceResults results)
{
try
{
using (FeatureClass startingPointsFeatureClass = defaultGeodatabase.OpenDataset<FeatureClass>(StartingPointsTableName))
using (RowCursor startingPointsCursor = startingPointsFeatureClass.Search())
{
if (startingPointsCursor.MoveNext())
{
Row row = startingPointsCursor.Current;
if (startingPointsCursor.MoveNext())
{
// If starting points table has more than one row, append warning message
results.Message += "Multiple starting points found. Only the first one was used.";
startingPointsCursor.Current.Dispose();
}
return row;
}
else
{
// If starting points table has no rows, exit with error message
results.Message += "No starting points found. Please create one using the Set Trace Locations tool.\n";
results.Success = false;
return null;
}
}
}
// If we cannot open the feature class, an exception is thrown
catch (Exception)
{
results.Message += "No starting points found. Please create one using the Set Trace Locations tool.\n";
results.Success = false;
return null;
}
}
/// <summary>
/// This routine takes a row from the starting (or barrier) point table and converts it to a [Network] Element that we can use for tracing
/// </summary>
/// <param name="pointRow">The Row (either starting point or barrier point)</param>
/// <param name="utilityNetwork">Utility Network to be used</param>
/// <param name="definition">Utility Network definition to be used</param>
/// <returns>newly created element</returns>
private static Element GetElementFromPointRow(Row pointRow,
UtilityNetwork utilityNetwork, UtilityNetworkDefinition definition)
{
// Fetch the SourceID, AssetGroupCode, AssetType, GlobalID, and TerminalID values from the starting point row
int sourceID = (int)pointRow[PointsSourceIDFieldName];
int assetGroupID = (int)pointRow[PointsAssetGroupFieldName];
int assetTypeID = (int)pointRow[PointsAssetTypeFieldName];
Guid globalID = new Guid(pointRow[PointsGlobalIDFieldName].ToString());
int terminalID = (int)pointRow[PointsTerminalFieldName];
double percentAlong = (double)pointRow[PointsPercentAlong];
// Fetch the NetworkSource, AssetGroup, and AssetType objects
NetworkSource networkSource = definition.GetNetworkSources().First(x => x.ID == sourceID);
AssetGroup assetGroup = networkSource.GetAssetGroups().First(x => x.Code == assetGroupID);
AssetType assetType = assetGroup.GetAssetTypes().First(x => x.Code == assetTypeID);
// Fetch the Terminal object from the ID
Terminal terminal = null;
if (assetType.IsTerminalConfigurationSupported())
{
TerminalConfiguration terminalConfiguration = assetType.GetTerminalConfiguration();
terminal = terminalConfiguration.Terminals.First(x => x.ID == terminalID);
}
// Create and return a FeatureElement object
// If we have an edge, set the PercentAlongEdge property; otherwise set the Terminal property
if (networkSource.Type == SourceType.Edge)
{
Element element = utilityNetwork.CreateElement(assetType, globalID);
element.PercentAlongEdge = percentAlong;
return element;
}
else
{
Element element = utilityNetwork.CreateElement(assetType, globalID, terminal);
return element;
}
}
/// <summary>
/// This routine validates the utility network schema matches what we are expecting
/// </summary>
/// <param name="utilityNetwork"></param>
/// <returns>true if the data model has all of the correct schema</returns>
private bool ValidateDataModel(UtilityNetwork utilityNetwork)
{
bool dataModelIsValid = false;
using (UtilityNetworkDefinition utilityNetworkDefinition = utilityNetwork.GetDefinition())
{
try
{
DomainNetwork electricDomainNetwork = utilityNetworkDefinition.GetDomainNetwork(ElectricDomainNetwork);
Tier mediumVoltageTier = electricDomainNetwork.GetTier(MediumVoltageTier);
NetworkAttribute phaseNetworkAttribute = utilityNetworkDefinition.GetNetworkAttribute(PhaseAttributeName);
NetworkAttribute loadNetworkAttribute = utilityNetworkDefinition.GetNetworkAttribute(LoadAttributeName);
if (utilityNetworkDefinition.GetAvailableCategories().Contains(ServicePointCategory))
{
dataModelIsValid = true;
}
}
catch (Exception) { };
}
return dataModelIsValid;
}
}
}
| |
using Microsoft.Practices.ServiceLocation;
using Prism.Properties;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Windows;
namespace Prism.Regions
{
/// <summary>
/// Implementation of <see cref="IRegion"/> that allows multiple active views.
/// </summary>
public class Region : IRegion
{
private ObservableCollection<ItemMetadata> itemMetadataCollection;
private string name;
private ViewsCollection views;
private ViewsCollection activeViews;
private object context;
private IRegionManager regionManager;
private IRegionNavigationService regionNavigationService;
private Comparison<object> sort;
/// <summary>
/// Initializes a new instance of <see cref="Region"/>.
/// </summary>
public Region()
{
this.Behaviors = new RegionBehaviorCollection(this);
this.sort = Region.DefaultSortComparison;
}
/// <summary>
/// Occurs when a property value changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Gets the collection of <see cref="IRegionBehavior"/>s that can extend the behavior of regions.
/// </summary>
public IRegionBehaviorCollection Behaviors { get; private set; }
/// <summary>
/// Gets or sets a context for the region. This value can be used by the user to share context with the views.
/// </summary>
/// <value>The context value to be shared.</value>
public object Context
{
get
{
return this.context;
}
set
{
if (this.context != value)
{
this.context = value;
this.OnPropertyChanged("Context");
}
}
}
/// <summary>
/// Gets the name of the region that uniequely identifies the region within a <see cref="IRegionManager"/>.
/// </summary>
/// <value>The name of the region.</value>
public string Name
{
get
{
return this.name;
}
set
{
if (this.name != null && this.name != value)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.CannotChangeRegionNameException, this.name));
}
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(Resources.RegionNameCannotBeEmptyException);
}
this.name = value;
this.OnPropertyChanged("Name");
}
}
/// <summary>
/// Gets a readonly view of the collection of views in the region.
/// </summary>
/// <value>An <see cref="IViewsCollection"/> of all the added views.</value>
public virtual IViewsCollection Views
{
get
{
if (this.views == null)
{
this.views = new ViewsCollection(ItemMetadataCollection, x => true);
this.views.SortComparison = this.sort;
}
return this.views;
}
}
/// <summary>
/// Gets a readonly view of the collection of all the active views in the region.
/// </summary>
/// <value>An <see cref="IViewsCollection"/> of all the active views.</value>
public virtual IViewsCollection ActiveViews
{
get
{
if (this.activeViews == null)
{
this.activeViews = new ViewsCollection(ItemMetadataCollection, x => x.IsActive);
this.activeViews.SortComparison = this.sort;
}
return this.activeViews;
}
}
/// <summary>
/// Gets or sets the comparison used to sort the views.
/// </summary>
/// <value>The comparison to use.</value>
public Comparison<object> SortComparison
{
get
{
return this.sort;
}
set
{
this.sort = value;
if (this.activeViews != null)
{
this.activeViews.SortComparison = this.sort;
}
if (this.views != null)
{
this.views.SortComparison = this.sort;
}
}
}
/// <summary>
/// Gets or sets the <see cref="IRegionManager"/> that will be passed to the views when adding them to the region, unless the view is added by specifying createRegionManagerScope as <see langword="true" />.
/// </summary>
/// <value>The <see cref="IRegionManager"/> where this <see cref="IRegion"/> is registered.</value>
/// <remarks>This is usually used by implementations of <see cref="IRegionManager"/> and should not be
/// used by the developer explicitely.</remarks>
public IRegionManager RegionManager
{
get
{
return this.regionManager;
}
set
{
if (this.regionManager != value)
{
this.regionManager = value;
this.OnPropertyChanged("RegionManager");
}
}
}
/// <summary>
/// Gets the navigation service.
/// </summary>
/// <value>The navigation service.</value>
public IRegionNavigationService NavigationService
{
get
{
if (this.regionNavigationService == null)
{
this.regionNavigationService = ServiceLocator.Current.GetInstance<IRegionNavigationService>();
this.regionNavigationService.Region = this;
}
return this.regionNavigationService;
}
set
{
this.regionNavigationService = value;
}
}
/// <summary>
/// Gets the collection with all the views along with their metadata.
/// </summary>
/// <value>An <see cref="ObservableCollection{T}"/> of <see cref="ItemMetadata"/> with all the added views.</value>
protected virtual ObservableCollection<ItemMetadata> ItemMetadataCollection
{
get
{
if (this.itemMetadataCollection == null)
{
this.itemMetadataCollection = new ObservableCollection<ItemMetadata>();
}
return this.itemMetadataCollection;
}
}
/// <overloads>Adds a new view to the region.</overloads>
/// <summary>
/// Adds a new view to the region.
/// </summary>
/// <param name="view">The view to add.</param>
/// <returns>The <see cref="IRegionManager"/> that is set on the view if it is a <see cref="DependencyObject"/>. It will be the current region manager when using this overload.</returns>
public IRegionManager Add(object view)
{
return this.Add(view, null, false);
}
/// <summary>
/// Adds a new view to the region.
/// </summary>
/// <param name="view">The view to add.</param>
/// <param name="viewName">The name of the view. This can be used to retrieve it later by calling <see cref="IRegion.GetView"/>.</param>
/// <returns>The <see cref="IRegionManager"/> that is set on the view if it is a <see cref="DependencyObject"/>. It will be the current region manager when using this overload.</returns>
public IRegionManager Add(object view, string viewName)
{
if (string.IsNullOrEmpty(viewName))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.StringCannotBeNullOrEmpty, "viewName"));
}
return this.Add(view, viewName, false);
}
/// <summary>
/// Adds a new view to the region.
/// </summary>
/// <param name="view">The view to add.</param>
/// <param name="viewName">The name of the view. This can be used to retrieve it later by calling <see cref="IRegion.GetView"/>.</param>
/// <param name="createRegionManagerScope">When <see langword="true"/>, the added view will receive a new instance of <see cref="IRegionManager"/>, otherwise it will use the current region manager for this region.</param>
/// <returns>The <see cref="IRegionManager"/> that is set on the view if it is a <see cref="DependencyObject"/>.</returns>
public virtual IRegionManager Add(object view, string viewName, bool createRegionManagerScope)
{
IRegionManager manager = createRegionManagerScope ? this.RegionManager.CreateRegionManager() : this.RegionManager;
this.InnerAdd(view, viewName, manager);
return manager;
}
/// <summary>
/// Removes the specified view from the region.
/// </summary>
/// <param name="view">The view to remove.</param>
public virtual void Remove(object view)
{
ItemMetadata itemMetadata = this.GetItemMetadataOrThrow(view);
this.ItemMetadataCollection.Remove(itemMetadata);
DependencyObject dependencyObject = view as DependencyObject;
if (dependencyObject != null && Regions.RegionManager.GetRegionManager(dependencyObject) == this.RegionManager)
{
dependencyObject.ClearValue(Regions.RegionManager.RegionManagerProperty);
}
}
/// <summary>
/// Removes all views from the region.
/// </summary>
public void RemoveAll()
{
foreach (var view in Views)
{
Remove(view);
}
}
/// <summary>
/// Marks the specified view as active.
/// </summary>
/// <param name="view">The view to activate.</param>
public virtual void Activate(object view)
{
ItemMetadata itemMetadata = this.GetItemMetadataOrThrow(view);
if (!itemMetadata.IsActive)
{
itemMetadata.IsActive = true;
}
}
/// <summary>
/// Marks the specified view as inactive.
/// </summary>
/// <param name="view">The view to deactivate.</param>
public virtual void Deactivate(object view)
{
ItemMetadata itemMetadata = this.GetItemMetadataOrThrow(view);
if (itemMetadata.IsActive)
{
itemMetadata.IsActive = false;
}
}
/// <summary>
/// Returns the view instance that was added to the region using a specific name.
/// </summary>
/// <param name="viewName">The name used when adding the view to the region.</param>
/// <returns>Returns the named view or <see langword="null"/> if the view with <paramref name="viewName"/> does not exist in the current region.</returns>
public virtual object GetView(string viewName)
{
if (string.IsNullOrEmpty(viewName))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.StringCannotBeNullOrEmpty, "viewName"));
}
ItemMetadata metadata = this.ItemMetadataCollection.FirstOrDefault(x => x.Name == viewName);
if (metadata != null)
{
return metadata.Item;
}
return null;
}
/// <summary>
/// Initiates navigation to the specified target.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="navigationCallback">A callback to execute when the navigation request is completed.</param>
public void RequestNavigate(Uri target, Action<NavigationResult> navigationCallback)
{
this.RequestNavigate(target, navigationCallback, null);
}
/// <summary>
/// Initiates navigation to the specified target.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="navigationCallback">A callback to execute when the navigation request is completed.</param>
/// <param name="navigationParameters">The navigation parameters specific to the navigation request.</param>
public void RequestNavigate(Uri target, Action<NavigationResult> navigationCallback, NavigationParameters navigationParameters)
{
this.NavigationService.RequestNavigate(target, navigationCallback, navigationParameters);
}
private void InnerAdd(object view, string viewName, IRegionManager scopedRegionManager)
{
if (this.ItemMetadataCollection.FirstOrDefault(x => x.Item == view) != null)
{
throw new InvalidOperationException(Resources.RegionViewExistsException);
}
ItemMetadata itemMetadata = new ItemMetadata(view);
if (!string.IsNullOrEmpty(viewName))
{
if (this.ItemMetadataCollection.FirstOrDefault(x => x.Name == viewName) != null)
{
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, Resources.RegionViewNameExistsException, viewName));
}
itemMetadata.Name = viewName;
}
DependencyObject dependencyObject = view as DependencyObject;
if (dependencyObject != null)
{
Regions.RegionManager.SetRegionManager(dependencyObject, scopedRegionManager);
}
this.ItemMetadataCollection.Add(itemMetadata);
}
private ItemMetadata GetItemMetadataOrThrow(object view)
{
if (view == null)
throw new ArgumentNullException(nameof(view));
ItemMetadata itemMetadata = this.ItemMetadataCollection.FirstOrDefault(x => x.Item == view);
if (itemMetadata == null)
throw new ArgumentException(Resources.ViewNotInRegionException, nameof(view));
return itemMetadata;
}
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler eventHandler = this.PropertyChanged;
if (eventHandler != null)
{
eventHandler(this, new PropertyChangedEventArgs(propertyName));
}
}
/// <summary>
/// The default sort algorithm.
/// </summary>
/// <param name="x">The first view to compare.</param>
/// <param name="y">The second view to compare.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "y")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "x")]
public static int DefaultSortComparison(object x, object y)
{
if (x == null)
{
if (y == null)
{
return 0;
}
else
{
return -1;
}
}
else
{
if (y == null)
{
return 1;
}
else
{
Type xType = x.GetType();
Type yType = y.GetType();
ViewSortHintAttribute xAttribute = xType.GetCustomAttributes(typeof(ViewSortHintAttribute), true).FirstOrDefault() as ViewSortHintAttribute;
ViewSortHintAttribute yAttribute = yType.GetCustomAttributes(typeof(ViewSortHintAttribute), true).FirstOrDefault() as ViewSortHintAttribute;
return ViewSortHintAttributeComparison(xAttribute, yAttribute);
}
}
}
private static int ViewSortHintAttributeComparison(ViewSortHintAttribute x, ViewSortHintAttribute y)
{
if (x == null)
{
if (y == null)
{
return 0;
}
else
{
return -1;
}
}
else
{
if (y == null)
{
return 1;
}
else
{
return string.Compare(x.Hint, y.Hint, StringComparison.Ordinal);
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Web.UI.WebControls;
using System.Xml;
using Rainbow.Framework;
using Rainbow.Framework.Content.Data;
using Rainbow.Framework.Site.Configuration;
using Rainbow.Framework.Web.UI;
using History=Rainbow.Framework.History;
namespace Rainbow.Content.Web.Modules
{
/// <summary>
/// Rainbow Portal Pictures module - Edit page part
/// (c)2002 by Ender Malkoc
/// </summary>
[History("Jes1111", "2003/03/04", "Cache flushing now handled by inherited page")]
public partial class PicturesEdit : AddEditItemPage
{
#region Declarations
/// <summary>
///
/// </summary>
protected RequiredFieldValidator RequiredFieldValidatorPicture;
/// <summary>
///
/// </summary>
protected RequiredFieldValidator RequiredFieldValidatorShortDescription;
/// <summary>
///
/// </summary>
protected RequiredFieldValidator RequiredFieldValidatorLongDescription;
protected XmlDocument Metadata;
#endregion
#region Puiblic Properties
/// <summary>
/// Thumbnail file name
/// </summary>
protected string ThumbnailFilename
{
get { return (string) ViewState["ThumbnailFilename"]; }
set { ViewState["ThumbnailFilename"] = value; }
}
/// <summary>
/// Modified file name
/// </summary>
protected string ModifiedFilename
{
get { return (string) ViewState["ModifiedFilename"]; }
set { ViewState["ModifiedFilename"] = value; }
}
/// <summary>
/// Metadata for Esperantus.Esperantus.Localize. image in XML format
/// </summary>
protected string MetadataXml
{
get { return (string) ViewState["MetadataXml"]; }
set { ViewState["MetadataXml"] = value; }
}
#endregion
/// <summary>
/// Esperantus.Esperantus.Localize. Page_Load event on this Page is used to obtain Esperantus.Esperantus.Localize. ModuleID
/// and ItemID of Esperantus.Esperantus.Localize. picture to edit.
/// It Esperantus.Esperantus.Localize.n uses Esperantus.Esperantus.Localize. Rainbow.PicturesDB() data component
/// to populate Esperantus.Esperantus.Localize. page's edit controls with Esperantus.Esperantus.Localize. picture details.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
[History("Tim Capps", "tim@cappsnet.com", "2.4 beta", "2004/02/18", "added hide/show bulk load logic")]
private void Page_Load(object sender, EventArgs e)
{
// If Esperantus.Esperantus.Localize. page is being requested Esperantus.Esperantus.Localize. first time, determine if a
// picture itemID value is specified, and if so populate page
// contents with Esperantus.Esperantus.Localize. picture details
Metadata = new XmlDocument();
if (Page.IsPostBack == false)
{
BulkDir.Visible = false; // make bulk load controls not visible for now
BulkDirLiteral.Visible = false;
if (ItemID != 0)
{
// Obtain a single row of picture information
PicturesDB pictures = new PicturesDB();
SqlDataReader dr = pictures.GetSinglePicture(ItemID, WorkFlowVersion.Staging);
try
{
// Read first row from database
if (dr.Read())
{
ShortDescription.Text = (string) dr["ShortDescription"];
MetadataXml = (string) dr["MetadataXml"];
Metadata.LoadXml(MetadataXml);
Keywords.Text = GetMetadata("Keywords");
LongDescription.Text = GetMetadata("LongDescription");
Caption.Text = GetMetadata("Caption");
DisplayOrder.Text = ((int) dr["DisplayOrder"]).ToString();
ThumbnailFilename = GetMetadata("ThumbnailFilename");
ModifiedFilename = GetMetadata("ModifiedFilename");
}
}
finally
{
// Close datareader
dr.Close();
}
}
else
{
Metadata.AppendChild(Metadata.CreateElement("Metadata"));
MetadataXml = Metadata.OuterXml;
if (bool.Parse((SettingItem) moduleSettings["AllowBulkLoad"]) == true)
{
// Esperantus.Esperantus.Localize.y are adding, and we are allowed to bulk load so
// make Esperantus.Esperantus.Localize. controls visible
BulkDir.Visible = true;
BulkDirLiteral.Visible = true;
}
}
}
else
{
Metadata.LoadXml(MetadataXml);
}
}
/// <summary>
/// Set Esperantus.Esperantus.Localize. module guids with free access to this page
/// </summary>
/// <value>The allowed modules.</value>
protected override ArrayList AllowedModules
{
get
{
ArrayList al = new ArrayList();
al.Add("B29CB86B-AEA1-4E94-8B77-B4E4239258B0");
return al;
}
}
/// <summary>
/// Esperantus.Esperantus.Localize. UpdateBtn_Click event handler on this Page is used to eiEsperantus.Esperantus.Localize.r
/// create or update a picture. It uses Esperantus.Esperantus.Localize. Rainbow.PicturesDB()
/// data component to encapsulate all data functionality.
/// </summary>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
[History("Tim Capps", "tim@cappsnet.com", "2.4 beta", "2004/02/18", "added bulk load logic")]
protected override void OnUpdate(EventArgs e)
{
base.OnUpdate(e);
// Only Update if Entered data is Valid
if (Page.IsValid == true)
{
// Create an instance of Esperantus.Esperantus.Localize. PicturesDB component
PicturesDB pictures = new PicturesDB();
Bitmap fullPicture = null;
//Get Esperantus.Esperantus.Localize. resize option for Esperantus.Esperantus.Localize. thumbnail
Pictures.ResizeOption thumbnailResize =
moduleSettings["ThumbnailResize"].ToString() == string.Empty
?
Pictures.ResizeOption.FixedWidthHeight
:
(Pictures.ResizeOption) Int32.Parse((SettingItem) moduleSettings["ThumbnailResize"]);
//Get Esperantus.Esperantus.Localize. resize option for Esperantus.Esperantus.Localize. original picture
Pictures.ResizeOption originalResize =
moduleSettings["OriginalResize"].ToString() == string.Empty
?
Pictures.ResizeOption.NoResize
:
(Pictures.ResizeOption) Int32.Parse((SettingItem) moduleSettings["OriginalResize"]);
//Where are we going to save Esperantus.Esperantus.Localize. picture?
string PathToSave = Server.MapPath(((SettingItem) moduleSettings["AlbumPath"]).FullPath) + "\\";
//Dimensions of Esperantus.Esperantus.Localize. thumbnail as specified in settings
int thumbnailWidth = Int32.Parse((SettingItem) moduleSettings["ThumbnailWidth"]);
int thumbnailHeight = Int32.Parse((SettingItem) moduleSettings["ThumbnailHeight"]);
//Dimensions of Esperantus.Esperantus.Localize. original picture as specified in settings
int originalWidth = Int32.Parse((SettingItem) moduleSettings["OriginalWidth"]);
int originalHeight = Int32.Parse((SettingItem) moduleSettings["OriginalHeight"]);
// See if Esperantus.Esperantus.Localize.y are doing a bulk load. Esperantus.Esperantus.Localize.y must have specified
// a bulk load directory (which is on Esperantus.Esperantus.Localize. server) and Esperantus.Esperantus.Localize.y must not
// have specified a specific upload file name, and Esperantus.Esperantus.Localize.y must not be
// editing an item.
if (ItemID == 0 && flPicture.PostedFile.FileName == string.Empty &&
BulkDir.Text != string.Empty)
{
// Esperantus.Esperantus.Localize.y are bulk loading - run through Esperantus.Esperantus.Localize. specified directory and
// insert all .JPG files into Esperantus.Esperantus.Localize. database. User is expected to
// provide a FULL file path on Esperantus.Esperantus.Localize. SERVER.
string[] files = Directory.GetFiles(BulkDir.Text, "*.jpg");
foreach (string file in files)
{
MetadataXml = null;
// Create a new FileInfo object for this filename
FileInfo fileInfo = new FileInfo(file);
//Create new filenames for Esperantus.Esperantus.Localize. thumbnail and Esperantus.Esperantus.Localize. original picture
ModifiedFilename = ModuleID.ToString() + "m" + Guid.NewGuid().ToString() + ".jpg";
SetMetadata("ModifiedFilename", ModifiedFilename);
ThumbnailFilename = ModuleID.ToString() + "m" + Guid.NewGuid().ToString() + ".jpg";
SetMetadata("ThumbnailFilename", ThumbnailFilename);
//Full path of Esperantus.Esperantus.Localize. original picture
string physicalPath = PathToSave + ModifiedFilename;
//Make sure Esperantus.Esperantus.Localize. picture target directory exists
Directory.CreateDirectory(PathToSave);
SetMetadata("OriginalFilename", fileInfo.FullName);
try
{
//Create a bitmap from Esperantus.Esperantus.Localize. saved picture
fullPicture = new Bitmap(fileInfo.FullName);
}
catch (Exception ex)
{
Message.Text =
General.GetString("PICTURES_INVALID_IMAGE_FILE", "Invalid Image File", this) + "!<br>" +
ex.Message;
return;
}
SetMetadata("OriginalWidth", fullPicture.Width.ToString());
SetMetadata("OriginalHeight", fullPicture.Height.ToString());
if (chkIncludeExif.Checked) SetExifInformation(fullPicture);
RotateFlip(fullPicture, selFlip.SelectedItem.Value, selRotate.SelectedItem.Value);
try
{
//Resize Esperantus.Esperantus.Localize. original picture with Esperantus.Esperantus.Localize. given settings to create Esperantus.Esperantus.Localize. thumbnail
Bitmap thumbnail =
ResizeImage(fullPicture, thumbnailWidth, thumbnailHeight, thumbnailResize);
thumbnail.Save(PathToSave + ThumbnailFilename, ImageFormat.Jpeg);
SetMetadata("ThumbnailWidth", thumbnail.Width.ToString());
SetMetadata("ThumbnailHeight", thumbnail.Height.ToString());
thumbnail.Dispose();
}
catch (Exception ex)
{
Message.Text =
General.GetString("PICTURES_THUMBNAIL_ERROR",
"Error occured while creating Esperantus.Esperantus.Localize. thumbnail",
this) + "!<br>" + ex.Message;
return;
}
Bitmap modified = null;
try
{
//Resize original image
modified = ResizeImage(fullPicture, originalWidth, originalHeight, originalResize);
}
catch (Exception ex)
{
Message.Text =
General.GetString("PICTURES_RESIZE_ERROR",
"Error occured while resizing Esperantus.Esperantus.Localize. image",
this) + "!<br>" + ex.Message;
return;
}
SetMetadata("ModifiedWidth", modified.Width.ToString());
SetMetadata("ModifiedHeight", modified.Height.ToString());
fullPicture.Dispose();
//Save Esperantus.Esperantus.Localize. resized one
modified.Save(physicalPath, ImageFormat.Jpeg);
modified.Dispose();
FileInfo fi = new FileInfo(physicalPath);
SetMetadata("ModifiedFileSize", fi.Length.ToString());
int displayOrder = 0;
try
{
displayOrder = Int32.Parse(DisplayOrder.Text);
}
catch
{
}
SetMetadata("ShortDescription", ShortDescription.Text);
SetMetadata("LongDescription", LongDescription.Text);
SetMetadata("Caption", Caption.Text);
SetMetadata("Keywords", Keywords.Text);
SetMetadata("UploadDate", DateTime.Now.ToString());
SetMetadata("CreatedBy", PortalSettings.CurrentUser.Identity.Email);
SetMetadata("DisplayOrder", displayOrder.ToString());
//Add new picture to Esperantus.Esperantus.Localize. database
ItemID =
pictures.AddPicture(ModuleID, ItemID, displayOrder, MetadataXml, ShortDescription.Text,
Keywords.Text, PortalSettings.CurrentUser.Identity.Email, DateTime.Now);
}
}
else
{
// Determine wheEsperantus.Esperantus.Localize.r a file was uploaded
if (flPicture.PostedFile.FileName.Length != 0)
{
//Create new filenames for Esperantus.Esperantus.Localize. thumbnail and Esperantus.Esperantus.Localize. original picture
ModifiedFilename = ModuleID.ToString() + "m" + Guid.NewGuid().ToString() + ".jpg";
SetMetadata("ModifiedFilename", ModifiedFilename);
ThumbnailFilename = ModuleID.ToString() + "m" + Guid.NewGuid().ToString() + ".jpg";
SetMetadata("ThumbnailFilename", ThumbnailFilename);
//Full path of Esperantus.Esperantus.Localize. original picture
string physicalPath = PathToSave + ModifiedFilename;
try
{
// Save Esperantus.Esperantus.Localize. picture
flPicture.PostedFile.SaveAs(physicalPath);
}
catch (DirectoryNotFoundException ex)
{
// If Esperantus.Esperantus.Localize. directory is not found, create and Esperantus.Esperantus.Localize.n save
Directory.CreateDirectory(PathToSave);
flPicture.PostedFile.SaveAs(physicalPath);
//This line is here to supress Esperantus.Esperantus.Localize. warning
ex.ToString();
}
catch (Exception ex)
{
// If oEsperantus.Esperantus.Localize.r error occured report to Esperantus.Esperantus.Localize. user
Message.Text = General.GetString("PICTURES_INVALID_FILENAME", "Invalid Filename", this) +
"!<br>" + ex.Message;
return;
}
SetMetadata("OriginalFilename", flPicture.PostedFile.FileName);
try
{
//Create a bitmap from Esperantus.Esperantus.Localize. saved picture
fullPicture = new Bitmap(physicalPath);
}
catch (Exception ex)
{
Message.Text =
General.GetString("PICTURES_INVALID_IMAGE_FILE", "Invalid Image File", this) + "!<br>" +
ex.Message;
return;
}
SetMetadata("OriginalWidth", fullPicture.Width.ToString());
SetMetadata("OriginalHeight", fullPicture.Height.ToString());
if (chkIncludeExif.Checked) SetExifInformation(fullPicture);
RotateFlip(fullPicture, selFlip.SelectedItem.Value, selRotate.SelectedItem.Value);
try
{
//Resize Esperantus.Esperantus.Localize. original picture with Esperantus.Esperantus.Localize. given settings to create Esperantus.Esperantus.Localize. thumbnail
Bitmap thumbnail =
ResizeImage(fullPicture, thumbnailWidth, thumbnailHeight, thumbnailResize);
thumbnail.Save(PathToSave + ThumbnailFilename, ImageFormat.Jpeg);
SetMetadata("ThumbnailWidth", thumbnail.Width.ToString());
SetMetadata("ThumbnailHeight", thumbnail.Height.ToString());
thumbnail.Dispose();
}
catch (Exception ex)
{
Message.Text =
General.GetString("PICTURES_THUMBNAIL_ERROR",
"Error occured while creating Esperantus.Esperantus.Localize. thumbnail",
this) + "!<br>" + ex.Message;
return;
}
Bitmap modified = null;
try
{
//Resize original image
modified = ResizeImage(fullPicture, originalWidth, originalHeight, originalResize);
}
catch (Exception ex)
{
Message.Text =
General.GetString("PICTURES_RESIZE_ERROR",
"Error occured while resizing Esperantus.Esperantus.Localize. image",
this) + "!<br>" + ex.Message;
return;
}
SetMetadata("ModifiedWidth", modified.Width.ToString());
SetMetadata("ModifiedHeight", modified.Height.ToString());
fullPicture.Dispose();
//Delete Esperantus.Esperantus.Localize. original
File.Delete(physicalPath);
//Save Esperantus.Esperantus.Localize. resized one
modified.Save(physicalPath, ImageFormat.Jpeg);
modified.Dispose();
FileInfo fi = new FileInfo(physicalPath);
SetMetadata("ModifiedFileSize", fi.Length.ToString());
}
else if (ItemID == 0)
{
Message.Text =
General.GetString("PICTURES_SPECIFY_FILENAME", "Please specify a filename", this) + "!<br>";
return;
}
int displayOrder = 0;
try
{
displayOrder = Int32.Parse(DisplayOrder.Text);
}
catch
{
}
SetMetadata("ShortDescription", ShortDescription.Text);
SetMetadata("LongDescription", LongDescription.Text);
SetMetadata("Caption", Caption.Text);
SetMetadata("Keywords", Keywords.Text);
SetMetadata("UploadDate", DateTime.Now.ToString());
SetMetadata("CreatedBy", PortalSettings.CurrentUser.Identity.Email);
SetMetadata("DisplayOrder", displayOrder.ToString());
if (ItemID == 0)
{
//If this is a new picture add it to Esperantus.Esperantus.Localize. database
ItemID =
pictures.AddPicture(ModuleID, ItemID, displayOrder, MetadataXml, ShortDescription.Text,
Keywords.Text, PortalSettings.CurrentUser.Identity.Email, DateTime.Now);
}
else
{
//Update Esperantus.Esperantus.Localize. existing one
pictures.UpdatePicture(ModuleID, ItemID, displayOrder, MetadataXml, ShortDescription.Text,
Keywords.Text, PortalSettings.CurrentUser.Identity.Email, DateTime.Now);
}
}
// Redirect back to Esperantus.Esperantus.Localize. portal home page
RedirectBackToReferringPage();
}
}
/// <summary>
/// Esperantus.Esperantus.Localize. DeleteBtn_Click event handler on this Page is used to delete
/// a picture. It uses Esperantus.Esperantus.Localize. Rainbow.PicturesDB()
/// data component to encapsulate all data functionality.
/// </summary>
protected override void OnDelete(EventArgs e)
{
base.OnDelete(e);
// Only attempt to delete Esperantus.Esperantus.Localize. item if it is an existing item
// (new items will have "ItemID" of 0)
if (ItemID != 0)
{
PicturesDB pictures = new PicturesDB();
string PathToDelete = Server.MapPath(((SettingItem) moduleSettings["AlbumPath"]).FullPath) + "\\";
SqlDataReader dr = pictures.GetSinglePicture(ItemID, WorkFlowVersion.Staging);
string filename = string.Empty;
string thumbnailFilename = string.Empty;
try
{
// Read first row from database
if (dr.Read())
{
Metadata.LoadXml((string) dr["MetadataXml"]);
filename = GetMetadata("ModifiedFilename");
thumbnailFilename = GetMetadata("ThumbnailFilename");
}
}
finally
{
// Close datareader
dr.Close();
}
try
{
//Delete Esperantus.Esperantus.Localize. files
File.Delete(PathToDelete + filename);
File.Delete(PathToDelete + thumbnailFilename);
}
catch
{
// We don't really have much to do at this point
}
//Delete Esperantus.Esperantus.Localize. record from database.
pictures.DeletePicture(ItemID);
}
// Redirect back to Esperantus.Esperantus.Localize. portal home page
RedirectBackToReferringPage();
}
/// <summary>
///
/// </summary>
public PicturesEdit()
{
Page.Init += new EventHandler(Page_Init);
}
/// <summary>
/// Gets the metadata.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public string GetMetadata(string key)
{
XmlNode targetNode = Metadata.SelectSingleNode("/Metadata/@" + key);
if (targetNode == null)
{
return null;
}
else
{
return targetNode.Value;
}
}
/// <summary>
/// Sets the metadata.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="data">The data.</param>
public void SetMetadata(string key, string data)
{
XmlNode targetNode = Metadata.SelectSingleNode("/Metadata/@" + key);
if (targetNode == null)
{
XmlAttribute newAttribute = Metadata.CreateAttribute(key);
newAttribute.Value = data;
Metadata.DocumentElement.Attributes.Append(newAttribute);
}
else
{
targetNode.Value = data;
}
MetadataXml = Metadata.OuterXml;
}
/// <summary>
/// Converts the byte array to string.
/// </summary>
/// <param name="array">The array.</param>
/// <returns></returns>
private string ConvertByteArrayToString(byte[] array)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.Length - 1; i++) sb.Append((char) array[i]);
return sb.ToString();
}
/// <summary>
/// Converts the byte array to byte.
/// </summary>
/// <param name="array">The array.</param>
/// <returns></returns>
private byte ConvertByteArrayToByte(byte[] array)
{
return array[0];
}
/// <summary>
/// Converts the byte array to short.
/// </summary>
/// <param name="array">The array.</param>
/// <returns></returns>
private short ConvertByteArrayToShort(byte[] array)
{
short val = 0;
for (int i = 0; i < array.Length; i++) val += (short) (array[i]*Math.Pow(2, (i*8)));
return val;
}
/// <summary>
/// Converts the byte array to long.
/// </summary>
/// <param name="array">The array.</param>
/// <returns></returns>
private long ConvertByteArrayToLong(byte[] array)
{
long val = 0;
for (int i = 0; i < array.Length; i++) val += (array[i]*(long) Math.Pow(2, (i*8)));
return val;
}
/// <summary>
/// Converts the byte array to rational.
/// </summary>
/// <param name="array">The array.</param>
/// <returns></returns>
private string ConvertByteArrayToRational(byte[] array)
{
int val1 = 0;
int val2 = 0;
for (int i = 0; i < 4; i++) val1 += (array[i]*(int) Math.Pow(2, (i*8)));
for (int i = 4; i < 8; i++) val2 += (array[i]*(int) Math.Pow(2, ((i - 4)*8)));
if (val2 == 1)
{
return val1.ToString();
}
else
{
return ((double) val1/(double) val2).ToString();
}
}
/// <summary>
/// Converts the byte array to S rational.
/// </summary>
/// <param name="array">The array.</param>
/// <returns></returns>
private string ConvertByteArrayToSRational(byte[] array)
{
int val1 = 0;
int val2 = 0;
for (int i = 0; i < 4; i++) val1 += (array[i]*(int) Math.Pow(2, (i*8)));
for (int i = 4; i < 8; i++) val2 += (array[i]*(int) Math.Pow(2, ((i - 4)*8)));
if (val2 == 1)
{
return val1.ToString();
}
else
{
return ((double) val1/(double) val2).ToString();
}
}
/// <summary>
/// Rotates the flip.
/// </summary>
/// <param name="original">The original.</param>
/// <param name="flip">The flip.</param>
/// <param name="rotate">The rotate.</param>
/// <returns></returns>
private Bitmap RotateFlip(Bitmap original, string flip, string rotate)
{
RotateFlipType rotateFlipType = RotateFlipType.RotateNoneFlipNone;
if (flip == "None" && rotate == "180")
{
rotateFlipType = RotateFlipType.Rotate180FlipNone;
}
else if (flip == "X" && rotate == "180")
{
rotateFlipType = RotateFlipType.Rotate180FlipX;
}
else if (flip == "XY" && rotate == "180")
{
rotateFlipType = RotateFlipType.Rotate180FlipXY;
}
else if (flip == "Y" && rotate == "180")
{
rotateFlipType = RotateFlipType.Rotate180FlipY;
}
else if (flip == "None" && rotate == "270")
{
rotateFlipType = RotateFlipType.Rotate270FlipNone;
}
else if (flip == "X" && rotate == "270")
{
rotateFlipType = RotateFlipType.Rotate270FlipX;
}
else if (flip == "XY" && rotate == "270")
{
rotateFlipType = RotateFlipType.Rotate270FlipXY;
}
else if (flip == "Y" && rotate == "270")
{
rotateFlipType = RotateFlipType.Rotate270FlipY;
}
else if (flip == "None" && rotate == "90")
{
rotateFlipType = RotateFlipType.Rotate90FlipNone;
}
else if (flip == "X" && rotate == "90")
{
rotateFlipType = RotateFlipType.Rotate90FlipX;
}
else if (flip == "XY" && rotate == "90")
{
rotateFlipType = RotateFlipType.Rotate90FlipXY;
}
else if (flip == "Y" && rotate == "90")
{
rotateFlipType = RotateFlipType.Rotate90FlipY;
}
else if (flip == "None" && rotate == "None")
{
rotateFlipType = RotateFlipType.RotateNoneFlipNone;
}
else if (flip == "X" && rotate == "None")
{
rotateFlipType = RotateFlipType.RotateNoneFlipX;
}
else if (flip == "XY" && rotate == "None")
{
rotateFlipType = RotateFlipType.RotateNoneFlipXY;
}
else if (flip == "Y" && rotate == "None")
{
rotateFlipType = RotateFlipType.RotateNoneFlipY;
}
original.RotateFlip(rotateFlipType);
return original;
}
/// <summary>
/// Resize a given image
/// </summary>
/// <param name="original">Original Bitmap that needs resizing</param>
/// <param name="newWidth">New width of Esperantus.Esperantus.Localize. bitmap</param>
/// <param name="newHeight">New height of Esperantus.Esperantus.Localize. bitmap</param>
/// <param name="option">Option for resizing</param>
/// <returns></returns>
private Bitmap ResizeImage(Bitmap original, int newWidth, int newHeight, Pictures.ResizeOption option)
{
if (original.Width == 0 || original.Height == 0 || newWidth == 0 || newHeight == 0) return null;
if (original.Width < newWidth) newWidth = original.Width;
if (original.Height < newHeight) newHeight = original.Height;
switch (option)
{
case Pictures.ResizeOption.NoResize:
newWidth = original.Width;
newHeight = original.Height;
break;
case Pictures.ResizeOption.FixedWidthHeight:
break;
case Pictures.ResizeOption.MaintainAspectWidth:
newHeight = (newWidth*original.Height/original.Width);
break;
case Pictures.ResizeOption.MaintainAspectHeight:
newWidth = (newHeight*original.Width/original.Height);
break;
}
Bitmap newBitmap = new Bitmap(newWidth, newHeight);
Graphics g = Graphics.FromImage(newBitmap);
g.DrawImage(original, 0, 0, newWidth, newHeight);
return newBitmap;
}
/// <summary>
/// Handles the Init event of the Page control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
private void Page_Init(object sender, EventArgs e)
{
}
/// <summary>
/// Thumbnails the callback.
/// </summary>
/// <returns></returns>
public bool ThumbnailCallback()
{
return false;
}
/// <summary>
/// Sets the exif information.
/// </summary>
/// <param name="bitmap">The bitmap.</param>
private void SetExifInformation(Bitmap bitmap)
{
foreach (PropertyItem pi in bitmap.PropertyItems)
{
switch (pi.Id)
{
case 0x010F:
SetMetadata("EquipMake", ConvertByteArrayToString(pi.Value));
break;
case 0x0110:
SetMetadata("EquipModel", ConvertByteArrayToString(pi.Value));
break;
case 0x0112:
switch (ConvertByteArrayToShort(pi.Value))
{
case 1:
SetMetadata("Orientation", "upper left");
break;
case 2:
SetMetadata("Orientation", "upper right");
break;
case 3:
SetMetadata("Orientation", "lower right");
break;
case 4:
SetMetadata("Orientation", "lower left");
break;
case 5:
SetMetadata("Orientation", "upper left flipped");
break;
case 6:
SetMetadata("Orientation", "upper right flipped");
break;
case 7:
SetMetadata("Orientation", "lower right flipped");
break;
case 8:
SetMetadata("Orientation", "lower left flipped");
break;
}
break;
case 0x011a:
SetMetadata("XResolution", ConvertByteArrayToRational(pi.Value));
break;
case 0x011b:
SetMetadata("YResolution", ConvertByteArrayToRational(pi.Value));
break;
case 0x0128:
SetMetadata("ResolutionUnit", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x0132:
SetMetadata("Datetime", ConvertByteArrayToString(pi.Value));
break;
case 0x0213:
SetMetadata("YCbCrPositioning", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x00FE:
SetMetadata("NewSubfileType", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x00FF:
SetMetadata("SubfileType", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x0100:
SetMetadata("ImageWidth", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x0101:
SetMetadata("ImageHeight", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x0102:
SetMetadata("BitsPerSample", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x0103:
SetMetadata("Compression", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x0106:
SetMetadata("PhotometricInterp", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x0107:
SetMetadata("ThreshHolding", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x0108:
SetMetadata("CellWidth", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x0109:
SetMetadata("CellHeight", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x010A:
SetMetadata("FillOrder", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x010D:
SetMetadata("DocumentName", ConvertByteArrayToString(pi.Value));
break;
case 0x010E:
SetMetadata("ImageDescription", ConvertByteArrayToString(pi.Value));
break;
case 0x0111:
SetMetadata("StripOffsets", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x0115:
SetMetadata("SamplesPerPixel", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x0116:
SetMetadata("RowsPerStrip", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x0117:
SetMetadata("StripBytesCount", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x0118:
SetMetadata("MinSampleValue", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x0119:
SetMetadata("MaxSampleValue", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x011C:
SetMetadata("PlanarConfig", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x011D:
SetMetadata("PageName", ConvertByteArrayToString(pi.Value));
break;
case 0x011E:
SetMetadata("XPosition", ConvertByteArrayToRational(pi.Value));
break;
case 0x011F:
SetMetadata("YPosition", ConvertByteArrayToRational(pi.Value));
break;
case 0x0120:
SetMetadata("FreeOffset", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x0121:
SetMetadata("FreeByteCounts", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x0122:
SetMetadata("GrayResponseUnit", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x0123:
SetMetadata("GrayResponseCurve", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x0124:
SetMetadata("T4Option", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x0125:
SetMetadata("T6Option", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x0129:
SetMetadata("PageNumber", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x012D:
SetMetadata("TransferFunction", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x0131:
SetMetadata("SoftwareUsed", ConvertByteArrayToString(pi.Value));
break;
case 0x013B:
SetMetadata("Artist", ConvertByteArrayToString(pi.Value));
break;
case 0x013C:
SetMetadata("HostComputer", ConvertByteArrayToString(pi.Value));
break;
case 0x013D:
SetMetadata("Predictor", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x013E:
SetMetadata("WhitePoint", ConvertByteArrayToRational(pi.Value));
break;
case 0x013F:
SetMetadata("PrimaryChromaticities", ConvertByteArrayToRational(pi.Value));
break;
case 0x0140:
SetMetadata("ColorMap", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x0141:
SetMetadata("HalftoneHints", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x0142:
SetMetadata("TileWidth", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x0143:
SetMetadata("TileLength", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x0144:
SetMetadata("TileOffset", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x0145:
SetMetadata("TileByteCounts", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x014C:
SetMetadata("InkSet", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x014D:
SetMetadata("InkNames", ConvertByteArrayToString(pi.Value));
break;
case 0x014E:
SetMetadata("NumberOfInks", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x0150:
SetMetadata("DotRange", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x0151:
SetMetadata("TargetPrinter", ConvertByteArrayToString(pi.Value));
break;
case 0x0152:
SetMetadata("ExtraSamples", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x0153:
SetMetadata("SampleFormat", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x0156:
SetMetadata("TransferRange", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x0200:
SetMetadata("JPEGProc", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x0201:
SetMetadata("JPEGInterFormat", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x0202:
SetMetadata("JPEGInterLength", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x0203:
SetMetadata("JPEGRestartInterval", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x0205:
SetMetadata("JPEGLosslessPredictors", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x0206:
SetMetadata("JPEGPointTransforms", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x0207:
SetMetadata("JPEGQTables", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x0208:
SetMetadata("JPEGDCTables", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x0209:
SetMetadata("JPEGACTables", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x0211:
SetMetadata("YCbCrCoefficients", ConvertByteArrayToRational(pi.Value));
break;
case 0x0212:
SetMetadata("YCbCrSubsampling", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x0214:
SetMetadata("REFBlackWhite", ConvertByteArrayToRational(pi.Value));
break;
case 0x0301:
SetMetadata("Gamma", ConvertByteArrayToRational(pi.Value));
break;
case 0x0302:
SetMetadata("ICCProfileDescriptor", ConvertByteArrayToString(pi.Value));
break;
case 0x0303:
switch (ConvertByteArrayToShort(pi.Value))
{
case 0:
SetMetadata("SRGBRenderingIntent", "perceptual");
break;
case 1:
SetMetadata("SRGBRenderingIntent", "relative colorimetric");
break;
case 2:
SetMetadata("SRGBRenderingIntent", "saturation");
break;
case 3:
SetMetadata("SRGBRenderingIntent", "absolute colorimetric");
break;
}
break;
case 0x0320:
SetMetadata("ImageTitle", ConvertByteArrayToString(pi.Value));
break;
case 0x5001:
SetMetadata("ResolutionXUnit", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x5002:
SetMetadata("ResolutionYUnit", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x5003:
SetMetadata("ResolutionXLengthUnit", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x5004:
SetMetadata("ResolutionYLengthUnit", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x5005:
SetMetadata("PrintFlags", ConvertByteArrayToString(pi.Value));
break;
case 0x5006:
SetMetadata("PrintFlagsVersion", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x5007:
SetMetadata("PrintFlagsCrop", ConvertByteArrayToByte(pi.Value).ToString());
break;
case 0x5008:
SetMetadata("PrintFlagsBleedWidth", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x5009:
SetMetadata("PrintFlagsBleedWidthScale", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x500A:
SetMetadata("HalftoneLPI", ConvertByteArrayToRational(pi.Value));
break;
case 0x500B:
SetMetadata("HalftoneLPIUnit", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x500C:
SetMetadata("HalftoneDegree", ConvertByteArrayToRational(pi.Value));
break;
case 0x500D:
SetMetadata("HalftoneShape", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x500E:
SetMetadata("HalftoneMisc", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x500F:
SetMetadata("HalftoneScreen", ConvertByteArrayToByte(pi.Value).ToString());
break;
case 0x5010:
SetMetadata("JPEGQuality", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x5012:
SetMetadata("ThumbnailFormat", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x5013:
SetMetadata("ThumbnailWidth", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x5014:
SetMetadata("ThumbnailHeight", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x5015:
SetMetadata("ThumbnailColorDepth", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x5016:
SetMetadata("ThumbnailPlanes", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x5017:
SetMetadata("ThumbnailRawBytes", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x5018:
SetMetadata("ThumbnailSize", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x5019:
SetMetadata("ThumbnailCompressedSize", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x501B:
SetMetadata("ThumbnailData", ConvertByteArrayToByte(pi.Value).ToString());
break;
case 0x5020:
SetMetadata("ThumbnailImageWidth", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x5021:
SetMetadata("ThumbnailImageHeight", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x5022:
SetMetadata("ThumbnailBitsPerSample", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x5023:
SetMetadata("ThumbnailCompression", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x5024:
SetMetadata("ThumbnailPhotometricInterp", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x5025:
SetMetadata("ThumbnailImageDescription", ConvertByteArrayToString(pi.Value));
break;
case 0x5026:
SetMetadata("ThumbnailEquipMake", ConvertByteArrayToString(pi.Value));
break;
case 0x5027:
SetMetadata("ThumbnailEquipModel", ConvertByteArrayToString(pi.Value));
break;
case 0x5028:
SetMetadata("ThumbnailStripOffsets", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x5029:
SetMetadata("ThumbnailOrientation", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x502A:
SetMetadata("ThumbnailSamplesPerPixel", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x502B:
SetMetadata("ThumbnailRowsPerStrip", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x502C:
SetMetadata("ThumbnailStripBytesCount", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x502F:
SetMetadata("ThumbnailPlanarConfig", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x5030:
SetMetadata("ThumbnailResolutionUnit", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x5031:
SetMetadata("ThumbnailTransferFunction", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x5032:
SetMetadata("ThumbnailSoftwareUsed", ConvertByteArrayToString(pi.Value));
break;
case 0x5033:
SetMetadata("ThumbnailDateTime", ConvertByteArrayToString(pi.Value));
break;
case 0x5034:
SetMetadata("ThumbnailArtist", ConvertByteArrayToString(pi.Value));
break;
case 0x5035:
SetMetadata("ThumbnailWhitePoint", ConvertByteArrayToRational(pi.Value));
break;
case 0x5036:
SetMetadata("ThumbnailPrimaryChromaticities", ConvertByteArrayToRational(pi.Value));
break;
case 0x5037:
SetMetadata("ThumbnailYCbCrCoefficients", ConvertByteArrayToRational(pi.Value));
break;
case 0x5038:
SetMetadata("ThumbnailYCbCrSubsampling", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x5039:
SetMetadata("ThumbnailYCbCrPositioning", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x503A:
SetMetadata("ThumbnailRefBlackWhite", ConvertByteArrayToRational(pi.Value));
break;
case 0x503B:
SetMetadata("ThumbnailCopyRight", ConvertByteArrayToString(pi.Value));
break;
case 0x5090:
SetMetadata("LuminanceTable", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x5091:
SetMetadata("ChrominanceTable", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x5100:
SetMetadata("FrameDelay", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x5101:
SetMetadata("LoopCount", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x5110:
SetMetadata("PixelUnit", ConvertByteArrayToByte(pi.Value).ToString());
break;
case 0x5111:
SetMetadata("PixelPerUnitX", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x5112:
SetMetadata("PixelPerUnitY", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x5113:
SetMetadata("PaletteHistogram", ConvertByteArrayToByte(pi.Value).ToString());
break;
case 0x8298:
SetMetadata("Copyright", ConvertByteArrayToString(pi.Value));
break;
case 0x829A:
SetMetadata("ExifExposureTime", ConvertByteArrayToRational(pi.Value));
break;
case 0x829D:
SetMetadata("ExifFNumber", ConvertByteArrayToRational(pi.Value));
break;
case 0x8769:
SetMetadata("ExifIFD", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x8773:
SetMetadata("ICCProfile", ConvertByteArrayToByte(pi.Value).ToString());
break;
case 0x8822:
switch (ConvertByteArrayToShort(pi.Value))
{
case 0:
SetMetadata("ExifExposureProg", "Not defined");
break;
case 1:
SetMetadata("ExifExposureProg", "Manual");
break;
case 2:
SetMetadata("ExifExposureProg", "Normal Program");
break;
case 3:
SetMetadata("ExifExposureProg", "Aperture Priority");
break;
case 4:
SetMetadata("ExifExposureProg", "Shutter Priority");
break;
case 5:
SetMetadata("ExifExposureProg", "Creative program (biased toward depth of field)");
break;
case 6:
SetMetadata("ExifExposureProg", "Action program (biased toward fast shutter speed)");
break;
case 7:
SetMetadata("ExifExposureProg",
"Portrait mode (for close-up photos with Esperantus.Esperantus.Localize. background out of focus)");
break;
case 8:
SetMetadata("ExifExposureProg",
"Landscape mode (for landscape photos with Esperantus.Esperantus.Localize. background in focus)");
break;
default:
SetMetadata("ExifExposureProg", "Unknown");
break;
}
break;
case 0x8824:
SetMetadata("ExifSpectralSense", ConvertByteArrayToString(pi.Value));
break;
case 0x8825:
SetMetadata("GpsIFD", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0x8827:
SetMetadata("ExifISOSpeed", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0x9003:
SetMetadata("ExifDTOrig", ConvertByteArrayToString(pi.Value));
break;
case 0x9004:
SetMetadata("ExifDTDigitized", ConvertByteArrayToString(pi.Value));
break;
case 0x9102:
SetMetadata("ExifCompBPP", ConvertByteArrayToRational(pi.Value));
break;
case 0x9201:
SetMetadata("ExifShutterSpeed", ConvertByteArrayToSRational(pi.Value));
break;
case 0x9202:
SetMetadata("ExifAperture", ConvertByteArrayToRational(pi.Value));
break;
case 0x9203:
SetMetadata("ExifBrightness", ConvertByteArrayToSRational(pi.Value));
break;
case 0x9204:
SetMetadata("ExifExposureBias", ConvertByteArrayToSRational(pi.Value));
break;
case 0x9205:
SetMetadata("ExifMaxAperture", ConvertByteArrayToRational(pi.Value));
break;
case 0x9206:
SetMetadata("ExifSubjectDist", ConvertByteArrayToRational(pi.Value));
break;
case 0x9207:
switch (ConvertByteArrayToShort(pi.Value))
{
case 0:
SetMetadata("ExifMeteringMode", "Unknown");
break;
case 1:
SetMetadata("ExifMeteringMode", "Average");
break;
case 2:
SetMetadata("ExifMeteringMode", "CenterWeightedAverage");
break;
case 3:
SetMetadata("ExifMeteringMode", "Spot");
break;
case 4:
SetMetadata("ExifMeteringMode", "MultiSpot");
break;
case 5:
SetMetadata("ExifMeteringMode", "Pattern");
break;
case 6:
SetMetadata("ExifMeteringMode", "Partial");
break;
case 255:
SetMetadata("ExifMeteringMode", "OEsperantus.Esperantus.Localize.r");
break;
default:
SetMetadata("ExifMeteringMode", "Unknown");
break;
}
break;
case 0x9208:
switch (ConvertByteArrayToShort(pi.Value))
{
case 0:
SetMetadata("ExifLightSource", "Unknown");
break;
case 1:
SetMetadata("ExifLightSource", "Daylight");
break;
case 2:
SetMetadata("ExifLightSource", "Flourescent");
break;
case 3:
SetMetadata("ExifLightSource", "Tungsten");
break;
case 17:
SetMetadata("ExifLightSource", "Standard Light A");
break;
case 18:
SetMetadata("ExifLightSource", "Standard Light B");
break;
case 19:
SetMetadata("ExifLightSource", "Standard Light C");
break;
case 20:
SetMetadata("ExifLightSource", "D55");
break;
case 21:
SetMetadata("ExifLightSource", "D65");
break;
case 22:
SetMetadata("ExifLightSource", "D75");
break;
case 255:
SetMetadata("ExifLightSource", "OEsperantus.Esperantus.Localize.r");
break;
default:
SetMetadata("ExifLightSource", "Unknown");
break;
}
break;
case 0x9209:
switch (ConvertByteArrayToShort(pi.Value))
{
case 0:
SetMetadata("ExifFlash", "Flash did not fire");
break;
case 1:
SetMetadata("ExifFlash", "Flash fired");
break;
case 5:
SetMetadata("ExifFlash", "Strobe return light not detected");
break;
default:
SetMetadata("ExifFlash", "Uknown");
break;
}
break;
case 0x920A:
SetMetadata("ExifFocalLength", ConvertByteArrayToRational(pi.Value));
break;
case 0x9290:
SetMetadata("ExifDTSubsec", ConvertByteArrayToString(pi.Value));
break;
case 0x9291:
SetMetadata("ExifDTOrigSS", ConvertByteArrayToString(pi.Value));
break;
case 0x9292:
SetMetadata("ExifDTDigSS", ConvertByteArrayToString(pi.Value));
break;
case 0xA001:
switch (ConvertByteArrayToLong(pi.Value))
{
case 0x1:
SetMetadata("ExifColorSpace", "sRGB");
break;
case 0xFFFF:
SetMetadata("ExifColorSpace", "Uncalibrated");
break;
default:
SetMetadata("ExifColorSpace", "Reserved");
break;
}
break;
case 0xA002:
SetMetadata("ExifPixXDim", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0xA003:
SetMetadata("ExifPixYDim", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0xA004:
SetMetadata("ExifRelatedWav", ConvertByteArrayToString(pi.Value));
break;
case 0xA005:
SetMetadata("ExifInterop", ConvertByteArrayToLong(pi.Value).ToString());
break;
case 0xA20B:
SetMetadata("ExifFlashEnergy", ConvertByteArrayToRational(pi.Value));
break;
case 0xA20E:
SetMetadata("ExifFocalXRes", ConvertByteArrayToRational(pi.Value));
break;
case 0xA20F:
SetMetadata("ExifFocalYRes", ConvertByteArrayToRational(pi.Value));
break;
case 0xA210:
switch (ConvertByteArrayToShort(pi.Value))
{
case 2:
SetMetadata("ExifFocalResUnit", "Inch");
break;
case 3:
SetMetadata("ExifFocalResUnit", "Centimeter");
break;
}
break;
case 0xA214:
SetMetadata("ExifSubjectLoc", ConvertByteArrayToShort(pi.Value).ToString());
break;
case 0xA215:
SetMetadata("ExifExposureIndex", ConvertByteArrayToRational(pi.Value));
break;
case 0xA217:
switch (ConvertByteArrayToShort(pi.Value))
{
case 1:
SetMetadata("ExifSensingMethod", "Not defined");
break;
case 2:
SetMetadata("ExifSensingMethod", "One-chip color area sensor");
break;
case 3:
SetMetadata("ExifSensingMethod", "Two-chip color area sensor");
break;
case 4:
SetMetadata("ExifSensingMethod", "Three-chip color area sensor");
break;
case 5:
SetMetadata("ExifSensingMethod", "Color sequential area sensor");
break;
case 7:
SetMetadata("ExifSensingMethod", "Trilinear sensor");
break;
case 8:
SetMetadata("ExifSensingMethod", "Color sequential linear sensor");
break;
default:
SetMetadata("ExifSensingMethod", "Reserved");
break;
}
break;
}
}
}
#region Web Form Designer generated code
/// <summary>
/// Raises OnInitEvent
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
protected override void OnInit(EventArgs e)
{
this.Load += new EventHandler(this.Page_Load);
base.OnInit(e);
}
#endregion
}
}
| |
using System.Collections.Generic;
using FarseerGames.FarseerPhysics.Collisions;
using FarseerGames.FarseerPhysics.Controllers;
using FarseerGames.FarseerPhysics.Dynamics;
using FarseerGames.FarseerPhysics.Dynamics.Joints;
#if (XNA)
using Microsoft.Xna.Framework;
#else
using FarseerGames.FarseerPhysics.Mathematics;
#endif
namespace FarseerGames.FarseerPhysics.Factories
{
/// <summary>
/// An easy to use factory for creating complex structures
/// </summary>
public class ComplexFactory
{
private static ComplexFactory _instance;
public float Min { get; set; }
public float Max { get; set; }
public float SpringConstant { get; set; }
public float DampingConstant { get; set; }
public float SpringRestLengthFactor { get; set; }
private ComplexFactory()
{
SpringRestLengthFactor = 1f;
}
public static ComplexFactory Instance
{
get
{
if (_instance == null)
{
_instance = new ComplexFactory();
}
return _instance;
}
}
/// <summary>
/// Creates a chain from start to end points containing the specified number of links.
/// </summary>
/// <param name="physicsSimulator"><see cref="PhysicsSimulator"/> to add the chain to.</param>
/// <param name="start">Starting point of the chain.</param>
/// <param name="end">Ending point of the chain.</param>
/// <param name="links">Number of links desired in the chain.</param>
/// <param name="height">Height of each link.</param>
/// <param name="mass">Mass of each link.</param>
/// <param name="type">The joint/spring type.</param>
/// <returns>Path</returns>
public Path CreateChain(PhysicsSimulator physicsSimulator, Vector2 start, Vector2 end, int links, float height,
float mass, LinkType type)
{
Path p = CreateChain(start, end, (Vector2.Distance(start, end) / links), height, mass, type);
p.AddToPhysicsSimulator(physicsSimulator);
return p;
}
/// <summary>
/// Creates a chain from start to end points containing the specified number of links.
/// </summary>
/// <param name="start">Starting point of the chain.</param>
/// <param name="end">Ending point of the chain.</param>
/// <param name="links">Number of links desired in the chain.</param>
/// <param name="height">Height of each link.</param>
/// <param name="mass">Mass of each link.</param>
/// <param name="type">The joint/spring type.</param>
/// <returns>Path</returns>
public Path CreateChain(Vector2 start, Vector2 end, int links, float height, float mass, LinkType type)
{
return CreateChain(start, end, (Vector2.Distance(start, end) / links), height, mass, type);
}
/// <summary>
/// Creates a chain from start to end points containing the specified number of links.
/// </summary>
/// <param name="physicsSimulator"><see cref="PhysicsSimulator"/> to add the chain too.</param>
/// <param name="start">Starting point of the chain.</param>
/// <param name="end">Ending point of the chain.</param>
/// <param name="links">Number of links desired in the chain.</param>
/// <param name="mass">Mass of each link.</param>
/// <param name="type">The joint/spring type.</param>
/// <returns>Path</returns>
public Path CreateChain(PhysicsSimulator physicsSimulator, Vector2 start, Vector2 end, int links, float mass,
LinkType type)
{
Path path = CreateChain(start, end, (Vector2.Distance(start, end) / links),
(Vector2.Distance(start, end) / links) * (1.0f / 3.0f), mass, type);
path.AddToPhysicsSimulator(physicsSimulator);
return path;
}
/// <summary>
/// Creates a chain.
/// </summary>
/// <param name="start">The start.</param>
/// <param name="end">The end.</param>
/// <param name="links">The links.</param>
/// <param name="mass">The mass.</param>
/// <param name="type">The joint/spring type.</param>
/// <returns></returns>
public Path CreateChain(Vector2 start, Vector2 end, int links, float mass, LinkType type)
{
return CreateChain(start, end, (Vector2.Distance(start, end) / links),
(Vector2.Distance(start, end) / links) * (1.0f / 3.0f), mass, type);
}
/// <summary>
/// Creates a chain.
/// </summary>
/// <param name="physicsSimulator"><see cref="PhysicsSimulator"/> to add the chain to.</param>
/// <param name="start">The start.</param>
/// <param name="end">The end.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="mass">The mass.</param>
/// <param name="type">The joint/spring type.</param>
/// <returns></returns>
public Path CreateChain(PhysicsSimulator physicsSimulator, Vector2 start, Vector2 end, float width, float height,
float mass, LinkType type)
{
Path path = CreateChain(start, end, width, height, mass, false, false, type);
path.AddToPhysicsSimulator(physicsSimulator);
return path;
}
/// <summary>
/// Creates a chain.
/// </summary>
/// <param name="physicsSimulator"><see cref="PhysicsSimulator"/> to add the chain to.</param>
/// <param name="start">The start.</param>
/// <param name="end">The end.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="mass">The mass.</param>
/// <param name="pinStart">if set to <c>true</c> [pin start].</param>
/// <param name="pinEnd">if set to <c>true</c> [pin end].</param>
/// <param name="type">The joint/spring type.</param>
/// <returns></returns>
public Path CreateChain(PhysicsSimulator physicsSimulator, Vector2 start, Vector2 end, float width, float height,
float mass, bool pinStart, bool pinEnd, LinkType type)
{
Path path = CreateChain(start, end, width, height, mass, pinStart, pinEnd, type);
path.AddToPhysicsSimulator(physicsSimulator);
return path;
}
/// <summary>
/// Creates a chain.
/// </summary>
/// <param name="physicsSimulator"><see cref="PhysicsSimulator"/> to add the chain to.</param>
/// <param name="start">The start.</param>
/// <param name="end">The end.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="linkWidth">The distance between links.</param>
/// <param name="mass">The mass.</param>
/// <param name="pinStart">if set to <c>true</c> [pin start].</param>
/// <param name="pinEnd">if set to <c>true</c> [pin end].</param>
/// <param name="type">The joint/spring type.</param>
/// <returns></returns>
public Path CreateChain(PhysicsSimulator physicsSimulator, Vector2 start, Vector2 end, float width, float height, float linkWidth,
float mass, bool pinStart, bool pinEnd, LinkType type)
{
Path path = CreateChain(start, end, width, height, linkWidth, mass, pinStart, pinEnd, type);
path.AddToPhysicsSimulator(physicsSimulator);
return path;
}
/// <summary>
/// Creates a chain.
/// </summary>
/// <param name="start">The start.</param>
/// <param name="end">The end.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="mass">The mass.</param>
/// <param name="type">The joint/spring type.</param>
/// <returns></returns>
public Path CreateChain(Vector2 start, Vector2 end, float width, float height, float mass, LinkType type)
{
return CreateChain(start, end, width, height, mass, false, false, type);
}
/// <summary>
/// Creates a chain.
/// </summary>
/// <param name="start">The start.</param>
/// <param name="end">The end.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="mass">The mass.</param>
/// <param name="pinStart">if set to <c>true</c> [pin start].</param>
/// <param name="pinEnd">if set to <c>true</c> [pin end].</param>
/// <param name="type">The joint/spring type.</param>
/// <returns></returns>
public Path CreateChain(Vector2 start, Vector2 end, float width, float height, float mass, bool pinStart,
bool pinEnd, LinkType type)
{
return CreateChain(start, end, width, height, width, mass, pinStart, pinEnd, type);
}
/// <summary>
/// Creates a chain.
/// </summary>
/// <param name="start">The start.</param>
/// <param name="end">The end.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="linkWidth">The distance between links.</param>
/// <param name="mass">The mass.</param>
/// <param name="pinStart">if set to <c>true</c> [pin start].</param>
/// <param name="pinEnd">if set to <c>true</c> [pin end].</param>
/// <param name="type">The joint/spring type.</param>
/// <returns></returns>
public Path CreateChain(Vector2 start, Vector2 end, float width, float height, float linkWidth, float mass, bool pinStart,
bool pinEnd, LinkType type)
{
Path path = new Path(width, height, linkWidth, mass, false); // create the path
path.Add(start); // add starting point
path.Add(Path.FindMidpoint(start, end));
// add midpoint of line (must have this because my code needs at least 3 control points)
path.Add(end); // add end point
path.Update(); // call update to create all the bodies
path.LinkBodies(type, Min, Max, SpringConstant, DampingConstant, SpringRestLengthFactor); // link bodies together
if (pinStart)
path.Add(JointFactory.Instance.CreateFixedRevoluteJoint(path.Bodies[0], start));
if (pinEnd)
path.Add(JointFactory.Instance.CreateFixedRevoluteJoint(path.Bodies[path.Bodies.Count - 1],
path.ControlPoints[2]));
foreach (Joint j in path.Joints) // chains need a little give ;)
{
j.BiasFactor = 0.01f;
j.Softness = 0.05f;
}
return (path);
}
/// <summary>
/// Creates a rope.
/// </summary>
/// <param name="start">The start.</param>
/// <param name="end">The end.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="mass">The mass.</param>
/// <param name="pinStart">if set to <c>true</c> [pin start].</param>
/// <param name="pinEnd">if set to <c>true</c> [pin end].</param>
/// <param name="type">The joint/spring type.</param>
/// <returns></returns>
public Path CreateRope(Vector2 start, Vector2 end, float width, float height, float mass, bool pinStart,
bool pinEnd, LinkType type)
{
Path path = new Path(width, height, mass, false); // create the path
path.Add(start); // add starting point
path.Add(Path.FindMidpoint(start, end));
// add midpoint of line (must have this because my code needs at least 3 control points)
path.Add(end); // add end point
path.Update(); // call update to create all the bodies
path.LinkBodies(type, Min, Max, SpringConstant, DampingConstant, SpringRestLengthFactor); // link bodies together
if (pinStart)
path.Add(JointFactory.Instance.CreateFixedRevoluteJoint(path.Bodies[0], start));
if (pinEnd)
path.Add(JointFactory.Instance.CreateFixedRevoluteJoint(path.Bodies[path.Bodies.Count - 1],
path.ControlPoints[2]));
foreach (Joint j in path.Joints) // ropes need a little give ;)
{
j.BiasFactor = 0.01f;
j.Softness = 0.05f;
}
return (path);
}
/// <summary>
/// Creates a track.
/// </summary>
/// <param name="points">The points.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="mass">The mass.</param>
/// <param name="endless">if set to <c>true</c> [endless].</param>
/// <param name="collisionGroup">Collision group for the chain.</param>
/// <param name="type">The joint/spring type.</param>
/// <returns></returns>
public Path CreateTrack(Vertices points, float width, float height, float mass, bool endless, int collisionGroup, LinkType type)
{
Path path = new Path(width, height, mass, endless); // create the path
foreach (Vector2 v in points)
path.Add(v); // add all the points to the path
path.Update(); // update the path
Geom geom;
for (int i = 0; i < path.Bodies.Count; i++)
{
geom = GeomFactory.Instance.CreateRectangleGeom(path.Bodies[i], width, height);
geom.CollisionGroup = collisionGroup;
path.Add(geom); // add a geom to the chain
}
path.LinkBodies(type, Min, Max, SpringConstant, DampingConstant); // link bodies together
return path;
}
/// <summary>
/// Creates a track.
/// </summary>
/// <param name="physicsSimulator">The physics simulator.</param>
/// <param name="points">The points.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="mass">The mass.</param>
/// <param name="endless">if set to <c>true</c> [endless].</param>
/// <param name="collisionGroup">Collision group for the chain.</param>
/// <param name="type">The joint/spring type.</param>
/// <returns></returns>
public Path CreateTrack(PhysicsSimulator physicsSimulator, Vertices points, float width, float height,
float mass, bool endless, int collisionGroup, LinkType type)
{
Path path = CreateTrack(points, width, height, mass, endless, collisionGroup, type);
path.AddToPhysicsSimulator(physicsSimulator);
return path;
}
/// <summary>
/// Creates a gravity controller and adds it to the physics simulator.
/// </summary>
/// <param name="simulator">the physicsSimulator used by this controller.</param>
/// <param name="bodies">The bodies you want to generate gravity.</param>
/// <param name="type">the type of gravity this uses.</param>
/// <param name="strength">the maximum strength of gravity (the gravity strength when two bodies are on the same spot)</param>
/// <param name="radius">the maximum distance that can be between 2 bodies before it will stop trying to apply gravity between them.</param>
public GravityController CreateGravityController(PhysicsSimulator simulator, List<Body> bodies, GravityType type, float strength, float radius)
{
GravityController gravityController = new GravityController(simulator, bodies, strength, radius);
gravityController.GravityType = type;
simulator.Add(gravityController);
return gravityController;
}
/// <summary>
/// Creates a gravity controller and adds it to the physics simulator.
/// </summary>
/// <param name="simulator">the physicsSimulator used by this controller.</param>
/// <param name="bodies">The bodies you want to generate gravity.</param>
/// <param name="strength">the maximum strength of gravity (the gravity strength when two bodies are on the same spot)</param>
/// <param name="radius">the maximum distance that can be between 2 bodies before it will stop trying to apply gravity between them.</param>
/// <returns></returns>
public GravityController CreateGravityController(PhysicsSimulator simulator, List<Body> bodies, float strength, float radius)
{
GravityController gravityController = new GravityController(simulator, bodies, strength, radius);
simulator.Add(gravityController);
return gravityController;
}
/// <summary>
/// Creates a gravity controller and adds it to the physics simulator.
/// </summary>
/// <param name="simulator">the physicsSimulator used by this controller.</param>
/// <param name="points">The points you want to generate gravity.</param>
/// <param name="type">the type of gravity this uses.</param>
/// <param name="strength">the maximum strength of gravity (the gravity strength when two bodies are on the same spot)</param>
/// <param name="radius">the maximum distance that can be between 2 bodies before it will stop trying to apply gravity between them.</param>
public GravityController CreateGravityController(PhysicsSimulator simulator, List<Vector2> points, GravityType type, float strength, float radius)
{
GravityController gravityController = new GravityController(simulator, points, strength, radius);
gravityController.GravityType = type;
simulator.Add(gravityController);
return gravityController;
}
/// <summary>
/// Creates a gravity controller and adds it to the physics simulator.
/// </summary>
/// <param name="simulator">the physicsSimulator used by this controller.</param>
/// <param name="points">The points you want to generate gravity.</param>
/// <param name="strength">the maximum strength of gravity (the gravity strength when two bodies are on the same spot)</param>
/// <param name="radius">the maximum distance that can be between 2 bodies before it will stop trying to apply gravity between them.</param>
/// <returns></returns>
public GravityController CreateGravityController(PhysicsSimulator simulator, List<Vector2> points, float strength, float radius)
{
GravityController gravityController = new GravityController(simulator, points, strength, radius);
simulator.Add(gravityController);
return gravityController;
}
}
}
| |
//
// SelectionRatioDialog.cs
//
// Author:
// Stephane Delcroix <sdelcroix@src.gnome.org>
//
// Copyright (C) 2008 Novell, Inc.
// Copyright (C) 2008 Stephane Delcroix
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Xml.Serialization;
using System.Collections.Generic;
using Gtk;
using Mono.Unix;
using Hyena;
namespace FSpot.UI.Dialog {
public class SelectionRatioDialog : BuilderDialog
{
[Serializable]
public struct SelectionConstraint {
private string label;
public string Label {
get { return label; }
set { label = value; }
}
private double ratio;
public double XyRatio {
get { return ratio; }
set { ratio = value; }
}
public SelectionConstraint (string label, double ratio)
{
this.label = label;
this.ratio = ratio;
}
}
[GtkBeans.Builder.Object] Button close_button;
[GtkBeans.Builder.Object] Button add_button;
[GtkBeans.Builder.Object] Button delete_button;
[GtkBeans.Builder.Object] Button up_button;
[GtkBeans.Builder.Object] Button down_button;
[GtkBeans.Builder.Object] TreeView content_treeview;
private ListStore constraints_store;
public SelectionRatioDialog () : base ("SelectionRatioDialog.ui", "customratio_dialog")
{
close_button.Clicked += delegate (object o, EventArgs e) {SavePrefs (); this.Destroy (); };
add_button.Clicked += delegate (object o, EventArgs e) {constraints_store.AppendValues ("New Selection", 1.0);};
delete_button.Clicked += DeleteSelectedRows;
up_button.Clicked += MoveUp;
down_button.Clicked += MoveDown;
CellRendererText text_renderer = new CellRendererText ();
text_renderer.Editable = true;
text_renderer.Edited += HandleLabelEdited;
content_treeview.AppendColumn (Catalog.GetString ("Label"), text_renderer, "text", 0);
text_renderer = new CellRendererText ();
text_renderer.Editable = true;
text_renderer.Edited += HandleRatioEdited;
content_treeview.AppendColumn (Catalog.GetString ("Ratio"), text_renderer, "text", 1);
LoadPreference (Preferences.CUSTOM_CROP_RATIOS);
Preferences.SettingChanged += OnPreferencesChanged;
}
private void Populate ()
{
constraints_store = new ListStore (typeof (string), typeof (double));
content_treeview.Model = constraints_store;
XmlSerializer serializer = new XmlSerializer (typeof(SelectionConstraint));
string [] vals = Preferences.Get<string []> (Preferences.CUSTOM_CROP_RATIOS);
if (vals != null)
foreach (string xml in vals) {
SelectionConstraint constraint = (SelectionConstraint)serializer.Deserialize (new StringReader (xml));
constraints_store.AppendValues (constraint.Label, constraint.XyRatio);
}
}
private void OnPreferencesChanged (object sender, NotifyEventArgs args)
{
LoadPreference (args.Key);
}
private void LoadPreference (String key)
{
switch (key) {
case Preferences.CUSTOM_CROP_RATIOS:
Populate ();
break;
}
}
private void SavePrefs ()
{
List<string> prefs = new List<string> ();
XmlSerializer serializer = new XmlSerializer (typeof (SelectionConstraint));
foreach (object[] row in constraints_store) {
StringWriter sw = new StringWriter ();
serializer.Serialize (sw, new SelectionConstraint ((string)row[0], (double)row[1]));
sw.Close ();
prefs.Add (sw.ToString ());
}
#if !GCONF_SHARP_2_18
if (prefs.Count != 0)
#endif
Preferences.Set (Preferences.CUSTOM_CROP_RATIOS, prefs.ToArray());
#if !GCONF_SHARP_2_18
else
Preferences.Set (Preferences.CUSTOM_CROP_RATIOS, -1);
#endif
}
public void HandleLabelEdited (object sender, EditedArgs args)
{
args.RetVal = false;
TreeIter iter;
if (!constraints_store.GetIterFromString (out iter, args.Path))
return;
using (GLib.Value val = new GLib.Value (args.NewText))
constraints_store.SetValue (iter, 0, val);
args.RetVal = true;
}
public void HandleRatioEdited (object sender, EditedArgs args)
{
args.RetVal = false;
TreeIter iter;
if (!constraints_store.GetIterFromString (out iter, args.Path))
return;
double ratio;
try {
ratio = ParseRatio (args.NewText);
} catch (FormatException fe) {
Log.Exception (fe);
return;
}
if (ratio < 1.0)
ratio = 1.0 / ratio;
using (GLib.Value val = new GLib.Value (ratio))
constraints_store.SetValue (iter, 1, val);
args.RetVal = true;
}
private double ParseRatio (string text)
{
try {
return Convert.ToDouble (text);
} catch (FormatException) {
char [] separators = {'/', ':'};
foreach (char c in separators) {
if (text.IndexOf (c) != -1) {
double ratio = Convert.ToDouble (text.Substring (0, text.IndexOf (c)));
ratio /= Convert.ToDouble (text.Substring (text.IndexOf (c) + 1));
return ratio;
}
}
throw new FormatException (String.Format ("unable to parse {0}", text));
}
}
private void DeleteSelectedRows (object o, EventArgs e)
{
TreeIter iter;
TreeModel model;
if (content_treeview.Selection.GetSelected (out model, out iter))
(model as ListStore).Remove (ref iter);
}
private void MoveUp (object o, EventArgs e)
{
TreeIter selected;
TreeModel model;
if (content_treeview.Selection.GetSelected (out model, out selected)) {
//no IterPrev :(
TreeIter prev;
TreePath path = model.GetPath (selected);
if (path.Prev ())
if (model.GetIter (out prev, path))
(model as ListStore).Swap (prev, selected);
}
}
private void MoveDown (object o, EventArgs e)
{
TreeIter current;
TreeModel model;
if (content_treeview.Selection.GetSelected (out model, out current)) {
TreeIter next = current;
if ((model as ListStore).IterNext (ref next))
(model as ListStore).Swap (current, next);
}
}
}
}
| |
#region Copyright (c) 2007 Ryan Williams <drcforbin@gmail.com>
/// <copyright>
/// Copyright (c) 2007 Ryan Williams <drcforbin@gmail.com>
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
/// </copyright>
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Diagnostics;
namespace Obfuscar
{
interface IMapWriter
{
void WriteMap (ObfuscationMap map);
}
class TextMapWriter : IMapWriter, IDisposable
{
private readonly TextWriter writer;
public TextMapWriter (TextWriter writer)
{
this.writer = writer;
}
public void WriteMap (ObfuscationMap map)
{
writer.WriteLine ("Renamed Types:");
foreach (ObfuscatedClass classInfo in map.ClassMap.Values) {
// print the ones we didn't skip first
if (classInfo.Status == ObfuscationStatus.Renamed)
DumpClass (classInfo);
}
writer.WriteLine ();
writer.WriteLine ("Skipped Types:");
foreach (ObfuscatedClass classInfo in map.ClassMap.Values) {
// now print the stuff we skipped
if (classInfo.Status == ObfuscationStatus.Skipped)
DumpClass (classInfo);
}
writer.WriteLine ();
writer.WriteLine ("Renamed Resources:");
writer.WriteLine ();
foreach (ObfuscatedThing info in map.Resources) {
if (info.Status == ObfuscationStatus.Renamed)
writer.WriteLine ("{0} -> {1}", info.Name, info.StatusText);
}
writer.WriteLine ();
writer.WriteLine ("Skipped Resources:");
writer.WriteLine ();
foreach (ObfuscatedThing info in map.Resources) {
if (info.Status == ObfuscationStatus.Skipped)
writer.WriteLine ("{0} ({1})", info.Name, info.StatusText);
}
}
private void DumpClass (ObfuscatedClass classInfo)
{
writer.WriteLine ();
if (classInfo.Status == ObfuscationStatus.Renamed)
writer.WriteLine ("{0} -> {1}", classInfo.Name, classInfo.StatusText);
else {
Debug.Assert (classInfo.Status == ObfuscationStatus.Skipped,
"Status is expected to be either Renamed or Skipped.");
writer.WriteLine ("{0} skipped: {1}", classInfo.Name, classInfo.StatusText);
}
writer.WriteLine ("{");
int numRenamed = 0;
foreach (KeyValuePair<MethodKey, ObfuscatedThing> method in classInfo.Methods) {
if (method.Value.Status == ObfuscationStatus.Renamed) {
DumpMethod (method.Key, method.Value);
numRenamed++;
}
}
// add a blank line to separate renamed from skipped...it's pretty.
if (numRenamed < classInfo.Methods.Count)
writer.WriteLine ();
foreach (KeyValuePair<MethodKey, ObfuscatedThing> method in classInfo.Methods) {
if (method.Value.Status == ObfuscationStatus.Skipped)
DumpMethod (method.Key, method.Value);
}
// add a blank line to separate methods from field...it's pretty.
if (classInfo.Methods.Count > 0 && classInfo.Fields.Count > 0)
writer.WriteLine ();
numRenamed = 0;
foreach (KeyValuePair<FieldKey, ObfuscatedThing> field in classInfo.Fields) {
if (field.Value.Status == ObfuscationStatus.Renamed) {
DumpField (writer, field.Key, field.Value);
numRenamed++;
}
}
// add a blank line to separate renamed from skipped...it's pretty.
if (numRenamed < classInfo.Fields.Count)
writer.WriteLine ();
foreach (KeyValuePair<FieldKey, ObfuscatedThing> field in classInfo.Fields) {
if (field.Value.Status == ObfuscationStatus.Skipped)
DumpField (writer, field.Key, field.Value);
}
// add a blank line to separate props...it's pretty.
if (classInfo.Properties.Count > 0)
writer.WriteLine ();
numRenamed = 0;
foreach (KeyValuePair<PropertyKey, ObfuscatedThing> field in classInfo.Properties) {
if (field.Value.Status == ObfuscationStatus.Renamed) {
DumpProperty (writer, field.Key, field.Value);
numRenamed++;
}
}
// add a blank line to separate renamed from skipped...it's pretty.
if (numRenamed < classInfo.Properties.Count)
writer.WriteLine ();
foreach (KeyValuePair<PropertyKey, ObfuscatedThing> field in classInfo.Properties) {
if (field.Value.Status == ObfuscationStatus.Skipped)
DumpProperty (writer, field.Key, field.Value);
}
// add a blank line to separate events...it's pretty.
if (classInfo.Events.Count > 0)
writer.WriteLine ();
numRenamed = 0;
foreach (KeyValuePair<EventKey, ObfuscatedThing> field in classInfo.Events) {
if (field.Value.Status == ObfuscationStatus.Renamed) {
DumpEvent (writer, field.Key, field.Value);
numRenamed++;
}
}
// add a blank line to separate renamed from skipped...it's pretty.
if (numRenamed < classInfo.Events.Count)
writer.WriteLine ();
foreach (KeyValuePair<EventKey, ObfuscatedThing> field in classInfo.Events) {
if (field.Value.Status == ObfuscationStatus.Skipped)
DumpEvent (writer, field.Key, field.Value);
}
writer.WriteLine ("}");
}
private void DumpMethod (MethodKey key, ObfuscatedThing info)
{
writer.Write ("\t{0}(", info.Name);
for (int i = 0; i < key.Count; i++) {
if (i > 0)
writer.Write (", ");
else
writer.Write (" ");
writer.Write (key.ParamTypes [i]);
}
if (info.Status == ObfuscationStatus.Renamed)
writer.WriteLine (" ) -> {0}", info.StatusText);
else {
Debug.Assert (info.Status == ObfuscationStatus.Skipped,
"Status is expected to be either Renamed or Skipped.");
writer.WriteLine (" ) skipped: {0}", info.StatusText);
}
}
private void DumpField (TextWriter writer, FieldKey key, ObfuscatedThing info)
{
if (info.Status == ObfuscationStatus.Renamed)
writer.WriteLine ("\t{0} {1} -> {2}", key.Type, info.Name, info.StatusText);
else {
Debug.Assert (info.Status == ObfuscationStatus.Skipped,
"Status is expected to be either Renamed or Skipped.");
writer.WriteLine ("\t{0} {1} skipped: {2}", key.Type, info.Name, info.StatusText);
}
}
private void DumpProperty (TextWriter writer, PropertyKey key, ObfuscatedThing info)
{
if (info.Status == ObfuscationStatus.Renamed)
writer.WriteLine ("\t{0} {1} -> {2}", key.Type, info.Name, info.StatusText);
else {
Debug.Assert (info.Status == ObfuscationStatus.Skipped,
"Status is expected to be either Renamed or Skipped.");
writer.WriteLine ("\t{0} {1} skipped: {2}", key.Type, info.Name, info.StatusText);
}
}
private void DumpEvent (TextWriter writer, EventKey key, ObfuscatedThing info)
{
if (info.Status == ObfuscationStatus.Renamed)
writer.WriteLine ("\t{0} {1} -> {2}", key.Type, info.Name, info.StatusText);
else {
Debug.Assert (info.Status == ObfuscationStatus.Skipped,
"Status is expected to be either Renamed or Skipped.");
writer.WriteLine ("\t{0} {1} skipped: {2}", key.Type, info.Name, info.StatusText);
}
}
public void Dispose ()
{
writer.Close ();
}
}
class XmlMapWriter : IMapWriter, IDisposable
{
private readonly XmlWriter writer;
public XmlMapWriter (TextWriter writer)
{
this.writer = new XmlTextWriter (writer);
}
public void WriteMap (ObfuscationMap map)
{
writer.WriteStartElement ("mapping");
writer.WriteStartElement ("renamedTypes");
foreach (ObfuscatedClass classInfo in map.ClassMap.Values) {
// print the ones we didn't skip first
if (classInfo.Status == ObfuscationStatus.Renamed)
DumpClass (classInfo);
}
writer.WriteEndElement ();
writer.WriteString ("\r\n");
writer.WriteStartElement ("skippedTypes");
foreach (ObfuscatedClass classInfo in map.ClassMap.Values) {
// now print the stuff we skipped
if (classInfo.Status == ObfuscationStatus.Skipped)
DumpClass (classInfo);
}
writer.WriteEndElement ();
writer.WriteString ("\r\n");
writer.WriteStartElement ("renamedResources");
foreach (ObfuscatedThing info in map.Resources) {
if (info.Status == ObfuscationStatus.Renamed) {
writer.WriteStartElement ("renamedResource");
writer.WriteAttributeString ("oldName", info.Name);
writer.WriteAttributeString ("newName", info.StatusText);
writer.WriteEndElement ();
}
}
writer.WriteEndElement ();
writer.WriteString ("\r\n");
writer.WriteStartElement ("skippedResources");
foreach (ObfuscatedThing info in map.Resources) {
if (info.Status == ObfuscationStatus.Skipped) {
writer.WriteStartElement ("skippedResource");
writer.WriteAttributeString ("name", info.Name);
writer.WriteAttributeString ("reason", info.StatusText);
writer.WriteEndElement ();
}
}
writer.WriteEndElement ();
writer.WriteString ("\r\n");
writer.WriteEndElement ();
writer.WriteString ("\r\n");
}
private void DumpClass (ObfuscatedClass classInfo)
{
if (classInfo.Status != ObfuscationStatus.Renamed) {
Debug.Assert (classInfo.Status == ObfuscationStatus.Skipped,
"Status is expected to be either Renamed or Skipped.");
writer.WriteStartElement ("skippedClass");
writer.WriteAttributeString ("name", classInfo.Name);
writer.WriteAttributeString ("reason", classInfo.StatusText);
} else {
writer.WriteStartElement ("renamedClass");
writer.WriteAttributeString ("oldName", classInfo.Name);
writer.WriteAttributeString ("newName", classInfo.StatusText);
}
int numRenamed = 0;
foreach (KeyValuePair<MethodKey, ObfuscatedThing> method in classInfo.Methods) {
if (method.Value.Status == ObfuscationStatus.Renamed) {
DumpMethod (method.Key, method.Value);
numRenamed++;
}
}
foreach (KeyValuePair<MethodKey, ObfuscatedThing> method in classInfo.Methods) {
if (method.Value.Status == ObfuscationStatus.Skipped)
DumpMethod (method.Key, method.Value);
}
foreach (KeyValuePair<FieldKey, ObfuscatedThing> field in classInfo.Fields) {
if (field.Value.Status == ObfuscationStatus.Renamed) {
DumpField (writer, field.Key, field.Value);
}
}
//
foreach (KeyValuePair<FieldKey, ObfuscatedThing> field in classInfo.Fields) {
if (field.Value.Status == ObfuscationStatus.Skipped)
DumpField (writer, field.Key, field.Value);
}
foreach (KeyValuePair<PropertyKey, ObfuscatedThing> field in classInfo.Properties) {
if (field.Value.Status == ObfuscationStatus.Renamed) {
DumpProperty (writer, field.Key, field.Value);
}
}
foreach (KeyValuePair<PropertyKey, ObfuscatedThing> field in classInfo.Properties) {
if (field.Value.Status == ObfuscationStatus.Skipped)
DumpProperty (writer, field.Key, field.Value);
}
foreach (KeyValuePair<EventKey, ObfuscatedThing> field in classInfo.Events) {
if (field.Value.Status == ObfuscationStatus.Renamed) {
DumpEvent (writer, field.Key, field.Value);
}
}
foreach (KeyValuePair<EventKey, ObfuscatedThing> field in classInfo.Events) {
if (field.Value.Status == ObfuscationStatus.Skipped)
DumpEvent (writer, field.Key, field.Value);
}
writer.WriteEndElement ();
writer.WriteString ("\r\n");
}
private void DumpMethod (MethodKey key, ObfuscatedThing info)
{
StringBuilder sb = new StringBuilder ();
sb.AppendFormat ("{0}(", info.Name);
for (int i = 0; i < key.Count; i++) {
if (i > 0)
sb.Append (",");
sb.Append (key.ParamTypes [i]);
}
sb.Append (")");
if (info.Status == ObfuscationStatus.Renamed) {
writer.WriteStartElement ("renamedMethod");
writer.WriteAttributeString ("oldName", sb.ToString ());
writer.WriteAttributeString ("newName", info.StatusText);
writer.WriteEndElement ();
writer.WriteString ("\r\n");
} else {
writer.WriteStartElement ("skippedMethod");
writer.WriteAttributeString ("name", sb.ToString ());
writer.WriteAttributeString ("reason", info.StatusText);
writer.WriteEndElement ();
writer.WriteString ("\r\n");
}
}
private void DumpField (XmlWriter writer, FieldKey key, ObfuscatedThing info)
{
if (info.Status == ObfuscationStatus.Renamed) {
writer.WriteStartElement ("renamedField");
writer.WriteAttributeString ("oldName", info.Name);
writer.WriteAttributeString ("newName", info.StatusText);
writer.WriteEndElement ();
writer.WriteString ("\r\n");
} else {
writer.WriteStartElement ("skippedField");
writer.WriteAttributeString ("name", info.Name);
writer.WriteAttributeString ("reason", info.StatusText);
writer.WriteEndElement ();
writer.WriteString ("\r\n");
}
}
private void DumpProperty (XmlWriter writer, PropertyKey key, ObfuscatedThing info)
{
if (info.Status == ObfuscationStatus.Renamed) {
writer.WriteStartElement ("renamedProperty");
writer.WriteAttributeString ("oldName", info.Name);
writer.WriteAttributeString ("newName", info.StatusText);
writer.WriteEndElement ();
writer.WriteString ("\r\n");
} else {
writer.WriteStartElement ("skippedProperty");
writer.WriteAttributeString ("name", info.Name);
writer.WriteAttributeString ("reason", info.StatusText);
writer.WriteEndElement ();
writer.WriteString ("\r\n");
}
}
private void DumpEvent (XmlWriter writer, EventKey key, ObfuscatedThing info)
{
if (info.Status == ObfuscationStatus.Renamed) {
writer.WriteStartElement ("renamedEvent");
writer.WriteAttributeString ("oldName", info.Name);
writer.WriteAttributeString ("newName", info.StatusText);
writer.WriteEndElement ();
writer.WriteString ("\r\n");
} else {
writer.WriteStartElement ("skippedEvent");
writer.WriteAttributeString ("name", info.Name);
writer.WriteAttributeString ("reason", info.StatusText);
writer.WriteEndElement ();
writer.WriteString ("\r\n");
}
}
public void Dispose ()
{
writer.Close ();
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// 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 DiscUtils.Udf
{
using System;
using System.Collections.Generic;
using System.Text;
internal class FileContentBuffer : IBuffer
{
private UdfContext _context;
private Partition _partition;
private FileEntry _fileEntry;
private uint _blockSize;
private List<CookedExtent> _extents;
public FileContentBuffer(UdfContext context, Partition partition, FileEntry fileEntry, uint blockSize)
{
_context = context;
_partition = partition;
_fileEntry = fileEntry;
_blockSize = blockSize;
LoadExtents();
}
public bool CanRead
{
get { return true; }
}
public bool CanWrite
{
get { return false; }
}
public long Capacity
{
get { return (long)_fileEntry.InformationLength; }
}
public IEnumerable<StreamExtent> Extents
{
get { throw new NotImplementedException(); }
}
public int Read(long pos, byte[] buffer, int offset, int count)
{
if (_fileEntry.InformationControlBlock.AllocationType == AllocationType.Embedded)
{
byte[] srcBuffer = _fileEntry.AllocationDescriptors;
if (pos > srcBuffer.Length)
{
return 0;
}
int toCopy = (int)Math.Min(srcBuffer.Length - pos, count);
Array.Copy(srcBuffer, pos, buffer, offset, toCopy);
return toCopy;
}
else
{
return ReadFromExtents(pos, buffer, offset, count);
}
}
public void Write(long pos, byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public void Clear(long pos, int count)
{
throw new NotSupportedException();
}
public void Flush()
{
}
public void SetCapacity(long value)
{
throw new NotImplementedException();
}
public IEnumerable<StreamExtent> GetExtentsInRange(long start, long count)
{
throw new NotImplementedException();
}
private void LoadExtents()
{
_extents = new List<CookedExtent>();
byte[] activeBuffer = _fileEntry.AllocationDescriptors;
AllocationType allocType = _fileEntry.InformationControlBlock.AllocationType;
if (allocType == AllocationType.ShortDescriptors)
{
long filePos = 0;
int i = 0;
while (i < activeBuffer.Length)
{
ShortAllocationDescriptor sad = Utilities.ToStruct<ShortAllocationDescriptor>(activeBuffer, i);
if (sad.ExtentLength == 0)
{
break;
}
if (sad.Flags != ShortAllocationFlags.RecordedAndAllocated)
{
throw new NotImplementedException("Extents that are not 'recorded and allocated' not implemented");
}
CookedExtent newExtent = new CookedExtent
{
FileContentOffset = filePos,
Partition = int.MaxValue,
StartPos = sad.ExtentLocation * (long)_blockSize,
Length = sad.ExtentLength
};
_extents.Add(newExtent);
filePos += sad.ExtentLength;
i += sad.Size;
}
}
else if (allocType == AllocationType.Embedded)
{
// do nothing
}
else if (allocType == AllocationType.LongDescriptors)
{
long filePos = 0;
int i = 0;
while (i < activeBuffer.Length)
{
LongAllocationDescriptor lad = Utilities.ToStruct<LongAllocationDescriptor>(activeBuffer, i);
if (lad.ExtentLength == 0)
{
break;
}
CookedExtent newExtent = new CookedExtent
{
FileContentOffset = filePos,
Partition = lad.ExtentLocation.Partition,
StartPos = lad.ExtentLocation.LogicalBlock * (long)_blockSize,
Length = lad.ExtentLength
};
_extents.Add(newExtent);
filePos += lad.ExtentLength;
i += lad.Size;
}
}
else
{
throw new NotImplementedException("Allocation Type: " + _fileEntry.InformationControlBlock.AllocationType);
}
}
private int ReadFromExtents(long pos, byte[] buffer, int offset, int count)
{
int totalToRead = (int)Math.Min(Capacity - pos, count);
int totalRead = 0;
while (totalRead < totalToRead)
{
CookedExtent extent = FindExtent(pos + totalRead);
long extentOffset = (pos + totalRead) - extent.FileContentOffset;
int toRead = (int)Math.Min(totalToRead - totalRead, extent.Length - extentOffset);
Partition part;
if (extent.Partition != int.MaxValue)
{
part = _context.LogicalPartitions[extent.Partition];
}
else
{
part = _partition;
}
int numRead = part.Content.Read(extent.StartPos + extentOffset, buffer, offset + totalRead, toRead);
if (numRead == 0)
{
return totalRead;
}
totalRead += numRead;
}
return totalRead;
}
private CookedExtent FindExtent(long pos)
{
foreach (var extent in _extents)
{
if (extent.FileContentOffset + extent.Length > pos)
{
return extent;
}
}
return null;
}
private class CookedExtent
{
public long FileContentOffset;
public int Partition;
public long StartPos;
public long Length;
}
}
}
| |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using DebuggerApi;
using NUnit.Framework;
using NSubstitute;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
using YetiVSI.DebugEngine;
using System.Collections.Generic;
using YetiVSI.DebugEngine.Variables;
using System;
using DebuggerCommonApi;
using Microsoft.VisualStudio.Threading;
using YetiVSI.DebugEngine.AsyncOperations;
using YetiVSI.DebugEngine.Interfaces;
namespace YetiVSI.Test.DebugEngine
{
[TestFixture]
class DebugStackFrameTests
{
const ulong _testPc = 0x123456789abcdef0;
const string _name = "DebugStackFrameTests";
RemoteTarget _mockTarget;
IDebugStackFrame _stackFrame;
RemoteFrame _mockDebuggerStackFrame;
LineEntryInfo _lineEntry;
IDebugDocumentContext2 _mockDocumentContext;
IDebugThread _mockThread;
DebugDocumentContext.Factory _mockDocumentContextFactory;
DebugCodeContext.Factory _mockCodeContextFactory;
IDebugExpressionFactory _mockExpressionFactory;
IDebugModuleCache _mockModuleCache;
IDebugEngineHandler _mockDebugEngineHandler;
ITaskExecutor _taskExecutor;
IGgpDebugProgram _mockProgram;
[SetUp]
public void SetUp()
{
_lineEntry = new LineEntryInfo();
_mockDocumentContext = Substitute.For<IDebugDocumentContext2>();
_mockThread = Substitute.For<IDebugThread>();
_mockDocumentContextFactory = Substitute.For<DebugDocumentContext.Factory>();
_mockDocumentContextFactory.Create(_lineEntry).Returns(_mockDocumentContext);
_mockDebuggerStackFrame = Substitute.For<RemoteFrame>();
_mockDebuggerStackFrame.GetLineEntry().Returns(_lineEntry);
_mockDebuggerStackFrame.GetPC().Returns(_testPc);
_mockDebuggerStackFrame.GetFunctionName().Returns(_name);
_mockDebuggerStackFrame.GetFunctionNameWithSignature().Returns(_name);
_mockCodeContextFactory = Substitute.For<DebugCodeContext.Factory>();
_mockExpressionFactory = Substitute.For<IDebugExpressionFactory>();
_mockModuleCache = Substitute.For<IDebugModuleCache>();
_mockDebugEngineHandler = Substitute.For<IDebugEngineHandler>();
_mockProgram = Substitute.For<IGgpDebugProgram>();
_mockTarget = Substitute.For<RemoteTarget>();
_mockProgram.Target.Returns(_mockTarget);
_taskExecutor = new TaskExecutor(new JoinableTaskContext().Factory);
var childAdapterFactory = new RemoteValueChildAdapter.Factory();
var varInfoFactory = new LLDBVariableInformationFactory(childAdapterFactory);
var varInfoEnumFactory = new VariableInformationEnum.Factory(_taskExecutor);
var childrenProviderFactory = new ChildrenProvider.Factory();
var propertyFactory = new DebugAsyncProperty.Factory(
varInfoEnumFactory, childrenProviderFactory,
Substitute.For<DebugCodeContext.Factory>(), new VsExpressionCreator(),
_taskExecutor);
childrenProviderFactory.Initialize(propertyFactory);
var registerSetsBuilderFactory = new RegisterSetsBuilder.Factory(varInfoFactory);
_stackFrame = new DebugAsyncStackFrame.Factory(_mockDocumentContextFactory,
childrenProviderFactory,
_mockCodeContextFactory,
_mockExpressionFactory, varInfoFactory,
varInfoEnumFactory,
registerSetsBuilderFactory,
_taskExecutor)
.Create(new AD7FrameInfoCreator(_mockModuleCache), _mockDebuggerStackFrame,
_mockThread,
_mockDebugEngineHandler, _mockProgram);
}
[Test]
public void GetCodeContext()
{
var mockCodeContext = Substitute.For<IGgpDebugCodeContext>();
_mockCodeContextFactory.Create(_mockTarget, _testPc, _name, _mockDocumentContext)
.Returns(mockCodeContext);
Assert.AreEqual(VSConstants.S_OK,
_stackFrame.GetCodeContext(out IDebugCodeContext2 codeContext));
Assert.AreEqual(codeContext, mockCodeContext);
}
[Test]
public void GetCodeContextNoDocumentContext()
{
var mockCodeContext = Substitute.For<IGgpDebugCodeContext>();
_mockCodeContextFactory.Create(_mockTarget, _testPc, _name, null)
.Returns(mockCodeContext);
LineEntryInfo lineEntryNull = null;
_mockDebuggerStackFrame.GetLineEntry().Returns(lineEntryNull);
Assert.AreEqual(VSConstants.S_OK,
_stackFrame.GetCodeContext(out IDebugCodeContext2 codeContext));
Assert.AreEqual(codeContext, mockCodeContext);
}
[Test]
public void GetDocumentContext()
{
Assert.AreEqual(VSConstants.S_OK,
_stackFrame.GetDocumentContext(
out IDebugDocumentContext2 documentContext));
Assert.AreEqual(_mockDocumentContext, documentContext);
}
[Test]
public void GetDocumentContextNoLineEntry()
{
LineEntryInfo lineEntryNull = null;
_mockDebuggerStackFrame.GetLineEntry().Returns(lineEntryNull);
Assert.AreEqual(VSConstants.E_FAIL,
_stackFrame.GetDocumentContext(
out IDebugDocumentContext2 documentContext));
Assert.AreEqual(null, documentContext);
}
[Test]
public void GetExpressionContext()
{
Assert.AreEqual(VSConstants.S_OK,
_stackFrame.GetExpressionContext(out IDebugExpressionContext2 context));
Assert.AreEqual(_stackFrame, context);
}
[Test]
public void ParseText()
{
var testExpression = "test expression";
var mockExpression = Substitute.For<IDebugExpression>();
_mockExpressionFactory.Create(_mockDebuggerStackFrame, testExpression,
_mockDebugEngineHandler, _mockProgram, _mockThread)
.Returns(mockExpression);
Assert.AreEqual(VSConstants.S_OK,
_stackFrame.ParseText(testExpression, 0, 0,
out IDebugExpression2 expression,
out string errorString, out uint error));
Assert.AreEqual(mockExpression, expression);
Assert.AreEqual(0, error);
Assert.AreEqual("", errorString);
}
[Test]
public void EnumPropertiesSupportedFilter()
{
_mockDebuggerStackFrame.GetVariables(false, true, false, true)
.Returns(new List<RemoteValue> { });
var guidFilter = FrameVariablesProvider.PropertyFilterGuids.AllLocals;
Assert.AreEqual(VSConstants.S_OK,
_stackFrame.EnumProperties(
enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_NAME, 0, ref guidFilter, 0,
out uint count, out IEnumDebugPropertyInfo2 propertyEnum));
}
[Test]
public void EnumPropertiesUnsupportedFilter()
{
var guidFilter = new Guid("12345678-1234-1234-1234-123456789123");
Assert.AreEqual(VSConstants.E_NOTIMPL,
_stackFrame.EnumProperties(
enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_NAME, 0, ref guidFilter, 0,
out uint count, out IEnumDebugPropertyInfo2 propertyEnum));
}
[Test]
public void GetThread()
{
Assert.AreEqual(VSConstants.S_OK, _stackFrame.GetThread(out IDebugThread2 thread));
Assert.AreEqual(_mockThread, thread);
}
[Test]
public void GetFrame()
{
_mockDebuggerStackFrame.GetInfo(FrameInfoFlags.FIF_FRAME).Returns(
new FrameInfo<SbModule> { ValidFields = FrameInfoFlags.FIF_FRAME });
var info = new FRAMEINFO[1];
var fields = enum_FRAMEINFO_FLAGS.FIF_FRAME;
Assert.AreEqual(VSConstants.S_OK, _stackFrame.GetInfo(fields, 0, info));
Assert.AreEqual(enum_FRAMEINFO_FLAGS.FIF_FRAME,
info[0].m_dwValidFields & enum_FRAMEINFO_FLAGS.FIF_FRAME);
Assert.AreEqual(_stackFrame, info[0].m_pFrame);
}
[Test]
public void GetModule()
{
var mockModule = Substitute.For<SbModule>();
_mockDebuggerStackFrame.GetInfo(FrameInfoFlags.FIF_DEBUG_MODULEP).Returns(
new FrameInfo<SbModule>
{
ValidFields = FrameInfoFlags.FIF_DEBUG_MODULEP,
Module = mockModule
});
var debugModule = Substitute.For<IDebugModule3>();
_mockModuleCache.GetOrCreate(mockModule, _mockProgram).Returns(debugModule);
var info = new FRAMEINFO[1];
var fields = enum_FRAMEINFO_FLAGS.FIF_DEBUG_MODULEP;
Assert.AreEqual(VSConstants.S_OK, _stackFrame.GetInfo(fields, 0, info));
Assert.AreEqual(enum_FRAMEINFO_FLAGS.FIF_DEBUG_MODULEP,
info[0].m_dwValidFields & enum_FRAMEINFO_FLAGS.FIF_DEBUG_MODULEP);
Assert.AreEqual(debugModule, info[0].m_pModule);
}
[Test]
public void EnsureFrameInfoFlagsMatchAd7()
{
CollectionAssert.AreEqual(Enum.GetNames(typeof(enum_FRAMEINFO_FLAGS)),
Enum.GetNames(typeof(FrameInfoFlags)));
Assert.AreEqual(Enum.GetUnderlyingType(typeof(enum_FRAMEINFO_FLAGS)),
Enum.GetUnderlyingType(typeof(FrameInfoFlags)));
Type underlyingType = Enum.GetUnderlyingType(typeof(FrameInfoFlags));
Array ad7Values = Enum.GetValues(typeof(enum_FRAMEINFO_FLAGS));
Array customValues = Enum.GetValues(typeof(FrameInfoFlags));
for (int i = 0; i < ad7Values.Length; ++i)
{
Assert.AreEqual(Convert.ChangeType(ad7Values.GetValue(i), underlyingType),
Convert.ChangeType(customValues.GetValue(i), underlyingType));
}
}
[Test]
public void GetPropertyProvider()
{
Guid guidFilter = FrameVariablesProvider.PropertyFilterGuids.AllLocals;
int status = _stackFrame.GetPropertyProvider(
(uint) enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_NAME, 0, ref guidFilter, 0,
out IAsyncDebugPropertyInfoProvider provider);
Assert.AreEqual(VSConstants.S_OK, status);
Assert.IsNotNull(provider);
Assert.IsInstanceOf<AsyncDebugRootPropertyInfoProvider>(provider);
}
}
}
| |
// Copyright 2017 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using UnityEngine;
using PolyToolkit;
namespace PolyToolkitInternal {
public enum GltfSchemaVersion { GLTF1, GLTF2 }
public class BadJson : Exception {
public BadJson(string message) : base(message) {}
public BadJson(string fmt, params System.Object[] args)
: base(string.Format(fmt, args)) {}
public BadJson(Exception inner, string fmt, params System.Object[] args)
: base(string.Format(fmt, args), inner) {}
}
//
// JSON.net magic for reading in a Matrix4x4 from a json float-array
//
public class JsonVectorConverter : JsonConverter {
public override bool CanConvert(Type objectType) {
return (objectType == typeof(Vector3)
|| objectType == typeof(Matrix4x4?)
|| objectType == typeof(Matrix4x4)
|| objectType == typeof(Color));
}
private static float ReadFloat(JsonReader reader) {
reader.Read();
if (reader.TokenType == JsonToken.Float || reader.TokenType == JsonToken.Integer) {
return Convert.ToSingle(reader.Value);
}
throw new BadJson("Expected numeric value");
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer) {
if (reader.TokenType != JsonToken.StartArray) {
throw new BadJson("Expected array");
}
object result;
if (objectType == typeof(Vector3)) {
result = new Vector3(
ReadFloat(reader),
ReadFloat(reader),
ReadFloat(reader));
} else if (objectType == typeof(Matrix4x4) ||
objectType == typeof(Matrix4x4?)) {
// Matrix members are m<row><col>
// Gltf stores matrices in column-major order
result = new Matrix4x4 {
m00=ReadFloat(reader), m10=ReadFloat(reader), m20=ReadFloat(reader), m30=ReadFloat(reader),
m01=ReadFloat(reader), m11=ReadFloat(reader), m21=ReadFloat(reader), m31=ReadFloat(reader),
m02=ReadFloat(reader), m12=ReadFloat(reader), m22=ReadFloat(reader), m32=ReadFloat(reader),
m03=ReadFloat(reader), m13=ReadFloat(reader), m23=ReadFloat(reader), m33=ReadFloat(reader)
};
} else if (objectType == typeof(Color) || objectType == typeof(Color?)) {
result = new Color(
ReadFloat(reader),
ReadFloat(reader),
ReadFloat(reader),
ReadFloat(reader));
} else {
Debug.Assert(false, "Converter registered with bad type");
throw new BadJson("Internal error");
}
reader.Read();
if (reader.TokenType != JsonToken.EndArray) {
throw new BadJson("Expected array end");
}
return result;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
throw new NotImplementedException();
}
}
// Specify converter for types that we can't annotate
public class GltfJsonContractResolver : DefaultContractResolver {
protected override JsonContract CreateContract(Type objectType) {
JsonContract contract = base.CreateContract(objectType);
if (objectType == typeof(Vector3)
|| objectType == typeof(Matrix4x4)
|| objectType == typeof(Matrix4x4?)
|| objectType == typeof(Color?)
|| objectType == typeof(Color)) {
contract.Converter = new JsonVectorConverter();
}
return contract;
}
}
//
// C# classes corresponding to the gltf json schema
//
[Serializable]
public class GltfAsset {
public Dictionary<string, string> extensions;
public Dictionary<string, string> extras;
public string copyright;
public string generator;
public bool premultipliedAlpha;
// public GltfProfile profile; not currently needed
public string version;
}
/// A bucket of mesh data in the format that Unity wants it
/// (or as close to it as possible)
public class MeshPrecursor {
public Vector3[] vertices;
public Vector3[] normals;
public Color[] colors;
public Vector4[] tangents;
public Array[] uvSets = new Array[2];
public int[] triangles;
}
// Note about the *Base classes: these are the base classes for the GLTF 1 and GLTF 2 versions
// of each entity. The fields that are common to both versions of the format go in the base
// class. The fields that differ (in name or type) between versions go in the subclasses.
// The version-specific subclasses are in Gltf{1,2}Schema.cs.
// For more info on the spec, see:
// https://github.com/KhronosGroup/glTF/
public abstract class GltfRootBase : IDisposable {
public GltfAsset asset;
// Tilt Brush/Blocks version that generated the gltf; null if not generated by that program
[JsonIgnore] public Version? tiltBrushVersion;
[JsonIgnore] public Version? blocksVersion;
public abstract GltfSceneBase ScenePtr { get; }
public abstract IEnumerable<GltfImageBase> Images { get; }
public abstract IEnumerable<GltfTextureBase> Textures { get; }
public abstract IEnumerable<GltfMaterialBase> Materials { get; }
public abstract void Dereference(IUriLoader uriLoader = null, PolyFormat gltfFormat = null);
// Disposable pattern, with Dispose(void) and Dispose(bool), as recommended by:
// https://docs.microsoft.com/en-us/dotnet/api/system.idisposable
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
// Subclasses should override Dispose(bool) and call base class implementation.
protected virtual void Dispose(bool disposing) {}
}
public abstract class GltfBufferBase {
public long byteLength;
public string uri;
[JsonIgnore] public IBufferReader data;
}
public abstract class GltfAccessorBase {
[Serializable] public enum ComponentType {
BYTE = 5120, UNSIGNED_BYTE = 5121, SHORT = 5122, UNSIGNED_SHORT = 5123, FLOAT = 5126
}
public int byteOffset;
public int byteStride;
public ComponentType componentType;
public int count;
public List<float> max;
public List<float> min;
public string type;
public abstract GltfBufferViewBase BufferViewPtr { get; }
}
public abstract class GltfBufferViewBase {
public int byteLength;
public int byteOffset;
public int target;
public abstract GltfBufferBase BufferPtr { get; }
}
public abstract class GltfPrimitiveBase {
[Serializable] public enum Mode { TRIANGLES = 4 }
public Mode mode = Mode.TRIANGLES;
// Not part of the schema; this is for lazy-creation convenience
// There may be more than one if the gltf primitive is too big for Unity
[JsonIgnore] public List<MeshPrecursor> precursorMeshes;
[JsonIgnore] public List<Mesh> unityMeshes;
public abstract GltfMaterialBase MaterialPtr { get; }
public abstract GltfAccessorBase IndicesPtr { get; }
public abstract GltfAccessorBase GetAttributePtr(string attributeName);
public abstract void ReplaceAttribute(string original, string replacement);
public abstract HashSet<string> GetAttributeNames();
}
public abstract class GltfImageBase {
public string uri;
[JsonIgnore] public RawImage data;
}
public abstract class GltfTextureBase {
[JsonIgnore] public Texture2D unityTexture;
public abstract object GltfId { get; }
public abstract GltfImageBase SourcePtr { get; }
}
public abstract class GltfMaterialBase {
public string name;
public abstract Dictionary<string,string> TechniqueExtras { get; }
public abstract IEnumerable<GltfTextureBase> ReferencedTextures { get; }
}
public abstract class GltfMeshBase {
public string name;
public abstract IEnumerable<GltfPrimitiveBase> Primitives { get ; }
public abstract int PrimitiveCount { get; }
public abstract GltfPrimitiveBase GetPrimitiveAt(int i);
}
public abstract class GltfNodeBase {
public string name;
public Matrix4x4? matrix;
// May return null
public abstract GltfMeshBase Mesh { get; }
public abstract IEnumerable<GltfNodeBase> Children { get; }
}
public abstract class GltfSceneBase {
public Dictionary<string, string> extras;
public abstract IEnumerable<GltfNodeBase> Nodes { get; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Foundatio.Caching;
using Foundatio.Parsers.ElasticQueries.Extensions;
using Foundatio.Repositories.Elasticsearch.Configuration;
using Foundatio.Repositories.Elasticsearch.Extensions;
using Foundatio.Repositories.Elasticsearch.Queries.Builders;
using Foundatio.Repositories.Extensions;
using Foundatio.Repositories.Models;
using Foundatio.Repositories.Options;
using Foundatio.Repositories.Queries;
using Foundatio.Utility;
using Microsoft.Extensions.Logging;
using Nest;
namespace Foundatio.Repositories.Elasticsearch {
public abstract class ElasticReadOnlyRepositoryBase<T> : IElasticReadOnlyRepository<T> where T : class, new() {
protected static readonly bool HasIdentity = typeof(IIdentity).IsAssignableFrom(typeof(T));
protected static readonly bool HasDates = typeof(IHaveDates).IsAssignableFrom(typeof(T));
protected static readonly bool HasCreatedDate = typeof(IHaveCreatedDate).IsAssignableFrom(typeof(T));
protected static readonly bool SupportsSoftDeletes = typeof(ISupportSoftDeletes).IsAssignableFrom(typeof(T));
protected static readonly bool HasVersion = typeof(IVersioned).IsAssignableFrom(typeof(T));
protected static readonly string EntityTypeName = typeof(T).Name;
protected static readonly IReadOnlyCollection<T> EmptyList = new List<T>(0).AsReadOnly();
private readonly List<Lazy<Field>> _defaultExcludes = new List<Lazy<Field>>();
protected readonly Lazy<string> _idField;
protected readonly ILogger _logger;
protected readonly Lazy<IElasticClient> _lazyClient;
protected IElasticClient _client => _lazyClient.Value;
private ScopedCacheClient _scopedCacheClient;
protected ElasticReadOnlyRepositoryBase(IIndexType<T> indexType) {
ElasticType = indexType;
if (HasIdentity)
_idField = new Lazy<string>(() => indexType.GetFieldName(doc => ((IIdentity)doc).Id) ?? "id");
_lazyClient = new Lazy<IElasticClient>(() => indexType.Configuration.Client);
SetCache(indexType.Configuration.Cache);
_logger = indexType.Configuration.LoggerFactory.CreateLogger(GetType());
}
public virtual Task<FindResults<T>> FindAsync(RepositoryQueryDescriptor<T> query, CommandOptionsDescriptor<T> options = null) {
return FindAsAsync<T>(query.Configure(), options.Configure());
}
public virtual Task<FindResults<T>> FindAsync(IRepositoryQuery query, ICommandOptions options = null) {
return FindAsAsync<T>(query, options);
}
public virtual Task<FindResults<TResult>> FindAsAsync<TResult>(RepositoryQueryDescriptor<T> query, CommandOptionsDescriptor<T> options = null) where TResult : class, new() {
return FindAsAsync<TResult>(query.Configure(), options.Configure());
}
public virtual async Task<FindResults<TResult>> FindAsAsync<TResult>(IRepositoryQuery query, ICommandOptions options = null) where TResult : class, new() {
if (query == null)
query = new RepositoryQuery();
options = ConfigureOptions(options);
bool useSnapshotPaging = options.ShouldUseSnapshotPaging();
// don't use caching with snapshot paging.
bool allowCaching = IsCacheEnabled && useSnapshotPaging == false;
await OnBeforeQueryAsync(query, options, typeof(TResult)).AnyContext();
async Task<FindResults<TResult>> GetNextPageFunc(FindResults<TResult> r) {
var previousResults = r;
if (previousResults == null)
throw new ArgumentException(nameof(r));
string scrollId = previousResults.GetScrollId();
if (!String.IsNullOrEmpty(scrollId)) {
var scrollResponse = await _client.ScrollAsync<TResult>(options.GetSnapshotLifetime(), scrollId).AnyContext();
_logger.LogTraceRequest(scrollResponse);
var results = scrollResponse.ToFindResults();
results.Page = previousResults.Page + 1;
results.HasMore = scrollResponse.Hits.Count >= options.GetLimit();
return results;
}
if (options.ShouldUseSearchAfterPaging()) {
var lastDocument = previousResults.Documents.LastOrDefault();
if (lastDocument != null) {
var searchAfterValues = new List<object>();
var sorts = query.GetSorts();
if (sorts.Count > 0) {
foreach (var sort in query.GetSorts()) {
if (sort.SortKey.Property?.DeclaringType == lastDocument.GetType()) {
searchAfterValues.Add(sort.SortKey.Property.GetValue(lastDocument));
} else if (typeof(TResult) == typeof(T) && sort.SortKey.Expression is Expression<Func<T, object>> valueGetterExpression) {
var valueGetter = valueGetterExpression.Compile();
if (lastDocument is T typedLastDocument) {
object value = valueGetter.Invoke(typedLastDocument);
searchAfterValues.Add(value);
}
} else if (sort.SortKey.Name != null) {
var propertyInfo = lastDocument.GetType().GetProperty(sort.SortKey.Name);
if (propertyInfo != null)
searchAfterValues.Add(propertyInfo.GetValue(lastDocument));
} else {
// TODO: going to to need to take the Expression and pull the string name from it
}
}
} else if (lastDocument is IIdentity lastDocumentId) {
searchAfterValues.Add(lastDocumentId.Id);
}
if (searchAfterValues.Count > 0)
options.SearchAfter(searchAfterValues.ToArray());
else
throw new ArgumentException("Unable to automatically calculate values for SearchAfterPaging.");
}
}
if (options == null)
return new FindResults<TResult>();
options?.PageNumber(!options.HasPageNumber() ? 2 : options.GetPage() + 1);
return await FindAsAsync<TResult>(query, options).AnyContext();
}
string cacheSuffix = options?.HasPageLimit() == true ? String.Concat(options.GetPage().ToString(), ":", options.GetLimit().ToString()) : null;
FindResults<TResult> result;
if (allowCaching) {
result = await GetCachedQueryResultAsync<FindResults<TResult>>(options, cacheSuffix: cacheSuffix).AnyContext();
if (result != null) {
((IGetNextPage<TResult>)result).GetNextPageFunc = async r => await GetNextPageFunc(r).AnyContext();
return result;
}
}
ISearchResponse<TResult> response;
if (useSnapshotPaging == false || !options.HasSnapshotScrollId()) {
var searchDescriptor = await CreateSearchDescriptorAsync(query, options).AnyContext();
if (useSnapshotPaging)
searchDescriptor.Scroll(options.GetSnapshotLifetime());
if (query.ShouldOnlyHaveIds())
searchDescriptor.Source(false);
response = await _client.SearchAsync<TResult>(searchDescriptor).AnyContext();
} else {
response = await _client.ScrollAsync<TResult>(options.GetSnapshotLifetime(), options.GetSnapshotScrollId()).AnyContext();
}
if (response.IsValid) {
_logger.LogTraceRequest(response);
} else {
if (response.ApiCall.HttpStatusCode.GetValueOrDefault() == 404)
return new FindResults<TResult>();
_logger.LogErrorRequest(response, "Error while searching");
throw new ApplicationException(response.GetErrorMessage(), response.OriginalException);
}
if (useSnapshotPaging) {
result = response.ToFindResults();
result.HasMore = response.Hits.Count >= options.GetLimit();
((IGetNextPage<TResult>)result).GetNextPageFunc = GetNextPageFunc;
} else if (options.HasPageLimit()) {
int limit = options.GetLimit();
result = response.ToFindResults(limit);
result.HasMore = response.Hits.Count > limit;
((IGetNextPage<TResult>)result).GetNextPageFunc = GetNextPageFunc;
} else {
result = response.ToFindResults();
}
result.Page = options.GetPage();
if (!allowCaching)
return result;
var nextPageFunc = ((IGetNextPage<TResult>)result).GetNextPageFunc;
((IGetNextPage<TResult>)result).GetNextPageFunc = null;
await SetCachedQueryResultAsync(options, result, cacheSuffix: cacheSuffix).AnyContext();
((IGetNextPage<TResult>)result).GetNextPageFunc = nextPageFunc;
return result;
}
public virtual Task<FindHit<T>> FindOneAsync(RepositoryQueryDescriptor<T> query, CommandOptionsDescriptor<T> options = null) {
return FindOneAsync(query.Configure(), options.Configure());
}
public virtual async Task<FindHit<T>> FindOneAsync(IRepositoryQuery query, ICommandOptions options = null) {
if (query == null)
throw new ArgumentNullException(nameof(query));
options = ConfigureOptions(options);
var result = IsCacheEnabled ? await GetCachedQueryResultAsync<FindHit<T>>(options).AnyContext() : null;
if (result != null)
return result;
await OnBeforeQueryAsync(query, options, typeof(T)).AnyContext();
var searchDescriptor = (await CreateSearchDescriptorAsync(query, options).AnyContext()).Size(1);
var response = await _client.SearchAsync<T>(searchDescriptor).AnyContext();
if (response.IsValid) {
_logger.LogTraceRequest(response);
} else {
if (response.ApiCall.HttpStatusCode.GetValueOrDefault() == 404)
return FindHit<T>.Empty;
_logger.LogErrorRequest(response, "Error while finding document");
throw new ApplicationException(response.GetErrorMessage(), response.OriginalException);
}
result = response.Hits.FirstOrDefault()?.ToFindHit();
if (IsCacheEnabled)
await SetCachedQueryResultAsync(options, result).AnyContext();
return result;
}
public virtual Task<FindResults<T>> SearchAsync(ISystemFilter systemFilter, string filter = null, string criteria = null, string sort = null, string aggregations = null, ICommandOptions options = null) {
var search = NewQuery()
.MergeFrom(systemFilter?.GetQuery())
.FilterExpression(filter)
.SearchExpression(criteria)
.AggregationsExpression(aggregations)
.SortExpression(sort);
return FindAsync(search, options);
}
public virtual async Task<T> GetByIdAsync(Id id, ICommandOptions options = null) {
if (String.IsNullOrEmpty(id.Value))
return null;
options = ConfigureOptions(options);
CacheValue<T> hit = null;
if (IsCacheEnabled && options.ShouldReadCache())
hit = await Cache.GetAsync<T>(id).AnyContext();
bool isTraceLogLevelEnabled = _logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Trace);
if (hit != null && hit.HasValue) {
if (isTraceLogLevelEnabled)
_logger.LogTrace("Cache hit: type={ElasticType} key={Id}", ElasticType.Name, id);
return hit.Value;
}
T document = null;
if (!HasParent || id.Routing != null) {
var request = new GetRequest(GetIndexById(id), ElasticType.Name, id.Value);
if (id.Routing != null)
request.Routing = id.Routing;
var response = await _client.GetAsync<T>(request).AnyContext();
if (isTraceLogLevelEnabled)
_logger.LogTraceRequest(response);
document = response.Found ? response.ToFindHit().Document : null;
} else {
// we don't have the parent id so we have to do a query
// TODO: Ensure this is find one query is not cached.
var findResult = await FindOneAsync(NewQuery().Id(id)).AnyContext();
if (findResult != null)
document = findResult.Document;
}
if (IsCacheEnabled && options.ShouldUseCache())
await Cache.SetAsync(id, document, options.GetExpiresIn()).AnyContext();
return document;
}
public virtual async Task<IReadOnlyCollection<T>> GetByIdsAsync(Ids ids, ICommandOptions options = null) {
var idList = ids?.Distinct().Where(i => !String.IsNullOrEmpty(i)).ToList();
if (idList == null || idList.Count == 0)
return EmptyList;
if (!HasIdentity)
throw new NotSupportedException("Model type must implement IIdentity.");
options = ConfigureOptions(options);
var hits = new List<T>();
if (IsCacheEnabled && options.ShouldReadCache()) {
var cacheHits = await Cache.GetAllAsync<T>(idList.Select(id => id.Value)).AnyContext();
hits.AddRange(cacheHits.Where(kvp => kvp.Value.HasValue).Select(kvp => kvp.Value.Value));
}
var itemsToFind = idList.Except(hits.OfType<IIdentity>().Select(i => (Id)i.Id)).ToList();
if (itemsToFind.Count == 0)
return hits.Where(h => h != null).ToList().AsReadOnly();
var multiGet = new MultiGetDescriptor();
foreach (var id in itemsToFind.Where(i => i.Routing != null || !HasParent)) {
multiGet.Get<T>(f => {
f.Id(id.Value).Index(GetIndexById(id)).Type(ElasticType.Name);
if (id.Routing != null)
f.Routing(id.Routing);
return f;
});
}
var multiGetResults = await _client.MultiGetAsync(multiGet).AnyContext();
_logger.LogTraceRequest(multiGetResults);
foreach (var doc in multiGetResults.Documents) {
hits.Add(((IMultiGetHit<T>)doc).ToFindHit().Document);
itemsToFind.Remove(new Id(doc.Id, doc.Routing));
}
// fallback to doing a find
if (itemsToFind.Count > 0 && (HasParent || HasMultipleIndexes)) {
var response = await FindAsync(q => q.Id(itemsToFind.Select(id => id.Value)), o => o.PageLimit(1000)).AnyContext();
do {
if (response.Hits.Count > 0)
hits.AddRange(response.Hits.Where(h => h.Document != null).Select(h => h.Document));
} while (await response.NextPageAsync().AnyContext());
}
if (IsCacheEnabled && options.ShouldUseCache()) {
var expiresIn = options.GetExpiresIn();
await Cache.SetAllAsync(idList.ToDictionary(id => id.Value, id => hits.OfType<IIdentity>().FirstOrDefault(h => h.Id == id.Value))).AnyContext();
}
return hits.Where(h => h != null).ToList().AsReadOnly();
}
public virtual Task<FindResults<T>> GetAllAsync(ICommandOptions options = null) {
return FindAsync(null, options);
}
public virtual async Task<bool> ExistsAsync(Id id) {
if (String.IsNullOrEmpty(id.Value))
return false;
if (!HasParent || id.Routing != null) {
var response = await _client.DocumentExistsAsync(new DocumentPath<T>(id.Value), d => {
d.Index(GetIndexById(id));
if (id.Routing != null)
d.Routing(id.Routing);
return d;
}).AnyContext();
_logger.LogTraceRequest(response);
return response.Exists;
}
return await ExistsAsync(q => q.Id(id)).AnyContext();
}
public virtual Task<bool> ExistsAsync(RepositoryQueryDescriptor<T> query) {
return ExistsAsync(query.Configure());
}
public virtual async Task<bool> ExistsAsync(IRepositoryQuery query) {
if (query == null)
throw new ArgumentNullException(nameof(query));
var options = ConfigureOptions(null);
await OnBeforeQueryAsync(query, options, typeof(T)).AnyContext();
var searchDescriptor = (await CreateSearchDescriptorAsync(query, options).AnyContext()).Size(1);
searchDescriptor.DocvalueFields(_idField.Value);
var response = await _client.SearchAsync<T>(searchDescriptor).AnyContext();
if (response.IsValid) {
_logger.LogTraceRequest(response);
} else {
if (response.ApiCall.HttpStatusCode.GetValueOrDefault() == 404)
return false;
_logger.LogErrorRequest(response, "Error checking if document exists");
throw new ApplicationException(response.GetErrorMessage(), response.OriginalException);
}
return response.HitsMetaData.Total > 0;
}
public virtual Task<CountResult> CountAsync(RepositoryQueryDescriptor<T> query, CommandOptionsDescriptor<T> options = null) {
return CountAsync(query.Configure(), options.Configure());
}
public virtual async Task<CountResult> CountAsync(IRepositoryQuery query, ICommandOptions options = null) {
if (query == null)
throw new ArgumentNullException(nameof(query));
options = ConfigureOptions(options);
var result = await GetCachedQueryResultAsync<CountResult>(options, "count").AnyContext();
if (result != null)
return result;
await OnBeforeQueryAsync(query, options, typeof(T)).AnyContext();
var searchDescriptor = await CreateSearchDescriptorAsync(query, options).AnyContext();
searchDescriptor.Size(0);
var response = await _client.SearchAsync<T>(searchDescriptor).AnyContext();
if (response.IsValid) {
_logger.LogTraceRequest(response);
} else {
if (response.ApiCall.HttpStatusCode.GetValueOrDefault() == 404)
return new CountResult();
_logger.LogErrorRequest(response, "Error getting document count");
throw new ApplicationException(response.GetErrorMessage(), response.OriginalException);
}
result = new CountResult(response.Total, response.ToAggregations());
await SetCachedQueryResultAsync(options, result, "count").AnyContext();
return result;
}
public virtual async Task<long> CountAsync(ICommandOptions options = null) {
options = ConfigureOptions(options);
var response = await _client.CountAsync<T>(c => c.Query(q => q.MatchAll()).Index(String.Join(",", GetIndexesByQuery(null))).Type(ElasticType.Name)).AnyContext();
if (response.IsValid) {
_logger.LogTraceRequest(response);
} else {
if (response.ApiCall.HttpStatusCode.GetValueOrDefault() == 404)
return 0;
_logger.LogErrorRequest(response, "Error getting document count");
throw new ApplicationException(response.GetErrorMessage(), response.OriginalException);
}
return response.Count;
}
public virtual Task<CountResult> CountBySearchAsync(ISystemFilter systemFilter, string filter = null, string aggregations = null, ICommandOptions options = null) {
var search = NewQuery()
.MergeFrom(systemFilter?.GetQuery())
.FilterExpression(filter)
.AggregationsExpression(aggregations);
return CountAsync(search, options);
}
protected virtual IRepositoryQuery<T> NewQuery() {
return new RepositoryQuery<T>();
}
protected virtual IRepositoryQuery ConfigureQuery(IRepositoryQuery query) {
if (query == null)
query = new RepositoryQuery<T>();
if (_defaultExcludes.Count > 0 && query.GetExcludes().Count == 0)
query.Exclude(_defaultExcludes.Select(e => e.Value));
return query;
}
protected void AddDefaultExclude(string field) {
_defaultExcludes.Add(new Lazy<Field>(() => field));
}
protected void AddDefaultExclude(Lazy<string> field) {
_defaultExcludes.Add(new Lazy<Field>(() => field.Value));
}
protected void AddDefaultExclude(Expression<Func<T, object>> objectPath) {
_defaultExcludes.Add(new Lazy<Field>(() => ElasticType.GetPropertyName(objectPath)));
}
protected void AddDefaultExclude(params Expression<Func<T, object>>[] objectPaths) {
_defaultExcludes.AddRange(objectPaths.Select(o => new Lazy<Field>(() => ElasticType.GetPropertyName(o))));
}
public bool IsCacheEnabled { get; private set; } = true;
protected ScopedCacheClient Cache => _scopedCacheClient ?? new ScopedCacheClient(new NullCacheClient());
private void SetCache(ICacheClient cache) {
IsCacheEnabled = cache != null;
_scopedCacheClient = new ScopedCacheClient(cache ?? new NullCacheClient(), EntityTypeName);
}
protected void DisableCache() {
IsCacheEnabled = false;
_scopedCacheClient = new ScopedCacheClient(new NullCacheClient(), EntityTypeName);
}
protected virtual async Task InvalidateCacheAsync(IReadOnlyCollection<ModifiedDocument<T>> documents, ICommandOptions options) {
if (!IsCacheEnabled)
return;
if (documents != null && documents.Count > 0 && HasIdentity) {
var keys = documents.Select(d => ((IIdentity)d.Value).Id).ToList();
if (keys.Count > 0)
await Cache.RemoveAllAsync(keys).AnyContext();
}
}
public virtual Task InvalidateCacheAsync(T document, ICommandOptions options = null) {
if (document == null)
throw new ArgumentNullException(nameof(document));
if (!IsCacheEnabled)
return Task.CompletedTask;
return InvalidateCacheAsync(new[] { document }, options);
}
public virtual Task InvalidateCacheAsync(IEnumerable<T> documents, ICommandOptions options = null) {
var docs = documents?.ToList();
if (docs == null || docs.Any(d => d == null))
throw new ArgumentNullException(nameof(documents));
if (!IsCacheEnabled)
return Task.CompletedTask;
return InvalidateCacheAsync(docs.Select(d => new ModifiedDocument<T>(d, null)).ToList(), options);
}
protected virtual Task<SearchDescriptor<T>> CreateSearchDescriptorAsync(IRepositoryQuery query, ICommandOptions options) {
return ConfigureSearchDescriptorAsync(null, query, options);
}
protected virtual async Task<SearchDescriptor<T>> ConfigureSearchDescriptorAsync(SearchDescriptor<T> search, IRepositoryQuery query, ICommandOptions options) {
if (search == null)
search = new SearchDescriptor<T>();
query = ConfigureQuery(query);
search.Type(ElasticType.Name);
string[] indices = GetIndexesByQuery(query);
if (indices?.Length > 0)
search.Index(String.Join(",", indices));
if (HasVersion)
search.Version(HasVersion);
search.IgnoreUnavailable();
await ElasticType.QueryBuilder.ConfigureSearchAsync(query, options, search).AnyContext();
return search;
}
protected virtual ICommandOptions ConfigureOptions(ICommandOptions options) {
if (options == null)
options = new CommandOptions<T>();
options.ElasticType(ElasticType);
return options;
}
protected virtual string[] GetIndexesByQuery(IRepositoryQuery query, ICommandOptions options = null) {
return HasMultipleIndexes ? TimeSeriesType.GetIndexesByQuery(query) : new[] { ElasticIndex.Name };
}
protected virtual string GetIndexById(Id id) {
return HasMultipleIndexes ? TimeSeriesType.GetIndexById(id) : ElasticIndex.Name;
}
protected Func<T, string> GetParentIdFunc => HasParent ? d => ChildType.GetParentId(d) : (Func<T, string>)null;
protected Func<T, string> GetDocumentIndexFunc => HasMultipleIndexes ? d => TimeSeriesType.GetDocumentIndex(d) : (Func<T, string>)(d => ElasticIndex.Name);
protected async Task<TResult> GetCachedQueryResultAsync<TResult>(ICommandOptions options, string cachePrefix = null, string cacheSuffix = null) {
if (!IsCacheEnabled || options == null || !options.ShouldReadCache() || !options.HasCacheKey())
return default;
string cacheKey = cachePrefix != null ? cachePrefix + ":" + options.GetCacheKey() : options.GetCacheKey();
if (!String.IsNullOrEmpty(cacheSuffix))
cacheKey += ":" + cacheSuffix;
var result = await Cache.GetAsync<TResult>(cacheKey, default).AnyContext();
if (_logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Trace))
_logger.LogTrace("Cache {HitOrMiss}: type={ElasticType} key={CacheKey}", (result != null ? "hit" : "miss"), ElasticType.Name, cacheKey);
return result;
}
protected async Task SetCachedQueryResultAsync<TResult>(ICommandOptions options, TResult result, string cachePrefix = null, string cacheSuffix = null) {
if (!IsCacheEnabled || result == null || options == null || !options.ShouldUseCache() || !options.HasCacheKey())
return;
string cacheKey = cachePrefix != null ? cachePrefix + ":" + options.GetCacheKey() : options.GetCacheKey();
if (!String.IsNullOrEmpty(cacheSuffix))
cacheKey += ":" + cacheSuffix;
await Cache.SetAsync(cacheKey, result, options.GetExpiresIn()).AnyContext();
if (_logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Trace))
_logger.LogTrace("Set cache: type={ElasticType} key={CacheKey}", ElasticType.Name, cacheKey);
}
#region Elastic Type Configuration
protected IIndex ElasticIndex => ElasticType.Index;
private IIndexType<T> _elasticType;
protected IIndexType<T> ElasticType {
get { return _elasticType; }
private set {
_elasticType = value;
if (_elasticType is IChildIndexType<T>) {
HasParent = true;
ChildType = _elasticType as IChildIndexType<T>;
} else {
HasParent = false;
ChildType = null;
}
if (_elasticType is ITimeSeriesIndexType) {
HasMultipleIndexes = true;
TimeSeriesType = _elasticType as ITimeSeriesIndexType<T>;
} else {
HasMultipleIndexes = false;
TimeSeriesType = null;
}
}
}
protected bool HasParent { get; private set; }
protected IChildIndexType<T> ChildType { get; private set; }
protected bool HasMultipleIndexes { get; private set; }
protected ITimeSeriesIndexType<T> TimeSeriesType { get; private set; }
#endregion
#region Events
public AsyncEvent<BeforeQueryEventArgs<T>> BeforeQuery { get; } = new AsyncEvent<BeforeQueryEventArgs<T>>();
private async Task OnBeforeQueryAsync(IRepositoryQuery query, ICommandOptions options, Type resultType) {
if (SupportsSoftDeletes && IsCacheEnabled && query.GetSoftDeleteMode() == SoftDeleteQueryMode.ActiveOnly) {
var deletedIds = await Cache.GetSetAsync<string>("deleted").AnyContext();
if (deletedIds.HasValue)
query.ExcludedId(deletedIds.Value);
}
if (BeforeQuery == null)
return;
await BeforeQuery.InvokeAsync(this, new BeforeQueryEventArgs<T>(query, options, this, resultType)).AnyContext();
}
#endregion
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.IO;
namespace _4PosBackOffice.NET
{
public class clsRC4
{
[DllImport("kernel32", EntryPoint = "RtlMoveMemory", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern void CopyMemory(long Destination, long Source, long Length);
private string m_Key;
private int[] m_sBox = new int[256];
private byte[] m_bytIndex = new byte[64];
private byte[] m_bytReverseIndex = new byte[256];
private const byte k_bytEqualSign = 61;
private const byte k_bytMask1 = 3;
private const byte k_bytMask2 = 15;
private const byte k_bytMask3 = 63;
private const byte k_bytMask4 = 192;
private const byte k_bytMask5 = 240;
private const byte k_bytMask6 = 252;
private const byte k_bytShift2 = 4;
private const byte k_bytShift4 = 16;
private const byte k_bytShift6 = 64;
private const long k_lMaxBytesPerLine = 152;
private void Initialize64()
{
int x = 0;
int y = 0;
for (x = 0; x <= 51; x++) {
m_bytIndex[x] = x + 65;
}
for (x = 52; x <= 61; x++) {
m_bytIndex[x] = x - 4;
m_bytReverseIndex[x - 4] = x;
}
m_bytIndex[62] = 43;
//Asc("+")
m_bytIndex[63] = 47;
//Asc("/")
y = 0;
for (x = 65; x <= 122; x++) {
m_bytReverseIndex[x] = y;
y = y + 1;
}
m_bytReverseIndex[43] = 62;
//Asc("+")
m_bytReverseIndex[47] = 63;
//Asc("/")
}
public string Decode64(string sInput)
{
string functionReturnValue = null;
if (string.IsNullOrEmpty(sInput))
return functionReturnValue;
functionReturnValue = Encoding.ASCII.GetString(DecodeArray64(sInput));
return functionReturnValue;
}
public byte[] DecodeArray64(string sInput)
{
if (m_bytReverseIndex[47] != 63)
Initialize64();
byte[] bytInput = null;
byte[] bytWorkspace = null;
byte[] bytResult = null;
long lInputCounter = 0;
long lWorkspaceCounter = 0;
string innerString = Strings.Replace(sInput, Constants.vbCrLf, "");
string outerString = Strings.Replace(innerString, "=", "");
bytInput = UTF8Encoding.UTF8.GetBytes(outerString);
bytWorkspace = new byte[(Information.UBound(bytInput) * 2) + 1];
lWorkspaceCounter = Information.LBound(bytWorkspace);
for (lInputCounter = Information.LBound(bytInput); lInputCounter <= Information.UBound(bytInput); lInputCounter++) {
bytInput[lInputCounter] = m_bytReverseIndex[bytInput[lInputCounter]];
}
for (lInputCounter = Information.LBound(bytInput); lInputCounter <= (Information.UBound(bytInput) - ((Information.UBound(bytInput) % 8) + 8)); lInputCounter += 8) {
bytWorkspace[lWorkspaceCounter] = (bytInput[lInputCounter] * k_bytShift2) + (bytInput[lInputCounter + 2] / k_bytShift4);
bytWorkspace[lWorkspaceCounter + 1] = ((bytInput[lInputCounter + 2] & k_bytMask2) * k_bytShift4) + (bytInput[lInputCounter + 4] / k_bytShift2);
bytWorkspace[lWorkspaceCounter + 2] = ((bytInput[lInputCounter + 4] & k_bytMask1) * k_bytShift6) + bytInput[lInputCounter + 6];
lWorkspaceCounter = lWorkspaceCounter + 3;
}
switch ((Information.UBound(bytInput) % 8)) {
case 3:
bytWorkspace[lWorkspaceCounter] = (bytInput[lInputCounter] * k_bytShift2) + (bytInput[lInputCounter + 2] / k_bytShift4);
break;
case 5:
bytWorkspace[lWorkspaceCounter] = (bytInput[lInputCounter] * k_bytShift2) + (bytInput[lInputCounter + 2] / k_bytShift4);
bytWorkspace[lWorkspaceCounter + 1] = ((bytInput[lInputCounter + 2] & k_bytMask2) * k_bytShift4) + (bytInput[lInputCounter + 4] / k_bytShift2);
lWorkspaceCounter = lWorkspaceCounter + 1;
break;
case 7:
bytWorkspace[lWorkspaceCounter] = (bytInput[lInputCounter] * k_bytShift2) + (bytInput[lInputCounter + 2] / k_bytShift4);
bytWorkspace[lWorkspaceCounter + 1] = ((bytInput[lInputCounter + 2] & k_bytMask2) * k_bytShift4) + (bytInput[lInputCounter + 4] / k_bytShift2);
bytWorkspace[lWorkspaceCounter + 2] = ((bytInput[lInputCounter + 4] & k_bytMask1) * k_bytShift6) + bytInput[lInputCounter + 6];
lWorkspaceCounter = lWorkspaceCounter + 2;
break;
}
bytResult = new byte[lWorkspaceCounter + 1];
if (Information.LBound(bytWorkspace) == 0)
lWorkspaceCounter = lWorkspaceCounter + 1;
CopyMemory(VarPtr.VarPtr(bytResult[Information.LBound(bytResult)]), VarPtr.VarPtr(bytWorkspace[Information.LBound(bytWorkspace)]), lWorkspaceCounter);
return bytResult;
}
public string Encode64(ref string sInput)
{
string functionReturnValue = null;
if (string.IsNullOrEmpty(sInput))
return functionReturnValue;
byte[] bytTemp = null;
bytTemp = Encoding.ASCII.GetBytes(sInput);
functionReturnValue = EncodeArray64(ref bytTemp);
return functionReturnValue;
}
public string EncodeArray64(ref byte[] bytInput)
{
string functionReturnValue = null;
// ERROR: Not supported in C#: OnErrorStatement
if (m_bytReverseIndex[47] != 63)
Initialize64();
byte[] bytWorkspace = null;
byte[] bytResult = null;
byte[] bytCrLf = new byte[4];
long lCounter = 0;
long lWorkspaceCounter = 0;
long lLineCounter = 0;
long lCompleteLines = 0;
long lBytesRemaining = 0;
long lpWorkSpace = 0;
long lpResult = 0;
long lpCrLf = 0;
if (Information.UBound(bytInput) < 1024) {
bytWorkspace = new byte[(Information.LBound(bytInput) + 4096) + 1];
} else {
bytWorkspace = new byte[(Information.UBound(bytInput) * 4) + 1];
}
lWorkspaceCounter = Information.LBound(bytWorkspace);
for (lCounter = Information.LBound(bytInput); lCounter <= (Information.UBound(bytInput) - ((Information.UBound(bytInput) % 3) + 3)); lCounter += 3) {
bytWorkspace[lWorkspaceCounter] = m_bytIndex[(bytInput[lCounter] / k_bytShift2)];
bytWorkspace[lWorkspaceCounter + 2] = m_bytIndex[((bytInput[lCounter] & k_bytMask1) * k_bytShift4) + ((bytInput[lCounter + 1]) / k_bytShift4)];
bytWorkspace[lWorkspaceCounter + 4] = m_bytIndex[((bytInput[lCounter + 1] & k_bytMask2) * k_bytShift2) + (bytInput[lCounter + 2] / k_bytShift6)];
bytWorkspace[lWorkspaceCounter + 6] = m_bytIndex[bytInput[lCounter + 2] & k_bytMask3];
lWorkspaceCounter = lWorkspaceCounter + 8;
}
switch ((Information.UBound(bytInput) % 3)) {
case 0:
bytWorkspace[lWorkspaceCounter] = m_bytIndex[(bytInput[lCounter] / k_bytShift2)];
bytWorkspace[lWorkspaceCounter + 2] = m_bytIndex[(bytInput[lCounter] & k_bytMask1) * k_bytShift4];
bytWorkspace[lWorkspaceCounter + 4] = k_bytEqualSign;
bytWorkspace[lWorkspaceCounter + 6] = k_bytEqualSign;
break;
case 1:
bytWorkspace[lWorkspaceCounter] = m_bytIndex[(bytInput[lCounter] / k_bytShift2)];
bytWorkspace[lWorkspaceCounter + 2] = m_bytIndex[((bytInput[lCounter] & k_bytMask1) * k_bytShift4) + ((bytInput[lCounter + 1]) / k_bytShift4)];
bytWorkspace[lWorkspaceCounter + 4] = m_bytIndex[(bytInput[lCounter + 1] & k_bytMask2) * k_bytShift2];
bytWorkspace[lWorkspaceCounter + 6] = k_bytEqualSign;
break;
case 2:
bytWorkspace[lWorkspaceCounter] = m_bytIndex[(bytInput[lCounter] / k_bytShift2)];
bytWorkspace[lWorkspaceCounter + 2] = m_bytIndex[((bytInput[lCounter] & k_bytMask1) * k_bytShift4) + ((bytInput[lCounter + 1]) / k_bytShift4)];
bytWorkspace[lWorkspaceCounter + 4] = m_bytIndex[((bytInput[lCounter + 1] & k_bytMask2) * k_bytShift2) + ((bytInput[lCounter + 2]) / k_bytShift6)];
bytWorkspace[lWorkspaceCounter + 6] = m_bytIndex[bytInput[lCounter + 2] & k_bytMask3];
break;
}
lWorkspaceCounter = lWorkspaceCounter + 8;
if (lWorkspaceCounter <= k_lMaxBytesPerLine) {
functionReturnValue = Strings.Left(bytWorkspace.ToString(), Strings.InStr(1, bytWorkspace.ToString(), "") - 1);
} else {
bytCrLf[0] = 13;
bytCrLf[1] = 0;
bytCrLf[2] = 10;
bytCrLf[3] = 0;
bytResult = new byte[Information.UBound(bytWorkspace) + 1];
lpWorkSpace = VarPtr.VarPtr(bytWorkspace[Information.LBound(bytWorkspace)]);
lpResult = VarPtr.VarPtr(bytResult[Information.LBound(bytResult)]);
lpCrLf = VarPtr.VarPtr(bytCrLf[Information.LBound(bytCrLf)]);
lCompleteLines = Conversion.Fix(lWorkspaceCounter / k_lMaxBytesPerLine);
for (lLineCounter = 0; lLineCounter <= lCompleteLines; lLineCounter++) {
CopyMemory(lpResult, lpWorkSpace, k_lMaxBytesPerLine);
lpWorkSpace = lpWorkSpace + k_lMaxBytesPerLine;
lpResult = lpResult + k_lMaxBytesPerLine;
CopyMemory(lpResult, lpCrLf, 4L);
lpResult = lpResult + 4L;
}
lBytesRemaining = lWorkspaceCounter - (lCompleteLines * k_lMaxBytesPerLine);
if (lBytesRemaining > 0)
CopyMemory(lpResult, lpWorkSpace, lBytesRemaining);
functionReturnValue = Strings.Left(bytResult.ToString(), Strings.InStr(1, bytResult.ToString(), "") - 1);
}
return functionReturnValue;
ErrorHandler:
bytResult = null;
functionReturnValue = bytResult.ToString();
return functionReturnValue;
}
public bool EncryptFile(string InFile, string OutFile, bool Overwrite, string Key = "", bool OutputIn64 = false)
{
bool functionReturnValue = false;
// ERROR: Not supported in C#: OnErrorStatement
if (FileExist(InFile) == false) {
functionReturnValue = false;
return functionReturnValue;
}
if (FileExist(OutFile) == true & Overwrite == false) {
functionReturnValue = false;
return functionReturnValue;
}
int FileO = 0;
byte[] Buffer = null;
FileO = FileSystem.FreeFile();
FileStream inStream = new FileStream(FileO.ToString(), FileMode.Open);
BinaryReader binRead = new BinaryReader(inStream);
Buffer = new byte[FileSystem.FileLen(FileO.ToString() - 1) + 1];
Buffer = binRead.ReadBytes(FileSystem.FileLen(FileO.ToString() - 1));
binRead.Close();
inStream.Close();
EncryptByte(Buffer, Key);
if (FileExist(OutFile) == true)
FileSystem.Kill(OutFile);
FileO = FileSystem.FreeFile();
FileStream outStream = new FileStream(FileO.ToString(), FileMode.Create);
BinaryWriter binWrite = new BinaryWriter(outStream);
if (OutputIn64 == true) {
binWrite.Write(EncodeArray64(ref Buffer));
} else {
binWrite.Write(Buffer);
}
binWrite.Close();
outStream.Close();
functionReturnValue = true;
return functionReturnValue;
ErrorHandler:
functionReturnValue = false;
return functionReturnValue;
}
public bool DecryptFile(string InFile, string OutFile, bool Overwrite, string Key = "", bool IsFileIn64 = false)
{
bool functionReturnValue = false;
// ERROR: Not supported in C#: OnErrorStatement
if (FileExist(InFile) == false) {
functionReturnValue = false;
return functionReturnValue;
}
if (FileExist(OutFile) == true & Overwrite == false) {
functionReturnValue = false;
return functionReturnValue;
}
int FileO = 0;
byte[] Buffer = null;
FileO = FileSystem.FreeFile();
FileStream inStream = new FileStream(FileO.ToString(), FileMode.Open);
BinaryReader binRead = new BinaryReader(inStream);
Buffer = new byte[FileSystem.FileLen(FileO.ToString())];
Buffer = binRead.ReadBytes(FileSystem.FileLen(FileO.ToString()) - 1);
binRead.Close();
inStream.Close();
if (IsFileIn64 == true)
Buffer = DecodeArray64(Encoding.ASCII.GetString(Buffer));
DecryptByte(Buffer, Key);
if (FileExist(OutFile) == true)
FileSystem.Kill(OutFile);
FileO = FileSystem.FreeFile();
FileStream outStream = new FileStream(FileO.ToString(), FileMode.Create);
BinaryWriter binWrite = new BinaryWriter(outStream);
binWrite.Write(Buffer);
binWrite.Close();
outStream.Close();
functionReturnValue = true;
return functionReturnValue;
ErrorHandler:
functionReturnValue = false;
return functionReturnValue;
}
public void DecryptByte(byte[] byteArray, string Key = "")
{
EncryptByte(byteArray, Key);
}
public string EncryptString(string Text, string Key = "", bool OutputIn64 = false)
{
string functionReturnValue = null;
byte[] byteArray = null;
byteArray = Encoding.ASCII.GetBytes(Text);
EncryptByte(byteArray, Key);
functionReturnValue = Encoding.ASCII.GetString(byteArray);
if (OutputIn64 == true)
functionReturnValue = Encode64(ref EncryptString());
return functionReturnValue;
}
public string DecryptString(string Text, string Key = "", bool IsTextIn64 = false)
{
byte[] byteArray = null;
if (IsTextIn64 == true)
Text = Decode64(Text);
byteArray = Encoding.ASCII.GetBytes(Text);
DecryptByte(byteArray, Key);
return Encoding.ASCII.GetString(byteArray);
}
public void EncryptByte(byte[] byteArray, string Key = "")
{
long i = 0;
long j = 0;
byte Temp = 0;
long Offset = 0;
long OrigLen = 0;
long CipherLen = 0;
long CurrPercent = 0;
long NextPercent = 0;
int[] sBox = new int[256];
if ((Strings.Len(Key) > 0))
this.Key = Key;
CopyMemory(sBox[0], m_sBox[0], 512);
OrigLen = Information.UBound(byteArray) + 1;
CipherLen = OrigLen;
for (Offset = 0; Offset <= (OrigLen - 1); Offset++) {
i = (i + 1) % 256;
j = (j + sBox[i]) % 256;
Temp = sBox[i];
sBox[i] = sBox[j];
sBox[j] = Temp;
byteArray[Offset] = byteArray[Offset] ^ (sBox[(sBox[i] + sBox[j]) % 256]);
if ((Offset >= NextPercent)) {
CurrPercent = Conversion.Int((Offset / CipherLen) * 100);
NextPercent = (CipherLen * ((CurrPercent + 1) / 100)) + 1;
//RaiseEvent Progress(CurrPercent)
}
}
//If (CurrPercent <> 100) Then RaiseEvent Progress(100)
}
private bool FileExist(string Filename)
{
bool functionReturnValue = false;
// ERROR: Not supported in C#: OnErrorStatement
FileSystem.FileLen(Filename);
functionReturnValue = true;
return functionReturnValue;
ErrorHandler:
functionReturnValue = false;
return functionReturnValue;
}
public string Key {
set {
long a = 0;
long b = 0;
byte Temp = 0;
byte[] myKey = null;
long KeyLen = 0;
if ((m_Key == value))
return;
m_Key = value;
//myKey = StrConv(m_Key, vbFromUnicode)
myKey = Encoding.ASCII.GetBytes(m_Key);
KeyLen = Strings.Len(m_Key);
for (a = 0; a <= 255; a++) {
m_sBox[a] = a;
}
for (a = 0; a <= 255; a++) {
b = (b + m_sBox[a] + myKey[a % KeyLen]) % 256;
Temp = m_sBox[a];
m_sBox[a] = m_sBox[b];
m_sBox[b] = Temp;
}
}
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections;
using System.Collections.Generic;
namespace WeifenLuo.WinFormsUI.Docking
{
internal class VS2005DockPaneStrip : DockPaneStripBase
{
private class TabVS2005 : Tab
{
public TabVS2005(IDockContent content)
: base(content)
{
}
private int m_tabX;
public int TabX
{
get { return m_tabX; }
set { m_tabX = value; }
}
private int m_tabWidth;
public int TabWidth
{
get { return m_tabWidth; }
set { m_tabWidth = value; }
}
private int m_maxWidth;
public int MaxWidth
{
get { return m_maxWidth; }
set { m_maxWidth = value; }
}
private bool m_flag;
protected internal bool Flag
{
get { return m_flag; }
set { m_flag = value; }
}
}
protected internal override DockPaneStripBase.Tab CreateTab(IDockContent content)
{
return new TabVS2005(content);
}
private sealed class InertButton : InertButtonBase
{
private Bitmap m_image0, m_image1;
public InertButton(Bitmap image0, Bitmap image1)
: base()
{
m_image0 = image0;
m_image1 = image1;
}
private int m_imageCategory = 0;
public int ImageCategory
{
get { return m_imageCategory; }
set
{
if (m_imageCategory == value)
return;
m_imageCategory = value;
Invalidate();
}
}
public override Bitmap Image
{
get { return ImageCategory == 0 ? m_image0 : m_image1; }
}
protected override void OnRefreshChanges()
{
if (VS2005DockPaneStrip.ColorDocumentActiveText != ForeColor)
{
ForeColor = VS2005DockPaneStrip.ColorDocumentActiveText;
Invalidate();
}
}
}
#region consts
private const int _ToolWindowStripGapTop = 0;
private const int _ToolWindowStripGapBottom = 1;
private const int _ToolWindowStripGapLeft = 0;
private const int _ToolWindowStripGapRight = 0;
private const int _ToolWindowImageHeight = 16;
private const int _ToolWindowImageWidth = 16;
private const int _ToolWindowImageGapTop = 3;
private const int _ToolWindowImageGapBottom = 1;
private const int _ToolWindowImageGapLeft = 2;
private const int _ToolWindowImageGapRight = 0;
private const int _ToolWindowTextGapRight = 3;
private const int _ToolWindowTabSeperatorGapTop = 3;
private const int _ToolWindowTabSeperatorGapBottom = 3;
private const int _DocumentStripGapTop = 0;
private const int _DocumentStripGapBottom = 1;
private const int _DocumentTabMaxWidth = 200;
private const int _DocumentButtonGapTop = 4;
private const int _DocumentButtonGapBottom = 4;
private const int _DocumentButtonGapBetween = 0;
private const int _DocumentButtonGapRight = 3;
private const int _DocumentTabGapTop = 3;
private const int _DocumentTabGapLeft = 3;
private const int _DocumentTabGapRight = 3;
private const int _DocumentIconGapBottom = 2;
private const int _DocumentIconGapLeft = 8;
private const int _DocumentIconGapRight = 0;
private const int _DocumentIconHeight = 16;
private const int _DocumentIconWidth = 16;
private const int _DocumentTextGapRight = 3;
#endregion
private static Bitmap _imageButtonClose;
private static Bitmap ImageButtonClose
{
get
{
if (_imageButtonClose == null)
_imageButtonClose = Resources.DockPane_Close;
return _imageButtonClose;
}
}
private InertButton m_buttonClose;
private InertButton ButtonClose
{
get
{
if (m_buttonClose == null)
{
m_buttonClose = new InertButton(ImageButtonClose, ImageButtonClose);
m_toolTip.SetToolTip(m_buttonClose, ToolTipClose);
m_buttonClose.Click += new EventHandler(Close_Click);
Controls.Add(m_buttonClose);
}
return m_buttonClose;
}
}
private static Bitmap _imageButtonWindowList;
private static Bitmap ImageButtonWindowList
{
get
{
if (_imageButtonWindowList == null)
_imageButtonWindowList = Resources.DockPane_Option;
return _imageButtonWindowList;
}
}
private static Bitmap _imageButtonWindowListOverflow;
private static Bitmap ImageButtonWindowListOverflow
{
get
{
if (_imageButtonWindowListOverflow == null)
_imageButtonWindowListOverflow = Resources.DockPane_OptionOverflow;
return _imageButtonWindowListOverflow;
}
}
private InertButton m_buttonWindowList;
private InertButton ButtonWindowList
{
get
{
if (m_buttonWindowList == null)
{
m_buttonWindowList = new InertButton(ImageButtonWindowList, ImageButtonWindowListOverflow);
m_toolTip.SetToolTip(m_buttonWindowList, ToolTipSelect);
m_buttonWindowList.Click += new EventHandler(WindowList_Click);
Controls.Add(m_buttonWindowList);
}
return m_buttonWindowList;
}
}
private static GraphicsPath GraphicsPath
{
get { return VS2005AutoHideStrip.GraphicsPath; }
}
private IContainer m_components;
private ToolTip m_toolTip;
private IContainer Components
{
get { return m_components; }
}
#region Customizable Properties
private static int ToolWindowStripGapTop
{
get { return _ToolWindowStripGapTop; }
}
private static int ToolWindowStripGapBottom
{
get { return _ToolWindowStripGapBottom; }
}
private static int ToolWindowStripGapLeft
{
get { return _ToolWindowStripGapLeft; }
}
private static int ToolWindowStripGapRight
{
get { return _ToolWindowStripGapRight; }
}
private static int ToolWindowImageHeight
{
get { return _ToolWindowImageHeight; }
}
private static int ToolWindowImageWidth
{
get { return _ToolWindowImageWidth; }
}
private static int ToolWindowImageGapTop
{
get { return _ToolWindowImageGapTop; }
}
private static int ToolWindowImageGapBottom
{
get { return _ToolWindowImageGapBottom; }
}
private static int ToolWindowImageGapLeft
{
get { return _ToolWindowImageGapLeft; }
}
private static int ToolWindowImageGapRight
{
get { return _ToolWindowImageGapRight; }
}
private static int ToolWindowTextGapRight
{
get { return _ToolWindowTextGapRight; }
}
private static int ToolWindowTabSeperatorGapTop
{
get { return _ToolWindowTabSeperatorGapTop; }
}
private static int ToolWindowTabSeperatorGapBottom
{
get { return _ToolWindowTabSeperatorGapBottom; }
}
private static string _toolTipClose;
private static string ToolTipClose
{
get
{
if (_toolTipClose == null)
_toolTipClose = Strings.DockPaneStrip_ToolTipClose;
return _toolTipClose;
}
}
private static string _toolTipSelect;
private static string ToolTipSelect
{
get
{
if (_toolTipSelect == null)
_toolTipSelect = Strings.DockPaneStrip_ToolTipWindowList;
return _toolTipSelect;
}
}
private TextFormatFlags ToolWindowTextFormat
{
get
{
TextFormatFlags textFormat = TextFormatFlags.EndEllipsis |
TextFormatFlags.HorizontalCenter |
TextFormatFlags.SingleLine |
TextFormatFlags.VerticalCenter;
if (RightToLeft == RightToLeft.Yes)
return textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right;
else
return textFormat;
}
}
private static int DocumentStripGapTop
{
get { return _DocumentStripGapTop; }
}
private static int DocumentStripGapBottom
{
get { return _DocumentStripGapBottom; }
}
private TextFormatFlags DocumentTextFormat
{
get
{
TextFormatFlags textFormat = TextFormatFlags.PathEllipsis | TextFormatFlags.EndEllipsis |
TextFormatFlags.SingleLine |
TextFormatFlags.VerticalCenter |
TextFormatFlags.PreserveGraphicsClipping |
TextFormatFlags.HorizontalCenter;
if (RightToLeft == RightToLeft.Yes)
return textFormat | TextFormatFlags.RightToLeft;
else
return textFormat;
}
}
private static int DocumentTabMaxWidth
{
get { return _DocumentTabMaxWidth; }
}
private static int DocumentButtonGapTop
{
get { return _DocumentButtonGapTop; }
}
private static int DocumentButtonGapBottom
{
get { return _DocumentButtonGapBottom; }
}
private static int DocumentButtonGapBetween
{
get { return _DocumentButtonGapBetween; }
}
private static int DocumentButtonGapRight
{
get { return _DocumentButtonGapRight; }
}
private static int DocumentTabGapTop
{
get { return _DocumentTabGapTop; }
}
private static int DocumentTabGapLeft
{
get { return _DocumentTabGapLeft; }
}
private static int DocumentTabGapRight
{
get { return _DocumentTabGapRight; }
}
private static int DocumentIconGapBottom
{
get { return _DocumentIconGapBottom; }
}
private static int DocumentIconGapLeft
{
get { return _DocumentIconGapLeft; }
}
private static int DocumentIconGapRight
{
get { return _DocumentIconGapRight; }
}
private static int DocumentIconWidth
{
get { return _DocumentIconWidth; }
}
private static int DocumentIconHeight
{
get { return _DocumentIconHeight; }
}
private static int DocumentTextGapRight
{
get { return _DocumentTextGapRight; }
}
private static Pen PenToolWindowTabBorder
{
get { return SystemPens.GrayText; }
}
private static Pen PenDocumentTabActiveBorder
{
get { return SystemPens.ControlDarkDark; }
}
private static Pen PenDocumentTabInactiveBorder
{
get { return SystemPens.GrayText; }
}
private static Brush BrushToolWindowActiveBackground
{
get { return SystemBrushes.Control; }
}
private static Brush BrushDocumentActiveBackground
{
get { return SystemBrushes.ControlLightLight; }
}
private static Brush BrushDocumentInactiveBackground
{
get { return SystemBrushes.ControlLight; }
}
private static Color ColorToolWindowActiveText
{
get { return SystemColors.ControlText; }
}
private static Color ColorDocumentActiveText
{
get { return SystemColors.ControlText; }
}
private static Color ColorToolWindowInactiveText
{
get { return SystemColors.ControlDarkDark; }
}
private static Color ColorDocumentInactiveText
{
get { return SystemColors.ControlText; }
}
#endregion
public VS2005DockPaneStrip(DockPane pane) : base(pane)
{
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SuspendLayout();
Font = SystemInformation.MenuFont;
m_components = new Container();
m_toolTip = new ToolTip(Components);
m_selectMenu = new ContextMenuStrip(Components);
ResumeLayout();
}
protected override void Dispose(bool disposing)
{
if (disposing)
Components.Dispose();
base.Dispose (disposing);
}
private Font m_boldFont;
private Font BoldFont
{
get
{
if (m_boldFont == null)
m_boldFont = new Font(Font, FontStyle.Bold);
return m_boldFont;
}
}
protected override void OnFontChanged(EventArgs e)
{
base.OnFontChanged(e);
if (m_boldFont != null)
{
m_boldFont.Dispose();
m_boldFont = null;
}
}
private int m_startDisplayingTab = 0;
private int StartDisplayingTab
{
get { return m_startDisplayingTab; }
set
{
m_startDisplayingTab = value;
Invalidate();
}
}
private int m_endDisplayingTab = 0;
private int EndDisplayingTab
{
get { return m_endDisplayingTab; }
set { m_endDisplayingTab = value; }
}
private bool m_documentTabsOverflow = false;
private bool DocumentTabsOverflow
{
set
{
if (m_documentTabsOverflow == value)
return;
m_documentTabsOverflow = value;
if (value)
ButtonWindowList.ImageCategory = 1;
else
ButtonWindowList.ImageCategory = 0;
}
}
protected internal override int MeasureHeight()
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return MeasureHeight_ToolWindow();
else
return MeasureHeight_Document();
}
private int MeasureHeight_ToolWindow()
{
if (DockPane.IsAutoHide || Tabs.Count <= 1)
return 0;
int height = Math.Max(Font.Height, ToolWindowImageHeight + ToolWindowImageGapTop + ToolWindowImageGapBottom)
+ ToolWindowStripGapTop + ToolWindowStripGapBottom;
return height;
}
private int MeasureHeight_Document()
{
int height = Math.Max(Font.Height + DocumentTabGapTop,
ButtonClose.Height + DocumentButtonGapTop + DocumentButtonGapBottom)
+ DocumentStripGapBottom + DocumentStripGapTop;
return height;
}
protected override void OnPaint(PaintEventArgs e)
{
if (DockPane.Disposing) return;
if (Appearance == DockPane.AppearanceStyle.Document)
{
if (BackColor != SystemColors.Control)
BackColor = SystemColors.Control;
}
else
{
if (BackColor != SystemColors.ControlLight)
BackColor = SystemColors.ControlLight;
}
base.OnPaint (e);
CalculateTabs();
if (Appearance == DockPane.AppearanceStyle.Document && DockPane.ActiveContent != null)
{
try // lsl
{
if (EnsureDocumentTabVisible(DockPane.ActiveContent, false))
CalculateTabs();
}
catch { }
}
DrawTabStrip(e.Graphics);
}
protected override void OnRefreshChanges()
{
SetInertButtons();
Invalidate();
}
protected internal override GraphicsPath GetOutline(int index)
{
if (Appearance == DockPane.AppearanceStyle.Document)
return GetOutline_Document(index);
else
return GetOutline_ToolWindow(index);
}
private GraphicsPath GetOutline_Document(int index)
{
Rectangle rectTab = GetTabRectangle(index);
rectTab.X -= rectTab.Height / 2;
rectTab.Intersect(TabsRectangle);
rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab));
int y = rectTab.Top;
Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle);
GraphicsPath path = new GraphicsPath();
GraphicsPath pathTab = GetTabOutline_Document(Tabs[index], true, true, true);
path.AddPath(pathTab, true);
path.AddLine(rectTab.Right, rectTab.Bottom, rectPaneClient.Right, rectTab.Bottom);
path.AddLine(rectPaneClient.Right, rectTab.Bottom, rectPaneClient.Right, rectPaneClient.Bottom);
path.AddLine(rectPaneClient.Right, rectPaneClient.Bottom, rectPaneClient.Left, rectPaneClient.Bottom);
path.AddLine(rectPaneClient.Left, rectPaneClient.Bottom, rectPaneClient.Left, rectTab.Bottom);
path.AddLine(rectPaneClient.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom);
return path;
}
private GraphicsPath GetOutline_ToolWindow(int index)
{
Rectangle rectTab = GetTabRectangle(index);
rectTab.Intersect(TabsRectangle);
rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab));
int y = rectTab.Top;
Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle);
GraphicsPath path = new GraphicsPath();
GraphicsPath pathTab = GetTabOutline(Tabs[index], true, true);
path.AddPath(pathTab, true);
path.AddLine(rectTab.Left, rectTab.Top, rectPaneClient.Left, rectTab.Top);
path.AddLine(rectPaneClient.Left, rectTab.Top, rectPaneClient.Left, rectPaneClient.Top);
path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Right, rectPaneClient.Top);
path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Right, rectTab.Top);
path.AddLine(rectPaneClient.Right, rectTab.Top, rectTab.Right, rectTab.Top);
return path;
}
private void CalculateTabs()
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
CalculateTabs_ToolWindow();
else
CalculateTabs_Document();
}
private void CalculateTabs_ToolWindow()
{
if (Tabs.Count <= 1 || DockPane.IsAutoHide)
return;
Rectangle rectTabStrip = TabStripRectangle;
// Calculate tab widths
int countTabs = Tabs.Count;
foreach (TabVS2005 tab in Tabs)
{
tab.MaxWidth = GetMaxTabWidth(Tabs.IndexOf(tab));
tab.Flag = false;
}
// Set tab whose max width less than average width
bool anyWidthWithinAverage = true;
int totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight;
int totalAllocatedWidth = 0;
int averageWidth = totalWidth / countTabs;
int remainedTabs = countTabs;
for (anyWidthWithinAverage=true; anyWidthWithinAverage && remainedTabs>0;)
{
anyWidthWithinAverage = false;
foreach (TabVS2005 tab in Tabs)
{
if (tab.Flag)
continue;
if (tab.MaxWidth <= averageWidth)
{
tab.Flag = true;
tab.TabWidth = tab.MaxWidth;
totalAllocatedWidth += tab.TabWidth;
anyWidthWithinAverage = true;
remainedTabs--;
}
}
if (remainedTabs != 0)
averageWidth = (totalWidth - totalAllocatedWidth) / remainedTabs;
}
// If any tab width not set yet, set it to the average width
if (remainedTabs > 0)
{
int roundUpWidth = (totalWidth - totalAllocatedWidth) - (averageWidth * remainedTabs);
foreach (TabVS2005 tab in Tabs)
{
if (tab.Flag)
continue;
tab.Flag = true;
if (roundUpWidth > 0)
{
tab.TabWidth = averageWidth + 1;
roundUpWidth --;
}
else
tab.TabWidth = averageWidth;
}
}
// Set the X position of the tabs
int x = rectTabStrip.X + ToolWindowStripGapLeft;
foreach (TabVS2005 tab in Tabs)
{
tab.TabX = x;
x += tab.TabWidth;
}
}
private bool CalculateDocumentTab(Rectangle rectTabStrip, ref int x, int index)
{
bool overflow = false;
TabVS2005 tab = Tabs[index] as TabVS2005;
tab.MaxWidth = GetMaxTabWidth(index);
int width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth);
if (x + width < rectTabStrip.Right || index == StartDisplayingTab)
{
tab.TabX = x;
tab.TabWidth = width;
EndDisplayingTab = index;
}
else
{
tab.TabX = 0;
tab.TabWidth = 0;
overflow = true;
}
x += width;
return overflow;
}
private void CalculateTabs_Document()
{
if (m_startDisplayingTab >= Tabs.Count)
m_startDisplayingTab = 0;
Rectangle rectTabStrip = TabsRectangle;
int x = rectTabStrip.X + rectTabStrip.Height / 2;
bool overflow = false;
for (int i = StartDisplayingTab; i < Tabs.Count; i++)
overflow = CalculateDocumentTab(rectTabStrip, ref x, i);
for (int i = 0; i < StartDisplayingTab; i++)
overflow = CalculateDocumentTab(rectTabStrip, ref x, i);
if (!overflow)
{
m_startDisplayingTab = 0;
x = rectTabStrip.X + rectTabStrip.Height / 2;
foreach (TabVS2005 tab in Tabs)
{
tab.TabX = x;
x += tab.TabWidth;
}
}
DocumentTabsOverflow = overflow;
}
protected internal override void EnsureTabVisible(IDockContent content)
{
if (Appearance != DockPane.AppearanceStyle.Document || !Tabs.Contains(content))
return;
CalculateTabs();
EnsureDocumentTabVisible(content, true);
}
private bool EnsureDocumentTabVisible(IDockContent content, bool repaint)
{
int index = Tabs.IndexOf(content);
TabVS2005 tab = Tabs[index] as TabVS2005;
if (tab.TabWidth != 0)
return false;
StartDisplayingTab = index;
if (repaint)
Invalidate();
return true;
}
private int GetMaxTabWidth(int index)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return GetMaxTabWidth_ToolWindow(index);
else
return GetMaxTabWidth_Document(index);
}
private int GetMaxTabWidth_ToolWindow(int index)
{
IDockContent content = Tabs[index].Content;
Size sizeString = TextRenderer.MeasureText(content.DockHandler.TabText, Font);
return ToolWindowImageWidth + sizeString.Width + ToolWindowImageGapLeft
+ ToolWindowImageGapRight + ToolWindowTextGapRight;
}
private int GetMaxTabWidth_Document(int index)
{
IDockContent content = Tabs[index].Content;
int height = GetTabRectangle_Document(index).Height;
Size sizeText = TextRenderer.MeasureText(content.DockHandler.TabText, BoldFont, new Size(DocumentTabMaxWidth, height), DocumentTextFormat);
if (DockPane.DockPanel.ShowDocumentIcon)
return sizeText.Width + DocumentIconWidth + DocumentIconGapLeft + DocumentIconGapRight + DocumentTextGapRight;
else
return sizeText.Width + DocumentIconGapLeft + DocumentTextGapRight;
}
private void DrawTabStrip(Graphics g)
{
if (Appearance == DockPane.AppearanceStyle.Document)
DrawTabStrip_Document(g);
else
DrawTabStrip_ToolWindow(g);
}
private void DrawTabStrip_Document(Graphics g)
{
int count = Tabs.Count;
if (count == 0)
return;
Rectangle rectTabStrip = TabStripRectangle;
// Draw the tabs
Rectangle rectTabOnly = TabsRectangle;
Rectangle rectTab = Rectangle.Empty;
TabVS2005 tabActive = null;
g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly));
for (int i=0; i<count; i++)
{
rectTab = GetTabRectangle(i);
if (Tabs[i].Content == DockPane.ActiveContent)
{
tabActive = Tabs[i] as TabVS2005;
continue;
}
if (rectTab.IntersectsWith(rectTabOnly))
DrawTab(g, Tabs[i] as TabVS2005, rectTab);
}
g.SetClip(rectTabStrip);
g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Bottom - 1,
rectTabStrip.Right, rectTabStrip.Bottom - 1);
g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly));
if (tabActive != null)
{
rectTab = GetTabRectangle(Tabs.IndexOf(tabActive));
if (rectTab.IntersectsWith(rectTabOnly))
DrawTab(g, tabActive, rectTab);
}
}
private void DrawTabStrip_ToolWindow(Graphics g)
{
Rectangle rectTabStrip = TabStripRectangle;
g.DrawLine(PenToolWindowTabBorder, rectTabStrip.Left, rectTabStrip.Top,
rectTabStrip.Right, rectTabStrip.Top);
for (int i=0; i<Tabs.Count; i++)
DrawTab(g, Tabs[i] as TabVS2005, GetTabRectangle(i));
}
private Rectangle GetTabRectangle(int index)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return GetTabRectangle_ToolWindow(index);
else
return GetTabRectangle_Document(index);
}
private Rectangle GetTabRectangle_ToolWindow(int index)
{
Rectangle rectTabStrip = TabStripRectangle;
TabVS2005 tab = (TabVS2005)(Tabs[index]);
return new Rectangle(tab.TabX, rectTabStrip.Y, tab.TabWidth, rectTabStrip.Height);
}
private Rectangle GetTabRectangle_Document(int index)
{
Rectangle rectTabStrip = TabStripRectangle;
TabVS2005 tab = (TabVS2005)Tabs[index];
return new Rectangle(tab.TabX, rectTabStrip.Y + DocumentTabGapTop, tab.TabWidth, rectTabStrip.Height - DocumentTabGapTop);
}
private void DrawTab(Graphics g, TabVS2005 tab, Rectangle rect)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
DrawTab_ToolWindow(g, tab, rect);
else
DrawTab_Document(g, tab, rect);
}
private GraphicsPath GetTabOutline(Tab tab, bool rtlTransform, bool toScreen)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return GetTabOutline_ToolWindow(tab, rtlTransform, toScreen);
else
return GetTabOutline_Document(tab, rtlTransform, toScreen, false);
}
private GraphicsPath GetTabOutline_ToolWindow(Tab tab, bool rtlTransform, bool toScreen)
{
Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab));
if (rtlTransform)
rect = DrawHelper.RtlTransform(this, rect);
if (toScreen)
rect = RectangleToScreen(rect);
DrawHelper.GetRoundedCornerTab(GraphicsPath, rect, false);
return GraphicsPath;
}
private GraphicsPath GetTabOutline_Document(Tab tab, bool rtlTransform, bool toScreen, bool full)
{
int curveSize = 6;
GraphicsPath.Reset();
Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab));
if (rtlTransform)
rect = DrawHelper.RtlTransform(this, rect);
if (toScreen)
rect = RectangleToScreen(rect);
if (tab.Content == DockPane.ActiveContent || Tabs.IndexOf(tab) == StartDisplayingTab || full)
{
if (RightToLeft == RightToLeft.Yes)
{
GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right + rect.Height / 2, rect.Bottom);
GraphicsPath.AddLine(rect.Right + rect.Height / 2, rect.Bottom, rect.Right - rect.Height / 2 + curveSize / 2, rect.Top + curveSize / 2);
}
else
{
GraphicsPath.AddLine(rect.Left, rect.Bottom, rect.Left - rect.Height / 2, rect.Bottom);
GraphicsPath.AddLine(rect.Left - rect.Height / 2, rect.Bottom, rect.Left + rect.Height / 2 - curveSize / 2, rect.Top + curveSize / 2);
}
}
else
{
if (RightToLeft == RightToLeft.Yes)
{
GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right, rect.Bottom - rect.Height / 2);
GraphicsPath.AddLine(rect.Right, rect.Bottom - rect.Height / 2, rect.Right - rect.Height / 2 + curveSize / 2, rect.Top + curveSize / 2);
}
else
{
GraphicsPath.AddLine(rect.Left, rect.Bottom, rect.Left, rect.Bottom - rect.Height / 2);
GraphicsPath.AddLine(rect.Left, rect.Bottom - rect.Height / 2, rect.Left + rect.Height / 2 - curveSize / 2, rect.Top + curveSize / 2);
}
}
if (RightToLeft == RightToLeft.Yes)
{
GraphicsPath.AddLine(rect.Right - rect.Height / 2 - curveSize / 2, rect.Top, rect.Left + curveSize / 2, rect.Top);
GraphicsPath.AddArc(new Rectangle(rect.Left, rect.Top, curveSize, curveSize), 180, 90);
}
else
{
GraphicsPath.AddLine(rect.Left + rect.Height / 2 + curveSize / 2, rect.Top, rect.Right - curveSize / 2, rect.Top);
GraphicsPath.AddArc(new Rectangle(rect.Right - curveSize, rect.Top, curveSize, curveSize), -90, 90);
}
if (Tabs.IndexOf(tab) != EndDisplayingTab &&
(Tabs.IndexOf(tab) != Tabs.Count - 1 && Tabs[Tabs.IndexOf(tab) + 1].Content == DockPane.ActiveContent)
&& !full)
{
if (RightToLeft == RightToLeft.Yes)
{
GraphicsPath.AddLine(rect.Left, rect.Top + curveSize / 2, rect.Left, rect.Top + rect.Height / 2);
GraphicsPath.AddLine(rect.Left, rect.Top + rect.Height / 2, rect.Left + rect.Height / 2, rect.Bottom);
}
else
{
GraphicsPath.AddLine(rect.Right, rect.Top + curveSize / 2, rect.Right, rect.Top + rect.Height / 2);
GraphicsPath.AddLine(rect.Right, rect.Top + rect.Height / 2, rect.Right - rect.Height / 2, rect.Bottom);
}
}
else
{
if (RightToLeft == RightToLeft.Yes)
GraphicsPath.AddLine(rect.Left, rect.Top + curveSize / 2, rect.Left, rect.Bottom);
else
GraphicsPath.AddLine(rect.Right, rect.Top + curveSize / 2, rect.Right, rect.Bottom);
}
return GraphicsPath;
}
private void DrawTab_ToolWindow(Graphics g, TabVS2005 tab, Rectangle rect)
{
Rectangle rectIcon = new Rectangle(
rect.X + ToolWindowImageGapLeft,
rect.Y + rect.Height - 1 - ToolWindowImageGapBottom - ToolWindowImageHeight,
ToolWindowImageWidth, ToolWindowImageHeight);
Rectangle rectText = rectIcon;
rectText.X += rectIcon.Width + ToolWindowImageGapRight;
rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft -
ToolWindowImageGapRight - ToolWindowTextGapRight;
Rectangle rectTab = DrawHelper.RtlTransform(this, rect);
rectText = DrawHelper.RtlTransform(this, rectText);
rectIcon = DrawHelper.RtlTransform(this, rectIcon);
GraphicsPath path = GetTabOutline(tab, true, false);
if (DockPane.ActiveContent == tab.Content)
{
g.FillPath(BrushToolWindowActiveBackground, path);
g.DrawPath(PenToolWindowTabBorder, path);
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, Font, rectText, ColorToolWindowActiveText, ToolWindowTextFormat);
}
else
{
if (Tabs.IndexOf(DockPane.ActiveContent) != Tabs.IndexOf(tab) + 1)
{
Point pt1 = new Point(rect.Right, rect.Top + ToolWindowTabSeperatorGapTop);
Point pt2 = new Point(rect.Right, rect.Bottom - ToolWindowTabSeperatorGapBottom);
g.DrawLine(PenToolWindowTabBorder, DrawHelper.RtlTransform(this, pt1), DrawHelper.RtlTransform(this, pt2));
}
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, Font, rectText, ColorToolWindowInactiveText, ToolWindowTextFormat);
}
if (rectTab.Contains(rectIcon))
g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon);
}
private void DrawTab_Document(Graphics g, TabVS2005 tab, Rectangle rect)
{
if (tab.TabWidth == 0)
return;
Rectangle rectIcon = new Rectangle(
rect.X + DocumentIconGapLeft,
rect.Y + rect.Height - 1 - DocumentIconGapBottom - DocumentIconHeight,
DocumentIconWidth, DocumentIconHeight);
Rectangle rectText = rectIcon;
if (DockPane.DockPanel.ShowDocumentIcon)
{
rectText.X += rectIcon.Width + DocumentIconGapRight;
rectText.Y = rect.Y;
rectText.Width = rect.Width - rectIcon.Width - DocumentIconGapLeft -
DocumentIconGapRight - DocumentTextGapRight;
rectText.Height = rect.Height;
}
else
rectText.Width = rect.Width - DocumentIconGapLeft - DocumentTextGapRight;
Rectangle rectTab = DrawHelper.RtlTransform(this, rect);
rectText = DrawHelper.RtlTransform(this, rectText);
rectIcon = DrawHelper.RtlTransform(this, rectIcon);
GraphicsPath path = GetTabOutline(tab, true, false);
if (DockPane.ActiveContent == tab.Content)
{
g.FillPath(BrushDocumentActiveBackground, path);
g.DrawPath(PenDocumentTabActiveBorder, path);
if (DockPane.IsActiveDocumentPane)
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, BoldFont, rectText, ColorDocumentActiveText, DocumentTextFormat);
else
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, Font, rectText, ColorDocumentActiveText, DocumentTextFormat);
}
else
{
g.FillPath(BrushDocumentInactiveBackground, path);
g.DrawPath(PenDocumentTabInactiveBorder, path);
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, Font, rectText, ColorDocumentInactiveText, DocumentTextFormat);
}
if (rectTab.Contains(rectIcon) && DockPane.DockPanel.ShowDocumentIcon)
g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon);
}
private Rectangle TabStripRectangle
{
get
{
if (Appearance == DockPane.AppearanceStyle.Document)
return TabStripRectangle_Document;
else
return TabStripRectangle_ToolWindow;
}
}
private Rectangle TabStripRectangle_ToolWindow
{
get
{
Rectangle rect = ClientRectangle;
return new Rectangle(rect.X, rect.Top + ToolWindowStripGapTop, rect.Width, rect.Height - ToolWindowStripGapTop - ToolWindowStripGapBottom);
}
}
private Rectangle TabStripRectangle_Document
{
get
{
Rectangle rect = ClientRectangle;
return new Rectangle(rect.X, rect.Top + DocumentStripGapTop, rect.Width, rect.Height - DocumentStripGapTop - ToolWindowStripGapBottom);
}
}
private Rectangle TabsRectangle
{
get
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return TabStripRectangle;
Rectangle rectWindow = TabStripRectangle;
int x = rectWindow.X;
int y = rectWindow.Y;
int width = rectWindow.Width;
int height = rectWindow.Height;
x += DocumentTabGapLeft;
width -= DocumentTabGapLeft +
DocumentTabGapRight +
DocumentButtonGapRight +
ButtonClose.Width +
ButtonWindowList.Width +
2 * DocumentButtonGapBetween;
return new Rectangle(x, y, width, height);
}
}
private ContextMenuStrip m_selectMenu;
private ContextMenuStrip SelectMenu
{
get { return m_selectMenu; }
}
private void WindowList_Click(object sender, EventArgs e)
{
int x = 0;
int y = ButtonWindowList.Location.Y + ButtonWindowList.Height;
SelectMenu.Items.Clear();
foreach (TabVS2005 tab in Tabs)
{
IDockContent content = tab.Content;
ToolStripItem item = SelectMenu.Items.Add(content.DockHandler.TabText, content.DockHandler.Icon.ToBitmap());
item.Tag = tab.Content;
item.Click += new EventHandler(ContextMenuItem_Click);
}
SelectMenu.Show(ButtonWindowList, x, y);
}
private void ContextMenuItem_Click(object sender, EventArgs e)
{
ToolStripMenuItem item = sender as ToolStripMenuItem;
if (item != null)
{
IDockContent content = (IDockContent)item.Tag;
DockPane.ActiveContent = content;
}
}
private void SetInertButtons()
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
{
if (m_buttonClose != null)
m_buttonClose.Left = -m_buttonClose.Width;
if (m_buttonWindowList != null)
m_buttonWindowList.Left = -m_buttonWindowList.Width;
}
else
{
bool showCloseButton = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButton;
ButtonClose.Enabled = showCloseButton;
ButtonClose.RefreshChanges();
ButtonWindowList.RefreshChanges();
}
}
protected override void OnLayout(LayoutEventArgs levent)
{
if (Appearance != DockPane.AppearanceStyle.Document)
{
base.OnLayout(levent);
return;
}
Rectangle rectTabStrip = TabStripRectangle;
// Set position and size of the buttons
int buttonWidth = ButtonClose.Image.Width;
int buttonHeight = ButtonClose.Image.Height;
int height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom;
if (buttonHeight < height)
{
buttonWidth = buttonWidth * (height / buttonHeight);
buttonHeight = height;
}
Size buttonSize = new Size(buttonWidth, buttonHeight);
int x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft
- DocumentButtonGapRight - buttonWidth;
int y = rectTabStrip.Y + DocumentButtonGapTop;
Point point = new Point(x, y);
ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize));
point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0);
ButtonWindowList.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize));
OnRefreshChanges();
base.OnLayout (levent);
}
private void Close_Click(object sender, EventArgs e)
{
DockPane.CloseActiveContent();
}
protected internal override int HitTest(Point ptMouse)
{
Rectangle rectTabStrip = TabsRectangle;
if (!TabsRectangle.Contains(ptMouse))
return -1;
foreach (Tab tab in Tabs)
{
try
{
GraphicsPath path = GetTabOutline(tab, true, false);
if (path.IsVisible(ptMouse))
return Tabs.IndexOf(tab);
}
catch { return -1; }
}
return -1;
}
protected override void OnMouseHover(EventArgs e)
{
int index = HitTest(PointToClient(Control.MousePosition));
string toolTip = string.Empty;
base.OnMouseHover(e);
if (index != -1)
{
TabVS2005 tab = Tabs[index] as TabVS2005;
if (!String.IsNullOrEmpty(tab.Content.DockHandler.ToolTipText))
toolTip = tab.Content.DockHandler.ToolTipText;
else if (tab.MaxWidth > tab.TabWidth)
toolTip = tab.Content.DockHandler.TabText;
}
if (m_toolTip.GetToolTip(this) != toolTip)
{
m_toolTip.Active = false;
m_toolTip.SetToolTip(this, toolTip);
m_toolTip.Active = true;
}
// requires further tracking of mouse hover behavior,
ResetMouseEventArgs();
}
protected override void OnRightToLeftChanged(EventArgs e)
{
base.OnRightToLeftChanged(e);
PerformLayout();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.Collections.Immutable
{
/// <content>
/// Contains the inner <see cref="ImmutableSortedDictionary{TKey, TValue}.Builder"/> class.
/// </content>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
public sealed partial class ImmutableSortedDictionary<TKey, TValue>
{
/// <summary>
/// A sorted dictionary that mutates with little or no memory allocations,
/// can produce and/or build on immutable sorted dictionary instances very efficiently.
/// </summary>
/// <remarks>
/// <para>
/// This class allows multiple combinations of changes to be made to a set with equal efficiency.
/// </para>
/// <para>
/// Instance members of this class are <em>not</em> thread-safe.
/// </para>
/// </remarks>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Ignored")]
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableSortedDictionaryBuilderDebuggerProxy<,>))]
public sealed class Builder : IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue>, IDictionary
{
/// <summary>
/// The binary tree used to store the contents of the map. Contents are typically not entirely frozen.
/// </summary>
private Node _root = Node.EmptyNode;
/// <summary>
/// The key comparer.
/// </summary>
private IComparer<TKey> _keyComparer = Comparer<TKey>.Default;
/// <summary>
/// The value comparer.
/// </summary>
private IEqualityComparer<TValue> _valueComparer = EqualityComparer<TValue>.Default;
/// <summary>
/// The number of entries in the map.
/// </summary>
private int _count;
/// <summary>
/// Caches an immutable instance that represents the current state of the collection.
/// </summary>
/// <value>Null if no immutable view has been created for the current version.</value>
private ImmutableSortedDictionary<TKey, TValue> _immutable;
/// <summary>
/// A number that increments every time the builder changes its contents.
/// </summary>
private int _version;
/// <summary>
/// The object callers may use to synchronize access to this collection.
/// </summary>
private object _syncRoot;
/// <summary>
/// Initializes a new instance of the <see cref="Builder"/> class.
/// </summary>
/// <param name="map">A map to act as the basis for a new map.</param>
internal Builder(ImmutableSortedDictionary<TKey, TValue> map)
{
Requires.NotNull(map, "map");
_root = map._root;
_keyComparer = map.KeyComparer;
_valueComparer = map.ValueComparer;
_count = map.Count;
_immutable = map;
}
#region IDictionary<TKey, TValue> Properties and Indexer
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get { return this.Root.Keys.ToArray(this.Count); }
}
/// <summary>
/// See <see cref="IReadOnlyDictionary{TKey, TValue}"/>
/// </summary>
public IEnumerable<TKey> Keys
{
get { return this.Root.Keys; }
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get { return this.Root.Values.ToArray(this.Count); }
}
/// <summary>
/// See <see cref="IReadOnlyDictionary{TKey, TValue}"/>
/// </summary>
public IEnumerable<TValue> Values
{
get { return this.Root.Values; }
}
/// <summary>
/// Gets the number of elements in this map.
/// </summary>
public int Count
{
get { return _count; }
}
/// <summary>
/// Gets a value indicating whether this instance is read-only.
/// </summary>
/// <value>Always <c>false</c>.</value>
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return false; }
}
#endregion
/// <summary>
/// Gets the current version of the contents of this builder.
/// </summary>
internal int Version
{
get { return _version; }
}
/// <summary>
/// Gets or sets the root node that represents the data in this collection.
/// </summary>
private Node Root
{
get
{
return _root;
}
set
{
// We *always* increment the version number because some mutations
// may not create a new value of root, although the existing root
// instance may have mutated.
_version++;
if (_root != value)
{
_root = value;
// Clear any cached value for the immutable view since it is now invalidated.
_immutable = null;
}
}
}
#region IDictionary<TKey, TValue> Indexer
/// <summary>
/// Gets or sets the value for a given key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>The value associated with the given key.</returns>
public TValue this[TKey key]
{
get
{
TValue value;
if (this.TryGetValue(key, out value))
{
return value;
}
throw new KeyNotFoundException();
}
set
{
bool replacedExistingValue, mutated;
this.Root = _root.SetItem(key, value, _keyComparer, _valueComparer, out replacedExistingValue, out mutated);
if (mutated && !replacedExistingValue)
{
_count++;
}
}
}
#endregion
#region IDictionary Properties
/// <summary>
/// Gets a value indicating whether the <see cref="IDictionary"/> object has a fixed size.
/// </summary>
/// <returns>true if the <see cref="IDictionary"/> object has a fixed size; otherwise, false.</returns>
bool IDictionary.IsFixedSize
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only.
/// </summary>
/// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false.
/// </returns>
bool IDictionary.IsReadOnly
{
get { return false; }
}
/// <summary>
/// Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <returns>
/// An <see cref="ICollection{T}"/> containing the keys of the object that implements <see cref="IDictionary{TKey, TValue}"/>.
/// </returns>
ICollection IDictionary.Keys
{
get { return this.Keys.ToArray(this.Count); }
}
/// <summary>
/// Gets an <see cref="ICollection{T}"/> containing the values in the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <returns>
/// An <see cref="ICollection{T}"/> containing the values in the object that implements <see cref="IDictionary{TKey, TValue}"/>.
/// </returns>
ICollection IDictionary.Values
{
get { return this.Values.ToArray(this.Count); }
}
#endregion
#region ICollection Properties
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>.
/// </summary>
/// <returns>An object that can be used to synchronize access to the <see cref="ICollection"/>.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="ICollection"/> is synchronized (thread safe).
/// </summary>
/// <returns>true if access to the <see cref="ICollection"/> is synchronized (thread safe); otherwise, false.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
bool ICollection.IsSynchronized
{
get { return false; }
}
/// <summary>
/// Gets or sets the key comparer.
/// </summary>
/// <value>
/// The key comparer.
/// </value>
public IComparer<TKey> KeyComparer
{
get
{
return _keyComparer;
}
set
{
Requires.NotNull(value, "value");
if (value != _keyComparer)
{
var newRoot = Node.EmptyNode;
int count = 0;
foreach (var item in this)
{
bool mutated;
newRoot = newRoot.Add(item.Key, item.Value, value, _valueComparer, out mutated);
if (mutated)
{
count++;
}
}
_keyComparer = value;
this.Root = newRoot;
_count = count;
}
}
}
/// <summary>
/// Gets or sets the value comparer.
/// </summary>
/// <value>
/// The value comparer.
/// </value>
public IEqualityComparer<TValue> ValueComparer
{
get
{
return _valueComparer;
}
set
{
Requires.NotNull(value, "value");
if (value != _valueComparer)
{
// When the key comparer is the same but the value comparer is different, we don't need a whole new tree
// because the structure of the tree does not depend on the value comparer.
// We just need a new root node to store the new value comparer.
_valueComparer = value;
_immutable = null; // invalidate cached immutable
}
}
}
#endregion
#region IDictionary Methods
/// <summary>
/// Adds an element with the provided key and value to the <see cref="IDictionary"/> object.
/// </summary>
/// <param name="key">The <see cref="object"/> to use as the key of the element to add.</param>
/// <param name="value">The <see cref="object"/> to use as the value of the element to add.</param>
void IDictionary.Add(object key, object value)
{
this.Add((TKey)key, (TValue)value);
}
/// <summary>
/// Determines whether the <see cref="IDictionary"/> object contains an element with the specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="IDictionary"/> object.</param>
/// <returns>
/// true if the <see cref="IDictionary"/> contains an element with the key; otherwise, false.
/// </returns>
bool IDictionary.Contains(object key)
{
return this.ContainsKey((TKey)key);
}
/// <summary>
/// Returns an <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object.
/// </summary>
/// <returns>
/// An <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object.
/// </returns>
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new DictionaryEnumerator<TKey, TValue>(this.GetEnumerator());
}
/// <summary>
/// Removes the element with the specified key from the <see cref="IDictionary"/> object.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
void IDictionary.Remove(object key)
{
this.Remove((TKey)key);
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
object IDictionary.this[object key]
{
get { return this[(TKey)key]; }
set { this[(TKey)key] = (TValue)value; }
}
#endregion
#region ICollection methods
/// <summary>
/// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
void ICollection.CopyTo(Array array, int index)
{
this.Root.CopyTo(array, index, this.Count);
}
#endregion
#region IDictionary<TKey, TValue> Methods
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public void Add(TKey key, TValue value)
{
bool mutated;
this.Root = this.Root.Add(key, value, _keyComparer, _valueComparer, out mutated);
if (mutated)
{
_count++;
}
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public bool ContainsKey(TKey key)
{
return this.Root.ContainsKey(key, _keyComparer);
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public bool Remove(TKey key)
{
bool mutated;
this.Root = this.Root.Remove(key, _keyComparer, out mutated);
if (mutated)
{
_count--;
}
return mutated;
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public bool TryGetValue(TKey key, out TValue value)
{
return this.Root.TryGetValue(key, _keyComparer, out value);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public bool TryGetKey(TKey equalKey, out TKey actualKey)
{
Requires.NotNullAllowStructs(equalKey, "equalKey");
return this.Root.TryGetKey(equalKey, _keyComparer, out actualKey);
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public void Add(KeyValuePair<TKey, TValue> item)
{
this.Add(item.Key, item.Value);
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public void Clear()
{
this.Root = ImmutableSortedDictionary<TKey, TValue>.Node.EmptyNode;
_count = 0;
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return this.Root.Contains(item, _keyComparer, _valueComparer);
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
this.Root.CopyTo(array, arrayIndex, this.Count);
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public bool Remove(KeyValuePair<TKey, TValue> item)
{
if (this.Contains(item))
{
return this.Remove(item.Key);
}
return false;
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public ImmutableSortedDictionary<TKey, TValue>.Enumerator GetEnumerator()
{
return this.Root.GetEnumerator(this);
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region Public methods
/// <summary>
/// Determines whether the <see cref="ImmutableSortedDictionary{TKey, TValue}"/>
/// contains an element with the specified value.
/// </summary>
/// <param name="value">
/// The value to locate in the <see cref="ImmutableSortedDictionary{TKey, TValue}"/>.
/// The value can be null for reference types.
/// </param>
/// <returns>
/// true if the <see cref="ImmutableSortedDictionary{TKey, TValue}"/> contains
/// an element with the specified value; otherwise, false.
/// </returns>
[Pure]
public bool ContainsValue(TValue value)
{
return _root.ContainsValue(value, _valueComparer);
}
/// <summary>
/// Removes any entries from the dictionaries with keys that match those found in the specified sequence.
/// </summary>
/// <param name="items">The keys for entries to remove from the dictionary.</param>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public void AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
Requires.NotNull(items, "items");
foreach (var pair in items)
{
this.Add(pair);
}
}
/// <summary>
/// Removes any entries from the dictionaries with keys that match those found in the specified sequence.
/// </summary>
/// <param name="keys">The keys for entries to remove from the dictionary.</param>
public void RemoveRange(IEnumerable<TKey> keys)
{
Requires.NotNull(keys, "keys");
foreach (var key in keys)
{
this.Remove(key);
}
}
/// <summary>
/// Gets the value for a given key if a matching key exists in the dictionary.
/// </summary>
/// <param name="key">The key to search for.</param>
/// <returns>The value for the key, or the default value for type <typeparamref name="TValue"/> if no matching key was found.</returns>
[Pure]
public TValue GetValueOrDefault(TKey key)
{
return this.GetValueOrDefault(key, default(TValue));
}
/// <summary>
/// Gets the value for a given key if a matching key exists in the dictionary.
/// </summary>
/// <param name="key">The key to search for.</param>
/// <param name="defaultValue">The default value to return if no matching key is found in the dictionary.</param>
/// <returns>
/// The value for the key, or <paramref name="defaultValue"/> if no matching key was found.
/// </returns>
[Pure]
public TValue GetValueOrDefault(TKey key, TValue defaultValue)
{
Requires.NotNullAllowStructs(key, "key");
TValue value;
if (this.TryGetValue(key, out value))
{
return value;
}
return defaultValue;
}
/// <summary>
/// Creates an immutable sorted dictionary based on the contents of this instance.
/// </summary>
/// <returns>An immutable map.</returns>
/// <remarks>
/// This method is an O(n) operation, and approaches O(1) time as the number of
/// actual mutations to the set since the last call to this method approaches 0.
/// </remarks>
public ImmutableSortedDictionary<TKey, TValue> ToImmutable()
{
// Creating an instance of ImmutableSortedMap<T> with our root node automatically freezes our tree,
// ensuring that the returned instance is immutable. Any further mutations made to this builder
// will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked.
if (_immutable == null)
{
_immutable = Wrap(this.Root, _count, _keyComparer, _valueComparer);
}
return _immutable;
}
#endregion
}
}
/// <summary>
/// A simple view of the immutable collection that the debugger can show to the developer.
/// </summary>
internal class ImmutableSortedDictionaryBuilderDebuggerProxy<TKey, TValue>
{
/// <summary>
/// The collection to be enumerated.
/// </summary>
private readonly ImmutableSortedDictionary<TKey, TValue>.Builder _map;
/// <summary>
/// The simple view of the collection.
/// </summary>
private KeyValuePair<TKey, TValue>[] _contents;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSortedDictionaryBuilderDebuggerProxy{TKey, TValue}"/> class.
/// </summary>
/// <param name="map">The collection to display in the debugger</param>
public ImmutableSortedDictionaryBuilderDebuggerProxy(ImmutableSortedDictionary<TKey, TValue>.Builder map)
{
Requires.NotNull(map, "map");
_map = map;
}
/// <summary>
/// Gets a simple debugger-viewable collection.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public KeyValuePair<TKey, TValue>[] Contents
{
get
{
if (_contents == null)
{
_contents = _map.ToArray(_map.Count);
}
return _contents;
}
}
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections;
namespace log4net.Core
{
/// <summary>
/// A strongly-typed collection of <see cref="Level"/> objects.
/// </summary>
/// <author>Nicko Cadell</author>
public class LevelCollection : ICollection, IList, IEnumerable, ICloneable
{
#region Interfaces
/// <summary>
/// Supports type-safe iteration over a <see cref="LevelCollection"/>.
/// </summary>
public interface ILevelCollectionEnumerator
{
/// <summary>
/// Gets the current element in the collection.
/// </summary>
Level Current { get; }
/// <summary>
/// Advances the enumerator to the next element in the collection.
/// </summary>
/// <returns>
/// <c>true</c> if the enumerator was successfully advanced to the next element;
/// <c>false</c> if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
bool MoveNext();
/// <summary>
/// Sets the enumerator to its initial position, before the first element in the collection.
/// </summary>
void Reset();
}
#endregion
private const int DEFAULT_CAPACITY = 16;
#region Implementation (data)
private Level[] m_array;
private int m_count = 0;
private int m_version = 0;
#endregion
#region Static Wrappers
/// <summary>
/// Creates a read-only wrapper for a <c>LevelCollection</c> instance.
/// </summary>
/// <param name="list">list to create a readonly wrapper arround</param>
/// <returns>
/// A <c>LevelCollection</c> wrapper that is read-only.
/// </returns>
public static LevelCollection ReadOnly(LevelCollection list)
{
if(list==null) throw new ArgumentNullException("list");
return new ReadOnlyLevelCollection(list);
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <c>LevelCollection</c> class
/// that is empty and has the default initial capacity.
/// </summary>
public LevelCollection()
{
m_array = new Level[DEFAULT_CAPACITY];
}
/// <summary>
/// Initializes a new instance of the <c>LevelCollection</c> class
/// that has the specified initial capacity.
/// </summary>
/// <param name="capacity">
/// The number of elements that the new <c>LevelCollection</c> is initially capable of storing.
/// </param>
public LevelCollection(int capacity)
{
m_array = new Level[capacity];
}
/// <summary>
/// Initializes a new instance of the <c>LevelCollection</c> class
/// that contains elements copied from the specified <c>LevelCollection</c>.
/// </summary>
/// <param name="c">The <c>LevelCollection</c> whose elements are copied to the new collection.</param>
public LevelCollection(LevelCollection c)
{
m_array = new Level[c.Count];
AddRange(c);
}
/// <summary>
/// Initializes a new instance of the <c>LevelCollection</c> class
/// that contains elements copied from the specified <see cref="Level"/> array.
/// </summary>
/// <param name="a">The <see cref="Level"/> array whose elements are copied to the new list.</param>
public LevelCollection(Level[] a)
{
m_array = new Level[a.Length];
AddRange(a);
}
/// <summary>
/// Initializes a new instance of the <c>LevelCollection</c> class
/// that contains elements copied from the specified <see cref="Level"/> collection.
/// </summary>
/// <param name="col">The <see cref="Level"/> collection whose elements are copied to the new list.</param>
public LevelCollection(ICollection col)
{
m_array = new Level[col.Count];
AddRange(col);
}
/// <summary>
/// Type visible only to our subclasses
/// Used to access protected constructor
/// </summary>
protected internal enum Tag
{
/// <summary>
/// A value
/// </summary>
Default
}
/// <summary>
/// Allow subclasses to avoid our default constructors
/// </summary>
/// <param name="tag"></param>
protected internal LevelCollection(Tag tag)
{
m_array = null;
}
#endregion
#region Operations (type-safe ICollection)
/// <summary>
/// Gets the number of elements actually contained in the <c>LevelCollection</c>.
/// </summary>
public virtual int Count
{
get { return m_count; }
}
/// <summary>
/// Copies the entire <c>LevelCollection</c> to a one-dimensional
/// <see cref="Level"/> array.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Level"/> array to copy to.</param>
public virtual void CopyTo(Level[] array)
{
this.CopyTo(array, 0);
}
/// <summary>
/// Copies the entire <c>LevelCollection</c> to a one-dimensional
/// <see cref="Level"/> array, starting at the specified index of the target array.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Level"/> array to copy to.</param>
/// <param name="start">The zero-based index in <paramref name="array"/> at which copying begins.</param>
public virtual void CopyTo(Level[] array, int start)
{
if (m_count > array.GetUpperBound(0) + 1 - start)
{
throw new System.ArgumentException("Destination array was not long enough.");
}
Array.Copy(m_array, 0, array, start, m_count);
}
/// <summary>
/// Gets a value indicating whether access to the collection is synchronized (thread-safe).
/// </summary>
/// <value>true if access to the ICollection is synchronized (thread-safe); otherwise, false.</value>
public virtual bool IsSynchronized
{
get { return m_array.IsSynchronized; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the collection.
/// </summary>
public virtual object SyncRoot
{
get { return m_array.SyncRoot; }
}
#endregion
#region Operations (type-safe IList)
/// <summary>
/// Gets or sets the <see cref="Level"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para>
/// </exception>
public virtual Level this[int index]
{
get
{
ValidateIndex(index); // throws
return m_array[index];
}
set
{
ValidateIndex(index); // throws
++m_version;
m_array[index] = value;
}
}
/// <summary>
/// Adds a <see cref="Level"/> to the end of the <c>LevelCollection</c>.
/// </summary>
/// <param name="item">The <see cref="Level"/> to be added to the end of the <c>LevelCollection</c>.</param>
/// <returns>The index at which the value has been added.</returns>
public virtual int Add(Level item)
{
if (m_count == m_array.Length)
{
EnsureCapacity(m_count + 1);
}
m_array[m_count] = item;
m_version++;
return m_count++;
}
/// <summary>
/// Removes all elements from the <c>LevelCollection</c>.
/// </summary>
public virtual void Clear()
{
++m_version;
m_array = new Level[DEFAULT_CAPACITY];
m_count = 0;
}
/// <summary>
/// Creates a shallow copy of the <see cref="LevelCollection"/>.
/// </summary>
/// <returns>A new <see cref="LevelCollection"/> with a shallow copy of the collection data.</returns>
public virtual object Clone()
{
LevelCollection newCol = new LevelCollection(m_count);
Array.Copy(m_array, 0, newCol.m_array, 0, m_count);
newCol.m_count = m_count;
newCol.m_version = m_version;
return newCol;
}
/// <summary>
/// Determines whether a given <see cref="Level"/> is in the <c>LevelCollection</c>.
/// </summary>
/// <param name="item">The <see cref="Level"/> to check for.</param>
/// <returns><c>true</c> if <paramref name="item"/> is found in the <c>LevelCollection</c>; otherwise, <c>false</c>.</returns>
public virtual bool Contains(Level item)
{
for (int i=0; i != m_count; ++i)
{
if (m_array[i].Equals(item))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns the zero-based index of the first occurrence of a <see cref="Level"/>
/// in the <c>LevelCollection</c>.
/// </summary>
/// <param name="item">The <see cref="Level"/> to locate in the <c>LevelCollection</c>.</param>
/// <returns>
/// The zero-based index of the first occurrence of <paramref name="item"/>
/// in the entire <c>LevelCollection</c>, if found; otherwise, -1.
/// </returns>
public virtual int IndexOf(Level item)
{
for (int i=0; i != m_count; ++i)
{
if (m_array[i].Equals(item))
{
return i;
}
}
return -1;
}
/// <summary>
/// Inserts an element into the <c>LevelCollection</c> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param>
/// <param name="item">The <see cref="Level"/> to insert.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para>
/// </exception>
public virtual void Insert(int index, Level item)
{
ValidateIndex(index, true); // throws
if (m_count == m_array.Length)
{
EnsureCapacity(m_count + 1);
}
if (index < m_count)
{
Array.Copy(m_array, index, m_array, index + 1, m_count - index);
}
m_array[index] = item;
m_count++;
m_version++;
}
/// <summary>
/// Removes the first occurrence of a specific <see cref="Level"/> from the <c>LevelCollection</c>.
/// </summary>
/// <param name="item">The <see cref="Level"/> to remove from the <c>LevelCollection</c>.</param>
/// <exception cref="ArgumentException">
/// The specified <see cref="Level"/> was not found in the <c>LevelCollection</c>.
/// </exception>
public virtual void Remove(Level item)
{
int i = IndexOf(item);
if (i < 0)
{
throw new System.ArgumentException("Cannot remove the specified item because it was not found in the specified Collection.");
}
++m_version;
RemoveAt(i);
}
/// <summary>
/// Removes the element at the specified index of the <c>LevelCollection</c>.
/// </summary>
/// <param name="index">The zero-based index of the element to remove.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para>
/// </exception>
public virtual void RemoveAt(int index)
{
ValidateIndex(index); // throws
m_count--;
if (index < m_count)
{
Array.Copy(m_array, index + 1, m_array, index, m_count - index);
}
// We can't set the deleted entry equal to null, because it might be a value type.
// Instead, we'll create an empty single-element array of the right type and copy it
// over the entry we want to erase.
Level[] temp = new Level[1];
Array.Copy(temp, 0, m_array, m_count, 1);
m_version++;
}
/// <summary>
/// Gets a value indicating whether the collection has a fixed size.
/// </summary>
/// <value>true if the collection has a fixed size; otherwise, false. The default is false</value>
public virtual bool IsFixedSize
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the IList is read-only.
/// </summary>
/// <value>true if the collection is read-only; otherwise, false. The default is false</value>
public virtual bool IsReadOnly
{
get { return false; }
}
#endregion
#region Operations (type-safe IEnumerable)
/// <summary>
/// Returns an enumerator that can iterate through the <c>LevelCollection</c>.
/// </summary>
/// <returns>An <see cref="Enumerator"/> for the entire <c>LevelCollection</c>.</returns>
public virtual ILevelCollectionEnumerator GetEnumerator()
{
return new Enumerator(this);
}
#endregion
#region Public helpers (just to mimic some nice features of ArrayList)
/// <summary>
/// Gets or sets the number of elements the <c>LevelCollection</c> can contain.
/// </summary>
public virtual int Capacity
{
get
{
return m_array.Length;
}
set
{
if (value < m_count)
{
value = m_count;
}
if (value != m_array.Length)
{
if (value > 0)
{
Level[] temp = new Level[value];
Array.Copy(m_array, 0, temp, 0, m_count);
m_array = temp;
}
else
{
m_array = new Level[DEFAULT_CAPACITY];
}
}
}
}
/// <summary>
/// Adds the elements of another <c>LevelCollection</c> to the current <c>LevelCollection</c>.
/// </summary>
/// <param name="x">The <c>LevelCollection</c> whose elements should be added to the end of the current <c>LevelCollection</c>.</param>
/// <returns>The new <see cref="LevelCollection.Count"/> of the <c>LevelCollection</c>.</returns>
public virtual int AddRange(LevelCollection x)
{
if (m_count + x.Count >= m_array.Length)
{
EnsureCapacity(m_count + x.Count);
}
Array.Copy(x.m_array, 0, m_array, m_count, x.Count);
m_count += x.Count;
m_version++;
return m_count;
}
/// <summary>
/// Adds the elements of a <see cref="Level"/> array to the current <c>LevelCollection</c>.
/// </summary>
/// <param name="x">The <see cref="Level"/> array whose elements should be added to the end of the <c>LevelCollection</c>.</param>
/// <returns>The new <see cref="LevelCollection.Count"/> of the <c>LevelCollection</c>.</returns>
public virtual int AddRange(Level[] x)
{
if (m_count + x.Length >= m_array.Length)
{
EnsureCapacity(m_count + x.Length);
}
Array.Copy(x, 0, m_array, m_count, x.Length);
m_count += x.Length;
m_version++;
return m_count;
}
/// <summary>
/// Adds the elements of a <see cref="Level"/> collection to the current <c>LevelCollection</c>.
/// </summary>
/// <param name="col">The <see cref="Level"/> collection whose elements should be added to the end of the <c>LevelCollection</c>.</param>
/// <returns>The new <see cref="LevelCollection.Count"/> of the <c>LevelCollection</c>.</returns>
public virtual int AddRange(ICollection col)
{
if (m_count + col.Count >= m_array.Length)
{
EnsureCapacity(m_count + col.Count);
}
foreach(object item in col)
{
Add((Level)item);
}
return m_count;
}
/// <summary>
/// Sets the capacity to the actual number of elements.
/// </summary>
public virtual void TrimToSize()
{
this.Capacity = m_count;
}
#endregion
#region Implementation (helpers)
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="i"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="i"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para>
/// </exception>
private void ValidateIndex(int i)
{
ValidateIndex(i, false);
}
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="i"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="i"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para>
/// </exception>
private void ValidateIndex(int i, bool allowEqualEnd)
{
int max = (allowEqualEnd) ? (m_count) : (m_count-1);
if (i < 0 || i > max)
{
throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("i", (object)i, "Index was out of range. Must be non-negative and less than the size of the collection. [" + (object)i + "] Specified argument was out of the range of valid values.");
}
}
private void EnsureCapacity(int min)
{
int newCapacity = ((m_array.Length == 0) ? DEFAULT_CAPACITY : m_array.Length * 2);
if (newCapacity < min)
{
newCapacity = min;
}
this.Capacity = newCapacity;
}
#endregion
#region Implementation (ICollection)
void ICollection.CopyTo(Array array, int start)
{
Array.Copy(m_array, 0, array, start, m_count);
}
#endregion
#region Implementation (IList)
object IList.this[int i]
{
get { return (object)this[i]; }
set { this[i] = (Level)value; }
}
int IList.Add(object x)
{
return this.Add((Level)x);
}
bool IList.Contains(object x)
{
return this.Contains((Level)x);
}
int IList.IndexOf(object x)
{
return this.IndexOf((Level)x);
}
void IList.Insert(int pos, object x)
{
this.Insert(pos, (Level)x);
}
void IList.Remove(object x)
{
this.Remove((Level)x);
}
void IList.RemoveAt(int pos)
{
this.RemoveAt(pos);
}
#endregion
#region Implementation (IEnumerable)
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)(this.GetEnumerator());
}
#endregion
#region Nested enumerator class
/// <summary>
/// Supports simple iteration over a <see cref="LevelCollection"/>.
/// </summary>
private sealed class Enumerator : IEnumerator, ILevelCollectionEnumerator
{
#region Implementation (data)
private readonly LevelCollection m_collection;
private int m_index;
private int m_version;
#endregion
#region Construction
/// <summary>
/// Initializes a new instance of the <c>Enumerator</c> class.
/// </summary>
/// <param name="tc"></param>
internal Enumerator(LevelCollection tc)
{
m_collection = tc;
m_index = -1;
m_version = tc.m_version;
}
#endregion
#region Operations (type-safe IEnumerator)
/// <summary>
/// Gets the current element in the collection.
/// </summary>
public Level Current
{
get { return m_collection[m_index]; }
}
/// <summary>
/// Advances the enumerator to the next element in the collection.
/// </summary>
/// <returns>
/// <c>true</c> if the enumerator was successfully advanced to the next element;
/// <c>false</c> if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
public bool MoveNext()
{
if (m_version != m_collection.m_version)
{
throw new System.InvalidOperationException("Collection was modified; enumeration operation may not execute.");
}
++m_index;
return (m_index < m_collection.Count);
}
/// <summary>
/// Sets the enumerator to its initial position, before the first element in the collection.
/// </summary>
public void Reset()
{
m_index = -1;
}
#endregion
#region Implementation (IEnumerator)
object IEnumerator.Current
{
get { return this.Current; }
}
#endregion
}
#endregion
#region Nested Read Only Wrapper class
private sealed class ReadOnlyLevelCollection : LevelCollection
{
#region Implementation (data)
private readonly LevelCollection m_collection;
#endregion
#region Construction
internal ReadOnlyLevelCollection(LevelCollection list) : base(Tag.Default)
{
m_collection = list;
}
#endregion
#region Type-safe ICollection
public override void CopyTo(Level[] array)
{
m_collection.CopyTo(array);
}
public override void CopyTo(Level[] array, int start)
{
m_collection.CopyTo(array,start);
}
public override int Count
{
get { return m_collection.Count; }
}
public override bool IsSynchronized
{
get { return m_collection.IsSynchronized; }
}
public override object SyncRoot
{
get { return this.m_collection.SyncRoot; }
}
#endregion
#region Type-safe IList
public override Level this[int i]
{
get { return m_collection[i]; }
set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); }
}
public override int Add(Level x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override void Clear()
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override bool Contains(Level x)
{
return m_collection.Contains(x);
}
public override int IndexOf(Level x)
{
return m_collection.IndexOf(x);
}
public override void Insert(int pos, Level x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override void Remove(Level x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override void RemoveAt(int pos)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override bool IsFixedSize
{
get { return true; }
}
public override bool IsReadOnly
{
get { return true; }
}
#endregion
#region Type-safe IEnumerable
public override ILevelCollectionEnumerator GetEnumerator()
{
return m_collection.GetEnumerator();
}
#endregion
#region Public Helpers
// (just to mimic some nice features of ArrayList)
public override int Capacity
{
get { return m_collection.Capacity; }
set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); }
}
public override int AddRange(LevelCollection x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override int AddRange(Level[] x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
#endregion
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Linq;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Text;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.Xml;
using System.Security.Cryptography.X509Certificates;
using Xunit;
using Test.Cryptography;
namespace System.Security.Cryptography.Pkcs.Tests
{
public static class Pkcs9AttributeTests
{
[Fact]
public static void Pkcs9AttributeObjectNullaryCtor()
{
Pkcs9AttributeObject p = new Pkcs9AttributeObject();
Assert.Null(p.Oid);
Assert.Null(p.RawData);
}
[Fact]
public static void Pkcs9AttributeAsnEncodedDataCtorNullOid()
{
AsnEncodedData a = new AsnEncodedData(new byte[3]);
object ign;
Assert.Throws<ArgumentNullException>(() => ign = new Pkcs9AttributeObject(a));
}
[Fact]
public static void Pkcs9AttributeAsnEncodedDataCtorNullOidValue()
{
Oid oid = new Oid(Oids.Aes128);
oid.Value = null;
AsnEncodedData a = new AsnEncodedData(oid, new byte[3]);
object ign;
Assert.Throws<ArgumentNullException>(() => ign = new Pkcs9AttributeObject(a));
}
[Fact]
public static void Pkcs9AttributeAsnEncodedDataCtorEmptyOidValue()
{
Oid oid = new Oid(Oids.Aes128);
oid.Value = string.Empty;
AsnEncodedData a = new AsnEncodedData(oid, new byte[3]);
object ign;
AssertExtensions.Throws<ArgumentException>("oid.Value", () => ign = new Pkcs9AttributeObject(a));
}
[Fact]
public static void Pkcs9AttributeCopyFromNullAsn()
{
Pkcs9AttributeObject p = new Pkcs9AttributeObject();
Assert.Throws<ArgumentNullException>(() => p.CopyFrom(null));
}
[Fact]
public static void Pkcs9AttributeCopyFromAsnNotAPkcs9Attribute()
{
// Pkcs9AttributeObject.CopyFrom(AsnEncodedData) refuses to accept any AsnEncodedData that isn't a Pkcs9AttributeObject-derived class.
Pkcs9AttributeObject p = new Pkcs9AttributeObject();
byte[] rawData = "041e4d00790020004400650073006300720069007000740069006f006e000000".HexToByteArray();
AsnEncodedData a = new AsnEncodedData(Oids.DocumentName, rawData);
AssertExtensions.Throws<ArgumentException>(null, () => p.CopyFrom(a));
}
[Fact]
public static void DocumentDescriptionNullary()
{
Pkcs9DocumentDescription p = new Pkcs9DocumentDescription();
Assert.Null(p.RawData);
Assert.Null(p.DocumentDescription);
string oid = p.Oid.Value;
Assert.Equal(s_OidDocumentDescription, oid);
}
[Fact]
public static void DocumentDescriptionFromRawData()
{
byte[] rawData = "041e4d00790020004400650073006300720069007000740069006f006e000000".HexToByteArray();
Pkcs9DocumentDescription p = new Pkcs9DocumentDescription(rawData);
Assert.Equal(rawData, p.RawData);
string cookedData = p.DocumentDescription;
Assert.Equal("My Description", cookedData);
string oid = p.Oid.Value;
Assert.Equal(s_OidDocumentDescription, oid);
}
[Fact]
public static void DocumentDescriptionFromCookedData()
{
Pkcs9DocumentDescription p = new Pkcs9DocumentDescription("My Description");
string oid = p.Oid.Value;
Assert.Equal(s_OidDocumentDescription, oid);
Pkcs9DocumentDescription p2 = new Pkcs9DocumentDescription(p.RawData);
string cookedData = p2.DocumentDescription;
Assert.Equal("My Description", cookedData);
}
[Fact]
public static void DocumentDescriptionNullValue()
{
object ignore;
Assert.Throws<ArgumentNullException>(() => ignore = new Pkcs9DocumentDescription((string)null));
}
[Fact]
public static void DocumentNameNullary()
{
Pkcs9DocumentName p = new Pkcs9DocumentName();
Assert.Null(p.RawData);
Assert.Null(p.DocumentName);
string oid = p.Oid.Value;
Assert.Equal(s_OidDocumentName, oid);
}
[Fact]
public static void DocumentNameFromRawData()
{
byte[] rawData = "04104d00790020004e0061006d0065000000".HexToByteArray();
Pkcs9DocumentName p = new Pkcs9DocumentName(rawData);
Assert.Equal(rawData, p.RawData);
string cookedData = p.DocumentName;
Assert.Equal("My Name", cookedData);
string oid = p.Oid.Value;
Assert.Equal(s_OidDocumentName, oid);
}
[Fact]
public static void DocumentNameFromCookedData()
{
Pkcs9DocumentName p = new Pkcs9DocumentName("My Name");
string oid = p.Oid.Value;
Assert.Equal(s_OidDocumentName, oid);
Pkcs9DocumentName p2 = new Pkcs9DocumentName(p.RawData);
string cookedData = p2.DocumentName;
Assert.Equal("My Name", cookedData);
}
[Fact]
public static void DocumentNamenNullValue()
{
object ignore;
Assert.Throws<ArgumentNullException>(() => ignore = new Pkcs9DocumentName((string)null));
}
[Fact]
public static void SigningTimeNullary()
{
Pkcs9SigningTime p = new Pkcs9SigningTime();
// the default constructor initializes with DateTime.Now.
Assert.NotNull(p.RawData);
string oid = p.Oid.Value;
Assert.Equal(s_OidSigningTime, oid);
}
[Fact]
public static void SigningTimeFromRawData()
{
DateTime dateTime = new DateTime(2015, 4, 1);
byte[] rawData = "170d3135303430313030303030305a".HexToByteArray();
Pkcs9SigningTime p = new Pkcs9SigningTime(rawData);
Assert.Equal(rawData, p.RawData);
DateTime cookedData = p.SigningTime;
Assert.Equal(dateTime, cookedData);
string oid = p.Oid.Value;
Assert.Equal(s_OidSigningTime, oid);
}
[Fact]
public static void SigningTimeFromCookedData()
{
DateTime dateTime = new DateTime(2015, 4, 1);
Pkcs9SigningTime p = new Pkcs9SigningTime(dateTime);
string oid = p.Oid.Value;
Assert.Equal(s_OidSigningTime, oid);
Pkcs9SigningTime p2 = new Pkcs9SigningTime(p.RawData);
DateTime cookedData = p2.SigningTime;
Assert.Equal(dateTime, cookedData);
}
[Fact]
public static void ContentTypeNullary()
{
Pkcs9ContentType p = new Pkcs9ContentType();
Assert.Null(p.RawData);
Assert.Null(p.ContentType);
string oid = p.Oid.Value;
Assert.Equal(s_OidContentType, oid);
}
[Fact]
public static void ContentTypeFromRawData()
{
byte[] rawData = { ASN_TAG_OBJID, 0, 42, 0x9f, 0xa2, 0, 0x82, 0xf3, 0 };
rawData[1] = (byte)(rawData.Length - 2);
Pkcs9ContentType p = CreatePkcs9ContentType(rawData);
Assert.Equal(rawData, p.RawData);
string cookedData = p.ContentType.Value;
Assert.Equal("1.2.512256.47488", cookedData);
string oid = p.Oid.Value;
Assert.Equal(s_OidContentType, oid);
}
[Fact]
public static void ContentTypeFromCookedData()
{
string contentType = "1.3.8473.23.4773.23";
byte[] encodedContentType = "06072bc21917a52517".HexToByteArray();
Pkcs9ContentType p = new Pkcs9ContentType();
Pkcs9AttributeObject pkcs9AttributeObject = new Pkcs9AttributeObject(p.Oid, encodedContentType);
p.CopyFrom(pkcs9AttributeObject);
string cookedData = p.ContentType.Value;
Assert.Equal(contentType, cookedData);
string oid = p.Oid.Value;
Assert.Equal(s_OidContentType, oid);
}
[Fact]
public static void ContentTypeFromRawDataMinimal()
{
byte[] rawData = { ASN_TAG_OBJID, 0 };
rawData[1] = (byte)(rawData.Length - 2);
Pkcs9ContentType p = CreatePkcs9ContentType(rawData);
Assert.Equal(rawData, p.RawData);
string cookedData = p.ContentType.Value;
Assert.Equal("", cookedData);
string oid = p.Oid.Value;
Assert.Equal(s_OidContentType, oid);
}
[Fact]
public static void ContentTypeBadData()
{
Assert.ThrowsAny<CryptographicException>(() => CreatePkcs9ContentTypeAndExtractContentType(new byte[0])); // Too short
Assert.ThrowsAny<CryptographicException>(() => CreatePkcs9ContentTypeAndExtractContentType(new byte[1])); // Too short
Assert.ThrowsAny<CryptographicException>(() => CreatePkcs9ContentTypeAndExtractContentType(new byte[2])); // Does not start with ASN_TAG_OBJID.
Assert.ThrowsAny<CryptographicException>(() => CreatePkcs9ContentTypeAndExtractContentType(new byte[] { ASN_TAG_OBJID, 1 })); // Bad length byte.
}
[Fact]
public static void MessageDigestNullary()
{
Pkcs9MessageDigest p = new Pkcs9MessageDigest();
Assert.Null(p.RawData);
Assert.Null(p.MessageDigest);
string oid = p.Oid.Value;
Assert.Equal(s_OidMessageDigest, oid);
}
[Fact]
public static void MessageDigestFromRawData()
{
byte[] messageDigest = { 3, 45, 88, 128, 93 };
List<byte> encodedMessageDigestList = new List<byte>(messageDigest.Length + 2);
encodedMessageDigestList.Add(4);
encodedMessageDigestList.Add(checked((byte)(messageDigest.Length)));
encodedMessageDigestList.AddRange(messageDigest);
byte[] encodedMessageDigest = encodedMessageDigestList.ToArray();
Pkcs9MessageDigest p = new Pkcs9MessageDigest();
Pkcs9AttributeObject pAttribute = new Pkcs9AttributeObject(s_OidMessageDigest, encodedMessageDigest);
p.CopyFrom(pAttribute);
Assert.Equal<byte>(encodedMessageDigest, p.RawData);
Assert.Equal<byte>(messageDigest, p.MessageDigest);
string oid = p.Oid.Value;
Assert.Equal(s_OidMessageDigest, oid);
}
private static void CreatePkcs9ContentTypeAndExtractContentType(byte[] rawData)
{
Oid contentType = CreatePkcs9ContentType(rawData).ContentType;
}
private static Pkcs9ContentType CreatePkcs9ContentType(byte[] rawData)
{
Pkcs9ContentType pkcs9ContentType = new Pkcs9ContentType();
Pkcs9AttributeObject pkcs9AttributeObject = new Pkcs9AttributeObject(pkcs9ContentType.Oid, rawData);
pkcs9ContentType.CopyFrom(pkcs9AttributeObject);
return pkcs9ContentType;
}
private const byte ASN_TAG_OBJID = 0x06;
private const string s_OidDocumentDescription = "1.3.6.1.4.1.311.88.2.2";
private const string s_OidDocumentName = "1.3.6.1.4.1.311.88.2.1";
private const string s_OidSigningTime = "1.2.840.113549.1.9.5";
private const string s_OidContentType = "1.2.840.113549.1.9.3";
private const string s_OidMessageDigest = "1.2.840.113549.1.9.4";
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Rest.Generator.Ruby.Templates
{
#line 1 "ServiceClientTemplate.cshtml"
using Microsoft.Rest.Generator.Ruby
#line default
#line hidden
;
#line 2 "ServiceClientTemplate.cshtml"
using Microsoft.Rest.Generator.Ruby.Templates
#line default
#line hidden
;
#line 3 "ServiceClientTemplate.cshtml"
using Microsoft.Rest.Generator.Utilities
#line default
#line hidden
;
#line 4 "ServiceClientTemplate.cshtml"
using System.Linq
#line default
#line hidden
;
#line 5 "ServiceClientTemplate.cshtml"
using Microsoft.Rest.Generator.Ruby.TemplateModels
#line default
#line hidden
;
using System.Threading.Tasks;
public class ServiceClientTemplate : Microsoft.Rest.Generator.Template<Microsoft.Rest.Generator.Ruby.ServiceClientTemplateModel>
{
#line hidden
public ServiceClientTemplate()
{
}
#pragma warning disable 1998
public override async Task ExecuteAsync()
{
#line 7 "ServiceClientTemplate.cshtml"
Write(Header("# "));
#line default
#line hidden
WriteLiteral("\r\n");
#line 8 "ServiceClientTemplate.cshtml"
Write(EmptyLine);
#line default
#line hidden
WriteLiteral("\r\nmodule ");
#line 9 "ServiceClientTemplate.cshtml"
Write(Settings.Namespace);
#line default
#line hidden
WriteLiteral("\r\n #\r\n ");
#line 11 "ServiceClientTemplate.cshtml"
Write(WrapComment("# ", Model.Documentation));
#line default
#line hidden
WriteLiteral("\r\n #\r\n class ");
#line 13 "ServiceClientTemplate.cshtml"
Write(Model.Name);
#line default
#line hidden
WriteLiteral(" < ");
#line 13 "ServiceClientTemplate.cshtml"
Write(Model.BaseType);
#line default
#line hidden
WriteLiteral("\r\n # @return [String] the base URI of the service.\r\n attr_accessor :base_ur" +
"l\r\n");
#line 16 "ServiceClientTemplate.cshtml"
Write(EmptyLine);
#line default
#line hidden
WriteLiteral("\r\n\r\n");
#line 18 "ServiceClientTemplate.cshtml"
foreach (var property in Model.Properties)
{
#line default
#line hidden
WriteLiteral(" ");
#line 20 "ServiceClientTemplate.cshtml"
Write(WrapComment("# ", string.Format("@return {0}{1}", property.Type.GetYardDocumentation(), property.Documentation)));
#line default
#line hidden
WriteLiteral("\r\n ");
#line 21 "ServiceClientTemplate.cshtml"
Write(property.IsReadOnly ? "attr_reader" : "attr_accessor");
#line default
#line hidden
WriteLiteral(" :");
#line 21 "ServiceClientTemplate.cshtml"
Write(property.Name);
#line default
#line hidden
WriteLiteral("\r\n");
#line 22 "ServiceClientTemplate.cshtml"
#line default
#line hidden
#line 22 "ServiceClientTemplate.cshtml"
Write(EmptyLine);
#line default
#line hidden
#line 22 "ServiceClientTemplate.cshtml"
}
#line default
#line hidden
WriteLiteral("\r\n");
#line 25 "ServiceClientTemplate.cshtml"
foreach (var operation in Model.MethodGroups)
{
#line default
#line hidden
WriteLiteral(" ");
#line 27 "ServiceClientTemplate.cshtml"
Write(WrapComment("# ", string.Format("@return {0}", RubyCodeNamer.UnderscoreCase(operation))));
#line default
#line hidden
WriteLiteral("\r\n attr_reader :");
#line 28 "ServiceClientTemplate.cshtml"
Write(RubyCodeNamer.UnderscoreCase(operation));
#line default
#line hidden
WriteLiteral("\r\n");
#line 29 "ServiceClientTemplate.cshtml"
#line default
#line hidden
#line 29 "ServiceClientTemplate.cshtml"
Write(EmptyLine);
#line default
#line hidden
#line 29 "ServiceClientTemplate.cshtml"
}
#line default
#line hidden
WriteLiteral("\r\n");
#line 32 "ServiceClientTemplate.cshtml"
var parameters = Model.Properties.Where(p => p.IsRequired);
#line default
#line hidden
WriteLiteral("\r\n\r\n #\r\n # Creates and initializes a new instance of the ");
#line 35 "ServiceClientTemplate.cshtml"
Write(Model.Name);
#line default
#line hidden
WriteLiteral(" class.\r\n # @param base_url [String] base url for accessing current service.\r\n" +
"");
#line 37 "ServiceClientTemplate.cshtml"
#line default
#line hidden
#line 37 "ServiceClientTemplate.cshtml"
foreach (var param in parameters)
{
#line default
#line hidden
#line 39 "ServiceClientTemplate.cshtml"
Write(WrapComment("# ", string.Format("@param {0} {1}{2}", param.Name, param.Type.GetYardDocumentation(), param.Documentation)));
#line default
#line hidden
#line 39 "ServiceClientTemplate.cshtml"
#line default
#line hidden
WriteLiteral(" \r\n");
#line 41 "ServiceClientTemplate.cshtml"
}
#line default
#line hidden
WriteLiteral(" #\r\n def initialize(base_url = nil");
#line 43 "ServiceClientTemplate.cshtml"
Write(Model.RequiredContructorParametersWithSeparator);
#line default
#line hidden
WriteLiteral(")\r\n super()\r\n @base_url = base_url || \'");
#line 45 "ServiceClientTemplate.cshtml"
Write(Model.BaseUrl);
#line default
#line hidden
WriteLiteral("\'\r\n");
#line 46 "ServiceClientTemplate.cshtml"
#line default
#line hidden
#line 46 "ServiceClientTemplate.cshtml"
foreach (var operation in Model.MethodGroups)
{
#line default
#line hidden
WriteLiteral(" @");
#line 48 "ServiceClientTemplate.cshtml"
Write(RubyCodeNamer.UnderscoreCase(operation));
#line default
#line hidden
WriteLiteral(" = ");
#line 48 "ServiceClientTemplate.cshtml"
Write(operation);
#line default
#line hidden
WriteLiteral(".new(self)\r\n");
#line 49 "ServiceClientTemplate.cshtml"
}
#line default
#line hidden
WriteLiteral(" ");
#line 50 "ServiceClientTemplate.cshtml"
foreach (var param in parameters)
{
#line default
#line hidden
WriteLiteral(" fail ArgumentError, \'");
#line 52 "ServiceClientTemplate.cshtml"
Write(param.Name);
#line default
#line hidden
WriteLiteral(" is nil\' if ");
#line 52 "ServiceClientTemplate.cshtml"
Write(param.Name);
#line default
#line hidden
WriteLiteral(".nil?\r\n");
#line 53 "ServiceClientTemplate.cshtml"
}
#line default
#line hidden
WriteLiteral(" ");
#line 54 "ServiceClientTemplate.cshtml"
foreach (var param in parameters)
{
#line default
#line hidden
WriteLiteral(" @");
#line 56 "ServiceClientTemplate.cshtml"
Write(param.Name);
#line default
#line hidden
WriteLiteral(" = ");
#line 56 "ServiceClientTemplate.cshtml"
Write(param.Name);
#line default
#line hidden
WriteLiteral(";\r\n");
#line 57 "ServiceClientTemplate.cshtml"
}
#line default
#line hidden
WriteLiteral("\r\n end\r\n\r\n ");
#line 61 "ServiceClientTemplate.cshtml"
Write(EmptyLine);
#line default
#line hidden
WriteLiteral("\r\n");
#line 62 "ServiceClientTemplate.cshtml"
#line default
#line hidden
#line 62 "ServiceClientTemplate.cshtml"
foreach (var method in Model.MethodTemplateModels)
{
#line default
#line hidden
WriteLiteral(" ");
#line 64 "ServiceClientTemplate.cshtml"
Write(Include(new MethodTemplate(), method));
#line default
#line hidden
WriteLiteral("\r\n");
#line 65 "ServiceClientTemplate.cshtml"
#line default
#line hidden
#line 65 "ServiceClientTemplate.cshtml"
Write(EmptyLine);
#line default
#line hidden
#line 65 "ServiceClientTemplate.cshtml"
#line default
#line hidden
WriteLiteral(" \r\n");
#line 67 "ServiceClientTemplate.cshtml"
}
#line default
#line hidden
WriteLiteral(" end\r\nend\r\n");
}
#pragma warning restore 1998
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using SharpDX.Mathematics.Interop;
using System;
namespace SharpDX.Direct3D11
{
public partial class EffectScalarVariable
{
/// <summary>
/// Set a floating-point variable.
/// </summary>
/// <param name="value">A reference to the variable. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D10EffectScalarVariable::SetFloat([None] float Value)</unmanaged>
public void Set(float value)
{
SetFloat(value);
}
/// <summary>
/// Set an array of floating-point variables.
/// </summary>
/// <param name="dataRef">A reference to the start of the data to set. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D10EffectScalarVariable::SetFloatArray([In, Buffer] float* pData,[None] int Offset,[None] int Count)</unmanaged>
public void Set(float[] dataRef)
{
Set(dataRef, 0);
}
/// <summary>
/// Set an array of floating-point variables.
/// </summary>
/// <param name="dataRef">A reference to the start of the data to set. </param>
/// <param name="offset">Must be set to 0; this is reserved for future use. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D10EffectScalarVariable::SetFloatArray([In, Buffer] float* pData,[None] int Offset,[None] int Count)</unmanaged>
public void Set(float[] dataRef, int offset)
{
SetFloatArray(dataRef, offset, dataRef.Length);
}
/// <summary>
/// Get an array of floating-point variables.
/// </summary>
/// <param name="count">The number of array elements to set. </param>
/// <returns>Returns an array of floats. </returns>
/// <unmanaged>HRESULT ID3D10EffectScalarVariable::GetFloatArray([Out, Buffer] float* pData,[None] int Offset,[None] int Count)</unmanaged>
public float[] GetFloatArray(int count)
{
return GetFloatArray(0, count);
}
/// <summary>
/// Get an array of floating-point variables.
/// </summary>
/// <param name="offset">Must be set to 0; this is reserved for future use. </param>
/// <param name="count">The number of array elements to set. </param>
/// <returns>Returns an array of floats. </returns>
/// <unmanaged>HRESULT ID3D10EffectScalarVariable::GetFloatArray([Out, Buffer] float* pData,[None] int Offset,[None] int Count)</unmanaged>
public float[] GetFloatArray(int offset, int count)
{
var temp = new float[count];
GetFloatArray(temp, offset, count);
return temp;
}
/// <summary>
/// Set an unsigned integer variable.
/// </summary>
/// <param name="value">A reference to the variable. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D10EffectScalarVariable::SetInt([None] int Value)</unmanaged>
public void Set(uint value)
{
int temp = 0;
unchecked { temp = (int)value; }
SetInt(temp);
}
/// <summary>
/// Set an array of unsigned integer variables.
/// </summary>
/// <param name="dataRef">A reference to the start of the data to set. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D10EffectScalarVariable::SetIntArray([In, Buffer] int* pData,[None] int Offset,[None] int Count)</unmanaged>
public void Set(uint[] dataRef)
{
int[] temp = new int[dataRef.Length];
unchecked { for (int n = 0; n < dataRef.Length; n++) temp[n] = (int)dataRef[n]; }
Set(temp, 0);
}
/// <summary>
/// Set an integer variable.
/// </summary>
/// <param name="value">A reference to the variable. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D10EffectScalarVariable::SetInt([None] int Value)</unmanaged>
public void Set(int value)
{
SetInt(value);
}
/// <summary>
/// Set an array of integer variables.
/// </summary>
/// <param name="dataRef">A reference to the start of the data to set. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D10EffectScalarVariable::SetIntArray([In, Buffer] int* pData,[None] int Offset,[None] int Count)</unmanaged>
public void Set(int[] dataRef)
{
Set(dataRef, 0);
}
/// <summary>
/// Set an array of integer variables.
/// </summary>
/// <param name="dataRef">A reference to the start of the data to set. </param>
/// <param name="offset">Must be set to 0; this is reserved for future use. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D10EffectScalarVariable::SetIntArray([In, Buffer] int* pData,[None] int Offset,[None] int Count)</unmanaged>
public void Set(int[] dataRef, int offset)
{
SetIntArray(dataRef, offset, dataRef.Length);
}
/// <summary>
/// Get an array of integer variables.
/// </summary>
/// <param name="count">The number of array elements to set. </param>
/// <returns>Returns an array of integer variables. </returns>
/// <unmanaged>HRESULT ID3D10EffectScalarVariable::GetIntArray([Out, Buffer] int* pData,[None] int Offset,[None] int Count)</unmanaged>
public int[] GetIntArray(int count)
{
return GetIntArray(0, count);
}
/// <summary>
/// Get an array of integer variables.
/// </summary>
/// <param name="offset">Must be set to 0; this is reserved for future use. </param>
/// <param name="count">The number of array elements to set. </param>
/// <returns>Returns an array of integer variables. </returns>
/// <unmanaged>HRESULT ID3D10EffectScalarVariable::GetIntArray([Out, Buffer] int* pData,[None] int Offset,[None] int Count)</unmanaged>
public int[] GetIntArray(int offset, int count)
{
var temp = new int[count];
GetIntArray(temp, offset, count);
return temp;
}
/// <summary>
/// Set a boolean variable.
/// </summary>
/// <param name="value">A reference to the variable. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D10EffectScalarVariable::SetBool([None] BOOL Value)</unmanaged>
public void Set(bool value)
{
SetBool(value);
}
/// <summary>
/// Get a boolean variable.
/// </summary>
/// <returns>Returns a boolean. </returns>
/// <unmanaged>HRESULT ID3D10EffectScalarVariable::GetBool([Out] BOOL* pValue)</unmanaged>
public bool GetBool()
{
RawBool temp;
GetBool(out temp);
return temp;
}
/// <summary>
/// Set an array of boolean variables.
/// </summary>
/// <param name="dataRef">A reference to the start of the data to set. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D10EffectScalarVariable::SetBoolArray([In, Buffer] BOOL* pData,[None] int Offset,[None] int Count)</unmanaged>
public void Set(bool[] dataRef)
{
Set(dataRef, 0);
}
/// <summary>
/// Set an array of boolean variables.
/// </summary>
/// <param name="dataRef">A reference to the start of the data to set. </param>
/// <param name="offset">Must be set to 0; this is reserved for future use. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D10EffectScalarVariable::SetBoolArray([In, Buffer] BOOL* pData,[None] int Offset,[None] int Count)</unmanaged>
public void Set(bool[] dataRef, int offset)
{
SetBoolArray(Utilities.ConvertToIntArray(dataRef), offset, dataRef.Length);
}
/// <summary>
/// Get an array of boolean variables.
/// </summary>
/// <param name="offset">Must be set to 0; this is reserved for future use. </param>
/// <param name="count">The number of array elements to set. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D10EffectScalarVariable::GetBoolArray([Out, Buffer] BOOL* pData,[None] int Offset,[None] int Count)</unmanaged>
public bool[] GetBoolArray(int offset, int count)
{
RawBool[] temp = new RawBool[count];
GetBoolArray(temp, offset, count);
return Utilities.ConvertToBoolArray(temp);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Security;
using System.Net.Sockets;
using System.Runtime.ExceptionServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.WebSockets
{
internal sealed class WebSocketHandle
{
/// <summary>Per-thread cached StringBuilder for building of strings to send on the connection.</summary>
[ThreadStatic]
private static StringBuilder t_cachedStringBuilder;
/// <summary>Default encoding for HTTP requests. Latin alphabeta no 1, ISO/IEC 8859-1.</summary>
private static readonly Encoding s_defaultHttpEncoding = Encoding.GetEncoding(28591);
/// <summary>Size of the receive buffer to use.</summary>
private const int DefaultReceiveBufferSize = 0x1000;
/// <summary>GUID appended by the server as part of the security key response. Defined in the RFC.</summary>
private const string WSServerGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
private readonly CancellationTokenSource _abortSource = new CancellationTokenSource();
private WebSocketState _state = WebSocketState.Connecting;
private ManagedWebSocket _webSocket;
public static WebSocketHandle Create() => new WebSocketHandle();
public static bool IsValid(WebSocketHandle handle) => handle != null;
public WebSocketCloseStatus? CloseStatus => _webSocket?.CloseStatus;
public string CloseStatusDescription => _webSocket?.CloseStatusDescription;
public WebSocketState State => _webSocket?.State ?? _state;
public string SubProtocol => _webSocket?.SubProtocol;
public static void CheckPlatformSupport() { /* nop */ }
public void Dispose()
{
_state = WebSocketState.Closed;
_webSocket?.Dispose();
}
public void Abort()
{
_abortSource.Cancel();
_webSocket?.Abort();
}
public Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) =>
_webSocket.SendAsync(buffer, messageType, endOfMessage, cancellationToken);
public Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer, CancellationToken cancellationToken) =>
_webSocket.ReceiveAsync(buffer, cancellationToken);
public Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) =>
_webSocket.CloseAsync(closeStatus, statusDescription, cancellationToken);
public Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) =>
_webSocket.CloseOutputAsync(closeStatus, statusDescription, cancellationToken);
public async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options)
{
// TODO #14480 : Not currently implemented, or explicitly ignored:
// - ClientWebSocketOptions.UseDefaultCredentials
// - ClientWebSocketOptions.Credentials
// - ClientWebSocketOptions.Proxy
// - ClientWebSocketOptions._sendBufferSize
// Establish connection to the server
CancellationTokenRegistration registration = cancellationToken.Register(s => ((WebSocketHandle)s).Abort(), this);
try
{
// Connect to the remote server
Socket connectedSocket = await ConnectSocketAsync(uri.Host, uri.Port, cancellationToken).ConfigureAwait(false);
Stream stream = new NetworkStream(connectedSocket, ownsSocket:true);
// Upgrade to SSL if needed
if (uri.Scheme == UriScheme.Wss)
{
var sslStream = new SslStream(stream);
await sslStream.AuthenticateAsClientAsync(
uri.Host,
options.ClientCertificates,
SecurityProtocol.AllowedSecurityProtocols,
checkCertificateRevocation: false).ConfigureAwait(false);
stream = sslStream;
}
// Create the security key and expected response, then build all of the request headers
KeyValuePair<string, string> secKeyAndSecWebSocketAccept = CreateSecKeyAndSecWebSocketAccept();
byte[] requestHeader = BuildRequestHeader(uri, options, secKeyAndSecWebSocketAccept.Key);
// Write out the header to the connection
await stream.WriteAsync(requestHeader, 0, requestHeader.Length, cancellationToken).ConfigureAwait(false);
// Parse the response and store our state for the remainder of the connection
string subprotocol = await ParseAndValidateConnectResponseAsync(stream, options, secKeyAndSecWebSocketAccept.Value, cancellationToken).ConfigureAwait(false);
_webSocket = ManagedWebSocket.CreateFromConnectedStream(
stream, false, subprotocol, options.KeepAliveInterval, options.ReceiveBufferSize, options.Buffer);
// If a concurrent Abort or Dispose came in before we set _webSocket, make sure to update it appropriately
if (_state == WebSocketState.Aborted)
{
_webSocket.Abort();
}
else if (_state == WebSocketState.Closed)
{
_webSocket.Dispose();
}
}
catch (Exception exc)
{
if (_state < WebSocketState.Closed)
{
_state = WebSocketState.Closed;
}
Abort();
if (exc is WebSocketException)
{
throw;
}
throw new WebSocketException(SR.net_webstatus_ConnectFailure, exc);
}
finally
{
registration.Dispose();
}
}
/// <summary>Connects a socket to the specified host and port, subject to cancellation and aborting.</summary>
/// <param name="host">The host to which to connect.</param>
/// <param name="port">The port to which to connect on the host.</param>
/// <param name="cancellationToken">The CancellationToken to use to cancel the websocket.</param>
/// <returns>The connected Socket.</returns>
private async Task<Socket> ConnectSocketAsync(string host, int port, CancellationToken cancellationToken)
{
IPAddress[] addresses = await Dns.GetHostAddressesAsync(host).ConfigureAwait(false);
ExceptionDispatchInfo lastException = null;
foreach (IPAddress address in addresses)
{
var socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
using (cancellationToken.Register(s => ((Socket)s).Dispose(), socket))
using (_abortSource.Token.Register(s => ((Socket)s).Dispose(), socket))
{
try
{
await socket.ConnectAsync(address, port).ConfigureAwait(false);
}
catch (ObjectDisposedException ode)
{
// If the socket was disposed because cancellation was requested, translate the exception
// into a new OperationCanceledException. Otherwise, let the original ObjectDisposedexception propagate.
CancellationToken token = cancellationToken.IsCancellationRequested ? cancellationToken : _abortSource.Token;
if (token.IsCancellationRequested)
{
throw new OperationCanceledException(new OperationCanceledException().Message, ode, token);
}
}
}
cancellationToken.ThrowIfCancellationRequested(); // in case of a race and socket was disposed after the await
_abortSource.Token.ThrowIfCancellationRequested();
return socket;
}
catch (Exception exc)
{
socket.Dispose();
lastException = ExceptionDispatchInfo.Capture(exc);
}
}
lastException?.Throw();
Debug.Fail("We should never get here. We should have already returned or an exception should have been thrown.");
throw new WebSocketException(SR.net_webstatus_ConnectFailure);
}
/// <summary>Creates a byte[] containing the headers to send to the server.</summary>
/// <param name="uri">The Uri of the server.</param>
/// <param name="options">The options used to configure the websocket.</param>
/// <param name="secKey">The generated security key to send in the Sec-WebSocket-Key header.</param>
/// <returns>The byte[] containing the encoded headers ready to send to the network.</returns>
private static byte[] BuildRequestHeader(Uri uri, ClientWebSocketOptions options, string secKey)
{
StringBuilder builder = t_cachedStringBuilder ?? (t_cachedStringBuilder = new StringBuilder());
Debug.Assert(builder.Length == 0, $"Expected builder to be empty, got one of length {builder.Length}");
try
{
builder.Append("GET ").Append(uri.PathAndQuery).Append(" HTTP/1.1\r\n");
// Add all of the required headers, honoring Host header if set.
string hostHeader = options.RequestHeaders[HttpKnownHeaderNames.Host];
builder.Append("Host: ");
if (string.IsNullOrEmpty(hostHeader))
{
builder.Append(uri.IdnHost).Append(':').Append(uri.Port).Append("\r\n");
}
else
{
builder.Append(hostHeader).Append("\r\n");
}
builder.Append("Connection: Upgrade\r\n");
builder.Append("Upgrade: websocket\r\n");
builder.Append("Sec-WebSocket-Version: 13\r\n");
builder.Append("Sec-WebSocket-Key: ").Append(secKey).Append("\r\n");
// Add all of the additionally requested headers
foreach (string key in options.RequestHeaders.AllKeys)
{
if (string.Equals(key, HttpKnownHeaderNames.Host, StringComparison.OrdinalIgnoreCase))
{
// Host header handled above
continue;
}
builder.Append(key).Append(": ").Append(options.RequestHeaders[key]).Append("\r\n");
}
// Add the optional subprotocols header
if (options.RequestedSubProtocols.Count > 0)
{
builder.Append(HttpKnownHeaderNames.SecWebSocketProtocol).Append(": ");
builder.Append(options.RequestedSubProtocols[0]);
for (int i = 1; i < options.RequestedSubProtocols.Count; i++)
{
builder.Append(", ").Append(options.RequestedSubProtocols[i]);
}
builder.Append("\r\n");
}
// Add an optional cookies header
if (options.Cookies != null)
{
string header = options.Cookies.GetCookieHeader(uri);
if (!string.IsNullOrWhiteSpace(header))
{
builder.Append(HttpKnownHeaderNames.Cookie).Append(": ").Append(header).Append("\r\n");
}
}
// End the headers
builder.Append("\r\n");
// Return the bytes for the built up header
return s_defaultHttpEncoding.GetBytes(builder.ToString());
}
finally
{
// Make sure we clear the builder
builder.Clear();
}
}
/// <summary>
/// Creates a pair of a security key for sending in the Sec-WebSocket-Key header and
/// the associated response we expect to receive as the Sec-WebSocket-Accept header value.
/// </summary>
/// <returns>A key-value pair of the request header security key and expected response header value.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "Required by RFC6455")]
private static KeyValuePair<string, string> CreateSecKeyAndSecWebSocketAccept()
{
string secKey = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
using (SHA1 sha = SHA1.Create())
{
return new KeyValuePair<string, string>(
secKey,
Convert.ToBase64String(sha.ComputeHash(Encoding.ASCII.GetBytes(secKey + WSServerGuid))));
}
}
/// <summary>Read and validate the connect response headers from the server.</summary>
/// <param name="stream">The stream from which to read the response headers.</param>
/// <param name="options">The options used to configure the websocket.</param>
/// <param name="expectedSecWebSocketAccept">The expected value of the Sec-WebSocket-Accept header.</param>
/// <param name="cancellationToken">The CancellationToken to use to cancel the websocket.</param>
/// <returns>The agreed upon subprotocol with the server, or null if there was none.</returns>
private async Task<string> ParseAndValidateConnectResponseAsync(
Stream stream, ClientWebSocketOptions options, string expectedSecWebSocketAccept, CancellationToken cancellationToken)
{
// Read the first line of the response
string statusLine = await ReadResponseHeaderLineAsync(stream, cancellationToken).ConfigureAwait(false);
// Depending on the underlying sockets implementation and timing, connecting to a server that then
// immediately closes the connection may either result in an exception getting thrown from the connect
// earlier, or it may result in getting to here but reading 0 bytes. If we read 0 bytes and thus have
// an empty status line, treat it as a connect failure.
if (string.IsNullOrEmpty(statusLine))
{
throw new WebSocketException(SR.Format(SR.net_webstatus_ConnectFailure));
}
const string ExpectedStatusStart = "HTTP/1.1 ";
const string ExpectedStatusStatWithCode = "HTTP/1.1 101"; // 101 == SwitchingProtocols
// If the status line doesn't begin with "HTTP/1.1" or isn't long enough to contain a status code, fail.
if (!statusLine.StartsWith(ExpectedStatusStart, StringComparison.Ordinal) || statusLine.Length < ExpectedStatusStatWithCode.Length)
{
throw new WebSocketException(WebSocketError.HeaderError);
}
// If the status line doesn't contain a status code 101, or if it's long enough to have a status description
// but doesn't contain whitespace after the 101, fail.
if (!statusLine.StartsWith(ExpectedStatusStatWithCode, StringComparison.Ordinal) ||
(statusLine.Length > ExpectedStatusStatWithCode.Length && !char.IsWhiteSpace(statusLine[ExpectedStatusStatWithCode.Length])))
{
throw new WebSocketException(SR.net_webstatus_ConnectFailure);
}
// Read each response header. Be liberal in parsing the response header, treating
// everything to the left of the colon as the key and everything to the right as the value, trimming both.
// For each header, validate that we got the expected value.
bool foundUpgrade = false, foundConnection = false, foundSecWebSocketAccept = false;
string subprotocol = null;
string line;
while (!string.IsNullOrEmpty(line = await ReadResponseHeaderLineAsync(stream, cancellationToken).ConfigureAwait(false)))
{
int colonIndex = line.IndexOf(':');
if (colonIndex == -1)
{
throw new WebSocketException(WebSocketError.HeaderError);
}
string headerName = line.SubstringTrim(0, colonIndex);
string headerValue = line.SubstringTrim(colonIndex + 1);
// The Connection, Upgrade, and SecWebSocketAccept headers are required and with specific values.
ValidateAndTrackHeader(HttpKnownHeaderNames.Connection, "Upgrade", headerName, headerValue, ref foundConnection);
ValidateAndTrackHeader(HttpKnownHeaderNames.Upgrade, "websocket", headerName, headerValue, ref foundUpgrade);
ValidateAndTrackHeader(HttpKnownHeaderNames.SecWebSocketAccept, expectedSecWebSocketAccept, headerName, headerValue, ref foundSecWebSocketAccept);
// The SecWebSocketProtocol header is optional. We should only get it with a non-empty value if we requested subprotocols,
// and then it must only be one of the ones we requested. If we got a subprotocol other than one we requested (or if we
// already got one in a previous header), fail. Otherwise, track which one we got.
if (string.Equals(HttpKnownHeaderNames.SecWebSocketProtocol, headerName, StringComparison.OrdinalIgnoreCase) &&
!string.IsNullOrWhiteSpace(headerValue))
{
string newSubprotocol = options.RequestedSubProtocols.Find(requested => string.Equals(requested, headerValue, StringComparison.OrdinalIgnoreCase));
if (newSubprotocol == null || subprotocol != null)
{
throw new WebSocketException(
WebSocketError.UnsupportedProtocol,
SR.Format(SR.net_WebSockets_AcceptUnsupportedProtocol, string.Join(", ", options.RequestedSubProtocols), subprotocol));
}
subprotocol = newSubprotocol;
}
}
if (!foundUpgrade || !foundConnection || !foundSecWebSocketAccept)
{
throw new WebSocketException(SR.net_webstatus_ConnectFailure);
}
return subprotocol;
}
/// <summary>Validates a received header against expected values and tracks that we've received it.</summary>
/// <param name="targetHeaderName">The header name against which we're comparing.</param>
/// <param name="targetHeaderValue">The header value against which we're comparing.</param>
/// <param name="foundHeaderName">The actual header name received.</param>
/// <param name="foundHeaderValue">The actual header value received.</param>
/// <param name="foundHeader">A bool tracking whether this header has been seen.</param>
private static void ValidateAndTrackHeader(
string targetHeaderName, string targetHeaderValue,
string foundHeaderName, string foundHeaderValue,
ref bool foundHeader)
{
bool isTargetHeader = string.Equals(targetHeaderName, foundHeaderName, StringComparison.OrdinalIgnoreCase);
if (!foundHeader)
{
if (isTargetHeader)
{
if (!string.Equals(targetHeaderValue, foundHeaderValue, StringComparison.OrdinalIgnoreCase))
{
throw new WebSocketException(SR.Format(SR.net_WebSockets_InvalidResponseHeader, targetHeaderName, foundHeaderValue));
}
foundHeader = true;
}
}
else
{
if (isTargetHeader)
{
throw new WebSocketException(SR.Format(SR.net_webstatus_ConnectFailure));
}
}
}
/// <summary>Reads a line from the stream.</summary>
/// <param name="stream">The stream from which to read.</param>
/// <param name="cancellationToken">The CancellationToken used to cancel the websocket.</param>
/// <returns>The read line, or null if none could be read.</returns>
private static async Task<string> ReadResponseHeaderLineAsync(Stream stream, CancellationToken cancellationToken)
{
StringBuilder sb = t_cachedStringBuilder;
if (sb != null)
{
t_cachedStringBuilder = null;
Debug.Assert(sb.Length == 0, $"Expected empty StringBuilder");
}
else
{
sb = new StringBuilder();
}
var arr = new byte[1];
char prevChar = '\0';
try
{
// TODO: Reading one byte is extremely inefficient. The problem, however,
// is that if we read multiple bytes, we could end up reading bytes post-headers
// that are part of messages meant to be read by the managed websocket after
// the connection. The likely solution here is to wrap the stream in a BufferedStream,
// though a) that comes at the expense of an extra set of virtual calls, b)
// it adds a buffer when the managed websocket will already be using a buffer, and
// c) it's not exposed on the version of the System.IO contract we're currently using.
while (await stream.ReadAsync(arr, 0, 1, cancellationToken).ConfigureAwait(false) == 1)
{
// Process the next char
char curChar = (char)arr[0];
if (prevChar == '\r' && curChar == '\n')
{
break;
}
sb.Append(curChar);
prevChar = curChar;
}
if (sb.Length > 0 && sb[sb.Length - 1] == '\r')
{
sb.Length = sb.Length - 1;
}
return sb.ToString();
}
finally
{
sb.Clear();
t_cachedStringBuilder = sb;
}
}
}
}
| |
// Copyright 2021 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 ArcGISRuntime.Samples.Managers;
using Esri.ArcGISRuntime.LocalServices;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
namespace ArcGISRuntime.WPF.Samples.LocalServerServices
{
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Local server services",
category: "Local Server",
description: "Demonstrates how to start and stop the Local Server and start and stop a local map, feature, and geoprocessing service running on the Local Server.",
instructions: "Click `Start Local Server` to start the Local Server. Click `Stop Local Server` to stop the Local Server.",
tags: new[] { "feature", "geoprocessing", "local services", "map", "server", "service" })]
[ArcGISRuntime.Samples.Shared.Attributes.OfflineData("85c34847bbe1402fa115a1b9b87561ce", "92ca5cdb3ff1461384bf80dc008e297b", "a680362d6a7447e8afe2b1eb85fcde30")]
public partial class LocalServerServices
{
// Hold references to the individual services
private LocalMapService _localMapService;
private LocalFeatureService _localFeatureService;
private LocalGeoprocessingService _localGeoprocessingService;
// Generic reference to the service selected in the UI
private LocalService _selectedService;
public LocalServerServices()
{
InitializeComponent();
// Set up the sample
Initialize();
}
private void Initialize()
{
try
{
// Subscribe to event notification for the local server instance
LocalServer.Instance.StatusChanged += (o, e) =>
{
UpdateUiWithServiceUpdate("Local Server", e.Status);
};
}
catch (Exception ex)
{
var localServerTypeInfo = typeof(LocalMapService).GetTypeInfo();
var localServerVersion = FileVersionInfo.GetVersionInfo(localServerTypeInfo.Assembly.Location);
MessageBox.Show($"Please ensure that local server {localServerVersion.FileVersion} is installed prior to using the sample. The download link is in the description. Message: {ex.Message}", "Local Server failed to start");
}
}
private void UpdateUiWithServiceUpdate(string server, LocalServerStatus status)
{
// Construct the new status text
string updateStatus = String.Format("{0} status: {1} \t\t {2}\n{3}", server, status,
DateTime.Now.ToShortTimeString(), StatusTextbox.Text);
// Update the status box text
StatusTextbox.Text = updateStatus;
// Update the list of running services
ServicesListbox.ItemsSource = LocalServer.Instance.Services.Select(m => m.Name + " : " + m.Url);
}
private void CreateServices()
{
try
{
// Arrange the data before starting the services
string mapServicePath = GetMpkPath();
string featureServicePath = GetFeatureLayerPath();
string geoprocessingPath = GetGpPath();
// Create each service but don't start any
_localMapService = new LocalMapService(mapServicePath);
_localFeatureService = new LocalFeatureService(featureServicePath);
_localGeoprocessingService = new LocalGeoprocessingService(geoprocessingPath);
// Subscribe to status updates for each service
_localMapService.StatusChanged += (o, e) => { UpdateUiWithServiceUpdate("Map Service", e.Status); };
_localFeatureService.StatusChanged += (o, e) => { UpdateUiWithServiceUpdate("Feature Service", e.Status); };
_localGeoprocessingService.StatusChanged += (o, e) => { UpdateUiWithServiceUpdate("Geoprocessing Service", e.Status); };
// Enable the UI to select services
ServiceSelectionCombo.IsEnabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Failed to create services");
}
}
private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Get the text of the selected item
string selection = ((ComboBoxItem)ServiceSelectionCombo.SelectedItem).Content.ToString();
// Update the selection
switch (selection)
{
case "Map Service":
_selectedService = _localMapService;
break;
case "Feature Service":
_selectedService = _localFeatureService;
break;
case "Geoprocessing Service":
_selectedService = _localGeoprocessingService;
break;
}
// Return if selection is invalid
if (_selectedService == null)
{
return;
}
// Update the state of the start and stop buttons
UpdateServiceControlUi();
}
private void UpdateServiceControlUi()
{
if (_selectedService == null)
{
return;
}
// Update the UI
if (_selectedService.Status == LocalServerStatus.Started)
{
ServiceStopButton.IsEnabled = true;
ServiceStartButton.IsEnabled = false;
}
else
{
ServiceStopButton.IsEnabled = false;
ServiceStartButton.IsEnabled = true;
}
}
private async void StartServiceButtonClicked(object sender, RoutedEventArgs e)
{
try
{
// Start the selected service
await _selectedService.StartAsync();
// Update the UI
UpdateServiceControlUi();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Failed to start service");
}
}
private async void StopServiceButtonClicked(object sender, RoutedEventArgs e)
{
try
{
// Stop the selected service
await _selectedService.StopAsync();
// Update the UI
UpdateServiceControlUi();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Failed to stop service");
}
}
private static string GetMpkPath()
{
return DataManager.GetDataFolder("85c34847bbe1402fa115a1b9b87561ce", "RelationshipID.mpkx");
}
private static string GetFeatureLayerPath()
{
return DataManager.GetDataFolder("92ca5cdb3ff1461384bf80dc008e297b", "PointsOfInterest.mpkx");
}
private static string GetGpPath()
{
return DataManager.GetDataFolder("a680362d6a7447e8afe2b1eb85fcde30", "Contour.gpkx");
}
private async void StartServerButtonClicked(object sender, RoutedEventArgs e)
{
try
{
// LocalServer must not be running when setting the data path.
if (LocalServer.Instance.Status == LocalServerStatus.Started)
{
await LocalServer.Instance.StopAsync();
}
// Set the local data path - must be done before starting. On most systems, this will be C:\EsriSamples\AppData.
// This path should be kept short to avoid Windows path length limitations.
string tempDataPathRoot = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.Windows)).FullName;
string tempDataPath = Path.Combine(tempDataPathRoot, "EsriSamples", "AppData");
Directory.CreateDirectory(tempDataPath); // CreateDirectory won't overwrite if it already exists.
LocalServer.Instance.AppDataPath = tempDataPath;
// Start the server
await LocalServer.Instance.StartAsync();
// Create the services
CreateServices();
}
catch (Exception ex)
{
var localServerTypeInfo = typeof(LocalMapService).GetTypeInfo();
var localServerVersion = FileVersionInfo.GetVersionInfo(localServerTypeInfo.Assembly.Location);
MessageBox.Show($"Please ensure that local server {localServerVersion.FileVersion} is installed prior to using the sample. The download link is in the description. Message: {ex.Message}", "Local Server failed to start");
}
// Update the UI
LocalServerStopButton.IsEnabled = true;
LocalServerStartButton.IsEnabled = false;
}
private async void StopServerButtonClicked(object sender, RoutedEventArgs e)
{
// Update the UI
ServiceStartButton.IsEnabled = false;
ServiceStopButton.IsEnabled = false;
LocalServerStartButton.IsEnabled = true;
LocalServerStopButton.IsEnabled = false;
// Stop the server
await LocalServer.Instance.StopAsync();
// Clear references to the services
_localFeatureService = null;
_localMapService = null;
_localGeoprocessingService = null;
}
private void NavigateButtonClicked(object sender, RoutedEventArgs e)
{
// Return if selection is empty
if (ServicesListbox.SelectedItems.Count < 1) { return; }
try
{
// Get the full text in the selection
string strFullName = ServicesListbox.SelectedItems[0].ToString();
// Create array of characters to split text by; ':' separates the service name and the URI
char[] splitChars = { ':' };
// Extract the service URL
string serviceUri = strFullName.Split(splitChars, 2)[1].Trim();
// Navigate to the service
Process.Start(new ProcessStartInfo(serviceUri) { UseShellExecute = true });
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Couldn't navigate to service");
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Text.Tests
{
public class UTF8EncodingEncode
{
public static IEnumerable<object[]> Encode_TestData()
{
// All ASCII chars
for (char c = char.MinValue; c <= 0x7F; c++)
{
yield return new object[] { c.ToString(), 0, 1, new byte[] { (byte)c } };
yield return new object[] { "a" + c.ToString() + "b", 1, 1, new byte[] { (byte)c } };
yield return new object[] { "a" + c.ToString() + "b", 2, 1, new byte[] { 98 } };
yield return new object[] { "a" + c.ToString() + "b", 0, 3, new byte[] { 97, (byte)c, 98 } };
}
// Misc ASCII and Unicode strings
yield return new object[] { "FooBA\u0400R", 0, 7, new byte[] { 70, 111, 111, 66, 65, 208, 128, 82 } };
yield return new object[] { "\u00C0nima\u0300l", 0, 7, new byte[] { 195, 128, 110, 105, 109, 97, 204, 128, 108 } };
yield return new object[] { "Test\uD803\uDD75Test", 0, 10, new byte[] { 84, 101, 115, 116, 240, 144, 181, 181, 84, 101, 115, 116 } };
yield return new object[] { "\u0130", 0, 1, new byte[] { 196, 176 } };
yield return new object[] { "\uD803\uDD75\uD803\uDD75\uD803\uDD75", 0, 6, new byte[] { 240, 144, 181, 181, 240, 144, 181, 181, 240, 144, 181, 181 } };
yield return new object[] { "za\u0306\u01FD\u03B2\uD8FF\uDCFF", 0, 7, new byte[] { 122, 97, 204, 134, 199, 189, 206, 178, 241, 143, 179, 191 } };
yield return new object[] { "za\u0306\u01FD\u03B2\uD8FF\uDCFF", 4, 3, new byte[] { 206, 178, 241, 143, 179, 191 } };
yield return new object[] { "\u0023\u0025\u03a0\u03a3", 1, 2, new byte[] { 37, 206, 160 } };
yield return new object[] { "\u00C5", 0, 1, new byte[] { 0xC3, 0x85 } };
yield return new object[] { "\u0065\u0065\u00E1\u0065\u0065\u8000\u00E1\u0065\uD800\uDC00\u8000\u00E1\u0065\u0065\u0065", 0, 15, new byte[] { 0x65, 0x65, 0xC3, 0xA1, 0x65, 0x65, 0xE8, 0x80, 0x80, 0xC3, 0xA1, 0x65, 0xF0, 0x90, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xC3, 0xA1, 0x65, 0x65, 0x65 } };
yield return new object[] { "\u00A4\u00D0aR|{AnGe\u00A3\u00A4", 0, 12, new byte[] { 0xC2, 0xA4, 0xC3, 0x90, 0x61, 0x52, 0x7C, 0x7B, 0x41, 0x6E, 0x47, 0x65, 0xC2, 0xA3, 0xC2, 0xA4 } };
// Control codes
yield return new object[] { "\u001F\u0010\u0000\u0009", 0, 4, new byte[] { 0x1F, 0x10, 0x00, 0x09 } };
// Long ASCII strings
yield return new object[] { "eeeee", 0, 5, new byte[] { 0x65, 0x65, 0x65, 0x65, 0x65 } };
yield return new object[] { "e\u00E1eee", 0, 5, new byte[] { 0x65, 0xC3, 0xA1, 0x65, 0x65, 0x65 } };
yield return new object[] { "\u0065\u8000\u0065\u0065\u0065", 0, 5, new byte[] { 0x65, 0xE8, 0x80, 0x80, 0x65, 0x65, 0x65 } };
yield return new object[] { "\u0065\uD800\uDC00\u0065\u0065\u0065", 0, 6, new byte[] { 0x65, 0xF0, 0x90, 0x80, 0x80, 0x65, 0x65, 0x65 } };
yield return new object[] { "eeeeeeeeeeeeeee", 0, 15, new byte[] { 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65 } };
yield return new object[] { "eeeeee\u00E1eeeeeeee", 0, 15, new byte[] { 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0xC3, 0xA1, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65 } };
yield return new object[] { "\u0065\u0065\u0065\u0065\u0065\u0065\u8000\u0065\u0065\u0065\u0065\u0065\u0065\u0065\u0065", 0, 15, new byte[] { 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0xE8, 0x80, 0x80, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65 } };
yield return new object[] { "\u0065\u0065\u0065\u0065\u0065\u0065\uD800\uDC00\u0065\u0065\u0065\u0065\u0065\u0065\u0065\u0065", 0, 16, new byte[] { 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0xF0, 0x90, 0x80, 0x80, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65 } };
// 2 bytes
yield return new object[] { "\u00E1", 0, 1, new byte[] { 0xC3, 0xA1 } };
yield return new object[] { "\u00E1\u00E1\u00E1\u00E1\u00E1", 0, 5, new byte[] { 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1 } };
yield return new object[] { "\u00E1e\u00E1\u00E1\u00E1", 0, 5, new byte[] { 0xC3, 0xA1, 0x65, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1 } };
yield return new object[] { "\u00E1\u8000\u00E1\u00E1\u00E1", 0, 5, new byte[] { 0xC3, 0xA1, 0xE8, 0x80, 0x80, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1 } };
yield return new object[] { "\u00E1\uD800\uDC00\u00E1\u00E1\u00E1", 0, 6, new byte[] { 0xC3, 0xA1, 0xF0, 0x90, 0x80, 0x80, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1 } };
yield return new object[] { "\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1", 0, 15, new byte[] { 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1 } };
yield return new object[] { "\u00E1\u00E1e\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1", 0, 15, new byte[] { 0xC3, 0xA1, 0xC3, 0xA1, 0x65, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1 } };
yield return new object[] { "\u00E1\u00E1\u8000\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1", 0, 15, new byte[] { 0xC3, 0xA1, 0xC3, 0xA1, 0xE8, 0x80, 0x80, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1 } };
yield return new object[] { "\u00E1\u00E1\uD800\uDC00\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1\u00E1", 0, 16, new byte[] { 0xC3, 0xA1, 0xC3, 0xA1, 0xF0, 0x90, 0x80, 0x80, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1, 0xC3, 0xA1 } };
// 3 bytes
yield return new object[] { "\u8000", 0, 1, new byte[] { 0xE8, 0x80, 0x80 } };
yield return new object[] { "\u8000\u8000\u8000\u8000", 0, 4, new byte[] { 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80 } };
yield return new object[] { "\u8000\u0065\u8000\u8000", 0, 4, new byte[] { 0xE8, 0x80, 0x80, 0x65, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80 } };
yield return new object[] { "\u8000\u00E1\u8000\u8000", 0, 4, new byte[] { 0xE8, 0x80, 0x80, 0xC3, 0xA1, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80 } };
yield return new object[] { "\u8000\uD800\uDC00\u8000\u8000", 0, 5, new byte[] { 0xE8, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80 } };
yield return new object[] { "\u8000\u8000\u8000\u8000\u8000\u8000\u8000\u8000\u8000\u8000\u8000\u8000\u8000\u8000\u8000", 0, 15, new byte[] { 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80 } };
yield return new object[] { "\u8000\u8000\u8000\u0065\u8000\u8000\u8000\u8000\u8000\u8000\u8000\u8000\u8000\u8000\u8000", 0, 15, new byte[] { 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0x65, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80 } };
yield return new object[] { "\u8000\u8000\u8000\u00E1\u8000\u8000\u8000\u8000\u8000\u8000\u8000\u8000\u8000\u8000\u8000", 0, 15, new byte[] { 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xC3, 0xA1, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80 } };
yield return new object[] { "\u8000\u8000\u8000\uD800\uDC00\u8000\u8000\u8000\u8000\u8000\u8000\u8000\u8000\u8000\u8000\u8000", 0, 16, new byte[] { 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xE8, 0x80, 0x80 } };
// Surrogate pairs
yield return new object[] { "\uD800\uDC00", 0, 2, new byte[] { 240, 144, 128, 128 } };
yield return new object[] { "a\uD800\uDC00b", 0, 4, new byte[] { 97, 240, 144, 128, 128, 98 } };
yield return new object[] { "\uDB80\uDC00", 0, 2, new byte[] { 0xF3, 0xB0, 0x80, 0x80 } };
yield return new object[] { "\uD800\uDFFF", 0, 2, new byte[] { 0xF0, 0x90, 0x8F, 0xBF } };
yield return new object[] { "\uDBFF\uDC00", 0, 2, new byte[] { 0xF4, 0x8F, 0xB0, 0x80 } };
yield return new object[] { "\uDBFF\uDFFF", 0, 2, new byte[] { 0xF4, 0x8F, 0xBF, 0xBF } };
yield return new object[] { "\uD800\uDC00\uD800\uDC00\uD800\uDC00", 0, 6, new byte[] { 0xF0, 0x90, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80 } };
yield return new object[] { "\uD800\uDC00\u0065\uD800\uDC00", 0, 5, new byte[] { 0xF0, 0x90, 0x80, 0x80, 0x65, 0xF0, 0x90, 0x80, 0x80 } };
yield return new object[] { "\uD800\uDC00\u00E1\uD800\uDC00", 0, 5, new byte[] { 0xF0, 0x90, 0x80, 0x80, 0xC3, 0xA1, 0xF0, 0x90, 0x80, 0x80 } };
yield return new object[] { "\uD800\uDC00\u8000\uD800\uDC00", 0, 5, new byte[] { 0xF0, 0x90, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80 } };
yield return new object[] { "\uD800\uDC00\uD800\uDC00\uD800\uDC00\uD800\uDC00\uD800\uDC00\uD800\uDC00\uD800\uDC00\uD800\uDC00", 0, 16, new byte[] { 0xF0, 0x90, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80 } };
yield return new object[] { "\uD800\uDC00\u0065\uD800\uDC00\uD800\uDC00\uD800\uDC00\uD800\uDC00\uD800\uDC00\uD800\uDC00", 0, 15, new byte[] { 0xF0, 0x90, 0x80, 0x80, 0x65, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80 } };
yield return new object[] { "\uD800\uDC00\u00E1\uD800\uDC00\uD800\uDC00\uD800\uDC00\uD800\uDC00\uD800\uDC00\uD800\uDC00", 0, 15, new byte[] { 0xF0, 0x90, 0x80, 0x80, 0xC3, 0xA1, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80 } };
yield return new object[] { "\uD800\uDC00\u8000\uD800\uDC00\uD800\uDC00\uD800\uDC00\uD800\uDC00\uD800\uDC00\uD800\uDC00", 0, 15, new byte[] { 0xF0, 0x90, 0x80, 0x80, 0xE8, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0x90, 0x80, 0x80 } };
// U+FDD0 - U+FDEF
yield return new object[] { "\uFDD0\uFDEF", 0, 2, new byte[] { 0xEF, 0xB7, 0x90, 0xEF, 0xB7, 0xAF } };
// BOM
yield return new object[] { "\uFEFF\u0041", 0, 2, new byte[] { 0xEF, 0xBB, 0xBF, 0x41 } };
// High BMP non-chars
yield return new object[] { "\uFFFD", 0, 1, new byte[] { 239, 191, 189 } };
yield return new object[] { "\uFFFE", 0, 1, new byte[] { 239, 191, 190 } };
yield return new object[] { "\uFFFF", 0, 1, new byte[] { 239, 191, 191 } };
// Empty strings
yield return new object[] { string.Empty, 0, 0, new byte[0] };
yield return new object[] { "abc", 3, 0, new byte[0] };
yield return new object[] { "abc", 0, 0, new byte[0] };
}
[Theory]
[MemberData(nameof(Encode_TestData))]
public void Encode(string chars, int index, int count, byte[] expected)
{
EncodingHelpers.Encode(
new UTF8Encoding(encoderShouldEmitUTF8Identifier: true, throwOnInvalidBytes: false),
chars, index, count, expected);
EncodingHelpers.Encode(
new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false),
chars, index, count, expected);
EncodingHelpers.Encode(
new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true),
chars, index, count, expected);
EncodingHelpers.Encode(
new UTF8Encoding(encoderShouldEmitUTF8Identifier: true, throwOnInvalidBytes: true),
chars, index, count, expected);
}
public static IEnumerable<object[]> Encode_InvalidChars_TestData()
{
byte[] unicodeReplacementBytes1 = new byte[] { 239, 191, 189 };
// Lone high surrogate
yield return new object[] { "\uD800", 0, 1, unicodeReplacementBytes1 };
yield return new object[] { "\uDD75", 0, 1, unicodeReplacementBytes1 };
yield return new object[] { "\uDBFF", 0, 1, unicodeReplacementBytes1 };
// Lone low surrogate
yield return new object[] { "\uDC00", 0, 1, unicodeReplacementBytes1 };
yield return new object[] { "\uDC00", 0, 1, unicodeReplacementBytes1 };
// Surrogate pair out of range
yield return new object[] { "\uD800\uDC00", 0, 1, unicodeReplacementBytes1 };
yield return new object[] { "\uD800\uDC00", 1, 1, unicodeReplacementBytes1 };
// Invalid surrogate pair
yield return new object[] { "\u0041\uD800\uE000", 0, 3, new byte[] { 0x41, 0xEF, 0xBF, 0xBD, 0xEE, 0x80, 0x80 } };
yield return new object[] { "\uD800\u0041\uDC00", 0, 3, new byte[] { 0xEF, 0xBF, 0xBD, 0x41, 0xEF, 0xBF, 0xBD } };
yield return new object[] { "\uD800\u0041\u0042\u07FF\u0043\uDC00", 0, 6, new byte[] { 0xEF, 0xBF, 0xBD, 0x41, 0x42, 0xDF, 0xBF, 0x43, 0xEF, 0xBF, 0xBD } };
// Mixture of ASCII, valid Unicode and invalid unicode
yield return new object[] { "\uDD75\uDD75\uD803\uDD75\uDD75\uDD75\uDD75\uD803\uD803\uD803\uDD75\uDD75\uDD75\uDD75", 0, 14, new byte[] { 239, 191, 189, 239, 191, 189, 240, 144, 181, 181, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 240, 144, 181, 181, 239, 191, 189, 239, 191, 189, 239, 191, 189 } };
yield return new object[] { "Test\uD803Test", 0, 9, new byte[] { 84, 101, 115, 116, 239, 191, 189, 84, 101, 115, 116 } };
yield return new object[] { "Test\uDD75Test", 0, 9, new byte[] { 84, 101, 115, 116, 239, 191, 189, 84, 101, 115, 116 } };
yield return new object[] { "TestTest\uDD75", 0, 9, new byte[] { 84, 101, 115, 116, 84, 101, 115, 116, 239, 191, 189 } };
yield return new object[] { "TestTest\uD803", 0, 9, new byte[] { 84, 101, 115, 116, 84, 101, 115, 116, 239, 191, 189 } };
byte[] unicodeReplacementBytes2 = new byte[] { 239, 191, 189, 239, 191, 189 };
yield return new object[] { "\uD800\uD800", 0, 2, unicodeReplacementBytes2 }; // High, high
yield return new object[] { "\uDC00\uD800", 0, 2, unicodeReplacementBytes2 }; // Low, high
yield return new object[] { "\uDC00\uDC00", 0, 2, unicodeReplacementBytes2 }; // Low, low
}
[Fact]
public static unsafe void GetBytes_ValidASCIIUnicode()
{
Encoding encoding = Encoding.UTF8;
// Bytes has enough capacity to accomodate result
string s = "T\uD83D\uDE01est";
Assert.Equal(4, encoding.GetBytes(s, 0, 2, new byte[4], 0));
Assert.Equal(5, encoding.GetBytes(s, 0, 3, new byte[5], 0));
Assert.Equal(6, encoding.GetBytes(s, 0, 4, new byte[6], 0));
Assert.Equal(7, encoding.GetBytes(s, 0, 5, new byte[7], 0));
char[] c = s.ToCharArray();
Assert.Equal(4, encoding.GetBytes(c, 0, 2, new byte[4], 0));
Assert.Equal(5, encoding.GetBytes(c, 0, 3, new byte[5], 0));
Assert.Equal(6, encoding.GetBytes(c, 0, 4, new byte[6], 0));
Assert.Equal(7, encoding.GetBytes(c, 0, 5, new byte[7], 0));
byte[] b = new byte[8];
fixed (char* pChar = c)
fixed (byte* pByte = b)
{
Assert.Equal(4, encoding.GetBytes(pChar, 2, pByte, 4));
Assert.Equal(5, encoding.GetBytes(pChar, 3, pByte, 5));
Assert.Equal(6, encoding.GetBytes(pChar, 4, pByte, 6));
Assert.Equal(7, encoding.GetBytes(pChar, 5, pByte, 7));
}
}
[Fact]
public static unsafe void GetBytes_InvalidASCIIUnicode()
{
Encoding encoding = Encoding.UTF8;
// Bytes does not have enough capacity to accomodate result
string s = "T\uD83D\uDE01est";
AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes(s, 0, 2, new byte[3], 0));
AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes(s, 0, 3, new byte[4], 0));
AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes(s, 0, 4, new byte[5], 0));
AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes(s, 0, 5, new byte[6], 0));
char[] c = s.ToCharArray();
AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes(c, 0, 2, new byte[3], 0));
AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes(c, 0, 3, new byte[4], 0));
AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes(c, 0, 4, new byte[5], 0));
AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes(c, 0, 5, new byte[6], 0));
byte[] b = new byte[8];
AssertExtensions.Throws<ArgumentException>("bytes", () => FixedEncodingHelper(c, 2, b, 3));
AssertExtensions.Throws<ArgumentException>("bytes", () => FixedEncodingHelper(c, 3, b, 4));
AssertExtensions.Throws<ArgumentException>("bytes", () => FixedEncodingHelper(c, 4, b, 5));
AssertExtensions.Throws<ArgumentException>("bytes", () => FixedEncodingHelper(c, 5, b, 6));
}
private static unsafe void FixedEncodingHelper(char[] c, int charCount, byte[] b, int byteCount)
{
Encoding encoding = Encoding.UTF8;
fixed (char* pChar = c)
fixed (byte* pByte = b)
{
Assert.Equal(byteCount, encoding.GetBytes(pChar, charCount, pByte, byteCount));
}
}
[Theory]
[MemberData(nameof(Encode_InvalidChars_TestData))]
public void Encode_InvalidChars(string chars, int index, int count, byte[] expected)
{
EncodingHelpers.Encode(
new UTF8Encoding(encoderShouldEmitUTF8Identifier: true, throwOnInvalidBytes: false),
chars, index, count, expected);
EncodingHelpers.Encode(
new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false),
chars, index, count, expected);
NegativeEncodingTests.Encode_Invalid(
new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true),
chars, index, count);
NegativeEncodingTests.Encode_Invalid(
new UTF8Encoding(encoderShouldEmitUTF8Identifier: true, throwOnInvalidBytes: true),
chars, index, count);
}
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2014 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit mindtouch.com;
* please review the licensing section.
*
* 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.IO;
using System.Text;
using MindTouch.IO;
using MindTouch.Tasking;
using MindTouch.Web;
using MindTouch.Xml;
namespace MindTouch.Dream {
using Yield = IEnumerator<IYield>;
/// <summary>
/// Provides the Dream encapsulations of Http request and response objects.
/// </summary>
public class DreamMessage {
//--- Class Fields ---
private static log4net.ILog _log = LogUtils.CreateLog();
//--- Class Methods ---
/// <summary>
/// New Message with HTTP status: Ok (200).
/// </summary>
/// <returns>New DreamMessage.</returns>
public static DreamMessage Ok() {
return new DreamMessage(DreamStatus.Ok, null);
}
/// <summary>
/// New Message with HTTP status: Ok (200).
/// </summary>
/// <param name="doc">Message body.</param>
/// <returns>New DreamMessage.</returns>
public static DreamMessage Ok(XDoc doc) {
return new DreamMessage(DreamStatus.Ok, null, doc);
}
/// <summary>
/// New Message with HTTP status: Ok (200).
/// </summary>
/// <param name="contentType">Content Mime-Type.</param>
/// <param name="doc">Message body.</param>
/// <returns>New DreamMessage.</returns>
public static DreamMessage Ok(MimeType contentType, XDoc doc) {
return new DreamMessage(DreamStatus.Ok, null, contentType, doc);
}
/// <summary>
/// New Message with HTTP status: Ok (200).
/// </summary>
/// <param name="contentType">Content Mime-Type.</param>
/// <param name="text">Message body.</param>
/// <returns>New DreamMessage.</returns>
public static DreamMessage Ok(MimeType contentType, string text) {
return new DreamMessage(DreamStatus.Ok, null, contentType, text);
}
/// <summary>
/// New Message with HTTP status: Ok (200).
/// </summary>
/// <param name="values">Name/value pair body.</param>
/// <returns>New DreamMessage.</returns>
public static DreamMessage Ok(KeyValuePair<string, string>[] values) {
return new DreamMessage(DreamStatus.Ok, null, MimeType.FORM_URLENCODED, XUri.RenderParams(values) ?? string.Empty);
}
/// <summary>
/// New Message with HTTP status: Ok (200).
/// </summary>
/// <param name="contentType">Content Mime-Type.</param>
/// <param name="content">Message body.</param>
/// <returns>New DreamMessage.</returns>
public static DreamMessage Ok(MimeType contentType, byte[] content) {
return new DreamMessage(DreamStatus.Ok, null, contentType, content);
}
/// <summary>
/// New Message with HTTP status: Ok (200).
/// </summary>
/// <param name="contentType">Content Mime-Type.</param>
/// <param name="contentLength">Content length.</param>
/// <param name="content">Message body.</param>
/// <returns>New DreamMessage.</returns>
public static DreamMessage Ok(MimeType contentType, long contentLength, Stream content) {
return new DreamMessage(DreamStatus.Ok, null, contentType, contentLength, content);
}
/// <summary>
/// New Message with HTTP status: Created (201).
/// </summary>
/// <param name="uri">Location of created resource.</param>
/// <param name="doc">Message body.</param>
/// <returns>New DreamMessage.</returns>
public static DreamMessage Created(XUri uri, XDoc doc) {
DreamMessage result = new DreamMessage(DreamStatus.Created, null, doc);
result.Headers.Location = uri;
return result;
}
/// <summary>
/// New Message with HTTP status: Not Modified (304).
/// </summary>
/// <returns>New DreamMessage.</returns>
public static DreamMessage NotModified() {
return new DreamMessage(DreamStatus.NotModified, null, XDoc.Empty);
}
/// <summary>
/// New Message with HTTP status: Not Found (404).
/// </summary>
/// <param name="reason">Reason.</param>
/// <returns>New DreamMessage.</returns>
public static DreamMessage NotFound(string reason) {
_log.DebugFormat("Response: Not Found - {0}{1}", reason, DebugOnly_GetRequestPath());
return new DreamMessage(DreamStatus.NotFound, null, GetDefaultErrorResponse(DreamStatus.NotFound, "Not Found", reason));
}
/// <summary>
/// New Message with HTTP status: Bad Request (400).
/// </summary>
/// <param name="reason">Reason.</param>
/// <returns>New DreamMessage.</returns>
public static DreamMessage BadRequest(string reason) {
_log.DebugFormat("Response: Bad Request - {0}{1}", reason, DebugOnly_GetRequestPath());
return new DreamMessage(DreamStatus.BadRequest, null, GetDefaultErrorResponse(DreamStatus.BadRequest, "Bad Request", reason));
}
/// <summary>
/// New Message with HTTP status: Not Implemented (501).
/// </summary>
/// <param name="reason">Reason.</param>
/// <returns>New DreamMessage.</returns>
public static DreamMessage NotImplemented(string reason) {
_log.DebugFormat("Response: Not Implemented - {0}{1}", reason, DebugOnly_GetRequestPath());
return new DreamMessage(DreamStatus.NotImplemented, null, GetDefaultErrorResponse(DreamStatus.NotImplemented, "Not Implemented", reason));
}
/// <summary>
/// New Message with HTTP status: Conflict (409).
/// </summary>
/// <param name="doc">Message body.</param>
/// <returns>New DreamMessage.</returns>
public static DreamMessage Conflict(XDoc doc) {
_log.DebugMethodCall("Response: Conflict");
return new DreamMessage(DreamStatus.Conflict, null, doc);
}
/// <summary>
/// New Message with HTTP status: Conflict (409).
/// </summary>
/// <param name="reason">Reason.</param>
/// <returns>New DreamMessage.</returns>
public static DreamMessage Conflict(string reason) {
_log.DebugFormat("Response: Conflict - {0}{1}", reason, DebugOnly_GetRequestPath());
return new DreamMessage(DreamStatus.Conflict, null, GetDefaultErrorResponse(DreamStatus.Conflict, "Conflict", reason));
}
/// <summary>
/// New Message with HTTP status: Found (302)
/// </summary>
/// <param name="uri">Redirect target.</param>
/// <returns>New DreamMessage.</returns>
public static DreamMessage Redirect(XUri uri) {
DreamMessage result = new DreamMessage(DreamStatus.Found, null, XDoc.Empty);
result.Headers.Location = uri;
return result;
}
/// <summary>
/// New Message with HTTP status: Unauthorized (401)
/// </summary>
/// <param name="accessRealm">Access Realm.</param>
/// <param name="reason">Reason.</param>
/// <returns>New DreamMessage.</returns>
public static DreamMessage AccessDenied(string accessRealm, string reason) {
_log.DebugFormat("Response: Unauthorized - {0}{1}", reason, DebugOnly_GetRequestPath());
DreamMessage result = new DreamMessage(DreamStatus.Unauthorized, null, GetDefaultErrorResponse(DreamStatus.Unauthorized, "Unauthorized", reason));
if(!string.IsNullOrWhiteSpace(accessRealm)) {
result.Headers.Authenticate = string.Format("Basic realm=\"{0}\"", accessRealm);
}
return result;
}
/// <summary>
/// New Message with HTTP status: LicenseRequired (402)
/// </summary>
/// <param name="reason">Reason.</param>
/// <returns>New DreamMessage.</returns>
public static DreamMessage LicenseRequired(string reason) {
_log.DebugFormat("Response: LicenseRequired - {0}{1}", reason, DebugOnly_GetRequestPath());
return new DreamMessage(DreamStatus.LicenseRequired, null, GetDefaultErrorResponse(DreamStatus.LicenseRequired, "LicenseRequired", reason));
}
/// <summary>
/// New Message with HTTP status: Forbidden (403)
/// </summary>
/// <param name="reason">Reason.</param>
/// <returns>New DreamMessage.</returns>
public static DreamMessage Forbidden(string reason) {
_log.DebugFormat("Response: Forbidden - {0}{1}", reason, DebugOnly_GetRequestPath());
return new DreamMessage(DreamStatus.Forbidden, null, GetDefaultErrorResponse(DreamStatus.Forbidden, "Forbidden", reason));
}
/// <summary>
/// New Message with HTTP status: Method Not Allowed (405)
/// </summary>
/// <param name="allowedMethods">Array of allowed request Verbs.</param>
/// <param name="reason">Reason.</param>
/// <returns>New DreamMessage.</returns>
public static DreamMessage MethodNotAllowed(string[] allowedMethods, string reason) {
_log.DebugFormat("Response: MethodNotAllowed - {0}{1}", reason, DebugOnly_GetRequestPath());
DreamMessage result = new DreamMessage(DreamStatus.MethodNotAllowed, null, GetDefaultErrorResponse(DreamStatus.MethodNotAllowed, "Method Not Allowed", reason));
result.Headers.Allow = string.Join(",", allowedMethods);
return result;
}
/// <summary>
/// New Message with HTTP status: Internal Error (500)
/// </summary>
/// <returns>New DreamMessage.</returns>
public static DreamMessage InternalError() {
_log.DebugMethodCall("Response: Internal Error");
return new DreamMessage(DreamStatus.InternalError, null, XDoc.Empty);
}
/// <summary>
/// New Message with HTTP status: Internal Error (500)
/// </summary>
/// <param name="text">Error message.</param>
/// <returns>New DreamMessage.</returns>
public static DreamMessage InternalError(string text) {
_log.DebugMethodCall("Response: Internal Error", text);
return new DreamMessage(DreamStatus.InternalError, null, GetDefaultErrorResponse(DreamStatus.InternalError, "Internal Error", text));
}
/// <summary>
/// New Message with HTTP status: Internal Error (500)
/// </summary>
/// <param name="e">Exception responsible for internal error.</param>
/// <returns>New DreamMessage.</returns>
public static DreamMessage InternalError(Exception e) {
_log.DebugExceptionMethodCall(e, "Response: Internal Error");
return new DreamMessage(DreamStatus.InternalError, null, MimeType.DREAM_EXCEPTION, (e != null) ? new XException(e) : XDoc.Empty);
}
/// <summary>
/// Create a message from a file.
/// </summary>
/// <param name="filename">Path to file.</param>
/// <returns>New DreamMessage.</returns>
public static DreamMessage FromFile(string filename) {
return FromFile(filename, false);
}
/// <summary>
/// Create a message from a file.
/// </summary>
/// <param name="filename">Path to file.</param>
/// <param name="omitFileContents">If <see langword="True"/> the contents of the file are omitted.</param>
/// <returns>New DreamMessage.</returns>
public static DreamMessage FromFile(string filename, bool omitFileContents) {
return FromFile(filename, null, null, omitFileContents);
}
/// <summary>
/// Create a message from a file.
/// </summary>
/// <param name="filename">Path to file.</param>
/// <param name="contentType">Mime-Type of message.</param>
/// <param name="displayName">File name to emit.</param>
/// <param name="omitFileContents">If <see langword="True"/> the contents of the file are omitted.</param>
/// <returns>New DreamMessage.</returns>
public static DreamMessage FromFile(string filename, MimeType contentType, string displayName, bool omitFileContents) {
if(contentType == null) {
contentType = MimeType.FromFileExtension(filename);
}
DreamMessage result;
if(omitFileContents) {
result = new DreamMessage(DreamStatus.Ok, null, contentType, new FileInfo(filename).Length, Stream.Null);
} else {
FileStream stream = File.OpenRead(filename);
result = new DreamMessage(DreamStatus.Ok, null, contentType, stream.Length, stream);
}
if((displayName != null) && !StringUtil.EqualsInvariantIgnoreCase(Path.GetFileName(filename), displayName)) {
result.Headers.ContentDisposition = new ContentDisposition(true, File.GetLastWriteTimeUtc(filename), null, null, displayName, result.ContentLength);
}
return result;
}
/// <summary>
/// Create a new message tied to a Stream for streaming data.
/// </summary>
/// <param name="mime">Content Mime-Type.</param>
/// <param name="message">The message to be created.</param>
/// <param name="writer">The stream that will supply the streaming data.</param>
public static void ForStreaming(MimeType mime, out DreamMessage message, out Stream writer) {
Stream reader;
StreamUtil.CreatePipe(out writer, out reader);
message = Ok(mime, -1, reader);
}
/// <summary>
/// Get a status string from a DreamMessage or null, or null, if the message is null.
/// </summary>
/// <param name="message">A DreamMessage instance or null.</param>
/// <returns>The <see cref="Status"/> as an information string message if a non-null message was provide, or null otherwise.</returns>
public static string GetStatusStringOrNull(DreamMessage message) {
if(message != null) {
return string.Format("HTTP Status: {0}({1})", message.Status, (int)message.Status);
}
return null;
}
private static XDoc GetDefaultErrorResponse(DreamStatus status, string title, string message) {
XDoc result = new XDoc("error");
DreamContext context = DreamContext.CurrentOrNull;
if((context != null) && (context.Env.Self != null)) {
result.WithXslTransform(context.AsPublicUri(context.Env.Self).At("resources", "error.xslt").Path);
}
result.Elem("status", (int)status).Elem("title", title).Elem("message", message);
if(context != null) {
result.Elem("uri", context.Uri);
}
return result;
}
private static string DebugOnly_GetRequestPath() {
if(!_log.IsDebugEnabled) {
return null;
}
DreamContext context = DreamContext.CurrentOrNull;
if(context == null) {
return null;
}
return ", path: " + context.Uri.Path;
}
//--- Fields ---
/// <summary>
/// Http Status of message.
/// </summary>
public readonly DreamStatus Status;
/// <summary>
/// Message Http header collection.
/// </summary>
public readonly DreamHeaders Headers;
private readonly bool _noContent;
private XDoc _doc;
private byte[] _bytes;
private Stream _stream;
private bool _streamOpen;
private System.Diagnostics.StackTrace _stackTrace = DebugUtil.GetStackTrace();
//--- Constructors ---
/// <summary>
/// Create a new message.
/// </summary>
/// <param name="status">Http status.</param>
/// <param name="headers">Header collection.</param>
public DreamMessage(DreamStatus status, DreamHeaders headers) {
this.Status = status;
this.Headers = new DreamHeaders(headers);
_bytes = new byte[0];
_noContent = true;
}
/// <summary>
/// Create a new message.
/// </summary>
/// <param name="status">Http status.</param>
/// <param name="headers">Header collection.</param>
/// <param name="contentType">Content Mime-Type.</param>
/// <param name="doc">Message body.</param>
public DreamMessage(DreamStatus status, DreamHeaders headers, MimeType contentType, XDoc doc) {
if(doc == null) {
throw new ArgumentNullException("doc");
}
this.Status = status;
this.Headers = new DreamHeaders(headers);
// check if document is empty
if(doc.IsEmpty) {
// we store empty XML documents as text content; it causes less confusion for browsers
this.Headers.ContentType = MimeType.TEXT;
this.Headers.ContentLength = 0L;
_doc = doc;
_bytes = new byte[0];
} else {
this.Headers.ContentType = contentType ?? MimeType.XML;
_doc = doc.Clone();
}
}
/// <summary>
/// Create a new message.
/// </summary>
/// <param name="status">Http status.</param>
/// <param name="headers">Header collection.</param>
/// <param name="doc">Message body.</param>
public DreamMessage(DreamStatus status, DreamHeaders headers, XDoc doc) : this(status, headers, MimeType.XML, doc) { }
/// <summary>
/// Create a new message.
/// </summary>
/// <param name="status">Http status.</param>
/// <param name="headers">Header collection.</param>
/// <param name="contentType">Content Mime-Type</param>
/// <param name="contentLength">Content byte langth</param>
/// <param name="stream">Stream to uas as the source for the message's content.</param>
public DreamMessage(DreamStatus status, DreamHeaders headers, MimeType contentType, long contentLength, Stream stream) {
this.Status = status;
this.Headers = new DreamHeaders(headers);
if(contentLength != -1) {
this.Headers.ContentLength = contentLength;
}
this.Headers.ContentType = contentType ?? MimeType.DefaultMimeType;
// set stream
_stream = stream ?? Stream.Null;
_streamOpen = !_stream.IsStreamMemorized();
}
/// <summary>
/// Create a new message.
/// </summary>
/// <param name="status">Http status.</param>
/// <param name="headers">Header collection.</param>
/// <param name="contentType">Content Mime-Type.</param>
/// <param name="bytes">Message body.</param>
public DreamMessage(DreamStatus status, DreamHeaders headers, MimeType contentType, byte[] bytes) {
if(bytes == null) {
throw new ArgumentNullException("bytes");
}
this.Status = status;
this.Headers = new DreamHeaders(headers);
this.Headers.ContentLength = bytes.LongLength;
this.Headers.ContentType = contentType ?? MimeType.DefaultMimeType;
// set bytes
_bytes = bytes;
}
/// <summary>
/// Create a new message.
/// </summary>
/// <param name="status">Http status.</param>
/// <param name="headers">Header collection.</param>
/// <param name="contentType">Content Mime-Type.</param>
/// <param name="text">Message body.</param>
public DreamMessage(DreamStatus status, DreamHeaders headers, MimeType contentType, string text)
: this(status, headers, contentType, contentType.CharSet.GetBytes(text)) { }
#if DEBUG
/// <summary>
/// Finalizer for DreamMessage to warn and possibly throw an exception if a message with an open stream reaches garbage collection.
/// </summary>
~DreamMessage() {
if(_streamOpen) {
_log.WarnMethodCall("message stream was not closed", _stackTrace);
if(_stackTrace != null) {
throw new Exception("message stream was not closed: " + _stackTrace);
}
}
}
#endif
//--- Properties ---
/// <summary>
/// <see langword="True"/> if the Status indicates a successful response.
/// </summary>
/// <remarks>Requests are always marked as successful. Only responses use the status to convey information.</remarks>
public bool IsSuccessful { get { return (Status >= DreamStatus.Ok) && (Status < DreamStatus.MultipleChoices); } }
/// <summary>
/// Message Content Mime-Type.
/// </summary>
public MimeType ContentType { get { return Headers.ContentType ?? MimeType.DefaultMimeType; } }
/// <summary>
/// Message contains cookies.
/// </summary>
public bool HasCookies { get { return Headers.HasCookies; } }
/// <summary>
/// Cookies.
/// </summary>
public List<DreamCookie> Cookies { get { return Headers.Cookies; } }
/// <summary>
/// Content Disposition Header.
/// </summary>
public ContentDisposition ContentDisposition { get { return Headers.ContentDisposition; } }
/// <summary>
/// <see langword="True"/> if the underlying content stream is closed.
/// </summary>
public bool IsClosed { get { return (_doc == null) && (_stream == null) && (_bytes == null); } }
/// <summary>
/// Total number of bytes in message.
/// </summary>
public long ContentLength {
get {
long? result = Headers.ContentLength;
if(result != null) {
return result.Value;
}
if(IsClosed) {
return 0;
} else if(_bytes != null) {
return _bytes.LongLength;
} else if(_stream.IsStreamMemorized()) {
return _stream.Length;
}
return -1;
}
}
/// <summary>
/// <see langword="True"/> if the message content can be retrieved as an <see cref="XDoc"/> instance.
/// </summary>
public bool HasDocument {
get {
if(_doc == null) {
MimeType mime = ContentType;
return mime.IsXml || mime.Match(MimeType.FORM_URLENCODED);
}
return true;
}
}
/// <summary>
/// Can this message be clone?
/// </summary>
/// <remarks>In general only false for closed messages and messages with non-memorized streams.</remarks>
public bool IsCloneable {
get {
return !IsClosed && (_stream == null || _stream == Stream.Null || _stream.IsStreamMemorized());
}
}
//--- Methods ---
/// <summary>
/// Get the message body as a document.
/// </summary>
/// <returns>XDoc instance.</returns>
public XDoc ToDocument() {
MakeDocument();
return _doc;
}
/// <summary>
/// Get the message body as a Stream.
/// </summary>
/// <returns>Content Stream.</returns>
public Stream ToStream() {
MakeStream();
return _stream;
}
/// <summary>
/// Convert the message body into a byte array.
/// </summary>
/// <remarks>This method is potentially thread-blocking. Please avoid using it if possible.</remarks>
/// <returns>Array of bytes.</returns>
#if WARN_ON_SYNC
[Obsolete("This method is potentially thread-blocking. Please avoid using it if possible.")]
#endif
public byte[] ToBytes() {
MakeBytes();
return _bytes;
}
/// <summary>
/// Convert the message body to plain text.
/// </summary>
/// <returns>Content text.</returns>
public string ToText() {
return ContentType.CharSet.GetString(ToBytes());
}
/// <summary>
/// Convert the message body to a text reader.
/// </summary>
/// <returns>New text reader instance.</returns>
public TextReader ToTextReader() {
return new StreamReader(ToStream(), ContentType.CharSet);
}
/// <summary>
/// Set Caching headers.
/// </summary>
/// <param name="timestamp">Last modified timestamp.</param>
public void SetCacheMustRevalidate(DateTime timestamp) {
Headers.CacheControl = "must-revalidate,private";
Headers.Vary = "Accept-Encoding";
Headers.LastModified = timestamp;
Headers.ETag = timestamp.ToUniversalTime().ToString("r");
}
/// <summary>
/// Check if the cache needs ot be re-validated
/// </summary>
/// <param name="timestamp">Last modified timestamp.</param>
/// <returns><see langword="True"/> if the cache needs to be re-validated.</returns>
public bool CheckCacheRevalidation(DateTime timestamp) {
DateTime rounded = new DateTime(timestamp.Year, timestamp.Month, timestamp.Day, timestamp.Hour, timestamp.Minute, timestamp.Second, timestamp.Kind);
// check if an 'If-Modified-Since' header is present
DateTime ifModSince = Headers.IfModifiedSince ?? DateTime.MinValue;
if(rounded <= ifModSince) {
return true;
}
// check if an 'ETag' header is present
string ifNoneMatch = Headers.IfNoneMatch;
if(!string.IsNullOrEmpty(ifNoneMatch)) {
if(timestamp.ToUniversalTime().ToString("r") == ifNoneMatch) {
return true;
}
}
// either there was not validation check or the cached copy is out-of-date
return false;
}
/// <summary>
/// Clone the current message.
/// </summary>
/// <returns>A new message instance.</returns>
public DreamMessage Clone() {
if(!IsCloneable) {
throw new InvalidOperationException("The current message cannot be cloned. It is either closed or contains a payload that cannot be duplicated.");
}
DreamMessage result;
if(_noContent) {
result = new DreamMessage(Status, Headers);
} else if(_doc != null) {
result = new DreamMessage(Status, Headers, _doc.Clone());
} else if(_stream == Stream.Null || (_stream != null && _stream.IsStreamMemorized())) {
_stream.Position = 0;
var copy = new MemoryStream((int)_stream.Length);
_stream.CopyToStream(copy, _stream.Length);
_stream.Position = 0;
copy.Position = 0;
result = new DreamMessage(Status, Headers, ContentType, ContentLength, copy);
} else {
var bytes = ToBytes();
result = new DreamMessage(Status, Headers, ContentType, bytes);
// length may differ for HEAD requests
if(bytes.LongLength != ContentLength) {
result.Headers.ContentLength = bytes.LongLength;
}
}
if(HasCookies) {
result.Cookies.AddRange(Cookies);
}
return result;
}
/// <summary>
/// Close any underlying stream on the message.
/// </summary>
public void Close() {
if(_stream != null) {
_stream.Close();
_streamOpen = false;
}
_doc = null;
_stream = null;
_bytes = null;
}
/// <summary>
/// Memorize the content stream.
/// </summary>
/// <param name="result">The synchronization handle to return.</param>
/// <returns>Synchronization handle for memorization completion.</returns>
public Result Memorize(Result result) {
return Memorize(-1, result);
}
/// <summary>
/// Memorize the content stream.
/// </summary>
/// <param name="result">The synchronization handle to return.</param>
/// <param name="max">Maximum number of bytes to memorize.</param>
/// <returns>Synchronization handle for memorization completion.</returns>
public Result Memorize(long max, Result result) {
// check if we need to call Memorize_Helper()
if((_stream == null) || _stream.IsStreamMemorized()) {
// message already contains a document or byte array or a memory stream
// we don't need to memorize those
result.Return();
return result;
}
return Coroutine.Invoke(Memorize_Helper, max, result);
}
private Yield Memorize_Helper(long max, Result result) {
// NOTE (steveb): this method is used to load an external stream into memory; this alleviates the problem of streams not being closed for simple operations
if(max < 0) {
max = long.MaxValue - 1;
}
// check if we already know that the stream will not fit
long length = ContentLength;
if(length > max) {
// mark stream as closed
_stream.Close();
_stream = null;
_streamOpen = false;
// throw size exceeded exception
result.Throw(new InternalBufferOverflowException("message body exceeded max size"));
yield break;
}
if(length < 0) {
length = long.MaxValue;
}
// NOTE: the content-length and body length may differ (e.g. HEAD verb)
// copy contents asynchronously
var buffer = new MemoryStream();
Result<long> res;
// TODO (steveb): use WithCleanup() to dispose of resources in case of failure
yield return res = _stream.CopyToStream(buffer, Math.Min(length, max + 1), new Result<long>(TimeSpan.MaxValue)).Catch();
// mark stream as closed
_stream.Close();
_stream = null;
_streamOpen = false;
// confirm successful outcome for asynchronous operation
res.Confirm();
if(buffer.Length > max) {
result.Throw(new InternalBufferOverflowException("message body exceeded max size"));
yield break;
}
buffer.Position = 0;
_stream = buffer;
result.Return();
}
/// <summary>
/// Convert the message into a string.
/// </summary>
/// <returns>String.</returns>
public override string ToString() {
return new XMessage(this).ToString();
}
private void MakeDocument() {
if(IsClosed) {
throw new InvalidOperationException("message has already been closed");
}
if(_doc == null) {
try {
MakeStream();
_doc = XDocFactory.From(_stream, ContentType);
if((_doc == null) || _doc.IsEmpty) {
throw new InvalidDataException(string.Format("message body with content type '{0}' is not well-formed xml", ContentType));
}
} finally {
if(_stream != null) {
_stream.Close();
_stream = null;
_streamOpen = false;
}
}
}
}
private void MakeStream() {
if(IsClosed) {
throw new InvalidOperationException("message has already been closed");
}
if(_stream == null) {
if(_bytes != null) {
_stream = new MemoryStream(_bytes, 0, _bytes.Length, true, true);
} else {
var stream = new MemoryStream();
_doc.WriteTo(stream, ContentType.CharSet);
stream.Position = 0;
_stream = stream;
}
_streamOpen = false;
// NOTE: the content-length and body length may differ (e.g. HEAD verb)
// update content-length if it isn't set yet
if(Headers.ContentLength == null) {
Headers.ContentLength = _stream.Length;
}
}
}
private void MakeBytes() {
if(IsClosed) {
throw new InvalidOperationException("message has already been closed");
}
if(_bytes == null) {
if(_stream == null) {
Encoding encoding = ContentType.CharSet;
_bytes = encoding.GetBytes(_doc.ToString(encoding));
} else if(_stream is MemoryStream) {
_bytes = ((MemoryStream)_stream).ToArray();
_stream = null;
_streamOpen = false;
} else {
// NOTE: the content-length and body length may differ (e.g. HEAD verb)
try {
var buffer = new MemoryStream();
_stream.CopyToStream(buffer, ContentLength);
_bytes = buffer.ToArray();
} finally {
_stream.Close();
_stream = null;
_streamOpen = false;
}
}
}
}
}
}
| |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Cloud.Debugger.V2
{
/// <summary>
/// Settings for a <see cref="Debugger2Client"/>.
/// </summary>
public sealed partial class Debugger2Settings : ServiceSettingsBase
{
/// <summary>
/// Get a new instance of the default <see cref="Debugger2Settings"/>.
/// </summary>
/// <returns>
/// A new instance of the default <see cref="Debugger2Settings"/>.
/// </returns>
public static Debugger2Settings GetDefault() => new Debugger2Settings();
/// <summary>
/// Constructs a new <see cref="Debugger2Settings"/> object with default settings.
/// </summary>
public Debugger2Settings() { }
private Debugger2Settings(Debugger2Settings existing) : base(existing)
{
GaxPreconditions.CheckNotNull(existing, nameof(existing));
SetBreakpointSettings = existing.SetBreakpointSettings;
GetBreakpointSettings = existing.GetBreakpointSettings;
DeleteBreakpointSettings = existing.DeleteBreakpointSettings;
ListBreakpointsSettings = existing.ListBreakpointsSettings;
ListDebuggeesSettings = existing.ListDebuggeesSettings;
OnCopy(existing);
}
partial void OnCopy(Debugger2Settings existing);
/// <summary>
/// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry
/// for "Idempotent" <see cref="Debugger2Client"/> RPC methods.
/// </summary>
/// <remarks>
/// The eligible RPC <see cref="StatusCode"/>s for retry for "Idempotent" RPC methods are:
/// <list type="bullet">
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// </remarks>
public static Predicate<RpcException> IdempotentRetryFilter { get; } =
RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Unavailable);
/// <summary>
/// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry
/// for "NonIdempotent" <see cref="Debugger2Client"/> RPC methods.
/// </summary>
/// <remarks>
/// There are no RPC <see cref="StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods.
/// </remarks>
public static Predicate<RpcException> NonIdempotentRetryFilter { get; } =
RetrySettings.FilterForStatusCodes();
/// <summary>
/// "Default" retry backoff for <see cref="Debugger2Client"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" retry backoff for <see cref="Debugger2Client"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" retry backoff for <see cref="Debugger2Client"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial delay: 100 milliseconds</description></item>
/// <item><description>Maximum delay: 60000 milliseconds</description></item>
/// <item><description>Delay multiplier: 1.3</description></item>
/// </list>
/// </remarks>
public static BackoffSettings GetDefaultRetryBackoff() => new BackoffSettings(
delay: TimeSpan.FromMilliseconds(100),
maxDelay: TimeSpan.FromMilliseconds(60000),
delayMultiplier: 1.3
);
/// <summary>
/// "Default" timeout backoff for <see cref="Debugger2Client"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" timeout backoff for <see cref="Debugger2Client"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" timeout backoff for <see cref="Debugger2Client"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial timeout: 60000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Maximum timeout: 60000 milliseconds</description></item>
/// </list>
/// </remarks>
public static BackoffSettings GetDefaultTimeoutBackoff() => new BackoffSettings(
delay: TimeSpan.FromMilliseconds(60000),
maxDelay: TimeSpan.FromMilliseconds(60000),
delayMultiplier: 1.0
);
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>Debugger2Client.SetBreakpoint</c> and <c>Debugger2Client.SetBreakpointAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>Debugger2Client.SetBreakpoint</c> and
/// <c>Debugger2Client.SetBreakpointAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 60000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 60000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description>No status codes</description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public CallSettings SetBreakpointSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)),
retryFilter: NonIdempotentRetryFilter
)));
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>Debugger2Client.GetBreakpoint</c> and <c>Debugger2Client.GetBreakpointAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>Debugger2Client.GetBreakpoint</c> and
/// <c>Debugger2Client.GetBreakpointAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 60000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 60000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public CallSettings GetBreakpointSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>Debugger2Client.DeleteBreakpoint</c> and <c>Debugger2Client.DeleteBreakpointAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>Debugger2Client.DeleteBreakpoint</c> and
/// <c>Debugger2Client.DeleteBreakpointAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 60000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 60000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public CallSettings DeleteBreakpointSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>Debugger2Client.ListBreakpoints</c> and <c>Debugger2Client.ListBreakpointsAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>Debugger2Client.ListBreakpoints</c> and
/// <c>Debugger2Client.ListBreakpointsAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 60000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 60000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public CallSettings ListBreakpointsSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>Debugger2Client.ListDebuggees</c> and <c>Debugger2Client.ListDebuggeesAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>Debugger2Client.ListDebuggees</c> and
/// <c>Debugger2Client.ListDebuggeesAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 60000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 60000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public CallSettings ListDebuggeesSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// Creates a deep clone of this object, with all the same property values.
/// </summary>
/// <returns>A deep clone of this <see cref="Debugger2Settings"/> object.</returns>
public Debugger2Settings Clone() => new Debugger2Settings(this);
}
/// <summary>
/// Debugger2 client wrapper, for convenient use.
/// </summary>
public abstract partial class Debugger2Client
{
/// <summary>
/// The default endpoint for the Debugger2 service, which is a host of "clouddebugger.googleapis.com" and a port of 443.
/// </summary>
public static ServiceEndpoint DefaultEndpoint { get; } = new ServiceEndpoint("clouddebugger.googleapis.com", 443);
/// <summary>
/// The default Debugger2 scopes.
/// </summary>
/// <remarks>
/// The default Debugger2 scopes are:
/// <list type="bullet">
/// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item>
/// <item><description>"https://www.googleapis.com/auth/cloud_debugger"</description></item>
/// </list>
/// </remarks>
public static IReadOnlyList<string> DefaultScopes { get; } = new ReadOnlyCollection<string>(new string[] {
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud_debugger",
});
private static readonly ChannelPool s_channelPool = new ChannelPool(DefaultScopes);
// Note: we could have parameterless overloads of Create and CreateAsync,
// documented to just use the default endpoint, settings and credentials.
// Pros:
// - Might be more reassuring on first use
// - Allows method group conversions
// Con: overloads!
/// <summary>
/// Asynchronously creates a <see cref="Debugger2Client"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary.
/// </summary>
/// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="Debugger2Settings"/>.</param>
/// <returns>The task representing the created <see cref="Debugger2Client"/>.</returns>
public static async Task<Debugger2Client> CreateAsync(ServiceEndpoint endpoint = null, Debugger2Settings settings = null)
{
Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false);
return Create(channel, settings);
}
/// <summary>
/// Synchronously creates a <see cref="Debugger2Client"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary.
/// </summary>
/// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="Debugger2Settings"/>.</param>
/// <returns>The created <see cref="Debugger2Client"/>.</returns>
public static Debugger2Client Create(ServiceEndpoint endpoint = null, Debugger2Settings settings = null)
{
Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint);
return Create(channel, settings);
}
/// <summary>
/// Creates a <see cref="Debugger2Client"/> which uses the specified channel for remote operations.
/// </summary>
/// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param>
/// <param name="settings">Optional <see cref="Debugger2Settings"/>.</param>
/// <returns>The created <see cref="Debugger2Client"/>.</returns>
public static Debugger2Client Create(Channel channel, Debugger2Settings settings = null)
{
GaxPreconditions.CheckNotNull(channel, nameof(channel));
Debugger2.Debugger2Client grpcClient = new Debugger2.Debugger2Client(channel);
return new Debugger2ClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create(ServiceEndpoint, Debugger2Settings)"/>
/// and <see cref="CreateAsync(ServiceEndpoint, Debugger2Settings)"/>. Channels which weren't automatically
/// created are not affected.
/// </summary>
/// <remarks>After calling this method, further calls to <see cref="Create(ServiceEndpoint, Debugger2Settings)"/>
/// and <see cref="CreateAsync(ServiceEndpoint, Debugger2Settings)"/> will create new channels, which could
/// in turn be shut down by another call to this method.</remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync();
/// <summary>
/// The underlying gRPC Debugger2 client.
/// </summary>
public virtual Debugger2.Debugger2Client GrpcClient
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// Sets the breakpoint to the debuggee.
/// </summary>
/// <param name="debuggeeId">
/// ID of the debuggee where the breakpoint is to be set.
/// </param>
/// <param name="breakpoint">
/// Breakpoint specification to set.
/// The field `location` of the breakpoint must be set.
/// </param>
/// <param name="clientVersion">
/// The client version making the call.
/// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`).
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<SetBreakpointResponse> SetBreakpointAsync(
string debuggeeId,
Breakpoint breakpoint,
string clientVersion,
CallSettings callSettings = null) => SetBreakpointAsync(
new SetBreakpointRequest
{
DebuggeeId = GaxPreconditions.CheckNotNullOrEmpty(debuggeeId, nameof(debuggeeId)),
Breakpoint = GaxPreconditions.CheckNotNull(breakpoint, nameof(breakpoint)),
ClientVersion = GaxPreconditions.CheckNotNullOrEmpty(clientVersion, nameof(clientVersion)),
},
callSettings);
/// <summary>
/// Sets the breakpoint to the debuggee.
/// </summary>
/// <param name="debuggeeId">
/// ID of the debuggee where the breakpoint is to be set.
/// </param>
/// <param name="breakpoint">
/// Breakpoint specification to set.
/// The field `location` of the breakpoint must be set.
/// </param>
/// <param name="clientVersion">
/// The client version making the call.
/// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`).
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<SetBreakpointResponse> SetBreakpointAsync(
string debuggeeId,
Breakpoint breakpoint,
string clientVersion,
CancellationToken cancellationToken) => SetBreakpointAsync(
debuggeeId,
breakpoint,
clientVersion,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Sets the breakpoint to the debuggee.
/// </summary>
/// <param name="debuggeeId">
/// ID of the debuggee where the breakpoint is to be set.
/// </param>
/// <param name="breakpoint">
/// Breakpoint specification to set.
/// The field `location` of the breakpoint must be set.
/// </param>
/// <param name="clientVersion">
/// The client version making the call.
/// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`).
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual SetBreakpointResponse SetBreakpoint(
string debuggeeId,
Breakpoint breakpoint,
string clientVersion,
CallSettings callSettings = null) => SetBreakpoint(
new SetBreakpointRequest
{
DebuggeeId = GaxPreconditions.CheckNotNullOrEmpty(debuggeeId, nameof(debuggeeId)),
Breakpoint = GaxPreconditions.CheckNotNull(breakpoint, nameof(breakpoint)),
ClientVersion = GaxPreconditions.CheckNotNullOrEmpty(clientVersion, nameof(clientVersion)),
},
callSettings);
/// <summary>
/// Sets the breakpoint to the debuggee.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<SetBreakpointResponse> SetBreakpointAsync(
SetBreakpointRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Sets the breakpoint to the debuggee.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual SetBreakpointResponse SetBreakpoint(
SetBreakpointRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets breakpoint information.
/// </summary>
/// <param name="debuggeeId">
/// ID of the debuggee whose breakpoint to get.
/// </param>
/// <param name="breakpointId">
/// ID of the breakpoint to get.
/// </param>
/// <param name="clientVersion">
/// The client version making the call.
/// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`).
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<GetBreakpointResponse> GetBreakpointAsync(
string debuggeeId,
string breakpointId,
string clientVersion,
CallSettings callSettings = null) => GetBreakpointAsync(
new GetBreakpointRequest
{
DebuggeeId = GaxPreconditions.CheckNotNullOrEmpty(debuggeeId, nameof(debuggeeId)),
BreakpointId = GaxPreconditions.CheckNotNullOrEmpty(breakpointId, nameof(breakpointId)),
ClientVersion = GaxPreconditions.CheckNotNullOrEmpty(clientVersion, nameof(clientVersion)),
},
callSettings);
/// <summary>
/// Gets breakpoint information.
/// </summary>
/// <param name="debuggeeId">
/// ID of the debuggee whose breakpoint to get.
/// </param>
/// <param name="breakpointId">
/// ID of the breakpoint to get.
/// </param>
/// <param name="clientVersion">
/// The client version making the call.
/// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`).
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<GetBreakpointResponse> GetBreakpointAsync(
string debuggeeId,
string breakpointId,
string clientVersion,
CancellationToken cancellationToken) => GetBreakpointAsync(
debuggeeId,
breakpointId,
clientVersion,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Gets breakpoint information.
/// </summary>
/// <param name="debuggeeId">
/// ID of the debuggee whose breakpoint to get.
/// </param>
/// <param name="breakpointId">
/// ID of the breakpoint to get.
/// </param>
/// <param name="clientVersion">
/// The client version making the call.
/// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`).
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual GetBreakpointResponse GetBreakpoint(
string debuggeeId,
string breakpointId,
string clientVersion,
CallSettings callSettings = null) => GetBreakpoint(
new GetBreakpointRequest
{
DebuggeeId = GaxPreconditions.CheckNotNullOrEmpty(debuggeeId, nameof(debuggeeId)),
BreakpointId = GaxPreconditions.CheckNotNullOrEmpty(breakpointId, nameof(breakpointId)),
ClientVersion = GaxPreconditions.CheckNotNullOrEmpty(clientVersion, nameof(clientVersion)),
},
callSettings);
/// <summary>
/// Gets breakpoint information.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<GetBreakpointResponse> GetBreakpointAsync(
GetBreakpointRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets breakpoint information.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual GetBreakpointResponse GetBreakpoint(
GetBreakpointRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Deletes the breakpoint from the debuggee.
/// </summary>
/// <param name="debuggeeId">
/// ID of the debuggee whose breakpoint to delete.
/// </param>
/// <param name="breakpointId">
/// ID of the breakpoint to delete.
/// </param>
/// <param name="clientVersion">
/// The client version making the call.
/// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`).
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task DeleteBreakpointAsync(
string debuggeeId,
string breakpointId,
string clientVersion,
CallSettings callSettings = null) => DeleteBreakpointAsync(
new DeleteBreakpointRequest
{
DebuggeeId = GaxPreconditions.CheckNotNullOrEmpty(debuggeeId, nameof(debuggeeId)),
BreakpointId = GaxPreconditions.CheckNotNullOrEmpty(breakpointId, nameof(breakpointId)),
ClientVersion = GaxPreconditions.CheckNotNullOrEmpty(clientVersion, nameof(clientVersion)),
},
callSettings);
/// <summary>
/// Deletes the breakpoint from the debuggee.
/// </summary>
/// <param name="debuggeeId">
/// ID of the debuggee whose breakpoint to delete.
/// </param>
/// <param name="breakpointId">
/// ID of the breakpoint to delete.
/// </param>
/// <param name="clientVersion">
/// The client version making the call.
/// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`).
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task DeleteBreakpointAsync(
string debuggeeId,
string breakpointId,
string clientVersion,
CancellationToken cancellationToken) => DeleteBreakpointAsync(
debuggeeId,
breakpointId,
clientVersion,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Deletes the breakpoint from the debuggee.
/// </summary>
/// <param name="debuggeeId">
/// ID of the debuggee whose breakpoint to delete.
/// </param>
/// <param name="breakpointId">
/// ID of the breakpoint to delete.
/// </param>
/// <param name="clientVersion">
/// The client version making the call.
/// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`).
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual void DeleteBreakpoint(
string debuggeeId,
string breakpointId,
string clientVersion,
CallSettings callSettings = null) => DeleteBreakpoint(
new DeleteBreakpointRequest
{
DebuggeeId = GaxPreconditions.CheckNotNullOrEmpty(debuggeeId, nameof(debuggeeId)),
BreakpointId = GaxPreconditions.CheckNotNullOrEmpty(breakpointId, nameof(breakpointId)),
ClientVersion = GaxPreconditions.CheckNotNullOrEmpty(clientVersion, nameof(clientVersion)),
},
callSettings);
/// <summary>
/// Deletes the breakpoint from the debuggee.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task DeleteBreakpointAsync(
DeleteBreakpointRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Deletes the breakpoint from the debuggee.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual void DeleteBreakpoint(
DeleteBreakpointRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Lists all breakpoints for the debuggee.
/// </summary>
/// <param name="debuggeeId">
/// ID of the debuggee whose breakpoints to list.
/// </param>
/// <param name="clientVersion">
/// The client version making the call.
/// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`).
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<ListBreakpointsResponse> ListBreakpointsAsync(
string debuggeeId,
string clientVersion,
CallSettings callSettings = null) => ListBreakpointsAsync(
new ListBreakpointsRequest
{
DebuggeeId = GaxPreconditions.CheckNotNullOrEmpty(debuggeeId, nameof(debuggeeId)),
ClientVersion = GaxPreconditions.CheckNotNullOrEmpty(clientVersion, nameof(clientVersion)),
},
callSettings);
/// <summary>
/// Lists all breakpoints for the debuggee.
/// </summary>
/// <param name="debuggeeId">
/// ID of the debuggee whose breakpoints to list.
/// </param>
/// <param name="clientVersion">
/// The client version making the call.
/// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`).
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<ListBreakpointsResponse> ListBreakpointsAsync(
string debuggeeId,
string clientVersion,
CancellationToken cancellationToken) => ListBreakpointsAsync(
debuggeeId,
clientVersion,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Lists all breakpoints for the debuggee.
/// </summary>
/// <param name="debuggeeId">
/// ID of the debuggee whose breakpoints to list.
/// </param>
/// <param name="clientVersion">
/// The client version making the call.
/// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`).
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual ListBreakpointsResponse ListBreakpoints(
string debuggeeId,
string clientVersion,
CallSettings callSettings = null) => ListBreakpoints(
new ListBreakpointsRequest
{
DebuggeeId = GaxPreconditions.CheckNotNullOrEmpty(debuggeeId, nameof(debuggeeId)),
ClientVersion = GaxPreconditions.CheckNotNullOrEmpty(clientVersion, nameof(clientVersion)),
},
callSettings);
/// <summary>
/// Lists all breakpoints for the debuggee.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<ListBreakpointsResponse> ListBreakpointsAsync(
ListBreakpointsRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Lists all breakpoints for the debuggee.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual ListBreakpointsResponse ListBreakpoints(
ListBreakpointsRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Lists all the debuggees that the user has access to.
/// </summary>
/// <param name="project">
/// Project number of a Google Cloud project whose debuggees to list.
/// </param>
/// <param name="clientVersion">
/// The client version making the call.
/// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`).
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<ListDebuggeesResponse> ListDebuggeesAsync(
string project,
string clientVersion,
CallSettings callSettings = null) => ListDebuggeesAsync(
new ListDebuggeesRequest
{
Project = GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)),
ClientVersion = GaxPreconditions.CheckNotNullOrEmpty(clientVersion, nameof(clientVersion)),
},
callSettings);
/// <summary>
/// Lists all the debuggees that the user has access to.
/// </summary>
/// <param name="project">
/// Project number of a Google Cloud project whose debuggees to list.
/// </param>
/// <param name="clientVersion">
/// The client version making the call.
/// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`).
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<ListDebuggeesResponse> ListDebuggeesAsync(
string project,
string clientVersion,
CancellationToken cancellationToken) => ListDebuggeesAsync(
project,
clientVersion,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Lists all the debuggees that the user has access to.
/// </summary>
/// <param name="project">
/// Project number of a Google Cloud project whose debuggees to list.
/// </param>
/// <param name="clientVersion">
/// The client version making the call.
/// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`).
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual ListDebuggeesResponse ListDebuggees(
string project,
string clientVersion,
CallSettings callSettings = null) => ListDebuggees(
new ListDebuggeesRequest
{
Project = GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)),
ClientVersion = GaxPreconditions.CheckNotNullOrEmpty(clientVersion, nameof(clientVersion)),
},
callSettings);
/// <summary>
/// Lists all the debuggees that the user has access to.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<ListDebuggeesResponse> ListDebuggeesAsync(
ListDebuggeesRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Lists all the debuggees that the user has access to.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual ListDebuggeesResponse ListDebuggees(
ListDebuggeesRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
}
/// <summary>
/// Debugger2 client wrapper implementation, for convenient use.
/// </summary>
public sealed partial class Debugger2ClientImpl : Debugger2Client
{
private readonly ApiCall<SetBreakpointRequest, SetBreakpointResponse> _callSetBreakpoint;
private readonly ApiCall<GetBreakpointRequest, GetBreakpointResponse> _callGetBreakpoint;
private readonly ApiCall<DeleteBreakpointRequest, Empty> _callDeleteBreakpoint;
private readonly ApiCall<ListBreakpointsRequest, ListBreakpointsResponse> _callListBreakpoints;
private readonly ApiCall<ListDebuggeesRequest, ListDebuggeesResponse> _callListDebuggees;
/// <summary>
/// Constructs a client wrapper for the Debugger2 service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="Debugger2Settings"/> used within this client </param>
public Debugger2ClientImpl(Debugger2.Debugger2Client grpcClient, Debugger2Settings settings)
{
GrpcClient = grpcClient;
Debugger2Settings effectiveSettings = settings ?? Debugger2Settings.GetDefault();
ClientHelper clientHelper = new ClientHelper(effectiveSettings);
_callSetBreakpoint = clientHelper.BuildApiCall<SetBreakpointRequest, SetBreakpointResponse>(
GrpcClient.SetBreakpointAsync, GrpcClient.SetBreakpoint, effectiveSettings.SetBreakpointSettings);
_callGetBreakpoint = clientHelper.BuildApiCall<GetBreakpointRequest, GetBreakpointResponse>(
GrpcClient.GetBreakpointAsync, GrpcClient.GetBreakpoint, effectiveSettings.GetBreakpointSettings);
_callDeleteBreakpoint = clientHelper.BuildApiCall<DeleteBreakpointRequest, Empty>(
GrpcClient.DeleteBreakpointAsync, GrpcClient.DeleteBreakpoint, effectiveSettings.DeleteBreakpointSettings);
_callListBreakpoints = clientHelper.BuildApiCall<ListBreakpointsRequest, ListBreakpointsResponse>(
GrpcClient.ListBreakpointsAsync, GrpcClient.ListBreakpoints, effectiveSettings.ListBreakpointsSettings);
_callListDebuggees = clientHelper.BuildApiCall<ListDebuggeesRequest, ListDebuggeesResponse>(
GrpcClient.ListDebuggeesAsync, GrpcClient.ListDebuggees, effectiveSettings.ListDebuggeesSettings);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void OnConstruction(Debugger2.Debugger2Client grpcClient, Debugger2Settings effectiveSettings, ClientHelper clientHelper);
/// <summary>
/// The underlying gRPC Debugger2 client.
/// </summary>
public override Debugger2.Debugger2Client GrpcClient { get; }
// Partial modifier methods contain '_' to ensure no name conflicts with RPC methods.
partial void Modify_SetBreakpointRequest(ref SetBreakpointRequest request, ref CallSettings settings);
partial void Modify_GetBreakpointRequest(ref GetBreakpointRequest request, ref CallSettings settings);
partial void Modify_DeleteBreakpointRequest(ref DeleteBreakpointRequest request, ref CallSettings settings);
partial void Modify_ListBreakpointsRequest(ref ListBreakpointsRequest request, ref CallSettings settings);
partial void Modify_ListDebuggeesRequest(ref ListDebuggeesRequest request, ref CallSettings settings);
/// <summary>
/// Sets the breakpoint to the debuggee.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task<SetBreakpointResponse> SetBreakpointAsync(
SetBreakpointRequest request,
CallSettings callSettings = null)
{
Modify_SetBreakpointRequest(ref request, ref callSettings);
return _callSetBreakpoint.Async(request, callSettings);
}
/// <summary>
/// Sets the breakpoint to the debuggee.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override SetBreakpointResponse SetBreakpoint(
SetBreakpointRequest request,
CallSettings callSettings = null)
{
Modify_SetBreakpointRequest(ref request, ref callSettings);
return _callSetBreakpoint.Sync(request, callSettings);
}
/// <summary>
/// Gets breakpoint information.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task<GetBreakpointResponse> GetBreakpointAsync(
GetBreakpointRequest request,
CallSettings callSettings = null)
{
Modify_GetBreakpointRequest(ref request, ref callSettings);
return _callGetBreakpoint.Async(request, callSettings);
}
/// <summary>
/// Gets breakpoint information.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override GetBreakpointResponse GetBreakpoint(
GetBreakpointRequest request,
CallSettings callSettings = null)
{
Modify_GetBreakpointRequest(ref request, ref callSettings);
return _callGetBreakpoint.Sync(request, callSettings);
}
/// <summary>
/// Deletes the breakpoint from the debuggee.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task DeleteBreakpointAsync(
DeleteBreakpointRequest request,
CallSettings callSettings = null)
{
Modify_DeleteBreakpointRequest(ref request, ref callSettings);
return _callDeleteBreakpoint.Async(request, callSettings);
}
/// <summary>
/// Deletes the breakpoint from the debuggee.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override void DeleteBreakpoint(
DeleteBreakpointRequest request,
CallSettings callSettings = null)
{
Modify_DeleteBreakpointRequest(ref request, ref callSettings);
_callDeleteBreakpoint.Sync(request, callSettings);
}
/// <summary>
/// Lists all breakpoints for the debuggee.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task<ListBreakpointsResponse> ListBreakpointsAsync(
ListBreakpointsRequest request,
CallSettings callSettings = null)
{
Modify_ListBreakpointsRequest(ref request, ref callSettings);
return _callListBreakpoints.Async(request, callSettings);
}
/// <summary>
/// Lists all breakpoints for the debuggee.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override ListBreakpointsResponse ListBreakpoints(
ListBreakpointsRequest request,
CallSettings callSettings = null)
{
Modify_ListBreakpointsRequest(ref request, ref callSettings);
return _callListBreakpoints.Sync(request, callSettings);
}
/// <summary>
/// Lists all the debuggees that the user has access to.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task<ListDebuggeesResponse> ListDebuggeesAsync(
ListDebuggeesRequest request,
CallSettings callSettings = null)
{
Modify_ListDebuggeesRequest(ref request, ref callSettings);
return _callListDebuggees.Async(request, callSettings);
}
/// <summary>
/// Lists all the debuggees that the user has access to.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override ListDebuggeesResponse ListDebuggees(
ListDebuggeesRequest request,
CallSettings callSettings = null)
{
Modify_ListDebuggeesRequest(ref request, ref callSettings);
return _callListDebuggees.Sync(request, callSettings);
}
}
// Partial classes to enable page-streaming
}
| |
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org.
// ****************************************************************
using System;
using System.IO;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
using System.ComponentModel;
using System.Reflection;
using NUnit.Core;
using NUnit.Core.Filters;
using NUnit.Util;
namespace NUnit.UiKit
{
public delegate void SelectedTestChangedHandler( ITest test );
public delegate void CheckedTestChangedHandler( ITest[] tests );
/// <summary>
/// TestSuiteTreeView is a tree view control
/// specialized for displaying the tests
/// in an assembly. Clients should always
/// use TestNode rather than TreeNode when
/// dealing with this class to be sure of
/// calling the proper methods.
/// </summary>
public class TestSuiteTreeView : TreeView
{
static Logger log = InternalTrace.GetLogger(typeof(TestSuiteTreeView));
#region DisplayStyle Enumeraton
/// <summary>
/// Indicates how a tree should be displayed
/// </summary>
public enum DisplayStyle
{
Auto, // Select based on space available
Expand, // Expand fully
Collapse, // Collpase fully
HideTests // Expand all but the fixtures, leaving
// leaf nodes hidden
}
#endregion
#region TreeStructureChangedException
private class TreeStructureChangedException : Exception
{
public TreeStructureChangedException(string message)
:base( message ) { }
}
#endregion
#region Instance Variables
/// <summary>
/// Hashtable provides direct access to TestNodes
/// </summary>
private Hashtable treeMap = new Hashtable();
/// <summary>
/// The TestNode on which a right click was done
/// </summary>
private TestSuiteTreeNode contextNode;
/// <summary>
/// Whether the browser supports running tests,
/// or just loading and examining them
/// </summary>
private bool runCommandSupported = true;
/// <summary>
/// Whether or not we track progress of tests visibly in the tree
/// </summary>
private bool displayProgress = true;
/// <summary>
/// The properties dialog if displayed
/// </summary>
private TestPropertiesDialog propertiesDialog;
/// <summary>
/// Source of events that the tree responds to and
/// target for the run command.
/// </summary>
private ITestLoader loader;
public System.Windows.Forms.ImageList treeImages;
private System.ComponentModel.IContainer components;
/// <summary>
/// True if the UI should allow a run command to be selected
/// </summary>
private bool runCommandEnabled = false;
private ITest[] runningTests;
private TestFilter categoryFilter = TestFilter.Empty;
private bool suppressEvents = false;
private bool fixtureLoaded = false;
private bool showInconclusiveResults = false;
#endregion
#region Construction and Initialization
public TestSuiteTreeView()
{
InitializeComponent();
this.ContextMenu = new System.Windows.Forms.ContextMenu();
this.ContextMenu.Popup += new System.EventHandler( ContextMenu_Popup );
LoadAlternateImages();
Services.UserSettings.Changed += new SettingsEventHandler(UserSettings_Changed);
}
private void UserSettings_Changed(object sender, SettingsEventArgs args)
{
if (args.SettingName == "Gui.TestTree.AlternateImageSet")
{
LoadAlternateImages();
Invalidate();
}
}
private void LoadAlternateImages()
{
string imageSet = Services.UserSettings.GetSetting("Gui.TestTree.AlternateImageSet") as string;
if (imageSet != null)
{
string[] imageNames = { "Skipped", "Failure", "Success", "Ignored", "Inconclusive" };
for (int index = 0; index < imageNames.Length; index++)
LoadAlternateImage(index, imageNames[index], imageSet);
}
}
private void LoadAlternateImage(int index, string name, string imageSet)
{
string imageDir = PathUtils.Combine(Assembly.GetExecutingAssembly(), "Images", "Tree", imageSet);
string[] extensions = { ".png", ".jpg" };
foreach (string ext in extensions)
{
string filePath = Path.Combine(imageDir, name + ext);
if (File.Exists(filePath))
{
treeImages.Images[index] = Image.FromFile(filePath);
break;
}
}
}
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TestSuiteTreeView));
this.treeImages = new System.Windows.Forms.ImageList(this.components);
this.SuspendLayout();
//
// treeImages
//
this.treeImages.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("treeImages.ImageStream")));
this.treeImages.TransparentColor = System.Drawing.Color.White;
this.treeImages.Images.SetKeyName(0, "Skipped.png");
this.treeImages.Images.SetKeyName(1, "Failure.png");
this.treeImages.Images.SetKeyName(2, "Success.png");
this.treeImages.Images.SetKeyName(3, "Ignored.png");
this.treeImages.Images.SetKeyName(4, "Inconclusive.png");
//
// TestSuiteTreeView
//
this.ImageIndex = 0;
this.ImageList = this.treeImages;
this.SelectedImageIndex = 0;
this.DoubleClick += new System.EventHandler(this.TestSuiteTreeView_DoubleClick);
this.DragDrop += new System.Windows.Forms.DragEventHandler(this.TestSuiteTreeView_DragDrop);
this.DragEnter += new System.Windows.Forms.DragEventHandler(this.TestSuiteTreeView_DragEnter);
this.ResumeLayout(false);
}
public void Initialize( ITestLoader loader, ITestEvents events )
{
this.loader = loader;
events.TestLoaded += new TestEventHandler( OnTestLoaded );
events.TestReloaded += new TestEventHandler( OnTestChanged );
events.TestUnloaded += new TestEventHandler( OnTestUnloaded );
events.RunStarting += new TestEventHandler( OnRunStarting );
events.RunFinished += new TestEventHandler( OnRunFinished );
events.TestFinished += new TestEventHandler( OnTestResult );
events.SuiteFinished+= new TestEventHandler( OnTestResult );
}
#endregion
#region Properties and Events
/// <summary>
/// Property determining whether the run command
/// is supported from the tree context menu and
/// by double-clicking test cases.
/// </summary>
[Category( "Behavior" ), DefaultValue( true )]
[Description("Indicates whether the tree context menu should include a run command")]
public bool RunCommandSupported
{
get { return runCommandSupported; }
set { runCommandSupported = value; }
}
/// <summary>
/// Property determining whether tree should reDraw nodes
/// as tests are complete in order to show progress.
/// </summary>
[Category( "Behavior" ), DefaultValue( true )]
[Description("Indicates whether results should be displayed in the tree as each test completes")]
public bool DisplayTestProgress
{
get { return displayProgress; }
set { displayProgress = value; }
}
[Category( "Appearance" ), DefaultValue( false )]
[Description("Indicates whether checkboxes are displayed beside test nodes")]
public new bool CheckBoxes
{
get { return base.CheckBoxes; }
set
{
if ( base.CheckBoxes != value )
{
VisualState visualState = !value && this.TopNode != null
? new VisualState(this)
: null;
base.CheckBoxes = value;
if ( CheckBoxesChanged != null )
CheckBoxesChanged(this, new EventArgs());
if (visualState != null)
{
try
{
suppressEvents = true;
visualState.ShowCheckBoxes = this.CheckBoxes;
//RestoreVisualState( visualState );
visualState.Restore(this);
}
finally
{
suppressEvents = false;
}
}
}
}
}
public bool ShowInconclusiveResults
{
get { return showInconclusiveResults; }
}
/// <summary>
/// The currently selected test.
/// </summary>
[Browsable( false )]
public ITest SelectedTest
{
get
{
TestSuiteTreeNode node = (TestSuiteTreeNode)SelectedNode;
return node == null ? null : node.Test;
}
}
[Browsable( false )]
public ITest[] CheckedTests
{
get
{
CheckedTestFinder finder = new CheckedTestFinder( this );
return finder.GetCheckedTests( CheckedTestFinder.SelectionFlags.All );
}
}
[Browsable( false )]
public ITest[] SelectedTests
{
get
{
ITest[] result = null;
if ( this.CheckBoxes )
{
CheckedTestFinder finder = new CheckedTestFinder( this );
result = finder.GetCheckedTests(
CheckedTestFinder.SelectionFlags.Top | CheckedTestFinder.SelectionFlags.Explicit );
}
if ( result == null || result.Length == 0 )
if ( this.SelectedTest != null )
result = new ITest[] { this.SelectedTest };
return result;
}
}
[Browsable( false )]
public ITest[] FailedTests
{
get
{
FailedTestsFilterVisitor visitor = new FailedTestsFilterVisitor();
Accept(visitor);
return visitor.Tests;
}
}
/// <summary>
/// The currently selected test result or null
/// </summary>
[Browsable( false )]
public TestResult SelectedTestResult
{
get
{
TestSuiteTreeNode node = (TestSuiteTreeNode)SelectedNode;
return node == null ? null : node.Result;
}
}
[Browsable(false)]
public TestFilter CategoryFilter
{
get { return categoryFilter; }
set
{
categoryFilter = value;
TestFilterVisitor visitor = new TestFilterVisitor( categoryFilter );
this.Accept( visitor );
}
}
public event SelectedTestChangedHandler SelectedTestChanged;
public event CheckedTestChangedHandler CheckedTestChanged;
public event EventHandler CheckBoxesChanged;
public TestSuiteTreeNode this[string uniqueName]
{
get { return treeMap[uniqueName] as TestSuiteTreeNode; }
}
/// <summary>
/// Test node corresponding to a test
/// </summary>
private TestSuiteTreeNode this[ITest test]
{
get { return FindNode( test ); }
}
/// <summary>
/// Test node corresponding to a TestResultInfo
/// </summary>
private TestSuiteTreeNode this[TestResult result]
{
get { return FindNode( result.Test ); }
}
#endregion
#region Handlers for events related to loading and running tests
private void OnTestLoaded( object sender, TestEventArgs e )
{
CheckPropertiesDialog();
TestNode test = e.Test as TestNode;
if ( test != null )
Load( test );
runCommandEnabled = true;
}
private void OnTestChanged( object sender, TestEventArgs e )
{
TestNode test = e.Test as TestNode;
if ( test != null )
Invoke( new LoadHandler( Reload ), new object[]{ test } );
}
private void OnTestUnloaded( object sender, TestEventArgs e)
{
ClosePropertiesDialog();
if ( Services.UserSettings.GetSetting( "Gui.TestTree.SaveVisualState", true ) && loader != null)
try
{
new VisualState(this).Save(VisualState.GetVisualStateFileName(loader.TestFileName));
}
catch(Exception ex)
{
Debug.WriteLine( "Unable to save visual state." );
Debug.WriteLine( ex );
}
Clear();
contextNode = null;
runCommandEnabled = false;
}
private void OnRunStarting( object sender, TestEventArgs e )
{
CheckPropertiesDialog();
#if ACCUMULATE_RESULTS
if ( runningTests != null )
foreach( ITest test in runningTests )
this[test].ClearResults();
#else
ClearAllResults();
#endif
runCommandEnabled = false;
}
private void OnRunFinished( object sender, TestEventArgs e )
{
if ( runningTests != null )
foreach( ITest test in runningTests )
this[test].Expand();
if ( propertiesDialog != null )
propertiesDialog.Invoke( new PropertiesDisplayHandler( propertiesDialog.DisplayProperties ) );
runningTests = null;
runCommandEnabled = true;
}
private void OnTestResult( object sender, TestEventArgs e )
{
SetTestResult(e.Result);
}
#endregion
#region Context Menu
/// <summary>
/// Handles right mouse button down by
/// remembering the proper context item
/// and implements multiple select with the left button.
/// </summary>
/// <param name="e">MouseEventArgs structure with information about the mouse position and button state</param>
protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Right )
{
CheckPropertiesDialog();
TreeNode theNode = GetNodeAt( e.X, e.Y );
contextNode = theNode as TestSuiteTreeNode;
}
// else if (e.Button == MouseButtons.Left )
// {
// if ( Control.ModifierKeys == Keys.Control )
// {
// TestSuiteTreeNode theNode = GetNodeAt( e.X, e.Y ) as TestSuiteTreeNode;
// if ( theNode != null )
// theNode.IsSelected = true;
// }
// else
// {
// ClearSelected();
// }
// }
base.OnMouseDown( e );
}
/// <summary>
/// Build treeview context menu dynamically on popup
/// </summary>
private void ContextMenu_Popup(object sender, System.EventArgs e)
{
this.ContextMenu.MenuItems.Clear();
TestSuiteTreeNode targetNode = contextNode != null ? contextNode : (TestSuiteTreeNode)SelectedNode;
if ( targetNode == null )
return;
if ( RunCommandSupported )
{
// TODO: handle in Starting event
if ( loader.Running )
runCommandEnabled = false;
MenuItem runMenuItem = new MenuItem( "&Run", new EventHandler( runMenuItem_Click ) );
runMenuItem.DefaultItem = runMenuItem.Enabled = runCommandEnabled && targetNode.Included &&
(targetNode.Test.RunState == RunState.Runnable || targetNode.Test.RunState == RunState.Explicit);
this.ContextMenu.MenuItems.Add( runMenuItem );
this.ContextMenu.MenuItems.Add("-");
}
TestSuiteTreeNode theoryNode = targetNode.GetTheoryNode();
if (theoryNode != null)
{
MenuItem failedAssumptionsMenuItem = new MenuItem("Show Failed Assumptions", new EventHandler(failedAssumptionsMenuItem_Click));
failedAssumptionsMenuItem.Checked = theoryNode.ShowFailedAssumptions;
this.ContextMenu.MenuItems.Add(failedAssumptionsMenuItem);
this.ContextMenu.MenuItems.Add("-");
}
MenuItem showCheckBoxesMenuItem = new MenuItem("Show CheckBoxes", new EventHandler(showCheckBoxesMenuItem_Click));
showCheckBoxesMenuItem.Checked = this.CheckBoxes;
this.ContextMenu.MenuItems.Add(showCheckBoxesMenuItem);
this.ContextMenu.MenuItems.Add("-");
MenuItem loadFixtureMenuItem = new MenuItem("Load Fixture", new EventHandler(loadFixtureMenuItem_Click));
loadFixtureMenuItem.Enabled = targetNode.Test.IsSuite && targetNode != Nodes[0];
this.ContextMenu.MenuItems.Add( loadFixtureMenuItem );
MenuItem clearFixtureMenuItem = new MenuItem( "Clear Fixture", new EventHandler( clearFixtureMenuItem_Click ) );
clearFixtureMenuItem.Enabled = fixtureLoaded;
this.ContextMenu.MenuItems.Add( clearFixtureMenuItem );
this.ContextMenu.MenuItems.Add( "-" );
MenuItem propertiesMenuItem = new MenuItem(
"&Properties", new EventHandler( propertiesMenuItem_Click ) );
this.ContextMenu.MenuItems.Add( propertiesMenuItem );
}
private void showCheckBoxesMenuItem_Click( object sender, System.EventArgs e)
{
this.CheckBoxes = !this.CheckBoxes;
}
/// <summary>
/// When Expand context menu item is clicked, expand the node
/// </summary>
private void expandMenuItem_Click(object sender, System.EventArgs e)
{
TestSuiteTreeNode targetNode = contextNode != null ? contextNode : (TestSuiteTreeNode)SelectedNode;
if ( targetNode != null )
targetNode.Expand();
}
/// <summary>
/// When Collapse context menu item is clicked, collapse the node
/// </summary>
private void collapseMenuItem_Click(object sender, System.EventArgs e)
{
TestSuiteTreeNode targetNode = contextNode != null ? contextNode : (TestSuiteTreeNode)SelectedNode;
if ( targetNode != null )
targetNode.Collapse();
}
private void expandAllMenuItem_Click(object sender, System.EventArgs e)
{
this.BeginUpdate();
this.ExpandAll();
this.EndUpdate();
}
private void collapseAllMenuItem_Click(object sender, System.EventArgs e)
{
this.BeginUpdate();
this.CollapseAll();
this.EndUpdate();
// Compensate for a bug in the underlying control
if ( this.Nodes.Count > 0 )
this.SelectedNode = this.Nodes[0];
}
private void failedAssumptionsMenuItem_Click(object sender, System.EventArgs e)
{
TestSuiteTreeNode targetNode = contextNode != null ? contextNode : (TestSuiteTreeNode)SelectedNode;
TestSuiteTreeNode theoryNode = targetNode != null ? targetNode.GetTheoryNode() : null;
if (theoryNode != null)
{
MenuItem item = (MenuItem)sender;
BeginUpdate();
item.Checked = !item.Checked;
theoryNode.ShowFailedAssumptions = item.Checked;
EndUpdate();
}
}
/// <summary>
/// When Run context menu item is clicked, run the test that
/// was selected when the right click was done.
/// </summary>
private void runMenuItem_Click(object sender, System.EventArgs e)
{
//TODO: some sort of lock on these booleans?
if ( runCommandEnabled )
{
runCommandEnabled = false;
if ( contextNode != null )
RunTests( new ITest[] { contextNode.Test }, false );
else
RunSelectedTests();
}
}
private void runAllMenuItem_Click(object sender, System.EventArgs e)
{
if ( runCommandEnabled )
{
runCommandEnabled = false;
RunAllTests();
}
}
private void runFailedMenuItem_Click(object sender, System.EventArgs e)
{
if ( runCommandEnabled )
{
runCommandEnabled = false;
RunFailedTests();
}
}
private void loadFixtureMenuItem_Click( object sender, System.EventArgs e)
{
if ( contextNode != null )
{
loader.LoadTest( contextNode.Test.TestName.FullName );
fixtureLoaded = true;
}
}
private void clearFixtureMenuItem_Click( object sender, System.EventArgs e)
{
loader.LoadTest();
fixtureLoaded = false;
}
private void propertiesMenuItem_Click( object sender, System.EventArgs e)
{
TestSuiteTreeNode targetNode = contextNode != null ? contextNode : (TestSuiteTreeNode)SelectedNode;
if ( targetNode != null )
ShowPropertiesDialog( targetNode );
}
#endregion
#region Drag and drop
/// <summary>
/// Helper method to determine if an IDataObject is valid
/// for dropping on the tree view. It must be a the drop
/// of a single file with a valid assembly file type.
/// </summary>
/// <param name="data">IDataObject to be tested</param>
/// <returns>True if dropping is allowed</returns>
private bool IsValidFileDrop( IDataObject data )
{
if ( !data.GetDataPresent( DataFormats.FileDrop ) )
return false;
string [] fileNames = data.GetData( DataFormats.FileDrop ) as string [];
if ( fileNames == null || fileNames.Length == 0 )
return false;
// We can't open more than one project at a time
// so handle length of 1 separately.
if ( fileNames.Length == 1 )
{
string fileName = fileNames[0];
bool isProject = NUnitProject.IsNUnitProjectFile( fileName );
if ( Services.UserSettings.GetSetting( "Options.TestLoader.VisualStudioSupport", false ) )
isProject |= Services.ProjectService.CanConvertFrom( fileName );
return isProject || PathUtils.IsAssemblyFileType( fileName );
}
// Multiple assemblies are allowed - we
// assume they are all in the same directory
// since they are being dragged together.
foreach( string fileName in fileNames )
{
if ( !PathUtils.IsAssemblyFileType( fileName ) )
return false;
}
return true;
}
private void TestSuiteTreeView_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
if ( IsValidFileDrop( e.Data ) )
{
string[] fileNames = (string[])e.Data.GetData( DataFormats.FileDrop );
if ( fileNames.Length == 1 )
loader.LoadProject( fileNames[0] );
else
loader.LoadProject( fileNames );
if (loader.IsProjectLoaded && loader.TestProject.IsLoadable)
loader.LoadTest();
}
}
private void TestSuiteTreeView_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
if ( IsValidFileDrop( e.Data ) )
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
#endregion
#region UI Event Handlers
private void TestSuiteTreeView_DoubleClick(object sender, System.EventArgs e)
{
TestSuiteTreeNode node = SelectedNode as TestSuiteTreeNode;
if ( runCommandSupported && runCommandEnabled && node.Nodes.Count == 0 && node.Included )
{
runCommandEnabled = false;
// TODO: Since this is a terminal node, don't use a category filter
RunTests( new ITest[] { SelectedTest }, true );
}
}
protected override void OnAfterSelect(System.Windows.Forms.TreeViewEventArgs e)
{
if ( !suppressEvents )
{
if ( SelectedTestChanged != null )
SelectedTestChanged( SelectedTest );
base.OnAfterSelect( e );
}
}
protected override void OnAfterCheck(TreeViewEventArgs e)
{
if ( !suppressEvents )
{
if (CheckedTestChanged != null)
CheckedTestChanged(CheckedTests);
base.OnAfterCheck (e);
}
}
#endregion
#region Public methods to manipulate the tree
/// <summary>
/// Clear all the results in the tree.
/// </summary>
public void ClearAllResults()
{
foreach ( TestSuiteTreeNode rootNode in Nodes )
rootNode.ClearResults();
}
/// <summary>
/// Load the tree with a test hierarchy
/// </summary>
/// <param name="test">Test to be loaded</param>
public void Load( TestNode test )
{
using( new CP.Windows.Forms.WaitCursor() )
{
Clear();
BeginUpdate();
try
{
AddTreeNodes( Nodes, test, false );
SetInitialExpansion();
}
finally
{
EndUpdate();
contextNode = null;
this.Select();
}
if ( Services.UserSettings.GetSetting( "Gui.TestTree.SaveVisualState", true ) && loader != null)
RestoreVisualState();
}
}
/// <summary>
/// Load the tree from a test result
/// </summary>
/// <param name="result"></param>
public void Load( TestResult result )
{
using ( new CP.Windows.Forms.WaitCursor( ) )
{
Clear();
BeginUpdate();
try
{
AddTreeNodes( Nodes, result, false );
SetInitialExpansion();
}
finally
{
EndUpdate();
}
}
}
/// <summary>
/// Reload the tree with a changed test hierarchy
/// while maintaining as much gui state as possible.
/// </summary>
/// <param name="test">Test suite to be loaded</param>
public void Reload( TestNode test )
{
TestResult result = ((TestSuiteTreeNode)Nodes[0]).Result;
VisualState visualState = new VisualState(this);
Load(test);
visualState.Restore(this);
if (result != null && !Services.UserSettings.GetSetting("Options.TestLoader.ClearResultsOnReload", false))
RestoreResults(result);
}
/// <summary>
/// Clear all the info in the tree.
/// </summary>
public void Clear()
{
treeMap.Clear();
Nodes.Clear();
}
protected override void OnAfterCollapse(TreeViewEventArgs e)
{
if ( !suppressEvents )
base.OnAfterCollapse (e);
}
protected override void OnAfterExpand(TreeViewEventArgs e)
{
if ( !suppressEvents )
base.OnAfterExpand (e);
}
public void Accept(TestSuiteTreeNodeVisitor visitor)
{
foreach(TestSuiteTreeNode node in Nodes)
{
node.Accept(visitor);
}
}
public void ClearCheckedNodes()
{
Accept(new ClearCheckedNodesVisitor());
}
public void CheckFailedNodes()
{
Accept(new CheckFailedNodesVisitor());
}
/// <summary>
/// Add the result of a test to the tree
/// </summary>
/// <param name="result">The result of the test</param>
public void SetTestResult(TestResult result)
{
TestSuiteTreeNode node = this[result];
if (node == null)
{
Debug.WriteLine("Test not found in tree: " + result.Test.TestName.UniqueName);
}
else
{
node.Result = result;
if (result.Test.TestType == "Theory")
node.RepopulateTheoryNode();
if (DisplayTestProgress && node.IsVisible)
{
Invalidate(node.Bounds);
Update();
}
}
}
public void HideTests()
{
this.BeginUpdate();
foreach( TestSuiteTreeNode node in Nodes )
HideTestsUnderNode( node );
this.EndUpdate();
}
public void ShowPropertiesDialog( ITest test )
{
ShowPropertiesDialog( this[ test ] );
}
private void ShowPropertiesDialog( TestSuiteTreeNode node )
{
if ( propertiesDialog == null )
{
Form owner = this.FindForm();
propertiesDialog = new TestPropertiesDialog( node );
propertiesDialog.Owner = owner;
propertiesDialog.Font = owner.Font;
propertiesDialog.StartPosition = FormStartPosition.Manual;
propertiesDialog.Left = Math.Max(0, owner.Left + ( owner.Width - propertiesDialog.Width ) / 2);
propertiesDialog.Top = Math.Max(0, owner.Top + ( owner.Height - propertiesDialog.Height ) / 2);
propertiesDialog.Show();
propertiesDialog.Closed += new EventHandler( OnPropertiesDialogClosed );
}
else
{
propertiesDialog.DisplayProperties( node );
}
}
private void ClosePropertiesDialog()
{
if ( propertiesDialog != null )
propertiesDialog.Close();
}
private void CheckPropertiesDialog()
{
if ( propertiesDialog != null && !propertiesDialog.Pinned )
propertiesDialog.Close();
}
private void OnPropertiesDialogClosed( object sender, System.EventArgs e )
{
propertiesDialog = null;
}
#endregion
#region Running Tests
public void RunAllTests()
{
RunAllTests(true);
}
public void RunAllTests(bool ignoreCategories)
{
if (Nodes.Count > 0)
{
runCommandEnabled = false;
RunTests(new ITest[] { ((TestSuiteTreeNode)Nodes[0]).Test }, ignoreCategories);
}
}
public void RunSelectedTests()
{
runCommandEnabled = false;
RunTests( SelectedTests, false );
}
public void RunFailedTests()
{
runCommandEnabled = false;
RunTests( FailedTests, true );
}
private void RunTests( ITest[] tests, bool ignoreCategories )
{
if (tests != null && tests.Length > 0)
{
runningTests = tests;
ITestFilter filter = ignoreCategories
? MakeNameFilter(tests)
: MakeFilter(tests);
loader.RunTests(filter);
}
}
private TestFilter MakeFilter( ITest[] tests )
{
TestFilter nameFilter = MakeNameFilter( tests );
if ( nameFilter == TestFilter.Empty )
return CategoryFilter;
if ( tests.Length == 1 )
{
TestSuiteTreeNode rootNode = (TestSuiteTreeNode)Nodes[0];
if ( tests[0] == rootNode.Test )
return CategoryFilter;
}
if ( CategoryFilter.IsEmpty )
return nameFilter;
return new AndFilter( nameFilter, CategoryFilter );
}
private TestFilter MakeNameFilter( ITest[] tests )
{
if ( tests == null || tests.Length == 0 )
return TestFilter.Empty;
NameFilter nameFilter = new NameFilter();
foreach( ITest test in tests )
nameFilter.Add( test.TestName );
return nameFilter;
}
#endregion
#region Helper Methods
/// <summary>
/// Add nodes to the tree constructed from a test
/// </summary>
/// <param name="nodes">The TreeNodeCollection to which the new node should be added</param>
/// <param name="rootTest">The test for which a node is to be built</param>
/// <param name="highlight">If true, highlight the text for this node in the tree</param>
/// <returns>A newly constructed TestNode, possibly with descendant nodes</returns>
private TestSuiteTreeNode AddTreeNodes( IList nodes, TestNode rootTest, bool highlight )
{
TestSuiteTreeNode node = new TestSuiteTreeNode( rootTest );
// if ( highlight ) node.ForeColor = Color.Blue;
AddToMap( node );
nodes.Add( node );
if ( rootTest.IsSuite )
{
foreach( TestNode test in rootTest.Tests )
AddTreeNodes( node.Nodes, test, highlight );
}
return node;
}
private TestSuiteTreeNode AddTreeNodes( IList nodes, TestResult rootResult, bool highlight )
{
TestSuiteTreeNode node = new TestSuiteTreeNode( rootResult );
AddToMap( node );
nodes.Add( node );
if ( rootResult.HasResults )
{
foreach( TestResult result in rootResult.Results )
AddTreeNodes( node.Nodes, result, highlight );
}
node.UpdateImageIndex();
return node;
}
private void AddToMap( TestSuiteTreeNode node )
{
string key = node.Test.TestName.UniqueName;
if ( treeMap.ContainsKey( key ) )
log.Error( "Duplicate entry: " + key );
// UserMessage.Display( string.Format(
// "The test {0} is duplicated\r\rResults will not be displayed correctly in the tree.", node.Test.FullName ), "Duplicate Test" );
else
{
log.Debug( "Added to map: " + node.Test.TestName.UniqueName );
treeMap.Add( key, node );
}
}
private void RemoveFromMap( TestSuiteTreeNode node )
{
foreach( TestSuiteTreeNode child in node.Nodes )
RemoveFromMap( child );
treeMap.Remove( node.Test.TestName.UniqueName );
}
/// <summary>
/// Remove a node from the tree itself and the hashtable
/// </summary>
/// <param name="node">Node to remove</param>
private void RemoveNode( TestSuiteTreeNode node )
{
if ( contextNode == node )
contextNode = null;
RemoveFromMap( node );
node.Remove();
}
/// <summary>
/// Delegate for use in invoking the tree loader
/// from the watcher thread.
/// </summary>
private delegate void LoadHandler( TestNode test );
private delegate void PropertiesDisplayHandler();
/// <summary>
/// Helper collapses all fixtures under a node
/// </summary>
/// <param name="node">Node under which to collapse fixtures</param>
private void HideTestsUnderNode( TestSuiteTreeNode node )
{
if (node.Test.IsSuite)
{
if (node.Test.TestType == "TestFixture")
node.Collapse();
else
{
node.Expand();
foreach (TestSuiteTreeNode child in node.Nodes)
HideTestsUnderNode(child);
}
}
}
/// <summary>
/// Helper used to figure out the display style
/// to use when the setting is Auto
/// </summary>
/// <returns>DisplayStyle to be used</returns>
private DisplayStyle GetDisplayStyle()
{
DisplayStyle initialDisplay = (TestSuiteTreeView.DisplayStyle)
Services.UserSettings.GetSetting( "Gui.TestTree.InitialTreeDisplay", DisplayStyle.Auto );
if ( initialDisplay != DisplayStyle.Auto )
return initialDisplay;
if ( VisibleCount >= this.GetNodeCount( true ) )
return DisplayStyle.Expand;
return DisplayStyle.HideTests;
}
public void SetInitialExpansion()
{
CollapseAll();
switch ( GetDisplayStyle() )
{
case DisplayStyle.Expand:
ExpandAll();
break;
case DisplayStyle.HideTests:
HideTests();
break;
case DisplayStyle.Collapse:
default:
break;
}
SelectedNode = Nodes[0];
SelectedNode.EnsureVisible();
}
private TestSuiteTreeNode FindNode( ITest test )
{
TestSuiteTreeNode node = treeMap[test.TestName.UniqueName] as TestSuiteTreeNode;
if (node == null)
node = FindNodeByName(test.TestName.FullName);
return node;
}
private TestSuiteTreeNode FindNodeByName( string fullName )
{
foreach( string uname in treeMap.Keys )
{
int rbrack = uname.IndexOf(']');
string name = rbrack >=0 ? uname.Substring(rbrack+1) : uname;
if ( name == fullName )
return treeMap[uname] as TestSuiteTreeNode;
}
return null;
}
private void RestoreVisualState()
{
if (loader != null)
{
string fileName = VisualState.GetVisualStateFileName(loader.TestFileName);
if (File.Exists(fileName))
{
VisualState.LoadFrom(fileName).Restore(this);
}
}
}
private void RestoreResults(TestResult result)
{
if (result.HasResults)
foreach (TestResult childResult in result.Results)
RestoreResults(childResult);
SetTestResult(result);
}
#endregion
}
#region Helper Classes
#region ClearCheckedNodesVisitor
internal class ClearCheckedNodesVisitor : TestSuiteTreeNodeVisitor
{
public override void Visit(TestSuiteTreeNode node)
{
node.Checked = false;
}
}
#endregion
#region CheckFailedNodesVisitor
internal class CheckFailedNodesVisitor : TestSuiteTreeNodeVisitor
{
public override void Visit(TestSuiteTreeNode node)
{
if (!node.Test.IsSuite && node.HasResult &&
(node.Result.ResultState == ResultState.Failure ||
node.Result.ResultState == ResultState.Error) )
{
node.Checked = true;
node.EnsureVisible();
}
else
node.Checked = false;
}
}
#endregion
#region FailedTestsFilterVisitor
internal class FailedTestsFilterVisitor : TestSuiteTreeNodeVisitor
{
List<ITest> tests = new List<ITest>();
public ITest[] Tests
{
get { return tests.ToArray(); }
}
public override void Visit(TestSuiteTreeNode node)
{
if (!node.Test.IsSuite && node.HasResult &&
(node.Result.ResultState == ResultState.Failure ||
node.Result.ResultState == ResultState.Error) )
{
tests.Add(node.Test);
}
}
}
#endregion
#region TestFilterVisitor
public class TestFilterVisitor : TestSuiteTreeNodeVisitor
{
private ITestFilter filter;
public TestFilterVisitor( ITestFilter filter )
{
this.filter = filter;
}
public override void Visit( TestSuiteTreeNode node )
{
node.Included = filter.Pass( node.Test );
}
}
#endregion
#region CheckedTestFinder
internal class CheckedTestFinder
{
[Flags]
public enum SelectionFlags
{
Top= 1,
Sub = 2,
Explicit = 4,
All = Top + Sub
}
private List<CheckedTestInfo> checkedTests = new List<CheckedTestInfo>();
private struct CheckedTestInfo
{
public ITest Test;
public bool TopLevel;
public CheckedTestInfo( ITest test, bool topLevel )
{
this.Test = test;
this.TopLevel = topLevel;
}
}
public ITest[] GetCheckedTests( SelectionFlags flags )
{
int count = 0;
foreach( CheckedTestInfo info in checkedTests )
if ( isSelected( info, flags ) ) count++;
ITest[] result = new ITest[count];
int index = 0;
foreach( CheckedTestInfo info in checkedTests )
if ( isSelected( info, flags ) )
result[index++] = info.Test;
return result;
}
private bool isSelected( CheckedTestInfo info, SelectionFlags flags )
{
if ( info.TopLevel && (flags & SelectionFlags.Top) != 0 )
return true;
else if ( !info.TopLevel && (flags & SelectionFlags.Sub) != 0 )
return true;
else if ( info.Test.RunState == RunState.Explicit && (flags & SelectionFlags.Explicit) != 0 )
return true;
else
return false;
}
public CheckedTestFinder( TestSuiteTreeView treeView )
{
FindCheckedNodes( treeView.Nodes, true );
}
private void FindCheckedNodes( TestSuiteTreeNode node, bool topLevel )
{
if ( node.Checked )
{
checkedTests.Add( new CheckedTestInfo( node.Test, topLevel ) );
topLevel = false;
}
FindCheckedNodes( node.Nodes, topLevel );
}
private void FindCheckedNodes( TreeNodeCollection nodes, bool topLevel )
{
foreach( TestSuiteTreeNode node in nodes )
FindCheckedNodes( node, topLevel );
}
}
#endregion
#endregion
}
| |
// Commons.GetOptions.ForCompilers
//
// Copyright (c) 2002-2015 Rafael 'Monoman' Teixeira, Managed Commons Team
//
// 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.Diagnostics;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using Commons.GetOptions;
using static System.Console;
namespace Commons.Compilers
{
public delegate void AssemblyAdder(Assembly loadedAssembly);
public delegate void ModuleAdder(System.Reflection.Module module);
public enum InternalCompilerErrorReportAction
{
prompt, send, none
}
public enum TargetType
{
Library, Exe, Module, WinExe
};
public struct FileToCompile
{
public Encoding Encoding;
public string Filename;
public FileToCompile(string filename, Encoding encoding)
{
Filename = filename;
Encoding = encoding;
}
}
public class CommonCompilerOptions : OptionsWithSecondLevel
{
[Option("Allows unsafe code", Name = "unsafe", SecondLevelHelp = true)]
public bool AllowUnsafeCode = false;
public ArrayList AssembliesToReference = new ArrayList();
// TODO: force option to accept number in hex format
// [Option("[NOT IMPLEMENTED YET]The base {address} for a library or module (hex)", SecondLevelHelp = true)]
public int baseaddress;
public bool CheckedContext = true;
// support for the Compact Framework
//------------------------------------------------------------------
// [Option("[NOT IMPLEMENTED YET]Sets the compiler to TargetFileType the Compact Framework", Name = "netcf")]
public bool CompileForCompactFramework = false;
// [Option("[NOT IMPLEMENTED YET]Create bug report {file}", Name = "bugreport")]
public string CreateBugReport;
public ArrayList DebugListOfArguments = new ArrayList();
public bool DebugSymbolsDbOnly = false;
// Defines
//------------------------------------------------------------------
public Hashtable Defines = new Hashtable();
// Signing options
//------------------------------------------------------------------
// [Option("[NOT IMPLEMENTED YET]Delay-sign the assembly using only the public portion of the strong name key", VBCStyleBoolean = true)]
public bool delaysign;
[Option("Do not display compiler copyright banner", Name = "nologo")]
public bool DontShowBanner = false;
// resource options
//------------------------------------------------------------------
public ArrayList EmbeddedResources = new ArrayList();
public bool FullDebugging = true;
public ArrayList Imports = new ArrayList();
// [Option("[NOT IMPLEMENTED YET]Specifies a strong name key {container}")]
public string keycontainer;
// [Option("[NOT IMPLEMENTED YET]Specifies a strong name key {file}")]
public string keyfile;
public ArrayList LinkedResources = new ArrayList();
[Option("Specifies the {name} of the Class or Module that contains Sub Main \tor inherits from System.Windows.Forms.Form.\tNeeded to select among many entry-points for a program (target=exe|winexe)", ShortForm = 'm', Name = "main")]
public string MainClassName = null;
public ArrayList NetModulesToAdd = new ArrayList();
[Option("Disables implicit references to assemblies", Name = "noconfig", SecondLevelHelp = true)]
public bool NoConfig = false;
[Option("Don\'t assume the standard library", Name = "nostdlib", SecondLevelHelp = true)]
public bool NoStandardLibraries = false;
// [Option("[NOT IMPLEMENTED YET]Enable optimizations", Name = "optimize", VBCStyleBoolean = true)]
public bool Optimize = false;
[Option("[IGNORED] Emit compiler output in UTF8 character encoding", Name = "utf8output", SecondLevelHelp = true, VBCStyleBoolean = true)]
public bool OutputInUTF8;
public ArrayList PathsToSearchForLibraries = new ArrayList();
[Option("Specifies the root {namespace} for all type declarations", Name = "rootnamespace", SecondLevelHelp = true)]
public string RootNamespace = null;
// [Option("[NOT IMPLEMENTED YET]Specifies the {path} to the location of mscorlib.dll and microsoft.visualbasic.dll", Name = "sdkpath")]
public string SDKPath = null;
public ArrayList SourceFilesToCompile = new ArrayList();
// Compiler output options
//------------------------------------------------------------------
//TODO: Correct semantics
[Option("Commands the compiler to show only error messages for syntax-related errors and warnings", ShortForm = 'q', Name = "quiet", SecondLevelHelp = true)]
public bool SuccintErrorDisplay = false;
// Output file options
//------------------------------------------------------------------
public TargetType TargetFileType = TargetType.Exe;
[Option("Display verbose messages", ShortForm = 'v', Name = "verbose", SecondLevelHelp = true)]
public bool Verbose = false;
[Option("Emit full debugging information", ShortForm = 'g', Name = "debug", VBCStyleBoolean = true)]
public bool WantDebuggingSupport = false;
[Option("Sets warning {level} (the highest is 4, the default)", Name = "wlevel", SecondLevelHelp = true)]
public int WarningLevel = 4;
[Option("Treat warnings as errors", Name = "warnaserror", SecondLevelHelp = true)]
public bool WarningsAreErrors = false;
public ArrayList Win32Icons = new ArrayList();
public ArrayList Win32Resources = new ArrayList();
public CommonCompilerOptions(string[] args = null, ErrorReporter reportError = null)
: base(BuildDefaultContext(reportError), args)
{
PathsToSearchForLibraries.Add(Directory.GetCurrentDirectory());
}
[Option("List of directories to search for referenced assemblies. \t{path-list}:path,...", Name = "libpath", AlternateForm = "lib")]
public string AddedLibPath { set { foreach (string path in value.Split(',')) PathsToSearchForLibraries.Add(path); } }
[Option("Adds the specified file as a linked assembly resource. \t{details}:file[,id[,public|private]]", MaxOccurs = -1, Name = "linkresource", AlternateForm = "linkres")]
public string AddedLinkresource { set { LinkedResources.Add(value); } }
// input file options
//------------------------------------------------------------------
[Option("Imports all type information from files in the module-list. {module-list}:module,...", MaxOccurs = -1, Name = "addmodule")]
public string AddedModule { set { foreach (string module in value.Split(',')) NetModulesToAdd.Add(module); } }
[Option("References metadata from the specified assembly-list. \t{assembly-list}:assembly,...", MaxOccurs = -1, ShortForm = 'r', Name = "reference")]
public string AddedReference { set { foreach (string assembly in value.Split(',')) AssembliesToReference.Add(assembly); } }
//TODO: support -res:file[,id[,public|private]] what depends on changes at Mono.GetOptions
[Option("Adds the specified file as an embedded assembly resource. \t{details}:file[,id[,public|private]]", MaxOccurs = -1, Name = "resource", AlternateForm = "res")]
public string AddedResource { set { EmbeddedResources.Add(value); } }
// [Option("[NOT IMPLEMENTED YET]Specifies a Win32 icon {file} (.ico) for the default Win32 resources",
// MaxOccurs = -1, Name = "win32icon")]
public string AddedWin32icon { set { Win32Icons.Add(value); } }
// [Option("[NOT IMPLEMENTED YET]Specifies a Win32 resource {file} (.res)",
// MaxOccurs = -1, Name = "win32resource")]
public string AddedWin32resource { set { Win32Resources.Add(value); } }
// For now the "default config" is hardcoded we can move this outside later
public virtual string[] AssembliesToReferenceSoftly => new string[] { "System", "System.Data", "System.Xml" };
public bool BeQuiet => DontShowBanner || SuccintErrorDisplay;
[Option("Select codepage by {ID} (number, 'utf8' or 'reset') to process following source files", MaxOccurs = -1, Name = "codepage")]
public string CurrentCodepage
{
set
{
switch (value.ToLower()) {
case "reset":
_currentEncoding = null;
break;
case "utf8":
case "utf-8":
_currentEncoding = Encoding.UTF8;
break;
default:
try {
_currentEncoding = Encoding.GetEncoding(int.Parse(value));
} catch (NotSupportedException) {
Context.ReportError(0, string.Format("Ignoring unsupported codepage number {0}.", value));
} catch (Exception) {
Context.ReportError(0, string.Format("Ignoring unsupported codepage ID {0}.", value));
}
break;
}
}
}
[Option("Emit full debugging information (default)", Name = "debug:full", SecondLevelHelp = true)]
public bool debugfull
{
set
{
WantDebuggingSupport = value;
FullDebugging = value;
DebugSymbolsDbOnly = !value;
}
}
[Option("Emit debug symbols file only", Name = "debug:pdbonly", SecondLevelHelp = true)]
public bool debugpdbonly
{
set
{
WantDebuggingSupport = value;
FullDebugging = !value;
DebugSymbolsDbOnly = value;
}
}
[Option("Declares global conditional compilation symbol(s). {symbol-list}:name=value,...", MaxOccurs = -1, ShortForm = 'd', Name = "define")]
public string DefineSymbol
{
set
{
foreach (string item in value.Split(',')) {
string[] dados = item.Split('=');
if (dados.Length > 1)
Defines.Add(dados[0], dados[1]);
else
Defines.Add(dados[0], "true");
}
}
}
[Option("Declare global Imports for listed namespaces. {import-list}:namespace,...", MaxOccurs = -1, Name = "imports")]
public string ImportNamespaces
{
set
{
foreach (string importedNamespace in value.Split(','))
Imports.Add(importedNamespace);
}
}
public virtual bool NothingToCompile
{
get
{
if (SourceFilesToCompile.Count == 0) {
if (!BeQuiet)
DoHelp();
return true;
}
if (!BeQuiet)
ShowBanner();
return false;
}
}
// errors and warnings options
//------------------------------------------------------------------
[Option("Disable warnings", Name = "nowarn", SecondLevelHelp = true)]
public bool NoWarnings { set { if (value) WarningLevel = 0; } }
[Option("Specifies the output {file} name", ShortForm = 'o', Name = "out")]
public string OutputFileName
{
set
{
_outputFileName = value;
}
get
{
if (_outputFileName == null) {
int pos = _firstSourceFile.LastIndexOf(".", StringComparison.Ordinal);
if (pos > 0)
_outputFileName = _firstSourceFile.Substring(0, pos);
else
_outputFileName = _firstSourceFile;
_outputFileName += _targetFileExtension;
}
return _outputFileName;
}
}
[Option("Displays time stamps of various compiler events", Name = "timestamp", SecondLevelHelp = true)]
public virtual bool PrintTimeStamps
{
#pragma warning disable RECS0029 // Warns about property or indexer setters and event adders or removers that do not use the value parameter
set
{
_printTimeStamps = true;
_last_time = DateTime.Now;
DebugListOfArguments.Add("timestamp");
}
#pragma warning restore RECS0029 // Warns about property or indexer setters and event adders or removers that do not use the value parameter
}
// code generation options
//------------------------------------------------------------------
[Option("Remove integer checks. Default off.", SecondLevelHelp = true, VBCStyleBoolean = true)]
public virtual bool removeintchecks { set { CheckedContext = !value; } }
public int[] WarningsToIgnore => (int[])_warningsToIgnore.ToArray(typeof(int));
public static OptionsContext BuildDefaultContext(ErrorReporter reportError) => new OptionsContext
{
BreakSingleDashManyLettersIntoManyOptions = false,
DontSplitOnCommas = true,
EndOptionProcessingWithDoubleDash = true,
ParsingMode = OptionsParsingMode.Both,
ReportError = reportError ?? OptionsContext.DefaultErrorReporter
};
public void AdjustCodegenWhenTargetIsNetModule(AssemblyBuilder assemblyBuilder)
{
if (TargetFileType == TargetType.Module) {
StartTime("Adjusting AssemblyBuilder for NetModule target");
PropertyInfo module_only = typeof(AssemblyBuilder).GetProperty("IsModuleOnly", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (module_only == null)
UnsupportedFeatureOnthisRuntime("/target:module");
MethodInfo set_method = module_only.GetSetMethod(true);
set_method.Invoke(assemblyBuilder, BindingFlags.Default, null, new object[] { true }, null);
ShowTime(" Done");
}
}
[ArgumentProcessor]
public void DefaultArgumentProcessor(string fileName)
{
if (_firstSourceFile == null)
_firstSourceFile = fileName;
if (!_sourceFiles.Contains(fileName)) {
SourceFilesToCompile.Add(new FileToCompile(fileName, _currentEncoding));
_sourceFiles.Add(fileName, fileName);
}
}
public void EmbedResources(AssemblyBuilder builder)
{
if (EmbeddedResources != null)
foreach (string file in EmbeddedResources)
builder.AddResourceFile(file, file); // TODO: deal with resource IDs
}
public bool LoadAddedNetModules(AssemblyBuilder assemblyBuilder, ModuleAdder adder)
{
int errors = 0;
if (NetModulesToAdd.Count > 0) {
StartTime("Loading added netmodules");
MethodInfo adder_method = typeof(AssemblyBuilder).GetMethod("AddModule", BindingFlags.Instance | BindingFlags.NonPublic);
if (adder_method == null)
UnsupportedFeatureOnthisRuntime("/addmodule");
foreach (string module in NetModulesToAdd)
LoadModule(adder_method, assemblyBuilder, adder, module, ref errors);
ShowTime(" Done");
}
return errors == 0;
}
/// <summary>
/// Loads all assemblies referenced on the command line
/// </summary>
public bool LoadReferencedAssemblies(AssemblyAdder adder)
{
StartTime("Loading referenced assemblies");
int errors = 0;
int soft_errors = 0;
// Load Core Library for default compilation
if (!NoStandardLibraries)
LoadAssembly(adder, "mscorlib", ref errors, false);
foreach (string r in AssembliesToReference)
LoadAssembly(adder, r, ref errors, false);
if (!NoConfig)
foreach (string r in AssembliesToReferenceSoftly)
if (!(AssembliesToReference.Contains(r) || AssembliesToReference.Contains(r + ".dll")))
LoadAssembly(adder, r, ref soft_errors, true);
ShowTime("References loaded");
return errors == 0;
}
// [Option("[NOT IMPLEMENTED YET]Include all files in the current directory and subdirectories according to the {wildcard}", Name = "recurse")]
//AddFiles (DirName, true); // TODO wrong semantics
public WhatToDoNext Recurse(string wildcard) => WhatToDoNext.GoAhead;
public bool ReferencePackage(string packageName)
{
if (packageName == "") {
DoAbout();
return false;
}
var pi = new ProcessStartInfo();
pi.FileName = "pkg-config";
pi.RedirectStandardOutput = true;
pi.UseShellExecute = false;
pi.Arguments = "--libs " + packageName;
Process p = null;
try {
p = Process.Start(pi);
} catch (Exception e) {
Context.ReportError(0, "Couldn't run pkg-config: " + e.Message);
return false;
}
if (p.StandardOutput == null) {
Context.ReportError(0, "Specified package did not return any information");
}
string pkgout = p.StandardOutput.ReadToEnd();
p.WaitForExit();
if (p.ExitCode != 0) {
Context.ReportError(0, "Error running pkg-config. Check the above output.");
return false;
}
p.Close();
if (pkgout != null) {
string[] xargs = pkgout.Trim(new Char[] { ' ', '\n', '\r', '\t' }).
Split(new Char[] { ' ', '\t' });
foreach (string arg in xargs) {
string[] zargs = arg.Split(':', '=');
try {
if (zargs.Length > 1)
AddedReference = zargs[1];
else
AddedReference = arg;
} catch (Exception e) {
Context.ReportError(0, "Something wrong with argument (" + arg + ") in 'pkg-config --libs' output: " + e.Message);
return false;
}
}
}
return true;
}
[Option("References packages listed. {packagelist}=package,...", MaxOccurs = -1, Name = "pkg")]
public WhatToDoNext ReferenceSomePackage(string packageName) => ReferencePackage(packageName) ? WhatToDoNext.GoAhead : WhatToDoNext.AbandonProgram;
[Option("Debugger {arguments}", Name = "debug-args", SecondLevelHelp = true)]
public WhatToDoNext SetDebugArgs(string args)
{
DebugListOfArguments.AddRange(args.Split(','));
return WhatToDoNext.GoAhead;
}
[Option("Ignores warning number {XXXX}", MaxOccurs = -1, Name = "ignorewarn", SecondLevelHelp = true)]
public WhatToDoNext SetIgnoreWarning(int warningNumber)
{
_warningsToIgnore.Add(warningNumber);
return WhatToDoNext.GoAhead;
}
[Option("Specifies the target {type} for the output file (exe [default], winexe, library, module)", ShortForm = 't', Name = "target")]
public WhatToDoNext SetTarget(string type)
{
switch (type.ToLower()) {
case "library":
TargetFileType = TargetType.Library;
_targetFileExtension = ".dll";
break;
case "exe":
TargetFileType = TargetType.Exe;
_targetFileExtension = ".exe";
break;
case "winexe":
TargetFileType = TargetType.WinExe;
_targetFileExtension = ".exe";
break;
case "module":
TargetFileType = TargetType.Module;
_targetFileExtension = ".netmodule";
break;
}
return WhatToDoNext.GoAhead;
}
public void ShowTime(string msg)
{
if (!_printTimeStamps)
return;
DateTime now = DateTime.Now;
TimeSpan span = now - _last_time;
_last_time = now;
WriteLine(
"[{0:00}:{1:000}] {2}",
(int)span.TotalSeconds, span.Milliseconds, msg);
}
public void StartTime(string msg)
{
if (!_printTimeStamps)
return;
_last_time = DateTime.Now;
WriteLine("[*] {0}", msg);
}
public void UnsupportedFeatureOnthisRuntime(string feature)
{
Context.ReportError(0, string.Format("Cannot use {0} on this runtime: Try the Mono runtime instead.", feature));
Environment.Exit(1);
}
Encoding _currentEncoding = null;
string _firstSourceFile = null;
//
// Last time we took the time
//
DateTime _last_time;
string _outputFileName = null;
bool _printTimeStamps = false;
Hashtable _sourceFiles = new Hashtable();
string _targetFileExtension = ".exe";
ArrayList _warningsToIgnore = new ArrayList();
static string[] GetDirs(string path)
{
try {
return Directory.GetDirectories(path);
#pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body
} catch {
#pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body
}
return new string[0];
}
bool AddFiles(string spec, bool recurse)
{
string path, pattern;
SplitPathAndPattern(spec, out path, out pattern);
if (pattern.IndexOf("*", StringComparison.Ordinal) == -1) {
DefaultArgumentProcessor(spec);
return true;
}
string[] files = null;
try {
files = Directory.GetFiles(path, pattern);
} catch (System.IO.DirectoryNotFoundException) {
Context.ReportError(2001, "Source file '" + spec + "' could not be found");
return false;
} catch (System.IO.IOException) {
Context.ReportError(2001, "Source file '" + spec + "' could not be found");
return false;
}
foreach (string f in files)
DefaultArgumentProcessor(f);
if (!recurse)
return true;
foreach (string d in GetDirs(path)) {
// Don't include path in this string, as each
// directory entry already does
AddFiles(d + "/" + pattern, true);
}
return true;
}
void LoadAssembly(AssemblyAdder adder, string assemblyName, ref int errors, bool soft)
{
Assembly a = null;
string total_log = "";
try {
char[] path_chars = { '/', '\\' };
if (assemblyName.IndexOfAny(path_chars) != -1)
a = Assembly.LoadFrom(assemblyName);
else {
string ass = assemblyName;
if (ass.EndsWith(".dll", StringComparison.Ordinal))
ass = assemblyName.Substring(0, assemblyName.Length - 4);
a = Assembly.Load(ass);
}
adder(a);
return;
} catch (FileNotFoundException) {
if (PathsToSearchForLibraries != null) {
foreach (string dir in PathsToSearchForLibraries) {
string full_path = Path.Combine(dir, assemblyName + ".dll");
try {
a = Assembly.LoadFrom(full_path);
adder(a);
return;
} catch (FileNotFoundException ff) {
total_log += ff.FusionLog;
continue;
}
}
}
if (soft)
return;
Context.ReportError(6, "Can not find assembly '" + assemblyName + "'\nLog: " + total_log);
} catch (BadImageFormatException f) {
Context.ReportError(6, "Bad file format while loading assembly\nLog: " + f.FusionLog);
} catch (FileLoadException f) {
Context.ReportError(6, "File Load Exception: " + assemblyName + "\nLog: " + f.FusionLog);
} catch (ArgumentNullException) {
Context.ReportError(6, "Argument Null exception");
}
errors++;
}
void LoadModule(MethodInfo adder_method, AssemblyBuilder assemblyBuilder, ModuleAdder adder, string module, ref int errors)
{
System.Reflection.Module m;
string total_log = "";
try {
try {
m = (System.Reflection.Module)adder_method.Invoke(assemblyBuilder, new object[] { module });
} catch (TargetInvocationException ex) {
throw ex.InnerException;
}
adder(m);
} catch (FileNotFoundException) {
foreach (string dir in PathsToSearchForLibraries) {
string full_path = Path.Combine(dir, module);
if (!module.EndsWith(".netmodule", StringComparison.Ordinal))
full_path += ".netmodule";
try {
try {
m = (System.Reflection.Module)adder_method.Invoke(assemblyBuilder, new object[] { full_path });
} catch (TargetInvocationException ex) {
throw ex.InnerException;
}
adder(m);
return;
} catch (FileNotFoundException ff) {
total_log += ff.FusionLog;
continue;
}
}
Context.ReportError(6, "Cannot find module `" + module + "'");
WriteLine("Log: \n" + total_log);
} catch (BadImageFormatException f) {
Context.ReportError(6, "Cannot load module (bad file format)" + f.FusionLog);
} catch (FileLoadException f) {
Context.ReportError(6, "Cannot load module " + f.FusionLog);
} catch (ArgumentNullException) {
Context.ReportError(6, "Cannot load module (null argument)");
}
errors++;
}
//
// Given a path specification, splits the path from the file/pattern
//
void SplitPathAndPattern(string spec, out string path, out string pattern)
{
int p = spec.LastIndexOf("/", StringComparison.Ordinal);
if (p != -1) {
//
// Windows does not like /file.cs, switch that to:
// "\", "file.cs"
//
if (p == 0) {
path = "\\";
pattern = spec.Substring(1);
} else {
path = spec.Substring(0, p);
pattern = spec.Substring(p + 1);
}
return;
}
p = spec.LastIndexOf("\\", StringComparison.Ordinal);
if (p != -1) {
path = spec.Substring(0, p);
pattern = spec.Substring(p + 1);
return;
}
path = ".";
pattern = spec;
}
}
public class CommonCompilerOptions2 : CommonCompilerOptions
{
[Option("Filealign internal blocks to the {blocksize} in bytes. Valid values are 512, 1024, 2048, 4096, and 8192.", Name = "filealign", SecondLevelHelp = true)]
public int FileAlignBlockSize = 0;
[Option("Generate documentation from xml commments.", Name = "doc", SecondLevelHelp = true, VBCStyleBoolean = true)]
public bool GenerateXmlDocumentation = false;
// 0 means use appropriate (not fixed) default
[Option("Generate documentation from xml commments to an specific {file}.", Name = "docto", SecondLevelHelp = true)]
public string GenerateXmlDocumentationToFileName = null;
[Option("What {action} (prompt | send | none) should be done when an internal compiler error occurs.\tThe default is none what just prints the error data in the compiler output", Name = "errorreport", SecondLevelHelp = true)]
public InternalCompilerErrorReportAction HowToReportErrors = InternalCompilerErrorReportAction.none;
[Option("Specify target CPU platform {ID}. ID can be x86, Itanium, x64 (AMD 64bit) or anycpu (the default).", Name = "platform", SecondLevelHelp = true)]
public string TargetPlatform;
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\BehaviorTree\BehaviorTreeComponent.h:81
namespace UnrealEngine
{
public partial class UBehaviorTreeComponent : UBrainComponent
{
public UBehaviorTreeComponent(IntPtr adress)
: base(adress)
{
}
public UBehaviorTreeComponent(UObject Parent = null, string Name = "BehaviorTreeComponent")
: base(IntPtr.Zero)
{
NativePointer = E_NewObject_UBehaviorTreeComponent(Parent, Name);
NativeManager.AddNativeWrapper(NativePointer, this);
}
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern int E_PROP_UBehaviorTreeComponent_ChildIndex_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UBehaviorTreeComponent_ChildIndex_SET(IntPtr Ptr, int Value);
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_NewObject_UBehaviorTreeComponent(IntPtr Parent, string Name);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern int E_UBehaviorTreeComponent_FindInstanceContainingNode(IntPtr self, IntPtr node);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern ObjectPointerDescription E_UBehaviorTreeComponent_FindTemplateNode(IntPtr self, IntPtr node);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern ObjectPointerDescription E_UBehaviorTreeComponent_GetActiveNode(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern ObjectPointerDescription E_UBehaviorTreeComponent_GetCurrentTree(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_UBehaviorTreeComponent_GetNodeMemory(IntPtr self, IntPtr node, int instanceIdx);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern ObjectPointerDescription E_UBehaviorTreeComponent_GetRootTree(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UBehaviorTreeComponent_IsAbortPending(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UBehaviorTreeComponent_IsExecutingBranch(IntPtr self, IntPtr node);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UBehaviorTreeComponent_IsRestartPending(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBehaviorTreeComponent_ProcessExecutionRequest(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBehaviorTreeComponent_RegisterMessageObserver(IntPtr self, IntPtr taskNode, string messageType);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBehaviorTreeComponent_RegisterParallelTask(IntPtr self, IntPtr taskNode);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBehaviorTreeComponent_RequestExecution(IntPtr self, IntPtr requestedBy);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBehaviorTreeComponent_RestartTree(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBehaviorTreeComponent_ScheduleExecutionUpdate(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UBehaviorTreeComponent_TreeHasBeenStarted(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBehaviorTreeComponent_UnregisterAuxNodesInBranch(IntPtr self, IntPtr node, bool bApplyImmediately);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBehaviorTreeComponent_UnregisterAuxNodesInRange(IntPtr self, IntPtr fromIndex, IntPtr toIndex);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBehaviorTreeComponent_UnregisterAuxNodesUpTo(IntPtr self, IntPtr index);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBehaviorTreeComponent_UnregisterMessageObserversFrom(IntPtr self, IntPtr taskNode);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBehaviorTreeComponent_UnregisterMessageObserversFrom_o1(IntPtr self, IntPtr taskIdx);
#endregion
#region Property
public int ChildIndex
{
get => E_PROP_UBehaviorTreeComponent_ChildIndex_GET(NativePointer);
set => E_PROP_UBehaviorTreeComponent_ChildIndex_SET(NativePointer, value);
}
#endregion
#region ExternMethods
/// <summary>
/// tries to find behavior tree instance in context
/// </summary>
public int FindInstanceContainingNode(UBTNode node)
=> E_UBehaviorTreeComponent_FindInstanceContainingNode(this, node);
/// <summary>
/// tries to find template node for given instanced node
/// </summary>
public UBTNode FindTemplateNode(UBTNode node)
=> E_UBehaviorTreeComponent_FindTemplateNode(this, node);
/// <summary>
/// </summary>
/// <return>active</return>
public UBTNode GetActiveNode()
=> E_UBehaviorTreeComponent_GetActiveNode(this);
/// <summary>
/// </summary>
/// <return>current</return>
public UBehaviorTree GetCurrentTree()
=> E_UBehaviorTreeComponent_GetCurrentTree(this);
/// <summary>
/// </summary>
/// <return>node</return>
public byte GetNodeMemory(UBTNode node, int instanceIdx)
=> E_UBehaviorTreeComponent_GetNodeMemory(this, node, instanceIdx);
/// <summary>
/// </summary>
/// <return>tree</return>
public UBehaviorTree GetRootTree()
=> E_UBehaviorTreeComponent_GetRootTree(this);
/// <summary>
/// </summary>
/// <return>true</return>
public bool IsAbortPending()
=> E_UBehaviorTreeComponent_IsAbortPending(this);
/// <summary>
/// </summary>
/// <return>true</return>
public bool IsExecutingBranch(UBTNode node)
=> E_UBehaviorTreeComponent_IsExecutingBranch(this, node);
/// <summary>
/// </summary>
/// <return>true</return>
public bool IsRestartPending()
=> E_UBehaviorTreeComponent_IsRestartPending(this);
/// <summary>
/// process execution flow
/// </summary>
public void ProcessExecutionRequest()
=> E_UBehaviorTreeComponent_ProcessExecutionRequest(this);
/// <summary>
/// setup message observer for given task
/// </summary>
public void RegisterMessageObserver(UBTTaskNode taskNode, string messageType)
=> E_UBehaviorTreeComponent_RegisterMessageObserver(this, taskNode, messageType);
/// <summary>
/// add active parallel task
/// </summary>
public void RegisterParallelTask(UBTTaskNode taskNode)
=> E_UBehaviorTreeComponent_RegisterParallelTask(this, taskNode);
/// <summary>
/// request execution change: helpers for decorator nodes
/// </summary>
public void RequestExecution(UBTDecorator requestedBy)
=> E_UBehaviorTreeComponent_RequestExecution(this, requestedBy);
/// <summary>
/// restarts execution from root
/// </summary>
public void RestartTree()
=> E_UBehaviorTreeComponent_RestartTree(this);
/// <summary>
/// schedule execution flow update in next tick
/// </summary>
public void ScheduleExecutionUpdate()
=> E_UBehaviorTreeComponent_ScheduleExecutionUpdate(this);
/// <summary>
/// indicates instance has been initialized to work with specific BT asset
/// </summary>
public bool TreeHasBeenStarted()
=> E_UBehaviorTreeComponent_TreeHasBeenStarted(this);
/// <summary>
/// unregister all aux nodes in branch of tree
/// </summary>
public void UnregisterAuxNodesInBranch(UBTCompositeNode node, bool bApplyImmediately = true)
=> E_UBehaviorTreeComponent_UnregisterAuxNodesInBranch(this, node, bApplyImmediately);
/// <summary>
/// unregister all aux nodes between given execution index range: FromIndex < AuxIndex < ToIndex
/// </summary>
public void UnregisterAuxNodesInRange(FBTNodeIndex fromIndex, FBTNodeIndex toIndex)
=> E_UBehaviorTreeComponent_UnregisterAuxNodesInRange(this, fromIndex, toIndex);
/// <summary>
/// unregister all aux nodes less important than given index
/// </summary>
public void UnregisterAuxNodesUpTo(FBTNodeIndex index)
=> E_UBehaviorTreeComponent_UnregisterAuxNodesUpTo(this, index);
/// <summary>
/// remove message observers registered with task
/// </summary>
public void UnregisterMessageObserversFrom(UBTTaskNode taskNode)
=> E_UBehaviorTreeComponent_UnregisterMessageObserversFrom(this, taskNode);
public void UnregisterMessageObserversFrom(FBTNodeIndex taskIdx)
=> E_UBehaviorTreeComponent_UnregisterMessageObserversFrom_o1(this, taskIdx);
#endregion
public static implicit operator IntPtr(UBehaviorTreeComponent self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator UBehaviorTreeComponent(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<UBehaviorTreeComponent>(PtrDesc);
}
}
}
| |
namespace Nancy.Bootstrapper
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Nancy.Extensions;
/// <summary>
/// Scans the app domain for assemblies and types
/// </summary>
public static class AppDomainAssemblyTypeScanner
{
static AppDomainAssemblyTypeScanner()
{
LoadAssembliesWithNancyReferences();
}
/// <summary>
/// Nancy core assembly
/// </summary>
private static Assembly nancyAssembly = typeof(NancyEngine).Assembly;
/// <summary>
/// App domain type cache
/// </summary>
private static IEnumerable<Type> types;
/// <summary>
/// App domain assemblies cache
/// </summary>
private static IEnumerable<Assembly> assemblies;
/// <summary>
/// Indicates whether the all Assemblies, that references a Nancy assembly, have already been loaded
/// </summary>
private static bool nancyReferencingAssembliesLoaded;
private static IEnumerable<Func<Assembly, bool>> assembliesToScan;
/// <summary>
/// The default assemblies for scanning.
/// Includes the nancy assembly and anything referencing a nancy assembly
/// </summary>
public static Func<Assembly, bool>[] DefaultAssembliesToScan = new Func<Assembly, bool>[]
{
x => x == nancyAssembly,
x =>
{
return !x.GetName().Name.StartsWith("Nancy.Testing",StringComparison.OrdinalIgnoreCase) &&
x.GetReferencedAssemblies().Any(r => r.Name.StartsWith("Nancy", StringComparison.OrdinalIgnoreCase));
}
};
/// <summary>
/// Gets or sets a set of rules for which assemblies are scanned
/// Defaults to just assemblies that have references to nancy, and nancy
/// itself.
/// Each item in the enumerable is a delegate that takes the assembly and
/// returns true if it is to be included. Returning false doesn't mean it won't
/// be included as a true from another delegate will take precedence.
/// </summary>
public static IEnumerable<Func<Assembly, bool>> AssembliesToScan
{
private get
{
return assembliesToScan ?? (assembliesToScan = DefaultAssembliesToScan);
}
set
{
assembliesToScan = value;
UpdateTypes();
}
}
/// <summary>
/// Gets app domain types.
/// </summary>
public static IEnumerable<Type> Types
{
get
{
return types;
}
}
/// <summary>
/// Gets app domain types.
/// </summary>
public static IEnumerable<Assembly> Assemblies
{
get
{
return assemblies;
}
}
/// <summary>
/// Add assemblies to the list of assemblies to scan for Nancy types
/// </summary>
/// <param name="assemblyNames">One or more assembly names</param>
public static void AddAssembliesToScan(params string[] assemblyNames)
{
var normalisedNames = GetNormalisedAssemblyNames(assemblyNames).ToArray();
foreach (var assemblyName in normalisedNames)
{
LoadAssemblies(assemblyName + ".dll");
LoadAssemblies(assemblyName + ".exe");
}
var scanningPredicates = normalisedNames.Select(s =>
{
return (Func<Assembly, bool>)(a => a.GetName().Name == s);
});
AssembliesToScan = AssembliesToScan.Union(scanningPredicates);
}
/// <summary>
/// Add assemblies to the list of assemblies to scan for Nancy types
/// </summary>
/// <param name="assemblies">One of more assemblies</param>
public static void AddAssembliesToScan(params Assembly[] assemblies)
{
foreach (var assembly in assemblies)
{
LoadAssemblies(assembly.GetName() + ".dll");
LoadAssemblies(assembly.GetName() + ".exe");
}
var scanningPredicates = assemblies.Select(an => (Func<Assembly, bool>)(a => a == an));
AssembliesToScan = AssembliesToScan.Union(scanningPredicates);
}
/// <summary>
/// Add predicates for determining which assemblies to scan for Nancy types
/// </summary>
/// <param name="predicates">One or more predicates</param>
public static void AddAssembliesToScan(params Func<Assembly, bool>[] predicates)
{
AssembliesToScan = AssembliesToScan.Union(predicates);
}
/// <summary>
/// Load assemblies from a the app domain base directory matching a given wildcard.
/// Assemblies will only be loaded if they aren't already in the appdomain.
/// </summary>
/// <param name="wildcardFilename">Wildcard to match the assemblies to load</param>
public static void LoadAssemblies(string wildcardFilename)
{
foreach (var directory in GetAssemblyDirectories())
{
LoadAssemblies(directory, wildcardFilename);
}
}
/// <summary>
/// Load assemblies from a given directory matching a given wildcard.
/// Assemblies will only be loaded if they aren't already in the appdomain.
/// </summary>
/// <param name="containingDirectory">Directory containing the assemblies</param>
/// <param name="wildcardFilename">Wildcard to match the assemblies to load</param>
public static void LoadAssemblies(string containingDirectory, string wildcardFilename)
{
UpdateAssemblies();
var existingAssemblyPaths = assemblies.Select(a => a.Location).ToArray();
var unloadedAssemblies =
Directory.GetFiles(containingDirectory, wildcardFilename).Where(
f => !existingAssemblyPaths.Contains(f, StringComparer.InvariantCultureIgnoreCase)).ToArray();
foreach (var unloadedAssembly in unloadedAssemblies)
{
Assembly.Load(AssemblyName.GetAssemblyName(unloadedAssembly));
}
UpdateTypes();
}
/// <summary>
/// Refreshes the type cache if additional assemblies have been loaded.
/// Note: This is called automatically if assemblies are loaded using LoadAssemblies.
/// </summary>
public static void UpdateTypes()
{
UpdateAssemblies();
types = (from assembly in assemblies
from type in assembly.SafeGetExportedTypes()
where !type.IsAbstract
select type).ToArray();
}
/// <summary>
/// Updates the assembly cache from the appdomain
/// </summary>
private static void UpdateAssemblies()
{
assemblies = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
where AssembliesToScan.Any(asm => asm(assembly))
where !assembly.IsDynamic
where !assembly.ReflectionOnly
select assembly).ToArray();
}
/// <summary>
/// Loads any assembly that references a Nancy assembly.
/// </summary>
public static void LoadAssembliesWithNancyReferences()
{
if (nancyReferencingAssembliesLoaded)
{
return;
}
UpdateAssemblies();
var existingAssemblyPaths =
assemblies.Select(a => a.Location).ToArray();
foreach (var directory in GetAssemblyDirectories())
{
var unloadedAssemblies = Directory
.GetFiles(directory, "*.dll")
.Where(f => !existingAssemblyPaths.Contains(f, StringComparer.InvariantCultureIgnoreCase)).ToArray();
foreach (var unloadedAssembly in unloadedAssemblies)
{
Assembly inspectedAssembly = null;
try
{
inspectedAssembly = Assembly.ReflectionOnlyLoadFrom(unloadedAssembly);
}
catch (BadImageFormatException biEx)
{
//the assembly maybe it's not managed code
}
if (inspectedAssembly != null && inspectedAssembly.GetReferencedAssemblies().Any(r => r.Name.StartsWith("Nancy", StringComparison.OrdinalIgnoreCase)))
{
try
{
Assembly.Load(inspectedAssembly.GetName());
}
catch
{
}
}
}
}
UpdateTypes();
nancyReferencingAssembliesLoaded = true;
}
/// <summary>
/// Gets all types implementing a particular interface/base class
/// </summary>
/// <param name="type">Type to search for</param>
/// <returns>An <see cref="IEnumerable{T}"/> of types.</returns>
/// <remarks>Will scan with <see cref="ScanMode.All"/>.</remarks>
public static IEnumerable<Type> TypesOf(Type type)
{
return TypesOf(type, ScanMode.All);
}
/// <summary>
/// Gets all types implementing a particular interface/base class
/// </summary>
/// <param name="type">Type to search for</param>
/// <param name="mode">A <see cref="ScanMode"/> value to determine which type set to scan in.</param>
/// <returns>An <see cref="IEnumerable{T}"/> of types.</returns>
public static IEnumerable<Type> TypesOf(Type type, ScanMode mode)
{
var returnTypes =
Types.Where(type.IsAssignableFrom);
switch (mode)
{
case ScanMode.OnlyNancy:
return returnTypes.Where(t => t.Assembly == nancyAssembly);
case ScanMode.ExcludeNancy:
return returnTypes.Where(t => t.Assembly != nancyAssembly);
case ScanMode.OnlyNancyNamespace:
return returnTypes.Where(t => t.Namespace.StartsWith("Nancy"));
case ScanMode.ExcludeNancyNamespace:
return returnTypes.Where(t => !t.Namespace.StartsWith("Nancy"));
default://mode == ScanMode.All
return returnTypes;
}
}
/// <summary>
/// Gets all types implementing a particular interface/base class
/// </summary>
/// <typeparam name="TType">Type to search for</typeparam>
/// <returns>An <see cref="IEnumerable{T}"/> of types.</returns>
/// <remarks>Will scan with <see cref="ScanMode.All"/>.</remarks>
public static IEnumerable<Type> TypesOf<TType>()
{
return TypesOf<TType>(ScanMode.All);
}
/// <summary>
/// Gets all types implementing a particular interface/base class
/// </summary>
/// <typeparam name="TType">Type to search for</typeparam>
/// <param name="mode">A <see cref="ScanMode"/> value to determine which type set to scan in.</param>
/// <returns>An <see cref="IEnumerable{T}"/> of types.</returns>
public static IEnumerable<Type> TypesOf<TType>(ScanMode mode)
{
return TypesOf(typeof(TType), mode);
}
/// <summary>
/// Returns the directories containing dll files. It uses the default convention as stated by microsoft.
/// </summary>
/// <see cref="http://msdn.microsoft.com/en-us/library/system.appdomainsetup.privatebinpathprobe.aspx"/>
private static IEnumerable<string> GetAssemblyDirectories()
{
var privateBinPathDirectories = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath == null
? new string[] { }
: AppDomain.CurrentDomain.SetupInformation.PrivateBinPath.Split(';');
foreach (var privateBinPathDirectory in privateBinPathDirectories)
{
if (!string.IsNullOrWhiteSpace(privateBinPathDirectory))
{
yield return privateBinPathDirectory;
}
}
if (AppDomain.CurrentDomain.SetupInformation.PrivateBinPathProbe == null)
{
yield return AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
}
}
private static IEnumerable<string> GetNormalisedAssemblyNames(string[] assemblyNames)
{
foreach (var assemblyName in assemblyNames)
{
if (assemblyName.EndsWith(".dll") || assemblyName.EndsWith(".exe"))
{
yield return Path.GetFileNameWithoutExtension(assemblyName);
}
else
{
yield return assemblyName;
}
}
}
}
public static class AppDomainAssemblyTypeScannerExtensions
{
public static IEnumerable<Type> NotOfType<TType>(this IEnumerable<Type> types)
{
return types.Where(t => !typeof(TType).IsAssignableFrom(t));
}
}
}
| |
// <copyright file="ArrayStatistics.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2015 Math.NET
//
// 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.
// </copyright>
using System;
using MathNet.Numerics.Properties;
namespace MathNet.Numerics.Statistics
{
/// <summary>
/// Statistics operating on arrays assumed to be unsorted.
/// WARNING: Methods with the Inplace-suffix may modify the data array by reordering its entries.
/// </summary>
/// <seealso cref="SortedArrayStatistics"/>
/// <seealso cref="StreamingStatistics"/>
/// <seealso cref="Statistics"/>
public static partial class ArrayStatistics
{
// TODO: Benchmark various options to find out the best approach (-> branch prediction)
// TODO: consider leveraging MKL
/// <summary>
/// Returns the smallest value from the unsorted data array.
/// Returns NaN if data is empty or any entry is NaN.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed.</param>
public static double Minimum(double[] data)
{
if (data.Length == 0)
{
return double.NaN;
}
double min = double.PositiveInfinity;
for (int i = 0; i < data.Length; i++)
{
if (data[i] < min || double.IsNaN(data[i]))
{
min = data[i];
}
}
return min;
}
/// <summary>
/// Returns the largest value from the unsorted data array.
/// Returns NaN if data is empty or any entry is NaN.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed.</param>
public static double Maximum(double[] data)
{
if (data.Length == 0)
{
return double.NaN;
}
double max = double.NegativeInfinity;
for (int i = 0; i < data.Length; i++)
{
if (data[i] > max || double.IsNaN(data[i]))
{
max = data[i];
}
}
return max;
}
/// <summary>
/// Returns the smallest absolute value from the unsorted data array.
/// Returns NaN if data is empty or any entry is NaN.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed.</param>
public static double MinimumAbsolute(double[] data)
{
if (data.Length == 0)
{
return double.NaN;
}
double min = double.PositiveInfinity;
for (int i = 0; i < data.Length; i++)
{
if (Math.Abs(data[i]) < min || double.IsNaN(data[i]))
{
min = Math.Abs(data[i]);
}
}
return min;
}
/// <summary>
/// Returns the largest absolute value from the unsorted data array.
/// Returns NaN if data is empty or any entry is NaN.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed.</param>
public static double MaximumAbsolute(double[] data)
{
if (data.Length == 0)
{
return double.NaN;
}
double max = 0.0d;
for (int i = 0; i < data.Length; i++)
{
if (Math.Abs(data[i]) > max || double.IsNaN(data[i]))
{
max = Math.Abs(data[i]);
}
}
return max;
}
/// <summary>
/// Estimates the arithmetic sample mean from the unsorted data array.
/// Returns NaN if data is empty or any entry is NaN.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed.</param>
public static double Mean(double[] data)
{
if (data.Length == 0)
{
return double.NaN;
}
double mean = 0;
ulong m = 0;
for (int i = 0; i < data.Length; i++)
{
mean += (data[i] - mean)/++m;
}
return mean;
}
/// <summary>
/// Evaluates the geometric mean of the unsorted data array.
/// Returns NaN if data is empty or any entry is NaN.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed.</param>
public static double GeometricMean(double[] data)
{
if (data.Length == 0)
{
return double.NaN;
}
double sum = 0;
for (int i = 0; i < data.Length; i++)
{
sum += Math.Log(data[i]);
}
return Math.Exp(sum/data.Length);
}
/// <summary>
/// Evaluates the harmonic mean of the unsorted data array.
/// Returns NaN if data is empty or any entry is NaN.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed.</param>
public static double HarmonicMean(double[] data)
{
if (data.Length == 0)
{
return double.NaN;
}
double sum = 0;
for (int i = 0; i < data.Length; i++)
{
sum += 1.0/data[i];
}
return data.Length/sum;
}
/// <summary>
/// Estimates the unbiased population variance from the provided samples as unsorted array.
/// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
/// Returns NaN if data has less than two entries or if any entry is NaN.
/// </summary>
/// <param name="samples">Sample array, no sorting is assumed.</param>
public static double Variance(double[] samples)
{
if (samples.Length <= 1)
{
return double.NaN;
}
double variance = 0;
double t = samples[0];
for (int i = 1; i < samples.Length; i++)
{
t += samples[i];
double diff = ((i + 1)*samples[i]) - t;
variance += (diff*diff)/((i + 1.0)*i);
}
return variance/(samples.Length - 1);
}
/// <summary>
/// Evaluates the population variance from the full population provided as unsorted array.
/// On a dataset of size N will use an N normalizer and would thus be biased if applied to a subset.
/// Returns NaN if data is empty or if any entry is NaN.
/// </summary>
/// <param name="population">Sample array, no sorting is assumed.</param>
public static double PopulationVariance(double[] population)
{
if (population.Length == 0)
{
return double.NaN;
}
double variance = 0;
double t = population[0];
for (int i = 1; i < population.Length; i++)
{
t += population[i];
double diff = ((i + 1)*population[i]) - t;
variance += (diff*diff)/((i + 1.0)*i);
}
return variance/population.Length;
}
/// <summary>
/// Estimates the unbiased population standard deviation from the provided samples as unsorted array.
/// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
/// Returns NaN if data has less than two entries or if any entry is NaN.
/// </summary>
/// <param name="samples">Sample array, no sorting is assumed.</param>
public static double StandardDeviation(double[] samples)
{
return Math.Sqrt(Variance(samples));
}
/// <summary>
/// Evaluates the population standard deviation from the full population provided as unsorted array.
/// On a dataset of size N will use an N normalizer and would thus be biased if applied to a subset.
/// Returns NaN if data is empty or if any entry is NaN.
/// </summary>
/// <param name="population">Sample array, no sorting is assumed.</param>
public static double PopulationStandardDeviation(double[] population)
{
return Math.Sqrt(PopulationVariance(population));
}
/// <summary>
/// Estimates the arithmetic sample mean and the unbiased population variance from the provided samples as unsorted array.
/// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
/// Returns NaN for mean if data is empty or any entry is NaN and NaN for variance if data has less than two entries or if any entry is NaN.
/// </summary>
/// <param name="samples">Sample array, no sorting is assumed.</param>
public static Tuple<double, double> MeanVariance(double[] samples)
{
return new Tuple<double, double>(Mean(samples), Variance(samples));
}
/// <summary>
/// Estimates the arithmetic sample mean and the unbiased population standard deviation from the provided samples as unsorted array.
/// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
/// Returns NaN for mean if data is empty or any entry is NaN and NaN for standard deviation if data has less than two entries or if any entry is NaN.
/// </summary>
/// <param name="samples">Sample array, no sorting is assumed.</param>
public static Tuple<double, double> MeanStandardDeviation(double[] samples)
{
return new Tuple<double, double>(Mean(samples), StandardDeviation(samples));
}
/// <summary>
/// Estimates the unbiased population covariance from the provided two sample arrays.
/// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
/// Returns NaN if data has less than two entries or if any entry is NaN.
/// </summary>
/// <param name="samples1">First sample array.</param>
/// <param name="samples2">Second sample array.</param>
public static double Covariance(double[] samples1, double[] samples2)
{
if (samples1.Length != samples2.Length)
{
throw new ArgumentException(Resources.ArgumentVectorsSameLength);
}
if (samples1.Length <= 1)
{
return double.NaN;
}
double mean1 = Mean(samples1);
double mean2 = Mean(samples2);
double covariance = 0.0;
for (int i = 0; i < samples1.Length; i++)
{
covariance += (samples1[i] - mean1)*(samples2[i] - mean2);
}
return covariance/(samples1.Length - 1);
}
/// <summary>
/// Evaluates the population covariance from the full population provided as two arrays.
/// On a dataset of size N will use an N normalizer and would thus be biased if applied to a subset.
/// Returns NaN if data is empty or if any entry is NaN.
/// </summary>
/// <param name="population1">First population array.</param>
/// <param name="population2">Second population array.</param>
public static double PopulationCovariance(double[] population1, double[] population2)
{
if (population1.Length != population2.Length)
{
throw new ArgumentException(Resources.ArgumentVectorsSameLength);
}
if (population1.Length == 0)
{
return double.NaN;
}
double mean1 = Mean(population1);
double mean2 = Mean(population2);
double covariance = 0.0;
for (int i = 0; i < population1.Length; i++)
{
covariance += (population1[i] - mean1)*(population2[i] - mean2);
}
return covariance/population1.Length;
}
/// <summary>
/// Estimates the root mean square (RMS) also known as quadratic mean from the unsorted data array.
/// Returns NaN if data is empty or any entry is NaN.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed.</param>
public static double RootMeanSquare(double[] data)
{
if (data.Length == 0)
{
return double.NaN;
}
double mean = 0;
ulong m = 0;
for (int i = 0; i < data.Length; i++)
{
mean += (data[i]*data[i] - mean)/++m;
}
return Math.Sqrt(mean);
}
/// <summary>
/// Returns the order statistic (order 1..N) from the unsorted data array.
/// WARNING: Works inplace and can thus causes the data array to be reordered.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param>
/// <param name="order">One-based order of the statistic, must be between 1 and N (inclusive).</param>
public static double OrderStatisticInplace(double[] data, int order)
{
if (order < 1 || order > data.Length)
{
return double.NaN;
}
if (order == 1)
{
return Minimum(data);
}
if (order == data.Length)
{
return Maximum(data);
}
return SelectInplace(data, order - 1);
}
/// <summary>
/// Estimates the median value from the unsorted data array.
/// WARNING: Works inplace and can thus causes the data array to be reordered.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param>
public static double MedianInplace(double[] data)
{
var k = data.Length/2;
return data.Length.IsOdd()
? SelectInplace(data, k)
: (SelectInplace(data, k - 1) + SelectInplace(data, k))/2.0;
}
/// <summary>
/// Estimates the p-Percentile value from the unsorted data array.
/// If a non-integer Percentile is needed, use Quantile instead.
/// Approximately median-unbiased regardless of the sample distribution (R8).
/// WARNING: Works inplace and can thus causes the data array to be reordered.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param>
/// <param name="p">Percentile selector, between 0 and 100 (inclusive).</param>
public static double PercentileInplace(double[] data, int p)
{
return QuantileInplace(data, p/100d);
}
/// <summary>
/// Estimates the first quartile value from the unsorted data array.
/// Approximately median-unbiased regardless of the sample distribution (R8).
/// WARNING: Works inplace and can thus causes the data array to be reordered.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param>
public static double LowerQuartileInplace(double[] data)
{
return QuantileInplace(data, 0.25d);
}
/// <summary>
/// Estimates the third quartile value from the unsorted data array.
/// Approximately median-unbiased regardless of the sample distribution (R8).
/// WARNING: Works inplace and can thus causes the data array to be reordered.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param>
public static double UpperQuartileInplace(double[] data)
{
return QuantileInplace(data, 0.75d);
}
/// <summary>
/// Estimates the inter-quartile range from the unsorted data array.
/// Approximately median-unbiased regardless of the sample distribution (R8).
/// WARNING: Works inplace and can thus causes the data array to be reordered.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param>
public static double InterquartileRangeInplace(double[] data)
{
return QuantileInplace(data, 0.75d) - QuantileInplace(data, 0.25d);
}
/// <summary>
/// Estimates {min, lower-quantile, median, upper-quantile, max} from the unsorted data array.
/// Approximately median-unbiased regardless of the sample distribution (R8).
/// WARNING: Works inplace and can thus causes the data array to be reordered.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param>
public static double[] FiveNumberSummaryInplace(double[] data)
{
if (data.Length == 0)
{
return new[] { double.NaN, double.NaN, double.NaN, double.NaN, double.NaN };
}
// TODO: Benchmark: is this still faster than sorting the array then using SortedArrayStatistics instead?
return new[] { Minimum(data), QuantileInplace(data, 0.25d), MedianInplace(data), QuantileInplace(data, 0.75d), Maximum(data) };
}
/// <summary>
/// Estimates the tau-th quantile from the unsorted data array.
/// The tau-th quantile is the data value where the cumulative distribution
/// function crosses tau.
/// Approximately median-unbiased regardless of the sample distribution (R8).
/// WARNING: Works inplace and can thus causes the data array to be reordered.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param>
/// <param name="tau">Quantile selector, between 0.0 and 1.0 (inclusive).</param>
/// <remarks>
/// R-8, SciPy-(1/3,1/3):
/// Linear interpolation of the approximate medians for order statistics.
/// When tau < (2/3) / (N + 1/3), use x1. When tau >= (N - 1/3) / (N + 1/3), use xN.
/// </remarks>
public static double QuantileInplace(double[] data, double tau)
{
if (tau < 0d || tau > 1d || data.Length == 0)
{
return double.NaN;
}
double h = (data.Length + 1d/3d)*tau + 1d/3d;
var hf = (int)h;
if (hf <= 0 || tau == 0d)
{
return Minimum(data);
}
if (hf >= data.Length || tau == 1d)
{
return Maximum(data);
}
var a = SelectInplace(data, hf - 1);
var b = SelectInplace(data, hf);
return a + (h - hf)*(b - a);
}
/// <summary>
/// Estimates the tau-th quantile from the unsorted data array.
/// The tau-th quantile is the data value where the cumulative distribution
/// function crosses tau. The quantile defintion can be specified
/// by 4 parameters a, b, c and d, consistent with Mathematica.
/// WARNING: Works inplace and can thus causes the data array to be reordered.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param>
/// <param name="tau">Quantile selector, between 0.0 and 1.0 (inclusive)</param>
/// <param name="a">a-parameter</param>
/// <param name="b">b-parameter</param>
/// <param name="c">c-parameter</param>
/// <param name="d">d-parameter</param>
public static double QuantileCustomInplace(double[] data, double tau, double a, double b, double c, double d)
{
if (tau < 0d || tau > 1d || data.Length == 0)
{
return double.NaN;
}
var x = a + (data.Length + b)*tau - 1;
#if PORTABLE
var ip = (int)x;
#else
var ip = Math.Truncate(x);
#endif
var fp = x - ip;
if (Math.Abs(fp) < 1e-9)
{
return SelectInplace(data, (int)ip);
}
var lower = SelectInplace(data, (int)Math.Floor(x));
var upper = SelectInplace(data, (int)Math.Ceiling(x));
return lower + (upper - lower)*(c + d*fp);
}
/// <summary>
/// Estimates the tau-th quantile from the unsorted data array.
/// The tau-th quantile is the data value where the cumulative distribution
/// function crosses tau. The quantile definition can be specified to be compatible
/// with an existing system.
/// WARNING: Works inplace and can thus causes the data array to be reordered.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param>
/// <param name="tau">Quantile selector, between 0.0 and 1.0 (inclusive)</param>
/// <param name="definition">Quantile definition, to choose what product/definition it should be consistent with</param>
public static double QuantileCustomInplace(double[] data, double tau, QuantileDefinition definition)
{
if (tau < 0d || tau > 1d || data.Length == 0)
{
return double.NaN;
}
if (tau == 0d || data.Length == 1)
{
return Minimum(data);
}
if (tau == 1d)
{
return Maximum(data);
}
switch (definition)
{
case QuantileDefinition.R1:
{
double h = data.Length*tau + 0.5d;
return SelectInplace(data, (int)Math.Ceiling(h - 0.5d) - 1);
}
case QuantileDefinition.R2:
{
double h = data.Length*tau + 0.5d;
return (SelectInplace(data, (int)Math.Ceiling(h - 0.5d) - 1) + SelectInplace(data, (int)(h + 0.5d) - 1))*0.5d;
}
case QuantileDefinition.R3:
{
double h = data.Length*tau;
return SelectInplace(data, (int)Math.Round(h) - 1);
}
case QuantileDefinition.R4:
{
double h = data.Length*tau;
var hf = (int)h;
var lower = SelectInplace(data, hf - 1);
var upper = SelectInplace(data, hf);
return lower + (h - hf)*(upper - lower);
}
case QuantileDefinition.R5:
{
double h = data.Length*tau + 0.5d;
var hf = (int)h;
var lower = SelectInplace(data, hf - 1);
var upper = SelectInplace(data, hf);
return lower + (h - hf)*(upper - lower);
}
case QuantileDefinition.R6:
{
double h = (data.Length + 1)*tau;
var hf = (int)h;
var lower = SelectInplace(data, hf - 1);
var upper = SelectInplace(data, hf);
return lower + (h - hf)*(upper - lower);
}
case QuantileDefinition.R7:
{
double h = (data.Length - 1)*tau + 1d;
var hf = (int)h;
var lower = SelectInplace(data, hf - 1);
var upper = SelectInplace(data, hf);
return lower + (h - hf)*(upper - lower);
}
case QuantileDefinition.R8:
{
double h = (data.Length + 1/3d)*tau + 1/3d;
var hf = (int)h;
var lower = SelectInplace(data, hf - 1);
var upper = SelectInplace(data, hf);
return lower + (h - hf)*(upper - lower);
}
case QuantileDefinition.R9:
{
double h = (data.Length + 0.25d)*tau + 0.375d;
var hf = (int)h;
var lower = SelectInplace(data, hf - 1);
var upper = SelectInplace(data, hf);
return lower + (h - hf)*(upper - lower);
}
default:
throw new NotSupportedException();
}
}
static double SelectInplace(double[] workingData, int rank)
{
// Numerical Recipes: select
// http://en.wikipedia.org/wiki/Selection_algorithm
if (rank <= 0)
{
return Minimum(workingData);
}
if (rank >= workingData.Length - 1)
{
return Maximum(workingData);
}
double[] a = workingData;
int low = 0;
int high = a.Length - 1;
while (true)
{
if (high <= low + 1)
{
if (high == low + 1 && a[high] < a[low])
{
var tmp = a[low];
a[low] = a[high];
a[high] = tmp;
}
return a[rank];
}
int middle = (low + high) >> 1;
var tmp1 = a[middle];
a[middle] = a[low + 1];
a[low + 1] = tmp1;
if (a[low] > a[high])
{
var tmp = a[low];
a[low] = a[high];
a[high] = tmp;
}
if (a[low + 1] > a[high])
{
var tmp = a[low + 1];
a[low + 1] = a[high];
a[high] = tmp;
}
if (a[low] > a[low + 1])
{
var tmp = a[low];
a[low] = a[low + 1];
a[low + 1] = tmp;
}
int begin = low + 1;
int end = high;
double pivot = a[begin];
while (true)
{
do
{
begin++;
}
while (a[begin] < pivot);
do
{
end--;
}
while (a[end] > pivot);
if (end < begin)
{
break;
}
var tmp = a[begin];
a[begin] = a[end];
a[end] = tmp;
}
a[low + 1] = a[end];
a[end] = pivot;
if (end >= rank)
{
high = end - 1;
}
if (end <= rank)
{
low = begin;
}
}
}
/// <summary>
/// Evaluates the rank of each entry of the unsorted data array.
/// The rank definition can be specified to be compatible
/// with an existing system.
/// WARNING: Works inplace and can thus causes the data array to be reordered.
/// </summary>
public static double[] RanksInplace(double[] data, RankDefinition definition = RankDefinition.Default)
{
var ranks = new double[data.Length];
var index = new int[data.Length];
for (int i = 0; i < index.Length; i++)
{
index[i] = i;
}
if (definition == RankDefinition.First)
{
Sorting.SortAll(data, index);
for (int i = 0; i < ranks.Length; i++)
{
ranks[index[i]] = i + 1;
}
return ranks;
}
Sorting.Sort(data, index);
int previousIndex = 0;
for (int i = 1; i < data.Length; i++)
{
if (Math.Abs(data[i] - data[previousIndex]) <= 0d)
{
continue;
}
if (i == previousIndex + 1)
{
ranks[index[previousIndex]] = i;
}
else
{
RanksTies(ranks, index, previousIndex, i, definition);
}
previousIndex = i;
}
RanksTies(ranks, index, previousIndex, data.Length, definition);
return ranks;
}
static void RanksTies(double[] ranks, int[] index, int a, int b, RankDefinition definition)
{
// TODO: potential for PERF optimization
double rank;
switch (definition)
{
case RankDefinition.Average:
{
rank = (b + a - 1)/2d + 1;
break;
}
case RankDefinition.Min:
{
rank = a + 1;
break;
}
case RankDefinition.Max:
{
rank = b;
break;
}
default:
throw new NotSupportedException();
}
for (int k = a; k < b; k++)
{
ranks[index[k]] = rank;
}
}
}
}
| |
// ------------------------------------------------------------------------------------
// 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 *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.
// ------------------------------------------------------------------------------------
namespace Amqp
{
using System;
using System.Threading;
using Amqp.Framing;
using Amqp.Sasl;
using Amqp.Types;
/// <summary>
/// The callback that is invoked when an open frame is received from peer.
/// </summary>
/// <param name="connection">The connection.</param>
/// <param name="open">The received open frame.</param>
public delegate void OnOpened(Connection connection, Open open);
/// <summary>
/// The Connection class represents an AMQP connection.
/// </summary>
public class Connection : AmqpObject
{
enum State
{
Start,
HeaderSent,
OpenPipe,
OpenClosePipe,
HeaderReceived,
HeaderExchanged,
OpenSent,
OpenReceived,
Opened,
CloseReceived,
ClosePipe,
CloseSent,
End
}
/// <summary>
/// A flag to disable server certificate validation when TLS is used.
/// </summary>
public static bool DisableServerCertValidation;
internal const uint DefaultMaxFrameSize = 16 * 1024;
internal const ushort DefaultMaxSessions = 256;
const uint MaxIdleTimeout = 30 * 60 * 1000;
static readonly TimerCallback onHeartBeatTimer = OnHeartBeatTimer;
readonly Address address;
readonly OnOpened onOpened;
Session[] localSessions;
Session[] remoteSessions;
ushort channelMax;
State state;
ITransport transport;
uint maxFrameSize;
Pump reader;
Timer heartBeatTimer;
Connection(ushort channelMax, uint maxFrameSize)
{
this.channelMax = channelMax;
this.maxFrameSize = maxFrameSize;
this.localSessions = new Session[1];
this.remoteSessions = new Session[1];
}
/// <summary>
/// Initializes a connection from the address.
/// </summary>
/// <param name="address">The address.</param>
public Connection(Address address)
: this(address, null, null, null)
{
}
/// <summary>
/// Initializes a connection with SASL profile, open and open callback.
/// </summary>
/// <param name="address">The address.</param>
/// <param name="saslProfile">The SASL profile to do authentication (optional). If it is null and address has user info, SASL PLAIN profile is used.</param>
/// <param name="open">The open frame to send (optional). If not null, all mandatory fields must be set. Ensure that other fields are set to desired values.</param>
/// <param name="onOpened">The callback to handle remote open frame (optional).</param>
public Connection(Address address, SaslProfile saslProfile, Open open, OnOpened onOpened)
: this(DefaultMaxSessions, DefaultMaxFrameSize)
{
this.address = address;
this.onOpened = onOpened;
if (open != null)
{
this.maxFrameSize = open.MaxFrameSize;
this.channelMax = open.ChannelMax;
}
else
{
open = new Open()
{
ContainerId = Guid.NewGuid().ToString(),
HostName = this.address.Host,
MaxFrameSize = this.maxFrameSize,
ChannelMax = this.channelMax
};
}
this.Connect(saslProfile, open);
}
#if DOTNET || NETFX_CORE
internal Connection(AmqpSettings amqpSettings, Address address, IAsyncTransport transport, Open open, OnOpened onOpened)
: this((ushort)(amqpSettings.MaxSessionsPerConnection - 1), (uint)amqpSettings.MaxFrameSize)
{
this.address = address;
this.onOpened = onOpened;
this.maxFrameSize = (uint)amqpSettings.MaxFrameSize;
this.transport = transport;
transport.SetConnection(this);
// after getting the transport, move state to open pipe before starting the pump
if (open == null)
{
open = new Open()
{
ContainerId = amqpSettings.ContainerId,
HostName = amqpSettings.HostName ?? this.address.Host,
ChannelMax = this.channelMax,
MaxFrameSize = this.maxFrameSize
};
}
this.SendHeader();
this.SendOpen(open);
this.state = State.OpenPipe;
}
/// <summary>
/// Gets a factory with default settings.
/// </summary>
public static ConnectionFactory Factory
{
get { return new ConnectionFactory(); }
}
#endif
object ThisLock
{
get { return this; }
}
internal ushort AddSession(Session session)
{
this.ThrowIfClosed("AddSession");
lock (this.ThisLock)
{
int count = this.localSessions.Length;
for (int i = 0; i < count; ++i)
{
if (this.localSessions[i] == null)
{
this.localSessions[i] = session;
return (ushort)i;
}
}
if (count - 1 < this.channelMax)
{
int size = Math.Min(count * 2, this.channelMax + 1);
Session[] expanded = new Session[size];
Array.Copy(this.localSessions, expanded, count);
this.localSessions = expanded;
this.localSessions[count] = session;
return (ushort)count;
}
throw new AmqpException(ErrorCode.NotAllowed,
Fx.Format(SRAmqp.AmqpHandleExceeded, this.channelMax));
}
}
internal void SendCommand(ushort channel, DescribedList command)
{
this.ThrowIfClosed("Send");
ByteBuffer buffer = Frame.Encode(FrameType.Amqp, channel, command);
this.transport.Send(buffer);
Trace.WriteLine(TraceLevel.Frame, "SEND (ch={0}) {1}", channel, command);
}
internal void SendCommand(ushort channel, Transfer transfer, ByteBuffer payload)
{
this.ThrowIfClosed("Send");
int payloadSize;
ByteBuffer buffer = Frame.Encode(FrameType.Amqp, channel, transfer, payload, (int)this.maxFrameSize, out payloadSize);
this.transport.Send(buffer);
Trace.WriteLine(TraceLevel.Frame, "SEND (ch={0}) {1} payload {2}", channel, transfer, payloadSize);
}
/// <summary>
/// Closes the connection.
/// </summary>
/// <param name="error"></param>
/// <returns></returns>
protected override bool OnClose(Error error)
{
lock (this.ThisLock)
{
State newState = State.Start;
if (this.state == State.OpenPipe )
{
newState = State.OpenClosePipe;
}
else if (state == State.OpenSent)
{
newState = State.ClosePipe;
}
else if (this.state == State.Opened)
{
newState = State.CloseSent;
}
else if (this.state == State.CloseReceived)
{
newState = State.End;
}
else if (this.state == State.End)
{
return true;
}
else
{
throw new AmqpException(ErrorCode.IllegalState,
Fx.Format(SRAmqp.AmqpIllegalOperationState, "Close", this.state));
}
this.SendClose(error);
this.state = newState;
return this.state == State.End;
}
}
static void OnHeartBeatTimer(object state)
{
var thisPtr = (Connection)state;
byte[] frame = new byte[] { 0, 0, 0, 8, 2, 0, 0, 0 };
thisPtr.transport.Send(new ByteBuffer(frame, 0, frame.Length, frame.Length));
Trace.WriteLine(TraceLevel.Frame, "SEND (ch=0) empty");
}
void Connect(SaslProfile saslProfile, Open open)
{
ITransport transport;
TcpTransport tcpTransport = new TcpTransport();
tcpTransport.Connect(this, this.address, DisableServerCertValidation);
transport = tcpTransport;
if (saslProfile != null)
{
transport = saslProfile.Open(this.address.Host, transport);
}
else if (this.address.User != null)
{
transport = new SaslPlainProfile(this.address.User, this.address.Password).Open(this.address.Host, transport);
}
this.transport = transport;
// after getting the transport, move state to open pipe before starting the pump
this.SendHeader();
this.SendOpen(open);
this.state = State.OpenPipe;
this.reader = new Pump(this);
this.reader.Start();
}
void ThrowIfClosed(string operation)
{
if (this.state >= State.ClosePipe)
{
throw new AmqpException(this.Error ??
new Error()
{
Condition = ErrorCode.IllegalState,
Description = Fx.Format(SRAmqp.AmqpIllegalOperationState, operation, this.state)
});
}
}
void SendHeader()
{
byte[] header = new byte[] { (byte)'A', (byte)'M', (byte)'Q', (byte)'P', 0, 1, 0, 0 };
this.transport.Send(new ByteBuffer(header, 0, header.Length, header.Length));
Trace.WriteLine(TraceLevel.Frame, "SEND AMQP 0 1.0.0");
}
void SendOpen(Open open)
{
this.SendCommand(0, open);
}
void SendClose(Error error)
{
this.SendCommand(0, new Close() { Error = error });
}
void OnOpen(Open open)
{
lock (this.ThisLock)
{
if (this.state == State.OpenSent)
{
this.state = State.Opened;
}
else if (this.state == State.ClosePipe)
{
this.state = State.CloseSent;
}
else
{
throw new AmqpException(ErrorCode.IllegalState,
Fx.Format(SRAmqp.AmqpIllegalOperationState, "OnOpen", this.state));
}
}
if (open.ChannelMax < this.channelMax)
{
this.channelMax = open.ChannelMax;
}
if (open.MaxFrameSize < this.maxFrameSize)
{
this.maxFrameSize = open.MaxFrameSize;
}
uint idleTimeout = open.IdleTimeOut;
if (idleTimeout > 0 && idleTimeout < uint.MaxValue)
{
idleTimeout -= 3000;
if (idleTimeout > MaxIdleTimeout)
{
idleTimeout = MaxIdleTimeout;
}
this.heartBeatTimer = new Timer(onHeartBeatTimer, this, (int)idleTimeout, (int)idleTimeout);
}
if (this.onOpened != null)
{
this.onOpened(this, open);
}
}
void OnClose(Close close)
{
lock (this.ThisLock)
{
if (this.state == State.Opened)
{
this.SendClose(null);
}
else if (this.state == State.CloseSent)
{
}
else
{
throw new AmqpException(ErrorCode.IllegalState,
Fx.Format(SRAmqp.AmqpIllegalOperationState, "OnClose", this.state));
}
this.state = State.End;
this.OnEnded(close.Error);
}
}
internal virtual void OnBegin(ushort remoteChannel, Begin begin)
{
lock (this.ThisLock)
{
if (remoteChannel > this.channelMax)
{
throw new AmqpException(ErrorCode.NotAllowed,
Fx.Format(SRAmqp.AmqpHandleExceeded, this.channelMax + 1));
}
Session session = this.GetSession(this.localSessions, begin.RemoteChannel);
session.OnBegin(remoteChannel, begin);
int count = this.remoteSessions.Length;
if (count - 1 < remoteChannel)
{
int size = Math.Min(count * 2, this.channelMax + 1);
Session[] expanded = new Session[size];
Array.Copy(this.remoteSessions, expanded, count);
this.remoteSessions = expanded;
}
var remoteSession = this.remoteSessions[remoteChannel];
if (remoteSession != null)
{
throw new AmqpException(ErrorCode.HandleInUse,
Fx.Format(SRAmqp.AmqpHandleInUse, remoteChannel, remoteSession.GetType().Name));
}
this.remoteSessions[remoteChannel] = session;
}
}
void OnEnd(ushort remoteChannel, End end)
{
Session session = this.GetSession(this.remoteSessions, remoteChannel);
if (session.OnEnd(end))
{
lock (this.ThisLock)
{
this.localSessions[session.Channel] = null;
this.remoteSessions[remoteChannel] = null;
}
}
}
void OnSessionCommand(ushort remoteChannel, DescribedList command, ByteBuffer buffer)
{
this.GetSession(this.remoteSessions, remoteChannel).OnCommand(command, buffer);
}
Session GetSession(Session[] sessions, ushort channel)
{
lock (this.ThisLock)
{
Session session = null;
if (channel < sessions.Length)
{
session = sessions[channel];
}
if (session == null)
{
throw new AmqpException(ErrorCode.NotFound,
Fx.Format(SRAmqp.AmqpChannelNotFound, channel));
}
return session;
}
}
internal bool OnHeader(ProtocolHeader header)
{
Trace.WriteLine(TraceLevel.Frame, "RECV AMQP {0}", header);
lock (this.ThisLock)
{
if (this.state == State.OpenPipe)
{
this.state = State.OpenSent;
}
else if (this.state == State.OpenClosePipe)
{
this.state = State.ClosePipe;
}
else
{
throw new AmqpException(ErrorCode.IllegalState,
Fx.Format(SRAmqp.AmqpIllegalOperationState, "OnHeader", this.state));
}
if (header.Major != 1 || header.Minor != 0 || header.Revision != 0)
{
throw new AmqpException(ErrorCode.NotImplemented, header.ToString());
}
}
return true;
}
internal bool OnFrame(ByteBuffer buffer)
{
bool shouldContinue = true;
try
{
ushort channel;
DescribedList command;
Frame.GetFrame(buffer, out channel, out command);
if (buffer.Length > 0)
{
Trace.WriteLine(TraceLevel.Frame, "RECV (ch={0}) {1} payload {2}", channel, command, buffer.Length);
}
else
{
Trace.WriteLine(TraceLevel.Frame, "RECV (ch={0}) {1}", channel, command);
}
if (command != null)
{
if (command.Descriptor.Code == Codec.Open.Code)
{
this.OnOpen((Open)command);
}
else if (command.Descriptor.Code == Codec.Close.Code)
{
this.OnClose((Close)command);
shouldContinue = false;
}
else if (command.Descriptor.Code == Codec.Begin.Code)
{
this.OnBegin(channel, (Begin)command);
}
else if (command.Descriptor.Code == Codec.End.Code)
{
this.OnEnd(channel, (End)command);
}
else
{
this.OnSessionCommand(channel, command, buffer);
}
}
}
catch (Exception exception)
{
this.OnException(exception);
shouldContinue = false;
}
return shouldContinue;
}
void OnException(Exception exception)
{
Trace.WriteLine(TraceLevel.Error, "Exception occurred: {0}", exception.ToString());
AmqpException amqpException = exception as AmqpException;
Error error = amqpException != null ?
amqpException.Error :
new Error() { Condition = ErrorCode.InternalError, Description = exception.Message };
if (this.state < State.ClosePipe)
{
try
{
this.Close(0, error);
}
catch
{
this.state = State.End;
}
}
else
{
this.state = State.End;
}
if (this.state == State.End)
{
this.OnEnded(error);
}
}
internal void OnIoException(Exception exception)
{
Trace.WriteLine(TraceLevel.Error, "I/O: {0}", exception.ToString());
if (this.state != State.End)
{
Error error = new Error() { Condition = ErrorCode.ConnectionForced };
for (int i = 0; i < this.localSessions.Length; i++)
{
if (this.localSessions[i] != null)
{
this.localSessions[i].Abort(error);
}
}
this.state = State.End;
this.OnEnded(error);
}
}
void OnEnded(Error error)
{
if (this.heartBeatTimer != null)
{
this.heartBeatTimer.Dispose();
}
if (this.transport != null)
{
this.transport.Close();
}
this.NotifyClosed(error);
}
sealed class Pump
{
readonly Connection connection;
public Pump(Connection connection)
{
this.connection = connection;
}
public void Start()
{
Fx.StartThread(this.PumpThread);
}
void PumpThread()
{
try
{
ProtocolHeader header = Reader.ReadHeader(this.connection.transport);
this.connection.OnHeader(header);
}
catch (Exception exception)
{
this.connection.OnIoException(exception);
return;
}
byte[] sizeBuffer = new byte[FixedWidth.UInt];
while (sizeBuffer != null && this.connection.state != State.End)
{
try
{
ByteBuffer buffer = Reader.ReadFrameBuffer(this.connection.transport, sizeBuffer, this.connection.maxFrameSize);
if (buffer != null)
{
this.connection.OnFrame(buffer);
}
else
{
sizeBuffer = null;
}
}
catch (Exception exception)
{
this.connection.OnIoException(exception);
}
}
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.VisualStudio.LanguageServices.Implementation.Options;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting
{
/// <summary>
/// Interaction logic for FormattingNewLinesOptionControl.xaml
/// </summary>
internal class NewLinesViewModel : AbstractOptionPreviewViewModel
{
private static string s_previewText = @"//[
class C {
}
//]";
private static string s_methodPreview = @"class c {
//[
void Foo(){
}
//]
}";
private static string s_propertyPreview = @"class c {
//[
public int Property {
get {
return 42;
}
set {
}
}
//]
}";
private static readonly string s_tryCatchFinallyPreview = @"using System;
class C {
void Foo() {
//[
try {
}
catch (Exception e) {
}
finally {
}
//]
}
}";
private static readonly string s_ifElsePreview = @"class C {
void Foo() {
//[
if (false) {
}
else {
}
//]
}
}";
private static readonly string s_forBlockPreview = @"class C {
void Foo() {
//[
for (int i; i < 10; i++){
}
//]
}
}";
private static readonly string s_lambdaPreview = @"using System;
class C {
void Foo() {
//[
Func<int, int> f = (x) => {
return 2 * x;
};
//]
}
}";
private static readonly string s_anonymousMethodPreview = @"using System;
delegate int D(int x);
class C {
void Foo() {
//[
D d = delegate(int x) {
return 2 * x;
};
//]
}
}";
private static readonly string s_anonymousTypePreview = @"using System;
class C {
void Foo() {
//[
var z = new {
A = 3, B = 4
};
//]
}
}";
private static readonly string s_InitializerPreviewTrue = @"using System;
using System.Collections.Generic;
class C {
void Foo() {
//[
var z = new B()
{
A = 3, B = 4
};
// During Brace Completion or Only if Empty Body
var collectionVariable = new List<int>
{
}
// During Brace Completion
var arrayVariable = new int[]
{
}
//]
}
}
class B {
public int A { get; set; }
public int B { get; set; }
}";
private static readonly string s_InitializerPreviewFalse = @"using System;
using System.Collections.Generic;
class C {
void Foo() {
//[
var z = new B() {
A = 3, B = 4
};
// During Brace Completion or Only if Empty Body
var collectionVariable = new List<int> {
}
// During Brace Completion
var arrayVariable = new int[] {
}
//]
}
}
class B {
public int A { get; set; }
public int B { get; set; }
}";
private static readonly string s_objectInitializerPreview = @"using System;
class C {
void Foo() {
//[
var z = new B() {
A = 3, B = 4
};
//]
}
}
class B {
public int A { get; set; }
public int B { get; set; }
}";
private static readonly string s_queryExpressionPreview = @"using System;
using System.Linq;
using System.Collections.Generic;
class C {
void Foo(IEnumerable<int> e) {
//[
var q = from a in e from b in e
select a * b;
//]
}
class B {
public int A { get; set; }
public int B { get; set; }
}";
public NewLinesViewModel(OptionSet options, IServiceProvider serviceProvider) : base(options, serviceProvider, LanguageNames.CSharp)
{
Items.Add(new HeaderItemViewModel() { Header = CSharpVSResources.New_line_options_for_braces });
Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInTypes, CSharpVSResources.Place_open_brace_on_new_line_for_types, s_previewText, this, options));
Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInMethods, CSharpVSResources.Place_open_brace_on_new_line_for_methods, s_methodPreview, this, options));
Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInProperties, CSharpVSResources.Place_open_brace_on_new_line_for_properties_indexers_and_events, s_propertyPreview, this, options));
Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInAccessors, CSharpVSResources.Place_open_brace_on_new_line_for_property_indexer_and_event_accessors, s_propertyPreview, this, options));
Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods, CSharpVSResources.Place_open_brace_on_new_line_for_anonymous_methods, s_anonymousMethodPreview, this, options));
Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInControlBlocks, CSharpVSResources.Place_open_brace_on_new_line_for_control_blocks, s_forBlockPreview, this, options));
Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes, CSharpVSResources.Place_open_brace_on_new_line_for_anonymous_types, s_anonymousTypePreview, this, options));
Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, CSharpVSResources.Place_open_brace_on_new_line_for_object_collection_and_array_initializers, s_InitializerPreviewTrue, s_InitializerPreviewFalse, this, options));
Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody, CSharpVSResources.Place_open_brace_on_new_line_for_lambda_expression, s_lambdaPreview, this, options));
Items.Add(new HeaderItemViewModel() { Header = CSharpVSResources.New_line_options_for_keywords });
Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLineForElse, CSharpVSResources.Place_else_on_new_line, s_ifElsePreview, this, options));
Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLineForCatch, CSharpVSResources.Place_catch_on_new_line, s_tryCatchFinallyPreview, this, options));
Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLineForFinally, CSharpVSResources.Place_finally_on_new_line, s_tryCatchFinallyPreview, this, options));
Items.Add(new HeaderItemViewModel() { Header = CSharpVSResources.New_line_options_for_expressions });
Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLineForMembersInObjectInit, CSharpVSResources.Place_members_in_object_initializers_on_new_line, s_objectInitializerPreview, this, options));
Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLineForMembersInAnonymousTypes, CSharpVSResources.Place_members_in_anonymous_types_on_new_line, s_anonymousTypePreview, this, options));
Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLineForClausesInQuery, CSharpVSResources.Place_query_expression_clauses_on_new_line, s_queryExpressionPreview, this, options));
}
}
}
| |
//*********************************************************
//
// 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 Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using SDKTemplate;
using System;
using Windows.Devices.PointOfService;
using System.Threading.Tasks;
using Windows.UI.Core;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace MagneticStripeReaderSample
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class Scenario2_AamvaCards : Page
{
// A pointer back to the main page. This is needed if you want to call methods in MainPage such
// as NotifyUser()
MainPage rootPage = MainPage.Current;
MagneticStripeReader _reader = null;
ClaimedMagneticStripeReader _claimedReader = null;
public Scenario2_AamvaCards()
{
this.InitializeComponent();
}
/// <summary>
/// Creates the default magnetic stripe reader.
/// </summary>
/// <returns>true if magnetic stripe reader is created. Otherwise returns false</returns>
private async Task<bool> CreateDefaultMagneticStripeReaderObject()
{
if (_reader == null)
{
_reader = await DeviceHelpers.GetFirstMagneticStripeReaderAsync();
if (_reader == null)
{
rootPage.NotifyUser("Magnetic Stripe Reader not found. Please connect a Magnetic Stripe Reader.", NotifyType.ErrorMessage);
return false;
}
}
return true;
}
/// <summary>
/// Claim the magnetic stripe reader
/// </summary>
/// <returns>true if claim is successful. Otherwise returns false</returns>
private async Task<bool> ClaimReader()
{
if (_claimedReader == null)
{
// claim the magnetic stripe reader
_claimedReader = await _reader.ClaimReaderAsync();
if (_claimedReader == null)
{
rootPage.NotifyUser("Claim Magnetic Stripe Reader failed.", NotifyType.ErrorMessage);
return false;
}
}
return true;
}
private async void ScenarioStartReadButton_Click(object sender, RoutedEventArgs e)
{
if (await CreateDefaultMagneticStripeReaderObject())
{
if (_reader != null)
{
// after successful creation, claim the reader for exclusive use and enable it so that data reveived events are received.
if (await ClaimReader())
{
if (_claimedReader != null)
{
// It is always a good idea to have a release device requested event handler. If this event is not handled, there is a chance that another app can
// claim ownsership of the magnetic stripe reader.
_claimedReader.ReleaseDeviceRequested += OnReleaseDeviceRequested;
// after successfully claiming and enabling, attach the AamvaCardDataReceived event handler.
// Note: If the scanner is not enabled (i.e. EnableAsync not called), attaching the event handler will not be of any use because the API will not fire the event
// if the claimedScanner has not beed Enabled
_claimedReader.AamvaCardDataReceived += OnAamvaCardDataReceived;
// Ask the API to decode the data by default. By setting this, API will decode the raw data from the magnetic stripe reader
_claimedReader.IsDecodeDataEnabled = true;
await _claimedReader.EnableAsync();
rootPage.NotifyUser("Ready to swipe. Device ID: " + _claimedReader.DeviceId, NotifyType.StatusMessage);
// reset the button state
ScenarioEndReadButton.IsEnabled = true;
ScenarioStartReadButton.IsEnabled = false;
}
}
}
}
}
/// <summary>
/// Event handler for End button
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void ScenarioEndReadButton_Click(object sender, RoutedEventArgs e)
{
ResetTheScenarioState();
}
/// <summary>
/// Event handler for the Release Device Requested event fired when magnetic stripe reader receives Claim request from another application
/// </summary>
/// <param name="sender"></param>
/// <param name="args"> Contains the ClaimedMagneticStripeReader that is sending this request</param>
void OnReleaseDeviceRequested(object sender, ClaimedMagneticStripeReader args)
{
// let us retain the device always. If it is not retained, this exclusive claim will be lost.
args.RetainDevice();
}
/// <summary>
/// Event handler for the DataReceived event fired when a AAMVA card is read by the magnetic stripe reader
/// </summary>
/// <param name="sender"></param>
/// <param name="args"> Contains the MagneticStripeReaderAamvaCardDataReceivedEventArgs which contains the data obtained in the scan</param>
async void OnAamvaCardDataReceived(object sender, MagneticStripeReaderAamvaCardDataReceivedEventArgs args)
{
// read the data and display
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser("Got data.", NotifyType.StatusMessage);
ScenarioOutputAddress.Text = args.Address;
ScenarioOutputBirthDate.Text = args.BirthDate;
ScenarioOutputCity.Text = args.City;
ScenarioOutputClass.Text = args.Class;
ScenarioOutputEndorsements.Text = args.Endorsements;
ScenarioOutputExpirationDate.Text = args.ExpirationDate;
ScenarioOutputEyeColor.Text = args.EyeColor;
ScenarioOutputFirstName.Text = args.FirstName;
ScenarioOutputGender.Text = args.Gender;
ScenarioOutputHairColor.Text = args.HairColor;
ScenarioOutputHeight.Text = args.Height;
ScenarioOutputLicenseNumber.Text = args.LicenseNumber;
ScenarioOutputPostalCode.Text = args.PostalCode;
ScenarioOutputRestrictions.Text = args.Restrictions;
ScenarioOutputState.Text = args.State;
ScenarioOutputSuffix.Text = args.Suffix;
ScenarioOutputSurname.Text = args.Surname;
ScenarioOutputWeight.Text = args.Weight;
});
}
/// <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();
base.OnNavigatedTo(e);
}
/// <summary>
/// Invoked when this page is no longer displayed.
/// </summary>
/// <param name="e"></param>
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
ResetTheScenarioState();
base.OnNavigatedFrom(e);
}
/// <summary>
/// Reset the Scenario state
/// </summary>
void ResetTheScenarioState()
{
if (_claimedReader != null)
{
// Detach the datareceived event handler and releasedevicerequested event handler
_claimedReader.AamvaCardDataReceived -= OnAamvaCardDataReceived;
_claimedReader.ReleaseDeviceRequested -= OnReleaseDeviceRequested;
// release the Claimed Magnetic Stripe Reader and set to null
_claimedReader.Dispose();
_claimedReader = null;
}
if (_reader != null)
{
// release the Magnetic Stripe Reader and set to null
_reader.Dispose();
_reader = null;
}
// Reset the strings in the UI
rootPage.NotifyUser("Click the Start Receiving Data Button.", NotifyType.StatusMessage);
ScenarioOutputAddress.Text = "No data";
ScenarioOutputBirthDate.Text = "No data";
ScenarioOutputCity.Text = "No data";
ScenarioOutputClass.Text = "No data";
ScenarioOutputEndorsements.Text = "No data";
ScenarioOutputExpirationDate.Text = "No data";
ScenarioOutputEyeColor.Text = "No data";
ScenarioOutputFirstName.Text = "No data";
ScenarioOutputGender.Text = "No data";
ScenarioOutputHairColor.Text = "No data";
ScenarioOutputHeight.Text = "No data";
ScenarioOutputLicenseNumber.Text = "No data";
ScenarioOutputPostalCode.Text = "No data";
ScenarioOutputRestrictions.Text = "No data";
ScenarioOutputState.Text = "No data";
ScenarioOutputSuffix.Text = "No data";
ScenarioOutputSurname.Text = "No data";
ScenarioOutputWeight.Text = "No data";
// reset the button state
ScenarioEndReadButton.IsEnabled = false;
ScenarioStartReadButton.IsEnabled = true;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Collections.Immutable;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a set of projects and their source code documents.
/// </summary>
public partial class Solution
{
// SolutionState that doesn't hold onto Project/Document
private readonly SolutionState _state;
// Values for all these are created on demand.
private ImmutableHashMap<ProjectId, Project> _projectIdToProjectMap;
private Solution(SolutionState state)
{
_projectIdToProjectMap = ImmutableHashMap<ProjectId, Project>.Empty;
_state = state;
}
internal Solution(Workspace workspace, SolutionInfo info)
: this(new SolutionState(workspace, info))
{
}
internal SolutionState State => _state;
internal int WorkspaceVersion => _state.WorkspaceVersion;
internal SolutionServices Services => _state.Services;
internal BranchId BranchId => _state.BranchId;
internal ProjectState GetProjectState(ProjectId projectId) => _state.GetProjectState(projectId);
/// <summary>
/// The Workspace this solution is associated with.
/// </summary>
public Workspace Workspace => _state.Workspace;
/// <summary>
/// The Id of the solution. Multiple solution instances may share the same Id.
/// </summary>
public SolutionId Id => _state.Id;
/// <summary>
/// The path to the solution file or null if there is no solution file.
/// </summary>
public string FilePath => _state.FilePath;
/// <summary>
/// The solution version. This equates to the solution file's version.
/// </summary>
public VersionStamp Version => _state.Version;
/// <summary>
/// A list of all the ids for all the projects contained by the solution.
/// </summary>
public IReadOnlyList<ProjectId> ProjectIds => _state.ProjectIds;
/// <summary>
/// A list of all the projects contained by the solution.
/// </summary>
public IEnumerable<Project> Projects => ProjectIds.Select(id => GetProject(id));
/// <summary>
/// The version of the most recently modified project.
/// </summary>
public VersionStamp GetLatestProjectVersion() => _state.GetLatestProjectVersion();
/// <summary>
/// True if the solution contains a project with the specified project ID.
/// </summary>
public bool ContainsProject(ProjectId projectId) => _state.ContainsProject(projectId);
/// <summary>
/// Gets the project in this solution with the specified project ID.
///
/// If the id is not an id of a project that is part of this solution the method returns null.
/// </summary>
public Project GetProject(ProjectId projectId)
{
if (projectId == null)
{
throw new ArgumentNullException(nameof(projectId));
}
if (this.ContainsProject(projectId))
{
return ImmutableHashMapExtensions.GetOrAdd(ref _projectIdToProjectMap, projectId, s_createProjectFunction, this);
}
return null;
}
private static readonly Func<ProjectId, Solution, Project> s_createProjectFunction = CreateProject;
private static Project CreateProject(ProjectId projectId, Solution solution)
{
return new Project(solution, solution.State.GetProjectState(projectId));
}
/// <summary>
/// Gets the <see cref="Project"/> associated with an assembly symbol.
/// </summary>
public Project GetProject(IAssemblySymbol assemblySymbol, CancellationToken cancellationToken = default(CancellationToken))
{
var projectState = _state.GetProjectState(assemblySymbol, cancellationToken);
return projectState == null ? null : GetProject(projectState.Id);
}
/// <summary>
/// True if the solution contains the document in one of its projects
/// </summary>
public bool ContainsDocument(DocumentId documentId) => _state.ContainsDocument(documentId);
/// <summary>
/// True if the solution contains the additional document in one of its projects
/// </summary>
public bool ContainsAdditionalDocument(DocumentId documentId) => _state.ContainsAdditionalDocument(documentId);
/// <summary>
/// Gets the documentId in this solution with the specified syntax tree.
/// </summary>
public DocumentId GetDocumentId(SyntaxTree syntaxTree) => GetDocumentId(syntaxTree, projectId: null);
/// <summary>
/// Gets the documentId in this solution with the specified syntax tree.
/// </summary>
public DocumentId GetDocumentId(SyntaxTree syntaxTree, ProjectId projectId)
{
if (syntaxTree != null)
{
// is this tree known to be associated with a document?
var documentId = DocumentState.GetDocumentIdForTree(syntaxTree);
if (documentId != null && (projectId == null || documentId.ProjectId == projectId))
{
// does this solution even have the document?
if (this.ContainsDocument(documentId))
{
return documentId;
}
}
}
return null;
}
/// <summary>
/// Gets the document in this solution with the specified document ID.
/// </summary>
public Document GetDocument(DocumentId documentId)
{
if (documentId != null && this.ContainsDocument(documentId))
{
return this.GetProject(documentId.ProjectId).GetDocument(documentId);
}
return null;
}
/// <summary>
/// Gets the additional document in this solution with the specified document ID.
/// </summary>
public TextDocument GetAdditionalDocument(DocumentId documentId)
{
if (documentId != null && this.ContainsAdditionalDocument(documentId))
{
return this.GetProject(documentId.ProjectId).GetAdditionalDocument(documentId);
}
return null;
}
/// <summary>
/// Gets the document in this solution with the specified syntax tree.
/// </summary>
public Document GetDocument(SyntaxTree syntaxTree)
{
return this.GetDocument(syntaxTree, projectId: null);
}
internal Document GetDocument(SyntaxTree syntaxTree, ProjectId projectId)
{
if (syntaxTree != null)
{
// is this tree known to be associated with a document?
var docId = DocumentState.GetDocumentIdForTree(syntaxTree);
if (docId != null && (projectId == null || docId.ProjectId == projectId))
{
// does this solution even have the document?
var document = this.GetDocument(docId);
if (document != null)
{
// does this document really have the syntax tree?
SyntaxTree documentTree;
if (document.TryGetSyntaxTree(out documentTree) && documentTree == syntaxTree)
{
return document;
}
}
}
}
return null;
}
/// <summary>
/// Creates a new solution instance that includes a project with the specified language and names.
/// Returns the new project.
/// </summary>
public Project AddProject(string name, string assemblyName, string language)
{
var id = ProjectId.CreateNewId(debugName: name);
return this.AddProject(id, name, assemblyName, language).GetProject(id);
}
/// <summary>
/// Creates a new solution instance that includes a project with the specified language and names.
/// </summary>
public Solution AddProject(ProjectId projectId, string name, string assemblyName, string language)
{
return this.AddProject(ProjectInfo.Create(projectId, VersionStamp.Create(), name, assemblyName, language));
}
/// <summary>
/// Create a new solution instance that includes a project with the specified project information.
/// </summary>
public Solution AddProject(ProjectInfo projectInfo)
{
var newState = _state.AddProject(projectInfo);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance without the project specified.
/// </summary>
public Solution RemoveProject(ProjectId projectId)
{
var newState = _state.RemoveProject(projectId);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the project specified updated to have the new
/// assembly name.
/// </summary>
public Solution WithProjectAssemblyName(ProjectId projectId, string assemblyName)
{
var newState = _state.WithProjectAssemblyName(projectId, assemblyName);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the project specified updated to have the output file path.
/// </summary>
public Solution WithProjectOutputFilePath(ProjectId projectId, string outputFilePath)
{
var newState = _state.WithProjectOutputFilePath(projectId, outputFilePath);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the project specified updated to have the name.
/// </summary>
public Solution WithProjectName(ProjectId projectId, string name)
{
var newState = _state.WithProjectName(projectId, name);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the project specified updated to have the project file path.
/// </summary>
public Solution WithProjectFilePath(ProjectId projectId, string filePath)
{
var newState = _state.WithProjectFilePath(projectId, filePath);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to have
/// the specified compilation options.
/// </summary>
public Solution WithProjectCompilationOptions(ProjectId projectId, CompilationOptions options)
{
var newState = _state.WithProjectCompilationOptions(projectId, options);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to have
/// the specified parse options.
/// </summary>
public Solution WithProjectParseOptions(ProjectId projectId, ParseOptions options)
{
var newState = _state.WithProjectParseOptions(projectId, options);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to have
/// the specified hasAllInformation.
/// </summary>
// TODO: make it public
internal Solution WithHasAllInformation(ProjectId projectId, bool hasAllInformation)
{
var newState = _state.WithHasAllInformation(projectId, hasAllInformation);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to include
/// the specified project reference.
/// </summary>
public Solution AddProjectReference(ProjectId projectId, ProjectReference projectReference)
{
var newState = _state.AddProjectReference(projectId, projectReference);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to include
/// the specified project references.
/// </summary>
public Solution AddProjectReferences(ProjectId projectId, IEnumerable<ProjectReference> projectReferences)
{
var newState = _state.AddProjectReferences(projectId, projectReferences);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to no longer
/// include the specified project reference.
/// </summary>
public Solution RemoveProjectReference(ProjectId projectId, ProjectReference projectReference)
{
var newState = _state.RemoveProjectReference(projectId, projectReference);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to contain
/// the specified list of project references.
/// </summary>
public Solution WithProjectReferences(ProjectId projectId, IEnumerable<ProjectReference> projectReferences)
{
var newState = _state.WithProjectReferences(projectId, projectReferences);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to include the
/// specified metadata reference.
/// </summary>
public Solution AddMetadataReference(ProjectId projectId, MetadataReference metadataReference)
{
var newState = _state.AddMetadataReference(projectId, metadataReference);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to include the
/// specified metadata references.
/// </summary>
public Solution AddMetadataReferences(ProjectId projectId, IEnumerable<MetadataReference> metadataReferences)
{
var newState = _state.AddMetadataReferences(projectId, metadataReferences);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to no longer include
/// the specified metadata reference.
/// </summary>
public Solution RemoveMetadataReference(ProjectId projectId, MetadataReference metadataReference)
{
var newState = _state.RemoveMetadataReference(projectId, metadataReference);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to include only the
/// specified metadata references.
/// </summary>
public Solution WithProjectMetadataReferences(ProjectId projectId, IEnumerable<MetadataReference> metadataReferences)
{
var newState = _state.WithProjectMetadataReferences(projectId, metadataReferences);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to include the
/// specified analyzer reference.
/// </summary>
public Solution AddAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference)
{
var newState = _state.AddAnalyzerReference(projectId, analyzerReference);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to include the
/// specified analyzer references.
/// </summary>
public Solution AddAnalyzerReferences(ProjectId projectId, IEnumerable<AnalyzerReference> analyzerReferences)
{
var newState = _state.AddAnalyzerReferences(projectId, analyzerReferences);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to no longer include
/// the specified analyzer reference.
/// </summary>
public Solution RemoveAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference)
{
var newState = _state.RemoveAnalyzerReference(projectId, analyzerReference);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to include only the
/// specified analyzer references.
/// </summary>
public Solution WithProjectAnalyzerReferences(ProjectId projectId, IEnumerable<AnalyzerReference> analyzerReferences)
{
var newState = _state.WithProjectAnalyzerReferences(projectId, analyzerReferences);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
private static SourceCodeKind GetSourceCodeKind(ProjectState project)
{
return project.ParseOptions != null ? project.ParseOptions.Kind : SourceCodeKind.Regular;
}
/// <summary>
/// Creates a new solution instance with the corresponding project updated to include a new
/// document instance defined by its name and text.
/// </summary>
public Solution AddDocument(DocumentId documentId, string name, string text, IEnumerable<string> folders = null, string filePath = null)
{
return this.AddDocument(documentId, name, SourceText.From(text), folders, filePath);
}
/// <summary>
/// Creates a new solution instance with the corresponding project updated to include a new
/// document instance defined by its name and text.
/// </summary>
public Solution AddDocument(DocumentId documentId, string name, SourceText text, IEnumerable<string> folders = null, string filePath = null, bool isGenerated = false)
{
if (documentId == null)
{
throw new ArgumentNullException(nameof(documentId));
}
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
var project = _state.GetProjectState(documentId.ProjectId);
var version = VersionStamp.Create();
var loader = TextLoader.From(TextAndVersion.Create(text, version, name));
var info = DocumentInfo.Create(
documentId,
name: name,
folders: folders,
sourceCodeKind: GetSourceCodeKind(project),
loader: loader,
filePath: filePath,
isGenerated: isGenerated);
return this.AddDocument(info);
}
/// <summary>
/// Creates a new solution instance with the corresponding project updated to include a new
/// document instance defined by its name and root <see cref="SyntaxNode"/>.
/// </summary>
public Solution AddDocument(DocumentId documentId, string name, SyntaxNode syntaxRoot, IEnumerable<string> folders = null, string filePath = null, bool isGenerated = false, PreservationMode preservationMode = PreservationMode.PreserveValue)
{
return this.AddDocument(documentId, name, SourceText.From(string.Empty), folders, filePath, isGenerated).WithDocumentSyntaxRoot(documentId, syntaxRoot, preservationMode);
}
/// <summary>
/// Creates a new solution instance with the project updated to include a new document with
/// the arguments specified.
/// </summary>
public Solution AddDocument(DocumentId documentId, string name, TextLoader loader, IEnumerable<string> folders = null)
{
if (documentId == null)
{
throw new ArgumentNullException(nameof(documentId));
}
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (loader == null)
{
throw new ArgumentNullException(nameof(loader));
}
var project = _state.GetProjectState(documentId.ProjectId);
var info = DocumentInfo.Create(
documentId,
name: name,
folders: folders,
sourceCodeKind: GetSourceCodeKind(project),
loader: loader);
return this.AddDocument(info);
}
/// <summary>
/// Create a new solution instance with the corresponding project updated to include a new
/// document instanced defined by the document info.
/// </summary>
public Solution AddDocument(DocumentInfo documentInfo)
{
var newState = _state.AddDocument(documentInfo);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the corresponding project updated to include a new
/// additional document instance defined by its name and text.
/// </summary>
public Solution AddAdditionalDocument(DocumentId documentId, string name, string text, IEnumerable<string> folders = null, string filePath = null)
{
return this.AddAdditionalDocument(documentId, name, SourceText.From(text), folders, filePath);
}
/// <summary>
/// Creates a new solution instance with the corresponding project updated to include a new
/// additional document instance defined by its name and text.
/// </summary>
public Solution AddAdditionalDocument(DocumentId documentId, string name, SourceText text, IEnumerable<string> folders = null, string filePath = null)
{
if (documentId == null)
{
throw new ArgumentNullException(nameof(documentId));
}
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
var project = _state.GetProjectState(documentId.ProjectId);
var version = VersionStamp.Create();
var loader = TextLoader.From(TextAndVersion.Create(text, version, name));
var info = DocumentInfo.Create(
documentId,
name: name,
folders: folders,
sourceCodeKind: GetSourceCodeKind(project),
loader: loader,
filePath: filePath);
return this.AddAdditionalDocument(info);
}
public Solution AddAdditionalDocument(DocumentInfo documentInfo)
{
var newState = _state.AddAdditionalDocument(documentInfo);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance that no longer includes the specified document.
/// </summary>
public Solution RemoveDocument(DocumentId documentId)
{
var newState = _state.RemoveDocument(documentId);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance that no longer includes the specified additional document.
/// </summary>
public Solution RemoveAdditionalDocument(DocumentId documentId)
{
var newState = _state.RemoveAdditionalDocument(documentId);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the document specified updated to be contained in
/// the sequence of logical folders.
/// </summary>
public Solution WithDocumentFolders(DocumentId documentId, IEnumerable<string> folders)
{
var newState = _state.WithDocumentFolders(documentId, folders);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have the text
/// specified.
/// </summary>
public Solution WithDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue)
{
var newState = _state.WithDocumentText(documentId, text, mode);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the additional document specified updated to have the text
/// specified.
/// </summary>
public Solution WithAdditionalDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue)
{
var newState = _state.WithAdditionalDocumentText(documentId, text, mode);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have the text
/// and version specified.
/// </summary>
public Solution WithDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue)
{
var newState = _state.WithDocumentText(documentId, textAndVersion, mode);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the additional document specified updated to have the text
/// and version specified.
/// </summary>
public Solution WithAdditionalDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue)
{
var newState = _state.WithAdditionalDocumentText(documentId, textAndVersion, mode);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have a syntax tree
/// rooted by the specified syntax node.
/// </summary>
public Solution WithDocumentSyntaxRoot(DocumentId documentId, SyntaxNode root, PreservationMode mode = PreservationMode.PreserveValue)
{
var newState = _state.WithDocumentSyntaxRoot(documentId, root, mode);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have the source
/// code kind specified.
/// </summary>
public Solution WithDocumentSourceCodeKind(DocumentId documentId, SourceCodeKind sourceCodeKind)
{
var newState = _state.WithDocumentSourceCodeKind(documentId, sourceCodeKind);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have the text
/// supplied by the text loader.
/// </summary>
public Solution WithDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode)
{
return WithDocumentTextLoader(documentId, loader, textOpt: null, mode: mode);
}
internal Solution WithDocumentTextLoader(DocumentId documentId, TextLoader loader, SourceText textOpt, PreservationMode mode)
{
var newState = _state.WithDocumentTextLoader(documentId, loader, textOpt, mode);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the additional document specified updated to have the text
/// supplied by the text loader.
/// </summary>
public Solution WithAdditionalDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode)
{
var newState = _state.WithAdditionalDocumentTextLoader(documentId, loader, mode);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a branch of the solution that has its compilations frozen in whatever state they are in at the time, assuming a background compiler is
/// busy building this compilations.
///
/// A compilation for the project containing the specified document id will be guaranteed to exist with at least the syntax tree for the document.
///
/// This not intended to be the public API, use Document.WithFrozenPartialSemantics() instead.
/// </summary>
internal async Task<Solution> WithFrozenPartialCompilationIncludingSpecificDocumentAsync(DocumentId documentId, CancellationToken cancellationToken)
{
var newState = await _state.WithFrozenPartialCompilationIncludingSpecificDocumentAsync(documentId, cancellationToken).ConfigureAwait(false);
return new Solution(newState);
}
internal async Task<Solution> WithMergedLinkedFileChangesAsync(
Solution oldSolution,
SolutionChanges? solutionChanges = null,
IMergeConflictHandler mergeConflictHandler = null,
CancellationToken cancellationToken = default(CancellationToken))
{
// we only log sessioninfo for actual changes committed to workspace which should exclude ones from preview
var session = new LinkedFileDiffMergingSession(oldSolution, this, solutionChanges ?? this.GetChanges(oldSolution), logSessionInfo: solutionChanges != null);
return (await session.MergeDiffsAsync(mergeConflictHandler, cancellationToken).ConfigureAwait(false)).MergedSolution;
}
internal ImmutableArray<DocumentId> GetRelatedDocumentIds(DocumentId documentId)
{
var projectState = _state.GetProjectState(documentId.ProjectId);
if (projectState == null)
{
// this document no longer exist
return ImmutableArray<DocumentId>.Empty;
}
var documentState = projectState.GetDocumentState(documentId);
if (documentState == null)
{
// this document no longer exist
return ImmutableArray<DocumentId>.Empty;
}
var filePath = documentState.FilePath;
if (string.IsNullOrEmpty(filePath))
{
// this document can't have any related document. only related document is itself.
return ImmutableArray.Create<DocumentId>(documentId);
}
var documentIds = this.GetDocumentIdsWithFilePath(filePath);
return this.FilterDocumentIdsByLanguage(documentIds, projectState.ProjectInfo.Language).ToImmutableArray();
}
internal Solution WithNewWorkspace(Workspace workspace, int workspaceVersion)
{
var newState = _state.WithNewWorkspace(workspace, workspaceVersion);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Gets a copy of the solution isolated from the original so that they do not share computed state.
///
/// Use isolated solutions when doing operations that are likely to access a lot of text,
/// syntax trees or compilations that are unlikely to be needed again after the operation is done.
/// When the isolated solution is reclaimed so will the computed state.
/// </summary>
public Solution GetIsolatedSolution()
{
var newState = _state.GetIsolatedSolution();
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with all the documents specified updated to have the same specified text.
/// </summary>
public Solution WithDocumentText(IEnumerable<DocumentId> documentIds, SourceText text, PreservationMode mode = PreservationMode.PreserveValue)
{
var newState = _state.WithDocumentText(documentIds, text, mode);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Gets an objects that lists the added, changed and removed projects between
/// this solution and the specified solution.
/// </summary>
public SolutionChanges GetChanges(Solution oldSolution)
{
if (oldSolution == null)
{
throw new ArgumentNullException(nameof(oldSolution));
}
return new SolutionChanges(this, oldSolution);
}
/// <summary>
/// Gets the set of <see cref="DocumentId"/>s in this <see cref="Solution"/> with a
/// <see cref="TextDocument.FilePath"/> that matches the given file path.
/// </summary>
public ImmutableArray<DocumentId> GetDocumentIdsWithFilePath(string filePath) => _state.GetDocumentIdsWithFilePath(filePath);
/// <summary>
/// Gets a <see cref="ProjectDependencyGraph"/> that details the dependencies between projects for this solution.
/// </summary>
public ProjectDependencyGraph GetProjectDependencyGraph() => _state.GetProjectDependencyGraph();
/// <summary>
/// Returns the options that should be applied to this solution. This consists of global options from <see cref="Workspace.Options"/>,
/// merged with any settings the user has specified at the solution level.
/// </summary>
public OptionSet Options
{
get
{
// TODO: merge with solution-specific options
return this.Workspace.Options;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.