context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
using System.Linq;
using GodLesZ.Library.Json.Utilities;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
#endif
namespace GodLesZ.Library.Json
{
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only access to serialized Json data.
/// </summary>
public abstract class JsonReader : IDisposable
{
/// <summary>
/// Specifies the state of the reader.
/// </summary>
protected internal enum State
{
/// <summary>
/// The Read method has not been called.
/// </summary>
Start,
/// <summary>
/// The end of the file has been reached successfully.
/// </summary>
Complete,
/// <summary>
/// Reader is at a property.
/// </summary>
Property,
/// <summary>
/// Reader is at the start of an object.
/// </summary>
ObjectStart,
/// <summary>
/// Reader is in an object.
/// </summary>
Object,
/// <summary>
/// Reader is at the start of an array.
/// </summary>
ArrayStart,
/// <summary>
/// Reader is in an array.
/// </summary>
Array,
/// <summary>
/// The Close method has been called.
/// </summary>
Closed,
/// <summary>
/// Reader has just read a value.
/// </summary>
PostValue,
/// <summary>
/// Reader is at the start of a constructor.
/// </summary>
ConstructorStart,
/// <summary>
/// Reader in a constructor.
/// </summary>
Constructor,
/// <summary>
/// An error occurred that prevents the read operation from continuing.
/// </summary>
Error,
/// <summary>
/// The end of the file has been reached successfully.
/// </summary>
Finished
}
// current Token data
private JsonToken _tokenType;
private object _value;
internal char _quoteChar;
internal State _currentState;
internal ReadType _readType;
private JsonPosition _currentPosition;
private CultureInfo _culture;
private DateTimeZoneHandling _dateTimeZoneHandling;
private int? _maxDepth;
private bool _hasExceededMaxDepth;
internal DateParseHandling _dateParseHandling;
internal FloatParseHandling _floatParseHandling;
private readonly List<JsonPosition> _stack;
/// <summary>
/// Gets the current reader state.
/// </summary>
/// <value>The current reader state.</value>
protected State CurrentState
{
get { return _currentState; }
}
/// <summary>
/// Gets or sets a value indicating whether the underlying stream or
/// <see cref="TextReader"/> should be closed when the reader is closed.
/// </summary>
/// <value>
/// true to close the underlying stream or <see cref="TextReader"/> when
/// the reader is closed; otherwise false. The default is true.
/// </value>
public bool CloseInput { get; set; }
/// <summary>
/// Gets the quotation mark character used to enclose the value of a string.
/// </summary>
public virtual char QuoteChar
{
get { return _quoteChar; }
protected internal set { _quoteChar = value; }
}
/// <summary>
/// Get or set how <see cref="DateTime"/> time zones are handling when reading JSON.
/// </summary>
public DateTimeZoneHandling DateTimeZoneHandling
{
get { return _dateTimeZoneHandling; }
set { _dateTimeZoneHandling = value; }
}
/// <summary>
/// Get or set how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON.
/// </summary>
public DateParseHandling DateParseHandling
{
get { return _dateParseHandling; }
set { _dateParseHandling = value; }
}
/// <summary>
/// Get or set how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text.
/// </summary>
public FloatParseHandling FloatParseHandling
{
get { return _floatParseHandling; }
set { _floatParseHandling = value; }
}
/// <summary>
/// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>.
/// </summary>
public int? MaxDepth
{
get { return _maxDepth; }
set
{
if (value <= 0)
throw new ArgumentException("Value must be positive.", "value");
_maxDepth = value;
}
}
/// <summary>
/// Gets the type of the current JSON token.
/// </summary>
public virtual JsonToken TokenType
{
get { return _tokenType; }
}
/// <summary>
/// Gets the text value of the current JSON token.
/// </summary>
public virtual object Value
{
get { return _value; }
}
/// <summary>
/// Gets The Common Language Runtime (CLR) type for the current JSON token.
/// </summary>
public virtual Type ValueType
{
get { return (_value != null) ? _value.GetType() : null; }
}
/// <summary>
/// Gets the depth of the current token in the JSON document.
/// </summary>
/// <value>The depth of the current token in the JSON document.</value>
public virtual int Depth
{
get
{
int depth = _stack.Count;
if (IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None)
return depth;
else
return depth + 1;
}
}
/// <summary>
/// Gets the path of the current JSON token.
/// </summary>
public virtual string Path
{
get
{
if (_currentPosition.Type == JsonContainerType.None)
return string.Empty;
bool insideContainer = (_currentState != State.ArrayStart
&& _currentState != State.ConstructorStart
&& _currentState != State.ObjectStart);
IEnumerable<JsonPosition> positions = (!insideContainer)
? _stack
: _stack.Concat(new[] {_currentPosition});
return JsonPosition.BuildPath(positions);
}
}
/// <summary>
/// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
public CultureInfo Culture
{
get { return _culture ?? CultureInfo.InvariantCulture; }
set { _culture = value; }
}
internal JsonPosition GetPosition(int depth)
{
if (depth < _stack.Count)
return _stack[depth];
return _currentPosition;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>.
/// </summary>
protected JsonReader()
{
_currentState = State.Start;
_stack = new List<JsonPosition>(4);
_dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
_dateParseHandling = DateParseHandling.DateTime;
_floatParseHandling = FloatParseHandling.Double;
CloseInput = true;
}
private void Push(JsonContainerType value)
{
UpdateScopeWithFinishedValue();
if (_currentPosition.Type == JsonContainerType.None)
{
_currentPosition = new JsonPosition(value);
}
else
{
_stack.Add(_currentPosition);
_currentPosition = new JsonPosition(value);
// this is a little hacky because Depth increases when first property/value is written but only testing here is faster/simpler
if (_maxDepth != null && Depth + 1 > _maxDepth && !_hasExceededMaxDepth)
{
_hasExceededMaxDepth = true;
throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth));
}
}
}
private JsonContainerType Pop()
{
JsonPosition oldPosition;
if (_stack.Count > 0)
{
oldPosition = _currentPosition;
_currentPosition = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
}
else
{
oldPosition = _currentPosition;
_currentPosition = new JsonPosition();
}
if (_maxDepth != null && Depth <= _maxDepth)
_hasExceededMaxDepth = false;
return oldPosition.Type;
}
private JsonContainerType Peek()
{
return _currentPosition.Type;
}
/// <summary>
/// Reads the next JSON token from the stream.
/// </summary>
/// <returns>true if the next token was read successfully; false if there are no more tokens to read.</returns>
public abstract bool Read();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Int32}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Int32}"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract int? ReadAsInt32();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="String"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract string ReadAsString();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="T:Byte[]"/>.
/// </summary>
/// <returns>A <see cref="T:Byte[]"/> or a null reference if the next JSON token is null. This method will return <c>null</c> at the end of an array.</returns>
public abstract byte[] ReadAsBytes();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract decimal? ReadAsDecimal();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTime}"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract DateTime? ReadAsDateTime();
#if !NET20
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{DateTimeOffset}"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract DateTimeOffset? ReadAsDateTimeOffset();
#endif
internal virtual bool ReadInternal()
{
throw new NotImplementedException();
}
#if !NET20
internal DateTimeOffset? ReadAsDateTimeOffsetInternal()
{
_readType = ReadType.ReadAsDateTimeOffset;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (t == JsonToken.Date)
{
if (Value is DateTime)
SetToken(JsonToken.Date, new DateTimeOffset((DateTime)Value));
return (DateTimeOffset)Value;
}
if (t == JsonToken.Null)
return null;
DateTimeOffset dt;
if (t == JsonToken.String)
{
string s = (string)Value;
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null);
return null;
}
if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
{
SetToken(JsonToken.Date, dt);
return dt;
}
else
{
throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
#endif
internal byte[] ReadAsBytesInternal()
{
_readType = ReadType.ReadAsBytes;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (IsWrappedInTypeObject())
{
byte[] data = ReadAsBytes();
ReadInternal();
SetToken(JsonToken.Bytes, data);
return data;
}
// attempt to convert possible base 64 string to bytes
if (t == JsonToken.String)
{
string s = (string)Value;
byte[] data = (s.Length == 0) ? new byte[0] : Convert.FromBase64String(s);
SetToken(JsonToken.Bytes, data);
return data;
}
if (t == JsonToken.Null)
return null;
if (t == JsonToken.Bytes)
return (byte[])Value;
if (t == JsonToken.StartArray)
{
List<byte> data = new List<byte>();
while (ReadInternal())
{
t = TokenType;
switch (t)
{
case JsonToken.Integer:
data.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture));
break;
case JsonToken.EndArray:
byte[] d = data.ToArray();
SetToken(JsonToken.Bytes, d);
return d;
case JsonToken.Comment:
// skip
break;
default:
throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
}
throw JsonReaderException.Create(this, "Unexpected end when reading bytes.");
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal decimal? ReadAsDecimalInternal()
{
_readType = ReadType.ReadAsDecimal;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (t == JsonToken.Integer || t == JsonToken.Float)
{
if (!(Value is decimal))
SetToken(JsonToken.Float, Convert.ToDecimal(Value, CultureInfo.InvariantCulture));
return (decimal)Value;
}
if (t == JsonToken.Null)
return null;
decimal d;
if (t == JsonToken.String)
{
string s = (string)Value;
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null);
return null;
}
if (decimal.TryParse(s, NumberStyles.Number, Culture, out d))
{
SetToken(JsonToken.Float, d);
return d;
}
else
{
throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal int? ReadAsInt32Internal()
{
_readType = ReadType.ReadAsInt32;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (t == JsonToken.Integer || t == JsonToken.Float)
{
if (!(Value is int))
SetToken(JsonToken.Integer, Convert.ToInt32(Value, CultureInfo.InvariantCulture));
return (int)Value;
}
if (t == JsonToken.Null)
return null;
int i;
if (t == JsonToken.String)
{
string s = (string)Value;
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null);
return null;
}
if (int.TryParse(s, NumberStyles.Integer, Culture, out i))
{
SetToken(JsonToken.Integer, i);
return i;
}
else
{
throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
internal string ReadAsStringInternal()
{
_readType = ReadType.ReadAsString;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (t == JsonToken.String)
return (string)Value;
if (t == JsonToken.Null)
return null;
if (IsPrimitiveToken(t))
{
if (Value != null)
{
string s;
if (Value is IFormattable)
s = ((IFormattable)Value).ToString(null, Culture);
else
s = Value.ToString();
SetToken(JsonToken.String, s);
return s;
}
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal DateTime? ReadAsDateTimeInternal()
{
_readType = ReadType.ReadAsDateTime;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
} while (TokenType == JsonToken.Comment);
if (TokenType == JsonToken.Date)
return (DateTime)Value;
if (TokenType == JsonToken.Null)
return null;
DateTime dt;
if (TokenType == JsonToken.String)
{
string s = (string)Value;
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null);
return null;
}
if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
{
dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
SetToken(JsonToken.Date, dt);
return dt;
}
else
{
throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
}
if (TokenType == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
private bool IsWrappedInTypeObject()
{
_readType = ReadType.Read;
if (TokenType == JsonToken.StartObject)
{
if (!ReadInternal())
throw JsonReaderException.Create(this, "Unexpected end when reading bytes.");
if (Value.ToString() == "$type")
{
ReadInternal();
if (Value != null && Value.ToString().StartsWith("System.Byte[]"))
{
ReadInternal();
if (Value.ToString() == "$value")
{
return true;
}
}
}
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject));
}
return false;
}
/// <summary>
/// Skips the children of the current token.
/// </summary>
public void Skip()
{
if (TokenType == JsonToken.PropertyName)
Read();
if (IsStartToken(TokenType))
{
int depth = Depth;
while (Read() && (depth < Depth))
{
}
}
}
/// <summary>
/// Sets the current token.
/// </summary>
/// <param name="newToken">The new token.</param>
protected void SetToken(JsonToken newToken)
{
SetToken(newToken, null);
}
/// <summary>
/// Sets the current token and value.
/// </summary>
/// <param name="newToken">The new token.</param>
/// <param name="value">The value.</param>
protected void SetToken(JsonToken newToken, object value)
{
_tokenType = newToken;
_value = value;
switch (newToken)
{
case JsonToken.StartObject:
_currentState = State.ObjectStart;
Push(JsonContainerType.Object);
break;
case JsonToken.StartArray:
_currentState = State.ArrayStart;
Push(JsonContainerType.Array);
break;
case JsonToken.StartConstructor:
_currentState = State.ConstructorStart;
Push(JsonContainerType.Constructor);
break;
case JsonToken.EndObject:
ValidateEnd(JsonToken.EndObject);
break;
case JsonToken.EndArray:
ValidateEnd(JsonToken.EndArray);
break;
case JsonToken.EndConstructor:
ValidateEnd(JsonToken.EndConstructor);
break;
case JsonToken.PropertyName:
_currentState = State.Property;
_currentPosition.PropertyName = (string) value;
break;
case JsonToken.Undefined:
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Date:
case JsonToken.String:
case JsonToken.Raw:
case JsonToken.Bytes:
_currentState = (Peek() != JsonContainerType.None) ? State.PostValue : State.Finished;
UpdateScopeWithFinishedValue();
break;
}
}
private void UpdateScopeWithFinishedValue()
{
if (_currentPosition.HasIndex)
_currentPosition.Position++;
}
private void ValidateEnd(JsonToken endToken)
{
JsonContainerType currentObject = Pop();
if (GetTypeForCloseToken(endToken) != currentObject)
throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, currentObject));
_currentState = (Peek() != JsonContainerType.None) ? State.PostValue : State.Finished;
}
/// <summary>
/// Sets the state based on current token type.
/// </summary>
protected void SetStateBasedOnCurrent()
{
JsonContainerType currentObject = Peek();
switch (currentObject)
{
case JsonContainerType.Object:
_currentState = State.Object;
break;
case JsonContainerType.Array:
_currentState = State.Array;
break;
case JsonContainerType.Constructor:
_currentState = State.Constructor;
break;
case JsonContainerType.None:
_currentState = State.Finished;
break;
default:
throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, currentObject));
}
}
internal static bool IsPrimitiveToken(JsonToken token)
{
switch (token)
{
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Undefined:
case JsonToken.Null:
case JsonToken.Date:
case JsonToken.Bytes:
return true;
default:
return false;
}
}
internal static bool IsStartToken(JsonToken token)
{
switch (token)
{
case JsonToken.StartObject:
case JsonToken.StartArray:
case JsonToken.StartConstructor:
return true;
default:
return false;
}
}
private JsonContainerType GetTypeForCloseToken(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
return JsonContainerType.Object;
case JsonToken.EndArray:
return JsonContainerType.Array;
case JsonToken.EndConstructor:
return JsonContainerType.Constructor;
default:
throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token));
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
void IDisposable.Dispose()
{
Dispose(true);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (_currentState != State.Closed && disposing)
Close();
}
/// <summary>
/// Changes the <see cref="State"/> to Closed.
/// </summary>
public virtual void Close()
{
_currentState = State.Closed;
_tokenType = JsonToken.None;
_value = null;
}
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using ParentLoadSoftDelete.DataAccess;
using ParentLoadSoftDelete.DataAccess.ERLevel;
namespace ParentLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// E07_Country_ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="E07_Country_ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="E06_Country"/> collection.
/// </remarks>
[Serializable]
public partial class E07_Country_ReChild : BusinessBase<E07_Country_ReChild>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int country_ID2 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Country_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Country_Child_NameProperty = RegisterProperty<string>(p => p.Country_Child_Name, "Regions Child Name");
/// <summary>
/// Gets or sets the Regions Child Name.
/// </summary>
/// <value>The Regions Child Name.</value>
public string Country_Child_Name
{
get { return GetProperty(Country_Child_NameProperty); }
set { SetProperty(Country_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="E07_Country_ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="E07_Country_ReChild"/> object.</returns>
internal static E07_Country_ReChild NewE07_Country_ReChild()
{
return DataPortal.CreateChild<E07_Country_ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="E07_Country_ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="E07_Country_ReChild"/> object.</returns>
internal static E07_Country_ReChild GetE07_Country_ReChild(SafeDataReader dr)
{
E07_Country_ReChild obj = new E07_Country_ReChild();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
// check all object rules and property rules
obj.BusinessRules.CheckRules();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="E07_Country_ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public E07_Country_ReChild()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="E07_Country_ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="E07_Country_ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Country_Child_NameProperty, dr.GetString("Country_Child_Name"));
// parent properties
country_ID2 = dr.GetInt32("Country_ID2");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="E07_Country_ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(E06_Country parent)
{
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnInsertPre(args);
var dal = dalManager.GetProvider<IE07_Country_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Insert(
parent.Country_ID,
Country_Child_Name
);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="E07_Country_ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(E06_Country parent)
{
if (!IsDirty)
return;
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnUpdatePre(args);
var dal = dalManager.GetProvider<IE07_Country_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Update(
parent.Country_ID,
Country_Child_Name
);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="E07_Country_ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(E06_Country parent)
{
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IE07_Country_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.Country_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
/***************************************************************
//This code just called you a tool
//What I meant to say is that this code was generated by a tool
//so don't mess with it unless you're debugging
//subject to change without notice, might regenerate while you're reading, etc
***************************************************************/
using Web;
using Voodoo.Messages;
using Web.Infrastructure.ExecutionPipeline;
using Web.Infrastructure.ExecutionPipeline.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Voodoo;
using Core.Operations.Users;
using Core.Operations.Users.Extras;
using Core.Operations.Members;
using Core.Operations.Members.Extras;
using Core.Operations.Lists;
using Core.Operations.Errors;
using Core.Operations.Errors.Extras;
using Core.Operations.CurrentUsers;
using Core.Identity;
using Core.Operations.ApplicationSettings;
using Core.Operations.ApplicationSettings.Extras;
namespace Web.Controllers.Api
{
[Route("api/[controller]")]
public class UserDetailController : ApiControllerBase
{
[HttpDelete]
public async Task<Response> Delete
( IdRequest request)
{
var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState
<IdRequest, Response>
{
Command = new UserDeleteCommand(request),
Context = HttpContext,
ModelState = ModelState,
Request = request,
SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { "Administrator" } }
};
var pipeline = new ExcecutionPipeline<IdRequest, Response>
(state);
await pipeline.ExecuteAsync();
return state.Response;
}
[HttpGet]
public async Task<Response<UserDetail>> Get
( IdRequest request)
{
var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState
<IdRequest, Response<UserDetail>>
{
Command = new UserDetailQuery(request),
Context = HttpContext,
ModelState = ModelState,
Request = request,
SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { "Administrator" } }
};
var pipeline = new ExcecutionPipeline<IdRequest, Response<UserDetail>>
(state);
await pipeline.ExecuteAsync();
return state.Response;
}
[HttpPut]
public async Task<NewItemResponse> Put
([FromBody] UserDetail request)
{
var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState
<UserDetail, NewItemResponse>
{
Command = new UserSaveCommand(request),
Context = HttpContext,
ModelState = ModelState,
Request = request,
SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { "Administrator" } }
};
var pipeline = new ExcecutionPipeline<UserDetail, NewItemResponse>
(state);
await pipeline.ExecuteAsync();
return state.Response;
}
}
[Route("api/[controller]")]
public class UserListController : ApiControllerBase
{
[HttpGet]
public async Task<UserListResponse> Get
( UserListRequest request)
{
var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState
<UserListRequest, UserListResponse>
{
Command = new UserListQuery(request),
Context = HttpContext,
ModelState = ModelState,
Request = request,
SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { "Administrator" } }
};
var pipeline = new ExcecutionPipeline<UserListRequest, UserListResponse>
(state);
await pipeline.ExecuteAsync();
return state.Response;
}
}
[Route("api/[controller]")]
public class MemberController : ApiControllerBase
{
[HttpDelete]
public async Task<Response> Delete
( IdRequest request)
{
var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState
<IdRequest, Response>
{
Command = new MemberDeleteCommand(request),
Context = HttpContext,
ModelState = ModelState,
Request = request,
SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } }
};
var pipeline = new ExcecutionPipeline<IdRequest, Response>
(state);
await pipeline.ExecuteAsync();
return state.Response;
}
[HttpGet]
public async Task<Response<MemberDetail>> Get
( IdRequest request)
{
var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState
<IdRequest, Response<MemberDetail>>
{
Command = new MemberDetailQuery(request),
Context = HttpContext,
ModelState = ModelState,
Request = request,
SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } }
};
var pipeline = new ExcecutionPipeline<IdRequest, Response<MemberDetail>>
(state);
await pipeline.ExecuteAsync();
return state.Response;
}
[HttpPut]
public async Task<NewItemResponse> Put
([FromBody] MemberDetail request)
{
var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState
<MemberDetail, NewItemResponse>
{
Command = new MemberSaveCommand(request),
Context = HttpContext,
ModelState = ModelState,
Request = request,
SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } }
};
var pipeline = new ExcecutionPipeline<MemberDetail, NewItemResponse>
(state);
await pipeline.ExecuteAsync();
return state.Response;
}
}
[Route("api/[controller]")]
public class MemberListController : ApiControllerBase
{
[HttpGet]
public async Task<MemberListResponse> Get
( MemberListRequest request)
{
var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState
<MemberListRequest, MemberListResponse>
{
Command = new MemberListQuery(request),
Context = HttpContext,
ModelState = ModelState,
Request = request,
SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } }
};
var pipeline = new ExcecutionPipeline<MemberListRequest, MemberListResponse>
(state);
await pipeline.ExecuteAsync();
return state.Response;
}
}
[Route("api/[controller]")]
public class ListsController : ApiControllerBase
{
[HttpGet]
public async Task<ListsResponse> Get
( ListsRequest request)
{
var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState
<ListsRequest, ListsResponse>
{
Command = new LookupsQuery(request),
Context = HttpContext,
ModelState = ModelState,
Request = request,
SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } }
};
var pipeline = new ExcecutionPipeline<ListsRequest, ListsResponse>
(state);
await pipeline.ExecuteAsync();
return state.Response;
}
}
[Route("api/[controller]")]
public class ErrorDetailController : ApiControllerBase
{
[HttpGet]
public async Task<Response<ErrorDetail>> Get
( IdRequest request)
{
var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState
<IdRequest, Response<ErrorDetail>>
{
Command = new ErrorDetailQuery(request),
Context = HttpContext,
ModelState = ModelState,
Request = request,
SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } }
};
var pipeline = new ExcecutionPipeline<IdRequest, Response<ErrorDetail>>
(state);
await pipeline.ExecuteAsync();
return state.Response;
}
}
[Route("api/[controller]")]
public class ErrorListController : ApiControllerBase
{
[HttpGet]
public async Task<ErrorListResponse> Get
( ErrorListRequest request)
{
var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState
<ErrorListRequest, ErrorListResponse>
{
Command = new ErrorListQuery(request),
Context = HttpContext,
ModelState = ModelState,
Request = request,
SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } }
};
var pipeline = new ExcecutionPipeline<ErrorListRequest, ErrorListResponse>
(state);
await pipeline.ExecuteAsync();
return state.Response;
}
}
[Route("api/[controller]")]
public class MobileErrorController : ApiControllerBase
{
[HttpPost]
public async Task<Response> Post
([FromBody] MobileErrorRequest request)
{
var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState
<MobileErrorRequest, Response>
{
Command = new MobileErrorAddCommand(request),
Context = HttpContext,
ModelState = ModelState,
Request = request,
SecurityContext = new SecurityContext { AllowAnonymouse = true, Roles=new string[] { } }
};
var pipeline = new ExcecutionPipeline<MobileErrorRequest, Response>
(state);
await pipeline.ExecuteAsync();
return state.Response;
}
}
[Route("api/[controller]")]
public class CurrentUserController : ApiControllerBase
{
[HttpGet]
public async Task<Response<AppPrincipal>> Get
( EmptyRequest request)
{
var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState
<EmptyRequest, Response<AppPrincipal>>
{
Command = new GetCurrentUserCommand(request),
Context = HttpContext,
ModelState = ModelState,
Request = request,
SecurityContext = new SecurityContext { AllowAnonymouse = true, Roles=new string[] { } }
};
var pipeline = new ExcecutionPipeline<EmptyRequest, Response<AppPrincipal>>
(state);
await pipeline.ExecuteAsync();
return state.Response;
}
}
[Route("api/[controller]")]
public class ApplicationSettingController : ApiControllerBase
{
[HttpDelete]
public async Task<Response> Delete
( IdRequest request)
{
var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState
<IdRequest, Response>
{
Command = new ApplicationSettingDeleteCommand(request),
Context = HttpContext,
ModelState = ModelState,
Request = request,
SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } }
};
var pipeline = new ExcecutionPipeline<IdRequest, Response>
(state);
await pipeline.ExecuteAsync();
return state.Response;
}
[HttpPut]
public async Task<NewItemResponse> Put
([FromBody] ApplicationSettingDetail request)
{
var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState
<ApplicationSettingDetail, NewItemResponse>
{
Command = new ApplicationSettingSaveCommand(request),
Context = HttpContext,
ModelState = ModelState,
Request = request,
SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } }
};
var pipeline = new ExcecutionPipeline<ApplicationSettingDetail, NewItemResponse>
(state);
await pipeline.ExecuteAsync();
return state.Response;
}
[HttpGet]
public async Task<Response<ApplicationSettingDetail>> Get
( IdRequest request)
{
var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState
<IdRequest, Response<ApplicationSettingDetail>>
{
Command = new ApplicationSettingDetailQuery(request),
Context = HttpContext,
ModelState = ModelState,
Request = request,
SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } }
};
var pipeline = new ExcecutionPipeline<IdRequest, Response<ApplicationSettingDetail>>
(state);
await pipeline.ExecuteAsync();
return state.Response;
}
}
[Route("api/[controller]")]
public class ApplicationSettingListController : ApiControllerBase
{
[HttpGet]
public async Task<ApplicationSettingListResponse> Get
( ApplicationSettingListRequest request)
{
var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState
<ApplicationSettingListRequest, ApplicationSettingListResponse>
{
Command = new ApplicationSettingListQuery(request),
Context = HttpContext,
ModelState = ModelState,
Request = request,
SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } }
};
var pipeline = new ExcecutionPipeline<ApplicationSettingListRequest, ApplicationSettingListResponse>
(state);
await pipeline.ExecuteAsync();
return state.Response;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
#if FEATURE_CTYPES
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using IronPython.Runtime;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using System.Text;
namespace IronPython.Modules {
/// <summary>
/// Provides support for interop with native code from Python code.
/// </summary>
public static partial class CTypes {
/// <summary>
/// Meta class for structures. Validates _fields_ on creation, provides factory
/// methods for creating instances from addresses and translating to parameters.
/// </summary>
[PythonType, PythonHidden]
public class StructType : PythonType, INativeType {
internal Field[] _fields;
private int? _size, _alignment, _pack;
private static readonly Field[] _emptyFields = new Field[0]; // fields were never initialized before a type was created
public StructType(CodeContext/*!*/ context, string name, PythonTuple bases, PythonDictionary members)
: base(context, name, bases, members) {
foreach (PythonType pt in ResolutionOrder) {
StructType st = pt as StructType;
if (st != this) {
st?.EnsureFinal();
}
if (pt is UnionType ut) {
ut.EnsureFinal();
}
}
if (members.TryGetValue("_pack_", out object pack)) {
if (!(pack is int) || ((int)pack < 0)) {
throw PythonOps.ValueError("pack must be a non-negative integer");
}
_pack = (int)pack;
}
if (members.TryGetValue("_fields_", out object fields)) {
__setattr__(context, "_fields_", fields);
}
// TODO: _anonymous_
}
private StructType(Type underlyingSystemType)
: base(underlyingSystemType) {
}
public static ArrayType/*!*/ operator *(StructType type, int count) {
return MakeArrayType(type, count);
}
public static ArrayType/*!*/ operator *(int count, StructType type) {
return MakeArrayType(type, count);
}
public _Structure from_address(CodeContext/*!*/ context, int address) {
return from_address(context, new IntPtr(address));
}
public _Structure from_address(CodeContext/*!*/ context, BigInteger address) {
return from_address(context, new IntPtr((long)address));
}
public _Structure from_address(CodeContext/*!*/ context, IntPtr ptr) {
_Structure res = (_Structure)CreateInstance(context);
res.SetAddress(ptr);
return res;
}
public _Structure from_buffer(CodeContext/*!*/ context, ArrayModule.array array, int offset = 0) {
ValidateArraySizes(array, offset, ((INativeType)this).Size);
_Structure res = (_Structure)CreateInstance(context);
IntPtr addr = array.GetArrayAddress();
res._memHolder = new MemoryHolder(addr.Add(offset), ((INativeType)this).Size);
res._memHolder.AddObject("ffffffff", array);
return res;
}
public _Structure from_buffer_copy(CodeContext/*!*/ context, ArrayModule.array array, int offset = 0) {
ValidateArraySizes(array, offset, ((INativeType)this).Size);
_Structure res = (_Structure)CreateInstance(Context.SharedContext);
res._memHolder = new MemoryHolder(((INativeType)this).Size);
res._memHolder.CopyFrom(array.GetArrayAddress().Add(offset), new IntPtr(((INativeType)this).Size));
GC.KeepAlive(array);
return res;
}
/// <summary>
/// Converts an object into a function call parameter.
///
/// Structures just return themselves.
/// </summary>
public object from_param(object obj) {
if (!Builtin.isinstance(obj, this)) {
throw PythonOps.TypeError("expected {0} instance got {1}", Name, PythonOps.GetPythonTypeName(obj));
}
return obj;
}
public object in_dll(object library, string name) {
throw new NotImplementedException("in dll");
}
public new virtual void __setattr__(CodeContext/*!*/ context, string name, object value) {
if (name == "_fields_") {
lock (this) {
if (_fields != null) {
throw PythonOps.AttributeError("_fields_ is final");
}
SetFields(value);
}
}
base.__setattr__(context, name, value);
}
#region INativeType Members
int INativeType.Size {
get {
EnsureSizeAndAlignment();
return _size.Value;
}
}
int INativeType.Alignment {
get {
EnsureSizeAndAlignment();
return _alignment.Value;
}
}
object INativeType.GetValue(MemoryHolder/*!*/ owner, object readingFrom, int offset, bool raw) {
_Structure res = (_Structure)CreateInstance(this.Context.SharedContext);
res._memHolder = owner.GetSubBlock(offset);
return res;
}
object INativeType.SetValue(MemoryHolder/*!*/ address, int offset, object value) {
try {
return SetValueInternal(address, offset, value);
} catch (ArgumentTypeException e) {
throw PythonOps.RuntimeError("({0}) <type 'exceptions.TypeError'>: {1}",
Name,
e.Message);
} catch (ArgumentException e) {
throw PythonOps.RuntimeError("({0}) <type 'exceptions.ValueError'>: {1}",
Name,
e.Message);
}
}
internal object SetValueInternal(MemoryHolder address, int offset, object value) {
IList<object> init = value as IList<object>;
if (init != null) {
if (init.Count > _fields.Length) {
throw PythonOps.TypeError("too many initializers");
}
for (int i = 0; i < init.Count; i++) {
_fields[i].SetValue(address, offset, init[i]);
}
} else {
CData data = value as CData;
if (data != null) {
data._memHolder.CopyTo(address, offset, data.Size);
return data._memHolder.EnsureObjects();
} else {
throw new NotImplementedException("set value");
}
}
return null;
}
Type/*!*/ INativeType.GetNativeType() {
EnsureFinal();
return GetMarshalTypeFromSize(_size.Value);
}
MarshalCleanup INativeType.EmitMarshalling(ILGenerator/*!*/ method, LocalOrArg argIndex, List<object>/*!*/ constantPool, int constantPoolArgument) {
Type argumentType = argIndex.Type;
argIndex.Emit(method);
if (argumentType.IsValueType) {
method.Emit(OpCodes.Box, argumentType);
}
constantPool.Add(this);
method.Emit(OpCodes.Ldarg, constantPoolArgument);
method.Emit(OpCodes.Ldc_I4, constantPool.Count - 1);
method.Emit(OpCodes.Ldelem_Ref);
method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod(nameof(ModuleOps.CheckCDataType)));
method.Emit(OpCodes.Call, typeof(CData).GetProperty(nameof(CData.UnsafeAddress)).GetGetMethod());
method.Emit(OpCodes.Ldobj, ((INativeType)this).GetNativeType());
return null;
}
Type/*!*/ INativeType.GetPythonType() {
return typeof(object);
}
void INativeType.EmitReverseMarshalling(ILGenerator method, LocalOrArg value, List<object> constantPool, int constantPoolArgument) {
value.Emit(method);
EmitCDataCreation(this, method, constantPool, constantPoolArgument);
}
string INativeType.TypeFormat {
get {
if (_pack != null || _fields == _emptyFields || _fields == null) {
return "B";
}
StringBuilder res = new StringBuilder();
res.Append("T{");
foreach (Field f in _fields) {
res.Append(f.NativeType is ArrayType arrayType ? arrayType.ShapeAndFormatRepr() : f.NativeType.TypeFormat);
res.Append(':');
res.Append(f.FieldName);
res.Append(':');
}
res.Append('}');
return res.ToString();
}
}
#endregion
internal static PythonType MakeSystemType(Type underlyingSystemType) {
return PythonType.SetPythonType(underlyingSystemType, new StructType(underlyingSystemType));
}
private void SetFields(object fields) {
lock (this) {
IList<object> list = GetFieldsList(fields);
int? bitCount = null;
int? curBitCount = null;
INativeType lastType = null;
List<Field> allFields = GetBaseSizeAlignmentAndFields(out int size, out int alignment);
IList<object> anonFields = GetAnonymousFields(this);
for (int fieldIndex = 0; fieldIndex < list.Count; fieldIndex++) {
object o = list[fieldIndex];
GetFieldInfo(this, o, out string fieldName, out INativeType cdata, out bitCount);
int prevSize = UpdateSizeAndAlignment(cdata, bitCount, lastType, ref size, ref alignment, ref curBitCount);
Field newField = new Field(fieldName, cdata, prevSize, allFields.Count, bitCount, curBitCount - bitCount);
allFields.Add(newField);
AddSlot(fieldName, newField);
if (anonFields != null && anonFields.Contains(fieldName)) {
AddAnonymousFields(this, allFields, cdata, newField);
}
lastType = cdata;
}
CheckAnonymousFields(allFields, anonFields);
if (bitCount != null) {
size += lastType.Size;
}
_fields = allFields.ToArray();
_size = PythonStruct.Align(size, alignment);
_alignment = alignment;
}
}
internal static void CheckAnonymousFields(List<Field> allFields, IList<object> anonFields) {
if (anonFields != null) {
foreach (string s in anonFields) {
bool found = false;
foreach (Field f in allFields) {
if (f.FieldName == s) {
found = true;
break;
}
}
if (!found) {
throw PythonOps.AttributeError("anonymous field {0} is not defined in this structure", s);
}
}
}
}
internal static IList<object> GetAnonymousFields(PythonType type) {
object anonymous;
IList<object> anonFields = null;
if (type.TryGetBoundAttr(type.Context.SharedContext, type, "_anonymous_", out anonymous)) {
anonFields = anonymous as IList<object>;
if (anonFields == null) {
throw PythonOps.TypeError("_anonymous_ must be a sequence");
}
}
return anonFields;
}
internal static void AddAnonymousFields(PythonType type, List<Field> allFields, INativeType cdata, Field newField) {
Field[] childFields;
if (cdata is StructType) {
childFields = ((StructType)cdata)._fields;
} else if (cdata is UnionType) {
childFields = ((UnionType)cdata)._fields;
} else {
throw PythonOps.TypeError("anonymous field must be struct or union");
}
foreach (Field existingField in childFields) {
Field anonField = new Field(
existingField.FieldName,
existingField.NativeType,
checked(existingField.offset + newField.offset),
allFields.Count
);
type.AddSlot(existingField.FieldName, anonField);
allFields.Add(anonField);
}
}
private List<Field> GetBaseSizeAlignmentAndFields(out int size, out int alignment) {
size = 0;
alignment = 1;
List<Field> allFields = new List<Field>();
INativeType lastType = null;
int? totalBitCount = null;
foreach (PythonType pt in BaseTypes) {
StructType st = pt as StructType;
if (st != null) {
foreach (Field f in st._fields) {
allFields.Add(f);
UpdateSizeAndAlignment(f.NativeType, f.BitCount, lastType, ref size, ref alignment, ref totalBitCount);
if (f.NativeType == this) {
throw StructureCannotContainSelf();
}
lastType = f.NativeType;
}
}
}
return allFields;
}
private int UpdateSizeAndAlignment(INativeType cdata, int? bitCount, INativeType lastType, ref int size, ref int alignment, ref int? totalBitCount) {
int prevSize = size;
if (bitCount != null) {
if (lastType != null && lastType.Size != cdata.Size) {
totalBitCount = null;
prevSize = size += lastType.Size;
}
size = PythonStruct.Align(size, cdata.Alignment);
if (totalBitCount != null) {
if ((bitCount + totalBitCount + 7) / 8 <= cdata.Size) {
totalBitCount = bitCount + totalBitCount;
} else {
size += lastType.Size;
prevSize = size;
totalBitCount = bitCount;
}
} else {
totalBitCount = bitCount;
}
} else {
if (totalBitCount != null) {
size += lastType.Size;
prevSize = size;
totalBitCount = null;
}
if (_pack != null) {
alignment = _pack.Value;
prevSize = size = PythonStruct.Align(size, _pack.Value);
size += cdata.Size;
} else {
alignment = Math.Max(alignment, cdata.Alignment);
prevSize = size = PythonStruct.Align(size, cdata.Alignment);
size += cdata.Size;
}
}
return prevSize;
}
internal void EnsureFinal() {
if (_fields == null) {
SetFields(PythonTuple.EMPTY);
if (_fields.Length == 0) {
// track that we were initialized w/o fields.
_fields = _emptyFields;
}
}
}
/// <summary>
/// If our size/alignment hasn't been initialized then grabs the size/alignment
/// from all of our base classes. If later new _fields_ are added we'll be
/// initialized and these values will be replaced.
/// </summary>
private void EnsureSizeAndAlignment() {
Debug.Assert(_size.HasValue == _alignment.HasValue);
// these are always iniitalized together
if (_size == null) {
lock (this) {
if (_size == null) {
int size, alignment;
GetBaseSizeAlignmentAndFields(out size, out alignment);
_size = size;
_alignment = alignment;
}
}
}
}
}
}
}
#endif
| |
using System;
using System.IO;
using System.Linq;
using Umbraco.Core.Configuration;
using Umbraco.Core.IO;
namespace Umbraco.Core
{
/// <summary>
/// Provides extension methods to <see cref="Uri"/>.
/// </summary>
public static class UriExtensions
{
/// <summary>
/// Checks if the current uri is a back office request
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
internal static bool IsBackOfficeRequest(this Uri url)
{
var authority = url.GetLeftPart(UriPartial.Authority);
var afterAuthority = url.GetLeftPart(UriPartial.Query)
.TrimStart(authority)
.TrimStart("/");
//check if this is in the umbraco back office
return afterAuthority.InvariantStartsWith(GlobalSettings.Path.TrimStart("/"));
}
/// <summary>
/// Checks if the current uri is an install request
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
internal static bool IsInstallerRequest(this Uri url)
{
var authority = url.GetLeftPart(UriPartial.Authority);
var afterAuthority = url.GetLeftPart(UriPartial.Query)
.TrimStart(authority)
.TrimStart("/");
//check if this is in the umbraco back office
return afterAuthority.InvariantStartsWith(IOHelper.ResolveUrl("~/install").TrimStart("/"));
}
/// <summary>
/// This is a performance tweak to check if this is a .css, .js or .ico, .jpg, .jpeg, .png, .gif file request since
/// .Net will pass these requests through to the module when in integrated mode.
/// We want to ignore all of these requests immediately.
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
internal static bool IsClientSideRequest(this Uri url)
{
// fixme - IsClientSideRequest should not use an hard-coded list of extensions
// a client-side request is anything that has an extension that is not .aspx?
var toIgnore = new[] { ".js", ".css", ".ico", ".png", ".jpg", ".jpeg", ".gif", ".html", ".svg" };
return toIgnore.Any(x => Path.GetExtension(url.LocalPath).InvariantEquals(x));
}
/// <summary>
/// Rewrites the path of uri.
/// </summary>
/// <param name="uri">The uri.</param>
/// <param name="path">The new path, which must begin with a slash.</param>
/// <returns>The rewritten uri.</returns>
/// <remarks>Everything else remains unchanged, except for the fragment which is removed.</remarks>
public static Uri Rewrite(this Uri uri, string path)
{
if (path.StartsWith("/") == false)
throw new ArgumentException("Path must start with a slash.", "path");
return uri.IsAbsoluteUri
? new Uri(uri.GetLeftPart(UriPartial.Authority) + path + uri.Query)
: new Uri(path + uri.GetSafeQuery(), UriKind.Relative);
}
/// <summary>
/// Rewrites the path and query of a uri.
/// </summary>
/// <param name="uri">The uri.</param>
/// <param name="path">The new path, which must begin with a slash.</param>
/// <param name="query">The new query, which must be empty or begin with a question mark.</param>
/// <returns>The rewritten uri.</returns>
/// <remarks>Everything else remains unchanged, except for the fragment which is removed.</remarks>
public static Uri Rewrite(this Uri uri, string path, string query)
{
if (path.StartsWith("/") == false)
throw new ArgumentException("Path must start with a slash.", "path");
if (query.Length > 0 && query.StartsWith("?") == false)
throw new ArgumentException("Query must start with a question mark.", "query");
if (query == "?")
query = "";
return uri.IsAbsoluteUri
? new Uri(uri.GetLeftPart(UriPartial.Authority) + path + query)
: new Uri(path + query, UriKind.Relative);
}
/// <summary>
/// Gets the absolute path of the uri, even if the uri is relative.
/// </summary>
/// <param name="uri">The uri.</param>
/// <returns>The absolute path of the uri.</returns>
/// <remarks>Default uri.AbsolutePath does not support relative uris.</remarks>
public static string GetSafeAbsolutePath(this Uri uri)
{
if (uri.IsAbsoluteUri)
return uri.AbsolutePath;
// cannot get .AbsolutePath on relative uri (InvalidOperation)
var s = uri.OriginalString;
var posq = s.IndexOf("?", StringComparison.Ordinal);
var posf = s.IndexOf("#", StringComparison.Ordinal);
var pos = posq > 0 ? posq : (posf > 0 ? posf : 0);
var path = pos > 0 ? s.Substring(0, pos) : s;
return path;
}
/// <summary>
/// Gets the decoded, absolute path of the uri.
/// </summary>
/// <param name="uri">The uri.</param>
/// <returns>The absolute path of the uri.</returns>
/// <remarks>Only for absolute uris.</remarks>
public static string GetAbsolutePathDecoded(this Uri uri)
{
return System.Web.HttpUtility.UrlDecode(uri.AbsolutePath);
}
/// <summary>
/// Gets the decoded, absolute path of the uri, even if the uri is relative.
/// </summary>
/// <param name="uri">The uri.</param>
/// <returns>The absolute path of the uri.</returns>
/// <remarks>Default uri.AbsolutePath does not support relative uris.</remarks>
public static string GetSafeAbsolutePathDecoded(this Uri uri)
{
return System.Web.HttpUtility.UrlDecode(uri.GetSafeAbsolutePath());
}
/// <summary>
/// Rewrites the path of the uri so it ends with a slash.
/// </summary>
/// <param name="uri">The uri.</param>
/// <returns>The rewritten uri.</returns>
/// <remarks>Everything else remains unchanged.</remarks>
public static Uri EndPathWithSlash(this Uri uri)
{
var path = uri.GetSafeAbsolutePath();
if (uri.IsAbsoluteUri)
{
if (path != "/" && path.EndsWith("/") == false)
uri = new Uri(uri.GetLeftPart(UriPartial.Authority) + path + "/" + uri.Query);
return uri;
}
if (path != "/" && path.EndsWith("/") == false)
uri = new Uri(path + "/" + uri.Query, UriKind.Relative);
return uri;
}
/// <summary>
/// Rewrites the path of the uri so it does not end with a slash.
/// </summary>
/// <param name="uri">The uri.</param>
/// <returns>The rewritten uri.</returns>
/// <remarks>Everything else remains unchanged.</remarks>
public static Uri TrimPathEndSlash(this Uri uri)
{
var path = uri.GetSafeAbsolutePath();
if (uri.IsAbsoluteUri)
{
if (path != "/")
uri = new Uri(uri.GetLeftPart(UriPartial.Authority) + path.TrimEnd('/') + uri.Query);
}
else
{
if (path != "/")
uri = new Uri(path.TrimEnd('/') + uri.Query, UriKind.Relative);
}
return uri;
}
/// <summary>
/// Transforms a relative uri into an absolute uri.
/// </summary>
/// <param name="uri">The relative uri.</param>
/// <param name="baseUri">The base absolute uri.</param>
/// <returns>The absolute uri.</returns>
public static Uri MakeAbsolute(this Uri uri, Uri baseUri)
{
if (uri.IsAbsoluteUri)
throw new ArgumentException("Uri is already absolute.", "uri");
return new Uri(baseUri.GetLeftPart(UriPartial.Authority) + uri.GetSafeAbsolutePath() + uri.GetSafeQuery());
}
static string GetSafeQuery(this Uri uri)
{
if (uri.IsAbsoluteUri)
return uri.Query;
// cannot get .Query on relative uri (InvalidOperation)
var s = uri.OriginalString;
var posq = s.IndexOf("?", StringComparison.Ordinal);
var posf = s.IndexOf("#", StringComparison.Ordinal);
var query = posq < 0 ? null : (posf < 0 ? s.Substring(posq) : s.Substring(posq, posf - posq));
return query;
}
}
}
| |
//
// MagicWandTool.cs
//
// Author:
// Olivier Dufour <olivier.duff@gmail.com>
//
// Copyright (c) 2010 Olivier Dufour
//
// 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 Cairo;
using Pinta.Core;
using Mono.Unix;
using ClipperLibrary;
using System.Collections.Generic;
namespace Pinta.Tools
{
public class MagicWandTool : FloodTool
{
private Gtk.ToolItem selection_sep;
private ToolBarLabel selection_label;
private ToolBarComboBox selection_combo_box;
private Dictionary<int, string> selectionCombinations = new Dictionary<int, string>();
private int SelectionMode = 0;
private CombineMode combineMode;
public override Gdk.Key ShortcutKey { get { return Gdk.Key.S; } }
public MagicWandTool()
{
LimitToSelection = false;
selectionCombinations.Add(0, Catalog.GetString("Replace"));
selectionCombinations.Add(1, Catalog.GetString("Union (+) (Ctrl + Left Click)"));
selectionCombinations.Add(2, Catalog.GetString("Exclude (-) (Right Click)"));
selectionCombinations.Add(3, Catalog.GetString("Xor (Ctrl + Right Click)"));
selectionCombinations.Add(4, Catalog.GetString("Intersect (Shift + Left Click)"));
}
protected override void OnBuildToolBar(Gtk.Toolbar tb)
{
base.OnBuildToolBar(tb);
if (selection_sep == null)
selection_sep = new Gtk.SeparatorToolItem();
tb.AppendItem(selection_sep);
if (selection_label == null)
selection_label = new ToolBarLabel(Catalog.GetString(" Selection Mode: "));
tb.AppendItem(selection_label);
if (selection_combo_box == null)
{
selection_combo_box = new ToolBarComboBox(170, 0, false);
selection_combo_box.ComboBox.Changed += (o, e) =>
{
Gtk.TreeIter iter;
if (selection_combo_box.ComboBox.GetActiveIter(out iter))
{
SelectionMode = ((KeyValuePair<int, string>)selection_combo_box.Model.GetValue(iter, 1)).Key;
}
};
foreach(KeyValuePair<int, string> sel in selectionCombinations)
{
selection_combo_box.Model.AppendValues(sel.Value, sel);
}
selection_combo_box.ComboBox.Active = 0;
}
tb.AppendItem(selection_combo_box);
}
public override string Name
{
get { return Catalog.GetString("Magic Wand Select"); }
}
public override string Icon
{
get { return "Tools.MagicWand.png"; }
}
public override string StatusBarText
{
get { return Catalog.GetString("Click to select region of similar color."); }
}
public override Gdk.Cursor DefaultCursor
{
get { return new Gdk.Cursor(PintaCore.Chrome.Canvas.Display, PintaCore.Resources.GetIcon("Cursor.MagicWand.png"), 21, 10); }
}
public override int Priority { get { return 17; } }
private enum CombineMode
{
Union, //Control + Left Click
Xor, //Control + Right Click
Exclude, //Right Click
Replace, //Left Click (and default)
Intersect //Shift + Left Click
}
protected override void OnMouseDown(Gtk.DrawingArea canvas, Gtk.ButtonPressEventArgs args, Cairo.PointD point)
{
Document doc = PintaCore.Workspace.ActiveDocument;
//SetCursor (Cursors.WaitCursor);
//Here is where the CombineMode for the Magic Wand Tool's selection is determined based on None/Ctrl/Shift + Left/Right Click.
switch (SelectionMode)
{
case 1:
combineMode = CombineMode.Union;
break;
case 2:
combineMode = CombineMode.Exclude;
break;
case 3:
combineMode = CombineMode.Xor;
break;
case 4:
combineMode = CombineMode.Intersect;
break;
default:
//Left Click (usually) - also the default
combineMode = CombineMode.Replace;
break;
}
if (args.Event.Button == 1)
{
if (args.Event.IsControlPressed())
{
//Control + Left Click
combineMode = CombineMode.Union;
}
else if (args.Event.IsShiftPressed())
{
//Shift + Left Click
combineMode = CombineMode.Intersect;
}
}
else if (args.Event.Button == 3)
{
if (args.Event.IsControlPressed())
{
//Control + Right Click
combineMode = CombineMode.Xor;
}
else
{
//Right Click
combineMode = CombineMode.Exclude;
}
}
base.OnMouseDown(canvas, args, point);
doc.ShowSelection = true;
}
protected override void OnFillRegionComputed(Point[][] polygonSet)
{
Document doc = PintaCore.Workspace.ActiveDocument;
SelectionHistoryItem undoAction = new SelectionHistoryItem(this.Icon, this.Name);
undoAction.TakeSnapshot();
//Convert Pinta's passed in Polygon Set to a Clipper Polygon collection.
List<List<IntPoint>> newPolygons = DocumentSelection.ConvertToPolygons(polygonSet);
using (Context g = new Context(PintaCore.Layers.CurrentLayer.Surface))
{
//Make sure time isn't wasted if the CombineMode is Replace - Replace is much simpler than the other 4 selection modes.
if (combineMode == CombineMode.Replace)
{
//Clear any previously stored Polygons.
doc.Selection.SelectionPolygons.Clear();
//Set the resulting selection path to the new selection path.
doc.Selection.SelectionPolygons = newPolygons;
doc.Selection.SelectionPath = g.CreatePolygonPath(polygonSet);
}
else
{
List<List<IntPoint>> resultingPolygons = new List<List<IntPoint>>();
//Specify the Clipper Subject (the previous Polygons) and the Clipper Clip (the new Polygons).
//Note: for Union, ignore the Clipper Library instructions - the new polygon(s) should be Clips, not Subjects!
doc.Selection.SelectionClipper.AddPolygons(doc.Selection.SelectionPolygons, PolyType.ptSubject);
doc.Selection.SelectionClipper.AddPolygons(newPolygons, PolyType.ptClip);
switch (combineMode)
{
case CombineMode.Xor:
//Xor means "Combine both Polygon sets, but leave out any areas of intersection between the two."
doc.Selection.SelectionClipper.Execute(ClipType.ctXor, resultingPolygons);
break;
case CombineMode.Exclude:
//Exclude == Difference
//Exclude/Difference means "Subtract any overlapping areas of the new Polygon set from the old Polygon set."
doc.Selection.SelectionClipper.Execute(ClipType.ctDifference, resultingPolygons);
break;
case CombineMode.Intersect:
//Intersect means "Leave only the overlapping areas between the new and old Polygon sets."
doc.Selection.SelectionClipper.Execute(ClipType.ctIntersection, resultingPolygons);
break;
default:
//Default should only be *CombineMode.Union*, but just in case...
//Union means "Combine both Polygon sets, and keep any overlapping areas as well."
doc.Selection.SelectionClipper.Execute(ClipType.ctUnion, resultingPolygons);
break;
}
//After using Clipper, it has to be cleared so there are no conflicts with its next usage.
doc.Selection.SelectionClipper.Clear();
//Set the resulting selection path to the calculated ("clipped") selection path.
doc.Selection.SelectionPolygons = resultingPolygons;
doc.Selection.SelectionPath = g.CreatePolygonPath(DocumentSelection.ConvertToPolygonSet(resultingPolygons));
}
}
doc.History.PushNewItem(undoAction);
doc.Workspace.Invalidate();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.AspNetCore.WebUtilities;
namespace Microsoft.AspNetCore.Mvc
{
/// <summary>
/// Provides programmatic configuration for the MVC framework.
/// </summary>
public class MvcOptions : IEnumerable<ICompatibilitySwitch>
{
internal const int DefaultMaxModelBindingCollectionSize = FormReader.DefaultValueCountLimit;
internal const int DefaultMaxModelBindingRecursionDepth = 32;
private readonly IReadOnlyList<ICompatibilitySwitch> _switches = Array.Empty<ICompatibilitySwitch>();
private int _maxModelStateErrors = ModelStateDictionary.DefaultMaxAllowedErrors;
private int _maxModelBindingCollectionSize = DefaultMaxModelBindingCollectionSize;
private int _maxModelBindingRecursionDepth = DefaultMaxModelBindingRecursionDepth;
private int? _maxValidationDepth = 32;
/// <summary>
/// Creates a new instance of <see cref="MvcOptions"/>.
/// </summary>
public MvcOptions()
{
CacheProfiles = new Dictionary<string, CacheProfile>(StringComparer.OrdinalIgnoreCase);
Conventions = new List<IApplicationModelConvention>();
Filters = new FilterCollection();
FormatterMappings = new FormatterMappings();
InputFormatters = new FormatterCollection<IInputFormatter>();
OutputFormatters = new FormatterCollection<IOutputFormatter>();
ModelBinderProviders = new List<IModelBinderProvider>();
ModelBindingMessageProvider = new DefaultModelBindingMessageProvider();
ModelMetadataDetailsProviders = new List<IMetadataDetailsProvider>();
ModelValidatorProviders = new List<IModelValidatorProvider>();
ValueProviderFactories = new List<IValueProviderFactory>();
}
/// <summary>
/// Gets or sets a value that determines if routing should use endpoints internally, or if legacy routing
/// logic should be used. Endpoint routing is used to match HTTP requests to MVC actions, and to generate
/// URLs with <see cref="IUrlHelper"/>.
/// </summary>
/// <value>
/// The default value is <see langword="true"/>.
/// </value>
public bool EnableEndpointRouting { get; set; } = true;
/// <summary>
/// Gets or sets the flag which decides whether body model binding (for example, on an
/// action method parameter with <see cref="FromBodyAttribute"/>) should treat empty
/// input as valid. <see langword="false"/> by default.
/// </summary>
/// <example>
/// When <see langword="false"/>, actions that model bind the request body (for example,
/// using <see cref="FromBodyAttribute"/>) will register an error in the
/// <see cref="ModelStateDictionary"/> if the incoming request body is empty.
/// </example>
public bool AllowEmptyInputInBodyModelBinding { get; set; }
/// <summary>
/// Gets a Dictionary of CacheProfile Names, <see cref="CacheProfile"/> which are pre-defined settings for
/// response caching.
/// </summary>
public IDictionary<string, CacheProfile> CacheProfiles { get; }
/// <summary>
/// Gets a list of <see cref="IApplicationModelConvention"/> instances that will be applied to
/// the <see cref="ApplicationModel"/> when discovering actions.
/// </summary>
public IList<IApplicationModelConvention> Conventions { get; }
/// <summary>
/// Gets a collection of <see cref="IFilterMetadata"/> which are used to construct filters that
/// apply to all actions.
/// </summary>
public FilterCollection Filters { get; }
/// <summary>
/// Used to specify mapping between the URL Format and corresponding media type.
/// </summary>
public FormatterMappings FormatterMappings { get; }
/// <summary>
/// Gets a list of <see cref="IInputFormatter"/>s that are used by this application.
/// </summary>
public FormatterCollection<IInputFormatter> InputFormatters { get; }
/// <summary>
/// Gets or sets a value that determines if the inference of <see cref="RequiredAttribute"/> for
/// properties and parameters of non-nullable reference types is suppressed. If <c>false</c>
/// (the default), then all non-nullable reference types will behave as-if <c>[Required]</c> has
/// been applied. If <c>true</c>, this behavior will be suppressed; nullable reference types and
/// non-nullable reference types will behave the same for the purposes of validation.
/// </summary>
/// <remarks>
/// <para>
/// This option controls whether MVC model binding and validation treats nullable and non-nullable
/// reference types differently.
/// </para>
/// <para>
/// By default, MVC will treat a non-nullable reference type parameters and properties as-if
/// <c>[Required]</c> has been applied, resulting in validation errors when no value was bound.
/// </para>
/// <para>
/// MVC does not support non-nullable reference type annotations on type arguments and type parameter
/// contraints. The framework will not infer any validation attributes for generic-typed properties
/// or collection elements.
/// </para>
/// </remarks>
public bool SuppressImplicitRequiredAttributeForNonNullableReferenceTypes { get; set; }
/// <summary>
/// Gets or sets a value that determines if buffering is disabled for input formatters that
/// synchronously read from the HTTP request body.
/// </summary>
public bool SuppressInputFormatterBuffering { get; set; }
/// <summary>
/// Gets or sets the flag that determines if buffering is disabled for output formatters that
/// synchronously write to the HTTP response body.
/// </summary>
public bool SuppressOutputFormatterBuffering { get; set; }
/// <summary>
/// Gets or sets the flag that determines if MVC should use action invoker extensibility. This will allow
/// custom <see cref="IActionInvokerFactory"/> and <see cref="IActionInvokerProvider"/> execute during the request pipeline.
/// </summary>
/// <remarks>This only applies when <see cref="EnableEndpointRouting"/> is true.</remarks>
/// <value>Defaults to <see langword="false" /> indicating that action invokers are unused by default.</value>
public bool EnableActionInvokers { get; set; }
/// <summary>
/// Gets or sets the maximum number of validation errors that are allowed by this application before further
/// errors are ignored.
/// </summary>
public int MaxModelValidationErrors
{
get => _maxModelStateErrors;
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_maxModelStateErrors = value;
}
}
/// <summary>
/// Gets a list of <see cref="IModelBinderProvider"/>s used by this application.
/// </summary>
public IList<IModelBinderProvider> ModelBinderProviders { get; }
/// <summary>
/// Gets the default <see cref="ModelBinding.Metadata.ModelBindingMessageProvider"/>. Changes here are copied to the
/// <see cref="ModelMetadata.ModelBindingMessageProvider"/> property of all <see cref="ModelMetadata"/>
/// instances unless overridden in a custom <see cref="IBindingMetadataProvider"/>.
/// </summary>
public DefaultModelBindingMessageProvider ModelBindingMessageProvider { get; }
/// <summary>
/// Gets a list of <see cref="IMetadataDetailsProvider"/> instances that will be used to
/// create <see cref="ModelMetadata"/> instances.
/// </summary>
/// <remarks>
/// A provider should implement one or more of the following interfaces, depending on what
/// kind of details are provided:
/// <ul>
/// <li><see cref="IBindingMetadataProvider"/></li>
/// <li><see cref="IDisplayMetadataProvider"/></li>
/// <li><see cref="IValidationMetadataProvider"/></li>
/// </ul>
/// </remarks>
public IList<IMetadataDetailsProvider> ModelMetadataDetailsProviders { get; }
/// <summary>
/// Gets a list of <see cref="IModelValidatorProvider"/>s used by this application.
/// </summary>
public IList<IModelValidatorProvider> ModelValidatorProviders { get; }
/// <summary>
/// Gets a list of <see cref="IOutputFormatter"/>s that are used by this application.
/// </summary>
public FormatterCollection<IOutputFormatter> OutputFormatters { get; }
/// <summary>
/// Gets or sets the flag which causes content negotiation to ignore Accept header
/// when it contains the media type <c>*/*</c>. <see langword="false"/> by default.
/// </summary>
public bool RespectBrowserAcceptHeader { get; set; }
/// <summary>
/// Gets or sets the flag which decides whether an HTTP 406 Not Acceptable response
/// will be returned if no formatter has been selected to format the response.
/// <see langword="false"/> by default.
/// </summary>
public bool ReturnHttpNotAcceptable { get; set; }
/// <summary>
/// Gets a list of <see cref="IValueProviderFactory"/> used by this application.
/// </summary>
public IList<IValueProviderFactory> ValueProviderFactories { get; }
/// <summary>
/// Gets or sets the SSL port that is used by this application when <see cref="RequireHttpsAttribute"/>
/// is used. If not set the port won't be specified in the secured URL e.g. https://localhost/path.
/// </summary>
public int? SslPort { get; set; }
/// <summary>
/// Gets or sets the default value for the Permanent property of <see cref="RequireHttpsAttribute"/>.
/// </summary>
public bool RequireHttpsPermanent { get; set; }
/// <summary>
/// Gets or sets the maximum depth to constrain the validation visitor when validating. Set to <see langword="null" />
/// to disable this feature.
/// <para>
/// <see cref="ValidationVisitor"/> traverses the object graph of the model being validated. For models
/// that are very deep or are infinitely recursive, validation may result in stack overflow.
/// </para>
/// <para>
/// When not <see langword="null"/>, <see cref="ValidationVisitor"/> will throw if
/// traversing an object exceeds the maximum allowed validation depth.
/// </para>
/// </summary>
/// <value>
/// The default value is <c>32</c>.
/// </value>
public int? MaxValidationDepth
{
get => _maxValidationDepth;
set
{
if (value != null && value <= 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_maxValidationDepth = value;
}
}
/// <summary>
/// Gets or sets a value that determines whether the validation visitor will perform validation of a complex type
/// if validation fails for any of its children.
/// <seealso cref="ValidationVisitor.ValidateComplexTypesIfChildValidationFails"/>
/// </summary>
/// <value>
/// The default value is <see langword="false"/>.
/// </value>
public bool ValidateComplexTypesIfChildValidationFails { get; set; }
/// <summary>
/// Gets or sets a value that determines if MVC will remove the suffix "Async" applied to
/// controller action names.
/// <para>
/// <see cref="ControllerActionDescriptor.ActionName"/> is used to construct the route to the action as
/// well as in view lookup. When <see langword="true"/>, MVC will trim the suffix "Async" applied
/// to action method names.
/// For example, the action name for <c>ProductsController.ListProductsAsync</c> will be
/// canonicalized as <c>ListProducts.</c>. Consequently, it will be routeable at
/// <c>/Products/ListProducts</c> with views looked up at <c>/Views/Products/ListProducts.cshtml</c>.
/// </para>
/// <para>
/// This option does not affect values specified using <see cref="ActionNameAttribute"/>.
/// </para>
/// </summary>
/// <value>
/// The default value is <see langword="true"/>.
/// </value>
public bool SuppressAsyncSuffixInActionNames { get; set; } = true;
/// <summary>
/// Gets or sets the maximum size of a complex collection to model bind. When this limit is reached, the model
/// binding system will throw an <see cref="InvalidOperationException"/>.
/// </summary>
/// <remarks>
/// <para>
/// When binding a collection, some element binders may succeed unconditionally and model binding may run out
/// of memory. This limit constrains such unbounded collection growth; it is a safeguard against incorrect
/// model binders and models.
/// </para>
/// <para>
/// This limit does not <em>correct</em> the bound model. The <see cref="InvalidOperationException"/> instead
/// informs the developer of an issue in their model or model binder. The developer must correct that issue.
/// </para>
/// <para>
/// This limit does not apply to collections of simple types. When
/// <see cref="CollectionModelBinder{TElement}"/> relies entirely on <see cref="IValueProvider"/>s, it cannot
/// create collections larger than the available data.
/// </para>
/// <para>
/// A very high value for this option (<c>int.MaxValue</c> for example) effectively removes the limit and is
/// not recommended.
/// </para>
/// </remarks>
/// <value>The default value is <c>1024</c>, matching <see cref="FormReader.DefaultValueCountLimit"/>.</value>
public int MaxModelBindingCollectionSize
{
get => _maxModelBindingCollectionSize;
set
{
// Disallowing an empty collection would cause the CollectionModelBinder to throw unconditionally.
if (value <= 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_maxModelBindingCollectionSize = value;
}
}
/// <summary>
/// Gets or sets the maximum recursion depth of the model binding system. The
/// <see cref="DefaultModelBindingContext"/> will throw an <see cref="InvalidOperationException"/> if more than
/// this number of <see cref="IModelBinder"/>s are on the stack. That is, an attempt to recurse beyond this
/// level will fail.
/// </summary>
/// <remarks>
/// <para>
/// For some self-referential models, some binders may succeed unconditionally and model binding may result in
/// stack overflow. This limit constrains such unbounded recursion; it is a safeguard against incorrect model
/// binders and models. This limit also protects against very deep model type hierarchies lacking
/// self-references.
/// </para>
/// <para>
/// This limit does not <em>correct</em> the bound model. The <see cref="InvalidOperationException"/> instead
/// informs the developer of an issue in their model. The developer must correct that issue.
/// </para>
/// <para>
/// A very high value for this option (<c>int.MaxValue</c> for example) effectively removes the limit and is
/// not recommended.
/// </para>
/// </remarks>
/// <value>The default value is <c>32</c>, matching the default <see cref="MaxValidationDepth"/> value.</value>
public int MaxModelBindingRecursionDepth
{
get => _maxModelBindingRecursionDepth;
set
{
// Disallowing one model binder (if supported) would cause the model binding system to throw
// unconditionally. DefaultModelBindingContext always allows a top-level binder i.e. its own creation.
if (value <= 1)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_maxModelBindingRecursionDepth = value;
}
}
/// <summary>
/// Gets or sets the most number of entries of an <see cref="IAsyncEnumerable{T}"/> that
/// that <see cref="ObjectResultExecutor"/> will buffer.
/// <para>
/// When <see cref="ObjectResult.Value" /> is an instance of <see cref="IAsyncEnumerable{T}"/>,
/// <see cref="ObjectResultExecutor"/> will eagerly read the enumeration and add to a synchronous collection
/// prior to invoking the selected formatter.
/// This property determines the most number of entries that the executor is allowed to buffer.
/// </para>
/// </summary>
/// <value>Defaults to <c>8192</c>.</value>
public int MaxIAsyncEnumerableBufferLimit { get; set; } = 8192;
IEnumerator<ICompatibilitySwitch> IEnumerable<ICompatibilitySwitch>.GetEnumerator() => _switches.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => _switches.GetEnumerator();
}
}
| |
namespace Microsoft.Protocols.TestSuites.SharedTestSuite
{
using System.Collections.Generic;
using System.Linq;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestSuites.SharedAdapter;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// A class which contains test cases used to capture the requirements related with CellSubRequest operation for creating new file on the server.
/// </summary>
[TestClass]
public abstract class S15_CreateFile : SharedTestSuiteBase
{
#region Test Suite Initialization
/// <summary>
/// A method used to initialize this class.
/// </summary>
/// <param name="testContext">A parameter represents the context of the test suite.</param>
[ClassInitialize]
public static new void ClassInitialize(TestContext testContext)
{
SharedTestSuiteBase.ClassInitialize(testContext);
}
/// <summary>
/// A method used to clean up the test environment.
/// </summary>
[ClassCleanup]
public static new void ClassCleanup()
{
SharedTestSuiteBase.ClassCleanup();
}
#endregion
#region Test Case Initialization
/// <summary>
/// A method used to initialize the test class.
/// </summary>
[TestInitialize]
public void S15_CreateFileInitialization()
{
// Initialize the default file URL, for this scenario, the target file URL should not need unique for each test case, just using the preparing one.
this.DefaultFileUrl = Common.GetConfigurationPropertyValue("NormalFile", this.Site);
}
#endregion
/// <summary>
/// This method is used to test uploading a file for the first time.
/// </summary>
[TestCategory("SHAREDTESTCASE"), TestMethod()]
public void TestCase_S15_TC01_CreateFile()
{
string randomFileUrl = SharedTestSuiteHelper.GenerateNonExistFileUrl(this.Site);
// Initialize the context using user01 and defaultFileUrl.
this.InitializeContext(randomFileUrl, this.UserName01, this.Password01, this.Domain);
CellSubRequestType putChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedPutChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), SharedTestSuiteHelper.GenerateRandomFileContent(this.Site));
putChange.SubRequestData.CoalesceSpecified = true;
putChange.SubRequestData.Coalesce = true;
CellStorageResponse response = Adapter.CellStorageRequest(randomFileUrl, new SubRequestType[] { putChange });
CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site);
this.Site.Assert.AreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site),
"When uploading contents if the protocol server was unable to find the URL for the file specified in the Url attribute,, the server returns success and create a new file using the specified contents in the file URI.");
// Query the updated file content.
CellSubRequestType queryChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedQueryChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID());
response = Adapter.CellStorageRequest(randomFileUrl, new SubRequestType[] { queryChange });
cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site);
if (SharedContext.Current.IsMsFsshttpRequirementsCaptured)
{
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R3103
// If queryChange subrequest can download a file from randomFileUrl, then capture MS-FSSHTTP_R3103.
Site.CaptureRequirementIfAreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site),
"MS-FSSHTTP",
3103,
@"[In Cell Subrequest] But for Put Changes subrequest, as described in [MS-FSSHTTPB] section 2.2.2.1.4, [If the protocol server was unable to find the URL for the file specified in the Url attribute] the protocol server creates a new file using the specified Url.");
}
else
{
Site.Assert.AreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site),
@"[In Cell Subrequest] But for Put Changes subrequest, as described in [MS-FSSHTTPB] section 2.2.2.1.4, [If the protocol server was unable to find the URL for the file specified in the Url attribute] the protocol server creates a new file using the specified Url.");
}
this.StatusManager.RecordFileUpload(randomFileUrl);
// Re-generate the non-exist file URL again.
randomFileUrl = SharedTestSuiteHelper.GenerateNonExistFileUrl(this.Site);
this.InitializeContext(randomFileUrl, this.UserName01, this.Password01, this.Domain);
putChange.SubRequestData.ExpectNoFileExistsSpecified = true;
putChange.SubRequestData.ExpectNoFileExists = true;
putChange.SubRequestData.Etag = string.Empty;
putChange.SubRequestData.CoalesceSpecified = true;
putChange.SubRequestData.Coalesce = true;
response = Adapter.CellStorageRequest(randomFileUrl, new SubRequestType[] { putChange });
cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site);
if (SharedContext.Current.IsMsFsshttpRequirementsCaptured)
{
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R2252
Site.CaptureRequirementIfAreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site),
"MS-FSSHTTP",
2252,
@"[In Cell Subrequest] In this case[If the ExpectNoFileExists attribute is set to true in a file content upload cell subrequest, the Etag attribute MUST be an empty string], the protocol server MUST NOT cause the cell subrequest to fail with a coherency error if the file does not exist on the server.");
}
else
{
Site.Assert.AreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site),
@"[In Cell Subrequest] In this case[If the ExpectNoFileExists attribute is set to true in a file content upload cell subrequest, the Etag attribute MUST be an empty string], the protocol server MUST NOT cause the cell subrequest to fail with a coherency error if the file does not exist on the server.");
}
this.StatusManager.RecordFileUpload(randomFileUrl);
}
/// <summary>
/// This method is used to test uploading a file for the first time with an exclusive lock.
/// </summary>
[TestCategory("SHAREDTESTCASE"), TestMethod()]
public void TestCase_S15_TC02_UploadContents_CreateFile_ExclusiveLock()
{
string randomFileUrl = SharedTestSuiteHelper.GenerateNonExistFileUrl(this.Site);
// Initialize the context using user01 and defaultFileUrl.
this.InitializeContext(randomFileUrl, this.UserName01, this.Password01, this.Domain);
CellSubRequestType putChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedPutChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), SharedTestSuiteHelper.GenerateRandomFileContent(this.Site));
putChange.SubRequestData.CoalesceSpecified = true;
putChange.SubRequestData.Coalesce = true;
putChange.SubRequestData.ExpectNoFileExistsSpecified = true;
putChange.SubRequestData.ExpectNoFileExists = true;
putChange.SubRequestData.ExclusiveLockID = SharedTestSuiteHelper.DefaultExclusiveLockID;
putChange.SubRequestData.Timeout = "3600";
CellStorageResponse response = Adapter.CellStorageRequest(randomFileUrl, new SubRequestType[] { putChange });
CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site);
this.Site.Assert.AreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site),
"When uploading contents if the protocol server was unable to find the URL for the file specified in the Url attribute,, the server returns success and create a new file using the specified contents in the file URI.");
bool isExclusiveLock = this.CheckExclusiveLockExist(randomFileUrl, SharedTestSuiteHelper.DefaultExclusiveLockID, this.UserName01, this.Password01, this.Domain);
Site.Log.Add(
TestTools.LogEntryKind.Debug,
"When creating a new file with ExclusiveLockID specified, the server will lock the new created file, but actually it {0}",
isExclusiveLock ? "locks" : "does not lock");
Site.Assert.IsTrue(
isExclusiveLock,
"When creating a new file with ExclusiveLockID specified, the server will lock the new created file");
this.StatusManager.RecordExclusiveLock(randomFileUrl, SharedTestSuiteHelper.DefaultExclusiveLockID, this.UserName01, this.Password01, this.Domain);
this.StatusManager.RecordFileUpload(randomFileUrl);
}
/// <summary>
/// This method is used to test uploading a new file incrementally by the contents which is downloading from the server.
/// </summary>
[TestCategory("SHAREDTESTCASE"), TestMethod()]
public void TestCase_S15_TC03_Download_UploadPartial()
{
string fileUrl = Common.GetConfigurationPropertyValue("BigFile", this.Site);
string uploadFileUrl = SharedTestSuiteHelper.GenerateNonExistFileUrl(Site);
bool partial = false;
Knowledge knowledge = null;
// Set the limit number of upload tries, this will allow 500000 * 10 bytes size file to be download and complete upload.
int limitNumberOfPartialUpload = 10;
do
{
this.InitializeContext(fileUrl, this.UserName01, this.Password01, this.Domain);
// Create query changes request with allow fragments flag with the value false.
FsshttpbCellRequest cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest();
QueryChangesCellSubRequest queryChange = SharedTestSuiteHelper.BuildFsshttpbQueryChangesSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), 0, false, false, true, 0, true, true, 0, null, 500000, null, knowledge);
cellRequest.AddSubRequest(queryChange, null);
CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64());
CellStorageResponse cellStorageResponse = this.Adapter.CellStorageRequest(fileUrl, new SubRequestType[] { cellSubRequest });
CellSubResponseType subResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(cellStorageResponse, 0, 0, this.Site);
this.Site.Assert.AreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(subResponse.ErrorCode, this.Site),
"Test case cannot continue unless the query changes succeed.");
FsshttpbResponse queryResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(subResponse, this.Site);
SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(queryResponse, this.Site);
QueryChangesSubResponseData data = queryResponse.CellSubResponses[0].GetSubResponseData<QueryChangesSubResponseData>();
partial = data.PartialResult;
knowledge = data.Knowledge;
this.InitializeContext(uploadFileUrl, this.UserName01, this.Password01, this.Domain);
cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest();
PutChangesCellSubRequest putChange = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), null);
putChange.Partial = partial ? 1 : 0;
putChange.PartialLast = partial ? 0 : 1;
putChange.StorageIndexExtendedGUID = partial ? null : data.StorageIndexExtendedGUID;
if (partial)
{
var storageIndex = queryResponse.DataElementPackage.DataElements.FirstOrDefault(e => e.DataElementType == DataElementType.StorageIndexDataElementData);
if (storageIndex != null)
{
queryResponse.DataElementPackage.DataElements.Remove(storageIndex);
}
}
cellRequest.AddSubRequest(putChange, queryResponse.DataElementPackage.DataElements);
cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64());
cellStorageResponse = this.Adapter.CellStorageRequest(uploadFileUrl, new SubRequestType[] { cellSubRequest });
subResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(cellStorageResponse, 0, 0, this.Site);
this.Site.Assert.AreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(subResponse.ErrorCode, this.Site),
"Test case cannot continue unless the query changes succeed.");
FsshttpbResponse putResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(subResponse, this.Site);
SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(putResponse, this.Site);
// Decrease the number of upload tries.
limitNumberOfPartialUpload--;
}
while (partial && limitNumberOfPartialUpload > 0);
this.StatusManager.RecordFileUpload(uploadFileUrl);
}
/// <summary>
/// This method is used to test uploading file contents succeeds when the file has an exclusive lock and the ByPassLockID is specified or not specified.
/// </summary>
[TestCategory("SHAREDTESTCASE"), TestMethod()]
public void TestCase_S15_TC04_UploadContents_ExclusiveLockSuccess()
{
string randomFileUrl = SharedTestSuiteHelper.GenerateNonExistFileUrl(this.Site);
// Initialize the context using user01 and defaultFileUrl.
this.InitializeContext(randomFileUrl, this.UserName01, this.Password01, this.Domain);
CellSubRequestType putChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedPutChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), SharedTestSuiteHelper.GenerateRandomFileContent(this.Site));
putChange.SubRequestData.CoalesceSpecified = true;
putChange.SubRequestData.Coalesce = true;
putChange.SubRequestData.ExpectNoFileExistsSpecified = true;
putChange.SubRequestData.ExpectNoFileExists = true;
putChange.SubRequestData.ExclusiveLockID = SharedTestSuiteHelper.DefaultExclusiveLockID;
putChange.SubRequestData.BypassLockID = putChange.SubRequestData.ExclusiveLockID;
putChange.SubRequestData.Timeout = "3600";
CellStorageResponse response = Adapter.CellStorageRequest(randomFileUrl, new SubRequestType[] { putChange });
CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site);
this.Site.Assert.AreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site),
"When the file is locked by exclusive lock and the ByPassLockID is specified by the valid exclusive lock id, the server returns the error code success.");
this.StatusManager.RecordExclusiveLock(randomFileUrl, SharedTestSuiteHelper.DefaultExclusiveLockID, this.UserName01, this.Password01, this.Domain);
this.StatusManager.RecordFileUpload(randomFileUrl);
if (SharedContext.Current.IsMsFsshttpRequirementsCaptured)
{
// If the server responds with the error code "Success",
// when the above steps show that the client has got an exclusive lock and the PutChange subrequest was sent with BypassLockID equal to ExclusiveLockID,
// then requirement MS-FSSHTTP_R833 is captured.
Site.CaptureRequirementIfAreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site),
"MS-FSSHTTP",
833,
@"[In CellSubRequestDataOptionalAttributes][BypassLockID] If a client has got an exclusive lock, this value[BypassLockID] MUST be the same as the value of ExclusiveLockID, as specified in section 2.3.1.1.");
// If the server responds with "ExclusiveLock" in LockType attribute, the requirement MS-FSSHTTP_R1533 is captured.
Site.CaptureRequirementIfAreEqual<string>(
"ExclusiveLock",
cellSubResponse.SubResponseData.LockType.ToString(),
"MS-FSSHTTP",
1533,
@"[In CellSubResponseDataType] The LockType attribute MUST be set to ""ExclusiveLock"" in the cell subresponse if the ExclusiveLockID attribute is sent in the cell subrequest and the protocol server is successfully able to take an exclusive lock.");
}
else
{
Site.Assert.AreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site),
@"[In CellSubRequestDataOptionalAttributes][BypassLockID] If a client has got an exclusive lock, this value[BypassLockID] MUST be the same as the value of ExclusiveLockID, as specified in section 2.3.1.1.");
Site.Assert.AreEqual<string>(
"ExclusiveLock",
cellSubResponse.SubResponseData.LockType.ToString(),
@"[In CellSubResponseDataType] The LockType attribute MUST be set to ""ExclusiveLock"" in the cell subresponse if the ExclusiveLockID attribute is sent in the cell subrequest and the protocol server is successfully able to take an exclusive lock.");
}
// Update contents without the ByPassLockID and coalesce true.
putChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedPutChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), SharedTestSuiteHelper.GenerateRandomFileContent(this.Site));
putChange.SubRequestData.BypassLockID = null;
putChange.SubRequestData.CoalesceSpecified = true;
putChange.SubRequestData.Coalesce = true;
response = Adapter.CellStorageRequest(randomFileUrl, new SubRequestType[] { putChange });
cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site);
this.Site.Assert.AreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site),
"When the file is locked by exclusive lock and the ByPassLockID is not specified, the server returns the error code success.");
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// PerPixelLighting.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
#endregion
namespace PerPixelLightingSample
{
/// <summary>
/// The central class for the sample Game.
/// </summary>
public class PerPixelLighting : Microsoft.Xna.Framework.Game
{
#region Sample Fields
private GraphicsDeviceManager graphics;
private SampleArcBallCamera camera;
private Vector2 safeBounds;
private Vector2 debugTextHeight;
private Model[] sampleMeshes;
private SampleGrid grid;
private int activeMesh, activeEffect, activeTechnique, activeCombination;
private int[,] effectTechniqueCombinations =
{
{0, 0}, {1, 0}, {0, 1}, {1, 1}, {1, 2}
};
private int effectTechniqueCombinationCount = 5;
private SpriteBatch spriteBatch;
private SpriteFont debugTextFont;
private GamePadState lastGpState;
private KeyboardState lastKbState;
#endregion
#region Specular Constant Fields
private const float specularPowerMinimum = 0.5f;
private const float specularPowerMaximum = 128f;
private const float specularIntensityMinimum = 0.01f;
private const float specularIntensityMaximum = 10f;
#endregion
/// <summary>
/// Example 1.1: Effect objects used for this example
/// </summary>
#region Effect Fields
private Effect[] effects;
private EffectParameter[] worldParameter = new EffectParameter[2];
private EffectParameter[] viewParameter = new EffectParameter[2];
private EffectParameter[] projectionParameter = new EffectParameter[2];
private EffectParameter[] cameraPositionParameter = new EffectParameter[2];
private EffectParameter[] specularPowerParameter = new EffectParameter[2];
private EffectParameter[] specularIntensityParameter = new EffectParameter[2];
#endregion
/// <summary>
/// Example 1.2: Data fields corresponding to the effect paramters
/// </summary>
#region Uniform Data Fields
private Matrix world;
private float specularPower, specularIntensity;
#endregion
#region Initialization and Cleanup
public PerPixelLighting()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Initialize the sample.
/// </summary>
protected override void Initialize()
{
// create a default world and matrix
world = Matrix.Identity;
// create the mesh array
sampleMeshes = new Model[5];
// Set up the reference grid
grid = new SampleGrid();
grid.GridColor = Color.LimeGreen;
grid.GridScale = 1.0f;
grid.GridSize = 32;
// Set the grid to draw on the x/z plane around the origin
grid.WorldMatrix = Matrix.Identity;
// set up the sample camera
camera = new SampleArcBallCamera(SampleArcBallCameraMode.RollConstrained);
camera.Distance = 3;
// orbit the camera so we're looking down the z=-1 axis,
// at the "front" of the object
camera.OrbitRight(MathHelper.Pi);
// orbit up a bit for perspective
camera.OrbitUp(.2f);
// set the initial effect, technique, and mesh
activeMesh = 1;
activeCombination = 0;
activeEffect = effectTechniqueCombinations[activeCombination, 0];
activeTechnique = effectTechniqueCombinations[activeCombination, 1];
// set the initial specular values
specularPower = 16;
specularIntensity = 1;
base.Initialize();
}
/// <summary>
/// Load the graphics content.
/// </summary>
protected override void LoadContent()
{
// Set up the reference grid and sample camera
grid.LoadGraphicsContent(graphics.GraphicsDevice);
// create the spritebatch for debug text
spriteBatch = new SpriteBatch(graphics.GraphicsDevice);
// load meshes
sampleMeshes[0] = Content.Load<Model>("Cube");
sampleMeshes[1] = Content.Load<Model>("SphereHighPoly");
sampleMeshes[2] = Content.Load<Model>("SphereLowPoly");
sampleMeshes[3] = Content.Load<Model>("Cylinder");
sampleMeshes[4] = Content.Load<Model>("Cone");
// load the sprite font for debug text
debugTextFont = Content.Load<SpriteFont>("DebugText");
debugTextHeight = new Vector2(0, debugTextFont.LineSpacing + 5);
// load the effects
effects = new Effect[2];
effects[0] = Content.Load<Effect>("VertexLighting");
effects[1] = Content.Load<Effect>("PerPixelLighting");
for (int i = 0; i < 2; i++)
{
// cache the effect parameters
worldParameter[i] = effects[i].Parameters["world"];
viewParameter[i] = effects[i].Parameters["view"];
projectionParameter[i] = effects[i].Parameters["projection"];
cameraPositionParameter[i] = effects[i].Parameters["cameraPosition"];
specularPowerParameter[i] = effects[i].Parameters["specularPower"];
specularIntensityParameter[i] = effects[i].Parameters["specularIntensity"];
cameraPositionParameter[i] = effects[i].Parameters["cameraPosition"];
//
// set up some basic effect parameters that do not change during the
// course of execution
//
// set the light colors
effects[i].Parameters["ambientLightColor"].SetValue(
Color.DarkSlateGray.ToVector4());
effects[i].Parameters["diffuseLightColor"].SetValue(
Color.CornflowerBlue.ToVector4());
effects[i].Parameters["specularLightColor"].SetValue(
Color.White.ToVector4());
// Set the light position to a fixed location.
// This will place the light source behind, to the right, and above the
// initial camera position.
effects[i].Parameters["lightPosition"].SetValue(
new Vector3(30f, 30f, 30f));
}
// Recalculate the projection properties on every LoadGraphicsContent call.
// That way, if the window gets resized, then the perspective matrix will be
// updated accordingly
float aspectRatio = (float)graphics.GraphicsDevice.Viewport.Width /
(float)graphics.GraphicsDevice.Viewport.Height;
float fieldOfView = aspectRatio * MathHelper.PiOver4 * 3f / 4f;
grid.ProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(
fieldOfView, aspectRatio, .1f, 1000f);
// calculate the safe left and top edges of the screen
safeBounds = new Vector2(
(float)graphics.GraphicsDevice.Viewport.X +
(float)graphics.GraphicsDevice.Viewport.Width * 0.1f,
(float)graphics.GraphicsDevice.Viewport.Y +
(float)graphics.GraphicsDevice.Viewport.Height * 0.1f
);
}
#endregion
#region Update and Render
/// <summary>
/// Update the game world.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
GamePadState gpState = GamePad.GetState(PlayerIndex.One);
KeyboardState kbState = Keyboard.GetState();
// Check for exit
if ((gpState.Buttons.Back == ButtonState.Pressed) ||
kbState.IsKeyDown(Keys.Escape))
{
Exit();
}
// Handle inputs for the sample camera
camera.HandleDefaultGamepadControls(gpState, gameTime);
camera.HandleDefaultKeyboardControls(kbState, gameTime);
// Handle inputs specific to this sample
HandleInput(gameTime, gpState, kbState);
// The built-in camera class provides the view matrix
grid.ViewMatrix = camera.ViewMatrix;
// The camera position should also be updated for the
// Phong specular component to be meaningful
cameraPositionParameter[activeEffect].SetValue(camera.Position);
// replace the "last" gamepad and keyboard states
lastGpState = gpState;
lastKbState = kbState;
base.Update(gameTime);
}
private void HandleInput(GameTime gameTime, GamePadState gpState,
KeyboardState kbState)
{
float elapsedTime = (float) gameTime.ElapsedGameTime.TotalSeconds;
//Handle input for selecting meshes
if (((gpState.Buttons.X == ButtonState.Pressed) &&
(lastGpState.Buttons.X == ButtonState.Released)) ||
(kbState.IsKeyDown(Keys.Tab) && lastKbState.IsKeyUp(Keys.Tab)))
{
//switch the active mesh
activeMesh = (activeMesh + 1) % sampleMeshes.Length;
}
//Handle input for selecting the active effect
if (((gpState.Buttons.Y == ButtonState.Pressed) &&
(lastGpState.Buttons.Y == ButtonState.Released)) ||
(kbState.IsKeyDown(Keys.Space) && lastKbState.IsKeyUp(Keys.Space)))
{
activeCombination = (activeCombination + 1) %
effectTechniqueCombinationCount;
activeEffect = effectTechniqueCombinations[activeCombination, 0];
activeTechnique = effectTechniqueCombinations[activeCombination, 1];
}
//handle mesh rotation inputs
float dx =
SampleArcBallCamera.ReadKeyboardAxis(kbState, Keys.Left, Keys.Right) +
gpState.ThumbSticks.Left.X;
float dy =
SampleArcBallCamera.ReadKeyboardAxis(kbState, Keys.Down, Keys.Up) +
gpState.ThumbSticks.Left.Y;
//apply mesh rotation to world matrix
if (dx != 0)
{
world *= Matrix.CreateFromAxisAngle(camera.Up, elapsedTime * dx);
}
if (dy != 0)
{
world *= Matrix.CreateFromAxisAngle(camera.Right, elapsedTime * -dy);
}
//handle specular power and intensity inputs
float dPower = SampleArcBallCamera.ReadKeyboardAxis(kbState,
Keys.Multiply, Keys.Divide);
if (gpState.DPad.Right == ButtonState.Pressed)
{
dPower = 1;
}
if (gpState.DPad.Left == ButtonState.Pressed)
{
dPower = -1;
}
float dIntensity = SampleArcBallCamera.ReadKeyboardAxis(kbState,
Keys.Add, Keys.Subtract);
if (gpState.DPad.Up == ButtonState.Pressed)
{
dIntensity = 1;
}
if (gpState.DPad.Down == ButtonState.Pressed)
{
dIntensity = -1;
}
if (dPower != 0)
{
specularPower *= 1 + (elapsedTime * dPower);
specularPower = MathHelper.Clamp(specularPower,
specularPowerMinimum, specularPowerMaximum);
}
if (dIntensity != 0)
{
specularIntensity *= 1 + (elapsedTime * dIntensity);
specularIntensity = MathHelper.Clamp(specularIntensity,
specularIntensityMinimum, specularIntensityMaximum);
}
}
/// <summary>
/// Example 1.4
///
/// The effect parameters set in this function
/// are shared between all of the rendered elements in the scene.
/// </summary>
private void SetSharedEffectParameters()
{
worldParameter[activeEffect].SetValue(world);
viewParameter[activeEffect].SetValue(grid.ViewMatrix);
projectionParameter[activeEffect].SetValue(grid.ProjectionMatrix);
specularPowerParameter[activeEffect].SetValue(specularPower);
specularIntensityParameter[activeEffect].SetValue(specularIntensity);
}
/// <summary>
/// Draw the current scene.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.Black);
// the SpriteBatch added below to draw the debug text is changing some
// needed render states, so they are reset here.
graphics.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
// draw the reference grid so it's easier to get our bearings
grid.Draw();
// always set the shared effects parameters
SetSharedEffectParameters();
// draw the mesh itself
DrawSampleMesh(sampleMeshes[activeMesh]);
// draw the technique name and specular settings
spriteBatch.Begin();
spriteBatch.DrawString(debugTextFont,
effects[activeEffect].CurrentTechnique.Name,
safeBounds, Color.White);
spriteBatch.DrawString(debugTextFont, "Specular Power: " +
specularPower.ToString("0.00"),
safeBounds + (1f * debugTextHeight), Color.White);
spriteBatch.DrawString(debugTextFont, "Specular Intensity: " +
specularIntensity.ToString("0.00"),
safeBounds + (2f * debugTextHeight), Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
/// <summary>
/// Example 1.6
///
/// Draws a sample mesh using a single effect with a single technique.
/// This pattern is very common in simple effect usage.
/// </summary>
/// <param name="sampleMesh"></param>
public void DrawSampleMesh(Model sampleMesh)
{
if (sampleMesh == null)
return;
// our sample meshes only contain a single part, so we don't need to bother
// looping over the ModelMesh and ModelMeshPart collections. If the meshes
// were more complex, we would repeat all the following code for each part
ModelMesh mesh = sampleMesh.Meshes[0];
ModelMeshPart meshPart = mesh.MeshParts[0];
// set the vertex source to the mesh's vertex buffer
graphics.GraphicsDevice.SetVertexBuffer(meshPart.VertexBuffer, meshPart.VertexOffset);
// set the current index buffer to the sample mesh's index buffer
graphics.GraphicsDevice.Indices = meshPart.IndexBuffer;
// determine the current effect and technique
effects[activeEffect].CurrentTechnique =
effects[activeEffect].Techniques[activeTechnique];
// now we loop through the passes in the teqnique, drawing each
// one in order
int passCount = effects[activeEffect].CurrentTechnique.Passes.Count;
for (int i = 0; i < passCount; i++)
{
// EffectPass.Apply will update the device to
// begin using the state information defined in the current pass
effects[activeEffect].CurrentTechnique.Passes[i].Apply();
// sampleMesh contains all of the information required to draw
// the current mesh
graphics.GraphicsDevice.DrawIndexedPrimitives(
PrimitiveType.TriangleList, 0, 0,
meshPart.NumVertices, meshPart.StartIndex, meshPart.PrimitiveCount);
}
}
#endregion
#region Entry Point
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
using (PerPixelLighting game = new PerPixelLighting())
{
game.Run();
}
}
#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.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Collections;
using System.Text;
namespace System.DirectoryServices.Protocols
{
public static class BerConverter
{
public static byte[] Encode(string format, params object[] value)
{
if (format == null)
throw new ArgumentNullException("format");
// no need to turn on invalid encoding detection as we just do string->byte[] conversion.
UTF8Encoding utf8Encoder = new UTF8Encoding();
byte[] encodingResult = null;
// value is allowed to be null in certain scenario, so if it is null, just set it to empty array.
if (value == null)
value = new object[0];
Debug.WriteLine("Begin encoding\n");
// allocate the berelement
BerSafeHandle berElement = new BerSafeHandle();
int valueCount = 0;
int error = 0;
for (int formatCount = 0; formatCount < format.Length; formatCount++)
{
char fmt = format[formatCount];
if (fmt == '{' || fmt == '}' || fmt == '[' || fmt == ']' || fmt == 'n')
{
// no argument needed
error = Wldap32.ber_printf_emptyarg(berElement, new string(fmt, 1));
}
else if (fmt == 't' || fmt == 'i' || fmt == 'e')
{
if (valueCount >= value.Length)
{
// we don't have enough argument for the format string
Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
}
if (!(value[valueCount] is int))
{
// argument is wrong
Debug.WriteLine("type should be int\n");
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
}
// one int argument
error = Wldap32.ber_printf_int(berElement, new string(fmt, 1), (int)value[valueCount]);
// increase the value count
valueCount++;
}
else if (fmt == 'b')
{
if (valueCount >= value.Length)
{
// we don't have enough argument for the format string
Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
}
if (!(value[valueCount] is bool))
{
// argument is wrong
Debug.WriteLine("type should be boolean\n");
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
}
// one int argument
error = Wldap32.ber_printf_int(berElement, new string(fmt, 1), (bool)value[valueCount] ? 1 : 0);
// increase the value count
valueCount++;
}
else if (fmt == 's')
{
if (valueCount >= value.Length)
{
// we don't have enough argument for the format string
Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
}
if (value[valueCount] != null && !(value[valueCount] is string))
{
// argument is wrong
Debug.WriteLine("type should be string, but receiving value has type of ");
Debug.WriteLine(value[valueCount].GetType());
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
}
// one string argument
byte[] tempValue = null;
if (value[valueCount] != null)
{
tempValue = utf8Encoder.GetBytes((string)value[valueCount]);
}
error = EncodingByteArrayHelper(berElement, tempValue, 'o');
// increase the value count
valueCount++;
}
else if (fmt == 'o' || fmt == 'X')
{
// we need to have one arguments
if (valueCount >= value.Length)
{
// we don't have enough argument for the format string
Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
}
if (value[valueCount] != null && !(value[valueCount] is byte[]))
{
// argument is wrong
Debug.WriteLine("type should be byte[], but receiving value has type of ");
Debug.WriteLine(value[valueCount].GetType());
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
}
byte[] tempValue = (byte[])value[valueCount];
error = EncodingByteArrayHelper(berElement, tempValue, fmt);
valueCount++;
}
else if (fmt == 'v')
{
// we need to have one arguments
if (valueCount >= value.Length)
{
// we don't have enough argument for the format string
Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
}
if (value[valueCount] != null && !(value[valueCount] is string[]))
{
// argument is wrong
Debug.WriteLine("type should be string[], but receiving value has type of ");
Debug.WriteLine(value[valueCount].GetType());
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
}
string[] stringValues = (string[])value[valueCount];
byte[][] tempValues = null;
if (stringValues != null)
{
tempValues = new byte[stringValues.Length][];
for (int i = 0; i < stringValues.Length; i++)
{
string s = stringValues[i];
if (s == null)
tempValues[i] = null;
else
{
tempValues[i] = utf8Encoder.GetBytes(s);
}
}
}
error = EncodingMultiByteArrayHelper(berElement, tempValues, 'V');
valueCount++;
}
else if (fmt == 'V')
{
// we need to have one arguments
if (valueCount >= value.Length)
{
// we don't have enough argument for the format string
Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
}
if (value[valueCount] != null && !(value[valueCount] is byte[][]))
{
// argument is wrong
Debug.WriteLine("type should be byte[][], but receiving value has type of ");
Debug.WriteLine(value[valueCount].GetType());
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
}
byte[][] tempValue = (byte[][])value[valueCount];
error = EncodingMultiByteArrayHelper(berElement, tempValue, fmt);
valueCount++;
}
else
{
Debug.WriteLine("Format string contains undefined character: ");
Debug.WriteLine(new string(fmt, 1));
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterUndefineChar));
}
// process the return value
if (error == -1)
{
Debug.WriteLine("ber_printf failed\n");
throw new BerConversionException();
}
}
// get the binary value back
berval binaryValue = new berval();
IntPtr flattenptr = IntPtr.Zero;
try
{
// can't use SafeBerval here as CLR creates a SafeBerval which points to a different memory location, but when doing memory
// deallocation, wldap has special check. So have to use IntPtr directly here.
error = Wldap32.ber_flatten(berElement, ref flattenptr);
if (error == -1)
{
Debug.WriteLine("ber_flatten failed\n");
throw new BerConversionException();
}
if (flattenptr != IntPtr.Zero)
{
Marshal.PtrToStructure(flattenptr, binaryValue);
}
if (binaryValue == null || binaryValue.bv_len == 0)
{
encodingResult = new byte[0];
}
else
{
encodingResult = new byte[binaryValue.bv_len];
Marshal.Copy(binaryValue.bv_val, encodingResult, 0, binaryValue.bv_len);
}
}
finally
{
if (flattenptr != IntPtr.Zero)
Wldap32.ber_bvfree(flattenptr);
}
return encodingResult;
}
public static object[] Decode(string format, byte[] value)
{
bool decodeSucceeded;
object[] decodeResult = TryDecode(format, value, out decodeSucceeded);
if (decodeSucceeded)
return decodeResult;
else
throw new BerConversionException();
}
internal static object[] TryDecode(string format, byte[] value, out bool decodeSucceeded)
{
if (format == null)
throw new ArgumentNullException("format");
Debug.WriteLine("Begin decoding\n");
UTF8Encoding utf8Encoder = new UTF8Encoding(false, true);
berval berValue = new berval();
ArrayList resultList = new ArrayList();
BerSafeHandle berElement = null;
object[] decodeResult = null;
decodeSucceeded = false;
if (value == null)
{
berValue.bv_len = 0;
berValue.bv_val = IntPtr.Zero;
}
else
{
berValue.bv_len = value.Length;
berValue.bv_val = Marshal.AllocHGlobal(value.Length);
Marshal.Copy(value, 0, berValue.bv_val, value.Length);
}
try
{
berElement = new BerSafeHandle(berValue);
}
finally
{
if (berValue.bv_val != IntPtr.Zero)
Marshal.FreeHGlobal(berValue.bv_val);
}
int error = 0;
for (int formatCount = 0; formatCount < format.Length; formatCount++)
{
char fmt = format[formatCount];
if (fmt == '{' || fmt == '}' || fmt == '[' || fmt == ']' || fmt == 'n' || fmt == 'x')
{
error = Wldap32.ber_scanf(berElement, new string(fmt, 1));
if (error != 0)
Debug.WriteLine("ber_scanf for {, }, [, ], n or x failed");
}
else if (fmt == 'i' || fmt == 'e' || fmt == 'b')
{
int result = 0;
error = Wldap32.ber_scanf_int(berElement, new string(fmt, 1), ref result);
if (error == 0)
{
if (fmt == 'b')
{
// should return a bool
bool boolResult = false;
if (result == 0)
boolResult = false;
else
boolResult = true;
resultList.Add(boolResult);
}
else
{
resultList.Add(result);
}
}
else
Debug.WriteLine("ber_scanf for format character 'i', 'e' or 'b' failed");
}
else if (fmt == 'a')
{
// return a string
byte[] byteArray = DecodingByteArrayHelper(berElement, 'O', ref error);
if (error == 0)
{
string s = null;
if (byteArray != null)
s = utf8Encoder.GetString(byteArray);
resultList.Add(s);
}
}
else if (fmt == 'O')
{
// return berval
byte[] byteArray = DecodingByteArrayHelper(berElement, fmt, ref error);
if (error == 0)
{
// add result to the list
resultList.Add(byteArray);
}
}
else if (fmt == 'B')
{
// return a bitstring and its length
IntPtr ptrResult = IntPtr.Zero;
int length = 0;
error = Wldap32.ber_scanf_bitstring(berElement, "B", ref ptrResult, ref length);
if (error == 0)
{
byte[] byteArray = null;
if (ptrResult != IntPtr.Zero)
{
byteArray = new byte[length];
Marshal.Copy(ptrResult, byteArray, 0, length);
}
resultList.Add(byteArray);
}
else
Debug.WriteLine("ber_scanf for format character 'B' failed");
// no need to free memory as wldap32 returns the original pointer instead of a duplicating memory pointer that
// needs to be freed
}
else if (fmt == 'v')
{
//null terminate strings
byte[][] byteArrayresult = null;
string[] stringArray = null;
byteArrayresult = DecodingMultiByteArrayHelper(berElement, 'V', ref error);
if (error == 0)
{
if (byteArrayresult != null)
{
stringArray = new string[byteArrayresult.Length];
for (int i = 0; i < byteArrayresult.Length; i++)
{
if (byteArrayresult[i] == null)
{
stringArray[i] = null;
}
else
{
stringArray[i] = utf8Encoder.GetString(byteArrayresult[i]);
}
}
}
resultList.Add(stringArray);
}
}
else if (fmt == 'V')
{
byte[][] result = null;
result = DecodingMultiByteArrayHelper(berElement, fmt, ref error);
if (error == 0)
{
resultList.Add(result);
}
}
else
{
Debug.WriteLine("Format string contains undefined character\n");
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterUndefineChar));
}
if (error != 0)
{
// decode failed, just return
return decodeResult;
}
}
decodeResult = new object[resultList.Count];
for (int count = 0; count < resultList.Count; count++)
{
decodeResult[count] = resultList[count];
}
decodeSucceeded = true;
return decodeResult;
}
private static int EncodingByteArrayHelper(BerSafeHandle berElement, byte[] tempValue, char fmt)
{
int error = 0;
// one byte array, one int arguments
if (tempValue != null)
{
IntPtr tmp = Marshal.AllocHGlobal(tempValue.Length);
Marshal.Copy(tempValue, 0, tmp, tempValue.Length);
HGlobalMemHandle memHandle = new HGlobalMemHandle(tmp);
error = Wldap32.ber_printf_bytearray(berElement, new string(fmt, 1), memHandle, tempValue.Length);
}
else
{
error = Wldap32.ber_printf_bytearray(berElement, new string(fmt, 1), new HGlobalMemHandle(IntPtr.Zero), 0);
}
return error;
}
private static byte[] DecodingByteArrayHelper(BerSafeHandle berElement, char fmt, ref int error)
{
error = 0;
IntPtr result = IntPtr.Zero;
berval binaryValue = new berval();
byte[] byteArray = null;
// can't use SafeBerval here as CLR creates a SafeBerval which points to a different memory location, but when doing memory
// deallocation, wldap has special check. So have to use IntPtr directly here.
error = Wldap32.ber_scanf_ptr(berElement, new string(fmt, 1), ref result);
try
{
if (error == 0)
{
if (result != IntPtr.Zero)
{
Marshal.PtrToStructure(result, binaryValue);
byteArray = new byte[binaryValue.bv_len];
Marshal.Copy(binaryValue.bv_val, byteArray, 0, binaryValue.bv_len);
}
}
else
Debug.WriteLine("ber_scanf for format character 'O' failed");
}
finally
{
if (result != IntPtr.Zero)
Wldap32.ber_bvfree(result);
}
return byteArray;
}
private static int EncodingMultiByteArrayHelper(BerSafeHandle berElement, byte[][] tempValue, char fmt)
{
IntPtr berValArray = IntPtr.Zero;
IntPtr tempPtr = IntPtr.Zero;
SafeBerval[] managedBerVal = null;
int error = 0;
try
{
if (tempValue != null)
{
int i = 0;
berValArray = Utility.AllocHGlobalIntPtrArray(tempValue.Length + 1);
int structSize = Marshal.SizeOf(typeof(SafeBerval));
managedBerVal = new SafeBerval[tempValue.Length];
for (i = 0; i < tempValue.Length; i++)
{
byte[] byteArray = tempValue[i];
// construct the managed berval
managedBerVal[i] = new SafeBerval();
if (byteArray == null)
{
managedBerVal[i].bv_len = 0;
managedBerVal[i].bv_val = IntPtr.Zero;
}
else
{
managedBerVal[i].bv_len = byteArray.Length;
managedBerVal[i].bv_val = Marshal.AllocHGlobal(byteArray.Length);
Marshal.Copy(byteArray, 0, managedBerVal[i].bv_val, byteArray.Length);
}
// allocate memory for the unmanaged structure
IntPtr valPtr = Marshal.AllocHGlobal(structSize);
Marshal.StructureToPtr(managedBerVal[i], valPtr, false);
tempPtr = (IntPtr)((long)berValArray + IntPtr.Size * i);
Marshal.WriteIntPtr(tempPtr, valPtr);
}
tempPtr = (IntPtr)((long)berValArray + IntPtr.Size * i);
Marshal.WriteIntPtr(tempPtr, IntPtr.Zero);
}
error = Wldap32.ber_printf_berarray(berElement, new string(fmt, 1), berValArray);
GC.KeepAlive(managedBerVal);
}
finally
{
if (berValArray != IntPtr.Zero)
{
for (int i = 0; i < tempValue.Length; i++)
{
IntPtr ptr = Marshal.ReadIntPtr(berValArray, IntPtr.Size * i);
if (ptr != IntPtr.Zero)
Marshal.FreeHGlobal(ptr);
}
Marshal.FreeHGlobal(berValArray);
}
}
return error;
}
private static byte[][] DecodingMultiByteArrayHelper(BerSafeHandle berElement, char fmt, ref int error)
{
error = 0;
// several berval
IntPtr ptrResult = IntPtr.Zero;
int i = 0;
ArrayList binaryList = new ArrayList();
IntPtr tempPtr = IntPtr.Zero;
byte[][] result = null;
try
{
error = Wldap32.ber_scanf_ptr(berElement, new string(fmt, 1), ref ptrResult);
if (error == 0)
{
if (ptrResult != IntPtr.Zero)
{
tempPtr = Marshal.ReadIntPtr(ptrResult);
while (tempPtr != IntPtr.Zero)
{
berval ber = new berval();
Marshal.PtrToStructure(tempPtr, ber);
byte[] berArray = new byte[ber.bv_len];
Marshal.Copy(ber.bv_val, berArray, 0, ber.bv_len);
binaryList.Add(berArray);
i++;
tempPtr = Marshal.ReadIntPtr(ptrResult, i * IntPtr.Size);
}
result = new byte[binaryList.Count][];
for (int j = 0; j < binaryList.Count; j++)
{
result[j] = (byte[])binaryList[j];
}
}
}
else
Debug.WriteLine("ber_scanf for format character 'V' failed");
}
finally
{
if (ptrResult != IntPtr.Zero)
{
Wldap32.ber_bvecfree(ptrResult);
}
}
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
#if !NET_40
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
#endif
namespace Kirkin.Linq
{
/// <summary>
/// Extension methods for types which implement the IEnumerable{T} interface.
/// </summary>
public static class EnumerableExtensions
{
/// <summary>
/// Produces a new sequence by iterating through all items in the
/// current collection and appending the given item at the end.
/// </summary>
/// <remarks>
/// Initially called "Add" but renamed to avoid confusion with
/// the mutable equivalent defined on many collection types.
/// </remarks>
internal static IEnumerable<T> Append<T>(this IEnumerable<T> collection, T item)
{
foreach (T element in collection) {
yield return element;
}
yield return item;
}
/// <summary>
/// Applies the given action to each element in the collection.
/// </summary>
public static IEnumerable<T> Do<T>(this IEnumerable<T> collection, Action<T> action)
{
foreach (T item in collection)
{
action(item);
yield return item;
}
}
/// <summary>
/// Returns the index of the given element inside
/// the collection or -1 if it cannot be found.
/// </summary>
public static int IndexOf<T>(this IEnumerable<T> collection, T itemToSeek)
{
// Optimisation.
IList<T> list = collection as IList<T>;
if (list != null) {
return list.IndexOf(itemToSeek);
}
// Seek.
int index = 0;
foreach (T item in collection)
{
if (Equals(item, itemToSeek)) {
return index;
}
index++;
}
return -1;
}
/// <summary>
/// Breaks up the given sequence into smaller
/// materialized sequences of the given size.
/// </summary>
public static IEnumerable<T[]> Chunkify<T>(this IEnumerable<T> collection, int chunkSize)
{
if (collection == null) throw new ArgumentNullException("collection");
if (chunkSize < 1) throw new ArgumentException("chunkSize");
T[] chunk = null;
int count = 0;
foreach (T obj in collection)
{
if (count == 0) {
chunk = new T[chunkSize];
}
chunk[count++] = obj;
if (count == chunkSize)
{
yield return chunk;
count = 0;
}
}
if (count != 0)
{
if (chunk.Length == count) {
yield return chunk;
}
// Resize required.
T[] tmp = new T[count];
Array.Copy(chunk, 0, tmp, 0, count);
yield return tmp;
}
}
/// <summary>
/// Returns the first item whose key is the smallest according to the default comparer.
/// Similar to collection.OrderBy(keySelector).FirstOrDefault() without the extra collection allocation and sorting,
/// or collection.FirstOrDefault(i => keySelector(i) == collection.Min(keySelector)).
/// </summary>
public static TElement FirstOrDefaultWithMin<TElement, TKey>(this IEnumerable<TElement> collection, Func<TElement, TKey> keySelector)
{
return FirstOrDefaultWithMin(collection, keySelector, Comparer<TKey>.Default);
}
/// <summary>
/// Returns the first item whose key is the smallest according to the specified comparer.
/// Similar to collection.OrderBy(keySelector, comparer).FirstOrDefault() without the extra collection allocation and sorting.
/// </summary>
public static TElement FirstOrDefaultWithMin<TElement, TKey>(this IEnumerable<TElement> collection, Func<TElement, TKey> keySelector, IComparer<TKey> comparer)
{
Value<TElement, TKey> current = new Value<TElement, TKey>();
foreach (TElement element in collection)
{
TKey key = keySelector(element);
if (!current.IsSet || comparer.Compare(key, current.Key) < 0) {
current = new Value<TElement, TKey>(element, key);
}
}
return current.Element;
}
/// <summary>
/// Returns the last item whose key is the largest according to the default comparer.
/// Similar to collection.OrderBy(keySelector).LastOrDefault() without the extra collection allocation and sorting,
/// or collection.LastOrDefault(i => keySelector(i) == collection.Max(keySelector)).
/// </summary>
public static TElement LastOrDefaultWithMax<TElement, TKey>(this IEnumerable<TElement> collection, Func<TElement, TKey> keySelector)
{
return LastOrDefaultWithMax(collection, keySelector, Comparer<TKey>.Default);
}
/// <summary>
/// Returns the last item whose key is the largest according to the specified comparer.
/// Similar to collection.OrderBy(keySelector, comparer).LastOrDefault() without the extra collection allocation and sorting.
/// </summary>
public static TElement LastOrDefaultWithMax<TElement, TKey>(this IEnumerable<TElement> collection, Func<TElement, TKey> keySelector, IComparer<TKey> comparer)
{
Value<TElement, TKey> current = new Value<TElement, TKey>();
foreach (TElement element in collection)
{
TKey key = keySelector(element);
if (!current.IsSet || comparer.Compare(key, current.Key) >= 0) {
current = new Value<TElement, TKey>(element, key);
}
}
return current.Element;
}
private struct Value<TElement, TKey>
{
internal bool IsSet;
internal TElement Element;
internal TKey Key;
internal Value(TElement element, TKey key)
{
IsSet = true;
Element = element;
Key = key;
}
}
#if !NET_40
/// <summary>
/// Returns an enumerable which eagerly iterates through the given collection on
/// the thread pool and stores resulting elements in a buffer before yielding them.
/// </summary>
/// <remarks>
/// As it stands, the buffering only starts at the first MoveNext call.
/// Moving forward, this behaviour is subject to change.
/// </remarks>
public static IEnumerable<TElement> LookAhead<TElement>(this IEnumerable<TElement> collection, int bufferSize = 1)
{
if (collection == null) throw new ArgumentNullException("collection");
if (bufferSize < 1) throw new ArgumentOutOfRangeException("bufferSize", "Minimum allowed buffer size is 1.");
using (BlockingCollection<TElement> buffer = new BlockingCollection<TElement>(bufferSize))
using (SemaphoreSlim semaphore = new SemaphoreSlim(bufferSize, bufferSize))
{
// Greedy item grab.
Task producer = Task.Run(async () =>
{
try
{
foreach (TElement item in collection)
{
await semaphore.WaitAsync().ConfigureAwait(false);
lock (buffer)
{
// IsAddingCompleted check required to prevent Add throwing
// because the main thread has already called CompleteAdding.
if (buffer.IsAddingCompleted) return;
buffer.Add(item);
}
}
}
finally
{
// No lock required as all additions are finished by now.
// Multiple/concurrent calls to CompleteAdding are fine.
buffer.CompleteAdding();
}
});
try
{
foreach (TElement item in buffer.GetConsumingEnumerable())
{
yield return item;
// Wake the producer. This will not be called if the consumer short-circuits.
// In that event Release will be called after CompleteAdding inside the finally block.
semaphore.Release();
}
}
finally
{
// Must be in "finally" as otherwise it
// won't be called if we break out early.
lock (buffer) {
buffer.CompleteAdding();
}
if (semaphore.CurrentCount < bufferSize)
{
// Only required if we broke out early. Wakes the producer only for it
// to immediately hit the buffer.IsAddingCompleted check and break out.
semaphore.Release();
}
// Block until completion and observe exceptions.
producer.GetAwaiter().GetResult();
}
}
}
#endif
/// <summary>
/// Produces a new sequence by first yielding the given item and
/// then iterating through all items in the current collection.
/// </summary>
internal static IEnumerable<T> Prepend<T>(this IEnumerable<T> collection, T item)
{
yield return item;
foreach (T element in collection) {
yield return element;
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.Dialogflow.V2
{
/// <summary>Settings for <see cref="FulfillmentsClient"/> instances.</summary>
public sealed partial class FulfillmentsSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="FulfillmentsSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="FulfillmentsSettings"/>.</returns>
public static FulfillmentsSettings GetDefault() => new FulfillmentsSettings();
/// <summary>Constructs a new <see cref="FulfillmentsSettings"/> object with default settings.</summary>
public FulfillmentsSettings()
{
}
private FulfillmentsSettings(FulfillmentsSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetFulfillmentSettings = existing.GetFulfillmentSettings;
UpdateFulfillmentSettings = existing.UpdateFulfillmentSettings;
OnCopy(existing);
}
partial void OnCopy(FulfillmentsSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>FulfillmentsClient.GetFulfillment</c> and <c>FulfillmentsClient.GetFulfillmentAsync</c>.
/// </summary>
/// <remarks>
/// <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>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>.</description>
/// </item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetFulfillmentSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>FulfillmentsClient.UpdateFulfillment</c> and <c>FulfillmentsClient.UpdateFulfillmentAsync</c>.
/// </summary>
/// <remarks>
/// <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>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>.</description>
/// </item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings UpdateFulfillmentSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="FulfillmentsSettings"/> object.</returns>
public FulfillmentsSettings Clone() => new FulfillmentsSettings(this);
}
/// <summary>
/// Builder class for <see cref="FulfillmentsClient"/> to provide simple configuration of credentials, endpoint etc.
/// </summary>
public sealed partial class FulfillmentsClientBuilder : gaxgrpc::ClientBuilderBase<FulfillmentsClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public FulfillmentsSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public FulfillmentsClientBuilder()
{
UseJwtAccessWithScopes = FulfillmentsClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref FulfillmentsClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<FulfillmentsClient> task);
/// <summary>Builds the resulting client.</summary>
public override FulfillmentsClient Build()
{
FulfillmentsClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<FulfillmentsClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<FulfillmentsClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private FulfillmentsClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return FulfillmentsClient.Create(callInvoker, Settings);
}
private async stt::Task<FulfillmentsClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return FulfillmentsClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => FulfillmentsClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => FulfillmentsClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => FulfillmentsClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>Fulfillments client wrapper, for convenient use.</summary>
/// <remarks>
/// Service for managing [Fulfillments][google.cloud.dialogflow.v2.Fulfillment].
/// </remarks>
public abstract partial class FulfillmentsClient
{
/// <summary>
/// The default endpoint for the Fulfillments service, which is a host of "dialogflow.googleapis.com" and a port
/// of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "dialogflow.googleapis.com:443";
/// <summary>The default Fulfillments scopes.</summary>
/// <remarks>
/// The default Fulfillments scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// <item><description>https://www.googleapis.com/auth/dialogflow</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/dialogflow",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="FulfillmentsClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="FulfillmentsClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="FulfillmentsClient"/>.</returns>
public static stt::Task<FulfillmentsClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new FulfillmentsClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="FulfillmentsClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="FulfillmentsClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="FulfillmentsClient"/>.</returns>
public static FulfillmentsClient Create() => new FulfillmentsClientBuilder().Build();
/// <summary>
/// Creates a <see cref="FulfillmentsClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="FulfillmentsSettings"/>.</param>
/// <returns>The created <see cref="FulfillmentsClient"/>.</returns>
internal static FulfillmentsClient Create(grpccore::CallInvoker callInvoker, FulfillmentsSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
Fulfillments.FulfillmentsClient grpcClient = new Fulfillments.FulfillmentsClient(callInvoker);
return new FulfillmentsClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> 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 stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC Fulfillments client</summary>
public virtual Fulfillments.FulfillmentsClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Retrieves the fulfillment.
/// </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 Fulfillment GetFulfillment(GetFulfillmentRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Retrieves the fulfillment.
/// </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 stt::Task<Fulfillment> GetFulfillmentAsync(GetFulfillmentRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Retrieves the fulfillment.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Fulfillment> GetFulfillmentAsync(GetFulfillmentRequest request, st::CancellationToken cancellationToken) =>
GetFulfillmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Retrieves the fulfillment.
/// </summary>
/// <param name="name">
/// Required. The name of the fulfillment.
/// Format: `projects/{Project ID}/agent/fulfillment`.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Fulfillment GetFulfillment(string name, gaxgrpc::CallSettings callSettings = null) =>
GetFulfillment(new GetFulfillmentRequest
{
Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)),
}, callSettings);
/// <summary>
/// Retrieves the fulfillment.
/// </summary>
/// <param name="name">
/// Required. The name of the fulfillment.
/// Format: `projects/{Project ID}/agent/fulfillment`.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Fulfillment> GetFulfillmentAsync(string name, gaxgrpc::CallSettings callSettings = null) =>
GetFulfillmentAsync(new GetFulfillmentRequest
{
Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)),
}, callSettings);
/// <summary>
/// Retrieves the fulfillment.
/// </summary>
/// <param name="name">
/// Required. The name of the fulfillment.
/// Format: `projects/{Project ID}/agent/fulfillment`.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Fulfillment> GetFulfillmentAsync(string name, st::CancellationToken cancellationToken) =>
GetFulfillmentAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Retrieves the fulfillment.
/// </summary>
/// <param name="name">
/// Required. The name of the fulfillment.
/// Format: `projects/{Project ID}/agent/fulfillment`.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Fulfillment GetFulfillment(FulfillmentName name, gaxgrpc::CallSettings callSettings = null) =>
GetFulfillment(new GetFulfillmentRequest
{
FulfillmentName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)),
}, callSettings);
/// <summary>
/// Retrieves the fulfillment.
/// </summary>
/// <param name="name">
/// Required. The name of the fulfillment.
/// Format: `projects/{Project ID}/agent/fulfillment`.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Fulfillment> GetFulfillmentAsync(FulfillmentName name, gaxgrpc::CallSettings callSettings = null) =>
GetFulfillmentAsync(new GetFulfillmentRequest
{
FulfillmentName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)),
}, callSettings);
/// <summary>
/// Retrieves the fulfillment.
/// </summary>
/// <param name="name">
/// Required. The name of the fulfillment.
/// Format: `projects/{Project ID}/agent/fulfillment`.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Fulfillment> GetFulfillmentAsync(FulfillmentName name, st::CancellationToken cancellationToken) =>
GetFulfillmentAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Updates the fulfillment.
/// </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 Fulfillment UpdateFulfillment(UpdateFulfillmentRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates the fulfillment.
/// </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 stt::Task<Fulfillment> UpdateFulfillmentAsync(UpdateFulfillmentRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates the fulfillment.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Fulfillment> UpdateFulfillmentAsync(UpdateFulfillmentRequest request, st::CancellationToken cancellationToken) =>
UpdateFulfillmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Updates the fulfillment.
/// </summary>
/// <param name="fulfillment">
/// Required. The fulfillment to update.
/// </param>
/// <param name="updateMask">
/// Required. The mask to control which fields get updated. If the mask is not
/// present, all fields will be updated.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Fulfillment UpdateFulfillment(Fulfillment fulfillment, wkt::FieldMask updateMask, gaxgrpc::CallSettings callSettings = null) =>
UpdateFulfillment(new UpdateFulfillmentRequest
{
Fulfillment = gax::GaxPreconditions.CheckNotNull(fulfillment, nameof(fulfillment)),
UpdateMask = gax::GaxPreconditions.CheckNotNull(updateMask, nameof(updateMask)),
}, callSettings);
/// <summary>
/// Updates the fulfillment.
/// </summary>
/// <param name="fulfillment">
/// Required. The fulfillment to update.
/// </param>
/// <param name="updateMask">
/// Required. The mask to control which fields get updated. If the mask is not
/// present, all fields will be updated.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Fulfillment> UpdateFulfillmentAsync(Fulfillment fulfillment, wkt::FieldMask updateMask, gaxgrpc::CallSettings callSettings = null) =>
UpdateFulfillmentAsync(new UpdateFulfillmentRequest
{
Fulfillment = gax::GaxPreconditions.CheckNotNull(fulfillment, nameof(fulfillment)),
UpdateMask = gax::GaxPreconditions.CheckNotNull(updateMask, nameof(updateMask)),
}, callSettings);
/// <summary>
/// Updates the fulfillment.
/// </summary>
/// <param name="fulfillment">
/// Required. The fulfillment to update.
/// </param>
/// <param name="updateMask">
/// Required. The mask to control which fields get updated. If the mask is not
/// present, all fields will be updated.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Fulfillment> UpdateFulfillmentAsync(Fulfillment fulfillment, wkt::FieldMask updateMask, st::CancellationToken cancellationToken) =>
UpdateFulfillmentAsync(fulfillment, updateMask, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>Fulfillments client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service for managing [Fulfillments][google.cloud.dialogflow.v2.Fulfillment].
/// </remarks>
public sealed partial class FulfillmentsClientImpl : FulfillmentsClient
{
private readonly gaxgrpc::ApiCall<GetFulfillmentRequest, Fulfillment> _callGetFulfillment;
private readonly gaxgrpc::ApiCall<UpdateFulfillmentRequest, Fulfillment> _callUpdateFulfillment;
/// <summary>
/// Constructs a client wrapper for the Fulfillments service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="FulfillmentsSettings"/> used within this client.</param>
public FulfillmentsClientImpl(Fulfillments.FulfillmentsClient grpcClient, FulfillmentsSettings settings)
{
GrpcClient = grpcClient;
FulfillmentsSettings effectiveSettings = settings ?? FulfillmentsSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetFulfillment = clientHelper.BuildApiCall<GetFulfillmentRequest, Fulfillment>(grpcClient.GetFulfillmentAsync, grpcClient.GetFulfillment, effectiveSettings.GetFulfillmentSettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callGetFulfillment);
Modify_GetFulfillmentApiCall(ref _callGetFulfillment);
_callUpdateFulfillment = clientHelper.BuildApiCall<UpdateFulfillmentRequest, Fulfillment>(grpcClient.UpdateFulfillmentAsync, grpcClient.UpdateFulfillment, effectiveSettings.UpdateFulfillmentSettings).WithGoogleRequestParam("fulfillment.name", request => request.Fulfillment?.Name);
Modify_ApiCall(ref _callUpdateFulfillment);
Modify_UpdateFulfillmentApiCall(ref _callUpdateFulfillment);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetFulfillmentApiCall(ref gaxgrpc::ApiCall<GetFulfillmentRequest, Fulfillment> call);
partial void Modify_UpdateFulfillmentApiCall(ref gaxgrpc::ApiCall<UpdateFulfillmentRequest, Fulfillment> call);
partial void OnConstruction(Fulfillments.FulfillmentsClient grpcClient, FulfillmentsSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC Fulfillments client</summary>
public override Fulfillments.FulfillmentsClient GrpcClient { get; }
partial void Modify_GetFulfillmentRequest(ref GetFulfillmentRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_UpdateFulfillmentRequest(ref UpdateFulfillmentRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Retrieves the fulfillment.
/// </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 Fulfillment GetFulfillment(GetFulfillmentRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetFulfillmentRequest(ref request, ref callSettings);
return _callGetFulfillment.Sync(request, callSettings);
}
/// <summary>
/// Retrieves the fulfillment.
/// </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 stt::Task<Fulfillment> GetFulfillmentAsync(GetFulfillmentRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetFulfillmentRequest(ref request, ref callSettings);
return _callGetFulfillment.Async(request, callSettings);
}
/// <summary>
/// Updates the fulfillment.
/// </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 Fulfillment UpdateFulfillment(UpdateFulfillmentRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateFulfillmentRequest(ref request, ref callSettings);
return _callUpdateFulfillment.Sync(request, callSettings);
}
/// <summary>
/// Updates the fulfillment.
/// </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 stt::Task<Fulfillment> UpdateFulfillmentAsync(UpdateFulfillmentRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateFulfillmentRequest(ref request, ref callSettings);
return _callUpdateFulfillment.Async(request, callSettings);
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Gdal
// Description: This is a data extension for the System.Spatial framework.
// ********************************************************************************************************
// The contents of this file are subject to the Gnu Lesser General Public License (LGPL)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from a plugin for MapWindow version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 7/1/2009 11:39:44 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// | Name | Date | Comments
// |-------------------|-------------|-------------------------------------------------------------------
// |Ben tidyup Tombs |18/11/2010 | Modified to add GDAL Helper class use for initialization of the GDAL Environment
// ********************************************************************************************************
using System;
using System.Diagnostics;
using System.IO;
using OSGeo.GDAL;
namespace DotSpatial.Data.Rasters.GdalExtension
{
/// <summary>
/// GdalRasterProvider
/// </summary>
public class GdalRasterProvider : IRasterProvider
{
#region Private Variables
#endregion Private Variables
#region Constructors
static GdalRasterProvider()
{
GdalConfiguration.ConfigureGdal();
}
/// <summary>
/// Creates a new instance of GdalRasterProvider
/// </summary>
public GdalRasterProvider()
{
// Add ourself in for these extensions, unless another provider is registered for them.
string[] extensions = { ".tif", ".tiff", ".adf" };
foreach (string extension in extensions)
{
if (!DataManager.DefaultDataManager.PreferredProviders.ContainsKey(extension))
{
DataManager.DefaultDataManager.PreferredProviders.Add(extension, this);
}
}
}
#endregion Constructors
private static string GetDriverCode(string fileExtension)
{
if (String.IsNullOrEmpty(fileExtension))
{
return null;
}
switch (fileExtension.ToLower())
{
case ".asc":
return "AAIGrid";
case ".adf":
return "AAIGrid";
case ".tiff":
case ".tif":
return "GTiff";
case ".img":
return "HFA";
case ".gff":
return "GFF";
case ".dt0":
case ".dt1":
case ".dt2":
return "DTED";
case ".ter":
return "Terragen";
case ".nc":
return "netCDF";
default:
return null;
}
}
#region IRasterProvider Members
/// <summary>
/// This create new method implies that this provider has the priority for creating a new file.
/// An instance of the dataset should be created and then returned. By this time, the fileName
/// will already be checked to see if it exists, and deleted if the user wants to overwrite it.
/// </summary>
/// <param name="name">The string fileName for the new instance.</param>
/// <param name="driverCode">The string short name of the driver for creating the raster.</param>
/// <param name="xSize">The number of columns in the raster.</param>
/// <param name="ySize">The number of rows in the raster.</param>
/// <param name="numBands">The number of bands to create in the raster.</param>
/// <param name="dataType">The data type to use for the raster.</param>
/// <param name="options">The options to be used.</param>
/// <returns>An IRaster</returns>
public IRaster Create(string name, string driverCode, int xSize, int ySize, int numBands, Type dataType, string[] options)
{
if (File.Exists(name)) File.Delete(name);
if (String.IsNullOrEmpty(driverCode))
{
driverCode = GetDriverCode(Path.GetExtension(name));
}
Driver d = Gdal.GetDriverByName(driverCode);
if (d == null)
{
// We didn't find a matching driver.
return null;
}
// Assign the Gdal dataType.
DataType dt;
if (dataType == typeof(int)) dt = DataType.GDT_Int32;
else if (dataType == typeof(short)) dt = DataType.GDT_Int16;
else if (dataType == typeof(UInt32)) dt = DataType.GDT_UInt32;
else if (dataType == typeof(UInt16)) dt = DataType.GDT_UInt16;
else if (dataType == typeof(double)) dt = DataType.GDT_Float64;
else if (dataType == typeof(float)) dt = DataType.GDT_Float32;
else if (dataType == typeof(byte)) dt = DataType.GDT_Byte;
else dt = DataType.GDT_Unknown;
// Width, Height, and bands must "be positive"
if (numBands == 0) numBands = 1;
Dataset dataset = d.Create(name, xSize, ySize, numBands, dt, options);
return WrapDataSetInRaster(name, dataType, dataset);
}
private static IRaster WrapDataSetInRaster(string name, Type dataType, Dataset dataset)
{
// todo: what about UInt32?
if (dataType == typeof(int) || dataType == typeof(UInt16))
{
return new GdalRaster<int>(name, dataset);
}
if (dataType == typeof(short))
{
return new GdalRaster<short>(name, dataset);
}
if (dataType == typeof(float))
{
return new GdalRaster<float>(name, dataset);
}
if (dataType == typeof(double))
{
return new GdalRaster<double>(name, dataset);
}
if (dataType == typeof(byte))
{
return new GdalRaster<byte>(name, dataset);
}
// It was an unsupported type.
if (dataset != null)
{
dataset.Dispose();
if (File.Exists(name)) File.Delete(name);
}
return null;
}
/// <summary>
/// Opens the specified file
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
[DebuggerStepThrough]
public IRaster Open(string fileName)
{
IRaster result = null;
var dataset = Helpers.Open(fileName);
if (dataset != null)
{
// Single band rasters are easy, just return the band as the raster.
// TODO: make a more complicated raster structure with individual bands.
result = GetBand(fileName, dataset, dataset.GetRasterBand(1));
//If we opened the dataset but did not find a raster to return, close the dataset
if (result == null)
{
dataset.Dispose();
}
}
return result;
}
//This function checks if a GeoTiff dataset should be interpreted as a one-band raster
//or as an image. Returns true if the dataset is a valid one-band raster.
/// <summary>
/// Description of the raster
/// </summary>
public string Description
{
get { return "GDAL Integer Raster"; }
}
/// <summary>
/// The dialog filter to use when opening a file
/// </summary>
public string DialogReadFilter
{
get { return "GDAL Rasters|*.asc;*.adf;*.bil;*.gen;*.thf;*.blx;*.xlb;*.bt;*.dt0;*.dt1;*.dt2;*.tif;*.dem;*.ter;*.mem;*.img;*.nc"; }
}
/// <summary>
/// The dialog filter to use when saving to a file
/// </summary>
public string DialogWriteFilter
{
get { return "AAIGrid|*.asc;*.adf|DTED|*.dt0;*.dt1;*.dt2|GTiff|*.tif;*.tiff|TERRAGEN|*.ter|GenBin|*.bil|netCDF|*.nc|Imagine|*.img|GFF|*.gff|Terragen|*.ter"; }
}
/// <summary>
/// Updated with progress information
/// </summary>
public IProgressHandler ProgressHandler { get; set; }
/// <summary>
/// The name of the provider
/// </summary>
public string Name
{
get { return "GDAL Raster Provider"; }
}
IDataSet IDataProvider.Open(string fileName)
{
return Open(fileName);
}
#endregion
private static IRaster GetBand(string fileName, Dataset dataset, Band band)
{
Raster result = null;
switch (band.DataType)
{
case DataType.GDT_Byte:
result = new GdalRaster<byte>(fileName, dataset, band);
break;
case DataType.GDT_CFloat32:
case DataType.GDT_CFloat64:
case DataType.GDT_CInt16:
case DataType.GDT_CInt32:
break;
case DataType.GDT_Float32:
result = new GdalRaster<float>(fileName, dataset, band);
break;
case DataType.GDT_Float64:
result = new GdalRaster<double>(fileName, dataset, band);
break;
case DataType.GDT_Int16:
result = new GdalRaster<short>(fileName, dataset, band);
break;
case DataType.GDT_UInt16:
case DataType.GDT_Int32:
result = new GdalRaster<int>(fileName, dataset, band);
break;
case DataType.GDT_TypeCount:
break;
case DataType.GDT_UInt32:
result = new GdalRaster<long>(fileName, dataset, band);
break;
case DataType.GDT_Unknown:
break;
default:
break;
}
if (result != null)
{
result.Open();
}
return result;
}
}
}
| |
using System;
namespace GUID_WinForm_V3
{
public class Ifc_Guid
{
#region Static Fields (IFC-REVIT)
/// <summary>
/// The replacement table
/// </summary>
private static readonly char[] Base64Chars =
{
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C',
'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c',
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '_', '$'
};
#endregion
#region Internal functions (IFC-REVIT)
/// <summary>
/// The reverse function to calculate the number from the characters
/// </summary>
/// <param name="str">
/// The char array to convert from
/// </param>
/// <param name="start">
/// Position in array to start read
/// </param>
/// <param name="len">
/// The length to read
/// </param>
/// <returns>
/// The calculated nuber
/// </returns>
private static uint CvFrom64(char[] str, int start, int len)
{
int i;
uint res = 0;
//Debug.Assert(len <= 4, "Length must be equal or less than 4");
if (len > 4) throw new Exception("Length must be equal or less than 4");
for (i = 0; i < len; i++)
{
int index = -1;
int j;
for (j = 0; j < 64; j++)
{
if (Base64Chars[j] == str[start + i])
{
index = j;
break;
}
}
//Debug.Assert(index >= 0, "Index is less than 0");
if (len < 0) throw new Exception("Index is less than 0");
res = (res * 64) + ((uint)index);
}
return res;
}
/// <summary>
/// Conversion of an integer into a characters with base 64
/// using the table Base64Chars
/// </summary>
/// <param name="number">
/// The number to convert
/// </param>
/// <param name="result">
/// The result char array to write to
/// </param>
/// <param name="start">
/// The position in the char array to start writing
/// </param>
/// <param name="len">
/// The length to write
/// </param>
private static void CvTo64(uint number, ref char[] result, int start, int len)
{
int digit;
//Debug.Assert(len <= 4, "Length must be equal or less than 4");
if (len > 4) throw new Exception("Length must be equal or less than 4");
uint act = number;
int digits = len;
for (digit = 0; digit < digits; digit++)
{
result[start + len - digit - 1] = Base64Chars[(int)(act % 64)];
act /= 64;
}
//Debug.Assert(act == 0, "Logic failed, act was not null: " + act);
if (act != 0) throw new Exception("Logic failed, act was not null: " + act);
}
/// <summary>
/// Reconstruction of the GUID from an IFC GUID string (base64)
/// </summary>
/// <param name="guid">
/// The GUID string to convert. Must be 22 characters long
/// </param>
/// <returns>
/// GUID correspondig to the string
/// </returns>
private static Guid FromIfcGuid(string guid)
{
//Debug.Assert(guid.Length == 22, "Input string must not be longer than 22 chars");
if (guid.Length > 22) throw new Exception("Input string must not be longer than 22 chars");
var num = new uint[6];
char[] str = guid.ToCharArray();
int n = 2, pos = 0, i;
for (i = 0; i < 6; i++)
{
num[i] = CvFrom64(str, pos, n);
pos += n;
n = 4;
}
var a = (int)((num[0] * 16777216) + num[1]);
var b = (short)(num[2] / 256);
var c = (short)(((num[2] % 256) * 256) + (num[3] / 65536));
var d = new byte[8];
d[0] = Convert.ToByte((num[3] / 256) % 256);
d[1] = Convert.ToByte(num[3] % 256);
d[2] = Convert.ToByte(num[4] / 65536);
d[3] = Convert.ToByte((num[4] / 256) % 256);
d[4] = Convert.ToByte(num[4] % 256);
d[5] = Convert.ToByte(num[5] / 65536);
d[6] = Convert.ToByte((num[5] / 256) % 256);
d[7] = Convert.ToByte(num[5] % 256);
return new Guid(a, b, c, d);
}
/// <summary>
/// Conversion of a GUID to a string representing the GUID
/// </summary>
/// <param name="guid">
/// The GUID to convert
/// </param>
/// <returns>
/// IFC (base64) encoded GUID string
/// </returns>
private static string ToIfcGuid(Guid guid)
{
var num = new uint[6];
var str = new char[22];
byte[] b = guid.ToByteArray();
// Creation of six 32 Bit integers from the components of the GUID structure
num[0] = BitConverter.ToUInt32(b, 0) / 16777216;
num[1] = BitConverter.ToUInt32(b, 0) % 16777216;
num[2] = (uint)((BitConverter.ToUInt16(b, 4) * 256) + (BitConverter.ToUInt16(b, 6) / 256));
num[3] = (uint)(((BitConverter.ToUInt16(b, 6) % 256) * 65536) + (b[8] * 256) + b[9]);
num[4] = (uint)((b[10] * 65536) + (b[11] * 256) + b[12]);
num[5] = (uint)((b[13] * 65536) + (b[14] * 256) + b[15]);
// Conversion of the numbers into a system using a base of 64
int n = 2;
int pos = 0;
for (int i = 0; i < 6; i++)
{
CvTo64(num[i], ref str, pos, n);
pos += n;
n = 4;
}
return new string(str);
}
#endregion
#region Static Fields (BYTE-HEX)
private static readonly uint[] _lookup32 = CreateLookup32();
private static uint[] CreateLookup32()
{
var result = new uint[256];
for (int i = 0; i < 256; i++)
{
string s = i.ToString("X2");
result[i] = ((uint)s[0]) + ((uint)s[1] << 16);
}
return result;
}
#endregion
#region Internal functions (BYTE-HEX)
private static string ByteArrayToHexViaLookup32(byte[] bytes)
{
var lookup32 = _lookup32;
var result = new char[bytes.Length * 2];
for (int i = 0; i < bytes.Length; i++)
{
var val = lookup32[bytes[i]];
result[2 * i] = (char)val;
result[2 * i + 1] = (char)(val >> 16);
}
return new string(result);
}
private static byte[] HexToByteArrayViaNybble(string hexString)
{
if ((hexString.Length & 1) != 0)
{
throw new ArgumentException("Input must have even number of characters");
}
byte[] ret = new byte[hexString.Length / 2];
for (int i = 0; i < ret.Length; i++)
{
int high = ParseNybble(hexString[i * 2]);
int low = ParseNybble(hexString[i * 2 + 1]);
ret[i] = (byte)((high << 4) | low);
}
return ret;
}
private static int ParseNybble(char c)
{
unchecked
{
uint i = (uint)(c - '0');
if (i < 10)
return (int)i;
i = ((uint)c & ~0x20u) - 'A';
if (i < 6)
return (int)i + 10;
throw new ArgumentException("Invalid nybble: " + c);
}
}
private static string ExclusiveOR(byte[] key, byte[] PAN)
{
if (key.Length == PAN.Length)
{
byte[] result = new byte[key.Length];
for (int i = 0; i < key.Length; i++)
{
result[i] = (byte)(key[i] ^ PAN[i]);
}
string hex = BitConverter.ToString(result).Replace("-", "");
return hex;
}
else
{
throw new ArgumentException();
}
}
#endregion
#region Internal functions (UUID-GUID)
private static string uuid_to_guid(string input)
{
string bytstr_0 = input.Replace("-", "");
string bytstr_1 = bytstr_0.Substring(24, 8);
string bytstr_2 = bytstr_0.Substring(32, 8);
string revit_guid_suffix = ExclusiveOR(HexToByteArrayViaNybble(bytstr_1), HexToByteArrayViaNybble(bytstr_2));
string revit_guid = input.Substring(0, 28) + revit_guid_suffix;
return revit_guid;
}
private static string guid_to_uuid(string uuid, string euid)
{
string bytstr_0 = uuid.Replace("-", "");
string bytstr_1 = bytstr_0.Substring(24, 8);
byte[] b_arr = BitConverter.GetBytes(UInt32.Parse(euid));
Array.Reverse(b_arr);
string bytstr_2 = ByteArrayToHexViaLookup32(b_arr).ToLower();
string revit_guid_suffix = ExclusiveOR(HexToByteArrayViaNybble(bytstr_1), HexToByteArrayViaNybble(bytstr_2)).ToLower();
string revit_guid = String.Join("-", new string[] {
bytstr_0.Substring(0, 8), bytstr_0.Substring(8, 4), bytstr_0.Substring(12, 4), bytstr_0.Substring(16, 4), bytstr_0.Substring(20, 4) + revit_guid_suffix, bytstr_2
});
return revit_guid;
}
#endregion
#region Public functions (UUID-GUID)
public static string IFC2REVIT(string IFC_UUID, uint IFC_EUID)
{
return guid_to_uuid(FromIfcGuid(IFC_UUID).ToString(), IFC_EUID.ToString());
}
public static string REVIT2IFC(string a)
{
return ToIfcGuid(new Guid(uuid_to_guid(a))).ToString();
}
public static String TestAlgorithm()
{
string[] Raw = {
"60f91daf-3dd7-4283-a86d-24137b73f3da-0001fd0b" ,
"7f62d588-71b3-428c-9f26-87d6e2a167c0-000755f0",
"60f91daf-3dd7-4283-a86d-24137b73f3da-0001fd1f"
};
string[] Expected = {
"1W_HslFTT2WwXj91DxSWxH",
"1$OjM8SRD2Z9ycXzRYfZ8m",
"1W_HslFTT2WwXj91DxSWx5"
};
string result = "";
for (int i = 0; i < Raw.Length; i++)
{
result += String.Join("\n", new string[] {
Raw[i], Expected[i], REVIT2IFC(Raw[i]), IFC2REVIT(Expected[i], BitConverter.ToUInt32(HexToByteArrayViaNybble(Raw[i].Substring(37,8)),0))
}) + "\n";
}
return result;
}
#endregion
}
}
| |
// GzipInputStream.cs
//
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
using System.IO;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
namespace ICSharpCode.SharpZipLib.GZip
{
/// <summary>
/// This filter stream is used to decompress a "GZIP" format stream.
/// The "GZIP" format is described baseInputStream RFC 1952.
///
/// author of the original java version : John Leuner
/// </summary>
/// <example> This sample shows how to unzip a gzipped file
/// <code>
/// using System;
/// using System.IO;
///
/// using ICSharpCode.SharpZipLib.GZip;
///
/// class MainClass
/// {
/// public static void Main(string[] args)
/// {
/// Stream s = new GZipInputStream(File.OpenRead(args[0]));
/// FileStream fs = File.Create(Path.GetFileNameWithoutExtension(args[0]));
/// int size = 2048;
/// byte[] writeData = new byte[2048];
/// while (true) {
/// size = s.Read(writeData, 0, size);
/// if (size > 0) {
/// fs.Write(writeData, 0, size);
/// } else {
/// break;
/// }
/// }
/// s.Close();
/// }
/// }
/// </code>
/// </example>
public class GZipInputStream : InflaterInputStream
{
/// <summary>
/// CRC-32 value for uncompressed data
/// </summary>
protected Crc32 crc = new Crc32();
/// <summary>
/// Indicates end of stream
/// </summary>
protected bool eos;
// Have we read the GZIP header yet?
bool readGZIPHeader;
/// <summary>
/// Creates a GzipInputStream with the default buffer size
/// </summary>
/// <param name="baseInputStream">
/// The stream to read compressed data from (baseInputStream GZIP format)
/// </param>
public GZipInputStream(Stream baseInputStream) : this(baseInputStream, 4096)
{
}
/// <summary>
/// Creates a GZIPInputStream with the specified buffer size
/// </summary>
/// <param name="baseInputStream">
/// The stream to read compressed data from (baseInputStream GZIP format)
/// </param>
/// <param name="size">
/// Size of the buffer to use
/// </param>
public GZipInputStream(Stream baseInputStream, int size) : base(baseInputStream, new Inflater(true), size)
{
}
/// <summary>
/// Reads uncompressed data into an array of bytes
/// </summary>
/// <param name="buf">
/// The buffer to read uncompressed data into
/// </param>
/// <param name="offset">
/// The offset indicating where the data should be placed
/// </param>
/// <param name="len">
/// The number of uncompressed bytes to be read
/// </param>
public override int Read(byte[] buf, int offset, int len)
{
// We first have to slurp baseInputStream the GZIP header, then we feed all the
// rest of the data to the superclass.
//
// As we do that we continually update the CRC32. Once the data is
// finished, we check the CRC32
//
// This means we don't need our own buffer, as everything is done
// baseInputStream the superclass.
if (!readGZIPHeader) {
ReadHeader();
}
if (eos) {
return 0;
}
// System.err.println("GZIPIS.read(byte[], off, len ... " + offset + " and len " + len);
//We don't have to read the header, so we just grab data from the superclass
int numRead = base.Read(buf, offset, len);
if (numRead > 0) {
crc.Update(buf, offset, numRead);
}
if (inf.IsFinished) {
ReadFooter();
}
return numRead;
}
void ReadHeader()
{
/* 1. Check the two magic bytes */
Crc32 headCRC = new Crc32();
int magic = baseInputStream.ReadByte();
if (magic < 0) {
eos = true;
return;
}
headCRC.Update(magic);
if (magic != (GZipConstants.GZIP_MAGIC >> 8)) {
throw new IOException("Error baseInputStream GZIP header, first byte doesn't match");
}
magic = baseInputStream.ReadByte();
if (magic != (GZipConstants.GZIP_MAGIC & 0xFF)) {
throw new IOException("Error baseInputStream GZIP header, second byte doesn't match");
}
headCRC.Update(magic);
/* 2. Check the compression type (must be 8) */
int CM = baseInputStream.ReadByte();
if (CM != 8) {
throw new IOException("Error baseInputStream GZIP header, data not baseInputStream deflate format");
}
headCRC.Update(CM);
/* 3. Check the flags */
int flags = baseInputStream.ReadByte();
if (flags < 0) {
throw new Exception("Early EOF baseInputStream GZIP header");
}
headCRC.Update(flags);
/* This flag byte is divided into individual bits as follows:
bit 0 FTEXT
bit 1 FHCRC
bit 2 FEXTRA
bit 3 FNAME
bit 4 FCOMMENT
bit 5 reserved
bit 6 reserved
bit 7 reserved
*/
/* 3.1 Check the reserved bits are zero */
if ((flags & 0xd0) != 0) {
throw new IOException("Reserved flag bits baseInputStream GZIP header != 0");
}
/* 4.-6. Skip the modification time, extra flags, and OS type */
for (int i=0; i< 6; i++) {
int readByte = baseInputStream.ReadByte();
if (readByte < 0) {
throw new Exception("Early EOF baseInputStream GZIP header");
}
headCRC.Update(readByte);
}
/* 7. Read extra field */
if ((flags & GZipConstants.FEXTRA) != 0) {
/* Skip subfield id */
for (int i=0; i< 2; i++) {
int readByte = baseInputStream.ReadByte();
if (readByte < 0) {
throw new Exception("Early EOF baseInputStream GZIP header");
}
headCRC.Update(readByte);
}
if (baseInputStream.ReadByte() < 0 || baseInputStream.ReadByte() < 0) {
throw new Exception("Early EOF baseInputStream GZIP header");
}
int len1, len2, extraLen;
len1 = baseInputStream.ReadByte();
len2 = baseInputStream.ReadByte();
if ((len1 < 0) || (len2 < 0)) {
throw new Exception("Early EOF baseInputStream GZIP header");
}
headCRC.Update(len1);
headCRC.Update(len2);
extraLen = (len1 << 8) | len2;
for (int i = 0; i < extraLen;i++) {
int readByte = baseInputStream.ReadByte();
if (readByte < 0)
{
throw new Exception("Early EOF baseInputStream GZIP header");
}
headCRC.Update(readByte);
}
}
/* 8. Read file name */
if ((flags & GZipConstants.FNAME) != 0) {
int readByte;
while ( (readByte = baseInputStream.ReadByte()) > 0) {
headCRC.Update(readByte);
}
if (readByte < 0) {
throw new Exception("Early EOF baseInputStream GZIP file name");
}
headCRC.Update(readByte);
}
/* 9. Read comment */
if ((flags & GZipConstants.FCOMMENT) != 0) {
int readByte;
while ( (readByte = baseInputStream.ReadByte()) > 0) {
headCRC.Update(readByte);
}
if (readByte < 0) {
throw new Exception("Early EOF baseInputStream GZIP comment");
}
headCRC.Update(readByte);
}
/* 10. Read header CRC */
if ((flags & GZipConstants.FHCRC) != 0) {
int tempByte;
int crcval = baseInputStream.ReadByte();
if (crcval < 0) {
throw new Exception("Early EOF baseInputStream GZIP header");
}
tempByte = baseInputStream.ReadByte();
if (tempByte < 0) {
throw new Exception("Early EOF baseInputStream GZIP header");
}
crcval = (crcval << 8) | tempByte;
if (crcval != ((int) headCRC.Value & 0xffff)) {
throw new IOException("Header CRC value mismatch");
}
}
readGZIPHeader = true;
//System.err.println("Read GZIP header");
}
void ReadFooter()
{
byte[] footer = new byte[8];
int avail = inf.RemainingInput;
if (avail > 8) {
avail = 8;
}
System.Array.Copy(buf, len - inf.RemainingInput, footer, 0, avail);
int needed = 8 - avail;
while (needed > 0) {
int count = baseInputStream.Read(footer, 8-needed, needed);
if (count <= 0) {
throw new ApplicationException("Early EOF baseInputStream GZIP footer");
}
needed -= count; //Jewel Jan 16
}
int crcval = (footer[0] & 0xff) | ((footer[1] & 0xff) << 8) | ((footer[2] & 0xff) << 16) | (footer[3] << 24);
if (crcval != (int) crc.Value) {
throw new ApplicationException("GZIP crc sum mismatch, theirs \"" + crcval + "\" and ours \"" + (int) crc.Value);
}
int total = (footer[4] & 0xff) | ((footer[5] & 0xff) << 8) | ((footer[6] & 0xff) << 16) | (footer[7] << 24);
if (total != inf.TotalOut) {
throw new ApplicationException("Number of bytes mismatch");
}
/* XXX Should we support multiple members.
* Difficult, since there may be some bytes still baseInputStream buf
*/
eos = true;
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Xml;
using System.Data;
using System.Collections;
namespace fyiReporting.Data
{
/// <summary>
/// Summary description for Class1.
/// </summary>
public class XmlCommand : IDbCommand
{
XmlConnection _xc; // connection we're running under
string _cmd; // command to execute
// parsed constituents of the command
string _Url; // url of the xml file
string _RowsXPath; // XPath specifying rows selection
ArrayList _ColumnsXPath; // XPath for each column
string _Type; // type of request
DataParameterCollection _Parameters = new DataParameterCollection();
public XmlCommand(XmlConnection conn)
{
_xc = conn;
}
internal string Url
{
get
{
// Check to see if "Url" or "@Url" is a parameter
IDbDataParameter dp= _Parameters["Url"] as IDbDataParameter;
if (dp == null)
dp= _Parameters["@Url"] as IDbDataParameter;
// Then check to see if the Url value is a parameter?
if (dp == null)
dp = _Parameters[_Url] as IDbDataParameter;
if (dp != null)
return dp.Value != null? dp.Value.ToString(): _Url; // don't pass null; pass existing value
return _Url; // the value must be a constant
}
set {_Url = value;}
}
internal string RowsXPath
{
get
{
IDbDataParameter dp= _Parameters["RowsXPath"] as IDbDataParameter;
if (dp == null)
dp= _Parameters["@RowsXPath"] as IDbDataParameter;
// Then check to see if the RowsXPath value is a parameter?
if (dp == null)
dp = _Parameters[_RowsXPath] as IDbDataParameter;
if (dp != null)
return dp.Value != null? dp.Value.ToString(): _RowsXPath; // don't pass null; pass existing value
return _RowsXPath; // the value must be a constant
}
set {_RowsXPath = value;}
}
internal ArrayList ColumnsXPath
{
get {return _ColumnsXPath;}
set {_ColumnsXPath = value;}
}
internal string Type
{
get {return _Type;}
set {_Type = value;}
}
#region IDbCommand Members
public void Cancel()
{
throw new NotImplementedException("Cancel not implemented");
}
public void Prepare()
{
return; // Prepare is a noop
}
public System.Data.CommandType CommandType
{
get
{
throw new NotImplementedException("CommandType not implemented");
}
set
{
throw new NotImplementedException("CommandType not implemented");
}
}
public IDataReader ExecuteReader(System.Data.CommandBehavior behavior)
{
if (!(behavior == CommandBehavior.SingleResult ||
behavior == CommandBehavior.SchemaOnly))
throw new ArgumentException("ExecuteReader supports SingleResult and SchemaOnly only.");
return new XmlDataReader(behavior, _xc, this);
}
IDataReader System.Data.IDbCommand.ExecuteReader()
{
return ExecuteReader(System.Data.CommandBehavior.SingleResult);
}
public object ExecuteScalar()
{
throw new NotImplementedException("ExecuteScalar not implemented");
}
public int ExecuteNonQuery()
{
throw new NotImplementedException("ExecuteNonQuery not implemented");
}
public int CommandTimeout
{
get
{
return 0;
}
set
{
throw new NotImplementedException("CommandTimeout not implemented");
}
}
public IDbDataParameter CreateParameter()
{
return new XmlDataParameter();
}
public IDbConnection Connection
{
get
{
return this._xc;
}
set
{
throw new NotImplementedException("Setting Connection not implemented");
}
}
public System.Data.UpdateRowSource UpdatedRowSource
{
get
{
throw new NotImplementedException("UpdatedRowSource not implemented");
}
set
{
throw new NotImplementedException("UpdatedRowSource not implemented");
}
}
public string CommandText
{
get
{
return this._cmd;
}
set
{
// Parse the command string for keyword value pairs separated by ';'
string[] args = value.Split(';');
string url=null;
string[] colxpaths=null;
string rowsxpath=null;
string type="both"; // assume we want both attributes and elements
foreach(string arg in args)
{
string[] param = arg.Trim().Split('=');
if (param == null || param.Length != 2)
continue;
string key = param[0].Trim().ToLower();
string val = param[1];
switch (key)
{
case "url":
case "file":
url = val;
break;
case "rowsxpath":
rowsxpath = val;
break;
case "type":
{
type = val.Trim().ToLower();
if (!(type == "attributes" || type == "elements" || type == "both"))
throw new ArgumentException(string.Format("type '{0}' is invalid. Must be 'attributes', 'elements' or 'both'", val));
break;
}
case "columnsxpath":
// column list is separated by ','
colxpaths = val.Trim().Split(',');
break;
default:
throw new ArgumentException(string.Format("{0} is an unknown parameter key", param[0]));
}
}
// User must specify both the url and the RowsXPath
if (url == null)
throw new ArgumentException("CommandText requires a 'Url=' parameter.");
if (rowsxpath == null)
throw new ArgumentException("CommandText requires a 'RowsXPath=' parameter.");
_cmd = value;
_Url = url;
_Type = type;
_RowsXPath = rowsxpath;
if (colxpaths != null)
_ColumnsXPath = new ArrayList(colxpaths);
}
}
public IDataParameterCollection Parameters
{
get
{
return _Parameters;
}
}
public IDbTransaction Transaction
{
get
{
throw new NotImplementedException("Transaction not implemented");
}
set
{
throw new NotImplementedException("Transaction not implemented");
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
// nothing to dispose of
}
#endregion
}
}
| |
/*
* @author Michael Holub
* @author Valentin Simonov / http://va.lent.in/
*/
using System;
using System.Collections.Generic;
using TouchScript.Pointers;
using TouchScript.Utils;
using UnityEngine;
using UnityEngine.Profiling;
namespace TouchScript.InputSources.InputHandlers
{
/// <summary>
/// Unity touch handling implementation which can be embedded and controlled from other (input) classes.
/// </summary>
public class TouchHandler : IInputSource, IDisposable
{
#region Public properties
/// <inheritdoc />
public ICoordinatesRemapper CoordinatesRemapper { get; set; }
/// <summary>
/// Gets a value indicating whether there any active pointers.
/// </summary>
/// <value> <c>true</c> if this instance has active pointers; otherwise, <c>false</c>. </value>
public bool HasPointers
{
get { return pointersNum > 0; }
}
#endregion
#region Private variables
private PointerDelegate addPointer;
private PointerDelegate updatePointer;
private PointerDelegate pressPointer;
private PointerDelegate releasePointer;
private PointerDelegate removePointer;
private PointerDelegate cancelPointer;
private ObjectPool<TouchPointer> touchPool;
// Unity fingerId -> TouchScript touch info
private Dictionary<int, TouchState> systemToInternalId = new Dictionary<int, TouchState>(10);
private int pointersNum;
private CustomSampler updateSampler;
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="TouchHandler" /> class.
/// </summary>
/// <param name="addPointer">A function called when a new pointer is detected.</param>
/// <param name="updatePointer">A function called when a pointer is moved or its parameter is updated.</param>
/// <param name="pressPointer">A function called when a pointer touches the surface.</param>
/// <param name="releasePointer">A function called when a pointer is lifted off.</param>
/// <param name="removePointer">A function called when a pointer is removed.</param>
/// <param name="cancelPointer">A function called when a pointer is cancelled.</param>
public TouchHandler(PointerDelegate addPointer, PointerDelegate updatePointer, PointerDelegate pressPointer, PointerDelegate releasePointer, PointerDelegate removePointer, PointerDelegate cancelPointer)
{
this.addPointer = addPointer;
this.updatePointer = updatePointer;
this.pressPointer = pressPointer;
this.releasePointer = releasePointer;
this.removePointer = removePointer;
this.cancelPointer = cancelPointer;
touchPool = new ObjectPool<TouchPointer>(10, () => new TouchPointer(this), null, resetPointer);
touchPool.Name = "Touch";
updateSampler = CustomSampler.Create("[TouchScript] Update touch");
}
#region Public methods
/// <inheritdoc />
public bool UpdateInput()
{
updateSampler.Begin();
for (var i = 0; i < Input.touchCount; ++i)
{
var t = Input.GetTouch(i);
TouchState touchState;
switch (t.phase)
{
case TouchPhase.Began:
if (systemToInternalId.TryGetValue(t.fingerId, out touchState) && touchState.Phase != TouchPhase.Canceled)
{
// Ending previous touch (missed a frame)
internalRemovePointer(touchState.Pointer);
systemToInternalId[t.fingerId] = new TouchState(internalAddPointer(t.position));
}
else
{
systemToInternalId.Add(t.fingerId, new TouchState(internalAddPointer(t.position)));
}
break;
case TouchPhase.Moved:
if (systemToInternalId.TryGetValue(t.fingerId, out touchState))
{
if (touchState.Phase != TouchPhase.Canceled)
{
touchState.Pointer.Position = t.position;
updatePointer(touchState.Pointer);
}
}
else
{
// Missed began phase
systemToInternalId.Add(t.fingerId, new TouchState(internalAddPointer(t.position)));
}
break;
// NOTE: Unity touch on Windows reports Cancelled as Ended
// when a touch goes out of display boundary
case TouchPhase.Ended:
if (systemToInternalId.TryGetValue(t.fingerId, out touchState))
{
systemToInternalId.Remove(t.fingerId);
if (touchState.Phase != TouchPhase.Canceled) internalRemovePointer(touchState.Pointer);
}
else
{
// Missed one finger begin-end transition
var pointer = internalAddPointer(t.position);
internalRemovePointer(pointer);
}
break;
case TouchPhase.Canceled:
if (systemToInternalId.TryGetValue(t.fingerId, out touchState))
{
systemToInternalId.Remove(t.fingerId);
if (touchState.Phase != TouchPhase.Canceled) internalCancelPointer(touchState.Pointer);
}
else
{
// Missed one finger begin-end transition
var pointer = internalAddPointer(t.position);
internalCancelPointer(pointer);
}
break;
case TouchPhase.Stationary:
if (systemToInternalId.TryGetValue(t.fingerId, out touchState)) {}
else
{
// Missed begin phase
systemToInternalId.Add(t.fingerId, new TouchState(internalAddPointer(t.position)));
}
break;
}
}
updateSampler.End();
return Input.touchCount > 0;
}
/// <inheritdoc />
public void UpdateResolution() {}
/// <inheritdoc />
public bool CancelPointer(Pointer pointer, bool shouldReturn)
{
var touch = pointer as TouchPointer;
if (touch == null) return false;
int fingerId = -1;
foreach (var touchState in systemToInternalId)
{
if (touchState.Value.Pointer == touch && touchState.Value.Phase != TouchPhase.Canceled)
{
fingerId = touchState.Key;
break;
}
}
if (fingerId > -1)
{
internalCancelPointer(touch);
if (shouldReturn) systemToInternalId[fingerId] = new TouchState(internalReturnPointer(touch));
else systemToInternalId[fingerId] = new TouchState(touch, TouchPhase.Canceled);
return true;
}
return false;
}
/// <summary>
/// Releases resources.
/// </summary>
public void Dispose()
{
foreach (var touchState in systemToInternalId)
{
if (touchState.Value.Phase != TouchPhase.Canceled) internalCancelPointer(touchState.Value.Pointer);
}
systemToInternalId.Clear();
}
#endregion
#region Internal methods
/// <inheritdoc />
public void INTERNAL_DiscardPointer(Pointer pointer)
{
var p = pointer as TouchPointer;
if (p == null) return;
touchPool.Release(p);
}
#endregion
#region Private functions
private Pointer internalAddPointer(Vector2 position)
{
pointersNum++;
var pointer = touchPool.Get();
pointer.Position = remapCoordinates(position);
pointer.Buttons |= Pointer.PointerButtonState.FirstButtonDown | Pointer.PointerButtonState.FirstButtonPressed;
addPointer(pointer);
pressPointer(pointer);
return pointer;
}
private TouchPointer internalReturnPointer(TouchPointer pointer)
{
pointersNum++;
var newPointer = touchPool.Get();
newPointer.CopyFrom(pointer);
pointer.Buttons |= Pointer.PointerButtonState.FirstButtonDown | Pointer.PointerButtonState.FirstButtonPressed;
newPointer.Flags |= Pointer.FLAG_RETURNED;
addPointer(newPointer);
pressPointer(newPointer);
return newPointer;
}
private void internalRemovePointer(Pointer pointer)
{
pointersNum--;
pointer.Buttons &= ~Pointer.PointerButtonState.FirstButtonPressed;
pointer.Buttons |= Pointer.PointerButtonState.FirstButtonUp;
releasePointer(pointer);
removePointer(pointer);
}
private void internalCancelPointer(Pointer pointer)
{
pointersNum--;
cancelPointer(pointer);
}
private Vector2 remapCoordinates(Vector2 position)
{
if (CoordinatesRemapper != null) return CoordinatesRemapper.Remap(position);
return position;
}
private void resetPointer(Pointer p)
{
p.INTERNAL_Reset();
}
#endregion
private struct TouchState
{
public Pointer Pointer;
public TouchPhase Phase;
public TouchState(Pointer pointer, TouchPhase phase = TouchPhase.Began)
{
Pointer = pointer;
Phase = phase;
}
}
}
}
| |
// 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.Management.Network
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// SecurityRulesOperations operations.
/// </summary>
internal partial class SecurityRulesOperations : IServiceOperations<NetworkManagementClient>, ISecurityRulesOperations
{
/// <summary>
/// Initializes a new instance of the SecurityRulesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal SecurityRulesOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Deletes the specified network security rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get the specified network security rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<SecurityRule>> GetWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkSecurityGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName");
}
if (securityRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "securityRuleName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.Add("securityRuleName", securityRuleName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName));
_url = _url.Replace("{securityRuleName}", System.Uri.EscapeDataString(securityRuleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", 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 (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<SecurityRule>();
_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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<SecurityRule>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a security rule in the specified network security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='securityRuleParameters'>
/// Parameters supplied to the create or update network security rule
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<SecurityRule>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<SecurityRule> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all security rules in a network security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<SecurityRule>>> ListWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkSecurityGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", 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 (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<SecurityRule>>();
_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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SecurityRule>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified network security rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkSecurityGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName");
}
if (securityRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "securityRuleName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.Add("securityRuleName", securityRuleName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName));
_url = _url.Replace("{securityRuleName}", System.Uri.EscapeDataString(securityRuleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", 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 (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204 && (int)_statusCode != 202 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a security rule in the specified network security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='securityRuleParameters'>
/// Parameters supplied to the create or update network security rule
/// operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<SecurityRule>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkSecurityGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName");
}
if (securityRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "securityRuleName");
}
if (securityRuleParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "securityRuleParameters");
}
if (securityRuleParameters != null)
{
securityRuleParameters.Validate();
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.Add("securityRuleName", securityRuleName);
tracingParameters.Add("securityRuleParameters", securityRuleParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName));
_url = _url.Replace("{securityRuleName}", System.Uri.EscapeDataString(securityRuleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", 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(securityRuleParameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(securityRuleParameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<SecurityRule>();
_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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<SecurityRule>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SecurityRule>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all security rules in a network security group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<SecurityRule>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", 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 (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<SecurityRule>>();
_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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SecurityRule>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using Aurora.DataManager;
using Aurora.Simulation.Base;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using Aurora.Framework;
using OpenSim.Services.Interfaces;
namespace OpenSim.Services
{
public class AgentInfoService : ConnectorBase, IService, IAgentInfoService
{
#region Declares
protected IAgentInfoConnector m_agentInfoConnector;
protected List<string> m_lockedUsers = new List<string>();
#endregion
#region IService Members
public string Name
{
get { return GetType().Name; }
}
public virtual void Initialize(IConfigSource config, IRegistryCore registry)
{
m_registry = registry;
IConfig handlerConfig = config.Configs["Handlers"];
if (handlerConfig.GetString("AgentInfoHandler", "") != Name)
return;
registry.RegisterModuleInterface<IAgentInfoService>(this);
Init(registry, Name);
}
public virtual void Start(IConfigSource config, IRegistryCore registry)
{
}
public virtual void FinishedStartup()
{
m_agentInfoConnector = DataManager.RequestPlugin<IAgentInfoConnector>();
}
#endregion
#region IAgentInfoService Members
public IAgentInfoService InnerService
{
get { return this; }
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public virtual UserInfo GetUserInfo(string userID)
{
object remoteValue = DoRemote(userID);
if (remoteValue != null || m_doRemoteOnly)
return (UserInfo)remoteValue;
return GetUserInfo(userID, true);
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public virtual List<UserInfo> GetUserInfos(List<string> userIDs)
{
object remoteValue = DoRemote(userIDs);
if (remoteValue != null || m_doRemoteOnly)
return (List<UserInfo>)remoteValue;
List<UserInfo> infos = new List<UserInfo>();
for (int i = 0; i < userIDs.Count; i++)
{
infos.Add(GetUserInfo(userIDs[i]));
}
return infos;
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public virtual List<string> GetAgentsLocations(string requestor, List<string> userIDs)
{
string[] infos = new string[userIDs.Count];
for (int i = 0; i < userIDs.Count; i++)
{
UserInfo user = GetUserInfo(userIDs[i]);
if (user != null && user.IsOnline)
{
Interfaces.GridRegion gr =
m_registry.RequestModuleInterface<IGridService>().GetRegionByUUID(UUID.Zero,
user.CurrentRegionID);
if (gr != null)
infos[i] = gr.ServerURI;
else
infos[i] = "NotOnline";
}
else if (user == null)
infos[i] = "NonExistant";
else
infos[i] = "NotOnline";
}
return new List<string>(infos);
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public virtual bool SetHomePosition(string userID, UUID homeID, Vector3 homePosition, Vector3 homeLookAt)
{
object remoteValue = DoRemote(userID, homeID, homePosition, homeLookAt);
if (remoteValue != null || m_doRemoteOnly)
return remoteValue == null ? false : (bool)remoteValue;
m_agentInfoConnector.SetHomePosition(userID, homeID, homePosition, homeLookAt);
return true;
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public virtual void SetLastPosition(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
{
object remoteValue = DoRemote(userID, regionID, lastPosition, lastLookAt);
if (remoteValue != null || m_doRemoteOnly)
return;
m_agentInfoConnector.SetLastPosition(userID, regionID, lastPosition, lastLookAt);
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Full)]
public virtual void LockLoggedInStatus(string userID, bool locked)
{
object remoteValue = DoRemote(userID, locked);
if (remoteValue != null || m_doRemoteOnly)
return;
if (locked && !m_lockedUsers.Contains(userID))
m_lockedUsers.Add(userID);
else
m_lockedUsers.Remove(userID);
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Full)]
public virtual void SetLoggedIn(string userID, bool loggingIn, bool fireLoggedInEvent, UUID enteringRegion)
{
object remoteValue = DoRemote(userID, loggingIn, fireLoggedInEvent, enteringRegion);
if (remoteValue != null || m_doRemoteOnly)
return;
UserInfo userInfo = GetUserInfo(userID, false); //We are changing the status, so don't look
if (userInfo == null)
{
Save(new UserInfo
{
IsOnline = loggingIn,
UserID = userID,
CurrentLookAt = Vector3.Zero,
CurrentPosition = Vector3.Zero,
CurrentRegionID = enteringRegion,
HomeLookAt = Vector3.Zero,
HomePosition = Vector3.Zero,
HomeRegionID = UUID.Zero,
Info = new OSDMap(),
LastLogin = DateTime.Now.ToUniversalTime(),
LastLogout = DateTime.Now.ToUniversalTime(),
});
}
if (m_lockedUsers.Contains(userID)){
return; //User is locked, leave them alone
}
Dictionary<string, object> agentUpdateValues = new Dictionary<string, object>();
agentUpdateValues["IsOnline"] = loggingIn ? 1 : 0;
if (loggingIn)
{
agentUpdateValues["LastLogin"] = Util.ToUnixTime(DateTime.Now.ToUniversalTime());
if (enteringRegion != UUID.Zero)
{
agentUpdateValues["CurrentRegionID"] = enteringRegion;
}
}
else
{
agentUpdateValues["LastLogout"] = Util.ToUnixTime(DateTime.Now.ToUniversalTime());
}
agentUpdateValues["LastSeen"] = Util.ToUnixTime(DateTime.Now.ToUniversalTime());
m_agentInfoConnector.Update(userID, agentUpdateValues);
if (fireLoggedInEvent)
{
//Trigger an event so listeners know
m_registry.RequestModuleInterface<ISimulationBase>().EventManager.FireGenericEventHandler(
"UserStatusChange", new object[] {userID, loggingIn, enteringRegion});
}
}
#endregion
#region Helpers
private UserInfo GetUserInfo(string userID, bool checkForOfflineStatus)
{
bool changed = false;
UserInfo info = m_agentInfoConnector.Get(userID, checkForOfflineStatus, out changed);
if (changed)
if (!m_lockedUsers.Contains(userID))
m_registry.RequestModuleInterface<ISimulationBase>().EventManager.FireGenericEventHandler(
"UserStatusChange", new object[] {userID, false, UUID.Zero});
return info;
}
public virtual void Save(UserInfo userInfo)
{
m_agentInfoConnector.Set(userInfo);
}
#endregion
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.Config.DataAccess;
using Frapid.Config.Api.Fakes;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Xunit;
namespace Frapid.Config.Api.Tests
{
public class CustomFieldFormTests
{
public static CustomFieldFormController Fixture()
{
CustomFieldFormController controller = new CustomFieldFormController(new CustomFieldFormRepository(), "", new LoginView());
return controller;
}
[Fact]
[Conditional("Debug")]
public void CountEntityColumns()
{
EntityView entityView = Fixture().GetEntityView();
Assert.Null(entityView.Columns);
}
[Fact]
[Conditional("Debug")]
public void Count()
{
long count = Fixture().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetAll()
{
int count = Fixture().GetAll().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Export()
{
int count = Fixture().Export().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Get()
{
Frapid.Config.Entities.CustomFieldForm customFieldForm = Fixture().Get(string.Empty);
Assert.NotNull(customFieldForm);
}
[Fact]
[Conditional("Debug")]
public void First()
{
Frapid.Config.Entities.CustomFieldForm customFieldForm = Fixture().GetFirst();
Assert.NotNull(customFieldForm);
}
[Fact]
[Conditional("Debug")]
public void Previous()
{
Frapid.Config.Entities.CustomFieldForm customFieldForm = Fixture().GetPrevious(string.Empty);
Assert.NotNull(customFieldForm);
}
[Fact]
[Conditional("Debug")]
public void Next()
{
Frapid.Config.Entities.CustomFieldForm customFieldForm = Fixture().GetNext(string.Empty);
Assert.NotNull(customFieldForm);
}
[Fact]
[Conditional("Debug")]
public void Last()
{
Frapid.Config.Entities.CustomFieldForm customFieldForm = Fixture().GetLast();
Assert.NotNull(customFieldForm);
}
[Fact]
[Conditional("Debug")]
public void GetMultiple()
{
IEnumerable<Frapid.Config.Entities.CustomFieldForm> customFieldForms = Fixture().Get(new string[] { });
Assert.NotNull(customFieldForms);
}
[Fact]
[Conditional("Debug")]
public void GetPaginatedResult()
{
int count = Fixture().GetPaginatedResult().Count();
Assert.Equal(1, count);
count = Fixture().GetPaginatedResult(1).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountWhere()
{
long count = Fixture().CountWhere(new JArray());
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetWhere()
{
int count = Fixture().GetWhere(1, new JArray()).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountFiltered()
{
long count = Fixture().CountFiltered("");
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetFiltered()
{
int count = Fixture().GetFiltered(1, "").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetDisplayFields()
{
int count = Fixture().GetDisplayFields().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetCustomFields()
{
int count = Fixture().GetCustomFields().Count();
Assert.Equal(1, count);
count = Fixture().GetCustomFields("").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void AddOrEdit()
{
try
{
var form = new JArray { null, null };
Fixture().AddOrEdit(form);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Add()
{
try
{
Fixture().Add(null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Edit()
{
try
{
Fixture().Edit(string.Empty, null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void BulkImport()
{
var collection = new JArray { null, null, null, null };
var actual = Fixture().BulkImport(collection);
Assert.NotNull(actual);
}
[Fact]
[Conditional("Debug")]
public void Delete()
{
try
{
Fixture().Delete(string.Empty);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.InternalServerError, ex.Response.StatusCode);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Should;
using NUnit.Framework;
namespace AutoMapper.UnitTests
{
namespace ConfigurationValidation
{
public class When_testing_a_dto_with_mismatched_members : NonValidatingSpecBase
{
public class ModelObject
{
public string Foo { get; set; }
public string Barr { get; set; }
}
public class ModelDto
{
public string Foo { get; set; }
public string Bar { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<ModelObject, ModelDto>();
}
[Test]
public void Should_fail_a_configuration_check()
{
typeof(AutoMapperConfigurationException).ShouldBeThrownBy(Mapper.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_fully_mapped_and_custom_matchers : NonValidatingSpecBase
{
public class ModelObject
{
public string Foo { get; set; }
public string Barr { get; set; }
}
public class ModelDto
{
public string Foo { get; set; }
public string Bar { get; set; }
}
protected override void Establish_context()
{
Mapper
.CreateMap<ModelObject, ModelDto>()
.ForMember(dto => dto.Bar, opt => opt.MapFrom(m => m.Barr));
}
[Test]
public void Should_pass_an_inspection_of_missing_mappings()
{
Mapper.AssertConfigurationIsValid();
}
}
public class When_testing_a_dto_with_matching_member_names_but_mismatched_types : NonValidatingSpecBase
{
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public decimal Value { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
}
[Test]
public void Should_fail_a_configuration_check()
{
typeof(AutoMapperConfigurationException).ShouldBeThrownBy(Mapper.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_member_type_mapped_mappings : AutoMapperSpecBase
{
private AutoMapperConfigurationException _exception;
public class Source
{
public int Value { get; set; }
public OtherSource Other { get; set; }
}
public class OtherSource
{
public int Value { get; set; }
}
public class Destination
{
public int Value { get; set; }
public OtherDest Other { get; set; }
}
public class OtherDest
{
public int Value { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
Mapper.CreateMap<OtherSource, OtherDest>();
}
protected override void Because_of()
{
try
{
Mapper.AssertConfigurationIsValid();
}
catch (AutoMapperConfigurationException ex)
{
_exception = ex;
}
}
[Test]
public void Should_pass_a_configuration_check()
{
_exception.ShouldBeNull();
}
}
public class When_testing_a_dto_with_matched_members_but_mismatched_types_that_are_ignored : AutoMapperSpecBase
{
private AutoMapperConfigurationException _exception;
public class ModelObject
{
public string Foo { get; set; }
public string Bar { get; set; }
}
public class ModelDto
{
public string Foo { get; set; }
public int Bar { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<ModelObject, ModelDto>()
.ForMember(dest => dest.Bar, opt => opt.Ignore());
}
protected override void Because_of()
{
try
{
Mapper.AssertConfigurationIsValid();
}
catch (AutoMapperConfigurationException ex)
{
_exception = ex;
}
}
[Test]
public void Should_pass_a_configuration_check()
{
_exception.ShouldBeNull();
}
}
public class When_testing_a_dto_with_array_types_with_mismatched_element_types : NonValidatingSpecBase
{
public class Source
{
public SourceItem[] Items;
}
public class Destination
{
public DestinationItem[] Items;
}
public class SourceItem
{
}
public class DestinationItem
{
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
}
[Test]
public void Should_fail_a_configuration_check()
{
typeof(AutoMapperConfigurationException).ShouldBeThrownBy(Mapper.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_list_types_with_mismatched_element_types : NonValidatingSpecBase
{
public class Source
{
public List<SourceItem> Items;
}
public class Destination
{
public List<DestinationItem> Items;
}
public class SourceItem
{
}
public class DestinationItem
{
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
}
[Test]
public void Should_fail_a_configuration_check()
{
typeof(AutoMapperConfigurationException).ShouldBeThrownBy(Mapper.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_readonly_members : NonValidatingSpecBase
{
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public int Value { get; set; }
public string ValuePlusOne { get { return (Value + 1).ToString(); } }
public int ValuePlusTwo { get { return Value + 2; } }
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
}
protected override void Because_of()
{
Mapper.Map<Source, Destination>(new Source {Value = 5});
}
[Test]
public void Should_be_valid()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Mapper.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_in_a_specfic_profile : NonValidatingSpecBase
{
public class GoodSource
{
public int Value { get; set; }
}
public class GoodDest
{
public int Value { get; set; }
}
public class BadDest
{
public int Valufffff { get; set; }
}
protected override void Because_of()
{
Mapper.Initialize(cfg =>
{
cfg.CreateProfile("Good", profile =>
{
profile.CreateMap<GoodSource, GoodDest>();
});
cfg.CreateProfile("Bad", profile =>
{
profile.CreateMap<GoodSource, BadDest>();
});
});
}
[Test]
public void Should_ignore_bad_dtos_in_other_profiles()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(() => Mapper.AssertConfigurationIsValid("Good"));
}
}
public class When_testing_a_dto_with_mismatched_custom_member_mapping : NonValidatingSpecBase
{
public class SubBarr { }
public class SubBar { }
public class ModelObject
{
public string Foo { get; set; }
public SubBarr Barr { get; set; }
}
public class ModelDto
{
public string Foo { get; set; }
public SubBar Bar { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<ModelObject, ModelDto>()
.ForMember(dest => dest.Bar, opt => opt.MapFrom(src => src.Barr));
}
[Test]
public void Should_fail_a_configuration_check()
{
typeof(AutoMapperConfigurationException).ShouldBeThrownBy(Mapper.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_value_specified_members : NonValidatingSpecBase
{
public class Source {}
public class Destination
{
public int Value { get; set; }
}
protected override void Establish_context()
{
object i = 7;
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Value, opt => opt.UseValue(i));
});
}
[Test]
public void Should_validate_successfully()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Mapper.AssertConfigurationIsValid);
}
}
}
}
| |
//
// Copyright (C) Microsoft. All rights reserved.
//
using System;
using System.IO;
using System.Reflection;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Management.Automation;
using System.Management.Automation.Provider;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
namespace Microsoft.WSMan.Management
{
/// <summary>
/// Creates a WSMan Session option hashtable which can be passed into WSMan
/// cmdlets:
/// Get-WSManInstance
/// Set-WSManInstance
/// Invoke-WSManAction
/// Connect-WSMan
/// </summary>
[Cmdlet(VerbsCommon.New, "WSManSessionOption", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=141449")]
public class NewWSManSessionOptionCommand : PSCmdlet
{
/// <summary>
///
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public ProxyAccessType ProxyAccessType
{
get
{
return _proxyaccesstype;
}
set
{
_proxyaccesstype = value;
}
}
private ProxyAccessType _proxyaccesstype;
/// <summary>
/// The following is the definition of the input parameter "ProxyAuthentication".
/// This parameter takes a set of authentication methods the user can select
/// from. The available options should be as follows:
/// - Negotiate: Use the default authentication (ad defined by the underlying
/// protocol) for establishing a remote connection.
/// - Basic: Use basic authentication for establishing a remote connection
/// - Digest: Use Digest authentication for establishing a remote connection
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public ProxyAuthentication ProxyAuthentication
{
get { return proxyauthentication; }
set
{
proxyauthentication = value;
}
}
private ProxyAuthentication proxyauthentication;
/// <summary>
/// The following is the definition of the input parameter "ProxyCredential".
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[Credential]
public PSCredential ProxyCredential
{
get { return _proxycredential; }
set
{
_proxycredential = value;
}
}
private PSCredential _proxycredential;
/// <summary>
/// The following is the definition of the input parameter "SkipCACheck".
/// When connecting over HTTPS, the client does not validate that the server
/// certificate is signed by a trusted certificate authority (CA). Use only when
/// the remote computer is trusted by other means, for example, if the remote
/// computer is part of a network that is physically secure and isolated or the
/// remote computer is listed as a trusted host in WinRM configuration
/// </summary>
[Parameter]
public SwitchParameter SkipCACheck
{
get { return skipcacheck; }
set
{
skipcacheck = value;
}
}
private bool skipcacheck;
/// <summary>
/// The following is the definition of the input parameter "SkipCNCheck".
/// Indicates that certificate common name (CN) of the server need not match the
/// hostname of the server. Used only in remote operations using https. This
/// option should only be used for trusted machines
/// </summary>
[Parameter]
public SwitchParameter SkipCNCheck
{
get { return skipcncheck; }
set
{
skipcncheck = value;
}
}
private bool skipcncheck;
/// <summary>
/// The following is the definition of the input parameter "SkipRevocation".
/// Indicates that certificate common name (CN) of the server need not match the
/// hostname of the server. Used only in remote operations using https. This
/// option should only be used for trusted machines
/// </summary>
[Parameter]
public SwitchParameter SkipRevocationCheck
{
get { return skiprevocationcheck; }
set
{
skiprevocationcheck = value;
}
}
private bool skiprevocationcheck;
/// <summary>
/// The following is the definition of the input parameter "SPNPort".
/// Appends port number to the connection Service Principal Name SPN of the
/// remote server.
/// SPN is used when authentication mechanism is Kerberos or Negotiate
/// </summary>
[Parameter]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SPN")]
[ValidateRange(0, Int32.MaxValue)]
public Int32 SPNPort
{
get { return spnport; }
set
{
spnport = value;
}
}
private Int32 spnport;
/// <summary>
/// The following is the definition of the input parameter "Timeout".
/// Defines the timeout in ms for the wsman operation
/// </summary>
[Parameter]
[Alias("OperationTimeoutMSec")]
[ValidateRange(0, Int32.MaxValue)]
public Int32 OperationTimeout
{
get { return operationtimeout; }
set
{
operationtimeout = value;
}
}
private Int32 operationtimeout;
/// <summary>
/// The following is the definition of the input parameter "UnEncrypted".
/// Specifies that no encryption will be used when doing remote operations over
/// http. Unencrypted traffic is not allowed by default and must be enabled in
/// the local configuration
/// </summary>
[Parameter]
public SwitchParameter NoEncryption
{
get { return noencryption; }
set
{
noencryption = value;
}
}
private bool noencryption;
/// <summary>
/// The following is the definition of the input parameter "UTF16".
/// Indicates the request is encoded in UTF16 format rather than UTF8 format;
/// UTF8 is the default.
/// </summary>
[Parameter]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "UTF")]
public SwitchParameter UseUTF16
{
get { return useutf16; }
set
{
useutf16 = value;
}
}
private bool useutf16;
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
WSManHelper helper = new WSManHelper(this);
if (proxyauthentication.Equals(ProxyAuthentication.Basic) || proxyauthentication.Equals(ProxyAuthentication.Digest))
{
if (_proxycredential == null)
{
InvalidOperationException ex = new InvalidOperationException(helper.GetResourceMsgFromResourcetext("NewWSManSessionOptionCred"));
ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, null);
WriteError(er);
return;
}
}
if ((_proxycredential != null) && (proxyauthentication == 0))
{
InvalidOperationException ex = new InvalidOperationException(helper.GetResourceMsgFromResourcetext("NewWSManSessionOptionAuth"));
ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, null);
WriteError(er);
return;
}
//Creating the Session Object
SessionOption objSessionOption = new SessionOption();
objSessionOption.SPNPort = spnport;
objSessionOption.UseUtf16 = useutf16;
objSessionOption.SkipCNCheck = skipcncheck;
objSessionOption.SkipCACheck = skipcacheck;
objSessionOption.OperationTimeout = operationtimeout;
objSessionOption.SkipRevocationCheck = skiprevocationcheck;
//Proxy Settings
objSessionOption.ProxyAccessType = _proxyaccesstype;
objSessionOption.ProxyAuthentication = proxyauthentication;
if (noencryption)
{
objSessionOption.UseEncryption = false;
}
if (_proxycredential != null)
{
NetworkCredential nwCredentials = _proxycredential.GetNetworkCredential();
objSessionOption.ProxyCredential = nwCredentials;
}
WriteObject(objSessionOption);
}//End BeginProcessing()
}//End Class
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace DotSpatial.Symbology.Forms
{
/// <summary>
/// HueSlider
/// </summary>
[DefaultEvent("PositionChanging")]
public class HueSlider : Control
{
#region Fields
private int _dx;
private int _hueShift;
private bool _inverted;
private int _max;
private int _min;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="HueSlider"/> class.
/// </summary>
public HueSlider()
{
_min = 0;
_max = 360;
LeftHandle = new HueHandle(this)
{
Position = 72,
Left = true
};
RightHandle = new HueHandle(this)
{
Position = 288
};
}
#endregion
#region Events
/// <summary>
/// Occurs after the user has finished adjusting the positions of either of the sliders and has released control
/// </summary>
public event EventHandler PositionChanged;
/// <summary>
/// Occurs as the user is adjusting the positions on either of the sliders
/// </summary>
public event EventHandler PositionChanging;
#endregion
#region Properties
/// <summary>
/// Gets or sets an integer value indicating how much to adjust the hue to change where wrapping occurs.
/// </summary>
[Description("Gets or sets an integer value indicating how much to adjust the hue to change where wrapping occurs.")]
public int HueShift
{
get
{
return _hueShift;
}
set
{
_hueShift = value;
Invalidate();
}
}
/// <summary>
/// Gets or sets a value indicating whether the hue pattern should be flipped.
/// </summary>
public bool Inverted
{
get
{
return _inverted;
}
set
{
_inverted = value;
Invalidate();
}
}
/// <summary>
/// Gets or sets the floating point position of the left slider. This must range
/// between 0 and 1, and to the left of the right slider, (therefore with a value lower than the right slider.)
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[TypeConverter(typeof(ExpandableObjectConverter))]
public HueHandle LeftHandle { get; set; }
/// <summary>
/// Gets or sets the value represented by the left handle, taking into account
/// whether or not the slider has been reversed.
/// </summary>
public float LeftValue
{
get
{
if (_inverted)
{
return _max - LeftHandle.Position;
}
return LeftHandle.Position;
}
set
{
if (_inverted)
{
LeftHandle.Position = _max - value;
return;
}
LeftHandle.Position = value;
}
}
/// <summary>
/// Gets or sets the maximum allowed value for the slider.
/// </summary>
[Description("Gets or sets the maximum allowed value for the slider.")]
public int Maximum
{
get
{
return _max;
}
set
{
_max = value;
if (_max < RightHandle.Position) RightHandle.Position = _max;
if (_max < LeftHandle.Position) LeftHandle.Position = _max;
}
}
/// <summary>
/// Gets or sets the minimum allowed value for the slider.
/// </summary>
[Description("Gets or sets the minimum allowed value for the slider.")]
public int Minimum
{
get
{
return _min;
}
set
{
_min = value;
if (LeftHandle.Position < _min) LeftHandle.Position = _min;
if (RightHandle.Position < _min) RightHandle.Position = _min;
}
}
/// <summary>
/// Gets or sets the floating point position of the right slider. This must range
/// between 0 and 1, and to the right of the left slider.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[TypeConverter(typeof(ExpandableObjectConverter))]
public HueHandle RightHandle { get; set; }
/// <summary>
/// Gets or sets the value represented by the right handle, taking into account
/// whether or not the slider has been reversed.
/// </summary>
public float RightValue
{
get
{
if (_inverted)
{
return _max - RightHandle.Position;
}
return RightHandle.Position;
}
set
{
if (_inverted)
{
RightHandle.Position = _max - value;
return;
}
RightHandle.Position = value;
}
}
#endregion
#region Methods
/// <summary>
/// Uses the hue values from the specified start and end color to set the handle positions.
/// </summary>
/// <param name="startColor">The start color that represents the left hue</param>
/// <param name="endColor">The start color that represents the right hue</param>
public void SetRange(Color startColor, Color endColor)
{
int hStart = (int)startColor.GetHue();
int hEnd = (int)endColor.GetHue();
_inverted = hStart > hEnd;
LeftValue = hStart;
RightValue = hEnd;
}
/// <summary>
/// Controls the actual drawing for this gradient slider control.
/// </summary>
/// <param name="g">The graphics object used for drawing.</param>
/// <param name="clipRectangle">The clip rectangle.</param>
protected virtual void OnDraw(Graphics g, Rectangle clipRectangle)
{
using (GraphicsPath gp = new GraphicsPath())
{
Rectangle innerRect = new Rectangle(LeftHandle.Width, 3, Width - 1 - RightHandle.Width - LeftHandle.Width, Height - 1 - 6);
gp.AddRoundedRectangle(innerRect, 2);
if (Width == 0 || Height == 0) return;
// Create a rounded gradient effect as the backdrop that other colors will be drawn to
LinearGradientBrush silver = new LinearGradientBrush(ClientRectangle, BackColor.Lighter(.2F), BackColor.Darker(.6F), LinearGradientMode.Vertical);
g.FillPath(silver, gp);
silver.Dispose();
using (LinearGradientBrush lgb = new LinearGradientBrush(innerRect, Color.White, Color.White, LinearGradientMode.Horizontal))
{
Color[] colors = new Color[37];
float[] positions = new float[37];
for (int i = 0; i <= 36; i++)
{
int j = _inverted ? 36 - i : i;
colors[j] = SymbologyGlobal.ColorFromHsl(((i * 10) + _hueShift) % 360, 1, .7).ToTransparent(.7f);
positions[i] = i / 36f;
}
ColorBlend cb = new ColorBlend
{
Colors = colors,
Positions = positions
};
lgb.InterpolationColors = cb;
g.FillPath(lgb, gp);
}
g.DrawPath(Pens.Gray, gp);
}
if (Enabled)
{
LeftHandle.Draw(g);
RightHandle.Draw(g);
}
}
/// <summary>
/// Initiates slider dragging.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left && Enabled)
{
Rectangle l = LeftHandle.GetBounds();
if (l.Contains(e.Location) && LeftHandle.Visible)
{
_dx = LeftHandle.GetBounds().Right - e.X;
LeftHandle.IsDragging = true;
}
Rectangle r = RightHandle.GetBounds();
if (r.Contains(e.Location) && RightHandle.Visible)
{
_dx = e.X - RightHandle.GetBounds().Left;
RightHandle.IsDragging = true;
}
}
base.OnMouseDown(e);
}
/// <summary>
/// Handles slider dragging
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnMouseMove(MouseEventArgs e)
{
float w = Width - LeftHandle.Width;
if (RightHandle.IsDragging)
{
float x = e.X - _dx;
int min = 0;
if (LeftHandle.Visible) min = LeftHandle.Width;
if (x > w) x = w;
if (x < min) x = min;
RightHandle.Position = _min + ((x / w) * (_max - _min));
if (LeftHandle.Visible)
{
if (LeftHandle.Position > RightHandle.Position)
{
LeftHandle.Position = RightHandle.Position;
}
}
OnPositionChanging();
}
if (LeftHandle.IsDragging)
{
float x = e.X + _dx;
int max = Width;
if (RightHandle.Visible) max = Width - RightHandle.Width;
if (x > max) x = max;
if (x < 0) x = 0;
LeftHandle.Position = _min + ((x / w) * (_max - _min));
if (RightHandle.Visible)
{
if (RightHandle.Position < LeftHandle.Position)
{
RightHandle.Position = LeftHandle.Position;
}
}
OnPositionChanging();
}
Invalidate();
base.OnMouseMove(e);
}
/// <summary>
/// Handles the mouse up situation
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnMouseUp(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (RightHandle.IsDragging) RightHandle.IsDragging = false;
if (LeftHandle.IsDragging) LeftHandle.IsDragging = false;
OnPositionChanged();
}
base.OnMouseUp(e);
}
/// <summary>
/// Draw the clipped portion
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnPaint(PaintEventArgs e)
{
Rectangle clip = e.ClipRectangle;
if (clip.IsEmpty) clip = ClientRectangle;
Bitmap bmp = new Bitmap(clip.Width, clip.Height);
Graphics g = Graphics.FromImage(bmp);
g.TranslateTransform(-clip.X, -clip.Y);
g.Clip = new Region(clip);
g.Clear(BackColor);
g.SmoothingMode = SmoothingMode.AntiAlias;
OnDraw(g, clip);
g.Dispose();
e.Graphics.DrawImage(bmp, clip, new Rectangle(0, 0, clip.Width, clip.Height), GraphicsUnit.Pixel);
}
/// <summary>
/// Prevent flicker.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnPaintBackground(PaintEventArgs e)
{
}
/// <summary>
/// Fires the Position Changed event after sliders are released.
/// </summary>
protected virtual void OnPositionChanged()
{
PositionChanged?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Fires the Position Changing event while either slider is being dragged.
/// </summary>
protected virtual void OnPositionChanging()
{
PositionChanging?.Invoke(this, EventArgs.Empty);
}
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Overlays.Settings;
using osu.Game.Rulesets;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Models;
using osuTK;
namespace osu.Game.Tournament.Screens.Editors
{
public class RoundEditorScreen : TournamentEditorScreen<RoundEditorScreen.RoundRow, TournamentRound>
{
protected override BindableList<TournamentRound> Storage => LadderInfo.Rounds;
public class RoundRow : CompositeDrawable, IModelBacked<TournamentRound>
{
public TournamentRound Model { get; }
[Resolved]
private LadderInfo ladderInfo { get; set; }
public RoundRow(TournamentRound round)
{
Model = round;
Masking = true;
CornerRadius = 10;
RoundBeatmapEditor beatmapEditor = new RoundBeatmapEditor(round)
{
Width = 0.95f
};
InternalChildren = new Drawable[]
{
new Box
{
Colour = OsuColour.Gray(0.1f),
RelativeSizeAxes = Axes.Both,
},
new FillFlowContainer
{
Margin = new MarginPadding(5),
Padding = new MarginPadding { Right = 160 },
Spacing = new Vector2(5),
Direction = FillDirection.Full,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Children = new Drawable[]
{
new SettingsTextBox
{
LabelText = "Name",
Width = 0.33f,
Bindable = Model.Name
},
new SettingsTextBox
{
LabelText = "Description",
Width = 0.33f,
Bindable = Model.Description
},
new DateTextBox
{
LabelText = "Start Time",
Width = 0.33f,
Bindable = Model.StartDate
},
new SettingsSlider<int>
{
LabelText = "Best of",
Width = 0.33f,
Bindable = Model.BestOf
},
new SettingsButton
{
Width = 0.2f,
Margin = new MarginPadding(10),
Text = "Add beatmap",
Action = () => beatmapEditor.CreateNew()
},
beatmapEditor
}
},
new DangerousSettingsButton
{
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreRight,
RelativeSizeAxes = Axes.None,
Width = 150,
Text = "Delete Round",
Action = () =>
{
Expire();
ladderInfo.Rounds.Remove(Model);
},
}
};
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
}
public class RoundBeatmapEditor : CompositeDrawable
{
private readonly TournamentRound round;
private readonly FillFlowContainer flow;
public RoundBeatmapEditor(TournamentRound round)
{
this.round = round;
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
InternalChild = flow = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
LayoutDuration = 200,
LayoutEasing = Easing.OutQuint,
ChildrenEnumerable = round.Beatmaps.Select(p => new RoundBeatmapRow(round, p))
};
}
public void CreateNew()
{
var user = new RoundBeatmap();
round.Beatmaps.Add(user);
flow.Add(new RoundBeatmapRow(round, user));
}
public class RoundBeatmapRow : CompositeDrawable
{
public RoundBeatmap Model { get; }
[Resolved]
protected IAPIProvider API { get; private set; }
private readonly Bindable<string> beatmapId = new Bindable<string>();
private readonly Bindable<string> mods = new Bindable<string>();
private readonly Container drawableContainer;
public RoundBeatmapRow(TournamentRound team, RoundBeatmap beatmap)
{
Model = beatmap;
Margin = new MarginPadding(10);
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Masking = true;
CornerRadius = 5;
InternalChildren = new Drawable[]
{
new Box
{
Colour = OsuColour.Gray(0.2f),
RelativeSizeAxes = Axes.Both,
},
new FillFlowContainer
{
Margin = new MarginPadding(5),
Padding = new MarginPadding { Right = 160 },
Spacing = new Vector2(5),
Direction = FillDirection.Horizontal,
AutoSizeAxes = Axes.Both,
Children = new Drawable[]
{
new SettingsNumberBox
{
LabelText = "Beatmap ID",
RelativeSizeAxes = Axes.None,
Width = 200,
Bindable = beatmapId,
},
new SettingsTextBox
{
LabelText = "Mods",
RelativeSizeAxes = Axes.None,
Width = 200,
Bindable = mods,
},
drawableContainer = new Container
{
Size = new Vector2(100, 70),
},
}
},
new DangerousSettingsButton
{
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreRight,
RelativeSizeAxes = Axes.None,
Width = 150,
Text = "Delete Beatmap",
Action = () =>
{
Expire();
team.Beatmaps.Remove(beatmap);
},
}
};
}
[BackgroundDependencyLoader]
private void load(RulesetStore rulesets)
{
beatmapId.Value = Model.ID.ToString();
beatmapId.BindValueChanged(idString =>
{
int parsed;
int.TryParse(idString.NewValue, out parsed);
Model.ID = parsed;
if (idString.NewValue != idString.OldValue)
Model.BeatmapInfo = null;
if (Model.BeatmapInfo != null)
{
updatePanel();
return;
}
var req = new GetBeatmapRequest(new BeatmapInfo { OnlineBeatmapID = Model.ID });
req.Success += res =>
{
Model.BeatmapInfo = res.ToBeatmap(rulesets);
updatePanel();
};
req.Failure += _ =>
{
Model.BeatmapInfo = null;
updatePanel();
};
API.Queue(req);
}, true);
mods.Value = Model.Mods;
mods.BindValueChanged(modString => Model.Mods = modString.NewValue);
}
private void updatePanel()
{
drawableContainer.Clear();
if (Model.BeatmapInfo != null)
drawableContainer.Child = new TournamentBeatmapPanel(Model.BeatmapInfo, Model.Mods)
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Width = 300
};
}
}
}
}
protected override RoundRow CreateDrawable(TournamentRound model) => new RoundRow(model);
}
}
| |
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
namespace System.ServiceModel.Activation
{
using System.Collections.Generic;
using System.Configuration;
using System.Net;
using System.Runtime;
using System.Security;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Permissions;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
class AspNetEnvironment
{
static readonly object thisLock = new object();
// Double-checked locking pattern requires volatile for read/write synchronization
static volatile AspNetEnvironment current;
static bool isEnabled;
static bool? isApplicationDomainHosted;
protected AspNetEnvironment()
{
}
public static AspNetEnvironment Current
{
get
{
if (current == null)
{
lock (thisLock)
{
if (current == null)
{
current = new AspNetEnvironment();
}
}
}
return current;
}
// AspNetEnvironment.Current is set by System.ServiceModel.Activation when it is brought into memory through
// the ASP.Net hosting environment. It is the only "real" implementer of this class.
protected set
{
Fx.Assert(!isEnabled, "should only be explicitly set once");
Fx.Assert(value != null, "should only be set to a valid environment");
current = value;
isEnabled = true;
}
}
public static bool Enabled
{
get
{
return isEnabled;
}
}
public bool RequiresImpersonation
{
get
{
return AspNetCompatibilityEnabled;
}
}
public virtual bool AspNetCompatibilityEnabled
{
get
{
// subclass will check AspNetCompatibility mode
return false;
}
}
public virtual string ConfigurationPath
{
get
{
return AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
}
}
// these ideally would be replaced with public APIs
public virtual bool IsConfigurationBased
{
get
{
// subclass will check ServiceActivationElement presence
return false;
}
}
public virtual string CurrentVirtualPath
{
get
{
// subclass will use calculation from HostingManager.CreateService
return null;
}
}
public virtual string XamlFileBaseLocation
{
get
{
// subclass will use calculation from HostingManager.CreateService
return null;
}
}
public virtual bool UsingIntegratedPipeline
{
get
{
return false;
}
}
public virtual string WebSocketVersion
{
get
{
return null;
}
}
// Indicates if the WebSocket module is loaded. When IIS hosted, it throws an exception when called before we determined if the module is loaded or not.
public bool IsWebSocketModuleLoaded
{
get
{
return this.WebSocketVersion != null;
}
}
public virtual void AddHostingBehavior(ServiceHostBase serviceHost, ServiceDescription description)
{
// subclass will add HostedBindingBehavior
}
public virtual bool IsWindowsAuthenticationConfigured()
{
// subclass will check Asp.Net authentication mode
return false;
}
public virtual List<Uri> GetBaseAddresses(Uri addressTemplate)
{
// subclass will provide multiple base address support
return null;
}
// check if ((System.Web.Configuration.WebContext)configHostingContext).ApplicationLevel == WebApplicationLevel.AboveApplication
public virtual bool IsWebConfigAboveApplication(object configHostingContext)
{
// there are currently only two known implementations of HostingContext, so we are
// pretty much guaranteed to be hosted in ASP.Net here. However, it may not be
// through our BuildProvider, so we still need to do some work in the base class.
// The HostedAspNetEnvironment subclass can perform more efficiently using reflection
return SystemWebHelper.IsWebConfigAboveApplication(configHostingContext);
}
public virtual void EnsureCompatibilityRequirements(ServiceDescription description)
{
// subclass will ensure AspNetCompatibilityRequirementsAttribute is in the behaviors collection
}
public virtual bool TryGetFullVirtualPath(out string virtualPath)
{
// subclass will use the virtual path from the compiled string
virtualPath = null;
return false;
}
public virtual string GetAnnotationFromHost(ServiceHostBase host)
{
// subclass will return "Website name\Application Virtual Path|\relative service virtual path|serviceName"
return string.Empty;
}
public virtual void EnsureAllReferencedAssemblyLoaded()
{
}
public virtual BaseUriWithWildcard GetBaseUri(string transportScheme, Uri listenUri)
{
return null;
}
public virtual void ValidateHttpSettings(string virtualPath, bool isMetadataListener, bool usingDefaultSpnList, ref AuthenticationSchemes supportedSchemes, ref ExtendedProtectionPolicy extendedProtectionPolicy, ref string realm)
{
}
// returns whether or not the caller should use the hosted client certificate mapping
public virtual bool ValidateHttpsSettings(string virtualPath, ref bool requireClientCertificate)
{
return false;
}
public virtual void ProcessNotMatchedEndpointAddress(Uri uri, string endpointName)
{
// subclass will throw as appropriate for compat mode
}
public virtual void ValidateCompatibilityRequirements(AspNetCompatibilityRequirementsMode compatibilityMode)
{
// validate that hosting settings are compatible with the requested requirements
if (compatibilityMode == AspNetCompatibilityRequirementsMode.Required)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.Hosting_CompatibilityServiceNotHosted)));
}
}
public virtual IAspNetMessageProperty GetHostingProperty(Message message)
{
// subclass will gen up a HostingMessageProperty
return null;
}
public virtual IAspNetMessageProperty GetHostingProperty(Message message, bool removeFromMessage)
{
// subclass will return the hosting property from the message
// and remove it from the message's properties.
return null;
}
public virtual void PrepareMessageForDispatch(Message message)
{
// subclass will wrap ReceiveContext for Busy Count
}
public virtual void ApplyHostedContext(TransportChannelListener listener, BindingContext context)
{
// subclass will push hosted information to the transport listeners
}
internal virtual void AddMetadataBindingParameters(Uri listenUri, KeyedByTypeCollection<IServiceBehavior> serviceBehaviors, BindingParameterCollection bindingParameters)
{
bindingParameters.Add(new ServiceMetadataExtension.MetadataBindingParameter());
}
internal virtual bool IsMetadataListener(BindingParameterCollection bindingParameters)
{
return bindingParameters.Find<ServiceMetadataExtension.MetadataBindingParameter>() != null;
}
public virtual void IncrementBusyCount()
{
// subclass will increment HostingEnvironment.BusyCount
}
public virtual void DecrementBusyCount()
{
// subclass will decrement HostingEnvironment.BusyCount
}
public virtual bool TraceIncrementBusyCountIsEnabled()
{
// subclass will return true if tracing for IncrementBusyCount is enabled.
//kept as a separate check from TraceIncrementBusyCount to avoid creating source string if Tracing is not enabled.
return false;
}
public virtual bool TraceDecrementBusyCountIsEnabled()
{
// subclass will return true if tracing for DecrementBusyCount is enabled.
//kept as a separate check from TraceDecrementBusyCount to avoid creating source string if Tracing is not enabled.
return false;
}
public virtual void TraceIncrementBusyCount(string data)
{
//callers are expected to check if TraceIncrementBusyCountIsEnabled() is true
//before calling this method
// subclass will emit trace for IncrementBusyCount
// data is emitted in the Trace as the source of the call to Increment.
}
public virtual void TraceDecrementBusyCount(string data)
{
//callers are expected to check if TraceDecrementBusyCountIsEnabled() is true
//before calling this method
// subclass will emit trace for DecrementBusyCount
// data is emitted in the Trace as the source of the call to Decrement.
}
public virtual object GetConfigurationSection(string sectionPath)
{
// subclass will interact with web.config system
return ConfigurationManager.GetSection(sectionPath);
}
// Be sure to update UnsafeGetSection if you modify this method
[Fx.Tag.SecurityNote(Critical = "Uses SecurityCritical method UnsafeGetSectionFromConfigurationManager which elevates.")]
[SecurityCritical]
public virtual object UnsafeGetConfigurationSection(string sectionPath)
{
// subclass will interact with web.config system
return UnsafeGetSectionFromConfigurationManager(sectionPath);
}
public virtual AuthenticationSchemes GetAuthenticationSchemes(Uri baseAddress)
{
// subclass will grab settings from the metabase
return AuthenticationSchemes.None;
}
public virtual bool IsSimpleApplicationHost
{
get
{
// subclass will grab settings from the ServiceHostingEnvironment
return false;
}
}
[Fx.Tag.SecurityNote(Critical = "Asserts ConfigurationPermission in order to fetch config from ConfigurationManager,"
+ "caller must guard return value.")]
[SecurityCritical]
[ConfigurationPermission(SecurityAction.Assert, Unrestricted = true)]
static object UnsafeGetSectionFromConfigurationManager(string sectionPath)
{
return ConfigurationManager.GetSection(sectionPath);
}
public virtual bool IsWithinApp(string absoluteVirtualPath)
{
return true;
}
internal static bool IsApplicationDomainHosted()
{
if (!AspNetEnvironment.isApplicationDomainHosted.HasValue)
{
lock (AspNetEnvironment.thisLock)
{
if (!AspNetEnvironment.isApplicationDomainHosted.HasValue)
{
bool isApplicationDomainHosted = false;
if (AspNetEnvironment.Enabled)
{
isApplicationDomainHosted = AspNetEnvironment.IsSystemWebAssemblyLoaded();
}
AspNetEnvironment.isApplicationDomainHosted = isApplicationDomainHosted;
}
}
}
return AspNetEnvironment.isApplicationDomainHosted.Value;
}
private static bool IsSystemWebAssemblyLoaded()
{
const string systemWebName = "System.Web,";
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
if (assembly.FullName.StartsWith(systemWebName, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
}
}
| |
using System;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Xml;
using dk.nita.saml20.Schema.Protocol;
using dk.nita.saml20.Utils;
using SfwEncryptedData = dk.nita.saml20.Schema.XEnc.EncryptedData;
namespace dk.nita.saml20
{
/// <summary>
/// Handles the <code>EncryptedAssertion</code> element.
/// </summary>
public class Saml20EncryptedAssertion
{
/// <summary>
/// Whether to use OAEP (Optimal Asymmetric Encryption Padding) by default, if no EncryptionMethod is specified
/// on the <EncryptedKey> element.
/// </summary>
private const bool USE_OAEP_DEFAULT = false;
/// <summary>
/// The assertion that is stored within the encrypted assertion.
/// </summary>
private XmlDocument _assertion;
/// <summary>
/// The <code>Assertion</code> element that is embedded within the <code>EncryptedAssertion</code> element.
/// </summary>
public XmlDocument Assertion
{
get { return _assertion; }
set { _assertion = value; }
}
/// <summary>
/// The <code>EncryptedAssertion</code> element containing an <code>Assertion</code>.
/// </summary>
private XmlDocument _encryptedAssertion;
/// <summary>
/// Initializes a new instance of <code>EncryptedAssertion</code>.
/// </summary>
public Saml20EncryptedAssertion()
{}
/// <summary>
/// Initializes a new instance of <code>EncryptedAssertion</code>.
/// </summary>
/// <param name="transportKey">The transport key is used for securing the symmetric key that has encrypted the assertion.</param>
public Saml20EncryptedAssertion(RSA transportKey) : this()
{
_transportKey = transportKey;
}
/// <summary>
/// Initializes a new instance of <code>EncryptedAssertion</code>.
/// </summary>
/// <param name="transportKey">The transport key is used for securing the symmetric key that has encrypted the assertion.</param>
/// <param name="encryptedAssertion">An <code>XmlDocument</code> containing an <code>EncryptedAssertion</code> element.</param>
public Saml20EncryptedAssertion(RSA transportKey, XmlDocument encryptedAssertion) : this(transportKey)
{
LoadXml(encryptedAssertion.DocumentElement);
}
/// <summary>
/// Initializes the instance with a new <code>EncryptedAssertion</code> element.
/// </summary>
public void LoadXml(XmlElement element)
{
CheckEncryptedAssertionElement(element);
_encryptedAssertion = new XmlDocument();
_encryptedAssertion.AppendChild(_encryptedAssertion.ImportNode(element, true));
}
/// <summary>
/// Verifies that the given <code>XmlElement</code> is actually a SAML 2.0 <code>EncryptedAssertion</code> element.
/// </summary>
private static void CheckEncryptedAssertionElement(XmlElement element)
{
if (element.LocalName != EncryptedAssertion.ELEMENT_NAME)
throw new ArgumentException("The element must be of type \"EncryptedAssertion\".");
if (element.NamespaceURI != Saml20Constants.ASSERTION)
throw new ArgumentException("The element must be of type \"" + Saml20Constants.ASSERTION + "#EncryptedAssertion\".");
}
/// <summary>
/// Returns the XML representation of the encrypted assertion.
/// </summary>
public XmlDocument GetXml()
{
return _encryptedAssertion;
}
private string _sessionKeyAlgorithm = EncryptedXml.XmlEncAES256Url;
/// <summary>
/// Specifiy the algorithm to use for the session key. The algorithm is specified using the identifiers given in the
/// Xml Encryption Specification. see also http://www.w3.org/TR/xmlenc-core/#sec-Algorithms
/// The class <code>EncryptedXml</code> contains public fields with the identifiers. If nothing is
/// specified, a 256 bit AES key is used.
/// </summary>
public string SessionKeyAlgorithm
{
get { return _sessionKeyAlgorithm; }
set
{
// Validate that the URI used to identify the algorithm of the session key is probably correct. Not a complete validation, but should catch most obvious mistakes.
if (!value.StartsWith(Saml20Constants.XENC))
throw new ArgumentException("The session key algorithm must be specified using the identifying URIs listed in the specification.");
_sessionKeyAlgorithm = value;
}
}
private RSA _transportKey;
/// <summary>
/// The transport key is used for securing the symmetric key that has encrypted the assertion.
/// </summary>
public RSA TransportKey
{
set { _transportKey = value; }
get { return _transportKey; }
}
/// <summary>
/// Encrypts the Assertion in the assertion property and creates an <code>EncryptedAssertion</code> element
/// that can be retrieved using the <code>GetXml</code> method.
/// </summary>
public void Encrypt()
{
if (_transportKey == null)
throw new InvalidOperationException("The \"TransportKey\" property is required to encrypt the assertion.");
if (_assertion == null)
throw new InvalidOperationException("The \"Assertion\" property is required for this operation.");
EncryptedData encryptedData = new EncryptedData();
encryptedData.Type = EncryptedXml.XmlEncElementUrl;
encryptedData.EncryptionMethod = new EncryptionMethod(_sessionKeyAlgorithm);
// Encrypt the assertion and add it to the encryptedData instance.
EncryptedXml encryptedXml = new EncryptedXml();
byte[] encryptedElement = encryptedXml.EncryptData(_assertion.DocumentElement, SessionKey, false);
encryptedData.CipherData.CipherValue = encryptedElement;
// Add an encrypted version of the key used.
encryptedData.KeyInfo = new KeyInfo();
EncryptedKey encryptedKey = new EncryptedKey();
encryptedKey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);
encryptedKey.CipherData = new CipherData(EncryptedXml.EncryptKey(SessionKey.Key, TransportKey, false));
encryptedData.KeyInfo.AddClause(new KeyInfoEncryptedKey(encryptedKey));
// Create an empty EncryptedAssertion to hook into.
EncryptedAssertion encryptedAssertion = new EncryptedAssertion();
encryptedAssertion.encryptedData = new SfwEncryptedData();
XmlDocument result = new XmlDocument();
result.LoadXml(Serialization.SerializeToXmlString(encryptedAssertion));
XmlElement encryptedDataElement = GetElement(SfwEncryptedData.ELEMENT_NAME, Saml20Constants.XENC, result.DocumentElement);
EncryptedXml.ReplaceElement(encryptedDataElement, encryptedData, false);
_encryptedAssertion = result;
}
/// <summary>
/// Decrypts the assertion using the key given as the method parameter. The resulting assertion
/// is available through the <code>Assertion</code> property.
/// </summary>
/// <exception cref="Saml20FormatException">Thrown if it not possible to decrypt the assertion.</exception>
public void Decrypt()
{
if (TransportKey == null)
throw new InvalidOperationException("The \"TransportKey\" property must contain the asymmetric key to decrypt the assertion.");
if (_encryptedAssertion == null)
throw new InvalidOperationException("Unable to find the <EncryptedAssertion> element. Use a constructor or the LoadXml - method to set it.");
XmlElement encryptedDataElement = GetElement(SfwEncryptedData.ELEMENT_NAME, Saml20Constants.XENC, _encryptedAssertion.DocumentElement);
EncryptedData encryptedData = new EncryptedData();
encryptedData.LoadXml(encryptedDataElement);
SymmetricAlgorithm sessionKey;
if (encryptedData.EncryptionMethod != null)
{
_sessionKeyAlgorithm = encryptedData.EncryptionMethod.KeyAlgorithm;
sessionKey = ExtractSessionKey(_encryptedAssertion, encryptedData.EncryptionMethod.KeyAlgorithm);
}
else
{
sessionKey = ExtractSessionKey(_encryptedAssertion);
}
/*
* NOTE:
* The EncryptedXml class can't handle an <EncryptedData> element without an underlying <EncryptionMethod> element,
* despite the standard dictating that this is ok.
* If this becomes a problem with other IDPs, consider adding a default EncryptionMethod instance manually before decrypting.
*/
EncryptedXml encryptedXml = new EncryptedXml();
byte[] plaintext = encryptedXml.DecryptData(encryptedData, sessionKey);
_assertion = new XmlDocument();
_assertion.PreserveWhitespace = true;
try
{
_assertion.Load(new StringReader(Encoding.UTF8.GetString(plaintext)));
} catch(XmlException e)
{
_assertion = null;
throw new Saml20FormatException("Unable to parse the decrypted assertion.", e);
}
}
/// <summary>
/// An overloaded version of ExtractSessionKey that does not require a keyAlgorithm.
/// </summary>
private SymmetricAlgorithm ExtractSessionKey(XmlDocument encryptedAssertionDoc)
{
return ExtractSessionKey(encryptedAssertionDoc, string.Empty);
}
/// <summary>
/// Locates and deserializes the key used for encrypting the assertion. Searches the list of keys below the <EncryptedAssertion> element and
/// the <KeyInfo> element of the <EncryptedData> element.
/// </summary>
/// <param name="encryptedAssertionDoc"></param>
/// <param name="keyAlgorithm">The XML Encryption standard identifier for the algorithm of the session key.</param>
/// <returns>A <code>SymmetricAlgorithm</code> containing the key if it was successfully found. Null if the method was unable to locate the key.</returns>
private SymmetricAlgorithm ExtractSessionKey(XmlDocument encryptedAssertionDoc, string keyAlgorithm)
{
// Check if there are any <EncryptedKey> elements immediately below the EncryptedAssertion element.
foreach (XmlNode node in encryptedAssertionDoc.DocumentElement.ChildNodes)
if (node.LocalName == Schema.XEnc.EncryptedKey.ELEMENT_NAME && node.NamespaceURI == Saml20Constants.XENC)
{
return ToSymmetricKey((XmlElement) node, keyAlgorithm);
}
// Check if the key is embedded in the <EncryptedData> element.
XmlElement encryptedData =
GetElement(SfwEncryptedData.ELEMENT_NAME, Saml20Constants.XENC, encryptedAssertionDoc.DocumentElement);
if (encryptedData != null)
{
XmlElement encryptedKeyElement =
GetElement(Schema.XEnc.EncryptedKey.ELEMENT_NAME, Saml20Constants.XENC, encryptedAssertionDoc.DocumentElement);
if (encryptedKeyElement != null)
{
return ToSymmetricKey(encryptedKeyElement, keyAlgorithm);
}
}
throw new Saml20FormatException("Unable to locate assertion decryption key.");
}
/// <summary>
/// Extracts the key from a <EncryptedKey> element.
/// </summary>
/// <param name="encryptedKeyElement"></param>
/// <param name="keyAlgorithm"></param>
/// <returns></returns>
private SymmetricAlgorithm ToSymmetricKey(XmlElement encryptedKeyElement, string keyAlgorithm)
{
EncryptedKey encryptedKey = new EncryptedKey();
encryptedKey.LoadXml(encryptedKeyElement);
bool useOAEP = USE_OAEP_DEFAULT;
if (encryptedKey.EncryptionMethod != null)
{
if (encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl)
useOAEP = true;
else
useOAEP = false;
}
if (encryptedKey.CipherData.CipherValue != null)
{
SymmetricAlgorithm key = GetKeyInstance(keyAlgorithm);
key.Key = EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, TransportKey, useOAEP);
return key;
}
throw new NotImplementedException("Unable to decode CipherData of type \"CipherReference\".");
}
/// <summary>
/// Creates an instance of a symmetric key, based on the algorithm identifier found in the Xml Encryption standard.
/// see also http://www.w3.org/TR/xmlenc-core/#sec-Algorithms
/// </summary>
/// <param name="algorithm">A string containing one of the algorithm identifiers found in the XML Encryption standard. The class
/// <code>EncryptedXml</code> contains the identifiers as fields.</param>
private static SymmetricAlgorithm GetKeyInstance(string algorithm)
{
SymmetricAlgorithm result;
switch(algorithm)
{
case EncryptedXml.XmlEncTripleDESUrl:
result = TripleDES.Create();
break;
case EncryptedXml.XmlEncAES128Url :
result = new RijndaelManaged();
result.KeySize = 128;
break;
case EncryptedXml.XmlEncAES192Url:
result = new RijndaelManaged();
result.KeySize = 192;
break;
case EncryptedXml.XmlEncAES256Url:
result = new RijndaelManaged();
result.KeySize = 256;
break;
default :
result = new RijndaelManaged();
result.KeySize = 256;
break;
}
return result;
}
/// <summary>
/// Utility method for retrieving a single element from a document.
/// </summary>
private static XmlElement GetElement(string element, string elementNS, XmlElement doc)
{
XmlNodeList list = doc.GetElementsByTagName(element, elementNS);
if (list.Count == 0)
return null;
return (XmlElement)list[0];
}
private SymmetricAlgorithm _sessionKey;
/// <summary>
/// The key used for encrypting the <code>Assertion</code>. This key is embedded within a <code>KeyInfo</code> element
/// in the <code>EncryptedAssertion</code> element. The session key is encrypted with the <code>TransportKey</code> before
/// being embedded.
/// </summary>
private SymmetricAlgorithm SessionKey
{
get
{
if ( _sessionKey == null)
{
_sessionKey = GetKeyInstance(_sessionKeyAlgorithm);
_sessionKey.GenerateKey();
}
return _sessionKey;
}
}
/// <summary>
/// Writes the assertion to the XmlWriter.
/// </summary>
/// <param name="writer">The writer.</param>
public void WriteAssertion(XmlWriter writer)
{
_encryptedAssertion.WriteTo(writer);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
namespace Cvv.WebUtility.Mvc
{
public interface IVisitorRecord
{
}
public interface ISessionRecord
{
}
public class SessionBase<S, V> : SessionBase
where S : class, ISessionRecord
where V : class, IVisitorRecord
{
private S _sessionRecord;
private V _visitorRecord;
public S SessionRecord
{
get
{
if (_sessionRecord == null)
_sessionRecord = WebAppConfig.SessionLoggingProvider.GetSessionObject<S>(SessionId);
return _sessionRecord;
}
}
public V VisitorRecord
{
get
{
if (_visitorRecord == null)
_visitorRecord = WebAppConfig.VisitorProvider.GetVisitorObject<V>(VisitorId);
return _visitorRecord;
}
}
}
public class SessionBase
{
private readonly IHttpSessionState _httpSession = null;
private string _sessionId = null;
private string _visitorId = null;
private long _userId = 0;
private long _right = 0;
private string _languageCode = null;
private string _theme = null;
public static IHttpResponse Response { get { return WebAppContext.Response; } }
public static IHttpRequest Request { get { return WebAppContext.Request; } }
public static IHttpServerUtility Server { get { return WebAppContext.Server; } }
public static SessionBase CurrentSession
{
get { return WebAppContext.Session; }
}
public SessionBase()
{
_httpSession = HttpContextBase.Current.Session;
SessionManager.CreateSessionProperties(this);
if (IsNewSession)
{
SessionId = CreateSessionDataObject();
this["_START_TIME_"] = DateTime.Now;
if (VisitorId == null)
VisitorId = CreateVisitor();
WebAppConfig.SessionLoggingProvider.AssignVisitorToSession(SessionId, VisitorId);
DetermineLanguage();
}
}
private void DetermineLanguage()
{
string lang = null;
string langParam = WebAppContext.GetData["lang"];
if (langParam != null && langParam.Length >= 2)
{
lang = langParam;
}
if (lang != null)
{
LanguageCode = lang;
}
else
{
LanguageCode = WebAppConfig.DefaultLanguageCode;
}
}
public object this[string key]
{
get
{
if (WebAppConfig.SessionSerializer != null)
return WebAppConfig.SessionSerializer.GetSessionVariable(SessionId, key);
return _httpSession[key];
}
set
{
if (WebAppConfig.SessionSerializer != null)
WebAppConfig.SessionSerializer.SetSessionVariable(SessionId, key, value);
else
_httpSession[key] = value;
}
}
public bool IsNewSession
{
get { return _httpSession.IsNewSession; }
}
public string InternalSessionID
{
get { return _httpSession.SessionID; }
}
private static void SetCookie(string cookieName, string cookieValue, bool permanent)
{
if (Response.Cookies[cookieName] != null)
Response.Cookies[cookieName].Value = cookieValue;
else
Response.Cookies.Add(new HttpCookie(cookieName, cookieValue));
if (permanent)
Response.Cookies[cookieName].Expires = DateTime.Now.AddYears(10);
}
private static string GetCookie(string cookieName)
{
HttpCookie httpCookie = Request.Cookies[cookieName];
if (httpCookie == null)
return null;
else
return httpCookie.Value;
}
public string SessionId
{
get
{
if (_sessionId == null)
_sessionId = GetCookie("_SESSIONID_");
return _sessionId;
}
set
{
SetCookie("_SESSIONID_", value, false);
_sessionId = value;
}
}
public string LanguageCode
{
get
{
if (_languageCode == null)
{
_languageCode = GetCookie("LANG");
if (_languageCode == null || _languageCode.Length < 2)
{
return (string)this["_LANG_"];
}
}
return _languageCode;
}
set
{
this["_LANG_"] = value;
SetCookie("LANG", value, true);
_languageCode = value;
}
}
public string Theme
{
get
{
if (_theme == null)
{
_theme = GetCookie("THEME");
if (string.IsNullOrEmpty(_theme))
{
return (string)this["_THEME_"];
}
}
return _theme;
}
set
{
this["_THEME_"] = value;
SetCookie("THEME", value, true);
_theme = value;
}
}
public string VisitorId
{
get
{
if (_visitorId == null)
_visitorId = GetCookie("_VISITORID_");
return _visitorId;
}
set
{
if (value != null)
{
SetCookie("_VISITORID_", value, true);
WebAppConfig.SessionLoggingProvider.AssignVisitorToSession(SessionId, value);
}
_visitorId = value;
}
}
public long UserId
{
get
{
if (_userId == 0)
{
if (this["_USER_ID_"] is long)
_userId = (long)this["_USER_ID_"];
}
return _userId;
}
internal set
{
this["_USER_ID_"] = value;
if (value > 0)
WebAppConfig.SessionLoggingProvider.AssignUserToSession(SessionId, UserId);
_userId = value;
}
}
public long Right
{
get
{
if (_right == 0)
{
if (this["_RIGHT_"] is long)
_right = (long)this["_RIGHT_"];
}
return _right;
}
internal set
{
this["_RIGHT_"] = value;
_right = value;
}
}
public DateTime LogonTime
{
get { return (DateTime)this["_START_TIME_"]; }
}
private static string CreateSessionDataObject()
{
return WebAppConfig.SessionLoggingProvider.CreateSession(Request.UrlReferrer == null ? "" : Request.UrlReferrer.OriginalString, Request.UserHostAddress, Request.UserAgent);
}
private static string CreateVisitor()
{
return WebAppConfig.VisitorProvider.CreateVisitor();
}
public virtual void OnSessionCreated()
{
}
}
}
| |
/*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// Represents the view settings in a folder search operation.
/// </summary>
public sealed class SeekToConditionItemView : ViewBase
{
private int pageSize;
private ItemTraversal traversal;
private SearchFilter condition;
private OffsetBasePoint offsetBasePoint = OffsetBasePoint.Beginning;
private OrderByCollection orderBy = new OrderByCollection();
private ServiceObjectType serviceObjType;
/// <summary>
/// Gets the type of service object this view applies to.
/// </summary>
/// <returns>A ServiceObjectType value.</returns>
internal override ServiceObjectType GetServiceObjectType()
{
return this.serviceObjType;
}
/// <summary>
/// Sets the type of service object this view applies to.
/// </summary>
/// <param name="objType">Service object type</param>
internal void SetServiceObjectType(ServiceObjectType objType)
{
this.serviceObjType = objType;
}
/// <summary>
/// Writes the attributes to XML.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void WriteAttributesToXml(EwsServiceXmlWriter writer)
{
if (this.serviceObjType == ServiceObjectType.Item)
{
writer.WriteAttributeValue(XmlAttributeNames.Traversal, this.Traversal);
}
}
/// <summary>
/// Gets the name of the view XML element.
/// </summary>
/// <returns>XML element name.</returns>
internal override string GetViewXmlElementName()
{
return XmlElementNames.SeekToConditionPageItemView;
}
/// <summary>
/// Validates this view.
/// </summary>
/// <param name="request">The request using this view.</param>
internal override void InternalValidate(ServiceRequestBase request)
{
base.InternalValidate(request);
}
/// <summary>
/// Write to XML.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void InternalWriteViewToXml(EwsServiceXmlWriter writer)
{
base.InternalWriteViewToXml(writer);
writer.WriteAttributeValue(XmlAttributeNames.BasePoint, this.OffsetBasePoint);
if (this.Condition != null)
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.Condition);
this.Condition.WriteToXml(writer);
writer.WriteEndElement(); // Restriction
}
}
/// <summary>
/// Internals the write search settings to XML.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="groupBy">The group by.</param>
internal override void InternalWriteSearchSettingsToXml(EwsServiceXmlWriter writer, Grouping groupBy)
{
if (groupBy != null)
{
groupBy.WriteToXml(writer);
}
}
/// <summary>
/// Gets the maximum number of items or folders the search operation should return.
/// </summary>
/// <returns>The maximum number of items that should be returned by the search operation.</returns>
internal override int? GetMaxEntriesReturned()
{
return this.PageSize;
}
/// <summary>
/// Writes OrderBy property to XML.
/// </summary>
/// <param name="writer">The writer</param>
internal override void WriteOrderByToXml(EwsServiceXmlWriter writer)
{
this.orderBy.WriteToXml(writer, XmlElementNames.SortOrder);
}
/// <summary>
/// Writes to XML.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="groupBy">The group by clause.</param>
internal override void WriteToXml(EwsServiceXmlWriter writer, Grouping groupBy)
{
if (this.serviceObjType == ServiceObjectType.Item)
{
this.GetPropertySetOrDefault().WriteToXml(writer, this.GetServiceObjectType());
}
writer.WriteStartElement(XmlNamespace.Messages, this.GetViewXmlElementName());
this.InternalWriteViewToXml(writer);
writer.WriteEndElement(); // this.GetViewXmlElementName()
}
/// <summary>
/// Initializes a new instance of the <see cref="SeekToConditionItemView"/> class.
/// </summary>
/// <param name="condition">Condition to be used when seeking.</param>
/// <param name="pageSize">The maximum number of elements the search operation should return.</param>
public SeekToConditionItemView(SearchFilter condition, int pageSize)
{
this.Condition = condition;
this.PageSize = pageSize;
this.serviceObjType = ServiceObjectType.Item;
}
/// <summary>
/// Initializes a new instance of the <see cref="SeekToConditionItemView"/> class.
/// </summary>
/// <param name="condition">Condition to be used when seeking.</param>
/// <param name="pageSize">The maximum number of elements the search operation should return.</param>
/// <param name="offsetBasePoint">The base point of the offset.</param>
public SeekToConditionItemView(
SearchFilter condition,
int pageSize,
OffsetBasePoint offsetBasePoint)
: this(condition, pageSize)
{
this.OffsetBasePoint = offsetBasePoint;
}
/// <summary>
/// The maximum number of items or folders the search operation should return.
/// </summary>
public int PageSize
{
get
{
return this.pageSize;
}
set
{
if (value <= 0)
{
throw new ArgumentException(Strings.ValueMustBeGreaterThanZero);
}
this.pageSize = value;
}
}
/// <summary>
/// Gets or sets the base point of the offset.
/// </summary>
public OffsetBasePoint OffsetBasePoint
{
get { return this.offsetBasePoint; }
set { this.offsetBasePoint = value; }
}
/// <summary>
/// Gets or sets the condition for seek. Available search filter classes include SearchFilter.IsEqualTo,
/// SearchFilter.ContainsSubstring and SearchFilter.SearchFilterCollection. If SearchFilter
/// is null, no search filters are applied.
/// </summary>
public SearchFilter Condition
{
get
{
return this.condition;
}
set
{
if (value == null)
{
throw new ArgumentNullException("Condition");
}
this.condition = value;
}
}
/// <summary>
/// Gets or sets the search traversal mode. Defaults to ItemTraversal.Shallow.
/// </summary>
public ItemTraversal Traversal
{
get { return this.traversal; }
set { this.traversal = value; }
}
/// <summary>
/// Gets the properties against which the returned items should be ordered.
/// </summary>
public OrderByCollection OrderBy
{
get { return this.orderBy; }
}
}
}
| |
//----------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime;
using System.Runtime.InteropServices;
//using System.Runtime.Remoting.Messaging;
using System.Security.Authentication.ExtendedProtection;
using System.ServiceModel;
using System.ServiceModel.Diagnostics.Application;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Security;
using ServiceModelActivity = System.ServiceModel.Diagnostics.ServiceModelActivity;
using TraceUtility = System.ServiceModel.Diagnostics.TraceUtility;
sealed class SecurityChannelFactory<TChannel>
: LayeredChannelFactory<TChannel>
{
ChannelBuilder channelBuilder;
SecurityProtocolFactory securityProtocolFactory;
SecuritySessionClientSettings<TChannel> sessionClientSettings;
bool sessionMode;
MessageVersion messageVersion;
ISecurityCapabilities securityCapabilities;
public SecurityChannelFactory(ISecurityCapabilities securityCapabilities, BindingContext context,
SecuritySessionClientSettings<TChannel> sessionClientSettings)
: this(securityCapabilities, context, sessionClientSettings.ChannelBuilder, sessionClientSettings.CreateInnerChannelFactory())
{
this.sessionMode = true;
this.sessionClientSettings = sessionClientSettings;
}
public SecurityChannelFactory(ISecurityCapabilities securityCapabilities, BindingContext context, ChannelBuilder channelBuilder, SecurityProtocolFactory protocolFactory)
: this(securityCapabilities, context, channelBuilder, protocolFactory, channelBuilder.BuildChannelFactory<TChannel>())
{
}
public SecurityChannelFactory(ISecurityCapabilities securityCapabilities, BindingContext context, ChannelBuilder channelBuilder, SecurityProtocolFactory protocolFactory, IChannelFactory innerChannelFactory)
: this(securityCapabilities, context, channelBuilder, innerChannelFactory)
{
this.securityProtocolFactory = protocolFactory;
}
SecurityChannelFactory(ISecurityCapabilities securityCapabilities, BindingContext context, ChannelBuilder channelBuilder, IChannelFactory innerChannelFactory)
: base(context.Binding, innerChannelFactory)
{
this.channelBuilder = channelBuilder;
this.messageVersion = context.Binding.MessageVersion;
this.securityCapabilities = securityCapabilities;
}
// used by internal test code
internal SecurityChannelFactory(Binding binding, SecurityProtocolFactory protocolFactory, IChannelFactory innerChannelFactory)
: base(binding, innerChannelFactory)
{
this.securityProtocolFactory = protocolFactory;
}
public ChannelBuilder ChannelBuilder
{
get
{
return this.channelBuilder;
}
}
public SecurityProtocolFactory SecurityProtocolFactory
{
get
{
return this.securityProtocolFactory;
}
}
public SecuritySessionClientSettings<TChannel> SessionClientSettings
{
get
{
Fx.Assert(SessionMode == true, "SessionClientSettings can only be used if SessionMode == true");
return this.sessionClientSettings;
}
}
public bool SessionMode
{
get
{
return this.sessionMode;
}
}
bool SupportsDuplex
{
get
{
ThrowIfProtocolFactoryNotSet();
return this.securityProtocolFactory.SupportsDuplex;
}
}
bool SupportsRequestReply
{
get
{
ThrowIfProtocolFactoryNotSet();
return this.securityProtocolFactory.SupportsRequestReply;
}
}
public MessageVersion MessageVersion
{
get
{
return this.messageVersion;
}
}
void CloseProtocolFactory(bool aborted, TimeSpan timeout)
{
if (this.securityProtocolFactory != null && !this.SessionMode)
{
this.securityProtocolFactory.Close(aborted, timeout);
this.securityProtocolFactory = null;
}
}
public override T GetProperty<T>()
{
if (this.SessionMode && (typeof(T) == typeof(IChannelSecureConversationSessionSettings)))
{
return (T)(object)this.SessionClientSettings;
}
else if (typeof(T) == typeof(ISecurityCapabilities))
{
return (T)(object)this.securityCapabilities;
}
return base.GetProperty<T>();
}
protected override void OnAbort()
{
base.OnAbort();
CloseProtocolFactory(true, TimeSpan.Zero);
if (this.sessionClientSettings != null)
{
this.sessionClientSettings.Abort();
}
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
List<OperationWithTimeoutBeginCallback> begins = new List<OperationWithTimeoutBeginCallback>();
List<OperationEndCallback> ends = new List<OperationEndCallback>();
begins.Add(new OperationWithTimeoutBeginCallback(base.OnBeginClose));
ends.Add(new OperationEndCallback(base.OnEndClose));
if (this.securityProtocolFactory != null && !this.SessionMode)
{
begins.Add(new OperationWithTimeoutBeginCallback(this.securityProtocolFactory.BeginClose));
ends.Add(new OperationEndCallback(this.securityProtocolFactory.EndClose));
}
if (this.sessionClientSettings != null)
{
begins.Add(new OperationWithTimeoutBeginCallback(this.sessionClientSettings.BeginClose));
ends.Add(new OperationEndCallback(this.sessionClientSettings.EndClose));
}
return OperationWithTimeoutComposer.BeginComposeAsyncOperations(timeout, begins.ToArray(), ends.ToArray(), callback, state);
}
protected override void OnEndClose(IAsyncResult result)
{
OperationWithTimeoutComposer.EndComposeAsyncOperations(result);
}
protected override void OnClose(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
base.OnClose(timeout);
CloseProtocolFactory(false, timeoutHelper.RemainingTime());
if (this.sessionClientSettings != null)
{
this.sessionClientSettings.Close(timeoutHelper.RemainingTime());
}
}
protected override TChannel OnCreateChannel(EndpointAddress address, Uri via)
{
ThrowIfDisposed();
if (this.SessionMode)
{
return this.sessionClientSettings.OnCreateChannel(address, via);
}
if (typeof(TChannel) == typeof(IOutputChannel))
{
return (TChannel)(object)new SecurityOutputChannel(this, this.securityProtocolFactory, ((IChannelFactory<IOutputChannel>)this.InnerChannelFactory).CreateChannel(address, via), address, via);
}
else if (typeof(TChannel) == typeof(IOutputSessionChannel))
{
return (TChannel)(object)new SecurityOutputSessionChannel(this, this.securityProtocolFactory, ((IChannelFactory<IOutputSessionChannel>)this.InnerChannelFactory).CreateChannel(address, via), address, via);
}
else if (typeof(TChannel) == typeof(IDuplexChannel))
{
return (TChannel)(object)new SecurityDuplexChannel(this, this.securityProtocolFactory, ((IChannelFactory<IDuplexChannel>)this.InnerChannelFactory).CreateChannel(address, via), address, via);
}
else if (typeof(TChannel) == typeof(IDuplexSessionChannel))
{
return (TChannel)(object)new SecurityDuplexSessionChannel(this, this.securityProtocolFactory, ((IChannelFactory<IDuplexSessionChannel>)this.InnerChannelFactory).CreateChannel(address, via), address, via);
}
else if (typeof(TChannel) == typeof(IRequestChannel))
{
return (TChannel)(object)new SecurityRequestChannel(this, this.securityProtocolFactory, ((IChannelFactory<IRequestChannel>)this.InnerChannelFactory).CreateChannel(address, via), address, via);
}
//typeof(TChannel) == typeof(IRequestSessionChannel)
return (TChannel)(object)new SecurityRequestSessionChannel(this, this.securityProtocolFactory, ((IChannelFactory<IRequestSessionChannel>)this.InnerChannelFactory).CreateChannel(address, via), address, via);
}
protected override void OnOpen(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
OnOpenCore(timeoutHelper.RemainingTime());
base.OnOpen(timeoutHelper.RemainingTime());
this.SetBufferManager();
}
void SetBufferManager()
{
ITransportFactorySettings transportSettings = this.GetProperty<ITransportFactorySettings>();
if (transportSettings == null)
return;
BufferManager bufferManager = transportSettings.BufferManager;
if (bufferManager == null)
return;
if (this.SessionMode && this.SessionClientSettings != null && this.SessionClientSettings.SessionProtocolFactory != null)
{
this.SessionClientSettings.SessionProtocolFactory.StreamBufferManager = bufferManager;
}
else
{
ThrowIfProtocolFactoryNotSet();
this.securityProtocolFactory.StreamBufferManager = bufferManager;
}
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return new OperationWithTimeoutAsyncResult(new OperationWithTimeoutCallback(this.OnOpen), timeout, callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
OperationWithTimeoutAsyncResult.End(result);
}
void OnOpenCore(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (this.SessionMode)
{
this.SessionClientSettings.Open(this, this.InnerChannelFactory, this.ChannelBuilder, timeoutHelper.RemainingTime());
}
else
{
ThrowIfProtocolFactoryNotSet();
this.securityProtocolFactory.Open(true, timeoutHelper.RemainingTime());
}
}
void ThrowIfDuplexNotSupported()
{
if (!this.SupportsDuplex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.SecurityProtocolFactoryDoesNotSupportDuplex, this.securityProtocolFactory)));
}
}
void ThrowIfProtocolFactoryNotSet()
{
if (this.securityProtocolFactory == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.SecurityProtocolFactoryShouldBeSetBeforeThisOperation)));
}
}
void ThrowIfRequestReplyNotSupported()
{
if (!this.SupportsRequestReply)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.SecurityProtocolFactoryDoesNotSupportRequestReply, this.securityProtocolFactory)));
}
}
abstract class ClientSecurityChannel<UChannel> : SecurityChannel<UChannel>
where UChannel : class, IChannel
{
EndpointAddress to;
Uri via;
SecurityProtocolFactory securityProtocolFactory;
ChannelParameterCollection channelParameters;
protected ClientSecurityChannel(ChannelManagerBase factory, SecurityProtocolFactory securityProtocolFactory,
UChannel innerChannel, EndpointAddress to, Uri via)
: base(factory, innerChannel)
{
this.to = to;
this.via = via;
this.securityProtocolFactory = securityProtocolFactory;
this.channelParameters = new ChannelParameterCollection(this);
}
protected SecurityProtocolFactory SecurityProtocolFactory
{
get { return this.securityProtocolFactory; }
}
public EndpointAddress RemoteAddress
{
get { return this.to; }
}
public Uri Via
{
get { return this.via; }
}
protected bool TryGetSecurityFaultException(Message faultMessage, out Exception faultException)
{
faultException = null;
if (!faultMessage.IsFault)
{
return false;
}
MessageFault fault = MessageFault.CreateFault(faultMessage, TransportDefaults.MaxSecurityFaultSize);
faultException = SecurityUtils.CreateSecurityFaultException(fault);
return true;
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
EnableChannelBindingSupport();
return new OpenAsyncResult(this, timeout, callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
OpenAsyncResult.End(result);
}
protected override void OnOpen(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
EnableChannelBindingSupport();
SecurityProtocol securityProtocol = this.SecurityProtocolFactory.CreateSecurityProtocol(
this.to,
this.Via,
null,
typeof(TChannel) == typeof(IRequestChannel),
timeoutHelper.RemainingTime());
OnProtocolCreationComplete(securityProtocol);
this.SecurityProtocol.Open(timeoutHelper.RemainingTime());
base.OnOpen(timeoutHelper.RemainingTime());
}
void EnableChannelBindingSupport()
{
if (this.securityProtocolFactory != null && this.securityProtocolFactory.ExtendedProtectionPolicy != null && this.securityProtocolFactory.ExtendedProtectionPolicy.CustomChannelBinding != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ExtendedProtectionPolicyCustomChannelBindingNotSupported)));
}
// Do not enable channel binding if there is no reason as it sets up chunking mode.
if ((SecurityUtils.IsChannelBindingDisabled) || (!SecurityUtils.IsSecurityBindingSuitableForChannelBinding(this.SecurityProtocolFactory.SecurityBindingElement as TransportSecurityBindingElement)))
return;
if (InnerChannel != null)
{
IChannelBindingProvider cbp = InnerChannel.GetProperty<IChannelBindingProvider>();
if (cbp != null)
{
cbp.EnableChannelBindingSupport();
}
}
}
void OnProtocolCreationComplete(SecurityProtocol securityProtocol)
{
this.SecurityProtocol = securityProtocol;
this.SecurityProtocol.ChannelParameters = this.channelParameters;
}
public override T GetProperty<T>()
{
if (typeof(T) == typeof(ChannelParameterCollection))
{
return (T)(object)this.channelParameters;
}
return base.GetProperty<T>();
}
sealed class OpenAsyncResult : AsyncResult
{
readonly ClientSecurityChannel<UChannel> clientChannel;
TimeoutHelper timeoutHelper;
static readonly AsyncCallback openInnerChannelCallback = Fx.ThunkCallback(new AsyncCallback(OpenInnerChannelCallback));
static readonly AsyncCallback openSecurityProtocolCallback = Fx.ThunkCallback(new AsyncCallback(OpenSecurityProtocolCallback));
public OpenAsyncResult(ClientSecurityChannel<UChannel> clientChannel, TimeSpan timeout,
AsyncCallback callback, object state)
: base(callback, state)
{
this.timeoutHelper = new TimeoutHelper(timeout);
this.clientChannel = clientChannel;
SecurityProtocol securityProtocol = this.clientChannel.SecurityProtocolFactory.CreateSecurityProtocol(this.clientChannel.to,
this.clientChannel.Via,
null, typeof(TChannel) == typeof(IRequestChannel), timeoutHelper.RemainingTime());
bool completeSelf = this.OnCreateSecurityProtocolComplete(securityProtocol);
if (completeSelf)
{
Complete(true);
}
}
internal static void End(IAsyncResult result)
{
AsyncResult.End<OpenAsyncResult>(result);
}
bool OnCreateSecurityProtocolComplete(SecurityProtocol securityProtocol)
{
this.clientChannel.OnProtocolCreationComplete(securityProtocol);
IAsyncResult result = securityProtocol.BeginOpen(timeoutHelper.RemainingTime(), openSecurityProtocolCallback, this);
if (!result.CompletedSynchronously)
{
return false;
}
securityProtocol.EndOpen(result);
return this.OnSecurityProtocolOpenComplete();
}
static void OpenSecurityProtocolCallback(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
OpenAsyncResult self = result.AsyncState as OpenAsyncResult;
if (self == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.InvalidAsyncResult), "result"));
}
Exception completionException = null;
bool completeSelf = false;
try
{
self.clientChannel.SecurityProtocol.EndOpen(result);
completeSelf = self.OnSecurityProtocolOpenComplete();
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completionException = e;
completeSelf = true;
}
if (completeSelf)
{
self.Complete(false, completionException);
}
}
bool OnSecurityProtocolOpenComplete()
{
IAsyncResult result = this.clientChannel.InnerChannel.BeginOpen(this.timeoutHelper.RemainingTime(), openInnerChannelCallback, this);
if (!result.CompletedSynchronously)
{
return false;
}
this.clientChannel.InnerChannel.EndOpen(result);
return true;
}
static void OpenInnerChannelCallback(IAsyncResult result)
{
if (result == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("result"));
}
if (result.CompletedSynchronously)
{
return;
}
OpenAsyncResult self = result.AsyncState as OpenAsyncResult;
if (self == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.InvalidAsyncResult), "result"));
}
Exception completionException = null;
try
{
self.clientChannel.InnerChannel.EndOpen(result);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completionException = e;
}
self.Complete(false, completionException);
}
}
}
class SecurityOutputChannel : ClientSecurityChannel<IOutputChannel>, IOutputChannel
{
public SecurityOutputChannel(ChannelManagerBase factory, SecurityProtocolFactory securityProtocolFactory, IOutputChannel innerChannel, EndpointAddress to, Uri via)
: base(factory, securityProtocolFactory, innerChannel, to, via)
{
}
public IAsyncResult BeginSend(Message message, AsyncCallback callback, object state)
{
return this.BeginSend(message, this.DefaultSendTimeout, callback, state);
}
public IAsyncResult BeginSend(Message message, TimeSpan timeout, AsyncCallback callback, object state)
{
ThrowIfFaulted();
ThrowIfDisposedOrNotOpen(message);
return new OutputChannelSendAsyncResult(message, this.SecurityProtocol, this.InnerChannel, timeout, callback, state);
}
public void EndSend(IAsyncResult result)
{
OutputChannelSendAsyncResult.End(result);
}
public void Send(Message message)
{
this.Send(message, this.DefaultSendTimeout);
}
public void Send(Message message, TimeSpan timeout)
{
ThrowIfFaulted();
ThrowIfDisposedOrNotOpen(message);
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
this.SecurityProtocol.SecureOutgoingMessage(ref message, timeoutHelper.RemainingTime());
this.InnerChannel.Send(message, timeoutHelper.RemainingTime());
}
}
sealed class SecurityOutputSessionChannel : SecurityOutputChannel, IOutputSessionChannel
{
public SecurityOutputSessionChannel(ChannelManagerBase factory, SecurityProtocolFactory securityProtocolFactory, IOutputSessionChannel innerChannel, EndpointAddress to, Uri via)
: base(factory, securityProtocolFactory, innerChannel, to, via)
{
}
public IOutputSession Session
{
get
{
return ((IOutputSessionChannel)this.InnerChannel).Session;
}
}
}
class SecurityRequestChannel : ClientSecurityChannel<IRequestChannel>, IRequestChannel
{
public SecurityRequestChannel(ChannelManagerBase factory, SecurityProtocolFactory securityProtocolFactory, IRequestChannel innerChannel, EndpointAddress to, Uri via)
: base(factory, securityProtocolFactory, innerChannel, to, via)
{
}
public IAsyncResult BeginRequest(Message message, AsyncCallback callback, object state)
{
return this.BeginRequest(message, this.DefaultSendTimeout, callback, state);
}
public IAsyncResult BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, object state)
{
ThrowIfFaulted();
ThrowIfDisposedOrNotOpen(message);
return new RequestChannelSendAsyncResult(message, this.SecurityProtocol, this.InnerChannel, this, timeout, callback, state);
}
public Message EndRequest(IAsyncResult result)
{
return RequestChannelSendAsyncResult.End(result);
}
public Message Request(Message message)
{
return this.Request(message, this.DefaultSendTimeout);
}
internal Message ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout)
{
if (reply != null)
{
if (DiagnosticUtility.ShouldUseActivity)
{
ServiceModelActivity replyActivity = TraceUtility.ExtractActivity(reply);
if (replyActivity != null &&
correlationState != null &&
correlationState.Activity != null &&
replyActivity.Id != correlationState.Activity.Id)
{
using (ServiceModelActivity.BoundOperation(replyActivity))
{
if (null != FxTrace.Trace)
{
FxTrace.Trace.TraceTransfer(correlationState.Activity.Id);
}
replyActivity.Stop();
}
}
}
ServiceModelActivity activity = correlationState == null ? null : correlationState.Activity;
using (ServiceModelActivity.BoundOperation(activity))
{
if (DiagnosticUtility.ShouldUseActivity)
{
TraceUtility.SetActivity(reply, activity);
}
Message unverifiedMessage = reply;
Exception faultException = null;
try
{
this.SecurityProtocol.VerifyIncomingMessage(ref reply, timeout, correlationState);
}
catch (MessageSecurityException)
{
TryGetSecurityFaultException(unverifiedMessage, out faultException);
if (faultException == null)
{
throw;
}
}
if (faultException != null)
{
this.Fault(faultException);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(faultException);
}
}
}
return reply;
}
public Message Request(Message message, TimeSpan timeout)
{
ThrowIfFaulted();
ThrowIfDisposedOrNotOpen(message);
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
SecurityProtocolCorrelationState correlationState = this.SecurityProtocol.SecureOutgoingMessage(ref message, timeoutHelper.RemainingTime(), null);
Message reply = this.InnerChannel.Request(message, timeoutHelper.RemainingTime());
return ProcessReply(reply, correlationState, timeoutHelper.RemainingTime());
}
}
sealed class SecurityRequestSessionChannel : SecurityRequestChannel, IRequestSessionChannel
{
public SecurityRequestSessionChannel(ChannelManagerBase factory, SecurityProtocolFactory securityProtocolFactory, IRequestSessionChannel innerChannel, EndpointAddress to, Uri via)
: base(factory, securityProtocolFactory, innerChannel, to, via)
{
}
public IOutputSession Session
{
get
{
return ((IRequestSessionChannel)this.InnerChannel).Session;
}
}
}
class SecurityDuplexChannel : SecurityOutputChannel, IDuplexChannel
{
public SecurityDuplexChannel(ChannelManagerBase factory, SecurityProtocolFactory securityProtocolFactory, IDuplexChannel innerChannel, EndpointAddress to, Uri via)
: base(factory, securityProtocolFactory, innerChannel, to, via)
{
}
internal IDuplexChannel InnerDuplexChannel
{
get { return (IDuplexChannel)this.InnerChannel; }
}
public EndpointAddress LocalAddress
{
get
{
return this.InnerDuplexChannel.LocalAddress;
}
}
internal virtual bool AcceptUnsecuredFaults
{
get { return false; }
}
public Message Receive()
{
return this.Receive(this.DefaultReceiveTimeout);
}
public Message Receive(TimeSpan timeout)
{
return InputChannel.HelpReceive(this, timeout);
}
public IAsyncResult BeginReceive(AsyncCallback callback, object state)
{
return this.BeginReceive(this.DefaultReceiveTimeout, callback, state);
}
public IAsyncResult BeginReceive(TimeSpan timeout, AsyncCallback callback, object state)
{
return InputChannel.HelpBeginReceive(this, timeout, callback, state);
}
public Message EndReceive(IAsyncResult result)
{
return InputChannel.HelpEndReceive(result);
}
public virtual IAsyncResult BeginTryReceive(TimeSpan timeout, AsyncCallback callback, object state)
{
if (DoneReceivingInCurrentState())
{
return new DoneReceivingAsyncResult(callback, state);
}
ClientDuplexReceiveMessageAndVerifySecurityAsyncResult result =
new ClientDuplexReceiveMessageAndVerifySecurityAsyncResult(this, this.InnerDuplexChannel, timeout, callback, state);
result.Start();
return result;
}
public virtual bool EndTryReceive(IAsyncResult result, out Message message)
{
DoneReceivingAsyncResult doneRecevingResult = result as DoneReceivingAsyncResult;
if (doneRecevingResult != null)
{
return DoneReceivingAsyncResult.End(doneRecevingResult, out message);
}
return ClientDuplexReceiveMessageAndVerifySecurityAsyncResult.End(result, out message);
}
internal Message ProcessMessage(Message message, TimeSpan timeout)
{
if (message == null)
{
return null;
}
Message unverifiedMessage = message;
Exception faultException = null;
try
{
this.SecurityProtocol.VerifyIncomingMessage(ref message, timeout);
}
catch (MessageSecurityException)
{
TryGetSecurityFaultException(unverifiedMessage, out faultException);
if (faultException == null)
{
throw;
}
}
if (faultException != null)
{
if (AcceptUnsecuredFaults)
{
Fault(faultException);
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(faultException);
}
return message;
}
public bool TryReceive(TimeSpan timeout, out Message message)
{
if (DoneReceivingInCurrentState())
{
message = null;
return true;
}
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (!this.InnerDuplexChannel.TryReceive(timeoutHelper.RemainingTime(), out message))
{
return false;
}
message = ProcessMessage(message, timeoutHelper.RemainingTime());
return true;
}
public bool WaitForMessage(TimeSpan timeout)
{
return this.InnerDuplexChannel.WaitForMessage(timeout);
}
public IAsyncResult BeginWaitForMessage(TimeSpan timeout, AsyncCallback callback, object state)
{
return this.InnerDuplexChannel.BeginWaitForMessage(timeout, callback, state);
}
public bool EndWaitForMessage(IAsyncResult result)
{
return this.InnerDuplexChannel.EndWaitForMessage(result);
}
}
sealed class SecurityDuplexSessionChannel : SecurityDuplexChannel, IDuplexSessionChannel
{
public SecurityDuplexSessionChannel(ChannelManagerBase factory, SecurityProtocolFactory securityProtocolFactory, IDuplexSessionChannel innerChannel, EndpointAddress to, Uri via)
: base(factory, securityProtocolFactory, innerChannel, to, via)
{
}
public IDuplexSession Session
{
get
{
return ((IDuplexSessionChannel)this.InnerChannel).Session;
}
}
internal override bool AcceptUnsecuredFaults
{
get { return true; }
}
}
sealed class RequestChannelSendAsyncResult : ApplySecurityAndSendAsyncResult<IRequestChannel>
{
Message reply;
SecurityRequestChannel securityChannel;
public RequestChannelSendAsyncResult(Message message, SecurityProtocol protocol, IRequestChannel channel, SecurityRequestChannel securityChannel, TimeSpan timeout,
AsyncCallback callback, object state)
: base(protocol, channel, timeout, callback, state)
{
this.securityChannel = securityChannel;
this.Begin(message, null);
}
protected override IAsyncResult BeginSendCore(IRequestChannel channel, Message message, TimeSpan timeout, AsyncCallback callback, object state)
{
return channel.BeginRequest(message, timeout, callback, state);
}
internal static Message End(IAsyncResult result)
{
RequestChannelSendAsyncResult self = result as RequestChannelSendAsyncResult;
OnEnd(self);
return self.reply;
}
protected override void EndSendCore(IRequestChannel channel, IAsyncResult result)
{
this.reply = channel.EndRequest(result);
}
protected override void OnSendCompleteCore(TimeSpan timeout)
{
this.reply = securityChannel.ProcessReply(reply, this.CorrelationState, timeout);
}
}
class ClientDuplexReceiveMessageAndVerifySecurityAsyncResult : ReceiveMessageAndVerifySecurityAsyncResultBase
{
SecurityDuplexChannel channel;
public ClientDuplexReceiveMessageAndVerifySecurityAsyncResult(SecurityDuplexChannel channel, IDuplexChannel innerChannel, TimeSpan timeout, AsyncCallback callback, object state)
: base(innerChannel, timeout, callback, state)
{
this.channel = channel;
}
protected override bool OnInnerReceiveDone(ref Message message, TimeSpan timeout)
{
message = this.channel.ProcessMessage(message, timeout);
return true;
}
}
}
}
| |
using UnityEngine;
using System.Collections;
[ExecuteInEditMode] // Make water live-update even when not in play mode
public class Water : MonoBehaviour
{
public enum WaterMode {
Simple = 0,
Reflective = 1,
Refractive = 2,
};
public WaterMode m_WaterMode = WaterMode.Refractive;
public bool m_DisablePixelLights = true;
public bool m_DisableTreesAndDetails = true;
public int m_TextureSize = 256;
public float m_ClipPlaneOffset = 0.07f;
public LayerMask m_ReflectLayers = -1;
public LayerMask m_RefractLayers = -1;
public Terrain terrain;
private Hashtable m_ReflectionCameras = new Hashtable(); // Camera -> Camera table
private Hashtable m_RefractionCameras = new Hashtable(); // Camera -> Camera table
private RenderTexture m_ReflectionTexture = null;
private RenderTexture m_RefractionTexture = null;
private WaterMode m_HardwareWaterSupport = WaterMode.Refractive;
private int m_OldReflectionTextureSize = 0;
private int m_OldRefractionTextureSize = 0;
private static bool s_InsideWater = false;
// This is called when it's known that the object will be rendered by some
// camera. We render reflections / refractions and do other updates here.
// Because the script executes in edit mode, reflections for the scene view
// camera will just work!
public void OnWillRenderObject()
{
if( !enabled || !renderer || !renderer.sharedMaterial || !renderer.enabled )
return;
Camera cam = Camera.current;
if( !cam )
return;
// Safeguard from recursive water reflections.
if( s_InsideWater )
return;
s_InsideWater = true;
// Actual water rendering mode depends on both the current setting AND
// the hardware support. There's no point in rendering refraction textures
// if they won't be visible in the end.
m_HardwareWaterSupport = FindHardwareWaterSupport();
WaterMode mode = GetWaterMode();
Camera reflectionCamera, refractionCamera;
CreateWaterObjects( cam, out reflectionCamera, out refractionCamera );
// find out the reflection plane: position and normal in world space
Vector3 pos = transform.position;
Vector3 normal = transform.up;
// Optionally disable pixel lights for reflection/refraction
int oldPixelLightCount = QualitySettings.pixelLightCount;
if( m_DisablePixelLights )
QualitySettings.pixelLightCount = 0;
float detailDistance = Terrain.activeTerrain.detailObjectDistance;
float treeDistance = Terrain.activeTerrain.treeDistance;
if(terrain && m_DisableTreesAndDetails)
{
terrain.detailObjectDistance = 0;
terrain.treeDistance = 0;
}
UpdateCameraModes( cam, reflectionCamera );
UpdateCameraModes( cam, refractionCamera );
// Render reflection if needed
if( mode >= WaterMode.Reflective )
{
// Reflect camera around reflection plane
float d = -Vector3.Dot (normal, pos) - m_ClipPlaneOffset;
Vector4 reflectionPlane = new Vector4 (normal.x, normal.y, normal.z, d);
Matrix4x4 reflection = Matrix4x4.zero;
CalculateReflectionMatrix (ref reflection, reflectionPlane);
Vector3 oldpos = cam.transform.position;
Vector3 newpos = reflection.MultiplyPoint( oldpos );
reflectionCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection;
// Setup oblique projection matrix so that near plane is our reflection
// plane. This way we clip everything below/above it for free.
Vector4 clipPlane = CameraSpacePlane( reflectionCamera, pos, normal, 1.0f );
Matrix4x4 projection = cam.projectionMatrix;
CalculateObliqueMatrix (ref projection, clipPlane);
reflectionCamera.projectionMatrix = projection;
reflectionCamera.cullingMask = ~(1<<4) & m_ReflectLayers.value; // never render water layer
reflectionCamera.targetTexture = m_ReflectionTexture;
GL.SetRevertBackfacing (true);
reflectionCamera.transform.position = newpos;
Vector3 euler = cam.transform.eulerAngles;
reflectionCamera.transform.eulerAngles = new Vector3(0, euler.y, euler.z);
reflectionCamera.Render();
reflectionCamera.transform.position = oldpos;
GL.SetRevertBackfacing (false);
renderer.sharedMaterial.SetTexture( "_ReflectionTex", m_ReflectionTexture );
}
// Render refraction
if( mode >= WaterMode.Refractive )
{
refractionCamera.worldToCameraMatrix = cam.worldToCameraMatrix;
// Setup oblique projection matrix so that near plane is our reflection
// plane. This way we clip everything below/above it for free.
Vector4 clipPlane = CameraSpacePlane( refractionCamera, pos, normal, -1.0f );
Matrix4x4 projection = cam.projectionMatrix;
CalculateObliqueMatrix (ref projection, clipPlane);
refractionCamera.projectionMatrix = projection;
refractionCamera.cullingMask = ~(1<<4) & m_RefractLayers.value; // never render water layer
refractionCamera.targetTexture = m_RefractionTexture;
refractionCamera.transform.position = cam.transform.position;
refractionCamera.transform.rotation = cam.transform.rotation;
refractionCamera.Render();
renderer.sharedMaterial.SetTexture( "_RefractionTex", m_RefractionTexture );
}
// Restore pixel light count
if( m_DisablePixelLights )
QualitySettings.pixelLightCount = oldPixelLightCount;
if(terrain && m_DisableTreesAndDetails)
{
terrain.detailObjectDistance = detailDistance;
terrain.treeDistance = treeDistance;
}
// Setup shader keywords based on water mode
switch( mode )
{
case WaterMode.Simple:
Shader.EnableKeyword( "WATER_SIMPLE" );
Shader.DisableKeyword( "WATER_REFLECTIVE" );
Shader.DisableKeyword( "WATER_REFRACTIVE" );
break;
case WaterMode.Reflective:
Shader.DisableKeyword( "WATER_SIMPLE" );
Shader.EnableKeyword( "WATER_REFLECTIVE" );
Shader.DisableKeyword( "WATER_REFRACTIVE" );
break;
case WaterMode.Refractive:
Shader.DisableKeyword( "WATER_SIMPLE" );
Shader.DisableKeyword( "WATER_REFLECTIVE" );
Shader.EnableKeyword( "WATER_REFRACTIVE" );
break;
}
s_InsideWater = false;
}
// Cleanup all the objects we possibly have created
void OnDisable()
{
if( m_ReflectionTexture ) {
DestroyImmediate( m_ReflectionTexture );
m_ReflectionTexture = null;
}
if( m_RefractionTexture ) {
DestroyImmediate( m_RefractionTexture );
m_RefractionTexture = null;
}
foreach( DictionaryEntry kvp in m_ReflectionCameras )
DestroyImmediate( ((Camera)kvp.Value).gameObject );
m_ReflectionCameras.Clear();
foreach( DictionaryEntry kvp in m_RefractionCameras )
DestroyImmediate( ((Camera)kvp.Value).gameObject );
m_RefractionCameras.Clear();
}
// This just sets up some matrices in the material; for really
// old cards to make water texture scroll.
void Update()
{
if( !renderer )
return;
Material mat = renderer.sharedMaterial;
if( !mat )
return;
Vector4 waveSpeed = mat.GetVector( "WaveSpeed" );
float waveScale = mat.GetFloat( "_WaveScale" );
Vector4 waveScale4 = new Vector4(waveScale, waveScale, waveScale * 0.4f, waveScale * 0.45f);
// Time since level load, and do intermediate calculations with doubles
double t = Time.timeSinceLevelLoad / 20.0;
Vector4 offsetClamped = new Vector4(
(float)System.Math.IEEERemainder(waveSpeed.x * waveScale4.x * t, 1.0),
(float)System.Math.IEEERemainder(waveSpeed.y * waveScale4.y * t, 1.0),
(float)System.Math.IEEERemainder(waveSpeed.z * waveScale4.z * t, 1.0),
(float)System.Math.IEEERemainder(waveSpeed.w * waveScale4.w * t, 1.0)
);
mat.SetVector( "_WaveOffset", offsetClamped );
mat.SetVector( "_WaveScale4", waveScale4 );
Vector3 waterSize = renderer.bounds.size;
Vector3 scale = new Vector3( waterSize.x*waveScale4.x, waterSize.z*waveScale4.y, 1 );
Matrix4x4 scrollMatrix = Matrix4x4.TRS( new Vector3(offsetClamped.x,offsetClamped.y,0), Quaternion.identity, scale );
mat.SetMatrix( "_WaveMatrix", scrollMatrix );
scale = new Vector3( waterSize.x*waveScale4.z, waterSize.z*waveScale4.w, 1 );
scrollMatrix = Matrix4x4.TRS( new Vector3(offsetClamped.z,offsetClamped.w,0), Quaternion.identity, scale );
mat.SetMatrix( "_WaveMatrix2", scrollMatrix );
}
private void UpdateCameraModes( Camera src, Camera dest )
{
if( dest == null )
return;
// set water camera to clear the same way as current camera
dest.clearFlags = src.clearFlags;
dest.backgroundColor = src.backgroundColor;
if( src.clearFlags == CameraClearFlags.Skybox )
{
Skybox sky = src.GetComponent(typeof(Skybox)) as Skybox;
Skybox mysky = dest.GetComponent(typeof(Skybox)) as Skybox;
if( !sky || !sky.material )
{
mysky.enabled = false;
}
else
{
mysky.enabled = true;
mysky.material = sky.material;
}
}
// update other values to match current camera.
// even if we are supplying custom camera&projection matrices,
// some of values are used elsewhere (e.g. skybox uses far plane)
dest.farClipPlane = src.farClipPlane;
dest.nearClipPlane = src.nearClipPlane;
dest.orthographic = src.orthographic;
dest.fieldOfView = src.fieldOfView;
dest.aspect = src.aspect;
dest.orthographicSize = src.orthographicSize;
}
// On-demand create any objects we need for water
private void CreateWaterObjects( Camera currentCamera, out Camera reflectionCamera, out Camera refractionCamera )
{
WaterMode mode = GetWaterMode();
reflectionCamera = null;
refractionCamera = null;
if( mode >= WaterMode.Reflective )
{
// Reflection render texture
if( !m_ReflectionTexture || m_OldReflectionTextureSize != m_TextureSize )
{
if( m_ReflectionTexture )
DestroyImmediate( m_ReflectionTexture );
m_ReflectionTexture = new RenderTexture( m_TextureSize, m_TextureSize, 16 );
m_ReflectionTexture.name = "__WaterReflection" + GetInstanceID();
m_ReflectionTexture.isPowerOfTwo = true;
m_ReflectionTexture.hideFlags = HideFlags.DontSave;
m_OldReflectionTextureSize = m_TextureSize;
}
// Camera for reflection
reflectionCamera = m_ReflectionCameras[currentCamera] as Camera;
if( !reflectionCamera ) // catch both not-in-dictionary and in-dictionary-but-deleted-GO
{
GameObject go = new GameObject( "Water Refl Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox) );
reflectionCamera = go.camera;
reflectionCamera.enabled = false;
reflectionCamera.transform.position = transform.position;
reflectionCamera.transform.rotation = transform.rotation;
reflectionCamera.gameObject.AddComponent("FlareLayer");
go.hideFlags = HideFlags.HideAndDontSave;
m_ReflectionCameras[currentCamera] = reflectionCamera;
}
}
if( mode >= WaterMode.Refractive )
{
// Refraction render texture
if( !m_RefractionTexture || m_OldRefractionTextureSize != m_TextureSize )
{
if( m_RefractionTexture )
DestroyImmediate( m_RefractionTexture );
m_RefractionTexture = new RenderTexture( m_TextureSize, m_TextureSize, 16 );
m_RefractionTexture.name = "__WaterRefraction" + GetInstanceID();
m_RefractionTexture.isPowerOfTwo = true;
m_RefractionTexture.hideFlags = HideFlags.DontSave;
m_OldRefractionTextureSize = m_TextureSize;
}
// Camera for refraction
refractionCamera = m_RefractionCameras[currentCamera] as Camera;
if( !refractionCamera ) // catch both not-in-dictionary and in-dictionary-but-deleted-GO
{
GameObject go = new GameObject( "Water Refr Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox) );
refractionCamera = go.camera;
refractionCamera.enabled = false;
refractionCamera.transform.position = transform.position;
refractionCamera.transform.rotation = transform.rotation;
refractionCamera.gameObject.AddComponent("FlareLayer");
go.hideFlags = HideFlags.HideAndDontSave;
m_RefractionCameras[currentCamera] = refractionCamera;
}
}
}
private WaterMode GetWaterMode()
{
if( m_HardwareWaterSupport < m_WaterMode )
return m_HardwareWaterSupport;
else
return m_WaterMode;
}
private WaterMode FindHardwareWaterSupport()
{
if( !SystemInfo.supportsRenderTextures || !renderer )
return WaterMode.Simple;
Material mat = renderer.sharedMaterial;
if( !mat )
return WaterMode.Simple;
string mode = mat.GetTag("WATERMODE", false);
if( mode == "Refractive" )
return WaterMode.Refractive;
if( mode == "Reflective" )
return WaterMode.Reflective;
return WaterMode.Simple;
}
// Extended sign: returns -1, 0 or 1 based on sign of a
private static float sgn(float a)
{
if (a > 0.0f) return 1.0f;
if (a < 0.0f) return -1.0f;
return 0.0f;
}
// Given position/normal of the plane, calculates plane in camera space.
private Vector4 CameraSpacePlane (Camera cam, Vector3 pos, Vector3 normal, float sideSign)
{
Vector3 offsetPos = pos + normal * m_ClipPlaneOffset;
Matrix4x4 m = cam.worldToCameraMatrix;
Vector3 cpos = m.MultiplyPoint( offsetPos );
Vector3 cnormal = m.MultiplyVector( normal ).normalized * sideSign;
return new Vector4( cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot(cpos,cnormal) );
}
// Adjusts the given projection matrix so that near plane is the given clipPlane
// clipPlane is given in camera space. See article in Game Programming Gems 5 and
// http://aras-p.info/texts/obliqueortho.html
private static void CalculateObliqueMatrix (ref Matrix4x4 projection, Vector4 clipPlane)
{
Vector4 q = projection.inverse * new Vector4(
sgn(clipPlane.x),
sgn(clipPlane.y),
1.0f,
1.0f
);
Vector4 c = clipPlane * (2.0F / (Vector4.Dot (clipPlane, q)));
// third row = clip plane - fourth row
projection[2] = c.x - projection[3];
projection[6] = c.y - projection[7];
projection[10] = c.z - projection[11];
projection[14] = c.w - projection[15];
}
// Calculates reflection matrix around the given plane
private static void CalculateReflectionMatrix (ref Matrix4x4 reflectionMat, Vector4 plane)
{
reflectionMat.m00 = (1F - 2F*plane[0]*plane[0]);
reflectionMat.m01 = ( - 2F*plane[0]*plane[1]);
reflectionMat.m02 = ( - 2F*plane[0]*plane[2]);
reflectionMat.m03 = ( - 2F*plane[3]*plane[0]);
reflectionMat.m10 = ( - 2F*plane[1]*plane[0]);
reflectionMat.m11 = (1F - 2F*plane[1]*plane[1]);
reflectionMat.m12 = ( - 2F*plane[1]*plane[2]);
reflectionMat.m13 = ( - 2F*plane[3]*plane[1]);
reflectionMat.m20 = ( - 2F*plane[2]*plane[0]);
reflectionMat.m21 = ( - 2F*plane[2]*plane[1]);
reflectionMat.m22 = (1F - 2F*plane[2]*plane[2]);
reflectionMat.m23 = ( - 2F*plane[3]*plane[2]);
reflectionMat.m30 = 0F;
reflectionMat.m31 = 0F;
reflectionMat.m32 = 0F;
reflectionMat.m33 = 1F;
}
}
| |
//Copyright (C) 2006 Richard J. Northedge
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//This file is based on the JWNLDictionary.java source file found in the
//original java implementation of OpenNLP. That source file contains the following header:
//Copyright (C) 2003 Thomas Morton
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this program; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
using System;
//UPGRADE_TODO: The type 'net.didion.jwnl.JWNLException' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
//using JWNLException = net.didion.jwnl.JWNLException;
////UPGRADE_TODO: The type 'net.didion.jwnl.data.Adjective' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
//using Adjective = net.didion.jwnl.data.Adjective;
////UPGRADE_TODO: The type 'net.didion.jwnl.data.FileDictionaryElementFactory' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
//using FileDictionaryElementFactory = net.didion.jwnl.data.FileDictionaryElementFactory;
////UPGRADE_TODO: The type 'net.didion.jwnl.data.IndexWord' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
//using IndexWord = net.didion.jwnl.data.IndexWord;
////UPGRADE_TODO: The type 'net.didion.jwnl.data.POS' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
//using POS = net.didion.jwnl.data.POS;
////UPGRADE_TODO: The type 'net.didion.jwnl.data.Pointer' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
//using Pointer = net.didion.jwnl.data.Pointer;
////UPGRADE_TODO: The type 'net.didion.jwnl.data.PointerType' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
//using PointerType = net.didion.jwnl.data.PointerType;
////UPGRADE_TODO: The type 'net.didion.jwnl.data.Synset' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
//using Synset = net.didion.jwnl.data.Synset;
////UPGRADE_TODO: The type 'net.didion.jwnl.data.VerbFrame' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
//using VerbFrame = net.didion.jwnl.data.VerbFrame;
////UPGRADE_TODO: The type 'net.didion.jwnl.dictionary.FileBackedDictionary' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
//using FileBackedDictionary = net.didion.jwnl.dictionary.FileBackedDictionary;
////UPGRADE_TODO: The type 'net.didion.jwnl.dictionary.MorphologicalProcessor' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
//using MorphologicalProcessor = net.didion.jwnl.dictionary.MorphologicalProcessor;
////UPGRADE_TODO: The type 'net.didion.jwnl.dictionary.file_manager.FileManager' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
//using FileManager = net.didion.jwnl.dictionary.file_manager.FileManager;
////UPGRADE_TODO: The type 'net.didion.jwnl.dictionary.file_manager.FileManagerImpl' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
//using FileManagerImpl = net.didion.jwnl.dictionary.file_manager.FileManagerImpl;
////UPGRADE_TODO: The type 'net.didion.jwnl.dictionary.morph.DefaultMorphologicalProcessor' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
//using DefaultMorphologicalProcessor = net.didion.jwnl.dictionary.morph.DefaultMorphologicalProcessor;
////UPGRADE_TODO: The type 'net.didion.jwnl.dictionary.morph.DetachSuffixesOperation' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
//using DetachSuffixesOperation = net.didion.jwnl.dictionary.morph.DetachSuffixesOperation;
////UPGRADE_TODO: The type 'net.didion.jwnl.dictionary.morph.LookupExceptionsOperation' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
//using LookupExceptionsOperation = net.didion.jwnl.dictionary.morph.LookupExceptionsOperation;
////UPGRADE_TODO: The type 'net.didion.jwnl.dictionary.morph.LookupIndexWordOperation' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
//using LookupIndexWordOperation = net.didion.jwnl.dictionary.morph.LookupIndexWordOperation;
////UPGRADE_TODO: The type 'net.didion.jwnl.dictionary.morph.Operation' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
//using Operation = net.didion.jwnl.dictionary.morph.Operation;
////UPGRADE_TODO: The type 'net.didion.jwnl.dictionary.morph.TokenizerOperation' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
//using TokenizerOperation = net.didion.jwnl.dictionary.morph.TokenizerOperation;
////UPGRADE_TODO: The type 'net.didion.jwnl.princeton.data.PrincetonWN17FileDictionaryElementFactory' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
//using PrincetonWN17FileDictionaryElementFactory = net.didion.jwnl.princeton.data.PrincetonWN17FileDictionaryElementFactory;
////UPGRADE_TODO: The type 'net.didion.jwnl.princeton.file.PrincetonRandomAccessDictionaryFile' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
//using PrincetonRandomAccessDictionaryFile = net.didion.jwnl.princeton.file.PrincetonRandomAccessDictionaryFile;
using SharpWordNet;
using System.Collections.Generic;
namespace OpenNLP.Tools.Coreference.Mention
{
/// <summary> An implementation of the Dictionary interface using the JWNL library. </summary>
public class JWNLDictionary : IDictionary
{
private WordNetEngine mEngine;
//private net.didion.jwnl.dictionary.Dictionary dict;
private WordNetEngine.MorphologicalProcessOperation morphologicalProcess;
//private MorphologicalProcessor morphy;
private static string[] empty = new string[0];
public JWNLDictionary(string searchDirectory)
{
//PointerType.initialize();
//Adjective.initialize();
//VerbFrame.initialize();
////UPGRADE_TODO: Class 'java.util.HashMap' was converted to 'System.Collections.Hashtable' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMap'"
//System.Collections.IDictionary suffixMap = new System.Collections.Hashtable();
//suffixMap[POS.NOUN] = new string[][]{new string[]{"s", ""}, new string[]{"ses", "s"}, new string[]{"xes", "x"}, new string[]{"zes", "z"}, new string[]{"ches", "ch"}, new string[]{"shes", "sh"}, new string[]{"men", "man"}, new string[]{"ies", "y"}};
//suffixMap[POS.VERB] = new string[][]{new string[]{"s", ""}, new string[]{"ies", "y"}, new string[]{"es", "e"}, new string[]{"es", ""}, new string[]{"ed", "e"}, new string[]{"ed", ""}, new string[]{"ing", "e"}, new string[]{"ing", ""}};
//suffixMap[POS.ADJECTIVE] = new string[][]{new string[]{"er", ""}, new string[]{"est", ""}, new string[]{"er", "e"}, new string[]{"est", "e"}};
//DetachSuffixesOperation tokDso = new DetachSuffixesOperation(suffixMap);
//tokDso.addDelegate(DetachSuffixesOperation.OPERATIONS, new Operation[]{new LookupIndexWordOperation(), new LookupExceptionsOperation()});
//TokenizerOperation tokOp = new TokenizerOperation(new string[]{" ", "-"});
//tokOp.addDelegate(TokenizerOperation.TOKEN_OPERATIONS, new Operation[]{new LookupIndexWordOperation(), new LookupExceptionsOperation(), tokDso});
//DetachSuffixesOperation morphDso = new DetachSuffixesOperation(suffixMap);
//morphDso.addDelegate(DetachSuffixesOperation.OPERATIONS, new Operation[]{new LookupIndexWordOperation(), new LookupExceptionsOperation()});
//Operation[] operations = new Operation[]{new LookupExceptionsOperation(), morphDso, tokOp};
//morphy = new DefaultMorphologicalProcessor(operations);
//FileManager manager = new FileManagerImpl(searchDirectory, typeof(PrincetonRandomAccessDictionaryFile));
//FileDictionaryElementFactory factory = new PrincetonWN17FileDictionaryElementFactory();
//FileBackedDictionary.install(manager, morphy, factory, true);
//dict = net.didion.jwnl.dictionary.Dictionary.getInstance();
//morphy = dict.getMorphologicalProcessor();
mEngine = new DataFileEngine(searchDirectory);
morphologicalProcess += mEngine.LookupExceptionsOperation;
morphologicalProcess += mEngine.LookupIndexWordOperation;
}
public virtual string[] getLemmas(string word, string tag)
{
//try
//{
string pos;
if (tag.StartsWith("N") || tag.StartsWith("n"))
{
pos = "noun";
}
else if (tag.StartsWith("N") || tag.StartsWith("v"))
{
pos = "verb";
}
else if (tag.StartsWith("J") || tag.StartsWith("a"))
{
pos = "adjective";
}
else if (tag.StartsWith("R") || tag.StartsWith("r"))
{
pos = "adverb";
}
else
{
pos = "noun";
}
// System.Collections.IList lemmas = morphy.lookupAllBaseForms(pos, word);
// return ((string[]) SupportClass.ICollectionSupport.ToArray(lemmas, new string[lemmas.Count]));
//}
//catch (JWNLException e)
//{
// e.printStackTrace();
// return null;
//}
return mEngine.GetBaseForms(word, pos, morphologicalProcess);
}
public virtual string getSenseKey(string lemma, string pos, int sense)
{
//try
//{
IndexWord indexWord = mEngine.GetIndexWord(lemma, "noun");
//IndexWord indexWord = dict.getIndexWord(POS.NOUN, lemma);
if (indexWord == null)
{
return null;
}
//return System.Convert.ToString(indexWord.getSynsetOffsets()[sense]);
return indexWord.SynsetOffsets[sense].ToString(System.Globalization.CultureInfo.InvariantCulture);
//}
//catch (JWNLException e)
//{
// e.printStackTrace();
// return null;
//}
//return null;
}
public virtual int getNumSenses(string lemma, string pos)
{
//try
//{
IndexWord indexWord = mEngine.GetIndexWord(lemma, "noun");
//IndexWord indexWord = dict.getIndexWord(POS.NOUN, lemma);
if (indexWord == null)
{
return 0;
}
//return indexWord.getSenseCount();
return indexWord.SenseCount;
//}
//catch (JWNLException e)
//{
// return 0;
//}
//return 0;
}
//private void getParents(Synset synset, System.Collections.IList parents)
//{
//Pointer[] pointers = synset.getPointers();
//for (int pi = 0, pn = pointers.length; pi < pn; pi++)
//{
// if (pointers[pi].getType() == PointerType.HYPERNYM)
// {
// Synset parent = pointers[pi].getTargetSynset();
// parents.Add(System.Convert.ToString(parent.getOffset()));
// getParents(parent, parents);
// }
//}
//}
private void getParents(Synset currentSynset, List<string> parentOffsets)
{
for (int currentRelation = 0;currentRelation < currentSynset.RelationCount;currentRelation++)
{
Relation relation = currentSynset.GetRelation(currentRelation);
if (relation.SynsetRelationType.Name == "Hypernym")
{
Synset parentSynset = relation.TargetSynset;
parentOffsets.Add(parentSynset.Offset.ToString(System.Globalization.CultureInfo.InvariantCulture));
getParents(parentSynset, parentOffsets);
}
}
}
public virtual string[] getParentSenseKeys(string lemma, string pos, int sense)
{
////System.err.println("JWNLDictionary.getParentSenseKeys: lemma="+lemma); this line was commented out in the java
//try
//{
Synset[] synsets = mEngine.GetSynsets(lemma, "noun");
//IndexWord indexWord= dict.getIndexWord(POS.NOUN, lemma);
if (synsets.Length > sense)
{
//Synset synset = indexWord.getSense(sense + 1); //the sense+1 is because in JWNL sense ids start at 1
List<string> parents = new List<string>();
getParents(synsets[sense], parents);
return parents.ToArray();
//return (string[])SupportClass.ICollectionSupport.ToArray(parents, new string[parents.Count]);
}
else
{
return empty;
}
//}
//catch (JWNLException e)
//{
// e.printStackTrace();
// return null;
//}
}
//[STAThread]
//public static void Main(string[] args)
//{
// //UPGRADE_ISSUE: Method 'java.lang.System.getProperty' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangSystem'"
// string searchDir = System_Renamed.getProperty("WNSEARCHDIR");
// System.Console.Error.WriteLine("searchDir=" + searchDir);
// if (searchDir != null)
// {
// //UPGRADE_ISSUE: Method 'java.lang.System.getProperty' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangSystem'"
// Dictionary dict = new JWNLDictionary(System_Renamed.getProperty("WNSEARCHDIR"));
// string word = args[0];
// string[] lemmas = dict.getLemmas(word, "NN");
// for (int li = 0, ln = lemmas.Length; li < ln; li++)
// {
// for (int si = 0, sn = dict.getNumSenses(lemmas[li], "NN"); si < sn; si++)
// {
// //UPGRADE_TODO: Method 'java.util.Arrays.asList' was converted to 'System.Collections.ArrayList' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilArraysasList_javalangObject[]'"
// System.Console.Out.WriteLine(lemmas[li] + " (" + si + ")\t" + SupportClass.CollectionToString(new System.Collections.ArrayList(dict.getParentSenseKeys(lemmas[li], "NN", si))));
// }
// }
// }
//}
}
}
| |
// 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.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB
{
public class PDBIteratorTests : CSharpPDBTestBase
{
[WorkItem(543376, "DevDiv")]
[Fact]
public void SimpleIterator1()
{
var text = @"
class Program
{
System.Collections.Generic.IEnumerable<int> Foo()
{
yield break;
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""Foo"">
<customDebugInfo>
<forwardIterator name=""<Foo>d__0"" />
</customDebugInfo>
</method>
<method containingType=""Program"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""21"" endLine=""9"" endColumn=""22"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""23"" endLine=""9"" endColumn=""24"" />
</sequencePoints>
</method>
<method containingType=""Program+<Foo>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""F"" />
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x17"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" />
<entry offset=""0x18"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""21"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(543376, "DevDiv")]
[Fact]
public void SimpleIterator2()
{
var text = @"
class Program
{
System.Collections.Generic.IEnumerable<int> Foo()
{
yield break;
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""Foo"">
<customDebugInfo>
<forwardIterator name=""<Foo>d__0"" />
</customDebugInfo>
</method>
<method containingType=""Program"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""21"" endLine=""9"" endColumn=""22"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""23"" endLine=""9"" endColumn=""24"" />
</sequencePoints>
</method>
<method containingType=""Program+<Foo>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""F"" />
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x17"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" />
<entry offset=""0x18"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""21"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(543490, "DevDiv")]
[Fact]
public void SimpleIterator3()
{
var text = @"
class Program
{
System.Collections.Generic.IEnumerable<int> Foo()
{
yield return 1; //hidden sequence point after this.
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""Foo"">
<customDebugInfo>
<forwardIterator name=""<Foo>d__0"" />
</customDebugInfo>
</method>
<method containingType=""Program"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""21"" endLine=""9"" endColumn=""22"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""23"" endLine=""9"" endColumn=""24"" />
</sequencePoints>
</method>
<method containingType=""Program+<Foo>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""F"" />
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x1f"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" />
<entry offset=""0x20"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""24"" />
<entry offset=""0x30"" hidden=""true"" />
<entry offset=""0x37"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void IteratorWithLocals_ReleasePdb()
{
var text = @"
class Program
{
System.Collections.Generic.IEnumerable<int> IEI<T>(int i0, int i1)
{
int x = i0;
yield return x;
yield return x;
{
int y = i1;
yield return y;
yield return y;
}
yield break;
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.ReleaseDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""IEI"" parameterNames=""i0, i1"">
<customDebugInfo>
<forwardIterator name=""<IEI>d__0"" />
</customDebugInfo>
</method>
<method containingType=""Program"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""17"" startColumn=""23"" endLine=""17"" endColumn=""24"" />
</sequencePoints>
</method>
<method containingType=""Program+<IEI>d__0`1"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""F"" />
<hoistedLocalScopes>
<slot startOffset=""0x2a"" endOffset=""0xb3"" />
<slot startOffset=""0x6e"" endOffset=""0xb1"" />
</hoistedLocalScopes>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x2a"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""20"" />
<entry offset=""0x36"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""24"" />
<entry offset=""0x4b"" hidden=""true"" />
<entry offset=""0x52"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""24"" />
<entry offset=""0x67"" hidden=""true"" />
<entry offset=""0x6e"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""24"" />
<entry offset=""0x7a"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""28"" />
<entry offset=""0x8f"" hidden=""true"" />
<entry offset=""0x96"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""28"" />
<entry offset=""0xab"" hidden=""true"" />
<entry offset=""0xb2"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""21"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void IteratorWithLocals_DebugPdb()
{
var text = @"
class Program
{
System.Collections.Generic.IEnumerable<int> IEI<T>(int i0, int i1)
{
int x = i0;
yield return x;
yield return x;
{
int y = i1;
yield return y;
yield return y;
}
yield break;
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""IEI"" parameterNames=""i0, i1"">
<customDebugInfo>
<forwardIterator name=""<IEI>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""0"" offset=""101"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType=""Program"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""17"" startColumn=""21"" endLine=""17"" endColumn=""22"" />
<entry offset=""0x1"" startLine=""17"" startColumn=""23"" endLine=""17"" endColumn=""24"" />
</sequencePoints>
</method>
<method containingType=""Program+<IEI>d__0`1"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""F"" />
<hoistedLocalScopes>
<slot startOffset=""0x39"" endOffset=""0xc5"" />
<slot startOffset=""0x7e"" endOffset=""0xc3"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x39"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" />
<entry offset=""0x3a"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""20"" />
<entry offset=""0x46"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""24"" />
<entry offset=""0x5b"" hidden=""true"" />
<entry offset=""0x62"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""24"" />
<entry offset=""0x77"" hidden=""true"" />
<entry offset=""0x7e"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" />
<entry offset=""0x7f"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""24"" />
<entry offset=""0x8b"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""28"" />
<entry offset=""0xa0"" hidden=""true"" />
<entry offset=""0xa7"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""28"" />
<entry offset=""0xbc"" hidden=""true"" />
<entry offset=""0xc3"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" />
<entry offset=""0xc4"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""21"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void IteratorWithCapturedSyntheticVariables()
{
// this iterator captures the synthetic variable generated from the expansion of the foreach loop
var text = @"// Based on LegacyTest csharp\Source\Conformance\iterators\blocks\using001.cs
using System;
using System.Collections.Generic;
class Test<T>
{
public static IEnumerator<T> M(IEnumerable<T> items)
{
T val = default(T);
foreach (T item in items)
{
val = item;
yield return val;
}
yield return val;
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}";
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Test`1"" name=""M"" parameterNames=""items"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""5"" offset=""42"" />
<slot kind=""0"" offset=""42"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType=""Test`1"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""19"" startColumn=""21"" endLine=""19"" endColumn=""22"" />
<entry offset=""0x1"" startLine=""19"" startColumn=""23"" endLine=""19"" endColumn=""24"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
</scope>
</method>
<method containingType=""Test`1+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Test`1"" methodName=""F"" />
<hoistedLocalScopes>
<slot startOffset=""0x32"" endOffset=""0xe1"" />
<slot startOffset=""0x0"" endOffset=""0x0"" />
<slot startOffset=""0x5b"" endOffset=""0xa4"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""temp"" />
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x32"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" />
<entry offset=""0x33"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""28"" />
<entry offset=""0x3f"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""16"" />
<entry offset=""0x40"" startLine=""11"" startColumn=""28"" endLine=""11"" endColumn=""33"" />
<entry offset=""0x59"" hidden=""true"" />
<entry offset=""0x5b"" startLine=""11"" startColumn=""18"" endLine=""11"" endColumn=""24"" />
<entry offset=""0x6c"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" />
<entry offset=""0x6d"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""24"" />
<entry offset=""0x79"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""30"" />
<entry offset=""0x90"" hidden=""true"" />
<entry offset=""0x98"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" />
<entry offset=""0xa5"" startLine=""11"" startColumn=""25"" endLine=""11"" endColumn=""27"" />
<entry offset=""0xc0"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""26"" />
<entry offset=""0xd7"" hidden=""true"" />
<entry offset=""0xde"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" />
<entry offset=""0xe2"" hidden=""true"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(542705, "DevDiv"), WorkItem(528790, "DevDiv"), WorkItem(543490, "DevDiv")]
[Fact()]
public void IteratorBackToNextStatementAfterYieldReturn()
{
var text = @"
using System.Collections.Generic;
class C
{
IEnumerable<decimal> M()
{
const decimal d1 = 0.1M;
yield return d1;
const decimal dx = 1.23m;
yield return dx;
{
const decimal d2 = 0.2M;
yield return d2;
}
yield break;
}
static void Main()
{
foreach (var i in new C().M())
{
System.Console.WriteLine(i);
}
}
}
";
using (new CultureContext("en-US"))
{
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.ReleaseExe);
c.VerifyPdb(@"
<symbols>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
</customDebugInfo>
</method>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""21"" startColumn=""27"" endLine=""21"" endColumn=""38"" />
<entry offset=""0x10"" hidden=""true"" />
<entry offset=""0x12"" startLine=""21"" startColumn=""18"" endLine=""21"" endColumn=""23"" />
<entry offset=""0x18"" startLine=""23"" startColumn=""13"" endLine=""23"" endColumn=""41"" />
<entry offset=""0x1d"" startLine=""21"" startColumn=""24"" endLine=""21"" endColumn=""26"" />
<entry offset=""0x27"" hidden=""true"" />
<entry offset=""0x31"" startLine=""25"" startColumn=""5"" endLine=""25"" endColumn=""6"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x32"">
<namespace name=""System.Collections.Generic"" />
</scope>
</method>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x26"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""25"" />
<entry offset=""0x3f"" hidden=""true"" />
<entry offset=""0x46"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""25"" />
<entry offset=""0x60"" hidden=""true"" />
<entry offset=""0x67"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""29"" />
<entry offset=""0x80"" hidden=""true"" />
<entry offset=""0x87"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""21"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x89"">
<scope startOffset=""0x26"" endOffset=""0x89"">
<constant name=""d1"" value=""0.1"" type=""Decimal"" />
<constant name=""dx"" value=""1.23"" type=""Decimal"" />
<scope startOffset=""0x67"" endOffset=""0x87"">
<constant name=""d2"" value=""0.2"" type=""Decimal"" />
</scope>
</scope>
</scope>
</method>
</methods>
</symbols>");
}
}
[WorkItem(543490, "DevDiv")]
[Fact()]
public void IteratorMultipleEnumerables()
{
var text = @"
using System;
using System.Collections;
using System.Collections.Generic;
public class Test<T> : IEnumerable<T> where T : class
{
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
foreach (var v in this.IterProp)
{
yield return v;
}
foreach (var v in IterMethod())
{
yield return v;
}
}
public IEnumerable<T> IterProp
{
get
{
yield return null;
yield return null;
}
}
public IEnumerable<T> IterMethod()
{
yield return default(T);
yield return null;
yield break;
}
}
public class Test
{
public static void Main()
{
foreach (var v in new Test<string>()) { }
}
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugExe);
c.VerifyPdb(@"
<symbols>
<entryPoint declaringType=""Test"" methodName=""Main"" />
<methods>
<method containingType=""Test`1"" name=""System.Collections.IEnumerable.GetEnumerator"">
<customDebugInfo>
<using>
<namespace usingCount=""3"" />
</using>
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""32"" />
<entry offset=""0xa"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xc"">
<namespace name=""System"" />
<namespace name=""System.Collections"" />
<namespace name=""System.Collections.Generic"" />
</scope>
</method>
<method containingType=""Test`1"" name=""GetEnumerator"">
<customDebugInfo>
<forwardIterator name=""<GetEnumerator>d__1"" />
<encLocalSlotMap>
<slot kind=""5"" offset=""11"" />
<slot kind=""0"" offset=""11"" />
<slot kind=""5"" offset=""104"" />
<slot kind=""0"" offset=""104"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType=""Test`1"" name=""get_IterProp"">
<customDebugInfo>
<forwardIterator name=""<get_IterProp>d__3"" />
</customDebugInfo>
</method>
<method containingType=""Test`1"" name=""IterMethod"">
<customDebugInfo>
<forwardIterator name=""<IterMethod>d__4"" />
</customDebugInfo>
</method>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<forward declaringType=""Test`1"" methodName=""System.Collections.IEnumerable.GetEnumerator"" />
<encLocalSlotMap>
<slot kind=""5"" offset=""11"" />
<slot kind=""0"" offset=""11"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""45"" startColumn=""5"" endLine=""45"" endColumn=""6"" />
<entry offset=""0x1"" startLine=""46"" startColumn=""9"" endLine=""46"" endColumn=""16"" />
<entry offset=""0x2"" startLine=""46"" startColumn=""27"" endLine=""46"" endColumn=""45"" />
<entry offset=""0xd"" hidden=""true"" />
<entry offset=""0xf"" startLine=""46"" startColumn=""18"" endLine=""46"" endColumn=""23"" />
<entry offset=""0x16"" startLine=""46"" startColumn=""47"" endLine=""46"" endColumn=""48"" />
<entry offset=""0x17"" startLine=""46"" startColumn=""49"" endLine=""46"" endColumn=""50"" />
<entry offset=""0x18"" startLine=""46"" startColumn=""24"" endLine=""46"" endColumn=""26"" />
<entry offset=""0x22"" hidden=""true"" />
<entry offset=""0x2d"" startLine=""47"" startColumn=""5"" endLine=""47"" endColumn=""6"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2e"">
<scope startOffset=""0xf"" endOffset=""0x18"">
<local name=""v"" il_index=""1"" il_start=""0xf"" il_end=""0x18"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""Test`1+<GetEnumerator>d__1"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Test`1"" methodName=""System.Collections.IEnumerable.GetEnumerator"" />
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x0"" />
<slot startOffset=""0x54"" endOffset=""0x94"" />
<slot startOffset=""0x0"" endOffset=""0x0"" />
<slot startOffset=""0xd1"" endOffset=""0x10e"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""temp"" />
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x32"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" />
<entry offset=""0x33"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""16"" />
<entry offset=""0x34"" startLine=""15"" startColumn=""27"" endLine=""15"" endColumn=""40"" />
<entry offset=""0x52"" hidden=""true"" />
<entry offset=""0x54"" startLine=""15"" startColumn=""18"" endLine=""15"" endColumn=""23"" />
<entry offset=""0x65"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" />
<entry offset=""0x66"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""28"" />
<entry offset=""0x80"" hidden=""true"" />
<entry offset=""0x88"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""10"" />
<entry offset=""0x95"" startLine=""15"" startColumn=""24"" endLine=""15"" endColumn=""26"" />
<entry offset=""0xb0"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""16"" />
<entry offset=""0xb1"" startLine=""19"" startColumn=""27"" endLine=""19"" endColumn=""39"" />
<entry offset=""0xcf"" hidden=""true"" />
<entry offset=""0xd1"" startLine=""19"" startColumn=""18"" endLine=""19"" endColumn=""23"" />
<entry offset=""0xe2"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""10"" />
<entry offset=""0xe3"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""28"" />
<entry offset=""0xfa"" hidden=""true"" />
<entry offset=""0x102"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" />
<entry offset=""0x10f"" startLine=""19"" startColumn=""24"" endLine=""19"" endColumn=""26"" />
<entry offset=""0x12a"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" />
<entry offset=""0x12e"" hidden=""true"" />
</sequencePoints>
</method>
<method containingType=""Test`1+<get_IterProp>d__3"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Test`1"" methodName=""System.Collections.IEnumerable.GetEnumerator"" />
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x2a"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""10"" />
<entry offset=""0x2b"" startLine=""29"" startColumn=""13"" endLine=""29"" endColumn=""31"" />
<entry offset=""0x40"" hidden=""true"" />
<entry offset=""0x47"" startLine=""30"" startColumn=""13"" endLine=""30"" endColumn=""31"" />
<entry offset=""0x5c"" hidden=""true"" />
<entry offset=""0x63"" startLine=""31"" startColumn=""9"" endLine=""31"" endColumn=""10"" />
</sequencePoints>
</method>
<method containingType=""Test`1+<IterMethod>d__4"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Test`1"" methodName=""System.Collections.IEnumerable.GetEnumerator"" />
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x2a"" startLine=""35"" startColumn=""5"" endLine=""35"" endColumn=""6"" />
<entry offset=""0x2b"" startLine=""36"" startColumn=""9"" endLine=""36"" endColumn=""33"" />
<entry offset=""0x40"" hidden=""true"" />
<entry offset=""0x47"" startLine=""37"" startColumn=""9"" endLine=""37"" endColumn=""27"" />
<entry offset=""0x5c"" hidden=""true"" />
<entry offset=""0x63"" startLine=""38"" startColumn=""9"" endLine=""38"" endColumn=""21"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void VariablesWithSubstitutedType1()
{
var text = @"
using System.Collections.Generic;
class C
{
static IEnumerable<T> F<T>(T[] o)
{
int i = 0;
T t = default(T);
yield return t;
yield return o[i];
}
}
";
var v = CompileAndVerify(text, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
"o", "<>3__o",
"<i>5__1",
"<t>5__2"
}, module.GetFieldNames("C.<F>d__0"));
});
v.VerifyPdb("C+<F>d__0`1.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<F>d__0`1"" name=""MoveNext"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<hoistedLocalScopes>
<slot startOffset=""0x2a"" endOffset=""0x82"" />
<slot startOffset=""0x2a"" endOffset=""0x82"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x2a"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" />
<entry offset=""0x2b"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""19"" />
<entry offset=""0x32"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""26"" />
<entry offset=""0x3e"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" />
<entry offset=""0x53"" hidden=""true"" />
<entry offset=""0x5a"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""27"" />
<entry offset=""0x7a"" hidden=""true"" />
<entry offset=""0x81"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x83"">
<namespace name=""System.Collections.Generic"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void IteratorWithConditionalBranchDiscriminator1()
{
var text = @"
using System.Collections.Generic;
class C
{
static bool B() => false;
static IEnumerable<int> F()
{
if (B())
{
yield return 1;
}
}
}
";
// Note that conditional branch discriminator is not hoisted.
var v = CompileAndVerify(text, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
}, module.GetFieldNames("C.<F>d__1"));
});
v.VerifyIL("C.<F>d__1.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 68 (0x44)
.maxstack 2
.locals init (int V_0,
bool V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__1.<>1__state""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0012
IL_000a: br.s IL_000c
IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: beq.s IL_0014
IL_0010: br.s IL_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_003a
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__1.<>1__state""
IL_001f: nop
IL_0020: call ""bool C.B()""
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: brfalse.s IL_0042
IL_0029: nop
IL_002a: ldarg.0
IL_002b: ldc.i4.1
IL_002c: stfld ""int C.<F>d__1.<>2__current""
IL_0031: ldarg.0
IL_0032: ldc.i4.1
IL_0033: stfld ""int C.<F>d__1.<>1__state""
IL_0038: ldc.i4.1
IL_0039: ret
IL_003a: ldarg.0
IL_003b: ldc.i4.m1
IL_003c: stfld ""int C.<F>d__1.<>1__state""
IL_0041: nop
IL_0042: ldc.i4.0
IL_0043: ret
}
");
v.VerifyPdb("C+<F>d__1.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<F>d__1"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""B"" />
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""1"" offset=""11"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x1f"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" />
<entry offset=""0x20"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""17"" />
<entry offset=""0x26"" hidden=""true"" />
<entry offset=""0x29"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" />
<entry offset=""0x2a"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""28"" />
<entry offset=""0x3a"" hidden=""true"" />
<entry offset=""0x41"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" />
<entry offset=""0x42"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void SynthesizedVariables1()
{
var source =
@"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> M(IDisposable disposable)
{
foreach (var item in new[] { 1, 2, 3 }) { lock (this) { yield return 1; } }
foreach (var item in new[] { 1, 2, 3 }) { }
lock (this) { yield return 2; }
if (disposable != null) { using (disposable) { yield return 3; } }
lock (this) { yield return 4; }
if (disposable != null) { using (disposable) { } }
lock (this) { }
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}";
CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
AssertEx.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
"<>4__this",
"disposable",
"<>3__disposable",
"<>7__wrap1",
"<>7__wrap2",
"<>7__wrap3",
"<>7__wrap4",
"<>7__wrap5",
}, module.GetFieldNames("C.<M>d__0"));
});
var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
AssertEx.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
"disposable",
"<>3__disposable",
"<>4__this",
"<>s__1",
"<>s__2",
"<item>5__3",
"<>s__4",
"<>s__5",
"<>s__6",
"<>s__7",
"<item>5__8",
"<>s__9",
"<>s__10",
"<>s__11",
"<>s__12",
"<>s__13",
"<>s__14",
"<>s__15",
"<>s__16"
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"" parameterNames=""disposable"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLocalSlotMap>
<slot kind=""6"" offset=""11"" />
<slot kind=""8"" offset=""11"" />
<slot kind=""0"" offset=""11"" />
<slot kind=""3"" offset=""53"" />
<slot kind=""2"" offset=""53"" />
<slot kind=""6"" offset=""96"" />
<slot kind=""8"" offset=""96"" />
<slot kind=""0"" offset=""96"" />
<slot kind=""3"" offset=""149"" />
<slot kind=""2"" offset=""149"" />
<slot kind=""4"" offset=""216"" />
<slot kind=""3"" offset=""266"" />
<slot kind=""2"" offset=""266"" />
<slot kind=""4"" offset=""333"" />
<slot kind=""3"" offset=""367"" />
<slot kind=""2"" offset=""367"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
}
[WorkItem(836491, "DevDiv")]
[WorkItem(827337, "DevDiv")]
[Fact]
public void DisplayClass_AcrossSuspensionPoints_Debug()
{
string source = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> M()
{
byte x1 = 1;
byte x2 = 1;
byte x3 = 1;
((Action)(() => { x1 = x2 = x3; }))();
yield return x1 + x2 + x3;
yield return x1 + x2 + x3;
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
"<>8__1", // hoisted display class
}, module.GetFieldNames("C.<M>d__0"));
});
// One iterator local entry for the lambda local.
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C+<>c__DisplayClass0_0"" methodName=""<M>b__0"" />
<hoistedLocalScopes>
<slot startOffset=""0x30"" endOffset=""0xea"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x30"" hidden=""true"" />
<entry offset=""0x3b"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" />
<entry offset=""0x3c"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" />
<entry offset=""0x48"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" />
<entry offset=""0x54"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" />
<entry offset=""0x60"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" />
<entry offset=""0x77"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""35"" />
<entry offset=""0xa9"" hidden=""true"" />
<entry offset=""0xb0"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""35"" />
<entry offset=""0xe2"" hidden=""true"" />
<entry offset=""0xe9"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(836491, "DevDiv")]
[WorkItem(827337, "DevDiv")]
[Fact]
public void DisplayClass_InBetweenSuspensionPoints_Release()
{
string source = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> M()
{
byte x1 = 1;
byte x2 = 1;
byte x3 = 1;
((Action)(() => { x1 = x2 = x3; }))();
yield return 1;
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
// TODO: Currently we don't have means necessary to pass information about the display
// class being pushed on evaluation stack, so that EE could find the locals.
// Thus the locals are not available in EE.
var v = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyIL("C.<M>d__0.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 90 (0x5a)
.maxstack 3
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<M>d__0.<>1__state""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0010
IL_000a: ldloc.0
IL_000b: ldc.i4.1
IL_000c: beq.s IL_0051
IL_000e: ldc.i4.0
IL_000f: ret
IL_0010: ldarg.0
IL_0011: ldc.i4.m1
IL_0012: stfld ""int C.<M>d__0.<>1__state""
IL_0017: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_001c: dup
IL_001d: ldc.i4.1
IL_001e: stfld ""byte C.<>c__DisplayClass0_0.x1""
IL_0023: dup
IL_0024: ldc.i4.1
IL_0025: stfld ""byte C.<>c__DisplayClass0_0.x2""
IL_002a: dup
IL_002b: ldc.i4.1
IL_002c: stfld ""byte C.<>c__DisplayClass0_0.x3""
IL_0031: ldftn ""void C.<>c__DisplayClass0_0.<M>b__0()""
IL_0037: newobj ""System.Action..ctor(object, System.IntPtr)""
IL_003c: callvirt ""void System.Action.Invoke()""
IL_0041: ldarg.0
IL_0042: ldc.i4.1
IL_0043: stfld ""int C.<M>d__0.<>2__current""
IL_0048: ldarg.0
IL_0049: ldc.i4.1
IL_004a: stfld ""int C.<M>d__0.<>1__state""
IL_004f: ldc.i4.1
IL_0050: ret
IL_0051: ldarg.0
IL_0052: ldc.i4.m1
IL_0053: stfld ""int C.<M>d__0.<>1__state""
IL_0058: ldc.i4.0
IL_0059: ret
}
");
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x17"" hidden=""true"" />
<entry offset=""0x1c"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" />
<entry offset=""0x23"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" />
<entry offset=""0x2a"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" />
<entry offset=""0x31"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" />
<entry offset=""0x41"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""24"" />
<entry offset=""0x51"" hidden=""true"" />
<entry offset=""0x58"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" />
</sequencePoints>
</method>
</methods>
</symbols>");
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""0"" />
<lambda offset=""95"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
}
[Fact]
public void DisplayClass_InBetweenSuspensionPoints_Debug()
{
string source = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> M()
{
byte x1 = 1;
byte x2 = 1;
byte x3 = 1;
((Action)(() => { x1 = x2 = x3; }))();
yield return 1;
// Possible EnC edit - add lambda:
// () => { x1 }
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
// We need to hoist display class variable to allow adding a new lambda after yield return
// that shares closure with the existing lambda.
var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
"<>8__1", // hoisted display class
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyIL("C.<M>d__0.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 127 (0x7f)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<M>d__0.<>1__state""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0012
IL_000a: br.s IL_000c
IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: beq.s IL_0014
IL_0010: br.s IL_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_0076
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<M>d__0.<>1__state""
IL_001f: ldarg.0
IL_0020: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0025: stfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1""
IL_002a: nop
IL_002b: ldarg.0
IL_002c: ldfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1""
IL_0031: ldc.i4.1
IL_0032: stfld ""byte C.<>c__DisplayClass0_0.x1""
IL_0037: ldarg.0
IL_0038: ldfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1""
IL_003d: ldc.i4.1
IL_003e: stfld ""byte C.<>c__DisplayClass0_0.x2""
IL_0043: ldarg.0
IL_0044: ldfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1""
IL_0049: ldc.i4.1
IL_004a: stfld ""byte C.<>c__DisplayClass0_0.x3""
IL_004f: ldarg.0
IL_0050: ldfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1""
IL_0055: ldftn ""void C.<>c__DisplayClass0_0.<M>b__0()""
IL_005b: newobj ""System.Action..ctor(object, System.IntPtr)""
IL_0060: callvirt ""void System.Action.Invoke()""
IL_0065: nop
IL_0066: ldarg.0
IL_0067: ldc.i4.1
IL_0068: stfld ""int C.<M>d__0.<>2__current""
IL_006d: ldarg.0
IL_006e: ldc.i4.1
IL_006f: stfld ""int C.<M>d__0.<>1__state""
IL_0074: ldc.i4.1
IL_0075: ret
IL_0076: ldarg.0
IL_0077: ldc.i4.m1
IL_0078: stfld ""int C.<M>d__0.<>1__state""
IL_007d: ldc.i4.0
IL_007e: ret
}
");
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
<hoistedLocalScopes>
<slot startOffset=""0x1f"" endOffset=""0x7e"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x1f"" hidden=""true"" />
<entry offset=""0x2a"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" />
<entry offset=""0x2b"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" />
<entry offset=""0x37"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" />
<entry offset=""0x43"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" />
<entry offset=""0x4f"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" />
<entry offset=""0x66"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""24"" />
<entry offset=""0x76"" hidden=""true"" />
<entry offset=""0x7d"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" />
</sequencePoints>
</method>
</methods>
</symbols>");
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""0"" />
<lambda offset=""95"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
}
[WorkItem(836491, "DevDiv")]
[WorkItem(827337, "DevDiv")]
[Fact]
public void DynamicLocal_AcrossSuspensionPoints_Debug()
{
string source = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> M()
{
dynamic d = 1;
yield return d;
d.ToString();
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var v = CompileAndVerify(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
"<d>5__1"
}, module.GetFieldNames("C.<M>d__0"));
});
// CHANGE: Dev12 emits a <dynamiclocal> entry for "d", but gives it slot "-1", preventing it from matching
// any locals when consumed by the EE (i.e. it has no effect). See FUNCBRECEE::IsLocalDynamic.
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
<hoistedLocalScopes>
<slot startOffset=""0x1f"" endOffset=""0xe2"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x1f"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" />
<entry offset=""0x20"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""23"" />
<entry offset=""0x2c"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" />
<entry offset=""0x82"" hidden=""true"" />
<entry offset=""0x89"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""22"" />
<entry offset=""0xe1"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" />
</sequencePoints>
</method>
</methods>
</symbols>");
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>
");
}
[WorkItem(836491, "DevDiv")]
[WorkItem(827337, "DevDiv")]
[WorkItem(1070519, "DevDiv")]
[Fact]
public void DynamicLocal_InBetweenSuspensionPoints_Release()
{
string source = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> M()
{
dynamic d = 1;
yield return d;
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var v = CompileAndVerify(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""1"" localName=""d"" />
</dynamicLocals>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x17"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""23"" />
<entry offset=""0x1e"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" />
<entry offset=""0x6d"" hidden=""true"" />
<entry offset=""0x74"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x76"">
<scope startOffset=""0x17"" endOffset=""0x76"">
<local name=""d"" il_index=""1"" il_start=""0x17"" il_end=""0x76"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(1070519, "DevDiv")]
[Fact]
public void DynamicLocal_InBetweenSuspensionPoints_Debug()
{
string source = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> M()
{
dynamic d = 1;
yield return d;
// Possible EnC edit:
// System.Console.WriteLine(d);
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var v = CompileAndVerify(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
"<d>5__1",
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
<hoistedLocalScopes>
<slot startOffset=""0x1f"" endOffset=""0x8a"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x1f"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" />
<entry offset=""0x20"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""23"" />
<entry offset=""0x2c"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" />
<entry offset=""0x82"" hidden=""true"" />
<entry offset=""0x89"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact, WorkItem(667579, "DevDiv")]
public void DebuggerHiddenIterator()
{
var text = @"
using System;
using System.Collections.Generic;
using System.Diagnostics;
class C
{
static void Main(string[] args)
{
foreach (var x in F()) ;
}
[DebuggerHidden]
static IEnumerable<int> F()
{
throw new Exception();
yield break;
}
}";
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll);
c.VerifyPdb("C+<F>d__1.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<F>d__1"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main"" parameterNames=""args"" />
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x17"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" />
<entry offset=""0x18"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""31"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
}
}
| |
/***************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
***************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.VisualStudio.OLE.Interop;
namespace Microsoft.Samples.VisualStudio.SourceControlIntegration.SccProvider
{
/// <summary>
/// Implements a managed Stream object on top of a COM IStream.
/// </summary>
public sealed class DataStreamFromComStream : Stream, IDisposable
{
private IStream comStream;
/// <summary>
/// Build the managed Stream object on top of the IStream COM object
/// </summary>
/// <param name="comStream">The COM IStream object.</param>
public DataStreamFromComStream(IStream comStream)
: base()
{
this.comStream = comStream;
}
/// <summary>
/// Gets or sets the position (relative to the stream's begin) inside the stream.
/// </summary>
public override long Position
{
get
{
return Seek(0, SeekOrigin.Current);
}
set
{
Seek(value, SeekOrigin.Begin);
}
}
/// <summary>
/// True if it is possible to write on the stream.
/// </summary>
public override bool CanWrite
{
get
{
return true;
}
}
/// <summary>
/// True if it is possible to change the current position inside the stream.
/// </summary>
public override bool CanSeek
{
get
{
return true;
}
}
/// <summary>
/// True if it is possible to read from the stream.
/// </summary>
public override bool CanRead
{
get
{
return true;
}
}
/// <summary>
/// Gets the length of the stream.
/// </summary>
public override long Length
{
get
{
long curPos = this.Position;
long endPos = Seek(0, SeekOrigin.End);
this.Position = curPos;
return endPos - curPos;
}
}
private void _NotImpl(string message)
{
NotSupportedException ex = new NotSupportedException();
throw ex;
}
/// <summary>
/// Dispose this object and release the COM stream.
/// </summary>
public new void Dispose()
{
try
{
if (comStream != null)
{
Flush();
comStream = null;
}
}
finally {
base.Dispose();
}
}
/// <summary>
/// Flush the pending data to the stream.
/// </summary>
public override void Flush()
{
if (comStream != null)
{
try
{
comStream.Commit(0);
}
catch (Exception)
{
}
}
}
/// <summary>
/// Reads a buffer of data from the stream.
/// </summary>
/// <param name="buffer">The buffer to read into.</param>
/// <param name="index">Starting position inside the buffer.</param>
/// <param name="count">Number of bytes to read.</param>
/// <returns>The number of bytes read.</returns>
public override int Read(byte[] buffer, int index, int count)
{
uint bytesRead;
byte[] b = buffer;
if (index != 0)
{
b = new byte[buffer.Length - index];
buffer.CopyTo(b, 0);
}
comStream.Read(b, (uint)count, out bytesRead);
if (index != 0)
{
b.CopyTo(buffer, index);
}
return (int)bytesRead;
}
/// <summary>
/// Sets the length of the stream.
/// </summary>
/// <param name="value">The new lenght.</param>
public override void SetLength(long value)
{
ULARGE_INTEGER ul = new ULARGE_INTEGER();
ul.QuadPart = (ulong)value;
comStream.SetSize(ul);
}
/// <summary>
/// Changes the seek pointer to a new location relative to the current seek pointer
/// or the beginning or end of the stream.
/// </summary>
/// <param name="offset">Displacement to be added to the location indicated by origin.</param>
/// <param name="origin">Specifies the origin for the displacement.</param>
/// <returns>Pointer to the location where this method writes the value of the new seek pointer from the beginning of the stream.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
LARGE_INTEGER l = new LARGE_INTEGER();
ULARGE_INTEGER[] ul = new ULARGE_INTEGER[1];
ul[0] = new ULARGE_INTEGER();
l.QuadPart = offset;
comStream.Seek(l, (uint)origin, ul);
return (long)ul[0].QuadPart;
}
/// <summary>
/// Writes a specified number of bytes into the stream object starting at the current seek pointer.
/// </summary>
/// <param name="buffer">The buffer to write into the stream.</param>
/// <param name="index">Index inside the buffer of the first byte to write.</param>
/// <param name="count">Number of bytes to write.</param>
public override void Write(byte[] buffer, int index, int count)
{
uint bytesWritten;
if (count > 0)
{
byte[] b = buffer;
if (index != 0)
{
b = new byte[buffer.Length - index];
buffer.CopyTo(b, 0);
}
comStream.Write(b, (uint)count, out bytesWritten);
if (bytesWritten != count)
throw new IOException("Didn't write enough bytes to IStream!"); // @TODO: Localize this.
if (index != 0)
{
b.CopyTo(buffer, index);
}
}
}
/// <summary>
/// Close the stream.
/// </summary>
public override void Close()
{
if (comStream != null)
{
Flush();
comStream = null;
GC.SuppressFinalize(this);
}
}
/// <summary></summary>
~DataStreamFromComStream()
{
// CANNOT CLOSE NATIVE STREAMS IN FINALIZER THREAD
// Close();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Timers;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Client;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "InstantMessageModule")]
public class InstantMessageModule : ISharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
/// <value>
/// Is this module enabled?
/// </value>
protected bool m_enabled = false;
protected readonly List<Scene> m_scenes = new List<Scene>();
#region Region Module interface
protected IMessageTransferModule m_TransferModule = null;
public virtual void Initialise(IConfigSource config)
{
if (config.Configs["Messaging"] != null)
{
if (config.Configs["Messaging"].GetString(
"InstantMessageModule", "InstantMessageModule") !=
"InstantMessageModule")
return;
}
m_enabled = true;
}
public virtual void AddRegion(Scene scene)
{
if (!m_enabled)
return;
lock (m_scenes)
{
if (!m_scenes.Contains(scene))
{
m_scenes.Add(scene);
scene.EventManager.OnClientConnect += OnClientConnect;
scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage;
}
}
}
public virtual void RegionLoaded(Scene scene)
{
if (!m_enabled)
return;
if (m_TransferModule == null)
{
m_TransferModule =
scene.RequestModuleInterface<IMessageTransferModule>();
if (m_TransferModule == null)
{
m_log.Error("[INSTANT MESSAGE]: No message transfer module, IM will not work!");
scene.EventManager.OnClientConnect -= OnClientConnect;
scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage;
m_scenes.Clear();
m_enabled = false;
}
}
}
public virtual void RemoveRegion(Scene scene)
{
if (!m_enabled)
return;
lock (m_scenes)
{
m_scenes.Remove(scene);
}
}
protected virtual void OnClientConnect(IClientCore client)
{
IClientIM clientIM;
if (client.TryGet(out clientIM))
{
clientIM.OnInstantMessage += OnInstantMessage;
}
}
public virtual void PostInitialise()
{
}
public virtual void Close()
{
}
public virtual string Name
{
get { return "InstantMessageModule"; }
}
public virtual Type ReplaceableInterface
{
get { return null; }
}
#endregion
/*
public virtual void OnViewerInstantMessage(IClientAPI client, GridInstantMessage im)
{
im.fromAgentName = client.FirstName + " " + client.LastName;
OnInstantMessage(client, im);
}
*/
public virtual void OnInstantMessage(IClientAPI client, GridInstantMessage im)
{
byte dialog = im.dialog;
if (dialog != (byte)InstantMessageDialog.MessageFromAgent
&& dialog != (byte)InstantMessageDialog.StartTyping
&& dialog != (byte)InstantMessageDialog.StopTyping
&& dialog != (byte)InstantMessageDialog.BusyAutoResponse
&& dialog != (byte)InstantMessageDialog.MessageFromObject)
{
return;
}
//DateTime dt = DateTime.UtcNow;
// Ticks from UtcNow, but make it look like local. Evil, huh?
//dt = DateTime.SpecifyKind(dt, DateTimeKind.Local);
//try
//{
// // Convert that to the PST timezone
// TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("America/Los_Angeles");
// dt = TimeZoneInfo.ConvertTime(dt, timeZoneInfo);
//}
//catch
//{
// //m_log.Info("[OFFLINE MESSAGING]: No PST timezone found on this machine. Saving with local timestamp.");
//}
//// And make it look local again to fool the unix time util
//dt = DateTime.SpecifyKind(dt, DateTimeKind.Utc);
// If client is null, this message comes from storage and IS offline
if (client != null)
im.offline = 0;
if (im.offline == 0)
im.timestamp = (uint)Util.UnixTimeSinceEpoch();
if (m_TransferModule != null)
{
m_TransferModule.SendInstantMessage(im,
delegate(bool success)
{
if (dialog == (uint)InstantMessageDialog.StartTyping ||
dialog == (uint)InstantMessageDialog.StopTyping ||
dialog == (uint)InstantMessageDialog.MessageFromObject)
{
return;
}
if ((client != null) && !success)
{
client.SendInstantMessage(
new GridInstantMessage(
null, new UUID(im.fromAgentID), "System",
new UUID(im.toAgentID),
(byte)InstantMessageDialog.BusyAutoResponse,
"Unable to send instant message. "+
"User is not logged in.", false,
new Vector3()));
}
}
);
}
}
/// <summary>
///
/// </summary>
/// <param name="msg"></param>
protected virtual void OnGridInstantMessage(GridInstantMessage msg)
{
// Just call the Text IM handler above
// This event won't be raised unless we have that agent,
// so we can depend on the above not trying to send
// via grid again
//
OnInstantMessage(null, msg);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Manufacturing.Api.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections;
using System.Globalization;
using BigMath;
using Raksha.Asn1;
using Raksha.Asn1.X9;
using Raksha.Math;
using Raksha.Math.EC;
using Raksha.Utilities;
using Raksha.Utilities.Collections;
using Raksha.Utilities.Encoders;
namespace Raksha.Asn1.Sec
{
public sealed class SecNamedCurves
{
private SecNamedCurves()
{
}
private static BigInteger FromHex(
string hex)
{
return new BigInteger(1, Hex.Decode(hex));
}
/*
* secp112r1
*/
internal class Secp112r1Holder
: X9ECParametersHolder
{
private Secp112r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp112r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = (2^128 - 3) / 76439
BigInteger p = FromHex("DB7C2ABF62E35E668076BEAD208B");
BigInteger a = FromHex("DB7C2ABF62E35E668076BEAD2088");
BigInteger b = FromHex("659EF8BA043916EEDE8911702B22");
byte[] S = Hex.Decode("00F50B028E4D696E676875615175290472783FB1");
BigInteger n = FromHex("DB7C2ABF62E35E7628DFAC6561C5");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "09487239995A5EE76B55F9C2F098"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "09487239995A5EE76B55F9C2F098"
+ "A89CE5AF8724C0A23E0E0FF77500"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp112r2
*/
internal class Secp112r2Holder
: X9ECParametersHolder
{
private Secp112r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp112r2Holder();
protected override X9ECParameters CreateParameters()
{
// p = (2^128 - 3) / 76439
BigInteger p = FromHex("DB7C2ABF62E35E668076BEAD208B");
BigInteger a = FromHex("6127C24C05F38A0AAAF65C0EF02C");
BigInteger b = FromHex("51DEF1815DB5ED74FCC34C85D709");
byte[] S = Hex.Decode("002757A1114D696E6768756151755316C05E0BD4");
BigInteger n = FromHex("36DF0AAFD8B8D7597CA10520D04B");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "4BA30AB5E892B4E1649DD0928643"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "4BA30AB5E892B4E1649DD0928643"
+ "ADCD46F5882E3747DEF36E956E97"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp128r1
*/
internal class Secp128r1Holder
: X9ECParametersHolder
{
private Secp128r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp128r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^128 - 2^97 - 1
BigInteger p = FromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF");
BigInteger a = FromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC");
BigInteger b = FromHex("E87579C11079F43DD824993C2CEE5ED3");
byte[] S = Hex.Decode("000E0D4D696E6768756151750CC03A4473D03679");
BigInteger n = FromHex("FFFFFFFE0000000075A30D1B9038A115");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "161FF7528B899B2D0C28607CA52C5B86"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "161FF7528B899B2D0C28607CA52C5B86"
+ "CF5AC8395BAFEB13C02DA292DDED7A83"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp128r2
*/
internal class Secp128r2Holder
: X9ECParametersHolder
{
private Secp128r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp128r2Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^128 - 2^97 - 1
BigInteger p = FromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF");
BigInteger a = FromHex("D6031998D1B3BBFEBF59CC9BBFF9AEE1");
BigInteger b = FromHex("5EEEFCA380D02919DC2C6558BB6D8A5D");
byte[] S = Hex.Decode("004D696E67687561517512D8F03431FCE63B88F4");
BigInteger n = FromHex("3FFFFFFF7FFFFFFFBE0024720613B5A3");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "7B6AA5D85E572983E6FB32A7CDEBC140"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "7B6AA5D85E572983E6FB32A7CDEBC140"
+ "27B6916A894D3AEE7106FE805FC34B44"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp160k1
*/
internal class Secp160k1Holder
: X9ECParametersHolder
{
private Secp160k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp160k1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73");
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(7);
byte[] S = null;
BigInteger n = FromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB"
+ "938CF935318FDCED6BC28286531733C3F03C4FEE"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp160r1
*/
internal class Secp160r1Holder
: X9ECParametersHolder
{
private Secp160r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp160r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^160 - 2^31 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF");
BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC");
BigInteger b = FromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45");
byte[] S = Hex.Decode("1053CDE42C14D696E67687561517533BF3F83345");
BigInteger n = FromHex("0100000000000000000001F4C8F927AED3CA752257");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "4A96B5688EF573284664698968C38BB913CBFC82"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "4A96B5688EF573284664698968C38BB913CBFC82"
+ "23A628553168947D59DCC912042351377AC5FB32"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp160r2
*/
internal class Secp160r2Holder
: X9ECParametersHolder
{
private Secp160r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp160r2Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73");
BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC70");
BigInteger b = FromHex("B4E134D3FB59EB8BAB57274904664D5AF50388BA");
byte[] S = Hex.Decode("B99B99B099B323E02709A4D696E6768756151751");
BigInteger n = FromHex("0100000000000000000000351EE786A818F3A1A16B");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "52DCB034293A117E1F4FF11B30F7199D3144CE6D"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "52DCB034293A117E1F4FF11B30F7199D3144CE6D"
+ "FEAFFEF2E331F296E071FA0DF9982CFEA7D43F2E"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp192k1
*/
internal class Secp192k1Holder
: X9ECParametersHolder
{
private Secp192k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp192k1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37");
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(3);
byte[] S = null;
BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D"
+ "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp192r1
*/
internal class Secp192r1Holder
: X9ECParametersHolder
{
private Secp192r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp192r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^192 - 2^64 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF");
BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC");
BigInteger b = FromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1");
byte[] S = Hex.Decode("3045AE6FC8422F64ED579528D38120EAE12196D5");
BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012"
+ "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp224k1
*/
internal class Secp224k1Holder
: X9ECParametersHolder
{
private Secp224k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp224k1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^224 - 2^32 - 2^12 - 2^11 - 2^9 - 2^7 - 2^4 - 2 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFE56D");
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(5);
byte[] S = null;
BigInteger n = FromHex("010000000000000000000000000001DCE8D2EC6184CAF0A971769FB1F7");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "A1455B334DF099DF30FC28A169A467E9E47075A90F7E650EB6B7A45C"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "A1455B334DF099DF30FC28A169A467E9E47075A90F7E650EB6B7A45C"
+ "7E089FED7FBA344282CAFBD6F7E319F7C0B0BD59E2CA4BDB556D61A5"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp224r1
*/
internal class Secp224r1Holder
: X9ECParametersHolder
{
private Secp224r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp224r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^224 - 2^96 + 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001");
BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE");
BigInteger b = FromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4");
byte[] S = Hex.Decode("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5");
BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21"
+ "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp256k1
*/
internal class Secp256k1Holder
: X9ECParametersHolder
{
private Secp256k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp256k1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^256 - 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F");
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(7);
byte[] S = null;
BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798"
+ "483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp256r1
*/
internal class Secp256r1Holder
: X9ECParametersHolder
{
private Secp256r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp256r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1
BigInteger p = FromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF");
BigInteger a = FromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC");
BigInteger b = FromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B");
byte[] S = Hex.Decode("C49D360886E704936A6678E1139D26B7819F7E90");
BigInteger n = FromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296"
+ "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp384r1
*/
internal class Secp384r1Holder
: X9ECParametersHolder
{
private Secp384r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp384r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^384 - 2^128 - 2^96 + 2^32 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF");
BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC");
BigInteger b = FromHex("B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF");
byte[] S = Hex.Decode("A335926AA319A27A1D00896A6773A4827ACDAC73");
BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7"
+ "3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp521r1
*/
internal class Secp521r1Holder
: X9ECParametersHolder
{
private Secp521r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp521r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^521 - 1
BigInteger p = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");
BigInteger a = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC");
BigInteger b = FromHex("0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00");
byte[] S = Hex.Decode("D09E8800291CB85396CC6717393284AAA0DA64BA");
BigInteger n = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66"
+ "011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect113r1
*/
internal class Sect113r1Holder
: X9ECParametersHolder
{
private Sect113r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect113r1Holder();
private const int m = 113;
private const int k = 9;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("003088250CA6E7C7FE649CE85820F7");
BigInteger b = FromHex("00E8BEE4D3E2260744188BE0E9C723");
byte[] S = Hex.Decode("10E723AB14D696E6768756151756FEBF8FCB49A9");
BigInteger n = FromHex("0100000000000000D9CCEC8A39E56F");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "009D73616F35F4AB1407D73562C10F"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "009D73616F35F4AB1407D73562C10F"
+ "00A52830277958EE84D1315ED31886"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect113r2
*/
internal class Sect113r2Holder
: X9ECParametersHolder
{
private Sect113r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect113r2Holder();
private const int m = 113;
private const int k = 9;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("00689918DBEC7E5A0DD6DFC0AA55C7");
BigInteger b = FromHex("0095E9A9EC9B297BD4BF36E059184F");
byte[] S = Hex.Decode("10C0FB15760860DEF1EEF4D696E676875615175D");
BigInteger n = FromHex("010000000000000108789B2496AF93");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "01A57A6A7B26CA5EF52FCDB8164797"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "01A57A6A7B26CA5EF52FCDB8164797"
+ "00B3ADC94ED1FE674C06E695BABA1D"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect131r1
*/
internal class Sect131r1Holder
: X9ECParametersHolder
{
private Sect131r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect131r1Holder();
private const int m = 131;
private const int k1 = 2;
private const int k2 = 3;
private const int k3 = 8;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("07A11B09A76B562144418FF3FF8C2570B8");
BigInteger b = FromHex("0217C05610884B63B9C6C7291678F9D341");
byte[] S = Hex.Decode("4D696E676875615175985BD3ADBADA21B43A97E2");
BigInteger n = FromHex("0400000000000000023123953A9464B54D");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "0081BAF91FDF9833C40F9C181343638399"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "0081BAF91FDF9833C40F9C181343638399"
+ "078C6E7EA38C001F73C8134B1B4EF9E150"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect131r2
*/
internal class Sect131r2Holder
: X9ECParametersHolder
{
private Sect131r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect131r2Holder();
private const int m = 131;
private const int k1 = 2;
private const int k2 = 3;
private const int k3 = 8;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("03E5A88919D7CAFCBF415F07C2176573B2");
BigInteger b = FromHex("04B8266A46C55657AC734CE38F018F2192");
byte[] S = Hex.Decode("985BD3ADBAD4D696E676875615175A21B43A97E3");
BigInteger n = FromHex("0400000000000000016954A233049BA98F");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "0356DCD8F2F95031AD652D23951BB366A8"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "0356DCD8F2F95031AD652D23951BB366A8"
+ "0648F06D867940A5366D9E265DE9EB240F"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect163k1
*/
internal class Sect163k1Holder
: X9ECParametersHolder
{
private Sect163k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect163k1Holder();
private const int m = 163;
private const int k1 = 3;
private const int k2 = 6;
private const int k3 = 7;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.ValueOf(1);
BigInteger b = BigInteger.ValueOf(1);
byte[] S = null;
BigInteger n = FromHex("04000000000000000000020108A2E0CC0D99F8A5EF");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "02FE13C0537BBC11ACAA07D793DE4E6D5E5C94EEE8"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "02FE13C0537BBC11ACAA07D793DE4E6D5E5C94EEE8"
+ "0289070FB05D38FF58321F2E800536D538CCDAA3D9"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect163r1
*/
internal class Sect163r1Holder
: X9ECParametersHolder
{
private Sect163r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect163r1Holder();
private const int m = 163;
private const int k1 = 3;
private const int k2 = 6;
private const int k3 = 7;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("07B6882CAAEFA84F9554FF8428BD88E246D2782AE2");
BigInteger b = FromHex("0713612DCDDCB40AAB946BDA29CA91F73AF958AFD9");
byte[] S = Hex.Decode("24B7B137C8A14D696E6768756151756FD0DA2E5C");
BigInteger n = FromHex("03FFFFFFFFFFFFFFFFFFFF48AAB689C29CA710279B");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "0369979697AB43897789566789567F787A7876A654"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "0369979697AB43897789566789567F787A7876A654"
+ "00435EDB42EFAFB2989D51FEFCE3C80988F41FF883"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect163r2
*/
internal class Sect163r2Holder
: X9ECParametersHolder
{
private Sect163r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect163r2Holder();
private const int m = 163;
private const int k1 = 3;
private const int k2 = 6;
private const int k3 = 7;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.ValueOf(1);
BigInteger b = FromHex("020A601907B8C953CA1481EB10512F78744A3205FD");
byte[] S = Hex.Decode("85E25BFE5C86226CDB12016F7553F9D0E693A268");
BigInteger n = FromHex("040000000000000000000292FE77E70C12A4234C33");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "03F0EBA16286A2D57EA0991168D4994637E8343E36"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "03F0EBA16286A2D57EA0991168D4994637E8343E36"
+ "00D51FBC6C71A0094FA2CDD545B11C5C0C797324F1"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect193r1
*/
internal class Sect193r1Holder
: X9ECParametersHolder
{
private Sect193r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect193r1Holder();
private const int m = 193;
private const int k = 15;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("0017858FEB7A98975169E171F77B4087DE098AC8A911DF7B01");
BigInteger b = FromHex("00FDFB49BFE6C3A89FACADAA7A1E5BBC7CC1C2E5D831478814");
byte[] S = Hex.Decode("103FAEC74D696E676875615175777FC5B191EF30");
BigInteger n = FromHex("01000000000000000000000000C7F34A778F443ACC920EBA49");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "01F481BC5F0FF84A74AD6CDF6FDEF4BF6179625372D8C0C5E1"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "01F481BC5F0FF84A74AD6CDF6FDEF4BF6179625372D8C0C5E1"
+ "0025E399F2903712CCF3EA9E3A1AD17FB0B3201B6AF7CE1B05"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect193r2
*/
internal class Sect193r2Holder
: X9ECParametersHolder
{
private Sect193r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect193r2Holder();
private const int m = 193;
private const int k = 15;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("0163F35A5137C2CE3EA6ED8667190B0BC43ECD69977702709B");
BigInteger b = FromHex("00C9BB9E8927D4D64C377E2AB2856A5B16E3EFB7F61D4316AE");
byte[] S = Hex.Decode("10B7B4D696E676875615175137C8A16FD0DA2211");
BigInteger n = FromHex("010000000000000000000000015AAB561B005413CCD4EE99D5");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "00D9B67D192E0367C803F39E1A7E82CA14A651350AAE617E8F"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "00D9B67D192E0367C803F39E1A7E82CA14A651350AAE617E8F"
+ "01CE94335607C304AC29E7DEFBD9CA01F596F927224CDECF6C"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect233k1
*/
internal class Sect233k1Holder
: X9ECParametersHolder
{
private Sect233k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect233k1Holder();
private const int m = 233;
private const int k = 74;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(1);
byte[] S = null;
BigInteger n = FromHex("8000000000000000000000000000069D5BB915BCD46EFB1AD5F173ABDF");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "017232BA853A7E731AF129F22FF4149563A419C26BF50A4C9D6EEFAD6126"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "017232BA853A7E731AF129F22FF4149563A419C26BF50A4C9D6EEFAD6126"
+ "01DB537DECE819B7F70F555A67C427A8CD9BF18AEB9B56E0C11056FAE6A3"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect233r1
*/
internal class Sect233r1Holder
: X9ECParametersHolder
{
private Sect233r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect233r1Holder();
private const int m = 233;
private const int k = 74;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.ValueOf(1);
BigInteger b = FromHex("0066647EDE6C332C7F8C0923BB58213B333B20E9CE4281FE115F7D8F90AD");
byte[] S = Hex.Decode("74D59FF07F6B413D0EA14B344B20A2DB049B50C3");
BigInteger n = FromHex("01000000000000000000000000000013E974E72F8A6922031D2603CFE0D7");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "00FAC9DFCBAC8313BB2139F1BB755FEF65BC391F8B36F8F8EB7371FD558B"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "00FAC9DFCBAC8313BB2139F1BB755FEF65BC391F8B36F8F8EB7371FD558B"
+ "01006A08A41903350678E58528BEBF8A0BEFF867A7CA36716F7E01F81052"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect239k1
*/
internal class Sect239k1Holder
: X9ECParametersHolder
{
private Sect239k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect239k1Holder();
private const int m = 239;
private const int k = 158;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(1);
byte[] S = null;
BigInteger n = FromHex("2000000000000000000000000000005A79FEC67CB6E91F1C1DA800E478A5");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "29A0B6A887A983E9730988A68727A8B2D126C44CC2CC7B2A6555193035DC"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "29A0B6A887A983E9730988A68727A8B2D126C44CC2CC7B2A6555193035DC"
+ "76310804F12E549BDB011C103089E73510ACB275FC312A5DC6B76553F0CA"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect283k1
*/
internal class Sect283k1Holder
: X9ECParametersHolder
{
private Sect283k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect283k1Holder();
private const int m = 283;
private const int k1 = 5;
private const int k2 = 7;
private const int k3 = 12;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(1);
byte[] S = null;
BigInteger n = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE9AE2ED07577265DFF7F94451E061E163C61");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "0503213F78CA44883F1A3B8162F188E553CD265F23C1567A16876913B0C2AC2458492836"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "0503213F78CA44883F1A3B8162F188E553CD265F23C1567A16876913B0C2AC2458492836"
+ "01CCDA380F1C9E318D90F95D07E5426FE87E45C0E8184698E45962364E34116177DD2259"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect283r1
*/
internal class Sect283r1Holder
: X9ECParametersHolder
{
private Sect283r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect283r1Holder();
private const int m = 283;
private const int k1 = 5;
private const int k2 = 7;
private const int k3 = 12;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.ValueOf(1);
BigInteger b = FromHex("027B680AC8B8596DA5A4AF8A19A0303FCA97FD7645309FA2A581485AF6263E313B79A2F5");
byte[] S = Hex.Decode("77E2B07370EB0F832A6DD5B62DFC88CD06BB84BE");
BigInteger n = FromHex("03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEF90399660FC938A90165B042A7CEFADB307");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "05F939258DB7DD90E1934F8C70B0DFEC2EED25B8557EAC9C80E2E198F8CDBECD86B12053"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "05F939258DB7DD90E1934F8C70B0DFEC2EED25B8557EAC9C80E2E198F8CDBECD86B12053"
+ "03676854FE24141CB98FE6D4B20D02B4516FF702350EDDB0826779C813F0DF45BE8112F4"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect409k1
*/
internal class Sect409k1Holder
: X9ECParametersHolder
{
private Sect409k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect409k1Holder();
private const int m = 409;
private const int k = 87;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(1);
byte[] S = null;
BigInteger n = FromHex("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE5F83B2D4EA20400EC4557D5ED3E3E7CA5B4B5C83B8E01E5FCF");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "0060F05F658F49C1AD3AB1890F7184210EFD0987E307C84C27ACCFB8F9F67CC2C460189EB5AAAA62EE222EB1B35540CFE9023746"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "0060F05F658F49C1AD3AB1890F7184210EFD0987E307C84C27ACCFB8F9F67CC2C460189EB5AAAA62EE222EB1B35540CFE9023746"
+ "01E369050B7C4E42ACBA1DACBF04299C3460782F918EA427E6325165E9EA10E3DA5F6C42E9C55215AA9CA27A5863EC48D8E0286B"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect409r1
*/
internal class Sect409r1Holder
: X9ECParametersHolder
{
private Sect409r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect409r1Holder();
private const int m = 409;
private const int k = 87;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.ValueOf(1);
BigInteger b = FromHex("0021A5C2C8EE9FEB5C4B9A753B7B476B7FD6422EF1F3DD674761FA99D6AC27C8A9A197B272822F6CD57A55AA4F50AE317B13545F");
byte[] S = Hex.Decode("4099B5A457F9D69F79213D094C4BCD4D4262210B");
BigInteger n = FromHex("010000000000000000000000000000000000000000000000000001E2AAD6A612F33307BE5FA47C3C9E052F838164CD37D9A21173");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "015D4860D088DDB3496B0C6064756260441CDE4AF1771D4DB01FFE5B34E59703DC255A868A1180515603AEAB60794E54BB7996A7"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "015D4860D088DDB3496B0C6064756260441CDE4AF1771D4DB01FFE5B34E59703DC255A868A1180515603AEAB60794E54BB7996A7"
+ "0061B1CFAB6BE5F32BBFA78324ED106A7636B9C5A7BD198D0158AA4F5488D08F38514F1FDF4B4F40D2181B3681C364BA0273C706"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect571k1
*/
internal class Sect571k1Holder
: X9ECParametersHolder
{
private Sect571k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect571k1Holder();
private const int m = 571;
private const int k1 = 2;
private const int k2 = 5;
private const int k3 = 10;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(1);
byte[] S = null;
BigInteger n = FromHex("020000000000000000000000000000000000000000000000000000000000000000000000131850E1F19A63E4B391A8DB917F4138B630D84BE5D639381E91DEB45CFE778F637C1001");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "026EB7A859923FBC82189631F8103FE4AC9CA2970012D5D46024804801841CA44370958493B205E647DA304DB4CEB08CBBD1BA39494776FB988B47174DCA88C7E2945283A01C8972"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "026EB7A859923FBC82189631F8103FE4AC9CA2970012D5D46024804801841CA44370958493B205E647DA304DB4CEB08CBBD1BA39494776FB988B47174DCA88C7E2945283A01C8972"
+ "0349DC807F4FBF374F4AEADE3BCA95314DD58CEC9F307A54FFC61EFC006D8A2C9D4979C0AC44AEA74FBEBBB9F772AEDCB620B01A7BA7AF1B320430C8591984F601CD4C143EF1C7A3"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect571r1
*/
internal class Sect571r1Holder
: X9ECParametersHolder
{
private Sect571r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect571r1Holder();
private const int m = 571;
private const int k1 = 2;
private const int k2 = 5;
private const int k3 = 10;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.ValueOf(1);
BigInteger b = FromHex("02F40E7E2221F295DE297117B7F3D62F5C6A97FFCB8CEFF1CD6BA8CE4A9A18AD84FFABBD8EFA59332BE7AD6756A66E294AFD185A78FF12AA520E4DE739BACA0C7FFEFF7F2955727A");
byte[] S = Hex.Decode("2AA058F73A0E33AB486B0F610410C53A7F132310");
BigInteger n = FromHex("03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE661CE18FF55987308059B186823851EC7DD9CA1161DE93D5174D66E8382E9BB2FE84E47");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "0303001D34B856296C16C0D40D3CD7750A93D1D2955FA80AA5F40FC8DB7B2ABDBDE53950F4C0D293CDD711A35B67FB1499AE60038614F1394ABFA3B4C850D927E1E7769C8EEC2D19"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "0303001D34B856296C16C0D40D3CD7750A93D1D2955FA80AA5F40FC8DB7B2ABDBDE53950F4C0D293CDD711A35B67FB1499AE60038614F1394ABFA3B4C850D927E1E7769C8EEC2D19"
+ "037BF27342DA639B6DCCFFFEB73D69D78C6C27A6009CBBCA1980F8533921E8A684423E43BAB08A576291AF8F461BB2A8B3531D2F0485C19B16E2F1516E23DD3C1A4827AF1B8AC15B"));
return new X9ECParameters(curve, G, n, h, S);
}
}
private static readonly IDictionary objIds = Platform.CreateHashtable();
private static readonly IDictionary curves = Platform.CreateHashtable();
private static readonly IDictionary names = Platform.CreateHashtable();
private static void DefineCurve(
string name,
DerObjectIdentifier oid,
X9ECParametersHolder holder)
{
objIds.Add(name, oid);
names.Add(oid, name);
curves.Add(oid, holder);
}
static SecNamedCurves()
{
DefineCurve("secp112r1", SecObjectIdentifiers.SecP112r1, Secp112r1Holder.Instance);
DefineCurve("secp112r2", SecObjectIdentifiers.SecP112r2, Secp112r2Holder.Instance);
DefineCurve("secp128r1", SecObjectIdentifiers.SecP128r1, Secp128r1Holder.Instance);
DefineCurve("secp128r2", SecObjectIdentifiers.SecP128r2, Secp128r2Holder.Instance);
DefineCurve("secp160k1", SecObjectIdentifiers.SecP160k1, Secp160k1Holder.Instance);
DefineCurve("secp160r1", SecObjectIdentifiers.SecP160r1, Secp160r1Holder.Instance);
DefineCurve("secp160r2", SecObjectIdentifiers.SecP160r2, Secp160r2Holder.Instance);
DefineCurve("secp192k1", SecObjectIdentifiers.SecP192k1, Secp192k1Holder.Instance);
DefineCurve("secp192r1", SecObjectIdentifiers.SecP192r1, Secp192r1Holder.Instance);
DefineCurve("secp224k1", SecObjectIdentifiers.SecP224k1, Secp224k1Holder.Instance);
DefineCurve("secp224r1", SecObjectIdentifiers.SecP224r1, Secp224r1Holder.Instance);
DefineCurve("secp256k1", SecObjectIdentifiers.SecP256k1, Secp256k1Holder.Instance);
DefineCurve("secp256r1", SecObjectIdentifiers.SecP256r1, Secp256r1Holder.Instance);
DefineCurve("secp384r1", SecObjectIdentifiers.SecP384r1, Secp384r1Holder.Instance);
DefineCurve("secp521r1", SecObjectIdentifiers.SecP521r1, Secp521r1Holder.Instance);
DefineCurve("sect113r1", SecObjectIdentifiers.SecT113r1, Sect113r1Holder.Instance);
DefineCurve("sect113r2", SecObjectIdentifiers.SecT113r2, Sect113r2Holder.Instance);
DefineCurve("sect131r1", SecObjectIdentifiers.SecT131r1, Sect131r1Holder.Instance);
DefineCurve("sect131r2", SecObjectIdentifiers.SecT131r2, Sect131r2Holder.Instance);
DefineCurve("sect163k1", SecObjectIdentifiers.SecT163k1, Sect163k1Holder.Instance);
DefineCurve("sect163r1", SecObjectIdentifiers.SecT163r1, Sect163r1Holder.Instance);
DefineCurve("sect163r2", SecObjectIdentifiers.SecT163r2, Sect163r2Holder.Instance);
DefineCurve("sect193r1", SecObjectIdentifiers.SecT193r1, Sect193r1Holder.Instance);
DefineCurve("sect193r2", SecObjectIdentifiers.SecT193r2, Sect193r2Holder.Instance);
DefineCurve("sect233k1", SecObjectIdentifiers.SecT233k1, Sect233k1Holder.Instance);
DefineCurve("sect233r1", SecObjectIdentifiers.SecT233r1, Sect233r1Holder.Instance);
DefineCurve("sect239k1", SecObjectIdentifiers.SecT239k1, Sect239k1Holder.Instance);
DefineCurve("sect283k1", SecObjectIdentifiers.SecT283k1, Sect283k1Holder.Instance);
DefineCurve("sect283r1", SecObjectIdentifiers.SecT283r1, Sect283r1Holder.Instance);
DefineCurve("sect409k1", SecObjectIdentifiers.SecT409k1, Sect409k1Holder.Instance);
DefineCurve("sect409r1", SecObjectIdentifiers.SecT409r1, Sect409r1Holder.Instance);
DefineCurve("sect571k1", SecObjectIdentifiers.SecT571k1, Sect571k1Holder.Instance);
DefineCurve("sect571r1", SecObjectIdentifiers.SecT571r1, Sect571r1Holder.Instance);
}
public static X9ECParameters GetByName(
string name)
{
DerObjectIdentifier oid = (DerObjectIdentifier)
objIds[name.ToLowerInvariant()];
return oid == null ? null : GetByOid(oid);
}
/**
* return the X9ECParameters object for the named curve represented by
* the passed in object identifier. Null if the curve isn't present.
*
* @param oid an object identifier representing a named curve, if present.
*/
public static X9ECParameters GetByOid(
DerObjectIdentifier oid)
{
X9ECParametersHolder holder = (X9ECParametersHolder) curves[oid];
return holder == null ? null : holder.Parameters;
}
/**
* return the object identifier signified by the passed in name. Null
* if there is no object identifier associated with name.
*
* @return the object identifier associated with name, if present.
*/
public static DerObjectIdentifier GetOid(
string name)
{
return (DerObjectIdentifier) objIds[name.ToLowerInvariant()];
}
/**
* return the named curve name represented by the given object identifier.
*/
public static string GetName(
DerObjectIdentifier oid)
{
return (string) names[oid];
}
/**
* returns an enumeration containing the name strings for curves
* contained in this structure.
*/
public static IEnumerable Names
{
get { return new EnumerableProxy(objIds.Keys); }
}
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
namespace EpisodeInformer
{
public partial class AboutBox : Form
{
public string AssemblyTitle
{
get
{
object[] customAttributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
if (customAttributes.Length > 0)
{
AssemblyTitleAttribute assemblyTitleAttribute = (AssemblyTitleAttribute)customAttributes[0];
if (assemblyTitleAttribute.Title != "")
return assemblyTitleAttribute.Title;
}
return Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
}
}
public string AssemblyVersion
{
get
{
return Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
public string AssemblyDescription
{
get
{
object[] customAttributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false);
if (customAttributes.Length == 0)
return "";
return ((AssemblyDescriptionAttribute)customAttributes[0]).Description;
}
}
public string AssemblyProduct
{
get
{
object[] customAttributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false);
if (customAttributes.Length == 0)
return "";
return ((AssemblyProductAttribute)customAttributes[0]).Product;
}
}
public string AssemblyCopyright
{
get
{
object[] customAttributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
if (customAttributes.Length == 0)
return "";
return ((AssemblyCopyrightAttribute)customAttributes[0]).Copyright;
}
}
public string AssemblyCompany
{
get
{
object[] customAttributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
if (customAttributes.Length == 0)
return "";
return ((AssemblyCompanyAttribute)customAttributes[0]).Company;
}
}
public AboutBox()
{
this.InitializeComponent();
this.Text = string.Format("About {0}", (object)this.AssemblyTitle);
this.labelProductName.Text = this.AssemblyProduct;
this.labelVersion.Text = string.Format("Version {0}", (object)this.AssemblyVersion);
this.labelCopyright.Text = this.AssemblyCopyright;
this.labelCompanyName.Text = this.AssemblyCompany;
this.Text = string.Format("About EpisodeInformer v{0}", (object)this.AssemblyVersion);
}
private void okButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
Process.Start("http://www.facebook.com/lokukarawita");
}
catch (Exception)
{
}
}
private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
Process.Start("http://www.gnu.org/licenses/gpl.html");
}
catch (Exception)
{
}
}
private void label1_Click(object sender, EventArgs e)
{
}
private void lnlLblTvDB_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
Process.Start("http://thetvdb.com/");
}
catch (Exception)
{
}
}
private void lnkLbkCCLicence_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
Process.Start("http://creativecommons.org/licenses/by/3.0/us/");
}
catch (Exception)
{
}
}
private void lnlLblCXEX_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
Process.Start("http://code.google.com/p/csexwb2/");
}
catch (Exception)
{
}
}
private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
Process.Start(" http://www.codeproject.com/KB/miscctrl/csEXWB.aspx");
}
catch (Exception)
{
}
}
private void lblGnuGPL2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
Process.Start("http://www.gnu.org/licenses/gpl.html");
}
catch (Exception)
{
}
}
private void lnlCPLices_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
Process.Start("http://www.codeproject.com/info/cpol10.aspx");
}
catch (Exception)
{
}
}
private void linkLabel4_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
Process.Start("\thttp://facebook.com/prashaneleperuma");
}
catch (Exception)
{
}
}
private void linkLabel5_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
Process.Start("http://www.facebook.com/profile.php?id=1034330747");
}
catch (Exception)
{
}
}
private void linkLabel2_LinkClicked_1(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
Process.Start("http://corlive.com/lokukarawita?subject=EpisodeInformer Contact:");
}
catch (Exception)
{
}
}
private void linkLabel7_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
Process.Start("http://corlive.com/lokukarawita?subject=EpisodeInformer Technical:");
}
catch (Exception)
{
}
}
private void linkLabel6_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
Process.Start("http://dotnetzip.codeplex.com/");
}
catch (Exception)
{
}
}
private void linkLabel8_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
Process.Start("http://dotnetzip.codeplex.com/license");
}
catch (Exception)
{
}
}
private void linkLabel9_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
Process.Start("http://sourceforge.net/projects/torrentloader");
}
catch (Exception)
{
}
}
}
}
| |
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEngine;
using UnityEngine.EventSystems;
using System;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Fungus
{
/// <summary>
/// Visual scripting controller for the Flowchart programming language.
/// Flowchart objects may be edited visually using the Flowchart editor window.
/// </summary>
[ExecuteInEditMode]
public class Flowchart : MonoBehaviour, ISubstitutionHandler
{
[HideInInspector]
[SerializeField] protected int version = 0; // Default to 0 to always trigger an update for older versions of Fungus.
[HideInInspector]
[SerializeField] protected Vector2 scrollPos;
[HideInInspector]
[SerializeField] protected Vector2 variablesScrollPos;
[HideInInspector]
[SerializeField] protected bool variablesExpanded = true;
[HideInInspector]
[SerializeField] protected float blockViewHeight = 400;
[HideInInspector]
[SerializeField] protected float zoom = 1f;
[HideInInspector]
[SerializeField] protected Rect scrollViewRect;
[HideInInspector]
[SerializeField] protected List<Block> selectedBlocks = new List<Block>();
[HideInInspector]
[SerializeField] protected List<Command> selectedCommands = new List<Command>();
[HideInInspector]
[SerializeField] protected List<Variable> variables = new List<Variable>();
[TextArea(3, 5)]
[Tooltip("Description text displayed in the Flowchart editor window")]
[SerializeField] protected string description = "";
[Range(0f, 5f)]
[Tooltip("Adds a pause after each execution step to make it easier to visualise program flow. Editor only, has no effect in platform builds.")]
[SerializeField] protected float stepPause = 0f;
[Tooltip("Use command color when displaying the command list in the Fungus Editor window")]
[SerializeField] protected bool colorCommands = true;
[Tooltip("Hides the Flowchart block and command components in the inspector. Deselect to inspect the block and command components that make up the Flowchart.")]
[SerializeField] protected bool hideComponents = true;
[Tooltip("Saves the selected block and commands when saving the scene. Helps avoid version control conflicts if you've only changed the active selection.")]
[SerializeField] protected bool saveSelection = true;
[Tooltip("Unique identifier for this flowchart in localized string keys. If no id is specified then the name of the Flowchart object will be used.")]
[SerializeField] protected string localizationId = "";
[Tooltip("Display line numbers in the command list in the Block inspector.")]
[SerializeField] protected bool showLineNumbers = false;
[Tooltip("List of commands to hide in the Add Command menu. Use this to restrict the set of commands available when editing a Flowchart.")]
[SerializeField] protected List<string> hideCommands = new List<string>();
[Tooltip("Lua Environment to be used by default for all Execute Lua commands in this Flowchart")]
[SerializeField] protected LuaEnvironment luaEnvironment;
[Tooltip("The ExecuteLua command adds a global Lua variable with this name bound to the flowchart prior to executing.")]
[SerializeField] protected string luaBindingName = "flowchart";
protected static List<Flowchart> cachedFlowcharts = new List<Flowchart>();
protected static bool eventSystemPresent;
protected StringSubstituter stringSubstituer;
#if UNITY_5_4_OR_NEWER
protected virtual void Awake()
{
CheckEventSystem();
UnityEngine.SceneManagement.SceneManager.activeSceneChanged += (A, B) => {
LevelWasLoaded();
};
}
#else
protected virtual void OnLevelWasLoaded(int level)
{
LevelWasLoaded();
}
#endif
protected virtual void LevelWasLoaded()
{
// Reset the flag for checking for an event system as there may not be one in the newly loaded scene.
eventSystemPresent = false;
}
protected virtual void Start()
{
CheckEventSystem();
}
// There must be an Event System in the scene for Say and Menu input to work.
// This method will automatically instantiate one if none exists.
protected virtual void CheckEventSystem()
{
if (eventSystemPresent)
{
return;
}
EventSystem eventSystem = GameObject.FindObjectOfType<EventSystem>();
if (eventSystem == null)
{
// Auto spawn an Event System from the prefab
GameObject prefab = Resources.Load<GameObject>("Prefabs/EventSystem");
if (prefab != null)
{
GameObject go = Instantiate(prefab) as GameObject;
go.name = "EventSystem";
}
}
eventSystemPresent = true;
}
protected virtual void OnEnable()
{
if (!cachedFlowcharts.Contains(this))
{
cachedFlowcharts.Add(this);
}
CheckItemIds();
CleanupComponents();
UpdateVersion();
StringSubstituter.RegisterHandler(this);
}
protected virtual void OnDisable()
{
cachedFlowcharts.Remove(this);
StringSubstituter.UnregisterHandler(this);
}
protected virtual void UpdateVersion()
{
if (version == FungusConstants.CurrentVersion)
{
// No need to update
return;
}
// Tell all components that implement IUpdateable to update to the new version
var components = GetComponents<Component>();
for (int i = 0; i < components.Length; i++)
{
var component = components[i];
IUpdateable u = component as IUpdateable;
if (u != null)
{
u.UpdateToVersion(version, FungusConstants.CurrentVersion);
}
}
version = FungusConstants.CurrentVersion;
}
protected virtual void CheckItemIds()
{
// Make sure item ids are unique and monotonically increasing.
// This should always be the case, but some legacy Flowcharts may have issues.
List<int> usedIds = new List<int>();
var blocks = GetComponents<Block>();
for (int i = 0; i < blocks.Length; i++)
{
var block = blocks[i];
if (block.ItemId == -1 || usedIds.Contains(block.ItemId))
{
block.ItemId = NextItemId();
}
usedIds.Add(block.ItemId);
}
var commands = GetComponents<Command>();
for (int i = 0; i < commands.Length; i++)
{
var command = commands[i];
if (command.ItemId == -1 || usedIds.Contains(command.ItemId))
{
command.ItemId = NextItemId();
}
usedIds.Add(command.ItemId);
}
}
protected virtual void CleanupComponents()
{
// Delete any unreferenced components which shouldn't exist any more
// Unreferenced components don't have any effect on the flowchart behavior, but
// they waste memory so should be cleared out periodically.
// Remove any null entries in the variables list
// It shouldn't happen but it seemed to occur for a user on the forum
variables.RemoveAll(item => item == null);
var allVariables = GetComponents<Variable>();
for (int i = 0; i < allVariables.Length; i++)
{
var variable = allVariables[i];
if (!variables.Contains(variable))
{
DestroyImmediate(variable);
}
}
var blocks = GetComponents<Block>();
var commands = GetComponents<Command>();
for (int i = 0; i < commands.Length; i++)
{
var command = commands[i];
bool found = false;
for (int j = 0; j < blocks.Length; j++)
{
var block = blocks[j];
if (block.CommandList.Contains(command))
{
found = true;
break;
}
}
if (!found)
{
DestroyImmediate(command);
}
}
var eventHandlers = GetComponents<EventHandler>();
for (int i = 0; i < eventHandlers.Length; i++)
{
var eventHandler = eventHandlers[i];
bool found = false;
for (int j = 0; j < blocks.Length; j++)
{
var block = blocks[j];
if (block._EventHandler == eventHandler)
{
found = true;
break;
}
}
if (!found)
{
DestroyImmediate(eventHandler);
}
}
}
protected virtual Block CreateBlockComponent(GameObject parent)
{
Block block = parent.AddComponent<Block>();
return block;
}
#region Public members
/// <summary>
/// Cached list of flowchart objects in the scene for fast lookup.
/// </summary>
public static List<Flowchart> CachedFlowcharts { get { return cachedFlowcharts; } }
/// <summary>
/// Sends a message to all Flowchart objects in the current scene.
/// Any block with a matching MessageReceived event handler will start executing.
/// </summary>
public static void BroadcastFungusMessage(string messageName)
{
var eventHandlers = UnityEngine.Object.FindObjectsOfType<MessageReceived>();
for (int i = 0; i < eventHandlers.Length; i++)
{
var eventHandler = eventHandlers[i];
eventHandler.OnSendFungusMessage(messageName);
}
}
/// <summary>
/// Scroll position of Flowchart editor window.
/// </summary>
public virtual Vector2 ScrollPos { get { return scrollPos; } set { scrollPos = value; } }
/// <summary>
/// Scroll position of Flowchart variables window.
/// </summary>
public virtual Vector2 VariablesScrollPos { get { return variablesScrollPos; } set { variablesScrollPos = value; } }
/// <summary>
/// Show the variables pane.
/// </summary>
public virtual bool VariablesExpanded { get { return variablesExpanded; } set { variablesExpanded = value; } }
/// <summary>
/// Height of command block view in inspector.
/// </summary>
public virtual float BlockViewHeight { get { return blockViewHeight; } set { blockViewHeight = value; } }
/// <summary>
/// Zoom level of Flowchart editor window.
/// </summary>
public virtual float Zoom { get { return zoom; } set { zoom = value; } }
/// <summary>
/// Scrollable area for Flowchart editor window.
/// </summary>
public virtual Rect ScrollViewRect { get { return scrollViewRect; } set { scrollViewRect = value; } }
/// <summary>
/// Current actively selected block in the Flowchart editor.
/// </summary>
public virtual Block SelectedBlock
{
get
{
return selectedBlocks.FirstOrDefault();
}
set
{
selectedBlocks.Clear();
selectedBlocks.Add(value);
}
}
public virtual List<Block> SelectedBlocks { get { return selectedBlocks; } set { selectedBlocks = value; } }
/// <summary>
/// Currently selected command in the Flowchart editor.
/// </summary>
public virtual List<Command> SelectedCommands { get { return selectedCommands; } }
/// <summary>
/// The list of variables that can be accessed by the Flowchart.
/// </summary>
public virtual List<Variable> Variables { get { return variables; } }
/// <summary>
/// Description text displayed in the Flowchart editor window
/// </summary>
public virtual string Description { get { return description; } }
/// <summary>
/// Slow down execution in the editor to make it easier to visualise program flow.
/// </summary>
public virtual float StepPause { get { return stepPause; } }
/// <summary>
/// Use command color when displaying the command list in the inspector.
/// </summary>
public virtual bool ColorCommands { get { return colorCommands; } }
/// <summary>
/// Saves the selected block and commands when saving the scene. Helps avoid version control conflicts if you've only changed the active selection.
/// </summary>
public virtual bool SaveSelection { get { return saveSelection; } }
/// <summary>
/// Unique identifier for identifying this flowchart in localized string keys.
/// </summary>
public virtual string LocalizationId { get { return localizationId; } }
/// <summary>
/// Display line numbers in the command list in the Block inspector.
/// </summary>
public virtual bool ShowLineNumbers { get { return showLineNumbers; } }
/// <summary>
/// Lua Environment to be used by default for all Execute Lua commands in this Flowchart.
/// </summary>
public virtual LuaEnvironment LuaEnv { get { return luaEnvironment; } }
/// <summary>
/// The ExecuteLua command adds a global Lua variable with this name bound to the flowchart prior to executing.
/// </summary>
public virtual string LuaBindingName { get { return luaBindingName; } }
/// <summary>
/// Position in the center of all blocks in the flowchart.
/// </summary>
public virtual Vector2 CenterPosition { set; get; }
/// <summary>
/// Variable to track flowchart's version so components can update to new versions.
/// </summary>
public int Version { set { version = value; } }
/// <summary>
/// Returns true if the Flowchart gameobject is active.
/// </summary>
public bool IsActive()
{
return gameObject.activeInHierarchy;
}
/// <summary>
/// Returns the Flowchart gameobject name.
/// </summary>
public string GetName()
{
return gameObject.name;
}
/// <summary>
/// Returns the next id to assign to a new flowchart item.
/// Item ids increase monotically so they are guaranteed to
/// be unique within a Flowchart.
/// </summary>
public int NextItemId()
{
int maxId = -1;
var blocks = GetComponents<Block>();
for (int i = 0; i < blocks.Length; i++)
{
var block = blocks[i];
maxId = Math.Max(maxId, block.ItemId);
}
var commands = GetComponents<Command>();
for (int i = 0; i < commands.Length; i++)
{
var command = commands[i];
maxId = Math.Max(maxId, command.ItemId);
}
return maxId + 1;
}
/// <summary>
/// Create a new block node which you can then add commands to.
/// </summary>
public virtual Block CreateBlock(Vector2 position)
{
Block b = CreateBlockComponent(gameObject);
b._NodeRect = new Rect(position.x, position.y, 0, 0);
b.BlockName = GetUniqueBlockKey(b.BlockName, b);
b.ItemId = NextItemId();
return b;
}
/// <summary>
/// Returns the named Block in the flowchart, or null if not found.
/// </summary>
public virtual Block FindBlock(string blockName)
{
var blocks = GetComponents<Block>();
for (int i = 0; i < blocks.Length; i++)
{
var block = blocks[i];
if (block.BlockName == blockName)
{
return block;
}
}
return null;
}
/// <summary>
/// Execute a child block in the Flowchart.
/// You can use this method in a UI event. e.g. to handle a button click.
public virtual void ExecuteBlock(string blockName)
{
var block = FindBlock(blockName);
if (block == null)
{
Debug.LogError("Block " + blockName + "does not exist");
return;
}
if (!ExecuteBlock(block))
{
Debug.LogWarning("Block " + blockName + "failed to execute");
}
}
/// <summary>
/// Stops an executing Block in the Flowchart.
/// </summary>
public virtual void StopBlock(string blockName)
{
var block = FindBlock(blockName);
if (block == null)
{
Debug.LogError("Block " + blockName + "does not exist");
return;
}
if (block.IsExecuting())
{
block.Stop();
}
}
/// <summary>
/// Execute a child block in the flowchart.
/// The block must be in an idle state to be executed.
/// This version provides extra options to control how the block is executed.
/// Returns true if the Block started execution.
/// </summary>
public virtual bool ExecuteBlock(Block block, int commandIndex = 0, Action onComplete = null)
{
if (block == null)
{
Debug.LogError("Block must not be null");
return false;
}
if (((Block)block).gameObject != gameObject)
{
Debug.LogError("Block must belong to the same gameobject as this Flowchart");
return false;
}
// Can't restart a running block, have to wait until it's idle again
if (block.IsExecuting())
{
return false;
}
// Start executing the Block as a new coroutine
StartCoroutine(block.Execute(commandIndex, onComplete));
return true;
}
/// <summary>
/// Stop all executing Blocks in this Flowchart.
/// </summary>
public virtual void StopAllBlocks()
{
var blocks = GetComponents<Block>();
for (int i = 0; i < blocks.Length; i++)
{
var block = blocks[i];
if (block.IsExecuting())
{
block.Stop();
}
}
}
/// <summary>
/// Sends a message to this Flowchart only.
/// Any block with a matching MessageReceived event handler will start executing.
/// </summary>
public virtual void SendFungusMessage(string messageName)
{
var eventHandlers = GetComponents<MessageReceived>();
for (int i = 0; i < eventHandlers.Length; i++)
{
var eventHandler = eventHandlers[i];
eventHandler.OnSendFungusMessage(messageName);
}
}
/// <summary>
/// Returns a new variable key that is guaranteed not to clash with any existing variable in the list.
/// </summary>
public virtual string GetUniqueVariableKey(string originalKey, Variable ignoreVariable = null)
{
int suffix = 0;
string baseKey = originalKey;
// Only letters and digits allowed
char[] arr = baseKey.Where(c => (char.IsLetterOrDigit(c) || c == '_')).ToArray();
baseKey = new string(arr);
// No leading digits allowed
baseKey = baseKey.TrimStart('0','1','2','3','4','5','6','7','8','9');
// No empty keys allowed
if (baseKey.Length == 0)
{
baseKey = "Var";
}
string key = baseKey;
while (true)
{
bool collision = false;
for (int i = 0; i < variables.Count; i++)
{
var variable = variables[i];
if (variable == null || variable == ignoreVariable || variable.Key == null)
{
continue;
}
if (variable.Key.Equals(key, StringComparison.CurrentCultureIgnoreCase))
{
collision = true;
suffix++;
key = baseKey + suffix;
}
}
if (!collision)
{
return key;
}
}
}
/// <summary>
/// Returns a new Block key that is guaranteed not to clash with any existing Block in the Flowchart.
/// </summary>
public virtual string GetUniqueBlockKey(string originalKey, Block ignoreBlock = null)
{
int suffix = 0;
string baseKey = originalKey.Trim();
// No empty keys allowed
if (baseKey.Length == 0)
{
baseKey = FungusConstants.DefaultBlockName;
}
var blocks = GetComponents<Block>();
string key = baseKey;
while (true)
{
bool collision = false;
for (int i = 0; i < blocks.Length; i++)
{
var block = blocks[i];
if (block == ignoreBlock || block.BlockName == null)
{
continue;
}
if (block.BlockName.Equals(key, StringComparison.CurrentCultureIgnoreCase))
{
collision = true;
suffix++;
key = baseKey + suffix;
}
}
if (!collision)
{
return key;
}
}
}
/// <summary>
/// Returns a new Label key that is guaranteed not to clash with any existing Label in the Block.
/// </summary>
public virtual string GetUniqueLabelKey(string originalKey, Label ignoreLabel)
{
int suffix = 0;
string baseKey = originalKey.Trim();
// No empty keys allowed
if (baseKey.Length == 0)
{
baseKey = "New Label";
}
var block = ignoreLabel.ParentBlock;
string key = baseKey;
while (true)
{
bool collision = false;
var commandList = block.CommandList;
for (int i = 0; i < commandList.Count; i++)
{
var command = commandList[i];
Label label = command as Label;
if (label == null || label == ignoreLabel)
{
continue;
}
if (label.Key.Equals(key, StringComparison.CurrentCultureIgnoreCase))
{
collision = true;
suffix++;
key = baseKey + suffix;
}
}
if (!collision)
{
return key;
}
}
}
/// <summary>
/// Returns the variable with the specified key, or null if the key is not found.
/// You will need to cast the returned variable to the correct sub-type.
/// You can then access the variable's value using the Value property. e.g.
/// BooleanVariable boolVar = flowchart.GetVariable("MyBool") as BooleanVariable;
/// boolVar.Value = false;
/// </summary>
public Variable GetVariable(string key)
{
for (int i = 0; i < variables.Count; i++)
{
var variable = variables[i];
if (variable != null && variable.Key == key)
{
return variable;
}
}
return null;
}
/// <summary>
/// Returns the variable with the specified key, or null if the key is not found.
/// You can then access the variable's value using the Value property. e.g.
/// BooleanVariable boolVar = flowchart.GetVariable<BooleanVariable>("MyBool");
/// boolVar.Value = false;
/// </summary>
public T GetVariable<T>(string key) where T : Variable
{
for (int i = 0; i < variables.Count; i++)
{
var variable = variables[i];
if (variable != null && variable.Key == key)
{
return variable as T;
}
}
Debug.LogWarning("Variable " + key + " not found.");
return null;
}
/// <summary>
/// Register a new variable with the Flowchart at runtime.
/// The variable should be added as a component on the Flowchart game object.
/// </summary>
public void SetVariable<T>(string key, T newvariable) where T : Variable
{
for (int i = 0; i < variables.Count; i++)
{
var v = variables[i];
if (v != null && v.Key == key)
{
T variable = v as T;
if (variable != null)
{
variable = newvariable;
return;
}
}
}
Debug.LogWarning("Variable " + key + " not found.");
}
/// <summary>
/// Checks if a given variable exists in the flowchart.
/// </summary>
public virtual bool HasVariable(string key)
{
for (int i = 0; i < variables.Count; i++)
{
var v = variables[i];
if (v != null && v.Key == key)
{
return true;
}
}
return false;
}
/// <summary>
/// Returns the list of variable names in the Flowchart.
/// </summary>
public virtual string[] GetVariableNames()
{
var vList = new string[variables.Count];
for (int i = 0; i < variables.Count; i++)
{
var v = variables[i];
if (v != null)
{
vList[i] = v.Key;
}
}
return vList;
}
/// <summary>
/// Gets a list of all variables with public scope in this Flowchart.
/// </summary>
public virtual List<Variable> GetPublicVariables()
{
var publicVariables = new List<Variable>();
for (int i = 0; i < variables.Count; i++)
{
var v = variables[i];
if (v != null && v.Scope == VariableScope.Public)
{
publicVariables.Add(v);
}
}
return publicVariables;
}
/// <summary>
/// Gets the value of a boolean variable.
/// Returns false if the variable key does not exist.
/// </summary>
public virtual bool GetBooleanVariable(string key)
{
var variable = GetVariable<BooleanVariable>(key);
if(variable != null)
{
return GetVariable<BooleanVariable>(key).Value;
}
else
{
return false;
}
}
/// <summary>
/// Sets the value of a boolean variable.
/// The variable must already be added to the list of variables for this Flowchart.
/// </summary>
public virtual void SetBooleanVariable(string key, bool value)
{
var variable = GetVariable<BooleanVariable>(key);
if(variable != null)
{
variable.Value = value;
}
}
/// <summary>
/// Gets the value of an integer variable.
/// Returns 0 if the variable key does not exist.
/// </summary>
public virtual int GetIntegerVariable(string key)
{
var variable = GetVariable<IntegerVariable>(key);
if (variable != null)
{
return GetVariable<IntegerVariable>(key).Value;
}
else
{
return 0;
}
}
/// <summary>
/// Sets the value of an integer variable.
/// The variable must already be added to the list of variables for this Flowchart.
/// </summary>
public virtual void SetIntegerVariable(string key, int value)
{
var variable = GetVariable<IntegerVariable>(key);
if (variable != null)
{
variable.Value = value;
}
}
/// <summary>
/// Gets the value of a float variable.
/// Returns 0 if the variable key does not exist.
/// </summary>
public virtual float GetFloatVariable(string key)
{
var variable = GetVariable<FloatVariable>(key);
if (variable != null)
{
return GetVariable<FloatVariable>(key).Value;
}
else
{
return 0f;
}
}
/// <summary>
/// Sets the value of a float variable.
/// The variable must already be added to the list of variables for this Flowchart.
/// </summary>
public virtual void SetFloatVariable(string key, float value)
{
var variable = GetVariable<FloatVariable>(key);
if (variable != null)
{
variable.Value = value;
}
}
/// <summary>
/// Gets the value of a string variable.
/// Returns the empty string if the variable key does not exist.
/// </summary>
public virtual string GetStringVariable(string key)
{
var variable = GetVariable<StringVariable>(key);
if (variable != null)
{
return GetVariable<StringVariable>(key).Value;
}
else
{
return "";
}
}
/// <summary>
/// Sets the value of a string variable.
/// The variable must already be added to the list of variables for this Flowchart.
/// </summary>
public virtual void SetStringVariable(string key, string value)
{
var variable = GetVariable<StringVariable>(key);
if (variable != null)
{
variable.Value = value;
}
}
/// <summary>
/// Gets the value of a GameObject variable.
/// Returns null if the variable key does not exist.
/// </summary>
public virtual GameObject GetGameObjectVariable(string key)
{
var variable = GetVariable<GameObjectVariable>(key);
if (variable != null)
{
return GetVariable<GameObjectVariable>(key).Value;
}
else
{
return null;
}
}
/// <summary>
/// Sets the value of a GameObject variable.
/// The variable must already be added to the list of variables for this Flowchart.
/// </summary>
public virtual void SetGameObjectVariable(string key, GameObject value)
{
var variable = GetVariable<GameObjectVariable>(key);
if (variable != null)
{
variable.Value = value;
}
}
/// <summary>
/// Gets the value of a Transform variable.
/// Returns null if the variable key does not exist.
/// </summary>
public virtual Transform GetTransformVariable(string key)
{
var variable = GetVariable<TransformVariable>(key);
if (variable != null)
{
return GetVariable<TransformVariable>(key).Value;
}
else
{
return null;
}
}
/// <summary>
/// Sets the value of a Transform variable.
/// The variable must already be added to the list of variables for this Flowchart.
/// </summary>
public virtual void SetTransformVariable(string key, Transform value)
{
var variable = GetVariable<TransformVariable>(key);
if (variable != null)
{
variable.Value = value;
}
}
/// <summary>
/// Set the block objects to be hidden or visible depending on the hideComponents property.
/// </summary>
public virtual void UpdateHideFlags()
{
if (hideComponents)
{
var blocks = GetComponents<Block>();
for (int i = 0; i < blocks.Length; i++)
{
var block = blocks[i];
block.hideFlags = HideFlags.HideInInspector;
if (block.gameObject != gameObject)
{
block.hideFlags = HideFlags.HideInHierarchy;
}
}
var commands = GetComponents<Command>();
for (int i = 0; i < commands.Length; i++)
{
var command = commands[i];
command.hideFlags = HideFlags.HideInInspector;
}
var eventHandlers = GetComponents<EventHandler>();
for (int i = 0; i < eventHandlers.Length; i++)
{
var eventHandler = eventHandlers[i];
eventHandler.hideFlags = HideFlags.HideInInspector;
}
}
else
{
var monoBehaviours = GetComponents<MonoBehaviour>();
for (int i = 0; i < monoBehaviours.Length; i++)
{
var monoBehaviour = monoBehaviours[i];
if (monoBehaviour == null)
{
continue;
}
monoBehaviour.hideFlags = HideFlags.None;
monoBehaviour.gameObject.hideFlags = HideFlags.None;
}
}
}
/// <summary>
/// Clears the list of selected commands.
/// </summary>
public virtual void ClearSelectedCommands()
{
selectedCommands.Clear();
}
/// <summary>
/// Adds a command to the list of selected commands.
/// </summary>
public virtual void AddSelectedCommand(Command command)
{
if (!selectedCommands.Contains(command))
{
selectedCommands.Add(command);
}
}
/// <summary>
/// Clears the list of selected blocks.
/// </summary>
public virtual void ClearSelectedBlocks()
{
selectedBlocks.Clear();
}
/// <summary>
/// Adds a block to the list of selected blocks.
/// </summary>
public virtual void AddSelectedBlock(Block block)
{
if (!selectedBlocks.Contains(block))
{
selectedBlocks.Add(block);
}
}
/// <summary>
/// Reset the commands and variables in the Flowchart.
/// </summary>
public virtual void Reset(bool resetCommands, bool resetVariables)
{
if (resetCommands)
{
var commands = GetComponents<Command>();
for (int i = 0; i < commands.Length; i++)
{
var command = commands[i];
command.OnReset();
}
}
if (resetVariables)
{
for (int i = 0; i < variables.Count; i++)
{
var variable = variables[i];
variable.OnReset();
}
}
}
/// <summary>
/// Override this in a Flowchart subclass to filter which commands are shown in the Add Command list.
/// </summary>
public virtual bool IsCommandSupported(CommandInfoAttribute commandInfo)
{
for (int i = 0; i < hideCommands.Count; i++)
{
// Match on category or command name (case insensitive)
var key = hideCommands[i];
if (String.Compare(commandInfo.Category, key, StringComparison.OrdinalIgnoreCase) == 0 || String.Compare(commandInfo.CommandName, key, StringComparison.OrdinalIgnoreCase) == 0)
{
return false;
}
}
return true;
}
/// <summary>
/// Returns true if there are any executing blocks in this Flowchart.
/// </summary>
public virtual bool HasExecutingBlocks()
{
var blocks = GetComponents<Block>();
for (int i = 0; i < blocks.Length; i++)
{
var block = blocks[i];
if (block.IsExecuting())
{
return true;
}
}
return false;
}
/// <summary>
/// Returns a list of all executing blocks in this Flowchart.
/// </summary>
public virtual List<Block> GetExecutingBlocks()
{
var executingBlocks = new List<Block>();
var blocks = GetComponents<Block>();
for (int i = 0; i < blocks.Length; i++)
{
var block = blocks[i];
if (block.IsExecuting())
{
executingBlocks.Add(block);
}
}
return executingBlocks;
}
/// <summary>
/// Substitute variables in the input text with the format {$VarName}
/// This will first match with private variables in this Flowchart, and then
/// with public variables in all Flowcharts in the scene (and any component
/// in the scene that implements StringSubstituter.ISubstitutionHandler).
/// </summary>
public virtual string SubstituteVariables(string input)
{
if (stringSubstituer == null)
{
stringSubstituer = new StringSubstituter();
}
// Use the string builder from StringSubstituter for efficiency.
StringBuilder sb = stringSubstituer._StringBuilder;
sb.Length = 0;
sb.Append(input);
// Instantiate the regular expression object.
Regex r = new Regex("{\\$.*?}");
bool changed = false;
// Match the regular expression pattern against a text string.
var results = r.Matches(input);
for (int i = 0; i < results.Count; i++)
{
Match match = results[i];
string key = match.Value.Substring(2, match.Value.Length - 3);
// Look for any matching private variables in this Flowchart first
for (int j = 0; j < variables.Count; j++)
{
var variable = variables[j];
if (variable == null)
continue;
if (variable.Scope == VariableScope.Private && variable.Key == key)
{
string value = variable.ToString();
sb.Replace(match.Value, value);
changed = true;
}
}
}
// Now do all other substitutions in the scene
changed |= stringSubstituer.SubstituteStrings(sb);
if (changed)
{
return sb.ToString();
}
else
{
return input;
}
}
#endregion
#region IStringSubstituter implementation
/// <summary>
/// Implementation of StringSubstituter.ISubstitutionHandler which matches any public variable in the Flowchart.
/// To perform full variable substitution with all substitution handlers in the scene, you should
/// use the SubstituteVariables() method instead.
/// </summary>
[MoonSharp.Interpreter.MoonSharpHidden]
public virtual bool SubstituteStrings(StringBuilder input)
{
// Instantiate the regular expression object.
Regex r = new Regex("{\\$.*?}");
bool modified = false;
// Match the regular expression pattern against a text string.
var results = r.Matches(input.ToString());
for (int i = 0; i < results.Count; i++)
{
Match match = results[i];
string key = match.Value.Substring(2, match.Value.Length - 3);
// Look for any matching public variables in this Flowchart
for (int j = 0; j < variables.Count; j++)
{
var variable = variables[j];
if (variable == null)
{
continue;
}
if (variable.Scope == VariableScope.Public && variable.Key == key)
{
string value = variable.ToString();
input.Replace(match.Value, value);
modified = true;
}
}
}
return modified;
}
#endregion
}
}
| |
using System;
/// <summary>
/// System.Text.StringBuilder.Remove
/// </summary>
public class StringBuilderRemove
{
private const int c_MIN_STRING_LEN = 8;
private const int c_MAX_STRING_LEN = 256;
public static int Main()
{
StringBuilderRemove test = new StringBuilderRemove();
TestLibrary.TestFramework.BeginTestCase("for Method:System.Text.StringBuilder.Remove(indexStart,length)");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
string oldString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
int startIndex = TestLibrary.Generator.GetInt32(-55) % Math.Max(1,oldString.Length);
int removedLength = TestLibrary.Generator.GetInt32(-55) % Math.Max(1,(oldString.Length-startIndex-1));
string newString = oldString.Remove(startIndex, removedLength);
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify Remove subString form a StringBuilder ...");
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(oldString);
System.Text.StringBuilder removedStringBuilder = new System.Text.StringBuilder(newString);
try
{
stringBuilder.Remove(startIndex,removedLength);
int compareResult = string.CompareOrdinal(stringBuilder.ToString(), removedStringBuilder.ToString());
if (compareResult != 0)
{
TestLibrary.TestFramework.LogError("001", "StringBuilder can't corrently remove");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2:Verify StringBuilder Remove itself ");
string oldString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
int startIndex = 0;
int removedLength = oldString.Length;
try
{
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(oldString);
stringBuilder.Remove(startIndex, removedLength);
if (stringBuilder.Length != 0)
{
TestLibrary.TestFramework.LogError("003", "StringBuilder can't corrently remove itself");
retVal = false;
}
}
catch(Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
string oldString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
int startIndex = 0;
int removedLength = TestLibrary.Generator.GetInt32(-55) % (oldString.Length - startIndex);
string newString = oldString.Remove(startIndex, removedLength);
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify StringBuilder Remove form posization of 0 index ...");
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(oldString);
System.Text.StringBuilder removedStringBuilder = new System.Text.StringBuilder(newString);
try
{
stringBuilder.Remove(startIndex, removedLength);
int compareResult = string.CompareOrdinal(stringBuilder.ToString(), removedStringBuilder.ToString());
if (compareResult != 0)
{
TestLibrary.TestFramework.LogError("005", "StringBuilder can't corrently remove from posization of 0 index");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
string oldString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
int startIndex = TestLibrary.Generator.GetInt32(-55) % oldString.Length;
int removedLength = 0;
string newString = oldString.Remove(startIndex, removedLength);
TestLibrary.TestFramework.BeginScenario("PosTest4: Verify StringBuilder Remove 0 length ...");
try
{
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(oldString);
System.Text.StringBuilder removedStringBuilder = new System.Text.StringBuilder(newString);
stringBuilder.Remove(startIndex, removedLength);
if (stringBuilder.ToString() != removedStringBuilder.ToString())
{
TestLibrary.TestFramework.LogError("007", "StringBuilder can't corrently Remove 0 length");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1: StingBuilder length is 0 and length of removed larger than 0";
const string c_TEST_ID = "N001";
string oldString = TestLibrary.Generator.GetString(-55, false, 0, 0);
int startIndex = 0;
int removedLength = 0;
while (removedLength == 0)
{
removedLength = TestLibrary.Generator.GetInt32(-55);
}
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(oldString);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder.Remove(startIndex, removedLength);
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected." );
retVal = false;
}
catch (ArgumentException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest2: StingBuilder length is 0 and started index larger than 0";
const string c_TEST_ID = "N002";
int startIndex = 0;
int removedLength = 0;
while (startIndex == 0)
{
startIndex = TestLibrary.Generator.GetInt32(-55);
}
string oldString = TestLibrary.Generator.GetString(-55, false, 0, 0);
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(oldString);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder.Remove(startIndex, removedLength);
TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected.");
retVal = false;
}
catch (ArgumentException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest3: length of Removed is larger than length of StringBuilder ";
const string c_TEST_ID = "N003";
string oldString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
int startIndex = TestLibrary.Generator.GetInt32(-55);
int removedLength = TestLibrary.Generator.GetInt32(-55);
while (startIndex <= oldString.Length )
{
startIndex = TestLibrary.Generator.GetInt32(-55);
}
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(oldString);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder.Remove(startIndex, removedLength);
TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected.");
retVal = false;
}
catch (ArgumentException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest4: Sum of length of Removed and index of started is larger than length of StringBuilder ";
const string c_TEST_ID = "N004";
string oldString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
int removedLength = TestLibrary.Generator.GetInt32(-55);
int startIndex = TestLibrary.Generator.GetInt32(-55) % (oldString.Length-removedLength);
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(oldString);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder.Remove(startIndex, removedLength);
TestLibrary.TestFramework.LogError("015" + " TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected.");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
}
| |
using System.IO;
using System.Threading;
namespace Omnius.Serialization
{
// https://developers.google.com/protocol-buffers/docs/encoding
public unsafe static class Varint
{
private static readonly ThreadLocal<byte[]> _threadLocalBuffer = new ThreadLocal<byte[]>(() => new byte[10]);
public static int ComputeSize(long value)
{
return Varint.ComputeSize((ulong)((value << 1) ^ (value >> 63)));
}
public static int ComputeSize(ulong value)
{
if (value <= 0x7F)
{
return 1;
}
else if (value <= 0x3FFF)
{
return 2;
}
else if (value <= 0x1FFFFF)
{
return 3;
}
else if (value <= 0xFFFFFFF)
{
return 4;
}
else if (value <= 0x7FFFFFFFF)
{
return 5;
}
else if (value <= 0x3FFFFFFFFFF)
{
return 6;
}
else if (value <= 0x1FFFFFFFFFFFF)
{
return 7;
}
else if (value <= 0xFFFFFFFFFFFFFF)
{
return 8;
}
else if (value <= 0x7FFFFFFFFFFFFFFF)
{
return 9;
}
else
{
return 10;
}
}
public static void SetInt64(Stream stream, long value)
{
Varint.SetUInt64(stream, (ulong)((value << 1) ^ (value >> 63)));
}
public static void SetUInt64(Stream stream, ulong value)
{
if (value <= 0x7F)
{
stream.WriteByte((byte)value);
}
else if (value <= 0x3FFF)
{
var buffer = _threadLocalBuffer.Value;
fixed (byte* p = buffer)
{
p[0] = (byte)((value >> 8 - 1) & 0x7F | 0x80);
p[1] = (byte)((value >> 0 - 0) & 0x7F);
}
stream.Write(buffer, 0, 2);
}
else if (value <= 0x1FFFFF)
{
var buffer = _threadLocalBuffer.Value;
fixed (byte* p = buffer)
{
p[0] = (byte)((value >> 16 - 2) & 0x7F | 0x80);
p[1] = (byte)((value >> 8 - 1) & 0x7F | 0x80);
p[2] = (byte)((value >> 0 - 0) & 0x7F);
}
stream.Write(buffer, 0, 3);
}
else if (value <= 0xFFFFFFF)
{
var buffer = _threadLocalBuffer.Value;
fixed (byte* p = buffer)
{
p[0] = (byte)((value >> 24 - 3) & 0x7F | 0x80);
p[1] = (byte)((value >> 16 - 2) & 0x7F | 0x80);
p[2] = (byte)((value >> 8 - 1) & 0x7F | 0x80);
p[3] = (byte)((value >> 0 - 0) & 0x7F);
}
stream.Write(buffer, 0, 4);
}
else if (value <= 0x7FFFFFFFF)
{
var buffer = _threadLocalBuffer.Value;
fixed (byte* p = buffer)
{
p[0] = (byte)((value >> 32 - 4) & 0x7F | 0x80);
p[1] = (byte)((value >> 24 - 3) & 0x7F | 0x80);
p[2] = (byte)((value >> 16 - 2) & 0x7F | 0x80);
p[3] = (byte)((value >> 8 - 1) & 0x7F | 0x80);
p[4] = (byte)((value >> 0 - 0) & 0x7F);
}
stream.Write(buffer, 0, 5);
}
else if (value <= 0x3FFFFFFFFFF)
{
var buffer = _threadLocalBuffer.Value;
fixed (byte* p = buffer)
{
p[0] = (byte)((value >> 40 - 5) & 0x7F | 0x80);
p[1] = (byte)((value >> 32 - 4) & 0x7F | 0x80);
p[2] = (byte)((value >> 24 - 3) & 0x7F | 0x80);
p[3] = (byte)((value >> 16 - 2) & 0x7F | 0x80);
p[4] = (byte)((value >> 8 - 1) & 0x7F | 0x80);
p[5] = (byte)((value >> 0 - 0) & 0x7F);
}
stream.Write(buffer, 0, 6);
}
else if (value <= 0x1FFFFFFFFFFFF)
{
var buffer = _threadLocalBuffer.Value;
fixed (byte* p = buffer)
{
p[0] = (byte)((value >> 48 - 6) & 0x7F | 0x80);
p[1] = (byte)((value >> 40 - 5) & 0x7F | 0x80);
p[2] = (byte)((value >> 32 - 4) & 0x7F | 0x80);
p[3] = (byte)((value >> 24 - 3) & 0x7F | 0x80);
p[4] = (byte)((value >> 16 - 2) & 0x7F | 0x80);
p[5] = (byte)((value >> 8 - 1) & 0x7F | 0x80);
p[6] = (byte)((value >> 0 - 0) & 0x7F);
}
stream.Write(buffer, 0, 7);
}
else if (value <= 0xFFFFFFFFFFFFFF)
{
var buffer = _threadLocalBuffer.Value;
fixed (byte* p = buffer)
{
p[0] = (byte)((value >> 56 - 7) & 0x7F | 0x80);
p[1] = (byte)((value >> 48 - 6) & 0x7F | 0x80);
p[2] = (byte)((value >> 40 - 5) & 0x7F | 0x80);
p[3] = (byte)((value >> 32 - 4) & 0x7F | 0x80);
p[4] = (byte)((value >> 24 - 3) & 0x7F | 0x80);
p[5] = (byte)((value >> 16 - 2) & 0x7F | 0x80);
p[6] = (byte)((value >> 8 - 1) & 0x7F | 0x80);
p[7] = (byte)((value >> 0 - 0) & 0x7F);
}
stream.Write(buffer, 0, 8);
}
else if (value <= 0x7FFFFFFFFFFFFFFF)
{
var buffer = _threadLocalBuffer.Value;
fixed (byte* p = buffer)
{
p[0] = (byte)((value >> 64 - 8) & 0x7F | 0x80);
p[1] = (byte)((value >> 56 - 7) & 0x7F | 0x80);
p[2] = (byte)((value >> 48 - 6) & 0x7F | 0x80);
p[3] = (byte)((value >> 40 - 5) & 0x7F | 0x80);
p[4] = (byte)((value >> 32 - 4) & 0x7F | 0x80);
p[5] = (byte)((value >> 24 - 3) & 0x7F | 0x80);
p[6] = (byte)((value >> 16 - 2) & 0x7F | 0x80);
p[7] = (byte)((value >> 8 - 1) & 0x7F | 0x80);
p[8] = (byte)((value >> 0 - 0) & 0x7F);
}
stream.Write(buffer, 0, 9);
}
else
{
var buffer = _threadLocalBuffer.Value;
fixed (byte* p = buffer)
{
p[0] = (byte)((value >> 72 - 9) & 0x7F | 0x80);
p[1] = (byte)((value >> 64 - 8) & 0x7F | 0x80);
p[2] = (byte)((value >> 56 - 7) & 0x7F | 0x80);
p[3] = (byte)((value >> 48 - 6) & 0x7F | 0x80);
p[4] = (byte)((value >> 40 - 5) & 0x7F | 0x80);
p[5] = (byte)((value >> 32 - 4) & 0x7F | 0x80);
p[6] = (byte)((value >> 24 - 3) & 0x7F | 0x80);
p[7] = (byte)((value >> 16 - 2) & 0x7F | 0x80);
p[8] = (byte)((value >> 8 - 1) & 0x7F | 0x80);
p[9] = (byte)((value >> 0 - 0) & 0x7F);
}
stream.Write(buffer, 0, 10);
}
}
public static long? GetInt64(Stream stream)
{
var result = Varint.GetUInt64(stream);
if (result == null) return null;
return (long)((ulong)result >> 1) ^ (-((long)result & 1));
}
public static ulong? GetUInt64(Stream stream)
{
ulong result = 0;
for (int count = 0; ; count++)
{
int b = stream.ReadByte();
if (b < 0) return null;
result = (result << 7) | (byte)(b & 0x7F);
if ((b & 0x80) != 0x80) break;
if (count > 10) return null;
}
return result;
}
public static bool IsEnd(byte value)
{
return ((value & 0x80) != 0x80);
}
}
}
| |
// 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void RoundToNegativeInfinityScalarSingle()
{
var test = new SimpleUnaryOpTest__RoundToNegativeInfinityScalarSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__RoundToNegativeInfinityScalarSingle
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Single> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__RoundToNegativeInfinityScalarSingle testClass)
{
var result = Sse41.RoundToNegativeInfinityScalar(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__RoundToNegativeInfinityScalarSingle testClass)
{
fixed (Vector128<Single>* pFld1 = &_fld1)
{
var result = Sse41.RoundToNegativeInfinityScalar(
Sse.LoadVector128((Single*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Vector128<Single> _clsVar1;
private Vector128<Single> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__RoundToNegativeInfinityScalarSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public SimpleUnaryOpTest__RoundToNegativeInfinityScalarSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.RoundToNegativeInfinityScalar(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse41.RoundToNegativeInfinityScalar(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse41.RoundToNegativeInfinityScalar(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNegativeInfinityScalar), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNegativeInfinityScalar), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNegativeInfinityScalar), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.RoundToNegativeInfinityScalar(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Single>* pClsVar1 = &_clsVar1)
{
var result = Sse41.RoundToNegativeInfinityScalar(
Sse.LoadVector128((Single*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var result = Sse41.RoundToNegativeInfinityScalar(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var result = Sse41.RoundToNegativeInfinityScalar(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var result = Sse41.RoundToNegativeInfinityScalar(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__RoundToNegativeInfinityScalarSingle();
var result = Sse41.RoundToNegativeInfinityScalar(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__RoundToNegativeInfinityScalarSingle();
fixed (Vector128<Single>* pFld1 = &test._fld1)
{
var result = Sse41.RoundToNegativeInfinityScalar(
Sse.LoadVector128((Single*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.RoundToNegativeInfinityScalar(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Single>* pFld1 = &_fld1)
{
var result = Sse41.RoundToNegativeInfinityScalar(
Sse.LoadVector128((Single*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.RoundToNegativeInfinityScalar(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse41.RoundToNegativeInfinityScalar(
Sse.LoadVector128((Single*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Single> op1, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(MathF.Floor(firstOp[0])))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(firstOp[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.RoundToNegativeInfinityScalar)}<Single>(Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Photogaleries.Services.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class GameManager : MonoBehaviour {
internal bool ending = false;
internal string username;
private GameObject user;
private Hashtable playernames;
private Hashtable playeralive;
private bool typing = false;
private bool paused = false;
private bool started = false;
// Chat Variables
private List<string> chat = new List<string>();
private string chatInput = "";
private bool chatEnable = false;
private float chatDelay = 0;
private float dChatDelay = 4;
private float matchTime = 0;
private float dMatchTime = 60;
private NetworkPlayer currentHunter;
void Start () {
playernames = new Hashtable(Network.maxConnections);
playeralive = new Hashtable(Network.maxConnections);
name = "Manager";
}
void Update () {
matchTime -= Time.deltaTime;
chatDelay -= Time.deltaTime;
if(Network.isServer && started){
int numAlive = 0;
foreach(bool a in playeralive.Values)
if(a)numAlive++;
if(matchTime<=0){
networkView.RPC("SendMatchEnd",RPCMode.All,"TimeOut");
}
if(dMatchTime-matchTime > 5){
if(!(bool)playeralive[currentHunter]){
networkView.RPC("SendMatchEnd",RPCMode.All,"SoldierWin");
}
if(numAlive == 0){
networkView.RPC("SendMatchEnd",RPCMode.All,"HunterWin");
}
}
}
if(Input.GetKeyDown(KeyCode.Return)) {
typing = !typing;
paused = typing;
if(typing) chatInput = "";
else SendChat ();
}
if(!typing){
if(started){
if(Input.GetKeyDown(KeyCode.Escape)) paused = !paused;
} else {
paused = true;
}
} else {
paused = true;
if(Input.GetKeyDown(KeyCode.Escape)) { typing = false; paused = false; }
}
Screen.lockCursor = !paused;
if(user)user.GetComponentInChildren<Controller>().paused = paused;
if(user)GetComponentInChildren<Interface>().paused = paused && !typing;
}
public void StartGame () { // Server Side
if(!Network.isServer)return;
// TODO improve spawn selection
bool[] hSpawns = new bool[GameObject.FindGameObjectsWithTag("HunterSpawn").Length];
bool[] sSpawns = new bool[GameObject.FindGameObjectsWithTag("SoldierSpawn").Length];
int spawn = -1;
NetworkPlayer[] players = new NetworkPlayer[playernames.Count];
playernames.Keys.CopyTo(players,0);
int hunter = Random.Range(0,players.Length);
for(int i = 0; i < players.Length; i++){
if(players[i]==Network.player){
if(i==hunter)currentHunter=players[i];
continue;
}
while(spawn<0){
spawn = Random.Range(0,(i==hunter?hSpawns.Length:sSpawns.Length)-1);
if(i==hunter?hSpawns[spawn]:sSpawns[spawn]){
spawn = -1;
if(i>=sSpawns.Length+(hunter<i?1:0) && i!=hunter){ // If there are no more soldier spawns
spawn = Random.Range(0,sSpawns.Length-1);
}
} else {
if(i==hunter)hSpawns[spawn] = true;
else sSpawns[spawn] = true;
}
}
if(i==hunter)currentHunter=players[i];
networkView.RPC("SendGameStart", players[i], i==hunter, spawn);
}
SendGameStart(Network.connections.Length==hunter,0);
}
GameObject AddPlayerController (bool hunter, int spawn){ // Any Side
GameObject[] hunterSpawns = GameObject.FindGameObjectsWithTag("HunterSpawn");
GameObject[] soldierSpawns = GameObject.FindGameObjectsWithTag("SoldierSpawn");
GameObject unit = Instantiate(Resources.Load("Prefabs/Hunter")) as GameObject;
if(hunter) {
unit.transform.position = hunterSpawns[spawn].transform.position;
} else {
unit.transform.position = soldierSpawns[spawn].transform.position;
}
unit.AddComponent<Controller>();
unit.AddComponent<Health>();
if(hunter) unit.AddComponent<Hunter>();
WeaponHolder weapon = unit.AddComponent<WeaponHolder>();
if(hunter){
weapon.Give("Knife","Grenade"); // TODO get loadout
} else {
weapon.Give("BaseGun");
}
unit.AddComponent<NetworkView>();
unit.networkView.viewID = Network.AllocateViewID();
unit.networkView.stateSynchronization = NetworkStateSynchronization.Unreliable;
unit.networkView.observed = unit.transform;
unit.AddComponent<Dummy>().Init();
Animator anim = unit.GetComponentInChildren<Animator>();
anim.gameObject.AddComponent<NetworkView>();
anim.networkView.viewID = Network.AllocateViewID();
anim.networkView.stateSynchronization = NetworkStateSynchronization.ReliableDeltaCompressed;
anim.networkView.observed = anim;
networkView.RPC("SendUserView", RPCMode.OthersBuffered, unit.networkView.viewID, anim.networkView.viewID);
return unit;
}
void OnUserSpawn(NetworkPlayer player) { // Any Side
if(!playeralive.ContainsKey(player))Debug.LogError("Player Not Found!");
playeralive[player] = true;
}
void OnUserDeath(NetworkPlayer player) { // Any Side
if(!playeralive.ContainsKey(player))Debug.LogError("Player Not Found!");
playeralive[player] = false;
}
void SendChat() {
if(chatInput.Length > 0) {
networkView.RPC("OnChat",RPCMode.All, chatInput, Network.player);
chatDelay = dChatDelay;
}
chatInput = "";
typing = false;
paused = false;
chatEnable = false;
}
void OnGUI() {
if(matchTime>0){
GUILayout.Space(40);
GUILayout.BeginHorizontal();
int min = 0;
int sec = (int)matchTime;
while(sec>=60){
min++;
sec-=60;
}
float wid1 = 0;
float wid2 = 0;
GUI.skin.box.CalcMinMaxWidth(new GUIContent(min+":"+sec),out wid1,out wid2);
GUILayout.Space(Screen.height/2-wid2);
GUILayout.Box(min+":"+sec);
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}
GUILayout.BeginArea(new Rect(20,20,Screen.width/2,Screen.height/2));
GUILayout.Box("Players: "+(playernames.Keys.Count).ToString(),GUILayout.Width(100));
GUILayout.Space(5);
if(!started){
if(Network.isServer){
if(GUILayout.Button("Start Game",GUILayout.Width(100))){
StartGame();
}
GUILayout.Space(5);
}
}
if(paused){
//GUI.skin.box.alignment = TextAnchor.MiddleLeft;
foreach(NetworkPlayer player in playernames.Keys){
GUILayout.Box(playernames[player] + ((bool)playeralive[player]==true?" - Alive":""),GUILayout.Width(Screen.width/8));
GUILayout.Space(5);
}
//GUI.skin.box.alignment = TextAnchor.MiddleCenter;
}
GUILayout.EndArea();
GUILayout.BeginArea(new Rect(20,Screen.height/2,Screen.width/4,Screen.height/3));
GUILayout.FlexibleSpace();
if(chatDelay > 0 || typing || paused){
GUI.skin.box.alignment = TextAnchor.LowerLeft;
while(chat.Count>18)chat.RemoveAt(0);
string showChat = chat.Count>0?chat[0]:"";
for(int i = 1; i<Mathf.Max(18,chat.Count); i++){
showChat = showChat + "\n" + (i<chat.Count?chat[i]:"");
}
GUILayout.Box(showChat);
GUI.skin.box.alignment = TextAnchor.MiddleCenter;
}
if(typing){
GUI.SetNextControlName("ChatInput");
chatInput = GUILayout.TextField(chatInput);
GUI.FocusControl("ChatInput");
if (Event.current.isKey && Event.current.keyCode == KeyCode.Return) {
chatEnable = !chatEnable;
if(!chatEnable)SendChat();
}
}
GUILayout.EndArea();
GUILayout.BeginArea(new Rect(20,Screen.height/2+Screen.height/3,Screen.width/2,Screen.height/6));
if((paused && !typing) || (!started)){
GUILayout.Space(5);
if(GUILayout.Button("Exit To Menu",GUILayout.Width(150)))Network.Disconnect();
GUILayout.Space(5);
if(GUILayout.Button("Exit To Desktop",GUILayout.Width(150)))Application.Quit();
}
GUILayout.EndArea();
}
void OnLevelWasLoaded(int lvl) { // Client Side
networkView.RPC("OnPlayerJoin",RPCMode.OthersBuffered,username,Network.player);
OnPlayerJoin(username, Network.player);
}
void OnPlayerConnected(NetworkPlayer player){ // Server Side
if(Network.isServer){
networkView.RPC("LoadNetLevel",player,"test01");
}
}
void OnPlayerDisconnected(NetworkPlayer player){ // Server Side
Network.RemoveRPCs(player);
Network.DestroyPlayerObjects(player);
}
void OnDisconnectedFromServer(NetworkDisconnection info) { // Client Side
ending = true;
Application.LoadLevel("MainMenu");
Destroy(gameObject);
}
[RPC]
public void OnChat(string input, NetworkPlayer player) {
chat.Add(playernames[player]+": "+input);
chatDelay = dChatDelay;
}
[RPC]
public void OnPlayerJoin(string name, NetworkPlayer player) { // Client Side
if(playernames == null || playeralive == null){
playernames = new Hashtable(Network.maxConnections);
playeralive = new Hashtable(Network.maxConnections);
name = "Manager";
}
playernames.Add(player,name);
playeralive.Add(player,false);
}
[RPC]
public void LoadNetLevel(string level) { // Client Side
Application.LoadLevel(level);
}
[RPC]
public void SendUserView(NetworkViewID view, NetworkViewID animview) { // Any Side
GameObject unit = new GameObject("Player");
unit.AddComponent<NetworkView>();
unit.networkView.stateSynchronization = NetworkStateSynchronization.Unreliable;
unit.networkView.observed = unit.transform;
unit.networkView.viewID = view;
unit.AddComponent<Dummy>().Init();
Animator anim = unit.GetComponentInChildren<Animator>();
anim.gameObject.AddComponent<NetworkView>();
anim.networkView.stateSynchronization = NetworkStateSynchronization.ReliableDeltaCompressed;
anim.networkView.observed = anim;
anim.networkView.viewID = view;
}
[RPC]
public void SendGameStart(bool hunter, int spawn) { // Client Side
user = AddPlayerController(hunter, spawn);
GetComponent<Interface>().user = user.transform;
GetComponent<Interface>().Init();
started = true;
paused = false;
matchTime = dMatchTime;
}
[RPC]
public void SendMatchEnd(string message) {
matchTime = 0;
Destroy(user);
started = false;
// TODO show winner
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using DotVVM.Framework.Binding;
using DotVVM.Framework.Configuration;
using DotVVM.Framework.Controls;
using DotVVM.Framework.Hosting;
using DotVVM.Framework.Parser;
namespace DotVVM.Framework.Runtime
{
/// <summary>
/// Default DotVVM control resolver.
/// </summary>
public class DefaultControlResolver : IControlResolver
{
private readonly DotvvmConfiguration configuration;
private readonly IControlBuilderFactory controlBuilderFactory;
private static ConcurrentDictionary<string, ControlType> cachedTagMappings = new ConcurrentDictionary<string, ControlType>();
private static ConcurrentDictionary<Type, ControlResolverMetadata> cachedMetadata = new ConcurrentDictionary<Type, ControlResolverMetadata>();
private static object locker = new object();
private static bool isInitialized = false;
/// <summary>
/// Initializes a new instance of the <see cref="DefaultControlResolver"/> class.
/// </summary>
public DefaultControlResolver(DotvvmConfiguration configuration)
{
this.configuration = configuration;
this.controlBuilderFactory = configuration.ServiceLocator.GetService<IControlBuilderFactory>();
if (!isInitialized)
{
lock (locker)
{
if (!isInitialized)
{
InvokeStaticConstructorsOnAllControls();
isInitialized = true;
}
}
}
}
/// <summary>
/// Invokes the static constructors on all controls to register all <see cref="DotvvmProperty"/>.
/// </summary>
private void InvokeStaticConstructorsOnAllControls()
{
// PERF: too many allocations - type.GetCustomAttribute<T> does ~220k allocs -> 4MB, get all types allocates additional 1.5MB
var dotvvmAssembly = typeof(DotvvmControl).Assembly.FullName;
var allTypes = AppDomain.CurrentDomain.GetAssemblies()
.Where(a => a.GetReferencedAssemblies().Any(r => r.FullName == dotvvmAssembly))
.Concat(new[] { typeof(DotvvmControl).Assembly })
.SelectMany(a => a.GetTypes()).Where(t => t.IsClass).ToList();
foreach (var type in allTypes)
{
if (type.GetCustomAttribute<ContainsDotvvmPropertiesAttribute>(true) != null)
{
RuntimeHelpers.RunClassConstructor(type.TypeHandle);
}
}
}
/// <summary>
/// Resolves the metadata for specified element.
/// </summary>
public ControlResolverMetadata ResolveControl(string tagPrefix, string tagName, out object[] activationParameters)
{
// html element has no prefix
if (string.IsNullOrEmpty(tagPrefix))
{
activationParameters = new object[] { tagName };
return ResolveControl(typeof (HtmlGenericControl));
}
// find cached value
var searchKey = GetSearchKey(tagPrefix, tagName);
activationParameters = null;
var controlType = cachedTagMappings.GetOrAdd(searchKey, _ => FindControlType(tagPrefix, tagName));
var metadata = ResolveControl(controlType);
return metadata;
}
private static string GetSearchKey(string tagPrefix, string tagName)
{
return tagPrefix + ":" + tagName;
}
/// <summary>
/// Resolves the control metadata for specified type.
/// </summary>
public ControlResolverMetadata ResolveControl(ControlType controlType)
{
return cachedMetadata.GetOrAdd(controlType.Type, _ => BuildControlMetadata(controlType));
}
public ControlResolverMetadata ResolveControl(Type controlType)
{
return ResolveControl(new ControlType(controlType));
}
/// <summary>
/// Resolves the binding type.
/// </summary>
public Type ResolveBinding(string bindingType, ref string bindingValue)
{
if (bindingType == Constants.ValueBinding)
{
return typeof (ValueBindingExpression);
}
else if (bindingType == Constants.CommandBinding)
{
return typeof (CommandBindingExpression);
}
//else if (bindingType == Constants.ControlStateBinding)
//{
// return typeof (ControlStateBindingExpression);
//}
else if (bindingType == Constants.ControlPropertyBinding)
{
bindingValue = "_control." + bindingValue;
return typeof (ControlPropertyBindingExpression);
}
else if (bindingType == Constants.ControlCommandBinding)
{
bindingValue = "_control." + bindingValue;
return typeof(ControlCommandBindingExpression);
}
else if (bindingType == Constants.ResourceBinding)
{
return typeof (ResourceBindingExpression);
}
else if(bindingType == Constants.StaticCommandBinding)
{
return typeof(StaticCommandBindingExpression);
}
else
{
throw new NotSupportedException(string.Format("The binding {{{0}: ... }} is unknown!", bindingType)); // TODO: exception handling
}
}
/// <summary>
/// Finds the control metadata.
/// </summary>
private ControlType FindControlType(string tagPrefix, string tagName)
{
// try to match the tag prefix and tag name
var rules = configuration.Markup.Controls.Where(r => r.IsMatch(tagPrefix, tagName));
foreach (var rule in rules)
{
// validate the rule
rule.Validate();
if (string.IsNullOrEmpty(rule.TagName))
{
// find the code only control
var compiledControl = FindCompiledControl(tagName, rule.Namespace, rule.Assembly);
if (compiledControl != null)
{
return compiledControl;
}
}
else
{
// find the markup control
return FindMarkupControl(rule.Src);
}
}
throw new Exception(string.Format(Resources.Controls.ControlResolver_ControlNotFound, tagPrefix, tagName));
}
/// <summary>
/// Finds the compiled control.
/// </summary>
private ControlType FindCompiledControl(string tagName, string namespaceName, string assemblyName)
{
var type = Type.GetType(namespaceName + "." + tagName + ", " + assemblyName, false);
if (type == null)
{
// the control was not found
return null;
}
return new ControlType(type);
}
/// <summary>
/// Finds the markup control.
/// </summary>
private ControlType FindMarkupControl(string file)
{
var controlBuilder = controlBuilderFactory.GetControlBuilder(file);
// TODO: do not build the control when i only need the type (?)
return new ControlType(controlBuilder.BuildControl(controlBuilderFactory).GetType(), controlBuilder.GetType(), file);
}
/// <summary>
/// Gets the control metadata.
/// </summary>
private ControlResolverMetadata BuildControlMetadata(ControlType type)
{
var attribute = type.Type.GetCustomAttribute<ControlMarkupOptionsAttribute>();
var properties = GetControlProperties(type.Type);
var metadata = new ControlResolverMetadata()
{
Name = type.Type.Name,
Namespace = type.Type.Namespace,
HasHtmlAttributesCollection = typeof(IControlWithHtmlAttributes).IsAssignableFrom(type.Type),
Type = type.Type,
ControlBuilderType = type.ControlBuilderType,
Properties = properties,
IsContentAllowed = attribute.AllowContent,
VirtualPath = type.VirtualPath,
DataContextConstraint = type.DataContextRequirement,
DefaultContentProperty = attribute.DefaultContentProperty != null ? properties[attribute.DefaultContentProperty] : null
};
return metadata;
}
/// <summary>
/// Gets the control properties.
/// </summary>
private Dictionary<string, DotvvmProperty> GetControlProperties(Type controlType)
{
return DotvvmProperty.ResolveProperties(controlType).ToDictionary(p => p.Name, p => p);
}
}
}
| |
// 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;
/// <summary>
/// Pass LPArray Size by ref keyword using SizeParamIndex Attributes
/// </summary>
public class ClientMarshalArrayAsSizeParamIndexByRefTest
{
#region ByRef
[DllImport("PInvokePassingByRefNative")]
private static extern bool MarshalCStyleArrayByte_AsByRef_AsSizeParamIndex(
ref byte arrSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] ref byte[] arrByte);
[DllImport("PInvokePassingByRefNative")]
private static extern bool MarshalCStyleArraySbyte_AsByRef_AsSizeParamIndex(
ref sbyte arrSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] ref sbyte[] arrSbyte);
[DllImport("PInvokePassingByRefNative")]
private static extern bool MarshalCStyleArrayShort_AsByRef_AsSizeParamIndex(
ref short arrSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] ref short[] arrShort);
[DllImport("PInvokePassingByRefNative")]
private static extern bool MarshalCStyleArrayShortReturnNegative_AsByRef_AsSizeParamIndex(
ref short arrSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] ref short[] arrShort);
[DllImport("PInvokePassingByRefNative")]
private static extern bool MarshalCStyleArrayUshort_AsByRef_AsSizeParamIndex(
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] ref ushort[] arrUshort, ref ushort arrSize);
[DllImport("PInvokePassingByRefNative")]
private static extern bool MarshalCStyleArrayInt_AsByRef_AsSizeParamIndex(
ref Int32 arrSize, Int32 unused, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] ref Int32[] arrInt32);
[DllImport("PInvokePassingByRefNative")]
private static extern bool MarshalCStyleArrayUInt_AsByRef_AsSizeParamIndex(
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] ref UInt32[] arrUInt32, UInt32 unused, ref UInt32 arrSize);
[DllImport("PInvokePassingByRefNative")]
private static extern bool MarshalCStyleArrayLong_AsByRef_AsSizeParamIndex(
ref long arrSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] ref long[] arrLong);
[DllImport("PInvokePassingByRefNative")]
private static extern bool MarshalCStyleArrayUlong_AsByRef_AsSizeParamIndex(
ref ulong arrSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] ref ulong[] arrUlong);
[DllImport("PInvokePassingByRefNative")]
private static extern bool MarshalCStyleArrayString_AsByRef_AsSizeParamIndex(
ref int arrSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0, ArraySubType = UnmanagedType.BStr)] ref string[] arrStr,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0, ArraySubType = UnmanagedType.LPStr)] ref string[] arrStr2);
#endregion
static void SizeParamTypeIsByte()
{
string strDescription = "Scenario(byte==>BYTE):Array_Size(M->N)=1,Array_Size(N->M)= byte.MinValue";
Console.WriteLine();
Console.WriteLine(strDescription + " Starts!");
byte byte_Array_Size = 1;
byte[] arrByte = Helper.InitArray<byte>(byte_Array_Size);
Assert.IsTrue(MarshalCStyleArrayByte_AsByRef_AsSizeParamIndex(ref byte_Array_Size, ref arrByte));
//Construct Expected array
int expected_ByteArray_Size = Byte.MinValue;
byte[] expectedArrByte = Helper.GetExpChangeArray<byte>(expected_ByteArray_Size);
Assert.IsTrue(Helper.EqualArray<byte>(arrByte, (int)byte_Array_Size, expectedArrByte, (int)expectedArrByte.Length));
Console.WriteLine(strDescription + " Ends!");
}
static void SizeParamTypeIsSByte()
{
string strDescription = "Scenario(sbyte==>CHAR): Array_Size(M->N) = 10, Array_Size(N->M) = sbyte.Max";
Console.WriteLine();
Console.WriteLine(strDescription + " Starts!");
sbyte sbyte_Array_Size = (sbyte)10;
sbyte[] arrSbyte = Helper.InitArray<sbyte>(sbyte_Array_Size);
Assert.IsTrue(MarshalCStyleArraySbyte_AsByRef_AsSizeParamIndex(ref sbyte_Array_Size, ref arrSbyte));
//Construct Expected
sbyte[] expectedArrSbyte = Helper.GetExpChangeArray<sbyte>(sbyte.MaxValue);
Assert.IsTrue(Helper.EqualArray<sbyte>(arrSbyte, (int)sbyte_Array_Size, expectedArrSbyte, (int)sbyte.MaxValue));
Console.WriteLine(strDescription + " Ends!");
}
static void SizeParamTypeIsShort1()
{
string strDescription = "Scenario(short==>SHORT)1: Array_Size(M->N) = -1, Array_Size(N->M) = 20";
Console.WriteLine();
Console.WriteLine(strDescription + " Starts!");
short short_Array_Size = (short)-1;
short[] arrShort = Helper.InitArray<short>(10);
int expected_ByteArraySize = 20;
Assert.IsTrue(MarshalCStyleArrayShort_AsByRef_AsSizeParamIndex(ref short_Array_Size, ref arrShort));
//Construct Expected
short[] expectedArrShort = Helper.GetExpChangeArray<short>(expected_ByteArraySize);
Assert.IsTrue(Helper.EqualArray<short>(arrShort, (int)short_Array_Size, expectedArrShort, expectedArrShort.Length));
Console.WriteLine(strDescription + " Ends!");
}
static void SizeParamTypeIsShort2()
{
string strDescription = "Scenario(short==>SHORT)2: Array_Size(M->N) = 10, Array_Size(N->M) = -1";
Console.WriteLine();
Console.WriteLine(strDescription + " Starts!");
short short_Array_Size = (short)10;
short[] arrShort = Helper.InitArray<short>(10);
Assert.Throws<OverflowException>(() => MarshalCStyleArrayShortReturnNegative_AsByRef_AsSizeParamIndex(ref short_Array_Size, ref arrShort));
Console.WriteLine(strDescription + " Ends!");
}
static void SizeParamTypeIsUShort()
{
string strDescription = "Scenario(ushort==>USHORT): Array_Size(M->N) = 0, Array_Size(N->M) = ushort.MaxValue";
Console.WriteLine();
Console.WriteLine(strDescription + " Starts!");
ushort ushort_Array_Size = 20;
ushort[] arrUshort = Helper.InitArray<ushort>(ushort_Array_Size);
int expected_UshortArraySize = ushort.MaxValue;
Assert.IsTrue(MarshalCStyleArrayUshort_AsByRef_AsSizeParamIndex(ref arrUshort, ref ushort_Array_Size));
//Construct Expected
ushort[] expectedArrShort = Helper.GetExpChangeArray<ushort>(expected_UshortArraySize);
Assert.IsTrue(Helper.EqualArray<ushort>(arrUshort, (int)ushort_Array_Size, expectedArrShort, expectedArrShort.Length));
Console.WriteLine(strDescription + " Ends!");
}
static void SizeParamTypeIsInt32()
{
string strDescription = "Scenario(Int32==>LONG):Array_Size(M->N)=10, Array_Size(N->M)=1";
Console.WriteLine();
Console.WriteLine(strDescription + " Starts!");
Int32 Int32_Array_Size = (Int32)10;
Int32[] arrInt32 = Helper.InitArray<Int32>(Int32_Array_Size);
Assert.IsTrue(MarshalCStyleArrayInt_AsByRef_AsSizeParamIndex(ref Int32_Array_Size, Int32.MaxValue, ref arrInt32));
//Construct Expected
int expected_UshortArraySize = 1;
Int32[] expectedArrInt32 = Helper.GetExpChangeArray<Int32>(expected_UshortArraySize);
Assert.IsTrue(Helper.EqualArray<Int32>(arrInt32, Int32_Array_Size, expectedArrInt32, expectedArrInt32.Length));
Console.WriteLine(strDescription + " Ends!");
}
static void SizeParamTypeIsUInt32()
{
string strDescription = "Scenario(UInt32==>ULONG):Array_Size(M->N)=1234,Array_Size(N->M)=4321";
Console.WriteLine();
Console.WriteLine(strDescription + " Starts!");
UInt32 UInt32_Array_Size = (UInt32)1234;
UInt32[] arrUInt32 = Helper.InitArray<UInt32>((Int32)UInt32_Array_Size);
Assert.IsTrue(MarshalCStyleArrayUInt_AsByRef_AsSizeParamIndex(ref arrUInt32, 1234, ref UInt32_Array_Size));
//Construct Expected
int expected_UInt32ArraySize = 4321;
UInt32[] expectedArrUInt32 = Helper.GetExpChangeArray<UInt32>(expected_UInt32ArraySize);
Assert.IsTrue(Helper.EqualArray<UInt32>(arrUInt32, (Int32)UInt32_Array_Size, expectedArrUInt32, (Int32)expectedArrUInt32.Length));
Console.WriteLine(strDescription + " Ends!");
}
static void SizeParamTypeIsLong()
{
string strDescription = "Scenario(long==>LONGLONG):Array_Size(M->N)=10,Array_Size(N->M)=20";
Console.WriteLine();
Console.WriteLine(strDescription + " Starts!");
long long_Array_Size = (long)10;
long[] arrLong = Helper.InitArray<long>((Int32)long_Array_Size);
Assert.IsTrue(MarshalCStyleArrayLong_AsByRef_AsSizeParamIndex(ref long_Array_Size, ref arrLong));
//Construct Expected Array
int expected_LongArraySize = 20;
long[] expectedArrLong = Helper.GetExpChangeArray<long>(expected_LongArraySize);
Assert.IsTrue(Helper.EqualArray<long>(arrLong, (Int32)long_Array_Size, expectedArrLong, (Int32)expectedArrLong.Length));
Console.WriteLine(strDescription + " Ends!");
}
static void SizeParamTypeIsULong()
{
string strDescription = "Scenario(ulong==>ULONGLONG):Array_Size(M->N)=0, Array_Size(N->M)=0";
Console.WriteLine();
Console.WriteLine(strDescription + " Starts!");
ulong ulong_Array_Size = (ulong)0;
ulong[] arrUlong = Helper.InitArray<ulong>((Int32)ulong_Array_Size);
Assert.IsTrue(MarshalCStyleArrayUlong_AsByRef_AsSizeParamIndex(ref ulong_Array_Size, ref arrUlong));
//Construct Expected
int expected_ULongArraySize = 0;
ulong[] expectedArrUlong = Helper.GetExpChangeArray<ulong>(expected_ULongArraySize);
Assert.IsTrue(Helper.EqualArray<ulong>(arrUlong, (Int32)ulong_Array_Size, expectedArrUlong, (Int32)expectedArrUlong.Length));
Console.WriteLine(strDescription + " Ends!");
}
static void SizeParamTypeIsString()
{
string strDescription = "Scenario(String==>BSTR):Array_Size(M->N)= 20, Array_Size(N->M)=10";
Console.WriteLine();
Console.WriteLine(strDescription + " Starts!");
int array_Size = 20;
String[] arrString = Helper.InitArray<String>(array_Size);
String[] arrString2 = Helper.InitArray<String>(array_Size);
Assert.IsTrue(MarshalCStyleArrayString_AsByRef_AsSizeParamIndex(ref array_Size, ref arrString, ref arrString2));
//Construct Expected
int expected_StringArraySize = 10;
String[] expArrString = Helper.GetExpChangeArray<String>(expected_StringArraySize);
Assert.IsTrue(Helper.EqualArray<String>(arrString, array_Size, expArrString, expArrString.Length));
Console.WriteLine(strDescription + " Ends!");
}
static int Main()
{
try{
SizeParamTypeIsByte();
SizeParamTypeIsSByte();
SizeParamTypeIsShort1();
SizeParamTypeIsShort2();
SizeParamTypeIsUShort();
SizeParamTypeIsInt32();
SizeParamTypeIsUInt32();
SizeParamTypeIsLong();
SizeParamTypeIsULong();
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
SizeParamTypeIsString();
}
return 100;
}
catch (Exception e)
{
Console.WriteLine($"Test Failure: {e}");
return 101;
}
}
}
| |
namespace System.Net.Mail
{
using System;
using System.IO;
using System.Text;
using System.Collections;
//Streams created are read only and return 0 once a full server reply has been read
//To get the next server reply, call GetNextReplyReader
class SmtpReplyReaderFactory
{
enum ReadState
{
Status0,
Status1,
Status2,
ContinueFlag,
ContinueCR,
ContinueLF,
LastCR,
LastLF,
Done
}
BufferedReadStream bufferedStream;
byte[] byteBuffer;
SmtpReplyReader currentReader;
const int DefaultBufferSize = 256;
ReadState readState = ReadState.Status0;
SmtpStatusCode statusCode;
internal SmtpReplyReaderFactory(Stream stream)
{
bufferedStream = new BufferedReadStream(stream);
}
internal SmtpReplyReader CurrentReader
{
get
{
return currentReader;
}
}
internal SmtpStatusCode StatusCode
{
get
{
return statusCode;
}
}
internal IAsyncResult BeginReadLines(SmtpReplyReader caller, AsyncCallback callback, object state)
{
ReadLinesAsyncResult result = new ReadLinesAsyncResult(this, callback, state);
result.Read(caller);
return result;
}
internal IAsyncResult BeginReadLine(SmtpReplyReader caller, AsyncCallback callback, object state)
{
ReadLinesAsyncResult result = new ReadLinesAsyncResult(this, callback, state, true);
result.Read(caller);
return result;
}
internal void Close(SmtpReplyReader caller)
{
if (currentReader == caller)
{
if (readState != ReadState.Done)
{
if (byteBuffer == null)
{
byteBuffer = new byte[SmtpReplyReaderFactory.DefaultBufferSize];
}
while (0 != Read(caller, byteBuffer, 0, byteBuffer.Length));
}
currentReader = null;
}
}
internal LineInfo[] EndReadLines(IAsyncResult result)
{
return ReadLinesAsyncResult.End(result);
}
internal LineInfo EndReadLine(IAsyncResult result)
{
LineInfo[] info = ReadLinesAsyncResult.End(result);
if(info != null && info.Length >0){
return info[0];
}
return new LineInfo();
}
internal SmtpReplyReader GetNextReplyReader()
{
if (currentReader != null)
{
currentReader.Close();
}
readState = ReadState.Status0;
currentReader = new SmtpReplyReader(this);
return currentReader;
}
int ProcessRead(byte[] buffer, int offset, int read, bool readLine)
{
// if 0 bytes were read,there was a failure
if (read == 0)
{
throw new IOException(SR.GetString(SR.net_io_readfailure, SR.net_io_connectionclosed));
}
unsafe
{
fixed (byte* pBuffer = buffer)
{
byte* start = pBuffer + offset;
byte* ptr = start;
byte* end = ptr + read;
switch (readState)
{
case ReadState.Status0:
{
if (ptr < end)
{
byte b = *ptr++;
if (b < '0' && b > '9')
{
throw new FormatException(SR.GetString(SR.SmtpInvalidResponse));
}
statusCode = (SmtpStatusCode)(100*(b - '0'));
goto case ReadState.Status1;
}
readState = ReadState.Status0;
break;
}
case ReadState.Status1:
{
if (ptr < end)
{
byte b = *ptr++;
if (b < '0' && b > '9')
{
throw new FormatException(SR.GetString(SR.SmtpInvalidResponse));
}
statusCode += 10*(b - '0');
goto case ReadState.Status2;
}
readState = ReadState.Status1;
break;
}
case ReadState.Status2:
{
if (ptr < end)
{
byte b = *ptr++;
if (b < '0' && b > '9')
{
throw new FormatException(SR.GetString(SR.SmtpInvalidResponse));
}
statusCode += b - '0';
goto case ReadState.ContinueFlag;
}
readState = ReadState.Status2;
break;
}
case ReadState.ContinueFlag:
{
if (ptr < end)
{
byte b = *ptr++;
if (b == ' ') // last line
{
goto case ReadState.LastCR;
}
else if (b == '-') // more lines coming
{
goto case ReadState.ContinueCR;
}
else // error
{
throw new FormatException(SR.GetString(SR.SmtpInvalidResponse));
}
}
readState = ReadState.ContinueFlag;
break;
}
case ReadState.ContinueCR:
{
while (ptr < end)
{
if (*ptr++ == '\r')
{
goto case ReadState.ContinueLF;
}
}
readState = ReadState.ContinueCR;
break;
}
case ReadState.ContinueLF:
{
if (ptr < end)
{
if (*ptr++ != '\n')
{
throw new FormatException(SR.GetString(SR.SmtpInvalidResponse));
}
if (readLine)
{
readState = ReadState.Status0;
return (int)(ptr - start);
}
goto case ReadState.Status0;
}
readState = ReadState.ContinueLF;
break;
}
case ReadState.LastCR:
{
while (ptr < end)
{
if (*ptr++ == '\r')
{
goto case ReadState.LastLF;
}
}
readState = ReadState.LastCR;
break;
}
case ReadState.LastLF:
{
if (ptr < end)
{
if (*ptr++ != '\n')
{
throw new FormatException(SR.GetString(SR.SmtpInvalidResponse));
}
goto case ReadState.Done;
}
readState = ReadState.LastLF;
break;
}
case ReadState.Done:
{
int actual = (int)(ptr - start);
readState = ReadState.Done;
return actual;
}
}
return (int)(ptr - start);
}
}
}
internal int Read(SmtpReplyReader caller, byte[] buffer, int offset, int count)
{
// if we've already found the delimitter, then return 0 indicating
// end of stream.
if (count == 0 || currentReader != caller || readState == ReadState.Done)
{
return 0;
}
int read = bufferedStream.Read(buffer, offset, count);
int actual = ProcessRead(buffer, offset, read, false);
if (actual < read)
{
bufferedStream.Push(buffer, offset + actual, read - actual);
}
return actual;
}
internal LineInfo ReadLine(SmtpReplyReader caller)
{
LineInfo[] info = ReadLines(caller,true);
if(info != null && info.Length >0){
return info[0];
}
return new LineInfo();
}
internal LineInfo[] ReadLines(SmtpReplyReader caller)
{
return ReadLines(caller,false);
}
internal LineInfo[] ReadLines(SmtpReplyReader caller, bool oneLine)
{
if (caller != currentReader || readState == ReadState.Done)
{
return new LineInfo[0];
}
if (byteBuffer == null)
{
byteBuffer = new byte[SmtpReplyReaderFactory.DefaultBufferSize];
}
System.Diagnostics.Debug.Assert(readState == ReadState.Status0);
StringBuilder builder = new StringBuilder();
ArrayList lines = new ArrayList();
int statusRead = 0;
for(int start = 0, read = 0; ; )
{
if (start == read)
{
read = bufferedStream.Read(byteBuffer, 0, byteBuffer.Length);
start = 0;
}
int actual = ProcessRead(byteBuffer, start, read - start, true);
if (statusRead < 4)
{
int left = Math.Min(4-statusRead, actual);
statusRead += left;
start += left;
actual -= left;
if (actual == 0)
{
continue;
}
}
builder.Append(Encoding.UTF8.GetString(byteBuffer, start, actual));
start += actual;
if (readState == ReadState.Status0)
{
statusRead = 0;
lines.Add(new LineInfo(statusCode, builder.ToString(0, builder.Length - 2))); // return everything except CRLF
if(oneLine){
bufferedStream.Push(byteBuffer, start, read - start);
return (LineInfo[])lines.ToArray(typeof(LineInfo));
}
builder = new StringBuilder();
}
else if (readState == ReadState.Done)
{
lines.Add(new LineInfo(statusCode, builder.ToString(0, builder.Length - 2))); // return everything except CRLF
bufferedStream.Push(byteBuffer, start, read - start);
return (LineInfo[])lines.ToArray(typeof(LineInfo));
}
}
}
class ReadLinesAsyncResult : LazyAsyncResult
{
StringBuilder builder;
ArrayList lines;
SmtpReplyReaderFactory parent;
static AsyncCallback readCallback = new AsyncCallback(ReadCallback);
int read;
int statusRead;
bool oneLine;
internal ReadLinesAsyncResult(SmtpReplyReaderFactory parent, AsyncCallback callback, object state) : base(null, state, callback)
{
this.parent = parent;
}
internal ReadLinesAsyncResult(SmtpReplyReaderFactory parent, AsyncCallback callback, object state, bool oneLine) : base(null, state, callback)
{
this.oneLine = oneLine;
this.parent = parent;
}
internal void Read(SmtpReplyReader caller){
// if we've already found the delimitter, then return 0 indicating
// end of stream.
if (parent.currentReader != caller || parent.readState == ReadState.Done)
{
InvokeCallback();
return;
}
if (parent.byteBuffer == null)
{
parent.byteBuffer = new byte[SmtpReplyReaderFactory.DefaultBufferSize];
}
System.Diagnostics.Debug.Assert(parent.readState == ReadState.Status0);
builder = new StringBuilder();
lines = new ArrayList();
Read();
}
internal static LineInfo[] End(IAsyncResult result)
{
ReadLinesAsyncResult thisPtr = (ReadLinesAsyncResult)result;
thisPtr.InternalWaitForCompletion();
return (LineInfo[])thisPtr.lines.ToArray(typeof(LineInfo));
}
void Read()
{
do
{
IAsyncResult result = parent.bufferedStream.BeginRead(parent.byteBuffer, 0, parent.byteBuffer.Length, readCallback, this);
if (!result.CompletedSynchronously)
{
return;
}
read = parent.bufferedStream.EndRead(result);
} while(ProcessRead());
}
static void ReadCallback(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
Exception exception = null;
ReadLinesAsyncResult thisPtr = (ReadLinesAsyncResult)result.AsyncState;
try
{
thisPtr.read = thisPtr.parent.bufferedStream.EndRead(result);
if (thisPtr.ProcessRead())
{
thisPtr.Read();
}
}
catch (Exception e)
{ exception = e;
}
if(exception != null){
thisPtr.InvokeCallback(exception);
}
}
}
bool ProcessRead()
{
if (read == 0)
{
throw new IOException(SR.GetString(SR.net_io_readfailure, SR.net_io_connectionclosed));
}
for(int start = 0; start != read; )
{
int actual = parent.ProcessRead(parent.byteBuffer, start, read - start, true);
if (statusRead < 4)
{
int left = Math.Min(4-statusRead, actual);
statusRead += left;
start += left;
actual -= left;
if (actual == 0)
{
continue;
}
}
builder.Append(Encoding.UTF8.GetString(parent.byteBuffer, start, actual));
start += actual;
if (parent.readState == ReadState.Status0)
{
lines.Add(new LineInfo(parent.statusCode, builder.ToString(0, builder.Length - 2))); // return everything except CRLF
builder = new StringBuilder();
statusRead = 0;
if (oneLine) {
parent.bufferedStream.Push(parent.byteBuffer, start, read - start);
InvokeCallback();
return false;
}
}
else if (parent.readState == ReadState.Done)
{
lines.Add(new LineInfo(parent.statusCode, builder.ToString(0, builder.Length - 2))); // return everything except CRLF
parent.bufferedStream.Push(parent.byteBuffer, start, read - start);
InvokeCallback();
return false;
}
}
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.Buffers;
using System.Diagnostics;
using System.IO;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Security
{
//
// This is a wrapping stream that does data encryption/decryption based on a successfully authenticated SSPI context.
//
internal partial class SslStreamInternal : IDisposable
{
private const int FrameOverhead = 32;
private const int ReadBufferSize = 4096 * 4 + FrameOverhead; // We read in 16K chunks + headers.
private readonly SslState _sslState;
private int _nestedWrite;
private int _nestedRead;
// Never updated directly, special properties are used. This is the read buffer.
private byte[] _internalBuffer;
private int _internalOffset;
private int _internalBufferCount;
private int _decryptedBytesOffset;
private int _decryptedBytesCount;
internal SslStreamInternal(SslState sslState)
{
_sslState = sslState;
_decryptedBytesOffset = 0;
_decryptedBytesCount = 0;
}
//We will only free the read buffer if it
//actually contains no decrypted or encrypted bytes
private void ReturnReadBufferIfEmpty()
{
if (_internalBuffer != null && _decryptedBytesCount == 0 && _internalBufferCount == 0)
{
ArrayPool<byte>.Shared.Return(_internalBuffer);
_internalBuffer = null;
_internalBufferCount = 0;
_internalOffset = 0;
_decryptedBytesCount = 0;
_decryptedBytesOffset = 0;
}
}
~SslStreamInternal()
{
Dispose(disposing: false);
}
public void Dispose()
{
Dispose(disposing: true);
if (_internalBuffer == null)
{
// Suppress finalizer if the read buffer was returned.
GC.SuppressFinalize(this);
}
}
private void Dispose(bool disposing)
{
// Ensure a Read operation is not in progress,
// block potential reads since SslStream is disposing.
// This leaves the _nestedRead = 1, but that's ok, since
// subsequent Reads first check if the context is still available.
if (Interlocked.CompareExchange(ref _nestedRead, 1, 0) == 0)
{
byte[] buffer = _internalBuffer;
if (buffer != null)
{
_internalBuffer = null;
_internalBufferCount = 0;
_internalOffset = 0;
ArrayPool<byte>.Shared.Return(buffer);
}
}
}
internal int ReadByte()
{
if (Interlocked.Exchange(ref _nestedRead, 1) == 1)
{
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, "ReadByte", "read"));
}
// If there's any data in the buffer, take one byte, and we're done.
try
{
if (_decryptedBytesCount > 0)
{
int b = _internalBuffer[_decryptedBytesOffset++];
_decryptedBytesCount--;
ReturnReadBufferIfEmpty();
return b;
}
}
finally
{
// Regardless of whether we were able to read a byte from the buffer,
// reset the read tracking. If we weren't able to read a byte, the
// subsequent call to Read will set the flag again.
_nestedRead = 0;
}
// Otherwise, fall back to reading a byte via Read, the same way Stream.ReadByte does.
// This allocation is unfortunate but should be relatively rare, as it'll only occur once
// per buffer fill internally by Read.
byte[] oneByte = new byte[1];
int bytesRead = Read(oneByte, 0, 1);
Debug.Assert(bytesRead == 0 || bytesRead == 1);
return bytesRead == 1 ? oneByte[0] : -1;
}
internal int Read(byte[] buffer, int offset, int count)
{
ValidateParameters(buffer, offset, count);
SslReadSync reader = new SslReadSync(_sslState);
return ReadAsyncInternal(reader, new Memory<byte>(buffer, offset, count)).GetAwaiter().GetResult();
}
internal void Write(byte[] buffer, int offset, int count)
{
ValidateParameters(buffer, offset, count);
SslWriteSync writeAdapter = new SslWriteSync(_sslState);
WriteAsyncInternal(writeAdapter, new ReadOnlyMemory<byte>(buffer, offset, count)).GetAwaiter().GetResult();
}
internal IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
return TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState);
}
internal Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
ValidateParameters(buffer, offset, count);
SslReadAsync read = new SslReadAsync(_sslState, cancellationToken);
return ReadAsyncInternal(read, new Memory<byte>(buffer, offset, count)).AsTask();
}
internal ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken)
{
SslReadAsync read = new SslReadAsync(_sslState, cancellationToken);
return ReadAsyncInternal(read, buffer);
}
internal int EndRead(IAsyncResult asyncResult) => TaskToApm.End<int>(asyncResult);
internal IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
return TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState);
}
internal void EndWrite(IAsyncResult asyncResult) => TaskToApm.End(asyncResult);
internal Task WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
{
SslWriteAsync writeAdapter = new SslWriteAsync(_sslState, cancellationToken);
return WriteAsyncInternal(writeAdapter, buffer);
}
internal Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
ValidateParameters(buffer, offset, count);
return WriteAsync(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken);
}
private void ResetReadBuffer()
{
Debug.Assert(_decryptedBytesCount == 0);
Debug.Assert(_internalBuffer == null || _internalBufferCount > 0);
if (_internalBuffer == null)
{
_internalBuffer = ArrayPool<byte>.Shared.Rent(ReadBufferSize);
}
else if (_internalOffset > 0)
{
// We have buffered data at a non-zero offset.
// To maximize the buffer space available for the next read,
// copy the existing data down to the beginning of the buffer.
Buffer.BlockCopy(_internalBuffer, _internalOffset, _internalBuffer, 0, _internalBufferCount);
_internalOffset = 0;
}
}
//
// Validates user parameters for all Read/Write methods.
//
private void ValidateParameters(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
if (count > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.net_offset_plus_count);
}
}
private async ValueTask<int> ReadAsyncInternal<TReadAdapter>(TReadAdapter adapter, Memory<byte> buffer)
where TReadAdapter : ISslReadAdapter
{
if (Interlocked.Exchange(ref _nestedRead, 1) == 1)
{
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, nameof(ReadAsync), "read"));
}
while (true)
{
int copyBytes;
if (_decryptedBytesCount != 0)
{
copyBytes = CopyDecryptedData(buffer);
_sslState.FinishRead(null);
_nestedRead = 0;
return copyBytes;
}
copyBytes = await adapter.LockAsync(buffer).ConfigureAwait(false);
try
{
if (copyBytes > 0)
{
return copyBytes;
}
ResetReadBuffer();
int readBytes = await FillBufferAsync(adapter, SecureChannel.ReadHeaderSize).ConfigureAwait(false);
if (readBytes == 0)
{
return 0;
}
int payloadBytes = _sslState.GetRemainingFrameSize(_internalBuffer, _internalOffset, readBytes);
if (payloadBytes < 0)
{
throw new IOException(SR.net_frame_read_size);
}
readBytes = await FillBufferAsync(adapter, SecureChannel.ReadHeaderSize + payloadBytes).ConfigureAwait(false);
if (readBytes < 0)
{
throw new IOException(SR.net_frame_read_size);
}
// At this point, readBytes contains the size of the header plus body.
// Set _decrytpedBytesOffset/Count to the current frame we have (including header)
// DecryptData will decrypt in-place and modify these to point to the actual decrypted data, which may be smaller.
_decryptedBytesOffset = _internalOffset;
_decryptedBytesCount = readBytes;
SecurityStatusPal status = _sslState.DecryptData(_internalBuffer, ref _decryptedBytesOffset, ref _decryptedBytesCount);
// Treat the bytes we just decrypted as consumed
// Note, we won't do another buffer read until the decrypted bytes are processed
ConsumeBufferedBytes(readBytes);
if (status.ErrorCode != SecurityStatusPalErrorCode.OK)
{
byte[] extraBuffer = null;
if (_decryptedBytesCount != 0)
{
extraBuffer = new byte[_decryptedBytesCount];
Buffer.BlockCopy(_internalBuffer, _decryptedBytesOffset, extraBuffer, 0, _decryptedBytesCount);
_decryptedBytesCount = 0;
}
ProtocolToken message = new ProtocolToken(null, status);
if (NetEventSource.IsEnabled)
NetEventSource.Info(null, $"***Processing an error Status = {message.Status}");
if (message.Renegotiate)
{
if (!_sslState._sslAuthenticationOptions.AllowRenegotiation)
{
throw new IOException(SR.net_ssl_io_renego);
}
_sslState.ReplyOnReAuthentication(extraBuffer);
// Loop on read.
continue;
}
if (message.CloseConnection)
{
_sslState.FinishRead(null);
return 0;
}
throw new IOException(SR.net_io_decrypt, message.GetException());
}
}
catch (Exception e)
{
_sslState.FinishRead(null);
if (e is IOException)
{
throw;
}
throw new IOException(SR.net_io_read, e);
}
finally
{
_nestedRead = 0;
}
}
}
private Task WriteAsyncInternal<TWriteAdapter>(TWriteAdapter writeAdapter, ReadOnlyMemory<byte> buffer)
where TWriteAdapter : struct, ISslWriteAdapter
{
_sslState.CheckThrow(authSuccessCheck: true, shutdownCheck: true);
if (buffer.Length == 0 && !SslStreamPal.CanEncryptEmptyMessage)
{
// If it's an empty message and the PAL doesn't support that, we're done.
return Task.CompletedTask;
}
if (Interlocked.Exchange(ref _nestedWrite, 1) == 1)
{
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, nameof(WriteAsync), "write"));
}
Task t = buffer.Length < _sslState.MaxDataSize ?
WriteSingleChunk(writeAdapter, buffer) :
WriteAsyncChunked(writeAdapter, buffer);
if (t.IsCompletedSuccessfully)
{
_nestedWrite = 0;
return t;
}
return ExitWriteAsync(t);
async Task ExitWriteAsync(Task task)
{
try
{
await task.ConfigureAwait(false);
}
catch (Exception e)
{
_sslState.FinishWrite();
if (e is IOException)
{
throw;
}
throw new IOException(SR.net_io_write, e);
}
finally
{
_nestedWrite = 0;
}
}
}
private Task WriteSingleChunk<TWriteAdapter>(TWriteAdapter writeAdapter, ReadOnlyMemory<byte> buffer)
where TWriteAdapter : struct, ISslWriteAdapter
{
// Request a write IO slot.
Task ioSlot = writeAdapter.LockAsync();
if (!ioSlot.IsCompletedSuccessfully)
{
// Operation is async and has been queued, return.
return WaitForWriteIOSlot(writeAdapter, ioSlot, buffer);
}
byte[] rentedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length + FrameOverhead);
byte[] outBuffer = rentedBuffer;
SecurityStatusPal status = _sslState.EncryptData(buffer, ref outBuffer, out int encryptedBytes);
if (status.ErrorCode != SecurityStatusPalErrorCode.OK)
{
// Re-handshake status is not supported.
ArrayPool<byte>.Shared.Return(rentedBuffer);
ProtocolToken message = new ProtocolToken(null, status);
return Task.FromException(new IOException(SR.net_io_encrypt, message.GetException()));
}
Task t = writeAdapter.WriteAsync(outBuffer, 0, encryptedBytes);
if (t.IsCompletedSuccessfully)
{
ArrayPool<byte>.Shared.Return(rentedBuffer);
_sslState.FinishWrite();
return t;
}
else
{
return CompleteAsync(t, rentedBuffer);
}
async Task WaitForWriteIOSlot(TWriteAdapter wAdapter, Task lockTask, ReadOnlyMemory<byte> buff)
{
await lockTask.ConfigureAwait(false);
await WriteSingleChunk(wAdapter, buff).ConfigureAwait(false);
}
async Task CompleteAsync(Task writeTask, byte[] bufferToReturn)
{
try
{
await writeTask.ConfigureAwait(false);
}
finally
{
ArrayPool<byte>.Shared.Return(bufferToReturn);
_sslState.FinishWrite();
}
}
}
private async Task WriteAsyncChunked<TWriteAdapter>(TWriteAdapter writeAdapter, ReadOnlyMemory<byte> buffer)
where TWriteAdapter : struct, ISslWriteAdapter
{
do
{
int chunkBytes = Math.Min(buffer.Length, _sslState.MaxDataSize);
await WriteSingleChunk(writeAdapter, buffer.Slice(0, chunkBytes)).ConfigureAwait(false);
buffer = buffer.Slice(chunkBytes);
} while (buffer.Length != 0);
}
private ValueTask<int> FillBufferAsync<TReadAdapter>(TReadAdapter adapter, int minSize)
where TReadAdapter : ISslReadAdapter
{
if (_internalBufferCount >= minSize)
{
return new ValueTask<int>(minSize);
}
int initialCount = _internalBufferCount;
do
{
ValueTask<int> t = adapter.ReadAsync(_internalBuffer, _internalBufferCount, _internalBuffer.Length - _internalBufferCount);
if (!t.IsCompletedSuccessfully)
{
return new ValueTask<int>(InternalFillBufferAsync(adapter, t.AsTask(), minSize, initialCount));
}
int bytes = t.Result;
if (bytes == 0)
{
if (_internalBufferCount != initialCount)
{
// We read some bytes, but not as many as we expected, so throw.
throw new IOException(SR.net_io_eof);
}
return new ValueTask<int>(0);
}
_internalBufferCount += bytes;
} while (_internalBufferCount < minSize);
return new ValueTask<int>(minSize);
async Task<int> InternalFillBufferAsync(TReadAdapter adap, Task<int> task, int min, int initial)
{
while (true)
{
int b = await task.ConfigureAwait(false);
if (b == 0)
{
if (_internalBufferCount != initial)
{
throw new IOException(SR.net_io_eof);
}
return 0;
}
_internalBufferCount += b;
if (_internalBufferCount >= min)
{
return min;
}
task = adap.ReadAsync(_internalBuffer, _internalBufferCount, _internalBuffer.Length - _internalBufferCount).AsTask();
}
}
}
private void ConsumeBufferedBytes(int byteCount)
{
Debug.Assert(byteCount >= 0);
Debug.Assert(byteCount <= _internalBufferCount);
_internalOffset += byteCount;
_internalBufferCount -= byteCount;
ReturnReadBufferIfEmpty();
}
private int CopyDecryptedData(Memory<byte> buffer)
{
Debug.Assert(_decryptedBytesCount > 0);
int copyBytes = Math.Min(_decryptedBytesCount, buffer.Length);
if (copyBytes != 0)
{
new Span<byte>(_internalBuffer, _decryptedBytesOffset, copyBytes).CopyTo(buffer.Span);
_decryptedBytesOffset += copyBytes;
_decryptedBytesCount -= copyBytes;
}
ReturnReadBufferIfEmpty();
return copyBytes;
}
}
}
| |
#pragma warning disable 1634, 1691
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections.Generic;
using System.Transactions;
using System.Management.Automation.Internal;
namespace System.Management.Automation
{
/// <summary>
/// The status of a PowerShell transaction.
/// </summary>
public enum PSTransactionStatus
{
/// <summary>
/// The transaction has been rolled back
/// </summary>
RolledBack = 0,
/// <summary>
/// The transaction has been committed
/// </summary>
Committed = 1,
/// <summary>
/// The transaction is currently active
/// </summary>
Active = 2
}
/// <summary>
/// Represents an active transaction
/// </summary>
///
public sealed class PSTransaction : IDisposable
{
/// <summary>
/// Initializes a new instance of the PSTransaction class
/// </summary>
///
internal PSTransaction(RollbackSeverity rollbackPreference, TimeSpan timeout)
{
_transaction = new CommittableTransaction(timeout);
RollbackPreference = rollbackPreference;
_subscriberCount = 1;
}
/// <summary>
/// Initializes a new instance of the PSTransaction class using a CommittableTransaction
/// </summary>
///
internal PSTransaction(CommittableTransaction transaction, RollbackSeverity severity)
{
_transaction = transaction;
RollbackPreference = severity;
_subscriberCount = 1;
}
private CommittableTransaction _transaction;
/// <summary>
/// Gets the rollback preference for this transaction
/// </summary>
///
public RollbackSeverity RollbackPreference { get; }
/// <summary>
/// Gets the number of subscribers to this transaction
/// </summary>
///
public int SubscriberCount
{
get
{
// Verify the transaction hasn't been rolled back beneath us
if (this.IsRolledBack)
{
this.SubscriberCount = 0;
}
return _subscriberCount;
}
set { _subscriberCount = value; }
}
private int _subscriberCount;
/// <summary>
/// Returns the status of this transaction.
/// </summary>
///
public PSTransactionStatus Status
{
get
{
if (IsRolledBack)
{
return PSTransactionStatus.RolledBack;
}
else if (IsCommitted)
{
return PSTransactionStatus.Committed;
}
else
{
return PSTransactionStatus.Active;
}
}
}
/// <summary>
/// Activates the transaction held by this PSTransaction
/// </summary>
///
internal void Activate()
{
Transaction.Current = _transaction;
}
/// <summary>
/// Commits the transaction held by this PSTransaction
/// </summary>
///
internal void Commit()
{
_transaction.Commit();
IsCommitted = true;
}
/// <summary>
/// Rolls back the transaction held by this PSTransaction
/// </summary>
///
internal void Rollback()
{
_transaction.Rollback();
_isRolledBack = true;
}
/// <summary>
/// Determines whether this PSTransaction has been
/// rolled back or not.
/// </summary>
///
internal bool IsRolledBack
{
get
{
// Check if it's been aborted underneath us
if (
(!_isRolledBack) &&
(_transaction != null) &&
(_transaction.TransactionInformation.Status == TransactionStatus.Aborted))
{
_isRolledBack = true;
}
return _isRolledBack;
}
set
{
_isRolledBack = value;
}
}
private bool _isRolledBack = false;
/// <summary>
/// Determines whether this PSTransaction
/// has been committed or not.
/// </summary>
///
internal bool IsCommitted { get; set; } = false;
/// <summary>
/// Destructor for the PSTransaction class
/// </summary>
///
~PSTransaction()
{
Dispose(false);
}
/// <summary>
/// Disposes the PSTransaction object.
/// </summary>
///
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes the PSTransaction object, which disposes the
/// underlying transaction.
///
/// <param name="disposing">
/// Whether to actually dispose the object.
/// </param>
/// </summary>
///
public void Dispose(bool disposing)
{
if (disposing)
{
if (_transaction != null)
{
_transaction.Dispose();
}
}
}
}
/// <summary>
/// Supports the transaction management infrastructure for the PowerShell engine
/// </summary>
///
public sealed class PSTransactionContext : IDisposable
{
/// <summary>
/// Initializes a new instance of the PSTransactionManager class
/// </summary>
///
internal PSTransactionContext(PSTransactionManager transactionManager)
{
_transactionManager = transactionManager;
transactionManager.SetActive();
}
private PSTransactionManager _transactionManager;
/// <summary>
/// Destructor for the PSTransactionManager class
/// </summary>
///
~PSTransactionContext()
{
Dispose(false);
}
/// <summary>
/// Disposes the PSTransactionContext object.
/// </summary>
///
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes the PSTransactionContext object, which resets the
/// active PSTransaction.
///
/// <param name="disposing">
/// Whether to actually dispose the object.
/// </param>
/// </summary>
///
private void Dispose(bool disposing)
{
if (disposing)
{
_transactionManager.ResetActive();
}
}
}
/// <summary>
/// The severity of error that causes PowerShell to automatically
/// rollback the transaction.
/// </summary>
public enum RollbackSeverity
{
/// <summary>
/// Non-terminating errors or worse
/// </summary>
Error,
/// <summary>
/// Terminating errors or worse
/// </summary>
TerminatingError,
/// <summary>
/// Do not rollback the transaction on error
/// </summary>
Never
}
}
namespace System.Management.Automation.Internal
{
/// <summary>
/// Supports the transaction management infrastructure for the PowerShell engine
/// </summary>
///
internal sealed class PSTransactionManager : IDisposable
{
/// <summary>
/// Initializes a new instance of the PSTransactionManager class
/// </summary>
///
internal PSTransactionManager()
{
_transactionStack = new Stack<PSTransaction>();
_transactionStack.Push(null);
}
/// <summary>
/// Called by engine APIs to ensure they are protected from
/// ambient transactions.
/// </summary>
///
internal static IDisposable GetEngineProtectionScope()
{
if (s_engineProtectionEnabled && (Transaction.Current != null))
{
return new System.Transactions.TransactionScope(
System.Transactions.TransactionScopeOption.Suppress);
}
else
{
return null;
}
}
/// <summary>
/// Called by the transaction manager to enable engine
/// protection the first time a transaction is activated.
/// Engine protection APIs remain protected from this point on.
/// </summary>
///
internal static void EnableEngineProtection()
{
s_engineProtectionEnabled = true;
}
private static bool s_engineProtectionEnabled = false;
/// <summary>
/// Gets the rollback preference for the active transaction
/// </summary>
///
internal RollbackSeverity RollbackPreference
{
get
{
PSTransaction currentTransaction = _transactionStack.Peek();
if (currentTransaction == null)
{
string error = TransactionStrings.NoTransactionActive;
// This is not an expected condition, and is just protective
// coding.
#pragma warning suppress 56503
throw new InvalidOperationException(error);
}
return currentTransaction.RollbackPreference;
}
}
/// <summary>
/// Creates a new Transaction if none are active. Otherwise, increments
/// the subscriber count for the active transaction.
/// </summary>
///
internal void CreateOrJoin()
{
CreateOrJoin(RollbackSeverity.Error, TimeSpan.FromMinutes(1));
}
/// <summary>
/// Creates a new Transaction if none are active. Otherwise, increments
/// the subscriber count for the active transaction.
/// </summary>
///
internal void CreateOrJoin(RollbackSeverity rollbackPreference, TimeSpan timeout)
{
PSTransaction currentTransaction = _transactionStack.Peek();
// There is a transaction on the stack
if (currentTransaction != null)
{
// If you are already in a transaction that has been aborted, or committed,
// create it.
if (currentTransaction.IsRolledBack || currentTransaction.IsCommitted)
{
// Clean up the "used" one
_transactionStack.Pop().Dispose();
// And add a new one to the stack
_transactionStack.Push(new PSTransaction(rollbackPreference, timeout));
}
else
{
// This is a usable one. Add a subscriber to it.
currentTransaction.SubscriberCount++;
}
}
else
{
// Add a new transaction to the stack
_transactionStack.Push(new PSTransaction(rollbackPreference, timeout));
}
}
/// <summary>
/// Creates a new Transaction that should be managed independently of
/// any parent transactions.
/// </summary>
///
internal void CreateNew()
{
CreateNew(RollbackSeverity.Error, TimeSpan.FromMinutes(1));
}
/// <summary>
/// Creates a new Transaction that should be managed independently of
/// any parent transactions.
/// </summary>
///
internal void CreateNew(RollbackSeverity rollbackPreference, TimeSpan timeout)
{
_transactionStack.Push(new PSTransaction(rollbackPreference, timeout));
}
/// <summary>
/// Completes the current transaction. If only one subscriber is active, this
/// commits the transaction. Otherwise, it reduces the subscriber count by one.
/// </summary>
///
internal void Commit()
{
PSTransaction currentTransaction = _transactionStack.Peek();
// Should not be able to commit a transaction that is not active
if (currentTransaction == null)
{
string error = TransactionStrings.NoTransactionActiveForCommit;
throw new InvalidOperationException(error);
}
// If you are already in a transaction that has been aborted
if (currentTransaction.IsRolledBack)
{
string error = TransactionStrings.TransactionRolledBackForCommit;
throw new TransactionAbortedException(error);
}
// If you are already in a transaction that has been committed
if (currentTransaction.IsCommitted)
{
string error = TransactionStrings.CommittedTransactionForCommit;
throw new InvalidOperationException(error);
}
if (currentTransaction.SubscriberCount == 1)
{
currentTransaction.Commit();
currentTransaction.SubscriberCount = 0;
}
else
{
currentTransaction.SubscriberCount--;
}
// Now that we've committed, go back to the last available transaction
while ((_transactionStack.Count > 2) &&
(_transactionStack.Peek().IsRolledBack || _transactionStack.Peek().IsCommitted))
{
_transactionStack.Pop().Dispose();
}
}
/// <summary>
/// Aborts the current transaction, no matter how many subscribers are part of it.
/// </summary>
///
internal void Rollback()
{
Rollback(false);
}
/// <summary>
/// Aborts the current transaction, no matter how many subscribers are part of it.
/// </summary>
///
internal void Rollback(bool suppressErrors)
{
PSTransaction currentTransaction = _transactionStack.Peek();
// Should not be able to roll back a transaction that is not active
if (currentTransaction == null)
{
string error = TransactionStrings.NoTransactionActiveForRollback;
throw new InvalidOperationException(error);
}
// If you are already in a transaction that has been aborted
if (currentTransaction.IsRolledBack)
{
if (!suppressErrors)
{
// Otherwise, you should not be able to roll it back.
string error = TransactionStrings.TransactionRolledBackForRollback;
throw new TransactionAbortedException(error);
}
}
// See if they've already committed the transaction
if (currentTransaction.IsCommitted)
{
if (!suppressErrors)
{
string error = TransactionStrings.CommittedTransactionForRollback;
throw new InvalidOperationException(error);
}
}
// Roll back the transaction if it hasn't been rolled back
currentTransaction.SubscriberCount = 0;
currentTransaction.Rollback();
// Now that we've rolled back, go back to the last available transaction
while ((_transactionStack.Count > 2) &&
(_transactionStack.Peek().IsRolledBack || _transactionStack.Peek().IsCommitted))
{
_transactionStack.Pop().Dispose();
}
}
/// <summary>
/// Sets the base transaction; any transactions created thereafter will be nested to this instance
/// </summary>
///
internal void SetBaseTransaction(CommittableTransaction transaction, RollbackSeverity severity)
{
if (this.HasTransaction)
{
throw new InvalidOperationException(TransactionStrings.BaseTransactionMustBeFirst);
}
PSTransaction currentTransaction = _transactionStack.Peek();
// If there is a "used" transaction at the top of the stack, clean it up
while (_transactionStack.Peek() != null &&
(_transactionStack.Peek().IsRolledBack || _transactionStack.Peek().IsCommitted))
{
_transactionStack.Pop().Dispose();
}
_baseTransaction = new PSTransaction(transaction, severity);
_transactionStack.Push(_baseTransaction);
}
/// <summary>
/// Removes the transaction added by SetBaseTransaction
/// </summary>
///
internal void ClearBaseTransaction()
{
if (_baseTransaction == null)
{
throw new InvalidOperationException(TransactionStrings.BaseTransactionNotSet);
}
if (_transactionStack.Peek() != _baseTransaction)
{
throw new InvalidOperationException(TransactionStrings.BaseTransactionNotActive);
}
_transactionStack.Pop().Dispose();
_baseTransaction = null;
}
private Stack<PSTransaction> _transactionStack;
private PSTransaction _baseTransaction;
/// <summary>
/// Returns the current engine transaction
/// </summary>
///
internal PSTransaction GetCurrent()
{
return _transactionStack.Peek();
}
/// <summary>
/// Activates the current transaction, both in the engine, and in the Ambient.
/// </summary>
///
internal void SetActive()
{
PSTransactionManager.EnableEngineProtection();
PSTransaction currentTransaction = _transactionStack.Peek();
// Should not be able to activate a transaction that is not active
if (currentTransaction == null)
{
string error = TransactionStrings.NoTransactionForActivation;
throw new InvalidOperationException(error);
}
// If you are already in a transaction that has been aborted, you should
// not be able to activate it.
if (currentTransaction.IsRolledBack)
{
string error = TransactionStrings.NoTransactionForActivationBecauseRollback;
throw new TransactionAbortedException(error);
}
_previousActiveTransaction = Transaction.Current;
currentTransaction.Activate();
}
private Transaction _previousActiveTransaction;
/// <summary>
/// Deactivates the current transaction in the engine, and restores the
/// ambient transaction.
/// </summary>
///
internal void ResetActive()
{
// Even if you are in a transaction that has been aborted, you
// should still be able to restore the current transaction.
Transaction.Current = _previousActiveTransaction;
_previousActiveTransaction = null;
}
/// <summary>
/// Determines if you have a transaction that you can set active and work on.
/// </summary>
///
internal bool HasTransaction
{
get
{
PSTransaction currentTransaction = _transactionStack.Peek();
if ((currentTransaction != null) &&
(!currentTransaction.IsCommitted) &&
(!currentTransaction.IsRolledBack))
{
return true;
}
else
{
return false;
}
}
}
/// <summary>
/// Determines if the last transaction has been committed.
/// </summary>
internal bool IsLastTransactionCommitted
{
get
{
PSTransaction currentTransaction = _transactionStack.Peek();
if (currentTransaction != null)
{
return currentTransaction.IsCommitted;
}
else
{
return false;
}
}
}
/// <summary>
/// Determines if the last transaction has been rolled back.
/// </summary>
internal bool IsLastTransactionRolledBack
{
get
{
PSTransaction currentTransaction = _transactionStack.Peek();
if (currentTransaction != null)
{
return currentTransaction.IsRolledBack;
}
else
{
return false;
}
}
}
/// <summary>
/// Destructor for the PSTransactionManager class
/// </summary>
///
~PSTransactionManager()
{
Dispose(false);
}
/// <summary>
/// Disposes the PSTransactionManager object.
/// </summary>
///
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes the PSTransactionContext object, which resets the
/// active PSTransaction.
///
/// <param name="disposing">
/// Whether to actually dispose the object.
/// </param>
/// </summary>
///
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "baseTransaction", Justification = "baseTransaction should not be disposed since we do not own it - it belongs to the caller")]
public void Dispose(bool disposing)
{
if (disposing)
{
ResetActive();
while (_transactionStack.Peek() != null)
{
PSTransaction currentTransaction = _transactionStack.Pop();
if (currentTransaction != _baseTransaction)
{
currentTransaction.Dispose();
}
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Practices.Prism.Logging;
using Microsoft.Practices.Prism.MefExtensions;
using Microsoft.Practices.Prism.Regions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.ComponentModel.Composition.Hosting;
namespace Microsoft.Practices.Prism.MefExtensions.Tests
{
[TestClass]
public class MefBootstrapperRunMethodFixture : BootstrapperFixtureBase
{
// TODO: Tests for ordering of calls in RUN
[TestMethod]
public void CanRunBootstrapper()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
}
[TestMethod]
public void RunShouldCallCreateLogger()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.CreateLoggerCalled);
}
[TestMethod]
public void RunConfiguresServiceLocatorProvider()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(ServiceLocation.ServiceLocator.Current is MefServiceLocatorAdapter);
}
[TestMethod]
public void RunShouldCallCreateAggregateCatalog()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.CreateAggregateCatalogCalled);
}
[TestMethod]
public void RunShouldCallCreateModuleCatalog()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.CreateModuleCatalogCalled);
}
[TestMethod]
public void RunShouldCallConfigureAggregateCatalog()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.ConfigureAggregateCatalogCalled);
}
[TestMethod]
public void RunShouldCallConfigureModuleCatalog()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.ConfigureModuleCatalogCalled);
}
[TestMethod]
public void RunShouldCallCreateContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.CreateContainerCalled);
}
[TestMethod]
public void RunShouldCallConfigureContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.ConfigureContainerCalled);
}
[TestMethod]
public void RunShouldCallConfigureRegionAdapterMappings()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.ConfigureRegionAdapterMappingsCalled);
}
[TestMethod]
public void RunShouldCallConfigureDefaultRegionBehaviors()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.ConfigureDefaultRegionBehaviorsCalled);
}
[TestMethod]
public void RunShouldCallRegisterFrameworkExceptionTypes()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.RegisterFrameworkExceptionTypesCalled);
}
[TestMethod]
public void RunShouldCallCreateShell()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.CreateShellCalled);
}
[TestMethod]
public void RunShouldCallInitializeShellWhenShellSucessfullyCreated()
{
var bootstrapper = new DefaultMefBootstrapper
{
ShellObject = new UserControl()
};
bootstrapper.Run();
Assert.IsTrue(bootstrapper.InitializeShellCalled);
}
[TestMethod]
public void RunShouldNotCallInitializeShellWhenShellNotCreated()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsFalse(bootstrapper.InitializeShellCalled);
}
[TestMethod]
public void RunShouldCallInitializeModules()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.InitializeModulesCalled);
}
[TestMethod]
public void RunShouldAssignRegionManagerToReturnedShell()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.ShellObject = new UserControl();
bootstrapper.Run();
Assert.IsNotNull(RegionManager.GetRegionManager(bootstrapper.BaseShell));
}
[TestMethod]
public void RunShouldLogLoggerCreationSuccess()
{
const string expectedMessageText = "Logger was created successfully.";
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutModuleCatalogCreation()
{
const string expectedMessageText = "Creating module catalog.";
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutConfiguringModuleCatalog()
{
const string expectedMessageText = "Configuring module catalog.";
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutAggregateCatalogCreation()
{
const string expectedMessageText = "Creating catalog for MEF";
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutConfiguringAggregateCatalog()
{
const string expectedMessageText = "Configuring catalog for MEF";
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutCreatingTheContainer()
{
const string expectedMessageText = "Creating Mef container";
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutConfiguringContainer()
{
const string expectedMessageText = "Configuring MEF container";
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutConfiguringRegionAdapters()
{
const string expectedMessageText = "Configuring region adapters";
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutConfiguringRegionBehaviors()
{
const string expectedMessageText = "Configuring default region behaviors";
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutRegisteringFrameworkExceptionTypes()
{
const string expectedMessageText = "Registering Framework Exception Types";
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutSettingTheRegionManager()
{
const string expectedMessageText = "Setting the RegionManager.";
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.ShellObject = new UserControl();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutUpdatingRegions()
{
const string expectedMessageText = "Updating Regions.";
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.ShellObject = new UserControl();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutCreatingTheShell()
{
const string expectedMessageText = "Creating shell";
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutInitializingTheShellIfShellCreated()
{
const string expectedMessageText = "Initializing shell";
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.ShellObject = new UserControl();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldNotLogAboutInitializingTheShellIfShellIsNotCreated()
{
const string expectedMessageText = "Initializing shell";
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsFalse(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutInitializingModules()
{
const string expectedMessageText = "Initializing modules";
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutRunCompleting()
{
const string expectedMessageText = "Bootstrapper sequence completed";
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldCallTheMethodsInOrder()
{
var bootstrapper = new DefaultMefBootstrapper{ShellObject = new UserControl()};
bootstrapper.Run();
Assert.AreEqual("CreateLogger", bootstrapper.MethodCalls[0]);
Assert.AreEqual("CreateModuleCatalog", bootstrapper.MethodCalls[1]);
Assert.AreEqual("ConfigureModuleCatalog", bootstrapper.MethodCalls[2]);
Assert.AreEqual("CreateAggregateCatalog", bootstrapper.MethodCalls[3]);
Assert.AreEqual("ConfigureAggregateCatalog", bootstrapper.MethodCalls[4]);
Assert.AreEqual("CreateContainer", bootstrapper.MethodCalls[5]);
Assert.AreEqual("ConfigureContainer", bootstrapper.MethodCalls[6]);
Assert.AreEqual("ConfigureServiceLocator", bootstrapper.MethodCalls[7]);
Assert.AreEqual("ConfigureRegionAdapterMappings", bootstrapper.MethodCalls[8]);
Assert.AreEqual("ConfigureDefaultRegionBehaviors", bootstrapper.MethodCalls[9]);
Assert.AreEqual("RegisterFrameworkExceptionTypes", bootstrapper.MethodCalls[10]);
Assert.AreEqual("CreateShell", bootstrapper.MethodCalls[11]);
Assert.AreEqual("InitializeShell", bootstrapper.MethodCalls[12]);
Assert.AreEqual("InitializeModules", bootstrapper.MethodCalls[13]);
}
}
internal class TestLogger : ILoggerFacade
{
public List<string> LogMessages = new List<string>();
public void Log(string message, Category category, Priority priority)
{
LogMessages.Add(message);
}
}
}
| |
//==============================================================================
// TorqueLab ->
// Copyright (c) 2015 All Right Reserved, http://nordiklab.com/
//------------------------------------------------------------------------------
/*
%cfgArray.setVal("FIELD", "DEFAULT" TAB "TEXT" TAB "TextEdit" TAB "" TAB "");
*/
//==============================================================================
//==============================================================================
function TerrainMaterialDlg::checkDirty( %this ) {
%butActive = ETerrainMaterialPersistMan.getDirtyObjectCount() > 0 ? "1" : "0";
TerMatDlg_RevertBut.active = %butActive;
//TerMatDlg_ApplyBut.active = %butActive;
}
//------------------------------------------------------------------------------
//==============================================================================
function TerrainMaterialDlg::setMatDirty( %this,%mat ) {
%file = %mat.getFileName();
if (%file $= "")
%file = "art/terrain/materials.cs";
ETerrainMaterialPersistMan.setDirty( %mat, %file );
%layerCtrl = EPainterStack.findObjectByInternalName(%mat.internalName,true);
if (isObject(%layerCtrl)){
%layerCtrl.text = %mat.internalName SPC "*";
EPainter-->saveDirtyMaterials.active = 1;
}
%this.checkDirty();
}
//------------------------------------------------------------------------------
//==============================================================================
function TerrainMaterialDlg::setMatNotDirty( %this,%mat ) {
ETerrainMaterialPersistMan.removeDirty( %mat );
%layerCtrl = EPainterStack.findObjectByInternalName(%mat.internalName,true);
if (isObject(%layerCtrl))
%layerCtrl.text = %mat.internalName;
%this.checkDirty();
}
//------------------------------------------------------------------------------
//==============================================================================
function TerrainMaterialDlg::saveAllDirty( %this ) {
%count = ETerrainMaterialPersistMan.getDirtyObjectCount();
for(%i = 0;%i < %count ; %i++){
%mat = ETerrainMaterialPersistMan.getDirtyObject(%i);
%this.setMatNotDirty(%mat);
}
ETerrainMaterialPersistMan.saveDirty();
EPainter-->saveDirtyMaterials.active = 0;
}
//------------------------------------------------------------------------------
//==============================================================================
function TerrainMaterialDlg::saveDirtyMaterial( %this,%mat ) {
if (ETerrainMaterialPersistMan.isDirty(%mat))
{
ETerrainMaterialPersistMan.saveDirtyObject(%mat);
%this.setMatNotDirty(%mat);
}
}
//------------------------------------------------------------------------------
//==============================================================================
function TerrainMaterialDlg::saveActiveDirty( %this ) {
TerrainMaterialDlg.checkMaterialDirty( TerrainMaterialDlg.activeMat,true );
}
//------------------------------------------------------------------------------
//==============================================================================
function TerrainMaterialDlg::checkMaterialDirty( %this, %mat,%saveIfDirty ) {
// Skip over obviously bad cases.
if ( !isObject( %mat ) ||
!%mat.isMemberOfClass( TerrainMaterial ) )
return;
if (!%this.canSaveDirty) {
warnLog("Save dirty is disabled. Material skipped:",%mat.internalName);
return;
}
// Read out properties from the dialog.
%newInternalName = %this-->internalNameCtrl.getText();
%newFile = %this-->matFileCtrl.getText();
foreach$(%bmpField in $TerMat_BitmapFields){
%bmpCtrl = %this.findObjectByInternalName(%bmpField@"Ctrl",true);
%new[%bmpField] = %bmpCtrl.bitmap $= "tlab/materialEditor/assets/unknownImage" ? "" : %bmpCtrl.bitmap;
}
foreach$(%field in $TerMat_GuiFields){
%ctrl = %this.findObjectByInternalName(%field@"Ctrl",true);
if (%ctrl.isMemberOfClass("GuiCheckboxCtrl"))
%new[%field] = %ctrl.isStateOn();
else
%new[%field] = %ctrl.getText();
//eval("%"@%field@" = %ctrl.getText();");
}
// If no properties of this materials have changed,
// return.
foreach$(%field in $TerMat_AllFields){
%matVal = %mat.getFieldValue(%field);
if (%matVal !$= %new[%field]){
devLog("Mat change detected for field:",%field,"Current = ",%matVal,"New =",%new[%field]);
%matChanged = true;
}
}
if (%mat.getFileName() !$= %newFile){
devLog("Mat change file detected",%mat.getFileName(),"New",%newFile);
%matFileChanged = true;
}
if (!%matChanged && !%matFileChanged)
return;
// Make sure the material name is unique.
if (%matFileChanged && isFile(%newFile)){
%mat.setFileName(%newFile);
}
else if (%matFileChanged){
devLog("New file don't exist, let's try to save anyway:",%newFile);
%mat.setFileName(%newFile);
}
if( %mat.internalName !$= %newInternalName ) {
%existingMat = TerrainMaterialSet.findObjectByInternalName( %newInternalName );
if( isObject( %existingMat ) ) {
LabMsgOK( "Error",
"There already is a terrain material called '" @ %newName @ "'.", "", "" );
// Get a unique internalName
%newInternalName = getUniqueInternalName(%newInternalName,TerrainMaterialSet,true);
%this-->internalNameCtrl.setText( %newInternalName );
}
%mat.setInternalName( %newInternalName );
}
foreach$(%field in $TerMat_AllFields){
%mat.setFieldValue(%field,%new[%field]);
}
if (%mat.diffuseMap !$= %newDiffuse)
%mat.diffuseMapDefault = %newDiffuse;
if (%mat.diffuseSize !$= %diffuseSize)
%mat.diffuseSizeDefault = %diffuseSize;
%this.setMatDirty(%mat);
if (%saveIfDirty)
%this.saveDirtyMaterial(%mat);
}
//------------------------------------------------------------------------------
//==============================================================================
//Call when TerrainMaterialDlg is open and create a copy of all materials
function TerrainMaterialDlg::snapshotMaterials( %this ) {
if( !isObject( TerrainMaterialDlgSnapshot ) )
new SimGroup( TerrainMaterialDlgSnapshot );
%group = TerrainMaterialDlgSnapshot;
%group.clear();
%matCount = TerrainMaterialSet.getCount();
//Fill the mat source menu at same time
TerMatDlg_CreateSourceMenu.clear();
TerMatDlg_CreateSourceMenu.add("Blank Material",0);
for( %i = 0; %i < %matCount; %i ++ ) {
%mat = TerrainMaterialSet.getObject( %i );
if( !isMemberOfClass( %mat.getClassName(), "TerrainMaterial" ) )
continue;
if (%mat.internalName !$= "")
TerMatDlg_CreateSourceMenu.add(%mat.internalName,%mat.getId());
%snapshot = new ScriptObject() {
parentGroup = %group;
material = %mat;
};
foreach$(%field in $TerMat_AllFields SPC $TerMat_DefaultFields){
%snapshot.setFieldValue(%field,%mat.getFieldValue(%field));
}
}
TerMatDlg_CreateSourceMenu.setSelected(0);
}
//------------------------------------------------------------------------------
//==============================================================================
// Restore the materials to the state of when the TerrainMaterialDlg was open
function TerrainMaterialDlg::restoreMaterials( %this ) {
if( !isObject( TerrainMaterialDlgSnapshot ) ) {
error( "TerrainMaterial::restoreMaterials - no snapshot present" );
return;
}
%count = TerrainMaterialDlgSnapshot.getCount();
for( %i = 0; %i < %count; %i ++ ) {
%obj = TerrainMaterialDlgSnapshot.getObject( %i );
%mat = %obj.material;
%mat.setInternalName( %obj.internalName );
foreach$(%field in $TerMat_AllFields SPC $TerMat_DefaultFields){
%mat.setFieldValue(%field,%obj.getFieldValue(%field));
}
}
}
//------------------------------------------------------------------------------
//==============================================================================
function TerrainMaterialDlg::deleteMat( %this ) {
if( !isObject( %this.activeMat ) )
return;
// Cannot delete this material if it is the only one left on the Terrain
if ( ( ETerrainEditor.getMaterialCount() == 1 ) &&
( ETerrainEditor.getMaterialIndex( %this.activeMat.internalName ) != -1 ) ) {
LabMsgOK( "Error", "Cannot delete this Material, it is the only " @
"Material still in use by the active Terrain." );
return;
}
%removeIndex = TerrainMaterialSet.getObjectIndex(%this.activeMat);
TerrainMaterialSet.remove( %this.activeMat );
TerrainMaterialDlgDeleteGroup.add( %this.activeMat );
%matLibTree = %this-->matLibTree;
%matLibTree.open( TerrainMaterialSet, false );
//%matLibTree.selectItem( 1 );
%removeIndex--;
if (%removeIndex < 0)
%removeIndex = 0;
%selectMat = TerrainMaterialSet.getObject(%removeIndex);
TerrainMaterialDlg.schedule(200,"selectObjectInTree",%selectMat);
}
//------------------------------------------------------------------------------
//==============================================================================
function TerrainMaterialDlg::trashImageMap( %this,%mapType ) {
%ctrl = %this.findObjectByInternalName(%mapType@"Ctrl",true);
if (!isObject(%ctrl))
return;
%ctrl.setBitmap("tlab/materialEditor/assets/unknownImage");
}
//------------------------------------------------------------------------------
| |
// 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.Data.SqlTypes;
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
[Trait("connection", "tcp")]
public static class DateTimeTest
{
[CheckConnStrSetupFact]
public static void SQLBU503165Test()
{
SqlParameter p = new SqlParameter();
p.SqlValue = new DateTime(1200, 1, 1);
p.SqlDbType = SqlDbType.DateTime2;
DateTime expectedValue = new DateTime(1200, 1, 1);
Assert.True(p.Value.Equals(expectedValue), "FAILED: Value did not match expected DateTime value");
Assert.True(p.SqlValue.Equals(expectedValue), "FAILED: SqlValue did not match expected DateTime value");
}
[CheckConnStrSetupFact]
public static void SQLBU527900Test()
{
object chs = new char[] { 'a', 'b', 'c' };
SqlCommand command = new SqlCommand();
SqlParameter parameter = command.Parameters.AddWithValue("@o", chs);
Assert.True(parameter.Value is char[], "FAILED: Expected parameter value to be char[]");
Assert.True(parameter.SqlValue is SqlChars, "FAILED: Expected parameter value to be SqlChars");
Assert.True(parameter.SqlValue is SqlChars, "FAILED: Expected parameter value to be SqlChars");
Assert.True(parameter.Value is char[], "FAILED: Expected parameter value to be char[]");
}
[CheckConnStrSetupFact]
public static void SQLBU503290Test()
{
using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
{
conn.Open();
SqlParameter p = new SqlParameter("@p", SqlDbType.DateTimeOffset);
p.Value = DBNull.Value;
p.Size = 27;
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT @p";
cmd.Parameters.Add(p);
Assert.True(cmd.ExecuteScalar() is DBNull, "FAILED: ExecuteScalar did not return a result of type DBNull");
}
}
[CheckConnStrSetupFact]
public static void ReaderParameterTest()
{
string tempTable = "#t_" + Guid.NewGuid().ToString().Replace('-', '_');
string tempProc = "#p_" + Guid.NewGuid().ToString().Replace('-', '_');
string tempProcN = "#pn_" + Guid.NewGuid().ToString().Replace('-', '_');
string prepTable1 = "CREATE TABLE " + tempTable + " (ci int, c0 dateTime, c1 date, c2 time(7), c3 datetime2(3), c4 datetimeoffset)";
string prepTable2 = "INSERT INTO " + tempTable + " VALUES (0, " +
"'1753-01-01 12:00AM', " +
"'1753-01-01', " +
"'20:12:13.36', " +
"'2000-12-31 23:59:59.997', " +
"'9999-12-31 15:59:59.997 -08:00')";
string prepTable3 = "INSERT INTO " + tempTable + " VALUES (@pi, @p0, @p1, @p2, @p3, @p4)";
string prepProc = "CREATE PROCEDURE " + tempProc + " @p0 datetime OUTPUT, @p1 date OUTPUT, @p2 time(7) OUTPUT, @p3 datetime2(3) OUTPUT, @p4 datetimeoffset OUTPUT";
prepProc += " AS ";
prepProc += " SET @p0 = '1753-01-01 12:00AM'";
prepProc += " SET @p1 = '1753-01-01'";
prepProc += " SET @p2 = '20:12:13.36'";
prepProc += " SET @p3 = '2000-12-31 23:59:59.997'";
prepProc += "SET @p4 = '9999-12-31 15:59:59.997 -08:00'";
string prepProcN = "CREATE PROCEDURE " + tempProcN + " @p0 datetime OUTPUT, @p1 date OUTPUT, @p2 time(7) OUTPUT, @p3 datetime2(3) OUTPUT, @p4 datetimeoffset OUTPUT";
prepProcN += " AS ";
prepProcN += " SET @p0 = NULL";
prepProcN += " SET @p1 = NULL";
prepProcN += " SET @p2 = NULL";
prepProcN += " SET @p3 = NULL";
prepProcN += " SET @p4 = NULL";
using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
{
// ReaderParameterTest Setup
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = prepTable1;
cmd.ExecuteNonQuery();
cmd.CommandText = prepTable2;
cmd.ExecuteNonQuery();
#region parameter
// Parameter Tests
// Test 1
SqlCommand cmd2 = conn.CreateCommand();
cmd2.CommandText = prepTable3;
SqlParameter pi = cmd2.Parameters.Add("@pi", SqlDbType.Int);
SqlParameter p0 = cmd2.Parameters.Add("@p0", SqlDbType.DateTime);
SqlParameter p1 = cmd2.Parameters.Add("@p1", SqlDbType.Date);
SqlParameter p2 = cmd2.Parameters.Add("@p2", SqlDbType.Time);
SqlParameter p3 = cmd2.Parameters.Add("@p3", SqlDbType.DateTime2);
SqlParameter p4 = cmd2.Parameters.Add("@p4", SqlDbType.DateTimeOffset);
pi.Value = DBNull.Value;
p0.Value = DBNull.Value;
p1.Value = DBNull.Value;
p2.Value = DBNull.Value;
p3.Value = DBNull.Value;
p4.Value = DBNull.Value;
p3.Scale = 7;
cmd2.ExecuteNonQuery();
pi.Value = 1;
p0.Value = new DateTime(2000, 12, 31);
p1.Value = new DateTime(2000, 12, 31);
p2.Value = new TimeSpan(23, 59, 59);
p3.Value = new DateTime(2000, 12, 31);
p4.Value = new DateTimeOffset(2000, 12, 31, 23, 59, 59, new TimeSpan(-8, 0, 0));
p3.Scale = 3;
cmd2.ExecuteNonQuery();
// Test 2
cmd2.CommandText = "SELECT COUNT(*) FROM " + tempTable + " WHERE @pi = ci AND @p0 = c0 AND @p1 = c1 AND @p2 = c2 AND @p3 = c3 AND @p4 = c4";
pi.Value = 0;
p0.Value = new DateTime(1753, 1, 1, 0, 0, 0);
p1.Value = new DateTime(1753, 1, 1, 0, 0, 0);
p2.Value = new TimeSpan(0, 20, 12, 13, 360);
p3.Value = new DateTime(2000, 12, 31, 23, 59, 59, 997);
p4.Value = new DateTimeOffset(9999, 12, 31, 23, 59, 59, 997, TimeSpan.Zero);
p4.Scale = 3;
object scalarResult = cmd2.ExecuteScalar();
Assert.True(scalarResult.Equals(1), string.Format("FAILED: Execute scalar returned unexpected result. Expected: {0}. Actual: {1}.", 1, scalarResult));
cmd2.Parameters.Clear();
pi = cmd2.Parameters.Add("@pi", SqlDbType.Int);
p0 = cmd2.Parameters.Add("@p0", SqlDbType.DateTime);
p1 = cmd2.Parameters.Add("@p1", SqlDbType.Date);
p2 = cmd2.Parameters.Add("@p2", SqlDbType.Time);
p3 = cmd2.Parameters.Add("@p3", SqlDbType.DateTime2);
p4 = cmd2.Parameters.Add("@p4", SqlDbType.DateTimeOffset);
pi.SqlValue = new SqlInt32(0);
p0.SqlValue = new SqlDateTime(1753, 1, 1, 0, 0, 0);
p1.SqlValue = new DateTime(1753, 1, 1, 0, 0, 0);
p2.SqlValue = new TimeSpan(0, 20, 12, 13, 360);
p3.SqlValue = new DateTime(2000, 12, 31, 23, 59, 59, 997);
p4.SqlValue = new DateTimeOffset(9999, 12, 31, 23, 59, 59, 997, TimeSpan.Zero);
p2.Scale = 3;
p3.Scale = 3;
p4.Scale = 3;
scalarResult = cmd2.ExecuteScalar();
Assert.True(scalarResult.Equals(1), string.Format("FAILED: ExecutScalar returned unexpected result. Expected: {0}. Actual: {1}.", 1, scalarResult));
// Test 3
cmd.CommandText = prepProc;
cmd.ExecuteNonQuery();
cmd.CommandText = prepProcN;
cmd.ExecuteNonQuery();
SqlCommand cmd3 = conn.CreateCommand();
cmd3.CommandType = CommandType.StoredProcedure;
cmd3.CommandText = tempProc;
p0 = cmd3.Parameters.Add("@p0", SqlDbType.DateTime);
p1 = cmd3.Parameters.Add("@p1", SqlDbType.Date);
p2 = cmd3.Parameters.Add("@p2", SqlDbType.Time);
p3 = cmd3.Parameters.Add("@p3", SqlDbType.DateTime2);
p4 = cmd3.Parameters.Add("@p4", SqlDbType.DateTimeOffset);
p0.Direction = ParameterDirection.Output;
p1.Direction = ParameterDirection.Output;
p2.Direction = ParameterDirection.Output;
p3.Direction = ParameterDirection.Output;
p4.Direction = ParameterDirection.Output;
p2.Scale = 7;
cmd3.ExecuteNonQuery();
Assert.True(p0.Value.Equals((new SqlDateTime(1753, 1, 1, 0, 0, 0)).Value), "FAILED: SqlParameter p0 contained incorrect value");
Assert.True(p1.Value.Equals(new DateTime(1753, 1, 1, 0, 0, 0)), "FAILED: SqlParameter p1 contained incorrect value");
Assert.True(p2.Value.Equals(new TimeSpan(0, 20, 12, 13, 360)), "FAILED: SqlParameter p2 contained incorrect value");
Assert.True(p2.Scale.Equals(7), "FAILED: SqlParameter p0 contained incorrect scale");
Assert.True(p3.Value.Equals(new DateTime(2000, 12, 31, 23, 59, 59, 997)), "FAILED: SqlParameter p3 contained incorrect value");
Assert.True(p3.Scale.Equals(7), "FAILED: SqlParameter p3 contained incorrect scale");
Assert.True(p4.Value.Equals(new DateTimeOffset(9999, 12, 31, 23, 59, 59, 997, TimeSpan.Zero)), "FAILED: SqlParameter p4 contained incorrect value");
Assert.True(p4.Scale.Equals(7), "FAILED: SqlParameter p4 contained incorrect scale");
// Test 4
cmd3.CommandText = tempProcN;
cmd3.ExecuteNonQuery();
Assert.True(p0.Value.Equals(DBNull.Value), "FAILED: SqlParameter p0 expected to be NULL");
Assert.True(p1.Value.Equals(DBNull.Value), "FAILED: SqlParameter p1 expected to be NULL");
Assert.True(p2.Value.Equals(DBNull.Value), "FAILED: SqlParameter p2 expected to be NULL");
Assert.True(p3.Value.Equals(DBNull.Value), "FAILED: SqlParameter p3 expected to be NULL");
Assert.True(p4.Value.Equals(DBNull.Value), "FAILED: SqlParameter p4 expected to be NULL");
// Date
Assert.False(IsValidParam(SqlDbType.Date, "c1", new DateTimeOffset(1753, 1, 1, 0, 0, 0, TimeSpan.Zero), conn, tempTable), "FAILED: Invalid param for Date SqlDbType");
Assert.False(IsValidParam(SqlDbType.Date, "c1", new SqlDateTime(1753, 1, 1, 0, 0, 0), conn, tempTable), "FAILED: Invalid param for Date SqlDbType");
Assert.True(IsValidParam(SqlDbType.Date, "c1", new DateTime(1753, 1, 1, 0, 0, 0, DateTimeKind.Unspecified), conn, tempTable), "FAILED: Invalid param for Date SqlDbType");
Assert.True(IsValidParam(SqlDbType.Date, "c1", new DateTime(1753, 1, 1, 0, 0, 0, DateTimeKind.Utc), conn, tempTable), "FAILED: Invalid param for Date SqlDbType");
Assert.True(IsValidParam(SqlDbType.Date, "c1", new DateTime(1753, 1, 1, 0, 0, 0, DateTimeKind.Local), conn, tempTable), "FAILED: Invalid param for Date SqlDbType");
Assert.False(IsValidParam(SqlDbType.Date, "c1", new TimeSpan(), conn, tempTable), "FAILED: Invalid param for Date SqlDbType");
Assert.True(IsValidParam(SqlDbType.Date, "c1", "1753-1-1", conn, tempTable), "FAILED: Invalid param for Date SqlDbType");
// Time
Assert.False(IsValidParam(SqlDbType.Time, "c2", new DateTimeOffset(1753, 1, 1, 0, 0, 0, TimeSpan.Zero), conn, tempTable), "FAILED: Invalid param for Time SqlDbType");
Assert.False(IsValidParam(SqlDbType.Time, "c2", new SqlDateTime(1753, 1, 1, 0, 0, 0), conn, tempTable), "FAILED: Invalid param for Time SqlDbType");
Assert.False(IsValidParam(SqlDbType.Time, "c2", new DateTime(1753, 1, 1, 0, 0, 0, DateTimeKind.Unspecified), conn, tempTable), "FAILED: Invalid param for Time SqlDbType");
Assert.False(IsValidParam(SqlDbType.Time, "c2", new DateTime(1753, 1, 1, 0, 0, 0, DateTimeKind.Utc), conn, tempTable), "FAILED: Invalid param for Time SqlDbType");
Assert.False(IsValidParam(SqlDbType.Time, "c2", new DateTime(1753, 1, 1, 0, 0, 0, DateTimeKind.Local), conn, tempTable), "FAILED: Invalid param for Time SqlDbType");
Assert.True(IsValidParam(SqlDbType.Time, "c2", TimeSpan.Parse("20:12:13.36"), conn, tempTable), "FAILED: Invalid param for Time SqlDbType");
Assert.True(IsValidParam(SqlDbType.Time, "c2", "20:12:13.36", conn, tempTable), "FAILED: Invalid param for Time SqlDbType");
// DateTime2
DateTime dt = DateTime.Parse("2000-12-31 23:59:59.997");
Assert.False(IsValidParam(SqlDbType.DateTime2, "c3", new DateTimeOffset(1753, 1, 1, 0, 0, 0, TimeSpan.Zero), conn, tempTable), "FAILED: Invalid param for DateTime2 SqlDbType");
Assert.False(IsValidParam(SqlDbType.DateTime2, "c3", new SqlDateTime(2000, 12, 31, 23, 59, 59, 997), conn, tempTable), "FAILED: Invalid param for DateTime2 SqlDbType");
Assert.True(IsValidParam(SqlDbType.DateTime2, "c3", new DateTime(2000, 12, 31, 23, 59, 59, 997, DateTimeKind.Unspecified), conn, tempTable), "FAILED: Invalid param for DateTime2 SqlDbType");
Assert.True(IsValidParam(SqlDbType.DateTime2, "c3", new DateTime(2000, 12, 31, 23, 59, 59, 997, DateTimeKind.Utc), conn, tempTable), "FAILED: Invalid param for DateTime2 SqlDbType");
Assert.True(IsValidParam(SqlDbType.DateTime2, "c3", new DateTime(2000, 12, 31, 23, 59, 59, 997, DateTimeKind.Local), conn, tempTable), "FAILED: Invalid param for DateTime2 SqlDbType");
Assert.False(IsValidParam(SqlDbType.DateTime2, "c3", new TimeSpan(), conn, tempTable), "FAILED: Invalid param for DateTime2 SqlDbType");
Assert.True(IsValidParam(SqlDbType.DateTime2, "c3", "2000-12-31 23:59:59.997", conn, tempTable), "FAILED: Invalid param for DateTime2 SqlDbType");
// DateTimeOffset
DateTimeOffset dto = DateTimeOffset.Parse("9999-12-31 23:59:59.997 +00:00");
Assert.True(IsValidParam(SqlDbType.DateTimeOffset, "c4", dto, conn, tempTable), "FAILED: Invalid param for DateTimeOffset SqlDbType");
Assert.False(IsValidParam(SqlDbType.DateTimeOffset, "c4", new SqlDateTime(1753, 1, 1, 0, 0, 0), conn, tempTable), "FAILED: Invalid param for DateTimeOffset SqlDbType");
Assert.True(IsValidParam(SqlDbType.DateTimeOffset, "c4", new DateTime(9999, 12, 31, 15, 59, 59, 997, DateTimeKind.Unspecified), conn, tempTable), "FAILED: Invalid param for DateTimeOffset SqlDbType");
Assert.True(IsValidParam(SqlDbType.DateTimeOffset, "c4", dto.UtcDateTime, conn, tempTable), "FAILED: Invalid param for DateTimeOffset SqlDbType");
Assert.True(IsValidParam(SqlDbType.DateTimeOffset, "c4", dto.LocalDateTime, conn, tempTable), "FAILED: Invalid param for DateTimeOffset SqlDbType");
Assert.False(IsValidParam(SqlDbType.DateTimeOffset, "c4", new TimeSpan(), conn, tempTable), "FAILED: Invalid param for DateTimeOffset SqlDbType");
Assert.True(IsValidParam(SqlDbType.DateTimeOffset, "c4", "9999-12-31 23:59:59.997 +00:00", conn, tempTable), "FAILED: Invalid param for DateTimeOffset SqlDbType");
#endregion
#region reader
// Reader Tests
cmd.CommandText = "SELECT * FROM " + tempTable;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
object[] values = new object[rdr.FieldCount];
object[] sqlValues = new object[rdr.FieldCount];
object[] psValues = new object[rdr.FieldCount];
while (rdr.Read())
{
rdr.GetValues(values);
rdr.GetSqlValues(sqlValues);
rdr.GetProviderSpecificValues(psValues);
for (int i = 0; i < rdr.FieldCount; ++i)
{
if (!rdr.IsDBNull(i))
{
bool parsingSucceeded = true;
try
{
switch (i)
{
case 0:
rdr.GetInt32(i);
break;
case 1:
rdr.GetDateTime(i);
break;
case 2:
rdr.GetDateTime(i);
break;
case 3:
rdr.GetTimeSpan(i);
break;
case 4:
rdr.GetDateTime(i);
break;
case 5:
rdr.GetDateTimeOffset(i);
break;
default:
Console.WriteLine("Received unknown column number {0} during ReaderParameterTest.", i);
parsingSucceeded = false;
break;
}
}
catch (InvalidCastException)
{
parsingSucceeded = false;
}
Assert.True(parsingSucceeded, "FAILED: SqlDataReader parsing failed for column: " + i);
// Check if each value cast is equivalent to the others
// Using ToString() helps get around different representations (mainly for values[] and GetValue())
string[] valueStrList =
{
sqlValues[i].ToString(), rdr.GetSqlValue(i).ToString(), psValues[i].ToString(),
rdr.GetProviderSpecificValue(i).ToString(), values[i].ToString(), rdr.GetValue(i).ToString()
};
string[] valueNameList = { "sqlValues[]", "GetSqlValue", "psValues[]", "GetProviderSpecificValue", "values[]", "GetValue" };
for (int valNum = 0; valNum < valueStrList.Length; valNum++)
{
string currValueStr = valueStrList[valNum].ToString();
for (int otherValNum = 0; otherValNum < valueStrList.Length; otherValNum++)
{
if (valNum == otherValNum) continue;
Assert.True(currValueStr.Equals(valueStrList[otherValNum]),
string.Format("FAILED: Value from {0} not equivalent to {1} result", valueNameList[valNum], valueNameList[otherValNum]));
}
}
}
}
}
}
#endregion
}
}
[CheckConnStrSetupFact]
public static void TypeVersionKnobTest()
{
string tempTable = "#t_" + Guid.NewGuid().ToString().Replace('-', '_');
string prepTable1 = "CREATE TABLE " + tempTable + " (ci int, c0 dateTime, c1 date, c2 time(7), c3 datetime2(3), c4 datetimeoffset)";
string prepTable2 = "INSERT INTO " + tempTable + " VALUES (0, " +
"'1753-01-01 12:00AM', " +
"'1753-01-01', " +
"'20:12:13.36', " +
"'2000-12-31 23:59:59.997', " +
"'9999-12-31 15:59:59.997 -08:00')";
string prepTable3 = "INSERT INTO " + tempTable + " VALUES (NULL, NULL, NULL, NULL, NULL, NULL)";
using (SqlConnection conn = new SqlConnection(new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { TypeSystemVersion = "SQL Server 2008" }.ConnectionString))
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = prepTable1;
cmd.ExecuteNonQuery();
cmd.CommandText = prepTable2;
cmd.ExecuteNonQuery();
cmd.CommandText = prepTable3;
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT * FROM " + tempTable;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
for (int i = 2; i < rdr.FieldCount; ++i)
{
Assert.True(IsNotString(rdr, i), string.Format("FAILED: IsNotString failed for column: {0}", i));
}
for (int i = 2; i < rdr.FieldCount; ++i)
{
ValidateReader(rdr, i);
}
}
}
}
using (SqlConnection conn = new SqlConnection(new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { TypeSystemVersion = "SQL Server 2005" }.ConnectionString))
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = prepTable1;
cmd.ExecuteNonQuery();
cmd.CommandText = prepTable2;
cmd.ExecuteNonQuery();
cmd.CommandText = prepTable3;
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT * FROM " + tempTable;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
for (int i = 2; i < rdr.FieldCount; ++i)
{
Assert.True(IsString(rdr, i), string.Format("FAILED: IsString failed for column: {0}", i));
}
for (int i = 2; i < rdr.FieldCount; ++i)
{
ValidateReader(rdr, i);
}
}
}
}
}
private static bool IsValidParam(SqlDbType dbType, string col, object value, SqlConnection conn, string tempTable)
{
try
{
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM " + tempTable + " WHERE " + col + " = @p", conn);
cmd.Parameters.Add("@p", dbType).Value = value;
cmd.ExecuteScalar();
}
catch (InvalidCastException)
{
return false;
}
return true;
}
private static bool IsString(SqlDataReader rdr, int column)
{
if (!rdr.IsDBNull(column))
{
try
{
rdr.GetString(column);
}
catch (InvalidCastException)
{
return false;
}
}
try
{
rdr.GetSqlString(column);
}
catch (InvalidCastException)
{
return false;
}
try
{
rdr.GetSqlChars(column);
}
catch (InvalidCastException)
{
return false;
}
object o = rdr.GetValue(column);
if (o != DBNull.Value && !(o is string))
{
return false;
}
o = rdr.GetSqlValue(column);
if (!(o is SqlString))
{
return false;
}
return true;
}
private static bool IsNotString(SqlDataReader rdr, int column)
{
if (!rdr.IsDBNull(column))
{
try
{
rdr.GetString(column);
return false;
}
catch (InvalidCastException)
{
}
}
try
{
rdr.GetSqlString(column);
return false;
}
catch (InvalidCastException)
{
}
try
{
rdr.GetSqlChars(column);
return false;
}
catch (InvalidCastException)
{
}
object o = rdr.GetValue(column);
if (o is string)
{
return false;
}
o = rdr.GetSqlValue(column);
if (o is SqlString)
{
return false;
}
return true;
}
private static void ValidateReader(SqlDataReader rdr, int column)
{
bool validateSucceeded = false;
Action[] nonDbNullActions =
{
() => rdr.GetDateTime(column),
() => rdr.GetTimeSpan(column),
() => rdr.GetDateTimeOffset(column),
() => rdr.GetString(column)
};
Action[] genericActions =
{
() => rdr.GetSqlString(column),
() => rdr.GetSqlChars(column),
() => rdr.GetSqlDateTime(column)
};
Action<Action[]> validateParsingActions =
(testActions) =>
{
foreach (Action testAction in testActions)
{
try
{
testAction();
validateSucceeded = true;
}
catch (InvalidCastException)
{
}
}
};
if (!rdr.IsDBNull(column))
{
validateParsingActions(nonDbNullActions);
}
validateParsingActions(genericActions);
// Server 2008 & 2005 seem to represent DBNull slightly differently. Might be related to a Timestamp IsDBNull bug
// in SqlDataReader, which requires different server versions to handle NULLs differently.
// Empty string is expected for DBNull SqlValue (as per API), but SqlServer 2005 returns "Null" for it.
// See GetSqlValue code path in SqlDataReader for more details
if (!validateSucceeded && rdr.IsDBNull(column) && rdr.GetValue(column).ToString().Equals(""))
{
validateSucceeded = true;
}
Assert.True(validateSucceeded, string.Format("FAILED: SqlDataReader failed reader validation for column: {0}. Column literal value: {1}", column, rdr.GetSqlValue(column)));
}
}
}
| |
/* created on 15.09.2008 10:44:55 from peg generator V1.0*/
using Peg.Base;
using System;
using System.IO;
using System.Text;
namespace json
{
enum Ejson{json_text= 1, expect_file_end= 2, top_element= 3, @object= 4,
members= 5, pair= 6, array= 7, elements= 8, value= 9, @string= 10,
@char= 11, escape= 12, number= 13, @int= 14, frac= 15, exp= 16,
control_chars= 17, unicode_char= 18, S= 19};
class json : PegCharParser
{
#region Input Properties
public static EncodingClass encodingClass = EncodingClass.unicode;
public static UnicodeDetection unicodeDetection = UnicodeDetection.FirstCharIsAscii;
#endregion Input Properties
#region Constructors
public json()
: base()
{
}
public json(string src,TextWriter FerrOut)
: base(src,FerrOut)
{
}
#endregion Constructors
#region Overrides
public override string GetRuleNameFromId(int id)
{
try
{
Ejson ruleEnum = (Ejson)id;
string s= ruleEnum.ToString();
int val;
if( int.TryParse(s,out val) ){
return base.GetRuleNameFromId(id);
}else{
return s;
}
}
catch (Exception)
{
return base.GetRuleNameFromId(id);
}
}
public override void GetProperties(out EncodingClass encoding, out UnicodeDetection detection)
{
encoding = encodingClass;
detection = unicodeDetection;
}
#endregion Overrides
#region Grammar Rules
public bool json_text() /*[1]json_text: S top_element expect_file_end ;*/
{
return And(()=> S() && top_element() && expect_file_end() );
}
public bool expect_file_end() /*[2]expect_file_end: !./ WARNING<"non-json stuff before end of file">;*/
{
return
Not(()=> Any() )
|| Warning("non-json stuff before end of file");
}
public bool top_element() /*[3]top_element: object / array /
FATAL<"json file must start with '{' or '['"> ;*/
{
return
@object()
|| array()
|| Fatal("json file must start with '{' or '['");
}
public bool @object() /*[4]object: '{' S (&'}'/members) @'}' S ;*/
{
return And(()=>
Char('{')
&& S()
&& ( Peek(()=> Char('}') ) || members())
&& ( Char('}') || Fatal("<<'}'>> expected"))
&& S() );
}
public bool members() /*[5]members: pair S (',' S pair S)* ;*/
{
return And(()=>
pair()
&& S()
&& OptRepeat(()=>
And(()=> Char(',') && S() && pair() && S() ) ) );
}
public bool pair() /*[6]pair: @string S @':' S value ;*/
{
return And(()=>
( @string() || Fatal("<<string>> expected"))
&& S()
&& ( Char(':') || Fatal("<<':'>> expected"))
&& S()
&& value() );
}
public bool array() /*[7]array: '[' S (&']'/elements) @']' S ;*/
{
return And(()=>
Char('[')
&& S()
&& ( Peek(()=> Char(']') ) || elements())
&& ( Char(']') || Fatal("<<']'>> expected"))
&& S() );
}
public bool elements() /*[8]elements: value S (','S value S)* ;*/
{
return And(()=>
value()
&& S()
&& OptRepeat(()=>
And(()=> Char(',') && S() && value() && S() ) ) );
}
public bool value() /*[9]value: @(string / number / object /
array / 'true' / 'false' / 'null') ;*/
{
return
(
@string()
|| number()
|| @object()
|| array()
|| Char('t','r','u','e')
|| Char('f','a','l','s','e')
|| Char('n','u','l','l'))
|| Fatal("<<(string or number or object or array or 'true' or 'false' or 'null')>> expected");
}
public bool @string() /*[10]string: '"' char* @'"' ;*/
{
return And(()=>
Char('"')
&& OptRepeat(()=> @char() )
&& ( Char('"') || Fatal("<<'\"'>> expected")) );
}
public bool @char() /*[11]char: escape / !(["\\]/control_chars)unicode_char ;*/
{
return
escape()
|| And(()=>
Not(()=> OneOf("\"\\") || control_chars() )
&& unicode_char() );
}
public bool escape() /*[12]escape: '\\' ( ["\\/bfnrt] /
'u' ([0-9A-Fa-f]{4}/FATAL<"4 hex digits expected">)/
FATAL<"illegal escape">);*/
{
return And(()=>
Char('\\')
&& (
OneOf(optimizedCharset0)
|| And(()=>
Char('u')
&& (
ForRepeat(4,4,()=> In('0','9', 'A','F', 'a','f') )
|| Fatal("4 hex digits expected")) )
|| Fatal("illegal escape")) );
}
public bool number() /*[13]number: '-'? int frac? exp? ;*/
{
return And(()=>
Option(()=> Char('-') )
&& @int()
&& Option(()=> frac() )
&& Option(()=> exp() ) );
}
public bool @int() /*[14]int: '0'/ [1-9][0-9]* ;*/
{
return
Char('0')
|| And(()=>
In('1','9')
&& OptRepeat(()=> In('0','9') ) );
}
public bool frac() /*[15]frac: '.' [0-9]+ ;*/
{
return And(()=> Char('.') && PlusRepeat(()=> In('0','9') ) );
}
public bool exp() /*[16]exp: [eE] [-+] [0-9]+ ;*/
{
return And(()=>
OneOf("eE")
&& OneOf("-+")
&& PlusRepeat(()=> In('0','9') ) );
}
public bool control_chars() /*[17]control_chars: [#x0-#x1F] ;*/
{
return In('\u0000','\u001f');
}
public bool unicode_char() /*[18]unicode_char: [#x0-#xFFFF] ;*/
{
return In('\u0000','\uffff');
}
public bool S() /*[19]S: [ \t\r\n]* ;*/
{
return OptRepeat(()=> OneOf(" \t\r\n") );
}
#endregion Grammar Rules
#region Optimization Data
internal static OptimizedCharset optimizedCharset0;
static json()
{
{
char[] oneOfChars = new char[] {'"','\\','/','b','f'
,'n','r','t'};
optimizedCharset0= new OptimizedCharset(null,oneOfChars);
}
}
#endregion Optimization Data
}
}
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// 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 Jim Heising 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.
//
///////////////////////////////////////////////////////////////////////////////////////////////
// Stephen Toub
// stoub@microsoft.com
// SecureClientChannelSink.cs
using System;
using System.IO;
using System.Threading;
using System.Collections;
using System.Security.Cryptography;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Messaging;
// PERFORMANCE NOTE:
// For ease of implementation, SecureClientChannelSink can take out some pretty big locks.
// Not a problem for demo purposes, but if this will be used as the basis for any kind of
// production level code, synchronization needs to reviewed and possibly greatly revamped.
namespace NET.Remoting.ChannelSinks
{
/// <summary>
/// Client channel sink that, in conjunction with SecureServerChannelSink, provides an
/// asymmetric key exchange and shared key encryption across a remoting channel.
/// </summary>
internal class SecureClientChannelSink :
BaseChannelSinkWithProperties, IClientChannelSink
{
#region Member Variables
/// <summary>The name of the symmetric algorithm to use.</summary>
private readonly string _algorithm;
/// <summary>Whether OAEP padding should be used.</summary>
private readonly bool _oaep;
/// <summary>The maximum number of times we should attempt to process the message.</summary>
private readonly int _maxAttempts;
/// <summary>Reference to the next sink in the sink chain.</summary>
private readonly IClientChannelSink _next;
/// <summary>The transaction ID to identify this client to the server.</summary>
private Guid _transactID = Guid.Empty;
/// <summary>
/// The symmetric algorithm provider to be used for all transactions from this client.
/// Note that all connections to objects from this client will use the same provider.
/// The server, on the other hand, will use a different provider (a different key) for
/// each connected client (though it, too, will use the same provider for all messages
/// from the same client, regardless of destination object).
/// </summary>
private volatile SymmetricAlgorithm _provider = null;
/// <summary>RSA provider used for encryption and decryption of shared key information.</summary>
private volatile RSACryptoServiceProvider _rsaProvider = null;
/// <summary>Used to take out a lock on transaction id and provider.</summary>
private readonly object _transactionLock = null;
/// <summary>Text for generic secure remoting exception.</summary>
private const string _defaultExceptionText = "The client sink is unable to maintain a secure channel with server.";
#endregion
#region Construction
/// <summary>Initialize the secure channel sink.</summary>
/// <param name="nextSink">The next sink in the chain.</param>
/// <param name="algorithm">The name of the symmetric algorithm to use for encryption.</param>
/// <param name="oaep">Whether OAEP padding should be used for asymmetric encryption.</param>
/// <param name="maxAttempts">The maximum number of times we should attempt to process the message.</param>
public SecureClientChannelSink(
IClientChannelSink nextSink,
string algorithm, bool oaep, int maxAttempts)
{
_algorithm = algorithm;
_oaep = oaep;
_next = nextSink;
_maxAttempts = maxAttempts;
_transactionLock = new object();
_rsaProvider = new RSACryptoServiceProvider();
}
#endregion
#region Synchronous Processing
/// <summary>Adds the headers for a shared-key request.</summary>
/// <param name="requestHeaders">Output headers for the request.</param>
private void CreateSharedKeyRequest(ITransportHeaders requestHeaders)
{
// Generate an RSA provider/key
string rsaKey = _rsaProvider.ToXmlString(false);
// Include client information and the public key
requestHeaders[CommonHeaders.Transaction] = ((int)SecureTransaction.SendingPublicKey).ToString();
requestHeaders[CommonHeaders.ID] = _transactID.ToString();
requestHeaders[CommonHeaders.PublicKey] = rsaKey;
}
/// <summary>Decrypts the incoming response given the response stream and headers.</summary>
/// <param name="responseStream">The response stream containing the response information.</param>
/// <param name="responseHeaders">The response headers containing the response header information.</param>
/// <returns>The decrypted stream if possible; null, otherwise.</returns>
private Stream DecryptResponse(Stream responseStream, ITransportHeaders responseHeaders)
{
try
{
// Check to make sure that the server is sending back to us the encrypted results.
// If it is, grab the results and return the decrypted stream. Otherwise, return a null stream.
if (responseHeaders != null &&
SecureTransaction.SendingEncryptedResult ==
(SecureTransaction)Convert.ToInt32((string)responseHeaders[CommonHeaders.Transaction]))
{
Stream decryptedStream = CryptoHelper.GetDecryptedStream(responseStream, _provider);
responseStream.Close(); // close the old stream as we won't be using it anymore
return decryptedStream;
}
}
catch{}
return null;
}
/// <summary>Processes response transport headers for a shared-key request.</summary>
/// <param name="responseHeaders">The headers from a shared-key request.</param>
/// <returns>A SymmetricAlgorithm with the key information sent from the server.</returns>
private SymmetricAlgorithm ProcessSharedKeyResponse(ITransportHeaders responseHeaders)
{
// Grab the returned shared key and IV (encrypted with our public key)
string encryptedKey = (string)responseHeaders[CommonHeaders.SharedKey];
string encryptedIV = (string)responseHeaders[CommonHeaders.SharedIV];
if (encryptedKey == null || encryptedKey == string.Empty) throw new SecureRemotingException("Expected shared key from server.");
if (encryptedIV == null || encryptedIV == string.Empty) throw new SecureRemotingException("Expected shared IV from server.");
// Generate the encryption objects
SymmetricAlgorithm sharedProvider = CryptoHelper.GetNewSymmetricProvider(_algorithm);
sharedProvider.Key = _rsaProvider.Decrypt(Convert.FromBase64String(encryptedKey), _oaep);
sharedProvider.IV = _rsaProvider.Decrypt(Convert.FromBase64String(encryptedIV), _oaep);
return sharedProvider;
}
/// <summary>
/// Creates an RSA key pair. Sends a message to the server secure sink which includes
/// the public key from the pair along with a newly created GUID to identify this client
/// to the server. The server responds with an encrypted shared key which can be used for
/// further communications between this client and server.
/// </summary>
/// <param name="msg">The original message passed to the sink.</param>
/// <returns>Byte array containing shared key</returns>
private SymmetricAlgorithm ObtainSharedKey(IMessage msg)
{
// We create new headers and a new stream for this roundtrip to the server.
// We don't need to use any headers that may have already been added to the collection
// because we can reasonably assume that they are destined for the server side sink paired
// with the client sink that created them; we're stopping at our matching server side
// sink and as sink order is most-likely mirrored on the server, any existing headers won't be
// used anyway (unless our assumption is incorrect and they are actually destined
// for an unrelated sink, but if that's the case, oh well).
TransportHeaders requestHeaders = new TransportHeaders();
MemoryStream requestStream = new MemoryStream();
ITransportHeaders responseHeaders;
Stream responseStream;
// Create the headers and stream for a shared-key request
CreateSharedKeyRequest(requestHeaders);
// Send the message. We do this by sending the message along the sink chain
// as if this were the real message.
_next.ProcessMessage(msg, requestHeaders, requestStream, out responseHeaders, out responseStream);
// Processes the response headers and pulls from them a symmetric algorithm
return ProcessSharedKeyResponse(responseHeaders);
}
/// <summary>Clears out the shared key and connection information.</summary>
/// <remarks>Should always be called inside a lock on _transactionLock.</remarks>
private void ClearSharedKey()
{
_provider = null;
_transactID = Guid.Empty;
}
/// <summary>Sets up the stream and headers for the encrypted message</summary>
/// <param name="requestHeaders">The headers to be sent to the server containing connection information.</param>
/// <param name="requestStream">The stream to be encrypted.</param>
/// <returns>The encrypted stream to be sent to the server.</returns>
private Stream SetupEncryptedMessage(ITransportHeaders requestHeaders, Stream requestStream)
{
// Encrypt the message
requestStream = CryptoHelper.GetEncryptedStream(requestStream, _provider);
// Setup the header information. The server is semi-stateless in that it can serve
// multiple clients at the same time. As such, we need to tell it who we are and what
// we're doing.
requestHeaders[CommonHeaders.Transaction] = ((int)SecureTransaction.SendingEncryptedMessage).ToString();
requestHeaders[CommonHeaders.ID] = _transactID.ToString();
// Return the encrypted message in a stream
return requestStream;
}
/// <summary>
/// Given a request stream, encrypts the stream with the shared key and sends
/// the encrypted message to the server. The server responds with an encrypted response
/// stream which is decrypted. This response stream is handed back to the caller.
/// </summary>
/// <param name="msg">The original message passed to the sink.</param>
/// <param name="requestHeaders">The original request headers passed to the sink.</param>
/// <param name="requestStream">The original request stream passed to the sink.</param>
/// <param name="responseHeaders">Output response headers.</param>
/// <param name="responseStream">Output response stream.</param>
/// <returns>true if success; false, otherwise.</returns>
private bool ProcessEncryptedMessage(
IMessage msg, ITransportHeaders requestHeaders, Stream requestStream,
out ITransportHeaders responseHeaders, out Stream responseStream)
{
// Encrypt the message. We track the id of the transaction so that we know
// whether the key has changed between encryption and decryption. If it has,
// we have a problem and need to try again.
Guid id;
lock(_transactionLock)
{
id = EnsureIDAndProvider(msg, requestHeaders);
requestStream = SetupEncryptedMessage(requestHeaders, requestStream);
}
// Send the encrypted request to the server
_next.ProcessMessage(
msg, requestHeaders, requestStream,
out responseHeaders, out responseStream);
// Decrypt the response stream. If decryption fails, and if no one has changed the
// transaction key (meaning someone else already had a problem and tried to fix
// it by clearing it out), then we need to clear it out such that it will be
// updated the next time through.
lock(_transactionLock)
{
responseStream = DecryptResponse(responseStream, responseHeaders);
if (responseStream == null && id.Equals(_transactID)) ClearSharedKey();
}
// Return whether we were successful
return responseStream != null;
}
/// <summary>Ensures that we've obtained shared-key information and a transaction ID.</summary>
/// <param name="msg">The message to process.</param>
/// <param name="requestHeaders">The headers to send to the server.</param>
/// <returns>The transaction ID.</returns>
/// <remarks>
/// May require a synchronous roundtrip to the server.
/// Should always be called inside a lock on _transactionLock.
/// </remarks>
private Guid EnsureIDAndProvider(IMessage msg, ITransportHeaders requestHeaders)
{
// If there is no transaction guid, create one.
// If we haven't yet received a shared key, get one.
if (_provider == null || _transactID.Equals(Guid.Empty))
{
_transactID = Guid.NewGuid();
_provider = ObtainSharedKey(msg); // roundtrip to server sink
}
return _transactID;
}
/// <summary>Requests message processing from the current sink.</summary>
/// <param name="msg">The message to process.</param>
/// <param name="requestHeaders">The headers to send to the server.</param>
/// <param name="requestStream">The stream to process and send to the server.</param>
/// <param name="responseHeaders">Response headers from the server.</param>
/// <param name="responseStream">Response stream from the server.</param>
/// <exception cref="SecureRemotingException">Thrown if a connection cannot be maintained with the server.</exception>
public void ProcessMessage(
IMessage msg, ITransportHeaders requestHeaders, Stream requestStream,
out ITransportHeaders responseHeaders, out Stream responseStream)
{
try
{
// Store the initial position on the stream so that we can restore
// our position and try again if the transaction fails.
long initialStreamPos = requestStream.CanSeek ? requestStream.Position : -1;
// Try multiple times, up to the max specified in the web.config.
for(int i=0; i<_maxAttempts; i++)
{
// Process the encrypted message.
if (ProcessEncryptedMessage(
msg, requestHeaders, requestStream,
out responseHeaders, out responseStream)) return;
// We failed for some reason, but we can try again. If we can't reset the initial
// position of the stream, we'll just give up. We could of course buffer the whole
// input stream first and then use that through the process, but is it worth it? Nah.
if (requestStream.CanSeek) requestStream.Position = initialStreamPos;
else break;
}
// If we made it this far, we're in trouble, as this means that we were unable to successfully
// send and receive an encrypted message, most likely due to the server not being
// able to identify us.
throw new SecureRemotingException(_defaultExceptionText);
}
finally
{
// Close the initial request stream just in case it hasn't been.
// After all, we're not sending it to anyone.
requestStream.Close();
}
}
/// <summary>Returns the Stream onto which the provided message is to be serialized.</summary>
/// <param name="msg">The message being sent.</param>
/// <param name="headers">The headers being sent to the server.</param>
/// <returns>The stream onto which the provided message is to be serialized.</returns>
public Stream GetRequestStream(System.Runtime.Remoting.Messaging.IMessage msg, System.Runtime.Remoting.Channels.ITransportHeaders headers)
{
return null;
}
/// <summary>Returns the next channel sink in the sink chain.</summary>
public IClientChannelSink NextChannelSink
{
get { return _next; }
}
#endregion
#region Asynchronous Processing
/// <summary>Stores information on the current request; used in case an async request fails.</summary>
private class AsyncProcessingState
{
#region Member Variables
/// <summary>The input stream.</summary>
private Stream _stream;
/// <summary>The transport headers.</summary>
private ITransportHeaders _headers;
/// <summary>The remoted message.</summary>
private IMessage _msg;
/// <summary>Transaction ID when processing started.</summary>
private Guid _id;
#endregion
#region Construction
/// <summary>Initialize the state.</summary>
/// <param name="msg">The message to be stored.</param>
/// <param name="headers">The transport headers to be stored.</param>
/// <param name="stream">The stream to be stored (copies the stream).</param>
/// <param name="id">Transaction ID when processing started.</param>
public AsyncProcessingState(
IMessage msg, ITransportHeaders headers, ref Stream stream, Guid id)
{
_msg = msg;
_headers = headers;
_stream = DuplicateStream(ref stream);
_id = id;
}
#endregion
#region Properties
/// <summary>Gets the input stream.</summary>
public Stream Stream { get { return _stream; } }
/// <summary>Gets the transport headers.</summary>
public ITransportHeaders Headers { get { return _headers; } }
/// <summary>Gets the remoted message.</summary>
public IMessage Message { get { return _msg; } }
/// <summary>Gets the transaction id from when the transaction started.</summary>
public Guid ID { get { return _id; } }
#endregion
#region Methods
/// <summary>Duplicates the stream.</summary>
/// <param name="stream">The stream to be duplicated.</param>
/// <returns>A copy of the stream.</returns>
/// <remarks>
/// Since we can't guarantee that Position will work on the input stream, we need
/// to create a new stream and set the old reference to a copy of the new one.
/// </remarks>
private Stream DuplicateStream(ref Stream stream)
{
// TODO: Test if Position will work and use that instead if it will
// Create two new streams, one to act as the duplicate and one to replace
// the original.
MemoryStream memStream1 = new MemoryStream();
MemoryStream memStream2 = new MemoryStream();
// Copy the old stream to the new streams
byte [] buffer = new byte[1024];
int read;
while((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
memStream1.Write(buffer, 0, read);
memStream2.Write(buffer, 0, read);
}
stream.Close();
// Reset the new ones to be at the beginning
memStream1.Position = 0;
memStream2.Position = 0;
// Reset the original reference and return the duplicate
stream = memStream1;
return memStream2;
}
#endregion
}
/// <summary>Requests asynchronous processing of a method call on the current sink.</summary>
/// <param name="sinkStack">A stack of channel sinks.</param>
/// <param name="msg">The message to process.</param>
/// <param name="headers">The headers to send to the server.</param>
/// <param name="stream">The stream headed to the transport sink.</param>
public void AsyncProcessRequest(
IClientChannelSinkStack sinkStack, IMessage msg, ITransportHeaders headers, Stream stream)
{
AsyncProcessingState state = null;
Stream encryptedStream = null;
Guid id;
lock(_transactionLock) // could be a big lock... probably a faster way, but for now suffices
{
// Establish connection information with the server; the roundtrip will hopefully
// only be done once, so we ensure that we have the necessary information.
id = EnsureIDAndProvider(msg, headers);
// Protect ourselves a bit. If the asynchronous call fails because the server forgot about
// us, we'll be in a bit of a fix. We'll need the current arguments as we'll need
// to retry the request synchronously. Store them into a state object and use
// that as the state when pushing ourself onto the stack. That way, AsyncProcessResponse
// have access to it.
state = new AsyncProcessingState(msg, headers, ref stream, id);
// Send encrypted message by encrypting the stream
encryptedStream = SetupEncryptedMessage(headers, stream);
}
// Push ourselves onto the stack with the necessary state and forward on to the next sink
sinkStack.Push(this, state);
_next.AsyncProcessRequest(sinkStack, msg, headers, encryptedStream);
}
/// <summary>Requests asynchronous processing of a response to a method call on the current sink.</summary>
/// <param name="sinkStack">A stack of sinks that called this sink.</param>
/// <param name="state">Information generated on the request side that is associated with this sink.</param>
/// <param name="headers">The headers retrieved from the server response stream.</param>
/// <param name="stream">The stream coming back from the transport sink.</param>
public void AsyncProcessResponse(
IClientResponseChannelSinkStack sinkStack, object state, ITransportHeaders headers, Stream stream)
{
// Get the async state we put on the stack
AsyncProcessingState asyncState = (AsyncProcessingState)state;
try
{
// Decrypt the response if possible
SecureTransaction transactType = (SecureTransaction)Convert.ToInt32((string)headers[CommonHeaders.Transaction]);
switch(transactType)
{
// The only valid value; the server is sending results encrypted,
// so we need to decrypt them
case SecureTransaction.SendingEncryptedResult:
lock(_transactionLock)
{
if (asyncState.ID.Equals(_transactID)) stream = DecryptResponse(stream, headers);
else throw new SecureRemotingException("The key has changed since the message was decrypted.");
}
break;
// The server has no record of the client, so error out.
// If this were synchronous, we could try again, first renewing
// the connection information. The best we can do here is null
// out our current connection information so that the next time
// through we'll create a new provider and identifier.
case SecureTransaction.UnknownIdentifier:
throw new SecureRemotingException(
"The server sink was unable to identify the client, " +
"most likely due to the connection information timing out.");
// Something happened and the response is not encrypted, i.e. there
// are no transport headers, or at least no transaction header, or it has
// been explicitly set by the server to Uninitialized.
// Regardless, do nothing.
default:
case SecureTransaction.Uninitialized:
break;
}
}
catch(SecureRemotingException)
{
// We got back a secure remoting exceptionIt would be difficult to retry this as an
// asynchronous call as we need to have the output ready to go before
// we return. Thus, we'll make a synchronous one by calling ProcessMessage()
// just as if we were the previous sink. Luckily, we kept all of the
// necessary information sitting around.
lock(_transactionLock) // This is a big, big lock, as are many locks in this app! Oh well.
{
if (_provider == null || asyncState.ID.Equals(_transactID)) ClearSharedKey();
ProcessMessage(
asyncState.Message, asyncState.Headers, asyncState.Stream,
out headers, out stream);
}
}
finally
{
// Close the old stream just in case it hasn't been closed yet.
asyncState.Stream.Close();
}
// Process through the rest of the sinks.
sinkStack.AsyncProcessResponse(headers, stream);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using Rainbow.Framework;
using Rainbow.Framework.Content.Data;
using Rainbow.Framework.Content.Security;
using Rainbow.Framework.Helpers;
using Rainbow.Framework.Settings;
using Rainbow.Framework.Web.UI.WebControls;
using History=Rainbow.Framework.History;
using ImageButton=Rainbow.Framework.Web.UI.WebControls.ImageButton;
using Label=Rainbow.Framework.Web.UI.WebControls.Label;
namespace Rainbow.Content.Web.Modules
{
[History("jminond", "2006/2/23", "Converted to partial class")]
public partial class Discussion : PortalModuleControl
{
//protected System.Web.UI.WebControls.DataList TopLevelList;
//protected System.Web.UI.WebControls.DataList DetailList;
/// <summary>
/// Searchable module
/// </summary>
/// <value></value>
public override bool Searchable
{
get { return true; }
}
/// <summary>
/// On the first invocation of Page_Load, the data is bound using BindList();
/// </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_Load(object sender, EventArgs e)
{
/*if (Page.IsPostBack == false)
{
BindList();
}*/
BindList();
}
/// <summary>
/// The BindList method obtains the list of top-level messages
/// from the Discussion table and then databinds them against
/// the "TopLevelList" asp:datalist server control. It uses
/// the Rainbow.DiscussionDB() data component to encapsulate
/// all data access functionality.
/// </summary>
private void BindList()
{
// Obtain a list of discussion messages for the module and bind to datalist
DiscussionDB discuss = new DiscussionDB();
TopLevelList.DataSource = discuss.GetTopLevelMessages(ModuleID);
TopLevelList.DataBind();
}
/// <summary>
/// The GetThreadMessages method is used to obtain the list
/// of messages contained within a sub-topic of the
/// a top-level discussion message thread. This method is
/// used to populate the "DetailList" asp:datalist server control
/// in the SelectedItemTemplate of "TopLevelList".
/// </summary>
/// <returns>returns a SqlDataReader object</returns>
protected SqlDataReader GetThreadMessages()
{
DiscussionDB discuss = new DiscussionDB();
int itemID = Int32.Parse(TopLevelList.DataKeys[TopLevelList.SelectedIndex].ToString());
SqlDataReader dr = discuss.GetThreadMessages(itemID, 'N');
return dr;
}
/// <summary>
/// The TopLevelList_Select server event handler is used to
/// expand/collapse a selected discussion topic and delte individual items
/// </summary>
/// <param name="Sender">The source of the event.</param>
/// <param name="e">DataListCommandEventAargs e</param>
public void TopLevelListOrDetailList_Select(object Sender, DataListCommandEventArgs e)
{
// Determine the command of the button
string command = ((CommandEventArgs) (e)).CommandName;
// Update asp:datalist selection index depending upon the type of command
// and then rebind the asp:datalist with content
switch (command)
{
case "CollapseThread":
{
TopLevelList.SelectedIndex = -1; // nothing is selected
break;
}
case "ExpandThread":
{
TopLevelList.SelectedIndex = e.Item.ItemIndex;
DiscussionDB discuss = new DiscussionDB();
int ItemID = Int32.Parse(e.CommandArgument.ToString());
discuss.IncrementViewCount(ItemID);
break;
}
case "ShowThreadNewWindow": // open up the entire thread in a new window
{
TopLevelList.SelectedIndex = e.Item.ItemIndex;
DiscussionDB discuss = new DiscussionDB();
int ItemID = Int32.Parse(e.CommandArgument.ToString());
discuss.IncrementViewCount(ItemID);
Response.Redirect(FormatUrlShowThread(ItemID));
break;
}
/*
case "SelectTitle":
TopLevelList.SelectedIndex = e.Item.ItemIndex;
Response.Redirect(FormatUrlShowThread((int)DataBinder.Eval(Container.DataItem, "ItemID")));
break;
*/
case "delete": // the "delete" command can come from the TopLevelList or the DetailList
{
DiscussionDB discuss = new DiscussionDB();
int ItemID = Int32.Parse(e.CommandArgument.ToString());
discuss.DeleteChildren(ItemID);
// DetailList.DataBind(); // synchronize the control and database after deletion
break;
}
default:
break;
}
BindList();
}
// set up a client-side javascript dialog to confirm deletions
// the 'confirm' dialog is called when onClick is triggered
// if the dialog returns false the server never gets the delete request
/// <summary>
/// Called when [item data bound].
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="T:System.Web.UI.WebControls.DataListItemEventArgs"/> instance containing the event data.</param>
protected void OnItemDataBound(object sender, DataListItemEventArgs e)
{
// 13/7/2004 Added Localization Mario Endara mario@softworks.com.uy
if (e.Item.FindControl("deleteBtn") != null)
{
((ImageButton) e.Item.FindControl("deleteBtn")).Attributes.Add("onClick", "return confirm('" +
General.GetString(
"DISCUSSION_DELETE_RESPONSE",
"Are you sure you want to delete the selected response message and ALL of its children ?") +
"');");
}
if (e.Item.FindControl("deleteBtnExpanded") != null)
{
((ImageButton) e.Item.FindControl("deleteBtnExpanded")).Attributes.Add("onClick", "return confirm('" +
General.GetString(
"DISCUSSION_DELETE_RESPONSE",
"Are you sure you want to delete the selected response message and ALL of its children ?") +
"');");
}
// 15/7/2004 added localization by Mario Endara mario@softworks.com.uy
if (e.Item.FindControl("Label4") != null)
{
if (((Label) e.Item.FindControl("Label4")).Text == "unknown")
{
((Label) e.Item.FindControl("Label4")).Text = General.GetString("UNKNOWN", "unknown");
}
}
if (e.Item.FindControl("Label10") != null)
{
if (((Label) e.Item.FindControl("Label10")).Text == "unknown")
{
((Label) e.Item.FindControl("Label10")).Text = General.GetString("UNKNOWN", "unknown");
}
}
if (e.Item.FindControl("Label6") != null)
{
((Label) e.Item.FindControl("Label6")).ToolTip =
General.GetString("DISCUSSION_REPLYS", "Number of replys to this topic");
}
if (e.Item.FindControl("Label5") != null)
{
((Label) e.Item.FindControl("Label5")).ToolTip =
General.GetString("DISCUSSION_VIEWED", "Number of times this topic has been viewed");
}
if (e.Item.FindControl("Label1") != null)
{
((Label) e.Item.FindControl("Label1")).ToolTip =
General.GetString("DISCUSSION_REPLYS", "Number of replys to this topic");
}
if (e.Item.FindControl("Label2") != null)
{
((Label) e.Item.FindControl("Label2")).ToolTip =
General.GetString("DISCUSSION_VIEWED", "Number of times this topic has been viewed");
}
if (e.Item.FindControl("btnCollapse") != null)
{
((ImageButton) e.Item.FindControl("btnCollapse")).ToolTip =
General.GetString("DISCUSSION_MSGCOLLAPSE", "Collapse the thread of this topic");
}
if (e.Item.FindControl("btnSelect") != null)
{
((ImageButton) e.Item.FindControl("btnSelect")).ToolTip =
General.GetString("DISCUSSION_MSGEXPAND", "Expand the thread of this topic inside this browser page");
}
if (e.Item.FindControl("btnNewWindow") != null)
{
((ImageButton) e.Item.FindControl("btnNewWindow")).ToolTip =
General.GetString("DISCUSSION_MSGSELECT", "Open the thread of this topic in a new browser page");
}
}
/// <summary>
/// Gets the reply image.
/// </summary>
/// <returns></returns>
protected string GetReplyImage()
{
if (DiscussionPermissions.HasAddPermissions(ModuleID) == true)
return getLocalImage("reply.gif");
else
return getLocalImage("1x1.gif");
}
/// <summary>
/// Gets the edit image.
/// </summary>
/// <param name="itemUserEmail">The item user email.</param>
/// <returns></returns>
protected string GetEditImage(string itemUserEmail)
{
if (DiscussionPermissions.HasEditPermissions(ModuleID, itemUserEmail))
return getLocalImage("edit.gif");
else
return getLocalImage("1x1.gif");
}
/// <summary>
/// Gets the delete image.
/// </summary>
/// <param name="itemID">The item ID.</param>
/// <param name="itemUserEmail">The item user email.</param>
/// <returns></returns>
protected string GetDeleteImage(int itemID, string itemUserEmail)
{
if (DiscussionPermissions.HasDeletePermissions(ModuleID, itemID, itemUserEmail) == true)
return getLocalImage("delete.gif");
else
return getLocalImage("1x1.gif");
}
/// <summary>
/// The FormatUrl method is a helper messages called by a
/// databinding statement within the <asp:DataList> server
/// control template. It is defined as a helper method here
/// (as opposed to inline within the template) to improve
/// code organization and avoid embedding logic within the
/// content template.
/// </summary>
/// <param name="itemID">ID of the currently selected topic</param>
/// <param name="mode">The mode.</param>
/// <returns>
/// Returns a properly formatted URL to call the DiscussionEdit page
/// </returns>
protected string FormatUrlEditItem(int itemID, string mode)
{
return
(HttpUrlBuilder.BuildUrl("~/DesktopModules/CommunityModules/Discussion/DiscussionEdit.aspx",
"ItemID=" + itemID + "&Mode=" + mode + "&mID=" + ModuleID + "&edit=1"));
}
/// <summary>
/// Formats the URL show thread.
/// </summary>
/// <param name="itemID">The item ID.</param>
/// <returns></returns>
protected string FormatUrlShowThread(int itemID)
{
return
(HttpUrlBuilder.BuildUrl("~/DesktopModules/CommunityModules/Discussion/DiscussionViewThread.aspx",
"ItemID=" + itemID + "&mID=" + ModuleID));
}
/// <summary>
/// The NodeImage method is a helper method called by a
/// databinding statement within the <asp:datalist> server
/// control template. It controls whether or not an item
/// in the list should be rendered as an expandable topic
/// or just as a single node within the list.
/// </summary>
/// <param name="count">Number of replys to the selected topic</param>
/// <returns></returns>
protected string NodeImage(int count)
{
return getLocalImage("plus.gif");
}
protected string getLocalImage(string img)
{
return Path.WebPathCombine(Path.ApplicationRoot, "DesktopModules/Discussion/images", img);
}
/// <summary>
/// GUID of module (mandatory)
/// </summary>
/// <value></value>
public override Guid GuidID
{
get { return new Guid("{2D86166C-4BDC-4A6F-A028-D17C2BB177C8}"); }
}
/// <summary>
/// Searchable module implementation
/// </summary>
/// <param name="portalID">The portal ID</param>
/// <param name="userID">ID of the user is searching</param>
/// <param name="searchString">The text to search</param>
/// <param name="searchField">The fields where perfoming the search</param>
/// <returns>The SELECT sql to perform a search on the current module</returns>
public override string SearchSqlSelect(int portalID, int userID, string searchString, string searchField)
{
SearchDefinition s =
new SearchDefinition("rb_Discussion", "Title", "Body", "CreatedByUser", "CreatedDate", searchField);
return s.SearchSqlSelect(portalID, userID, searchString);
}
#region Web Form Designer generated code
/// <summary>
/// Raises Init event
/// </summary>
/// <param name="e"></param>
protected override void OnInit(EventArgs e)
{
this.TopLevelList.ItemCommand +=
new System.Web.UI.WebControls.DataListCommandEventHandler(this.TopLevelListOrDetailList_Select);
// this.DetailList.ItemCommand += new System.Web.UI.WebControls.DataListCommandEventHandler(this.TopLevelListOrDetailList_Select);
this.Load += new System.EventHandler(this.Page_Load);
// Create a new Title the control
// ModuleTitle = new DesktopModuleTitle();
// Add a link for the edit page
// ModuleTitle.AddTarget = "_new"; // uncomment this if you want replies and new posts in a new web browser window
this.AddText = "DS_NEWTHREAD";
this.AddUrl = "~/DesktopModules/CommunityModules/Discussion/DiscussionEdit.aspx";
// Add title at the very beginning of the control's controls collection
// Controls.AddAt(0, ModuleTitle);
base.OnInit(e);
}
#endregion
# region Install / Uninstall Implementation
/// <summary>
/// Unknown
/// </summary>
/// <param name="stateSaver"></param>
public override void Install(System.Collections.IDictionary stateSaver)
{
string currentScriptName = System.IO.Path.Combine(Server.MapPath(TemplateSourceDirectory), "install.sql");
ArrayList errors = Rainbow.Framework.Data.DBHelper.ExecuteScript(currentScriptName, true);
if (errors.Count > 0)
{
// Call rollback
throw new Exception("Error occurred:" + errors[0].ToString());
}
}
/// <summary>
/// Unknown
/// </summary>
/// <param name="stateSaver"></param>
public override void Uninstall(System.Collections.IDictionary stateSaver)
{
string currentScriptName = System.IO.Path.Combine(Server.MapPath(TemplateSourceDirectory), "uninstall.sql");
ArrayList errors = Rainbow.Framework.Data.DBHelper.ExecuteScript(currentScriptName, true);
if (errors.Count > 0)
{
// Call rollback
throw new Exception("Error occurred:" + errors[0].ToString());
}
}
# endregion
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gagr = Google.Api.Gax.ResourceNames;
using gckv = Google.Cloud.Kms.V1;
namespace Google.Cloud.Kms.V1
{
public partial class ListKeyRingsRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class ListCryptoKeysRequest
{
/// <summary>
/// <see cref="KeyRingName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public KeyRingName ParentAsKeyRingName
{
get => string.IsNullOrEmpty(Parent) ? null : KeyRingName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class ListCryptoKeyVersionsRequest
{
/// <summary>
/// <see cref="CryptoKeyName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public CryptoKeyName ParentAsCryptoKeyName
{
get => string.IsNullOrEmpty(Parent) ? null : CryptoKeyName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class ListImportJobsRequest
{
/// <summary>
/// <see cref="KeyRingName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public KeyRingName ParentAsKeyRingName
{
get => string.IsNullOrEmpty(Parent) ? null : KeyRingName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetKeyRingRequest
{
/// <summary>
/// <see cref="gckv::KeyRingName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gckv::KeyRingName KeyRingName
{
get => string.IsNullOrEmpty(Name) ? null : gckv::KeyRingName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetCryptoKeyRequest
{
/// <summary>
/// <see cref="gckv::CryptoKeyName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gckv::CryptoKeyName CryptoKeyName
{
get => string.IsNullOrEmpty(Name) ? null : gckv::CryptoKeyName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetCryptoKeyVersionRequest
{
/// <summary>
/// <see cref="gckv::CryptoKeyVersionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gckv::CryptoKeyVersionName CryptoKeyVersionName
{
get => string.IsNullOrEmpty(Name) ? null : gckv::CryptoKeyVersionName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetPublicKeyRequest
{
/// <summary>
/// <see cref="gckv::CryptoKeyVersionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gckv::CryptoKeyVersionName CryptoKeyVersionName
{
get => string.IsNullOrEmpty(Name) ? null : gckv::CryptoKeyVersionName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetImportJobRequest
{
/// <summary>
/// <see cref="gckv::ImportJobName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gckv::ImportJobName ImportJobName
{
get => string.IsNullOrEmpty(Name) ? null : gckv::ImportJobName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateKeyRingRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class CreateCryptoKeyRequest
{
/// <summary>
/// <see cref="KeyRingName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public KeyRingName ParentAsKeyRingName
{
get => string.IsNullOrEmpty(Parent) ? null : KeyRingName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class CreateCryptoKeyVersionRequest
{
/// <summary>
/// <see cref="CryptoKeyName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public CryptoKeyName ParentAsCryptoKeyName
{
get => string.IsNullOrEmpty(Parent) ? null : CryptoKeyName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class ImportCryptoKeyVersionRequest
{
/// <summary>
/// <see cref="CryptoKeyName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public CryptoKeyName ParentAsCryptoKeyName
{
get => string.IsNullOrEmpty(Parent) ? null : CryptoKeyName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CryptoKeyVersionName"/>-typed view over the <see cref="CryptoKeyVersion"/> resource name
/// property.
/// </summary>
public CryptoKeyVersionName CryptoKeyVersionAsCryptoKeyVersionName
{
get => string.IsNullOrEmpty(CryptoKeyVersion) ? null : CryptoKeyVersionName.Parse(CryptoKeyVersion, allowUnparsed: true);
set => CryptoKeyVersion = value?.ToString() ?? "";
}
}
public partial class CreateImportJobRequest
{
/// <summary>
/// <see cref="KeyRingName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public KeyRingName ParentAsKeyRingName
{
get => string.IsNullOrEmpty(Parent) ? null : KeyRingName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class UpdateCryptoKeyPrimaryVersionRequest
{
/// <summary>
/// <see cref="gckv::CryptoKeyName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gckv::CryptoKeyName CryptoKeyName
{
get => string.IsNullOrEmpty(Name) ? null : gckv::CryptoKeyName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class DestroyCryptoKeyVersionRequest
{
/// <summary>
/// <see cref="gckv::CryptoKeyVersionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gckv::CryptoKeyVersionName CryptoKeyVersionName
{
get => string.IsNullOrEmpty(Name) ? null : gckv::CryptoKeyVersionName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class RestoreCryptoKeyVersionRequest
{
/// <summary>
/// <see cref="gckv::CryptoKeyVersionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gckv::CryptoKeyVersionName CryptoKeyVersionName
{
get => string.IsNullOrEmpty(Name) ? null : gckv::CryptoKeyVersionName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class EncryptRequest
{
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gax::IResourceName ResourceName
{
get => string.IsNullOrEmpty(Name) ? null : gax::UnparsedResourceName.Parse(Name);
set => Name = value?.ToString() ?? "";
}
}
public partial class DecryptRequest
{
/// <summary>
/// <see cref="gckv::CryptoKeyName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gckv::CryptoKeyName CryptoKeyName
{
get => string.IsNullOrEmpty(Name) ? null : gckv::CryptoKeyName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class AsymmetricSignRequest
{
/// <summary>
/// <see cref="gckv::CryptoKeyVersionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gckv::CryptoKeyVersionName CryptoKeyVersionName
{
get => string.IsNullOrEmpty(Name) ? null : gckv::CryptoKeyVersionName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class AsymmetricDecryptRequest
{
/// <summary>
/// <see cref="gckv::CryptoKeyVersionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gckv::CryptoKeyVersionName CryptoKeyVersionName
{
get => string.IsNullOrEmpty(Name) ? null : gckv::CryptoKeyVersionName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class MacSignRequest
{
/// <summary>
/// <see cref="gckv::CryptoKeyVersionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gckv::CryptoKeyVersionName CryptoKeyVersionName
{
get => string.IsNullOrEmpty(Name) ? null : gckv::CryptoKeyVersionName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class MacVerifyRequest
{
/// <summary>
/// <see cref="gckv::CryptoKeyVersionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gckv::CryptoKeyVersionName CryptoKeyVersionName
{
get => string.IsNullOrEmpty(Name) ? null : gckv::CryptoKeyVersionName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Security;
using Xunit;
using Microsoft.DotNet.RemoteExecutor;
using Microsoft.DotNet.XUnitExtensions;
namespace System.Diagnostics.Tests
{
public partial class ProcessTests : ProcessTestBase
{
[Fact]
private void TestWindowApisUnix()
{
// This tests the hardcoded implementations of these APIs on Unix.
using (Process p = Process.GetCurrentProcess())
{
Assert.True(p.Responding);
Assert.Equal(string.Empty, p.MainWindowTitle);
Assert.False(p.CloseMainWindow());
Assert.Throws<InvalidOperationException>(()=>p.WaitForInputIdle());
}
}
[Fact]
public void MainWindowHandle_GetUnix_ThrowsPlatformNotSupportedException()
{
CreateDefaultProcess();
Assert.Equal(IntPtr.Zero, _process.MainWindowHandle);
}
[Fact]
public void TestProcessOnRemoteMachineUnix()
{
Process currentProcess = Process.GetCurrentProcess();
Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessesByName(currentProcess.ProcessName, "127.0.0.1"));
Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessById(currentProcess.Id, "127.0.0.1"));
}
[Theory]
[MemberData(nameof(MachineName_Remote_TestData))]
public void GetProcessesByName_RemoteMachineNameUnix_ThrowsPlatformNotSupportedException(string machineName)
{
Process currentProcess = Process.GetCurrentProcess();
Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessesByName(currentProcess.ProcessName, machineName));
}
[Fact]
public void TestRootGetProcessById()
{
Process p = Process.GetProcessById(1);
Assert.Equal(1, p.Id);
}
[Fact]
[PlatformSpecific(TestPlatforms.Linux)]
public void ProcessStart_UseShellExecute_OnLinux_ThrowsIfNoProgramInstalled()
{
if (!s_allowedProgramsToRun.Any(program => IsProgramInstalled(program)))
{
Console.WriteLine($"None of the following programs were installed on this machine: {string.Join(",", s_allowedProgramsToRun)}.");
Assert.Throws<Win32Exception>(() => Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = Environment.CurrentDirectory }));
}
}
[Fact]
[OuterLoop("Opens program")]
public void ProcessStart_DirectoryNameInCurDirectorySameAsFileNameInExecDirectory_Success()
{
string fileToOpen = "dotnet";
string curDir = Environment.CurrentDirectory;
string dotnetFolder = Path.Combine(Path.GetTempPath(),"dotnet");
bool shouldDelete = !Directory.Exists(dotnetFolder);
try
{
Directory.SetCurrentDirectory(Path.GetTempPath());
Directory.CreateDirectory(dotnetFolder);
using (var px = Process.Start(fileToOpen))
{
Assert.NotNull(px);
}
}
finally
{
if (shouldDelete)
{
Directory.Delete(dotnetFolder);
}
Directory.SetCurrentDirectory(curDir);
}
}
[Fact]
[OuterLoop]
public void ProcessStart_UseShellExecute_OnUnix_OpenMissingFile_DoesNotThrow()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) &&
s_allowedProgramsToRun.FirstOrDefault(program => IsProgramInstalled(program)) == null)
{
return;
}
string fileToOpen = Path.Combine(Environment.CurrentDirectory, "_no_such_file.TXT");
using (var px = Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = fileToOpen }))
{
Assert.NotNull(px);
px.Kill();
px.WaitForExit();
Assert.True(px.HasExited);
}
}
[Theory, InlineData(true), InlineData(false)]
[OuterLoop("Opens program")]
public void ProcessStart_UseShellExecute_OnUnix_SuccessWhenProgramInstalled(bool isFolder)
{
string programToOpen = s_allowedProgramsToRun.FirstOrDefault(program => IsProgramInstalled(program));
string fileToOpen;
if (isFolder)
{
fileToOpen = Environment.CurrentDirectory;
}
else
{
fileToOpen = GetTestFilePath() + ".txt";
File.WriteAllText(fileToOpen, $"{nameof(ProcessStart_UseShellExecute_OnUnix_SuccessWhenProgramInstalled)}");
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || programToOpen != null)
{
using (var px = Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = fileToOpen }))
{
Assert.NotNull(px);
if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) // on OSX, process name is dotnet for some reason. Refer to #23972
{
Assert.Equal(programToOpen, px.ProcessName);
}
px.Kill();
px.WaitForExit();
Assert.True(px.HasExited);
}
}
}
// Active issue https://github.com/dotnet/corefx/issues/37739
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotRedHatFamily6))]
[PlatformSpecific(~TestPlatforms.OSX)] // On OSX, ProcessName returns the script interpreter.
public void ProcessNameMatchesScriptName()
{
string scriptName = GetTestFileName();
string filename = Path.Combine(TestDirectory, scriptName);
File.WriteAllText(filename, $"#!/bin/sh\nsleep 600\n"); // sleep 10 min.
// set x-bit
int mode = Convert.ToInt32("744", 8);
Assert.Equal(0, chmod(filename, mode));
using (var process = Process.Start(new ProcessStartInfo { FileName = filename }))
{
try
{
string stat = File.ReadAllText($"/proc/{process.Id}/stat");
Assert.Contains($"({scriptName.Substring(0, 15)})", stat);
string cmdline = File.ReadAllText($"/proc/{process.Id}/cmdline");
Assert.Equal($"/bin/sh\0{filename}\0", cmdline);
Assert.Equal(scriptName, process.ProcessName);
}
finally
{
process.Kill();
process.WaitForExit();
}
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Linux)] // s_allowedProgramsToRun is Linux specific
public void ProcessStart_UseShellExecute_OnUnix_FallsBackWhenNotRealExecutable()
{
// Create a script that we'll use to 'open' the file by putting it on PATH
// with the appropriate name.
string path = Path.Combine(TestDirectory, "Path");
Directory.CreateDirectory(path);
WriteScriptFile(path, s_allowedProgramsToRun[0], returnValue: 42);
// Create a file that has the x-bit set, but which isn't a valid script.
string filename = WriteScriptFile(TestDirectory, GetTestFileName(), returnValue: 0);
File.WriteAllText(filename, $"not a script");
int mode = Convert.ToInt32("744", 8);
Assert.Equal(0, chmod(filename, mode));
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.StartInfo.EnvironmentVariables["PATH"] = path;
RemoteExecutor.Invoke(fileToOpen =>
{
using (var px = Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = fileToOpen }))
{
Assert.NotNull(px);
px.WaitForExit();
Assert.True(px.HasExited);
Assert.Equal(42, px.ExitCode);
}
}, filename, options).Dispose();
}
[Fact]
[PlatformSpecific(TestPlatforms.Linux)] // test relies on xdg-open
public void ProcessStart_UseShellExecute_OnUnix_DocumentFile_IgnoresArguments()
{
Assert.Equal(s_allowedProgramsToRun[0], "xdg-open");
if (!IsProgramInstalled("xdg-open"))
{
return;
}
// Open a file that doesn't exist with an argument that xdg-open considers invalid.
using (var px = Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = "/nosuchfile", Arguments = "invalid_arg" }))
{
Assert.NotNull(px);
px.WaitForExit();
// xdg-open returns different failure exit codes, 1 indicates an error in command line syntax.
Assert.NotEqual(0, px.ExitCode); // the command failed
Assert.NotEqual(1, px.ExitCode); // the failure is not due to the invalid argument
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Linux)]
public void ProcessStart_UseShellExecute_OnUnix_Executable_PassesArguments()
{
string testFilePath = GetTestFilePath();
Assert.False(File.Exists(testFilePath));
// Start a process that will create a file pass the filename as Arguments.
using (var px = Process.Start(new ProcessStartInfo { UseShellExecute = true,
FileName = "touch",
Arguments = testFilePath }))
{
Assert.NotNull(px);
px.WaitForExit();
Assert.Equal(0, px.ExitCode);
}
Assert.True(File.Exists(testFilePath));
}
[Theory]
[InlineData((string)null, true)]
[InlineData("", true)]
[InlineData("open", true)]
[InlineData("Open", true)]
[InlineData("invalid", false)]
[PlatformSpecific(TestPlatforms.Linux)] // s_allowedProgramsToRun is Linux specific
public void ProcessStart_UseShellExecute_OnUnix_ValidVerbs(string verb, bool isValid)
{
// Create a script that we'll use to 'open' the file by putting it on PATH
// with the appropriate name.
string path = Path.Combine(TestDirectory, "Path");
Directory.CreateDirectory(path);
WriteScriptFile(path, s_allowedProgramsToRun[0], returnValue: 42);
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.StartInfo.EnvironmentVariables["PATH"] = path;
RemoteExecutor.Invoke((argVerb, argValid) =>
{
if (argVerb == "<null>")
{
argVerb = null;
}
var psi = new ProcessStartInfo { UseShellExecute = true, FileName = "/", Verb = argVerb };
if (bool.Parse(argValid))
{
using (var px = Process.Start(psi))
{
Assert.NotNull(px);
px.WaitForExit();
Assert.True(px.HasExited);
Assert.Equal(42, px.ExitCode);
}
}
else
{
Assert.Throws<Win32Exception>(() => Process.Start(psi));
}
}, verb ?? "<null>", isValid.ToString(), options).Dispose();
}
[Fact]
[PlatformSpecific(TestPlatforms.Linux)]
public void ProcessStart_OnLinux_UsesSpecifiedProgram()
{
const string Program = "sleep";
using (var px = Process.Start(Program, "60"))
{
try
{
Assert.Equal(Program, px.ProcessName);
}
finally
{
px.Kill();
px.WaitForExit();
}
Assert.True(px.HasExited);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Linux)]
public void ProcessStart_OnLinux_UsesSpecifiedProgramUsingArgumentList()
{
const string Program = "sleep";
ProcessStartInfo psi = new ProcessStartInfo(Program);
psi.ArgumentList.Add("60");
using (var px = Process.Start(psi))
{
try
{
Assert.Equal(Program, px.ProcessName);
}
finally
{
px.Kill();
px.WaitForExit();
}
Assert.True(px.HasExited);
}
}
[Theory, InlineData("/usr/bin/open"), InlineData("/usr/bin/nano")]
[PlatformSpecific(TestPlatforms.OSX)]
[OuterLoop("Opens program")]
public void ProcessStart_OpenFileOnOsx_UsesSpecifiedProgram(string programToOpenWith)
{
string fileToOpen = GetTestFilePath() + ".txt";
File.WriteAllText(fileToOpen, $"{nameof(ProcessStart_OpenFileOnOsx_UsesSpecifiedProgram)}");
using (var px = Process.Start(programToOpenWith, fileToOpen))
{
// Assert.Equal(programToOpenWith, px.ProcessName); // on OSX, process name is dotnet for some reason. Refer to #23972
Console.WriteLine($"in OSX, {nameof(programToOpenWith)} is {programToOpenWith}, while {nameof(px.ProcessName)} is {px.ProcessName}.");
px.Kill();
px.WaitForExit();
Assert.True(px.HasExited);
}
}
[Theory, InlineData("Safari"), InlineData("\"Google Chrome\"")]
[PlatformSpecific(TestPlatforms.OSX)]
[OuterLoop("Opens browser")]
public void ProcessStart_OpenUrl_UsesSpecifiedApplication(string applicationToOpenWith)
{
using (var px = Process.Start("/usr/bin/open", "https://github.com/dotnet/corefx -a " + applicationToOpenWith))
{
Assert.NotNull(px);
px.Kill();
px.WaitForExit();
Assert.True(px.HasExited);
}
}
[Theory, InlineData("-a Safari"), InlineData("-a \"Google Chrome\"")]
[PlatformSpecific(TestPlatforms.OSX)]
[OuterLoop("Opens browser")]
public void ProcessStart_UseShellExecuteTrue_OpenUrl_SuccessfullyReadsArgument(string arguments)
{
var startInfo = new ProcessStartInfo { UseShellExecute = true, FileName = "https://github.com/dotnet/corefx", Arguments = arguments };
using (var px = Process.Start(startInfo))
{
Assert.NotNull(px);
px.Kill();
px.WaitForExit();
Assert.True(px.HasExited);
}
}
public static TheoryData<string[]> StartOSXProcessWithArgumentList => new TheoryData<string[]>
{
{ new string[] { "-a", "Safari" } },
{ new string[] { "-a", "\"Google Chrome\"" } }
};
[Theory,
MemberData(nameof(StartOSXProcessWithArgumentList))]
[PlatformSpecific(TestPlatforms.OSX)]
[OuterLoop("Opens browser")]
public void ProcessStart_UseShellExecuteTrue_OpenUrl_SuccessfullyReadsArgument(string[] argumentList)
{
var startInfo = new ProcessStartInfo { UseShellExecute = true, FileName = "https://github.com/dotnet/corefx"};
foreach (string item in argumentList)
{
startInfo.ArgumentList.Add(item);
}
using (var px = Process.Start(startInfo))
{
Assert.NotNull(px);
px.Kill();
px.WaitForExit();
Assert.True(px.HasExited);
}
}
[Fact]
[Trait(XunitConstants.Category, XunitConstants.RequiresElevation)]
public void TestPriorityClassUnix()
{
CreateDefaultProcess();
ProcessPriorityClass priorityClass = _process.PriorityClass;
_process.PriorityClass = ProcessPriorityClass.Idle;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Idle);
try
{
_process.PriorityClass = ProcessPriorityClass.High;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High);
_process.PriorityClass = ProcessPriorityClass.Normal;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal);
_process.PriorityClass = priorityClass;
}
catch (Win32Exception ex)
{
Assert.True(!PlatformDetection.IsSuperUser, $"Failed even though superuser {ex.ToString()}");
}
}
[Fact]
[Trait(XunitConstants.Category, XunitConstants.RequiresElevation)]
public void TestBasePriorityOnUnix()
{
CreateDefaultProcess();
ProcessPriorityClass originalPriority = _process.PriorityClass;
Assert.Equal(ProcessPriorityClass.Normal, originalPriority);
// https://github.com/dotnet/corefx/issues/25861 -- returns "-19" and not "19"
if (!PlatformDetection.IsWindowsSubsystemForLinux)
{
SetAndCheckBasePriority(ProcessPriorityClass.Idle, 19);
}
try
{
SetAndCheckBasePriority(ProcessPriorityClass.Normal, 0);
// https://github.com/dotnet/corefx/issues/25861 -- returns "11" and not "-11"
if (!PlatformDetection.IsWindowsSubsystemForLinux)
{
SetAndCheckBasePriority(ProcessPriorityClass.High, -11);
}
_process.PriorityClass = originalPriority;
}
catch (Win32Exception ex)
{
Assert.True(!PlatformDetection.IsSuperUser, $"Failed even though superuser {ex.ToString()}");
}
}
[Fact]
public void TestStartOnUnixWithBadPermissions()
{
string path = GetTestFilePath();
File.Create(path).Dispose();
int mode = Convert.ToInt32("644", 8);
Assert.Equal(0, chmod(path, mode));
Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(path));
Assert.NotEqual(0, e.NativeErrorCode);
}
[Fact]
public void TestStartOnUnixWithBadFormat()
{
string path = GetTestFilePath();
File.Create(path).Dispose();
int mode = Convert.ToInt32("744", 8);
Assert.Equal(0, chmod(path, mode)); // execute permissions
Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(path));
Assert.NotEqual(0, e.NativeErrorCode);
}
[Fact]
public void TestStartWithNonExistingUserThrows()
{
Process p = CreateProcessPortable(RemotelyInvokable.Dummy);
p.StartInfo.UserName = "DoesNotExist";
Assert.Throws<Win32Exception>(() => p.Start());
}
[Fact]
public void TestExitCodeKilledChild()
{
using (Process p = CreateProcessLong())
{
p.Start();
p.Kill();
p.WaitForExit();
// SIGKILL may change per platform
const int SIGKILL = 9; // Linux, macOS, FreeBSD, ...
Assert.Equal(128 + SIGKILL, p.ExitCode);
}
}
private static int CheckUserAndGroupIds(string userId, string groupId, string groupIdsJoined, string checkGroupsExact)
{
Assert.Equal(userId, getuid().ToString());
Assert.Equal(userId, geteuid().ToString());
Assert.Equal(groupId, getgid().ToString());
Assert.Equal(groupId, getegid().ToString());
var expectedGroups = new HashSet<uint>(groupIdsJoined.Split(',').Select(s => uint.Parse(s)));
if (bool.Parse(checkGroupsExact))
{
AssertExtensions.Equal(expectedGroups, GetGroups());
}
else
{
Assert.Subset(expectedGroups, GetGroups());
}
return RemoteExecutor.SuccessExitCode;
}
[Fact]
[ActiveIssue(35933, TestPlatforms.AnyUnix)]
public unsafe void TestCheckChildProcessUserAndGroupIds()
{
string userName = GetCurrentRealUserName();
string userId = GetUserId(userName);
string userGroupId = GetUserGroupId(userName);
string userGroupIds = GetUserGroupIds(userName);
// If this test runs as the user, we expect to be able to match the user groups exactly.
// Except on OSX, where getgrouplist may return a list of groups truncated to NGROUPS_MAX.
bool checkGroupsExact = userId == geteuid().ToString() &&
!RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
// Start as username
var invokeOptions = new RemoteInvokeOptions();
invokeOptions.StartInfo.UserName = userName;
using (RemoteInvokeHandle handle = RemoteExecutor.Invoke(CheckUserAndGroupIds, userId, userGroupId, userGroupIds, checkGroupsExact.ToString(),
invokeOptions))
{ }
}
/// <summary>
/// Tests when running as root and starting a new process as a normal user,
/// the new process doesn't have elevated privileges.
/// </summary>
[Theory]
[OuterLoop("Needs sudo access")]
[Trait(XunitConstants.Category, XunitConstants.RequiresElevation)]
[InlineData(true)]
[InlineData(false)]
[ActiveIssue(38833, TestPlatforms.AnyUnix)]
public unsafe void TestCheckChildProcessUserAndGroupIdsElevated(bool useRootGroups)
{
Func<string, string, int> runsAsRoot = (string username, string useRootGroupsArg) =>
{
// Verify we are root
Assert.Equal(0U, getuid());
Assert.Equal(0U, geteuid());
Assert.Equal(0U, getgid());
Assert.Equal(0U, getegid());
string userId = GetUserId(username);
string userGroupId = GetUserGroupId(username);
string userGroupIds = GetUserGroupIds(username);
if (bool.Parse(useRootGroupsArg))
{
uint rootGroups = 0;
int setGroupsRv = setgroups(1, &rootGroups);
Assert.Equal(0, setGroupsRv);
}
// On systems with a low value of NGROUPS_MAX (e.g 16 on OSX), the groups may be truncated.
// On Linux NGROUPS_MAX is 65536, so we expect to see every group.
bool checkGroupsExact = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
// Start as username
var invokeOptions = new RemoteInvokeOptions();
invokeOptions.StartInfo.UserName = username;
using (RemoteInvokeHandle handle = RemoteExecutor.Invoke(CheckUserAndGroupIds, userId, userGroupId, userGroupIds, checkGroupsExact.ToString(), invokeOptions))
{ }
return RemoteExecutor.SuccessExitCode;
};
// Start as root
string userName = GetCurrentRealUserName();
using (RemoteInvokeHandle handle = RemoteExecutor.Invoke(runsAsRoot, userName, useRootGroups.ToString(),
new RemoteInvokeOptions { RunAsSudo = true }))
{ }
}
private static string GetUserId(string username)
=> StartAndReadToEnd("id", new[] { "-u", username }).Trim('\n');
private static string GetUserGroupId(string username)
=> StartAndReadToEnd("id", new[] { "-g", username }).Trim('\n');
private static string GetUserGroupIds(string username)
{
string[] groupIds = StartAndReadToEnd("id", new[] { "-G", username })
.Split(new[] { ' ', '\n' }, StringSplitOptions.RemoveEmptyEntries);
return string.Join(",", groupIds.Select(s => uint.Parse(s)).OrderBy(id => id));
}
private static string GetCurrentRealUserName()
{
string realUserName = geteuid() == 0 ?
Environment.GetEnvironmentVariable("SUDO_USER") :
Environment.UserName;
Assert.NotNull(realUserName);
Assert.NotEqual("root", realUserName);
return realUserName;
}
/// <summary>
/// Tests whether child processes are reaped (cleaning up OS resources)
/// when they terminate.
/// </summary>
[Fact]
[PlatformSpecific(TestPlatforms.Linux)] // Test uses Linux specific '/proc' filesystem
public async Task TestChildProcessCleanup()
{
using (Process process = CreateShortProcess())
{
process.Start();
bool processReaped = await TryWaitProcessReapedAsync(process.Id, timeoutMs: 30000);
Assert.True(processReaped);
}
}
/// <summary>
/// Tests whether child processes are reaped (cleaning up OS resources)
/// when they terminate after the Process was Disposed.
/// </summary>
[Theory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, false)]
[InlineData(true, true)]
[PlatformSpecific(TestPlatforms.Linux)] // Test uses Linux specific '/proc' filesystem
public async Task TestChildProcessCleanupAfterDispose(bool shortProcess, bool enableEvents)
{
// We test using a long and short process. The long process will terminate after Dispose,
// The short process will terminate at the same time, possibly revealing race conditions.
int processId = -1;
using (Process process = shortProcess ? CreateShortProcess() : CreateSleepProcess(durationMs: 500))
{
process.Start();
processId = process.Id;
if (enableEvents)
{
// Dispose will disable the Exited event.
// We enable it to check this doesn't cause issues for process reaping.
process.EnableRaisingEvents = true;
}
}
bool processReaped = await TryWaitProcessReapedAsync(processId, timeoutMs: 30000);
Assert.True(processReaped);
}
private static Process CreateShortProcess()
{
Process process = new Process();
process.StartInfo.FileName = "uname";
return process;
}
private static async Task<bool> TryWaitProcessReapedAsync(int pid, int timeoutMs)
{
const int SleepTimeMs = 50;
// When the process is reaped, the '/proc/<pid>' directory to disappears.
bool procPidExists = true;
for (int attempt = 0; attempt < (timeoutMs / SleepTimeMs); attempt++)
{
procPidExists = Directory.Exists("/proc/" + pid);
if (procPidExists)
{
await Task.Delay(SleepTimeMs);
}
else
{
break;
}
}
return !procPidExists;
}
/// <summary>
/// Tests the ProcessWaitState reference count drops to zero.
/// </summary>
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Test validates Unix implementation
public async Task TestProcessWaitStateReferenceCount()
{
using (var exitedEventSemaphore = new SemaphoreSlim(0, 1))
{
object waitState = null;
int processId = -1;
// Process takes a reference
using (var process = CreateShortProcess())
{
process.EnableRaisingEvents = true;
// Exited event takes a reference
process.Exited += (o,e) => exitedEventSemaphore.Release();
process.Start();
processId = process.Id;
waitState = GetProcessWaitState(process);
process.WaitForExit();
Assert.False(GetWaitStateDictionary(childDictionary: false).Contains(processId));
Assert.True(GetWaitStateDictionary(childDictionary: true).Contains(processId));
}
exitedEventSemaphore.Wait();
// Child reaping holds a reference too
int referenceCount = -1;
const int SleepTimeMs = 50;
for (int i = 0; i < (30000 / SleepTimeMs); i++)
{
referenceCount = GetWaitStateReferenceCount(waitState);
if (referenceCount == 0)
{
break;
}
else
{
// Process was reaped but ProcessWaitState not unrefed yet
await Task.Delay(SleepTimeMs);
}
}
Assert.Equal(0, referenceCount);
Assert.Equal(0, GetWaitStateReferenceCount(waitState));
Assert.False(GetWaitStateDictionary(childDictionary: false).Contains(processId));
Assert.False(GetWaitStateDictionary(childDictionary: true).Contains(processId));
}
}
/// <summary>
/// Verifies a new Process instance can refer to a process with a recycled pid for which
/// there is still an existing Process instance. Operations on the existing instance will
/// throw since that process has exited.
/// </summary>
[ConditionalFact(typeof(TestEnvironment), nameof(TestEnvironment.IsStressModeEnabled))]
public void TestProcessRecycledPid()
{
const int LinuxPidMaxDefault = 32768;
var processes = new Dictionary<int, Process>(LinuxPidMaxDefault);
bool foundRecycled = false;
for (int i = 0; i < int.MaxValue; i++)
{
var process = CreateProcessLong();
process.Start();
Process recycled;
foundRecycled = processes.TryGetValue(process.Id, out recycled);
if (foundRecycled)
{
Assert.Throws<InvalidOperationException>(() => recycled.Kill());
}
process.Kill();
process.WaitForExit();
if (foundRecycled)
{
break;
}
else
{
processes.Add(process.Id, process);
}
}
Assert.True(foundRecycled);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task Kill_ExitedNonChildProcess_DoesNotThrow(bool killTree)
{
// In this test, we kill a process in a way the Process instance
// is not aware the process has terminated when we invoke Process.Kill.
using (Process nonChildProcess = CreateNonChildProcess())
{
// Kill the process.
int rv = kill(nonChildProcess.Id, SIGKILL);
Assert.Equal(0, rv);
// Wait until the process is reaped.
while (rv == 0)
{
rv = kill(nonChildProcess.Id, 0);
if (rv == 0)
{
// process still exists, wait some time.
await Task.Delay(100);
}
}
// Call Process.Kill.
nonChildProcess.Kill(killTree);
}
Process CreateNonChildProcess()
{
// Create a process that isn't a direct child.
int nonChildPid = -1;
RemoteInvokeHandle createNonChildProcess = RemoteExecutor.Invoke(arg =>
{
RemoteInvokeHandle nonChildProcess = RemoteExecutor.Invoke(
// Process that lives as long as the test process.
testProcessPid => Process.GetProcessById(int.Parse(testProcessPid)).WaitForExit(), arg,
// Don't pass our standard out to the sleepProcess or the ReadToEnd below won't return.
new RemoteInvokeOptions { StartInfo = new ProcessStartInfo() { RedirectStandardOutput = true } });
using (nonChildProcess)
{
Console.WriteLine(nonChildProcess.Process.Id);
// Don't wait for the process to exit.
nonChildProcess.Process = null;
}
}, Process.GetCurrentProcess().Id.ToString(), new RemoteInvokeOptions { StartInfo = new ProcessStartInfo() { RedirectStandardOutput = true } });
using (createNonChildProcess)
{
nonChildPid = int.Parse(createNonChildProcess.Process.StandardOutput.ReadToEnd());
}
return Process.GetProcessById(nonChildPid);
}
}
private static IDictionary GetWaitStateDictionary(bool childDictionary)
{
Assembly assembly = typeof(Process).Assembly;
Type waitStateType = assembly.GetType("System.Diagnostics.ProcessWaitState");
FieldInfo dictionaryField = waitStateType.GetField(childDictionary ? "s_childProcessWaitStates" : "s_processWaitStates", BindingFlags.NonPublic | BindingFlags.Static);
return (IDictionary)dictionaryField.GetValue(null);
}
private static object GetProcessWaitState(Process p)
{
MethodInfo getWaitState = typeof(Process).GetMethod("GetWaitState", BindingFlags.NonPublic | BindingFlags.Instance);
return getWaitState.Invoke(p, null);
}
private static int GetWaitStateReferenceCount(object waitState)
{
FieldInfo referenCountField = waitState.GetType().GetField("_outstandingRefCount", BindingFlags.NonPublic | BindingFlags.Instance);
return (int)referenCountField.GetValue(waitState);
}
private void RunTestAsSudo(Func<string, int> testMethod, string arg)
{
RemoteInvokeOptions options = new RemoteInvokeOptions()
{
RunAsSudo = true
};
using (RemoteInvokeHandle handle = RemoteExecutor.Invoke(testMethod, arg, options))
{ }
}
[DllImport("libc")]
private static extern int chmod(string path, int mode);
[DllImport("libc")]
private static extern uint geteuid();
[DllImport("libc")]
private static extern uint getuid();
[DllImport("libc")]
private static extern uint getegid();
[DllImport("libc")]
private static extern uint getgid();
[DllImport("libc", SetLastError = true)]
private unsafe static extern int getgroups(int size, uint* list);
private unsafe static HashSet<uint> GetGroups()
{
int maxSize = 128;
Span<uint> groups = stackalloc uint[maxSize];
fixed (uint* pGroups = groups)
{
int rv = getgroups(maxSize, pGroups);
if (rv == -1)
{
// If this throws with EINVAL, maxSize should be increased.
throw new Win32Exception();
}
// Return this as a HashSet to filter out duplicates.
return new HashSet<uint>(groups.Slice(0, rv).ToArray());
}
}
[DllImport("libc")]
private static extern int seteuid(uint euid);
[DllImport("libc")]
private static unsafe extern int setgroups(int length, uint* groups);
private const int SIGKILL = 9;
[DllImport("libc", SetLastError = true)]
private static extern int kill(int pid, int sig);
private static readonly string[] s_allowedProgramsToRun = new string[] { "xdg-open", "gnome-open", "kfmclient" };
private string WriteScriptFile(string directory, string name, int returnValue)
{
string filename = Path.Combine(directory, name);
File.WriteAllText(filename, $"#!/bin/sh\nexit {returnValue}\n");
// set x-bit
int mode = Convert.ToInt32("744", 8);
Assert.Equal(0, chmod(filename, mode));
return filename;
}
private static string StartAndReadToEnd(string filename, string[] arguments)
{
var psi = new ProcessStartInfo
{
FileName = filename,
RedirectStandardOutput = true
};
foreach (var arg in arguments)
{
psi.ArgumentList.Add(arg);
}
using (Process process = Process.Start(psi))
{
return process.StandardOutput.ReadToEnd();
}
}
}
}
| |
using System;
using System.Collections;
using Server.Network;
using Server.Items;
using Server.Mobiles;
namespace Server.Items.Crops
{
//naga
public class CocoSeed : BaseCrop
{
// return true to allow planting on Dirt Item (ItemID 0x32C9)
// See CropHelper.cs for other overriddable types
public override bool CanGrowGarden{ get{ return true; } }
[Constructable]
public CocoSeed() : this( 1 )
{
}
[Constructable]
public CocoSeed( int amount ) : base( 0xF27 )
{
Stackable = true;
Weight = .5;
Hue = 0x5E2;
Movable = true;
Amount = amount;
Name = AgriTxt.Seed + " de Cocotier";
}
public override void OnDoubleClick( Mobile from )
{
if ( from.Mounted && !CropHelper.CanWorkMounted )
{
from.SendMessage(AgriTxt.CannotWorkMounted);
return;
}
Point3D m_pnt = from.Location;
Map m_map = from.Map;
if ( !IsChildOf( from.Backpack ) )
{
from.SendLocalizedMessage( 1042010 ); //You must have the object in your backpack to use it.
return;
}
else if ( !CropHelper.CheckCanGrow( this, m_map, m_pnt.X, m_pnt.Y ) )
{
from.SendMessage(AgriTxt.CannotGrowHere);
return;
}
//check for BaseCrop on this tile
ArrayList cropshere = CropHelper.CheckCrop( m_pnt, m_map, 0 );
if ( cropshere.Count > 0 )
{
from.SendMessage(AgriTxt.AlreadyCrop);
return;
}
//check for over planting prohibt if 4 maybe 3 neighboring crops
ArrayList cropsnear = CropHelper.CheckCrop( m_pnt, m_map, 2 );//1
if ( ( cropsnear.Count > 1 ) || (( cropsnear.Count == 1 ) && Utility.RandomBool() ) )//3
{
from.SendMessage(AgriTxt.TooMuchCrops);
return;
}
if ( this.BumpZ ) ++m_pnt.Z;
if ( !from.Mounted )
from.Animate( 32, 5, 1, true, false, 0 ); // Bow
from.SendMessage(AgriTxt.CropPlanted);
this.Consume();
Item item = new CocoSapling();// from );
item.Location = m_pnt;
item.Map = m_map;
}
public CocoSeed( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
//naga
public class CocoSapling : BaseCrop
{
public Timer thisTimer;
public DateTime treeTime;
[CommandProperty( AccessLevel.GameMaster )]
public String FullGrown{ get{ return treeTime.ToString( "T" ); } }
[Constructable]
public CocoSapling() : base( Utility.RandomList ( 0xC9C, 0xC9B ) )
{
Movable = false;
Name = AgriTxt.Seedling + " de Cocotier";
init( this );
}
public static void init( CocoSapling plant )
{
TimeSpan delay = TreeHelper.SaplingTime;
plant.treeTime = DateTime.Now + delay;
plant.thisTimer = new TreeHelper.TreeTimer( plant, typeof(CocoTree), delay );
plant.thisTimer.Start();
}
public CocoSapling( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
init( this );
}
}
public class CocoTree : BaseTree
{
public Item i_trunk;
private Timer chopTimer;
private const int max = 12;
private DateTime lastpicked;
private int m_yield;
public Timer regrowTimer;
[CommandProperty( AccessLevel.GameMaster )]
public int Yield{ get{ return m_yield; } set{ m_yield = value; } }
public int Capacity{ get{ return max; } }
public DateTime LastPick{ get{ return lastpicked; } set{ lastpicked = value; } }
[Constructable]
public CocoTree( Point3D pnt, Map map ) : base( Utility.RandomList( 0xC96, 0xC95 ) ) // leaves
{
Name = "Cocotier";
Movable = false;
MoveToWorld( pnt, map );
int trunkID = 0x1B1F; // ((Item)this).ItemID - 2;
i_trunk = new TreeTrunk( trunkID, this );
i_trunk.MoveToWorld( pnt, map );
init( this, false );
}
public static void init ( CocoTree plant, bool full )
{
plant.LastPick = DateTime.Now;
plant.regrowTimer = new FruitTimer( plant );
if ( full )
{
plant.Yield = plant.Capacity;
}
else
{
plant.Yield = 0;
plant.regrowTimer.Start();
}
}
public override void OnAfterDelete()
{
if (( i_trunk != null ) && ( !i_trunk.Deleted ))
i_trunk.Delete();
base.OnAfterDelete();
}
public override void OnDoubleClick( Mobile from )
{
if ( from.Mounted && !TreeHelper.CanPickMounted )
{
from.SendMessage(AgriTxt.CannotWorkMounted);
return;
}
if ( DateTime.Now > lastpicked.AddSeconds(3) ) // 3 seconds between picking
{
lastpicked = DateTime.Now;
int lumberValue = (int)from.Skills[SkillName.Lumberjacking].Value / 5;
if ( from.Mounted )
++lumberValue;
if ( lumberValue < 3 )
{
from.SendMessage(AgriTxt.DunnoHowTo);
return;
}
if ( from.InRange( this.GetWorldLocation(), 2 ) )
{
if ( m_yield < 1 )
{
from.SendMessage(AgriTxt.NoCrop);
}
else //check skill
{
from.Direction = from.GetDirectionTo( this );
from.Animate( from.Mounted ? 26:17, 7, 1, true, false, 0 );
if ( lumberValue > m_yield )
lumberValue = m_yield + 1;
int pick = Utility.Random( lumberValue );
if ( pick == 0 )
{
from.SendMessage(AgriTxt.ZeroPicked);
return;
}
m_yield -= pick;
from.SendMessage(AgriTxt.YouPick + " {0} noix de coco!", pick);
//PublicOverheadMessage( MessageType.Regular, 0x3BD, false, string.Format( "{0}", m_yield ));
Coconut crop = new Coconut( pick );
from.AddToBackpack( crop );
if ( !regrowTimer.Running )
{
regrowTimer.Start();
}
}
}
else
{
from.SendLocalizedMessage( 500446 ); // That is too far away.
}
}
}
private class FruitTimer : Timer
{
private CocoTree i_plant;
public FruitTimer( CocoTree plant ) : base( TimeSpan.FromSeconds( 900 ), TimeSpan.FromSeconds( 30 ) )
{
Priority = TimerPriority.OneSecond;
i_plant = plant;
}
protected override void OnTick()
{
if ( ( i_plant != null ) && ( !i_plant.Deleted ) )
{
int current = i_plant.Yield;
if ( ++current >= i_plant.Capacity )
{
current = i_plant.Capacity;
Stop();
}
else if ( current <= 0 )
current = 1;
i_plant.Yield = current;
//i_plant.PublicOverheadMessage( MessageType.Regular, 0x22, false, string.Format( "{0}", current ));
}
else Stop();
}
}
public void Chop( Mobile from )
{
if ( from.InRange( this.GetWorldLocation(), 2 ) )
{
if ( ( chopTimer == null ) || ( !chopTimer.Running ) )
{
if ( ( TreeHelper.TreeOrdinance ) && ( from.AccessLevel == AccessLevel.Player ) )
{
if ( from.Region is Regions.GuardedRegion )
from.CriminalAction( true );
}
chopTimer = new TreeHelper.ChopAction( from );
Point3D pnt = this.Location;
Map map = this.Map;
from.Direction = from.GetDirectionTo( this );
chopTimer.Start();
double lumberValue = from.Skills[SkillName.Lumberjacking].Value / 100;
if ( ( lumberValue > .5 ) && ( Utility.RandomDouble() <= lumberValue ) )
{
Coconut fruit = new Coconut( (int)Utility.Random( 13 ) + m_yield );
from.AddToBackpack( fruit );
int cnt = Utility.Random( (int)( lumberValue * 10 ) + 1 );
Log logs = new Log( cnt ); // Fruitwood Logs ??
from.AddToBackpack( logs );
FruitTreeStump i_stump = new FruitTreeStump( typeof( CocoTree ) );
Timer poof = new StumpTimer( this, i_stump, from );
poof.Start();
}
else from.SendLocalizedMessage( 500495 ); // You hack at the tree for a while, but fail to produce any useable wood.
//PublicOverheadMessage( MessageType.Regular, 0x3BD, false, string.Format( "{0}", lumberValue ));
}
}
else from.SendLocalizedMessage( 500446 ); // That is too far away.
}
private class StumpTimer : Timer
{
private CocoTree i_tree;
private FruitTreeStump i_stump;
private Mobile m_chopper;
public StumpTimer( CocoTree Tree, FruitTreeStump Stump, Mobile from ) : base( TimeSpan.FromMilliseconds( 5500 ) )
{
Priority = TimerPriority.TenMS;
i_tree = Tree;
i_stump = Stump;
m_chopper = from;
}
protected override void OnTick()
{
i_stump.MoveToWorld( i_tree.Location, i_tree.Map );
i_tree.Delete();
m_chopper.SendMessage(AgriTxt.LogsAndFruits);
}
}
public override void OnChop( Mobile from )
{
if ( !this.Deleted )
Chop( from );
}
public CocoTree( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 );
writer.Write( (Item)i_trunk );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
Item item = reader.ReadItem();
if ( item != null )
i_trunk = item;
init( this, true );
}
}
}
| |
// ----------------------------------------------------------------------------
// <copyright file="Vaccines.cs" company="HIVacSim">
// Copyright (c) 2014 HIVacSim Contributors
// </copyright>
// <author>Israel Vieira</author>
// ----------------------------------------------------------------------------
namespace HIVacSim
{
using System;
using System.ComponentModel;
/// <summary>
/// Defines a container to hold the preventive vaccines.
/// </summary>
public class Vaccines
{
#region Local variables
private Vaccine[] _vaccines; // Collections of vaccines
private int _count; // The number of vaccines defined
private int _selected; // Index of the selected vaccine
#endregion
#region Constructor
/// <summary>
/// Default Constructor
/// </summary>
public Vaccines()
{
this._count = 0;
this._selected = -1;
}
#endregion
#region Public properties
/// <summary>
/// The number of vaccines defined
/// </summary>
public int Count
{
get { return this._count; }
}
/// <summary>
/// The index of the last selected vaccine
/// </summary>
public int Selected
{
get { return this._selected; }
}
/// <summary>
/// Get or set a vaccine property.
/// </summary>
public Vaccine this[int index]
{
get
{
if (index >= 0 && index < this._count)
{
this._selected = index;
return this._vaccines[index];
}
else
{
throw new ArgumentOutOfRangeException(
"index < 0 or index > Count",
"Invalid index argument.");
}
}
set
{
if (index >= 0 && index < this._count)
{
this._vaccines[index] = value;
}
else
{
throw new ArgumentOutOfRangeException(
"index < 0 or index > Count",
"Invalid index argument.");
}
}
}
#endregion //Properties
#region Public Methods
/// <summary>
/// Adds a new vaccine to the collection
/// </summary>
/// <param name="vacdef">The vaccine to be added</param>
/// <returns>The index of the new vaccine</returns>
public int Add(Vaccine vacdef)
{
//Initialise the container
if (this._count == 0)
{
//Adds a new vaccine
this._vaccines = new Vaccine[1];
this._vaccines[0] = vacdef;
this._count = 1;
}
else
{
// Resize the array and copy the old data
Vaccine[] tmpVac = this._vaccines;
this._vaccines = new Vaccine[this._count + 1];
Array.Copy(tmpVac, this._vaccines, tmpVac.Length);
this._vaccines[this._count] = vacdef;
this._count++;
}
return this._count - 1;
}
/// <summary>
/// Removes an existing vaccine
/// </summary>
/// <param name="index">The index of the vaccine to be removed</param>
public void Remove(int index)
{
if (index >= 0 && index < this._count)
{
//Data integrity check
if (this._vaccines[index].UsedBy.Count > 0)
{
throw new SimulationException(
"Vaccine [" + this._vaccines[index].Name +
"] is currently in use by one or more intervention strategies.");
}
this._count--;
//Check if population container is empty
if (this._count == 0)
{
this._vaccines = null;
this._count = 0;
this._selected = -1;
Vaccine.Reset();
}
else
{
// Resize the array and copy the old data
Vaccine[] tmpVac = this._vaccines;
this._vaccines = new Vaccine[this._count];
for (int i = 0; i < this._count; i++)
{
if (i < index)
{
this._vaccines[i] = tmpVac[i];
}
else
{
this._vaccines[i] = tmpVac[i + 1];
}
}
}
}
else
{
throw new ArgumentOutOfRangeException(
"index < 0 or index > Count.",
"Invalid index argument on Vaccines.RemoveVaccine.");
}
//Check selected index range
if (this._selected >= this._count)
{
this._selected = this._count - 1;
}
}
/// <summary>
/// Removes an existing vaccine
/// </summary>
/// <param name="vacid">The vaccine to be removed</param>
public void Remove(Vaccine vacid)
{
int index = IndexOf(vacid);
if (index >= 0)
{
this.Remove(index);
}
}
/// <summary>
/// Finds the index of an existing vaccine
/// </summary>
/// <param name="vacid">The vaccine to be found</param>
public int IndexOf(Vaccine vacid)
{
if (this._count > 0)
{
for (int i = 0; i < this._count; i++)
{
if (this._vaccines[i] == vacid)
{
return i;
}
}
return -1;
}
else
{
throw new ArgumentException(
"The population container is empty.",
"Invalid Vaccine, index < 0 or index > Count");
}
}
/// <summary>
/// Finds the index of an existing vaccine
/// </summary>
/// <param name="vacid">The ID of the vaccine to be found</param>
public int IndexOf(int vacid)
{
if (this._count > 0)
{
for (int i = 0; i < this._count; i++)
{
if (this._vaccines[i].Id == vacid)
{
return i;
}
}
return -1;
}
else
{
throw new ArgumentException(
"The population container is empty.",
"Invalid Vaccine, index < 0 or index > Count");
}
}
/// <summary>
/// Clear the vaccine container
/// </summary>
public void Clear()
{
this._vaccines = null;
this._count = 0;
this._selected = -1;
Vaccine.Reset();
}
#endregion //Public methods
}
}
| |
/*
* Copyright 2005 OpenXRI Foundation
* Subsequently ported and altered by Andrew Arnott and Troels Thomsen
*
* 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.Collections;
using System.Collections.Generic;
namespace DotNetXri.Syntax.Xri3.Impl.Parser
{
public class Displayer : Visitor
{
public void visit(Rule rule)
{
rule.visit(this);
}
public object visit_xri(Parser.xri rule)
{
return visitRules(rule.rules);
}
public object visit_xri_scheme(Parser.xri_scheme rule)
{
return visitRules(rule.rules);
}
public object visit_xri_noscheme(Parser.xri_noscheme rule)
{
return visitRules(rule.rules);
}
public object visit_xri_reference(Parser.xri_reference rule)
{
return visitRules(rule.rules);
}
public object visit_relative_xri_ref(Parser.relative_xri_ref rule)
{
return visitRules(rule.rules);
}
public object visit_relative_xri_part(Parser.relative_xri_part rule)
{
return visitRules(rule.rules);
}
public object visit_xri_hier_part(Parser.xri_hier_part rule)
{
return visitRules(rule.rules);
}
public object visit_xri_authority(Parser.xri_authority rule)
{
return visitRules(rule.rules);
}
public object visit_subseg(Parser.subseg rule)
{
return visitRules(rule.rules);
}
public object visit_global_subseg(Parser.global_subseg rule)
{
return visitRules(rule.rules);
}
public object visit_local_subseg(Parser.local_subseg rule)
{
return visitRules(rule.rules);
}
public object visit_gcs_char(Parser.gcs_char rule)
{
return visitRules(rule.rules);
}
public object visit_lcs_char(Parser.lcs_char rule)
{
return visitRules(rule.rules);
}
public object visit_rel_subseg(Parser.rel_subseg rule)
{
return visitRules(rule.rules);
}
public object visit_rel_subseg_nc(Parser.rel_subseg_nc rule)
{
return visitRules(rule.rules);
}
public object visit_literal(Parser.literal rule)
{
return visitRules(rule.rules);
}
public object visit_literal_nc(Parser.literal_nc rule)
{
return visitRules(rule.rules);
}
public object visit_xref(Parser.xref rule)
{
return visitRules(rule.rules);
}
public object visit_xref_empty(Parser.xref_empty rule)
{
return visitRules(rule.rules);
}
public object visit_xref_xri_reference(Parser.xref_xri_reference rule)
{
return visitRules(rule.rules);
}
public object visit_xref_IRI(Parser.xref_IRI rule)
{
return visitRules(rule.rules);
}
public object visit_xref_value(Parser.xref_value rule)
{
return visitRules(rule.rules);
}
public object visit_xri_path(Parser.xri_path rule)
{
return visitRules(rule.rules);
}
public object visit_xri_path_abempty(Parser.xri_path_abempty rule)
{
return visitRules(rule.rules);
}
public object visit_xri_path_abs(Parser.xri_path_abs rule)
{
return visitRules(rule.rules);
}
public object visit_xri_path_noscheme(Parser.xri_path_noscheme rule)
{
return visitRules(rule.rules);
}
public object visit_xri_segment(Parser.xri_segment rule)
{
return visitRules(rule.rules);
}
public object visit_xri_segment_nz(Parser.xri_segment_nz rule)
{
return visitRules(rule.rules);
}
public object visit_xri_segment_nc(Parser.xri_segment_nc rule)
{
return visitRules(rule.rules);
}
public object visit_xri_pchar(Parser.xri_pchar rule)
{
return visitRules(rule.rules);
}
public object visit_xri_pchar_nc(Parser.xri_pchar_nc rule)
{
return visitRules(rule.rules);
}
public object visit_xri_reserved(Parser.xri_reserved rule)
{
return visitRules(rule.rules);
}
public object visit_xri_gen_delims(Parser.xri_gen_delims rule)
{
return visitRules(rule.rules);
}
public object visit_xri_sub_delims(Parser.xri_sub_delims rule)
{
return visitRules(rule.rules);
}
public object visit_IRI(Parser.IRI rule)
{
return visitRules(rule.rules);
}
public object visit_scheme(Parser.scheme rule)
{
return visitRules(rule.rules);
}
public object visit_ihier_part(Parser.ihier_part rule)
{
return visitRules(rule.rules);
}
public object visit_iauthority(Parser.iauthority rule)
{
return visitRules(rule.rules);
}
public object visit_iuserinfo(Parser.iuserinfo rule)
{
return visitRules(rule.rules);
}
public object visit_ihost(Parser.ihost rule)
{
return visitRules(rule.rules);
}
public object visit_IP_literal(Parser.IP_literal rule)
{
return visitRules(rule.rules);
}
public object visit_IPvFuture(Parser.IPvFuture rule)
{
return visitRules(rule.rules);
}
public object visit_IPv6address(Parser.IPv6address rule)
{
return visitRules(rule.rules);
}
public object visit_ls32(Parser.ls32 rule)
{
return visitRules(rule.rules);
}
public object visit_h16(Parser.h16 rule)
{
return visitRules(rule.rules);
}
public object visit_IPv4address(Parser.IPv4address rule)
{
return visitRules(rule.rules);
}
public object visit_dec_octet(Parser.dec_octet rule)
{
return visitRules(rule.rules);
}
public object visit_ireg_name(Parser.ireg_name rule)
{
return visitRules(rule.rules);
}
public object visit_port(Parser.port rule)
{
return visitRules(rule.rules);
}
public object visit_ipath_abempty(Parser.ipath_abempty rule)
{
return visitRules(rule.rules);
}
public object visit_ipath_abs(Parser.ipath_abs rule)
{
return visitRules(rule.rules);
}
public object visit_ipath_rootless(Parser.ipath_rootless rule)
{
return visitRules(rule.rules);
}
public object visit_ipath_empty(Parser.ipath_empty rule)
{
return visitRules(rule.rules);
}
public object visit_isegment(Parser.isegment rule)
{
return visitRules(rule.rules);
}
public object visit_isegment_nz(Parser.isegment_nz rule)
{
return visitRules(rule.rules);
}
public object visit_iquery(Parser.iquery rule)
{
return visitRules(rule.rules);
}
public object visit_iprivate(Parser.iprivate rule)
{
return visitRules(rule.rules);
}
public object visit_ifragment(Parser.ifragment rule)
{
return visitRules(rule.rules);
}
public object visit_ipchar(Parser.ipchar rule)
{
return visitRules(rule.rules);
}
public object visit_iunreserved(Parser.iunreserved rule)
{
return visitRules(rule.rules);
}
public object visit_pct_encoded(Parser.pct_encoded rule)
{
return visitRules(rule.rules);
}
public object visit_ucschar(Parser.ucschar rule)
{
return visitRules(rule.rules);
}
public object visit_reserved(Parser.reserved rule)
{
return visitRules(rule.rules);
}
public object visit_gen_delims(Parser.gen_delims rule)
{
return visitRules(rule.rules);
}
public object visit_sub_delims(Parser.sub_delims rule)
{
return visitRules(rule.rules);
}
public object visit_unreserved(Parser.unreserved rule)
{
return visitRules(rule.rules);
}
public object visit_ALPHA(Parser.ALPHA rule)
{
return visitRules(rule.rules);
}
public object visit_BIT(Parser.BIT rule)
{
return visitRules(rule.rules);
}
public object visit_CHAR(Parser.CHAR rule)
{
return visitRules(rule.rules);
}
public object visit_CR(Parser.CR rule)
{
return visitRules(rule.rules);
}
public object visit_CRLF(Parser.CRLF rule)
{
return visitRules(rule.rules);
}
public object visit_CTL(Parser.CTL rule)
{
return visitRules(rule.rules);
}
public object visit_DIGIT(Parser.DIGIT rule)
{
return visitRules(rule.rules);
}
public object visit_DQUOTE(Parser.DQUOTE rule)
{
return visitRules(rule.rules);
}
public object visit_HEXDIG(Parser.HEXDIG rule)
{
return visitRules(rule.rules);
}
public object visit_HTAB(Parser.HTAB rule)
{
return visitRules(rule.rules);
}
public object visit_LF(Parser.LF rule)
{
return visitRules(rule.rules);
}
public object visit_LWSP(Parser.LWSP rule)
{
return visitRules(rule.rules);
}
public object visit_OCTET(Parser.OCTET rule)
{
return visitRules(rule.rules);
}
public object visit_SP(Parser.SP rule)
{
return visitRules(rule.rules);
}
public object visit_VCHAR(Parser.VCHAR rule)
{
return visitRules(rule.rules);
}
public object visit_WSP(Parser.WSP rule)
{
return visitRules(rule.rules);
}
public object visit_StringValue(Parser.StringValue value)
{
Logger.Info(value.spelling);
return null;
}
public object visit_NumericValue(Parser.NumericValue value)
{
Logger.Info(value.spelling);
return null;
}
private object visitRules(IList<Rule> rules)
{
for (IEnumerator<Rule> i = rules.GetEnumerator(); i.MoveNext(); )
i.Current.visit(this);
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
namespace Baseline.Reflection
{
public static class ReflectionExtensions
{
public static U? ValueOrDefault<T, U>(this T? root, Expression<Func<T, U>> expression)
where T : class
{
if (root == null)
{
return default(U);
}
var accessor = ReflectionHelper.GetAccessor(expression);
var result = accessor.GetValue(root);
return (U) (result ?? default(U))!;
}
public static T? GetAttribute<T>(this MemberInfo provider) where T : Attribute
{
var atts = provider.GetCustomAttributes(typeof (T), true);
return atts.FirstOrDefault() as T;
}
public static T? GetAttribute<T>(this Assembly provider) where T : Attribute
{
var atts = provider.GetCustomAttributes(typeof(T));
return atts.FirstOrDefault() as T;
}
public static T? GetAttribute<T>(this Module provider) where T : Attribute
{
var atts = provider.GetCustomAttributes(typeof(T));
return atts.FirstOrDefault() as T;
}
public static T? GetAttribute<T>(this ParameterInfo provider) where T : Attribute
{
var atts = provider.GetCustomAttributes(typeof(T), true);
return atts.FirstOrDefault() as T;
}
public static IEnumerable<T> GetAllAttributes<T>(this Assembly provider) where T : Attribute
{
return provider.GetCustomAttributes(typeof(T)).OfType<T>();
}
public static IEnumerable<T> GetAllAttributes<T>(this MemberInfo provider) where T : Attribute
{
return provider.GetCustomAttributes(typeof(T), true).OfType<T>();
}
public static IEnumerable<T> GetAllAttributes<T>(this Module provider) where T : Attribute
{
return provider.GetCustomAttributes(typeof(T)).OfType<T>();
}
public static IEnumerable<T> GetAllAttributes<T>(this ParameterInfo provider) where T : Attribute
{
return provider.GetCustomAttributes(typeof(T), true).OfType<T>();
}
public static IEnumerable<T>? GetAllAttributes<T>(this Accessor accessor) where T : Attribute
{
return accessor.InnerProperty?.GetAllAttributes<T>();
}
public static bool HasAttribute<T>(this Assembly provider) where T : Attribute
{
return provider.IsDefined(typeof(T));
}
public static bool HasAttribute<T>(this MemberInfo provider) where T : Attribute
{
return provider.IsDefined(typeof(T), true);
}
public static bool HasAttribute<T>(this Module provider) where T : Attribute
{
return provider.IsDefined(typeof(T));
}
public static bool HasAttribute<T>(this ParameterInfo provider) where T : Attribute
{
return provider.IsDefined(typeof(T), true);
}
public static void ForAttribute<T>(this Assembly provider, Action<T> action) where T : Attribute
{
foreach (T attribute in provider.GetAllAttributes<T>())
{
action(attribute);
}
}
public static void ForAttribute<T>(this MemberInfo provider, Action<T> action) where T : Attribute
{
foreach (T attribute in provider.GetAllAttributes<T>())
{
action(attribute);
}
}
public static void ForAttribute<T>(this Module provider, Action<T> action) where T : Attribute
{
foreach (T attribute in provider.GetAllAttributes<T>())
{
action(attribute);
}
}
public static void ForAttribute<T>(this ParameterInfo provider, Action<T> action) where T : Attribute
{
foreach (T attribute in provider.GetAllAttributes<T>())
{
action(attribute);
}
}
public static void ForAttribute<T>(this Assembly provider, Action<T> action, Action elseDo)
where T : Attribute
{
var found = false;
foreach (T attribute in provider.GetAllAttributes<T>())
{
action(attribute);
found = true;
}
if (!found) elseDo();
}
public static void ForAttribute<T>(this MemberInfo provider, Action<T> action, Action elseDo)
where T : Attribute
{
var found = false;
foreach (T attribute in provider.GetAllAttributes<T>())
{
action(attribute);
found = true;
}
if (!found) elseDo();
}
public static void ForAttribute<T>(this Module provider, Action<T> action, Action elseDo)
where T : Attribute
{
var found = false;
foreach (T attribute in provider.GetAllAttributes<T>())
{
action(attribute);
found = true;
}
if (!found) elseDo();
}
public static void ForAttribute<T>(this ParameterInfo provider, Action<T> action, Action elseDo)
where T : Attribute
{
var found = false;
foreach (T attribute in provider.GetAllAttributes<T>())
{
action(attribute);
found = true;
}
if (!found) elseDo();
}
public static void ForAttribute<T>(this Accessor accessor, Action<T> action) where T : Attribute
{
foreach (T attribute in accessor.InnerProperty!.GetAllAttributes<T>())
{
action(attribute);
}
}
public static T? GetAttribute<T>(this Accessor provider) where T : Attribute
{
return provider.InnerProperty?.GetAttribute<T>();
}
public static bool HasAttribute<T>(this Accessor provider) where T : Attribute
{
return provider.InnerProperty?.HasAttribute<T>() ?? false;
}
public static Accessor ToAccessor<T>(this Expression<Func<T, object>> expression)
{
return ReflectionHelper.GetAccessor(expression);
}
public static string GetName<T>(this Expression<Func<T, object>> expression)
{
return ReflectionHelper.GetAccessor(expression).Name;
}
public static void IfPropertyTypeIs<T>(this Accessor accessor, Action action)
{
if (accessor.PropertyType == typeof (T))
{
action();
}
}
public static bool IsInteger(this Accessor accessor)
{
return accessor.PropertyType.IsTypeOrNullableOf<int>() || accessor.PropertyType.IsTypeOrNullableOf<long>();
}
/// <summary>
/// Does a .Net type have a default, no arg constructor
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public static bool HasDefaultConstructor(this Type t)
{
return t.IsValueType || t.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null) != null;
}
// http://stackoverflow.com/a/15273117/426840
/// <summary>
/// Is the object an anonymous type that is not within a .Net
/// namespace. See http://stackoverflow.com/a/15273117/426840
/// </summary>
/// <param name="instance"></param>
/// <returns></returns>
public static bool IsAnonymousType(this object? instance)
{
if (instance == null)
return false;
return instance.GetType().Namespace == null;
}
/// <summary>
/// Get a user readable, "pretty" type name for a given type. Corrects for
/// generics and inner classes
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public static string GetPrettyName(this Type t)
{
if (!t.GetTypeInfo().IsGenericType)
return t.Name;
var sb = new StringBuilder();
sb.Append(t.Name.Substring(0, t.Name.LastIndexOf("`", StringComparison.Ordinal)));
sb.Append(t.GetGenericArguments().Aggregate("<",
(aggregate, type) => aggregate + (aggregate == "<" ? "" : ",") + GetPrettyName(type)));
sb.Append('>');
return sb.ToString();
}
}
}
| |
// 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void AlignRightSByte1()
{
var test = new ImmBinaryOpTest__AlignRightSByte1();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmBinaryOpTest__AlignRightSByte1
{
private struct TestStruct
{
public Vector128<SByte> _fld1;
public Vector128<SByte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__AlignRightSByte1 testClass)
{
var result = Ssse3.AlignRight(_fld1, _fld2, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static SByte[] _data2 = new SByte[Op2ElementCount];
private static Vector128<SByte> _clsVar1;
private static Vector128<SByte> _clsVar2;
private Vector128<SByte> _fld1;
private Vector128<SByte> _fld2;
private SimpleBinaryOpTest__DataTable<SByte, SByte, SByte> _dataTable;
static ImmBinaryOpTest__AlignRightSByte1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
}
public ImmBinaryOpTest__AlignRightSByte1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
_dataTable = new SimpleBinaryOpTest__DataTable<SByte, SByte, SByte>(_data1, _data2, new SByte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Ssse3.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Ssse3.AlignRight(
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Ssse3.AlignRight(
Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Ssse3.AlignRight(
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Ssse3).GetMethod(nameof(Ssse3.AlignRight), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Ssse3).GetMethod(nameof(Ssse3.AlignRight), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Ssse3).GetMethod(nameof(Ssse3.AlignRight), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Ssse3.AlignRight(
_clsVar1,
_clsVar2,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr);
var result = Ssse3.AlignRight(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr));
var result = Ssse3.AlignRight(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr));
var result = Ssse3.AlignRight(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__AlignRightSByte1();
var result = Ssse3.AlignRight(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Ssse3.AlignRight(_fld1, _fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Ssse3.AlignRight(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<SByte> left, Vector128<SByte> right, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != right[1])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (i == 15 ? left[0] : right[i+1]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Ssse3)}.{nameof(Ssse3.AlignRight)}<SByte>(Vector128<SByte>.1, Vector128<SByte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace NeedDotNet.Web.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using Facepunch.Network.Raknet;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Text;
namespace Rust_Interceptor {
[JsonConverter(typeof(Serializer.PacketConverter))]
public class Packet : Stream {
#region ENUM
public enum RakNet : byte {
CONNECTED_PING,
UNCONNECTED_PING,
UNCONNECTED_PING_OPEN_CONNECTIONS,
CONNECTED_PONG,
DETECT_LOST_CONNECTIONS,
OPEN_CONNECTION_REQUEST_1,
OPEN_CONNECTION_REPLY_1,
OPEN_CONNECTION_REQUEST_2,
OPEN_CONNECTION_REPLY_2,
CONNECTION_REQUEST,
REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY,
OUR_SYSTEM_REQUIRES_SECURITY,
PUBLIC_KEY_MISMATCH,
OUT_OF_BAND_INTERNAL,
SND_RECEIPT_ACKED,
SND_RECEIPT_LOSS,
CONNECTION_REQUEST_ACCEPTED,
CONNECTION_ATTEMPT_FAILED,
ALREADY_CONNECTED,
NEW_INCOMING_CONNECTION,
NO_FREE_INCOMING_CONNECTIONS,
DISCONNECTION_NOTIFICATION,
CONNECTION_LOST,
CONNECTION_BANNED,
INVALID_PASSWORD,
INCOMPATIBLE_PROTOCOL_VERSION,
IP_RECENTLY_CONNECTED,
TIMESTAMP,
UNCONNECTED_PONG,
ADVERTISE_SYSTEM,
DOWNLOAD_PROGRESS,
REMOTE_DISCONNECTION_NOTIFICATION,
REMOTE_CONNECTION_LOST,
REMOTE_NEW_INCOMING_CONNECTION,
FILE_LIST_TRANSFER_HEADER,
FILE_LIST_TRANSFER_FILE,
FILE_LIST_REFERENCE_PUSH_ACK,
DDT_DOWNLOAD_REQUEST,
TRANSPORT_STRING,
REPLICA_MANAGER_CONSTRUCTION,
REPLICA_MANAGER_SCOPE_CHANGE,
REPLICA_MANAGER_SERIALIZE,
REPLICA_MANAGER_DOWNLOAD_STARTED,
REPLICA_MANAGER_DOWNLOAD_COMPLETE,
RAKVOICE_OPEN_CHANNEL_REQUEST,
RAKVOICE_OPEN_CHANNEL_REPLY,
RAKVOICE_CLOSE_CHANNEL,
RAKVOICE_DATA,
AUTOPATCHER_GET_CHANGELIST_SINCE_DATE,
AUTOPATCHER_CREATION_LIST,
AUTOPATCHER_DELETION_LIST,
AUTOPATCHER_GET_PATCH,
AUTOPATCHER_PATCH_LIST,
AUTOPATCHER_REPOSITORY_FATAL_ERROR,
AUTOPATCHER_CANNOT_DOWNLOAD_ORIGINAL_UNMODIFIED_FILES,
AUTOPATCHER_FINISHED_INTERNAL,
AUTOPATCHER_FINISHED,
AUTOPATCHER_RESTART_APPLICATION,
NAT_PUNCHTHROUGH_REQUEST,
NAT_CONNECT_AT_TIME,
NAT_GET_MOST_RECENT_PORT,
NAT_CLIENT_READY,
NAT_TARGET_NOT_CONNECTED,
NAT_TARGET_UNRESPONSIVE,
NAT_CONNECTION_TO_TARGET_LOST,
NAT_ALREADY_IN_PROGRESS,
NAT_PUNCHTHROUGH_FAILED,
NAT_PUNCHTHROUGH_SUCCEEDED,
READY_EVENT_SET,
READY_EVENT_UNSET,
READY_EVENT_ALL_SET,
READY_EVENT_QUERY,
LOBBY_GENERAL,
RPC_REMOTE_ERROR,
RPC_PLUGIN,
FILE_LIST_REFERENCE_PUSH,
READY_EVENT_FORCE_ALL_SET,
ROOMS_EXECUTE_FUNC,
ROOMS_LOGON_STATUS,
ROOMS_HANDLE_CHANGE,
LOBBY2_SEND_MESSAGE,
LOBBY2_SERVER_ERROR,
FCM2_NEW_HOST,
FCM2_REQUEST_FCMGUID,
FCM2_RESPOND_CONNECTION_COUNT,
FCM2_INFORM_FCMGUID,
FCM2_UPDATE_MIN_TOTAL_CONNECTION_COUNT,
FCM2_VERIFIED_JOIN_START,
FCM2_VERIFIED_JOIN_CAPABLE,
FCM2_VERIFIED_JOIN_FAILED,
FCM2_VERIFIED_JOIN_ACCEPTED,
FCM2_VERIFIED_JOIN_REJECTED,
UDP_PROXY_GENERAL,
SQLite3_EXEC,
SQLite3_UNKNOWN_DB,
SQLLITE_LOGGER,
NAT_TYPE_DETECTION_REQUEST,
NAT_TYPE_DETECTION_RESULT,
ROUTER_2_INTERNAL,
ROUTER_2_FORWARDING_NO_PATH,
ROUTER_2_FORWARDING_ESTABLISHED,
ROUTER_2_REROUTED,
TEAM_BALANCER_INTERNAL,
TEAM_BALANCER_REQUESTED_TEAM_FULL,
TEAM_BALANCER_REQUESTED_TEAM_LOCKED,
TEAM_BALANCER_TEAM_REQUESTED_CANCELLED,
TEAM_BALANCER_TEAM_ASSIGNED,
LIGHTSPEED_INTEGRATION,
XBOX_LOBBY,
TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_SUCCESS,
TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_SUCCESS,
TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_FAILURE,
TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_FAILURE,
TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_TIMEOUT,
TWO_WAY_AUTHENTICATION_NEGOTIATION,
CLOUD_POST_REQUEST,
CLOUD_RELEASE_REQUEST,
CLOUD_GET_REQUEST,
CLOUD_GET_RESPONSE,
CLOUD_UNSUBSCRIBE_REQUEST,
CLOUD_SERVER_TO_SERVER_COMMAND,
CLOUD_SUBSCRIPTION_NOTIFICATION,
LIB_VOICE,
RELAY_PLUGIN,
NAT_REQUEST_BOUND_ADDRESSES,
NAT_RESPOND_BOUND_ADDRESSES,
FCM2_UPDATE_USER_CONTEXT,
RESERVED_3,
RESERVED_4,
RESERVED_5,
RESERVED_6,
RESERVED_7,
RESERVED_8,
RESERVED_9,
USER_PACKET_ENUM
}
public enum Rust : byte {
Welcome = 1,
Auth = 2,
Approved = 3,
Ready = 4,
Entities = 5,
EntityDestroy = 6,
GroupChange = 7,
GroupDestroy = 8,
RPCMessage = 9,
EntityPosition = 10,
ConsoleMessage = 11,
ConsoleCommand = 12,
Effect = 13,
DisconnectReason = 14,
Tick = 15,
Message = 16,
RequestUserInformation = 17,
GiveUserInformation = 18,
GroupEnter = 19,
GroupLeave = 20,
Last = 20
}
public enum PacketType : byte {
NONE = 255,
RAKNET = 0,
RUST = 140
}
#endregion
public MemoryStream baseStream = new MemoryStream();
public ulong incomingGUID;
public int incomingLength;
public byte packetID;
public Rust rustID {
get { return (Rust)packetID; }
}
public PacketType type = PacketType.NONE;
public long delay = 0;
internal bool Send(RakNetPeer peer, ulong guid) {
peer.SendStart();
peer.WriteBytes(baseStream.ToArray(), 0, incomingLength);
peer.SendTo(guid, RakNetPeer.Priority.Medium, RakNetPeer.SendMethod.Reliable, 0);
return true;
}
public string GetName() {
return type == PacketType.RAKNET ? Enum.GetName(typeof(RakNet), packetID) : Enum.GetName(typeof(Rust), packetID);
}
public string GetPacketTypeName() {
return type == PacketType.RAKNET ? "RAKNET" : "RUST";
}
public override string ToString() {
return string.Format("PacketOrigin: {0}\nPacketType: {1}\nPacketName: {2}\nPacketID: {3}\nPacketLength: {4}", GetOrigin(), GetPacketTypeName(), GetName(), packetID, incomingLength);
}
internal bool Receive(RakNetPeer peer) {
incomingLength = peer.incomingBytes;
incomingGUID = peer.incomingGUID;
Position = 0;
MemoryStream mem = peer.ReadBytes(incomingLength);
mem.Position = 0;
mem.WriteTo(baseStream);
SetLength(incomingLength);
Position = 0;
packetID = UInt8();
type = packetID < 140 ? PacketType.RAKNET : PacketType.RUST;
packetID -= (byte)type;
return true;
}
internal void Clear() {
Position = 0;
SetLength(0);
packetID = 0;
incomingLength = 0;
type = PacketType.NONE;
}
public static string GetOrigin(ulong guid) {
return string.Format("{0}", guid == RustInterceptor.clientGUID ? "Client" : "Server");
}
public static string GetOrigin(Packet packet) {
return GetOrigin(packet.incomingGUID);
}
public string GetOrigin() {
return GetOrigin(incomingGUID);
}
internal Packet Clone() {
var ret = new Packet();
ret.incomingGUID = incomingGUID;
ret.incomingLength = incomingLength;
ret.packetID = packetID;
ret.type = type;
ret.baseStream.Position = 0;
ret.baseStream.Write(baseStream.ToArray(), 0, incomingLength);
ret.Position = 1;
return ret;
}
/* Packet Stream Reader */
public override long Position {
get {
return baseStream.Position;
}
set { baseStream.Position = value; }
}
public override long Length {
get {
return incomingLength;
}
}
public override bool CanRead {
get {
return true;
}
}
public override bool CanSeek {
get {
return true;
}
}
public override bool CanWrite {
get {
return true;
}
}
public int length {
get {
return (int)baseStream.Length;
}
}
public int position {
get { return (int)baseStream.Position; }
}
public int unread {
get { return (int)(incomingLength - baseStream.Position); }
}
public override void Write(byte[] buffer, int offset, int count) {
baseStream.Write(buffer, offset, count);
}
public void WriteTo(Stream stream) {
var packet = (Packet)stream;
packet.Clear();
baseStream.WriteTo(packet);
}
public override void Flush() {
baseStream.Flush();
}
public override int ReadByte() {
if (baseStream.Position == Length)
return -1;
return (int)baseStream.ReadByte();
}
public override long Seek(long offset, SeekOrigin origin) {
return baseStream.Seek(offset, origin);
}
public override void SetLength(long value) {
baseStream.SetLength(value);
}
public byte UInt8() {
return (byte)ReadByte();
}
public bool Bit() {
return UInt8() > 0U;
}
public sbyte Int8() {
return (sbyte)UInt8();
}
public long Int64() {
return BitConverter.ToInt64(Read(8), 0);
}
public int Int32() {
return BitConverter.ToInt32(Read(4), 0);
}
public short Int16() {
return BitConverter.ToInt16(Read(2), 0);
}
public ulong UInt64() {
return BitConverter.ToUInt64(Read(8), 0);
}
public uint UInt32() {
return BitConverter.ToUInt32(Read(4), 0);
}
public ushort UInt16() {
return BitConverter.ToUInt16(Read(2), 0);
}
public float Float(bool unused = false) {
return BitConverter.ToSingle(Read(4), 0);
}
public double Double() {
return BitConverter.ToDouble(Read(8), 0);
}
public byte[] Read(int size) {
byte[] data = new byte[size];
baseStream.Read(data, 0, size);
if (!BitConverter.IsLittleEndian && data.Length > 1) Array.Reverse(data);
return data;
}
public override int Read(byte[] buffer, int offset, int count) {
return baseStream.Read(buffer, offset, count);
}
public byte[] BytesWithSize() {
uint num = UInt32();
if (num == 0)
return null;
if (num > 10485760U)
return null;
byte[] buffer = new byte[num];
if (baseStream.Read(buffer, 0, (int)num) != num)
return (byte[])null;
return buffer;
}
public string String() {
byte[] bytes = BytesWithSize();
if (bytes == null)
return string.Empty;
return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
public uint EntityID() {
return this.UInt32();
}
public uint GroupID() {
return this.UInt32();
}
public UnityEngine.Vector3 Vector3(bool compressed = false) {
return new UnityEngine.Vector3(this.Float(compressed), this.Float(compressed), this.Float(compressed));
}
public UnityEngine.Ray Ray() {
return new UnityEngine.Ray(this.Vector3(false), this.Vector3(false));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Pipes.Tests
{
/// <summary>
/// Tests that cover Write and WriteAsync behaviors that are shared between
/// AnonymousPipes and NamedPipes
/// </summary>
public abstract class PipeTest_Write : PipeTestBase
{
[Fact]
public void WriteWithNullBuffer_Throws_ArgumentNullException()
{
using (ServerClientPair pair = CreateServerClientPair())
{
PipeStream pipe = pair.writeablePipe;
Assert.True(pipe.IsConnected);
Assert.True(pipe.CanWrite);
// Null is an invalid Buffer
Assert.Throws<ArgumentNullException>("buffer", () => pipe.Write(null, 0, 1));
Assert.Throws<ArgumentNullException>("buffer", () => { pipe.WriteAsync(null, 0, 1); });
// Buffer validity is checked before Offset
Assert.Throws<ArgumentNullException>("buffer", () => pipe.Write(null, -1, 1));
Assert.Throws<ArgumentNullException>("buffer", () => { pipe.WriteAsync(null, -1, 1); });
// Buffer validity is checked before Count
Assert.Throws<ArgumentNullException>("buffer", () => pipe.Write(null, -1, -1));
Assert.Throws<ArgumentNullException>("buffer", () => { pipe.WriteAsync(null, -1, -1); });
}
}
[Fact]
public void WriteWithNegativeOffset_Throws_ArgumentOutOfRangeException()
{
using (ServerClientPair pair = CreateServerClientPair())
{
PipeStream pipe = pair.writeablePipe;
Assert.True(pipe.IsConnected);
Assert.True(pipe.CanWrite);
// Offset must be nonnegative
Assert.Throws<ArgumentOutOfRangeException>("offset", () => pipe.Write(new byte[5], -1, 1));
Assert.Throws<ArgumentOutOfRangeException>("offset", () => { pipe.WriteAsync(new byte[5], -1, 1); });
}
}
[Fact]
public void WriteWithNegativeCount_Throws_ArgumentOutOfRangeException()
{
using (ServerClientPair pair = CreateServerClientPair())
{
PipeStream pipe = pair.writeablePipe;
Assert.True(pipe.IsConnected);
Assert.True(pipe.CanWrite);
// Count must be nonnegative
Assert.Throws<ArgumentOutOfRangeException>("count", () => pipe.Write(new byte[5], 0, -1));
Assert.Throws<ArgumentOutOfRangeException>("count", () => { pipe.WriteAsync(new byte[5], 0, -1); });
}
}
[Fact]
public void WriteWithOutOfBoundsArray_Throws_ArgumentException()
{
using (ServerClientPair pair = CreateServerClientPair())
{
PipeStream pipe = pair.writeablePipe;
Assert.True(pipe.IsConnected);
Assert.True(pipe.CanWrite);
// offset out of bounds
Assert.Throws<ArgumentException>(null, () => pipe.Write(new byte[1], 1, 1));
// offset out of bounds for 0 count read
Assert.Throws<ArgumentException>(null, () => pipe.Write(new byte[1], 2, 0));
// offset out of bounds even for 0 length buffer
Assert.Throws<ArgumentException>(null, () => pipe.Write(new byte[0], 1, 0));
// combination offset and count out of bounds
Assert.Throws<ArgumentException>(null, () => pipe.Write(new byte[2], 1, 2));
// edges
Assert.Throws<ArgumentException>(null, () => pipe.Write(new byte[0], int.MaxValue, 0));
Assert.Throws<ArgumentException>(null, () => pipe.Write(new byte[0], int.MaxValue, int.MaxValue));
Assert.Throws<ArgumentException>(() => pipe.Write(new byte[5], 3, 4));
// offset out of bounds
Assert.Throws<ArgumentException>(null, () => { pipe.WriteAsync(new byte[1], 1, 1); });
// offset out of bounds for 0 count read
Assert.Throws<ArgumentException>(null, () => { pipe.WriteAsync(new byte[1], 2, 0); });
// offset out of bounds even for 0 length buffer
Assert.Throws<ArgumentException>(null, () => { pipe.WriteAsync(new byte[0], 1, 0); });
// combination offset and count out of bounds
Assert.Throws<ArgumentException>(null, () => { pipe.WriteAsync(new byte[2], 1, 2); });
// edges
Assert.Throws<ArgumentException>(null, () => { pipe.WriteAsync(new byte[0], int.MaxValue, 0); });
Assert.Throws<ArgumentException>(null, () => { pipe.WriteAsync(new byte[0], int.MaxValue, int.MaxValue); });
Assert.Throws<ArgumentException>(() => { pipe.WriteAsync(new byte[5], 3, 4); });
}
}
[Fact]
public virtual void ReadOnWriteOnlyPipe_Throws_NotSupportedException()
{
using (ServerClientPair pair = CreateServerClientPair())
{
PipeStream pipe = pair.writeablePipe;
Assert.True(pipe.IsConnected);
Assert.False(pipe.CanRead);
Assert.Throws<NotSupportedException>(() => pipe.Read(new byte[9], 0, 5));
Assert.Throws<NotSupportedException>(() => pipe.ReadByte());
Assert.Throws<NotSupportedException>(() => pipe.InBufferSize);
Assert.Throws<NotSupportedException>(() => { pipe.ReadAsync(new byte[10], 0, 5); });
}
}
[Fact]
public async Task WriteZeroLengthBuffer_Nop()
{
using (ServerClientPair pair = CreateServerClientPair())
{
PipeStream pipe = pair.writeablePipe;
// Shouldn't throw
pipe.Write(Array.Empty<byte>(), 0, 0);
Task writeTask = pipe.WriteAsync(Array.Empty<byte>(), 0, 0);
await writeTask;
}
}
[Fact]
public void WritePipeUnsupportedMembers_Throws_NotSupportedException()
{
using (ServerClientPair pair = CreateServerClientPair())
{
PipeStream pipe = pair.writeablePipe;
Assert.True(pipe.IsConnected);
Assert.Throws<NotSupportedException>(() => pipe.Length);
Assert.Throws<NotSupportedException>(() => pipe.SetLength(10L));
Assert.Throws<NotSupportedException>(() => pipe.Position);
Assert.Throws<NotSupportedException>(() => pipe.Position = 10L);
Assert.Throws<NotSupportedException>(() => pipe.Seek(10L, System.IO.SeekOrigin.Begin));
}
}
[Fact]
public void WriteToDisposedWriteablePipe_Throws_ObjectDisposedException()
{
using (ServerClientPair pair = CreateServerClientPair())
{
PipeStream pipe = pair.writeablePipe;
pipe.Dispose();
byte[] buffer = new byte[] { 0, 0, 0, 0 };
Assert.Throws<ObjectDisposedException>(() => pipe.Write(buffer, 0, buffer.Length));
Assert.Throws<ObjectDisposedException>(() => pipe.WriteByte(5));
Assert.Throws<ObjectDisposedException>(() => { pipe.WriteAsync(buffer, 0, buffer.Length); });
Assert.Throws<ObjectDisposedException>(() => pipe.Flush());
Assert.Throws<ObjectDisposedException>(() => pipe.IsMessageComplete);
Assert.Throws<ObjectDisposedException>(() => pipe.ReadMode);
}
}
[Fact]
public virtual void WriteToPipeWithClosedPartner_Throws_IOException()
{
using (ServerClientPair pair = CreateServerClientPair())
{
pair.readablePipe.Dispose();
byte[] buffer = new byte[] { 0, 0, 0, 0 };
Assert.Throws<IOException>(() => pair.writeablePipe.Write(buffer, 0, buffer.Length));
Assert.Throws<IOException>(() => pair.writeablePipe.WriteByte(123));
Assert.Throws<IOException>(() => { pair.writeablePipe.WriteAsync(buffer, 0, buffer.Length); });
Assert.Throws<IOException>(() => pair.writeablePipe.Flush());
}
}
[Fact]
public async Task ValidFlush_DoesntThrow()
{
using (ServerClientPair pair = CreateServerClientPair())
{
Task write = Task.Run(() => pair.writeablePipe.WriteByte(123));
pair.writeablePipe.Flush();
Assert.Equal(123, pair.readablePipe.ReadByte());
await write;
await pair.writeablePipe.FlushAsync();
}
}
}
}
| |
//
// Copyright (c) 2004-2020 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.
//
namespace NLog.LayoutRenderers
{
using System;
using System.ComponentModel;
using System.IO;
using System.Text;
using NLog.Config;
using NLog.Internal;
/// <summary>
/// The call site (class name, method name and source information).
/// </summary>
[LayoutRenderer("callsite")]
[ThreadAgnostic]
[ThreadSafe]
public class CallSiteLayoutRenderer : LayoutRenderer, IUsesStackTrace
{
/// <summary>
/// Initializes a new instance of the <see cref="CallSiteLayoutRenderer" /> class.
/// </summary>
public CallSiteLayoutRenderer()
{
ClassName = true;
MethodName = true;
CleanNamesOfAnonymousDelegates = false;
IncludeNamespace = true;
#if !SILVERLIGHT
FileName = false;
IncludeSourcePath = true;
#endif
}
/// <summary>
/// Gets or sets a value indicating whether to render the class name.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(true)]
public bool ClassName { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to render the include the namespace with <see cref="ClassName"/>.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(true)]
public bool IncludeNamespace { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to render the method name.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(true)]
public bool MethodName { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the method name will be cleaned up if it is detected as an anonymous delegate.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(false)]
public bool CleanNamesOfAnonymousDelegates { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the method and class names will be cleaned up if it is detected as an async continuation
/// (everything after an await-statement inside of an async method).
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(false)]
public bool CleanNamesOfAsyncContinuations { get; set; }
/// <summary>
/// Gets or sets the number of frames to skip.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(0)]
public int SkipFrames { get; set; }
#if !SILVERLIGHT
/// <summary>
/// Gets or sets a value indicating whether to render the source file name and line number.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(false)]
public bool FileName { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to include source file path.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(true)]
public bool IncludeSourcePath { get; set; }
#endif
/// <summary>
/// Gets the level of stack trace information required by the implementing class.
/// </summary>
StackTraceUsage IUsesStackTrace.StackTraceUsage
{
get
{
#if !SILVERLIGHT
if (FileName)
{
return StackTraceUsage.Max;
}
#endif
return StackTraceUsage.WithoutSource;
}
}
/// <summary>
/// Renders the call site and appends it to the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="logEvent">Logging event.</param>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
if (logEvent.CallSiteInformation != null)
{
if (ClassName || MethodName)
{
var method = logEvent.CallSiteInformation.GetCallerStackFrameMethod(SkipFrames);
if (ClassName)
{
string className = logEvent.CallSiteInformation.GetCallerClassName(method, IncludeNamespace, CleanNamesOfAsyncContinuations, CleanNamesOfAnonymousDelegates);
if (string.IsNullOrEmpty(className))
className = "<no type>";
builder.Append(className);
}
if (MethodName)
{
string methodName = logEvent.CallSiteInformation.GetCallerMemberName(method, false, CleanNamesOfAsyncContinuations, CleanNamesOfAnonymousDelegates);
if (string.IsNullOrEmpty(methodName))
methodName = "<no method>";
if (ClassName)
{
builder.Append(".");
}
builder.Append(methodName);
}
}
#if !SILVERLIGHT
if (FileName)
{
string fileName = logEvent.CallSiteInformation.GetCallerFilePath(SkipFrames);
if (!string.IsNullOrEmpty(fileName))
{
int lineNumber = logEvent.CallSiteInformation.GetCallerLineNumber(SkipFrames);
AppendFileName(builder, fileName, lineNumber);
}
}
#endif
}
}
#if !SILVERLIGHT
private void AppendFileName(StringBuilder builder, string fileName, int lineNumber)
{
builder.Append("(");
if (IncludeSourcePath)
{
builder.Append(fileName);
}
else
{
builder.Append(Path.GetFileName(fileName));
}
builder.Append(":");
builder.AppendInvariant(lineNumber);
builder.Append(")");
}
#endif
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: StringBuilder.cs
//
// 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 Dot42;
using Dot42.Internal;
using Java.Lang;
using Java.Text;
using Java.Util;
namespace System.Text
{
partial class StringBuilder
{
/// <summary>
/// Initialize a new instance with given initial and maximum capacity.
/// </summary>
/// <remarks>
/// The maximum capacity is not used in this implementation.</remarks>
/// <param name="capacity"></param>
/// <param name="maxCapacity"></param>
public StringBuilder(int capacity, int maxCapacity)
: this(capacity)
{
if ((maxCapacity < 1) || (capacity < 1) || (capacity > maxCapacity))
throw new ArgumentOutOfRangeException();
}
/// <summary>
/// Initialize a new instance with given initial value and capacity.
/// </summary>
public StringBuilder(string value, int capacity)
: this(capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException();
Append(value);
}
/// <summary>
/// Initialize a new instance with given substring of the given value and capacity.
/// </summary>
public StringBuilder(string value, int startIndex, int length, int capacity)
: this(capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException();
if (value != null)
{
if ((startIndex < 0) || (length < 0) || (startIndex + length > value.Length))
throw new ArgumentOutOfRangeException();
JavaAppend(value, startIndex, startIndex + length);
}
}
/// <summary>
/// Append a given number of the given characters.
/// </summary>
public StringBuilder Append(char value, int repeatCount)
{
// TODO: check if the allocation is more expensive than a simple while loop
char[] append = new char[repeatCount];
Arrays.Fill(append, value);
Append(append);
return this;
}
/// <summary>
/// Append a substring of the given string from into this builder.
/// </summary>
[Inline]
public StringBuilder Append(string value, int startIndex, int count)
{
JavaAppend(value, startIndex, startIndex + count);
return this;
}
/// <summary>
/// Append a substring of the given string from into this builder.
/// </summary>
public StringBuilder AppendFormat(string format, params object[] args)
{
Append(string.Format(format, args));
return this;
}
/// <summary>
/// Appends the default line terminator to the end of the current StringBuilder object.
/// </summary>
public StringBuilder AppendLine()
{
return Append(Environment.NewLine);
}
/// <summary>
/// Appends a copy of the specified string followed by the default line terminator to the end of the current StringBuilder object.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public StringBuilder AppendLine(string value)
{
Append(value);
return AppendLine();
}
/// <summary>
/// Insert the one or more copies of the given string at the given index in this string builder.
/// </summary>
public StringBuilder Insert(int index, string value, int count)
{
var length = value.Length;
while (count > 0)
{
JavaInsert(index, value, 0, length);
count--;
}
return this;
}
/// <summary>
/// Remove length characters from this string builder, starting at the given start index.
/// </summary>
[Inline]
public StringBuilder Remove(int startIndex, int length)
{
JavaDelete(startIndex, startIndex + length);
return this;
}
/// <summary>
/// Replace all occurrences of the given old character with the given new character.
/// </summary>
public StringBuilder Replace(char oldChar, char newChar)
{
var length = Length;
for (var i = 0; i < length; i++)
{
if (this[i] == oldChar)
{
SetCharAt(i, newChar);
}
}
return this;
}
/// <summary>
/// Replace all occurrences of the given old character with the given new character.
/// </summary>
public StringBuilder Replace(char oldChar, char newChar, int startIndex, int count)
{
if (startIndex < 0)
throw new ArgumentOutOfRangeException("startIndex");
if (count < 0)
throw new ArgumentOutOfRangeException("count");
if (startIndex + count > Length)
throw new ArgumentOutOfRangeException("overflow");
for (var i = 0; i < count; i++)
{
if (this[startIndex + i] == oldChar)
{
SetCharAt(startIndex + i, newChar);
}
}
return this;
}
/// <summary>
/// Replace all occurrences of the given old string with the given new string.
/// </summary>
public StringBuilder Replace(string oldValue, string newValue)
{
if (oldValue == null)
throw new ArgumentNullException("oldValue");
if (oldValue.Length == 0)
throw new ArgumentException("oldValue is empty");
var start = 0;
int index;
while ((index = IndexOf(oldValue, start)) >= 0)
{
Remove(index, oldValue.Length);
start = index;
if (!string.IsNullOrEmpty(newValue))
{
Insert(index, newValue);
start += newValue.Length;
}
}
return this;
}
/// <summary>
/// Replace all occurrences of the given old string with the given new string.
/// </summary>
public StringBuilder Replace(string oldValue, string newValue, int startIndex, int count)
{
if (oldValue == null)
throw new ArgumentNullException("oldValue");
if (oldValue.Length == 0)
throw new ArgumentException("oldValue is empty");
if (startIndex < 0)
throw new ArgumentOutOfRangeException("startIndex");
if (count < 0)
throw new ArgumentOutOfRangeException("count");
if ((startIndex + count > Length) || (startIndex + count < 0))
throw new ArgumentOutOfRangeException("overflow");
var start = startIndex;
int index;
while ((index = IndexOf(oldValue, start)) >= 0)
{
if (index >= startIndex + count)
break;
Remove(index, oldValue.Length);
start = index;
if (!string.IsNullOrEmpty(newValue))
{
Insert(index, newValue);
start += newValue.Length;
}
}
return this;
}
/// <summary>
/// Gets the maximum capacity of this builder.
/// </summary>
public int MaxCapacity
{
get { return int.MaxValue; }
}
/// <summary>
/// Return a substring of this instance.
/// </summary>
public string ToString(int startIndex, int length)
{
if (startIndex < 0)
throw new ArgumentOutOfRangeException("startIndex");
if (length < 0)
throw new ArgumentOutOfRangeException("length");
if ((startIndex + length > Length) || (startIndex + length < 0))
throw new ArgumentOutOfRangeException("overflow");
return JavaSubstring(startIndex, startIndex + length);
}
/// <summary>
/// Returns the number of chars in this string.
/// </summary>
public int Length
{
[Dot42.DexImport("length", "()I", AccessFlags = 257)]
get { return default(int); }
[Dot42.DexImport("setLength", "(I)V", AccessFlags = 1)]
set { }
}
/// <summary>
/// Returns the char at index.
/// </summary>
[global::System.Runtime.CompilerServices.IndexerName("Chars")]
public char this[int index]
{
[Dot42.DexImport("charAt", "(I)C", AccessFlags = 1)]
get { return default(char); }
[Dot42.DexImport("setCharAt", "(IC)V", AccessFlags = 1)]
set { }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using SimpleContainer.Configuration;
using SimpleContainer.Interface;
using SimpleContainer.Tests.Helpers;
namespace SimpleContainer.Tests
{
public abstract class FactoryConfiguration: SimpleContainerTestBase
{
public class ExplicitDelegateFactoryWithEnumerableInjection : FactoryConfiguration
{
public class A
{
public readonly IEnumerable<IX> instances;
public A(IEnumerable<IX> instances)
{
this.instances = instances;
}
}
public interface IX
{
}
public class X : IX
{
public readonly Type target;
public X(Type target)
{
this.target = target;
}
}
[Test]
public void Test()
{
var container = Container(b => b.Bind<IX>((c, t) => new X(t)));
Assert.That(container.Get<A>().instances.Cast<X>().Single().target, Is.EqualTo(typeof(A)));
}
}
public class FactoryDependantOnServiceType : FactoryConfiguration
{
public class ChildService
{
public ChildService(Type parentService)
{
ParentService = parentService;
}
public Type ParentService { get; private set; }
}
public class SomeService
{
public SomeService(ChildService childService)
{
ChildService = childService;
}
public ChildService ChildService { get; private set; }
}
[Test]
public void Test()
{
var container = Container(b => b.Bind((c, t) => new ChildService(t)));
Assert.That(container.Get<SomeService>().ChildService.ParentService, Is.EqualTo(typeof (SomeService)));
Assert.That(container.Get<ChildService>().ParentService, Is.Null);
}
}
public class FactoryWithServiceNotOwnByContainer : FactoryConfiguration
{
[Test]
public void Test()
{
var container = Container(b => b.Bind(c => new A(), false));
container.Get<A>();
container.Dispose();
Assert.That(A.disposeCallCount, Is.EqualTo(0));
}
public class A : IDisposable
{
public static int disposeCallCount;
public void Dispose()
{
disposeCallCount++;
}
}
}
public class FactoryDependantOnServiceTypeCalledOnlyOnceForEachTarget : FactoryConfiguration
{
[Test]
public void Test()
{
var callLog = new StringBuilder();
var container = Container(b => b.Bind((c, t) =>
{
callLog.AppendFormat("create for {0} ", t.Name);
return new A(t);
}));
var createTarget1 = container.Get<Func<Target1>>();
var createTarget2 = container.Get<Func<Target2>>();
Assert.That(callLog.ToString(), Is.EqualTo(""));
Assert.That(createTarget1().a.Target, Is.EqualTo(typeof(Target1)));
Assert.That(callLog.ToString(), Is.EqualTo("create for Target1 "));
Assert.That(createTarget1().a.Target, Is.EqualTo(typeof(Target1)));
Assert.That(callLog.ToString(), Is.EqualTo("create for Target1 "));
Assert.That(createTarget2().a.Target, Is.EqualTo(typeof(Target2)));
Assert.That(callLog.ToString(), Is.EqualTo("create for Target1 create for Target2 "));
Assert.That(createTarget2().a.Target, Is.EqualTo(typeof(Target2)));
Assert.That(callLog.ToString(), Is.EqualTo("create for Target1 create for Target2 "));
}
public class Target1
{
public readonly A a;
public Target1(A a)
{
this.a = a;
}
}
public class Target2
{
public readonly A a;
public Target2(A a)
{
this.a = a;
}
}
public class A
{
public Type Target { get; set; }
public A(Type target)
{
Target = target;
}
}
}
public class CanInjectStructViaExplicitConfiguration : FactoryConfiguration
{
public class A
{
public readonly Token token;
public A(Token token)
{
this.token = token;
}
}
public struct Token
{
public int value;
}
public class TokenSource
{
public Token CreateToken()
{
return new Token { value = 78 };
}
}
public class TokenConfigurator : IServiceConfigurator<Token>
{
public void Configure(ConfigurationContext context, ServiceConfigurationBuilder<Token> builder)
{
builder.Bind(c => c.Get<TokenSource>().CreateToken());
}
}
[Test]
public void Test()
{
var container = Container();
Assert.That(container.Get<A>().token.value, Is.EqualTo(78));
}
}
public class CanBindFactoryViaServiceConfigurator : FactoryConfiguration
{
public class A
{
public readonly B b;
public A(B b)
{
this.b = b;
}
}
public class B
{
public readonly Type ownerType;
public B(Type ownerType)
{
this.ownerType = ownerType;
}
}
public class AConfigurator : IServiceConfigurator<B>
{
public void Configure(ConfigurationContext context, ServiceConfigurationBuilder<B> builder)
{
builder.Bind((c, t) => new B(t));
}
}
[Test]
public void Test()
{
var container = Container();
var a = container.Get<A>();
Assert.That(a.b.ownerType, Is.EqualTo(typeof(A)));
}
}
public class ImplementationWithExplicitDelegateFactory : FactoryConfiguration
{
[Test]
public void Test()
{
var impl = new Impl();
var container = Container(x => x.Bind<IInterface>(c => impl));
Assert.That(container.Get<IInterface>(), Is.SameAs(impl));
}
public interface IInterface
{
}
public class Impl : IInterface
{
}
}
public class LastConfigurationWins : FactoryConfiguration
{
public class A
{
public readonly B parameter;
public A(B parameter)
{
this.parameter = parameter;
}
}
public class B
{
public int value;
}
[Test]
public void Test()
{
var container = Container(delegate(ContainerConfigurationBuilder b)
{
b.Bind(c => new B { value = 1 });
b.Bind<B>(new B { value = 2 });
});
Assert.That(container.Get<A>().parameter.value, Is.EqualTo(2));
}
}
public class HandleGracefullyFactoryCrash : FactoryConfiguration
{
[Test]
public void Test()
{
var container = Container(b => b.Bind<A>(c => { throw new InvalidOperationException("my test crash"); }));
var error = Assert.Throws<SimpleContainerException>(() => container.Get<AWrap>());
Assert.That(error.Message, Is.EqualTo(TestHelpers.FormatMessage(@"
service [A] construction exception
!AWrap
!A <---------------")));
Assert.That(error.InnerException, Is.InstanceOf<InvalidOperationException>());
Assert.That(error.InnerException.Message, Is.EqualTo("my test crash"));
}
public class AWrap
{
public readonly A a;
public AWrap(A a)
{
this.a = a;
}
}
public class A
{
}
}
public class HandleGracefullyFactoryWithTargetCrash : FactoryConfiguration
{
[Test]
public void Test()
{
var container = Container(b => b.Bind<A>((c, t) => { throw new InvalidOperationException("my test crash"); }));
var error = Assert.Throws<SimpleContainerException>(() => container.Get<AWrap>());
Assert.That(error.Message, Is.EqualTo(TestHelpers.FormatMessage(@"
service [A] construction exception
!AWrap
!A <---------------")));
Assert.That(error.InnerException, Is.InstanceOf<InvalidOperationException>());
Assert.That(error.InnerException.Message, Is.EqualTo("my test crash"));
}
public class AWrap
{
public readonly A a;
public AWrap(A a)
{
this.a = a;
}
}
public class A
{
}
}
public class HandleGracefullyDependencyFactoryCrash : FactoryConfiguration
{
[Test]
public void Test()
{
var container = Container(b => b.BindDependencyFactory<AWrap>("a",
_ => { throw new InvalidOperationException("my test crash"); }));
var error = Assert.Throws<SimpleContainerException>(() => container.Get<AWrap>());
Assert.That(error.Message, Is.EqualTo(TestHelpers.FormatMessage(@"
service [A] construction exception
!AWrap
!a <---------------")));
Assert.That(error.InnerException, Is.InstanceOf<InvalidOperationException>());
Assert.That(error.InnerException.Message, Is.EqualTo("my test crash"));
}
public class AWrap
{
public readonly A a;
public AWrap(A a)
{
this.a = a;
}
}
public class A
{
}
}
public class CanRefuseToCreateServiceFromFactory : FactoryConfiguration
{
[Test]
public void Test()
{
var container = Container(b => b.Bind<A>(c => { throw new ServiceCouldNotBeCreatedException("test refused"); }));
var resolvedWrap = container.Resolve<AWrap>();
Assert.That(resolvedWrap.Single().a, Is.Null);
Assert.That(resolvedWrap.GetConstructionLog(), Is.EqualTo(TestHelpers.FormatMessage(@"
AWrap
A - test refused -> <null>")));
}
public class AWrap
{
public readonly A a;
public AWrap(A a = null)
{
this.a = a;
}
}
public class A
{
}
}
}
}
| |
/*
* Copyright (c) 2006-2016, openmetaverse.co
* 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.
* - Neither the name of the openmetaverse.co 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;
using System.Runtime.InteropServices;
using System.Globalization;
namespace OpenMetaverse
{
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Vector4 : IComparable<Vector4>, IEquatable<Vector4>
{
/// <summary>X value</summary>
public float X;
/// <summary>Y value</summary>
public float Y;
/// <summary>Z value</summary>
public float Z;
/// <summary>W value</summary>
public float W;
#region Constructors
public Vector4(float x, float y, float z, float w)
{
X = x;
Y = y;
Z = z;
W = w;
}
public Vector4(Vector2 value, float z, float w)
{
X = value.X;
Y = value.Y;
Z = z;
W = w;
}
public Vector4(Vector3 value, float w)
{
X = value.X;
Y = value.Y;
Z = value.Z;
W = w;
}
public Vector4(float value)
{
X = value;
Y = value;
Z = value;
W = value;
}
/// <summary>
/// Constructor, builds a vector from a byte array
/// </summary>
/// <param name="byteArray">Byte array containing four four-byte floats</param>
/// <param name="pos">Beginning position in the byte array</param>
public Vector4(byte[] byteArray, int pos)
{
X = Y = Z = W = 0f;
FromBytes(byteArray, pos);
}
public Vector4(Vector4 value)
{
X = value.X;
Y = value.Y;
Z = value.Z;
W = value.W;
}
#endregion Constructors
#region Public Methods
public float Length()
{
return (float)Math.Sqrt(DistanceSquared(this, Zero));
}
public float LengthSquared()
{
return DistanceSquared(this, Zero);
}
public void Normalize()
{
this = Normalize(this);
}
/// <summary>
/// Test if this vector is equal to another vector, within a given
/// tolerance range
/// </summary>
/// <param name="vec">Vector to test against</param>
/// <param name="tolerance">The acceptable magnitude of difference
/// between the two vectors</param>
/// <returns>True if the magnitude of difference between the two vectors
/// is less than the given tolerance, otherwise false</returns>
public bool ApproxEquals(Vector4 vec, float tolerance)
{
Vector4 diff = this - vec;
return (diff.LengthSquared() <= tolerance * tolerance);
}
/// <summary>
/// IComparable.CompareTo implementation
/// </summary>
public int CompareTo(Vector4 vector)
{
return Length().CompareTo(vector.Length());
}
/// <summary>
/// Test if this vector is composed of all finite numbers
/// </summary>
public bool IsFinite()
{
return (Utils.IsFinite(X) && Utils.IsFinite(Y) && Utils.IsFinite(Z) && Utils.IsFinite(W));
}
/// <summary>
/// Builds a vector from a byte array
/// </summary>
/// <param name="byteArray">Byte array containing a 16 byte vector</param>
/// <param name="pos">Beginning position in the byte array</param>
public void FromBytes(byte[] byteArray, int pos)
{
if (!BitConverter.IsLittleEndian)
{
// Big endian architecture
byte[] conversionBuffer = new byte[16];
Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 16);
Array.Reverse(conversionBuffer, 0, 4);
Array.Reverse(conversionBuffer, 4, 4);
Array.Reverse(conversionBuffer, 8, 4);
Array.Reverse(conversionBuffer, 12, 4);
X = BitConverter.ToSingle(conversionBuffer, 0);
Y = BitConverter.ToSingle(conversionBuffer, 4);
Z = BitConverter.ToSingle(conversionBuffer, 8);
W = BitConverter.ToSingle(conversionBuffer, 12);
}
else
{
// Little endian architecture
X = BitConverter.ToSingle(byteArray, pos);
Y = BitConverter.ToSingle(byteArray, pos + 4);
Z = BitConverter.ToSingle(byteArray, pos + 8);
W = BitConverter.ToSingle(byteArray, pos + 12);
}
}
/// <summary>
/// Returns the raw bytes for this vector
/// </summary>
/// <returns>A 16 byte array containing X, Y, Z, and W</returns>
public byte[] GetBytes()
{
byte[] byteArray = new byte[16];
ToBytes(byteArray, 0);
return byteArray;
}
/// <summary>
/// Writes the raw bytes for this vector to a byte array
/// </summary>
/// <param name="dest">Destination byte array</param>
/// <param name="pos">Position in the destination array to start
/// writing. Must be at least 16 bytes before the end of the array</param>
public void ToBytes(byte[] dest, int pos)
{
Buffer.BlockCopy(BitConverter.GetBytes(X), 0, dest, pos + 0, 4);
Buffer.BlockCopy(BitConverter.GetBytes(Y), 0, dest, pos + 4, 4);
Buffer.BlockCopy(BitConverter.GetBytes(Z), 0, dest, pos + 8, 4);
Buffer.BlockCopy(BitConverter.GetBytes(W), 0, dest, pos + 12, 4);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(dest, pos + 0, 4);
Array.Reverse(dest, pos + 4, 4);
Array.Reverse(dest, pos + 8, 4);
Array.Reverse(dest, pos + 12, 4);
}
}
#endregion Public Methods
#region Static Methods
public static Vector4 Add(Vector4 value1, Vector4 value2)
{
value1.W += value2.W;
value1.X += value2.X;
value1.Y += value2.Y;
value1.Z += value2.Z;
return value1;
}
public static Vector4 Clamp(Vector4 value1, Vector4 min, Vector4 max)
{
return new Vector4(
Utils.Clamp(value1.X, min.X, max.X),
Utils.Clamp(value1.Y, min.Y, max.Y),
Utils.Clamp(value1.Z, min.Z, max.Z),
Utils.Clamp(value1.W, min.W, max.W));
}
public static float Distance(Vector4 value1, Vector4 value2)
{
return (float)Math.Sqrt(DistanceSquared(value1, value2));
}
public static float DistanceSquared(Vector4 value1, Vector4 value2)
{
return
(value1.W - value2.W) * (value1.W - value2.W) +
(value1.X - value2.X) * (value1.X - value2.X) +
(value1.Y - value2.Y) * (value1.Y - value2.Y) +
(value1.Z - value2.Z) * (value1.Z - value2.Z);
}
public static Vector4 Divide(Vector4 value1, Vector4 value2)
{
value1.W /= value2.W;
value1.X /= value2.X;
value1.Y /= value2.Y;
value1.Z /= value2.Z;
return value1;
}
public static Vector4 Divide(Vector4 value1, float divider)
{
float factor = 1f / divider;
value1.W *= factor;
value1.X *= factor;
value1.Y *= factor;
value1.Z *= factor;
return value1;
}
public static float Dot(Vector4 vector1, Vector4 vector2)
{
return vector1.X * vector2.X + vector1.Y * vector2.Y + vector1.Z * vector2.Z + vector1.W * vector2.W;
}
public static Vector4 Lerp(Vector4 value1, Vector4 value2, float amount)
{
return new Vector4(
Utils.Lerp(value1.X, value2.X, amount),
Utils.Lerp(value1.Y, value2.Y, amount),
Utils.Lerp(value1.Z, value2.Z, amount),
Utils.Lerp(value1.W, value2.W, amount));
}
public static Vector4 Max(Vector4 value1, Vector4 value2)
{
return new Vector4(
Math.Max(value1.X, value2.X),
Math.Max(value1.Y, value2.Y),
Math.Max(value1.Z, value2.Z),
Math.Max(value1.W, value2.W));
}
public static Vector4 Min(Vector4 value1, Vector4 value2)
{
return new Vector4(
Math.Min(value1.X, value2.X),
Math.Min(value1.Y, value2.Y),
Math.Min(value1.Z, value2.Z),
Math.Min(value1.W, value2.W));
}
public static Vector4 Multiply(Vector4 value1, Vector4 value2)
{
value1.W *= value2.W;
value1.X *= value2.X;
value1.Y *= value2.Y;
value1.Z *= value2.Z;
return value1;
}
public static Vector4 Multiply(Vector4 value1, float scaleFactor)
{
value1.W *= scaleFactor;
value1.X *= scaleFactor;
value1.Y *= scaleFactor;
value1.Z *= scaleFactor;
return value1;
}
public static Vector4 Negate(Vector4 value)
{
value.X = -value.X;
value.Y = -value.Y;
value.Z = -value.Z;
value.W = -value.W;
return value;
}
public static Vector4 Normalize(Vector4 vector)
{
const float MAG_THRESHOLD = 0.0000001f;
float factor = DistanceSquared(vector, Zero);
if (factor > MAG_THRESHOLD)
{
factor = 1f / (float)Math.Sqrt(factor);
vector.X *= factor;
vector.Y *= factor;
vector.Z *= factor;
vector.W *= factor;
}
else
{
vector.X = 0f;
vector.Y = 0f;
vector.Z = 0f;
vector.W = 0f;
}
return vector;
}
public static Vector4 SmoothStep(Vector4 value1, Vector4 value2, float amount)
{
return new Vector4(
Utils.SmoothStep(value1.X, value2.X, amount),
Utils.SmoothStep(value1.Y, value2.Y, amount),
Utils.SmoothStep(value1.Z, value2.Z, amount),
Utils.SmoothStep(value1.W, value2.W, amount));
}
public static Vector4 Subtract(Vector4 value1, Vector4 value2)
{
value1.W -= value2.W;
value1.X -= value2.X;
value1.Y -= value2.Y;
value1.Z -= value2.Z;
return value1;
}
public static Vector4 Transform(Vector2 position, Matrix4 matrix)
{
return new Vector4(
(position.X * matrix.M11) + (position.Y * matrix.M21) + matrix.M41,
(position.X * matrix.M12) + (position.Y * matrix.M22) + matrix.M42,
(position.X * matrix.M13) + (position.Y * matrix.M23) + matrix.M43,
(position.X * matrix.M14) + (position.Y * matrix.M24) + matrix.M44);
}
public static Vector4 Transform(Vector3 position, Matrix4 matrix)
{
return new Vector4(
(position.X * matrix.M11) + (position.Y * matrix.M21) + (position.Z * matrix.M31) + matrix.M41,
(position.X * matrix.M12) + (position.Y * matrix.M22) + (position.Z * matrix.M32) + matrix.M42,
(position.X * matrix.M13) + (position.Y * matrix.M23) + (position.Z * matrix.M33) + matrix.M43,
(position.X * matrix.M14) + (position.Y * matrix.M24) + (position.Z * matrix.M34) + matrix.M44);
}
public static Vector4 Transform(Vector4 vector, Matrix4 matrix)
{
return new Vector4(
(vector.X * matrix.M11) + (vector.Y * matrix.M21) + (vector.Z * matrix.M31) + (vector.W * matrix.M41),
(vector.X * matrix.M12) + (vector.Y * matrix.M22) + (vector.Z * matrix.M32) + (vector.W * matrix.M42),
(vector.X * matrix.M13) + (vector.Y * matrix.M23) + (vector.Z * matrix.M33) + (vector.W * matrix.M43),
(vector.X * matrix.M14) + (vector.Y * matrix.M24) + (vector.Z * matrix.M34) + (vector.W * matrix.M44));
}
public static Vector4 Parse(string val)
{
char[] splitChar = { ',' };
string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar);
return new Vector4(
float.Parse(split[0].Trim(), Utils.EnUsCulture),
float.Parse(split[1].Trim(), Utils.EnUsCulture),
float.Parse(split[2].Trim(), Utils.EnUsCulture),
float.Parse(split[3].Trim(), Utils.EnUsCulture));
}
public static bool TryParse(string val, out Vector4 result)
{
try
{
result = Parse(val);
return true;
}
catch (Exception)
{
result = new Vector4();
return false;
}
}
#endregion Static Methods
#region Overrides
public override bool Equals(object obj)
{
return (obj is Vector4) ? this == (Vector4)obj : false;
}
public bool Equals(Vector4 other)
{
return W == other.W
&& X == other.X
&& Y == other.Y
&& Z == other.Z;
}
public override int GetHashCode()
{
return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode() ^ W.GetHashCode();
}
public override string ToString()
{
return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}, {3}>", X, Y, Z, W);
}
/// <summary>
/// Get a string representation of the vector elements with up to three
/// decimal digits and separated by spaces only
/// </summary>
/// <returns>Raw string representation of the vector</returns>
public string ToRawString()
{
CultureInfo enUs = new CultureInfo("en-us");
enUs.NumberFormat.NumberDecimalDigits = 3;
return String.Format(enUs, "{0} {1} {2} {3}", X, Y, Z, W);
}
#endregion Overrides
#region Operators
public static bool operator ==(Vector4 value1, Vector4 value2)
{
return value1.W == value2.W
&& value1.X == value2.X
&& value1.Y == value2.Y
&& value1.Z == value2.Z;
}
public static bool operator !=(Vector4 value1, Vector4 value2)
{
return !(value1 == value2);
}
public static Vector4 operator +(Vector4 value1, Vector4 value2)
{
value1.W += value2.W;
value1.X += value2.X;
value1.Y += value2.Y;
value1.Z += value2.Z;
return value1;
}
public static Vector4 operator -(Vector4 value)
{
return new Vector4(-value.X, -value.Y, -value.Z, -value.W);
}
public static Vector4 operator -(Vector4 value1, Vector4 value2)
{
value1.W -= value2.W;
value1.X -= value2.X;
value1.Y -= value2.Y;
value1.Z -= value2.Z;
return value1;
}
public static Vector4 operator *(Vector4 value1, Vector4 value2)
{
value1.W *= value2.W;
value1.X *= value2.X;
value1.Y *= value2.Y;
value1.Z *= value2.Z;
return value1;
}
public static Vector4 operator *(Vector4 value1, float scaleFactor)
{
value1.W *= scaleFactor;
value1.X *= scaleFactor;
value1.Y *= scaleFactor;
value1.Z *= scaleFactor;
return value1;
}
public static Vector4 operator /(Vector4 value1, Vector4 value2)
{
value1.W /= value2.W;
value1.X /= value2.X;
value1.Y /= value2.Y;
value1.Z /= value2.Z;
return value1;
}
public static Vector4 operator /(Vector4 value1, float divider)
{
float factor = 1f / divider;
value1.W *= factor;
value1.X *= factor;
value1.Y *= factor;
value1.Z *= factor;
return value1;
}
#endregion Operators
/// <summary>A vector with a value of 0,0,0,0</summary>
public readonly static Vector4 Zero = new Vector4();
/// <summary>A vector with a value of 1,1,1,1</summary>
public readonly static Vector4 One = new Vector4(1f, 1f, 1f, 1f);
/// <summary>A vector with a value of 1,0,0,0</summary>
public readonly static Vector4 UnitX = new Vector4(1f, 0f, 0f, 0f);
/// <summary>A vector with a value of 0,1,0,0</summary>
public readonly static Vector4 UnitY = new Vector4(0f, 1f, 0f, 0f);
/// <summary>A vector with a value of 0,0,1,0</summary>
public readonly static Vector4 UnitZ = new Vector4(0f, 0f, 1f, 0f);
/// <summary>A vector with a value of 0,0,0,1</summary>
public readonly static Vector4 UnitW = new Vector4(0f, 0f, 0f, 1f);
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using Trionic5Tools;
namespace Trionic5Controls
{
public partial class CompareResults : DevExpress.XtraEditors.XtraUserControl
{
public delegate void NotifySelectSymbol(object sender, SelectSymbolEventArgs e);
public event CompareResults.NotifySelectSymbol onSymbolSelect;
private AddressLookupCollection m_compareAddressLookupCollection = new AddressLookupCollection();
public AddressLookupCollection CompareAddressLookupCollection
{
get { return m_compareAddressLookupCollection; }
set { m_compareAddressLookupCollection = value; }
}
private SymbolCollection m_compareSymbolCollection = new SymbolCollection();
public SymbolCollection CompareSymbolCollection
{
get { return m_compareSymbolCollection; }
set { m_compareSymbolCollection = value; }
}
private Trionic5File m_ComparedTrionic5File = new Trionic5File();
public Trionic5File ComparedTrionic5File
{
get { return m_ComparedTrionic5File; }
set { m_ComparedTrionic5File = value; }
}
private Trionic5FileInformation m_ComparedTrionic5FileInformation = new Trionic5FileInformation();
public Trionic5FileInformation ComparedTrionic5FileInformation
{
get { return m_ComparedTrionic5FileInformation; }
set { m_ComparedTrionic5FileInformation = value; }
}
private string m_filename = "";
public string Filename
{
get { return m_filename; }
set { m_filename = value; }
}
public CompareResults()
{
InitializeComponent();
}
public void SetGridWidth()
{
gridView1.BestFitColumns();
}
private void CastSelectEvent(int m_map_address, int m_map_length, string m_map_name)
{
if (onSymbolSelect != null)
{
// haal eerst de data uit de tabel van de gridview
onSymbolSelect(this, new SelectSymbolEventArgs(m_map_address, m_map_length, m_map_name, m_filename, false, m_compareSymbolCollection, m_compareAddressLookupCollection, m_ComparedTrionic5File, m_ComparedTrionic5FileInformation));
}
}
private void CastDifferenceEvent(int m_map_address, int m_map_length, string m_map_name)
{
if (onSymbolSelect != null)
{
// haal eerst de data uit de tabel van de gridview
onSymbolSelect(this, new SelectSymbolEventArgs(m_map_address, m_map_length, m_map_name, m_filename, true, m_compareSymbolCollection, m_compareAddressLookupCollection, m_ComparedTrionic5File, m_ComparedTrionic5FileInformation));
}
}
public void OpenGridViewGroups(GridControl ctrl, int groupleveltoexpand)
{
// open grouplevel 0 (if available)
ctrl.BeginUpdate();
try
{
GridView view = (GridView)ctrl.DefaultView;
//view.ExpandAllGroups();
view.MoveFirst();
while (!view.IsLastRow)
{
int rowhandle = view.FocusedRowHandle;
if (view.IsGroupRow(rowhandle))
{
int grouplevel = view.GetRowLevel(rowhandle);
if (grouplevel <= groupleveltoexpand)
{
view.ExpandGroupRow(rowhandle);
}
}
view.MoveNext();
}
view.MoveFirst();
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
ctrl.EndUpdate();
}
private void StartTableViewer()
{
if (gridView1.SelectedRowsCount > 0)
{
int[] selrows = gridView1.GetSelectedRows();
if (selrows.Length > 0)
{
DataRowView dr = (DataRowView)gridView1.GetRow((int)selrows.GetValue(0));
string Map_name = dr.Row["SYMBOLNAME"].ToString();
int address = Convert.ToInt32(dr.Row["FLASHADDRESS"].ToString());
int length = Convert.ToInt32(dr.Row["LENGTHBYTES"].ToString());
CastSelectEvent(address, length, Map_name);
}
}
}
private void gridView1_DoubleClick(object sender, EventArgs e)
{
int[] selectedrows = gridView1.GetSelectedRows();
if (selectedrows.Length > 0)
{
int grouplevel = gridView1.GetRowLevel((int)selectedrows.GetValue(0));
if (grouplevel >= gridView1.GroupCount)
{
StartTableViewer();
}
}
}
public class SelectSymbolEventArgs : System.EventArgs
{
private int _address;
private int _length;
private string _mapname;
private string _filename;
private bool _showdiffmap;
private SymbolCollection _symbols;
public SymbolCollection Symbols
{
get { return _symbols; }
set { _symbols = value; }
}
private AddressLookupCollection _addresses;
public AddressLookupCollection Addresses
{
get { return _addresses; }
set { _addresses = value; }
}
private Trionic5File m_CompTrionic5File;
public Trionic5File CompTrionic5File
{
get { return m_CompTrionic5File; }
set { m_CompTrionic5File = value; }
}
private Trionic5FileInformation m_CompTrionic5FileInformation;
public Trionic5FileInformation CompTrionic5FileInformation
{
get { return m_CompTrionic5FileInformation; }
set { m_CompTrionic5FileInformation = value; }
}
public bool ShowDiffMap
{
get
{
return _showdiffmap;
}
}
public int SymbolAddress
{
get
{
return _address;
}
}
public int SymbolLength
{
get
{
return _length;
}
}
public string SymbolName
{
get
{
return _mapname;
}
}
public string Filename
{
get
{
return _filename;
}
}
public SelectSymbolEventArgs(int address, int length, string mapname, string filename, bool showdiffmap, SymbolCollection symColl, AddressLookupCollection adrColl, Trionic5File _file, Trionic5FileInformation _fileinfo)
{
this._address = address;
this._length = length;
this._mapname = mapname;
this._filename = filename;
this._showdiffmap = showdiffmap;
this._symbols = symColl;
this._addresses = adrColl;
this.m_CompTrionic5File = _file;
this.m_CompTrionic5FileInformation = _fileinfo;
}
}
private void gridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
StartTableViewer();
e.Handled = true;
}
}
private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
{
if (e.Column.Name == gridColumn6.Name)
{
object o = gridView1.GetRowCellValue(e.RowHandle, "CATEGORY");
Color c = Color.White;
if (o != DBNull.Value)
{
if (Convert.ToInt32(o) == (int)XDFCategories.Fuel)
{
c = Color.LightSteelBlue;
}
else if (Convert.ToInt32(o) == (int)XDFCategories.Ignition)
{
c = Color.LightGreen;
}
else if (Convert.ToInt32(o) == (int)XDFCategories.Boost_control)
{
c = Color.OrangeRed;
}
else if (Convert.ToInt32(o) == (int)XDFCategories.Misc)
{
c = Color.LightGray;
}
else if (Convert.ToInt32(o) == (int)XDFCategories.Sensor)
{
c = Color.Yellow;
}
else if (Convert.ToInt32(o) == (int)XDFCategories.Correction)
{
c = Color.LightPink;
}
else if (Convert.ToInt32(o) == (int)XDFCategories.Idle)
{
c = Color.BurlyWood;
}
}
if (c != Color.White)
{
System.Drawing.Drawing2D.LinearGradientBrush gb = new System.Drawing.Drawing2D.LinearGradientBrush(e.Bounds, c, Color.White, System.Drawing.Drawing2D.LinearGradientMode.Horizontal);
e.Graphics.FillRectangle(gb, e.Bounds);
}
}
}
private void showDifferenceMapToolStripMenuItem_Click(object sender, EventArgs e)
{
// trek de ene map van de andere af en toon het resultaat in een mapviewer!
if (gridView1.SelectedRowsCount > 0)
{
int[] selrows = gridView1.GetSelectedRows();
if (selrows.Length > 0)
{
DataRowView dr = (DataRowView)gridView1.GetRow((int)selrows.GetValue(0));
string Map_name = dr.Row["SYMBOLNAME"].ToString();
int address = Convert.ToInt32(dr.Row["FLASHADDRESS"].ToString());
int length = Convert.ToInt32(dr.Row["LENGTHBYTES"].ToString());
CastDifferenceEvent(address, length, Map_name);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using TestLibrary;
class EncodingGetBytes1
{
static int Main()
{
EncodingGetBytes1 test = new EncodingGetBytes1();
TestFramework.BeginTestCase("Encoding.GetBytes");
if (test.RunTests())
{
TestFramework.EndTestCase();
TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestFramework.EndTestCase();
TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool ret = true;
ret &= Test1();
ret &= Test2();
ret &= Test3();
ret &= Test4();
ret &= Test5();
ret &= Test6();
ret &= Test7();
ret &= Test8();
ret &= Test9();
ret &= Test10();
ret &= Test11();
ret &= Test12();
ret &= Test13();
ret &= Test40();
ret &= Test41();
ret &= Test42();
ret &= Test43();
ret &= Test44();
ret &= Test45();
ret &= Test46();
ret &= Test47();
ret &= Test48();
ret &= Test49();
ret &= Test50();
ret &= Test51();
ret &= Test52();
ret &= Test53();
ret &= Test54();
ret &= Test55();
ret &= Test56();
ret &= Test57();
ret &= Test58();
ret &= Test59();
ret &= Test60();
ret &= Test61();
ret &= Test62();
ret &= Test63();
ret &= Test64();
ret &= Test65();
ret &= Test66();
ret &= Test69();
ret &= Test70();
ret &= Test71();
ret &= Test74();
ret &= Test75();
ret &= Test76();
ret &= Test7();
ret &= Test79();
ret &= Test80();
ret &= Test81();
ret &= Test82();
ret &= Test83();
ret &= Test84();
ret &= Test85();
ret &= Test96();
ret &= Test97();
ret &= Test98();
ret &= Test99();
ret &= Test100();
ret &= Test101();
ret &= Test102();
ret &= Test103();
ret &= Test104();
ret &= Test105();
ret &= Test106();
ret &= Test107();
ret &= Test108();
ret &= Test109();
ret &= Test110();
ret &= Test111();
ret &= Test112();
ret &= Test113();
ret &= Test114();
ret &= Test133();
ret &= Test134();
ret &= Test135();
ret &= Test136();
ret &= Test137();
ret &= Test138();
ret &= Test139();
ret &= Test140();
ret &= Test141();
ret &= Test142();
ret &= Test143();
ret &= Test144();
ret &= Test145();
ret &= Test146();
ret &= Test147();
ret &= Test148();
ret &= Test149();
ret &= Test150();
ret &= Test151();
ret &= Test152();
ret &= Test153();
ret &= Test154();
ret &= Test155();
ret &= Test156();
ret &= Test157();
ret &= Test158();
ret &= Test159();
ret &= Test107();
ret &= Test179();
ret &= Test180();
ret &= Test181();
ret &= Test182();
ret &= Test183();
ret &= Test184();
ret &= Test185();
ret &= Test186();
ret &= Test187();
ret &= Test188();
ret &= Test189();
ret &= Test190();
ret &= Test191();
ret &= Test192();
ret &= Test193();
ret &= Test194();
ret &= Test195();
return ret;
}
// Positive Tests
public bool Test1() { return PositiveTestString(Encoding.UTF8, "TestString", new byte[] { 84, 101, 115, 116, 83, 116, 114, 105, 110, 103 }, "00A"); }
public bool Test2() { return PositiveTestString(Encoding.UTF8, "", new byte[] { }, "00B"); }
public bool Test3() { return PositiveTestString(Encoding.UTF8, "FooBA\u0400R", new byte[] { 70, 111, 111, 66, 65, 208, 128, 82 }, "00C"); }
public bool Test4() { return PositiveTestString(Encoding.UTF8, "\u00C0nima\u0300l", new byte[] { 195, 128, 110, 105, 109, 97, 204, 128, 108 }, "00D"); }
public bool Test5() { return PositiveTestString(Encoding.UTF8, "Test\uD803\uDD75Test", new byte[] { 84, 101, 115, 116, 240, 144, 181, 181, 84, 101, 115, 116 }, "00E"); }
public bool Test6() { return PositiveTestString(Encoding.UTF8, "Test\uD803Test", new byte[] { 84, 101, 115, 116, 239, 191, 189, 84, 101, 115, 116 }, "00F"); }
public bool Test7() { return PositiveTestString(Encoding.UTF8, "Test\uDD75Test", new byte[] { 84, 101, 115, 116, 239, 191, 189, 84, 101, 115, 116 }, "00G"); }
public bool Test8() { return PositiveTestString(Encoding.UTF8, "TestTest\uDD75", new byte[] { 84, 101, 115, 116, 84, 101, 115, 116, 239, 191, 189 }, "00H"); }
public bool Test9() { return PositiveTestString(Encoding.UTF8, "TestTest\uD803", new byte[] { 84, 101, 115, 116, 84, 101, 115, 116, 239, 191, 189 }, "00I"); }
public bool Test10() { return PositiveTestString(Encoding.UTF8, "\uDD75", new byte[] { 239, 191, 189 }, "00J"); }
public bool Test11() { return PositiveTestString(Encoding.UTF8, "\uD803\uDD75\uD803\uDD75\uD803\uDD75", new byte[] { 240, 144, 181, 181, 240, 144, 181, 181, 240, 144, 181, 181 }, "00K"); }
public bool Test12() { return PositiveTestString(Encoding.UTF8, "\u0130", new byte[] { 196, 176 }, "00L"); }
public bool Test13() { return PositiveTestString(Encoding.UTF8, "\uDD75\uDD75\uD803\uDD75\uDD75\uDD75\uDD75\uD803\uD803\uD803\uDD75\uDD75\uDD75\uDD75", 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 }, "0A2"); }
public bool Test40() { return PositiveTestString(Encoding.Unicode, "TestString", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 83, 0, 116, 0, 114, 0, 105, 0, 110, 0, 103, 0 }, "00A3"); }
public bool Test41() { return PositiveTestString(Encoding.Unicode, "", new byte[] { }, "00B3"); }
public bool Test42() { return PositiveTestString(Encoding.Unicode, "FooBA\u0400R", new byte[] { 70, 0, 111, 0, 111, 0, 66, 0, 65, 0, 0, 4, 82, 0 }, "00C3"); }
public bool Test43() { return PositiveTestString(Encoding.Unicode, "\u00C0nima\u0300l", new byte[] { 192, 0, 110, 0, 105, 0, 109, 0, 97, 0, 0, 3, 108, 0 }, "00D3"); }
public bool Test44() { return PositiveTestString(Encoding.Unicode, "Test\uD803\uDD75Test", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 3, 216, 117, 221, 84, 0, 101, 0, 115, 0, 116, 0 }, "00E3"); }
public bool Test45() { return PositiveTestString(Encoding.Unicode, "Test\uD803Test", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 253, 255, 84, 0, 101, 0, 115, 0, 116, 0 }, "00F3"); }
public bool Test46() { return PositiveTestString(Encoding.Unicode, "Test\uDD75Test", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 253, 255, 84, 0, 101, 0, 115, 0, 116, 0, }, "00G3"); }
public bool Test47() { return PositiveTestString(Encoding.Unicode, "TestTest\uDD75", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 0, 253, 255 }, "00H3"); }
public bool Test48() { return PositiveTestString(Encoding.Unicode, "TestTest\uD803", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 0, 253, 255 }, "00I3"); }
public bool Test49() { return PositiveTestString(Encoding.Unicode, "\uDD75", new byte[] { 253, 255 }, "00J3"); }
public bool Test50() { return PositiveTestString(Encoding.Unicode, "\uD803\uDD75\uD803\uDD75\uD803\uDD75", new byte[] { 3, 216, 117, 221, 3, 216, 117, 221, 3, 216, 117, 221 }, "00K3"); }
public bool Test51() { return PositiveTestString(Encoding.Unicode, "\u0130", new byte[] { 48, 1 }, "00L3"); }
public bool Test52() { return PositiveTestString(Encoding.Unicode, "\uDD75\uDD75\uD803\uDD75\uDD75\uDD75\uDD75\uD803\uD803\uD803\uDD75\uDD75\uDD75\uDD75", new byte[] { 253, 255, 253, 255, 3, 216, 117, 221, 253, 255, 253, 255, 253, 255, 253, 255, 253, 255, 3, 216, 117, 221, 253, 255, 253, 255, 253, 255 }, "0A23"); }
public bool Test53() { return PositiveTestString(Encoding.BigEndianUnicode, "TestString", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 0, 83, 0, 116, 0, 114, 0, 105, 0, 110, 0, 103 }, "00A4"); }
public bool Test54() { return PositiveTestString(Encoding.BigEndianUnicode, "", new byte[] { }, "00B4"); }
public bool Test55() { return PositiveTestString(Encoding.BigEndianUnicode, "FooBA\u0400R", new byte[] { 0, 70, 0, 111, 0, 111, 0, 66, 0, 65, 4, 0, 0, 82 }, "00C4"); }
public bool Test56() { return PositiveTestString(Encoding.BigEndianUnicode, "\u00C0nima\u0300l", new byte[] { 0, 192, 0, 110, 0, 105, 0, 109, 0, 97, 3, 0, 0, 108 }, "00D4"); }
public bool Test57() { return PositiveTestString(Encoding.BigEndianUnicode, "Test\uD803\uDD75Test", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 216, 3, 221, 117, 0, 84, 0, 101, 0, 115, 0, 116 }, "00E4"); }
public bool Test58() { return PositiveTestString(Encoding.BigEndianUnicode, "Test\uD803Test", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 255, 253, 0, 84, 0, 101, 0, 115, 0, 116 }, "00F4"); }
public bool Test59() { return PositiveTestString(Encoding.BigEndianUnicode, "Test\uDD75Test", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 255, 253, 0, 84, 0, 101, 0, 115, 0, 116 }, "00G4"); }
public bool Test60() { return PositiveTestString(Encoding.BigEndianUnicode, "TestTest\uDD75", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 255, 253 }, "00H4"); }
public bool Test61() { return PositiveTestString(Encoding.BigEndianUnicode, "TestTest\uD803", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 255, 253 }, "00I4"); }
public bool Test62() { return PositiveTestString(Encoding.BigEndianUnicode, "\uDD75", new byte[] { 255, 253 }, "00J4"); }
public bool Test63() { return PositiveTestString(Encoding.BigEndianUnicode, "\uD803\uDD75\uD803\uDD75\uD803\uDD75", new byte[] { 216, 3, 221, 117, 216, 3, 221, 117, 216, 3, 221, 117 }, "00K4"); }
public bool Test64() { return PositiveTestString(Encoding.BigEndianUnicode, "\u0130", new byte[] { 1, 48 }, "00L4"); }
public bool Test65() { return PositiveTestString(Encoding.BigEndianUnicode, "\uDD75\uDD75\uD803\uDD75\uDD75\uDD75\uDD75\uD803\uD803\uD803\uDD75\uDD75\uDD75\uDD75", new byte[] { 255, 253, 255, 253, 216, 3, 221, 117, 255, 253, 255, 253, 255, 253, 255, 253, 255, 253, 216, 3, 221, 117, 255, 253, 255, 253, 255, 253 }, "0A24"); }
public bool Test66() { return PositiveTestChars(Encoding.UTF8, new char[] { 'T', 'e', 's', 't', 'S', 't', 'r', 'i', 'n', 'g' }, new byte[] { 84, 101, 115, 116, 83, 116, 114, 105, 110, 103 }, "00M"); }
public bool Test69() { return PositiveTestChars(Encoding.Unicode, new char[] { 'T', 'e', 's', 't', 'S', 't', 'r', 'i', 'n', 'g' }, new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 83, 0, 116, 0, 114, 0, 105, 0, 110, 0, 103, 0 }, "00M3"); }
public bool Test70() { return PositiveTestChars(Encoding.BigEndianUnicode, new char[] { 'T', 'e', 's', 't', 'S', 't', 'r', 'i', 'n', 'g' }, new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 0, 83, 0, 116, 0, 114, 0, 105, 0, 110, 0, 103 }, "00M4"); }
// Negative Tests
public bool Test71() { return NegativeTestString(new UTF8Encoding(), null, typeof(ArgumentNullException), "00N"); }
public bool Test74() { return NegativeTestString(new UnicodeEncoding(), null, typeof(ArgumentNullException), "00N3"); }
public bool Test75() { return NegativeTestString(new UnicodeEncoding(true, false), null, typeof(ArgumentNullException), "00N4"); }
public bool Test76() { return NegativeTestChars(new UTF8Encoding(), null, typeof(ArgumentNullException), "00O"); }
public bool Test79() { return NegativeTestChars(new UnicodeEncoding(), null, typeof(ArgumentNullException), "00O3"); }
public bool Test80() { return NegativeTestChars(new UnicodeEncoding(true, false), null, typeof(ArgumentNullException), "00O4"); }
public bool Test81() { return NegativeTestChars2(new UTF8Encoding(), null, 0, 0, typeof(ArgumentNullException), "00P"); }
public bool Test82() { return NegativeTestChars2(new UTF8Encoding(), new char[] { 't' }, -1, 1, typeof(ArgumentOutOfRangeException), "00P"); }
public bool Test83() { return NegativeTestChars2(new UTF8Encoding(), new char[] { 't' }, 1, -1, typeof(ArgumentOutOfRangeException), "00Q"); }
public bool Test84() { return NegativeTestChars2(new UTF8Encoding(), new char[] { 't' }, 0, 10, typeof(ArgumentOutOfRangeException), "00R"); }
public bool Test85() { return NegativeTestChars2(new UTF8Encoding(), new char[] { 't' }, 2, 0, typeof(ArgumentOutOfRangeException), "00S"); }
public bool Test96() { return NegativeTestChars2(new UnicodeEncoding(), null, 0, 0, typeof(ArgumentNullException), "00P3"); }
public bool Test97() { return NegativeTestChars2(new UnicodeEncoding(), new char[] { 't' }, -1, 1, typeof(ArgumentOutOfRangeException), "00P3"); }
public bool Test98() { return NegativeTestChars2(new UnicodeEncoding(), new char[] { 't' }, 1, -1, typeof(ArgumentOutOfRangeException), "00Q3"); }
public bool Test99() { return NegativeTestChars2(new UnicodeEncoding(), new char[] { 't' }, 0, 10, typeof(ArgumentOutOfRangeException), "00R3"); }
public bool Test100() { return NegativeTestChars2(new UnicodeEncoding(), new char[] { 't' }, 2, 0, typeof(ArgumentOutOfRangeException), "00S3"); }
public bool Test101() { return NegativeTestChars2(new UnicodeEncoding(true, false), null, 0, 0, typeof(ArgumentNullException), "00P4"); }
public bool Test102() { return NegativeTestChars2(new UnicodeEncoding(true, false), new char[] { 't' }, -1, 1, typeof(ArgumentOutOfRangeException), "00P4"); }
public bool Test103() { return NegativeTestChars2(new UnicodeEncoding(true, false), new char[] { 't' }, 1, -1, typeof(ArgumentOutOfRangeException), "00Q4"); }
public bool Test104() { return NegativeTestChars2(new UnicodeEncoding(true, false), new char[] { 't' }, 0, 10, typeof(ArgumentOutOfRangeException), "00R4"); }
public bool Test105() { return NegativeTestChars2(new UnicodeEncoding(true, false), new char[] { 't' }, 2, 0, typeof(ArgumentOutOfRangeException), "00S4"); }
static byte[] output = new byte[20];
public bool Test106() { return NegativeTestChars3(Encoding.UTF8, null, 0, 0, output, 0, typeof(ArgumentNullException), "00T"); }
public bool Test107() { return NegativeTestChars3(Encoding.UTF8, new char[] { 't' }, 0, 0, null, 0, typeof(ArgumentNullException), "00U"); }
public bool Test108() { return NegativeTestChars3(Encoding.UTF8, new char[] { 't' }, -1, 0, output, 0, typeof(ArgumentOutOfRangeException), "00V"); }
public bool Test109() { return NegativeTestChars3(Encoding.UTF8, new char[] { 't' }, 0, 0, output, -1, typeof(ArgumentOutOfRangeException), "00W"); }
public bool Test110() { return NegativeTestChars3(Encoding.UTF8, new char[] { 't' }, 2, 0, output, 0, typeof(ArgumentOutOfRangeException), "00X"); }
public bool Test111() { return NegativeTestChars3(Encoding.UTF8, new char[] { 't' }, 0, 0, output, 21, typeof(ArgumentOutOfRangeException), "00Y"); }
public bool Test112() { return NegativeTestChars3(Encoding.UTF8, new char[] { 't' }, 0, 10, output, 0, typeof(ArgumentOutOfRangeException), "00Z"); }
public bool Test113() { return NegativeTestChars3(Encoding.UTF8, new char[] { 't' }, 0, 1, output, 20, typeof(ArgumentException), "0A0"); }
public bool Test114() { return NegativeTestChars3(Encoding.UTF8, new char[] { 't' }, 0, -1, output, 0, typeof(ArgumentOutOfRangeException), "0A1"); }
public bool Test133() { return NegativeTestChars3(Encoding.Unicode, null, 0, 0, output, 0, typeof(ArgumentNullException), "00T3"); }
public bool Test134() { return NegativeTestChars3(Encoding.Unicode, new char[] { 't' }, 0, 0, null, 0, typeof(ArgumentNullException), "00U3"); }
public bool Test135() { return NegativeTestChars3(Encoding.Unicode, new char[] { 't' }, -1, 0, output, 0, typeof(ArgumentOutOfRangeException), "00V3"); }
public bool Test136() { return NegativeTestChars3(Encoding.Unicode, new char[] { 't' }, 0, 0, output, -1, typeof(ArgumentOutOfRangeException), "00W3"); }
public bool Test137() { return NegativeTestChars3(Encoding.Unicode, new char[] { 't' }, 2, 0, output, 0, typeof(ArgumentOutOfRangeException), "00X3"); }
public bool Test138() { return NegativeTestChars3(Encoding.Unicode, new char[] { 't' }, 0, 0, output, 21, typeof(ArgumentOutOfRangeException), "00Y3"); }
public bool Test139() { return NegativeTestChars3(Encoding.Unicode, new char[] { 't' }, 0, 10, output, 0, typeof(ArgumentOutOfRangeException), "00Z3"); }
public bool Test140() { return NegativeTestChars3(Encoding.Unicode, new char[] { 't' }, 0, 1, output, 20, typeof(ArgumentException), "0A03"); }
public bool Test141() { return NegativeTestChars3(Encoding.Unicode, new char[] { 't' }, 0, -1, output, 0, typeof(ArgumentOutOfRangeException), "0A13"); }
public bool Test142() { return NegativeTestChars3(Encoding.BigEndianUnicode, null, 0, 0, output, 0, typeof(ArgumentNullException), "00T4"); }
public bool Test143() { return NegativeTestChars3(Encoding.BigEndianUnicode, new char[] { 't' }, 0, 0, null, 0, typeof(ArgumentNullException), "00U4"); }
public bool Test144() { return NegativeTestChars3(Encoding.BigEndianUnicode, new char[] { 't' }, -1, 0, output, 0, typeof(ArgumentOutOfRangeException), "00V4"); }
public bool Test145() { return NegativeTestChars3(Encoding.BigEndianUnicode, new char[] { 't' }, 0, 0, output, -1, typeof(ArgumentOutOfRangeException), "00W4"); }
public bool Test146() { return NegativeTestChars3(Encoding.BigEndianUnicode, new char[] { 't' }, 2, 0, output, 0, typeof(ArgumentOutOfRangeException), "00X4"); }
public bool Test147() { return NegativeTestChars3(Encoding.BigEndianUnicode, new char[] { 't' }, 0, 0, output, 21, typeof(ArgumentOutOfRangeException), "00Y4"); }
public bool Test148() { return NegativeTestChars3(Encoding.BigEndianUnicode, new char[] { 't' }, 0, 10, output, 0, typeof(ArgumentOutOfRangeException), "00Z4"); }
public bool Test149() { return NegativeTestChars3(Encoding.BigEndianUnicode, new char[] { 't' }, 0, 1, output, 20, typeof(ArgumentException), "0A04"); }
public bool Test150() { return NegativeTestChars3(Encoding.BigEndianUnicode, new char[] { 't' }, 0, -1, output, 0, typeof(ArgumentOutOfRangeException), "0A14"); }
public bool Test151() { return NegativeTestString1(Encoding.UTF8, null, 0, 0, output, 0, typeof(ArgumentNullException), "00Ta"); }
public bool Test152() { return NegativeTestString1(Encoding.UTF8, "t", 0, 0, null, 0, typeof(ArgumentNullException), "00Ua"); }
public bool Test153() { return NegativeTestString1(Encoding.UTF8, "t", -1, 0, output, 0, typeof(ArgumentOutOfRangeException), "00Va"); }
public bool Test154() { return NegativeTestString1(Encoding.UTF8, "t", 0, 0, output, -1, typeof(ArgumentOutOfRangeException), "00Wa"); }
public bool Test155() { return NegativeTestString1(Encoding.UTF8, "t", 2, 0, output, 0, typeof(ArgumentOutOfRangeException), "00Xa"); }
public bool Test156() { return NegativeTestString1(Encoding.UTF8, "t", 0, 0, output, 21, typeof(ArgumentOutOfRangeException), "00Ya"); }
public bool Test157() { return NegativeTestString1(Encoding.UTF8, "t", 0, 10, output, 0, typeof(ArgumentOutOfRangeException), "00Za"); }
public bool Test158() { return NegativeTestString1(Encoding.UTF8, "t", 0, 1, output, 20, typeof(ArgumentException), "0A0a"); }
public bool Test159() { return NegativeTestString1(Encoding.UTF8, "t", 0, -1, output, 0, typeof(ArgumentOutOfRangeException), "0A1a"); }
public bool Test178() { return NegativeTestString1(Encoding.Unicode, null, 0, 0, output, 0, typeof(ArgumentNullException), "00T3a"); }
public bool Test179() { return NegativeTestString1(Encoding.Unicode, "t", 0, 0, null, 0, typeof(ArgumentNullException), "00U3a"); }
public bool Test180() { return NegativeTestString1(Encoding.Unicode, "t", -1, 0, output, 0, typeof(ArgumentOutOfRangeException), "00V3a"); }
public bool Test181() { return NegativeTestString1(Encoding.Unicode, "t", 0, 0, output, -1, typeof(ArgumentOutOfRangeException), "00W3a"); }
public bool Test182() { return NegativeTestString1(Encoding.Unicode, "t", 2, 0, output, 0, typeof(ArgumentOutOfRangeException), "00X3a"); }
public bool Test183() { return NegativeTestString1(Encoding.Unicode, "t", 0, 0, output, 21, typeof(ArgumentOutOfRangeException), "00Y3a"); }
public bool Test184() { return NegativeTestString1(Encoding.Unicode, "t", 0, 10, output, 0, typeof(ArgumentOutOfRangeException), "00Z3a"); }
public bool Test185() { return NegativeTestString1(Encoding.Unicode, "t", 0, 1, output, 20, typeof(ArgumentException), "0A03a"); }
public bool Test186() { return NegativeTestString1(Encoding.Unicode, "t", 0, -1, output, 0, typeof(ArgumentOutOfRangeException), "0A13a"); }
public bool Test187() { return NegativeTestString1(Encoding.BigEndianUnicode, null, 0, 0, output, 0, typeof(ArgumentNullException), "00T4a"); }
public bool Test188() { return NegativeTestString1(Encoding.BigEndianUnicode, "t", 0, 0, null, 0, typeof(ArgumentNullException), "00U4a"); }
public bool Test189() { return NegativeTestString1(Encoding.BigEndianUnicode, "t", -1, 0, output, 0, typeof(ArgumentOutOfRangeException), "00V4a"); }
public bool Test190() { return NegativeTestString1(Encoding.BigEndianUnicode, "t", 0, 0, output, -1, typeof(ArgumentOutOfRangeException), "00W4a"); }
public bool Test191() { return NegativeTestString1(Encoding.BigEndianUnicode, "t", 2, 0, output, 0, typeof(ArgumentOutOfRangeException), "00X4a"); }
public bool Test192() { return NegativeTestString1(Encoding.BigEndianUnicode, "t", 0, 0, output, 21, typeof(ArgumentOutOfRangeException), "00Y4a"); }
public bool Test193() { return NegativeTestString1(Encoding.BigEndianUnicode, "t", 0, 10, output, 0, typeof(ArgumentOutOfRangeException), "00Z4a"); }
public bool Test194() { return NegativeTestString1(Encoding.BigEndianUnicode, "t", 0, 1, output, 20, typeof(ArgumentException), "0A04a"); }
public bool Test195() { return NegativeTestString1(Encoding.BigEndianUnicode, "t", 0, -1, output, 0, typeof(ArgumentOutOfRangeException), "0A14a"); }
public bool PositiveTestString(Encoding enc, string str, byte[] expected, string id)
{
bool result = true;
TestFramework.BeginScenario(id + ": Getting bytes for " + str + " with encoding " + enc.WebName);
try
{
byte[] bytes = enc.GetBytes(str);
if (!Utilities.CompareBytes(bytes, expected))
{
result = false;
TestFramework.LogError("001", "Error in " + id + ", unexpected comparison result. Actual bytes " + Utilities.ByteArrayToString(bytes) + ", Expected: " + Utilities.ByteArrayToString(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 bytes with encoding " + enc.WebName);
try
{
byte[] bytes = enc.GetBytes(str);
result = false;
TestFramework.LogError("005", "Error in " + id + ", Expected exception not thrown. Actual bytes " + Utilities.ByteArrayToString(bytes) + ", 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, byte[] expected, string id)
{
bool result = true;
TestFramework.BeginScenario(id + ": Getting bytes for " + new string(chars) + " with encoding " + enc.WebName);
try
{
byte[] bytes = enc.GetBytes(chars);
if (!Utilities.CompareBytes(bytes, expected))
{
result = false;
TestFramework.LogError("003", "Error in " + id + ", unexpected comparison result. Actual bytes " + Utilities.ByteArrayToString(bytes) + ", Expected: " + Utilities.ByteArrayToString(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 bytes with encoding " + enc.WebName);
try
{
byte[] bytes = enc.GetBytes(str);
result = false;
TestFramework.LogError("007", "Error in " + id + ", Expected exception not thrown. Actual bytes " + Utilities.ByteArrayToString(bytes) + ", 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 bytes with encoding " + enc.WebName);
try
{
byte[] bytes = enc.GetBytes(str, index, count);
result = false;
TestFramework.LogError("009", "Error in " + id + ", Expected exception not thrown. Actual bytes " + Utilities.ByteArrayToString(bytes) + ", 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;
}
public bool NegativeTestChars3(Encoding enc, char[] str, int index, int count, byte[] bytes, int bIndex, Type excType, string id)
{
bool result = true;
TestFramework.BeginScenario(id + ": Getting bytes with encoding " + enc.WebName);
try
{
int output = enc.GetBytes(str, index, count, bytes, bIndex);
result = false;
TestFramework.LogError("011", "Error in " + id + ", Expected exception not thrown. Actual bytes " + Utilities.ByteArrayToString(bytes) + ", Expected exception type: " + excType.ToString());
}
catch (Exception exc)
{
if (exc.GetType() != excType)
{
result = false;
TestFramework.LogError("012", "Unexpected exception in " + id + ", excpetion: " + exc.ToString());
}
}
return result;
}
public bool NegativeTestString1(Encoding enc, string str, int index, int count, byte[] bytes, int bIndex, Type excType, string id)
{
bool result = true;
TestFramework.BeginScenario(id + ": Getting bytes with encoding " + enc.WebName);
try
{
int output = enc.GetBytes(str, index, count, bytes, bIndex);
result = false;
TestFramework.LogError("013", "Error in " + id + ", Expected exception not thrown. Actual bytes " + Utilities.ByteArrayToString(bytes) + ", Expected exception type: " + excType.ToString());
}
catch (Exception exc)
{
if (exc.GetType() != excType)
{
result = false;
TestFramework.LogError("014", "Unexpected exception in " + id + ", excpetion: " + exc.ToString());
}
}
return result;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: Searches for resources in Assembly manifest, used
** for assembly-based resource lookup.
**
**
===========================================================*/
namespace System.Resources {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using System.Diagnostics.Contracts;
using Microsoft.Win32;
#if !FEATURE_CORECLR
using System.Diagnostics.Tracing;
#endif
//
// Note: this type is integral to the construction of exception objects,
// and sometimes this has to be done in low memory situtations (OOM) or
// to create TypeInitializationExceptions due to failure of a static class
// constructor. This type needs to be extremely careful and assume that
// any type it references may have previously failed to construct, so statics
// belonging to that type may not be initialized. FrameworkEventSource.Log
// is one such example.
//
internal class ManifestBasedResourceGroveler : IResourceGroveler
{
private ResourceManager.ResourceManagerMediator _mediator;
public ManifestBasedResourceGroveler(ResourceManager.ResourceManagerMediator mediator)
{
// here and below: convert asserts to preconditions where appropriate when we get
// contracts story in place.
Contract.Requires(mediator != null, "mediator shouldn't be null; check caller");
_mediator = mediator;
}
[System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<String, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists, ref StackCrawlMark stackMark)
{
Contract.Assert(culture != null, "culture shouldn't be null; check caller");
Contract.Assert(localResourceSets != null, "localResourceSets shouldn't be null; check caller");
ResourceSet rs = null;
Stream stream = null;
RuntimeAssembly satellite = null;
// 1. Fixups for ultimate fallbacks
CultureInfo lookForCulture = UltimateFallbackFixup(culture);
// 2. Look for satellite assembly or main assembly, as appropriate
if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly)
{
// don't bother looking in satellites in this case
satellite = _mediator.MainAssembly;
}
#if RESOURCE_SATELLITE_CONFIG
// If our config file says the satellite isn't here, don't ask for it.
else if (!lookForCulture.HasInvariantCultureName && !_mediator.TryLookingForSatellite(lookForCulture))
{
satellite = null;
}
#endif
else
{
satellite = GetSatelliteAssembly(lookForCulture, ref stackMark);
if (satellite == null)
{
bool raiseException = (culture.HasInvariantCultureName && (_mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite));
// didn't find satellite, give error if necessary
if (raiseException)
{
HandleSatelliteMissing();
}
}
}
// get resource file name we'll search for. Note, be careful if you're moving this statement
// around because lookForCulture may be modified from originally requested culture above.
String fileName = _mediator.GetResourceFileName(lookForCulture);
// 3. If we identified an assembly to search; look in manifest resource stream for resource file
if (satellite != null)
{
// Handle case in here where someone added a callback for assembly load events.
// While no other threads have called into GetResourceSet, our own thread can!
// At that point, we could already have an RS in our hash table, and we don't
// want to add it twice.
lock (localResourceSets)
{
if (localResourceSets.TryGetValue(culture.Name, out rs))
{
#if !FEATURE_CORECLR
if (FrameworkEventSource.IsInitialized)
{
FrameworkEventSource.Log.ResourceManagerFoundResourceSetInCacheUnexpected(_mediator.BaseName, _mediator.MainAssembly, culture.Name);
}
#endif
}
}
stream = GetManifestResourceStream(satellite, fileName, ref stackMark);
}
#if !FEATURE_CORECLR
if (FrameworkEventSource.IsInitialized)
{
if (stream != null)
{
FrameworkEventSource.Log.ResourceManagerStreamFound(_mediator.BaseName, _mediator.MainAssembly, culture.Name, satellite, fileName);
}
else
{
FrameworkEventSource.Log.ResourceManagerStreamNotFound(_mediator.BaseName, _mediator.MainAssembly, culture.Name, satellite, fileName);
}
}
#endif
// 4a. Found a stream; create a ResourceSet if possible
if (createIfNotExists && stream != null && rs == null)
{
#if !FEATURE_CORECLR
if (FrameworkEventSource.IsInitialized)
{
FrameworkEventSource.Log.ResourceManagerCreatingResourceSet(_mediator.BaseName, _mediator.MainAssembly, culture.Name, fileName);
}
#endif
rs = CreateResourceSet(stream, satellite);
}
else if (stream == null && tryParents)
{
// 4b. Didn't find stream; give error if necessary
bool raiseException = culture.HasInvariantCultureName;
if (raiseException)
{
HandleResourceStreamMissing(fileName);
}
}
#if !FEATURE_CORECLR
if (!createIfNotExists && stream != null && rs == null)
{
if (FrameworkEventSource.IsInitialized)
{
FrameworkEventSource.Log.ResourceManagerNotCreatingResourceSet(_mediator.BaseName, _mediator.MainAssembly, culture.Name);
}
}
#endif
return rs;
}
#if !FEATURE_CORECLR
// Returns whether or not the main assembly contains a particular resource
// file in it's assembly manifest. Used to verify that the neutral
// Culture's .resources file is present in the main assembly
public bool HasNeutralResources(CultureInfo culture, String defaultResName)
{
String resName = defaultResName;
if (_mediator.LocationInfo != null && _mediator.LocationInfo.Namespace != null)
resName = _mediator.LocationInfo.Namespace + Type.Delimiter + defaultResName;
String[] resourceFiles = _mediator.MainAssembly.GetManifestResourceNames();
foreach(String s in resourceFiles)
if (s.Equals(resName))
return true;
return false;
}
#endif
private CultureInfo UltimateFallbackFixup(CultureInfo lookForCulture)
{
CultureInfo returnCulture = lookForCulture;
// If our neutral resources were written in this culture AND we know the main assembly
// does NOT contain neutral resources, don't probe for this satellite.
if (lookForCulture.Name == _mediator.NeutralResourcesCulture.Name &&
_mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly)
{
#if !FEATURE_CORECLR
if (FrameworkEventSource.IsInitialized)
{
FrameworkEventSource.Log.ResourceManagerNeutralResourcesSufficient(_mediator.BaseName, _mediator.MainAssembly, lookForCulture.Name);
}
#endif
returnCulture = CultureInfo.InvariantCulture;
}
else if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite)
{
returnCulture = _mediator.NeutralResourcesCulture;
}
return returnCulture;
}
[System.Security.SecurityCritical]
internal static CultureInfo GetNeutralResourcesLanguage(Assembly a, ref UltimateResourceFallbackLocation fallbackLocation)
{
#if FEATURE_LEGACYNETCF
// Windows Phone 7.0/7.1 ignore NeutralResourceLanguage attribute and
// defaults fallbackLocation to MainAssembly
if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)
{
fallbackLocation = UltimateResourceFallbackLocation.MainAssembly;
return CultureInfo.InvariantCulture;
}
#endif
Contract.Assert(a != null, "assembly != null");
string cultureName = null;
short fallback = 0;
if (GetNeutralResourcesLanguageAttribute(((RuntimeAssembly)a).GetNativeHandle(),
JitHelpers.GetStringHandleOnStack(ref cultureName),
out fallback)) {
if ((UltimateResourceFallbackLocation)fallback < UltimateResourceFallbackLocation.MainAssembly || (UltimateResourceFallbackLocation)fallback > UltimateResourceFallbackLocation.Satellite) {
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidNeutralResourcesLanguage_FallbackLoc", fallback));
}
fallbackLocation = (UltimateResourceFallbackLocation)fallback;
}
else {
#if !FEATURE_CORECLR
if (FrameworkEventSource.IsInitialized) {
FrameworkEventSource.Log.ResourceManagerNeutralResourceAttributeMissing(a);
}
#endif
fallbackLocation = UltimateResourceFallbackLocation.MainAssembly;
return CultureInfo.InvariantCulture;
}
try
{
CultureInfo c = CultureInfo.GetCultureInfo(cultureName);
return c;
}
catch (ArgumentException e)
{ // we should catch ArgumentException only.
// Note we could go into infinite loops if mscorlib's
// NeutralResourcesLanguageAttribute is mangled. If this assert
// fires, please fix the build process for the BCL directory.
if (a == typeof(Object).Assembly)
{
Contract.Assert(false, "mscorlib's NeutralResourcesLanguageAttribute is a malformed culture name! name: \"" + cultureName + "\" Exception: " + e);
return CultureInfo.InvariantCulture;
}
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidNeutralResourcesLanguage_Asm_Culture", a.ToString(), cultureName), e);
}
}
// Constructs a new ResourceSet for a given file name. The logic in
// here avoids a ReflectionPermission check for our RuntimeResourceSet
// for perf and working set reasons.
// Use the assembly to resolve assembly manifest resource references.
// Note that is can be null, but probably shouldn't be.
// This method could use some refactoring. One thing at a time.
[System.Security.SecurityCritical]
internal ResourceSet CreateResourceSet(Stream store, Assembly assembly)
{
Contract.Assert(store != null, "I need a Stream!");
// Check to see if this is a Stream the ResourceManager understands,
// and check for the correct resource reader type.
if (store.CanSeek && store.Length > 4)
{
long startPos = store.Position;
// not disposing because we want to leave stream open
BinaryReader br = new BinaryReader(store);
// Look for our magic number as a little endian Int32.
int bytes = br.ReadInt32();
if (bytes == ResourceManager.MagicNumber)
{
int resMgrHeaderVersion = br.ReadInt32();
String readerTypeName = null, resSetTypeName = null;
if (resMgrHeaderVersion == ResourceManager.HeaderVersionNumber)
{
br.ReadInt32(); // We don't want the number of bytes to skip.
readerTypeName = br.ReadString();
resSetTypeName = br.ReadString();
}
else if (resMgrHeaderVersion > ResourceManager.HeaderVersionNumber)
{
// Assume that the future ResourceManager headers will
// have two strings for us - the reader type name and
// resource set type name. Read those, then use the num
// bytes to skip field to correct our position.
int numBytesToSkip = br.ReadInt32();
long endPosition = br.BaseStream.Position + numBytesToSkip;
readerTypeName = br.ReadString();
resSetTypeName = br.ReadString();
br.BaseStream.Seek(endPosition, SeekOrigin.Begin);
}
else
{
// resMgrHeaderVersion is older than this ResMgr version.
// We should add in backwards compatibility support here.
throw new NotSupportedException(Environment.GetResourceString("NotSupported_ObsoleteResourcesFile", _mediator.MainAssembly.GetSimpleName()));
}
store.Position = startPos;
// Perf optimization - Don't use Reflection for our defaults.
// Note there are two different sets of strings here - the
// assembly qualified strings emitted by ResourceWriter, and
// the abbreviated ones emitted by InternalResGen.
if (CanUseDefaultResourceClasses(readerTypeName, resSetTypeName))
{
RuntimeResourceSet rs;
#if LOOSELY_LINKED_RESOURCE_REFERENCE
rs = new RuntimeResourceSet(store, assembly);
#else
rs = new RuntimeResourceSet(store);
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
return rs;
}
else
{
// we do not want to use partial binding here.
Type readerType = Type.GetType(readerTypeName, true);
Object[] args = new Object[1];
args[0] = store;
IResourceReader reader = (IResourceReader)Activator.CreateInstance(readerType, args);
Object[] resourceSetArgs =
#if LOOSELY_LINKED_RESOURCE_REFERENCE
new Object[2];
#else
new Object[1];
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
resourceSetArgs[0] = reader;
#if LOOSELY_LINKED_RESOURCE_REFERENCE
resourceSetArgs[1] = assembly;
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
Type resSetType;
if (_mediator.UserResourceSet == null)
{
Contract.Assert(resSetTypeName != null, "We should have a ResourceSet type name from the custom resource file here.");
resSetType = Type.GetType(resSetTypeName, true, false);
}
else
resSetType = _mediator.UserResourceSet;
ResourceSet rs = (ResourceSet)Activator.CreateInstance(resSetType,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance,
null,
resourceSetArgs,
null,
null);
return rs;
}
}
else
{
store.Position = startPos;
}
}
if (_mediator.UserResourceSet == null)
{
// Explicitly avoid CreateInstance if possible, because it
// requires ReflectionPermission to call private & protected
// constructors.
#if LOOSELY_LINKED_RESOURCE_REFERENCE
return new RuntimeResourceSet(store, assembly);
#else
return new RuntimeResourceSet(store);
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
}
else
{
Object[] args = new Object[2];
args[0] = store;
args[1] = assembly;
try
{
ResourceSet rs = null;
// Add in a check for a constructor taking in an assembly first.
try
{
rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args);
return rs;
}
catch (MissingMethodException) { }
args = new Object[1];
args[0] = store;
rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args);
#if LOOSELY_LINKED_RESOURCE_REFERENCE
rs.Assembly = assembly;
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
return rs;
}
catch (MissingMethodException e)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResMgrBadResSet_Type", _mediator.UserResourceSet.AssemblyQualifiedName), e);
}
}
}
[System.Security.SecurityCritical]
private Stream GetManifestResourceStream(RuntimeAssembly satellite, String fileName, ref StackCrawlMark stackMark)
{
Contract.Requires(satellite != null, "satellite shouldn't be null; check caller");
Contract.Requires(fileName != null, "fileName shouldn't be null; check caller");
// If we're looking in the main assembly AND if the main assembly was the person who
// created the ResourceManager, skip a security check for private manifest resources.
bool canSkipSecurityCheck = (_mediator.MainAssembly == satellite)
&& (_mediator.CallingAssembly == _mediator.MainAssembly);
Stream stream = satellite.GetManifestResourceStream(_mediator.LocationInfo, fileName, canSkipSecurityCheck, ref stackMark);
if (stream == null)
{
stream = CaseInsensitiveManifestResourceStreamLookup(satellite, fileName);
}
return stream;
}
// Looks up a .resources file in the assembly manifest using
// case-insensitive lookup rules. Yes, this is slow. The metadata
// dev lead refuses to make all assembly manifest resource lookups case-insensitive,
// even optionally case-insensitive.
[System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
private Stream CaseInsensitiveManifestResourceStreamLookup(RuntimeAssembly satellite, String name)
{
Contract.Requires(satellite != null, "satellite shouldn't be null; check caller");
Contract.Requires(name != null, "name shouldn't be null; check caller");
StringBuilder sb = new StringBuilder();
if (_mediator.LocationInfo != null)
{
String nameSpace = _mediator.LocationInfo.Namespace;
if (nameSpace != null)
{
sb.Append(nameSpace);
if (name != null)
sb.Append(Type.Delimiter);
}
}
sb.Append(name);
String givenName = sb.ToString();
CompareInfo comparer = CultureInfo.InvariantCulture.CompareInfo;
String canonicalName = null;
foreach (String existingName in satellite.GetManifestResourceNames())
{
if (comparer.Compare(existingName, givenName, CompareOptions.IgnoreCase) == 0)
{
if (canonicalName == null)
{
canonicalName = existingName;
}
else
{
throw new MissingManifestResourceException(Environment.GetResourceString("MissingManifestResource_MultipleBlobs", givenName, satellite.ToString()));
}
}
}
#if !FEATURE_CORECLR
if (FrameworkEventSource.IsInitialized)
{
if (canonicalName != null)
{
FrameworkEventSource.Log.ResourceManagerCaseInsensitiveResourceStreamLookupSucceeded(_mediator.BaseName, _mediator.MainAssembly, satellite.GetSimpleName(), givenName);
}
else
{
FrameworkEventSource.Log.ResourceManagerCaseInsensitiveResourceStreamLookupFailed(_mediator.BaseName, _mediator.MainAssembly, satellite.GetSimpleName(), givenName);
}
}
#endif
if (canonicalName == null)
{
return null;
}
// If we're looking in the main assembly AND if the main
// assembly was the person who created the ResourceManager,
// skip a security check for private manifest resources.
bool canSkipSecurityCheck = _mediator.MainAssembly == satellite && _mediator.CallingAssembly == _mediator.MainAssembly;
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Stream s = satellite.GetManifestResourceStream(canonicalName, ref stackMark, canSkipSecurityCheck);
// GetManifestResourceStream will return null if we don't have
// permission to read this stream from the assembly. For example,
// if the stream is private and we're trying to access it from another
// assembly (ie, ResMgr in mscorlib accessing anything else), we
// require Reflection TypeInformation permission to be able to read
// this.
#if !FEATURE_CORECLR
if (s!=null) {
if (FrameworkEventSource.IsInitialized)
{
FrameworkEventSource.Log.ResourceManagerManifestResourceAccessDenied(_mediator.BaseName, _mediator.MainAssembly, satellite.GetSimpleName(), canonicalName);
}
}
#endif
return s;
}
[System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
private RuntimeAssembly GetSatelliteAssembly(CultureInfo lookForCulture, ref StackCrawlMark stackMark)
{
if (!_mediator.LookedForSatelliteContractVersion)
{
_mediator.SatelliteContractVersion = _mediator.ObtainSatelliteContractVersion(_mediator.MainAssembly);
_mediator.LookedForSatelliteContractVersion = true;
}
RuntimeAssembly satellite = null;
String satAssemblyName = GetSatelliteAssemblyName();
// Look up the satellite assembly, but don't let problems
// like a partially signed satellite assembly stop us from
// doing fallback and displaying something to the user.
// Yet also somehow log this error for a developer.
try
{
satellite = _mediator.MainAssembly.InternalGetSatelliteAssembly(satAssemblyName, lookForCulture, _mediator.SatelliteContractVersion, false, ref stackMark);
}
// Jun 08: for cases other than ACCESS_DENIED, we'll assert instead of throw to give release builds more opportunity to fallback.
catch (FileLoadException fle)
{
// Ignore cases where the loader gets an access
// denied back from the OS. This showed up for
// href-run exe's at one point.
int hr = fle._HResult;
if (hr != Win32Native.MakeHRFromErrorCode(Win32Native.ERROR_ACCESS_DENIED))
{
Contract.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + " with error code 0x" + hr.ToString("X", CultureInfo.InvariantCulture) + Environment.NewLine + "Exception: " + fle);
}
}
// Don't throw for zero-length satellite assemblies, for compat with v1
catch (BadImageFormatException bife)
{
Contract.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + Environment.NewLine + "Exception: " + bife);
}
#if !FEATURE_CORECLR
if (FrameworkEventSource.IsInitialized)
{
if (satellite != null)
{
FrameworkEventSource.Log.ResourceManagerGetSatelliteAssemblySucceeded(_mediator.BaseName, _mediator.MainAssembly, lookForCulture.Name, satAssemblyName);
}
else
{
FrameworkEventSource.Log.ResourceManagerGetSatelliteAssemblyFailed(_mediator.BaseName, _mediator.MainAssembly, lookForCulture.Name, satAssemblyName);
}
}
#endif
return satellite;
}
// Perf optimization - Don't use Reflection for most cases with
// our .resources files. This makes our code run faster and we can
// creating a ResourceReader via Reflection. This would incur
// a security check (since the link-time check on the constructor that
// takes a String is turned into a full demand with a stack walk)
// and causes partially trusted localized apps to fail.
private bool CanUseDefaultResourceClasses(String readerTypeName, String resSetTypeName)
{
Contract.Assert(readerTypeName != null, "readerTypeName shouldn't be null; check caller");
Contract.Assert(resSetTypeName != null, "resSetTypeName shouldn't be null; check caller");
if (_mediator.UserResourceSet != null)
return false;
// Ignore the actual version of the ResourceReader and
// RuntimeResourceSet classes. Let those classes deal with
// versioning themselves.
AssemblyName mscorlib = new AssemblyName(ResourceManager.MscorlibName);
if (readerTypeName != null)
{
if (!ResourceManager.CompareNames(readerTypeName, ResourceManager.ResReaderTypeName, mscorlib))
return false;
}
if (resSetTypeName != null)
{
if (!ResourceManager.CompareNames(resSetTypeName, ResourceManager.ResSetTypeName, mscorlib))
return false;
}
return true;
}
[System.Security.SecurityCritical]
private String GetSatelliteAssemblyName()
{
String satAssemblyName = _mediator.MainAssembly.GetSimpleName();
satAssemblyName += ".resources";
return satAssemblyName;
}
[System.Security.SecurityCritical]
private void HandleSatelliteMissing()
{
String satAssemName = _mediator.MainAssembly.GetSimpleName() + ".resources.dll";
if (_mediator.SatelliteContractVersion != null)
{
satAssemName += ", Version=" + _mediator.SatelliteContractVersion.ToString();
}
AssemblyName an = new AssemblyName();
an.SetPublicKey(_mediator.MainAssembly.GetPublicKey());
byte[] token = an.GetPublicKeyToken();
int iLen = token.Length;
StringBuilder publicKeyTok = new StringBuilder(iLen * 2);
for (int i = 0; i < iLen; i++)
{
publicKeyTok.Append(token[i].ToString("x", CultureInfo.InvariantCulture));
}
satAssemName += ", PublicKeyToken=" + publicKeyTok;
String missingCultureName = _mediator.NeutralResourcesCulture.Name;
if (missingCultureName.Length == 0)
{
missingCultureName = "<invariant>";
}
throw new MissingSatelliteAssemblyException(Environment.GetResourceString("MissingSatelliteAssembly_Culture_Name", _mediator.NeutralResourcesCulture, satAssemName), missingCultureName);
}
[System.Security.SecurityCritical] // auto-generated
private void HandleResourceStreamMissing(String fileName)
{
// Keep people from bothering me about resources problems
if (_mediator.MainAssembly == typeof(Object).Assembly && _mediator.BaseName.Equals("mscorlib"))
{
// This would break CultureInfo & all our exceptions.
Contract.Assert(false, "Couldn't get mscorlib" + ResourceManager.ResFileExtension + " from mscorlib's assembly" + Environment.NewLine + Environment.NewLine + "Are you building the runtime on your machine? Chances are the BCL directory didn't build correctly. Type 'build -c' in the BCL directory. If you get build errors, look at buildd.log. If you then can't figure out what's wrong (and you aren't changing the assembly-related metadata code), ask a BCL dev.\n\nIf you did NOT build the runtime, you shouldn't be seeing this and you've found a bug.");
// We cannot continue further - simply FailFast.
string mesgFailFast = "mscorlib" + ResourceManager.ResFileExtension + " couldn't be found! Large parts of the BCL won't work!";
System.Environment.FailFast(mesgFailFast);
}
// We really don't think this should happen - we always
// expect the neutral locale's resources to be present.
String resName = String.Empty;
if (_mediator.LocationInfo != null && _mediator.LocationInfo.Namespace != null)
resName = _mediator.LocationInfo.Namespace + Type.Delimiter;
resName += fileName;
throw new MissingManifestResourceException(Environment.GetResourceString("MissingManifestResource_NoNeutralAsm", resName, _mediator.MainAssembly.GetSimpleName()));
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[System.Security.SecurityCritical] // Our security team doesn't yet allow safe-critical P/Invoke methods.
[System.Security.SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetNeutralResourcesLanguageAttribute(RuntimeAssembly assemblyHandle, StringHandleOnStack cultureName, out short fallbackLocation);
}
}
| |
// 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.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public class GroupJoinTests
{
private const int KeyFactor = 8;
private const int ElementFactor = 4;
public static IEnumerable<object[]> GroupJoinData(int[] leftCounts, int[] rightCounts)
{
foreach (object[] parms in UnorderedSources.BinaryRanges(leftCounts, rightCounts))
{
yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], parms[2], parms[3] };
}
}
//
// GroupJoin
//
[Theory]
[MemberData("BinaryRanges", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 }, MemberType = typeof(UnorderedSources))]
public static void GroupJoin_Unordered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, leftCount);
foreach (var p in leftQuery.GroupJoin(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)))
{
seen.Add(p.Key);
if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor)
{
Assert.Equal(p.Key * KeyFactor, Assert.Single(p.Value));
}
else
{
Assert.Empty(p.Value);
}
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("BinaryRanges", new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 4, 1024 * 8 }, MemberType = typeof(UnorderedSources))]
public static void GroupJoin_Unordered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
GroupJoin_Unordered(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("GroupJoinData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 })]
public static void GroupJoin(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
foreach (var p in leftQuery.GroupJoin(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)))
{
Assert.Equal(seen++, p.Key);
if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor)
{
Assert.Equal(p.Key * KeyFactor, Assert.Single(p.Value));
}
else
{
Assert.Empty(p.Value);
}
}
Assert.Equal(leftCount, seen);
}
[Theory]
[OuterLoop]
[MemberData("GroupJoinData", new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 4, 1024 * 8 })]
public static void GroupJoin_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
GroupJoin(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("BinaryRanges", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 }, MemberType = typeof(UnorderedSources))]
public static void GroupJoin_Unordered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, leftCount);
Assert.All(leftQuery.GroupJoin(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)).ToList(),
p =>
{
seen.Add(p.Key);
if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor)
{
Assert.Equal(p.Key * KeyFactor, Assert.Single(p.Value));
}
else
{
Assert.Empty(p.Value);
}
});
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("BinaryRanges", new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 4, 1024 * 8 }, MemberType = typeof(UnorderedSources))]
public static void GroupJoin_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
GroupJoin_Unordered_NotPipelined(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("GroupJoinData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 })]
public static void GroupJoin_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
Assert.All(leftQuery.GroupJoin(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)).ToList(),
p =>
{
Assert.Equal(seen++, p.Key);
if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor)
{
Assert.Equal(p.Key * KeyFactor, Assert.Single(p.Value));
}
else
{
Assert.Empty(p.Value);
}
});
Assert.Equal(leftCount, seen);
}
[Theory]
[OuterLoop]
[MemberData("GroupJoinData", new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 4, 1024 * 8 })]
public static void GroupJoin_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
GroupJoin_NotPipelined(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("BinaryRanges", new int[] { 0, 1, 2, 15, 16 }, new int[] { 0, 1, 16 }, MemberType = typeof(UnorderedSources))]
public static void GroupJoin_Unordered_Multiple(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seenOuter = new IntegerRangeSet(0, leftCount);
Assert.All(leftQuery.GroupJoin(rightQuery, x => x, y => y / KeyFactor, (x, y) => KeyValuePair.Create(x, y)),
p =>
{
seenOuter.Add(p.Key);
if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor)
{
IntegerRangeSet seenInner = new IntegerRangeSet(p.Key * KeyFactor, Math.Min(rightCount - p.Key * KeyFactor, KeyFactor));
Assert.All(p.Value, y => { Assert.Equal(p.Key, y / KeyFactor); seenInner.Add(y); });
seenInner.AssertComplete();
}
else
{
Assert.Empty(p.Value);
}
});
seenOuter.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("BinaryRanges", new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 4, 1024 * 8 }, MemberType = typeof(UnorderedSources))]
public static void GroupJoin_Unordered_Multiple_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
GroupJoin_Unordered_Multiple(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("GroupJoinData", new int[] { 0, 1, 2, 15, 16 }, new int[] { 0, 1, 16 })]
// GroupJoin doesn't always return elements from the right in order. See Issue #1155
public static void GroupJoin_Multiple(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seenOuter = 0;
Assert.All(leftQuery.GroupJoin(rightQuery, x => x, y => y / KeyFactor, (x, y) => KeyValuePair.Create(x, y)),
p =>
{
Assert.Equal(seenOuter++, p.Key);
if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor)
{
IntegerRangeSet seenInner = new IntegerRangeSet(p.Key * KeyFactor, Math.Min(rightCount - p.Key * KeyFactor, KeyFactor));
Assert.All(p.Value, y => { Assert.Equal(p.Key, y / KeyFactor); seenInner.Add(y); });
seenInner.AssertComplete();
}
else
{
Assert.Empty(p.Value);
}
});
Assert.Equal(leftCount, seenOuter);
}
[Theory]
[OuterLoop]
[MemberData("GroupJoinData", new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 4, 1024 * 8 })]
public static void GroupJoin_Multiple_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
GroupJoin_Multiple(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("BinaryRanges", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 }, MemberType = typeof(UnorderedSources))]
public static void GroupJoin_Unordered_CustomComparator(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seenOuter = new IntegerRangeSet(0, leftCount);
Assert.All(leftQuery.GroupJoin(rightQuery, x => x, y => y % ElementFactor, (x, y) => KeyValuePair.Create(x, y), new ModularCongruenceComparer(KeyFactor)),
p =>
{
seenOuter.Add(p.Key);
if (p.Key % KeyFactor < Math.Min(ElementFactor, rightCount))
{
IntegerRangeSet seenInner = new IntegerRangeSet(0, (rightCount + (ElementFactor - 1) - p.Key % ElementFactor) / ElementFactor);
Assert.All(p.Value, y => { Assert.Equal(p.Key % KeyFactor, y % ElementFactor); seenInner.Add(y / ElementFactor); });
seenInner.AssertComplete();
}
else
{
Assert.Empty(p.Value);
}
});
seenOuter.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("BinaryRanges", new int[] { 512, 1024 }, new int[] { 0, 1, 1024, 1024 * 4 }, MemberType = typeof(UnorderedSources))]
public static void GroupJoin_Unordered_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
GroupJoin_Unordered_CustomComparator(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("GroupJoinData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 })]
public static void GroupJoin_CustomComparator(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seenOuter = 0;
Assert.All(leftQuery.GroupJoin(rightQuery, x => x, y => y % ElementFactor, (x, y) => KeyValuePair.Create(x, y), new ModularCongruenceComparer(KeyFactor)),
p =>
{
Assert.Equal(seenOuter++, p.Key);
if (p.Key % KeyFactor < Math.Min(ElementFactor, rightCount))
{
IntegerRangeSet seenInner = new IntegerRangeSet(0, (rightCount + (ElementFactor - 1) - p.Key % ElementFactor) / ElementFactor);
Assert.All(p.Value, y => { Assert.Equal(p.Key % KeyFactor, y % ElementFactor); seenInner.Add(y / ElementFactor); });
seenInner.AssertComplete();
}
else
{
Assert.Empty(p.Value);
}
});
Assert.Equal(leftCount, seenOuter);
}
[Theory]
[OuterLoop]
[MemberData("GroupJoinData", new int[] { 512, 1024 }, new int[] { 0, 1, 1024, 1024 * 4 })]
public static void GroupJoin_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
GroupJoin_CustomComparator(left, leftCount, right, rightCount);
}
[Fact]
public static void GroupJoin_NotSupportedException()
{
#pragma warning disable 618
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(Enumerable.Range(0, 1), i => i, i => i, (i, j) => i));
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(Enumerable.Range(0, 1), i => i, i => i, (i, j) => i, null));
#pragma warning restore 618
}
[Fact]
// Should not get the same setting from both operands.
public static void GroupJoin_NoDuplicateSettings()
{
CancellationToken t = new CancellationTokenSource().Token;
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).GroupJoin(ParallelEnumerable.Range(0, 1).WithCancellation(t), x => x, y => y, (x, e) => e));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).GroupJoin(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1), x => x, y => y, (x, e) => e));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).GroupJoin(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default), x => x, y => y, (x, e) => e));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).GroupJoin(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default), x => x, y => y, (x, e) => e));
}
[Fact]
public static void GroupJoin_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, i => i, (i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupJoin((ParallelQuery<int>)null, i => i, i => i, (i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), (Func<int, int>)null, i => i, (i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, (Func<int, int>)null, (i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, i => i, (Func<int, IEnumerable<int>, int>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, i => i, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupJoin((ParallelQuery<int>)null, i => i, i => i, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), (Func<int, int>)null, i => i, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, (Func<int, int>)null, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, i => i, (Func<int, IEnumerable<int>, int>)null, EqualityComparer<int>.Default));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Diagnostics;
using System.ComponentModel;
using System.Xml;
using System.IO;
using System.Globalization;
using System.Text;
namespace System.Xml.Schema
{
/// <include file='doc\XmlSchemaDatatype.uex' path='docs/doc[@for="XmlSchemaDatatype"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public abstract class XmlSchemaDatatype
{
/// <include file='doc\XmlSchemaDatatype.uex' path='docs/doc[@for="XmlSchemaDatatype.ValueType"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public abstract Type ValueType { get; }
/// <include file='doc\XmlSchemaDatatype.uex' path='docs/doc[@for="XmlSchemaDatatype.TokenizedType"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public abstract XmlTokenizedType TokenizedType { get; }
/// <include file='doc\XmlSchemaDatatype.uex' path='docs/doc[@for="XmlSchemaDatatype.ParseValue"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public abstract object ParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr);
/// <include file='doc\XmlSchemaDatatype.uex' path='docs/doc[@for="XmlSchemaDatatype.Variety"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public virtual XmlSchemaDatatypeVariety Variety { get { return XmlSchemaDatatypeVariety.Atomic; } }
/// <include file='doc\XmlSchemaDatatype.uex' path='docs/doc[@for="XmlSchemaDatatype.ChangeType1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public virtual object ChangeType(object value, Type targetType)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (targetType == null)
{
throw new ArgumentNullException(nameof(targetType));
}
return ValueConverter.ChangeType(value, targetType);
}
/// <include file='doc\XmlSchemaDatatype.uex' path='docs/doc[@for="XmlSchemaDatatype.ChangeType2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public virtual object ChangeType(object value, Type targetType, IXmlNamespaceResolver namespaceResolver)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (targetType == null)
{
throw new ArgumentNullException(nameof(targetType));
}
if (namespaceResolver == null)
{
throw new ArgumentNullException(nameof(namespaceResolver));
}
return ValueConverter.ChangeType(value, targetType, namespaceResolver);
}
/// <include file='doc\XmlSchemaDatatype.uex' path='docs/doc[@for="XmlSchemaDatatype.TypeCode"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public virtual XmlTypeCode TypeCode { get { return XmlTypeCode.None; } }
/// <include file='doc\XmlSchemaDatatype.uex' path='docs/doc[@for="XmlSchemaDatatype.IsDerivedFrom"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public virtual bool IsDerivedFrom(XmlSchemaDatatype datatype)
{
return false;
}
internal abstract bool HasLexicalFacets { get; }
internal abstract bool HasValueFacets { get; }
internal abstract XmlValueConverter ValueConverter { get; }
internal abstract RestrictionFacets Restriction { get; set; }
internal abstract int Compare(object value1, object value2);
internal abstract object ParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, bool createAtomicValue);
internal abstract Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue);
internal abstract Exception TryParseValue(object value, XmlNameTable nameTable, IXmlNamespaceResolver namespaceResolver, out object typedValue);
internal abstract FacetsChecker FacetsChecker { get; }
internal abstract XmlSchemaWhiteSpace BuiltInWhitespaceFacet { get; }
internal abstract XmlSchemaDatatype DeriveByRestriction(XmlSchemaObjectCollection facets, XmlNameTable nameTable, XmlSchemaType schemaType);
internal abstract XmlSchemaDatatype DeriveByList(XmlSchemaType schemaType);
internal abstract void VerifySchemaValid(XmlSchemaObjectTable notations, XmlSchemaObject caller);
internal abstract bool IsEqual(object o1, object o2);
internal abstract bool IsComparable(XmlSchemaDatatype dtype);
//Error message helper
internal string TypeCodeString
{
get
{
string typeCodeString = string.Empty;
XmlTypeCode typeCode = this.TypeCode;
switch (this.Variety)
{
case XmlSchemaDatatypeVariety.List:
if (typeCode == XmlTypeCode.AnyAtomicType)
{ //List of union
typeCodeString = "List of Union";
}
else
{
typeCodeString = "List of " + TypeCodeToString(typeCode);
}
break;
case XmlSchemaDatatypeVariety.Union:
typeCodeString = "Union";
break;
case XmlSchemaDatatypeVariety.Atomic:
if (typeCode == XmlTypeCode.AnyAtomicType)
{
typeCodeString = "anySimpleType";
}
else
{
typeCodeString = TypeCodeToString(typeCode);
}
break;
}
return typeCodeString;
}
}
internal string TypeCodeToString(XmlTypeCode typeCode)
{
switch (typeCode)
{
case XmlTypeCode.None:
return "None";
case XmlTypeCode.Item:
return "AnyType";
case XmlTypeCode.AnyAtomicType:
return "AnyAtomicType";
case XmlTypeCode.String:
return "String";
case XmlTypeCode.Boolean:
return "Boolean";
case XmlTypeCode.Decimal:
return "Decimal";
case XmlTypeCode.Float:
return "Float";
case XmlTypeCode.Double:
return "Double";
case XmlTypeCode.Duration:
return "Duration";
case XmlTypeCode.DateTime:
return "DateTime";
case XmlTypeCode.Time:
return "Time";
case XmlTypeCode.Date:
return "Date";
case XmlTypeCode.GYearMonth:
return "GYearMonth";
case XmlTypeCode.GYear:
return "GYear";
case XmlTypeCode.GMonthDay:
return "GMonthDay";
case XmlTypeCode.GDay:
return "GDay";
case XmlTypeCode.GMonth:
return "GMonth";
case XmlTypeCode.HexBinary:
return "HexBinary";
case XmlTypeCode.Base64Binary:
return "Base64Binary";
case XmlTypeCode.AnyUri:
return "AnyUri";
case XmlTypeCode.QName:
return "QName";
case XmlTypeCode.Notation:
return "Notation";
case XmlTypeCode.NormalizedString:
return "NormalizedString";
case XmlTypeCode.Token:
return "Token";
case XmlTypeCode.Language:
return "Language";
case XmlTypeCode.NmToken:
return "NmToken";
case XmlTypeCode.Name:
return "Name";
case XmlTypeCode.NCName:
return "NCName";
case XmlTypeCode.Id:
return "Id";
case XmlTypeCode.Idref:
return "Idref";
case XmlTypeCode.Entity:
return "Entity";
case XmlTypeCode.Integer:
return "Integer";
case XmlTypeCode.NonPositiveInteger:
return "NonPositiveInteger";
case XmlTypeCode.NegativeInteger:
return "NegativeInteger";
case XmlTypeCode.Long:
return "Long";
case XmlTypeCode.Int:
return "Int";
case XmlTypeCode.Short:
return "Short";
case XmlTypeCode.Byte:
return "Byte";
case XmlTypeCode.NonNegativeInteger:
return "NonNegativeInteger";
case XmlTypeCode.UnsignedLong:
return "UnsignedLong";
case XmlTypeCode.UnsignedInt:
return "UnsignedInt";
case XmlTypeCode.UnsignedShort:
return "UnsignedShort";
case XmlTypeCode.UnsignedByte:
return "UnsignedByte";
case XmlTypeCode.PositiveInteger:
return "PositiveInteger";
default:
return typeCode.ToString();
}
}
internal static string ConcatenatedToString(object value)
{
Type t = value.GetType();
string stringValue = string.Empty;
if (t == typeof(IEnumerable) && t != typeof(string))
{
StringBuilder bldr = new StringBuilder();
IEnumerator enumerator = (value as IEnumerable).GetEnumerator();
if (enumerator.MoveNext())
{
bldr.Append("{");
object cur = enumerator.Current;
if (cur is IFormattable)
{
bldr.Append(((IFormattable)cur).ToString("", CultureInfo.InvariantCulture));
}
else
{
bldr.Append(cur.ToString());
}
while (enumerator.MoveNext())
{
bldr.Append(" , ");
cur = enumerator.Current;
if (cur is IFormattable)
{
bldr.Append(((IFormattable)cur).ToString("", CultureInfo.InvariantCulture));
}
else
{
bldr.Append(cur.ToString());
}
}
bldr.Append("}");
stringValue = bldr.ToString();
}
}
else if (value is IFormattable)
{
stringValue = ((IFormattable)value).ToString("", CultureInfo.InvariantCulture);
}
else
{
stringValue = value.ToString();
}
return stringValue;
}
internal static XmlSchemaDatatype FromXmlTokenizedType(XmlTokenizedType token)
{
return DatatypeImplementation.FromXmlTokenizedType(token);
}
internal static XmlSchemaDatatype FromXmlTokenizedTypeXsd(XmlTokenizedType token)
{
return DatatypeImplementation.FromXmlTokenizedTypeXsd(token);
}
internal static XmlSchemaDatatype FromXdrName(string name)
{
return DatatypeImplementation.FromXdrName(name);
}
internal static XmlSchemaDatatype DeriveByUnion(XmlSchemaSimpleType[] types, XmlSchemaType schemaType)
{
return DatatypeImplementation.DeriveByUnion(types, schemaType);
}
internal static string XdrCanonizeUri(string uri, XmlNameTable nameTable, SchemaNames schemaNames)
{
string canonicalUri;
int offset = 5;
bool convert = false;
if (uri.Length > 5 && uri.StartsWith("uuid:", StringComparison.Ordinal))
{
convert = true;
}
else if (uri.Length > 9 && uri.StartsWith("urn:uuid:", StringComparison.Ordinal))
{
convert = true;
offset = 9;
}
if (convert)
{
canonicalUri = nameTable.Add(uri.Substring(0, offset) + CultureInfo.InvariantCulture.TextInfo.ToUpper(uri.Substring(offset, uri.Length - offset)));
}
else
{
canonicalUri = uri;
}
if (
Ref.Equal(schemaNames.NsDataTypeAlias, canonicalUri) ||
Ref.Equal(schemaNames.NsDataTypeOld, canonicalUri)
)
{
canonicalUri = schemaNames.NsDataType;
}
else if (Ref.Equal(schemaNames.NsXdrAlias, canonicalUri))
{
canonicalUri = schemaNames.NsXdr;
}
return canonicalUri;
}
}
}
| |
// Copyright 2004-2009 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.DynamicProxy.Test
{
using System;
using System.Collections;
using System.Data;
using System.Reflection;
using NUnit.Framework;
using Castle.DynamicProxy;
using Castle.DynamicProxy.Test.Classes;
using Castle.DynamicProxy.Test.Interceptors;
using Castle.DynamicProxy.Test.ClassInterfaces;
[TestFixture]
public class ProxyGeneratorTestCase
{
private ProxyGenerator _generator;
[SetUp]
public void Init()
{
_generator = new ProxyGenerator();
}
[Test]
public void ProxyForClass()
{
object proxy = _generator.CreateClassProxy(
typeof(ServiceClass), new ResultModifiedInvocationHandler( ) );
Assert.IsNotNull( proxy );
Assert.IsTrue( typeof(ServiceClass).IsAssignableFrom( proxy.GetType() ) );
ServiceClass inter = (ServiceClass) proxy;
Assert.AreEqual( 44, inter.Sum( 20, 25 ) );
Assert.AreEqual( true, inter.Valid );
}
[Test]
public void ProxyForClassWithInterfaces()
{
object proxy = _generator.CreateClassProxy( typeof(ServiceClass), new Type[] { typeof(IDisposable) },
new ResultModifiedInvocationHandler( ) );
Assert.IsNotNull( proxy );
Assert.IsTrue( typeof(ServiceClass).IsAssignableFrom( proxy.GetType() ) );
Assert.IsTrue( typeof(IDisposable).IsAssignableFrom( proxy.GetType() ) );
ServiceClass inter = (ServiceClass) proxy;
Assert.AreEqual( 44, inter.Sum( 20, 25 ) );
Assert.AreEqual( true, inter.Valid );
}
[Test]
public void ProxyForClassWithSuperClass()
{
object proxy = _generator.CreateClassProxy(
typeof(SpecializedServiceClass), new ResultModifiedInvocationHandler( ) );
Assert.IsNotNull( proxy );
Assert.IsTrue( typeof(ServiceClass).IsAssignableFrom( proxy.GetType() ) );
Assert.IsTrue( typeof(SpecializedServiceClass).IsAssignableFrom( proxy.GetType() ) );
SpecializedServiceClass inter = (SpecializedServiceClass) proxy;
Assert.AreEqual( 44, inter.Sum( 20, 25 ) );
Assert.AreEqual( -6, inter.Subtract( 20, 25 ) );
Assert.AreEqual( true, inter.Valid );
}
[Test]
public void ProxyForClassWhichImplementsInterfaces()
{
object proxy = _generator.CreateClassProxy(
typeof(MyInterfaceImpl), new ResultModifiedInvocationHandler( ) );
Assert.IsNotNull( proxy );
Assert.IsTrue( typeof(MyInterfaceImpl).IsAssignableFrom( proxy.GetType() ) );
Assert.IsTrue( typeof(IMyInterface).IsAssignableFrom( proxy.GetType() ) );
IMyInterface inter = (IMyInterface) proxy;
Assert.AreEqual( 44, inter.Calc( 20, 25 ) );
}
[Test]
public void ProxyingClassWithoutVirtualMethods()
{
NoVirtualMethodClass proxy = (NoVirtualMethodClass) _generator.CreateClassProxy(
typeof(NoVirtualMethodClass), new StandardInterceptor( ) );
Assert.IsNotNull(proxy);
}
[Test]
public void ProxyingClassWithSealedMethods()
{
SealedMethodsClass proxy = (SealedMethodsClass) _generator.CreateClassProxy(
typeof(SealedMethodsClass), new StandardInterceptor() );
Assert.IsNotNull(proxy);
}
[Test]
public void HashtableProxy()
{
object proxy = _generator.CreateClassProxy(
typeof(Hashtable), new HashtableInterceptor() );
Assert.IsTrue( typeof(Hashtable).IsAssignableFrom( proxy.GetType() ) );
object value = (proxy as Hashtable)["key"];
Assert.IsTrue(value is String);
Assert.AreEqual("default", value.ToString());
}
[Test, ExpectedException(typeof(ArgumentException))]
public void CreateClassProxyInvalidBaseClass()
{
_generator.CreateClassProxy(
typeof(ICloneable), new StandardInterceptor( ) );
}
[Test, ExpectedException(typeof(ArgumentNullException))]
public void CreateClassProxyNullBaseClass()
{
_generator.CreateClassProxy(
null, new StandardInterceptor( ) );
}
[Test, ExpectedException(typeof(ArgumentNullException))]
public void CreateClassProxyNullInterceptor()
{
_generator.CreateClassProxy(
typeof(SpecializedServiceClass), null );
}
[Test]
public void TestGenerationSimpleInterface()
{
object proxy = _generator.CreateProxy(
typeof(IMyInterface), new ResultModifiedInvocationHandler(), new MyInterfaceImpl() );
Assert.IsNotNull( proxy );
Assert.IsTrue( typeof(IMyInterface).IsAssignableFrom( proxy.GetType() ) );
IMyInterface inter = (IMyInterface) proxy;
Assert.AreEqual( 44, inter.Calc( 20, 25 ) );
inter.Name = "opa";
Assert.AreEqual( "opa", inter.Name );
inter.Started = true;
Assert.AreEqual( true, inter.Started );
}
[Test]
public void UsingCache()
{
object proxy = _generator.CreateProxy(
typeof(IMyInterface), new StandardInterceptor(), new MyInterfaceImpl() );
Assert.IsNotNull( proxy );
Assert.IsTrue( typeof(IMyInterface).IsAssignableFrom( proxy.GetType() ) );
proxy = _generator.CreateProxy(
typeof(IMyInterface), new StandardInterceptor(), new MyInterfaceImpl() );
}
[Test]
public void TestGenerationWithInterfaceHeritage()
{
object proxy = _generator.CreateProxy(
typeof(IMySecondInterface), new StandardInterceptor( ), new MySecondInterfaceImpl() );
Assert.IsNotNull( proxy );
Assert.IsTrue( typeof(IMyInterface).IsAssignableFrom( proxy.GetType() ) );
Assert.IsTrue( typeof(IMySecondInterface).IsAssignableFrom( proxy.GetType() ) );
IMySecondInterface inter = (IMySecondInterface) proxy;
inter.Calc(1, 1);
inter.Name = "hammett";
Assert.AreEqual( "hammett", inter.Name );
inter.Address = "pereira leite, 44";
Assert.AreEqual( "pereira leite, 44", inter.Address );
Assert.AreEqual( 45, inter.Calc( 20, 25 ) );
}
[Test]
public void ClassWithConstructors()
{
object proxy = _generator.CreateClassProxy(
typeof(ClassWithConstructors),
new StandardInterceptor(),
new ArrayList() );
Assert.IsNotNull( proxy );
ClassWithConstructors objProxy = (ClassWithConstructors) proxy;
Assert.IsNotNull( objProxy.List );
Assert.IsNull( objProxy.Dictionary );
proxy = _generator.CreateClassProxy(
typeof(ClassWithConstructors),
new StandardInterceptor(),
new ArrayList(), new Hashtable() );
Assert.IsNotNull( proxy );
objProxy = (ClassWithConstructors) proxy;
Assert.IsNotNull( objProxy.List );
Assert.IsNotNull( objProxy.Dictionary );
}
[Test]
public void TestEnumProperties()
{
ServiceStatusImpl service = new ServiceStatusImpl();
object proxy = _generator.CreateProxy(
typeof(IServiceStatus), new StandardInterceptor( ), service );
Assert.IsNotNull( proxy );
Assert.IsTrue( typeof(IServiceStatus).IsAssignableFrom( proxy.GetType() ) );
IServiceStatus inter = (IServiceStatus) proxy;
Assert.AreEqual( State.Invalid, inter.ActualState );
inter.ChangeState( State.Valid );
Assert.AreEqual( State.Valid, inter.ActualState );
}
[Test]
public void TestAttributesForInterfaceProxies()
{
ServiceStatusImpl service = new ServiceStatusImpl();
object proxy = _generator.CreateProxy(
typeof(IServiceStatus), new MyInterfaceProxy( ), service );
Assert.IsNotNull( proxy );
Assert.IsTrue( typeof(IServiceStatus).IsAssignableFrom( proxy.GetType() ) );
IServiceStatus inter = (IServiceStatus) proxy;
Assert.AreEqual( State.Invalid, inter.ActualState );
inter.ChangeState( State.Valid );
Assert.AreEqual( State.Valid, inter.ActualState );
}
[Test]
public void ProxyForClassWithGuidProperty()
{
object proxy = _generator.CreateClassProxy(
typeof(ClassWithGuid), new StandardInterceptor() );
Assert.IsNotNull( proxy );
Assert.IsTrue( typeof(ClassWithGuid).IsAssignableFrom( proxy.GetType() ) );
ClassWithGuid inter = (ClassWithGuid) proxy;
Assert.IsNotNull( inter.GooId );
}
[Test]
public void ProxyingClassWithSByteEnum()
{
ClassWithSByteEnum proxy = (ClassWithSByteEnum)
_generator.CreateClassProxy(
typeof(ClassWithSByteEnum), new StandardInterceptor() );
Assert.IsNotNull(proxy);
}
[Test]
public void ProxyForMarshalByRefClass()
{
ClassMarshalByRef proxy = (ClassMarshalByRef)
_generator.CreateClassProxy(
typeof(ClassMarshalByRef), new StandardInterceptor());
Assert.IsNotNull(proxy);
object o = new object();
Assert.AreEqual(o, proxy.Ping(o));
int i = 10;
Assert.AreEqual(i, proxy.Pong(i));
}
[Test]
[Category("DotNetOnly")]
public void ProxyForRefAndOutClassWithPrimitiveTypeParams()
{
LogInvokeInterceptor interceptor = new LogInvokeInterceptor();
RefAndOutClass proxy = (RefAndOutClass)
_generator.CreateClassProxy(
typeof(RefAndOutClass), interceptor);
Assert.IsNotNull(proxy);
int int1 = -3;
proxy.RefInt(ref int1);
Assert.AreEqual(-2, int1);
char c = 'z';
proxy.RefChar(ref c);
Assert.AreEqual('a', c);
c = 'z';
proxy.OutChar(out c);
Assert.AreEqual('b', c);
int int2;
proxy.OutInt(out int2);
Assert.AreEqual(2, int2);
Assert.AreEqual("RefInt RefChar OutChar OutInt ", interceptor.LogContents);
}
[Test]
[Category("DotNetOnly")]
public void ProxyForRefAndOutClassWithReferenceTypeParams()
{
LogInvokeInterceptor interceptor = new LogInvokeInterceptor();
RefAndOutClass proxy = (RefAndOutClass)
_generator.CreateClassProxy(
typeof(RefAndOutClass), interceptor);
Assert.IsNotNull(proxy);
string string1 = "foobar";
proxy.RefString(ref string1);
Assert.AreEqual("foobar_string", string1);
string string2;
proxy.OutString(out string2);
Assert.AreEqual("string", string2);
Assert.AreEqual("RefString OutString ", interceptor.LogContents);
}
[Test]
[Category("DotNetOnly")]
public void ProxyForRefAndOutClassWithStructTypeParams()
{
LogInvokeInterceptor interceptor = new LogInvokeInterceptor();
RefAndOutClass proxy = (RefAndOutClass)
_generator.CreateClassProxy(
typeof(RefAndOutClass), interceptor);
Assert.IsNotNull(proxy);
DateTime dt1 = new DateTime(1999, 1, 1);
proxy.RefDateTime(ref dt1);
Assert.AreEqual(new DateTime(2000, 1, 1), dt1);
DateTime dt2;
proxy.OutDateTime(out dt2);
Assert.AreEqual(new DateTime(2005, 1, 1), dt2);
Assert.AreEqual("RefDateTime OutDateTime ", interceptor.LogContents);
}
[Test]
[Category("DotNetOnly")]
public void ProxyForRefAndOutClassWithEnumTypeParams()
{
LogInvokeInterceptor interceptor = new LogInvokeInterceptor();
RefAndOutClass proxy = (RefAndOutClass)
_generator.CreateClassProxy(
typeof(RefAndOutClass), interceptor);
Assert.IsNotNull(proxy);
SByteEnum value1 = SByteEnum.One;
proxy.RefSByteEnum(ref value1);
Assert.AreEqual(SByteEnum.Two, value1);
SByteEnum value2;
proxy.OutSByteEnum(out value2);
Assert.AreEqual(SByteEnum.Two, value2);
Assert.AreEqual("RefSByteEnum OutSByteEnum ", interceptor.LogContents);
}
[Test]
[Category("DotNetOnly")]
public void ProxyForRefAndOutClassWithPrimitiveTypeParamsWhereInterceptorModifiesTheValues()
{
RefAndOutInterceptor interceptor = new RefAndOutInterceptor();
RefAndOutClass proxy = (RefAndOutClass)
_generator.CreateClassProxy(
typeof(RefAndOutClass), interceptor);
Assert.IsNotNull(proxy);
int arg1 = -3;
proxy.RefInt(ref arg1);
Assert.AreEqual(98, arg1);
int arg2;
proxy.OutInt(out arg2);
Assert.AreEqual(102, arg2);
Assert.AreEqual("RefInt OutInt ", interceptor.LogContents);
}
[Test]
[Category("DotNetOnly")]
public void ProxyForRefAndOutClassWithReferenceTypeParamsWhereInterceptorModifiesTheValues()
{
RefAndOutInterceptor interceptor = new RefAndOutInterceptor();
RefAndOutClass proxy = (RefAndOutClass)
_generator.CreateClassProxy(
typeof(RefAndOutClass), interceptor);
Assert.IsNotNull(proxy);
string string1 = "foobar";
proxy.RefString(ref string1);
Assert.AreEqual("foobar_string_xxx", string1);
string string2;
proxy.OutString(out string2);
Assert.AreEqual("string_xxx", string2);
Assert.AreEqual("RefString OutString ", interceptor.LogContents);
}
[Test]
[Category("DotNetOnly")]
public void ProxyForRefAndOutClassWithStructTypeParamsWhereInterceptorModifiesTheValues()
{
RefAndOutInterceptor interceptor = new RefAndOutInterceptor();
RefAndOutClass proxy = (RefAndOutClass)
_generator.CreateClassProxy(
typeof(RefAndOutClass), interceptor);
Assert.IsNotNull(proxy);
DateTime dt1 = new DateTime(1999, 1, 1);
proxy.RefDateTime(ref dt1);
Assert.AreEqual(new DateTime(2000, 2, 1), dt1);
DateTime dt2;
proxy.OutDateTime(out dt2);
Assert.AreEqual(new DateTime(2005, 2, 1), dt2);
Assert.AreEqual("RefDateTime OutDateTime ", interceptor.LogContents);
}
[Test]
[Category("DotNetOnly")]
public void ProxyForRefAndOutClassWithEnumTypeParamsWhereInterceptorModifiesTheValues()
{
RefAndOutInterceptor interceptor = new RefAndOutInterceptor();
RefAndOutClass proxy = (RefAndOutClass)
_generator.CreateClassProxy(
typeof(RefAndOutClass), interceptor);
Assert.IsNotNull(proxy);
SByteEnum value1 = SByteEnum.One;
proxy.RefSByteEnum(ref value1);
Assert.AreEqual(SByteEnum.One, value1);
SByteEnum value2;
proxy.OutSByteEnum(out value2);
Assert.AreEqual(SByteEnum.One, value2);
Assert.AreEqual("RefSByteEnum OutSByteEnum ", interceptor.LogContents);
}
[Test]
public void ProtectedProperties()
{
object proxy = _generator.CreateClassProxy(
typeof(ClassWithProtectedMethods), new StandardInterceptor() );
Assert.IsTrue( proxy is ClassWithProtectedMethods );
}
[Test]
public void Indexer()
{
object proxy = _generator.CreateClassProxy(
typeof(ClassWithIndexer), new StandardInterceptor() );
Assert.IsTrue( proxy is ClassWithIndexer );
}
[Test]
public void Indexer2()
{
IndexerInterface proxy = (IndexerInterface)
_generator.CreateProxy( typeof(IndexerInterface),
new StandardInterceptor(), new IndexerClass() );
Assert.IsNotNull( proxy );
string dummy = proxy["1"];
dummy = proxy[1];
}
[Test]
public void ReflectionTest()
{
object proxy = _generator.CreateClassProxy(
typeof(MySerializableClass), new StandardInterceptor() );
Type type = proxy.GetType();
Assert.IsNotNull(type);
PropertyInfo info = type.GetProperty("Current", BindingFlags.DeclaredOnly|BindingFlags.Public|BindingFlags.Instance);
Assert.IsNotNull(info);
}
[Test]
public void MethodsAreInterceptedInChain()
{
LogInvocationInterceptor interceptor = new LogInvocationInterceptor();
object proxy = _generator.CreateClassProxy(
typeof(ServiceClass2), interceptor);
ServiceClass2 obj = (ServiceClass2) proxy;
obj.DoSomething();
obj.DoOtherThing();
Assert.AreEqual(4, interceptor.Invocations.Length);
Assert.AreEqual("DoOtherThing", interceptor.Invocations[0]);
Assert.AreEqual("DoSomethingElse", interceptor.Invocations[1]);
Assert.AreEqual("DoOtherThing", interceptor.Invocations[2]);
Assert.AreEqual("DoSomethingElse", interceptor.Invocations[3]);
}
/// <summary>
/// See http://support.castleproject.org/browse/DYNPROXY-42
/// </summary>
[Test]
public void NameBugReportedTest()
{
ProxyGenerator proxyGenerator = new ProxyGenerator();
Castle.DynamicProxy.Test.ClassInterfaces.C.IBubu bubuC = (Castle.DynamicProxy.Test.ClassInterfaces.C.IBubu)
proxyGenerator.CreateProxy(typeof(Castle.DynamicProxy.Test.ClassInterfaces.C.IBubu), new SimpleInterceptor(), new object());
bubuC.OperationA();
Castle.DynamicProxy.Test.ClassInterfaces.D.IBubu bubuD = (Castle.DynamicProxy.Test.ClassInterfaces.D.IBubu)
proxyGenerator.CreateProxy(typeof(Castle.DynamicProxy.Test.ClassInterfaces.D.IBubu), new SimpleInterceptor(), new object());
bubuD.OperationB();
}
[Test]
public void IDataReaderProxyGeneration()
{
IDataReader reader = IDataReaderProxy.NewInstance( new DummyReader() );
}
}
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using NUnit.Framework;
using Sensus.Concurrent;
namespace Sensus.Tests.Concurrent
{
[TestFixture]
public class ConcurrentObservableCollectionTests
{
#region Fields
private const int DelayTime = 2;
private readonly IConcurrent Concurrent;
#endregion
public ConcurrentObservableCollectionTests(): this(new LockConcurrent())
{ }
public ConcurrentObservableCollectionTests(IConcurrent concurrent)
{
Concurrent = concurrent;
}
[Test(Description="If this fails the DelayTime likely isn't large enough to cause a failure if future tests break.")]
public void DelayIsLongEnough()
{
var test = new List<int> { 1, 2, 3 };
var task1 = Task.Run(() =>
{
foreach (var i in test)
{
Task.Delay(DelayTime).Wait();
}
});
var task2 = Task.Run(() =>
{
test.Insert(0, 4);
Task.Delay(DelayTime).Wait();
test.Insert(0, 5);
});
Assert.Throws<AggregateException>(() => Task.WaitAll(task1, task2));
}
[Test]
public void AddIsThreadSafe()
{
var test = new ConcurrentObservableCollection<int> (Concurrent) { 1, 2, 3 };
var task1 = Task.Run(() =>
{
foreach (var i in test)
{
Task.Delay(DelayTime).Wait();
}
});
var task2 = Task.Run(() =>
{
test.Add(4);
Task.Delay(DelayTime).Wait();
test.Add(5);
});
Task.WaitAll(task1, task2);
}
[Test]
public void InsertIsThreadSafe()
{
var test = new ConcurrentObservableCollection<int>(Concurrent) { 1, 2, 3 };
var task1 = Task.Run(() =>
{
foreach (var i in test)
{
Task.Delay(DelayTime).Wait();
}
});
var task2 = Task.Run(() =>
{
test.Insert(0, 4);
Task.Delay(DelayTime).Wait();
test.Insert(0, 5);
});
Task.WaitAll(task1, task2);
}
[Test]
public void RemoveIsThreadSafe()
{
var test = new ConcurrentObservableCollection<int>(Concurrent) { 1, 2, 3 };
var task1 = Task.Run(() =>
{
foreach (var i in test)
{
Task.Delay(DelayTime).Wait();
}
});
var task2 = Task.Run(() =>
{
test.Remove(2);
Task.Delay(DelayTime).Wait();
test.Remove(1);
});
Task.WaitAll(task1, task2);
}
[Test]
public void ClearIsThreadSafe()
{
var test = new ConcurrentObservableCollection<int>(Concurrent) { 1, 2, 3 };
var task1 = Task.Run(() =>
{
foreach (var i in test)
{
Task.Delay(DelayTime).Wait();
}
});
var task2 = Task.Run(() =>
{
Task.Delay(DelayTime).Wait();
test.Clear();
});
Task.WaitAll(task1, task2);
}
[Test]
public void ContainsIsThreadSafe()
{
var test = new ConcurrentObservableCollection<int>(Concurrent) { 1, 2, 3 };
var task1 = Task.Run(() =>
{
for (var i = 0; i < 10; i++)
{
test.Contains(2);
Task.Delay(DelayTime).Wait();
test.Contains(4);
}
});
var task2 = Task.Run(() =>
{
for (var i = 0; i < 10; i++)
{
test.Add(4);
Task.Delay(DelayTime).Wait();
test.Add(5);
}
});
Task.WaitAll(task1, task2);
}
[Test]
public void CopyToIsThreadSafe()
{
var test = new ConcurrentObservableCollection<int>(Concurrent) { 1, 2, 3 };
var out1 = new int[5];
var out2 = new int[5];
var task1 = Task.Run(() =>
{
for (var i = 0; i < 10; i++)
{
test.CopyTo(out1, 0);
Task.Delay(DelayTime).Wait();
test.CopyTo(out2, 0);
}
});
var task2 = Task.Run(() =>
{
for (var i = 0; i < 10; i++)
{
test.Add(4);
Task.Delay(DelayTime).Wait();
test.Remove(4);
}
});
Task.WaitAll(task1, task2);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="CurrencyManager.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms {
using System;
using Microsoft.Win32;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.ComponentModel;
using System.Collections;
using System.Reflection;
using System.Globalization;
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager"]/*' />
/// <devdoc>
/// <para>Manages the position and bindings of a
/// list.</para>
/// </devdoc>
public class CurrencyManager : BindingManagerBase {
private Object dataSource;
private IList list;
private bool bound = false;
private bool shouldBind = true;
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.listposition"]/*' />
/// <internalonly/>
/// <devdoc>
/// </devdoc>
[
SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields") // We can't make CurrencyManager.listposition internal
// because it would be a breaking change.
]
protected int listposition = -1;
private int lastGoodKnownRow = -1;
private bool pullingData = false;
private bool inChangeRecordState = false;
private bool suspendPushDataInCurrentChanged = false;
// private bool onItemChangedCalled = false;
// private EventHandler onCurrentChanged;
// private CurrentChangingEventHandler onCurrentChanging;
private ItemChangedEventHandler onItemChanged;
private ListChangedEventHandler onListChanged;
private ItemChangedEventArgs resetEvent = new ItemChangedEventArgs(-1);
private EventHandler onMetaDataChangedHandler;
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.finalType"]/*' />
/// <devdoc>
/// <para>Gets the type of the list.</para>
/// </devdoc>
protected Type finalType;
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.ItemChanged"]/*' />
/// <devdoc>
/// <para>Occurs when the
/// current item has been
/// altered.</para>
/// </devdoc>
[SRCategory(SR.CatData)]
public event ItemChangedEventHandler ItemChanged {
add {
onItemChanged += value;
}
remove {
onItemChanged -= value;
}
}
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.ListChanged"]/*' />
public event ListChangedEventHandler ListChanged {
add {
onListChanged += value;
}
remove {
onListChanged -= value;
}
}
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.CurrencyManager"]/*' />
/// <devdoc>
/// </devdoc>
[
SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // If the constructor does not set the dataSource
// it would be a breaking change.
]
internal CurrencyManager(Object dataSource) {
SetDataSource(dataSource);
}
/// <devdoc>
/// <para>Gets a value indicating
/// whether items can be added to the list.</para>
/// </devdoc>
internal bool AllowAdd {
get {
if (list is IBindingList) {
return ((IBindingList)list).AllowNew;
}
if (list == null)
return false;
return !list.IsReadOnly && !list.IsFixedSize;
}
}
/// <devdoc>
/// <para>Gets a value
/// indicating whether edits to the list are allowed.</para>
/// </devdoc>
internal bool AllowEdit {
get {
if (list is IBindingList) {
return ((IBindingList)list).AllowEdit;
}
if (list == null)
return false;
return !list.IsReadOnly;
}
}
/// <devdoc>
/// <para>Gets a value indicating whether items can be removed from the list.</para>
/// </devdoc>
internal bool AllowRemove {
get {
if (list is IBindingList) {
return ((IBindingList)list).AllowRemove;
}
if (list == null)
return false;
return !list.IsReadOnly && !list.IsFixedSize;
}
}
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.Count"]/*' />
/// <devdoc>
/// <para>Gets the number of items in the list.</para>
/// </devdoc>
public override int Count {
get {
if (list == null)
return 0;
else
return list.Count;
}
}
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.Current"]/*' />
/// <devdoc>
/// <para>Gets the current item in the list.</para>
/// </devdoc>
public override Object Current {
get {
return this[Position];
}
}
internal override Type BindType {
get {
return ListBindingHelper.GetListItemType(this.List);
}
}
/// <devdoc>
/// <para>Gets the data source of the list.</para>
/// </devdoc>
internal override Object DataSource {
get {
return dataSource;
}
}
internal override void SetDataSource(Object dataSource) {
if (this.dataSource != dataSource) {
Release();
this.dataSource = dataSource;
this.list = null;
this.finalType = null;
Object tempList = dataSource;
if (tempList is Array) {
finalType = tempList.GetType();
tempList = (Array)tempList;
}
if (tempList is IListSource) {
tempList = ((IListSource)tempList).GetList();
}
if (tempList is IList) {
if (finalType == null) {
finalType = tempList.GetType();
}
this.list = (IList)tempList;
WireEvents(list);
if (list.Count > 0 )
listposition = 0;
else
listposition = -1;
OnItemChanged(resetEvent);
OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1, -1));
UpdateIsBinding();
}
else {
if (tempList == null) {
throw new ArgumentNullException("dataSource");
}
throw new ArgumentException(SR.GetString(SR.ListManagerSetDataSource, tempList.GetType().FullName), "dataSource");
}
}
}
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.IsBinding"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>Gets a value indicating whether the list is bound to a data source.</para>
/// </devdoc>
internal override bool IsBinding {
get {
return bound;
}
}
// The DataGridView needs this.
internal bool ShouldBind {
get {
return shouldBind;
}
}
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.List"]/*' />
/// <devdoc>
/// <para>Gets the list as an object.</para>
/// </devdoc>
public IList List {
get {
// NOTE: do not change this to throw an exception if the list is not IBindingList.
// doing this will cause a major performance hit when wiring the
// dataGrid to listen for MetaDataChanged events from the IBindingList
// (basically we would have to wrap all calls to CurrencyManager::List with
// a try/catch block.)
//
return list;
}
}
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.Position"]/*' />
/// <devdoc>
/// <para> Gets or sets the position you are at within the list.</para>
/// </devdoc>
public override int Position {
get {
return listposition;
}
set {
if (listposition == -1)
return;
if (value < 0)
value = 0;
int count = list.Count;
if (value >= count)
value = count - 1;
ChangeRecordState(value, listposition != value, true, true, false); // true for endCurrentEdit
// true for firingPositionChange notification
// data will be pulled from controls anyway.
}
}
/// <devdoc>
/// <para>Gets or sets the object at the specified index.</para>
/// </devdoc>
internal Object this[int index] {
get {
if (index < 0 || index >= list.Count) {
throw new IndexOutOfRangeException(SR.GetString(SR.ListManagerNoValue, index.ToString(CultureInfo.CurrentCulture)));
}
return list[index];
}
set {
if (index < 0 || index >= list.Count) {
throw new IndexOutOfRangeException(SR.GetString(SR.ListManagerNoValue, index.ToString(CultureInfo.CurrentCulture)));
}
list[index] = value;
}
}
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.AddNew"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override void AddNew() {
IBindingList ibl = list as IBindingList;
if (ibl != null) {
ibl.AddNew();
}
else {
// If the list is not IBindingList, then throw an exception:
throw new NotSupportedException(SR.GetString(SR.CurrencyManagerCantAddNew));
}
ChangeRecordState(list.Count - 1, (Position != list.Count - 1), (Position != list.Count - 1), true, true); // true for firingPositionChangeNotification
// true for pulling data from the controls
}
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.CancelCurrentEdit"]/*' />
/// <devdoc>
/// <para>Cancels the current edit operation.</para>
/// </devdoc>
public override void CancelCurrentEdit() {
if (Count > 0) {
Object item = (Position >= 0 && Position < list.Count) ? list[Position] : null;
// onItemChangedCalled = false;
IEditableObject iEditableItem = item as IEditableObject;
if (iEditableItem != null) {
iEditableItem.CancelEdit();
}
ICancelAddNew iListWithCancelAddNewSupport = list as ICancelAddNew;
if (iListWithCancelAddNewSupport != null) {
iListWithCancelAddNewSupport.CancelNew(this.Position);
}
OnItemChanged(new ItemChangedEventArgs(Position));
if (this.Position != -1) {
OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, this.Position));
}
}
}
private void ChangeRecordState(int newPosition, bool validating, bool endCurrentEdit, bool firePositionChange, bool pullData) {
if (newPosition == -1 && list.Count == 0) {
if (listposition != -1) {
this.listposition = -1;
OnPositionChanged(EventArgs.Empty);
}
return;
}
if ((newPosition < 0 || newPosition >= Count) && this.IsBinding) {
throw new IndexOutOfRangeException(SR.GetString(SR.ListManagerBadPosition));
}
// if PushData fails in the OnCurrentChanged and there was a lastGoodKnownRow
// then the position does not change, so we should not fire the OnPositionChanged
// event;
// this is why we have to cache the old position and compare that w/ the position that
// the user will want to navigate to
int oldPosition = listposition;
if (endCurrentEdit) {
// Do not PushData when pro. See ASURT 65095.
inChangeRecordState = true;
try {
EndCurrentEdit();
} finally {
inChangeRecordState = false;
}
}
// we pull the data from the controls only when the ListManager changes the list. when the backEnd changes the list we do not
// pull the data from the controls
if (validating && pullData) {
CurrencyManager_PullData();
}
// vsWhidbey 425961: EndCurrentEdit or PullData can cause the list managed by the CurrencyManager to shrink.
this.listposition = Math.Min(newPosition, Count - 1);
if (validating) {
OnCurrentChanged(EventArgs.Empty);
}
bool positionChanging = (oldPosition != listposition);
if (positionChanging && firePositionChange) {
OnPositionChanged(EventArgs.Empty);
}
}
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.CheckEmpty"]/*' />
/// <devdoc>
/// <para>Throws an exception if there is no list.</para>
/// </devdoc>
protected void CheckEmpty() {
if (dataSource == null || list == null || list.Count == 0) {
throw new InvalidOperationException(SR.GetString(SR.ListManagerEmptyList));
}
}
// will return true if this function changes the position in the list
private bool CurrencyManager_PushData() {
if (pullingData)
return false;
int initialPosition = listposition;
if (lastGoodKnownRow == -1) {
try {
PushData();
}
catch (Exception ex) {
OnDataError(ex);
// get the first item in the list that is good to push data
// for now, we assume that there is a row in the backEnd
// that is good for all the bindings.
FindGoodRow();
}
lastGoodKnownRow = listposition;
} else {
try {
PushData();
}
catch (Exception ex) {
OnDataError(ex);
listposition = lastGoodKnownRow;
PushData();
}
lastGoodKnownRow = listposition;
}
return initialPosition != listposition;
}
private bool CurrencyManager_PullData() {
bool success = true;
pullingData = true;
try {
PullData(out success);
} finally {
pullingData = false;
}
return success;
}
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.RemoveAt"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override void RemoveAt(int index) {
list.RemoveAt(index);
}
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.EndCurrentEdit"]/*' />
/// <devdoc>
/// <para>Ends the current edit operation.</para>
/// </devdoc>
public override void EndCurrentEdit() {
if (Count > 0) {
bool success = CurrencyManager_PullData();
if (success) {
Object item = (Position >= 0 && Position < list.Count) ? list[Position] : null;
IEditableObject iEditableItem = item as IEditableObject;
if (iEditableItem != null) {
iEditableItem.EndEdit();
}
ICancelAddNew iListWithCancelAddNewSupport = list as ICancelAddNew;
if (iListWithCancelAddNewSupport != null) {
iListWithCancelAddNewSupport.EndNew(this.Position);
}
}
}
}
private void FindGoodRow() {
int rowCount = this.list.Count;
for (int i = 0; i < rowCount; i++) {
listposition = i;
try {
PushData();
}
catch (Exception ex) {
OnDataError(ex);
continue;
}
listposition = i;
return;
}
// if we got here, the list did not contain any rows suitable for the bindings
// suspend binding and throw an exception
SuspendBinding();
throw new InvalidOperationException(SR.GetString(SR.DataBindingPushDataException));
}
/// <devdoc>
/// <para>Sets the column to sort by, and the direction of the sort.</para>
/// </devdoc>
internal void SetSort(PropertyDescriptor property, ListSortDirection sortDirection) {
if (list is IBindingList && ((IBindingList)list).SupportsSorting) {
((IBindingList)list).ApplySort(property, sortDirection);
}
}
/// <devdoc>
/// <para>Gets a <see cref='System.ComponentModel.PropertyDescriptor'/> for a CurrencyManager.</para>
/// </devdoc>
internal PropertyDescriptor GetSortProperty() {
if ((list is IBindingList) && ((IBindingList)list).SupportsSorting) {
return ((IBindingList)list).SortProperty;
}
return null;
}
/// <devdoc>
/// <para>Gets the sort direction of a list.</para>
/// </devdoc>
internal ListSortDirection GetSortDirection() {
if ((list is IBindingList) && ((IBindingList)list).SupportsSorting) {
return ((IBindingList)list).SortDirection;
}
return ListSortDirection.Ascending;
}
/// <devdoc>
/// <para>Find the position of a desired list item.</para>
/// </devdoc>
internal int Find(PropertyDescriptor property, Object key, bool keepIndex) {
if (key == null)
throw new ArgumentNullException("key");
if (property != null && (list is IBindingList) && ((IBindingList)list).SupportsSearching) {
return ((IBindingList)list).Find(property, key);
}
if (property != null) {
for (int i = 0; i < list.Count; i++) {
object value = property.GetValue(list[i]);
if (key.Equals(value)) {
return i;
}
}
}
return -1;
}
/// <devdoc>
/// <para>Gets the name of the list.</para>
/// </devdoc>
internal override string GetListName() {
if (list is ITypedList) {
return ((ITypedList)list).GetListName(null);
}
else {
return finalType.Name;
}
}
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.GetListName1"]/*' />
/// <devdoc>
/// <para>Gets the name of the specified list.</para>
/// </devdoc>
protected internal override string GetListName(ArrayList listAccessors) {
if (list is ITypedList) {
PropertyDescriptor[] properties = new PropertyDescriptor[listAccessors.Count];
listAccessors.CopyTo(properties, 0);
return ((ITypedList)list).GetListName(properties);
}
return "";
}
/// <devdoc>
/// </devdoc>
internal override PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors) {
return ListBindingHelper.GetListItemProperties(this.list, listAccessors);
}
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.GetItemProperties"]/*' />
/// <devdoc>
/// <para>Gets the <see cref='T:System.ComponentModel.PropertyDescriptorCollection'/> for
/// the list.</para>
/// </devdoc>
public override PropertyDescriptorCollection GetItemProperties() {
return GetItemProperties(null);
}
/// <devdoc>
/// <para>Gets the <see cref='T:System.ComponentModel.PropertyDescriptorCollection'/> for the specified list.</para>
/// </devdoc>
private void List_ListChanged(Object sender, System.ComponentModel.ListChangedEventArgs e) {
// If you change the assert below, better change the
// code in the OnCurrentChanged that deals w/ firing the OnCurrentChanged event
Debug.Assert(lastGoodKnownRow == -1 || lastGoodKnownRow == listposition, "if we have a valid lastGoodKnownRow, then it should equal the position in the list");
// bug 139627: when the data view fires an ItemMoved event where the old position is negative, that really means
// that a row was added
// bug 156236: when the data view fires an ItemMoved event where the new position is negative, that really means
// that a row was deleted
// dbe is our DataBindingEvent
//
ListChangedEventArgs dbe;
if (e.ListChangedType == ListChangedType.ItemMoved && e.OldIndex < 0) {
dbe = new ListChangedEventArgs(ListChangedType.ItemAdded, e.NewIndex, e.OldIndex);
} else if (e.ListChangedType == ListChangedType.ItemMoved && e.NewIndex < 0) {
dbe = new ListChangedEventArgs(ListChangedType.ItemDeleted, e.OldIndex, e.NewIndex);
} else {
dbe = e;
}
int oldposition = listposition;
UpdateLastGoodKnownRow(dbe);
UpdateIsBinding();
if (list.Count == 0) {
listposition = -1;
if (oldposition != -1) {
// if we used to have a current row, but not any more, then report current as changed
OnPositionChanged(EventArgs.Empty);
OnCurrentChanged(EventArgs.Empty);
}
if (dbe.ListChangedType == System.ComponentModel.ListChangedType.Reset && e.NewIndex == -1) {
// if the list is reset, then let our users know about it.
OnItemChanged(resetEvent);
}
if (dbe.ListChangedType == System.ComponentModel.ListChangedType.ItemDeleted) {
// if the list is reset, then let our users know about it.
OnItemChanged(resetEvent);
}
// we should still fire meta data change notification even when the list is empty
if (e.ListChangedType == System.ComponentModel.ListChangedType.PropertyDescriptorAdded ||
e.ListChangedType == System.ComponentModel.ListChangedType.PropertyDescriptorDeleted ||
e.ListChangedType == System.ComponentModel.ListChangedType.PropertyDescriptorChanged)
OnMetaDataChanged(EventArgs.Empty);
//
OnListChanged(dbe);
return;
}
suspendPushDataInCurrentChanged = true;
try {
switch (dbe.ListChangedType) {
case System.ComponentModel.ListChangedType.Reset:
Debug.WriteLineIf(CompModSwitches.DataCursor.TraceVerbose, "System.ComponentModel.ListChangedType.Reset Position: " + Position + " Count: " + list.Count);
if (listposition == -1 && list.Count > 0)
ChangeRecordState(0, true, false, true, false); // last false: we don't pull the data from the control when DM changes
else
ChangeRecordState(Math.Min(listposition,list.Count - 1), true, false, true, false);
UpdateIsBinding(/*raiseItemChangedEvent:*/ false);
OnItemChanged(resetEvent);
break;
case System.ComponentModel.ListChangedType.ItemAdded:
Debug.WriteLineIf(CompModSwitches.DataCursor.TraceVerbose, "System.ComponentModel.ListChangedType.ItemAdded " + dbe.NewIndex.ToString(CultureInfo.InvariantCulture));
if (dbe.NewIndex <= listposition && listposition < list.Count - 1) {
// this means the current row just moved down by one.
// the position changes, so end the current edit
ChangeRecordState(listposition + 1, true, true, listposition != list.Count - 2, false);
UpdateIsBinding();
// 85426: refresh the list after we got the item added event
OnItemChanged(resetEvent);
// 84460: when we get the itemAdded, and the position was at the end
// of the list, do the right thing and notify the positionChanged after refreshing the list
if (listposition == list.Count - 1)
OnPositionChanged(EventArgs.Empty);
break;
} else if (dbe.NewIndex == this.listposition && this.listposition == list.Count - 1 && this.listposition != -1) {
// The CurrencyManager has a non-empty list.
// The position inside the currency manager is at the end of the list and the list still fired an ItemAdded event.
// This could be the second ItemAdded event that the DataView fires to signal that the AddNew operation was commited.
// We need to fire CurrentItemChanged event so that relatedCurrencyManagers update their lists.
OnCurrentItemChanged(System.EventArgs.Empty);
}
if (listposition == -1) {
// do not call EndEdit on a row that was not there ( position == -1)
ChangeRecordState(0, false, false, true, false);
}
UpdateIsBinding();
// put the call to OnItemChanged after setting the position, so the
// controls would use the actual position.
// if we have a control bound to a dataView, and then we add a row to a the dataView,
// then the control will use the old listposition to get the data. and this is bad.
//
OnItemChanged(resetEvent);
break;
case System.ComponentModel.ListChangedType.ItemDeleted:
Debug.WriteLineIf(CompModSwitches.DataCursor.TraceVerbose, "System.ComponentModel.ListChangedType.ItemDeleted " + dbe.NewIndex.ToString(CultureInfo.InvariantCulture));
if (dbe.NewIndex == listposition) {
// this means that the current row got deleted.
// cannot end an edit on a row that does not exist anymore
ChangeRecordState(Math.Min(listposition, Count - 1), true, false, true, false);
// put the call to OnItemChanged after setting the position
// in the currencyManager, so controls will use the actual position
OnItemChanged(resetEvent);
break;
}
if (dbe.NewIndex < listposition) {
// this means the current row just moved up by one.
// cannot end an edit on a row that does not exist anymore
ChangeRecordState(listposition - 1, true, false, true, false);
// put the call to OnItemChanged after setting the position
// in the currencyManager, so controls will use the actual position
OnItemChanged(resetEvent);
break;
}
OnItemChanged(resetEvent);
break;
case System.ComponentModel.ListChangedType.ItemChanged:
Debug.WriteLineIf(CompModSwitches.DataCursor.TraceVerbose, "System.ComponentModel.ListChangedType.ItemChanged " + dbe.NewIndex.ToString(CultureInfo.InvariantCulture));
// the current item changed
if (dbe.NewIndex == this.listposition) {
OnCurrentItemChanged(EventArgs.Empty);
}
OnItemChanged(new ItemChangedEventArgs(dbe.NewIndex));
break;
case System.ComponentModel.ListChangedType.ItemMoved:
Debug.WriteLineIf(CompModSwitches.DataCursor.TraceVerbose, "System.ComponentModel.ListChangedType.ItemMoved " + dbe.NewIndex.ToString(CultureInfo.InvariantCulture));
if (dbe.OldIndex == listposition) { // current got moved.
// the position changes, so end the current edit. Make sure there is something that we can end edit...
ChangeRecordState(dbe.NewIndex, true, this.Position > -1 && this.Position < list.Count, true, false);
}
else if (dbe.NewIndex == listposition) { // current was moved
// the position changes, so end the current edit. Make sure there is something that we can end edit
ChangeRecordState(dbe.OldIndex, true, this.Position > -1 && this.Position < list.Count, true, false);
}
OnItemChanged(resetEvent);
break;
case System.ComponentModel.ListChangedType.PropertyDescriptorAdded:
case System.ComponentModel.ListChangedType.PropertyDescriptorDeleted:
case System.ComponentModel.ListChangedType.PropertyDescriptorChanged:
// reset lastGoodKnownRow because it was computed against property descriptors which changed
this.lastGoodKnownRow = -1;
// In Everett, metadata changes did not alter current list position. In Whidbey, this behavior
// preserved - except that we will now force the position to stay in valid range if necessary.
if (listposition == -1 && list.Count > 0)
ChangeRecordState(0, true, false, true, false);
else if (listposition > list.Count - 1)
ChangeRecordState(list.Count - 1, true, false, true, false);
// fire the MetaDataChanged event
OnMetaDataChanged(EventArgs.Empty);
break;
}
// send the ListChanged notification after the position changed in the list
//
OnListChanged(dbe);
} finally {
suspendPushDataInCurrentChanged = false;
}
Debug.Assert(lastGoodKnownRow == -1 || listposition == lastGoodKnownRow, "how did they get out of [....]?");
}
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.MetaDataChanged"]/*' />
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] //Exists in Everett
[SRCategory(SR.CatData)]
public event EventHandler MetaDataChanged {
add {
onMetaDataChangedHandler += value;
}
remove {
onMetaDataChangedHandler -= value;
}
}
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.OnCurrentChanged"]/*' />
/// <devdoc>
/// <para>Causes the CurrentChanged event to occur. </para>
/// </devdoc>
internal protected override void OnCurrentChanged(EventArgs e) {
if (!inChangeRecordState) {
Debug.WriteLineIf(CompModSwitches.DataView.TraceVerbose, "OnCurrentChanged() " + e.ToString());
int curLastGoodKnownRow = lastGoodKnownRow;
bool positionChanged = false;
if (!suspendPushDataInCurrentChanged)
positionChanged = CurrencyManager_PushData();
if (Count > 0) {
Object item = list[Position];
if (item is IEditableObject) {
((IEditableObject)item).BeginEdit();
}
}
try {
// if currencyManager changed position then we have two cases:
// 1. the previous lastGoodKnownRow was valid: in that case we fell back so do not fire onCurrentChanged
// 2. the previous lastGoodKnownRow was invalid: we have two cases:
// a. FindGoodRow actually found a good row, so it can't be the one before the user changed the position: fire the onCurrentChanged
// b. FindGoodRow did not find a good row: we should have gotten an exception so we should not even execute this code
if (!positionChanged ||(positionChanged && curLastGoodKnownRow != -1)) {
if (onCurrentChangedHandler != null) {
onCurrentChangedHandler(this, e);
}
// we fire OnCurrentItemChanged event every time we fire the CurrentChanged + when a property of the Current item changed
if (onCurrentItemChangedHandler != null) {
onCurrentItemChangedHandler(this, e);
}
}
}
catch (Exception ex) {
OnDataError(ex);
}
}
}
// this method should only be called when the currency manager receives the ListChangedType.ItemChanged event
// and when the index of the ListChangedEventArgs == the position in the currency manager
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.OnCurrentItemChanged"]/*' />
internal protected override void OnCurrentItemChanged(EventArgs e) {
if (onCurrentItemChangedHandler != null) {
onCurrentItemChangedHandler(this, e);
}
}
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.OnItemChanged"]/*' />
/// <devdoc>
/// </devdoc>
protected virtual void OnItemChanged(ItemChangedEventArgs e) {
// It is possible that CurrencyManager_PushData will change the position
// in the list. in that case we have to fire OnPositionChanged event
bool positionChanged = false;
// We should not push the data when we suspend the changeEvents.
// but we should still fire the OnItemChanged event that we get when processing the EndCurrentEdit method.
if ((e.Index == listposition || (e.Index == -1 && Position < Count)) && !inChangeRecordState)
positionChanged = CurrencyManager_PushData();
Debug.WriteLineIf(CompModSwitches.DataView.TraceVerbose, "OnItemChanged(" + e.Index.ToString(CultureInfo.InvariantCulture) + ") " + e.ToString());
try {
if (onItemChanged != null)
onItemChanged(this, e);
}
catch (Exception ex) {
OnDataError(ex);
}
if (positionChanged)
OnPositionChanged(EventArgs.Empty);
// onItemChangedCalled = true;
}
private void OnListChanged(ListChangedEventArgs e) {
if (onListChanged != null)
onListChanged(this, e);
}
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] //Exists in Everett
internal protected void OnMetaDataChanged(EventArgs e)
{
if (onMetaDataChangedHandler != null)
onMetaDataChangedHandler(this,e);
}
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.OnPositionChanged"]/*' />
/// <devdoc>
/// </devdoc>
protected virtual void OnPositionChanged(EventArgs e) {
// if (!inChangeRecordState) {
Debug.WriteLineIf(CompModSwitches.DataView.TraceVerbose, "OnPositionChanged(" + listposition.ToString(CultureInfo.InvariantCulture) + ") " + e.ToString());
try {
if (onPositionChangedHandler != null)
onPositionChangedHandler(this, e);
}
catch (Exception ex) {
OnDataError(ex);
}
// }
}
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.Refresh"]/*' />
/// <devdoc>
/// <para>
/// Forces a repopulation of the CurrencyManager
/// </para>
/// </devdoc>
public void Refresh() {
if (list.Count > 0 ) {
if (listposition >= list.Count) {
lastGoodKnownRow = -1;
listposition = 0;
}
} else {
listposition = -1;
}
List_ListChanged(list, new System.ComponentModel.ListChangedEventArgs(System.ComponentModel.ListChangedType.Reset, -1));
}
internal void Release() {
UnwireEvents(list);
}
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.ResumeBinding"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>Resumes binding of component properties to list items.</para>
/// </devdoc>
public override void ResumeBinding() {
lastGoodKnownRow = -1;
try {
if (!shouldBind) {
shouldBind = true;
// we need to put the listPosition at the beginning of the list if the list is not empty
this.listposition = (this.list != null && this.list.Count != 0) ? 0:-1;
UpdateIsBinding();
}
}
catch {
shouldBind = false;
UpdateIsBinding();
throw;
}
}
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.SuspendBinding"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>Suspends binding.</para>
/// </devdoc>
public override void SuspendBinding() {
lastGoodKnownRow = -1;
if (shouldBind) {
shouldBind = false;
UpdateIsBinding();
}
}
internal void UnwireEvents(IList list) {
if ((list is IBindingList) && ((IBindingList)list).SupportsChangeNotification) {
((IBindingList)list).ListChanged -= new System.ComponentModel.ListChangedEventHandler(List_ListChanged);
/*
ILiveList liveList = (ILiveList) list;
liveList.TableChanged -= new TableChangedEventHandler(List_TableChanged);
*/
}
}
/// <include file='doc\ListManager.uex' path='docs/doc[@for="CurrencyManager.UpdateIsBinding"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected override void UpdateIsBinding() {
UpdateIsBinding(true);
}
private void UpdateIsBinding(bool raiseItemChangedEvent) {
bool newBound = list != null && list.Count > 0 && shouldBind && listposition != -1;
if (list != null)
if (bound != newBound) {
// we will call end edit when moving from bound state to unbounded state
//
//bool endCurrentEdit = bound && !newBound;
bound = newBound;
int newPos = newBound ? 0 : -1;
ChangeRecordState(newPos, bound, (Position != newPos), true, false);
int numLinks = Bindings.Count;
for (int i = 0; i < numLinks; i++) {
Bindings[i].UpdateIsBinding();
}
if (raiseItemChangedEvent) {
OnItemChanged(resetEvent);
}
}
}
private void UpdateLastGoodKnownRow(System.ComponentModel.ListChangedEventArgs e) {
switch (e.ListChangedType) {
case System.ComponentModel.ListChangedType.ItemDeleted:
if (e.NewIndex == lastGoodKnownRow)
lastGoodKnownRow = -1;
break;
case System.ComponentModel.ListChangedType.Reset:
lastGoodKnownRow = -1;
break;
case System.ComponentModel.ListChangedType.ItemAdded:
if (e.NewIndex <= lastGoodKnownRow && lastGoodKnownRow < this.List.Count - 1)
lastGoodKnownRow ++;
break;
case System.ComponentModel.ListChangedType.ItemMoved:
if (e.OldIndex == lastGoodKnownRow)
lastGoodKnownRow = e.NewIndex;
break;
case System.ComponentModel.ListChangedType.ItemChanged:
if (e.NewIndex == lastGoodKnownRow)
lastGoodKnownRow = -1;
break;
}
}
internal void WireEvents(IList list) {
if ((list is IBindingList) && ((IBindingList)list).SupportsChangeNotification) {
((IBindingList)list).ListChanged += new System.ComponentModel.ListChangedEventHandler(List_ListChanged);
/*
ILiveList liveList = (ILiveList) list;
liveList.TableChanged += new TableChangedEventHandler(List_TableChanged);
*/
}
}
}
}
| |
#region Namespaces
using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using FloorCopy.Properties;
#endregion
namespace FloorCopy
{
[Transaction(TransactionMode.Manual)]
public class Command : IExternalCommand
{
const double _eps = 1.0e-9;
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
Application app = uiapp.Application;
Document doc = uidoc.Document;
Reference r;
try
{
r = uidoc.Selection.PickObject(ObjectType.Element,
new FloorSelectionFilter(), Resources.SelectFloor);
}
catch (Exception)
{
return Result.Cancelled;
}
var floor = doc.GetElement(r.ElementId) as Floor;
using (Transaction t =
new Transaction(doc, Resources.CopyFloor))
{
t.Start();
IList<FloorContainer> newFloors =
CopyFloor(floor);
t.Commit();
// Sort floors by area
List<FloorContainer> newFloorsSorted =
newFloors.OrderByDescending(fc =>
fc.Floor.get_Parameter(BuiltInParameter.HOST_AREA_COMPUTED).AsDouble())
.ToList();
// The largest of the floors was built from the outer boundary,
// this is the Floor to keep
Floor newFloor =
newFloorsSorted[0].Floor;
newFloorsSorted.RemoveAt(0);
// Prepare the other floors for deletion
List<ElementId> delIds =
newFloorsSorted
.Select(fc => fc.Floor.Id)
.ToList();
// Extract boundaries (those of all smaller floors)
// for opening creation
IEnumerable<CurveArray> sourceEdgesForOpenings =
newFloorsSorted.Select(fc => fc.Boundary);
List<Opening> openings = new List<Opening>();
t.Start("Create openings and delete smaller floors");
foreach(CurveArray boundary in sourceEdgesForOpenings)
{
var newOpening =
doc
.Create
.NewOpening(
newFloor,
boundary,
true );
openings.Add(newOpening);
}
doc.Delete(delIds);
// Transform newly created floor
XYZ translationVector = new XYZ(0, 0, 10);
ElementTransformUtils.MoveElement(
doc,
newFloor.Id,
translationVector);
t.Commit();
}
return Result.Succeeded;
}
// Create a new Floor from each EdgeLoop of the source Floor,
// store the new Floor and its corresponding boundary for later re-use.
private IList<FloorContainer> CopyFloor(Floor sourceFloor)
{
var floorGeometryElement =
sourceFloor.get_Geometry(new Options());
foreach (var geometryObject in floorGeometryElement)
{
var floorSolid =
geometryObject as Solid;
if (floorSolid == null)
continue;
var topFace =
GetTopFace(floorSolid);
if (topFace == null)
throw new NotSupportedException(Resources.FloorDoesNotHaveTopFace);
if (topFace.EdgeLoops.IsEmpty)
throw new NotSupportedException(Resources.FloorTopFateDoesNotHaveEdges);
var newFloorContainers = new List<FloorContainer>();
foreach(EdgeArray edgeloop in topFace.EdgeLoops)
{
// create new floor
CurveArray floorCurveArray =
GetCurveArrayFromEdgeArray(edgeloop);
var newFloor =
sourceFloor
.Document
.Create
.NewFloor(floorCurveArray, false);
newFloorContainers.Add(new FloorContainer(newFloor, floorCurveArray));
}
return newFloorContainers;
}
return null;
}
private CurveArray GetCurveArrayFromEdgeArray(EdgeArray edgeArray)
{
CurveArray curveArray =
new CurveArray();
foreach (Edge edge in edgeArray)
{
var edgeCurve =
edge.AsCurve();
curveArray.Append(edgeCurve);
}
return curveArray;
}
PlanarFace GetTopFace(Solid solid)
{
PlanarFace topFace = null;
FaceArray faces = solid.Faces;
foreach (Face f in faces)
{
PlanarFace pf = f as PlanarFace;
if (null != pf
&& (Math.Abs(pf.Normal.X - 0) < _eps && Math.Abs(pf.Normal.Y - 0) < _eps))
{
if ((null == topFace)
|| (topFace.Origin.Z < pf.Origin.Z))
{
topFace = pf;
}
}
}
return topFace;
}
}
struct FloorContainer
{
public Floor Floor;
public CurveArray Boundary;
public FloorContainer(Floor floor, CurveArray boundary)
{
Floor = floor;
Boundary = boundary;
}
}
public class FloorSelectionFilter : ISelectionFilter
{
public bool AllowElement(Element elem)
{
return elem is Floor;
}
public bool AllowReference(Reference reference, XYZ position)
{
throw new NotImplementedException();
}
}
}
| |
// 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftLeftLogical128BitLaneUInt641()
{
var test = new SimpleUnaryOpTest__ShiftLeftLogical128BitLaneUInt641();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__ShiftLeftLogical128BitLaneUInt641
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(UInt64);
private const int RetElementCount = VectorSize / sizeof(UInt64);
private static UInt64[] _data = new UInt64[Op1ElementCount];
private static Vector256<UInt64> _clsVar;
private Vector256<UInt64> _fld;
private SimpleUnaryOpTest__DataTable<UInt64, UInt64> _dataTable;
static SimpleUnaryOpTest__ShiftLeftLogical128BitLaneUInt641()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ulong)8; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar), ref Unsafe.As<UInt64, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__ShiftLeftLogical128BitLaneUInt641()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ulong)8; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ulong)8; }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt64, UInt64>(_data, new UInt64[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.ShiftLeftLogical128BitLane(
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.ShiftLeftLogical128BitLane(
Avx.LoadVector256((UInt64*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.ShiftLeftLogical128BitLane(
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector256<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector256<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt64*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector256<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.ShiftLeftLogical128BitLane(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArrayPtr);
var result = Avx2.ShiftLeftLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Avx.LoadVector256((UInt64*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftLeftLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftLeftLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ShiftLeftLogical128BitLaneUInt641();
var result = Avx2.ShiftLeftLogical128BitLane(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.ShiftLeftLogical128BitLane(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<UInt64> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt64[] firstOp, UInt64[] result, [CallerMemberName] string method = "")
{
if (result[0] != 2048)
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != 2048)
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.ShiftLeftLogical128BitLane)}<UInt64>(Vector256<UInt64><9>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System.Collections.Generic;
using System.Windows.Forms;
using XenAdmin.Actions;
using XenAdmin.Controls;
using XenAdmin.Dialogs;
using XenAPI;
using System.Linq;
using System.IO;
using XenAdmin.Alerts;
using XenAdmin.Core;
namespace XenAdmin.Wizards.PatchingWizard
{
/// <summary>
/// Remember that equals for patches dont work across connections because
/// we are not allow to override equals. YOU SHOULD NOT USE ANY OPERATION THAT IMPLIES CALL EQUALS OF Pool_path or Host_patch
/// You should do it manually or use delegates.
/// </summary>
public partial class PatchingWizard : XenWizardBase
{
private readonly PatchingWizard_PatchingPage PatchingWizard_PatchingPage;
private readonly PatchingWizard_SelectPatchPage PatchingWizard_SelectPatchPage;
private readonly PatchingWizard_ModePage PatchingWizard_ModePage;
private readonly PatchingWizard_SelectServers PatchingWizard_SelectServers;
private readonly PatchingWizard_UploadPage PatchingWizard_UploadPage;
private readonly PatchingWizard_PrecheckPage PatchingWizard_PrecheckPage;
private readonly PatchingWizard_FirstPage PatchingWizard_FirstPage;
private readonly PatchingWizard_AutomatedUpdatesPage PatchingWizard_AutomatedUpdatesPage;
public PatchingWizard()
{
InitializeComponent();
PatchingWizard_PatchingPage = new PatchingWizard_PatchingPage();
PatchingWizard_SelectPatchPage = new PatchingWizard_SelectPatchPage();
PatchingWizard_ModePage = new PatchingWizard_ModePage();
PatchingWizard_SelectServers = new PatchingWizard_SelectServers();
PatchingWizard_UploadPage = new PatchingWizard_UploadPage();
PatchingWizard_PrecheckPage = new PatchingWizard_PrecheckPage();
PatchingWizard_FirstPage = new PatchingWizard_FirstPage();
PatchingWizard_AutomatedUpdatesPage = new PatchingWizard_AutomatedUpdatesPage();
AddPage(PatchingWizard_FirstPage);
AddPage(PatchingWizard_SelectPatchPage);
AddPage(PatchingWizard_SelectServers);
AddPage(PatchingWizard_UploadPage);
AddPage(PatchingWizard_PrecheckPage);
AddPage(PatchingWizard_ModePage);
AddPage(PatchingWizard_PatchingPage);
}
public void AddAlert(XenServerPatchAlert alert)
{
PatchingWizard_SelectPatchPage.SelectDownloadAlert(alert);
PatchingWizard_SelectPatchPage.SelectedUpdateAlert = alert;
PatchingWizard_SelectServers.SelectedUpdateAlert = alert;
PatchingWizard_UploadPage.SelectedUpdateAlert = alert;
}
public void AddFile(string path)
{
PatchingWizard_SelectPatchPage.AddFile(path);
}
public void SelectServers(List<Host> selectedServers)
{
PatchingWizard_SelectServers.SelectServers(selectedServers);
PatchingWizard_SelectServers.DisableUnselectedServers();
}
protected override void UpdateWizardContent(XenTabPage senderPage)
{
var prevPageType = senderPage.GetType();
if (prevPageType == typeof(PatchingWizard_SelectPatchPage))
{
var wizardIsInAutomatedUpdatesMode = PatchingWizard_SelectPatchPage.IsInAutomatedUpdatesMode;
var updateType = wizardIsInAutomatedUpdatesMode ? UpdateType.NewRetail : PatchingWizard_SelectPatchPage.SelectedUpdateType;
var newPatch = wizardIsInAutomatedUpdatesMode ? null : PatchingWizard_SelectPatchPage.SelectedNewPatch;
var existPatch = wizardIsInAutomatedUpdatesMode ? null : PatchingWizard_SelectPatchPage.SelectedExistingPatch;
var alertPatch = wizardIsInAutomatedUpdatesMode ? null : PatchingWizard_SelectPatchPage.SelectedUpdateAlert;
var fileFromDiskAlertPatch = wizardIsInAutomatedUpdatesMode ? null : PatchingWizard_SelectPatchPage.FileFromDiskAlert;
PatchingWizard_SelectServers.IsInAutomaticMode = wizardIsInAutomatedUpdatesMode;
PatchingWizard_SelectServers.SelectedUpdateType = updateType;
PatchingWizard_SelectServers.Patch = existPatch;
PatchingWizard_SelectServers.SelectedUpdateAlert = alertPatch;
PatchingWizard_SelectServers.FileFromDiskAlert = fileFromDiskAlertPatch;
RemovePage(PatchingWizard_UploadPage);
RemovePage(PatchingWizard_ModePage);
RemovePage(PatchingWizard_PatchingPage);
RemovePage(PatchingWizard_AutomatedUpdatesPage);
if (!wizardIsInAutomatedUpdatesMode)
{
AddAfterPage(PatchingWizard_SelectServers, PatchingWizard_UploadPage);
AddAfterPage(PatchingWizard_PrecheckPage, PatchingWizard_ModePage);
AddAfterPage(PatchingWizard_ModePage, PatchingWizard_PatchingPage);
}
else
{
AddAfterPage(PatchingWizard_PrecheckPage, PatchingWizard_AutomatedUpdatesPage);
}
PatchingWizard_UploadPage.SelectedUpdateType = updateType;
PatchingWizard_UploadPage.SelectedExistingPatch = existPatch;
PatchingWizard_UploadPage.SelectedNewPatchPath = newPatch;
PatchingWizard_UploadPage.SelectedUpdateAlert = alertPatch;
PatchingWizard_ModePage.Patch = existPatch;
PatchingWizard_ModePage.SelectedUpdateAlert = alertPatch;
PatchingWizard_PrecheckPage.IsInAutomatedUpdatesMode = wizardIsInAutomatedUpdatesMode;
PatchingWizard_PrecheckPage.Patch = existPatch;
PatchingWizard_PrecheckPage.PoolUpdate = null; //reset the PoolUpdate property; it will be updated on leaving the Upload page, if this page is visible
PatchingWizard_PatchingPage.Patch = existPatch;
PatchingWizard_PrecheckPage.SelectedUpdateType = updateType;
PatchingWizard_ModePage.SelectedUpdateType = updateType;
PatchingWizard_PatchingPage.SelectedUpdateType = updateType;
PatchingWizard_PatchingPage.SelectedNewPatch = newPatch;
}
else if (prevPageType == typeof(PatchingWizard_SelectServers))
{
var selectedServers = PatchingWizard_SelectServers.SelectedServers;
var selectedPools = PatchingWizard_SelectServers.SelectedPools;
var selectedMasters = PatchingWizard_SelectServers.SelectedMasters;
PatchingWizard_PrecheckPage.SelectedServers = selectedServers;
PatchingWizard_ModePage.SelectedServers = selectedServers;
PatchingWizard_PatchingPage.SelectedMasters = selectedMasters;
PatchingWizard_PatchingPage.SelectedServers = selectedServers;
PatchingWizard_PatchingPage.SelectedPools = selectedPools;
PatchingWizard_UploadPage.SelectedMasters = selectedMasters;
PatchingWizard_UploadPage.SelectedServers = selectedServers;
PatchingWizard_AutomatedUpdatesPage.SelectedPools = selectedPools;
}
else if (prevPageType == typeof(PatchingWizard_UploadPage))
{
if (PatchingWizard_SelectPatchPage.SelectedUpdateType == UpdateType.NewRetail)
{
PatchingWizard_SelectPatchPage.SelectedUpdateType = UpdateType.Existing;
PatchingWizard_SelectPatchPage.SelectedExistingPatch = PatchingWizard_UploadPage.Patch;
PatchingWizard_SelectServers.SelectedUpdateType = UpdateType.Existing;
PatchingWizard_SelectServers.Patch = PatchingWizard_UploadPage.Patch;
PatchingWizard_PrecheckPage.Patch = PatchingWizard_UploadPage.Patch;
PatchingWizard_ModePage.Patch = PatchingWizard_UploadPage.Patch;
PatchingWizard_PatchingPage.Patch = PatchingWizard_UploadPage.Patch;
}
PatchingWizard_PrecheckPage.PoolUpdate = PatchingWizard_UploadPage.PoolUpdate;
PatchingWizard_PatchingPage.PoolUpdate = PatchingWizard_UploadPage.PoolUpdate;
PatchingWizard_ModePage.PoolUpdate = PatchingWizard_UploadPage.PoolUpdate;
PatchingWizard_PatchingPage.SuppPackVdis = PatchingWizard_UploadPage.SuppPackVdis;
}
else if (prevPageType == typeof(PatchingWizard_ModePage))
{
PatchingWizard_PatchingPage.ManualTextInstructions = PatchingWizard_ModePage.ManualTextInstructions;
PatchingWizard_PatchingPage.IsAutomaticMode = PatchingWizard_ModePage.IsAutomaticMode;
PatchingWizard_PatchingPage.RemoveUpdateFile = PatchingWizard_ModePage.RemoveUpdateFile;
}
else if (prevPageType == typeof(PatchingWizard_PrecheckPage))
{
PatchingWizard_PatchingPage.ProblemsResolvedPreCheck = PatchingWizard_PrecheckPage.ProblemsResolvedPreCheck;
PatchingWizard_PatchingPage.LivePatchCodesByHost = PatchingWizard_PrecheckPage.LivePatchCodesByHost;
PatchingWizard_ModePage.LivePatchCodesByHost = PatchingWizard_PrecheckPage.LivePatchCodesByHost;
PatchingWizard_AutomatedUpdatesPage.ProblemsResolvedPreCheck = PatchingWizard_PrecheckPage.ProblemsResolvedPreCheck;
}
}
private delegate List<AsyncAction> GetActionsDelegate();
private List<AsyncAction> BuildSubActions(params GetActionsDelegate[] getActionsDelegate)
{
List<AsyncAction> result = new List<AsyncAction>();
foreach (GetActionsDelegate getActionDelegate in getActionsDelegate)
{
var list = getActionDelegate();
if (list != null && list.Count > 0)
result.AddRange(list);
}
return result;
}
private List<AsyncAction> GetUnwindChangesActions()
{
if (PatchingWizard_PrecheckPage.ProblemsResolvedPreCheck == null)
return null;
var actionList = (from problem in PatchingWizard_PrecheckPage.ProblemsResolvedPreCheck
where problem.SolutionActionCompleted
select problem.UnwindChanges());
return actionList.Where(action => action != null &&
action.Connection != null &&
action.Connection.IsConnected).ToList();
}
private List<AsyncAction> GetRemovePatchActions(List<Pool_patch> patchesToRemove)
{
if (patchesToRemove == null)
return null;
List<AsyncAction> list = new List<AsyncAction>();
foreach (Pool_patch patch in patchesToRemove)
{
if (patch.Connection != null && patch.Connection.IsConnected)
{
if (patch.HostsAppliedTo().Count == 0)
{
list.Add(new RemovePatchAction(patch));
}
else
{
list.Add(new DelegatedAsyncAction(patch.Connection, Messages.REMOVE_PATCH, "", "", session => Pool_patch.async_pool_clean(session, patch.opaque_ref)));
}
}
}
return list;
}
private List<AsyncAction> GetRemovePatchActions()
{
return GetRemovePatchActions(PatchingWizard_UploadPage.NewUploadedPatches.Keys.ToList());
}
private List<AsyncAction> GetRemoveVdiActions(List<VDI> vdisToRemove)
{
if (vdisToRemove == null)
return null;
var list = (from vdi in vdisToRemove
where vdi.Connection != null && vdi.Connection.IsConnected
select new DestroyDiskAction(vdi));
return list.OfType<AsyncAction>().ToList();
}
private List<AsyncAction> GetRemoveVdiActions()
{
return GetRemoveVdiActions(PatchingWizard_UploadPage.AllCreatedSuppPackVdis); ;
}
private void RunMultipleActions(string title, string startDescription, string endDescription,
List<AsyncAction> subActions)
{
if (subActions.Count > 0)
{
using (MultipleAction multipleAction = new MultipleAction(xenConnection, title, startDescription,
endDescription, subActions, false, true))
{
using (var dialog = new ActionProgressDialog(multipleAction, ProgressBarStyle.Blocks))
dialog.ShowDialog(Program.MainWindow);
}
}
}
protected override void OnCancel()
{
base.OnCancel();
List<AsyncAction> subActions = BuildSubActions(GetUnwindChangesActions, GetRemovePatchActions, GetRemoveVdiActions, GetCleanUpPoolUpdateActions);
RunMultipleActions(Messages.REVERT_WIZARD_CHANGES, Messages.REVERTING_WIZARD_CHANGES,
Messages.REVERTED_WIZARD_CHANGES, subActions);
RemoveDownloadedPatches();
}
private void RemoveUnwantedPatches(List<Pool_patch> patchesToRemove)
{
List<AsyncAction> subActions = GetRemovePatchActions(patchesToRemove);
RunMultipleActions(Messages.PATCHINGWIZARD_REMOVE_UPDATES, Messages.PATCHINGWIZARD_REMOVING_UPDATES, Messages.PATCHINGWIZARD_REMOVED_UPDATES, subActions);
}
private void RemoveTemporaryVdis()
{
List<AsyncAction> subActions = GetRemoveVdiActions();
RunMultipleActions(Messages.PATCHINGWIZARD_REMOVE_UPDATES, Messages.PATCHINGWIZARD_REMOVING_UPDATES, Messages.PATCHINGWIZARD_REMOVED_UPDATES, subActions);
}
private void CleanUpPoolUpdates()
{
var subActions = GetCleanUpPoolUpdateActions();
RunMultipleActions(Messages.PATCHINGWIZARD_REMOVE_UPDATES, Messages.PATCHINGWIZARD_REMOVING_UPDATES, Messages.PATCHINGWIZARD_REMOVED_UPDATES, subActions);
}
private void RemoveDownloadedPatches()
{
var isInAutomaticMode = PatchingWizard_SelectPatchPage.IsInAutomatedUpdatesMode;
List<string> listOfDownloadedFiles = new List<string>();
if (isInAutomaticMode)
{
listOfDownloadedFiles.AddRange(PatchingWizard_AutomatedUpdatesPage.AllDownloadedPatches.Values);
}
else
{
listOfDownloadedFiles.AddRange(PatchingWizard_UploadPage.AllDownloadedPatches.Values);
}
foreach (string downloadedPatch in listOfDownloadedFiles)
{
try
{
if (File.Exists(downloadedPatch))
{
File.Delete(downloadedPatch);
}
}
catch
{
log.DebugFormat("Could not remove downloaded patch {0} ", downloadedPatch);
}
}
}
protected override void FinishWizard()
{
if (PatchingWizard_UploadPage.NewUploadedPatches != null)
{
List<Pool_patch> patchesToRemove =
PatchingWizard_UploadPage.NewUploadedPatches.Keys.ToList().Where(
patch => !string.Equals(patch.uuid, PatchingWizard_UploadPage.Patch.uuid, System.StringComparison.OrdinalIgnoreCase)).ToList();
RemoveUnwantedPatches(patchesToRemove);
}
if (PatchingWizard_UploadPage.AllCreatedSuppPackVdis != null)
RemoveTemporaryVdis();
CleanUpPoolUpdates();
RemoveDownloadedPatches();
Updates.CheckServerPatches();
base.FinishWizard();
}
private List<AsyncAction> GetCleanUpPoolUpdateActions()
{
if (PatchingWizard_UploadPage.AllIntroducedPoolUpdates != null && PatchingWizard_UploadPage.AllIntroducedPoolUpdates.Count > 0)
{
return PatchingWizard_UploadPage.AllIntroducedPoolUpdates.Keys.Select(GetCleanUpPoolUpdateAction).ToList();
}
return new List<AsyncAction>();
}
private static AsyncAction GetCleanUpPoolUpdateAction(Pool_update poolUpdate)
{
return
new DelegatedAsyncAction(poolUpdate.Connection, Messages.REMOVE_PATCH, "", "", session =>
{
try
{
Pool_update.pool_clean(session, poolUpdate.opaque_ref);
if(!poolUpdate.AppliedOnHosts.Any())
Pool_update.destroy(session, poolUpdate.opaque_ref);
}
catch (Failure f)
{
log.Error("Clean up failed", f);
}
});
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using EnvDTE;
using Typewriter.CodeModel.Implementation;
using Typewriter.Metadata.Providers;
using Typewriter.VisualStudio;
using VSLangProj;
namespace Typewriter.Generation.Controllers
{
public class TemplateController
{
private static readonly object locker = new object();
private readonly DTE dte;
private readonly IMetadataProvider metadataProvider;
private readonly SolutionMonitor solutionMonitor;
private readonly EventQueue eventQueue;
private bool solutionOpen;
private ICollection<Template> templates;
public TemplateController(DTE dte, IMetadataProvider metadataProvider, SolutionMonitor solutionMonitor, EventQueue eventQueue)
{
this.dte = dte;
this.metadataProvider = metadataProvider;
this.solutionMonitor = solutionMonitor;
this.eventQueue = eventQueue;
solutionMonitor.SolutionOpened += (sender, args) => SolutionOpened();
solutionMonitor.SolutionClosed += (sender, args) => SolutionClosed();
solutionMonitor.ProjectAdded += (o, e) => ProjectChanged();
solutionMonitor.ProjectRemoved += (o, e) => ProjectChanged();
solutionMonitor.FileAdded += (o, e) => FileChanged(e.Path);
solutionMonitor.FileChanged += (o, e) => FileSaved(e.Path);
solutionMonitor.FileDeleted += (o, e) => FileChanged(e.Path);
solutionMonitor.FileRenamed += (o, e) =>
{
FileChanged(e.OldPath);
FileChanged(e.NewPath);
};
}
private void SolutionOpened()
{
Log.Debug("Solution Opened");
solutionOpen = true;
}
private void SolutionClosed()
{
Log.Debug("Solution Closed");
solutionOpen = false;
}
private void ProjectChanged()
{
if (solutionOpen == false) return;
this.templates = null;
}
private bool FileChanged(string path)
{
if (path.EndsWith(Constants.Extension, StringComparison.InvariantCultureIgnoreCase))
{
this.templates = null;
return true;
}
return false;
}
private void FileSaved(string path)
{
if (!FileChanged(path)) return;
try
{
var projectItem = dte.Solution.FindProjectItem(path);
var template = new Template(projectItem);
foreach (var item in GetReferencedProjectItems(projectItem, ".cs"))
{
eventQueue.Enqueue(generationEvent => Render(template, generationEvent), GenerationType.Render, item.Path());
}
}
catch (Exception e)
{
Log.Debug(e.Message);
}
}
private void Render(Template template, GenerationEvent generationEvent)
{
try
{
var stopwatch = Stopwatch.StartNew();
var path = generationEvent.Paths[0];
Log.Debug("Render {0}", path);
var metadata = metadataProvider.GetFile(dte.Solution.FindProjectItem(path));
var file = new FileImpl(metadata);
var success = template.RenderFile(file, false);
if (success == false)
{
solutionMonitor.TriggerFileChanged(path);
}
stopwatch.Stop();
Log.Debug("Render completed in {0} ms", stopwatch.ElapsedMilliseconds);
}
catch (Exception exception)
{
Log.Error("Render Exception: {0}, {1}", exception.Message, exception.StackTrace);
}
}
public ICollection<Template> Templates => LoadTemplates();
private ICollection<Template> LoadTemplates()
{
var stopwatch = Stopwatch.StartNew();
//lock (locker)
//{
if (this.templates == null)
{
var items = GetProjectItems();
this.templates = items.Select(i =>
{
try
{
return new Template(i);
}
catch (Exception e)
{
Log.Debug(e.Message);
Log.Warn($"Template {i.Path()} will be ignored until the errors are removed.");
return null;
}
}).Where(t => t != null).ToList();
}
else
{
foreach (var template in this.templates)
{
try
{
template.VerifyProjectItem();
}
catch
{
Log.Debug("Invalid template");
this.templates = null;
return LoadTemplates();
}
}
}
//}
stopwatch.Stop();
Log.Debug("Templates loaded in {0} ms", stopwatch.ElapsedMilliseconds);
return this.templates;
}
private IEnumerable<ProjectItem> GetReferencedProjectItems(ProjectItem i, string extension)
{
var vsproject = i.ContainingProject.Object as VSProject;
if (vsproject != null)
{
foreach (Reference reference in vsproject.References)
{
var sp = reference.SourceProject;
if (sp != null)
{
foreach (var item in sp.AllProjectItems().Where(item => item.Name.EndsWith(extension, StringComparison.InvariantCultureIgnoreCase)))
{
yield return item;
}
}
}
foreach (var item in i.ContainingProject.AllProjectItems().Where(item => item.Name.EndsWith(extension, StringComparison.InvariantCultureIgnoreCase)))
{
yield return item;
}
}
}
private IEnumerable<ProjectItem> GetProjectItems()
{
var projects = dte.Solution.AllProjetcs().Select(p =>
{
try
{
return p.FileName;
}
catch (Exception ex)
{
Log.Debug("Error finding project file name ({0})", ex.Message);
return null;
}
});
var files = projects.Where(p => string.IsNullOrWhiteSpace(p) == false)
.SelectMany(p => new System.IO.FileInfo(p).Directory?.GetFiles("*.tst", SearchOption.AllDirectories))
.Where(f => f != null);
return files.Select(a => dte.Solution.FindProjectItem(a.FullName));
}
}
}
| |
// 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.
/*============================================================
**
** Class: ResourceWriter
**
**
**
** Purpose: Default way to write strings to a CLR resource
** file.
**
**
===========================================================*/
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Versioning;
using System.Runtime.Serialization;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Resources
{
// Generates a binary .resources file in the system default format
// from name and value pairs. Create one with a unique file name,
// call AddResource() at least once, then call Generate() to write
// the .resources file to disk, then call Dispose() to close the file.
//
// The resources generally aren't written out in the same order
// they were added.
//
// See the RuntimeResourceSet overview for details on the system
// default file format.
//
public sealed class ResourceWriter : IResourceWriter
{
// An initial size for our internal sorted list, to avoid extra resizes.
private const int AverageNameSize = 20 * 2; // chars in little endian Unicode
private const int AverageValueSize = 40;
private const string ResourceReaderFullyQualifiedName = "System.Resources.ResourceReader, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
private const string ResSetTypeName = "System.Resources.RuntimeResourceSet";
private const int ResSetVersion = 2;
private SortedDictionary<string, object> _resourceList;
private Stream _output;
private Dictionary<string, object> _caseInsensitiveDups;
private Dictionary<string, PrecannedResource> _preserializedData;
// Set this delegate to allow multi-targeting for .resources files.
public Func<Type, string> TypeNameConverter { get; set; }
public ResourceWriter(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
Contract.EndContractBlock();
_output = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None);
_resourceList = new SortedDictionary<string, object>(FastResourceComparer.Default);
_caseInsensitiveDups = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
}
public ResourceWriter(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (!stream.CanWrite)
throw new ArgumentException(SR.Argument_StreamNotWritable);
Contract.EndContractBlock();
_output = stream;
_resourceList = new SortedDictionary<string, object>(FastResourceComparer.Default);
_caseInsensitiveDups = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
}
// Adds a string resource to the list of resources to be written to a file.
// They aren't written until Generate() is called.
//
public void AddResource(string name, string value)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
if (_resourceList == null)
throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved);
// Check for duplicate resources whose names vary only by case.
_caseInsensitiveDups.Add(name, null);
_resourceList.Add(name, value);
}
// Adds a resource of type Object to the list of resources to be
// written to a file. They aren't written until Generate() is called.
//
public void AddResource(string name, object value)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
if (_resourceList == null)
throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved);
// needed for binary compat
if (value != null && value is Stream)
{
AddResourceInternal(name, (Stream)value, false);
}
else
{
// Check for duplicate resources whose names vary only by case.
_caseInsensitiveDups.Add(name, null);
_resourceList.Add(name, value);
}
}
// Adds a resource of type Stream to the list of resources to be
// written to a file. They aren't written until Generate() is called.
// Doesn't close the Stream when done.
//
public void AddResource(string name, Stream value)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
if (_resourceList == null)
throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved);
AddResourceInternal(name, value, false);
}
// Adds a resource of type Stream to the list of resources to be
// written to a file. They aren't written until Generate() is called.
// closeAfterWrite parameter indicates whether to close the stream when done.
//
public void AddResource(string name, Stream value, bool closeAfterWrite)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
if (_resourceList == null)
throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved);
AddResourceInternal(name, value, closeAfterWrite);
}
private void AddResourceInternal(string name, Stream value, bool closeAfterWrite)
{
if (value == null)
{
// Check for duplicate resources whose names vary only by case.
_caseInsensitiveDups.Add(name, null);
_resourceList.Add(name, value);
}
else
{
// make sure the Stream is seekable
if (!value.CanSeek)
throw new ArgumentException(SR.NotSupported_UnseekableStream);
// Check for duplicate resources whose names vary only by case.
_caseInsensitiveDups.Add(name, null);
_resourceList.Add(name, new StreamWrapper(value, closeAfterWrite));
}
}
// Adds a named byte array as a resource to the list of resources to
// be written to a file. They aren't written until Generate() is called.
//
public void AddResource(string name, byte[] value)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
if (_resourceList == null)
throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved);
// Check for duplicate resources whose names vary only by case.
_caseInsensitiveDups.Add(name, null);
_resourceList.Add(name, value);
}
public void AddResourceData(string name, string typeName, byte[] serializedData)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (typeName == null)
throw new ArgumentNullException(nameof(typeName));
if (serializedData == null)
throw new ArgumentNullException(nameof(serializedData));
Contract.EndContractBlock();
if (_resourceList == null)
throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved);
// Check for duplicate resources whose names vary only by case.
_caseInsensitiveDups.Add(name, null);
if (_preserializedData == null)
_preserializedData = new Dictionary<string, PrecannedResource>(FastResourceComparer.Default);
_preserializedData.Add(name, new PrecannedResource(typeName, serializedData));
}
// For cases where users can't create an instance of the deserialized
// type in memory, and need to pass us serialized blobs instead.
// LocStudio's managed code parser will do this in some cases.
private class PrecannedResource
{
internal readonly string TypeName;
internal readonly byte[] Data;
internal PrecannedResource(string typeName, byte[] data)
{
TypeName = typeName;
Data = data;
}
}
private class StreamWrapper
{
internal readonly Stream Stream;
internal readonly bool CloseAfterWrite;
internal StreamWrapper(Stream s, bool closeAfterWrite)
{
Stream = s;
CloseAfterWrite = closeAfterWrite;
}
}
public void Close()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (disposing)
{
if (_resourceList != null)
{
Generate();
}
if (_output != null)
{
_output.Dispose();
}
}
_output = null;
_caseInsensitiveDups = null;
}
public void Dispose()
{
Dispose(true);
}
// After calling AddResource, Generate() writes out all resources to the
// output stream in the system default format.
// If an exception occurs during object serialization or during IO,
// the .resources file is closed and deleted, since it is most likely
// invalid.
public void Generate()
{
if (_resourceList == null)
throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved);
BinaryWriter bw = new BinaryWriter(_output, Encoding.UTF8);
List<string> typeNames = new List<string>();
// Write out the ResourceManager header
// Write out magic number
bw.Write(ResourceManager.MagicNumber);
// Write out ResourceManager header version number
bw.Write(ResourceManager.HeaderVersionNumber);
MemoryStream resMgrHeaderBlob = new MemoryStream(240);
BinaryWriter resMgrHeaderPart = new BinaryWriter(resMgrHeaderBlob);
// Write out class name of IResourceReader capable of handling
// this file.
resMgrHeaderPart.Write(ResourceReaderFullyQualifiedName);
// Write out class name of the ResourceSet class best suited to
// handling this file.
// This needs to be the same even with multi-targeting. It's the
// full name -- not the assembly qualified name.
resMgrHeaderPart.Write(ResSetTypeName);
resMgrHeaderPart.Flush();
// Write number of bytes to skip over to get past ResMgr header
bw.Write((int)resMgrHeaderBlob.Length);
// Write the rest of the ResMgr header
Debug.Assert(resMgrHeaderBlob.Length > 0, "ResourceWriter: Expected non empty header");
resMgrHeaderBlob.Seek(0, SeekOrigin.Begin);
resMgrHeaderBlob.CopyTo(bw.BaseStream, (int)resMgrHeaderBlob.Length);
// End ResourceManager header
// Write out the RuntimeResourceSet header
// Version number
bw.Write(ResSetVersion);
// number of resources
int numResources = _resourceList.Count;
if (_preserializedData != null)
numResources += _preserializedData.Count;
bw.Write(numResources);
// Store values in temporary streams to write at end of file.
int[] nameHashes = new int[numResources];
int[] namePositions = new int[numResources];
int curNameNumber = 0;
MemoryStream nameSection = new MemoryStream(numResources * AverageNameSize);
BinaryWriter names = new BinaryWriter(nameSection, Encoding.Unicode);
Stream dataSection = new MemoryStream(); // Either a FileStream or a MemoryStream
using (dataSection)
{
BinaryWriter data = new BinaryWriter(dataSection, Encoding.UTF8);
if (_preserializedData != null)
{
foreach (KeyValuePair<string, PrecannedResource> entry in _preserializedData)
{
_resourceList.Add(entry.Key, entry.Value);
}
}
// Write resource name and position to the file, and the value
// to our temporary buffer. Save Type as well.
foreach (var item in _resourceList)
{
nameHashes[curNameNumber] = FastResourceComparer.HashFunction(item.Key);
namePositions[curNameNumber++] = (int)names.Seek(0, SeekOrigin.Current);
names.Write(item.Key); // key
names.Write((int)data.Seek(0, SeekOrigin.Current)); // virtual offset of value.
object value = item.Value;
ResourceTypeCode typeCode = FindTypeCode(value, typeNames);
// Write out type code
Write7BitEncodedInt(data, (int)typeCode);
var userProvidedResource = value as PrecannedResource;
if (userProvidedResource != null)
{
data.Write(userProvidedResource.Data);
}
else
{
WriteValue(typeCode, value, data);
}
}
// At this point, the ResourceManager header has been written.
// Finish RuntimeResourceSet header
// The reader expects a list of user defined type names
// following the size of the list, write 0 for this
// writer implementation
bw.Write(typeNames.Count);
foreach (var typeName in typeNames)
{
bw.Write(typeName);
}
// Write out the name-related items for lookup.
// Note that the hash array and the namePositions array must
// be sorted in parallel.
Array.Sort(nameHashes, namePositions);
// Prepare to write sorted name hashes (alignment fixup)
// Note: For 64-bit machines, these MUST be aligned on 8 byte
// boundaries! Pointers on IA64 must be aligned! And we'll
// run faster on X86 machines too.
bw.Flush();
int alignBytes = ((int)bw.BaseStream.Position) & 7;
if (alignBytes > 0)
{
for (int i = 0; i < 8 - alignBytes; i++)
bw.Write("PAD"[i % 3]);
}
// Write out sorted name hashes.
// Align to 8 bytes.
Debug.Assert((bw.BaseStream.Position & 7) == 0, "ResourceWriter: Name hashes array won't be 8 byte aligned! Ack!");
foreach (int hash in nameHashes)
{
bw.Write(hash);
}
// Write relative positions of all the names in the file.
// Note: this data is 4 byte aligned, occurring immediately
// after the 8 byte aligned name hashes (whose length may
// potentially be odd).
Debug.Assert((bw.BaseStream.Position & 3) == 0, "ResourceWriter: Name positions array won't be 4 byte aligned! Ack!");
foreach (int pos in namePositions)
{
bw.Write(pos);
}
// Flush all BinaryWriters to their underlying streams.
bw.Flush();
names.Flush();
data.Flush();
// Write offset to data section
int startOfDataSection = (int)(bw.Seek(0, SeekOrigin.Current) + nameSection.Length);
startOfDataSection += 4; // We're writing an int to store this data, adding more bytes to the header
bw.Write(startOfDataSection);
// Write name section.
if (nameSection.Length > 0)
{
nameSection.Seek(0, SeekOrigin.Begin);
nameSection.CopyTo(bw.BaseStream, (int)nameSection.Length);
}
names.Dispose();
// Write data section.
Debug.Assert(startOfDataSection == bw.Seek(0, SeekOrigin.Current), "ResourceWriter::Generate - start of data section is wrong!");
dataSection.Position = 0;
dataSection.CopyTo(bw.BaseStream);
data.Dispose();
} // using(dataSection) <--- Closes dataSection, which was opened w/ FileOptions.DeleteOnClose
bw.Flush();
// Indicate we've called Generate
_resourceList = null;
}
private static void Write7BitEncodedInt(BinaryWriter store, int value)
{
Debug.Assert(store != null);
// Write out an int 7 bits at a time. The high bit of the byte,
// when on, tells reader to continue reading more bytes.
uint v = (uint)value; // support negative numbers
while (v >= 0x80)
{
store.Write((byte)(v | 0x80));
v >>= 7;
}
store.Write((byte)v);
}
// Finds the ResourceTypeCode for a type, or adds this type to the
// types list.
private ResourceTypeCode FindTypeCode(object value, List<string> types)
{
if (value == null)
return ResourceTypeCode.Null;
Type type = value.GetType();
if (type == typeof(string))
return ResourceTypeCode.String;
else if (type == typeof(int))
return ResourceTypeCode.Int32;
else if (type == typeof(bool))
return ResourceTypeCode.Boolean;
else if (type == typeof(char))
return ResourceTypeCode.Char;
else if (type == typeof(byte))
return ResourceTypeCode.Byte;
else if (type == typeof(sbyte))
return ResourceTypeCode.SByte;
else if (type == typeof(short))
return ResourceTypeCode.Int16;
else if (type == typeof(long))
return ResourceTypeCode.Int64;
else if (type == typeof(ushort))
return ResourceTypeCode.UInt16;
else if (type == typeof(uint))
return ResourceTypeCode.UInt32;
else if (type == typeof(ulong))
return ResourceTypeCode.UInt64;
else if (type == typeof(float))
return ResourceTypeCode.Single;
else if (type == typeof(double))
return ResourceTypeCode.Double;
else if (type == typeof(decimal))
return ResourceTypeCode.Decimal;
else if (type == typeof(DateTime))
return ResourceTypeCode.DateTime;
else if (type == typeof(TimeSpan))
return ResourceTypeCode.TimeSpan;
else if (type == typeof(byte[]))
return ResourceTypeCode.ByteArray;
else if (type == typeof(StreamWrapper))
return ResourceTypeCode.Stream;
// This is a user type, or a precanned resource. Find type
// table index. If not there, add new element.
string typeName;
if (type == typeof(PrecannedResource)) {
typeName = ((PrecannedResource)value).TypeName;
if (typeName.StartsWith("ResourceTypeCode.", StringComparison.Ordinal)) {
typeName = typeName.Substring(17); // Remove through '.'
ResourceTypeCode typeCode = (ResourceTypeCode)Enum.Parse(typeof(ResourceTypeCode), typeName);
return typeCode;
}
}
else
{
typeName = MultitargetingHelpers.GetAssemblyQualifiedName(type, TypeNameConverter);
}
int typeIndex = types.IndexOf(typeName);
if (typeIndex == -1) {
typeIndex = types.Count;
types.Add(typeName);
}
return (ResourceTypeCode)(typeIndex + ResourceTypeCode.StartOfUserTypes);
}
private void WriteValue(ResourceTypeCode typeCode, object value, BinaryWriter writer)
{
Contract.Requires(writer != null);
switch (typeCode)
{
case ResourceTypeCode.Null:
break;
case ResourceTypeCode.String:
writer.Write((string)value);
break;
case ResourceTypeCode.Boolean:
writer.Write((bool)value);
break;
case ResourceTypeCode.Char:
writer.Write((ushort)(char)value);
break;
case ResourceTypeCode.Byte:
writer.Write((byte)value);
break;
case ResourceTypeCode.SByte:
writer.Write((sbyte)value);
break;
case ResourceTypeCode.Int16:
writer.Write((short)value);
break;
case ResourceTypeCode.UInt16:
writer.Write((ushort)value);
break;
case ResourceTypeCode.Int32:
writer.Write((int)value);
break;
case ResourceTypeCode.UInt32:
writer.Write((uint)value);
break;
case ResourceTypeCode.Int64:
writer.Write((long)value);
break;
case ResourceTypeCode.UInt64:
writer.Write((ulong)value);
break;
case ResourceTypeCode.Single:
writer.Write((float)value);
break;
case ResourceTypeCode.Double:
writer.Write((double)value);
break;
case ResourceTypeCode.Decimal:
writer.Write((decimal)value);
break;
case ResourceTypeCode.DateTime:
// Use DateTime's ToBinary & FromBinary.
long data = ((DateTime)value).ToBinary();
writer.Write(data);
break;
case ResourceTypeCode.TimeSpan:
writer.Write(((TimeSpan)value).Ticks);
break;
// Special Types
case ResourceTypeCode.ByteArray:
{
byte[] bytes = (byte[])value;
writer.Write(bytes.Length);
writer.Write(bytes, 0, bytes.Length);
break;
}
case ResourceTypeCode.Stream:
{
StreamWrapper sw = (StreamWrapper)value;
if (sw.Stream.GetType() == typeof(MemoryStream))
{
MemoryStream ms = (MemoryStream)sw.Stream;
if (ms.Length > int.MaxValue)
throw new ArgumentException(SR.ArgumentOutOfRange_StreamLength);
byte[] arr = ms.ToArray();
writer.Write(arr.Length);
writer.Write(arr, 0, arr.Length);
}
else
{
Stream s = sw.Stream;
// we've already verified that the Stream is seekable
if (s.Length > int.MaxValue)
throw new ArgumentException(SR.ArgumentOutOfRange_StreamLength);
s.Position = 0;
writer.Write((int)s.Length);
byte[] buffer = new byte[4096];
int read = 0;
while ((read = s.Read(buffer, 0, buffer.Length)) != 0)
{
writer.Write(buffer, 0, read);
}
if (sw.CloseAfterWrite)
{
s.Close();
}
}
break;
}
default:
Contract.Assert(typeCode >= ResourceTypeCode.StartOfUserTypes, string.Format(CultureInfo.InvariantCulture, "ResourceReader: Unsupported ResourceTypeCode in .resources file! {0}", typeCode));
throw new PlatformNotSupportedException(SR.NotSupported_BinarySerializedResources);
}
}
}
internal enum ResourceTypeCode {
// Primitives
Null = 0,
String = 1,
Boolean = 2,
Char = 3,
Byte = 4,
SByte = 5,
Int16 = 6,
UInt16 = 7,
Int32 = 8,
UInt32 = 9,
Int64 = 0xa,
UInt64 = 0xb,
Single = 0xc,
Double = 0xd,
Decimal = 0xe,
DateTime = 0xf,
TimeSpan = 0x10,
// A meta-value - change this if you add new primitives
LastPrimitive = TimeSpan,
// Types with a special representation, like byte[] and Stream
ByteArray = 0x20,
Stream = 0x21,
// User types - serialized using the binary formatter.
StartOfUserTypes = 0x40
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using Ductus.FluentDocker.Commands;
using Ductus.FluentDocker.Common;
using Ductus.FluentDocker.Executors;
using Ductus.FluentDocker.Extensions;
using Ductus.FluentDocker.Model.Common;
using Ductus.FluentDocker.Model.Containers;
namespace Ductus.FluentDocker.Services.Extensions
{
public static class ContainerExtensions
{
/// <summary>
/// Read the logs from the container.
/// </summary>
/// <param name="service">The container to read the logs from.</param>
/// <param name="follow">If continuous logs is wanted.</param>
/// <param name="token">The cancellation token for logs, especially needed when <paramref name="follow" /> is set to true.</param>
/// <returns>A console stream to consume.</returns>
public static ConsoleStream<string> Logs(this IContainerService service, bool follow = false,
CancellationToken token = default)
{
return service.DockerHost.Logs(service.Id, token, follow);
}
/// <summary>
/// Executes a command with arguments on the running container.
/// </summary>
/// <param name="service">The service to execute command in.</param>
/// <param name="arguments">The command and arguments to pass</param>
/// <remarks>
/// This will call the docker exec {containerId} "command and arguments".
/// </remarks>
public static CommandResponse<IList<string>> Execute(this IContainerService service, string arguments)
{
return service.DockerHost.Execute(service.Id, arguments, service.Certificates);
}
/// <summary>
/// Translates a docker exposed port and protocol (on format 'port/proto' e.g. '534/tcp') to a
/// host endpoint that can be contacted outside the container.
/// </summary>
/// <param name="service">The container to query.</param>
/// <param name="portAndProto">The port slash protocol to translate to a host based <see cref="IPEndPoint" />.</param>
/// <returns>A host based endpoint from a exposed port or null if none.</returns>
public static IPEndPoint ToHostExposedEndpoint(this IContainerService service, string portAndProto)
{
return service.GetConfiguration()?.NetworkSettings.Ports.ToHostPortCustomResolver(
service.CustomEndpointResolver, portAndProto, service.DockerHost
);
}
/// <summary>
/// Diffs the container from it's original state to the current state.
/// </summary>
/// <param name="service">The container to do the diff operation on.</param>
/// <returns>
/// An array, zero or more, <see cref="Model.Containers.Diff" /> instances, reflecting the changes from the container
/// starting point (when it has started).
/// </returns>
public static IList<Diff> Diff(this IContainerService service)
{
return service.DockerHost.Diff(service.Id, service.Certificates).Data;
}
/// <summary>
/// Diffs the container from it's original state to the current state.
/// </summary>
/// <param name="service">The container to do the diff operation on.</param>
/// <param name="result">
/// An array, zero or more, <see cref="Model.Containers.Diff" /> instances, reflecting the changes from the container
/// starting point (when it has started).
/// </param>
/// <returns>The service itself.</returns>
public static IContainerService Diff(this IContainerService service, out IList<Diff> result)
{
result = service.DockerHost.Diff(service.Id, service.Certificates).Data;
return service;
}
/// <summary>
/// Exports the container to specified fqPath.
/// </summary>
/// <param name="service">The container to export.</param>
/// <param name="fqPath">A fqPath (with filename) to export to.</param>
/// <param name="explode">
/// If set to true, this will become the directory instead where the exploded tar file will reside,
/// default is false.
/// </param>
/// <param name="throwOnError">If a exception shall be thrown if any error occurs.</param>
/// <returns>The service itself.</returns>
/// <exception cref="FluentDockerException">
/// The exception thrown when an error occurred and <paramref name="throwOnError" />
/// is set to true.
/// </exception>
public static IContainerService Export(this IContainerService service, TemplateString fqPath, bool explode = false,
bool throwOnError = false)
{
var path = explode ? Path.GetTempFileName() : (string)fqPath;
var res = service.DockerHost.Export(service.Id, path, service.Certificates);
if (!res.Success)
{
if (throwOnError)
{
throw new FluentDockerException(
$"Failed to export {service.Id} to {fqPath} - result: {res}");
}
return service;
}
if (!explode)
{
return service;
}
try
{
path.UnTar(fqPath);
}
catch (Exception e)
{
if (throwOnError)
{
throw new FluentDockerException("Exception while un-taring archive", e);
}
}
finally
{
File.Delete(path);
}
return service;
}
/// <summary>
/// Gets the running processes within the container.
/// </summary>
/// <param name="service">The container to get the processes from.</param>
/// <returns>A <see cref="Processes" /> instance with one or more process rows.</returns>
public static Processes GetRunningProcesses(this IContainerService service)
{
return service.DockerHost.Top(service.Id, service.Certificates).Data;
}
/// <summary>
/// Copies file or directory from the <paramref name="containerPath" /> to the host <paramref name="hostPath" />.
/// </summary>
/// <param name="service">The container to copy from.</param>
/// <param name="containerPath">The container path to copy from.</param>
/// <param name="hostPath">The host path to copy to.</param>
/// <param name="throwOnError">If it shall throw if any errors occur during copy.</param>
/// <returns>The path where the files where copied to if successful, otherwise null is returned.</returns>
/// <exception cref="FluentDockerException">If <paramref name="throwOnError" /> is true and error occurred during copy.</exception>
public static IContainerService CopyFrom(this IContainerService service, TemplateString containerPath,
TemplateString hostPath, bool throwOnError = false)
{
var res = service.DockerHost.CopyFromContainer(service.Id, containerPath, hostPath, service.Certificates);
if (res.Success)
{
return service;
}
Debug.WriteLine($"Failed to copy from {service.Id}:{containerPath} to {hostPath} - result: {res}");
if (throwOnError)
{
throw new FluentDockerException(
$"Failed to copy from {service.Id}:{containerPath} to {hostPath} - result: {res}");
}
return service;
}
/// <summary>
/// Copies file or directory from the <paramref name="hostPath" /> to the containers <paramref name="containerPath" />.
/// </summary>
/// <param name="service">The container to copy to.</param>
/// <param name="containerPath">The container path to copy to.</param>
/// <param name="hostPath">The host path to copy from.</param>
/// <param name="throwOnError">If it shall throw if any errors occur during copy.</param>
/// <returns>The path where the files where copied from if successful, otherwise null is returned.</returns>
/// <exception cref="FluentDockerException">If <paramref name="throwOnError" /> is true and error occurred during copy.</exception>
public static IContainerService CopyTo(this IContainerService service, TemplateString containerPath,
TemplateString hostPath, bool throwOnError = false)
{
var res = service.DockerHost.CopyToContainer(service.Id, containerPath, hostPath, service.Certificates);
if (res.Success)
{
return service;
}
Debug.WriteLine($"Failed to copy to {service.Id}:{containerPath} from {hostPath} - result: {res}");
if (throwOnError)
{
throw new FluentDockerException(
$"Failed to copy to {service.Id}:{containerPath} from {hostPath} - result: {res}");
}
return service;
}
/// <summary>
/// Waits for process to start.
/// </summary>
/// <param name="service">The service to check processes within.</param>
/// <param name="process">The process to wait for.</param>
/// <param name="millisTimeout">Timeout giving up the wait.</param>
/// <returns>The in param service.</returns>
public static IContainerService WaitForProcess(this IContainerService service, string process,
long millisTimeout = -1)
{
if (service == null)
return null;
Exception exception = null;
var stopwatch = Stopwatch.StartNew();
using (var mre = new ManualResetEventSlim())
{
Timer timer;
using (timer = new Timer(_ =>
{
var processes = service.GetRunningProcesses();
if (processes?.Rows.Any(x => x.Command == process) ?? false)
mre.Set();
if (stopwatch.ElapsedMilliseconds > millisTimeout)
{
exception = new FluentDockerException($"Wait expired for process {process} in container {service.Id}");
mre.Set();
}
}, null, 0, 500))
mre.Wait();
timer.Dispose();
}
if (exception != null)
throw exception;
return service;
}
/// <summary>
/// Waits for the container to be in a healthy state
/// </summary>
/// <param name="service">The service to check processes within.</param>
/// <param name="millisTimeout">Timeout giving up the wait.</param>
/// <returns>The in param service.</returns>
public static IContainerService WaitForHealthy(this IContainerService service, long millisTimeout = -1)
{
if (service == null)
return null;
Exception exception = null;
var stopwatch = Stopwatch.StartNew();
using (var mre = new ManualResetEventSlim())
{
Timer timer;
using (timer = new Timer(_ =>
{
var config = service.GetConfiguration(true);
if (config?.State?.Health?.Status == HealthState.Healthy)
mre.Set();
if (stopwatch.ElapsedMilliseconds > millisTimeout)
{
exception = new FluentDockerException($"Wait for healthy expired for container {service.Id}");
mre.Set();
}
}, null, 0, 500))
mre.Wait();
timer.Dispose();
}
if (exception != null)
throw exception;
return service;
}
/// <summary>
/// Waits for a specific message in the logs
/// </summary>
/// <param name="service">The service to check processes within.</param>
/// <param name="message">The message to wait for</param>
/// <param name="millisTimeout">Timeout giving up the wait.</param>
/// <returns>The in param service.</returns>
public static IContainerService WaitForMessageInLogs(this IContainerService service, string message, long millisTimeout = -1)
{
if (service == null)
return null;
Exception exception = null;
var stopwatch = Stopwatch.StartNew();
using (var mre = new ManualResetEventSlim())
{
Timer timer;
using (timer = new Timer(_ =>
{
var logs = service.Logs().ReadToEnd((int)millisTimeout);
var match = logs.FirstOrDefault(stringToCheck => stringToCheck.Contains(message));
if (match != null)
mre.Set();
if (stopwatch.ElapsedMilliseconds > millisTimeout)
{
exception = new FluentDockerException($"Wait for message '{message}' in logs for container {service.Id}");
mre.Set();
}
}, null, 0, 500))
mre.Wait();
timer.Dispose();
}
if (exception != null)
throw exception;
return service;
}
/// <summary>
/// Waits using an arbitrary function.
/// </summary>
/// <param name="service">The service this lambda holds.</param>
/// <param name="continuation">The lambda that do the custom action.</param>
/// <returns>The service for fluent access.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="continuation"/> is null.</exception>
/// <remarks>
/// The lambda do the actual action to determine if the wait is over or not. If it returns zero or less, the
/// wait is over. If it returns a positive value, the wait function will wait this amount of milliseconds before
/// invoking it again. The second argument is the invocation count. This can be used for the function to determine
/// any type of abort action due to the amount of invocations. If continuation wishes to abort, it shall throw
/// <see cref="FluentDockerException"/>.
/// </remarks>
public static IContainerService Wait(this IContainerService service, Func<IContainerService, int, int> continuation)
{
if (null == continuation)
throw new ArgumentNullException("Must specify a continuation", nameof(continuation));
int wait;
var count = 0;
do
{
wait = continuation.Invoke(service, count++);
if (wait > 0)
Thread.Sleep(wait);
} while (wait > 0);
return service;
}
}
}
| |
using UnityEngine;
using System;
using System.Collections.Generic;
public static class RXUtils
{
public static float GetAngle(this Vector2 vector)
{
return Mathf.Atan2(-vector.y, vector.x) * RXMath.RTOD;
}
public static float GetRadians(this Vector2 vector)
{
return Mathf.Atan2(-vector.y, vector.x);
}
public static Rect ExpandRect(Rect rect, float paddingX, float paddingY)
{
return new Rect(rect.x - paddingX, rect.y - paddingY, rect.width + paddingX*2, rect.height+paddingY*2);
}
public static void LogRect(string name, Rect rect)
{
Debug.Log (name+": ("+rect.x+","+rect.y+","+rect.width+","+rect.height+")");
}
public static void LogVectors(string name, params Vector2[] args)
{
string result = name + ": " + args.Length + " Vector2 "+ args[0].ToString()+"";
for(int a = 1; a<args.Length; ++a)
{
Vector2 arg = args[a];
result = result + ", "+ arg.ToString()+"";
}
Debug.Log(result);
}
public static void LogVectors(string name, params Vector3[] args)
{
string result = name + ": " + args.Length + " Vector3 "+args[0].ToString()+"";
for(int a = 1; a<args.Length; ++a)
{
Vector3 arg = args[a];
result = result + ", "+ arg.ToString()+"";
}
Debug.Log(result);
}
public static void LogVectorsDetailed(string name, params Vector2[] args)
{
string result = name + ": " + args.Length + " Vector2 "+ VectorDetailedToString(args[0])+"";
for(int a = 1; a<args.Length; ++a)
{
Vector2 arg = args[a];
result = result + ", "+ VectorDetailedToString(arg)+"";
}
Debug.Log(result);
}
public static string VectorDetailedToString(Vector2 vector)
{
return "("+vector.x + "," + vector.y +")";
}
public static Color GetColorFromHex(uint hex)
{
uint red = hex >> 16;
uint greenBlue = hex - (red<<16);
uint green = greenBlue >> 8;
uint blue = greenBlue - (green << 8);
return new Color(red/255.0f, green/255.0f, blue/255.0f);
}
public static Color GetColorFromHex(string hexString)
{
return GetColorFromHex(Convert.ToUInt32(hexString,16));
}
public static Vector2 GetVector2FromString(string input)
{
string[] parts = input.Split(new char[] {','});
return new Vector2(float.Parse(parts[0]), float.Parse(parts[1]));
}
}
public class RXColorHSL
{
public float h = 0.0f;
public float s = 0.0f;
public float l = 0.0f;
public RXColorHSL(float h, float s, float l)
{
this.h = h;
this.s = s;
this.l = l;
}
public RXColorHSL() : this(0.0f, 0.0f, 0.0f) {}
}
public class RXColor
{
//TODO: IMPLEMENT THIS
public static Color ColorFromRGBString(string rgbString)
{
return Color.red;
}
//TODO: IMPLEMENT THIS
public static Color ColorFromHSLString(string hslString)
{
return Color.green;
}
public static Color ColorFromHSL(RXColorHSL hsl)
{
return ColorFromHSL(hsl.h, hsl.s, hsl.l);
}
public static Color ColorFromHSL(float hue, float sat, float lum)
{
return ColorFromHSL(hue,sat,lum,1.0f);
}
//hue goes from 0 to 1
public static Color ColorFromHSL(float hue, float sat, float lum, float alpha) //default - sat:1, lum:0.5
{
hue = (100000.0f+hue)%1f; //hue wraps around
float r = lum;
float g = lum;
float b = lum;
float v = (lum <= 0.5f) ? (lum * (1.0f + sat)) : (lum + sat - lum * sat);
if (v > 0)
{
float m = lum + lum - v;
float sv = (v - m ) / v;
hue *= 6.0f;
int sextant = (int) hue;
float fract = hue - sextant;
float vsf = v * sv * fract;
float mid1 = m + vsf;
float mid2 = v - vsf;
switch (sextant)
{
case 0:
r = v;
g = mid1;
b = m;
break;
case 1:
r = mid2;
g = v;
b = m;
break;
case 2:
r = m;
g = v;
b = mid1;
break;
case 3:
r = m;
g = mid2;
b = v;
break;
case 4:
r = mid1;
g = m;
b = v;
break;
case 5:
r = v;
g = m;
b = mid2;
break;
}
}
return new Color(r,g,b,alpha);
}
//
// Math for the conversion found here: http://www.easyrgb.com/index.php?X=MATH
//
public static RXColorHSL HSLFromColor(Color rgb)
{
RXColorHSL c = new RXColorHSL();
float r = rgb.r;
float g = rgb.g;
float b = rgb.b;
float minChan = Mathf.Min(r, g, b); //Min. value of RGB
float maxChan = Mathf.Max(r, g, b); //Max. value of RGB
float deltaMax = maxChan - minChan; //Delta RGB value
c.l = (maxChan + minChan) * 0.5f;
if (Mathf.Abs(deltaMax) <= 0.0001f) //This is a gray, no chroma...
{
c.h = 0; //HSL results from 0 to 1
c.s = 0;
}
else //Chromatic data...
{
if ( c.l < 0.5f )
c.s = deltaMax / (maxChan + minChan);
else
c.s = deltaMax / (2.0f - maxChan - minChan);
float deltaR = (((maxChan - r) / 6.0f) + (deltaMax * 0.5f)) / deltaMax;
float deltaG = (((maxChan - g) / 6.0f) + (deltaMax * 0.5f)) / deltaMax;
float deltaB = (((maxChan - b) / 6.0f) + (deltaMax * 0.5f)) / deltaMax;
if (Mathf.Approximately(r, maxChan))
c.h = deltaB - deltaG;
else if (Mathf.Approximately(g, maxChan))
c.h = (1.0f / 3.0f) + deltaR - deltaB;
else if (Mathf.Approximately(b, maxChan))
c.h = (2.0f / 3.0f) + deltaG - deltaR;
if (c.h < 0.0f)
c.h += 1.0f;
else if (c.h > 1.0f)
c.h -= 1.0f;
}
return c;
}
public static Color GetColorFromHex(uint hex)
{
uint red = hex >> 16;
uint greenBlue = hex - (red<<16);
uint green = greenBlue >> 8;
uint blue = greenBlue - (green << 8);
return new Color(red/255.0f, green/255.0f, blue/255.0f);
}
}
public class RXMath
{
public const float RTOD = 180.0f/Mathf.PI;
public const float DTOR = Mathf.PI/180.0f;
public const float DOUBLE_PI = Mathf.PI*2.0f;
public const float HALF_PI = Mathf.PI/2.0f;
public const float PI = Mathf.PI;
public const float INVERSE_PI = 1.0f/Mathf.PI;
public const float INVERSE_DOUBLE_PI = 1.0f/(Mathf.PI*2.0f);
public static int Wrap(int input, int range)
{
return (input + (range*1000000)) % range;
}
public static float Wrap(float input, float range)
{
return (input + (range*1000000)) % range;
}
public static float GetDegreeDelta(float startAngle, float endAngle) //chooses the shortest angular distance
{
float delta = (endAngle - startAngle) % 360.0f;
if (delta != delta % 180.0f)
{
delta = (delta < 0) ? delta + 360.0f : delta - 360.0f;
}
return delta;
}
public static float GetRadianDelta(float startAngle, float endAngle) //chooses the shortest angular distance
{
float delta = (endAngle - startAngle) % DOUBLE_PI;
if (delta != delta % Mathf.PI)
{
delta = (delta < 0) ? delta + DOUBLE_PI : delta - DOUBLE_PI;
}
return delta;
}
//normalized ping pong (apparently Unity has this built in... so yeah) - Mathf.PingPong()
public static float PingPong(float input, float range)
{
float first = ((input + (range*1000000.0f)) % range)/range; //0 to 1
if(first < 0.5f) return first*2.0f;
else return 1.0f - ((first - 0.5f)*2.0f);
}
}
public static class RXRandom
{
private static System.Random _randomSource = new System.Random();
public static float Float()
{
return (float)_randomSource.NextDouble();
}
public static float Float(int seed)
{
return (float)new System.Random(seed).NextDouble();
}
public static double Double()
{
return _randomSource.NextDouble();
}
public static float Float(float max)
{
return (float)_randomSource.NextDouble() * max;
}
public static int Int()
{
return _randomSource.Next();
}
public static int Int(int max)
{
if(max == 0) return 0;
return _randomSource.Next() % max;
}
public static float Range(float low, float high)
{
return low + (high-low)*(float)_randomSource.NextDouble();
}
public static int Range(int low, int high)
{
int delta = high - low;
if(delta == 0) return 0;
return low + _randomSource.Next() % delta;
}
public static bool Bool()
{
return _randomSource.NextDouble() < 0.5;
}
//random item from all passed arguments/params - RXRandom.Select(one, two, three);
public static object Select(params object[] objects)
{
return objects[_randomSource.Next() % objects.Length];
}
//random item from an array
public static T AnyItem<T>(T[] items)
{
if(items.Length == 0) return default(T); //null
return items[_randomSource.Next() % items.Length];
}
//random item from a list
public static T AnyItem<T>(List<T> items)
{
if(items.Count == 0) return default(T); //null
return items[_randomSource.Next() % items.Count];
}
//this isn't really perfectly randomized, but good enough for most purposes
public static Vector2 Vector2Normalized()
{
return new Vector2(RXRandom.Range(-1.0f,1.0f),RXRandom.Range(-1.0f,1.0f)).normalized;
}
public static Vector3 Vector3Normalized()
{
return new Vector3(RXRandom.Range(-1.0f,1.0f),RXRandom.Range(-1.0f,1.0f),RXRandom.Range(-1.0f,1.0f)).normalized;
}
public static void ShuffleList<T>(List<T> list)
{
list.Sort(RandomComparison);
}
public static void Shuffle<T>(this List<T> list)
{
list.Sort(RandomComparison);
}
private static int RandomComparison<T>(T a, T b)
{
if(_randomSource.Next() % 2 == 0) return -1;
return 1;
}
}
public class RXCircle
{
public Vector2 center;
public float radius;
public float radiusSquared;
public RXCircle(Vector2 center, float radius)
{
this.center = center;
this.radius = radius;
this.radiusSquared = radius * radius;
}
public bool CheckIntersectWithRect(Rect rect)
{
return rect.CheckIntersectWithCircle(this);
}
public bool CheckIntersectWithCircle(RXCircle circle)
{
Vector2 delta = circle.center - this.center;
float radiusSumSquared = (circle.radius + this.radius) * (circle.radius + this.radius);
return (delta.sqrMagnitude <= radiusSumSquared);
}
}
//This class is incomplete, I just have to get around to converting all the equations to this simplified format
public static class RXEase
{
//based on GoKit's easing equations: https://github.com/prime31/GoKit/tree/master/Assets/Plugins/GoKit/easing
//but simplified to work with only normalized values (0..1)
//t = current time, b = starting value, c = final value, d = duration
//for our purposes, t = input, b = 0, d = 1, c = 1 :::: note that (t/d = input)
public static float QuadOut(float input)
{
return -input * (input - 2.0f);
}
public static float QuadIn(float input)
{
return input * input;
}
public static float QuadInOut(float input)
{
if (input < 0.5f) return 2.0f * input * input;
input = (input-0.5f) * 2.0f;
return 0.5f - 0.5f * input * (input - 2.0f);
}
public static float ExpoOut(float input)
{
return -Mathf.Pow( 2.0f, -10.0f * input) + 1.0f;
}
public static float ExpoIn(float input)
{
return Mathf.Pow(2.0f,10.0f * (input - 1.0f));
}
public static float ExpoInOut(float input)
{
if (input < 0.5f) return Mathf.Pow(2.0f,10.0f * (input*2.0f - 1.0f)) * 0.5f;
else return 0.5f + (-Mathf.Pow( 2.0f, -20.0f * (input-0.5f)) + 1.0f) * 0.5f;
}
public static float BackOut(float input) {return BackOut(input,1.7f);}
public static float BackOut(float input, float backAmount)
{
input = input - 1.0f;
return (input * input * ((backAmount + 1) * input + backAmount) + 1);
}
public static float BackIn(float input) {return BackIn(input,1.7f);}
public static float BackIn(float input, float backAmount)
{
return input * input * ((backAmount + 1.0f) * input - backAmount);
}
public static float BackInOut(float input) {return BackInOut(input,1.7f);}
public static float BackInOut(float input, float backAmount)
{
if (input < 0.5f) return BackIn(input*2.0f,backAmount)*0.5f;
else return 0.5f + BackOut((input-0.5f)*2.0f,backAmount)*0.5f;
}
public static float SinInOut(float input)
{
return -0.5f * (Mathf.Cos(Mathf.PI*input) - 1.0f);
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// MessageResource
/// </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.Chat.V2.Service.Channel
{
public class MessageResource : Resource
{
public sealed class OrderTypeEnum : StringEnum
{
private OrderTypeEnum(string value) : base(value) {}
public OrderTypeEnum() {}
public static implicit operator OrderTypeEnum(string value)
{
return new OrderTypeEnum(value);
}
public static readonly OrderTypeEnum Asc = new OrderTypeEnum("asc");
public static readonly OrderTypeEnum Desc = new OrderTypeEnum("desc");
}
public sealed class WebhookEnabledTypeEnum : StringEnum
{
private WebhookEnabledTypeEnum(string value) : base(value) {}
public WebhookEnabledTypeEnum() {}
public static implicit operator WebhookEnabledTypeEnum(string value)
{
return new WebhookEnabledTypeEnum(value);
}
public static readonly WebhookEnabledTypeEnum True = new WebhookEnabledTypeEnum("true");
public static readonly WebhookEnabledTypeEnum False = new WebhookEnabledTypeEnum("false");
}
private static Request BuildFetchRequest(FetchMessageOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Chat,
"/v2/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Messages/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Message parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Message </returns>
public static MessageResource Fetch(FetchMessageOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Message parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Message </returns>
public static async System.Threading.Tasks.Task<MessageResource> FetchAsync(FetchMessageOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// fetch
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to fetch the resource from </param>
/// <param name="pathChannelSid"> The SID of the Channel the message to fetch belongs to </param>
/// <param name="pathSid"> The SID of the Message resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Message </returns>
public static MessageResource Fetch(string pathServiceSid,
string pathChannelSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchMessageOptions(pathServiceSid, pathChannelSid, pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to fetch the resource from </param>
/// <param name="pathChannelSid"> The SID of the Channel the message to fetch belongs to </param>
/// <param name="pathSid"> The SID of the Message resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Message </returns>
public static async System.Threading.Tasks.Task<MessageResource> FetchAsync(string pathServiceSid,
string pathChannelSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchMessageOptions(pathServiceSid, pathChannelSid, pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildCreateRequest(CreateMessageOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Chat,
"/v2/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Messages",
postParams: options.GetParams(),
headerParams: options.GetHeaderParams()
);
}
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Message parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Message </returns>
public static MessageResource Create(CreateMessageOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Message parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Message </returns>
public static async System.Threading.Tasks.Task<MessageResource> CreateAsync(CreateMessageOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// create
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to create the resource under </param>
/// <param name="pathChannelSid"> The SID of the Channel the new resource belongs to </param>
/// <param name="from"> The Identity of the new message's author </param>
/// <param name="attributes"> A valid JSON string that contains application-specific data </param>
/// <param name="dateCreated"> The ISO 8601 date and time in GMT when the resource was created </param>
/// <param name="dateUpdated"> The ISO 8601 date and time in GMT when the resource was updated </param>
/// <param name="lastUpdatedBy"> The Identity of the User who last updated the Message </param>
/// <param name="body"> The message to send to the channel </param>
/// <param name="mediaSid"> The Media Sid to be attached to the new Message </param>
/// <param name="xTwilioWebhookEnabled"> The X-Twilio-Webhook-Enabled HTTP request header </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Message </returns>
public static MessageResource Create(string pathServiceSid,
string pathChannelSid,
string from = null,
string attributes = null,
DateTime? dateCreated = null,
DateTime? dateUpdated = null,
string lastUpdatedBy = null,
string body = null,
string mediaSid = null,
MessageResource.WebhookEnabledTypeEnum xTwilioWebhookEnabled = null,
ITwilioRestClient client = null)
{
var options = new CreateMessageOptions(pathServiceSid, pathChannelSid){From = from, Attributes = attributes, DateCreated = dateCreated, DateUpdated = dateUpdated, LastUpdatedBy = lastUpdatedBy, Body = body, MediaSid = mediaSid, XTwilioWebhookEnabled = xTwilioWebhookEnabled};
return Create(options, client);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to create the resource under </param>
/// <param name="pathChannelSid"> The SID of the Channel the new resource belongs to </param>
/// <param name="from"> The Identity of the new message's author </param>
/// <param name="attributes"> A valid JSON string that contains application-specific data </param>
/// <param name="dateCreated"> The ISO 8601 date and time in GMT when the resource was created </param>
/// <param name="dateUpdated"> The ISO 8601 date and time in GMT when the resource was updated </param>
/// <param name="lastUpdatedBy"> The Identity of the User who last updated the Message </param>
/// <param name="body"> The message to send to the channel </param>
/// <param name="mediaSid"> The Media Sid to be attached to the new Message </param>
/// <param name="xTwilioWebhookEnabled"> The X-Twilio-Webhook-Enabled HTTP request header </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Message </returns>
public static async System.Threading.Tasks.Task<MessageResource> CreateAsync(string pathServiceSid,
string pathChannelSid,
string from = null,
string attributes = null,
DateTime? dateCreated = null,
DateTime? dateUpdated = null,
string lastUpdatedBy = null,
string body = null,
string mediaSid = null,
MessageResource.WebhookEnabledTypeEnum xTwilioWebhookEnabled = null,
ITwilioRestClient client = null)
{
var options = new CreateMessageOptions(pathServiceSid, pathChannelSid){From = from, Attributes = attributes, DateCreated = dateCreated, DateUpdated = dateUpdated, LastUpdatedBy = lastUpdatedBy, Body = body, MediaSid = mediaSid, XTwilioWebhookEnabled = xTwilioWebhookEnabled};
return await CreateAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadMessageOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Chat,
"/v2/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Messages",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Message parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Message </returns>
public static ResourceSet<MessageResource> Read(ReadMessageOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<MessageResource>.FromJson("messages", response.Content);
return new ResourceSet<MessageResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Message parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Message </returns>
public static async System.Threading.Tasks.Task<ResourceSet<MessageResource>> ReadAsync(ReadMessageOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<MessageResource>.FromJson("messages", response.Content);
return new ResourceSet<MessageResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to read the resources from </param>
/// <param name="pathChannelSid"> The SID of the Channel the message to read belongs to </param>
/// <param name="order"> The sort order of the returned messages </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 Message </returns>
public static ResourceSet<MessageResource> Read(string pathServiceSid,
string pathChannelSid,
MessageResource.OrderTypeEnum order = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadMessageOptions(pathServiceSid, pathChannelSid){Order = order, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to read the resources from </param>
/// <param name="pathChannelSid"> The SID of the Channel the message to read belongs to </param>
/// <param name="order"> The sort order of the returned messages </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 Message </returns>
public static async System.Threading.Tasks.Task<ResourceSet<MessageResource>> ReadAsync(string pathServiceSid,
string pathChannelSid,
MessageResource.OrderTypeEnum order = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadMessageOptions(pathServiceSid, pathChannelSid){Order = order, 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<MessageResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<MessageResource>.FromJson("messages", 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<MessageResource> NextPage(Page<MessageResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Chat)
);
var response = client.Request(request);
return Page<MessageResource>.FromJson("messages", 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<MessageResource> PreviousPage(Page<MessageResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Chat)
);
var response = client.Request(request);
return Page<MessageResource>.FromJson("messages", response.Content);
}
private static Request BuildDeleteRequest(DeleteMessageOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.Chat,
"/v2/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Messages/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: options.GetHeaderParams()
);
}
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Message parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Message </returns>
public static bool Delete(DeleteMessageOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Message parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Message </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteMessageOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// delete
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to delete the resource from </param>
/// <param name="pathChannelSid"> The SID of the Channel the message to delete belongs to </param>
/// <param name="pathSid"> The SID of the Message resource to delete </param>
/// <param name="xTwilioWebhookEnabled"> The X-Twilio-Webhook-Enabled HTTP request header </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Message </returns>
public static bool Delete(string pathServiceSid,
string pathChannelSid,
string pathSid,
MessageResource.WebhookEnabledTypeEnum xTwilioWebhookEnabled = null,
ITwilioRestClient client = null)
{
var options = new DeleteMessageOptions(pathServiceSid, pathChannelSid, pathSid){XTwilioWebhookEnabled = xTwilioWebhookEnabled};
return Delete(options, client);
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to delete the resource from </param>
/// <param name="pathChannelSid"> The SID of the Channel the message to delete belongs to </param>
/// <param name="pathSid"> The SID of the Message resource to delete </param>
/// <param name="xTwilioWebhookEnabled"> The X-Twilio-Webhook-Enabled HTTP request header </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Message </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid,
string pathChannelSid,
string pathSid,
MessageResource.WebhookEnabledTypeEnum xTwilioWebhookEnabled = null,
ITwilioRestClient client = null)
{
var options = new DeleteMessageOptions(pathServiceSid, pathChannelSid, pathSid){XTwilioWebhookEnabled = xTwilioWebhookEnabled};
return await DeleteAsync(options, client);
}
#endif
private static Request BuildUpdateRequest(UpdateMessageOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Chat,
"/v2/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Messages/" + options.PathSid + "",
postParams: options.GetParams(),
headerParams: options.GetHeaderParams()
);
}
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update Message parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Message </returns>
public static MessageResource Update(UpdateMessageOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update Message parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Message </returns>
public static async System.Threading.Tasks.Task<MessageResource> UpdateAsync(UpdateMessageOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// update
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to update the resource from </param>
/// <param name="pathChannelSid"> The SID of the Channel the message belongs to </param>
/// <param name="pathSid"> The SID of the Message resource to update </param>
/// <param name="body"> The message to send to the channel </param>
/// <param name="attributes"> A valid JSON string that contains application-specific data </param>
/// <param name="dateCreated"> The ISO 8601 date and time in GMT when the resource was created </param>
/// <param name="dateUpdated"> The ISO 8601 date and time in GMT when the resource was updated </param>
/// <param name="lastUpdatedBy"> The Identity of the User who last updated the Message, if applicable </param>
/// <param name="from"> The Identity of the message's author </param>
/// <param name="xTwilioWebhookEnabled"> The X-Twilio-Webhook-Enabled HTTP request header </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Message </returns>
public static MessageResource Update(string pathServiceSid,
string pathChannelSid,
string pathSid,
string body = null,
string attributes = null,
DateTime? dateCreated = null,
DateTime? dateUpdated = null,
string lastUpdatedBy = null,
string from = null,
MessageResource.WebhookEnabledTypeEnum xTwilioWebhookEnabled = null,
ITwilioRestClient client = null)
{
var options = new UpdateMessageOptions(pathServiceSid, pathChannelSid, pathSid){Body = body, Attributes = attributes, DateCreated = dateCreated, DateUpdated = dateUpdated, LastUpdatedBy = lastUpdatedBy, From = from, XTwilioWebhookEnabled = xTwilioWebhookEnabled};
return Update(options, client);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to update the resource from </param>
/// <param name="pathChannelSid"> The SID of the Channel the message belongs to </param>
/// <param name="pathSid"> The SID of the Message resource to update </param>
/// <param name="body"> The message to send to the channel </param>
/// <param name="attributes"> A valid JSON string that contains application-specific data </param>
/// <param name="dateCreated"> The ISO 8601 date and time in GMT when the resource was created </param>
/// <param name="dateUpdated"> The ISO 8601 date and time in GMT when the resource was updated </param>
/// <param name="lastUpdatedBy"> The Identity of the User who last updated the Message, if applicable </param>
/// <param name="from"> The Identity of the message's author </param>
/// <param name="xTwilioWebhookEnabled"> The X-Twilio-Webhook-Enabled HTTP request header </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Message </returns>
public static async System.Threading.Tasks.Task<MessageResource> UpdateAsync(string pathServiceSid,
string pathChannelSid,
string pathSid,
string body = null,
string attributes = null,
DateTime? dateCreated = null,
DateTime? dateUpdated = null,
string lastUpdatedBy = null,
string from = null,
MessageResource.WebhookEnabledTypeEnum xTwilioWebhookEnabled = null,
ITwilioRestClient client = null)
{
var options = new UpdateMessageOptions(pathServiceSid, pathChannelSid, pathSid){Body = body, Attributes = attributes, DateCreated = dateCreated, DateUpdated = dateUpdated, LastUpdatedBy = lastUpdatedBy, From = from, XTwilioWebhookEnabled = xTwilioWebhookEnabled};
return await UpdateAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a MessageResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> MessageResource object represented by the provided JSON </returns>
public static MessageResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<MessageResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The JSON string that stores application-specific data
/// </summary>
[JsonProperty("attributes")]
public string Attributes { get; private set; }
/// <summary>
/// The SID of the Service that the resource is associated with
/// </summary>
[JsonProperty("service_sid")]
public string ServiceSid { get; private set; }
/// <summary>
/// The SID of the Channel that the message was sent to
/// </summary>
[JsonProperty("to")]
public string To { get; private set; }
/// <summary>
/// The SID of the Channel the Message resource belongs to
/// </summary>
[JsonProperty("channel_sid")]
public string ChannelSid { get; private set; }
/// <summary>
/// The RFC 2822 date and time in GMT when the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The RFC 2822 date and time in GMT when the resource was last updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The Identity of the User who last updated the Message
/// </summary>
[JsonProperty("last_updated_by")]
public string LastUpdatedBy { get; private set; }
/// <summary>
/// Whether the message has been edited since it was created
/// </summary>
[JsonProperty("was_edited")]
public bool? WasEdited { get; private set; }
/// <summary>
/// The Identity of the message's author
/// </summary>
[JsonProperty("from")]
public string From { get; private set; }
/// <summary>
/// The content of the message
/// </summary>
[JsonProperty("body")]
public string Body { get; private set; }
/// <summary>
/// The index of the message within the Channel
/// </summary>
[JsonProperty("index")]
public int? Index { get; private set; }
/// <summary>
/// The Message type
/// </summary>
[JsonProperty("type")]
public string Type { get; private set; }
/// <summary>
/// A Media object that describes the Message's media if attached; otherwise, null
/// </summary>
[JsonProperty("media")]
public object Media { get; private set; }
/// <summary>
/// The absolute URL of the Message resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
private MessageResource()
{
}
}
}
| |
namespace UniversalDemo
{
using System;
using Dropbox.Api;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Storage;
#if WINDOWS_APP
using Windows.UI.ApplicationSettings;
#endif
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
public sealed partial class App : Application
{
/// <summary>
/// The dropbox app key.
/// </summary>
/// <remarks>
/// This can be found in the
/// <a href="https://www.dropbox.com/developers/apps">App Console</a>.
/// </remarks>
public const string AppKey = "<<Enter your App Key here>>";
/// <summary>
/// The redirect URI
/// </summary>
public static readonly Uri RedirectUri = new Uri("http://localhost:5000/admin/auth");
/// <summary>
/// The dropbox client
/// </summary>
private DropboxClient dropboxClient;
#if WINDOWS_PHONE_APP
/// <summary>
/// The transitions
/// </summary>
private TransitionCollection transitions;
#endif
/// <summary>
/// Initializes a new instance of the <see cref="App"/> class.
/// </summary>
/// <remarks>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </remarks>
public App()
{
this.InitializeComponent();
this.Suspending += this.OnSuspending;
if (!string.IsNullOrEmpty(this.AccessToken))
{
this.SetNewDropboxClient();
}
}
/// <summary>
/// Occurs when the dropbox client is changed.
/// </summary>
/// <remarks>
/// This is typically if the user connects to, or disconnects from,
/// dropbox.
/// </remarks>
public event EventHandler DropboxClientChanged;
/// <summary>
/// Gets or sets the access token.
/// </summary>
public string AccessToken
{
get
{
var localSettings = ApplicationData.Current.LocalSettings;
object accessToken;
if (localSettings.Values.TryGetValue("DropboxAccessToken", out accessToken))
{
return accessToken.ToString();
}
return string.Empty;
}
set
{
var localSettings = ApplicationData.Current.LocalSettings;
if (string.IsNullOrEmpty(value))
{
localSettings.Values.Remove("DropboxAccessToken");
this.DropboxClient = null;
}
else
{
localSettings.Values["DropboxAccessToken"] = value;
this.SetNewDropboxClient();
}
}
}
/// <summary>
/// Gets the dropbox client.
/// </summary>
public DropboxClient DropboxClient
{
get
{
return this.dropboxClient;
}
private set
{
using (var old = this.dropboxClient)
{
this.dropboxClient = value;
}
var handler = this.DropboxClientChanged;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
#if WINDOWS_PHONE_APP
/// <summary>
/// Raises the <see cref="E:Activated" /> event.
/// </summary>
/// <param name="args">The <see cref="IActivatedEventArgs"/> instance containing the event data.</param>
protected override void OnActivated(IActivatedEventArgs args)
{
base.OnActivated(args);
if (args is WebAuthenticationBrokerContinuationEventArgs)
{
try
{
DropboxOAuth.ProcessContinuation((WebAuthenticationBrokerContinuationEventArgs)args);
}
catch(Exception)
{
// authentication was cancelled or failed, there's no useful way to surface this
// information.
}
}
}
#endif
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used when the application is launched to open a specific file, to display
/// search results, and so forth.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
/// <exception cref="System.Exception">Failed to create initial page</exception>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
// TODO: change this value to a cache size that is appropriate for your application
rootFrame.CacheSize = 1;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
// TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
#if WINDOWS_PHONE_APP
// Removes the turnstile navigation for startup.
if (rootFrame.ContentTransitions != null)
{
this.transitions = new TransitionCollection();
foreach (var c in rootFrame.ContentTransitions)
{
this.transitions.Add(c);
}
}
rootFrame.ContentTransitions = null;
rootFrame.Navigated += this.RootFrame_FirstNavigated;
#endif
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
if (!rootFrame.Navigate(typeof(MainPage), e.Arguments))
{
throw new Exception("Failed to create initial page");
}
}
// Ensure the current window is active
Window.Current.Activate();
}
/// <summary>
/// Raises the <see cref="E:WindowCreated" /> event.
/// </summary>
/// <param name="args">The <see cref="WindowCreatedEventArgs"/> instance containing the event data.</param>
protected override void OnWindowCreated(WindowCreatedEventArgs args)
{
#if WINDOWS_APP
SettingsPane.GetForCurrentView().CommandsRequested += (s, e) =>
{
e.Request.ApplicationCommands.Add(new SettingsCommand(
"Dropbox Settings",
"Dropbox Settings",
_ => { new DropboxSettings().Show(); }));
};
#endif
base.OnWindowCreated(args);
}
/// <summary>
/// Sets the new dropbox client.
/// </summary>
private void SetNewDropboxClient()
{
this.DropboxClient = new DropboxClient(this.AccessToken, new DropboxClientConfig("WindowsUniversalAppDemo"));
}
#if WINDOWS_PHONE_APP
/// <summary>
/// Restores the content transitions after the app has launched.
/// </summary>
/// <param name="sender">The object where the handler is attached.</param>
/// <param name="e">Details about the navigation event.</param>
private void RootFrame_FirstNavigated(object sender, NavigationEventArgs e)
{
var rootFrame = sender as Frame;
rootFrame.ContentTransitions = this.transitions ?? new TransitionCollection() { new NavigationThemeTransition() };
rootFrame.Navigated -= this.RootFrame_FirstNavigated;
}
#endif
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
// TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}
| |
/*
Copyright (C) 2013-2015 MetaMorph Software, Inc
Permission is hereby granted, free of charge, to any person obtaining a
copy of this data, including any software or models in source or binary
form, as well as any drawings, specifications, and documentation
(collectively "the Data"), to deal in the Data without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Data, and to
permit persons to whom the Data is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Data.
THE DATA IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS, SPONSORS, DEVELOPERS, CONTRIBUTORS, OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Tonka = ISIS.GME.Dsml.CyPhyML.Interfaces;
using TonkaClasses = ISIS.GME.Dsml.CyPhyML.Classes;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using META;
namespace CyPhy2Schematic.Schematic
{
public class CyPhyBuildVisitor : Visitor
{
//
// This Class contains visitor methods to build the lightweight Component Object network from CyPhy Models
//
public static Dictionary<string, Component> ComponentInstanceGUIDs { get; set; }
public static Dictionary<string, Component> Components { get; set; }
public static Dictionary<string, Port> Ports { get; set; }
public string ProjectDirectory { get; set; }
public CodeGenerator.Mode mode { get; private set; }
public CyPhyBuildVisitor(string projectDirectory, CodeGenerator.Mode mode) // this is a singleton object and the constructor will be called once
{
Components = new Dictionary<string, Component>();
ComponentInstanceGUIDs = new Dictionary<string, Component>();
Ports = new Dictionary<string, Port>();
Components.Clear();
ComponentInstanceGUIDs.Clear();
Ports.Clear();
this.ProjectDirectory = projectDirectory;
this.mode = mode;
}
~CyPhyBuildVisitor()
{
}
public override void visit(TestBench obj)
{
Logger.WriteDebug("CyPhyBuildVisitor::visit({0})", obj.Impl.Path);
var testBench = obj.Impl;
var ca = testBench.Children.ComponentAssemblyCollection.FirstOrDefault();
if (ca == null)
{
Logger.WriteFailed("No valid component assembly in testbench {0}", obj.Name);
return;
}
var componentAssembly_obj = new ComponentAssembly(ca);
obj.ComponentAssemblies.Add(componentAssembly_obj);
var tcs = testBench.Children.TestComponentCollection;
foreach (var tc in tcs)
{
var component_obj = new Component(tc);
obj.TestComponents.Add(component_obj);
CyPhyBuildVisitor.Components.Add(tc.ID, component_obj); // Add to global component list, are these instance ID-s or component type ID-s?
}
foreach (var param in testBench.Children.ParameterCollection)
{
var param_obj = new Parameter()
{
Name = param.Name,
Value = param.Attributes.Value
};
obj.Parameters.Add(param_obj);
}
// solver parameters - currently using Dymola Solver object
var solver = testBench.Children.SolverSettingsCollection.FirstOrDefault();
if (solver != null)
obj.SolverParameters.Add("SpiceAnalysis", solver.Attributes.ToolSpecificAnnotations);
}
public override void visit(ComponentAssembly obj)
{
Logger.WriteDebug("CyPhyBuildVisitor::visit({0})", obj.Impl.Path);
var ca = obj.Impl;
// ------- ComponentAssemblies -------
foreach (var innerComponentAssembly in ca.Children.ComponentAssemblyCollection)
{
var innerComponentAssembly_obj = new ComponentAssembly(innerComponentAssembly)
{
Parent = obj,
};
obj.ComponentAssemblyInstances.Add(innerComponentAssembly_obj);
}
// ------- Components -------
foreach (var component in ca.Children.ComponentCollection)
{
var component_obj = new Component(component)
{
Parent = obj,
};
obj.ComponentInstances.Add(component_obj);
CyPhyBuildVisitor.Components.Add(component.ID, component_obj); // Add to global component list, component type ID-s?
CyPhyBuildVisitor.ComponentInstanceGUIDs.Add(component.Attributes.InstanceGUID, component_obj); // component instance guid-s?
}
}
private bool SpiceClassRequiresModel(String spiceClass)
{
if ((spiceClass.Length == 1 && spiceClass.ToUpper() != "X") || (spiceClass.Length == 0))
{
// It's a primitive
return false;
}
else
{
// It's a sub-circuit or a refinement on a primitive.
return true;
}
}
public override void visit(Component obj)
{
Logger.WriteDebug("CyPhyBuildVisitor::visit({0})", obj.Impl.Path);
var component = obj.Impl;
var ca = obj.Parent;
var compBase = obj.Impl.ArcheType;
bool isTestComponent = component is Tonka.TestComponent;
Tonka.SchematicModel schematicModel = null;
//////////// EDA /////////////
if (mode == CodeGenerator.Mode.EDA)
{
var edaModel = component.Children.EDAModelCollection.FirstOrDefault();
if (edaModel == null)
{
Logger.WriteInfo("Skipping Component <a href=\"mga:{0}\">{1}</a> (no EDA model)",
obj.Impl.ID, obj.Impl.Name);
return;
}
schematicModel = edaModel;
// try and load the resource
bool hasResource = false;
String schAbsPath = "";
try
{
hasResource = edaModel.TryGetResourcePath(out schAbsPath, ComponentLibraryManager.PathConvention.REL_TO_PROJ_ROOT);
schAbsPath = Path.Combine(this.ProjectDirectory, schAbsPath);
}
catch (NotSupportedException ex)
{
// test component will not have / should not have resource
hasResource = false;
}
if (!hasResource && !isTestComponent)
{
Logger.WriteError("Couldn't determine path of schematic file for component <a href=\"mga:{0}\">{1}</a>. It may not be linked to a Resource object.", obj.Impl.ID, obj.Impl.Name);
return;
}
bool failedToLoadSchematicLib = false;
try
{
obj.SchematicLib = Eagle.eagle.LoadFromFile(schAbsPath);
}
catch (Exception e)
{
failedToLoadSchematicLib = true;
if (!isTestComponent) // test components don't need to have schematic
{
Logger.WriteError("Error Loading Schematic Library of <a href=\"mga:{0}\">{1}</a>: {2}",
obj.Impl.ID, obj.Impl.Name, e.Message);
}
}
if (failedToLoadSchematicLib)
obj.SchematicLib = new Eagle.eagle();
foreach (var param in edaModel.Children.EDAModelParameterCollection)
{
var val = param.Attributes.Value;
var valSrc = param.SrcConnections
.EDAModelParameterMapCollection
.Select(p => p.SrcEnd)
.FirstOrDefault();
if (valSrc != null)
{
var valProp = valSrc as Tonka.Property;
if (valProp != null)
val = valProp.Attributes.Value;
var valParam = valSrc as Tonka.Parameter;
if (valParam != null)
val = valParam.Attributes.Value;
}
var param_obj = new Parameter()
{
Name = param.Name,
Value = val
};
obj.Parameters.Add(param_obj);
}
}
///////////// SPICE //////////////
else if (mode == CodeGenerator.Mode.SPICE || mode == CodeGenerator.Mode.SPICE_SI)
{
var spiceModel = component.Children.SPICEModelCollection.FirstOrDefault();
if (spiceModel == null)
{
Logger.WriteInfo("Skipping Component <a href=\"mga:{0}\">{1}</a> (no SPICE model)",
obj.Impl.ID, obj.Impl.Name);
return;
}
schematicModel = spiceModel;
String spiceClass = spiceModel.Attributes.Class;
if (String.IsNullOrWhiteSpace(spiceClass))
{
Logger.WriteWarning("Component <a href=\"mga:{0}\">{1}</a> has a SPICE model, but its class is not specified",
obj.Impl.ID,
obj.Impl.Name);
}
// If this SPICE class requires a model file to be provided, try to find it and load it.
if (SpiceClassRequiresModel(spiceClass))
{
try
{
String spiceAbsPath;
spiceModel.TryGetResourcePath(out spiceAbsPath, ComponentLibraryManager.PathConvention.REL_TO_PROJ_ROOT);
spiceAbsPath = Path.Combine(this.ProjectDirectory, spiceAbsPath);
using (var spiceReader = new StreamReader(spiceAbsPath))
{
obj.SpiceLib = spiceReader.ReadToEnd();
}
}
catch (Exception e)
{
obj.SpiceLib = "";
if (!isTestComponent)
Logger.WriteError("Error Loading Spice Library of <a href=\"mga:{0}\">{1}</a>: {2}",
obj.Impl.ID, obj.Impl.Name, e.Message);
}
}
foreach (var param in spiceModel.Children.SPICEModelParameterCollection)
{
var val = param.Attributes.Value;
var valSrc = param.SrcConnections
.SPICEModelParameterMapCollection
.Select(p => p.SrcEnd)
.FirstOrDefault();
if (valSrc != null)
{
var valProp = valSrc as Tonka.Property;
if (valProp != null)
val = valProp.Attributes.Value;
var valParam = valSrc as Tonka.Parameter;
if (valParam != null)
val = valParam.Attributes.Value;
}
var param_obj = new Parameter()
{
Name = param.Name,
Value = val
};
obj.Parameters.Add(param_obj);
}
}
else
{
throw new NotSupportedException(String.Format("Mode {0} is not supported by visit(Component)", mode.ToString()));
}
// Both EDA and SPICE models have these ports in common.
if (schematicModel != null)
{
foreach (var port in schematicModel.Children.SchematicModelPortCollection)
{
var port_obj = new Port(port)
{
Parent = obj,
};
obj.Ports.Add(port_obj);
CyPhyBuildVisitor.Ports.Add(port.ID, port_obj);
Logger.WriteDebug("Mapping Port <a href=\"mga:{0}\">{1}</a>", port.ID, port.Name);
}
}
}
}
public class CyPhyLayoutVisitor : Visitor
{
public const float gridSize = 2.54f; // grid size is 0.1inch or 2.54mm
// These constants are multiples of 2.54 for the inch to mm conversion
// Eagle prefers 0.1 inch grid - though in theory anything can be set, but symbol pins have 0.1 inch spacing
const float symSpace = 7.62f;
const float gme2Eagle = 20.0f;
const float defSize = 10.16f;
// This class computes the layout of the flat schematic diagram starting from GME hierarchical diagrams
public override void upVisit(ComponentAssembly obj)
{
SortedList<Tuple<float, float>, object> nodes = new SortedList<Tuple<float, float>, object>();
// we have already visited all child nodes, and know their extents (canvasWidth and canvasHeight)
// now sort all child objects by their GME object location, and use the GME location as their initial position
foreach (var ca in obj.ComponentAssemblyInstances)
{
var allAspect = ca.Impl.Aspects.Where(a => a.Name.Equals("All")).FirstOrDefault();
float x = (allAspect != null) ? ((float)allAspect.X) / gme2Eagle : defSize;
float y = (allAspect != null) ? ((float)allAspect.Y) / gme2Eagle : defSize;
ca.CanvasX = (float)Math.Round(x / gridSize) * gridSize;
ca.CanvasY = (float)Math.Round(y / gridSize) * gridSize;
Tuple<float, float> location = new Tuple<float, float>(ca.CanvasX, ca.CanvasY);
nodes.Add(location, ca);
}
foreach (var ca in obj.ComponentInstances)
{
var allAspect = ca.Impl.Aspects.Where(a => a.Name.Equals("All")).FirstOrDefault();
float x = allAspect != null ? ((float)allAspect.X) / gme2Eagle : defSize;
float y = allAspect != null ? ((float)allAspect.Y) / gme2Eagle : defSize;
ca.CanvasX = (float)Math.Round(x / gridSize) * gridSize;
ca.CanvasY = (float)Math.Round(y / gridSize) * gridSize;
Tuple<float, float> location = new Tuple<float, float>(ca.CanvasX, ca.CanvasY);
nodes.Add(location, ca);
}
object[] nodeArr = nodes.Values.ToArray();
float maxWidth = 0;
float maxHeight = 0;
for (int i = 0; i < nodes.Count; i++)
{
var node = nodeArr[i];
var nx = node is Component ? (node as Component).CanvasX : (node as ComponentAssembly).CanvasX;
var ny = node is Component ? (node as Component).CanvasY : (node as ComponentAssembly).CanvasY;
for (int j = 0; j < i; j++)
{
var nodePre = nodeArr[j];
float npxw, npyh;
if (nodePre is Component)
{
var c = nodePre as Component;
npxw = c.CanvasX + c.CanvasWidth;
npyh = c.CanvasY + c.CanvasHeight;
}
else
{
var c = nodePre as ComponentAssembly;
npxw = c.CanvasX + c.CanvasWidth;
npyh = c.CanvasY + c.CanvasHeight;
}
if ( (nx - symSpace) <= npxw && (ny - symSpace) <= npyh) // overlap
{
if (j % 2 == 0)
nx = npxw + symSpace;
else
ny = npyh + symSpace;
}
}
float nxw, nyh;
if (node is Component)
{
var c = node as Component;
c.CanvasX = nx;
c.CanvasY = ny;
nxw = nx + c.CanvasWidth;
nyh = ny + c.CanvasHeight;
Logger.WriteDebug("Placing Node {0} in Assembly {1}: @ {2},{3}",
c.Name, obj.Name, nx, ny);
}
else
{
var c = node as ComponentAssembly;
c.CanvasX = nx;
c.CanvasY = ny;
nxw = nx + c.CanvasWidth;
nyh = ny + c.CanvasHeight;
}
maxWidth = Math.Max(maxWidth, nxw);
maxHeight = Math.Max(maxHeight, nyh);
}
// set the size of this container
obj.CanvasWidth = (float)Math.Round(maxWidth/(2.0f*gridSize))*2.0f*gridSize;
obj.CanvasHeight = (float)Math.Round(maxHeight/(2.0f*gridSize))*2.0f*gridSize;
}
public override void visit(Component obj)
{
Logger.WriteDebug("CyPhyLayoutVisitor::visit({0})", obj.Impl.Path);
// compute device dimension
// need gate objects + their locations within device
// need an overall device schematic symbol dimension
var compLib = (obj.SchematicLib != null) ? obj.SchematicLib.drawing.Item as Eagle.library : null;
if (compLib != null)
{
var gates = compLib.devicesets.deviceset.SelectMany(p => p.gates.gate);
float minx = float.MaxValue;
float maxx = float.MinValue;
float miny = float.MaxValue;
float maxy = float.MinValue;
foreach (var gate in gates)
{
var symbol = compLib.symbols.symbol.Where(q => q.name.Equals(gate.symbol)).FirstOrDefault();
float gx = float.Parse(gate.x);
float gy = float.Parse(gate.y);
var pins = symbol.Items.Where(p => p is Eagle.pin).Select(p => p as Eagle.pin);
foreach (var pin in pins)
{
float x = gx + float.Parse(pin.x);
float y = gy + float.Parse(pin.y);
minx = Math.Min(x, minx);
miny = Math.Min(y, miny);
maxx = Math.Max(x, maxx);
maxy = Math.Max(y, maxy);
}
var wires = symbol.Items.Where(p => p is Eagle.wire).Select(p => p as Eagle.wire);
foreach (var w in wires)
{
float x1 = float.Parse(w.x1);
float x2 = float.Parse(w.x2);
float y1 = float.Parse(w.y1);
float y2 = float.Parse(w.y2);
minx = Math.Min(minx, Math.Min(x1, x2));
miny = Math.Min(miny, Math.Min(y1, y2));
maxx = Math.Max(maxx, Math.Min(x1, x2));
maxy = Math.Max(maxy, Math.Min(y1, y2));
}
var rectangles = symbol.Items.Where(p => p is Eagle.rectangle).Select(p => p as Eagle.rectangle);
foreach (var w in rectangles)
{
float x1 = float.Parse(w.x1);
float x2 = float.Parse(w.x2);
float y1 = float.Parse(w.y1);
float y2 = float.Parse(w.y2);
minx = Math.Min(minx, Math.Min(x1, x2));
miny = Math.Min(miny, Math.Min(y1, y2));
maxx = Math.Max(maxx, Math.Min(x1, x2));
maxy = Math.Max(maxy, Math.Min(y1, y2));
}
var circles = symbol.Items.Where(p => p is Eagle.circle).Select(p => p as Eagle.circle);
foreach (var w in circles)
{
float x1 = float.Parse(w.x) - float.Parse(w.radius);
float x2 = float.Parse(w.x) + float.Parse(w.radius);
float y1 = float.Parse(w.y) - float.Parse(w.radius);
float y2 = float.Parse(w.y) + float.Parse(w.radius);
minx = Math.Min(minx, Math.Min(x1, x2));
miny = Math.Min(miny, Math.Min(y1, y2));
maxx = Math.Max(maxx, Math.Min(x1, x2));
maxy = Math.Max(maxy, Math.Min(y1, y2));
}
}
obj.CanvasWidth = (float) Math.Round((maxx - minx)/(2.0*gridSize)) * 2.0f * gridSize;
obj.CanvasHeight = (float) Math.Round((maxy - miny)/(2.0*gridSize)) * 2.0f * gridSize;
}
else
{
obj.CanvasWidth = defSize;
obj.CanvasHeight = defSize;
}
}
}
public class CyPhyLayout2Visitor : Visitor
{
public override void visit(ComponentAssembly obj)
{
if (obj.Parent != null)
{
obj.CanvasX += obj.Parent.CanvasX;
obj.CanvasY += obj.Parent.CanvasY;
}
}
public override void visit(Component obj)
{
if (obj.Parent != null) // test components may have null parent
{
obj.CanvasX += obj.Parent.CanvasX;
obj.CanvasY += obj.Parent.CanvasY;
}
// round off center to align with schematic grid based on gridSize parameter
double cx = (obj.CanvasX + (obj.CanvasWidth / 2.0f));
double cy = (obj.CanvasY + (obj.CanvasHeight / 2.0f));
// snap to grid
obj.CenterX = (float)Math.Round(cx / CyPhyLayoutVisitor.gridSize) * CyPhyLayoutVisitor.gridSize;
obj.CenterY = (float)Math.Round(cy / CyPhyLayoutVisitor.gridSize) * CyPhyLayoutVisitor.gridSize;
Logger.WriteDebug("Component {0}: Center {1},{2}, Size {3},{4}",
obj.Name,
obj.CenterX,
obj.CenterY, obj.CanvasWidth, obj.CanvasHeight);
}
public override void visit(Port obj)
{
float portX = float.Parse(obj.Impl.Attributes.EDASymbolLocationX);
float portY = float.Parse(obj.Impl.Attributes.EDASymbolLocationY);
var compLib = (obj.Parent.SchematicLib != null) ? obj.Parent.SchematicLib.drawing.Item as Eagle.library : null;
if (compLib != null)
{
var gate = compLib.devicesets.deviceset.
SelectMany(p => p.gates.gate).
Where(g => g.name.Equals(obj.Impl.Attributes.EDAGate)).
FirstOrDefault();
float gateX = gate != null ? float.Parse(gate.x) : 0.0f;
float gateY = gate != null ? float.Parse(gate.y) : 0.0f;
portX += gateX;
portY += gateY;
}
obj.CanvasX = obj.Parent.CenterX + portX;
obj.CanvasY = obj.Parent.CenterY + portY;
Logger.WriteDebug("Port {0}: Location {1},{2} Parent Center: {3},{4}",
obj.Name,
obj.CanvasX,
obj.CanvasY,
obj.Parent.CenterX,
obj.Parent.CenterY);
}
}
public class CyPhyConnectVisitor : Visitor
{
public Dictionary<string, Port> VisitedPorts { get; set; }
public CodeGenerator.Mode mode { get; private set; }
private Type SchematicModelType;
public CyPhyConnectVisitor(CodeGenerator.Mode mode)
{
VisitedPorts = new Dictionary<string, Port>();
VisitedPorts.Clear();
this.mode = mode;
switch (mode)
{
case CodeGenerator.Mode.EDA:
SchematicModelType = typeof(Tonka.EDAModel);
break;
case CodeGenerator.Mode.SPICE:
case CodeGenerator.Mode.SPICE_SI:
SchematicModelType = typeof(Tonka.SPICEModel);
break;
default:
throw new NotSupportedException(String.Format("Mode {0} is not supported.", mode.ToString()));
}
}
private bool portHasCorrectParentType(ISIS.GME.Common.Interfaces.FCO port)
{
ISIS.GME.Common.Interfaces.Container parent = port.ParentContainer;
Type parentType = parent.GetType();
return this.SchematicModelType.IsAssignableFrom(parentType);
}
public override void visit(Port obj)
{
Logger.WriteDebug("CyPhyConnectVisitor::visit({0})", obj.Impl.Path);
if (VisitedPorts.ContainsKey(obj.Impl.ID)) // this port was already visited in a connection traversal - no need to explore its connections again
return;
VisitedPorts.Add(obj.Impl.ID, obj);
Logger.WriteDebug("Connect Visit: port {0}", obj.Impl.Path);
var elecPort = obj.Impl as Tonka.SchematicModelPort;
if (elecPort != null)
{
// from schematic port navigate out to component port (or connector) in either connection direction
var compPorts = elecPort.DstConnections.PortCompositionCollection.Select(p => p.DstEnd).
Union(elecPort.SrcConnections.PortCompositionCollection.Select(p => p.SrcEnd));
foreach (var compPort in compPorts)
{
Dictionary<string, object> visited = new Dictionary<string, object>();
visited.Clear();
if (compPort.ParentContainer is Tonka.Connector) // traverse connector chain, carry port name in srcConnector
{
Traverse(compPort.Name, obj, obj.Parent.Impl, compPort.ParentContainer as Tonka.Connector, visited);
}
else if (compPort.ParentContainer is Tonka.DesignElement)
{
Traverse(obj, obj.Parent.Impl, compPort as Tonka.Port, visited); // traverse port chain
}
else if (portHasCorrectParentType(compPort)
&& CyPhyBuildVisitor.Ports.ContainsKey(compPort.ID))
{
ConnectPorts(obj, CyPhyBuildVisitor.Ports[compPort.ID]);
}
}
}
}
private void Traverse(string srcConnectorName, Port srcPort_obj, Tonka.DesignElement parent, Tonka.Connector connector, Dictionary<string, object> visited)
{
Logger.WriteDebug("Traverse Connector: {0}, Mapped-Pin: {1}",
connector.Path,
srcConnectorName);
if (visited.ContainsKey(connector.ID))
{
Logger.WriteWarning("Traverse Connector Revisit: {0}, Mapped-Pin: {1}", connector.Path, srcConnectorName);
return;
}
visited.Add(connector.ID, connector);
// continue traversal as connector
var remotes = connector.DstConnections.ConnectorCompositionCollection.Select(p => p.DstEnd).Union(
connector.SrcConnections.ConnectorCompositionCollection.Select(p => p.SrcEnd));
foreach (var remote in remotes)
{
if (visited.ContainsKey(remote.ID)) // already visited
continue;
if (remote.ParentContainer is Tonka.DesignElement)
Traverse(srcConnectorName, srcPort_obj, remote.ParentContainer as Tonka.DesignElement, remote as Tonka.Connector, visited);
}
// continue traversal through named port
var mappedPorts = connector.Children.SchematicModelPortCollection.Where(p => p.Name.Equals(srcConnectorName));
foreach (var mappedPort in mappedPorts)
{
var remotePorts = mappedPort.DstConnections.PortCompositionCollection.Select(p => p.DstEnd).Union(
mappedPort.SrcConnections.PortCompositionCollection.Select(p => p.SrcEnd));
foreach (var remotePort in remotePorts)
{
if (visited.ContainsKey(remotePort.ID)) // already visited
{
continue;
}
if (remotePort.ParentContainer is Tonka.Connector &&
!visited.ContainsKey(remotePort.ParentContainer.ID))
// traverse connector chain, carry port name in srcConnector
{
Traverse(remotePort.Name, srcPort_obj,
remotePort.ParentContainer.ParentContainer as Tonka.DesignElement,
remotePort.ParentContainer as Tonka.Connector, visited);
}
else if (remotePort.ParentContainer is Tonka.DesignElement)
{
Traverse(srcPort_obj, remotePort.ParentContainer as Tonka.DesignElement, remotePort as Tonka.Port, visited);
}
else if (portHasCorrectParentType(remotePort)
&& CyPhyBuildVisitor.Ports.ContainsKey(remotePort.ID))
{
ConnectPorts(srcPort_obj, CyPhyBuildVisitor.Ports[remotePort.ID]);
}
}
}
}
private void Traverse(Port srcPort_obj, Tonka.DesignElement parent, Tonka.Port port, Dictionary<string, object> visited)
{
Logger.WriteDebug("Traverse Port: port {0}",
port.Path);
if (visited.ContainsKey(port.ID))
{
Logger.WriteWarning("Traverse Port Revisit: {0}", port.Path);
return;
}
visited.Add(port.ID, port);
// continue traversal
var remotes = port.DstConnections.PortCompositionCollection.Select(p => p.DstEnd).Union(
port.SrcConnections.PortCompositionCollection.Select(p => p.SrcEnd));
foreach (var remote in remotes)
{
if (visited.ContainsKey(remote.ID))
continue; // already visited continue
if (remote.ParentContainer is Tonka.DesignElement) // remote is contained in a Component or ComponentAssembly
{
Traverse(srcPort_obj,
remote.ParentContainer as Tonka.DesignElement,
remote as Tonka.Port,
visited);
}
else if (remote.ParentContainer is Tonka.Connector) // remote is contained in a Connector
{
Traverse(remote.Name,
srcPort_obj,
remote.ParentContainer.ParentContainer as Tonka.DesignElement,
remote.ParentContainer as Tonka.Connector,
visited);
}
else if (portHasCorrectParentType(remote) // remote is contained in a SchematicModel
&& CyPhyBuildVisitor.Ports.ContainsKey(remote.ID))
{
ConnectPorts(srcPort_obj, CyPhyBuildVisitor.Ports[remote.ID]);
}
}
}
private void ConnectPorts(Port srcPort_obj, Port dstPort_obj)
{
if (srcPort_obj.Impl.Equals(dstPort_obj.Impl))
return;
Connection conn_obj = new Connection(srcPort_obj, dstPort_obj);
srcPort_obj.DstConnections.Add(conn_obj);
dstPort_obj.SrcConnections.Add(conn_obj);
Logger.WriteDebug("Connecting Port {0} to {1}", srcPort_obj.Impl.Name,
dstPort_obj.Impl.Name);
// mark the dstPort visited
if (!VisitedPorts.ContainsKey(dstPort_obj.Impl.ID))
VisitedPorts.Add(dstPort_obj.Impl.ID, dstPort_obj);
else
Logger.WriteDebug("Port {0} already in visited ports, don't add",
dstPort_obj.Impl.Path);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography.Pkcs;
using Htc.Vita.Core.Interop;
using Htc.Vita.Core.Log;
namespace Htc.Vita.Core.Diagnostics
{
public partial class FilePropertiesInfo
{
internal static class Authenticode
{
private const string OidRsaCounterSignature = "1.2.840.113549.1.9.6";
private const string OidRsaSigningTime = "1.2.840.113549.1.9.5";
internal static List<DateTime> GetTimestampList(FileInfo fileInfo)
{
var result = new List<DateTime>();
if (fileInfo == null || !fileInfo.Exists)
{
return result;
}
Windows.SafeCertContextHandle certContext = null;
Windows.SafeCertStoreHandle certStore = null;
Windows.SafeCryptMsgHandle cryptMsg = null;
byte[] encodedMessage = null;
try
{
Windows.CertEncoding certEncoding;
Windows.CertQueryContent certQueryContent;
Windows.CertQueryFormat certQueryFormat;
var success = Windows.CryptQueryObject(
Windows.CertQueryObject.File,
Marshal.StringToHGlobalUni(fileInfo.FullName),
Windows.CertQueryContentFlags.All,
Windows.CertQueryFormatFlag.All,
0,
out certEncoding,
out certQueryContent,
out certQueryFormat,
out certStore,
out cryptMsg,
out certContext
);
if (!success)
{
Logger.GetInstance(typeof(Authenticode)).Error($"Can not query crypt object for {fileInfo.FullName}, error code: {Marshal.GetLastWin32Error()}");
return result;
}
var cbData = 0;
success = Windows.CryptMsgGetParam(
cryptMsg,
Windows.CertMessageParameterType.EncodedMessage,
0,
null,
ref cbData
);
if (!success)
{
Logger.GetInstance(typeof(Authenticode)).Error($"Can not get crypt message parameter size, error code: {Marshal.GetLastWin32Error()}");
return result;
}
encodedMessage = new byte[cbData];
success = Windows.CryptMsgGetParam(
cryptMsg,
Windows.CertMessageParameterType.EncodedMessage,
0,
encodedMessage,
ref cbData
);
if (!success)
{
Logger.GetInstance(typeof(Authenticode)).Error($"Can not get crypt message parameter, error code: {Marshal.GetLastWin32Error()}");
return result;
}
}
catch (Exception e)
{
Logger.GetInstance(typeof(Authenticode)).Error($"Can not extract encoded message. error: {e.Message}");
}
finally
{
certContext?.Dispose();
certStore?.Dispose();
cryptMsg?.Dispose();
}
if (encodedMessage == null)
{
Logger.GetInstance(typeof(Authenticode)).Error("Can not find available encoded message.");
return result;
}
try
{
var signedCms = new SignedCms();
signedCms.Decode(encodedMessage);
foreach (var signerInfo in signedCms.SignerInfos)
{
if (signerInfo == null)
{
continue;
}
foreach (var unsignedAttribute in signerInfo.UnsignedAttributes)
{
if (unsignedAttribute == null)
{
continue;
}
if (!OidRsaCounterSignature.Equals(unsignedAttribute.Oid.Value))
{
continue;
}
foreach (var counterSignerInfo in signerInfo.CounterSignerInfos)
{
if (counterSignerInfo == null)
{
continue;
}
foreach (var signedAttribute in counterSignerInfo.SignedAttributes)
{
if (!OidRsaSigningTime.Equals(signedAttribute.Oid.Value))
{
continue;
}
foreach (var value in signedAttribute.Values)
{
var pkcs9SigningTime = value as Pkcs9SigningTime;
if (pkcs9SigningTime == null)
{
continue;
}
result.Add(pkcs9SigningTime.SigningTime);
}
}
}
}
}
}
catch (Exception e)
{
Logger.GetInstance(typeof(Authenticode)).Error($"Can not parse timestamp: {e.Message}");
}
return result;
}
internal static bool IsVerified(FileInfo fileInfo)
{
if (fileInfo == null || !fileInfo.Exists)
{
return false;
}
var winTrustFileInfo = new Windows.WinTrustFileInfo
{
cbStruct = (uint)Marshal.SizeOf(typeof(Windows.WinTrustFileInfo)),
pcwszFilePath = fileInfo.FullName,
hFile = IntPtr.Zero,
pgKnownSubject = IntPtr.Zero
};
var winTrustFileInfoPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Windows.WinTrustFileInfo)));
Marshal.StructureToPtr(winTrustFileInfo, winTrustFileInfoPtr, false);
var infoUnionChoice = new Windows.WinTrustDataUnionChoice
{
pFile = winTrustFileInfoPtr
};
var winTrustData = new Windows.WinTrustData
{
cbStruct = (uint)Marshal.SizeOf(typeof(Windows.WinTrustData)),
pPolicyCallbackData = IntPtr.Zero,
pSIPCallbackData = IntPtr.Zero,
dwUIChoice = Windows.WinTrustDataUI.None,
fdwRevocationChecks = Windows.WinTrustDataRevoke.None,
dwUnionChoice = Windows.WinTrustDataChoice.File,
infoUnion = infoUnionChoice,
dwStateAction = Windows.WinTrustDataStateAction.Ignore,
hWVTStateData = IntPtr.Zero,
pwszURLReference = IntPtr.Zero,
dwProvFlags = Windows.WinTrustDataProviderFlags.SaferFlag,
dwUIContext = Windows.WinTrustDataUIContext.Execute,
pSignatureSettings = IntPtr.Zero
};
var winTrustDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Windows.WinTrustData)));
Marshal.StructureToPtr(winTrustData, winTrustDataPtr, false);
var actionId = Guid.Parse(Windows.WinTrustActionGenericVerifyV2.ToString("D"));
var result = Windows.WinVerifyTrust(
IntPtr.Zero,
ref actionId,
winTrustDataPtr
);
var success = result == 0;
if (!success)
{
if (result == (uint)Windows.TrustError.ProviderUnknown)
{
Logger.GetInstance(typeof(FilePropertiesInfo)).Error("WinVerifyTrust result: TRUST_E_PROVIDER_UNKNOWN");
}
else if (result == (uint)Windows.TrustError.ActionUnknown)
{
Logger.GetInstance(typeof(FilePropertiesInfo)).Error("WinVerifyTrust result: TRUST_E_ACTION_UNKNOWN");
}
else if (result == (uint)Windows.TrustError.SubjectFormUnknown)
{
Logger.GetInstance(typeof(FilePropertiesInfo)).Error("WinVerifyTrust result: TRUST_E_SUBJECT_FORM_UNKNOWN");
}
else if (result == (uint)Windows.TrustError.SubjectNotTrusted)
{
Logger.GetInstance(typeof(FilePropertiesInfo)).Warn($"Can not trust {fileInfo.FullName}");
}
else
{
Logger.GetInstance(typeof(FilePropertiesInfo)).Error($"WinVerifyTrust result: 0x{result:X}");
}
}
Marshal.DestroyStructure(winTrustDataPtr, typeof(Windows.WinTrustData));
Marshal.FreeHGlobal(winTrustDataPtr);
Marshal.DestroyStructure(winTrustFileInfoPtr, typeof(Windows.WinTrustFileInfo));
Marshal.FreeHGlobal(winTrustFileInfoPtr);
return success;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace HoDashboard.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
#region Apache Notice
/*****************************************************************************
* $Revision: 383115 $
* $LastChangedDate: 2006-03-04 15:21:51 +0100 (sam., 04 mars 2006) $
* $LastChangedBy: gbayon $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2004 - Gilles Bayon
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
********************************************************************************/
#endregion
using System;
using IBatisNet.Common.Logging;
namespace IBatisNet.Common.Logging.Impl
{
/// <remarks>
/// Log4net is capable of outputting extended debug information about where the current
/// message was generated: class name, method name, file, line, etc. Log4net assumes that the location
/// information should be gathered relative to where Debug() was called. In IBatisNet,
/// Debug() is called in IBatisNet.Common.Logging.Impl.Log4NetLogger. This means that
/// the location information will indicate that IBatisNet.Common.Logging.Impl.Log4NetLogger always made
/// the call to Debug(). We need to know where IBatisNet.Common.Logging.ILog.Debug()
/// was called. To do this we need to use the log4net.ILog.Logger.Log method and pass in a Type telling
/// log4net where in the stack to begin looking for location information.
/// </remarks>
public class Log4NetLogger : ILog
{
#region Fields
private log4net.Core.ILogger _logger = null;
private readonly static Type declaringType = typeof(Log4NetLogger);
#endregion
/// <summary>
/// Constructor
/// </summary>
/// <param name="log"></param>
internal Log4NetLogger(log4net.ILog log)
{
_logger = log.Logger;
}
#region ILog Members
/// <summary>
///
/// </summary>
public bool IsInfoEnabled
{
get { return _logger.IsEnabledFor(log4net.Core.Level.Info); }
}
/// <summary>
///
/// </summary>
public bool IsWarnEnabled
{
get { return _logger.IsEnabledFor(log4net.Core.Level.Warn); }
}
/// <summary>
///
/// </summary>
public bool IsErrorEnabled
{
get { return _logger.IsEnabledFor(log4net.Core.Level.Error); }
}
/// <summary>
///
/// </summary>
public bool IsFatalEnabled
{
get { return _logger.IsEnabledFor(log4net.Core.Level.Fatal); }
}
/// <summary>
///
/// </summary>
public bool IsDebugEnabled
{
get { return _logger.IsEnabledFor(log4net.Core.Level.Debug); }
}
/// <summary>
///
/// </summary>
public bool IsTraceEnabled
{
get { return _logger.IsEnabledFor(log4net.Core.Level.Trace); }
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
/// <param name="e"></param>
public void Info(object message, Exception e)
{
_logger.Log(declaringType, log4net.Core.Level.Info, message, e);
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
public void Info(object message)
{
_logger.Log(declaringType, log4net.Core.Level.Info, message, null);
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
/// <param name="e"></param>
public void Debug(object message, Exception e)
{
_logger.Log(declaringType, log4net.Core.Level.Debug, message, e);
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
public void Debug(object message)
{
_logger.Log(declaringType, log4net.Core.Level.Debug, message, null);
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
/// <param name="e"></param>
public void Warn(object message, Exception e)
{
_logger.Log(declaringType, log4net.Core.Level.Warn, message, e);
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
public void Warn(object message)
{
_logger.Log(declaringType, log4net.Core.Level.Warn, message, null);
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
/// <param name="e"></param>
public void Trace(object message, Exception e)
{
_logger.Log(declaringType, log4net.Core.Level.Trace, message, e);
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
public void Trace(object message)
{
_logger.Log(declaringType, log4net.Core.Level.Trace, message, null);
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
/// <param name="e"></param>
public void Fatal(object message, Exception e)
{
_logger.Log(declaringType, log4net.Core.Level.Fatal, message, e);
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
public void Fatal(object message)
{
_logger.Log(declaringType, log4net.Core.Level.Fatal, message, null);
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
/// <param name="e"></param>
public void Error(object message, Exception e)
{
_logger.Log(declaringType, log4net.Core.Level.Error, message, e);
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
public void Error(object message)
{
_logger.Log(declaringType, log4net.Core.Level.Error, message, null);
}
#endregion
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Text;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Autodesk.Revit;
namespace Revit.SDK.Samples.ImportExport.CS
{
/// <summary>
/// Data class which stores lower priority information for exporting dwg format
/// </summary>
public class ExportDWGOptionsData
{
#region Class Memeber Variables
/// <summary>
/// String list of Layers and properties used in UI
/// </summary>
List<String> m_layersAndProperties;
/// <summary>
/// List of Autodesk.Revit.DB.PropOverrideMode
/// </summary>
List<Autodesk.Revit.DB.PropOverrideMode> m_enumLayersAndProperties;
/// <summary>
/// String list of Layer Settings used in UI
/// </summary>
List<String> m_layerMapping;
/// <summary>
/// String list of layer settings values defined in Revit
/// </summary>
List<String> m_enumLayerMapping;
/// <summary>
/// Layer setting option to export
/// </summary>
String m_exportLayerMapping;
/// <summary>
/// String list of Linetype scaling used in UI
/// </summary>
List<String> m_lineScaling;
/// <summary>
/// PropOverrideMode Option to export
/// </summary>
Autodesk.Revit.DB.PropOverrideMode m_exportLayersAndProperties;
/// <summary>
/// List of Autodesk.Revit.DB.LineScaling defined in Revit
/// </summary>
List<Autodesk.Revit.DB.LineScaling> m_enumLineScaling;
/// <summary>
/// Line scaling option to export
/// </summary>
Autodesk.Revit.DB.LineScaling m_exportLineScaling;
/// <summary>
/// String list of Coordinate system basis
/// </summary>
List<String> m_coorSystem;
/// <summary>
/// List of values whether to use shared coordinate system
/// </summary>
List<bool> m_enumCoorSystem;
/// <summary>
/// Coordinate system basis option to export
/// </summary>
bool m_exportCoorSystem;
/// <summary>
/// String list of DWG unit
/// </summary>
List<String> m_units;
/// <summary>
/// List of Autodesk.Revit.DB.ExportUnit values defined in Revit
/// </summary>
List<Autodesk.Revit.DB.ExportUnit> m_enumUnits;
/// <summary>
/// Export unit option to export
/// </summary>
Autodesk.Revit.DB.ExportUnit m_exportUnit;
/// <summary>
/// String list of solid used in UI
/// </summary>
List<String> m_solids;
/// <summary>
/// List of Autodesk.Revit.DB.SolidGeometry defined in Revit
/// </summary>
List<Autodesk.Revit.DB.SolidGeometry> m_enumSolids;
/// <summary>
/// Solid geometry option to export
/// </summary>
Autodesk.Revit.DB.SolidGeometry m_exportSolid;
/// <summary>
/// Whether to create separate files for each view/sheet
/// </summary>
bool m_exportMergeFiles;
//Export rooms and areas as polylines
bool m_exportAreas;
#endregion
#region Class Properties
/// <summary>
/// String collection of Layers and properties used in UI
/// </summary>
public ReadOnlyCollection<String> LayersAndProperties
{
get
{
return new ReadOnlyCollection<String>(m_layersAndProperties);
}
}
/// <summary>
/// Collection of Autodesk.Revit.DB.PropOverrideMode
/// </summary>
public ReadOnlyCollection<Autodesk.Revit.DB.PropOverrideMode> EnumLayersAndProperties
{
get
{
return new ReadOnlyCollection<Autodesk.Revit.DB.PropOverrideMode>(m_enumLayersAndProperties);
}
}
/// <summary>
/// PropOverrideMode Option to export
/// </summary>
public Autodesk.Revit.DB.PropOverrideMode ExportLayersAndProperties
{
get
{
return m_exportLayersAndProperties;
}
set
{
m_exportLayersAndProperties = value;
}
}
/// <summary>
/// String collection of Layer Settings used in UI
/// </summary>
public ReadOnlyCollection<String> LayerMapping
{
get
{
return new ReadOnlyCollection<String>(m_layerMapping);
}
}
/// <summary>
/// String collection of layer settings values defined in Revit
/// </summary>
public ReadOnlyCollection<String> EnumLayerMapping
{
get
{
return new ReadOnlyCollection<String>(m_enumLayerMapping);
}
}
/// <summary>
/// Layer setting option to export
/// </summary>
public String ExportLayerMapping
{
get
{
return m_exportLayerMapping;
}
set
{
m_exportLayerMapping = value;
}
}
/// <summary>
/// String collection of Linetype scaling used in UI
/// </summary>
public ReadOnlyCollection<String> LineScaling
{
get
{
return new ReadOnlyCollection<String>(m_lineScaling);
}
}
/// <summary>
/// Collection of Autodesk.Revit.DB.LineScaling defined in Revit
/// </summary>
public ReadOnlyCollection<Autodesk.Revit.DB.LineScaling> EnumLineScaling
{
get
{
return new ReadOnlyCollection<Autodesk.Revit.DB.LineScaling>(m_enumLineScaling);
}
}
/// <summary>
/// Line scaling option to export
/// </summary>
public Autodesk.Revit.DB.LineScaling ExportLineScaling
{
get
{
return m_exportLineScaling;
}
set
{
m_exportLineScaling = value;
}
}
/// <summary>
/// String collection of Coordinate system basis
/// </summary>
public ReadOnlyCollection<String> CoorSystem
{
get
{
return new ReadOnlyCollection<String>(m_coorSystem);
}
}
/// <summary>
/// Collection of values whether to use shared coordinate system
/// </summary>
public ReadOnlyCollection<bool> EnumCoorSystem
{
get
{
return new ReadOnlyCollection<bool>(m_enumCoorSystem);
}
}
/// <summary>
/// Coordinate system basis option to export
/// </summary>
public bool ExportCoorSystem
{
get
{
return m_exportCoorSystem;
}
set
{
m_exportCoorSystem = value;
}
}
/// <summary>
/// String collection of DWG unit
/// </summary>
public ReadOnlyCollection<String> Units
{
get
{
return new ReadOnlyCollection<String>(m_units);
}
}
/// <summary>
/// Collection of Autodesk.Revit.DB.ExportUnit values defined in Revit
/// </summary>
public ReadOnlyCollection<Autodesk.Revit.DB.ExportUnit> EnumUnits
{
get
{
return new ReadOnlyCollection<Autodesk.Revit.DB.ExportUnit>(m_enumUnits);
}
}
/// <summary>
/// Export unit option to export
/// </summary>
public Autodesk.Revit.DB.ExportUnit ExportUnit
{
get
{
return m_exportUnit;
}
set
{
m_exportUnit = value;
}
}
/// <summary>
/// String collection of solid used in UI
/// </summary>
public ReadOnlyCollection<String> Solids
{
get
{
return new ReadOnlyCollection<String>(m_solids);
}
}
/// <summary>
/// Collection of Autodesk.Revit.DB.SolidGeometry defined in Revit
/// </summary>
public ReadOnlyCollection<Autodesk.Revit.DB.SolidGeometry> EnumSolids
{
get
{
return new ReadOnlyCollection<Autodesk.Revit.DB.SolidGeometry>(m_enumSolids);
}
}
/// <summary>
/// Property of solid geometry option to export
/// </summary>
public Autodesk.Revit.DB.SolidGeometry ExportSolid
{
get
{
return m_exportSolid;
}
set
{
m_exportSolid = value;
}
}
/// <summary>
/// Export rooms and areas as polylines
/// </summary>
public bool ExportAreas
{
get
{
return m_exportAreas;
}
set
{
m_exportAreas = value;
}
}
/// <summary>
/// Whether to create separate files for each view/sheet
/// </summary>
public bool ExportMergeFiles
{
get
{
return m_exportMergeFiles;
}
set
{
m_exportMergeFiles = value;
}
}
#endregion
#region Class Member Methods
/// <summary>
/// Constructor
/// </summary>
public ExportDWGOptionsData()
{
Initialize();
}
/// <summary>
/// Initialize values
/// </summary>
void Initialize()
{
//Layers and properties:
m_layersAndProperties = new List<String>();
m_enumLayersAndProperties = new List<Autodesk.Revit.DB.PropOverrideMode>();
m_layersAndProperties.Add("Category properties BYLAYER, overrides BYENTITY");
m_enumLayersAndProperties.Add(Autodesk.Revit.DB.PropOverrideMode.ByEntity);
m_layersAndProperties.Add("All properties BYLAYER, no overrides");
m_enumLayersAndProperties.Add(Autodesk.Revit.DB.PropOverrideMode.ByLayer);
m_layersAndProperties.Add("All properties BYLAYER, new Layers for overrides");
m_enumLayersAndProperties.Add(Autodesk.Revit.DB.PropOverrideMode.NewLayer);
//Layer Settings:
m_layerMapping = new List<String>();
m_enumLayerMapping = new List<String>();
m_layerMapping.Add("AIA - American Institute of Architects standard");
m_enumLayerMapping.Add("AIA");
m_layerMapping.Add("ISO13567 - ISO standard 13567");
m_enumLayerMapping.Add("ISO13567");
m_layerMapping.Add("CP83 - Singapore standard 83");
m_enumLayerMapping.Add("CP83");
m_layerMapping.Add("BS1192 - British standard 1192");
m_enumLayerMapping.Add("BS1192");
//Linetype scaling:
m_lineScaling = new List<String>();
m_enumLineScaling = new List<Autodesk.Revit.DB.LineScaling>();
m_lineScaling.Add("Scaled Linetype definitions");
m_enumLineScaling.Add(Autodesk.Revit.DB.LineScaling.ViewScale);
m_lineScaling.Add("ModelSpace (PSLTSCALE = 0)");
m_enumLineScaling.Add(Autodesk.Revit.DB.LineScaling.ModelSpace);
m_lineScaling.Add("Paperspace (PSLTSCALE = 1)");
m_enumLineScaling.Add(Autodesk.Revit.DB.LineScaling.PaperSpace);
//Coordinate system basis
m_coorSystem = new List<String>();
m_enumCoorSystem = new List<bool>();
m_coorSystem.Add("Project Internal");
m_enumCoorSystem.Add(false);
m_coorSystem.Add("Shared");
m_enumCoorSystem.Add(true);
//One DWG unit
m_units = new List<String>();
m_enumUnits = new List<Autodesk.Revit.DB.ExportUnit>();
m_units.Add(Autodesk.Revit.DB.ExportUnit.Foot.ToString().ToLower());
m_enumUnits.Add(Autodesk.Revit.DB.ExportUnit.Foot);
m_units.Add(Autodesk.Revit.DB.ExportUnit.Inch.ToString().ToLower());
m_enumUnits.Add(Autodesk.Revit.DB.ExportUnit.Inch);
m_units.Add(Autodesk.Revit.DB.ExportUnit.Meter.ToString().ToLower());
m_enumUnits.Add(Autodesk.Revit.DB.ExportUnit.Meter);
m_units.Add(Autodesk.Revit.DB.ExportUnit.Centimeter.ToString().ToLower());
m_enumUnits.Add(Autodesk.Revit.DB.ExportUnit.Centimeter);
m_units.Add(Autodesk.Revit.DB.ExportUnit.Millimeter.ToString().ToLower());
m_enumUnits.Add(Autodesk.Revit.DB.ExportUnit.Millimeter);
m_solids = new List<String>();
m_enumSolids = new List<Autodesk.Revit.DB.SolidGeometry>();
m_solids.Add("Export as polymesh");
m_enumSolids.Add(Autodesk.Revit.DB.SolidGeometry.Polymesh);
m_solids.Add("Export as ACIS solids");
m_enumSolids.Add(Autodesk.Revit.DB.SolidGeometry.ACIS);
}
#endregion
}
}
| |
#define SQLITE_ASCII
#define SQLITE_DISABLE_LFS
#define SQLITE_ENABLE_OVERSIZE_CELL_CHECK
#define SQLITE_MUTEX_OMIT
#define SQLITE_OMIT_AUTHORIZATION
#define SQLITE_OMIT_DEPRECATED
#define SQLITE_OMIT_GET_TABLE
#define SQLITE_OMIT_INCRBLOB
#define SQLITE_OMIT_LOOKASIDE
#define SQLITE_OMIT_SHARED_CACHE
#define SQLITE_OMIT_UTF16
#define SQLITE_OMIT_WAL
#define SQLITE_OS_WIN
#define SQLITE_SYSTEM_MALLOC
#define VDBE_PROFILE_OFF
#define WINDOWS_MOBILE
#define NDEBUG
#define _MSC_VER
#define YYFALLBACK
using System.Diagnostics;
using DWORD = System.Int32;
using System.Threading;
using System;
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/*
** 2007 August 14
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the C functions that implement mutexes for win32
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-03-09 19:31:43 4ae453ea7be69018d8c16eb8dabe05617397dc4d
**
*************************************************************************
*/
//#include "sqliteInt.h"
/*
** The code in this file is only used if we are compiling multithreaded
** on a win32 system.
*/
#if SQLITE_MUTEX_W32
/*
** Each recursive mutex is an instance of the following structure.
*/
public partial class sqlite3_mutex
{
public Object mutex; /* Mutex controlling the lock */
public int id; /* Mutex type */
public int nRef; /* Number of enterances */
public DWORD owner; /* Thread holding this mutex */
#if SQLITE_DEBUG
public int trace; /* True to trace changes */
#endif
public sqlite3_mutex()
{
mutex = new Object();
}
public sqlite3_mutex( Mutex mutex, int id, int nRef, DWORD owner
#if SQLITE_DEBUG
, int trace
#endif
)
{
this.mutex = mutex;
this.id = id;
this.nRef = nRef;
this.owner = owner;
#if SQLITE_DEBUG
this.trace = 0;
#endif
}
};
//#define SQLITE_W32_MUTEX_INITIALIZER { 0 }
static Mutex SQLITE_W32_MUTEX_INITIALIZER = null;
#if SQLITE_DEBUG
//#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
#else
//#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0 }
#endif
/*
** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
** or WinCE. Return false (zero) for Win95, Win98, or WinME.
**
** Here is an interesting observation: Win95, Win98, and WinME lack
** the LockFileEx() API. But we can still statically link against that
** API as long as we don't call it win running Win95/98/ME. A call to
** this routine is used to determine if the host is Win95/98/ME or
** WinNT/2K/XP so that we will know whether or not we can safely call
** the LockFileEx() API.
**
** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
** which is only available if your application was compiled with
** _WIN32_WINNT defined to a value >= 0x0400. Currently, the only
** call to TryEnterCriticalSection() is #ifdef'ed out, so #if
** this out as well.
*/
#if FALSE
#if SQLITE_OS_WINCE
//# define mutexIsNT() (1)
#else
static int mutexIsNT(void){
static int osType = 0;
if( osType==0 ){
OSVERSIONINFO sInfo;
sInfo.dwOSVersionInfoSize = sizeof(sInfo);
GetVersionEx(&sInfo);
osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
}
return osType==2;
}
#endif //* SQLITE_OS_WINCE */
#endif
#if SQLITE_DEBUG
/*
** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
** intended for use only inside Debug.Assert() statements.
*/
static bool winMutexHeld( sqlite3_mutex p )
{
return p.nRef != 0 && p.owner == GetCurrentThreadId();
}
static bool winMutexNotheld2( sqlite3_mutex p, DWORD tid )
{
return p.nRef == 0 || p.owner != tid;
}
static bool winMutexNotheld( sqlite3_mutex p )
{
DWORD tid = GetCurrentThreadId();
return winMutexNotheld2( p, tid );
}
#endif
/*
** Initialize and deinitialize the mutex subsystem.
*/
//No MACROS under C#; Cannot use SQLITE3_MUTEX_INITIALIZER,
static sqlite3_mutex[] winMutex_staticMutexes = new sqlite3_mutex[]{
new sqlite3_mutex( SQLITE_W32_MUTEX_INITIALIZER, 0, 0, (DWORD)0
#if SQLITE_DEBUG
, 0
#endif
),// SQLITE3_MUTEX_INITIALIZER,
new sqlite3_mutex( SQLITE_W32_MUTEX_INITIALIZER, 0, 0, (DWORD)0
#if SQLITE_DEBUG
, 0
#endif
),// SQLITE3_MUTEX_INITIALIZER,
new sqlite3_mutex( SQLITE_W32_MUTEX_INITIALIZER, 0, 0, (DWORD)0
#if SQLITE_DEBUG
, 0
#endif
),// SQLITE3_MUTEX_INITIALIZER,
new sqlite3_mutex( SQLITE_W32_MUTEX_INITIALIZER, 0, 0, (DWORD)0
#if SQLITE_DEBUG
, 0
#endif
),// SQLITE3_MUTEX_INITIALIZER,
new sqlite3_mutex( SQLITE_W32_MUTEX_INITIALIZER, 0, 0, (DWORD)0
#if SQLITE_DEBUG
, 0
#endif
),// SQLITE3_MUTEX_INITIALIZER,
new sqlite3_mutex( SQLITE_W32_MUTEX_INITIALIZER, 0, 0, (DWORD)0
#if SQLITE_DEBUG
, 0
#endif
),// SQLITE3_MUTEX_INITIALIZER,
};
static int winMutex_isInit = 0;
/* As winMutexInit() and winMutexEnd() are called as part
** of the sqlite3_initialize and sqlite3_shutdown()
** processing, the "interlocked" magic is probably not
** strictly necessary.
*/
static long winMutex_lock = 0;
private static System.Object lockThis = new System.Object();
static int winMutexInit()
{
/* The first to increment to 1 does actual initialization */
lock ( lockThis )
//if ( Interlocked.CompareExchange(ref winMutex_lock, 1, 0 ) == 0 )
{
int i;
for ( i = 0; i < ArraySize( winMutex_staticMutexes ); i++ )
{
if (winMutex_staticMutexes[i].mutex== null) winMutex_staticMutexes[i].mutex = new Mutex();
//InitializeCriticalSection( winMutex_staticMutexes[i].mutex );
}
winMutex_isInit = 1;
}
//else
//{
// /* Someone else is in the process of initing the static mutexes */
// while ( 0 == winMutex_isInit )
// {
// Thread.Sleep( 1 );
// }
//}
return SQLITE_OK;
}
static int winMutexEnd()
{
/* The first to decrement to 0 does actual shutdown
** (which should be the last to shutdown.) */
if ( Interlocked.CompareExchange( ref winMutex_lock, 0, 1 ) == 1 )
{
if ( winMutex_isInit == 1 )
{
int i;
for ( i = 0; i < ArraySize( winMutex_staticMutexes ); i++ )
{
DeleteCriticalSection( winMutex_staticMutexes[i].mutex );
}
winMutex_isInit = 0;
}
}
return SQLITE_OK;
}
/*
** The sqlite3_mutex_alloc() routine allocates a new
** mutex and returns a pointer to it. If it returns NULL
** that means that a mutex could not be allocated. SQLite
** will unwind its stack and return an error. The argument
** to sqlite3_mutex_alloc() is one of these integer constants:
**
** <ul>
** <li> SQLITE_MUTEX_FAST
** <li> SQLITE_MUTEX_RECURSIVE
** <li> SQLITE_MUTEX_STATIC_MASTER
** <li> SQLITE_MUTEX_STATIC_MEM
** <li> SQLITE_MUTEX_STATIC_MEM2
** <li> SQLITE_MUTEX_STATIC_PRNG
** <li> SQLITE_MUTEX_STATIC_LRU
** <li> SQLITE_MUTEX_STATIC_LRU2
** </ul>
**
** The first two constants cause sqlite3_mutex_alloc() to create
** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
** The mutex implementation does not need to make a distinction
** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
** not want to. But SQLite will only request a recursive mutex in
** cases where it really needs one. If a faster non-recursive mutex
** implementation is available on the host platform, the mutex subsystem
** might return such a mutex in response to SQLITE_MUTEX_FAST.
**
** The other allowed parameters to sqlite3_mutex_alloc() each return
** a pointer to a static preexisting mutex. Six static mutexes are
** used by the current version of SQLite. Future versions of SQLite
** may add additional static mutexes. Static mutexes are for internal
** use by SQLite only. Applications that use SQLite mutexes should
** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
** SQLITE_MUTEX_RECURSIVE.
**
** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
** returns a different mutex on every call. But for the static
** mutex types, the same mutex is returned on every call that has
** the same type number.
*/
static sqlite3_mutex winMutexAlloc( int iType )
{
sqlite3_mutex p;
switch ( iType )
{
case SQLITE_MUTEX_FAST:
case SQLITE_MUTEX_RECURSIVE:
{
p = new sqlite3_mutex();//sqlite3MallocZero( sizeof(*p) );
if ( p != null )
{
p.id = iType;
InitializeCriticalSection( p.mutex );
}
break;
}
default:
{
Debug.Assert( winMutex_isInit == 1 );
Debug.Assert( iType - 2 >= 0 );
Debug.Assert( iType - 2 < ArraySize( winMutex_staticMutexes ) );
p = winMutex_staticMutexes[iType - 2];
p.id = iType;
break;
}
}
return p;
}
/*
** This routine deallocates a previously
** allocated mutex. SQLite is careful to deallocate every
** mutex that it allocates.
*/
static void winMutexFree( sqlite3_mutex p )
{
Debug.Assert( p != null );
Debug.Assert( p.nRef == 0 );
Debug.Assert( p.id == SQLITE_MUTEX_FAST || p.id == SQLITE_MUTEX_RECURSIVE );
DeleteCriticalSection( p.mutex );
p.owner = 0;
//sqlite3_free( p );
}
/*
** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
** to enter a mutex. If another thread is already within the mutex,
** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
** be entered multiple times by the same thread. In such cases the,
** mutex must be exited an equal number of times before another thread
** can enter. If the same thread tries to enter any other kind of mutex
** more than once, the behavior is undefined.
*/
static void winMutexEnter( sqlite3_mutex p )
{
DWORD tid = GetCurrentThreadId();
Debug.Assert( p.id == SQLITE_MUTEX_RECURSIVE || winMutexNotheld2( p, tid ) );
EnterCriticalSection( p.mutex );
p.owner = tid;
p.nRef++;
#if SQLITE_DEBUG
if ( p.trace != 0 )
{
printf( "enter mutex {0} ({1}) with nRef={2}\n", p.GetHashCode(), p.owner, p.nRef );
}
#endif
}
static int winMutexTry( sqlite3_mutex p )
{
#if !NDEBUG
DWORD tid = GetCurrentThreadId();
#endif
int rc = SQLITE_BUSY;
Debug.Assert( p.id == SQLITE_MUTEX_RECURSIVE || winMutexNotheld2( p, tid ) );
/*
** The sqlite3_mutex_try() routine is very rarely used, and when it
** is used it is merely an optimization. So it is OK for it to always
** fail.
**
** The TryEnterCriticalSection() interface is only available on WinNT.
** And some windows compilers complain if you try to use it without
** first doing some #defines that prevent SQLite from building on Win98.
** For that reason, we will omit this optimization for now. See
** ticket #2685.
*/
#if FALSE
if( mutexIsNT() && TryEnterCriticalSection(p.mutex) ){
p.owner = tid;
p.nRef++;
rc = SQLITE_OK;
}
#else
UNUSED_PARAMETER( p );
#endif
#if SQLITE_DEBUG
if ( rc == SQLITE_OK && p.trace != 0 )
{
printf( "try mutex {0} ({1}) with nRef={2}\n", p.GetHashCode(), p.owner, p.nRef );
}
#endif
return rc;
}
/*
** The sqlite3_mutex_leave() routine exits a mutex that was
** previously entered by the same thread. The behavior
** is undefined if the mutex is not currently entered or
** is not currently allocated. SQLite will never do either.
*/
static void winMutexLeave( sqlite3_mutex p )
{
#if !NDEBUG
DWORD tid = GetCurrentThreadId();
#endif
Debug.Assert( p.nRef > 0 );
Debug.Assert( p.owner == tid );
p.nRef--;
Debug.Assert( p.nRef == 0 || p.id == SQLITE_MUTEX_RECURSIVE );
if (p.nRef == 0) LeaveCriticalSection( p.mutex );
#if SQLITE_DEBUG
if ( p.trace != 0 )
{
printf( "leave mutex {0} ({1}) with nRef={2}\n", p.GetHashCode(), p.owner, p.nRef );
}
#endif
}
static sqlite3_mutex_methods sqlite3DefaultMutex()
{
sqlite3_mutex_methods sMutex = new sqlite3_mutex_methods (
(dxMutexInit)winMutexInit,
(dxMutexEnd)winMutexEnd,
(dxMutexAlloc)winMutexAlloc,
(dxMutexFree)winMutexFree,
(dxMutexEnter)winMutexEnter,
(dxMutexTry)winMutexTry,
(dxMutexLeave)winMutexLeave,
#if SQLITE_DEBUG
(dxMutexHeld)winMutexHeld,
(dxMutexNotheld)winMutexNotheld
#else
null,
null
#endif
);
return sMutex;
}
#endif // * SQLITE_MUTEX_W32 */
}
}
| |
/* Genuine Channels product.
*
* Copyright (c) 2002-2007 Dmitry Belikov. All rights reserved.
*
* This source code comes under and must be used and distributed according to the Genuine Channels license agreement.
*/
using System;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Win32.SafeHandles;
namespace Belikov.GenuineChannels.GenuineSharedMemory
{
/// <summary>
/// Contains declarations of windows API stuff related to shared memory functionality.
/// </summary>
public class WindowsAPI
{
[DllImport("kernel32", SetLastError=true, CharSet=CharSet.Auto)]
static internal extern IntPtr CreateFileMapping(IntPtr hFile, _SECURITY_ATTRIBUTES lpSecurityAttributes, uint flProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, string lpName);
[DllImport("kernel32", SetLastError=true, CharSet=CharSet.Auto)]
static internal extern IntPtr OpenFileMapping(uint dwDesiredAccess, int bInheritHandle, string lpName);
[DllImport("kernel32", SetLastError=true, CharSet=CharSet.Auto)]
static internal extern IntPtr MapViewOfFile(IntPtr hFileMappingObject, uint dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, uint dwNumberOfBytesToMap);
[DllImport("kernel32", SetLastError=true, CharSet=CharSet.Auto)]
static internal extern bool UnmapViewOfFile(IntPtr lpBaseAddress);
[DllImport("kernel32", SetLastError=true, CharSet=CharSet.Auto)]
static internal extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32", SetLastError=true, CharSet=CharSet.Auto)]
static internal extern int FormatMessage(uint dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, IntPtr lpBuffer, uint nSize, IntPtr pArguments);
[DllImport("kernel32", SetLastError=true, CharSet=CharSet.Auto)]
static internal extern IntPtr LocalFree(IntPtr hMem);
[DllImport("kernel32", SetLastError=true, CharSet=CharSet.Auto)]
static internal extern IntPtr CreateEvent(_SECURITY_ATTRIBUTES lpEventAttributes, int bManualReset, int bInitialState, string lpName);
[DllImport("kernel32", SetLastError=true, CharSet=CharSet.Auto)]
static internal extern bool SetEvent(IntPtr hEvent);
[DllImport("kernel32", SetLastError=true, CharSet=CharSet.Auto)]
static internal extern bool ResetEvent(IntPtr hEvent);
[DllImport("kernel32", SetLastError=true, CharSet=CharSet.Auto)]
static internal extern uint WaitForSingleObject(IntPtr hHandle, int dwMilliseconds);
[DllImport("kernel32", SetLastError=true, CharSet=CharSet.Auto)]
static internal extern IntPtr OpenEvent(int dwDesiredAccess, int bInheritHandle, string lpName);
/// <summary>
/// Page read/write constant.
/// </summary>
internal const int PAGE_READWRITE = 0x04;
/// <summary>
/// See Win API docs.
/// </summary>
internal const uint SECTION_QUERY = 0x0001;
/// <summary>
/// See Win API docs.
/// </summary>
internal const uint SECTION_MAP_WRITE = 0x0002;
/// <summary>
/// See Win API docs.
/// </summary>
internal const uint SECTION_MAP_READ = 0x0004;
/// <summary>
/// See Win API docs.
/// </summary>
internal const uint SECTION_MAP_EXECUTE = 0x0008;
/// <summary>
/// See Win API docs.
/// </summary>
internal const uint SECTION_EXTEND_SIZE = 0x0010;
/// <summary>
/// See Win API docs.
/// </summary>
internal const uint FILE_MAP_ALL_ACCESS = SECTION_QUERY | SECTION_MAP_WRITE | SECTION_MAP_READ | SECTION_MAP_EXECUTE | SECTION_EXTEND_SIZE;
/// <summary>
/// See Win API docs.
/// </summary>
internal const uint FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100;
/// <summary>
/// See Win API docs.
/// </summary>
internal const uint FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
/// <summary>
/// See Win API docs.
/// </summary>
internal const uint FORMAT_MESSAGE_FROM_STRING = 0x00000400;
/// <summary>
/// See Win API docs.
/// </summary>
internal const uint FORMAT_MESSAGE_FROM_HMODULE = 0x00000800;
/// <summary>
/// See Win API docs.
/// </summary>
internal const uint FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
/// <summary>
/// See Win API docs.
/// </summary>
internal const uint FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000;
/// <summary>
/// See Win API docs.
/// </summary>
internal const uint FORMAT_MESSAGE_MAX_WIDTH_MASK = 0x000000FF;
/// <summary>
/// See Win API docs.
/// </summary>
internal const uint WAIT_TIMEOUT = 258;
/// <summary>
/// See Win API docs.
/// </summary>
internal const int INFINITE = -1;
/// <summary>
/// See Win API docs.
/// </summary>
internal const int SYNCHRONIZE = 0x00100000;
/// <summary>
/// See Win API docs.
/// </summary>
internal const int STANDARD_RIGHTS_REQUIRED = 0x000F0000;
/// <summary>
/// See Win API docs.
/// </summary>
internal const int EVENT_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3;
/// <summary>
/// Security attributes.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal class _SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}
[DllImport("Advapi32", SetLastError=true, CharSet=CharSet.Auto)]
static private extern bool InitializeSecurityDescriptor(IntPtr pSecurityDescriptor, int dwRevision);
[DllImport("Advapi32", SetLastError=true, CharSet=CharSet.Auto)]
static private extern bool SetSecurityDescriptorDacl(IntPtr pSecurityDescriptor, bool bDaclPresent, IntPtr pDacl, bool bDaclDefaulted);
[DllImport("Kernel32", SetLastError=true, CharSet=CharSet.Auto)]
static private extern IntPtr CreateMutex(_SECURITY_ATTRIBUTES lpMutexAttributes, bool bInitialOwner, string lpName);
[DllImport("Kernel32", SetLastError=true, CharSet=CharSet.Auto)]
static private extern IntPtr OpenMutex(int dwDesiredAccess, bool bInheritHandle, string lpName);
private const int SECURITY_DESCRIPTOR_MIN_LENGTH = 20;
private const int SECURITY_DESCRIPTOR_REVISION = 1;
private const int MUTEX_ALL_ACCESS = 0x1F0001;
private const int MUTEX_MODIFY_STATE = 0x1;
private const int ERROR_ALREADY_EXISTS = 183;
static WindowsAPI()
{
NullAttribute = Marshal.AllocHGlobal(SECURITY_DESCRIPTOR_MIN_LENGTH);
if (NullAttribute == IntPtr.Zero)
return ;
try
{
if (! InitializeSecurityDescriptor(NullAttribute, SECURITY_DESCRIPTOR_REVISION))
throw GenuineExceptions.Get_Windows_SharedMemoryError(Marshal.GetLastWin32Error());
if (! SetSecurityDescriptorDacl(NullAttribute, true, IntPtr.Zero, false))
throw GenuineExceptions.Get_Windows_SharedMemoryError(Marshal.GetLastWin32Error());
AttributesWithNullDACL = new _SECURITY_ATTRIBUTES();
AttributesWithNullDACL.nLength = 12;
AttributesWithNullDACL.lpSecurityDescriptor = NullAttribute;
AttributesWithNullDACL.bInheritHandle = 1;
}
catch(Exception ex)
{
FailureReason = ex;
try
{
Marshal.FreeHGlobal(NullAttribute);
}
catch(Exception)
{
}
NullAttribute = IntPtr.Zero;
}
}
static private IntPtr NullAttribute = IntPtr.Zero;
static internal _SECURITY_ATTRIBUTES AttributesWithNullDACL;
static internal Exception FailureReason;
// /// <summary>
// /// Creates a new mutex with NULL DACL.
// /// </summary>
// /// <param name="mutex">The mutex.</param>
// /// <param name="name">The name of the mutex.</param>
// static internal void UpgrageMutexSecurity(Mutex mutex, string name)
// {
// CloseHandle(mutex.Handle);
// mutex.Handle = CreateMutex(AttributesWithNullDACL, false, name);
// }
/// <summary>
/// Opens an existent mutex.
/// </summary>
/// <param name="name">The name of the mutex.</param>
/// <returns>The opened mutex.</returns>
static internal Mutex OpenMutex(string name)
{
IntPtr result = OpenMutex(MUTEX_ALL_ACCESS, false, name);
if (result == IntPtr.Zero)
throw GenuineExceptions.Get_Windows_SharedMemoryError(Marshal.GetLastWin32Error());
Mutex mutex = new Mutex();
mutex.SafeWaitHandle = new SafeWaitHandle(result, true);
return mutex;
}
static internal Mutex CreateMutex(string name)
{
IntPtr result = CreateMutex(AttributesWithNullDACL, false, name);
if (result == IntPtr.Zero)
throw GenuineExceptions.Get_Windows_SharedMemoryError(Marshal.GetLastWin32Error());
if (Marshal.GetLastWin32Error() == ERROR_ALREADY_EXISTS)
throw GenuineExceptions.Get_Windows_SharedMemoryError(Marshal.GetLastWin32Error());
Mutex mutex = new Mutex();
mutex.SafeWaitHandle = new SafeWaitHandle(result, true);
return mutex;
}
}
}
| |
// 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 Microsoft.NodejsTools.Npm;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
namespace NpmTests
{
[TestClass]
public class PackageJsonTests : AbstractPackageJsonTests
{
private const string PkgSimpleBugs = @"{
""name"": ""TestPkg"",
""version"": ""0.1.0"",
""bugs"": ""http://www.mybugtracker.com/""
}";
private const string PkgMisSpelledAuthor = @"{
""name"": ""TestPkg"",
""version"": ""0.1.0"",
""author"": {
""misspelledname"": ""Firstname Lastname""
}
}";
private const string PkgSingleAuthorField = @"{
""name"": ""TestPkg"",
""version"": ""0.1.0"",
""author"": {
""name"": ""Firstname Lastname""
}
}";
private const string PkgSingleLicenseType = @"{
""name"": ""TestPkg"",
""version"": ""0.1.0"",
""license"" : ""BSD""
}";
private const string PkgStartScript = @"{
""name"": ""ScriptPkg"",
""version"": ""1.2.3"",
""scripts"": {""start"": ""node server.js""}
}";
private const string PkgLargeCompliant = @"{
""name"": ""mypackage"",
""version"": ""0.7.0"",
""description"": ""Sample package for CommonJS. This package demonstrates the required elements of a CommonJS package."",
""author"": {
""name"": ""Firstname Lastname"",
""email"": ""firstname@lastname.com"",
""url"": ""http://firstnamelastname.com""
},
""keywords"": [
""package"",
""example""
],
""homepage"": ""http://www.mypackagehomepage.com/"",
""maintainers"": [
{
""name"": ""Bill Smith"",
""email"": ""bills@example.com"",
""web"": ""http://www.example.com""
}
],
""contributors"": [
{
""name"": ""Mary Brown"",
""email"": ""maryb@embedthis.com"",
""web"": ""http://www.embedthis.com""
}
],
""bugs"": {
""email"": ""dev@example.com"",
""url"": ""http://www.example.com/bugs""
},
""licenses"": [
{
""type"": ""GPLv2"",
""url"": ""http://www.example.org/licenses/gpl.html""
}
],
""repositories"": [
{
""type"": ""git"",
""url"": ""http://hg.example.com/mypackage.git""
}
],
""dependencies"": {
""webkit"": ""1.2"",
""ssl"": {
""gnutls"": [""1.0"", ""2.0""],
""openssl"": ""0.9.8""
}
},
""implements"": [""cjs-module-0.3"", ""cjs-jsgi-0.1""],
""os"": [""linux"", ""macos"", ""win""],
""cpu"": [""x86"", ""ppc"", ""x86_64""],
""engines"": [""v8"", ""ejs"", ""node"", ""rhino""],
""scripts"": {
""install"": ""install.js"",
""uninstall"": ""uninstall.js"",
""build"": ""build.js"",
""test"": ""test.js""
},
""man"" : [ ""./man/foo.1"", ""./man/bar.1"" ],
""files"" : [""server.js"", ""customlib.js"", ""path/to/subfolder""],
""directories"": {
""lib"": ""src/lib"",
""bin"": ""local/binaries"",
""jars"": ""java""
}
}";
private const string PkgLargeNonCompliant = @"{
""name"": ""mypackage"",
""version"": ""0.7.0"",
""description"": ""Sample package for CommonJS. This package demonstrates the required elements of a CommonJS package."",
""author"": {
""url"": ""http://firstnamelastname.com"",
""name"": ""Firstname Lastname""
},
""keywords"": [
""package"",
""example""
],
""homepage"": [""http://www.mypackagehomepage.com/""],
""maintainers"": [
{
""name"": ""Bill Smith"",
""email"": ""bills@example.com"",
""web"": ""http://www.example.com""
}
],
""contributors"": [
{
""name"": ""Mary Brown"",
""email"": ""maryb@embedthis.com"",
""web"": ""http://www.embedthis.com""
}
],
""bugs"": {
""mail"": ""dev@example.com"",
""web"": ""http://www.example.com/bugs""
},
""licenses"": [
{
""type"": ""GPLv2"",
""url"": ""http://www.example.org/licenses/gpl.html""
}
],
""repositories"": [
{
""type"": ""git"",
""url"": ""http://hg.example.com/mypackage.git""
}
],
""dependencies"": {
""webkit"": ""1.2"",
""ssl"": {
""gnutls"": [""1.0"", ""2.0""],
""openssl"": ""0.9.8""
}
},
""implements"": [""cjs-module-0.3"", ""cjs-jsgi-0.1""],
""os"": [""linux"", ""macos"", ""win""],
""cpu"": [""x86"", ""ppc"", ""x86_64""],
""engines"": [""v8"", ""ejs"", ""node"", ""rhino""],
""scripts"": {
""install"": ""install.js"",
""uninstall"": ""uninstall.js"",
""build"": ""build.js"",
""test"": ""test.js""
},
""man"" : ""./man/foo.1"",
""directories"": {
""lib"": ""src/lib"",
""bin"": ""local/binaries"",
""jars"": ""java""
}
}";
[TestMethod, Priority(0)]
public void ReadNoNameNull()
{
var pkg = LoadFrom(PkgEmpty);
Assert.IsNull(pkg.Name, "Name should be null.");
}
[TestMethod, Priority(0)]
public void ReadNoVersionIsZeroed()
{
var pkg = LoadFrom(PkgEmpty);
Assert.AreEqual(new SemverVersion(), pkg.Version, "Empty version mismatch.");
}
[TestMethod, Priority(0)]
public void ReadNameAndVersion()
{
var pkgJson = LoadFrom(PkgSimple);
dynamic json = JsonConvert.DeserializeObject(PkgSimple);
Assert.AreEqual(json.name.ToString(), pkgJson.Name, "Mismatched package names.");
Assert.AreEqual(json.version.ToString(), pkgJson.Version.ToString(), "Mismatched version strings.");
SemverVersionTestHelper.AssertVersionsEqual(0, 1, 0, null, null, pkgJson.Version);
}
[TestMethod, Priority(0)]
public void ReadNoDescriptionNull()
{
var pkg = LoadFrom(PkgEmpty);
Assert.IsNull(pkg.Description, "Description should be null.");
}
[TestMethod, Priority(0)]
public void ReadDescription()
{
var pkg = LoadFrom(PkgLargeCompliant);
Assert.AreEqual(
"Sample package for CommonJS. This package demonstrates the required elements of a CommonJS package.",
pkg.Description,
"Description mismatch.");
}
[TestMethod, Priority(0)]
public void ReadEmptyKeywordsCountZero()
{
CheckEmptyArray(LoadFrom(PkgEmpty).Keywords);
}
[TestMethod, Priority(0)]
public void EnumerationOverKeywords()
{
CheckStringArrayContents(
LoadFrom(PkgLargeCompliant).Keywords,
2,
new[] { "package", "example" });
}
[TestMethod, Priority(0)]
public void ReadNoHomepageEmpty()
{
var pkg = LoadFrom(PkgSimple);
Assert.AreEqual(0, pkg.Homepages.Count, "Homepage should be empty.");
}
[TestMethod, Priority(0)]
public void ReadHomepageCompliant()
{
var pkg = LoadFrom(PkgLargeCompliant);
CheckStringArrayContents(
pkg.Homepages,
1,
new[] { "http://www.mypackagehomepage.com/" });
}
[TestMethod, Priority(0)]
public void ReadHomepageNonCompliant()
{
var pkg = LoadFrom(PkgLargeNonCompliant);
CheckStringArrayContents(
pkg.Homepages,
1,
new[] { "http://www.mypackagehomepage.com/" });
}
[TestMethod, Priority(0)]
public void ReadEmptyFilesEmpty()
{
CheckEmptyArray(LoadFrom(PkgSimple).Files);
}
[TestMethod, Priority(0)]
public void ReadFiles()
{
CheckStringArrayContents(
LoadFrom(PkgLargeCompliant).Files,
3,
new[] { "server.js", "customlib.js", "path/to/subfolder" });
}
[TestMethod, Priority(0)]
public void ReadEmptyAuthor()
{
Assert.IsNull(LoadFrom(PkgSimple).Author);
}
[TestMethod, Priority(0)]
public void ReadMisspelledAuthor()
{
Assert.AreEqual(
@"{
""misspelledname"": ""Firstname Lastname""
}",
LoadFrom(PkgMisSpelledAuthor).Author.Name
);
}
[TestMethod, Priority(0)]
public void ReadSingleAuthorField()
{
Assert.AreEqual(
"Firstname Lastname",
LoadFrom(PkgSingleAuthorField).Author.Name
);
}
[TestMethod, Priority(0)]
public void ReadAuthorCompliant()
{
var compliantAuthor = LoadFrom(PkgLargeCompliant).Author;
Assert.AreEqual("Firstname Lastname", compliantAuthor.Name);
Assert.AreEqual("firstname@lastname.com", compliantAuthor.Email);
Assert.AreEqual("http://firstnamelastname.com", compliantAuthor.Url);
}
[TestMethod, Priority(0)]
public void ReadAuthorNonCompliant()
{
var nonCompliantAuthor = LoadFrom(PkgLargeNonCompliant).Author;
Assert.AreEqual("Firstname Lastname", nonCompliantAuthor.Name);
Assert.AreEqual("http://firstnamelastname.com", nonCompliantAuthor.Url);
Assert.IsNull(nonCompliantAuthor.Email);
}
// TODO: authors, contributors, private, main, bin, directories (hash), repository, config,
}
}
| |
// 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.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
namespace System
{
// Implements the Decimal data type. The Decimal data type can
// represent values ranging from -79,228,162,514,264,337,593,543,950,335 to
// 79,228,162,514,264,337,593,543,950,335 with 28 significant digits. The
// Decimal data type is ideally suited to financial calculations that
// require a large number of significant digits and no round-off errors.
//
// The finite set of values of type Decimal are of the form m
// / 10e, where m is an integer such that
// -296 <; m <; 296, and e is an integer
// between 0 and 28 inclusive.
//
// Contrary to the float and double data types, decimal
// fractional numbers such as 0.1 can be represented exactly in the
// Decimal representation. In the float and double
// representations, such numbers are often infinite fractions, making those
// representations more prone to round-off errors.
//
// The Decimal class implements widening conversions from the
// ubyte, char, short, int, and long types
// to Decimal. These widening conversions never loose any information
// and never throw exceptions. The Decimal class also implements
// narrowing conversions from Decimal to ubyte, char,
// short, int, and long. These narrowing conversions round
// the Decimal value towards zero to the nearest integer, and then
// converts that integer to the destination type. An OverflowException
// is thrown if the result is not within the range of the destination type.
//
// The Decimal class provides a widening conversion from
// Currency to Decimal. This widening conversion never loses any
// information and never throws exceptions. The Currency class provides
// a narrowing conversion from Decimal to Currency. This
// narrowing conversion rounds the Decimal to four decimals and then
// converts that number to a Currency. An OverflowException
// is thrown if the result is not within the range of the Currency type.
//
// The Decimal class provides narrowing conversions to and from the
// float and double types. A conversion from Decimal to
// float or double may loose precision, but will not loose
// information about the overall magnitude of the numeric value, and will never
// throw an exception. A conversion from float or double to
// Decimal throws an OverflowException if the value is not within
// the range of the Decimal type.
[Serializable]
[StructLayout(LayoutKind.Explicit)]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public partial struct Decimal : IFormattable, IComparable, IConvertible, IComparable<Decimal>, IEquatable<Decimal>, IDeserializationCallback
{
// Sign mask for the flags field. A value of zero in this bit indicates a
// positive Decimal value, and a value of one in this bit indicates a
// negative Decimal value.
//
// Look at OleAut's DECIMAL_NEG constant to check for negative values
// in native code.
private const uint SignMask = 0x80000000;
// Scale mask for the flags field. This byte in the flags field contains
// the power of 10 to divide the Decimal value by. The scale byte must
// contain a value between 0 and 28 inclusive.
private const uint ScaleMask = 0x00FF0000;
// Number of bits scale is shifted by.
private const int ScaleShift = 16;
// Constant representing the Decimal value 0.
public const Decimal Zero = 0m;
// Constant representing the Decimal value 1.
public const Decimal One = 1m;
// Constant representing the Decimal value -1.
public const Decimal MinusOne = -1m;
// Constant representing the largest possible Decimal value. The value of
// this constant is 79,228,162,514,264,337,593,543,950,335.
public const Decimal MaxValue = 79228162514264337593543950335m;
// Constant representing the smallest possible Decimal value. The value of
// this constant is -79,228,162,514,264,337,593,543,950,335.
public const Decimal MinValue = -79228162514264337593543950335m;
private const int CurrencyScale = 4; // Divide the "Int64" representation by 1E4 to get the "true" value of the Currency.
// The lo, mid, hi, and flags fields contain the representation of the
// Decimal value. The lo, mid, and hi fields contain the 96-bit integer
// part of the Decimal. Bits 0-15 (the lower word) of the flags field are
// unused and must be zero; bits 16-23 contain must contain a value between
// 0 and 28, indicating the power of 10 to divide the 96-bit integer part
// by to produce the Decimal value; bits 24-30 are unused and must be zero;
// and finally bit 31 indicates the sign of the Decimal value, 0 meaning
// positive and 1 meaning negative.
//
// NOTE: Do not change the offsets of these fields. This structure maps to the OleAut DECIMAL structure
// and can be passed as such in P/Invokes.
[FieldOffset(0)]
private int flags; // Do not rename (binary serialization)
[FieldOffset(4)]
private int hi; // Do not rename (binary serialization)
[FieldOffset(8)]
private int lo; // Do not rename (binary serialization)
[FieldOffset(12)]
private int mid; // Do not rename (binary serialization)
// NOTE: This set of fields overlay the ones exposed to serialization (which have to be signed ints for serialization compat.)
// The code inside Decimal was ported from C++ and expect unsigned values.
[FieldOffset(0), NonSerialized]
private uint uflags;
[FieldOffset(4), NonSerialized]
private uint uhi;
[FieldOffset(8), NonSerialized]
private uint ulo;
[FieldOffset(12), NonSerialized]
private uint umid;
// Constructs a zero Decimal.
//public Decimal() {
// lo = 0;
// mid = 0;
// hi = 0;
// flags = 0;
//}
// Constructs a Decimal from an integer value.
//
public Decimal(int value)
{
// JIT today can't inline methods that contains "starg" opcode.
// For more details, see DevDiv Bugs 81184: x86 JIT CQ: Removing the inline striction of "starg".
int value_copy = value;
if (value_copy >= 0)
{
uflags = 0;
}
else
{
uflags = SignMask;
value_copy = -value_copy;
}
lo = value_copy;
mid = 0;
hi = 0;
}
// Constructs a Decimal from an unsigned integer value.
//
[CLSCompliant(false)]
public Decimal(uint value)
{
uflags = 0;
ulo = value;
umid = 0;
uhi = 0;
}
// Constructs a Decimal from a long value.
//
public Decimal(long value)
{
// JIT today can't inline methods that contains "starg" opcode.
// For more details, see DevDiv Bugs 81184: x86 JIT CQ: Removing the inline striction of "starg".
long value_copy = value;
if (value_copy >= 0)
{
uflags = 0;
}
else
{
uflags = SignMask;
value_copy = -value_copy;
}
ulo = (uint)value_copy;
umid = (uint)(value_copy >> 32);
uhi = 0;
}
// Constructs a Decimal from an unsigned long value.
//
[CLSCompliant(false)]
public Decimal(ulong value)
{
uflags = 0;
ulo = (uint)value;
umid = (uint)(value >> 32);
uhi = 0;
}
// Constructs a Decimal from a float value.
//
public Decimal(float value)
{
DecCalc.VarDecFromR4(value, out this);
}
// Constructs a Decimal from a double value.
//
public Decimal(double value)
{
DecCalc.VarDecFromR8(value, out this);
}
//
// Decimal <==> Currency conversion.
//
// A Currency represents a positive or negative decimal value with 4 digits past the decimal point. The actual Int64 representation used by these methods
// is the currency value multiplied by 10,000. For example, a currency value of $12.99 would be represented by the Int64 value 129,900.
//
public static Decimal FromOACurrency(long cy)
{
Decimal d = default(Decimal);
ulong absoluteCy; // has to be ulong to accommodate the case where cy == long.MinValue.
if (cy < 0)
{
d.Sign = true;
absoluteCy = (ulong)(-cy);
}
else
{
absoluteCy = (ulong)cy;
}
// In most cases, FromOACurrency() produces a Decimal with Scale set to 4. Unless, that is, some of the trailing digits past the decimal point are zero,
// in which case, for compatibility with .Net, we reduce the Scale by the number of zeros. While the result is still numerically equivalent, the scale does
// affect the ToString() value. In particular, it prevents a converted currency value of $12.95 from printing uglily as "12.9500".
int scale = CurrencyScale;
if (absoluteCy != 0) // For compatibility, a currency of 0 emits the Decimal "0.0000" (scale set to 4).
{
while (scale != 0 && ((absoluteCy % 10) == 0))
{
scale--;
absoluteCy /= 10;
}
}
// No need to set d.Hi32 - a currency will never go high enough for it to be anything other than zero.
d.Low64 = absoluteCy;
d.Scale = scale;
return d;
}
public static long ToOACurrency(Decimal value)
{
long cy;
DecCalc.VarCyFromDec(ref value, out cy);
return cy;
}
private static bool IsValid(uint flags) => (flags & ~(SignMask | ScaleMask)) == 0 && ((flags & ScaleMask) <= (28 << 16));
// Constructs a Decimal from an integer array containing a binary
// representation. The bits argument must be a non-null integer
// array with four elements. bits[0], bits[1], and
// bits[2] contain the low, middle, and high 32 bits of the 96-bit
// integer part of the Decimal. bits[3] contains the scale factor
// and sign of the Decimal: bits 0-15 (the lower word) are unused and must
// be zero; bits 16-23 must contain a value between 0 and 28, indicating
// the power of 10 to divide the 96-bit integer part by to produce the
// Decimal value; bits 24-30 are unused and must be zero; and finally bit
// 31 indicates the sign of the Decimal value, 0 meaning positive and 1
// meaning negative.
//
// Note that there are several possible binary representations for the
// same numeric value. For example, the value 1 can be represented as {1,
// 0, 0, 0} (integer value 1 with a scale factor of 0) and equally well as
// {1000, 0, 0, 0x30000} (integer value 1000 with a scale factor of 3).
// The possible binary representations of a particular value are all
// equally valid, and all are numerically equivalent.
//
public Decimal(int[] bits)
{
lo = 0;
mid = 0;
hi = 0;
flags = 0;
SetBits(bits);
}
private void SetBits(int[] bits)
{
if (bits == null)
throw new ArgumentNullException(nameof(bits));
Contract.EndContractBlock();
if (bits.Length == 4)
{
uint f = (uint)bits[3];
if (IsValid(f))
{
lo = bits[0];
mid = bits[1];
hi = bits[2];
uflags = f;
return;
}
}
throw new ArgumentException(SR.Arg_DecBitCtor);
}
// Constructs a Decimal from its constituent parts.
//
public Decimal(int lo, int mid, int hi, bool isNegative, byte scale)
{
if (scale > 28)
throw new ArgumentOutOfRangeException(nameof(scale), SR.ArgumentOutOfRange_DecimalScale);
Contract.EndContractBlock();
this.lo = lo;
this.mid = mid;
this.hi = hi;
uflags = ((uint)scale) << 16;
if (isNegative)
uflags |= SignMask;
}
void IDeserializationCallback.OnDeserialization(Object sender)
{
// OnDeserialization is called after each instance of this class is deserialized.
// This callback method performs decimal validation after being deserialized.
try
{
SetBits(GetBits(this));
}
catch (ArgumentException e)
{
throw new SerializationException(SR.Overflow_Decimal, e);
}
}
// Constructs a Decimal from its constituent parts.
private Decimal(int lo, int mid, int hi, int flags)
{
if ((flags & ~(SignMask | ScaleMask)) == 0 && (flags & ScaleMask) <= (28 << 16))
{
this.lo = lo;
this.mid = mid;
this.hi = hi;
this.flags = flags;
return;
}
throw new ArgumentException(SR.Arg_DecBitCtor);
}
// Returns the absolute value of the given Decimal. If d is
// positive, the result is d. If d is negative, the result
// is -d.
//
internal static Decimal Abs(Decimal d)
{
return new Decimal(d.lo, d.mid, d.hi, (int)(d.uflags & ~SignMask));
}
// Adds two Decimal values.
//
public static Decimal Add(Decimal d1, Decimal d2)
{
DecCalc.VarDecAdd(ref d1, ref d2);
return d1;
}
// Rounds a Decimal to an integer value. The Decimal argument is rounded
// towards positive infinity.
public static Decimal Ceiling(Decimal d)
{
return (-(Decimal.Floor(-d)));
}
// Compares two Decimal values, returning an integer that indicates their
// relationship.
//
public static int Compare(Decimal d1, Decimal d2)
{
return DecCalc.VarDecCmp(ref d1, ref d2);
}
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type Decimal, this method throws an ArgumentException.
//
public int CompareTo(Object value)
{
if (value == null)
return 1;
if (!(value is Decimal))
throw new ArgumentException(SR.Arg_MustBeDecimal);
Decimal other = (Decimal)value;
return DecCalc.VarDecCmp(ref this, ref other);
}
public int CompareTo(Decimal value)
{
return DecCalc.VarDecCmp(ref this, ref value);
}
// Divides two Decimal values.
//
public static Decimal Divide(Decimal d1, Decimal d2)
{
DecCalc.VarDecDiv(ref d1, ref d2);
return d1;
}
// Checks if this Decimal is equal to a given object. Returns true
// if the given object is a boxed Decimal and its value is equal to the
// value of this Decimal. Returns false otherwise.
//
public override bool Equals(Object value)
{
if (value is Decimal)
{
Decimal other = (Decimal)value;
return DecCalc.VarDecCmp(ref this, ref other) == 0;
}
return false;
}
public bool Equals(Decimal value)
{
return DecCalc.VarDecCmp(ref this, ref value) == 0;
}
// Returns the hash code for this Decimal.
//
public unsafe override int GetHashCode()
{
double dbl = DecCalc.VarR8FromDec(ref this);
if (dbl == 0.0)
// Ensure 0 and -0 have the same hash code
return 0;
// conversion to double is lossy and produces rounding errors so we mask off the lowest 4 bits
//
// For example these two numerically equal decimals with different internal representations produce
// slightly different results when converted to double:
//
// decimal a = new decimal(new int[] { 0x76969696, 0x2fdd49fa, 0x409783ff, 0x00160000 });
// => (decimal)1999021.176470588235294117647000000000 => (double)1999021.176470588
// decimal b = new decimal(new int[] { 0x3f0f0f0f, 0x1e62edcc, 0x06758d33, 0x00150000 });
// => (decimal)1999021.176470588235294117647000000000 => (double)1999021.1764705882
//
return (int)(((((uint*)&dbl)[0]) & 0xFFFFFFF0) ^ ((uint*)&dbl)[1]);
}
// Compares two Decimal values for equality. Returns true if the two
// Decimal values are equal, or false if they are not equal.
//
public static bool Equals(Decimal d1, Decimal d2)
{
return DecCalc.VarDecCmp(ref d1, ref d2) == 0;
}
// Rounds a Decimal to an integer value. The Decimal argument is rounded
// towards negative infinity.
//
public static Decimal Floor(Decimal d)
{
DecCalc.VarDecInt(ref d);
return d;
}
// Converts this Decimal to a string. The resulting string consists of an
// optional minus sign ("-") followed to a sequence of digits ("0" - "9"),
// optionally followed by a decimal point (".") and another sequence of
// digits.
//
public override String ToString()
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatDecimal(this, null, null);
}
public String ToString(String format)
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatDecimal(this, format, null);
}
public String ToString(IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatDecimal(this, null, provider);
}
public String ToString(String format, IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatDecimal(this, format, provider);
}
// Converts a string to a Decimal. The string must consist of an optional
// minus sign ("-") followed by a sequence of digits ("0" - "9"). The
// sequence of digits may optionally contain a single decimal point (".")
// character. Leading and trailing whitespace characters are allowed.
// Parse also allows a currency symbol, a trailing negative sign, and
// parentheses in the number.
//
public static Decimal Parse(String s)
{
return FormatProvider.ParseDecimal(s, NumberStyles.Number, null);
}
internal const NumberStyles InvalidNumberStyles = ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite
| NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign
| NumberStyles.AllowParentheses | NumberStyles.AllowDecimalPoint
| NumberStyles.AllowThousands | NumberStyles.AllowExponent
| NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier);
internal static void ValidateParseStyleFloatingPoint(NumberStyles style)
{
// Check for undefined flags
if ((style & InvalidNumberStyles) != 0)
{
throw new ArgumentException(SR.Argument_InvalidNumberStyles, nameof(style));
}
Contract.EndContractBlock();
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{ // Check for hex number
throw new ArgumentException(SR.Arg_HexStyleNotSupported);
}
}
public static Decimal Parse(String s, NumberStyles style)
{
ValidateParseStyleFloatingPoint(style);
return FormatProvider.ParseDecimal(s, style, null);
}
public static Decimal Parse(String s, IFormatProvider provider)
{
return FormatProvider.ParseDecimal(s, NumberStyles.Number, provider);
}
public static Decimal Parse(String s, NumberStyles style, IFormatProvider provider)
{
ValidateParseStyleFloatingPoint(style);
return FormatProvider.ParseDecimal(s, style, provider);
}
public static Boolean TryParse(String s, out Decimal result)
{
return FormatProvider.TryParseDecimal(s, NumberStyles.Number, null, out result);
}
public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Decimal result)
{
ValidateParseStyleFloatingPoint(style);
return FormatProvider.TryParseDecimal(s, style, provider, out result);
}
// Returns a binary representation of a Decimal. The return value is an
// integer array with four elements. Elements 0, 1, and 2 contain the low,
// middle, and high 32 bits of the 96-bit integer part of the Decimal.
// Element 3 contains the scale factor and sign of the Decimal: bits 0-15
// (the lower word) are unused; bits 16-23 contain a value between 0 and
// 28, indicating the power of 10 to divide the 96-bit integer part by to
// produce the Decimal value; bits 24-30 are unused; and finally bit 31
// indicates the sign of the Decimal value, 0 meaning positive and 1
// meaning negative.
//
public static int[] GetBits(Decimal d)
{
return new int[] { d.lo, d.mid, d.hi, d.flags };
}
internal static void GetBytes(Decimal d, byte[] buffer)
{
Debug.Assert((buffer != null && buffer.Length >= 16), "[GetBytes]buffer != null && buffer.Length >= 16");
buffer[0] = (byte)d.lo;
buffer[1] = (byte)(d.lo >> 8);
buffer[2] = (byte)(d.lo >> 16);
buffer[3] = (byte)(d.lo >> 24);
buffer[4] = (byte)d.mid;
buffer[5] = (byte)(d.mid >> 8);
buffer[6] = (byte)(d.mid >> 16);
buffer[7] = (byte)(d.mid >> 24);
buffer[8] = (byte)d.hi;
buffer[9] = (byte)(d.hi >> 8);
buffer[10] = (byte)(d.hi >> 16);
buffer[11] = (byte)(d.hi >> 24);
buffer[12] = (byte)d.flags;
buffer[13] = (byte)(d.flags >> 8);
buffer[14] = (byte)(d.flags >> 16);
buffer[15] = (byte)(d.flags >> 24);
}
// Returns the larger of two Decimal values.
//
internal static Decimal Max(Decimal d1, Decimal d2)
{
return Compare(d1, d2) >= 0 ? d1 : d2;
}
// Returns the smaller of two Decimal values.
//
internal static Decimal Min(Decimal d1, Decimal d2)
{
return Compare(d1, d2) < 0 ? d1 : d2;
}
public static Decimal Remainder(Decimal d1, Decimal d2)
{
return DecCalc.VarDecMod(ref d1, ref d2);
}
// Multiplies two Decimal values.
//
public static Decimal Multiply(Decimal d1, Decimal d2)
{
Decimal decRes;
DecCalc.VarDecMul(ref d1, ref d2, out decRes);
return decRes;
}
// Returns the negated value of the given Decimal. If d is non-zero,
// the result is -d. If d is zero, the result is zero.
//
public static Decimal Negate(Decimal d)
{
return new Decimal(d.lo, d.mid, d.hi, (int)(d.uflags ^ SignMask));
}
// Rounds a Decimal value to a given number of decimal places. The value
// given by d is rounded to the number of decimal places given by
// decimals. The decimals argument must be an integer between
// 0 and 28 inclusive.
//
// By default a mid-point value is rounded to the nearest even number. If the mode is
// passed in, it can also round away from zero.
public static Decimal Round(Decimal d)
{
return Round(d, 0);
}
public static Decimal Round(Decimal d, int decimals)
{
Decimal result = new Decimal();
if (decimals < 0 || decimals > 28)
throw new ArgumentOutOfRangeException(nameof(decimals), SR.ArgumentOutOfRange_DecimalRound);
DecCalc.VarDecRound(ref d, decimals, ref result);
d = result;
return d;
}
public static Decimal Round(Decimal d, MidpointRounding mode)
{
return Round(d, 0, mode);
}
public static Decimal Round(Decimal d, int decimals, MidpointRounding mode)
{
if (decimals < 0 || decimals > 28)
throw new ArgumentOutOfRangeException(nameof(decimals), SR.ArgumentOutOfRange_DecimalRound);
if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero)
throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, "MidpointRounding"), nameof(mode));
Contract.EndContractBlock();
if (mode == MidpointRounding.ToEven)
{
Decimal result = new Decimal();
DecCalc.VarDecRound(ref d, decimals, ref result);
d = result;
}
else
{
DecCalc.InternalRoundFromZero(ref d, decimals);
}
return d;
}
// Subtracts two Decimal values.
//
public static Decimal Subtract(Decimal d1, Decimal d2)
{
DecCalc.VarDecSub(ref d1, ref d2);
return d1;
}
// Converts a Decimal to an unsigned byte. The Decimal value is rounded
// towards zero to the nearest integer value, and the result of this
// operation is returned as a byte.
//
public static byte ToByte(Decimal value)
{
uint temp;
try
{
temp = ToUInt32(value);
}
catch (OverflowException e)
{
throw new OverflowException(SR.Overflow_Byte, e);
}
if (temp < Byte.MinValue || temp > Byte.MaxValue) throw new OverflowException(SR.Overflow_Byte);
return (byte)temp;
}
// Converts a Decimal to a signed byte. The Decimal value is rounded
// towards zero to the nearest integer value, and the result of this
// operation is returned as a byte.
//
[CLSCompliant(false)]
public static sbyte ToSByte(Decimal value)
{
int temp;
try
{
temp = ToInt32(value);
}
catch (OverflowException e)
{
throw new OverflowException(SR.Overflow_SByte, e);
}
if (temp < SByte.MinValue || temp > SByte.MaxValue) throw new OverflowException(SR.Overflow_SByte);
return (sbyte)temp;
}
// Converts a Decimal to a short. The Decimal value is
// rounded towards zero to the nearest integer value, and the result of
// this operation is returned as a short.
//
public static short ToInt16(Decimal value)
{
int temp;
try
{
temp = ToInt32(value);
}
catch (OverflowException e)
{
throw new OverflowException(SR.Overflow_Int16, e);
}
if (temp < Int16.MinValue || temp > Int16.MaxValue) throw new OverflowException(SR.Overflow_Int16);
return (short)temp;
}
// Converts a Decimal to a double. Since a double has fewer significant
// digits than a Decimal, this operation may produce round-off errors.
//
public static double ToDouble(Decimal d)
{
return DecCalc.VarR8FromDec(ref d);
}
// Converts a Decimal to an integer. The Decimal value is rounded towards
// zero to the nearest integer value, and the result of this operation is
// returned as an integer.
//
public static int ToInt32(Decimal d)
{
if (d.Scale != 0) DecCalc.VarDecFix(ref d);
if (d.hi == 0 && d.mid == 0)
{
int i = d.lo;
if (!d.Sign)
{
if (i >= 0) return i;
}
else
{
i = -i;
if (i <= 0) return i;
}
}
throw new OverflowException(SR.Overflow_Int32);
}
// Converts a Decimal to a long. The Decimal value is rounded towards zero
// to the nearest integer value, and the result of this operation is
// returned as a long.
//
public static long ToInt64(Decimal d)
{
if (d.Scale != 0) DecCalc.VarDecFix(ref d);
if (d.uhi == 0)
{
long l = d.ulo | (long)(int)d.umid << 32;
if (!d.Sign)
{
if (l >= 0) return l;
}
else
{
l = -l;
if (l <= 0) return l;
}
}
throw new OverflowException(SR.Overflow_Int64);
}
// Converts a Decimal to an ushort. The Decimal
// value is rounded towards zero to the nearest integer value, and the
// result of this operation is returned as an ushort.
//
[CLSCompliant(false)]
public static ushort ToUInt16(Decimal value)
{
uint temp;
try
{
temp = ToUInt32(value);
}
catch (OverflowException e)
{
throw new OverflowException(SR.Overflow_UInt16, e);
}
if (temp < UInt16.MinValue || temp > UInt16.MaxValue) throw new OverflowException(SR.Overflow_UInt16);
return (ushort)temp;
}
// Converts a Decimal to an unsigned integer. The Decimal
// value is rounded towards zero to the nearest integer value, and the
// result of this operation is returned as an unsigned integer.
//
[CLSCompliant(false)]
public static uint ToUInt32(Decimal d)
{
if (d.Scale != 0) DecCalc.VarDecFix(ref d);
if (d.uhi == 0 && d.umid == 0)
{
if (!d.Sign || d.ulo == 0)
return d.ulo;
}
throw new OverflowException(SR.Overflow_UInt32);
}
// Converts a Decimal to an unsigned long. The Decimal
// value is rounded towards zero to the nearest integer value, and the
// result of this operation is returned as a long.
//
[CLSCompliant(false)]
public static ulong ToUInt64(Decimal d)
{
if (d.Scale != 0) DecCalc.VarDecFix(ref d);
if (d.uhi == 0)
{
ulong l = (ulong)d.ulo | ((ulong)d.umid << 32);
if (!d.Sign || l == 0)
return l;
}
throw new OverflowException(SR.Overflow_UInt64);
}
// Converts a Decimal to a float. Since a float has fewer significant
// digits than a Decimal, this operation may produce round-off errors.
//
public static float ToSingle(Decimal d)
{
return DecCalc.VarR4FromDec(ref d);
}
// Truncates a Decimal to an integer value. The Decimal argument is rounded
// towards zero to the nearest integer value, corresponding to removing all
// digits after the decimal point.
//
public static Decimal Truncate(Decimal d)
{
DecCalc.VarDecFix(ref d);
return d;
}
public static implicit operator Decimal(byte value)
{
return new Decimal(value);
}
[CLSCompliant(false)]
public static implicit operator Decimal(sbyte value)
{
return new Decimal(value);
}
public static implicit operator Decimal(short value)
{
return new Decimal(value);
}
[CLSCompliant(false)]
public static implicit operator Decimal(ushort value)
{
return new Decimal(value);
}
public static implicit operator Decimal(char value)
{
return new Decimal(value);
}
public static implicit operator Decimal(int value)
{
return new Decimal(value);
}
[CLSCompliant(false)]
public static implicit operator Decimal(uint value)
{
return new Decimal(value);
}
public static implicit operator Decimal(long value)
{
return new Decimal(value);
}
[CLSCompliant(false)]
public static implicit operator Decimal(ulong value)
{
return new Decimal(value);
}
public static explicit operator Decimal(float value)
{
return new Decimal(value);
}
public static explicit operator Decimal(double value)
{
return new Decimal(value);
}
public static explicit operator byte(Decimal value)
{
return ToByte(value);
}
[CLSCompliant(false)]
public static explicit operator sbyte(Decimal value)
{
return ToSByte(value);
}
public static explicit operator char(Decimal value)
{
UInt16 temp;
try
{
temp = ToUInt16(value);
}
catch (OverflowException e)
{
throw new OverflowException(SR.Overflow_Char, e);
}
return (char)temp;
}
public static explicit operator short(Decimal value)
{
return ToInt16(value);
}
[CLSCompliant(false)]
public static explicit operator ushort(Decimal value)
{
return ToUInt16(value);
}
public static explicit operator int(Decimal value)
{
return ToInt32(value);
}
[CLSCompliant(false)]
public static explicit operator uint(Decimal value)
{
return ToUInt32(value);
}
public static explicit operator long(Decimal value)
{
return ToInt64(value);
}
[CLSCompliant(false)]
public static explicit operator ulong(Decimal value)
{
return ToUInt64(value);
}
public static explicit operator float(Decimal value)
{
return ToSingle(value);
}
public static explicit operator double(Decimal value)
{
return ToDouble(value);
}
public static Decimal operator +(Decimal d)
{
return d;
}
public static Decimal operator -(Decimal d)
{
return Negate(d);
}
public static Decimal operator ++(Decimal d)
{
return Add(d, One);
}
public static Decimal operator --(Decimal d)
{
return Subtract(d, One);
}
public static Decimal operator +(Decimal d1, Decimal d2)
{
return Add(d1, d2);
}
public static Decimal operator -(Decimal d1, Decimal d2)
{
return Subtract(d1, d2);
}
public static Decimal operator *(Decimal d1, Decimal d2)
{
return Multiply(d1, d2);
}
public static Decimal operator /(Decimal d1, Decimal d2)
{
return Divide(d1, d2);
}
public static Decimal operator %(Decimal d1, Decimal d2)
{
return Remainder(d1, d2);
}
public static bool operator ==(Decimal d1, Decimal d2)
{
return DecCalc.VarDecCmp(ref d1, ref d2) == 0;
}
public static bool operator !=(Decimal d1, Decimal d2)
{
return DecCalc.VarDecCmp(ref d1, ref d2) != 0;
}
public static bool operator <(Decimal d1, Decimal d2)
{
return DecCalc.VarDecCmp(ref d1, ref d2) < 0;
}
public static bool operator <=(Decimal d1, Decimal d2)
{
return DecCalc.VarDecCmp(ref d1, ref d2) <= 0;
}
public static bool operator >(Decimal d1, Decimal d2)
{
return DecCalc.VarDecCmp(ref d1, ref d2) > 0;
}
public static bool operator >=(Decimal d1, Decimal d2)
{
return DecCalc.VarDecCmp(ref d1, ref d2) >= 0;
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.Decimal;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(this);
}
char IConvertible.ToChar(IFormatProvider provider)
{
throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Decimal", "Char"));
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(this);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(this);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(this);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(this);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(this);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(this);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(this);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(this);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(this);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(this);
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return this;
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Decimal", "DateTime"));
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Compute.Fluent
{
using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.Graph.RBAC.Fluent;
using Microsoft.Azure.Management.Msi.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Utility class to set Managed Service Identity (MSI) and MSI related resources for a virtual machine.
/// </summary>
internal partial class VirtualMachineMsiHelper : RoleAssignmentHelper
{
private ISet<string> creatableIdentityKeys;
private IDictionary<string, VirtualMachineIdentityUserAssignedIdentitiesValue> userAssignedIdentities;
private VirtualMachineImpl virtualMachine;
/// <summary>
/// Creates VirtualMachineMsiHelper.
/// </summary>
/// <param name="rbacManager">The graph rbac manager.</param>
internal VirtualMachineMsiHelper(IGraphRbacManager rbacManager, VirtualMachineImpl virtualMachine)
: base(rbacManager, new VmIdProvider(virtualMachine))
{
this.virtualMachine = virtualMachine;
this.creatableIdentityKeys = new HashSet<string>();
this.userAssignedIdentities = new Dictionary<string, VirtualMachineIdentityUserAssignedIdentitiesValue>();
}
internal void Clear()
{
this.userAssignedIdentities.Clear();
}
internal void HandleExternalIdentities()
{
if (this.userAssignedIdentities.Any())
{
this.virtualMachine.Inner.Identity.UserAssignedIdentities = this.userAssignedIdentities;
}
}
internal void HandleExternalIdentities(VirtualMachineUpdate vmUpdate)
{
if (this.HandleRemoveAllExternalIdentitiesCase(vmUpdate))
{
return;
}
else
{
// At this point one of the following condition is met:
//
// 1. User don't want touch the 'VM.Identity.UserAssignedIdentities' property
// [this.userAssignedIdentities.Empty() == true]
// 2. User want to add some identities to 'VM.Identity.UserAssignedIdentities'
// [this.userAssignedIdentities.Empty() == false and this.virtualMachine.Inner().Identity() != null]
// 3. User want to remove some (not all) identities in 'VM.Identity.UserAssignedIdentities'
// [this.userAssignedIdentities.Empty() == false and this.virtualMachine.Inner().Identity() != null]
// Note: The scenario where this.virtualMachine.Inner().Identity() is null in #3 is already handled in
// handleRemoveAllExternalIdentitiesCase method
// 4. User want to add and remove (all or subset) some identities in 'VM.Identity.UserAssignedIdentities'
// [this.userAssignedIdentities.Empty() == false and this.virtualMachine.Inner().Identity() != null]
//
var currentIdentity = this.virtualMachine.Inner.Identity;
vmUpdate.Identity = currentIdentity;
if (this.userAssignedIdentities.Any())
{
// At this point its guaranteed that 'currentIdentity' is not null so vmUpdate.Identity() is.
vmUpdate.Identity.UserAssignedIdentities = this.userAssignedIdentities;
}
else
{
// User don't want to touch 'VM.Identity.UserAssignedIdentities' property
if (currentIdentity != null)
{
// and currently there is identity exists or user want to manipulate some other properties of
// identity, set identities to null so that it won't send over wire.
currentIdentity.UserAssignedIdentities = null;
}
}
}
}
internal void ProcessCreatedExternalIdentities()
{
foreach (var key in this.creatableIdentityKeys)
{
var identity = (IIdentity)this.virtualMachine.CreatorTaskGroup.CreatedResource(key);
this.userAssignedIdentities[identity.Id] = new VirtualMachineIdentityUserAssignedIdentitiesValue();
}
this.creatableIdentityKeys.Clear();
}
/// <summary>
/// Specifies that given identity should be set as one of the External Managed Service Identity
/// of the virtual machine.
/// </summary>
/// <param name="identity">An identity to associate.</param>
/// <return>VirtualMachineMsiHandler.</return>
internal VirtualMachineMsiHelper WithExistingExternalManagedServiceIdentity(IIdentity identity)
{
this.InitVMIdentity(Fluent.Models.ResourceIdentityType.UserAssigned);
this.userAssignedIdentities[identity.Id] = new VirtualMachineIdentityUserAssignedIdentitiesValue();
return this;
}
/// <summary>
/// Specifies that Local Managed Service Identity needs to be enabled in the virtual machine.
/// If MSI extension is not already installed then it will be installed with access token
/// port as 50342.
/// </summary>
/// <return>VirtualMachineMsiHandler.</return>
internal VirtualMachineMsiHelper WithLocalManagedServiceIdentity()
{
this.InitVMIdentity(Fluent.Models.ResourceIdentityType.SystemAssigned);
return this;
}
/// <summary>
/// Specifies that given identity should be set as one of the External Managed Service Identity
/// of the virtual machine.
/// </summary>
/// <param name="creatableIdentity">Yet-to-be-created identity to be associated with the virtual machine.</param>
/// <return>VirtualMachineMsiHandler.</return>
internal VirtualMachineMsiHelper WithNewExternalManagedServiceIdentity(ICreatable<IIdentity> creatableIdentity)
{
if (!this.creatableIdentityKeys.Contains(creatableIdentity.Key))
{
this.InitVMIdentity(Fluent.Models.ResourceIdentityType.UserAssigned);
this.creatableIdentityKeys.Add(creatableIdentity.Key);
((creatableIdentity as IResourceCreator<IHasId>).CreatorTaskGroup).Merge(this.virtualMachine.CreatorTaskGroup);
}
return this;
}
/// <summary>
/// Specifies that given identity should be removed from the list of External Managed Service Identity
/// associated with the virtual machine machine.
/// </summary>
/// <param name="identityId">Resource id of the identity.</param>
/// <return>VirtualMachineMsiHandler.</return>
internal VirtualMachineMsiHelper WithoutExternalManagedServiceIdentity(string identityId)
{
this.userAssignedIdentities[identityId] = null;
return this;
}
/// <summary>
/// Specifies that Local Managed Service Identity needs to be disabled in the virtual machine.
/// </summary>
/// <return>VirtualMachineMsiHandler.</return>
internal VirtualMachineMsiHelper WithoutLocalManagedServiceIdentity()
{
if (this.virtualMachine.Inner.Identity == null ||
this.virtualMachine.Inner.Identity.Type == null ||
this.virtualMachine.Inner.Identity.Type.Equals(ResourceIdentityTypeEnumExtension.ToSerializedValue(Models.ResourceIdentityType.None), StringComparison.OrdinalIgnoreCase) ||
this.virtualMachine.Inner.Identity.Type.Equals(ResourceIdentityTypeEnumExtension.ToSerializedValue(Models.ResourceIdentityType.UserAssigned), StringComparison.OrdinalIgnoreCase))
{
return this;
}
else if (this.virtualMachine.Inner.Identity.Type.Equals(ResourceIdentityTypeEnumExtension.ToSerializedValue(Models.ResourceIdentityType.SystemAssigned), StringComparison.OrdinalIgnoreCase))
{
this.virtualMachine.Inner.Identity.Type = ResourceIdentityTypeEnumExtension.ToSerializedValue(Models.ResourceIdentityType.None);
}
else if (this.virtualMachine.Inner.Identity.Type.Equals(ResourceIdentityTypeEnumExtension.ToSerializedValue(Models.ResourceIdentityType.SystemAssignedUserAssigned), StringComparison.OrdinalIgnoreCase))
{
this.virtualMachine.Inner.Identity.Type = ResourceIdentityTypeEnumExtension.ToSerializedValue(Models.ResourceIdentityType.UserAssigned);
}
return this;
}
/// <summary>
/// Method that handle the case where user request indicates all it want to do is remove all identities associated
/// with the virtual machine.
/// </summary>
/// <param name="vmUpdate">The vm update payload model.</param>
/// <return>True if user indented to remove all the identities.</return>
private bool HandleRemoveAllExternalIdentitiesCase(VirtualMachineUpdate vmUpdate)
{
if (this.userAssignedIdentities.Any())
{
int rmCount = 0;
foreach(var v in this.userAssignedIdentities.Values)
{
if (v == null)
{
rmCount++;
}
else
{
break;
}
}
var containsRemoveOnly = rmCount > 0 && rmCount == this.userAssignedIdentities.Count;
// Check if user request contains only request for removal of identities.
if (containsRemoveOnly)
{
var currentIds = new HashSet<string>();
var currentIdentity = this.virtualMachine.Inner.Identity;
if (currentIdentity != null && currentIdentity.UserAssignedIdentities != null)
{
foreach(var id in currentIdentity.UserAssignedIdentities.Keys)
{
currentIds.Add(id.ToLower());
}
}
var removeIds = new HashSet<string>();
foreach (var entrySet in this.userAssignedIdentities)
{
if (entrySet.Value == null)
{
removeIds.Add(entrySet.Key.ToLower());
}
}
// If so check user want to remove all the identities
var removeAllCurrentIds = currentIds.Count == removeIds.Count && !removeIds.Any(id => !currentIds.Contains(id)); // Java part looks like this -> && currentIds.ContainsAll(removeIds);
if (removeAllCurrentIds)
{
// If so adjust the identity type [Setting type to SYSTEM_ASSIGNED orNONE will remove all the identities]
if (currentIdentity == null || currentIdentity.Type == null)
{
vmUpdate.Identity = new VirtualMachineIdentity { Type = ResourceIdentityTypeEnumExtension.ToSerializedValue(Models.ResourceIdentityType.None) };
}
else if (currentIdentity.Type.Equals(ResourceIdentityTypeEnumExtension.ToSerializedValue(Models.ResourceIdentityType.SystemAssignedUserAssigned), StringComparison.OrdinalIgnoreCase))
{
vmUpdate.Identity = currentIdentity;
vmUpdate.Identity.Type = ResourceIdentityTypeEnumExtension.ToSerializedValue(Models.ResourceIdentityType.SystemAssigned);
}
else if (currentIdentity.Type.Equals(ResourceIdentityTypeEnumExtension.ToSerializedValue(Models.ResourceIdentityType.UserAssigned), StringComparison.OrdinalIgnoreCase))
{
vmUpdate.Identity = currentIdentity;
vmUpdate.Identity.Type = ResourceIdentityTypeEnumExtension.ToSerializedValue(Models.ResourceIdentityType.None);
}
// and set identities property in the payload model to null so that it won't be sent
vmUpdate.Identity.UserAssignedIdentities = null;
return true;
}
else
{
// Check user is asking to remove identities though there is no identities currently associated
if (currentIds.Count == 0 &&
removeIds.Count != 0 &&
currentIdentity == null)
{
// If so we are in a invalid state but we want to send user input to service and let service
// handle it (ignore or error).
vmUpdate.Identity = new VirtualMachineIdentity { Type = ResourceIdentityTypeEnumExtension.ToSerializedValue(Models.ResourceIdentityType.None) };
vmUpdate.Identity.UserAssignedIdentities = null;
return true;
}
}
}
}
return false;
}
/// <summary>
/// Initialize VM's identity property.
/// </summary>
/// <param name="identityType">The identity type to set.</param>
private void InitVMIdentity(Fluent.Models.ResourceIdentityType identityType)
{
if (!identityType.Equals(Models.ResourceIdentityType.UserAssigned) &&
!identityType.Equals(Models.ResourceIdentityType.SystemAssigned))
{
throw new ArgumentException("Invalid argument: " + identityType);
}
var virtualMachineInner = this.virtualMachine.Inner;
if (virtualMachineInner.Identity == null)
{
virtualMachineInner.Identity = new VirtualMachineIdentity();
}
if (virtualMachineInner.Identity.Type == null ||
virtualMachineInner.Identity.Type.Equals(ResourceIdentityTypeEnumExtension.ToSerializedValue(Models.ResourceIdentityType.None), StringComparison.OrdinalIgnoreCase) ||
virtualMachineInner.Identity.Type.Equals(ResourceIdentityTypeEnumExtension.ToSerializedValue(identityType), StringComparison.OrdinalIgnoreCase))
{
virtualMachineInner.Identity.Type = ResourceIdentityTypeEnumExtension.ToSerializedValue(identityType);
}
else
{
virtualMachineInner.Identity.Type = ResourceIdentityTypeEnumExtension.ToSerializedValue(Models.ResourceIdentityType.SystemAssignedUserAssigned);
}
}
/// <summary>
/// Gets the MSI identity type.
/// </summary>
/// <param name="inner">the virtual machine inner</param>
/// <returns>the MSI identity type</returns>
internal static Models.ResourceIdentityType? ManagedServiceIdentityType(VirtualMachineInner inner)
{
if (inner.Identity != null)
{
return ResourceIdentityTypeEnumExtension.ParseResourceIdentityType(inner.Identity.Type);
}
return null;
}
}
internal class VmIdProvider : IIdProvider
{
private readonly VirtualMachineImpl vm;
internal VmIdProvider(VirtualMachineImpl vm)
{
this.vm = vm;
}
public string PrincipalId
{
get
{
if (this.vm.Inner != null && this.vm.Inner.Identity != null)
{
return this.vm.Inner.Identity.PrincipalId;
}
else
{
return null;
}
}
}
public string ResourceId
{
get
{
if (this.vm.Inner != null)
{
return this.vm.Inner.Id;
}
else
{
return null;
}
}
}
}
}
| |
// 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.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using mshtml;
using OpenLiveWriter.ApplicationFramework.Skinning;
using OpenLiveWriter.BlogClient;
using OpenLiveWriter.BlogClient.Detection;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.Marketization;
using OpenLiveWriter.Extensibility.BlogClient;
using OpenLiveWriter.HtmlEditor;
using OpenLiveWriter.HtmlParser.Parser;
using OpenLiveWriter.Localization;
using OpenLiveWriter.ApplicationFramework;
using OpenLiveWriter.Controls;
using OpenLiveWriter.Mshtml;
using OpenLiveWriter.PostEditor.Commands;
using OpenLiveWriter.PostEditor.PostPropertyEditing;
//using OpenLiveWriter.SpellChecker;
//using OpenLiveWriter.SpellChecker.NLG;
// @RIBBON TODO: Cleanly remove obsolete code
namespace OpenLiveWriter.PostEditor.PostHtmlEditing
{
internal class BlogPostHtmlEditor : OpenLiveWriter.PostEditor.ContentEditor, INewCategoryContext, IBlogPostEditor
{
private string instanceId = Guid.NewGuid().ToString();
// The panel that holds blog this band, formatting bar, editor, tabs, and general post properties
private Panel _editorContainer;
// Post properties tray, BlogPostHtmlEditor is in charge of pushing IBlogPostEditor calls through to it
private PostPropertiesBandControl _postPropertyEditor;
// Edit / Preview / Source tabs, and status bar
private PostEditorFooter _postEditorFooter;
protected SemanticHtmlGalleryCommand commandSemanticHtml;
// Formatting bar
//private CommandBarControl _commandBarControl;
//private EditorCommandBarLightweightControl _editorCommandBar = new EditorCommandBarLightweightControl();
private Command commandInsertExtendedEntry;
private Command commandViewUseStyles;
private BlogPostHtmlEditor(IMainFrameWindow mainFrameWindow, Panel panelEditorContainer, IBlogPostEditingSite postEditingSite)
: base(mainFrameWindow, panelEditorContainer, postEditingSite, new BlogPostHtmlEditorControl.BlogPostHtmlEditorSecurityManager(), new BlogPostTemplateStrategy(), MshtmlOptions.DEFAULT_DLCTL)
{
_editorContainer = panelEditorContainer;
//InitializeCommandBar(commandBarDefinition);
//_editorCommandBar.VerticalLineX = (BidiHelper.IsRightToLeft ? _htmlEditorSidebarHost.Right - 1 : _htmlEditorSidebarHost.Left);
//_editorCommandBar.DrawVerticalLine = _htmlEditorSidebarHost.Visible;
panelEditorContainer.SizeChanged += new EventHandler(editorContainer_SizeChanged);
_htmlEditorSidebarHost.VisibleChanged += new EventHandler(_htmlEditorSidebarHost_VisibleChanged);
CreateTabs();
InitializePropertyEditors();
ApplySpellingSettings(null, EventArgs.Empty);
//ToDo: OLW Spell Checker
//SpellingSettings.SpellingSettingsChanged += ApplySpellingSettings;
EditorLoaded += new EventHandler(BlogPostHtmlEditor_EditorLoaded);
FixCommandEvent += new FixCommendsDelegate(BlogPostHtmlEditor_FixCommandEvent);
}
public override void Dispose()
{
//ToDo: OLW Spell Checker
//SpellingSettings.SpellingSettingsChanged -= ApplySpellingSettings;
base.Dispose();
}
public override void OnEditorAccountChanged(IEditorAccount newEditorAccount)
{
//ToDo: OLW Spell Checker
// Crashes here: return value of CommandManager.Get(CommandId.IgnoreOnce) is null
Command cmd = CommandManager.Get(CommandId.IgnoreOnce);
if (cmd != null)
{
cmd.On = GlobalEditorOptions.SupportsFeature(ContentEditorFeature.SpellCheckIgnoreOnce);
}
base.OnEditorAccountChanged(newEditorAccount);
// If any of these are null(or more likely all of them all null) then the editor has not been
// fully loaded. This will get called 1 time before the editor is fully loaded, this is
// why SetAccountId is called at the end of Initialize()
if (commandSemanticHtml != null && _currentEditor != null)
commandSemanticHtml.SetAccountId(_currentBlog.Id, IsRTLTemplate, false);
}
private void ApplySpellingSettings(object sender, EventArgs args)
{
//ToDo: OLW Spell Checker
//SpellingCheckerLanguage language = SpellingSettings.Language;
//if (language == SpellingCheckerLanguage.None)
//{
// No language selected. Disable the speller and return.
DisableSpelling();
return;
//ToDo: OLW Spell Checker
//ToDo: OLW Spell Checker
// SpellingLanguageEntry languageEntry = SpellingSettings.GetInstalledLanguage(language);
//uint sobit = 0;
//if (SpellingSettings.IgnoreUppercase)
// sobit |= (uint)SpellerOptionBit.IgnoreAllCaps;
//if (SpellingSettings.IgnoreWordsWithNumbers)
// sobit |= (uint)SpellerOptionBit.IgnoreMixedDigits;
//sobit |= (uint)SpellerOptionBit.IgnoreSingleLetter;
//List<string> lexAbsPaths = new List<string>(languageEntry.CSAPILex.Length);
//foreach (string path in languageEntry.CSAPILex)
// lexAbsPaths.Add(Path.Combine(SpellingSettings.DictionaryPath, path));
//string engineDllAbsPath = Path.Combine(SpellingSettings.DictionaryPath, languageEntry.CSAPIEngine);
//SetSpellingOptions(engineDllAbsPath,
// languageEntry.LCID,
// lexAbsPaths.ToArray(),
// SpellingSettings.UserDictionaryPath,
// sobit,
// SpellingSettings.EnableAutoCorrect);
}
void BlogPostHtmlEditor_FixCommandEvent(bool fullyEditableActive)
{
commandInsertExtendedEntry.Enabled = SupportsExtendedEntries && fullyEditableActive;
}
void commandSemanticHtml_ExecuteWithArgs(object sender, ExecuteEventHandlerArgs args)
{
int selectedIndex = args.GetInt(CommandId.SemanticHtmlGallery.ToString());
IHtmlFormattingStyle style = commandSemanticHtml.Items[selectedIndex] as IHtmlFormattingStyle;
ApplyHtmlFormattingStyle(style);
}
void BlogPostHtmlEditor_EditorLoaded(object sender, EventArgs e)
{
if (CurrentEditingMode == EditingMode.PlainText)
{
// Somehow the editor changed itself to plain text, dont change the tab
Debug.Fail("PlainText mode should not be used inside of BlogPostHtmlEditor.");
return;
}
if (CurrentEditingMode == EditingMode.Wysiwyg)
_postEditorFooter.SelectTab(0);
else if (CurrentEditingMode == EditingMode.Preview)
_postEditorFooter.SelectTab(1);
else
_postEditorFooter.SelectTab(2);
}
public void Initialize(IBlogPostEditingContext editingContext, IBlogClientOptions clientOptions)
{
// this needs to happen before an editor is loaded, it is needed to know if
// if the blog this band should show or not.
bool firstTimeInitialization = _currentEditor == null;
InitDefaultEditorForBlog();
base.Initialize(editingContext, clientOptions, GetStyledHtml(), GetPreviewHtml(), true);
commandSemanticHtml.SetAccountId(_currentBlog.Id, IsRTLTemplate, false);
_postPropertyEditor.Initialize(editingContext, clientOptions);
}
public override void SaveChanges(BlogPost post, BlogPostSaveOptions options)
{
base.SaveChanges(post, options);
_postPropertyEditor.SaveChanges(post, options);
}
private bool CheckTagsReminder()
{
if (!PostEditorSettings.TagReminder)
return true;
bool hasTags;
if (_currentBlog.ClientOptions.SupportsKeywords)
{
hasTags = _postPropertyEditor.HasKeywords;
}
else
{
hasTags = _normalHtmlContentEditor.HasTags;
}
if (hasTags)
return true;
if (DisplayMessage.Show(MessageId.TagReminder, this) == DialogResult.No)
{
return false;
}
return true;
}
public override void OnPublishSucceeded(BlogPost blogPost, PostResult postResult)
{
// delegate to property editor
_postPropertyEditor.OnPublishSucceeded(blogPost, postResult);
IsDirty = false;
}
void INewCategoryContext.NewCategoryAdded(BlogPostCategory newCategory)
{
(_postPropertyEditor as INewCategoryContext).NewCategoryAdded(newCategory);
}
public override bool IsDirty
{
get
{
return base.IsDirty || (_postPropertyEditor != null && _postPropertyEditor.IsDirty);
}
}
public void OnBlogSettingsChanged(bool templateChanged)
{
if (templateChanged)
UpdateTemplateToBlogTheme();
commandSemanticHtml.SetAccountId(_currentBlog.Id, IsRTLTemplate, templateChanged);
UpdateExtendedEntryStatus();
_postPropertyEditor.OnBlogSettingsChanged(templateChanged);
}
private Blog _currentBlog;
public void OnBlogChanged(Blog newBlog)
{
_currentBlog = newBlog;
// save dirty state of current editor
bool isDirty = _currentEditor != null ? _currentEditor.IsDirty : false;
OnEditorAccountChanged(newBlog);
_postPropertyEditor.OnBlogChanged(newBlog);
_editorContainer.DockPadding.Bottom = _postPropertyEditor.Visible ? 0 : 5;
// determine what type of template we should be using for this weblog
if (_currentEditor != null) //if null, then the editors haven't been loaded yet
{
InitDefaultEditorForBlog();
UpdateTemplateToBlogTheme();
}
commandSemanticHtml.SetAccountId(_currentBlog.Id, IsRTLTemplate, false);
// restore dirty state
if (_currentEditor != null)
_currentEditor.IsDirty = isDirty;
}
public void CreateTabs()
{
string[] tabNames = new string[_views.Length];
string[] shortcuts = new string[_views.Length];
for (int i = 0; i < tabNames.Length; i++)
{
tabNames[i] = _views[i].Text;
if (_views[i].Shortcut != Shortcut.None)
shortcuts[i] = KeyboardHelper.FormatShortcutString(_views[i].Shortcut);
}
_postEditorFooter = new PostEditorFooter();
_postEditorFooter.TabNames = tabNames;
_postEditorFooter.Shortcuts = shortcuts;
_postEditorFooter.Dock = DockStyle.Bottom;
_postEditorFooter.SelectedTabChanged += tabsControl_SelectedTabChanged;
_postEditorFooter.SetStatusMessage(Res.Get(StringId.StatusDraftUnsaved));
_editorContainer.Controls.Add(_postEditorFooter);
}
void tabsControl_SelectedTabChanged(object sender, EventArgs args)
{
Command viewCommand = _views[_postEditorFooter.SelectedTabIndex];
if (!viewCommand.Latched)
viewCommand.PerformExecute();
}
public override bool ValidatePublish()
{
// property editors (categories)
if (!_postPropertyEditor.ValidatePublish())
{
return false;
}
if (!CheckTagsReminder())
{
return false;
}
return base.ValidatePublish();
}
void _htmlEditorSidebarHost_VisibleChanged(object sender, EventArgs e)
{
//_editorCommandBar.DrawVerticalLine = _htmlEditorSidebarHost.Visible;
}
public override IStatusBar StatusBar
{
get
{
return new StatusBarShim(this);
}
}
private class StatusBarShim : IStatusBar
{
private readonly BlogPostHtmlEditor parent;
public StatusBarShim(BlogPostHtmlEditor parent)
{
this.parent = parent;
}
public void SetWordCountMessage(string msg)
{
parent._postEditorFooter.SetWordCountMessage(msg);
}
public void PushStatusMessage(string msg)
{
parent._postEditorFooter.PushStatusMessage(msg);
}
public void PopStatusMessage()
{
parent._postEditorFooter.PopStatusMessage();
}
public void SetStatusMessage(string msg)
{
parent._postEditorFooter.SetStatusMessage(msg);
}
}
public static BlogPostHtmlEditor Create(IMainFrameWindow mainFrameWindow, Control editorContainer, IBlogPostEditingSite postEditingSite)
{
Panel panelBase = new Panel();
panelBase.Dock = DockStyle.Fill;
editorContainer.Controls.Add(panelBase);
return new BlogPostHtmlEditor(mainFrameWindow, panelBase, postEditingSite);
}
private void InitializePropertyEditors()
{
_postPropertyEditor = new PostPropertiesBandControl(CommandManager);
_postPropertyEditor.TabStop = true;
_postPropertyEditor.TabIndex = 2;
_postPropertyEditor.Dock = DockStyle.Top;
_postPropertyEditor.AccessibleName = Res.Get(StringId.PropertiesPanel);
_editorContainer.Controls.Add(_postPropertyEditor);
Trace.WriteLine(_postPropertyEditor.Width + " " + _postPropertyEditor.Parent.Width);
}
void editorContainer_SizeChanged(object sender, EventArgs e)
{
//_editorCommandBar.VerticalLineX = (BidiHelper.IsRightToLeft ? _htmlEditorSidebarHost.Right - 1 : _htmlEditorSidebarHost.Left);
}
private void commandUpdateWeblogStyle_Execute(object sender, EventArgs e)
{
if (_postEditingSite.UpdateWeblogTemplate(_currentBlog.Id))
{
if (commandViewUseStyles.Latched)
ReloadEditor();
else
commandViewUseStyles.PerformExecute();
}
}
protected override void InitializeCommands()
{
CommandManager.BeginUpdate();
base.InitializeCommands();
CommandManager.Add(CommandId.UpdateWeblogStyle, commandUpdateWeblogStyle_Execute);
commandViewUseStyles = CommandManager.Add(CommandId.ViewUseStyles, commandViewUseStyles_Execute);
commandSemanticHtml = new SemanticHtmlGalleryCommand(CommandId.SemanticHtmlGallery, _postEditingSite, GetPreviewHtml, CommandManager, _currentEditor as IHtmlEditorComponentContext);
commandSemanticHtml.ExecuteWithArgs += new ExecuteEventHandler(commandSemanticHtml_ExecuteWithArgs);
commandSemanticHtml.ComponentContext = () => _currentEditor as IHtmlEditorComponentContext;
CommandManager.Add(commandSemanticHtml);
commandInsertablePlugins = new InsertablePluginsGalleryCommand();
commandInsertablePlugins.ExecuteWithArgs += new ExecuteEventHandler(commandInsertablePlugins_ExecuteWithArgs);
commandInsertablePlugins.LoadItems();
CommandManager.Add(commandInsertablePlugins);
commandInsertWebImage = new Command(CommandId.WebImage);
commandInsertWebImage.Execute += new EventHandler(commandInsertWebImage_Execute);
CommandManager.Add(commandInsertWebImage);
commandInsertExtendedEntry = CommandManager.Add(CommandId.InsertExtendedEntry, commandInsertExtendedEntry_Execute);
EditorLoaded += new EventHandler(ContentEditor_EditorHtmlReloaded);
// QAT
CommandManager.Add(new GalleryCommand<CommandId>(CommandId.QAT));
// Outspace
CommandManager.Add(new RecentItemsCommand(_postEditingSite));
CommandManager.Add(new GroupCommand(CommandId.InsertImageSplit, CommandManager.Get(CommandId.InsertPictureFromFile)));
// WinLive 181138 - A targetted fix to ensure the InsertVideoSplit command is disabled if we don't support InsertVideo (e.g zh-CN doesn't support video)
// The problem is related to Windows 7 #712524 & #758433 and this is a work around for this particular case.
// The dropdown commands for this (InsertVideoFromFile etc) are already disabled based on the feature support. We explicitly set the state of
// group command here so that it has the right state to begin with (otherwise a switch tab/app is required to refresh).
GroupCommand commandInsertVideoSplit = new GroupCommand(CommandId.InsertVideoSplit, CommandManager.Get(CommandId.InsertVideoFromFile));
commandInsertVideoSplit.Enabled = MarketizationOptions.IsFeatureEnabled(MarketizationOptions.Feature.VideoProviders);
CommandManager.Add(commandInsertVideoSplit);
foreach (CommandId commandId in new CommandId[] {
CommandId.SplitNew,
CommandId.SplitSave,
CommandId.SplitPrint,
CommandId.PasteSplit,
CommandId.FormatTablePropertiesSplit})
{
CommandManager.Add(new Command(commandId));
}
_commandClosePreview = CommandManager.Add(CommandId.ClosePreview, commandClosePreview_Execute, false);
CommandManager.EndUpdate();
}
private Command _commandClosePreview;
protected override void ManageCommandsForEditingMode()
{
base.ManageCommandsForEditingMode();
bool allowInsertCommands = (CurrentEditingMode == EditingMode.Source || CurrentEditingMode == EditingMode.Wysiwyg);
// Enable/disable heading styles
commandSemanticHtml.Enabled = allowInsertCommands;
// Enable/disable 3rd party plugins
commandInsertablePlugins.Enabled = allowInsertCommands;
// Enable/disable inserting web images
commandInsertWebImage.Enabled = allowInsertCommands;
_commandClosePreview.Enabled = CurrentEditingMode == EditingMode.Preview;
}
void commandInsertablePlugins_ExecuteWithArgs(object sender, ExecuteEventHandlerArgs args)
{
string pluginId = commandInsertablePlugins.Items[args.GetInt(commandInsertablePlugins.CommandId.ToString())].Cookie;
Command command = CommandManager.Get(pluginId);
command.PerformExecute();
}
void commandInsertWebImage_Execute(object sender, EventArgs e)
{
CommandManager.Get(ImageInsertion.WebImages.WebImageContentSource.ID).PerformExecute();
}
void commandClosePreview_Execute(object sender, EventArgs e)
{
switch (LastNonPreviewEditingMode)
{
case EditingMode.Source:
ChangeToCodeMode();
break;
case EditingMode.Wysiwyg:
ChangeToWysiwygMode();
break;
case EditingMode.PlainText:
ChangeToPlainTextMode();
break;
default:
break;
}
}
private InsertablePluginsGalleryCommand commandInsertablePlugins;
private Command commandInsertWebImage;
protected override void ContentEditor_SelectionChanged(object sender, EventArgs e)
{
// For managing Writer-specific commands
commandInsertablePlugins.Enabled = InSourceOrWysiwygModeAndEditFieldIsNotSelected();
commandInsertWebImage.Enabled = InSourceOrWysiwygModeAndEditFieldIsNotSelected();
base.ContentEditor_SelectionChanged(sender, e);
}
private void commandInsertExtendedEntry_Execute(object sender, EventArgs e)
{
_currentEditor.InsertExtendedEntryBreak();
}
void ContentEditor_EditorHtmlReloaded(object sender, EventArgs e)
{
UpdateExtendedEntryStatus();
}
void UpdateExtendedEntryStatus()
{
//toggle commands based on the new blog's capabilities
commandInsertExtendedEntry.Enabled = SupportsExtendedEntries;
/*
CT: Bug 607202 - just disable this command so we're consistent with the toolbar, which also just disables.
if (commandInsertExtendedEntry.On != SupportsExtendedEntries)
{
commandInsertExtendedEntry.On = SupportsExtendedEntries;
CommandManager.OnChanged(EventArgs.Empty);
}
*/
}
private bool SupportsExtendedEntries
{
get
{
return _currentBlog.ClientOptions.SupportsExtendedEntries && !_isPage;
}
}
private void commandViewUseStyles_Execute(object sender, EventArgs e)
{
using (PostHtmlEditingSettings editSettings = new PostHtmlEditingSettings(_currentBlog.Id))
{
commandViewUseStyles.Latched = !commandViewUseStyles.Latched;
editSettings.EditUsingBlogStyles = commandViewUseStyles.Latched;
ShowWebLayoutWarningIfNecessary();
// When we update the editors theme because the user toggled 'Edit using Themes'
// we suppress the editor reload. The reload will happen in the following call to ChangeToWysiwygMode()
using (SuppressEditorLoad())
UpdateTemplateToBlogTheme();
ReloadEditor();
}
}
private void InitDefaultEditorForBlog()
{
using (PostHtmlEditingSettings editSettings = new PostHtmlEditingSettings(_currentBlog.Id))
{
// initialize the editing template based on the last used view
bool useStyles = EditUsingWebLayout(editSettings);
commandViewUseStyles.Latched = useStyles;
}
}
private bool EditUsingWebLayout(PostHtmlEditingSettings editSettings)
{
if (!editSettings.EditUsingBlogStylesIsSet && string.IsNullOrEmpty(editSettings.LastEditingView))
editSettings.EditUsingBlogStyles = _currentBlog.DefaultView != EditingViews.Normal;
return editSettings.EditUsingBlogStyles;
}
private void ShowWebLayoutWarningIfNecessary()
{
// if the blog's DefaultView is not WebLayout and the user has not chosen
// to supress the web-layout warning dialog then show a warning prior
// to proceeding
if (_currentBlog.DefaultView != EditingViews.WebLayout)
{
using (PostHtmlEditingSettings editSettings = new PostHtmlEditingSettings(_currentBlog.Id))
{
if (editSettings.DisplayWebLayoutWarning)
{
using (WebLayoutViewWarningForm warningForm = new WebLayoutViewWarningForm())
{
warningForm.ShowDialog(_mainFrameWindow);
if (warningForm.DontShowMessageAgain)
editSettings.DisplayWebLayoutWarning = false;
}
}
}
}
}
private void UpdateTemplateToBlogTheme()
{
SetTheme(GetStyledHtml(), GetPreviewHtml(), true);
}
protected override void BeforeSetTheme(ref string wysiwygHTML, ref string previewHTML, bool containsTitle)
{
// Remove a very common snippet of code from the theme that has been copied and pasted
// into a lot of the blogger templates. The snippet of CSS should fix the user's theme for IE5
// however, when inside of Writer causes problems with new lines in the editor.
wysiwygHTML = Regex.Replace(wysiwygHTML, "\\.post-body\\s+p\\s+\\{\\s+/\\*\\s+Fix\\s+bug\\s+in\\s+IE5/Win\\s+with\\s+italics\\s+in\\s+posts\\s+\\*/\\s+margin:\\s+0px\\s+0px\\s+0px\\s+0px;\\s+padding:\\s+3px\\s+0px\\s+3px\\s+0px;\\s+display:\\s+inline;\\s+/\\*\\s+to\\s+fix\\s+floating-ads\\s+wrapping\\s+problem\\s+in\\s+IE\\s+\\*/\\s+height:\\s+1%;\\s+overflow:\\s+visible;\\s*}", "");
// Remove noscript tags from the editing template. If a user has a blog theme of
// <html><head><noscript></noscript></head><body><div></div></body></html> we will parse it to
// <html><head><noscript></head><body><div></div></body></noscript></html> and this code will change it to
// <html><head></head><body><div></div></body></html> which will allow us to attach our beavhiors to the body element
wysiwygHTML = Regex.Replace(wysiwygHTML, "</?NOSCRIPT>", "", RegexOptions.IgnoreCase);
// Remove any scroll=no attributes. Sharepoint 2010 adds these.
wysiwygHTML = Regex.Replace(wysiwygHTML, "scroll=[\"']?no[\"']?", "", RegexOptions.IgnoreCase);
}
private string GetStyledHtml()
{
BlogEditingTemplateType type;
if (commandViewUseStyles.Latched)
type = BlogEditingTemplateType.Framed;
else
type = BlogEditingTemplateType.Normal;
return EditingTemplateLoader.LoadBlogTemplate(_currentBlog.Id, type, IsRTLTemplate);
}
protected override string GetPreviewHtml()
{
return GetPreviewHtml(_currentBlog.Id);
}
private string GetPreviewHtml(string blogId)
{
return EditingTemplateLoader.LoadBlogTemplate(blogId, BlogEditingTemplateType.Webpage, IsRTLTemplate);
}
protected override string GetPostBodyInlineStyleOverrides()
{
return "min-height: 400px;";
}
// @SharedCanvas - is there a better way to do this using the CE?
public override IFocusableControl[] GetFocusablePanes()
{
return new IFocusableControl[]
{
EditorFocusControl,
new FocusableControl(_postPropertyEditor),
new FocusableControl(_htmlEditorSidebarHost)
};
}
internal class BlogPostTemplateStrategy : BlogPostHtmlEditorControl.TemplateStrategy
{
public override string OnBodyInserted(string bodyContents)
{
return String.Format(CultureInfo.InvariantCulture, "<div id=\"{0}\" class='postBody' style='margin: 4px 0px 0px 0px; padding: 0px 0px 0px 0px; border: 0px;'>{1}</div>", BODY_FRAGMENT_ID, bodyContents); ;
}
public override string OnTitleInserted(string title)
{
return String.Format(CultureInfo.InvariantCulture, "<span id=\"{0}\" class='postTitle' style='margin: 0px 0px 0px 0px; padding: 0px 0px 0px 0px; border: 0px;'>{1}</span>", TITLE_FRAGMENT_ID, HtmlUtils.EscapeEntities(title));
}
public override void OnDocumentComplete(IHTMLDocument2 doc)
{
return;
}
public override IHTMLElement PostBodyElement(IHTMLDocument2 doc)
{
return HTMLElementHelper.GetFragmentElement((IHTMLDocument3)doc, BODY_FRAGMENT_ID);
}
public override IHTMLElement TitleElement(IHTMLDocument2 doc)
{
return HTMLElementHelper.GetFragmentElement((IHTMLDocument3)doc, TITLE_FRAGMENT_ID);
}
}
}
}
| |
#region License
//L
// 2007 - 2013 Copyright Northwestern University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/annotation-and-image-markup/LICENSE.txt for details.
//L
#endregion
using ClearCanvas.Common;
using ClearCanvas.Desktop;
using ClearCanvas.Desktop.Configuration;
using ClearCanvas.Desktop.Validation;
namespace AIM.Annotation.Configuration
{
[ExtensionPoint]
public sealed class AimConfigurationComponentViewExtensionPoint : ExtensionPoint<IApplicationComponentView>
{
}
/// <summary>
/// AimConfigurationComponent class.
/// </summary>
[AssociateView(typeof(AimConfigurationComponentViewExtensionPoint))]
public class AimConfigurationComponent : ConfigurationApplicationComponent
{
public static readonly string Path = "AIM";
private AimSettings _settings;
private bool _sendNewXmlAnnotationsToGrid;
private bool _storeXmlAnnotationsLocally;
private bool _storeXmlInMyDocuments;
private string _localAnnotationStoreFolder;
private bool _requireUserInfo;
private bool _requireMarkupInAnnotation;
private string _localTemplateStoreFolder;
public bool SendNewXmlAnnotationsToGrid
{
get { return _sendNewXmlAnnotationsToGrid; }
set
{
if (_sendNewXmlAnnotationsToGrid != value)
{
_sendNewXmlAnnotationsToGrid = value;
Modified = true;
NotifyPropertyChanged("SendNewXmlAnnotationsToGrid");
}
}
}
public bool StoreXmlAnnotationsLocally
{
get { return _storeXmlAnnotationsLocally; }
set
{
if (_storeXmlAnnotationsLocally != value)
{
_storeXmlAnnotationsLocally = value;
Modified = true;
NotifyPropertyChanged("StoreXmlAnnotationsLocally");
}
}
}
public bool StoreXmlInMyDocuments
{
get { return _storeXmlInMyDocuments; }
set
{
if (_storeXmlInMyDocuments != value)
{
_storeXmlInMyDocuments = value;
Modified = true;
NotifyPropertyChanged("StoreXmlInMyDocuments");
NotifyPropertyChanged("StoreXmlInSpecifiedFolder");
}
}
}
public bool StoreXmlInSpecifiedFolder
{
get { return !StoreXmlInMyDocuments; }
set { StoreXmlInMyDocuments = !value; }
}
public string LocalAnnotationStoreFolder
{
get { return _localAnnotationStoreFolder; }
set
{
if (_localAnnotationStoreFolder != value)
{
_localAnnotationStoreFolder = value;
Modified = true;
NotifyPropertyChanged("LocalAnnotationStoreFolder");
}
}
}
public bool LocalAnnotationStoreFolderEnabled
{
get { return StoreXmlAnnotationsLocally && StoreXmlInSpecifiedFolder; }
}
[ValidationMethodFor("LocalAnnotationStoreFolder")]
protected ValidationResult LocalAnnotationFolderValidation()
{
if (!StoreXmlAnnotationsLocally || StoreXmlInMyDocuments)
return new ValidationResult(true, "");
return new ValidationResult(System.IO.Directory.Exists(LocalAnnotationStoreFolder), "Local AIM storage folder does not exist");
}
public bool RequireUserInfo
{
get { return _requireUserInfo; }
set
{
if (_requireUserInfo != value)
{
_requireUserInfo = value;
Modified = true;
NotifyPropertyChanged("RequireUserInfo");
}
}
}
public bool RequireMarkupInAnnotation
{
get { return _requireMarkupInAnnotation; }
set
{
if (_requireMarkupInAnnotation != value)
{
_requireMarkupInAnnotation = value;
Modified = true;
NotifyPropertyChanged("RequireMarkupInAnnotation");
}
}
}
public string LocalTemplatesStoreFolder
{
get { return _localTemplateStoreFolder; }
set
{
if (_localTemplateStoreFolder != value)
{
_localTemplateStoreFolder = value;
Modified = true;
NotifyPropertyChanged("LocalTemplatesStoreFolder");
}
}
}
[ValidationMethodFor("LocalTemplatesStoreFolder")]
protected ValidationResult LocalTemplatesFolderValidation()
{
if (string.IsNullOrEmpty(LocalTemplatesStoreFolder))
return new ValidationResult(true, "");
return new ValidationResult(System.IO.Directory.Exists(LocalTemplatesStoreFolder), "Local AIM Templates storage folder does not exist");
}
public override void Start()
{
base.Start();
_settings = AimSettings.Default;
_sendNewXmlAnnotationsToGrid = _settings.SendNewXmlAnnotationsToGrid;
_storeXmlAnnotationsLocally = _settings.StoreXmlAnnotationsLocally;
_storeXmlInMyDocuments = _settings.StoreXmlInMyDocuments;
_localAnnotationStoreFolder = _settings.LocalAnnotationsFolder;
_requireUserInfo = _settings.RequireUserInfo;
_requireMarkupInAnnotation = _settings.RequireMarkupInAnnotation;
_localTemplateStoreFolder = _settings.LocalTemplatesFolder;
}
/// <summary>
/// Called by the host when the application component is being terminated.
/// </summary>
public override void Stop()
{
_settings = null;
base.Stop();
}
public override void Save()
{
_settings.SendNewXmlAnnotationsToGrid = _sendNewXmlAnnotationsToGrid;
_settings.StoreXmlAnnotationsLocally = _storeXmlAnnotationsLocally;
_settings.StoreXmlInMyDocuments = _storeXmlInMyDocuments;
_settings.LocalAnnotationsFolder = System.IO.Directory.Exists(_localAnnotationStoreFolder) ? _localAnnotationStoreFolder : "";
_settings.RequireUserInfo = _requireUserInfo;
_settings.RequireMarkupInAnnotation = _requireMarkupInAnnotation;
_settings.LocalTemplatesFolder = _localTemplateStoreFolder;
_settings.Save();
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Threading.Tasks.TaskFactory.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Threading.Tasks
{
public partial class TaskFactory
{
#region Methods and constructors
public Task<TResult> ContinueWhenAll<TResult>(Task[] tasks, Func<Task[], TResult> continuationFunction, TaskContinuationOptions continuationOptions)
{
return default(Task<TResult>);
}
public Task<TResult> ContinueWhenAll<TResult>(Task[] tasks, Func<Task[], TResult> continuationFunction, System.Threading.CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
return default(Task<TResult>);
}
public Task<TResult> ContinueWhenAll<TResult>(Task[] tasks, Func<Task[], TResult> continuationFunction)
{
return default(Task<TResult>);
}
public Task<TResult> ContinueWhenAll<TResult>(Task[] tasks, Func<Task[], TResult> continuationFunction, System.Threading.CancellationToken cancellationToken)
{
return default(Task<TResult>);
}
public Task<TResult> ContinueWhenAll<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction, TaskContinuationOptions continuationOptions)
{
return default(Task<TResult>);
}
public Task<TResult> ContinueWhenAll<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction, System.Threading.CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
return default(Task<TResult>);
}
public Task<TResult> ContinueWhenAll<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction)
{
return default(Task<TResult>);
}
public Task<TResult> ContinueWhenAll<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction, System.Threading.CancellationToken cancellationToken)
{
return default(Task<TResult>);
}
public Task ContinueWhenAll(Task[] tasks, Action<Task[]> continuationAction, TaskContinuationOptions continuationOptions)
{
return default(Task);
}
public Task ContinueWhenAll(Task[] tasks, Action<Task[]> continuationAction, System.Threading.CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
return default(Task);
}
public Task ContinueWhenAll(Task[] tasks, Action<Task[]> continuationAction)
{
return default(Task);
}
public Task ContinueWhenAll(Task[] tasks, Action<Task[]> continuationAction, System.Threading.CancellationToken cancellationToken)
{
return default(Task);
}
public Task ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>[]> continuationAction, TaskContinuationOptions continuationOptions)
{
return default(Task);
}
public Task ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>[]> continuationAction, System.Threading.CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
return default(Task);
}
public Task ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>[]> continuationAction)
{
return default(Task);
}
public Task ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>[]> continuationAction, System.Threading.CancellationToken cancellationToken)
{
return default(Task);
}
public Task<TResult> ContinueWhenAny<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction, TaskContinuationOptions continuationOptions)
{
return default(Task<TResult>);
}
public Task<TResult> ContinueWhenAny<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction, System.Threading.CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
return default(Task<TResult>);
}
public Task<TResult> ContinueWhenAny<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction)
{
return default(Task<TResult>);
}
public Task<TResult> ContinueWhenAny<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction, System.Threading.CancellationToken cancellationToken)
{
return default(Task<TResult>);
}
public Task ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>> continuationAction, TaskContinuationOptions continuationOptions)
{
return default(Task);
}
public Task ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>> continuationAction, System.Threading.CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
return default(Task);
}
public Task ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>> continuationAction)
{
return default(Task);
}
public Task ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>> continuationAction, System.Threading.CancellationToken cancellationToken)
{
return default(Task);
}
public Task ContinueWhenAny(Task[] tasks, Action<Task> continuationAction, TaskContinuationOptions continuationOptions)
{
return default(Task);
}
public Task ContinueWhenAny(Task[] tasks, Action<Task> continuationAction, System.Threading.CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
return default(Task);
}
public Task ContinueWhenAny(Task[] tasks, Action<Task> continuationAction)
{
return default(Task);
}
public Task ContinueWhenAny(Task[] tasks, Action<Task> continuationAction, System.Threading.CancellationToken cancellationToken)
{
return default(Task);
}
public Task<TResult> ContinueWhenAny<TResult>(Task[] tasks, Func<Task, TResult> continuationFunction, TaskContinuationOptions continuationOptions)
{
return default(Task<TResult>);
}
public Task<TResult> ContinueWhenAny<TResult>(Task[] tasks, Func<Task, TResult> continuationFunction, System.Threading.CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
return default(Task<TResult>);
}
public Task<TResult> ContinueWhenAny<TResult>(Task[] tasks, Func<Task, TResult> continuationFunction)
{
return default(Task<TResult>);
}
public Task<TResult> ContinueWhenAny<TResult>(Task[] tasks, Func<Task, TResult> continuationFunction, System.Threading.CancellationToken cancellationToken)
{
return default(Task<TResult>);
}
public Task<TResult> FromAsync<TArg1, TArg2, TResult>(Func<TArg1, TArg2, AsyncCallback, Object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod, TArg1 arg1, TArg2 arg2, Object state, TaskCreationOptions creationOptions)
{
return default(Task<TResult>);
}
public Task<TResult> FromAsync<TArg1, TArg2, TResult>(Func<TArg1, TArg2, AsyncCallback, Object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod, TArg1 arg1, TArg2 arg2, Object state)
{
return default(Task<TResult>);
}
public Task<TResult> FromAsync<TArg1, TArg2, TArg3, TResult>(Func<TArg1, TArg2, TArg3, AsyncCallback, Object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod, TArg1 arg1, TArg2 arg2, TArg3 arg3, Object state, TaskCreationOptions creationOptions)
{
return default(Task<TResult>);
}
public Task<TResult> FromAsync<TArg1, TArg2, TArg3, TResult>(Func<TArg1, TArg2, TArg3, AsyncCallback, Object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod, TArg1 arg1, TArg2 arg2, TArg3 arg3, Object state)
{
return default(Task<TResult>);
}
public Task FromAsync<TArg1>(Func<TArg1, AsyncCallback, Object, IAsyncResult> beginMethod, Action<IAsyncResult> endMethod, TArg1 arg1, Object state, TaskCreationOptions creationOptions)
{
return default(Task);
}
public Task FromAsync<TArg1>(Func<TArg1, AsyncCallback, Object, IAsyncResult> beginMethod, Action<IAsyncResult> endMethod, TArg1 arg1, Object state)
{
return default(Task);
}
public Task FromAsync<TArg1, TArg2>(Func<TArg1, TArg2, AsyncCallback, Object, IAsyncResult> beginMethod, Action<IAsyncResult> endMethod, TArg1 arg1, TArg2 arg2, Object state, TaskCreationOptions creationOptions)
{
return default(Task);
}
public Task FromAsync<TArg1, TArg2>(Func<TArg1, TArg2, AsyncCallback, Object, IAsyncResult> beginMethod, Action<IAsyncResult> endMethod, TArg1 arg1, TArg2 arg2, Object state)
{
return default(Task);
}
public Task FromAsync(Func<AsyncCallback, Object, IAsyncResult> beginMethod, Action<IAsyncResult> endMethod, Object state, TaskCreationOptions creationOptions)
{
return default(Task);
}
public Task FromAsync(IAsyncResult asyncResult, Action<IAsyncResult> endMethod, TaskCreationOptions creationOptions)
{
return default(Task);
}
public Task FromAsync(IAsyncResult asyncResult, Action<IAsyncResult> endMethod)
{
return default(Task);
}
public Task FromAsync(Func<AsyncCallback, Object, IAsyncResult> beginMethod, Action<IAsyncResult> endMethod, Object state)
{
return default(Task);
}
public Task FromAsync(IAsyncResult asyncResult, Action<IAsyncResult> endMethod, TaskCreationOptions creationOptions, TaskScheduler scheduler)
{
return default(Task);
}
public Task<TResult> FromAsync<TResult>(Func<AsyncCallback, Object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod, Object state, TaskCreationOptions creationOptions)
{
return default(Task<TResult>);
}
public Task<TResult> FromAsync<TResult>(Func<AsyncCallback, Object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod, Object state)
{
return default(Task<TResult>);
}
public Task<TResult> FromAsync<TArg1, TResult>(Func<TArg1, AsyncCallback, Object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod, TArg1 arg1, Object state, TaskCreationOptions creationOptions)
{
return default(Task<TResult>);
}
public Task<TResult> FromAsync<TArg1, TResult>(Func<TArg1, AsyncCallback, Object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod, TArg1 arg1, Object state)
{
return default(Task<TResult>);
}
public Task<TResult> FromAsync<TResult>(IAsyncResult asyncResult, Func<IAsyncResult, TResult> endMethod, TaskCreationOptions creationOptions, TaskScheduler scheduler)
{
return default(Task<TResult>);
}
public Task FromAsync<TArg1, TArg2, TArg3>(Func<TArg1, TArg2, TArg3, AsyncCallback, Object, IAsyncResult> beginMethod, Action<IAsyncResult> endMethod, TArg1 arg1, TArg2 arg2, TArg3 arg3, Object state, TaskCreationOptions creationOptions)
{
return default(Task);
}
public Task FromAsync<TArg1, TArg2, TArg3>(Func<TArg1, TArg2, TArg3, AsyncCallback, Object, IAsyncResult> beginMethod, Action<IAsyncResult> endMethod, TArg1 arg1, TArg2 arg2, TArg3 arg3, Object state)
{
return default(Task);
}
public Task<TResult> FromAsync<TResult>(IAsyncResult asyncResult, Func<IAsyncResult, TResult> endMethod, TaskCreationOptions creationOptions)
{
return default(Task<TResult>);
}
public Task<TResult> FromAsync<TResult>(IAsyncResult asyncResult, Func<IAsyncResult, TResult> endMethod)
{
return default(Task<TResult>);
}
public Task StartNew(Action<Object> action, Object state)
{
Contract.Ensures(Contract.Result<System.Threading.Tasks.Task>() != null);
return default(Task);
}
public Task StartNew(Action<Object> action, Object state, System.Threading.CancellationToken cancellationToken)
{
Contract.Ensures(Contract.Result<System.Threading.Tasks.Task>() != null);
return default(Task);
}
public Task StartNew(Action<Object> action, Object state, TaskCreationOptions creationOptions)
{
Contract.Ensures(Contract.Result<System.Threading.Tasks.Task>() != null);
return default(Task);
}
public Task StartNew(Action action, System.Threading.CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler)
{
Contract.Ensures(Contract.Result<System.Threading.Tasks.Task>() != null);
return default(Task);
}
public Task StartNew(Action action)
{
Contract.Ensures(Contract.Result<System.Threading.Tasks.Task>() != null);
return default(Task);
}
public Task StartNew(Action action, System.Threading.CancellationToken cancellationToken)
{
Contract.Ensures(Contract.Result<System.Threading.Tasks.Task>() != null);
return default(Task);
}
public Task StartNew(Action action, TaskCreationOptions creationOptions)
{
Contract.Ensures(Contract.Result<System.Threading.Tasks.Task>() != null);
return default(Task);
}
public Task StartNew(Action<Object> action, Object state, System.Threading.CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler)
{
Contract.Ensures(Contract.Result<System.Threading.Tasks.Task>() != null);
return default(Task);
}
public Task<TResult> StartNew<TResult>(Func<Object, TResult> function, Object state, System.Threading.CancellationToken cancellationToken)
{
return default(Task<TResult>);
}
public Task<TResult> StartNew<TResult>(Func<Object, TResult> function, Object state)
{
return default(Task<TResult>);
}
public Task<TResult> StartNew<TResult>(Func<Object, TResult> function, Object state, System.Threading.CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler)
{
return default(Task<TResult>);
}
public Task<TResult> StartNew<TResult>(Func<Object, TResult> function, Object state, TaskCreationOptions creationOptions)
{
return default(Task<TResult>);
}
public Task<TResult> StartNew<TResult>(Func<TResult> function, System.Threading.CancellationToken cancellationToken)
{
return default(Task<TResult>);
}
public Task<TResult> StartNew<TResult>(Func<TResult> function)
{
return default(Task<TResult>);
}
public Task<TResult> StartNew<TResult>(Func<TResult> function, System.Threading.CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler)
{
return default(Task<TResult>);
}
public Task<TResult> StartNew<TResult>(Func<TResult> function, TaskCreationOptions creationOptions)
{
return default(Task<TResult>);
}
public TaskFactory()
{
}
public TaskFactory(System.Threading.CancellationToken cancellationToken)
{
}
public TaskFactory(System.Threading.CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
}
public TaskFactory(TaskCreationOptions creationOptions, TaskContinuationOptions continuationOptions)
{
}
public TaskFactory(TaskScheduler scheduler)
{
}
#endregion
#region Properties and indexers
public System.Threading.CancellationToken CancellationToken
{
get
{
return default(System.Threading.CancellationToken);
}
}
public TaskContinuationOptions ContinuationOptions
{
get
{
return default(TaskContinuationOptions);
}
}
public TaskCreationOptions CreationOptions
{
get
{
return default(TaskCreationOptions);
}
}
public TaskScheduler Scheduler
{
get
{
return default(TaskScheduler);
}
}
#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 Microsoft.Xml;
using System.Text;
using System;
namespace Microsoft.Xml
{
using System;
// Specifies the context that the XmLReader will use for xml fragment
public class XmlParserContext
{
private XmlNameTable _nt = null;
private XmlNamespaceManager _nsMgr = null;
private String _docTypeName = String.Empty;
private String _pubId = String.Empty;
private String _sysId = String.Empty;
private String _internalSubset = String.Empty;
private String _xmlLang = String.Empty;
private XmlSpace _xmlSpace;
private String _baseURI = String.Empty;
private Encoding _encoding = null;
public XmlParserContext(XmlNameTable nt, XmlNamespaceManager nsMgr, String xmlLang, XmlSpace xmlSpace)
: this(nt, nsMgr, null, null, null, null, String.Empty, xmlLang, xmlSpace)
{
// Intentionally Empty
}
public XmlParserContext(XmlNameTable nt, XmlNamespaceManager nsMgr, String xmlLang, XmlSpace xmlSpace, Encoding enc)
: this(nt, nsMgr, null, null, null, null, String.Empty, xmlLang, xmlSpace, enc)
{
// Intentionally Empty
}
public XmlParserContext(XmlNameTable nt, XmlNamespaceManager nsMgr, String docTypeName,
String pubId, String sysId, String internalSubset, String baseURI,
String xmlLang, XmlSpace xmlSpace)
: this(nt, nsMgr, docTypeName, pubId, sysId, internalSubset, baseURI, xmlLang, xmlSpace, null)
{
// Intentionally Empty
}
public XmlParserContext(XmlNameTable nt, XmlNamespaceManager nsMgr, String docTypeName,
String pubId, String sysId, String internalSubset, String baseURI,
String xmlLang, XmlSpace xmlSpace, Encoding enc)
{
if (nsMgr != null)
{
if (nt == null)
{
_nt = nsMgr.NameTable;
}
else
{
if ((object)nt != (object)nsMgr.NameTable)
{
throw new XmlException(ResXml.Xml_NotSameNametable, string.Empty);
}
_nt = nt;
}
}
else
{
_nt = nt;
}
_nsMgr = nsMgr;
_docTypeName = (null == docTypeName ? String.Empty : docTypeName);
_pubId = (null == pubId ? String.Empty : pubId);
_sysId = (null == sysId ? String.Empty : sysId);
_internalSubset = (null == internalSubset ? String.Empty : internalSubset);
_baseURI = (null == baseURI ? String.Empty : baseURI);
_xmlLang = (null == xmlLang ? String.Empty : xmlLang);
_xmlSpace = xmlSpace;
_encoding = enc;
}
public XmlNameTable NameTable
{
get
{
return _nt;
}
set
{
_nt = value;
}
}
public XmlNamespaceManager NamespaceManager
{
get
{
return _nsMgr;
}
set
{
_nsMgr = value;
}
}
public String DocTypeName
{
get
{
return _docTypeName;
}
set
{
_docTypeName = (null == value ? String.Empty : value);
}
}
public String PublicId
{
get
{
return _pubId;
}
set
{
_pubId = (null == value ? String.Empty : value);
}
}
public String SystemId
{
get
{
return _sysId;
}
set
{
_sysId = (null == value ? String.Empty : value);
}
}
public String BaseURI
{
get
{
return _baseURI;
}
set
{
_baseURI = (null == value ? String.Empty : value);
}
}
public String InternalSubset
{
get
{
return _internalSubset;
}
set
{
_internalSubset = (null == value ? String.Empty : value);
}
}
public String XmlLang
{
get
{
return _xmlLang;
}
set
{
_xmlLang = (null == value ? String.Empty : value);
}
}
public XmlSpace XmlSpace
{
get
{
return _xmlSpace;
}
set
{
_xmlSpace = value;
}
}
public Encoding Encoding
{
get
{
return _encoding;
}
set
{
_encoding = value;
}
}
internal bool HasDtdInfo
{
get
{
return (_internalSubset != string.Empty || _pubId != string.Empty || _sysId != string.Empty);
}
}
} // class XmlContext
} // namespace Microsoft.Xml
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: BufferedStream
**
** <OWNER>gpaperin</OWNER>
**
** Purpose: A composable Stream that buffers reads & writes to the underlying stream.
**
**
===========================================================*/
/*
* https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/io/bufferedstream.cs
*/
using System;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Threading;
namespace System.IO
{
/// <summary>
/// One of the design goals here is to prevent the buffer from getting in the way and slowing
/// down underlying stream accesses when it is not needed. If you always read and write for sizes
/// greater than the internal buffer size, then this class may not even allocate the internal buffer.
/// See a large comment in Write for the details of the write buffer heuristic.
///
/// This class buffers reads and writes in a shared buffer.
/// (If you maintained two buffers separately, one operation would always trash the other buffer
/// anyways, so we might as well use one buffer.)
/// The assumption here is you will almost always be doing a series of reads or writes, but rarely
/// alternate between the two of them on the same stream.
///
/// Class Invariants:
/// The class has one buffer, shared for reading and writing.
/// It can only be used for one or the other at any point in time - not both.
/// The following should be true:
/// <![CDATA[
/// * 0 <= _readPos <= _readLen < _bufferSize
/// * 0 <= _writePos < _bufferSize
/// * _readPos == _readLen && _readPos > 0 implies the read buffer is valid, but we're at the end of the buffer.
/// * _readPos == _readLen == 0 means the read buffer contains garbage.
/// * Either _writePos can be greater than 0, or _readLen & _readPos can be greater than zero,
/// but neither can be greater than zero at the same time.
/// ]]>
/// This class will never cache more bytes than the max specified buffer size.
/// However, it may use a temporary buffer of up to twice the size in order to combine several IO operations on
/// the underlying stream into a single operation. This is because we assume that memory copies are significantly
/// faster than IO operations on the underlying stream (if this was not true, using buffering is never appropriate).
/// The max size of this "shadow" buffer is limited as to not allocate it on the LOH.
/// Shadowing is always transient. Even when using this technique, this class still guarantees that the number of
/// bytes cached (not yet written to the target stream or not yet consumed by the user) is never larger than the
/// actual specified buffer size.
/// </summary>
public sealed class BufferedStream : Stream
{
private const Int32 _DefaultBufferSize = 4096;
private Stream _stream; // Underlying stream. Close sets _stream to null.
private Byte[] _buffer; // Shared read/write buffer. Alloc on first use.
private readonly Int32 _bufferSize; // Length of internal buffer (not counting the shadow buffer).
private Int32 _readPos; // Read pointer within shared buffer.
private Int32 _readLen; // Number of bytes read in buffer from _stream.
private Int32 _writePos; // Write pointer within shared buffer.
// Removing a private default constructor is a breaking change for the DataContractSerializer.
// Because this ctor was here previously we need to keep it around.
private BufferedStream()
{
}
public BufferedStream(Stream stream)
: this(stream, _DefaultBufferSize)
{
}
public BufferedStream(Stream stream, Int32 bufferSize)
{
if (stream == null)
throw new ArgumentNullException("stream");
if (bufferSize <= 0)
throw new ArgumentOutOfRangeException("bufferSize");
_stream = stream;
_bufferSize = bufferSize;
// Allocate _buffer on its first use - it will not be used if all reads
// & writes are greater than or equal to buffer size.
if (!_stream.CanRead && !_stream.CanWrite)
__Error.StreamIsClosed();
}
private void EnsureNotClosed()
{
if (_stream == null)
__Error.StreamIsClosed();
}
private void EnsureCanSeek()
{
Contract.Requires(_stream != null);
if (!_stream.CanSeek)
__Error.SeekNotSupported();
}
private void EnsureCanRead()
{
Contract.Requires(_stream != null);
if (!_stream.CanRead)
__Error.ReadNotSupported();
}
private void EnsureCanWrite()
{
Contract.Requires(_stream != null);
if (!_stream.CanWrite)
__Error.WriteNotSupported();
}
/// <summary><code>MaxShadowBufferSize</code> is chosed such that shadow buffers are not allocated on the Large Object Heap.
/// Currently, an object is allocated on the LOH if it is larger than 85000 bytes. See LARGE_OBJECT_SIZE in ndp\clr\src\vm\gc.h
/// We will go with exactly 80 KBytes, although this is somewhat arbitrary.</summary>
private const Int32 MaxShadowBufferSize = 81920; // Make sure not to get to the Large Object Heap.
private void EnsureShadowBufferAllocated()
{
Contract.Assert(_buffer != null);
Contract.Assert(_bufferSize > 0);
// Already have shadow buffer?
if (_buffer.Length != _bufferSize || _bufferSize >= MaxShadowBufferSize)
return;
Byte[] shadowBuffer = new Byte[Math.Min(_bufferSize + _bufferSize, MaxShadowBufferSize)];
Array.Copy(_buffer, 0, shadowBuffer, 0, _writePos);
_buffer = shadowBuffer;
}
private void EnsureBufferAllocated()
{
Contract.Assert(_bufferSize > 0);
// BufferedStream is not intended for multi-threaded use, so no worries about the get/set ---- on _buffer.
if (_buffer == null)
_buffer = new Byte[_bufferSize];
}
internal Stream UnderlyingStream
{
[Pure]
get
{
return _stream;
}
}
internal Int32 BufferSize
{
[Pure]
get
{
return _bufferSize;
}
}
public override bool CanRead
{
[Pure]
get
{
return _stream != null && _stream.CanRead;
}
}
public override bool CanWrite
{
[Pure]
get
{
return _stream != null && _stream.CanWrite;
}
}
public override bool CanSeek
{
[Pure]
get
{
return _stream != null && _stream.CanSeek;
}
}
public override Int64 Length
{
get
{
EnsureNotClosed();
if (_writePos > 0)
FlushWrite();
return _stream.Length;
}
}
public override Int64 Position
{
get
{
EnsureNotClosed();
EnsureCanSeek();
Contract.Assert(!(_writePos > 0 && _readPos != _readLen), "Read and Write buffers cannot both have data in them at the same time.");
return _stream.Position + (_readPos - _readLen + _writePos);
}
set
{
if (value < 0)
throw new ArgumentOutOfRangeException("value");
Contract.EndContractBlock();
EnsureNotClosed();
EnsureCanSeek();
if (_writePos > 0)
FlushWrite();
_readPos = 0;
_readLen = 0;
_stream.Seek(value, SeekOrigin.Begin);
}
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing && _stream != null)
{
try
{
Flush();
}
finally
{
_stream.Close();
}
}
}
finally
{
_stream = null;
_buffer = null;
#if !FEATURE_PAL && FEATURE_ASYNC_IO
_lastSyncCompletedReadTask = null;
#endif // !FEATURE_PAL && FEATURE_ASYNC_IO
// Call base.Dispose(bool) to cleanup async IO resources
base.Dispose(disposing);
}
}
public override void Flush()
{
EnsureNotClosed();
// Has WRITE data in the buffer:
if (_writePos > 0)
{
FlushWrite();
Contract.Assert(_writePos == 0 && _readPos == 0 && _readLen == 0);
return;
}
// Has READ data in the buffer:
if (_readPos < _readLen)
{
// If the underlying stream is not seekable AND we have something in the read buffer, then FlushRead would throw.
// We can either throw away the buffer resulting in data loss (!) or ignore the Flush.
// (We cannot throw becasue it would be a breaking change.) We opt into ignoring the Flush in that situation.
if (!_stream.CanSeek)
return;
FlushRead();
// User streams may have opted to throw from Flush if CanWrite is false (although the abstract Stream does not do so).
// However, if we do not forward the Flush to the underlying stream, we may have problems when chaining several streams.
// Let us make a best effort attempt:
if (_stream.CanWrite || _stream is BufferedStream)
_stream.Flush();
Contract.Assert(_writePos == 0 && _readPos == 0 && _readLen == 0);
return;
}
// We had no data in the buffer, but we still need to tell the underlying stream to flush.
if (_stream.CanWrite || _stream is BufferedStream)
_stream.Flush();
_writePos = _readPos = _readLen = 0;
}
// Reading is done in blocks, but someone could read 1 byte from the buffer then write.
// At that point, the underlying stream's pointer is out of sync with this stream's position.
// All write functions should call this function to ensure that the buffered data is not lost.
private void FlushRead()
{
Contract.Assert(_writePos == 0, "BufferedStream: Write buffer must be empty in FlushRead!");
if (_readPos - _readLen != 0)
_stream.Seek(_readPos - _readLen, SeekOrigin.Current);
_readPos = 0;
_readLen = 0;
}
private void ClearReadBufferBeforeWrite()
{
// This is called by write methods to clear the read buffer.
Contract.Assert(_readPos <= _readLen, "_readPos <= _readLen [" + _readPos + " <= " + _readLen + "]");
// No READ data in the buffer:
if (_readPos == _readLen)
{
_readPos = _readLen = 0;
return;
}
// Must have READ data.
Contract.Assert(_readPos < _readLen);
// If the underlying stream cannot seek, FlushRead would end up throwing NotSupported.
// However, since the user did not call a method that is intuitively expected to seek, a better message is in order.
// Ideally, we would throw an InvalidOperation here, but for backward compat we have to stick with NotSupported.
if (!_stream.CanSeek)
throw new NotSupportedException();
FlushRead();
}
private void FlushWrite()
{
Contract.Assert(_readPos == 0 && _readLen == 0,
"BufferedStream: Read buffer must be empty in FlushWrite!");
Contract.Assert(_buffer != null && _bufferSize >= _writePos,
"BufferedStream: Write buffer must be allocated and write position must be in the bounds of the buffer in FlushWrite!");
_stream.Write(_buffer, 0, _writePos);
_writePos = 0;
_stream.Flush();
}
private Int32 ReadFromBuffer(Byte[] array, Int32 offset, Int32 count)
{
Int32 readBytes = _readLen - _readPos;
Contract.Assert(readBytes >= 0);
if (readBytes == 0)
return 0;
Contract.Assert(readBytes > 0);
if (readBytes > count)
readBytes = count;
Array.Copy(_buffer, _readPos, array, offset, readBytes);
_readPos += readBytes;
return readBytes;
}
private Int32 ReadFromBuffer(Byte[] array, Int32 offset, Int32 count, out Exception error)
{
try
{
error = null;
return ReadFromBuffer(array, offset, count);
}
catch (Exception ex)
{
error = ex;
return 0;
}
}
public override int Read([In, Out] Byte[] array, Int32 offset, Int32 count)
{
if (array == null)
throw new ArgumentNullException("array");
if (offset < 0)
throw new ArgumentOutOfRangeException("offset");
if (count < 0)
throw new ArgumentOutOfRangeException("count");
if (array.Length - offset < count)
throw new ArgumentException();
Contract.EndContractBlock();
EnsureNotClosed();
EnsureCanRead();
Int32 bytesFromBuffer = ReadFromBuffer(array, offset, count);
// We may have read less than the number of bytes the user asked for, but that is part of the Stream contract.
// Reading again for more data may cause us to block if we're using a device with no clear end of file,
// such as a serial port or pipe. If we blocked here and this code was used with redirected pipes for a
// process's standard output, this can lead to deadlocks involving two processes.
// BUT - this is a breaking change.
// So: If we could not read all bytes the user asked for from the buffer, we will try once from the underlying
// stream thus ensuring the same blocking behaviour as if the underlying stream was not wrapped in this BufferedStream.
if (bytesFromBuffer == count)
return bytesFromBuffer;
Int32 alreadySatisfied = bytesFromBuffer;
if (bytesFromBuffer > 0)
{
count -= bytesFromBuffer;
offset += bytesFromBuffer;
}
// So the READ buffer is empty.
Contract.Assert(_readLen == _readPos);
_readPos = _readLen = 0;
// If there was anything in the WRITE buffer, clear it.
if (_writePos > 0)
FlushWrite();
// If the requested read is larger than buffer size, avoid the buffer and still use a single read:
if (count >= _bufferSize)
{
return _stream.Read(array, offset, count) + alreadySatisfied;
}
// Ok. We can fill the buffer:
EnsureBufferAllocated();
_readLen = _stream.Read(_buffer, 0, _bufferSize);
bytesFromBuffer = ReadFromBuffer(array, offset, count);
// We may have read less than the number of bytes the user asked for, but that is part of the Stream contract.
// Reading again for more data may cause us to block if we're using a device with no clear end of stream,
// such as a serial port or pipe. If we blocked here & this code was used with redirected pipes for a process's
// standard output, this can lead to deadlocks involving two processes. Additionally, translating one read on the
// BufferedStream to more than one read on the underlying Stream may defeat the whole purpose of buffering of the
// underlying reads are significantly more expensive.
return bytesFromBuffer + alreadySatisfied;
}
public override Int32 ReadByte()
{
EnsureNotClosed();
EnsureCanRead();
if (_readPos == _readLen)
{
if (_writePos > 0)
FlushWrite();
EnsureBufferAllocated();
_readLen = _stream.Read(_buffer, 0, _bufferSize);
_readPos = 0;
}
if (_readPos == _readLen)
return -1;
Int32 b = _buffer[_readPos++];
return b;
}
private void WriteToBuffer(Byte[] array, ref Int32 offset, ref Int32 count)
{
Int32 bytesToWrite = Math.Min(_bufferSize - _writePos, count);
if (bytesToWrite <= 0)
return;
EnsureBufferAllocated();
Array.Copy(array, offset, _buffer, _writePos, bytesToWrite);
_writePos += bytesToWrite;
count -= bytesToWrite;
offset += bytesToWrite;
}
private void WriteToBuffer(Byte[] array, ref Int32 offset, ref Int32 count, out Exception error)
{
try
{
error = null;
WriteToBuffer(array, ref offset, ref count);
}
catch (Exception ex)
{
error = ex;
}
}
public override void Write(Byte[] array, Int32 offset, Int32 count)
{
if (array == null)
throw new ArgumentNullException("array");
if (offset < 0)
throw new ArgumentOutOfRangeException("offset");
if (count < 0)
throw new ArgumentOutOfRangeException("count");
if (array.Length - offset < count)
throw new ArgumentException();
Contract.EndContractBlock();
EnsureNotClosed();
EnsureCanWrite();
if (_writePos == 0)
ClearReadBufferBeforeWrite();
#region Write algorithm comment
// We need to use the buffer, while avoiding unnecessary buffer usage / memory copies.
// We ASSUME that memory copies are much cheaper than writes to the underlying stream, so if an extra copy is
// guaranteed to reduce the number of writes, we prefer it.
// We pick a simple strategy that makes degenerate cases rare if our assumptions are right.
//
// For ever write, we use a simple heuristic (below) to decide whether to use the buffer.
// The heuristic has the desirable property (*) that if the specified user data can fit into the currently available
// buffer space without filling it up completely, the heuristic will always tell us to use the buffer. It will also
// tell us to use the buffer in cases where the current write would fill the buffer, but the remaining data is small
// enough such that subsequent operations can use the buffer again.
//
// Algorithm:
// Determine whether or not to buffer according to the heuristic (below).
// If we decided to use the buffer:
// Copy as much user data as we can into the buffer.
// If we consumed all data: We are finished.
// Otherwise, write the buffer out.
// Copy the rest of user data into the now cleared buffer (no need to write out the buffer again as the heuristic
// will prevent it from being filled twice).
// If we decided not to use the buffer:
// Can the data already in the buffer and current user data be combines to a single write
// by allocating a "shadow" buffer of up to twice the size of _bufferSize (up to a limit to avoid LOH)?
// Yes, it can:
// Allocate a larger "shadow" buffer and ensure the buffered data is moved there.
// Copy user data to the shadow buffer.
// Write shadow buffer to the underlying stream in a single operation.
// No, it cannot (amount of data is still too large):
// Write out any data possibly in the buffer.
// Write out user data directly.
//
// Heuristic:
// If the subsequent write operation that follows the current write operation will result in a write to the
// underlying stream in case that we use the buffer in the current write, while it would not have if we avoided
// using the buffer in the current write (by writing current user data to the underlying stream directly), then we
// prefer to avoid using the buffer since the corresponding memory copy is wasted (it will not reduce the number
// of writes to the underlying stream, which is what we are optimising for).
// ASSUME that the next write will be for the same amount of bytes as the current write (most common case) and
// determine if it will cause a write to the underlying stream. If the next write is actually larger, our heuristic
// still yields the right behaviour, if the next write is actually smaller, we may making an unnecessary write to
// the underlying stream. However, this can only occur if the current write is larger than half the buffer size and
// we will recover after one iteration.
// We have:
// useBuffer = (_writePos + count + count < _bufferSize + _bufferSize)
//
// Example with _bufferSize = 20, _writePos = 6, count = 10:
//
// +---------------------------------------+---------------------------------------+
// | current buffer | next iteration's "future" buffer |
// +---------------------------------------+---------------------------------------+
// |0| | | | | | | | | |1| | | | | | | | | |2| | | | | | | | | |3| | | | | | | | | |
// |0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9|
// +-----------+-------------------+-------------------+---------------------------+
// | _writePos | current count | assumed next count|avail buff after next write|
// +-----------+-------------------+-------------------+---------------------------+
//
// A nice property (*) of this heuristic is that it will always succeed if the user data completely fits into the
// available buffer, i.e. if count < (_bufferSize - _writePos).
#endregion Write algorithm comment
Contract.Assert(_writePos < _bufferSize);
Int32 totalUserBytes;
bool useBuffer;
checked
{ // We do not expect buffer sizes big enough for an overflow, but if it happens, lets fail early:
totalUserBytes = _writePos + count;
useBuffer = (totalUserBytes + count < (_bufferSize + _bufferSize));
}
if (useBuffer)
{
WriteToBuffer(array, ref offset, ref count);
if (_writePos < _bufferSize)
{
Contract.Assert(count == 0);
return;
}
Contract.Assert(count >= 0);
Contract.Assert(_writePos == _bufferSize);
Contract.Assert(_buffer != null);
_stream.Write(_buffer, 0, _writePos);
_writePos = 0;
WriteToBuffer(array, ref offset, ref count);
Contract.Assert(count == 0);
Contract.Assert(_writePos < _bufferSize);
}
else
{ // if (!useBuffer)
// Write out the buffer if necessary.
if (_writePos > 0)
{
Contract.Assert(_buffer != null);
Contract.Assert(totalUserBytes >= _bufferSize);
// Try avoiding extra write to underlying stream by combining previously buffered data with current user data:
if (totalUserBytes <= (_bufferSize + _bufferSize) && totalUserBytes <= MaxShadowBufferSize)
{
EnsureShadowBufferAllocated();
Array.Copy(array, offset, _buffer, _writePos, count);
_stream.Write(_buffer, 0, totalUserBytes);
_writePos = 0;
return;
}
_stream.Write(_buffer, 0, _writePos);
_writePos = 0;
}
// Write out user data.
_stream.Write(array, offset, count);
}
}
public override void WriteByte(Byte value)
{
EnsureNotClosed();
if (_writePos == 0)
{
EnsureCanWrite();
ClearReadBufferBeforeWrite();
EnsureBufferAllocated();
}
// We should not be flushing here, but only writing to the underlying stream, but previous version flushed, so we keep this.
if (_writePos >= _bufferSize - 1)
FlushWrite();
_buffer[_writePos++] = value;
Contract.Assert(_writePos < _bufferSize);
}
public override Int64 Seek(Int64 offset, SeekOrigin origin)
{
EnsureNotClosed();
EnsureCanSeek();
// If we have bytes in the WRITE buffer, flush them out, seek and be done.
if (_writePos > 0)
{
// We should be only writing the buffer and not flushing,
// but the previous version did flush and we stick to it for back-compat reasons.
FlushWrite();
return _stream.Seek(offset, origin);
}
// The buffer is either empty or we have a buffered READ.
if (_readLen - _readPos > 0 && origin == SeekOrigin.Current)
{
// If we have bytes in the READ buffer, adjust the seek offset to account for the resulting difference
// between this stream's position and the underlying stream's position.
offset -= (_readLen - _readPos);
}
Int64 oldPos = Position;
Contract.Assert(oldPos == _stream.Position + (_readPos - _readLen));
Int64 newPos = _stream.Seek(offset, origin);
// If the seek destination is still within the data currently in the buffer, we want to keep the buffer data and continue using it.
// Otherwise we will throw away the buffer. This can only happen on READ, as we flushed WRITE data above.
// The offset of the new/updated seek pointer within _buffer:
_readPos = (Int32)(newPos - (oldPos - _readPos));
// If the offset of the updated seek pointer in the buffer is still legal, then we can keep using the buffer:
if (0 <= _readPos && _readPos < _readLen)
{
// Adjust the seek pointer of the underlying stream to reflect the amount of useful bytes in the read buffer:
_stream.Seek(_readLen - _readPos, SeekOrigin.Current);
}
else
{ // The offset of the updated seek pointer is not a legal offset. Loose the buffer.
_readPos = _readLen = 0;
}
Contract.Assert(newPos == Position, "newPos (=" + newPos + ") == Position (=" + Position + ")");
return newPos;
}
public override void SetLength(Int64 value)
{
if (value < 0)
throw new ArgumentOutOfRangeException("value");
Contract.EndContractBlock();
EnsureNotClosed();
EnsureCanSeek();
EnsureCanWrite();
Flush();
_stream.SetLength(value);
}
} // class BufferedStream
} // namespace
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.